From db5462603e20d5fa56814380274ad475bf388fb2 Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Sat, 8 Aug 2026 16:20:49 +0800 Subject: [PATCH] Move pal directory to private repository (#191) (#254) Co-authored-by: qiuguohua --- .github/workflows/native-ts-build.yml | 1 + .gitignore | 8 + cc.config.json | 88 +- cocos/render-scene/core/render-window.ts | 13 +- package-lock.json | 24 +- package.json | 12 +- pal/audio/audio-buffer-manager.ts | 82 - pal/audio/audio-timer.ts | 119 - pal/audio/minigame/player-minigame.ts | 393 -- pal/audio/minigame/player-web.ts | 323 -- pal/audio/minigame/player.ts | 132 - pal/audio/native/player.ts | 343 -- pal/audio/nodejs/player.ts | 246 - pal/audio/operation-queue.ts | 122 - pal/audio/type.ts | 84 - pal/audio/web/player-dom.ts | 277 - pal/audio/web/player-web.ts | 493 -- pal/audio/web/player.ts | 130 - pal/env/minigame/env.ts | 56 - pal/env/native/env.ts | 74 - pal/env/nodejs/env.ts | 40 - pal/env/runtime/env.ts | 50 - pal/env/web/env.ts | 68 - pal/input/input-source.ts | 327 -- pal/input/keycodes.ts | 104 - pal/input/minigame/accelerometer-input.ts | 95 - pal/input/minigame/gamepad-input.ts | 216 - pal/input/minigame/handheld-input.ts | 57 - pal/input/minigame/handle-input.ts | 201 - pal/input/minigame/hmd-input.ts | 76 - pal/input/minigame/index.ts | 36 - pal/input/minigame/keyboard-input.ts | 181 - pal/input/minigame/mouse-input.ts | 117 - pal/input/minigame/touch-input.ts | 99 - pal/input/native/accelerometer-input.ts | 106 - pal/input/native/gamepad-input.ts | 427 -- pal/input/native/handheld-input.ts | 97 - pal/input/native/handle-input.ts | 478 -- pal/input/native/hmd-input.ts | 123 - pal/input/native/index.ts | 36 - pal/input/native/keyboard-input.ts | 109 - pal/input/native/mouse-input.ts | 238 - pal/input/native/touch-input.ts | 156 - pal/input/nodejs/accelerometer-input.ts | 49 - pal/input/nodejs/gamepad-input.ts | 131 - pal/input/nodejs/handheld-input.ts | 54 - pal/input/nodejs/handle-input.ts | 113 - pal/input/nodejs/hmd-input.ts | 74 - pal/input/nodejs/index.ts | 36 - pal/input/nodejs/keyboard-input.ts | 47 - pal/input/nodejs/mouse-input.ts | 53 - pal/input/nodejs/touch-input.ts | 45 - pal/input/touch-manager.ts | 159 - pal/input/web/accelerometer-input.ts | 145 - pal/input/web/gamepad-input.ts | 899 --- pal/input/web/handheld-input.ts | 57 - pal/input/web/handle-input.ts | 433 -- pal/input/web/hmd-input.ts | 146 - pal/input/web/index.ts | 36 - pal/input/web/keyboard-input.ts | 79 - pal/input/web/mouse-input.ts | 216 - pal/input/web/touch-input.ts | 138 - pal/integrity-check.ts | 55 - pal/minigame/alipay.ts | 171 - pal/minigame/baidu.ts | 116 - pal/minigame/bytedance.ts | 126 - pal/minigame/non-minigame.ts | 30 - pal/minigame/runtime.ts | 136 - pal/minigame/taobao.ts | 219 - pal/minigame/taobao_minigame.ts | 227 - pal/minigame/wechat.ts | 254 - pal/minigame/wechat_mini_program.ts | 195 - pal/minigame/xiaomi.ts | 156 - pal/pacer/pacer-minigame.ts | 84 - pal/pacer/pacer-native.ts | 84 - pal/pacer/pacer-nodejs.ts | 99 - pal/pacer/pacer-web.ts | 151 - pal/screen-adapter/enum-type/index.ts | 26 - pal/screen-adapter/enum-type/orientation.ts | 32 - pal/screen-adapter/enum-type/screen-event.ts | 25 - pal/screen-adapter/minigame/screen-adapter.ts | 183 - pal/screen-adapter/native/screen-adapter.ts | 174 - pal/screen-adapter/nodejs/screen-adapter.ts | 139 - pal/screen-adapter/web/screen-adapter.ts | 663 --- pal/system-info/enum-type/browser-type.ts | 141 - pal/system-info/enum-type/event.ts | 25 - pal/system-info/enum-type/feature.ts | 115 - pal/system-info/enum-type/index.ts | 31 - pal/system-info/enum-type/language.ts | 151 - pal/system-info/enum-type/network-type.ts | 41 - pal/system-info/enum-type/operating-system.ts | 66 - pal/system-info/enum-type/platform.ts | 56 - pal/system-info/minigame/system-info.ts | 385 -- pal/system-info/native/system-info.ts | 199 - pal/system-info/nodejs/system-info.ts | 164 - pal/system-info/web/system-info.ts | 401 -- pal/utils.ts | 242 - pal/wasm/wasm-minigame.ts | 129 - pal/wasm/wasm-native.ts | 78 - pal/wasm/wasm-nodejs.ts | 60 - pal/wasm/wasm-web.ts | 105 - platforms/.eslintrc.yaml | 77 - platforms/minigame/README.md | 7 - .../minigame/common/engine/AssetManager.js | 465 -- platforms/minigame/common/engine/Editbox.js | 178 - .../minigame/common/engine/cache-manager.js | 300 - platforms/minigame/common/engine/index.js | 2 - .../minigame/common/xmldom/dom-parser.js | 254 - platforms/minigame/common/xmldom/dom.js | 1246 ----- platforms/minigame/common/xmldom/entities.js | 244 - platforms/minigame/common/xmldom/sax.js | 616 --- platforms/minigame/openDataContext/engine.js | 4838 ----------------- platforms/minigame/openDataContext/index.js | 28 - .../openDataContext/render/avatar.png | Bin 95816 -> 0 bytes .../openDataContext/render/dataDemo.js | 23 - .../minigame/openDataContext/render/style.js | 109 - .../openDataContext/render/template.js | 33 - .../platforms/alipay/wrapper/builtin/Audio.js | 215 - .../alipay/wrapper/builtin/Base64.js | 55 - .../alipay/wrapper/builtin/Canvas.js | 17 - .../alipay/wrapper/builtin/Element.js | 29 - .../platforms/alipay/wrapper/builtin/Event.js | 17 - .../wrapper/builtin/EventIniter/MouseEvent.js | 3 - .../wrapper/builtin/EventIniter/TouchEvent.js | 35 - .../wrapper/builtin/EventIniter/index.js | 2 - .../alipay/wrapper/builtin/EventTarget.js | 56 - .../alipay/wrapper/builtin/FileReader.js | 3 - .../wrapper/builtin/HTMLAudioElement.js | 7 - .../wrapper/builtin/HTMLCanvasElement.js | 8 - .../alipay/wrapper/builtin/HTMLElement.js | 25 - .../wrapper/builtin/HTMLImageElement.js | 8 - .../wrapper/builtin/HTMLMediaElement.js | 22 - .../wrapper/builtin/HTMLVideoElement.js | 8 - .../platforms/alipay/wrapper/builtin/Image.js | 28 - .../alipay/wrapper/builtin/ImageBitmap.js | 5 - .../platforms/alipay/wrapper/builtin/Node.js | 37 - .../wrapper/builtin/WebGLRenderingContext.js | 5 - .../alipay/wrapper/builtin/WebSocket.js | 112 - .../wrapper/builtin/WindowProperties.js | 14 - .../alipay/wrapper/builtin/XMLHttpRequest.js | 153 - .../alipay/wrapper/builtin/document.js | 191 - .../platforms/alipay/wrapper/builtin/index.js | 51 - .../alipay/wrapper/builtin/localStorage.js | 46 - .../alipay/wrapper/builtin/location.js | 13 - .../alipay/wrapper/builtin/navigator.js | 52 - .../alipay/wrapper/builtin/utils/noop.js | 3 - .../alipay/wrapper/builtin/utils/util.js | 80 - .../alipay/wrapper/builtin/window.js | 38 - .../alipay/wrapper/engine/AudioPlayer.js | 3 - .../alipay/wrapper/engine/Console.js | 12 - .../platforms/alipay/wrapper/engine/Label.js | 24 - .../platforms/alipay/wrapper/engine/index.js | 5 - .../platforms/alipay/wrapper/fs-utils.js | 284 - .../platforms/alipay/wrapper/unify.js | 108 - .../platforms/alipay/wrapper/utils.js | 16 - .../bytedance/wrapper/builtin/Audio.js | 205 - .../bytedance/wrapper/builtin/Canvas.js | 64 - .../bytedance/wrapper/builtin/Element.js | 10 - .../bytedance/wrapper/builtin/Event.js | 14 - .../wrapper/builtin/EventIniter/MouseEvent.js | 5 - .../wrapper/builtin/EventIniter/TouchEvent.js | 32 - .../wrapper/builtin/EventIniter/index.js | 2 - .../bytedance/wrapper/builtin/EventTarget.js | 57 - .../bytedance/wrapper/builtin/FileReader.js | 7 - .../wrapper/builtin/HTMLAudioElement.js | 7 - .../wrapper/builtin/HTMLCanvasElement.js | 20 - .../bytedance/wrapper/builtin/HTMLElement.js | 54 - .../wrapper/builtin/HTMLImageElement.js | 16 - .../wrapper/builtin/HTMLMediaElement.js | 25 - .../wrapper/builtin/HTMLVideoElement.js | 8 - .../bytedance/wrapper/builtin/Image.js | 9 - .../bytedance/wrapper/builtin/ImageBitmap.js | 5 - .../bytedance/wrapper/builtin/Node.js | 34 - .../wrapper/builtin/WebGLRenderingContext.js | 5 - .../bytedance/wrapper/builtin/WebSocket.js | 87 - .../wrapper/builtin/WindowProperties.js | 21 - .../bytedance/wrapper/builtin/Worker.js | 5 - .../wrapper/builtin/XMLHttpRequest.js | 170 - .../bytedance/wrapper/builtin/document.js | 127 - .../bytedance/wrapper/builtin/index.js | 64 - .../bytedance/wrapper/builtin/localStorage.js | 31 - .../bytedance/wrapper/builtin/location.js | 8 - .../bytedance/wrapper/builtin/navigator.js | 38 - .../bytedance/wrapper/builtin/util/index.js | 1 - .../bytedance/wrapper/builtin/window.js | 41 - .../bytedance/wrapper/engine/Label.js | 24 - .../bytedance/wrapper/engine/VideoPlayer.js | 364 -- .../bytedance/wrapper/engine/index.js | 4 - .../platforms/bytedance/wrapper/fs-utils.js | 270 - .../platforms/bytedance/wrapper/unify.js | 117 - .../platforms/bytedance/wrapper/utils.js | 16 - .../taobao-mini-game/wrapper/builtin/Audio.js | 205 - .../wrapper/builtin/Canvas.js | 71 - .../wrapper/builtin/Element.js | 10 - .../taobao-mini-game/wrapper/builtin/Event.js | 14 - .../wrapper/builtin/EventTarget.js | 57 - .../wrapper/builtin/HTMLAudioElement.js | 7 - .../wrapper/builtin/HTMLCanvasElement.js | 10 - .../wrapper/builtin/HTMLElement.js | 54 - .../wrapper/builtin/HTMLImageElement.js | 6 - .../taobao-mini-game/wrapper/builtin/Image.js | 7 - .../wrapper/builtin/ImageBitmap.js | 5 - .../wrapper/builtin/MultiWebSocket.js | 91 - .../taobao-mini-game/wrapper/builtin/Node.js | 34 - .../wrapper/builtin/WebGLRenderingContext.js | 5 - .../wrapper/builtin/WebSocket.js | 155 - .../wrapper/builtin/WindowProperties.js | 26 - .../wrapper/builtin/XMLHttpRequest.js | 136 - .../wrapper/builtin/cancelAnimationFrame.js | 4 - .../wrapper/builtin/document.js | 124 - .../taobao-mini-game/wrapper/builtin/index.js | 90 - .../wrapper/builtin/localStorage.js | 37 - .../wrapper/builtin/location.js | 8 - .../wrapper/builtin/navigator.js | 38 - .../wrapper/builtin/requestAnimationFrame.js | 4 - .../wrapper/builtin/util/index.js | 1 - .../wrapper/builtin/window.js | 23 - .../wrapper/engine/AssetManager.js | 72 - .../wrapper/engine/Console.js | 12 - .../wrapper/engine/Editbox.js | 91 - .../taobao-mini-game/wrapper/engine/Label.js | 22 - .../wrapper/engine/cache-manager.js | 53 - .../taobao-mini-game/wrapper/engine/index.js | 6 - .../taobao-mini-game/wrapper/fs-utils.js | 275 - .../taobao-mini-game/wrapper/unify.js | 128 - .../taobao-mini-game/wrapper/utils.js | 111 - .../platforms/taobao/wrapper/builtin/Audio.js | 205 - .../taobao/wrapper/builtin/Canvas.js | 69 - .../taobao/wrapper/builtin/Element.js | 10 - .../platforms/taobao/wrapper/builtin/Event.js | 14 - .../taobao/wrapper/builtin/EventTarget.js | 57 - .../wrapper/builtin/HTMLAudioElement.js | 7 - .../wrapper/builtin/HTMLCanvasElement.js | 3 - .../taobao/wrapper/builtin/HTMLElement.js | 54 - .../wrapper/builtin/HTMLImageElement.js | 4 - .../platforms/taobao/wrapper/builtin/Image.js | 7 - .../taobao/wrapper/builtin/ImageBitmap.js | 5 - .../platforms/taobao/wrapper/builtin/Node.js | 34 - .../wrapper/builtin/WebGLRenderingContext.js | 5 - .../taobao/wrapper/builtin/WebSocket.js | 139 - .../wrapper/builtin/WindowProperties.js | 31 - .../taobao/wrapper/builtin/XMLHttpRequest.js | 172 - .../wrapper/builtin/cancelAnimationFrame.js | 4 - .../taobao/wrapper/builtin/document.js | 124 - .../platforms/taobao/wrapper/builtin/index.js | 64 - .../taobao/wrapper/builtin/localStorage.js | 37 - .../taobao/wrapper/builtin/location.js | 8 - .../taobao/wrapper/builtin/navigator.js | 38 - .../wrapper/builtin/requestAnimationFrame.js | 4 - .../taobao/wrapper/builtin/util/index.js | 1 - .../taobao/wrapper/builtin/window.js | 15 - .../taobao/wrapper/engine/AssetManager.js | 72 - .../taobao/wrapper/engine/Editbox.js | 91 - .../platforms/taobao/wrapper/engine/Label.js | 22 - .../platforms/taobao/wrapper/engine/index.js | 5 - .../platforms/taobao/wrapper/fs-utils.js | 259 - .../platforms/taobao/wrapper/unify.js | 149 - .../platforms/taobao/wrapper/utils.js | 111 - .../platforms/wechat/wrapper/builtin/Audio.js | 205 - .../wechat/wrapper/builtin/Canvas.js | 74 - .../wechat/wrapper/builtin/Element.js | 10 - .../platforms/wechat/wrapper/builtin/Event.js | 14 - .../wrapper/builtin/EventIniter/MouseEvent.js | 5 - .../wrapper/builtin/EventIniter/TouchEvent.js | 38 - .../wrapper/builtin/EventIniter/index.js | 2 - .../wechat/wrapper/builtin/EventTarget.js | 57 - .../wechat/wrapper/builtin/FileReader.js | 7 - .../wrapper/builtin/HTMLAudioElement.js | 7 - .../wrapper/builtin/HTMLCanvasElement.js | 20 - .../wechat/wrapper/builtin/HTMLElement.js | 54 - .../wrapper/builtin/HTMLImageElement.js | 16 - .../wrapper/builtin/HTMLMediaElement.js | 25 - .../wrapper/builtin/HTMLVideoElement.js | 8 - .../platforms/wechat/wrapper/builtin/Image.js | 10 - .../wechat/wrapper/builtin/ImageBitmap.js | 5 - .../platforms/wechat/wrapper/builtin/Node.js | 34 - .../wrapper/builtin/WebGLRenderingContext.js | 302 - .../wechat/wrapper/builtin/WebSocket.js | 87 - .../wrapper/builtin/WindowProperties.js | 21 - .../wechat/wrapper/builtin/Worker.js | 5 - .../wechat/wrapper/builtin/XMLHttpRequest.js | 172 - .../wechat/wrapper/builtin/document.js | 127 - .../platforms/wechat/wrapper/builtin/index.js | 65 - .../wechat/wrapper/builtin/localStorage.js | 31 - .../wechat/wrapper/builtin/location.js | 8 - .../wechat/wrapper/builtin/navigator.js | 38 - .../wechat/wrapper/builtin/util/index.js | 1 - .../wechat/wrapper/builtin/window.js | 41 - .../wechat/wrapper/engine/VideoPlayer.js | 384 -- .../platforms/wechat/wrapper/engine/index.js | 4 - .../wechat/wrapper/engine/sprite-frame.js | 25 - .../platforms/wechat/wrapper/fs-utils.js | 279 - .../platforms/wechat/wrapper/unify.js | 125 - .../platforms/wechat/wrapper/utils.js | 16 - .../platforms/xiaomi/wrapper/builtin.js | 1168 ---- .../xiaomi/wrapper/engine/Editbox.js | 180 - .../xiaomi/wrapper/engine/download-ttf.js | 12 - .../platforms/xiaomi/wrapper/engine/index.js | 4 - .../platforms/xiaomi/wrapper/fs-utils.js | 262 - .../platforms/xiaomi/wrapper/unify.js | 123 - .../platforms/xiaomi/wrapper/utils.js | 16 - platforms/native/README.md | 6 - platforms/native/builtin/Blob.js | 223 - platforms/native/builtin/base64/base64.min.js | 1 - platforms/native/builtin/index.js | 225 - platforms/native/builtin/jsb-adapter/Audio.js | 8 - .../jsb-adapter/CanvasRenderingContext2D.js | 155 - .../native/builtin/jsb-adapter/DOMRect.js | 14 - .../builtin/jsb-adapter/DeviceMotionEvent.js | 37 - .../native/builtin/jsb-adapter/Element.js | 34 - platforms/native/builtin/jsb-adapter/Event.js | 174 - .../native/builtin/jsb-adapter/EventTarget.js | 289 - .../native/builtin/jsb-adapter/FileReader.js | 31 - .../native/builtin/jsb-adapter/FontFace.js | 28 - .../native/builtin/jsb-adapter/FontFaceSet.js | 62 - .../builtin/jsb-adapter/HTMLAudioElement.js | 87 - .../builtin/jsb-adapter/HTMLCanvasElement.js | 140 - .../native/builtin/jsb-adapter/HTMLElement.js | 34 - .../builtin/jsb-adapter/HTMLImageElement.js | 66 - .../builtin/jsb-adapter/HTMLMediaElement.js | 70 - .../builtin/jsb-adapter/HTMLScriptElement.js | 31 - .../builtin/jsb-adapter/HTMLVideoElement.js | 15 - platforms/native/builtin/jsb-adapter/Image.js | 9 - .../native/builtin/jsb-adapter/ImageData.js | 36 - .../builtin/jsb-adapter/KeyboardEvent.js | 289 - .../native/builtin/jsb-adapter/MediaError.js | 20 - .../native/builtin/jsb-adapter/MouseEvent.js | 54 - platforms/native/builtin/jsb-adapter/Node.js | 50 - .../native/builtin/jsb-adapter/TouchEvent.js | 12 - .../native/builtin/jsb-adapter/document.js | 125 - platforms/native/builtin/jsb-adapter/fetch.js | 499 -- platforms/native/builtin/jsb-adapter/index.js | 2 - .../native/builtin/jsb-adapter/location.js | 11 - .../native/builtin/jsb-adapter/navigator.js | 19 - .../native/builtin/jsb-adapter/util/index.js | 3 - .../native/builtin/jsb-adapter/window.js | 137 - platforms/native/builtin/jsb_audioengine.js | 21 - platforms/native/builtin/jsb_input.js | 99 - platforms/native/builtin/jsb_prepare.js | 48 - platforms/native/builtin/promise.min.js | 13 - platforms/native/builtin/wasm.js | 75 - platforms/native/builtin/xmldom/dom-parser.js | 252 - platforms/native/builtin/xmldom/dom.js | 1240 ----- platforms/native/builtin/xmldom/entities.js | 244 - platforms/native/builtin/xmldom/sax.js | 616 --- platforms/native/engine/index.js | 42 - platforms/native/engine/jsb-assets-manager.js | 60 - platforms/native/engine/jsb-cache-manager.js | 146 - platforms/native/engine/jsb-dragonbones.js | 744 --- platforms/native/engine/jsb-editbox.js | 212 - platforms/native/engine/jsb-editor-support.js | 127 - platforms/native/engine/jsb-fs-utils.js | 240 - platforms/native/engine/jsb-game.js | 39 - platforms/native/engine/jsb-gfx.js | 167 - platforms/native/engine/jsb-loader.js | 421 -- platforms/native/engine/jsb-physics.js | 1084 ---- .../engine/jsb-videoplayer-openharmony.js | 453 -- platforms/native/engine/jsb-videoplayer.js | 280 - platforms/native/engine/jsb-webview.js | 184 - platforms/native/jsbWindow.js | 3 - platforms/native/modules.json | 197 - platforms/nodejs/builtin/Blob.js | 223 - platforms/nodejs/builtin/base64/base64.min.js | 1 - platforms/nodejs/builtin/index.js | 40 - .../nodejs/builtin/node-adapter/Audio.js | 8 - .../node-adapter/CanvasRenderingContext2D.js | 145 - .../nodejs/builtin/node-adapter/DOMRect.js | 14 - .../builtin/node-adapter/DeviceMotionEvent.js | 37 - .../nodejs/builtin/node-adapter/Element.js | 34 - .../nodejs/builtin/node-adapter/Event.js | 174 - .../builtin/node-adapter/EventTarget.js | 289 - .../nodejs/builtin/node-adapter/FileReader.js | 31 - .../nodejs/builtin/node-adapter/FontFace.js | 28 - .../builtin/node-adapter/FontFaceSet.js | 62 - .../builtin/node-adapter/HTMLAudioElement.js | 87 - .../builtin/node-adapter/HTMLCanvasElement.js | 139 - .../builtin/node-adapter/HTMLElement.js | 34 - .../builtin/node-adapter/HTMLImageElement.js | 75 - .../builtin/node-adapter/HTMLMediaElement.js | 70 - .../builtin/node-adapter/HTMLScriptElement.js | 31 - .../builtin/node-adapter/HTMLVideoElement.js | 15 - .../nodejs/builtin/node-adapter/Image.js | 9 - .../nodejs/builtin/node-adapter/ImageData.js | 36 - .../builtin/node-adapter/KeyboardEvent.js | 289 - .../nodejs/builtin/node-adapter/MediaError.js | 20 - .../nodejs/builtin/node-adapter/MouseEvent.js | 54 - platforms/nodejs/builtin/node-adapter/Node.js | 50 - .../nodejs/builtin/node-adapter/TouchEvent.js | 12 - .../nodejs/builtin/node-adapter/document.js | 124 - .../nodejs/builtin/node-adapter/fetch.js | 499 -- .../nodejs/builtin/node-adapter/index.js | 2 - .../nodejs/builtin/node-adapter/location.js | 11 - .../nodejs/builtin/node-adapter/util/index.js | 3 - .../nodejs/builtin/node-adapter/window.js | 131 - platforms/nodejs/builtin/promise.min.js | 13 - platforms/nodejs/builtin/wasm.js | 75 - platforms/nodejs/builtin/xmldom/dom-parser.js | 252 - platforms/nodejs/builtin/xmldom/dom.js | 1240 ----- platforms/nodejs/builtin/xmldom/entities.js | 244 - platforms/nodejs/builtin/xmldom/sax.js | 616 --- platforms/nodejs/engine/asset-manager.js | 383 -- platforms/nodejs/engine/cache-manager.js | 219 - platforms/nodejs/engine/fs-utils.js | 237 - platforms/nodejs/engine/index.js | 1 - platforms/runtime/README.md | 6 - platforms/runtime/common/engine/EditBox.js | 172 - .../runtime/common/engine/asset-manager.js | 419 -- .../runtime/common/engine/cache-manager.js | 262 - platforms/runtime/common/engine/canvas.js | 6 - platforms/runtime/common/engine/fs-utils.js | 263 - platforms/runtime/common/engine/game.js | 8 - platforms/runtime/common/engine/index.js | 30 - platforms/runtime/common/engine/wasm.js | 4 - .../honor-mini-game/engine/asset-manager.js | 419 -- .../platforms/honor-mini-game/engine/index.js | 5 - .../huawei-quick-game/engine/index.js | 1 - .../migu-mini-game/engine/asset-manager.js | 419 -- .../platforms/migu-mini-game/engine/index.js | 5 - .../oppo-mini-game/engine/VideoPlayer.js | 405 -- .../platforms/oppo-mini-game/engine/index.js | 2 - .../platforms/vivo-mini-game/engine/index.js | 1 - scripts/spread-adapter.cjs | 38 + scripts/spread-pal.cjs | 48 + tsconfig.json | 3 + 424 files changed, 182 insertions(+), 53571 deletions(-) delete mode 100644 pal/audio/audio-buffer-manager.ts delete mode 100644 pal/audio/audio-timer.ts delete mode 100644 pal/audio/minigame/player-minigame.ts delete mode 100644 pal/audio/minigame/player-web.ts delete mode 100644 pal/audio/minigame/player.ts delete mode 100644 pal/audio/native/player.ts delete mode 100644 pal/audio/nodejs/player.ts delete mode 100644 pal/audio/operation-queue.ts delete mode 100644 pal/audio/type.ts delete mode 100644 pal/audio/web/player-dom.ts delete mode 100644 pal/audio/web/player-web.ts delete mode 100644 pal/audio/web/player.ts delete mode 100644 pal/env/minigame/env.ts delete mode 100644 pal/env/native/env.ts delete mode 100644 pal/env/nodejs/env.ts delete mode 100644 pal/env/runtime/env.ts delete mode 100644 pal/env/web/env.ts delete mode 100644 pal/input/input-source.ts delete mode 100644 pal/input/keycodes.ts delete mode 100644 pal/input/minigame/accelerometer-input.ts delete mode 100644 pal/input/minigame/gamepad-input.ts delete mode 100644 pal/input/minigame/handheld-input.ts delete mode 100644 pal/input/minigame/handle-input.ts delete mode 100644 pal/input/minigame/hmd-input.ts delete mode 100644 pal/input/minigame/index.ts delete mode 100644 pal/input/minigame/keyboard-input.ts delete mode 100644 pal/input/minigame/mouse-input.ts delete mode 100644 pal/input/minigame/touch-input.ts delete mode 100644 pal/input/native/accelerometer-input.ts delete mode 100644 pal/input/native/gamepad-input.ts delete mode 100644 pal/input/native/handheld-input.ts delete mode 100644 pal/input/native/handle-input.ts delete mode 100644 pal/input/native/hmd-input.ts delete mode 100644 pal/input/native/index.ts delete mode 100644 pal/input/native/keyboard-input.ts delete mode 100644 pal/input/native/mouse-input.ts delete mode 100644 pal/input/native/touch-input.ts delete mode 100644 pal/input/nodejs/accelerometer-input.ts delete mode 100644 pal/input/nodejs/gamepad-input.ts delete mode 100644 pal/input/nodejs/handheld-input.ts delete mode 100644 pal/input/nodejs/handle-input.ts delete mode 100644 pal/input/nodejs/hmd-input.ts delete mode 100644 pal/input/nodejs/index.ts delete mode 100644 pal/input/nodejs/keyboard-input.ts delete mode 100644 pal/input/nodejs/mouse-input.ts delete mode 100644 pal/input/nodejs/touch-input.ts delete mode 100644 pal/input/touch-manager.ts delete mode 100644 pal/input/web/accelerometer-input.ts delete mode 100644 pal/input/web/gamepad-input.ts delete mode 100644 pal/input/web/handheld-input.ts delete mode 100644 pal/input/web/handle-input.ts delete mode 100644 pal/input/web/hmd-input.ts delete mode 100644 pal/input/web/index.ts delete mode 100644 pal/input/web/keyboard-input.ts delete mode 100644 pal/input/web/mouse-input.ts delete mode 100644 pal/input/web/touch-input.ts delete mode 100644 pal/integrity-check.ts delete mode 100644 pal/minigame/alipay.ts delete mode 100644 pal/minigame/baidu.ts delete mode 100644 pal/minigame/bytedance.ts delete mode 100644 pal/minigame/non-minigame.ts delete mode 100644 pal/minigame/runtime.ts delete mode 100644 pal/minigame/taobao.ts delete mode 100644 pal/minigame/taobao_minigame.ts delete mode 100644 pal/minigame/wechat.ts delete mode 100644 pal/minigame/wechat_mini_program.ts delete mode 100644 pal/minigame/xiaomi.ts delete mode 100644 pal/pacer/pacer-minigame.ts delete mode 100644 pal/pacer/pacer-native.ts delete mode 100644 pal/pacer/pacer-nodejs.ts delete mode 100644 pal/pacer/pacer-web.ts delete mode 100644 pal/screen-adapter/enum-type/index.ts delete mode 100644 pal/screen-adapter/enum-type/orientation.ts delete mode 100644 pal/screen-adapter/enum-type/screen-event.ts delete mode 100644 pal/screen-adapter/minigame/screen-adapter.ts delete mode 100644 pal/screen-adapter/native/screen-adapter.ts delete mode 100644 pal/screen-adapter/nodejs/screen-adapter.ts delete mode 100644 pal/screen-adapter/web/screen-adapter.ts delete mode 100644 pal/system-info/enum-type/browser-type.ts delete mode 100644 pal/system-info/enum-type/event.ts delete mode 100644 pal/system-info/enum-type/feature.ts delete mode 100644 pal/system-info/enum-type/index.ts delete mode 100644 pal/system-info/enum-type/language.ts delete mode 100644 pal/system-info/enum-type/network-type.ts delete mode 100644 pal/system-info/enum-type/operating-system.ts delete mode 100644 pal/system-info/enum-type/platform.ts delete mode 100644 pal/system-info/minigame/system-info.ts delete mode 100644 pal/system-info/native/system-info.ts delete mode 100644 pal/system-info/nodejs/system-info.ts delete mode 100644 pal/system-info/web/system-info.ts delete mode 100644 pal/utils.ts delete mode 100644 pal/wasm/wasm-minigame.ts delete mode 100644 pal/wasm/wasm-native.ts delete mode 100644 pal/wasm/wasm-nodejs.ts delete mode 100644 pal/wasm/wasm-web.ts delete mode 100644 platforms/.eslintrc.yaml delete mode 100644 platforms/minigame/README.md delete mode 100644 platforms/minigame/common/engine/AssetManager.js delete mode 100644 platforms/minigame/common/engine/Editbox.js delete mode 100644 platforms/minigame/common/engine/cache-manager.js delete mode 100644 platforms/minigame/common/engine/index.js delete mode 100644 platforms/minigame/common/xmldom/dom-parser.js delete mode 100755 platforms/minigame/common/xmldom/dom.js delete mode 100644 platforms/minigame/common/xmldom/entities.js delete mode 100644 platforms/minigame/common/xmldom/sax.js delete mode 100644 platforms/minigame/openDataContext/engine.js delete mode 100644 platforms/minigame/openDataContext/index.js delete mode 100644 platforms/minigame/openDataContext/render/avatar.png delete mode 100644 platforms/minigame/openDataContext/render/dataDemo.js delete mode 100644 platforms/minigame/openDataContext/render/style.js delete mode 100644 platforms/minigame/openDataContext/render/template.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/Audio.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/Base64.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/Canvas.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/Element.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/Event.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/EventIniter/MouseEvent.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/EventIniter/TouchEvent.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/EventIniter/index.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/EventTarget.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/FileReader.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/HTMLAudioElement.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/HTMLCanvasElement.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/HTMLElement.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/HTMLImageElement.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/HTMLMediaElement.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/HTMLVideoElement.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/Image.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/ImageBitmap.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/Node.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/WebGLRenderingContext.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/WebSocket.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/WindowProperties.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/XMLHttpRequest.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/document.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/index.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/localStorage.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/location.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/navigator.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/utils/noop.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/utils/util.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/builtin/window.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/engine/AudioPlayer.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/engine/Console.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/engine/Label.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/engine/index.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/fs-utils.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/unify.js delete mode 100644 platforms/minigame/platforms/alipay/wrapper/utils.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/Audio.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/Canvas.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/Element.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/Event.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/EventIniter/MouseEvent.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/EventIniter/TouchEvent.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/EventIniter/index.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/EventTarget.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/FileReader.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLAudioElement.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLCanvasElement.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLElement.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLImageElement.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLMediaElement.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLVideoElement.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/Image.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/ImageBitmap.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/Node.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/WebGLRenderingContext.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/WebSocket.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/WindowProperties.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/Worker.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/XMLHttpRequest.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/document.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/index.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/localStorage.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/location.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/navigator.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/util/index.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/builtin/window.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/engine/Label.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/engine/VideoPlayer.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/engine/index.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/fs-utils.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/unify.js delete mode 100644 platforms/minigame/platforms/bytedance/wrapper/utils.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Audio.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Canvas.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Element.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Event.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/EventTarget.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/HTMLAudioElement.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/HTMLCanvasElement.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/HTMLElement.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/HTMLImageElement.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Image.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/ImageBitmap.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/MultiWebSocket.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Node.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/WebGLRenderingContext.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/WebSocket.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/WindowProperties.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/XMLHttpRequest.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/cancelAnimationFrame.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/document.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/index.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/localStorage.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/location.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/navigator.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/requestAnimationFrame.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/util/index.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/window.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/engine/AssetManager.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/engine/Console.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/engine/Editbox.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/engine/Label.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/engine/cache-manager.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/engine/index.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/fs-utils.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/unify.js delete mode 100644 platforms/minigame/platforms/taobao-mini-game/wrapper/utils.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/Audio.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/Canvas.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/Element.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/Event.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/EventTarget.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/HTMLAudioElement.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/HTMLCanvasElement.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/HTMLElement.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/HTMLImageElement.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/Image.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/ImageBitmap.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/Node.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/WebGLRenderingContext.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/WebSocket.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/WindowProperties.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/XMLHttpRequest.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/cancelAnimationFrame.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/document.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/index.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/localStorage.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/location.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/navigator.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/requestAnimationFrame.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/util/index.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/builtin/window.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/engine/AssetManager.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/engine/Editbox.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/engine/Label.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/engine/index.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/fs-utils.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/unify.js delete mode 100644 platforms/minigame/platforms/taobao/wrapper/utils.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/Audio.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/Canvas.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/Element.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/Event.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/EventIniter/MouseEvent.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/EventIniter/TouchEvent.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/EventIniter/index.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/EventTarget.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/FileReader.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/HTMLAudioElement.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/HTMLCanvasElement.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/HTMLElement.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/HTMLImageElement.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/HTMLMediaElement.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/HTMLVideoElement.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/Image.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/ImageBitmap.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/Node.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/WebGLRenderingContext.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/WebSocket.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/WindowProperties.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/Worker.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/XMLHttpRequest.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/document.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/index.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/localStorage.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/location.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/navigator.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/util/index.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/builtin/window.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/engine/VideoPlayer.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/engine/index.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/engine/sprite-frame.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/fs-utils.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/unify.js delete mode 100644 platforms/minigame/platforms/wechat/wrapper/utils.js delete mode 100644 platforms/minigame/platforms/xiaomi/wrapper/builtin.js delete mode 100644 platforms/minigame/platforms/xiaomi/wrapper/engine/Editbox.js delete mode 100644 platforms/minigame/platforms/xiaomi/wrapper/engine/download-ttf.js delete mode 100644 platforms/minigame/platforms/xiaomi/wrapper/engine/index.js delete mode 100644 platforms/minigame/platforms/xiaomi/wrapper/fs-utils.js delete mode 100644 platforms/minigame/platforms/xiaomi/wrapper/unify.js delete mode 100644 platforms/minigame/platforms/xiaomi/wrapper/utils.js delete mode 100644 platforms/native/README.md delete mode 100644 platforms/native/builtin/Blob.js delete mode 100644 platforms/native/builtin/base64/base64.min.js delete mode 100644 platforms/native/builtin/index.js delete mode 100755 platforms/native/builtin/jsb-adapter/Audio.js delete mode 100644 platforms/native/builtin/jsb-adapter/CanvasRenderingContext2D.js delete mode 100644 platforms/native/builtin/jsb-adapter/DOMRect.js delete mode 100644 platforms/native/builtin/jsb-adapter/DeviceMotionEvent.js delete mode 100755 platforms/native/builtin/jsb-adapter/Element.js delete mode 100644 platforms/native/builtin/jsb-adapter/Event.js delete mode 100644 platforms/native/builtin/jsb-adapter/EventTarget.js delete mode 100755 platforms/native/builtin/jsb-adapter/FileReader.js delete mode 100644 platforms/native/builtin/jsb-adapter/FontFace.js delete mode 100644 platforms/native/builtin/jsb-adapter/FontFaceSet.js delete mode 100755 platforms/native/builtin/jsb-adapter/HTMLAudioElement.js delete mode 100644 platforms/native/builtin/jsb-adapter/HTMLCanvasElement.js delete mode 100755 platforms/native/builtin/jsb-adapter/HTMLElement.js delete mode 100755 platforms/native/builtin/jsb-adapter/HTMLImageElement.js delete mode 100755 platforms/native/builtin/jsb-adapter/HTMLMediaElement.js delete mode 100644 platforms/native/builtin/jsb-adapter/HTMLScriptElement.js delete mode 100644 platforms/native/builtin/jsb-adapter/HTMLVideoElement.js delete mode 100755 platforms/native/builtin/jsb-adapter/Image.js delete mode 100644 platforms/native/builtin/jsb-adapter/ImageData.js delete mode 100644 platforms/native/builtin/jsb-adapter/KeyboardEvent.js delete mode 100644 platforms/native/builtin/jsb-adapter/MediaError.js delete mode 100644 platforms/native/builtin/jsb-adapter/MouseEvent.js delete mode 100755 platforms/native/builtin/jsb-adapter/Node.js delete mode 100755 platforms/native/builtin/jsb-adapter/TouchEvent.js delete mode 100755 platforms/native/builtin/jsb-adapter/document.js delete mode 100644 platforms/native/builtin/jsb-adapter/fetch.js delete mode 100755 platforms/native/builtin/jsb-adapter/index.js delete mode 100755 platforms/native/builtin/jsb-adapter/location.js delete mode 100755 platforms/native/builtin/jsb-adapter/navigator.js delete mode 100755 platforms/native/builtin/jsb-adapter/util/index.js delete mode 100755 platforms/native/builtin/jsb-adapter/window.js delete mode 100644 platforms/native/builtin/jsb_audioengine.js delete mode 100644 platforms/native/builtin/jsb_input.js delete mode 100644 platforms/native/builtin/jsb_prepare.js delete mode 100644 platforms/native/builtin/promise.min.js delete mode 100644 platforms/native/builtin/wasm.js delete mode 100644 platforms/native/builtin/xmldom/dom-parser.js delete mode 100644 platforms/native/builtin/xmldom/dom.js delete mode 100644 platforms/native/builtin/xmldom/entities.js delete mode 100644 platforms/native/builtin/xmldom/sax.js delete mode 100644 platforms/native/engine/index.js delete mode 100644 platforms/native/engine/jsb-assets-manager.js delete mode 100644 platforms/native/engine/jsb-cache-manager.js delete mode 100644 platforms/native/engine/jsb-dragonbones.js delete mode 100644 platforms/native/engine/jsb-editbox.js delete mode 100644 platforms/native/engine/jsb-editor-support.js delete mode 100644 platforms/native/engine/jsb-fs-utils.js delete mode 100644 platforms/native/engine/jsb-game.js delete mode 100644 platforms/native/engine/jsb-gfx.js delete mode 100644 platforms/native/engine/jsb-loader.js delete mode 100644 platforms/native/engine/jsb-physics.js delete mode 100644 platforms/native/engine/jsb-videoplayer-openharmony.js delete mode 100644 platforms/native/engine/jsb-videoplayer.js delete mode 100644 platforms/native/engine/jsb-webview.js delete mode 100644 platforms/native/jsbWindow.js delete mode 100644 platforms/native/modules.json delete mode 100644 platforms/nodejs/builtin/Blob.js delete mode 100644 platforms/nodejs/builtin/base64/base64.min.js delete mode 100644 platforms/nodejs/builtin/index.js delete mode 100644 platforms/nodejs/builtin/node-adapter/Audio.js delete mode 100644 platforms/nodejs/builtin/node-adapter/CanvasRenderingContext2D.js delete mode 100644 platforms/nodejs/builtin/node-adapter/DOMRect.js delete mode 100644 platforms/nodejs/builtin/node-adapter/DeviceMotionEvent.js delete mode 100644 platforms/nodejs/builtin/node-adapter/Element.js delete mode 100644 platforms/nodejs/builtin/node-adapter/Event.js delete mode 100644 platforms/nodejs/builtin/node-adapter/EventTarget.js delete mode 100644 platforms/nodejs/builtin/node-adapter/FileReader.js delete mode 100644 platforms/nodejs/builtin/node-adapter/FontFace.js delete mode 100644 platforms/nodejs/builtin/node-adapter/FontFaceSet.js delete mode 100644 platforms/nodejs/builtin/node-adapter/HTMLAudioElement.js delete mode 100644 platforms/nodejs/builtin/node-adapter/HTMLCanvasElement.js delete mode 100644 platforms/nodejs/builtin/node-adapter/HTMLElement.js delete mode 100644 platforms/nodejs/builtin/node-adapter/HTMLImageElement.js delete mode 100644 platforms/nodejs/builtin/node-adapter/HTMLMediaElement.js delete mode 100644 platforms/nodejs/builtin/node-adapter/HTMLScriptElement.js delete mode 100644 platforms/nodejs/builtin/node-adapter/HTMLVideoElement.js delete mode 100644 platforms/nodejs/builtin/node-adapter/Image.js delete mode 100644 platforms/nodejs/builtin/node-adapter/ImageData.js delete mode 100644 platforms/nodejs/builtin/node-adapter/KeyboardEvent.js delete mode 100644 platforms/nodejs/builtin/node-adapter/MediaError.js delete mode 100644 platforms/nodejs/builtin/node-adapter/MouseEvent.js delete mode 100644 platforms/nodejs/builtin/node-adapter/Node.js delete mode 100644 platforms/nodejs/builtin/node-adapter/TouchEvent.js delete mode 100644 platforms/nodejs/builtin/node-adapter/document.js delete mode 100644 platforms/nodejs/builtin/node-adapter/fetch.js delete mode 100644 platforms/nodejs/builtin/node-adapter/index.js delete mode 100644 platforms/nodejs/builtin/node-adapter/location.js delete mode 100644 platforms/nodejs/builtin/node-adapter/util/index.js delete mode 100644 platforms/nodejs/builtin/node-adapter/window.js delete mode 100644 platforms/nodejs/builtin/promise.min.js delete mode 100644 platforms/nodejs/builtin/wasm.js delete mode 100644 platforms/nodejs/builtin/xmldom/dom-parser.js delete mode 100644 platforms/nodejs/builtin/xmldom/dom.js delete mode 100644 platforms/nodejs/builtin/xmldom/entities.js delete mode 100644 platforms/nodejs/builtin/xmldom/sax.js delete mode 100644 platforms/nodejs/engine/asset-manager.js delete mode 100644 platforms/nodejs/engine/cache-manager.js delete mode 100644 platforms/nodejs/engine/fs-utils.js delete mode 100644 platforms/nodejs/engine/index.js delete mode 100644 platforms/runtime/README.md delete mode 100644 platforms/runtime/common/engine/EditBox.js delete mode 100644 platforms/runtime/common/engine/asset-manager.js delete mode 100644 platforms/runtime/common/engine/cache-manager.js delete mode 100644 platforms/runtime/common/engine/canvas.js delete mode 100644 platforms/runtime/common/engine/fs-utils.js delete mode 100644 platforms/runtime/common/engine/game.js delete mode 100644 platforms/runtime/common/engine/index.js delete mode 100644 platforms/runtime/common/engine/wasm.js delete mode 100644 platforms/runtime/platforms/honor-mini-game/engine/asset-manager.js delete mode 100644 platforms/runtime/platforms/honor-mini-game/engine/index.js delete mode 100644 platforms/runtime/platforms/huawei-quick-game/engine/index.js delete mode 100644 platforms/runtime/platforms/migu-mini-game/engine/asset-manager.js delete mode 100644 platforms/runtime/platforms/migu-mini-game/engine/index.js delete mode 100644 platforms/runtime/platforms/oppo-mini-game/engine/VideoPlayer.js delete mode 100644 platforms/runtime/platforms/oppo-mini-game/engine/index.js delete mode 100644 platforms/runtime/platforms/vivo-mini-game/engine/index.js create mode 100644 scripts/spread-adapter.cjs create mode 100644 scripts/spread-pal.cjs diff --git a/.github/workflows/native-ts-build.yml b/.github/workflows/native-ts-build.yml index e74be8351e..7d262b3b57 100644 --- a/.github/workflows/native-ts-build.yml +++ b/.github/workflows/native-ts-build.yml @@ -28,6 +28,7 @@ jobs: with: node-version: ${{ matrix.node-version }} - run: npm ci --ignore-scripts + - run: node scripts/spread-pal.cjs - run: npm run build:debug-infos - name: Download external run: | diff --git a/.gitignore b/.gitignore index 036a6c64fc..d9b00981d9 100644 --- a/.gitignore +++ b/.gitignore @@ -46,3 +46,11 @@ platforms/runtime/platforms/vivo-mini-game/ral.min.js @types/consts.d.ts __TS_ENGINE__/ + +# pal 由 @cocos/engine-pal 在 postinstall 挂载(软链/复制),不入库 +/pal + +# platforms 源码已抽到 @cocos/engine-platforms;其预打包 adapter 由 postinstall 的 +# spread-adapter.cjs 复制到 bin/adapter(/bin 已忽略)。platforms 源码不再入库。 +/platforms + diff --git a/cc.config.json b/cc.config.json index 9970fe42df..a0549df564 100644 --- a/cc.config.json +++ b/cc.config.json @@ -382,70 +382,70 @@ "test": "context.buildTimeConstants && context.buildTimeConstants.HTML5", "isVirtualModule": true, "overrides": { - "pal/minigame": "pal/minigame/non-minigame.ts", - "pal/audio": "pal/audio/web/player.ts", - "pal/system-info": "pal/system-info/web/system-info.ts", - "pal/screen-adapter": "pal/screen-adapter/web/screen-adapter.ts", - "pal/input": "pal/input/web/index.ts", - "pal/env": "pal/env/web/env.ts", - "pal/pacer": "pal/pacer/pacer-web.ts", - "pal/wasm": "pal/wasm/wasm-web.ts" + "pal/minigame": "pal/minigame/non-minigame.js", + "pal/audio": "pal/audio/web/player.js", + "pal/system-info": "pal/system-info/web/system-info.js", + "pal/screen-adapter": "pal/screen-adapter/web/screen-adapter.js", + "pal/input": "pal/input/web/index.js", + "pal/env": "pal/env/web/env.js", + "pal/pacer": "pal/pacer/pacer-web.js", + "pal/wasm": "pal/wasm/wasm-web.js" } }, { "test": "context.buildTimeConstants && context.buildTimeConstants.NATIVE", "isVirtualModule": true, "overrides": { - "pal/minigame": "pal/minigame/non-minigame.ts", - "pal/audio": "pal/audio/native/player.ts", - "pal/system-info": "pal/system-info/native/system-info.ts", - "pal/screen-adapter": "pal/screen-adapter/native/screen-adapter.ts", - "pal/input": "pal/input/native/index.ts", - "pal/env": "pal/env/native/env.ts", - "pal/pacer": "pal/pacer/pacer-native.ts", - "pal/wasm": "pal/wasm/wasm-native.ts" + "pal/minigame": "pal/minigame/non-minigame.js", + "pal/audio": "pal/audio/native/player.js", + "pal/system-info": "pal/system-info/native/system-info.js", + "pal/screen-adapter": "pal/screen-adapter/native/screen-adapter.js", + "pal/input": "pal/input/native/index.js", + "pal/env": "pal/env/native/env.js", + "pal/pacer": "pal/pacer/pacer-native.js", + "pal/wasm": "pal/wasm/wasm-native.js" } }, { "test": "context.buildTimeConstants && context.buildTimeConstants.MINIGAME", "isVirtualModule": true, "overrides": { - "pal/minigame": "pal/minigame/{{context.platform.toLowerCase()}}.ts", - "pal/audio": "pal/audio/minigame/player.ts", - "pal/system-info": "pal/system-info/minigame/system-info.ts", - "pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.ts", - "pal/input": "pal/input/minigame/index.ts", - "pal/env": "pal/env/minigame/env.ts", - "pal/pacer": "pal/pacer/pacer-minigame.ts", - "pal/wasm": "pal/wasm/wasm-minigame.ts" + "pal/minigame": "pal/minigame/{{context.platform.toLowerCase()}}.js", + "pal/audio": "pal/audio/minigame/player.js", + "pal/system-info": "pal/system-info/minigame/system-info.js", + "pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.js", + "pal/input": "pal/input/minigame/index.js", + "pal/env": "pal/env/minigame/env.js", + "pal/pacer": "pal/pacer/pacer-minigame.js", + "pal/wasm": "pal/wasm/wasm-minigame.js" } }, { "test": "context.buildTimeConstants && context.buildTimeConstants.RUNTIME_BASED", "isVirtualModule": true, "overrides": { - "pal/minigame": "pal/minigame/runtime.ts", - "pal/audio": "pal/audio/minigame/player.ts", - "pal/system-info": "pal/system-info/minigame/system-info.ts", - "pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.ts", - "pal/input": "pal/input/minigame/index.ts", - "pal/env": "pal/env/runtime/env.ts", - "pal/pacer": "pal/pacer/pacer-minigame.ts", - "pal/wasm": "pal/wasm/wasm-minigame.ts" + "pal/minigame": "pal/minigame/runtime.js", + "pal/audio": "pal/audio/minigame/player.js", + "pal/system-info": "pal/system-info/minigame/system-info.js", + "pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.js", + "pal/input": "pal/input/minigame/index.js", + "pal/env": "pal/env/runtime/env.js", + "pal/pacer": "pal/pacer/pacer-minigame.js", + "pal/wasm": "pal/wasm/wasm-minigame.js" } }, { "test": "context.buildTimeConstants && context.buildTimeConstants.NODEJS", "isVirtualModule": true, "overrides": { - "pal/minigame": "pal/minigame/non-minigame.ts", - "pal/audio": "pal/audio/nodejs/player.ts", - "pal/system-info": "pal/system-info/nodejs/system-info.ts", - "pal/screen-adapter": "pal/screen-adapter/nodejs/screen-adapter.ts", - "pal/input": "pal/input/nodejs/index.ts", - "pal/env": "pal/env/nodejs/env.ts", - "pal/pacer": "pal/pacer/pacer-nodejs.ts", - "pal/wasm": "pal/wasm/wasm-nodejs.ts" + "pal/minigame": "pal/minigame/non-minigame.js", + "pal/audio": "pal/audio/nodejs/player.js", + "pal/system-info": "pal/system-info/nodejs/system-info.js", + "pal/screen-adapter": "pal/screen-adapter/nodejs/screen-adapter.js", + "pal/input": "pal/input/nodejs/index.js", + "pal/env": "pal/env/nodejs/env.js", + "pal/pacer": "pal/pacer/pacer-nodejs.js", + "pal/wasm": "pal/wasm/wasm-nodejs.js" } }, { @@ -885,10 +885,10 @@ "cocos/asset/asset-manager/weak-cache.ts", "cocos/2d/framework/ui-skew-utils.ts", "cocos/spine/lib/spine-binary.ts", - "pal/input/minigame/gamepad-input.ts", - "pal/input/minigame/handheld-input.ts", - "pal/input/minigame/handle-input.ts", - "pal/input/minigame/hmd-input.ts" + "pal/input/minigame/gamepad-input.js", + "pal/input/minigame/handheld-input.js", + "pal/input/minigame/handle-input.js", + "pal/input/minigame/hmd-input.js" ] } } diff --git a/cocos/render-scene/core/render-window.ts b/cocos/render-scene/core/render-window.ts index 1fdb6ad9f9..899161630c 100644 --- a/cocos/render-scene/core/render-window.ts +++ b/cocos/render-scene/core/render-window.ts @@ -21,12 +21,14 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +import { DEBUG } from 'internal:constants'; import { screenAdapter } from 'pal/screen-adapter'; import { Orientation } from '../../../pal/screen-adapter/enum-type'; import { TextureType, TextureUsageBit, Format, RenderPass, Texture, Framebuffer, RenderPassInfo, Device, TextureInfo, FramebufferInfo, Swapchain, SurfaceTransform, TextureFlagBit, TextureFlags, } from '../../gfx'; +import { warn } from '../../core/platform/debug'; import { Root } from '../../root'; import { Camera } from '../scene'; @@ -41,7 +43,10 @@ export interface IRenderWindowInfo { externalFlag?: TextureFlags; // external texture type normal or oes } -const orientationMap: Record = { +// NOTE: `Orientation` is a flag enum whose composite members (LANDSCAPE, AUTO) are never +// actual runtime orientations, so this map intentionally only covers the physical ones. +// It is therefore typed as Partial rather than a total Record. +const orientationMap: Partial> = { [Orientation.PORTRAIT]: SurfaceTransform.IDENTITY, [Orientation.LANDSCAPE_RIGHT]: SurfaceTransform.ROTATE_90, [Orientation.PORTRAIT_UPSIDE_DOWN]: SurfaceTransform.ROTATE_180, @@ -253,7 +258,11 @@ export class RenderWindow { */ public resize (width: number, height: number): void { if (this._swapchain) { - this._swapchain.resize(width, height, orientationMap[screenAdapter.orientation]); + const surfaceTransform = orientationMap[screenAdapter.orientation]; + if (DEBUG && surfaceTransform === undefined) { + warn(`Unexpected screen orientation: ${screenAdapter.orientation}`); + } + this._swapchain.resize(width, height, surfaceTransform || SurfaceTransform.IDENTITY); this._width = this._swapchain.width; this._height = this._swapchain.height; } else { diff --git a/package-lock.json b/package-lock.json index ced020d96a..8281d7813a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,8 +13,10 @@ "@babel/plugin-proposal-class-properties": "^7.18.6", "@cocos/box2d": "1.0.2", "@cocos/cannon": "1.2.8", - "@cocos/ccbuild": "^2.3.16", + "@cocos/ccbuild": "^2.3.21", "@cocos/dragonbones-js": "^1.0.1", + "@cocos/engine-pal": "^1.0.4", + "@cocos/engine-platforms": "^1.0.5", "@types/jest": "^24.9.1" }, "devDependencies": { @@ -2064,9 +2066,13 @@ } }, "node_modules/@cocos/ccbuild": { - "version": "2.3.16", - "resolved": "https://registry.npmjs.org/@cocos/ccbuild/-/ccbuild-2.3.16.tgz", - "integrity": "sha512-ZfY2ZJXs0uIMyjQLuZH9CZ4CGhM4YTdn9eGBPV62tXaSLkIHU/o0Vp99CqVxP1vYM1Ud1Z6a/fArLP/Qe3/IIQ==", + "version": "2.3.21", + "resolved": "https://registry.npmmirror.com/@cocos/ccbuild/-/ccbuild-2.3.21.tgz", + "integrity": "sha512-hwsuAQKW55jGCZvVmH/09Mvz3i6hv8XN5udHGJJrQc2IYOLCctymoHfuyobcQ+LI+qHRSRKKgc+cKN2jWZ0sTA==", + "license": "MIT", + "workspaces": [ + "./modules/*" + ], "dependencies": { "@babel/core": "^7.20.12", "@babel/generator": "^7.22.10", @@ -2561,6 +2567,16 @@ "resolved": "https://registry.npmjs.org/@cocos/dragonbones-js/-/dragonbones-js-1.0.1.tgz", "integrity": "sha512-1bWAW8td2WTGicyCqxtpIjc1YuK5EzMWfMEWaJlskPAQwLS0JfxEGka71sZ1BzudiWiKS7hPMg+FvXr5NRnVwQ==" }, + "node_modules/@cocos/engine-pal": { + "version": "1.0.4", + "resolved": "https://registry.npmmirror.com/@cocos/engine-pal/-/engine-pal-1.0.4.tgz", + "integrity": "sha512-VtvO0xE2ZviVtwqWn4P6cysn2BX7QABm9sNc1rfy4gy+FHtiwSMkLLL3l3Faw+yZiTE6EwxjPvnc96Igb7mNuQ==" + }, + "node_modules/@cocos/engine-platforms": { + "version": "1.0.5", + "resolved": "https://registry.npmmirror.com/@cocos/engine-platforms/-/engine-platforms-1.0.5.tgz", + "integrity": "sha512-ES004q8DkuexPk8B4teXzCmAZNW8G4iqnLYJn/VZhYEOMDpySF8HhNfBl2M91BMnsCXlvJILABLKEVUCqUL+aA==" + }, "node_modules/@cocos/rollup-plugin-terser": { "version": "0.4.5", "resolved": "https://registry.npmjs.org/@cocos/rollup-plugin-terser/-/rollup-plugin-terser-0.4.5.tgz", diff --git a/package.json b/package.json index b934b3c12d..e650cc3c6d 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "node": ">=18.0.0" }, "scripts": { - "postinstall": "npm run build:debug-infos && npm run build:declaration && npm run build:adapter && npm run build:native-pack-tool", + "postinstall": "node scripts/spread-pal.cjs && npm run build:debug-infos && npm run build:declaration && node scripts/spread-adapter.cjs && npm run build:native-pack-tool", "build": "npm run build:min && npm run build:declaration", "build:cli": "npm run build:cli-min && npm run build:declaration", "build:adapter": "node ./scripts/build-adapter.js", @@ -81,8 +81,14 @@ "@babel/plugin-proposal-class-properties": "^7.18.6", "@cocos/box2d": "1.0.2", "@cocos/cannon": "1.2.8", - "@cocos/ccbuild": "^2.3.16", + "@cocos/ccbuild": "^2.3.21", "@cocos/dragonbones-js": "^1.0.1", + "@cocos/engine-pal": "^1.0.4", + "@cocos/engine-platforms": "^1.0.5", "@types/jest": "^24.9.1" - } + }, + "creator": { + "version": "3.8.8" + }, + "uuid": "8be51d4a-79ad-481c-adbf-265693b5adbf" } diff --git a/pal/audio/audio-buffer-manager.ts b/pal/audio/audio-buffer-manager.ts deleted file mode 100644 index 7cd539334e..0000000000 --- a/pal/audio/audio-buffer-manager.ts +++ /dev/null @@ -1,82 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { warnID } from '../../cocos/core/platform/debug'; - -/** @mangle */ -interface CachedAudioBufferData { - usedCount: number, - audioBuffer: AudioBuffer, -} - -interface AudioBufferDataMap { - [url: string]: CachedAudioBufferData; -} - -/** - * This is a manager to manage the cache of audio buffer for web audio. - * @mangle - */ -class AudioBufferManager { - private _audioBufferDataMap: AudioBufferDataMap = {}; - - public addCache (url: string, audioBuffer: AudioBuffer): void { - const audioBufferData = this._audioBufferDataMap[url]; - if (audioBufferData) { - warnID(5204, url); - return; - } - this._audioBufferDataMap[url] = { - usedCount: 1, - audioBuffer, - }; - } - - public retainCache (url: string): void { - const audioBufferData = this._audioBufferDataMap[url]; - if (!audioBufferData) { - warnID(5203, url); - return; - } - audioBufferData.usedCount++; - } - - public getCache (url: string): AudioBuffer | null | undefined { - const audioBufferData = this._audioBufferDataMap[url]; - return audioBufferData?.audioBuffer; - } - - public tryReleasingCache (url: string): void { - const audioBufferData = this._audioBufferDataMap[url]; - if (!audioBufferData) { - warnID(5203, url); - return; - } - if (--audioBufferData.usedCount <= 0) { - delete this._audioBufferDataMap[url]; - } - } -} - -export const audioBufferManager = new AudioBufferManager(); diff --git a/pal/audio/audio-timer.ts b/pal/audio/audio-timer.ts deleted file mode 100644 index dac75ce420..0000000000 --- a/pal/audio/audio-timer.ts +++ /dev/null @@ -1,119 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { clamp } from '../../cocos/core/math/utils'; - -/** - * Tool class to calculate audio current time. - * For some platforms where audio.currentTime doesn't work well or isn't implemented. - */ - -interface IDuration { - duration: number; -} - -export default class AudioTimer { - private _nativeAudio: IDuration; - private _startTime = 0; - private _startOffset = 0; - private _isPaused = true; - - constructor (nativeAudio: IDuration) { - this._nativeAudio = nativeAudio; - } - - public destroy (): void { - // NOTE: 'undefined' is not assignable to type 'IDuration' - this._nativeAudio = undefined as any; - } - - get duration (): number { - return this._nativeAudio.duration; - } - - /** - * Get the current time of audio timer. - */ - get currentTime (): number { - if (this._isPaused) { - return this._startOffset; - } else { - return this._calculateCurrentTime(); - } - } - - private _now (): number { - return performance.now() / 1000; - } - - private _calculateCurrentTime (): number { - const timePassed = this._now() - this._startTime; - const currentTime = this._startOffset + timePassed; - if (currentTime >= this.duration) { - // timer loop - this._startTime = this._now(); - this._startOffset = 0; - } - return currentTime % this.duration; - } - - /** - * Start the audio timer. - * Call this method when audio is played. - */ - start (): void { - this._isPaused = false; - this._startTime = this._now(); - } - - /** - * Pause the audio timer. - * Call this method when audio is paused or interrupted. - */ - pause (): void { - if (this._isPaused) { - return; - } - this._isPaused = true; - this._startOffset = this._calculateCurrentTime(); - } - - /** - * Stop the audio timer. - * Call this method when audio playing ended or audio is stopped. - */ - stop (): void { - this._isPaused = true; - this._startOffset = 0; - } - - /** - * Seek the audio timer. - * Call this method when audio is seeked. - */ - seek (time: number): void { - this._startTime = this._now(); - this._startOffset = clamp(time, 0, this.duration); - } -} diff --git a/pal/audio/minigame/player-minigame.ts b/pal/audio/minigame/player-minigame.ts deleted file mode 100644 index 05d582cbd6..0000000000 --- a/pal/audio/minigame/player-minigame.ts +++ /dev/null @@ -1,393 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { minigame } from 'pal/minigame'; -import { systemInfo } from 'pal/system-info'; -import { TAOBAO, TAOBAO_MINIGAME, HUAWEI, VIVO, OPPO } from 'internal:constants'; -import { EventTarget } from '../../../cocos/core/event'; -import { AudioEvent, AudioPCMDataView, AudioState, AudioType } from '../type'; -import { clamp, clamp01 } from '../../../cocos/core'; -import { enqueueOperation, OperationInfo, OperationQueueable } from '../operation-queue'; -import { OS } from '../../system-info/enum-type'; - -export class OneShotAudioMinigame { - private declare _innerAudioContext: InnerAudioContext; - private _onPlayCb?: () => void; - get onPlay (): (() => void) | undefined { - return this._onPlayCb; - } - set onPlay (cb) { - this._onPlayCb = cb; - } - - private _onEndCb?: () => void; - get onEnd (): (() => void) | undefined { - return this._onEndCb; - } - set onEnd (cb) { - this._onEndCb = cb; - } - - private constructor (nativeAudio: InnerAudioContext, volume: number) { - this._innerAudioContext = nativeAudio; - nativeAudio.volume = volume; - nativeAudio.onPlay(() => { - this._onPlayCb?.(); - }); - const endCallback = (): void => { - if (this._innerAudioContext) { - // NOTE: Type 'null' is not assignable to type 'InnerAudioContext'. - this._innerAudioContext = null as any; - systemInfo.off('hide', this._onInterruptedBegin, this); - systemInfo.off('show', this._onInterruptedEnd, this); - this._onEndCb?.(); - /**The destroy interface, in some platform implementations, internally invokes stop, - * triggering the onStop callback, consequently leading to an infinite loop. **/ - nativeAudio.destroy(); - } - }; - nativeAudio.onEnded(endCallback); - nativeAudio.onStop(endCallback);//OneShotAudio can not be reused. - - // event - systemInfo.on('hide', this._onInterruptedBegin, this); - systemInfo.on('show', this._onInterruptedEnd, this); - } - - private _onInterruptedBegin (): void { - this._innerAudioContext.pause(); - } - - private _onInterruptedEnd (): void { - this._innerAudioContext.play(); - } - - public play (): void { - this._innerAudioContext.play(); - } - public stop (): void { - this._innerAudioContext.stop(); - } -} - -export class AudioPlayerMinigame implements OperationQueueable { - private declare _innerAudioContext: InnerAudioContext; - private _state: AudioState = AudioState.INIT; - private _cacheTime = 0; - private _needSeek = false; - private _seeking = false; - - private declare _onPlay: () => void; - private declare _onPause: () => void; - private declare _onStop: () => void; - private declare _onSeeked: () => void; - private declare _onEnded: () => void; - private _readyToHandleOnShow = false; - - private _resetSeekCache (): void { - this._cacheTime = 0; - this._needSeek = false; - this._seeking = false; - if ((HUAWEI || VIVO || OPPO) && this._innerAudioContext) { - this._innerAudioContext.startTime = 0; - } - } - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _eventTarget: EventTarget = new EventTarget(); - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _operationQueue: OperationInfo[] = []; - - constructor (innerAudioContext: InnerAudioContext) { - const self = this; - self._innerAudioContext = innerAudioContext; - - // event - systemInfo.on('hide', self._onInterruptedBegin, self); - systemInfo.on('show', self._onInterruptedEnd, self); - const eventTarget = self._eventTarget; - self._onPlay = (): void => { - self._state = AudioState.PLAYING; - eventTarget.emit(AudioEvent.PLAYED); - if (self._needSeek) { - // eslint-disable-next-line @typescript-eslint/no-empty-function - self.seek(self._cacheTime).catch((e) => {}); - } - }; - innerAudioContext.onPlay(self._onPlay); - self._onPause = (): void => { - self._state = AudioState.PAUSED; - try { - const currentTime = self._innerAudioContext.currentTime; - if (currentTime !== null && currentTime !== undefined) { - self._cacheTime = currentTime; - } - } catch { - // Do nothing, cacheTime is not updated. - } - eventTarget.emit(AudioEvent.PAUSED); - }; - innerAudioContext.onPause(self._onPause); - self._onStop = (): void => { - self._state = AudioState.STOPPED; - // Reset all properties - self._resetSeekCache(); - eventTarget.emit(AudioEvent.STOPPED); - if (TAOBAO || TAOBAO_MINIGAME) { - /**Unable to seek again after stop; After stop, regardless of whether the starttime has been set, - the playback will always start from 0 again**/ - } else { - const currentTime = self._innerAudioContext ? self._innerAudioContext.currentTime : 0; - if (currentTime !== 0) { - self._innerAudioContext.seek(0); - } - } - }; - innerAudioContext.onStop(self._onStop); - self._onSeeked = (): void => { - eventTarget.emit(AudioEvent.SEEKED); - self._seeking = false; - if (self._needSeek) { - self._needSeek = false; - if (self._cacheTime.toFixed(2) !== self._innerAudioContext.currentTime.toFixed(2)) { - // eslint-disable-next-line @typescript-eslint/no-empty-function - self.seek(self._cacheTime).catch((e) => {}); - } - } - }; - innerAudioContext.onSeeked(self._onSeeked); - self._onEnded = (): void => { - self._state = AudioState.INIT; - self._resetSeekCache(); - eventTarget.emit(AudioEvent.ENDED); - }; - innerAudioContext.onEnded(self._onEnded); - } - destroy (): void { - const self = this; - systemInfo.off('hide', self._onInterruptedBegin, self); - systemInfo.off('show', self._onInterruptedEnd, self); - const innerAudioContext = self._innerAudioContext; - if (innerAudioContext) { - ['Play', 'Pause', 'Stop', 'Seeked', 'Ended'].forEach((event) => { - self._offEvent(event); - }); - // NOTE: innerAudioContext might not stop the audio playing, have to call it explicitly. - innerAudioContext.stop(); - innerAudioContext.destroy(); - // NOTE: Type 'null' is not assignable to type 'InnerAudioContext' - self._innerAudioContext = null as any; - // Restore the state of the audio, otherwise it will cause 'destroy' to be called first and 'stop' to be called later. - // this will cause a error. - self._state = AudioState.INIT; - } - } - private _onInterruptedBegin (): void { - if (this._state === AudioState.PLAYING) { - this.pause().then(() => { - this._state = AudioState.INTERRUPTED; - this._readyToHandleOnShow = true; - this._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN); - // eslint-disable-next-line @typescript-eslint/no-empty-function - }).catch((e) => {}); - } - } - private _onInterruptedEnd (): void { - // We don't know whether onShow or resolve callback in pause promise is called at first. - if (!this._readyToHandleOnShow) { - this._eventTarget.once(AudioEvent.INTERRUPTION_END, this._onInterruptedEnd, this); - return; - } - if (this._state === AudioState.INTERRUPTED) { - this.play().then(() => { - this._eventTarget.emit(AudioEvent.INTERRUPTION_END); - // eslint-disable-next-line @typescript-eslint/no-empty-function - }).catch((e) => {}); - } - this._readyToHandleOnShow = false; - } - private _offEvent (eventName: string): void { - if (this[`_on${eventName}`]) { - this._innerAudioContext[`off${eventName}`](this[`_on${eventName}`]); - this[`_on${eventName}`] = null; - } - } - - get src (): string { - return this._innerAudioContext ? this._innerAudioContext.src : ''; - } - get type (): AudioType { - return AudioType.MINIGAME_AUDIO; - } - static load (url: string): Promise { - return new Promise((resolve, reject) => { - AudioPlayerMinigame.loadNative(url).then((innerAudioContext) => { - resolve(new AudioPlayerMinigame(innerAudioContext as InnerAudioContext)); - }).catch(reject); - }); - } - static loadNative (url: string): Promise { - return new Promise((resolve, reject) => { - const innerAudioContext = minigame.createInnerAudioContext(); - const timer = setTimeout(() => { - clearEvent(); - resolve(innerAudioContext); - }, 8000); - function clearEvent (): void { - innerAudioContext.offCanplay(success); - innerAudioContext.offError(fail); - } - function success (): void { - clearEvent(); - clearTimeout(timer); - resolve(innerAudioContext); - } - function fail (err): void { - clearEvent(); - clearTimeout(timer); - // eslint-disable-next-line no-console - console.error('failed to load innerAudioContext'); - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - reject(new Error(err)); - } - innerAudioContext.onCanplay(success); - innerAudioContext.onError(fail); - innerAudioContext.src = url; - }); - } - static loadOneShotAudio (url: string, volume: number): Promise { - return new Promise((resolve, reject) => { - AudioPlayerMinigame.loadNative(url).then((innerAudioContext) => { - // HACK: AudioPlayer should be a friend class in OneShotAudio - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - resolve(new (OneShotAudioMinigame as any)(innerAudioContext, volume)); - }).catch(reject); - }); - } - - get state (): AudioState { - return this._state; - } - get loop (): boolean { - return this._innerAudioContext.loop; - } - set loop (val: boolean) { - this._innerAudioContext.loop = val; - } - get volume (): number { - return this._innerAudioContext.volume; - } - set volume (val: number) { - val = clamp01(val); - this._innerAudioContext.volume = val; - } - get duration (): number { - // KNOWN ISSUES: duration doesn't work well - // On WeChat platform, duration is 0 at the time audio is loaded. - return this._innerAudioContext.duration; - } - get currentTime (): number { - if ((HUAWEI || VIVO || OPPO) && (this._state === AudioState.STOPPED || this._state === AudioState.INIT)) { - return this._innerAudioContext.startTime; - } - if (this._state !== AudioState.PLAYING || this._needSeek || this._seeking) { - return this._cacheTime; - } - return this._innerAudioContext.currentTime; - } - - get sampleRate (): number { - return 0; - } - - public getPCMData (channelIndex: number): AudioPCMDataView | undefined { - return undefined; - } - - @enqueueOperation - seek (time: number): Promise { - return new Promise((resolve) => { - // KNOWN ISSUES: on Baidu: currentTime returns without numbers on decimal places - if (this._state === AudioState.PLAYING && !this._seeking) { - time = clamp(time, 0, this.duration); - this._seeking = true; - this._cacheTime = time; - this._eventTarget.once(AudioEvent.SEEKED, resolve); - this._innerAudioContext.seek(time); - } else { - //Huawei, vivo, Oppo platform, after stop, regardless of whether the seek has been called, the playback will always start from 0 again - if ((HUAWEI || VIVO || OPPO) && (this._state === AudioState.STOPPED || this._state === AudioState.INIT)) { - this._innerAudioContext.startTime = time; - } else if (this._cacheTime !== time) { // Skip the invalid seek - this._cacheTime = time; - this._needSeek = true; - } - resolve(); - } - }); - } - - @enqueueOperation - play (): Promise { - return new Promise((resolve) => { - this._eventTarget.once(AudioEvent.PLAYED, resolve); - this._innerAudioContext.play(); - }); - } - - @enqueueOperation - pause (): Promise { - return new Promise((resolve) => { - if (this.state !== AudioState.PLAYING) { - resolve(); - } else { - this._eventTarget.once(AudioEvent.PAUSED, resolve); - this._innerAudioContext.pause(); - } - }); - } - - @enqueueOperation - stop (): Promise { - return new Promise((resolve) => { - if (AudioState.INIT === this._state) { - this._resetSeekCache(); - resolve(); - return; - } - this._eventTarget.once(AudioEvent.STOPPED, resolve); - this._innerAudioContext.stop(); - }); - } - - onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); } - offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); } - onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); } - offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); } - onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); } - offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); } -} diff --git a/pal/audio/minigame/player-web.ts b/pal/audio/minigame/player-web.ts deleted file mode 100644 index b5e8ae909c..0000000000 --- a/pal/audio/minigame/player-web.ts +++ /dev/null @@ -1,323 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { minigame } from 'pal/minigame'; -import { systemInfo } from 'pal/system-info'; -import { clamp01 } from '../../../cocos/core'; -import * as debug from '../../../cocos/core/platform/debug'; -import { EventTarget } from '../../../cocos/core/event'; -import { audioBufferManager } from '../audio-buffer-manager'; -import AudioTimer from '../audio-timer'; -import { enqueueOperation, OperationInfo, OperationQueueable } from '../operation-queue'; -import { AudioEvent, AudioPCMDataView, AudioState, AudioType } from '../type'; -import { Game, game } from '../../../cocos/game'; - -declare const fsUtils: any; -const audioContext = minigame.tt?.getAudioContext?.(); - -export class OneShotAudioWeb { - private _bufferSourceNode: AudioBufferSourceNode; - private _onPlayCb?: () => void; - private _url: string; - - get onPlay (): (() => void) | undefined { - return this._onPlayCb; - } - set onPlay (cb) { - this._onPlayCb = cb; - } - - private _onEndCb?: () => void; - get onEnd (): (() => void) | undefined { - return this._onEndCb; - } - set onEnd (cb) { - this._onEndCb = cb; - } - - private constructor (audioBuffer: AudioBuffer, volume: number, url: string) { - this._bufferSourceNode = audioContext!.createBufferSource(); - this._bufferSourceNode.buffer = audioBuffer; - this._bufferSourceNode.loop = false; - this._url = url; - - const gainNode = audioContext!.createGain(); - gainNode.gain.value = volume; - - this._bufferSourceNode.connect(gainNode); - gainNode.connect(audioContext!.destination); - } - - public play (): void { - this._bufferSourceNode.start(); - this.onPlay?.(); - this._bufferSourceNode.onended = (): void => { - audioBufferManager.tryReleasingCache(this._url); - this._onEndCb?.(); - }; - } - - public stop (): void { - this._bufferSourceNode.onended = null; // stop will call ended callback - audioBufferManager.tryReleasingCache(this._url); - this._bufferSourceNode.stop(); - this._bufferSourceNode.disconnect(); - this._bufferSourceNode.buffer = null; - } -} - -export class AudioPlayerWeb implements OperationQueueable { - private _src: string; - private _audioBuffer: AudioBuffer; - private _sourceNode?: AudioBufferSourceNode; - private _gainNode: GainNode; - private _volume = 1; - private _loop = false; - private _state: AudioState = AudioState.INIT; - private _audioTimer: AudioTimer; - private _readyToHandleOnShow = false; - - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _eventTarget: EventTarget = new EventTarget(); - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _operationQueue: OperationInfo[] = []; - - constructor (audioBuffer: AudioBuffer, url: string) { - this._audioBuffer = audioBuffer; - this._audioTimer = new AudioTimer(audioBuffer); - this._gainNode = audioContext!.createGain(); - this._gainNode.connect(audioContext!.destination); - - this._src = url; - // event - game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this); - game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this); - } - destroy (): void { - this._audioTimer.destroy(); - if (this._audioBuffer) { - // NOTE: need to release AudioBuffer instance - this._audioBuffer = null as any; - } - audioBufferManager.tryReleasingCache(this._src); - game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this); - game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this); - } - private _onInterruptedBegin (): void { - if (this._state === AudioState.PLAYING) { - this.pause().then(() => { - this._state = AudioState.INTERRUPTED; - this._readyToHandleOnShow = true; - this._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN); - }).catch((e) => { debug.warn('_onInterruptedBegin error', e); }); - } - } - private _onInterruptedEnd (): void { - // We don't know whether onShow or resolve callback in pause promise is called at first. - if (!this._readyToHandleOnShow) { - this._eventTarget.once(AudioEvent.INTERRUPTION_BEGIN, this._onInterruptedEnd, this); - return; - } - if (this._state === AudioState.INTERRUPTED) { - this.play().then(() => { - this._eventTarget.emit(AudioEvent.INTERRUPTION_END); - }).catch((e) => { debug.warn('_onInterruptedEnd error', e); }); - } - this._readyToHandleOnShow = false; - } - static load (url: string): Promise { - return new Promise((resolve, reject) => { - AudioPlayerWeb.loadNative(url).then((audioBuffer) => { - resolve(new AudioPlayerWeb(audioBuffer, url)); - }).catch(reject); - }); - } - static loadNative (url: string): Promise { - return new Promise((resolve, reject) => { - // NOTE: maybe url is a temp path, which is not reliable. - // need to cache the decoded audio buffer. - const cachedAudioBuffer = audioBufferManager.getCache(url); - if (cachedAudioBuffer) { - audioBufferManager.retainCache(url); - resolve(cachedAudioBuffer); - return; - } - // TODO: use pal/fs - globalThis.fsUtils.readArrayBuffer(url, (err: Error, arrayBuffer: ArrayBuffer) => { - if (err) { - reject(err); - return; - } - audioContext!.decodeAudioData(arrayBuffer).then((decodedAudioBuffer) => { - audioBufferManager.addCache(url, decodedAudioBuffer); - resolve(decodedAudioBuffer); - }).catch(reject); - }); - }); - } - - static loadOneShotAudio (url: string, volume: number): Promise { - return new Promise((resolve, reject) => { - AudioPlayerWeb.loadNative(url).then((audioBuffer) => { - // HACK: AudioPlayer should be a friend class in OneShotAudio - const oneShotAudio = new (OneShotAudioWeb as any)(audioBuffer, volume, url); - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - resolve(oneShotAudio); - }).catch(reject); - }); - } - - get src (): string { - return this._src; - } - get type (): AudioType { - return AudioType.WEB_AUDIO; - } - get state (): AudioState { - return this._state; - } - get loop (): boolean { - return this._loop; - } - set loop (val: boolean) { - this._loop = val; - if (this._sourceNode) { - this._sourceNode.loop = val; - } - } - get volume (): number { - return this._volume; - } - set volume (val: number) { - val = clamp01(val); - this._volume = val; - this._gainNode.gain.value = val; - } - get duration (): number { - return this._audioBuffer.duration; - } - get currentTime (): number { - return this._audioTimer.currentTime; - } - - get sampleRate (): number { - return this._audioBuffer.sampleRate; - } - - public getPCMData (channelIndex: number): AudioPCMDataView | undefined { - return new AudioPCMDataView(this._audioBuffer.getChannelData(channelIndex), 1); - } - - @enqueueOperation - seek (time: number): Promise { - return new Promise((resolve) => { - this._audioTimer.seek(time); - if (this._state === AudioState.PLAYING) { - // one AudioBufferSourceNode can't start twice - // need to create a new one to start from the offset - this._doPlay().then(resolve).catch((e) => { debug.warn('seek error', e); }); - } else { - resolve(); - } - }); - } - - @enqueueOperation - play (): Promise { - return this._doPlay(); - } - - // The decorated play() method can't be call in seek() - // so we define this method to ensure that the audio seeking works. - private _doPlay (): Promise { - return new Promise((resolve) => { - // one AudioBufferSourceNode can't start twice - this._stopSourceNode(); - this._sourceNode = audioContext!.createBufferSource(); - this._sourceNode.buffer = this._audioBuffer; - this._sourceNode.loop = this._loop; - this._sourceNode.connect(this._gainNode); - - this._sourceNode.start(0, this._audioTimer.currentTime); - this._state = AudioState.PLAYING; - this._audioTimer.start(); - - this._sourceNode.onended = (): void => { - this._audioTimer.stop(); - this._eventTarget.emit(AudioEvent.ENDED); - this._state = AudioState.INIT; - }; - resolve(); - }); - } - - private _stopSourceNode (): void { - try { - if (this._sourceNode) { - this._sourceNode.onended = null; // stop will call ended callback - this._sourceNode.stop(); - this._sourceNode.disconnect(); - this._sourceNode.buffer = null; - this._sourceNode = undefined; - } - } catch (e) { - // sourceNode can't be stopped twice, especially on Safari. - } - } - - @enqueueOperation - pause (): Promise { - if (this._state !== AudioState.PLAYING || !this._sourceNode) { - return Promise.resolve(); - } - this._audioTimer.pause(); - this._state = AudioState.PAUSED; - this._stopSourceNode(); - return Promise.resolve(); - } - - @enqueueOperation - stop (): Promise { - if (!this._sourceNode) { - this._audioTimer.stop(); - this._state = AudioState.STOPPED; - return Promise.resolve(); - } - this._audioTimer.stop(); - this._state = AudioState.STOPPED; - this._stopSourceNode(); - return Promise.resolve(); - } - - onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); } - offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); } - onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); } - offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); } - onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); } - offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); } -} diff --git a/pal/audio/minigame/player.ts b/pal/audio/minigame/player.ts deleted file mode 100644 index 128bc512c8..0000000000 --- a/pal/audio/minigame/player.ts +++ /dev/null @@ -1,132 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { minigame } from 'pal/minigame'; -import { legacyCC } from '../../../cocos/core/global-exports'; -import { AudioLoadOptions, AudioType, AudioState, AudioPCMDataView } from '../type'; -import { AudioPlayerMinigame, OneShotAudioMinigame } from './player-minigame'; -import { AudioPlayerWeb, OneShotAudioWeb } from './player-web'; - -type AbstractOneShotAudio = OneShotAudioMinigame | OneShotAudioWeb; -type AbstractAudioPlayer = AudioPlayerMinigame | AudioPlayerWeb; - -export class OneShotAudio { - private _audio: AbstractOneShotAudio; - get onPlay (): (() => void) | undefined { - return this._audio.onPlay; - } - set onPlay (v) { - this._audio.onPlay = v; - } - - get onEnd (): (() => void) | undefined { - return this._audio.onEnd; - } - set onEnd (v) { - this._audio.onEnd = v; - } - - private constructor (audio: AbstractOneShotAudio) { - this._audio = audio; - } - public play (): void { - this._audio.play(); - } - public stop (): void { - this._audio.stop(); - } -} - -export class AudioPlayer { - private _player: AbstractAudioPlayer; - constructor (player: AbstractAudioPlayer) { - this._player = player; - } - - static load (url: string, opts?: AudioLoadOptions): Promise { - return new Promise((resolve, reject) => { - /*if (typeof minigame.tt === 'object' && typeof minigame.tt.getAudioContext !== 'undefined') { - AudioPlayerWeb.load(url).then((webPlayer) => { - resolve(new AudioPlayer(webPlayer)); - }).catch(reject); - } else {*/ - AudioPlayerMinigame.load(url).then((minigamePlayer) => { - resolve(new AudioPlayer(minigamePlayer)); - }).catch(reject); - // } - }); - } - destroy (): void { - this._player.destroy(); - } - static loadNative (url: string, opts?: AudioLoadOptions): Promise { - /*if (typeof minigame.tt === 'object' && typeof minigame.tt.getAudioContext !== 'undefined') { - return AudioPlayerWeb.loadNative(url); - }*/ - return AudioPlayerMinigame.loadNative(url); - } - static loadOneShotAudio (url: string, volume: number, opts?: AudioLoadOptions): Promise { - return new Promise((resolve, reject) => { - /*if (typeof minigame.tt === 'object' && typeof minigame.tt.getAudioContext !== 'undefined') { - AudioPlayerWeb.loadOneShotAudio(url, volume).then((oneShotAudioWeb) => { - // HACK: AudioPlayer should be a friend class in OneShotAudio - resolve(new (OneShotAudio as any)(oneShotAudioWeb)); - }).catch(reject); - } else {*/ - AudioPlayerMinigame.loadOneShotAudio(url, volume).then((oneShotAudioMinigame) => { - // HACK: AudioPlayer should be a friend class in OneShotAudio - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - resolve(new (OneShotAudio as any)(oneShotAudioMinigame)); - }).catch(reject); - //} - }); - } - static readonly maxAudioChannel = 10; - - get src (): string { return this._player.src; } - get type (): AudioType { return this._player.type; } - get state (): AudioState { return this._player.state; } - get loop (): boolean { return this._player.loop; } - set loop (val: boolean) { this._player.loop = val; } - get volume (): number { return this._player.volume; } - set volume (val: number) { this._player.volume = val; } - get duration (): number { return this._player.duration; } - get currentTime (): number { return this._player.currentTime; } - get sampleRate (): number { return this._player.sampleRate; } - getPCMData (channelIndex: number): AudioPCMDataView | undefined { return this._player.getPCMData(channelIndex); } - seek (time: number): Promise { return this._player.seek(time); } - - play (): Promise { return this._player.play(); } - pause (): Promise { return this._player.pause(); } - stop (): Promise { return this._player.stop(); } - onInterruptionBegin (cb: () => void): void { this._player.onInterruptionBegin(cb); } - offInterruptionBegin (cb?: () => void): void { this._player.offInterruptionBegin(cb); } - onInterruptionEnd (cb: () => void): void { this._player.onInterruptionEnd(cb); } - offInterruptionEnd (cb?: () => void): void { this._player.offInterruptionEnd(cb); } - onEnded (cb: () => void): void { this._player.onEnded(cb); } - offEnded (cb?: () => void): void { this._player.offEnded(cb); } -} - -// REMOVE_ME -legacyCC.AudioPlayer = AudioPlayer; diff --git a/pal/audio/native/player.ts b/pal/audio/native/player.ts deleted file mode 100644 index d7b20f746e..0000000000 --- a/pal/audio/native/player.ts +++ /dev/null @@ -1,343 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { systemInfo } from 'pal/system-info'; -import { AudioType, AudioState, AudioEvent, AudioPCMDataView, AudioBufferView, AudioLoadOptions } from '../type'; -import { EventTarget } from '../../../cocos/core/event'; -import { legacyCC } from '../../../cocos/core/global-exports'; -import { clamp, clamp01 } from '../../../cocos/core'; -import { enqueueOperation, OperationInfo, OperationQueueable } from '../operation-queue'; -import { Platform } from '../../system-info/enum-type'; -import { Game, game } from '../../../cocos/game'; - -const urlCount: Record = {}; -const audioEngine = jsb.AudioEngine; -const INVALID_AUDIO_ID = -1; - -enum AudioBufferFormat { - UNKNOWN = 0, - SIGNED_8, - UNSIGNED_8, - SIGNED_16, - UNSIGNED_16, - SIGNED_32, - UNSIGNED_32, - FLOAT_32, - FLOAT_64 -} - -interface AudioBufferInfo { - ctor: Constructor, - maxValue: number; -} - -const bufferConstructorMap: Record = { - [AudioBufferFormat.UNKNOWN]: undefined, - [AudioBufferFormat.SIGNED_8]: { ctor: Int8Array, maxValue: 127 }, - [AudioBufferFormat.UNSIGNED_8]: { ctor: Uint8Array, maxValue: 255 }, - [AudioBufferFormat.SIGNED_16]: { ctor: Int16Array, maxValue: 32767 }, - [AudioBufferFormat.UNSIGNED_16]: { ctor: Uint16Array, maxValue: 65535 }, - [AudioBufferFormat.SIGNED_32]: { ctor: Int32Array, maxValue: 2147483647 }, - [AudioBufferFormat.UNSIGNED_32]: { ctor: Uint32Array, maxValue: 4294967295 }, - // decoded float data is normalized data, so we specify the maxValue as 1. - [AudioBufferFormat.FLOAT_32]: { ctor: Float32Array, maxValue: 1 }, - [AudioBufferFormat.FLOAT_64]: { ctor: Float64Array, maxValue: 1 }, -}; - -export class OneShotAudio { - private _id: number = INVALID_AUDIO_ID; - private _url: string; - private _volume: number; - private _onPlayCb?: () => void; - get onPlay (): (() => void) | undefined { - return this._onPlayCb; - } - set onPlay (cb) { - this._onPlayCb = cb; - } - - private _onEndCb?: () => void; - get onEnd (): (() => void) | undefined { - return this._onEndCb; - } - set onEnd (cb) { - this._onEndCb = cb; - } - - private constructor (url: string, volume: number) { - this._url = url; - this._volume = volume; - } - public play (): void { - this._id = jsb.AudioEngine.play2d(this._url, false, this._volume); - jsb.AudioEngine.setFinishCallback(this._id, () => { - this.onEnd?.(); - }); - this.onPlay?.(); - } - public stop (): void { - if (this._id === INVALID_AUDIO_ID) { - return; - } - jsb.AudioEngine.stop(this._id); - } -} - -export class AudioPlayer implements OperationQueueable { - private _url: string; - private _id: number = INVALID_AUDIO_ID; - private _state: AudioState = AudioState.INIT; - private _pcmHeader: jsb.PCMHeader | null; - - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _eventTarget: EventTarget = new EventTarget(); - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _operationQueue: OperationInfo[] = []; - - // NOTE: we need to cache the state in case the audio id is invalid. - private _cachedState = { - duration: 1, // wrong value before playing - loop: false, - currentTime: 0, - volume: 1, - } - - constructor (url: string) { - this._url = url; - // this._pcmHeader = audioEngine.getPCMHeader(url); - this._pcmHeader = null; - // event - game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this); - game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this); - } - destroy (): void { - game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this); - game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this); - if (--urlCount[this._url] <= 0) { - audioEngine.uncache(this._url); - } - } - private _onInterruptedBegin (): void { - if (this._state === AudioState.PLAYING) { - this.pause().then(() => { - this._state = AudioState.INTERRUPTED; - this._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN); - }).catch((e) => {}); - } - } - private _onInterruptedEnd (): void { - if (this._state === AudioState.INTERRUPTED) { - this.play().then(() => { - this._eventTarget.emit(AudioEvent.INTERRUPTION_END); - }).catch((e) => {}); - } - } - static load (url: string, opts?: AudioLoadOptions): Promise { - return new Promise((resolve, reject) => { - AudioPlayer.loadNative(url, opts).then((url) => { - resolve(new AudioPlayer(url as string)); - }).catch((err) => reject(err)); - }); - } - static loadNative (url: string, opts?: AudioLoadOptions): Promise { - return new Promise((resolve, reject) => { - if (systemInfo.platform === Platform.WIN32) { - // NOTE: audioEngine.preload() not works well on Win32 platform. - // Especially when there is not audio output device. But still need to preload - audioEngine.preload(url, (isSuccess) => { - console.debug('somehow preload success on windows'); - }); - resolve(url); - } else { - audioEngine.preload(url, (isSuccess) => { - if (isSuccess) { - resolve(url); - } else { - reject(new Error('load audio failed')); - } - }); - } - }); - } - static loadOneShotAudio (url: string, volume: number, opts?: AudioLoadOptions): Promise { - return new Promise((resolve, reject) => { - AudioPlayer.loadNative(url, opts).then((url) => { - // HACK: AudioPlayer should be a friend class in OneShotAudio - resolve(new (OneShotAudio as any)(url, volume)); - }).catch(reject); - }); - } - static readonly maxAudioChannel: number = audioEngine.getMaxAudioInstance(); - - private get _isValid (): boolean { - return this._id !== INVALID_AUDIO_ID; - } - - get src (): string { - return this._url; - } - get type (): AudioType { - return AudioType.NATIVE_AUDIO; - } - get state (): AudioState { - return this._state; - } - get loop (): boolean { - if (!this._isValid) { - return this._cachedState.loop; - } - return audioEngine.isLoop(this._id); - } - set loop (val: boolean) { - if (this._isValid) { - audioEngine.setLoop(this._id, val); - } - this._cachedState.loop = val; - } - get volume (): number { - if (!this._isValid) { - return this._cachedState.volume; - } - return audioEngine.getVolume(this._id); - } - set volume (val: number) { - val = clamp01(val); - if (this._isValid) { - audioEngine.setVolume(this._id, val); - } - this._cachedState.volume = val; - } - get duration (): number { - if (!this._isValid) { - return this._cachedState.duration; - } - return audioEngine.getDuration(this._id); - } - get currentTime (): number { - if (!this._isValid) { - return this._cachedState.currentTime; - } - return audioEngine.getCurrentTime(this._id); - } - - get sampleRate (): number { - if (this._pcmHeader === null) { - this._pcmHeader = jsb.AudioEngine.getPCMHeader(this._url); - } - return this._pcmHeader.sampleRate; - } - - public getPCMData (channelIndex: number): AudioPCMDataView | undefined { - const arrayBuffer = audioEngine.getOriginalPCMBuffer(this._url, channelIndex); - if (this._pcmHeader === null) { - this._pcmHeader = jsb.AudioEngine.getPCMHeader(this._url); - } - const audioBufferInfo = bufferConstructorMap[this._pcmHeader.audioFormat]; - if (!arrayBuffer || !audioBufferInfo) { - return undefined; - } - return new AudioPCMDataView(arrayBuffer, audioBufferInfo.ctor, 1 / audioBufferInfo.maxValue); - } - - @enqueueOperation - seek (time: number): Promise { - return new Promise((resolve) => { - // Duration is invalid before player - // time = clamp(time, 0, this.duration); - if (this._isValid) { - audioEngine.setCurrentTime(this._id, time); - } - this._cachedState.currentTime = time; - return resolve(); - }); - } - - @enqueueOperation - play (): Promise { - return new Promise((resolve) => { - if (this._isValid) { - if (this._state === AudioState.PAUSED || this._state === AudioState.INTERRUPTED) { - audioEngine.resume(this._id); - } else if (this._state === AudioState.PLAYING) { - audioEngine.pause(this._id); - audioEngine.setCurrentTime(this._id, 0); - audioEngine.resume(this._id); - } - } else { - this._id = audioEngine.play2d(this._url, this._cachedState.loop, this._cachedState.volume); - if (this._isValid) { - if (this._cachedState.currentTime !== 0) { - audioEngine.setCurrentTime(this._id, this._cachedState.currentTime); - this._cachedState.currentTime = 0; - } - audioEngine.setFinishCallback(this._id, () => { - this._cachedState.currentTime = 0; - this._id = INVALID_AUDIO_ID; - this._state = AudioState.INIT; - this._eventTarget.emit(AudioEvent.ENDED); - }); - } - } - this._state = AudioState.PLAYING; - resolve(); - }); - } - - @enqueueOperation - pause (): Promise { - return new Promise((resolve) => { - if (this._isValid) { - audioEngine.pause(this._id); - } - this._state = AudioState.PAUSED; - resolve(); - }); - } - - @enqueueOperation - stop (): Promise { - return new Promise((resolve) => { - if (this._isValid) { - audioEngine.stop(this._id); - } - this._state = AudioState.STOPPED; - this._id = INVALID_AUDIO_ID; - this._cachedState.currentTime = 0; - resolve(); - }); - } - onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); } - offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); } - onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); } - offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); } - onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); } - offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); } -} - -// REMOVE_ME -legacyCC.AudioPlayer = AudioPlayer; diff --git a/pal/audio/nodejs/player.ts b/pal/audio/nodejs/player.ts deleted file mode 100644 index e6fe5409e6..0000000000 --- a/pal/audio/nodejs/player.ts +++ /dev/null @@ -1,246 +0,0 @@ -/* - Copyright (c) 2025 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { systemInfo } from 'pal/system-info'; -import { AudioType, AudioState, AudioEvent, AudioPCMDataView, AudioBufferView, AudioLoadOptions } from '../type'; -import { EventTarget } from '../../../cocos/core/event'; -import { legacyCC } from '../../../cocos/core/global-exports'; -import { clamp, clamp01 } from '../../../cocos/core'; -import { enqueueOperation, OperationInfo, OperationQueueable } from '../operation-queue'; -import { Platform } from '../../system-info/enum-type'; - -const urlCount: Record = {}; -const INVALID_AUDIO_ID = -1; - -enum AudioBufferFormat { - UNKNOWN = 0, - SIGNED_8, - UNSIGNED_8, - SIGNED_16, - UNSIGNED_16, - SIGNED_32, - UNSIGNED_32, - FLOAT_32, - FLOAT_64 -} - -interface AudioBufferInfo { - ctor: Constructor, - maxValue: number; -} - -const bufferConstructorMap: Record = { - [AudioBufferFormat.UNKNOWN]: undefined, - [AudioBufferFormat.SIGNED_8]: { ctor: Int8Array, maxValue: 127 }, - [AudioBufferFormat.UNSIGNED_8]: { ctor: Uint8Array, maxValue: 255 }, - [AudioBufferFormat.SIGNED_16]: { ctor: Int16Array, maxValue: 32767 }, - [AudioBufferFormat.UNSIGNED_16]: { ctor: Uint16Array, maxValue: 65535 }, - [AudioBufferFormat.SIGNED_32]: { ctor: Int32Array, maxValue: 2147483647 }, - [AudioBufferFormat.UNSIGNED_32]: { ctor: Uint32Array, maxValue: 4294967295 }, - // decoded float data is normalized data, so we specify the maxValue as 1. - [AudioBufferFormat.FLOAT_32]: { ctor: Float32Array, maxValue: 1 }, - [AudioBufferFormat.FLOAT_64]: { ctor: Float64Array, maxValue: 1 }, -}; - -export class OneShotAudio { - private _id: number = INVALID_AUDIO_ID; - private _onPlayCb?: () => void; - get onPlay (): (() => void) | undefined { - return this._onPlayCb; - } - set onPlay (cb) { - this._onPlayCb = cb; - } - - private _onEndCb?: () => void; - get onEnd (): (() => void) | undefined { - return this._onEndCb; - } - set onEnd (cb) { - this._onEndCb = cb; - } - - private constructor (url: string, volume: number) { - } - public play (): void { - - } - public stop (): void { - if (this._id === INVALID_AUDIO_ID) { - return; - } - } -} - -export class AudioPlayer implements OperationQueueable { - private _id: number = INVALID_AUDIO_ID; - private _state: AudioState = AudioState.INIT; - - - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _eventTarget: EventTarget = new EventTarget(); - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _operationQueue: OperationInfo[] = []; - - // NOTE: we need to cache the state in case the audio id is invalid. - private _cachedState = { - duration: 1, // wrong value before playing - loop: false, - currentTime: 0, - volume: 1, - } - - constructor (url: string) { - - } - destroy (): void { - - } - - static load (url: string, opts?: AudioLoadOptions): Promise { - return new Promise((resolve, reject) => { - AudioPlayer.loadNative(url, opts).then((url) => { - resolve(new AudioPlayer(url as string)); - }).catch((err) => reject(err)); - }); - } - static loadNative (url: string, opts?: AudioLoadOptions): Promise { - return new Promise((resolve, reject) => { - // Todo(qgh): We need to parse the audio file, but this feature is not yet implemented. - console.warn("Audio file parsing is not supported."); - resolve(url); - }); - } - static loadOneShotAudio (url: string, volume: number, opts?: AudioLoadOptions): Promise { - return new Promise((resolve, reject) => { - AudioPlayer.loadNative(url, opts).then((url) => { - // HACK: AudioPlayer should be a friend class in OneShotAudio - resolve(new (OneShotAudio as any)(url, volume)); - }).catch(reject); - }); - } - - private get _isValid (): boolean { - return this._id !== INVALID_AUDIO_ID; - } - - get src (): string { - return ""; - } - get type (): AudioType { - return AudioType.NATIVE_AUDIO; - } - get state (): AudioState { - return this._state; - } - get loop (): boolean { - if (!this._isValid) { - return this._cachedState.loop; - } - return false; - } - set loop (val: boolean) { - if (this._isValid) { - } - this._cachedState.loop = val; - } - get volume (): number { - if (!this._isValid) { - return this._cachedState.volume; - } - return 0; - } - set volume (val: number) { - val = clamp01(val); - if (this._isValid) { - } - this._cachedState.volume = val; - } - get duration (): number { - if (!this._isValid) { - return this._cachedState.duration; - } - return 0; - } - get currentTime (): number { - if (!this._isValid) { - return this._cachedState.currentTime; - } - return 0; - } - - get sampleRate (): number { - return 0; - } - - public getPCMData (channelIndex: number): AudioPCMDataView | undefined { - return undefined; - } - - @enqueueOperation - seek (time: number): Promise { - return new Promise((resolve) => { - // Duration is invalid before player - // time = clamp(time, 0, this.duration); - if (this._isValid) { - } - this._cachedState.currentTime = time; - return resolve(); - }); - } - - @enqueueOperation - play (): Promise { - return new Promise((resolve) => { - resolve(); - }); - } - - @enqueueOperation - pause (): Promise { - return new Promise((resolve) => { - resolve(); - }); - } - - @enqueueOperation - stop (): Promise { - return new Promise((resolve) => { - resolve(); - }); - } - onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); } - offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); } - onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); } - offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); } - onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); } - offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); } -} - -// REMOVE_ME -legacyCC.AudioPlayer = AudioPlayer; diff --git a/pal/audio/operation-queue.ts b/pal/audio/operation-queue.ts deleted file mode 100644 index 285a93dd20..0000000000 --- a/pal/audio/operation-queue.ts +++ /dev/null @@ -1,122 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { EventTarget } from '../../cocos/core'; - -type OperationMethod = (...args: any[]) => Promise; -export interface OperationInfo { - op: string; - id: number; - func: OperationMethod; - args: any[], - invoking: boolean, -} - -/** @mangle */ -export interface OperationQueueable { - _operationQueue: OperationInfo[]; - _eventTarget: EventTarget; -} - -function removeUnneededCalls (instance: OperationQueueable): void { - const size = instance._operationQueue.length; - const tmpQueue = instance._operationQueue.slice(); - const reserveOps: OperationInfo[] = []; - let seekSearched = false; - for (let i = size - 1; i >= 0; i--) { - const opInfo = tmpQueue[i]; - if (opInfo.op === 'stop') { - reserveOps.push(opInfo); - break; - } else if (opInfo.op === 'seek') { - if (!seekSearched) { - reserveOps.push(opInfo); - seekSearched = true; - } - } else if (seekSearched) { - reserveOps.push(opInfo); - break; - } else if (reserveOps.length === 0) { - reserveOps.push(opInfo); - } - } - instance._operationQueue = reserveOps.reverse(); -} - -let operationId = 0; -function _tryCallingRecursively (target: T, opInfo: OperationInfo): void { - if (opInfo.invoking) { - return; - } - opInfo.invoking = true; - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - opInfo.func.call(target, ...opInfo.args).then(() => { - opInfo.invoking = false; - target._operationQueue.shift(); - target._eventTarget.emit(opInfo.id.toString()); - target._eventTarget.off(opInfo.id.toString()); // remove the key from _eventTarget._callbackTable - removeUnneededCalls(target); - const nextOpInfo: OperationInfo = target._operationQueue[0]; - if (nextOpInfo) { - _tryCallingRecursively(target, nextOpInfo); - } - // eslint-disable-next-line @typescript-eslint/no-empty-function - }).catch((e) => {}); -} - -/** - * This is a method decorator for media player class such as Audio or Video. - * Most of the operations in media player are asynchronous. - * When all these asynchronous operations are called concurrently, they need to be queued. - * - * Note: the decorated class need to implement the interface `OperationQueueable` - * and the decorated method should be declared as `(...args: any[]): Promise`. - * - * When you apply `enqueueOperation` on a method, remember to provide a pure operation implementation. - * It means that, for example, you can't call stop in the implementation of play operation, - * because that would cause the operation deadlock. - */ -// eslint-disable-next-line max-len -export function enqueueOperation (target: T, propertyKey: string, descriptor: TypedPropertyDescriptor): void { - const originalOperation = descriptor.value!; - // eslint-disable-next-line func-names - descriptor.value = function (...args: any[]): Promise { - return new Promise((resolve) => { - const id = operationId++; - const instance = this as OperationQueueable; - // enqueue operation - instance._operationQueue.push({ - op: propertyKey, - id, - func: originalOperation, - args, - invoking: false, - }); - // call resolve when this operation id is finishied - instance._eventTarget.once(id.toString(), resolve); - const opInfo: OperationInfo = instance._operationQueue[0]; - _tryCallingRecursively(instance, opInfo); - }); - }; -} diff --git a/pal/audio/type.ts b/pal/audio/type.ts deleted file mode 100644 index 0051b84d6d..0000000000 --- a/pal/audio/type.ts +++ /dev/null @@ -1,84 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -export enum AudioEvent { - PLAYED = 'play', - PAUSED = 'pause', - STOPPED = 'stop', - SEEKED = 'seeked', - ENDED = 'ended', - INTERRUPTION_BEGIN = 'interruptionBegin', - INTERRUPTION_END = 'interruptionEnd', - USER_GESTURE = 'on_gesture', // only web needed -} - -export enum AudioType { - DOM_AUDIO, - WEB_AUDIO, - MINIGAME_AUDIO, - NATIVE_AUDIO, - UNKNOWN_AUDIO, -} - -export interface AudioLoadOptions { - audioLoadMode?: AudioType, -} - -export enum AudioState { - INIT, - PLAYING, - PAUSED, - STOPPED, - INTERRUPTED, -} - -export type AudioBufferView = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; - -export class AudioPCMDataView { - private _bufferView: AudioBufferView; - private _normalizeFactor = 1; - - constructor (arrayBufferView: AudioBufferView, normalizeFactor: number); - constructor (arrayBuffer: ArrayBuffer, Ctor: Constructor, normalizeFactor: number); - constructor (...args: any[]) { - if (args.length === 2) { - this._bufferView = args[0] as AudioBufferView; - this._normalizeFactor = args[1] as number; - } else { - const arrayBuffer = args[0] as ArrayBuffer; - const Ctor = args[1] as Constructor; - const normalizeFactor = args[2] as number; - this._bufferView = new Ctor(arrayBuffer); - this._normalizeFactor = normalizeFactor; - } - } - - get length (): number { - return this._bufferView.length; - } - - public getData (offset: number): number { - return this._bufferView[offset] * this._normalizeFactor; - } -} diff --git a/pal/audio/web/player-dom.ts b/pal/audio/web/player-dom.ts deleted file mode 100644 index b0e397a7a8..0000000000 --- a/pal/audio/web/player-dom.ts +++ /dev/null @@ -1,277 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { systemInfo } from 'pal/system-info'; -import { AudioEvent, AudioState, AudioPCMDataView, AudioType } from '../type'; -import { EventTarget } from '../../../cocos/core/event'; -import { clamp, clamp01 } from '../../../cocos/core'; -import { enqueueOperation, OperationInfo, OperationQueueable } from '../operation-queue'; -import { BrowserType, OS } from '../../system-info/enum-type'; -import { Game, game } from '../../../cocos/game'; - -function ensurePlaying (domAudio: HTMLAudioElement): Promise { - return new Promise((resolve) => { - const promise = domAudio.play(); - if (promise === undefined) { // Chrome50/Firefox53 below - return resolve(); - } - promise.then(resolve).catch((): void => { - const onGesture = (): void => { - domAudio.play().then(() => { - // HACK NOTE: if the user slide after touch start, the context cannot be resumed correctly. - canvas?.removeEventListener('touchend', onGesture, { capture: true }); - canvas?.removeEventListener('mouseup', onGesture, { capture: true }); - }).catch((e) => {}); - resolve(); - }; - const canvas = document.getElementById('GameCanvas') as HTMLCanvasElement; - canvas?.addEventListener('touchend', onGesture, { capture: true }); - canvas?.addEventListener('mouseup', onGesture, { capture: true }); - }); - return null; - }); -} - -export class OneShotAudioDOM { - private _domAudio: HTMLAudioElement; - private _onPlayCb?: () => void; - get onPlay (): (() => void) | undefined { - return this._onPlayCb; - } - set onPlay (cb) { - this._onPlayCb = cb; - } - - private _onEndCb?: () => void; - get onEnd (): (() => void) | undefined { - return this._onEndCb; - } - set onEnd (cb) { - if (this._onEndCb) { - this._domAudio.removeEventListener('ended', this._onEndCb); - } - this._onEndCb = cb; - if (cb) { - this._domAudio.addEventListener('ended', cb); - } - } - - private constructor (nativeAudio: HTMLAudioElement, volume: number) { - this._domAudio = nativeAudio; - nativeAudio.volume = volume; - } - public play (): void { - ensurePlaying(this._domAudio).then(() => { - this.onPlay?.(); - }).catch((e) => {}); - } - public stop (): void { - this._domAudio.pause(); - } -} - -export class AudioPlayerDOM implements OperationQueueable { - private _domAudio: HTMLAudioElement; - private _state: AudioState = AudioState.INIT; - private _onEnded: () => void; - - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _eventTarget: EventTarget = new EventTarget(); - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _operationQueue: OperationInfo[] = []; - - constructor (nativeAudio: HTMLAudioElement) { - this._domAudio = nativeAudio; - - // event - game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this); - game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this); - this._onEnded = (): void => { - this.seek(0).catch((e) => {}); - this._state = AudioState.INIT; - this._eventTarget.emit(AudioEvent.ENDED); - }; - this._domAudio.addEventListener('ended', this._onEnded); - } - - destroy (): void { - game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this); - game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this); - this._domAudio.removeEventListener('ended', this._onEnded); - // NOTE: need to release DOM Audio instance - this._domAudio = null as any; - } - static load (url: string): Promise { - return new Promise((resolve, reject) => { - AudioPlayerDOM.loadNative(url).then((domAudio) => { - resolve(new AudioPlayerDOM(domAudio)); - }).catch(reject); - }); - } - static loadNative (url: string): Promise { - return new Promise((resolve, reject) => { - const domAudio = document.createElement('audio'); - let loadedEvent = 'canplaythrough'; - if (systemInfo.os === OS.IOS) { - // iOS no event that used to parse completed callback - // this time is not complete, can not play - loadedEvent = 'loadedmetadata'; - } else if (systemInfo.browserType === BrowserType.FIREFOX) { - loadedEvent = 'canplay'; - } - - const timer = setTimeout(() => { - if (domAudio.readyState === 0) { - failure(); - } else { - success(); - } - }, 8000); - const clearEvent = (): void => { - clearTimeout(timer); - domAudio.removeEventListener(loadedEvent, success, false); - domAudio.removeEventListener('error', failure, false); - }; - const success = (): void => { - clearEvent(); - resolve(domAudio); - }; - const failure = (): void => { - clearEvent(); - const message = `load audio failure - ${url}`; - reject(new Error(message)); - }; - domAudio.addEventListener(loadedEvent, success, false); - domAudio.addEventListener('error', failure, false); - domAudio.src = url; - }); - } - static loadOneShotAudio (url: string, volume: number): Promise { - return new Promise((resolve, reject) => { - AudioPlayerDOM.loadNative(url).then((domAudio) => { - // HACK: AudioPlayer should be a friend class in OneShotAudio - const oneShotAudio = new (OneShotAudioDOM as any)(domAudio, volume); - resolve(oneShotAudio); - }).catch(reject); - }); - } - - private _onInterruptedBegin (): void { - if (this._state === AudioState.PLAYING) { - this.pause().then(() => { - this._state = AudioState.INTERRUPTED; - this._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN); - }).catch((e) => {}); - } - } - private _onInterruptedEnd (): void { - if (this._state === AudioState.INTERRUPTED) { - this.play().then(() => { - this._eventTarget.emit(AudioEvent.INTERRUPTION_END); - }).catch((e) => {}); - } - } - - get src (): string { - return this._domAudio ? this._domAudio.src : ''; - } - get type (): AudioType { - return AudioType.DOM_AUDIO; - } - get state (): AudioState { - return this._state; - } - get loop (): boolean { - return this._domAudio.loop; - } - set loop (val: boolean) { - this._domAudio.loop = val; - } - get volume (): number { - return this._domAudio.volume; - } - set volume (val: number) { - val = clamp01(val); - this._domAudio.volume = val; - } - get duration (): number { - return this._domAudio.duration; - } - get currentTime (): number { - return this._domAudio.currentTime; - } - - get sampleRate (): number { - return 0; - } - - public getPCMData (channelIndex: number): AudioPCMDataView | undefined { - return undefined; - } - - @enqueueOperation - seek (time: number): Promise { - time = clamp(time, 0, this.duration); - this._domAudio.currentTime = time; - return Promise.resolve(); - } - - @enqueueOperation - play (): Promise { - return new Promise((resolve) => { - ensurePlaying(this._domAudio).then(() => { - this._state = AudioState.PLAYING; - resolve(); - }).catch((e) => {}); - }); - } - - @enqueueOperation - pause (): Promise { - this._domAudio.pause(); - this._state = AudioState.PAUSED; - return Promise.resolve(); - } - - @enqueueOperation - stop (): Promise { - return new Promise((resolve) => { - this._domAudio.pause(); - this._domAudio.currentTime = 0; - this._state = AudioState.STOPPED; - resolve(); - }); - } - - onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); } - offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); } - onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); } - offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); } - onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); } - offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); } -} diff --git a/pal/audio/web/player-web.ts b/pal/audio/web/player-web.ts deleted file mode 100644 index 2fa7dad615..0000000000 --- a/pal/audio/web/player-web.ts +++ /dev/null @@ -1,493 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; -import { AudioPCMDataView, AudioEvent, AudioState, AudioType } from '../type'; -import { EventTarget } from '../../../cocos/core/event'; -import { clamp01 } from '../../../cocos/core'; -import * as debug from '../../../cocos/core/platform/debug'; -import { enqueueOperation, OperationInfo, OperationQueueable } from '../operation-queue'; -import AudioTimer from '../audio-timer'; -import { audioBufferManager } from '../audio-buffer-manager'; -import { Game, game } from '../../../cocos/game'; - -// NOTE: fix CI -const AudioContextClass = (window.AudioContext || window.webkitAudioContext || window.mozAudioContext); -const _contextRunningEvent = 'on-context-running'; - -export class AudioContextAgent { - public static support = !!AudioContextClass; - - private _eventTarget: EventTarget; - private _context: AudioContext; - private _isRunning = false; - constructor () { - this._context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); - this._eventTarget = new EventTarget(); - this._context.onstatechange = (): void => { - if (this._context.state === 'running') { - this._isRunning = true; - this._eventTarget.emit(_contextRunningEvent); - } else { - this._isRunning = false; - } - }; - } - - get isRunning (): boolean { - return this._isRunning; - } - - get currentTime (): number { - return this._context.currentTime; - } - - public onceRunning (cb: (...args: any[]) => void, target?: any): void { - this._eventTarget.once(_contextRunningEvent, cb, target); - } - - public offRunning (cb?: (...args: any[]) => void, target?: any): void { - this._eventTarget.off(_contextRunningEvent, cb, target); - } - - public decodeAudioData (audioData: ArrayBuffer): Promise { - return new Promise((resolve, reject) => { - const promise = this._context.decodeAudioData(audioData, (audioBuffer) => { - resolve(audioBuffer); - }, (err) => { - // TODO: need to reject the error. - // eslint-disable-next-line no-console - console.error('failed to load Web Audio', err); - }); - promise?.catch(reject); // Safari doesn't support the promise based decodeAudioData - }); - } - - public runContext (): Promise { - return new Promise((resolve) => { - if (this.isRunning) { - resolve(); - return; - } - const context = this._context; - if (!context.resume) { - resolve(); - return; - } - // only state is suspended can involve resume function - if (context.state === 'suspended') { - context.resume().catch((e) => { debug.warn('runContext error', e); }); - } else if (context.state === 'running') { - resolve(); - return; - } - // Force running audio context if state is not 'running', may be 'suspended' or 'interrupted'. - const canvas = document.getElementById('GameCanvas') as HTMLCanvasElement; - // HACK NOTE: if the user slide after touch start, the context cannot be resumed correctly. - const onGesture = (): void => { - context.resume().then(() => { - canvas?.removeEventListener('touchend', onGesture, { capture: true }); - canvas?.removeEventListener('mouseup', onGesture, { capture: true }); - resolve(); - }).catch((e) => { debug.warn('onGesture resume error', e); }); - }; - canvas?.addEventListener('touchend', onGesture, { capture: true }); - canvas?.addEventListener('mouseup', onGesture, { capture: true }); - }); - } - - public createBufferSource (audioBuffer?: AudioBuffer, loop?: boolean): AudioBufferSourceNode { - const sourceBufferNode = this._context.createBufferSource(); - if (audioBuffer !== undefined) { - sourceBufferNode.buffer = audioBuffer; - } - if (loop !== undefined) { - sourceBufferNode.loop = loop; - } - return sourceBufferNode; - } - - public createGain (volume = 1): GainNode { - const gainNode = this._context.createGain(); - this.setGainValue(gainNode, volume); - return gainNode; - } - - public setGainValue (gain: GainNode, volume: number): void { - if (gain.gain.setTargetAtTime) { - try { - gain.gain.setTargetAtTime(volume, this._context.currentTime, 0); - } catch (e) { - // Some unknown browsers may crash if timeConstant is 0 - gain.gain.setTargetAtTime(volume, this._context.currentTime, 0.01); - } - } else { - gain.gain.value = volume; - } - } - - public connectContext (audioNode: GainNode): void { - if (!this._context) { - return; - } - audioNode.connect(this._context.destination); - } -} - -let audioContextAgent: AudioContextAgent | undefined; -if (AudioContextAgent.support) { - audioContextAgent = new AudioContextAgent(); -} - -export class OneShotAudioWeb { - private _duration: number; - private _bufferSourceNode: AudioBufferSourceNode; - private _onPlayCb?: () => void; - private _currentTimer = 0; - private _url: string; - - get onPlay (): (() => void) | undefined { - return this._onPlayCb; - } - set onPlay (cb) { - this._onPlayCb = cb; - } - - private _onEndCb?: () => void; - get onEnd (): (() => void) | undefined { - return this._onEndCb; - } - set onEnd (cb) { - this._onEndCb = cb; - } - - private constructor (audioBuffer: AudioBuffer, volume: number, url: string) { - this._duration = audioBuffer.duration; - this._url = url; - this._bufferSourceNode = audioContextAgent!.createBufferSource(audioBuffer, false); - const gainNode = audioContextAgent!.createGain(volume); - this._bufferSourceNode.connect(gainNode); - audioContextAgent!.connectContext(gainNode); - } - - public play (): void { - if (EDITOR_NOT_IN_PREVIEW) { - return; - } - this._bufferSourceNode.start(); - // audioContextAgent does exist - audioContextAgent!.runContext().then(() => { - this.onPlay?.(); - this._currentTimer = window.setTimeout(() => { - audioBufferManager.tryReleasingCache(this._url); - this.onEnd?.(); - }, this._duration * 1000); - }).catch((e) => { debug.warn('play error', e); }); - } - - public stop (): void { - clearTimeout(this._currentTimer); - audioBufferManager.tryReleasingCache(this._url); - this._bufferSourceNode.stop(); - this._bufferSourceNode.disconnect(); - this._bufferSourceNode.buffer = null; - } -} - -export class AudioPlayerWeb implements OperationQueueable { - private _src: string; - private _audioBuffer: AudioBuffer; - private _sourceNode?: AudioBufferSourceNode; - private _gainNode: GainNode; - private _currentTimer = 0; - private _volume = 1; - private _loop = false; - private _state: AudioState = AudioState.INIT; - private _audioTimer: AudioTimer; - private _runningCallback?: () => void; - - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _eventTarget: EventTarget = new EventTarget(); - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _operationQueue: OperationInfo[] = []; - - constructor (audioBuffer: AudioBuffer, url: string) { - this._audioBuffer = audioBuffer; - this._audioTimer = new AudioTimer(audioBuffer); - this._gainNode = audioContextAgent!.createGain(); - audioContextAgent!.connectContext(this._gainNode); - this._src = url; - // event - game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this); - game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this); - } - destroy (): void { - window.clearTimeout(this._currentTimer); - this._audioTimer.destroy(); - if (this._audioBuffer) { - // NOTE: need to release AudioBuffer instance - this._audioBuffer = null as any; - } - audioBufferManager.tryReleasingCache(this._src); - game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this); - game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this); - this.offRunning(); - } - static load (url: string): Promise { - return new Promise((resolve, reject) => { - AudioPlayerWeb.loadNative(url).then((audioBuffer) => { - resolve(new AudioPlayerWeb(audioBuffer, url)); - }).catch(reject); - }); - } - static loadNative (url: string): Promise { - return new Promise((resolve, reject) => { - const cachedAudioBuffer = audioBufferManager.getCache(url); - if (cachedAudioBuffer) { - audioBufferManager.retainCache(url); - resolve(cachedAudioBuffer); - return; - } - const xhr = new XMLHttpRequest(); - const errInfo = `load audio failed: ${url}, status: `; - xhr.open('GET', url, true); - xhr.responseType = 'arraybuffer'; - - xhr.onload = (): void => { - if (xhr.status === 200 || xhr.status === 0) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - audioContextAgent!.decodeAudioData(xhr.response).then((decodedAudioBuffer) => { - audioBufferManager.addCache(url, decodedAudioBuffer); - resolve(decodedAudioBuffer); - }).catch((e) => { debug.warn('loadNative error', url, e); }); - } else { - reject(new Error(`${errInfo}${xhr.status}(no response)`)); - } - }; - xhr.onerror = (): void => { reject(new Error(`${errInfo}${xhr.status}(error)`)); }; - xhr.ontimeout = (): void => { reject(new Error(`${errInfo}${xhr.status}(time out)`)); }; - xhr.onabort = (): void => { reject(new Error(`${errInfo}${xhr.status}(abort)`)); }; - - xhr.send(null); - }); - } - static loadOneShotAudio (url: string, volume: number): Promise { - return new Promise((resolve, reject) => { - AudioPlayerWeb.loadNative(url).then((audioBuffer) => { - // HACK: AudioPlayer should be a friend class in OneShotAudio - const oneShotAudio = new (OneShotAudioWeb as any)(audioBuffer, volume, url); - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - resolve(oneShotAudio); - }).catch(reject); - }); - } - - get sampleRate (): number { - return this._audioBuffer.sampleRate; - } - - public getPCMData (channelIndex: number): AudioPCMDataView | undefined { - return new AudioPCMDataView(this._audioBuffer.getChannelData(channelIndex), 1); - } - - private _onInterruptedBegin (): void { - if (this._state === AudioState.PLAYING) { - this.pause().then(() => { - this._state = AudioState.INTERRUPTED; - this._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN); - }).catch((e) => { debug.warn('_onInterruptedBegin error', e); }); - } - } - private _onInterruptedEnd (): void { - if (this._state === AudioState.INTERRUPTED) { - this.play().then(() => { - this._eventTarget.emit(AudioEvent.INTERRUPTION_END); - }).catch((e) => { debug.warn('_onInterruptedEnd error', e); }); - } - } - - get src (): string { - return this._src; - } - get type (): AudioType { - return AudioType.WEB_AUDIO; - } - get state (): AudioState { - return this._state; - } - get loop (): boolean { - return this._loop; - } - set loop (val: boolean) { - this._loop = val; - if (this._sourceNode) { - this._sourceNode.loop = val; - } - } - get volume (): number { - return this._volume; - } - set volume (val: number) { - val = clamp01(val); - this._volume = val; - audioContextAgent!.setGainValue(this._gainNode, val); - } - get duration (): number { - return this._audioBuffer.duration; - } - get currentTime (): number { - return this._audioTimer.currentTime; - } - private offRunning (): void { - if (this._runningCallback) { - audioContextAgent!.offRunning(this._runningCallback); - this._runningCallback = undefined; - } - } - - @enqueueOperation - seek (time: number): Promise { - return new Promise((resolve) => { - this.offRunning(); - this._audioTimer.seek(time); - if (this._state === AudioState.PLAYING) { - // one AudioBufferSourceNode can't start twice - // need to create a new one to start from the offset - this._doPlay().then(resolve).catch((e) => { debug.warn('seek error', e); }); - } else { - resolve(); - } - }); - } - - @enqueueOperation - play (): Promise { - this.offRunning(); - if (EDITOR_NOT_IN_PREVIEW) { - return Promise.resolve(); - } - return this._doPlay(); - } - - // The decorated play() method can't be call in seek() - // so we define this method to ensure that the audio seeking works. - private _doPlay (): Promise { - return new Promise((resolve) => { - if (audioContextAgent!.isRunning) { - this._startSourceNode(); - resolve(); - } else { - this.offRunning(); - this._runningCallback = (): void => { - this._startSourceNode(); - resolve(); - }; - // Running event may be emit when: - // - manually resume audio context. - // - system automatically resume audio context when enter foreground from background. - audioContextAgent!.onceRunning(this._runningCallback); - // Ensure resume context. - audioContextAgent!.runContext().catch((e) => { debug.warn('doPlay error', e); }); - } - }); - } - - private _startSourceNode (): void { - // one AudioBufferSourceNode can't start twice - this._stopSourceNode(); - this._sourceNode = audioContextAgent!.createBufferSource(this._audioBuffer, this.loop); - this._sourceNode.connect(this._gainNode); - this._sourceNode.loop = this._loop; - this._sourceNode.start(0, this._audioTimer.currentTime); - this._state = AudioState.PLAYING; - this._audioTimer.start(); - - /* still not supported by all platforms * - this._sourceNode.onended = this._onEnded; - /* doing it manually for now */ - const checkEnded = (): void => { - if (this.loop) { - this._currentTimer = window.setTimeout(checkEnded, this._audioBuffer.duration * 1000); - } else { // do ended - this._audioTimer.stop(); - this._eventTarget.emit(AudioEvent.ENDED); - this._state = AudioState.INIT; - } - }; - window.clearTimeout(this._currentTimer); - this._currentTimer = window.setTimeout(checkEnded, (this._audioBuffer.duration - this._audioTimer.currentTime) * 1000); - } - - private _stopSourceNode (): void { - try { - if (this._sourceNode) { - this._sourceNode.stop(); - this._sourceNode.disconnect(); - this._sourceNode.buffer = null; - this._sourceNode = undefined; - } - } catch (e) { - // sourceNode can't be stopped twice, especially on Safari. - } - } - - @enqueueOperation - pause (): Promise { - this.offRunning(); - if (this._state !== AudioState.PLAYING || !this._sourceNode) { - return Promise.resolve(); - } - this._audioTimer.pause(); - this._state = AudioState.PAUSED; - window.clearTimeout(this._currentTimer); - this._stopSourceNode(); - return Promise.resolve(); - } - - @enqueueOperation - stop (): Promise { - this.offRunning(); - if (!this._sourceNode) { - this._audioTimer.stop(); - this._state = AudioState.STOPPED; - return Promise.resolve(); - } - this._audioTimer.stop(); - this._state = AudioState.STOPPED; - window.clearTimeout(this._currentTimer); - this._stopSourceNode(); - return Promise.resolve(); - } - - onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); } - offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); } - onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); } - offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); } - onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); } - offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); } -} diff --git a/pal/audio/web/player.ts b/pal/audio/web/player.ts deleted file mode 100644 index c171805432..0000000000 --- a/pal/audio/web/player.ts +++ /dev/null @@ -1,130 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { warnID } from '../../../cocos/core'; -import { AudioLoadOptions, AudioType, AudioState, AudioPCMDataView } from '../type'; -import { AudioPlayerDOM, OneShotAudioDOM } from './player-dom'; -import { AudioContextAgent, AudioPlayerWeb, OneShotAudioWeb } from './player-web'; - -type AbstractOneShotAudio = OneShotAudioDOM | OneShotAudioWeb; -type AbstractAudioPlayer = AudioPlayerDOM | AudioPlayerWeb; - -export class OneShotAudio { - private _audio: AbstractOneShotAudio; - get onPlay (): (() => void) | undefined { - return this._audio.onPlay; - } - set onPlay (v) { - this._audio.onPlay = v; - } - - get onEnd (): (() => void) | undefined { - return this._audio.onEnd; - } - set onEnd (v) { - this._audio.onEnd = v; - } - - private constructor (audio: AbstractOneShotAudio) { - this._audio = audio; - } - public play (): void { - this._audio.play(); - } - public stop (): void { - this._audio.stop(); - } -} - -export class AudioPlayer { - private _player: AbstractAudioPlayer; - constructor (player: AbstractAudioPlayer) { - this._player = player; - } - - static load (url: string, opts?: AudioLoadOptions): Promise { - return new Promise((resolve, reject) => { - if (opts?.audioLoadMode === AudioType.DOM_AUDIO || !AudioContextAgent.support) { - if (!AudioContextAgent.support) { warnID(5201); } - AudioPlayerDOM.load(url).then((domPlayer) => { - resolve(new AudioPlayer(domPlayer)); - }).catch(reject); - } else { - AudioPlayerWeb.load(url).then((webPlayer) => { - resolve(new AudioPlayer(webPlayer)); - }).catch(reject); - } - }); - } - destroy (): void { - this._player.destroy(); - } - static loadNative (url: string, opts?: AudioLoadOptions): Promise { - if (opts?.audioLoadMode === AudioType.DOM_AUDIO || !AudioContextAgent.support) { - if (!AudioContextAgent.support) { warnID(5201); } - return AudioPlayerDOM.loadNative(url); - } - return AudioPlayerWeb.loadNative(url); - } - static loadOneShotAudio (url: string, volume: number, opts?: AudioLoadOptions): Promise { - return new Promise((resolve, reject) => { - if (opts?.audioLoadMode === AudioType.DOM_AUDIO || !AudioContextAgent.support) { - if (!AudioContextAgent.support) { warnID(5201); } - AudioPlayerDOM.loadOneShotAudio(url, volume).then((oneShotAudioDOM) => { - // HACK: AudioPlayer should be a friend class in OneShotAudio - resolve(new (OneShotAudio as any)(oneShotAudioDOM)); - }).catch(reject); - } else { - AudioPlayerWeb.loadOneShotAudio(url, volume).then((oneShotAudioWeb) => { - // HACK: AudioPlayer should be a friend class in OneShotAudio - resolve(new (OneShotAudio as any)(oneShotAudioWeb)); - }).catch(reject); - } - }); - } - static readonly maxAudioChannel = 24; - - get src (): string { return this._player.src; } - get type (): AudioType { return this._player.type; } - get state (): AudioState { return this._player.state; } - get loop (): boolean { return this._player.loop; } - set loop (val: boolean) { this._player.loop = val; } - get volume (): number { return this._player.volume; } - set volume (val: number) { this._player.volume = val; } - get duration (): number { return this._player.duration; } - get currentTime (): number { return this._player.currentTime; } - get sampleRate (): number { return this._player.sampleRate; } - getPCMData (channelIndex: number): AudioPCMDataView | undefined { return this._player.getPCMData(channelIndex); } - seek (time: number): Promise { return this._player.seek(time); } - - play (): Promise { return this._player.play(); } - pause (): Promise { return this._player.pause(); } - stop (): Promise { return this._player.stop(); } - onInterruptionBegin (cb: () => void): void { this._player.onInterruptionBegin(cb); } - offInterruptionBegin (cb?: () => void): void { this._player.offInterruptionBegin(cb); } - onInterruptionEnd (cb: () => void): void { this._player.onInterruptionEnd(cb); } - offInterruptionEnd (cb?: () => void): void { this._player.offInterruptionEnd(cb); } - onEnded (cb: () => void): void { this._player.onEnded(cb); } - offEnded (cb?: () => void): void { this._player.offEnded(cb); } -} diff --git a/pal/env/minigame/env.ts b/pal/env/minigame/env.ts deleted file mode 100644 index 9f29c09e48..0000000000 --- a/pal/env/minigame/env.ts +++ /dev/null @@ -1,56 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -/* eslint-disable import/no-dynamic-require */ -import { TAOBAO, TAOBAO_MINIGAME, WECHAT, WECHAT_MINI_PROGRAM, XIAOMI } from 'internal:constants'; -import { checkPalIntegrity, withImpl } from '../../integrity-check'; - -declare const require: (path: string) => any; -declare const __baiduRequire: (path: string) => any; -declare const __wxRequire: (path: string) => any; -declare const __taobaoRequire: (path: string) => any; - -export function findCanvas (): { frame: HTMLDivElement, container: HTMLDivElement, canvas: HTMLCanvasElement } { - const container = document.createElement('div'); - return { frame: container, canvas: window.canvas, container }; -} - -export function loadJsFile (path: string): any { - if (XIAOMI) { - return require(`../../${path}`); - } - if (WECHAT || WECHAT_MINI_PROGRAM) { - return __wxRequire(path); - } - if (TAOBAO_MINIGAME) { - return globalThis.__taobaoRequire(path); - } - if (TAOBAO) { - // NOTE: Taobao doesn't support dynamic require - return undefined; - } - return require(`../${path}`); -} - -checkPalIntegrity(withImpl()); diff --git a/pal/env/native/env.ts b/pal/env/native/env.ts deleted file mode 100644 index 77960f946c..0000000000 --- a/pal/env/native/env.ts +++ /dev/null @@ -1,74 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { NATIVE, PREVIEW } from 'internal:constants'; -import { checkPalIntegrity, withImpl } from '../../integrity-check'; - -declare const require: (path: string) => Promise; - -const ccwindow = typeof globalThis.jsb !== 'undefined' ? (typeof jsb.window !== 'undefined' ? jsb.window : window) : window; -const ccdocument = ccwindow.document; - -export function findCanvas (): { frame: HTMLDivElement, container: HTMLDivElement, canvas: HTMLCanvasElement } { - const container = ccdocument.createElement('div'); - const frame = ccdocument.documentElement as HTMLDivElement; - const canvas = ccwindow.__canvas; - return { frame, canvas, container }; -} - -export function loadJsFile (path: string): Promise { - if (NATIVE && window.oh && window.scriptEngineType === 'napi') { - // TODO(qgh):OpenHarmony does not currently support dynamic require expressions - window.oh.loadModule(path); - return Promise.resolve(); - } else { - if (PREVIEW) { - // NOTE: in native preview (simulator), we need to request script with url http://x.x.x.x:xxxx/plugins/xxx.js - // so that the editor preview server would resolve the plugin script and return the code. - // here we use window.eval() function to execute the code of plugin script. - return new Promise((resolve, reject) => { - const sourceURL = window.location.href + path; - const xhr = new XMLHttpRequest(); - xhr.onload = (): void => { - if (xhr.status !== 200) { - reject(new Error(`load js file failed: ${sourceURL}, error status: ${xhr.status}`)); - return; - } - // eslint-disable-next-line no-eval - window.eval(`${xhr.response as string}\n//# sourceURL=${sourceURL}`); - resolve(); - }; - xhr.onerror = (): void => { - reject(new Error(`load js file failed: ${sourceURL}`)); - }; - xhr.open('GET', sourceURL, true); - xhr.send(null); - }); - } - // eslint-disable-next-line import/no-dynamic-require - return require(`${path}`); - } -} - -checkPalIntegrity(withImpl()); diff --git a/pal/env/nodejs/env.ts b/pal/env/nodejs/env.ts deleted file mode 100644 index c594041645..0000000000 --- a/pal/env/nodejs/env.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* - Copyright (c) 2025 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { checkPalIntegrity, withImpl } from '../../integrity-check'; - -export function findCanvas (): { frame: HTMLDivElement, container: HTMLDivElement, canvas: HTMLCanvasElement } { - const frame = document.querySelector('#GameDiv') as HTMLDivElement; - const container = document.querySelector('#Cocos3dGameContainer') as HTMLDivElement; - const canvas = document.querySelector('#GameCanvas') as HTMLCanvasElement; - - return { frame, container, canvas }; -} - -export function loadJsFile (path: string): Promise { - // eslint-disable-next-line import/no-dynamic-require - return globalThis.nodeEnv.require(`${path}`); -} - -checkPalIntegrity(withImpl()); diff --git a/pal/env/runtime/env.ts b/pal/env/runtime/env.ts deleted file mode 100644 index 78538f72cc..0000000000 --- a/pal/env/runtime/env.ts +++ /dev/null @@ -1,50 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { HUAWEI, OPPO, VIVO } from 'internal:constants'; -import { checkPalIntegrity, withImpl } from '../../integrity-check'; - -declare const require: (path: string) => Promise; -declare const ral: any; - -export function findCanvas (): { frame: HTMLDivElement, container: HTMLDivElement, canvas: HTMLCanvasElement } { - const container = document.createElement('div'); - const frame = container.parentNode === document.body ? document.documentElement : container.parentNode as any; - - let canvas; - if (VIVO) { - canvas = window.mainCanvas; - window.mainCanvas = undefined; - } else { - canvas = ral.createCanvas(); - } - return { frame, canvas, container }; -} - -export function loadJsFile (path: string): Promise { - // eslint-disable-next-line import/no-dynamic-require - return require(`${path}`); -} - -checkPalIntegrity(withImpl()); diff --git a/pal/env/web/env.ts b/pal/env/web/env.ts deleted file mode 100644 index e0aee6672a..0000000000 --- a/pal/env/web/env.ts +++ /dev/null @@ -1,68 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { checkPalIntegrity, withImpl } from '../../integrity-check'; - -export function findCanvas (): { frame: HTMLDivElement, container: HTMLDivElement, canvas: HTMLCanvasElement } { - const frame = document.querySelector('#GameDiv') as HTMLDivElement; - const container = document.querySelector('#Cocos3dGameContainer') as HTMLDivElement; - const canvas = document.querySelector('#GameCanvas') as HTMLCanvasElement; - - return { frame, container, canvas }; -} - -export function loadJsFile (path: string): Promise { - return new Promise((resolve, reject) => { - let err; - function windowErrorListener (evt): void { - if (evt.filename === path) { - err = evt.error; - } - } - window.addEventListener('error', windowErrorListener); - const script = document.createElement('script'); - script.charset = 'utf-8'; - script.async = true; - script.crossOrigin = 'anonymous'; - script.addEventListener('error', () => { - window.removeEventListener('error', windowErrorListener); - reject(Error(`Error loading ${path}`)); - }); - script.addEventListener('load', () => { - window.removeEventListener('error', windowErrorListener); - document.head.removeChild(script); - // Note that if an error occurs that isn't caught by this if statement, - // that getRegister will return null and a "did not instantiate" error will be thrown. - if (err) { - reject(err); - } else { - resolve(); - } - }); - script.src = path.replace('#', '%23'); - document.head.appendChild(script); - }); -} - -checkPalIntegrity(withImpl()); diff --git a/pal/input/input-source.ts b/pal/input/input-source.ts deleted file mode 100644 index 165732fb06..0000000000 --- a/pal/input/input-source.ts +++ /dev/null @@ -1,327 +0,0 @@ -/* - Copyright (c) 2022 Chukong Technologies Inc. - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated 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 { Vec2, Vec3, Quat } from '../../cocos/core/math'; - -/** - * @en The abstract class for input source, which is used to control the input signal of a mono input source - * @zh InputSource 抽象类,该类用于控制单一输入源的输入信号 - */ -export abstract class InputSource { - /** - * @en Get the signal value of the input source - * @zh 获取输入源的信号值 - */ - abstract getValue (): T; -} - -/** - * @en The class for input source of 1D Axis, which is used to control the input signal of a mono input source - * @zh 1D 轴的 InputSource 类,该类用于控制单一输入源的输入信号 - */ -export class InputSourceAxis1D extends InputSource { - /** - * @en Get the signal value of the input source, ranged from -1 to 1 - * @zh 获取输入源的信号值,取值范围从 -1 到 1 - */ - getValue (): number { - throw new Error('Method not implemented.'); - } -} - -/** - * @en The class for input source of 2D Axis, which is used to control the input signal of a mono input source - * @zh 2D 轴的 InputSource 类,该类用于控制单一输入源的输入信号 - */ -export class InputSourceAxis2D extends InputSource { - /** - * @en Get the signal value of the input source, which returns a Vec2 object. - * @zh 获取输入源的信号值,该方法返回一个 Vec2 对象 - */ - getValue (): Vec2 { - throw new Error('Method not implemented.'); - } -} - -/** - * @en The class for input source of 3D Axis, which is used to control the input signal of a mono input source - * @zh 3D 轴的 InputSource 类,该类用于控制单一输入源的输入信号 - */ -export class InputSourceAxis3D extends InputSource { - /** - * @en Get the signal value of the input source, which returns a Vec3 object. - * @zh 获取输入源的信号值,该方法返回一个 Vec3 对象 - */ - getValue (): Vec3 { - throw new Error('Method not implemented.'); - } -} - -/** - * @en The class for input source of Quaternion, which is used to control the input signal of a mono input source - * @zh 四元数的 InputSource 类,该类用于控制单一输入源的输入信号 - */ -export class InputSourceQuat extends InputSource { - /** - * @en Get the signal value of the input source, which returns a Quat object. - * @zh 获取输入源的信号值,该方法返回一个 Quat 对象 - */ - getValue (): Quat { - throw new Error('Method not implemented.'); - } -} - -/** - * @en The class for input source of 1D Axis, which is used to control the input signal of a composite of multi input source - * @zh 1D 轴的 InputSource 类,该类用于控制多个输入源组合的输入信号 - */ -export class CompositeInputSourceAxis1D extends InputSourceAxis1D { - /** - * @en The input source object of positive 1D axis - * @zh 1D 轴的正向的输入源对象 - */ - public declare positive: InputSourceButton; - /** - * @en The input source object of negative 1D axis - * @zh 1D 轴的负向的输入源对象 - */ - public declare negative: InputSourceButton; - constructor (options: {positive: InputSourceButton, negative: InputSourceButton}) { - super(); - this.positive = options.positive; - this.negative = options.negative; - } - /** - * @en Get the signal value of the input source, ranged from -1 to 1. - * @zh 获取输入源的信号值,取值范围从 -1 到 1 - */ - public getValue (): number { - const positiveValue = this.positive.getValue(); - const negativeValue = this.negative.getValue(); - if (Math.abs(positiveValue) > Math.abs(negativeValue)) { - return positiveValue; - } - return -negativeValue; - } -} - -/** - * @en The class for input source of 2D Axis, which is used to control the input signal of a composite of multi input source - * @zh 2D 轴的 InputSource 类,该类用于控制多个输入源组合的输入信号 - */ -export class CompositeInputSourceAxis2D extends InputSourceAxis2D { - /** - * @en The input source object of up direction of 2D axis - * @zh 2D 轴的向上的输入源对象 - */ - public declare up: InputSourceButton; - /** - * @en The input source object of down direction of 2D axis - * @zh 2D 轴的向下的输入源对象 - */ - public declare down: InputSourceButton; - /** - * @en The input source object of left direction of 2D axis - * @zh 2D 轴的向左的输入源对象 - */ - public declare left: InputSourceButton; - /** - * @en The input source object of right direction of 2D axis - * @zh 2D 轴的向右的输入源对象 - */ - public declare right: InputSourceButton; - - /** - * @en The composite input source object on the x axis of 2D axis - * @zh 2D 轴在 x 轴上的组合输入源对象 - */ - public declare xAxis: CompositeInputSourceAxis1D; - /** - * @en The composite input source object on the y axis of 2D axis - * @zh 2D 轴在 y 轴上的组合输入源对象 - */ - public declare yAxis: CompositeInputSourceAxis1D; - constructor (options: {up: InputSourceButton, down: InputSourceButton, left: InputSourceButton, right: InputSourceButton}) { - super(); - this.up = options.up; - this.down = options.down; - this.left = options.left; - this.right = options.right; - this.xAxis = new CompositeInputSourceAxis1D({ positive: this.right, negative: this.left }); - this.yAxis = new CompositeInputSourceAxis1D({ positive: this.up, negative: this.down }); - } - /** - * @en Get the signal value of the input source, which returns a Vec2 object. - * @zh 获取输入源的信号值,该方法返回一个 Vec2 对象 - */ - getValue (): Vec2 { - return new Vec2(this.xAxis.getValue(), this.yAxis.getValue()); - } -} - -/** - * @en The class for input source of 3D Axis, which is used to control the input signal of a composite of multi input source - * @zh 3D 轴的 InputSource 类,该类用于控制多个输入源组合的输入信号 - */ -export class CompositeInputSourceAxis3D extends InputSourceAxis3D { - /** - * @en The input source object of up direction of 3D axis - * @zh 3D 轴的向上的输入源对象 - */ - public declare up: InputSourceButton; - /** - * @en The input source object of down direction of 3D axis - * @zh 3D 轴的向下的输入源对象 - */ - public declare down: InputSourceButton; - /** - * @en The input source object of left direction of 3D axis - * @zh 3D 轴的向左的输入源对象 - */ - public declare left: InputSourceButton; - /** - * @en The input source object of right direction of 3D axis - * @zh 3D 轴的向右的输入源对象 - */ - public declare right: InputSourceButton; - /** - * @en The input source object of forward direction of 3D axis - * @zh 3D 轴的向前的输入源对象 - */ - public declare forward: InputSourceButton; - /** - * @en The input source object of backward direction of 3D axis - * @zh 3D 轴的向后的输入源对象 - */ - public declare backward: InputSourceButton; - - /** - * @en The composite input source object on the x axis of 3D axis - * @zh 3D 轴在 x 轴上的组合输入源对象 - */ - public declare xAxis: CompositeInputSourceAxis1D; - /** - * @en The composite input source object on the y axis of 3D axis - * @zh 3D 轴在 y 轴上的组合输入源对象 - */ - public declare yAxis: CompositeInputSourceAxis1D; - /** - * @en The composite input source object on the z axis of 3D axis - * @zh 3D 轴在 z 轴上的组合输入源对象 - */ - public declare zAxis: CompositeInputSourceAxis1D; - constructor (options: {up: InputSourceButton, down: InputSourceButton, left: InputSourceButton, - right: InputSourceButton, forward: InputSourceButton, backward: InputSourceButton}) { - super(); - this.up = options.up; - this.down = options.down; - this.left = options.left; - this.right = options.right; - this.forward = options.forward; - this.backward = options.backward; - - this.xAxis = new CompositeInputSourceAxis1D({ positive: this.right, negative: this.left }); - this.yAxis = new CompositeInputSourceAxis1D({ positive: this.up, negative: this.down }); - this.zAxis = new CompositeInputSourceAxis1D({ positive: this.forward, negative: this.backward }); - } - - /** - * @en Get the signal value of the input source, which returns a Vec3 object. - * @zh 获取输入源的信号值,该方法返回一个 Vec3 对象 - */ - getValue (): Vec3 { - return new Vec3(this.xAxis.getValue(), this.yAxis.getValue(), this.zAxis.getValue()); - } -} - -/** - * @en The class for input source of mono button, whose input signal value is ranged from 0 to 1 - * @zh 单一按键输入源类, 输入信号源的取值范围是 0 到 1 - */ -export class InputSourceButton extends InputSourceAxis1D { - /** - * @en Get the signal value of the input source, ranged from 0 to 1 - * @zh 获取输入源的信号值,取值范围从 0 到 1 - */ - getValue (): number { - return super.getValue(); - } -} - -/** - * @en The class for input source of dpad, whose input signal value a Vec2 object - * @zh 手柄方向键输入源类, 输入信号源的取值是一个 Vec2 对象 - */ -export class InputSourceDpad extends CompositeInputSourceAxis2D { -} - -/** - * @en The class for input source of stick, whose input signal value a Vec2 object - * @zh 摇杆输入源类, 输入信号源的取值是一个 Vec2 对象 - */ -export class InputSourceStick extends CompositeInputSourceAxis2D { -} - -/** - * @en The class for input source of orientation, whose input signal value a Quat object - * @zh 方向输入源类, 输入信号源的取值是一个 Quat 对象 - */ -export class InputSourceOrientation extends InputSourceQuat { - /** - * @en Get the signal value of the input source, which returns a Quat object. - * @zh 获取输入源的信号值,该方法返回一个 Quat 对象 - */ - getValue (): Quat { - return super.getValue(); - } -} - -/** - * @en The class for input source of position, whose input signal value a Vec3 object - * @zh 坐标输入源类, 输入信号源的取值是一个 Vec3 对象 - */ -export class InputSourcePosition extends InputSourceAxis3D { - /** - * @en Get the signal value of the input source, which returns a Vec3 object. - * @zh 获取输入源的信号值,该方法返回一个 Vec3 对象 - */ - getValue (): Vec3 { - return super.getValue(); - } -} - -/** - * @en The class for input source of mono button touch, whose input signal value is ranged from 0 or 1 - * @zh 单一按键触摸输入源类, 输入信号源的取值范围是 0 或 1 - */ -export class InputSourceTouch extends InputSourceAxis1D { - /** - * @en Get the signal value of the input source, ranged from 0 or 1 - * @zh 获取输入源的信号值,取值范围从 0 或 1 - */ - getValue (): number { - return super.getValue(); - } -} diff --git a/pal/input/keycodes.ts b/pal/input/keycodes.ts deleted file mode 100644 index 8159e43ae5..0000000000 --- a/pal/input/keycodes.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { KeyCode } from '../../cocos/input/types'; - -export const code2KeyCode: Record = { - Backspace: KeyCode.BACKSPACE, - Tab: KeyCode.TAB, - Enter: KeyCode.ENTER, - ShiftLeft: KeyCode.SHIFT_LEFT, - ControlLeft: KeyCode.CTRL_LEFT, - AltLeft: KeyCode.ALT_LEFT, - ShiftRight: KeyCode.SHIFT_RIGHT, - ControlRight: KeyCode.CTRL_RIGHT, - AltRight: KeyCode.ALT_RIGHT, - Pause: KeyCode.PAUSE, - CapsLock: KeyCode.CAPS_LOCK, - Escape: KeyCode.ESCAPE, - Space: KeyCode.SPACE, - PageUp: KeyCode.PAGE_UP, - PageDown: KeyCode.PAGE_DOWN, - End: KeyCode.END, - Home: KeyCode.HOME, - ArrowLeft: KeyCode.ARROW_LEFT, - ArrowUp: KeyCode.ARROW_UP, - ArrowRight: KeyCode.ARROW_RIGHT, - ArrowDown: KeyCode.ARROW_DOWN, - Insert: KeyCode.INSERT, - Delete: KeyCode.DELETE, - Digit0: KeyCode.DIGIT_0, - Digit1: KeyCode.DIGIT_1, - Digit2: KeyCode.DIGIT_2, - Digit3: KeyCode.DIGIT_3, - Digit4: KeyCode.DIGIT_4, - Digit5: KeyCode.DIGIT_5, - Digit6: KeyCode.DIGIT_6, - Digit7: KeyCode.DIGIT_7, - Digit8: KeyCode.DIGIT_8, - Digit9: KeyCode.DIGIT_9, - KeyA: KeyCode.KEY_A, - KeyB: KeyCode.KEY_B, - KeyC: KeyCode.KEY_C, - KeyD: KeyCode.KEY_D, - KeyE: KeyCode.KEY_E, - KeyF: KeyCode.KEY_F, - KeyG: KeyCode.KEY_G, - KeyH: KeyCode.KEY_H, - KeyI: KeyCode.KEY_I, - KeyJ: KeyCode.KEY_J, - KeyK: KeyCode.KEY_K, - KeyL: KeyCode.KEY_L, - KeyM: KeyCode.KEY_M, - KeyN: KeyCode.KEY_N, - KeyO: KeyCode.KEY_O, - KeyP: KeyCode.KEY_P, - KeyQ: KeyCode.KEY_Q, - KeyR: KeyCode.KEY_R, - KeyS: KeyCode.KEY_S, - KeyT: KeyCode.KEY_T, - KeyU: KeyCode.KEY_U, - KeyV: KeyCode.KEY_V, - KeyW: KeyCode.KEY_W, - KeyX: KeyCode.KEY_X, - KeyY: KeyCode.KEY_Y, - KeyZ: KeyCode.KEY_Z, - Numpad0: KeyCode.NUM_0, - Numpad1: KeyCode.NUM_1, - Numpad2: KeyCode.NUM_2, - Numpad3: KeyCode.NUM_3, - Numpad4: KeyCode.NUM_4, - Numpad5: KeyCode.NUM_5, - Numpad6: KeyCode.NUM_6, - Numpad7: KeyCode.NUM_7, - Numpad8: KeyCode.NUM_8, - Numpad9: KeyCode.NUM_9, - NumpadMultiply: KeyCode.NUM_MULTIPLY, - NumpadAdd: KeyCode.NUM_PLUS, - NumpadSubtract: KeyCode.NUM_SUBTRACT, - NumpadDecimal: KeyCode.NUM_DECIMAL, - NumpadDivide: KeyCode.NUM_DIVIDE, - NumpadEnter: KeyCode.NUM_ENTER, - F1: KeyCode.F1, - F2: KeyCode.F2, - F3: KeyCode.F3, - F4: KeyCode.F4, - F5: KeyCode.F5, - F6: KeyCode.F6, - F7: KeyCode.F7, - F8: KeyCode.F8, - F9: KeyCode.F9, - F10: KeyCode.F10, - F11: KeyCode.F11, - F12: KeyCode.F12, - NumLock: KeyCode.NUM_LOCK, - ScrollLock: KeyCode.SCROLL_LOCK, - Semicolon: KeyCode.SEMICOLON, - Equal: KeyCode.EQUAL, - Comma: KeyCode.COMMA, - Minus: KeyCode.DASH, - Period: KeyCode.PERIOD, - Slash: KeyCode.SLASH, - Backquote: KeyCode.BACK_QUOTE, - BracketLeft: KeyCode.BRACKET_LEFT, - Backslash: KeyCode.BACKSLASH, - BracketRight: KeyCode.BRACKET_RIGHT, - Quote: KeyCode.QUOTE, -}; diff --git a/pal/input/minigame/accelerometer-input.ts b/pal/input/minigame/accelerometer-input.ts deleted file mode 100644 index d278ff7933..0000000000 --- a/pal/input/minigame/accelerometer-input.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { AccelerometerCallback } from 'pal/input'; -import { minigame, AccelerometerIntervalMode } from 'pal/minigame'; -import { Acceleration, EventAcceleration } from '../../../cocos/input/types'; -import { EventTarget } from '../../../cocos/core/event'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { errorID } from '../../../cocos/core/platform/debug'; - -export class AccelerometerInputSource { - private _isStarted = false; - private _accelMode: AccelerometerIntervalMode = 'normal'; - private _eventTarget: EventTarget = new EventTarget(); - private declare _didAccelerateFunc: (event: AccelerometerData) => void; - - constructor () { - this._didAccelerateFunc = this._didAccelerate.bind(this); - } - - private _registerEvent (): void { - minigame.onAccelerometerChange(this._didAccelerateFunc); - } - - private _unregisterEvent (): void { - minigame.offAccelerometerChange(this._didAccelerateFunc); - } - - private _didAccelerate (event: AccelerometerData): void { - const timestamp = performance.now(); - const acceleration = new Acceleration(event.x, event.y, event.z, timestamp); - const eventAcceleration = new EventAcceleration(acceleration); - this._eventTarget.emit(InputEventType.DEVICEMOTION, eventAcceleration); - } - - public start (): void { - this._registerEvent(); - minigame.startAccelerometer({ - interval: this._accelMode, - success: () => { - this._isStarted = true; - }, - }); - } - public stop (): void { - minigame.stopAccelerometer({ - success: () => { - this._isStarted = false; - }, - fail () { - errorID(16305); - }, - }); - this._unregisterEvent(); - } - public setInterval (intervalInMileseconds: number): void { - // reference: https://developers.weixin.qq.com/minigame/dev/api/device/accelerometer/wx.startAccelerometer.html - if (intervalInMileseconds >= 200) { - this._accelMode = 'normal'; - } else if (intervalInMileseconds >= 60) { - this._accelMode = 'ui'; - } else { - this._accelMode = 'game'; - } - if (this._isStarted) { - // restart accelerometer - this.stop(); - this.start(); - } - } - public on (eventType: InputEventType, callback: AccelerometerCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } -} diff --git a/pal/input/minigame/gamepad-input.ts b/pal/input/minigame/gamepad-input.ts deleted file mode 100644 index caa32884b6..0000000000 --- a/pal/input/minigame/gamepad-input.ts +++ /dev/null @@ -1,216 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { GamepadCallback } from 'pal/input'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { InputSourceButton, InputSourceDpad, InputSourceOrientation, InputSourcePosition, InputSourceStick } from '../input-source'; -import { Quat, Vec3 } from '../../../cocos/core'; - -export class GamepadInputDevice { - public static all: GamepadInputDevice[] = []; - public static xr: (GamepadInputDevice | null) = null; - - public get buttonNorth (): InputSourceButton { return this._buttonNorth; } - public get buttonEast (): InputSourceButton { return this._buttonEast; } - public get buttonWest (): InputSourceButton { return this._buttonWest; } - public get buttonSouth (): InputSourceButton { return this._buttonSouth; } - public get buttonL1 (): InputSourceButton { return this._buttonL1; } - public get buttonL2 (): InputSourceButton { return this._buttonL2; } - public get buttonL3 (): InputSourceButton { return this._buttonL3; } - public get buttonR1 (): InputSourceButton { return this._buttonR1; } - public get buttonR2 (): InputSourceButton { return this._buttonR2; } - public get buttonR3 (): InputSourceButton { return this._buttonR3; } - // public get buttonTouchPad () { return this._buttonTouchPad; } - // public get buttonHome () { return this._buttonHome; } - public get buttonShare (): InputSourceButton { return this._buttonShare; } - public get buttonOptions (): InputSourceButton { return this._buttonOptions; } - public get dpad (): InputSourceDpad { return this._dpad; } - public get leftStick (): InputSourceStick { return this._leftStick; } - public get rightStick (): InputSourceStick { return this._rightStick; } - public get buttonStart (): InputSourceButton { return this._buttonStart; } - public get gripLeft (): InputSourceButton { return this._gripLeft; } - public get gripRight (): InputSourceButton { return this._gripRight; } - public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; } - public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; } - public get handRightPosition (): InputSourcePosition { return this._handRightPosition; } - public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; } - public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; } - public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; } - public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; } - public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; } - - public get deviceId (): number { - return this._deviceId; - } - public get connected (): boolean { - return this._connected; - } - - private static _eventTarget: EventTarget = new EventTarget(); - - private declare _buttonNorth: InputSourceButton; - private declare _buttonEast: InputSourceButton; - private declare _buttonWest: InputSourceButton; - private declare _buttonSouth: InputSourceButton; - private declare _buttonL1: InputSourceButton; - private declare _buttonL2: InputSourceButton; - private declare _buttonL3: InputSourceButton; - private declare _buttonR1: InputSourceButton; - private declare _buttonR2: InputSourceButton; - private declare _buttonR3: InputSourceButton; - // private declare buttonTouchPad: InputSourceButton; - // private declare buttonHome: InputSourceButton; - private declare _buttonShare: InputSourceButton; - private declare _buttonOptions: InputSourceButton; - private declare _dpad: InputSourceDpad; - private declare _leftStick: InputSourceStick; - private declare _rightStick: InputSourceStick; - private declare _buttonStart: InputSourceButton; - private declare _gripLeft: InputSourceButton; - private declare _gripRight: InputSourceButton; - private declare _handLeftPosition: InputSourcePosition; - private declare _handLeftOrientation: InputSourceOrientation; - private declare _handRightPosition: InputSourcePosition; - private declare _handRightOrientation: InputSourceOrientation; - private declare _aimLeftPosition: InputSourcePosition; - private declare _aimLeftOrientation: InputSourceOrientation; - private declare _aimRightPosition: InputSourcePosition; - private declare _aimRightOrientation: InputSourceOrientation; - - private _deviceId = -1; - private _connected = false; - - constructor (deviceId: number) { - this._deviceId = deviceId; - this._initInputSource(); - } - - /** - * @engineInternal - */ - public static _init (): void { - // not supported - } - - /** - * @engineInternal - */ - public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any): void { - GamepadInputDevice._eventTarget.on(eventType, cb, target); - } - - private _initInputSource (): void { - const self = this; - self._buttonNorth = new InputSourceButton(); - self._buttonNorth.getValue = (): number => 0; - self._buttonEast = new InputSourceButton(); - self._buttonEast.getValue = (): number => 0; - self._buttonWest = new InputSourceButton(); - self._buttonWest.getValue = (): number => 0; - self._buttonSouth = new InputSourceButton(); - self._buttonSouth.getValue = (): number => 0; - - self._buttonL1 = new InputSourceButton(); - self._buttonL1.getValue = (): number => 0; - self._buttonL2 = new InputSourceButton(); - self._buttonL2.getValue = (): number => 0; - self._buttonL3 = new InputSourceButton(); - self._buttonL3.getValue = (): number => 0; - self._buttonR1 = new InputSourceButton(); - self._buttonR1.getValue = (): number => 0; - self._buttonR2 = new InputSourceButton(); - self._buttonR2.getValue = (): number => 0; - self._buttonR3 = new InputSourceButton(); - self._buttonR3.getValue = (): number => 0; - - // self._buttonTouchPad = new InputSourceButton(); - // self._buttonTouchPad.getValue = () => 0; - // self._buttonHome = new InputSourceButton(); - // self._buttonHome.getValue = () => 0; - - self._buttonShare = new InputSourceButton(); - self._buttonShare.getValue = (): number => 0; - self._buttonOptions = new InputSourceButton(); - self._buttonOptions.getValue = (): number => 0; - - const dpadUp = new InputSourceButton(); - dpadUp.getValue = (): number => 0; - const dpadDown = new InputSourceButton(); - dpadDown.getValue = (): number => 0; - const dpadLeft = new InputSourceButton(); - dpadLeft.getValue = (): number => 0; - const dpadRight = new InputSourceButton(); - dpadRight.getValue = (): number => 0; - self._dpad = new InputSourceDpad({ up: dpadUp, down: dpadDown, left: dpadLeft, right: dpadRight }); - - const leftStickUp = new InputSourceButton(); - leftStickUp.getValue = (): number => 0; - const leftStickDown = new InputSourceButton(); - leftStickDown.getValue = (): number => 0; - const leftStickLeft = new InputSourceButton(); - leftStickLeft.getValue = (): number => 0; - const leftStickRight = new InputSourceButton(); - leftStickRight.getValue = (): number => 0; - self._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); - - const rightStickUp = new InputSourceButton(); - rightStickUp.getValue = (): number => 0; - const rightStickDown = new InputSourceButton(); - rightStickDown.getValue = (): number => 0; - const rightStickLeft = new InputSourceButton(); - rightStickLeft.getValue = (): number => 0; - const rightStickRight = new InputSourceButton(); - rightStickRight.getValue = (): number => 0; - self._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); - - self._buttonStart = new InputSourceButton(); - self._buttonStart.getValue = (): number => 0; - - self._gripLeft = new InputSourceButton(); - self._gripLeft.getValue = (): number => 0; - self._gripRight = new InputSourceButton(); - self._gripRight.getValue = (): number => 0; - - self._handLeftPosition = new InputSourcePosition(); - self._handLeftPosition.getValue = (): Readonly => Vec3.ZERO; - self._handLeftOrientation = new InputSourceOrientation(); - self._handLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; - - self._handRightPosition = new InputSourcePosition(); - self._handRightPosition.getValue = (): Readonly => Vec3.ZERO; - self._handRightOrientation = new InputSourceOrientation(); - self._handRightOrientation.getValue = (): Readonly => Quat.IDENTITY; - - self._aimLeftPosition = new InputSourcePosition(); - self._aimLeftPosition.getValue = (): Readonly => Vec3.ZERO; - self._aimLeftOrientation = new InputSourceOrientation(); - self._aimLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; - - self._aimRightPosition = new InputSourcePosition(); - self._aimRightPosition.getValue = (): Readonly => Vec3.ZERO; - self._aimRightOrientation = new InputSourceOrientation(); - self._aimRightOrientation.getValue = (): Readonly => Quat.IDENTITY; - } -} diff --git a/pal/input/minigame/handheld-input.ts b/pal/input/minigame/handheld-input.ts deleted file mode 100644 index 4f5b6ba920..0000000000 --- a/pal/input/minigame/handheld-input.ts +++ /dev/null @@ -1,57 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated 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 { HandheldCallback } from 'pal/input'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { InputSourcePosition, InputSourceOrientation } from '../input-source'; -import { Quat, Vec3 } from '../../../cocos/core/math'; - -export class HandheldInputDevice { - public get handheldPosition (): InputSourcePosition { return this._handheldPosition; } - public get handheldOrientation (): InputSourceOrientation { return this._handheldOrientation; } - - private _eventTarget: EventTarget = new EventTarget(); - - private declare _handheldPosition: InputSourcePosition; - private declare _handheldOrientation: InputSourceOrientation; - - constructor () { - this._initInputSource(); - } - - /** - * @engineInternal - */ - public _on (eventType: InputEventType, callback: HandheldCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - - private _initInputSource (): void { - this._handheldPosition = new InputSourcePosition(); - this._handheldPosition.getValue = (): Readonly => Vec3.ZERO; - this._handheldOrientation = new InputSourceOrientation(); - this._handheldOrientation.getValue = (): Readonly => Quat.IDENTITY; - } -} diff --git a/pal/input/minigame/handle-input.ts b/pal/input/minigame/handle-input.ts deleted file mode 100644 index e3cb4d8798..0000000000 --- a/pal/input/minigame/handle-input.ts +++ /dev/null @@ -1,201 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { HandleCallback } from 'pal/input'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { EventTarget } from '../../../cocos/core/event'; -import { InputSourceButton, InputSourceStick, InputSourcePosition, InputSourceOrientation, InputSourceTouch } from '../input-source'; -import { Vec3, Quat } from '../../../cocos/core/math'; - -export class HandleInputDevice { - public get buttonNorth (): InputSourceButton { return this._buttonNorth; } - public get buttonEast (): InputSourceButton { return this._buttonEast; } - public get buttonWest (): InputSourceButton { return this._buttonWest; } - public get buttonSouth (): InputSourceButton { return this._buttonSouth; } - public get buttonTriggerLeft (): InputSourceButton { return this._buttonTriggerLeft; } - public get buttonTriggerRight (): InputSourceButton { return this._buttonTriggerRight; } - public get triggerLeft (): InputSourceButton { return this._triggerLeft; } - public get triggerRight (): InputSourceButton { return this._triggerRight; } - public get gripLeft (): InputSourceButton { return this._gripLeft; } - public get gripRight (): InputSourceButton { return this._gripRight; } - public get leftStick (): InputSourceStick { return this._leftStick; } - public get rightStick (): InputSourceStick { return this._rightStick; } - public get buttonLeftStick (): InputSourceButton { return this._buttonLeftStick; } - public get buttonRightStick (): InputSourceButton { return this._buttonRightStick; } - public get buttonOptions (): InputSourceButton { return this._buttonOptions; } - public get buttonStart (): InputSourceButton { return this._buttonStart; } - public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; } - public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; } - public get handRightPosition (): InputSourcePosition { return this._handRightPosition; } - public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; } - public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; } - public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; } - public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; } - public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; } - public get touchButtonA (): InputSourceTouch { return this._touchButtonA; } - public get touchButtonB (): InputSourceTouch { return this._touchButtonB; } - public get touchButtonX (): InputSourceTouch { return this._touchButtonX; } - public get touchButtonY (): InputSourceTouch { return this._touchButtonY; } - public get touchButtonTriggerLeft (): InputSourceTouch { return this._touchButtonTriggerLeft; } - public get touchButtonTriggerRight (): InputSourceTouch { return this._touchButtonTriggerRight; } - public get touchButtonThumbStickLeft (): InputSourceTouch { return this._touchButtonThumbStickLeft; } - public get touchButtonThumbStickRight (): InputSourceTouch { return this._touchButtonThumbStickRight; } - - private _eventTarget: EventTarget = new EventTarget(); - - private declare _buttonNorth: InputSourceButton; - private declare _buttonEast: InputSourceButton; - private declare _buttonWest: InputSourceButton; - private declare _buttonSouth: InputSourceButton; - private declare _buttonTriggerLeft: InputSourceButton; - private declare _buttonTriggerRight: InputSourceButton; - private declare _triggerLeft: InputSourceButton; - private declare _triggerRight: InputSourceButton; - private declare _gripLeft: InputSourceButton; - private declare _gripRight: InputSourceButton; - private declare _leftStick: InputSourceStick; - private declare _rightStick: InputSourceStick; - private declare _buttonLeftStick: InputSourceButton; - private declare _buttonRightStick: InputSourceButton; - private declare _buttonOptions: InputSourceButton; - private declare _buttonStart: InputSourceButton; - private declare _handLeftPosition: InputSourcePosition; - private declare _handLeftOrientation: InputSourceOrientation; - private declare _handRightPosition: InputSourcePosition; - private declare _handRightOrientation: InputSourceOrientation; - private declare _aimLeftPosition: InputSourcePosition; - private declare _aimLeftOrientation: InputSourceOrientation; - private declare _aimRightPosition: InputSourcePosition; - private declare _aimRightOrientation: InputSourceOrientation; - private declare _touchButtonA: InputSourceTouch; - private declare _touchButtonB: InputSourceTouch; - private declare _touchButtonX: InputSourceTouch; - private declare _touchButtonY: InputSourceTouch; - private declare _touchButtonTriggerLeft: InputSourceTouch; - private declare _touchButtonTriggerRight: InputSourceTouch; - private declare _touchButtonThumbStickLeft: InputSourceTouch; - private declare _touchButtonThumbStickRight: InputSourceTouch; - - constructor () { - this._initInputSource(); - } - - /** - * @engineInternal - */ - public _on (eventType: InputEventType, callback: HandleCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - - private _initInputSource (): void { - const self = this; - self._buttonNorth = new InputSourceButton(); - self._buttonNorth.getValue = (): number => 0; - self._buttonEast = new InputSourceButton(); - self._buttonEast.getValue = (): number => 0; - self._buttonWest = new InputSourceButton(); - self._buttonWest.getValue = (): number => 0; - self._buttonSouth = new InputSourceButton(); - self._buttonSouth.getValue = (): number => 0; - - self._buttonTriggerLeft = new InputSourceButton(); - self._buttonTriggerLeft.getValue = (): number => 0; - self._buttonTriggerRight = new InputSourceButton(); - self._buttonTriggerRight.getValue = (): number => 0; - self._triggerLeft = new InputSourceButton(); - self._triggerLeft.getValue = (): number => 0; - self._triggerRight = new InputSourceButton(); - self._triggerRight.getValue = (): number => 0; - self._gripLeft = new InputSourceButton(); - self._gripLeft.getValue = (): number => 0; - self._gripRight = new InputSourceButton(); - self._gripRight.getValue = (): number => 0; - - self._buttonLeftStick = new InputSourceButton(); - self._buttonLeftStick.getValue = (): number => 0; - const leftStickUp = new InputSourceButton(); - leftStickUp.getValue = (): number => 0; - const leftStickDown = new InputSourceButton(); - leftStickDown.getValue = (): number => 0; - const leftStickLeft = new InputSourceButton(); - leftStickLeft.getValue = (): number => 0; - const leftStickRight = new InputSourceButton(); - leftStickRight.getValue = (): number => 0; - self._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); - - self._buttonRightStick = new InputSourceButton(); - self._buttonRightStick.getValue = (): number => 0; - const rightStickUp = new InputSourceButton(); - rightStickUp.getValue = (): number => 0; - const rightStickDown = new InputSourceButton(); - rightStickDown.getValue = (): number => 0; - const rightStickLeft = new InputSourceButton(); - rightStickLeft.getValue = (): number => 0; - const rightStickRight = new InputSourceButton(); - rightStickRight.getValue = (): number => 0; - self._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); - - self._buttonOptions = new InputSourceButton(); - self._buttonOptions.getValue = (): number => 0; - self._buttonStart = new InputSourceButton(); - self._buttonStart.getValue = (): number => 0; - - self._handLeftPosition = new InputSourcePosition(); - self._handLeftPosition.getValue = (): Readonly => Vec3.ZERO; - self._handLeftOrientation = new InputSourceOrientation(); - self._handLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; - - self._handRightPosition = new InputSourcePosition(); - self._handRightPosition.getValue = (): Readonly => Vec3.ZERO; - self._handRightOrientation = new InputSourceOrientation(); - self._handRightOrientation.getValue = (): Readonly => Quat.IDENTITY; - - self._aimLeftPosition = new InputSourcePosition(); - self._aimLeftPosition.getValue = (): Readonly => Vec3.ZERO; - self._aimLeftOrientation = new InputSourceOrientation(); - self._aimLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; - - self._aimRightPosition = new InputSourcePosition(); - self._aimRightPosition.getValue = (): Readonly => Vec3.ZERO; - self._aimRightOrientation = new InputSourceOrientation(); - self._aimRightOrientation.getValue = (): Readonly => Quat.IDENTITY; - - self._touchButtonA = new InputSourceTouch(); - self._touchButtonA.getValue = (): number => 0; - self._touchButtonB = new InputSourceTouch(); - self._touchButtonB.getValue = (): number => 0; - self._touchButtonX = new InputSourceTouch(); - self._touchButtonX.getValue = (): number => 0; - self._touchButtonY = new InputSourceTouch(); - self._touchButtonY.getValue = (): number => 0; - self._touchButtonTriggerLeft = new InputSourceTouch(); - self._touchButtonTriggerLeft.getValue = (): number => 0; - self._touchButtonTriggerRight = new InputSourceTouch(); - self._touchButtonTriggerRight.getValue = (): number => 0; - self._touchButtonThumbStickLeft = new InputSourceTouch(); - self._touchButtonThumbStickLeft.getValue = (): number => 0; - self._touchButtonThumbStickRight = new InputSourceTouch(); - self._touchButtonThumbStickRight.getValue = (): number => 0; - } -} diff --git a/pal/input/minigame/hmd-input.ts b/pal/input/minigame/hmd-input.ts deleted file mode 100644 index 0ff04bd1cf..0000000000 --- a/pal/input/minigame/hmd-input.ts +++ /dev/null @@ -1,76 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { HMDCallback } from 'pal/input'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { InputSourcePosition, InputSourceOrientation } from '../input-source'; -import { Vec3, Quat } from '../../../cocos/core/math'; - -export class HMDInputDevice { - public get viewLeftPosition (): InputSourcePosition { return this._viewLeftPosition; } - public get viewLeftOrientation (): InputSourceOrientation { return this._viewLeftOrientation; } - public get viewRightPosition (): InputSourcePosition { return this._viewRightPosition; } - public get viewRightOrientation (): InputSourceOrientation { return this._viewRightOrientation; } - public get headMiddlePosition (): InputSourcePosition { return this._headMiddlePosition; } - public get headMiddleOrientation (): InputSourceOrientation { return this._headMiddleOrientation; } - - private _eventTarget: EventTarget = new EventTarget(); - - private declare _viewLeftPosition: InputSourcePosition; - private declare _viewLeftOrientation: InputSourceOrientation; - private declare _viewRightPosition: InputSourcePosition; - private declare _viewRightOrientation: InputSourceOrientation; - private declare _headMiddlePosition: InputSourcePosition; - private declare _headMiddleOrientation: InputSourceOrientation; - - constructor () { - this._initInputSource(); - } - - /** - * @engineInternal - */ - public _on (eventType: InputEventType, callback: HMDCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - - private _initInputSource (): void { - const self = this; - self._viewLeftPosition = new InputSourcePosition(); - self._viewLeftPosition.getValue = (): Readonly => Vec3.ZERO; - self._viewLeftOrientation = new InputSourceOrientation(); - self._viewLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; - - self._viewRightPosition = new InputSourcePosition(); - self._viewRightPosition.getValue = (): Readonly => Vec3.ZERO; - self._viewRightOrientation = new InputSourceOrientation(); - self._viewRightOrientation.getValue = (): Readonly => Quat.IDENTITY; - - self._headMiddlePosition = new InputSourcePosition(); - self._headMiddlePosition.getValue = (): Readonly => Vec3.ZERO; - self._headMiddleOrientation = new InputSourceOrientation(); - self._headMiddleOrientation.getValue = (): Readonly => Quat.IDENTITY; - } -} diff --git a/pal/input/minigame/index.ts b/pal/input/minigame/index.ts deleted file mode 100644 index a30638e368..0000000000 --- a/pal/input/minigame/index.ts +++ /dev/null @@ -1,36 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { checkPalIntegrity, withImpl } from '../../integrity-check'; - -export * from './accelerometer-input'; -export * from './gamepad-input'; -export * from './handle-input'; -export * from './hmd-input'; -export * from './handheld-input'; -export * from './keyboard-input'; -export * from './mouse-input'; -export * from './touch-input'; - -checkPalIntegrity(withImpl()); diff --git a/pal/input/minigame/keyboard-input.ts b/pal/input/minigame/keyboard-input.ts deleted file mode 100644 index c78f15e741..0000000000 --- a/pal/input/minigame/keyboard-input.ts +++ /dev/null @@ -1,181 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { KeyboardCallback } from 'pal/input'; -import { KeyboardEventData, minigame } from 'pal/minigame'; -import { systemInfo } from 'pal/system-info'; -import { KeyCode, EventKeyboard } from '../../../cocos/input/types'; -import { EventTarget } from '../../../cocos/core/event'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { Feature } from '../../system-info/enum-type'; - -const code2KeyCode: Record = { - Backspace: KeyCode.BACKSPACE, - Tab: KeyCode.TAB, - Enter: KeyCode.ENTER, - ShiftLeft: KeyCode.SHIFT_LEFT, - ControlLeft: KeyCode.CTRL_LEFT, - AltLeft: KeyCode.ALT_LEFT, - ShiftRight: KeyCode.SHIFT_RIGHT, - ControlRight: KeyCode.CTRL_RIGHT, - AltRight: KeyCode.ALT_RIGHT, - Pause: KeyCode.PAUSE, - CapsLock: KeyCode.CAPS_LOCK, - Escape: KeyCode.ESCAPE, - Space: KeyCode.SPACE, - PageUp: KeyCode.PAGE_UP, - PageDown: KeyCode.PAGE_DOWN, - End: KeyCode.END, - Home: KeyCode.HOME, - ArrowLeft: KeyCode.ARROW_LEFT, - ArrowUp: KeyCode.ARROW_UP, - ArrowRight: KeyCode.ARROW_RIGHT, - ArrowDown: KeyCode.ARROW_DOWN, - Insert: KeyCode.INSERT, - Delete: KeyCode.DELETE, - Digit0: KeyCode.DIGIT_0, - Digit1: KeyCode.DIGIT_1, - Digit2: KeyCode.DIGIT_2, - Digit3: KeyCode.DIGIT_3, - Digit4: KeyCode.DIGIT_4, - Digit5: KeyCode.DIGIT_5, - Digit6: KeyCode.DIGIT_6, - Digit7: KeyCode.DIGIT_7, - Digit8: KeyCode.DIGIT_8, - Digit9: KeyCode.DIGIT_9, - KeyA: KeyCode.KEY_A, - KeyB: KeyCode.KEY_B, - KeyC: KeyCode.KEY_C, - KeyD: KeyCode.KEY_D, - KeyE: KeyCode.KEY_E, - KeyF: KeyCode.KEY_F, - KeyG: KeyCode.KEY_G, - KeyH: KeyCode.KEY_H, - KeyI: KeyCode.KEY_I, - KeyJ: KeyCode.KEY_J, - KeyK: KeyCode.KEY_K, - KeyL: KeyCode.KEY_L, - KeyM: KeyCode.KEY_M, - KeyN: KeyCode.KEY_N, - KeyO: KeyCode.KEY_O, - KeyP: KeyCode.KEY_P, - KeyQ: KeyCode.KEY_Q, - KeyR: KeyCode.KEY_R, - KeyS: KeyCode.KEY_S, - KeyT: KeyCode.KEY_T, - KeyU: KeyCode.KEY_U, - KeyV: KeyCode.KEY_V, - KeyW: KeyCode.KEY_W, - KeyX: KeyCode.KEY_X, - KeyY: KeyCode.KEY_Y, - KeyZ: KeyCode.KEY_Z, - Numpad0: KeyCode.NUM_0, - Numpad1: KeyCode.NUM_1, - Numpad2: KeyCode.NUM_2, - Numpad3: KeyCode.NUM_3, - Numpad4: KeyCode.NUM_4, - Numpad5: KeyCode.NUM_5, - Numpad6: KeyCode.NUM_6, - Numpad7: KeyCode.NUM_7, - Numpad8: KeyCode.NUM_8, - Numpad9: KeyCode.NUM_9, - NumpadMultiply: KeyCode.NUM_MULTIPLY, - NumpadAdd: KeyCode.NUM_PLUS, - NumpadSubtract: KeyCode.NUM_SUBTRACT, - NumpadDecimal: KeyCode.NUM_DECIMAL, - NumpadDivide: KeyCode.NUM_DIVIDE, - NumpadEnter: KeyCode.NUM_ENTER, - F1: KeyCode.F1, - F2: KeyCode.F2, - F3: KeyCode.F3, - F4: KeyCode.F4, - F5: KeyCode.F5, - F6: KeyCode.F6, - F7: KeyCode.F7, - F8: KeyCode.F8, - F9: KeyCode.F9, - F10: KeyCode.F10, - F11: KeyCode.F11, - F12: KeyCode.F12, - NumLock: KeyCode.NUM_LOCK, - ScrollLock: KeyCode.SCROLL_LOCK, - Semicolon: KeyCode.SEMICOLON, - Equal: KeyCode.EQUAL, - Comma: KeyCode.COMMA, - Minus: KeyCode.DASH, - Period: KeyCode.PERIOD, - Slash: KeyCode.SLASH, - Backquote: KeyCode.BACK_QUOTE, - BracketLeft: KeyCode.BRACKET_LEFT, - Backslash: KeyCode.BACKSLASH, - BracketRight: KeyCode.BRACKET_RIGHT, - Quote: KeyCode.QUOTE, -}; - -function getKeyCode (code: string): KeyCode { - return code2KeyCode[code] || KeyCode.NONE; -} - -export class KeyboardInputSource { - private _eventTarget: EventTarget = new EventTarget(); - - // KeyboardEvent.repeat is not supported on Wechat PC platform. - private _keyStateMap: Record = {}; - - constructor () { - if (systemInfo.hasFeature(Feature.EVENT_KEYBOARD)) { - this._registerEvent(); - } - } - - private _registerEvent (): void { - minigame.wx?.onKeyDown?.((res) => { - const keyCode = getKeyCode(res.code); - if (!this._keyStateMap[keyCode]) { - const eventKeyDown = this._getInputEvent(res, InputEventType.KEY_DOWN); - this._eventTarget.emit(InputEventType.KEY_DOWN, eventKeyDown); - } else { - const eventKeyPressing = this._getInputEvent(res, InputEventType.KEY_PRESSING); - this._eventTarget.emit(InputEventType.KEY_PRESSING, eventKeyPressing); - } - this._keyStateMap[keyCode] = true; - }); - minigame.wx?.onKeyUp?.((res) => { - const keyCode = getKeyCode(res.code); - const eventKeyUp = this._getInputEvent(res, InputEventType.KEY_UP); - this._keyStateMap[keyCode] = false; - this._eventTarget.emit(InputEventType.KEY_UP, eventKeyUp); - }); - } - - private _getInputEvent (event: KeyboardEventData, eventType: InputEventType): EventKeyboard { - const keyCode = getKeyCode(event.code); - const eventKeyboard = new EventKeyboard(keyCode, eventType); - return eventKeyboard; - } - - public on (eventType: InputEventType, callback: KeyboardCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } -} diff --git a/pal/input/minigame/mouse-input.ts b/pal/input/minigame/mouse-input.ts deleted file mode 100644 index f49355b7ed..0000000000 --- a/pal/input/minigame/mouse-input.ts +++ /dev/null @@ -1,117 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { MouseCallback } from 'pal/input'; -import { MouseEventData, MouseWheelEventData, minigame } from 'pal/minigame'; -import { screenAdapter } from 'pal/screen-adapter'; -import { systemInfo } from 'pal/system-info'; -import { Vec2 } from '../../../cocos/core/math'; -import { EventTarget } from '../../../cocos/core/event'; -import { EventMouse } from '../../../cocos/input/types'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { Feature } from '../../system-info/enum-type'; - -export class MouseInputSource { - private _eventTarget: EventTarget = new EventTarget(); - private _isPressed = false; - private _preMousePos: Vec2 = new Vec2(); - - constructor () { - if (systemInfo.hasFeature(Feature.EVENT_MOUSE)) { - this._registerEvent(); - } - } - - private _getLocation (event: MouseEventData): Vec2 { - const windowSize = screenAdapter.windowSize; - const dpr = screenAdapter.devicePixelRatio; - const x = event.x * dpr; - const y = windowSize.height - event.y * dpr; - return new Vec2(x, y); - } - - private _registerEvent (): void { - minigame.wx?.onMouseDown?.(this._createCallback(InputEventType.MOUSE_DOWN)); - minigame.wx?.onMouseMove?.(this._createCallback(InputEventType.MOUSE_MOVE)); - minigame.wx?.onMouseUp?.(this._createCallback(InputEventType.MOUSE_UP)); - minigame.wx?.onWheel?.(this._handleMouseWheel.bind(this)); - } - - private _createCallback (eventType: InputEventType) { - return (event: MouseEventData): void => { - const location = this._getLocation(event); - let button = event.button; - switch (eventType) { - case InputEventType.MOUSE_DOWN: - this._isPressed = true; - break; - case InputEventType.MOUSE_UP: - this._isPressed = false; - break; - case InputEventType.MOUSE_MOVE: - if (!this._isPressed) { - button = EventMouse.BUTTON_MISSING; - } - break; - default: - break; - } - - const eventMouse = new EventMouse(eventType, false, this._preMousePos); - eventMouse.setLocation(location.x, location.y); - eventMouse.setButton(button); - eventMouse.movementX = location.x - this._preMousePos.x; - eventMouse.movementY = this._preMousePos.y - location.y; - - // update previous mouse position. - this._preMousePos.set(location.x, location.y); - this._eventTarget.emit(eventType, eventMouse); - }; - } - - private _handleMouseWheel (event: MouseWheelEventData): void { - const eventType = InputEventType.MOUSE_WHEEL; - const location = this._getLocation(event); - const button = event.button; - - const eventMouse = new EventMouse(eventType, false, this._preMousePos); - eventMouse.setLocation(location.x, location.y); - eventMouse.setButton(button); - eventMouse.movementX = location.x - this._preMousePos.x; - eventMouse.movementY = this._preMousePos.y - location.y; - - eventMouse.setScrollData(event.deltaX, -event.deltaY); - // update previous mouse position. - this._preMousePos.set(location.x, location.y); - this._eventTarget.emit(InputEventType.MOUSE_WHEEL, eventMouse); - } - - public on (eventType: InputEventType, callback: MouseCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - - public dispatchEventsInCache (): void { - // Do nothing - } -} diff --git a/pal/input/minigame/touch-input.ts b/pal/input/minigame/touch-input.ts deleted file mode 100644 index 4413922d5f..0000000000 --- a/pal/input/minigame/touch-input.ts +++ /dev/null @@ -1,99 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { TouchCallback } from 'pal/input'; -import { minigame } from 'pal/minigame'; -import { screenAdapter } from 'pal/screen-adapter'; -import { systemInfo } from 'pal/system-info'; -import { Size, Vec2 } from '../../../cocos/core/math'; -import { EventTarget } from '../../../cocos/core/event'; -import { EventTouch, Touch } from '../../../cocos/input/types'; -import { touchManager } from '../touch-manager'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { Feature } from '../../system-info/enum-type'; - -export class TouchInputSource { - private _eventTarget: EventTarget = new EventTarget(); - - constructor () { - if (systemInfo.hasFeature(Feature.INPUT_TOUCH)) { - this._registerEvent(); - } - } - - private _registerEvent (): void { - minigame.onTouchStart(this._createCallback(InputEventType.TOUCH_START)); - minigame.onTouchMove(this._createCallback(InputEventType.TOUCH_MOVE)); - minigame.onTouchEnd(this._createCallback(InputEventType.TOUCH_END)); - minigame.onTouchCancel(this._createCallback(InputEventType.TOUCH_CANCEL)); - } - - private _createCallback (eventType: InputEventType) { - return (event: TouchEvent): void => { - const handleTouches: Touch[] = []; - const windowSize = screenAdapter.windowSize; - const dpr = screenAdapter.devicePixelRatio; - const length = event.changedTouches.length; - for (let i = 0; i < length; ++i) { - const changedTouch = event.changedTouches[i]; - const touchID = changedTouch.identifier; - if (touchID === null) { - continue; - } - const location = this._getLocation(changedTouch, windowSize, dpr); - const touch = touchManager.getOrCreateTouch(touchID, location.x, location.y); - if (!touch) { - continue; - } - if (eventType === InputEventType.TOUCH_END || eventType === InputEventType.TOUCH_CANCEL) { - touchManager.releaseTouch(touchID); - } - handleTouches.push(touch); - } - if (handleTouches.length > 0) { - const eventTouch = new EventTouch( - handleTouches, - false, - eventType, - touchManager.getAllTouches(), - ); - this._eventTarget.emit(eventType, eventTouch); - } - }; - } - - private _getLocation (touch: globalThis.Touch, windowSize: Size, dpr: number): Vec2 { - const x = touch.clientX * dpr; - const y = windowSize.height - touch.clientY * dpr; - return new Vec2(x, y); - } - - public on (eventType: InputEventType, callback: TouchCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - - public dispatchEventsInCache (): void { - // Do nothing - } -} diff --git a/pal/input/native/accelerometer-input.ts b/pal/input/native/accelerometer-input.ts deleted file mode 100644 index e19ba3331f..0000000000 --- a/pal/input/native/accelerometer-input.ts +++ /dev/null @@ -1,106 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { systemInfo } from 'pal/system-info'; -import { screenAdapter } from 'pal/screen-adapter'; -import { EventTarget } from '../../../cocos/core/event'; -import { OS } from '../../system-info/enum-type'; -import { Orientation } from '../../screen-adapter/enum-type'; -import { Acceleration, EventAcceleration } from '../../../cocos/input/types'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; - -export type AccelerometerCallback = (res: EventAcceleration) => void; - -export class AccelerometerInputSource { - private _intervalInSeconds = 0.2; - private _intervalId?: number; - private _isEnabled = false; - private _eventTarget: EventTarget = new EventTarget(); - private declare _didAccelerateFunc: () => void; - - constructor () { - this._didAccelerateFunc = this._didAccelerate.bind(this); - } - - private _didAccelerate (): void { - const deviceMotionValue = jsb.device.getDeviceMotionValue(); - let x = deviceMotionValue[3] * 0.1; - let y = deviceMotionValue[4] * 0.1; - const z = deviceMotionValue[5] * 0.1; - - const orientation = screenAdapter.orientation; - const tmpX = x; - if (orientation === Orientation.LANDSCAPE_RIGHT) { - x = -y; - y = tmpX; - } else if (orientation === Orientation.LANDSCAPE_LEFT) { - x = y; - y = -tmpX; - } else if (orientation === Orientation.PORTRAIT_UPSIDE_DOWN) { - x = -x; - y = -y; - } - - // fix android acc values are opposite - if (systemInfo.os === OS.ANDROID || systemInfo.os === OS.OHOS || systemInfo.os === OS.OPENHARMONY) { - x = -x; - y = -y; - } - - const timestamp = performance.now(); - const acceleration = new Acceleration(x, y, z, timestamp); - const eventAcceleration = new EventAcceleration(acceleration); - this._eventTarget.emit(InputEventType.DEVICEMOTION, eventAcceleration); - } - - public start (): void { - if (this._intervalId) { - clearInterval(this._intervalId); - } - this._intervalId = setInterval(this._didAccelerateFunc, this._intervalInSeconds * 1000); - jsb.device.setAccelerometerInterval(this._intervalInSeconds); - jsb.device.setAccelerometerEnabled(true); - this._isEnabled = true; - } - public stop (): void { - if (this._intervalId) { - clearInterval(this._intervalId); - this._intervalId = undefined; - } - jsb.device.setAccelerometerEnabled(false); - this._isEnabled = false; - } - public setInterval (intervalInMileseconds: number): void { - this._intervalInSeconds = intervalInMileseconds / 1000; - jsb.device.setAccelerometerInterval(this._intervalInSeconds); - if (this._isEnabled) { - // restart accelerometer - jsb.device.setAccelerometerEnabled(false); - jsb.device.setAccelerometerEnabled(true); - } - } - public on (eventType: InputEventType, callback: AccelerometerCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } -} diff --git a/pal/input/native/gamepad-input.ts b/pal/input/native/gamepad-input.ts deleted file mode 100644 index 802a3a180d..0000000000 --- a/pal/input/native/gamepad-input.ts +++ /dev/null @@ -1,427 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -/* eslint-disable brace-style */ -import { systemInfo } from 'pal/system-info'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { Feature } from '../../system-info/enum-type'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { EventGamepad } from '../../../cocos/input/types'; -import { InputSourceButton, InputSourceDpad, InputSourceOrientation, InputSourcePosition, InputSourceStick } from '../input-source'; -import { Quat, Vec3, js } from '../../../cocos/core'; - -export type GamepadCallback = (res: EventGamepad) => void; - -enum Button { - BUTTON_SOUTH, - BUTTON_EAST, - BUTTON_WEST, - BUTTON_NORTH, - NS_MINUS, - NS_PLUS, - BUTTON_L1, - BUTTON_L2, - BUTTON_L3, - BUTTON_R1, - BUTTON_R2, - BUTTON_R3, - DPAD_UP, - DPAD_DOWN, - DPAD_LEFT, - DPAD_RIGHT, - LEFT_STICK_UP, - LEFT_STICK_DOWN, - LEFT_STICK_LEFT, - LEFT_STICK_RIGHT, - RIGHT_STICK_UP, - RIGHT_STICK_DOWN, - RIGHT_STICK_LEFT, - RIGHT_STICK_RIGHT, - ROKID_MENU, - ROKID_START, -} - -type NativeButtonState = Record - -const _nativeButtonMap = { - 1: Button.BUTTON_EAST, - 2: Button.BUTTON_SOUTH, - 3: Button.BUTTON_NORTH, - 4: Button.BUTTON_WEST, - 5: Button.BUTTON_L1, - 6: Button.BUTTON_R1, - 7: Button.NS_MINUS, - 8: Button.NS_PLUS, - 9: Button.BUTTON_L3, - 10: Button.BUTTON_R3, - 11: Button.ROKID_MENU, - 12: Button.ROKID_START, -}; - -interface IAxisValue { - negative: number; - positive: number; -} - -export class GamepadInputDevice { - public static all: GamepadInputDevice[] = []; - public static xr: (GamepadInputDevice | null) = null; - - public get buttonNorth (): InputSourceButton { return this._buttonNorth; } - public get buttonEast (): InputSourceButton { return this._buttonEast; } - public get buttonWest (): InputSourceButton { return this._buttonWest; } - public get buttonSouth (): InputSourceButton { return this._buttonSouth; } - public get buttonL1 (): InputSourceButton { return this._buttonL1; } - public get buttonL2 (): InputSourceButton { return this._buttonL2; } - public get buttonL3 (): InputSourceButton { return this._buttonL3; } - public get buttonR1 (): InputSourceButton { return this._buttonR1; } - public get buttonR2 (): InputSourceButton { return this._buttonR2; } - public get buttonR3 (): InputSourceButton { return this._buttonR3; } - // public get buttonTouchPad () { return this._buttonTouchPad; } - // public get buttonHome () { return this._buttonHome; } - public get buttonShare (): InputSourceButton { return this._buttonShare; } - public get buttonOptions (): InputSourceButton { return this._buttonOptions; } - public get dpad (): InputSourceDpad { return this._dpad; } - public get leftStick (): InputSourceStick { return this._leftStick; } - public get rightStick (): InputSourceStick { return this._rightStick; } - public get buttonStart (): InputSourceButton { return this._buttonStart; } - public get gripLeft (): InputSourceButton { return this._gripLeft; } - public get gripRight (): InputSourceButton { return this._gripRight; } - public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; } - public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; } - public get handRightPosition (): InputSourcePosition { return this._handRightPosition; } - public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; } - public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; } - public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; } - public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; } - public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; } - - public get deviceId (): number { - return this._deviceId; - } - public get connected (): boolean { - return this._connected; - } - - private static _eventTarget: EventTarget = new EventTarget(); - - private declare _buttonNorth: InputSourceButton; - private declare _buttonEast: InputSourceButton; - private declare _buttonWest: InputSourceButton; - private declare _buttonSouth: InputSourceButton; - private declare _buttonL1: InputSourceButton; - private declare _buttonL2: InputSourceButton; - private declare _buttonL3: InputSourceButton; - private declare _buttonR1: InputSourceButton; - private declare _buttonR2: InputSourceButton; - private declare _buttonR3: InputSourceButton; - // private declare buttonTouchPad: InputSourceButton; - // private declare buttonHome: InputSourceButton; - private declare _buttonShare: InputSourceButton; - private declare _buttonOptions: InputSourceButton; - private declare _dpad: InputSourceDpad; - private declare _leftStick: InputSourceStick; - private declare _rightStick: InputSourceStick; - private declare _buttonStart: InputSourceButton; - private declare _gripLeft: InputSourceButton; - private declare _gripRight: InputSourceButton; - private declare _handLeftPosition: InputSourcePosition; - private declare _handLeftOrientation: InputSourceOrientation; - private declare _handRightPosition: InputSourcePosition; - private declare _handRightOrientation: InputSourceOrientation; - private declare _aimLeftPosition: InputSourcePosition; - private declare _aimLeftOrientation: InputSourceOrientation; - private declare _aimRightPosition: InputSourcePosition; - private declare _aimRightOrientation: InputSourceOrientation; - - private _deviceId = -1; - private _connected = false; - private _nativeButtonState: NativeButtonState = { - [Button.BUTTON_SOUTH]: 0, - [Button.BUTTON_EAST]: 0, - [Button.BUTTON_WEST]: 0, - [Button.BUTTON_NORTH]: 0, - [Button.NS_MINUS]: 0, - [Button.NS_PLUS]: 0, - [Button.BUTTON_L1]: 0, - [Button.BUTTON_L2]: 0, - [Button.BUTTON_L3]: 0, - [Button.BUTTON_R1]: 0, - [Button.BUTTON_R2]: 0, - [Button.BUTTON_R3]: 0, - [Button.DPAD_UP]: 0, - [Button.DPAD_DOWN]: 0, - [Button.DPAD_LEFT]: 0, - [Button.DPAD_RIGHT]: 0, - [Button.LEFT_STICK_UP]: 0, - [Button.LEFT_STICK_DOWN]: 0, - [Button.LEFT_STICK_LEFT]: 0, - [Button.LEFT_STICK_RIGHT]: 0, - [Button.RIGHT_STICK_UP]: 0, - [Button.RIGHT_STICK_DOWN]: 0, - [Button.RIGHT_STICK_LEFT]: 0, - [Button.RIGHT_STICK_RIGHT]: 0, - [Button.ROKID_MENU]: 0, - [Button.ROKID_START]: 0, - }; - - constructor (deviceId: number) { - this._deviceId = deviceId; - this._initInputSource(); - } - - /** - * @engineInternal - */ - public static _init (): void { - if (!systemInfo.hasFeature(Feature.EVENT_GAMEPAD)) { - return; - } - GamepadInputDevice._registerEvent(); - } - - /** - * @engineInternal - */ - public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any): void { - GamepadInputDevice._eventTarget.on(eventType, cb, target); - } - - private static _removeInputDevice (id: number): void { - const removeIndex = GamepadInputDevice.all.findIndex((device) => device.deviceId === id); - if (removeIndex === -1) { - return; - } - js.array.fastRemoveAt(GamepadInputDevice.all, removeIndex); - } - private static _getInputDevice (id: number): GamepadInputDevice | undefined { - return GamepadInputDevice.all.find((device) => device.deviceId === id); - } - private static _createInputDevice (id: number, connected: boolean): GamepadInputDevice { - const device = new GamepadInputDevice(id); - device._connected = connected; - GamepadInputDevice.all.push(device); - return device; - } - private static _getOrCreateInputDevice (id: number, connected: boolean): GamepadInputDevice { - let device = GamepadInputDevice._getInputDevice(id); - if (!device) { - device = GamepadInputDevice._createInputDevice(id, connected); - } - device._connected = connected; - return device; - } - - private static _registerEvent (): void { - jsb.onControllerInput = (infoList: jsb.ControllerInfo[]): void => { - for (let i = 0; i < infoList.length; ++i) { - const info = infoList[i]; - const device = GamepadInputDevice._getOrCreateInputDevice(info.id, true); - device._updateNativeButtonState(info); - GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_INPUT, new EventGamepad(InputEventType.GAMEPAD_INPUT, device)); - } - }; - - jsb.onControllerChange = (controllerIds): void => { - // check connecting - for (let i = 0; i < controllerIds.length; ++i) { - const id = controllerIds[i]; - let device = GamepadInputDevice._getInputDevice(id); - if (!device) { - device = GamepadInputDevice._createInputDevice(id, true); - GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device)); - } - } - // check disconnecting - const allDevices = GamepadInputDevice.all; - for (let i = 0; i < allDevices.length; ++i) { - const device = allDevices[i]; - if (!controllerIds.includes(device.deviceId)) { - GamepadInputDevice._removeInputDevice(device.deviceId); - device._connected = false; - GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device)); - } - } - }; - } - - private _axisToButtons (axisValue: number): IAxisValue { - const value = Math.abs(axisValue); - if (axisValue > 0) { - return { negative: 0, positive: value }; - } else if (axisValue < 0) { - return { negative: value, positive: 0 }; - } else { - return { negative: 0, positive: 0 }; - } - } - - private _updateNativeButtonState (info: jsb.ControllerInfo): void { - const { buttonInfoList, axisInfoList } = info; - for (let i = 0; i < buttonInfoList.length; ++i) { - const buttonInfo = buttonInfoList[i]; - const button = _nativeButtonMap[buttonInfo.code]; - this._nativeButtonState[button] = buttonInfo.isPressed ? 1 : 0; - } - for (let i = 0; i < axisInfoList.length; ++i) { - const axisInfo = axisInfoList[i]; - const { code, value } = axisInfo; - let negativeButton: Button | undefined; - let positiveButton: Button | undefined; - let axisValue: IAxisValue | undefined; - switch (code) { - case 1: - negativeButton = Button.DPAD_LEFT; - positiveButton = Button.DPAD_RIGHT; - axisValue = this._axisToButtons(value); - break; - case 2: - negativeButton = Button.DPAD_DOWN; - positiveButton = Button.DPAD_UP; - axisValue = this._axisToButtons(value); - break; - case 3: - negativeButton = Button.LEFT_STICK_LEFT; - positiveButton = Button.LEFT_STICK_RIGHT; - axisValue = this._axisToButtons(value); - break; - case 4: - negativeButton = Button.LEFT_STICK_DOWN; - positiveButton = Button.LEFT_STICK_UP; - axisValue = this._axisToButtons(value); - break; - case 5: - negativeButton = Button.RIGHT_STICK_LEFT; - positiveButton = Button.RIGHT_STICK_RIGHT; - axisValue = this._axisToButtons(value); - break; - case 6: - negativeButton = Button.RIGHT_STICK_DOWN; - positiveButton = Button.RIGHT_STICK_UP; - axisValue = this._axisToButtons(value); - break; - default: - if (code === 7) { this._nativeButtonState[Button.BUTTON_L2] = value; } - else if (code === 8) { this._nativeButtonState[Button.BUTTON_R2] = value; } - break; - } - if (negativeButton && positiveButton && axisValue) { - this._nativeButtonState[negativeButton] = axisValue.negative; - this._nativeButtonState[positiveButton] = axisValue.positive; - } - } - } - - private _initInputSource (): void { - this._buttonNorth = new InputSourceButton(); - this._buttonNorth.getValue = (): number => this._nativeButtonState[Button.BUTTON_NORTH]; - this._buttonEast = new InputSourceButton(); - this._buttonEast.getValue = (): number => this._nativeButtonState[Button.BUTTON_EAST]; - this._buttonWest = new InputSourceButton(); - this._buttonWest.getValue = (): number => this._nativeButtonState[Button.BUTTON_WEST]; - this._buttonSouth = new InputSourceButton(); - this._buttonSouth.getValue = (): number => this._nativeButtonState[Button.BUTTON_SOUTH]; - - this._buttonL1 = new InputSourceButton(); - this._buttonL1.getValue = (): number => this._nativeButtonState[Button.BUTTON_L1]; - this._buttonL2 = new InputSourceButton(); - this._buttonL2.getValue = (): number => this._nativeButtonState[Button.BUTTON_L2]; - this._buttonL3 = new InputSourceButton(); - this._buttonL3.getValue = (): number => this._nativeButtonState[Button.BUTTON_L3]; - this._buttonR1 = new InputSourceButton(); - this._buttonR1.getValue = (): number => this._nativeButtonState[Button.BUTTON_R1]; - this._buttonR2 = new InputSourceButton(); - this._buttonR2.getValue = (): number => this._nativeButtonState[Button.BUTTON_R2]; - this._buttonR3 = new InputSourceButton(); - this._buttonR3.getValue = (): number => this._nativeButtonState[Button.BUTTON_R3]; - - // this._buttonTouchPad = new InputSourceButton(); - // this._buttonTouchPad.getValue = () => 0; // TODO: NX unavailable - // this._buttonHome = new InputSourceButton(); - // this._buttonHome.getValue = () => 0; // TODO: NX unavailable - - this._buttonShare = new InputSourceButton(); - this._buttonShare.getValue = (): number => this._nativeButtonState[Button.NS_MINUS]; // TODO: NX only for now - this._buttonOptions = new InputSourceButton(); - this._buttonOptions.getValue = (): number => this._nativeButtonState[Button.NS_PLUS] || this._nativeButtonState[Button.ROKID_MENU]; - - const dpadUp = new InputSourceButton(); - dpadUp.getValue = (): number => this._nativeButtonState[Button.DPAD_UP]; - const dpadDown = new InputSourceButton(); - dpadDown.getValue = (): number => this._nativeButtonState[Button.DPAD_DOWN]; - const dpadLeft = new InputSourceButton(); - dpadLeft.getValue = (): number => this._nativeButtonState[Button.DPAD_LEFT]; - const dpadRight = new InputSourceButton(); - dpadRight.getValue = (): number => this._nativeButtonState[Button.DPAD_RIGHT]; - this._dpad = new InputSourceDpad({ up: dpadUp, down: dpadDown, left: dpadLeft, right: dpadRight }); - - const leftStickUp = new InputSourceButton(); - leftStickUp.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_UP]; - const leftStickDown = new InputSourceButton(); - leftStickDown.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_DOWN]; - const leftStickLeft = new InputSourceButton(); - leftStickLeft.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_LEFT]; - const leftStickRight = new InputSourceButton(); - leftStickRight.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_RIGHT]; - this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); - - const rightStickUp = new InputSourceButton(); - rightStickUp.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_UP]; - const rightStickDown = new InputSourceButton(); - rightStickDown.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_DOWN]; - const rightStickLeft = new InputSourceButton(); - rightStickLeft.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_LEFT]; - const rightStickRight = new InputSourceButton(); - rightStickRight.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_RIGHT]; - this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); - - this._buttonStart = new InputSourceButton(); - this._buttonStart.getValue = (): number => this._nativeButtonState[Button.ROKID_START]; // TODO: Rokid only for now - - this._gripLeft = new InputSourceButton(); - this._gripLeft.getValue = (): number => 0; - this._gripRight = new InputSourceButton(); - this._gripRight.getValue = (): number => 0; - - this._handLeftPosition = new InputSourcePosition(); - this._handLeftPosition.getValue = (): Readonly => Vec3.ZERO; - this._handLeftOrientation = new InputSourceOrientation(); - this._handLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; - - this._handRightPosition = new InputSourcePosition(); - this._handRightPosition.getValue = (): Readonly => Vec3.ZERO; - this._handRightOrientation = new InputSourceOrientation(); - this._handRightOrientation.getValue = (): Readonly => Quat.IDENTITY; - - this._aimLeftPosition = new InputSourcePosition(); - this._aimLeftPosition.getValue = (): Readonly => Vec3.ZERO; - this._aimLeftOrientation = new InputSourceOrientation(); - this._aimLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; - - this._aimRightPosition = new InputSourcePosition(); - this._aimRightPosition.getValue = (): Readonly => Vec3.ZERO; - this._aimRightOrientation = new InputSourceOrientation(); - this._aimRightOrientation.getValue = (): Readonly => Quat.IDENTITY; - } -} diff --git a/pal/input/native/handheld-input.ts b/pal/input/native/handheld-input.ts deleted file mode 100644 index 1132cfebdf..0000000000 --- a/pal/input/native/handheld-input.ts +++ /dev/null @@ -1,97 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated 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 { InputEventType } from '../../../cocos/input/types/event-enum'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { EventHandheld } from '../../../cocos/input/types'; -import { InputSourcePosition, InputSourceOrientation } from '../input-source'; -import { Vec3, Quat } from '../../../cocos/core/math'; - -export type HandheldCallback = (res: EventHandheld) => void; - -enum Pose { - AR_MOBILE, -} - -interface IPoseValue { - position: Vec3; - orientation: Quat; -} - -type NativePoseState = Record - -export class HandheldInputDevice { - public get handheldPosition (): InputSourcePosition { return this._handheldPosition; } - public get handheldOrientation (): InputSourceOrientation { return this._handheldOrientation; } - - private _eventTarget: EventTarget = new EventTarget(); - - private declare _handheldPosition: InputSourcePosition; - private declare _handheldOrientation: InputSourceOrientation; - - private _nativePoseState: NativePoseState = { - [Pose.AR_MOBILE]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, - }; - - constructor () { - this._initInputSource(); - this._registerEvent(); - } - - private _registerEvent (): void { - jsb.onHandheldPoseInput = (infoList: jsb.PoseInfo[]): void => { - for (let i = 0; i < infoList.length; ++i) { - const info = infoList[i]; - this._updateNativePoseState(info); - } - - this._eventTarget.emit(InputEventType.HANDHELD_POSE_INPUT, new EventHandheld(InputEventType.HANDHELD_POSE_INPUT, this)); - }; - } - - /** - * @engineInternal - */ - public _on (eventType: InputEventType, callback: HandheldCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - - private _updateNativePoseState (info: jsb.PoseInfo): void { - switch (info.code) { - case 7: - this._nativePoseState[Pose.AR_MOBILE] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; - break; - default: - break; - } - } - - private _initInputSource (): void { - this._handheldPosition = new InputSourcePosition(); - this._handheldPosition.getValue = (): Vec3 => this._nativePoseState[Pose.AR_MOBILE].position; - - this._handheldOrientation = new InputSourceOrientation(); - this._handheldOrientation.getValue = (): Quat => this._nativePoseState[Pose.AR_MOBILE].orientation; - } -} diff --git a/pal/input/native/handle-input.ts b/pal/input/native/handle-input.ts deleted file mode 100644 index b1ccc019fa..0000000000 --- a/pal/input/native/handle-input.ts +++ /dev/null @@ -1,478 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { EventHandle } from '../../../cocos/input/types'; -import { InputSourceButton, InputSourceStick, InputSourcePosition, InputSourceOrientation, InputSourceTouch } from '../input-source'; -import { Vec3, Quat } from '../../../cocos/core/math'; - -export type HandleCallback = (res: EventHandle) => void; - -enum Button { - BUTTON_EAST, - BUTTON_SOUTH, - BUTTON_WEST, - BUTTON_NORTH, - BUTTON_TRIGGER_LEFT, - BUTTON_TRIGGER_RIGHT, - TRIGGER_LEFT, - TRIGGER_RIGHT, - GRIP_LEFT, - GRIP_RIGHT, - BUTTON_LEFT_STICK, - LEFT_STICK_UP, - LEFT_STICK_DOWN, - LEFT_STICK_LEFT, - LEFT_STICK_RIGHT, - BUTTON_RIGHT_STICK, - RIGHT_STICK_UP, - RIGHT_STICK_DOWN, - RIGHT_STICK_LEFT, - RIGHT_STICK_RIGHT, - ROKID_MENU, - ROKID_START, -} - -enum Pose { - HAND_LEFT, - HAND_RIGHT, - AIM_LEFT, - AIM_RIGHT, -} - -enum StickKeyCode { - UNDEFINE = 0, - A, - B, - X, - Y, - L1, - R1, - MINUS, - PLUS, - L3, - R3, - MENU, - START, - TRIGGER_LEFT, - TRIGGER_RIGHT, -} - -enum StickAxisCode { - UNDEFINE = 0, - X, - Y, - LEFT_STICK_X, - LEFT_STICK_Y, - RIGHT_STICK_X, - RIGHT_STICK_Y, - L2, - R2, - LEFT_GRIP, - RIGHT_GRIP, -} - -enum StickTouchCode { - UNDEFINE = 0, - A, - B, - X, - Y, - LEFT_TRIGGER, - RIGHT_TRIGGER, - LEFT_THUMBSTICK, - RIGHT_THUMBSTICK, -} - -interface IPoseValue { - position: Vec3; - orientation: Quat; -} - -type NativeButtonState = Record -type NativeTouchState = Record -type NativePoseState = Record - -const _nativeButtonMap = { - 1: Button.BUTTON_EAST, - 2: Button.BUTTON_SOUTH, - 3: Button.BUTTON_NORTH, - 4: Button.BUTTON_WEST, - 9: Button.BUTTON_LEFT_STICK, - 10: Button.BUTTON_RIGHT_STICK, - 11: Button.ROKID_MENU, - 12: Button.ROKID_START, - 13: Button.BUTTON_TRIGGER_LEFT, - 14: Button.BUTTON_TRIGGER_RIGHT, -}; - -interface IAxisValue { - negative: number; - positive: number; -} - -export class HandleInputDevice { - public get buttonNorth (): InputSourceButton { return this._buttonNorth; } - public get buttonEast (): InputSourceButton { return this._buttonEast; } - public get buttonWest (): InputSourceButton { return this._buttonWest; } - public get buttonSouth (): InputSourceButton { return this._buttonSouth; } - public get buttonTriggerLeft (): InputSourceButton { return this._buttonTriggerLeft; } - public get buttonTriggerRight (): InputSourceButton { return this._buttonTriggerRight; } - public get triggerLeft (): InputSourceButton { return this._triggerLeft; } - public get triggerRight (): InputSourceButton { return this._triggerRight; } - public get gripLeft (): InputSourceButton { return this._gripLeft; } - public get gripRight (): InputSourceButton { return this._gripRight; } - public get leftStick (): InputSourceStick { return this._leftStick; } - public get rightStick (): InputSourceStick { return this._rightStick; } - public get buttonLeftStick (): InputSourceButton { return this._buttonLeftStick; } - public get buttonRightStick (): InputSourceButton { return this._buttonRightStick; } - public get buttonOptions (): InputSourceButton { return this._buttonOptions; } - public get buttonStart (): InputSourceButton { return this._buttonStart; } - public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; } - public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; } - public get handRightPosition (): InputSourcePosition { return this._handRightPosition; } - public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; } - public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; } - public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; } - public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; } - public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; } - public get touchButtonA (): InputSourceTouch { return this._touchButtonA; } - public get touchButtonB (): InputSourceTouch { return this._touchButtonB; } - public get touchButtonX (): InputSourceTouch { return this._touchButtonX; } - public get touchButtonY (): InputSourceTouch { return this._touchButtonY; } - public get touchButtonTriggerLeft (): InputSourceTouch { return this._touchButtonTriggerLeft; } - public get touchButtonTriggerRight (): InputSourceTouch { return this._touchButtonTriggerRight; } - public get touchButtonThumbStickLeft (): InputSourceTouch { return this._touchButtonThumbStickLeft; } - public get touchButtonThumbStickRight (): InputSourceTouch { return this._touchButtonThumbStickRight; } - - private _eventTarget: EventTarget = new EventTarget(); - - private declare _buttonNorth: InputSourceButton; - private declare _buttonEast: InputSourceButton; - private declare _buttonWest: InputSourceButton; - private declare _buttonSouth: InputSourceButton; - private declare _buttonTriggerLeft: InputSourceButton; - private declare _buttonTriggerRight: InputSourceButton; - private declare _triggerLeft: InputSourceButton; - private declare _triggerRight: InputSourceButton; - private declare _gripLeft: InputSourceButton; - private declare _gripRight: InputSourceButton; - private declare _leftStick: InputSourceStick; - private declare _rightStick: InputSourceStick; - private declare _buttonLeftStick: InputSourceButton; - private declare _buttonRightStick: InputSourceButton; - private declare _buttonOptions: InputSourceButton; - private declare _buttonStart: InputSourceButton; - private declare _handLeftPosition: InputSourcePosition; - private declare _handLeftOrientation: InputSourceOrientation; - private declare _handRightPosition: InputSourcePosition; - private declare _handRightOrientation: InputSourceOrientation; - private declare _aimLeftPosition: InputSourcePosition; - private declare _aimLeftOrientation: InputSourceOrientation; - private declare _aimRightPosition: InputSourcePosition; - private declare _aimRightOrientation: InputSourceOrientation; - private declare _touchButtonA: InputSourceTouch; - private declare _touchButtonB: InputSourceTouch; - private declare _touchButtonX: InputSourceTouch; - private declare _touchButtonY: InputSourceTouch; - private declare _touchButtonTriggerLeft: InputSourceTouch; - private declare _touchButtonTriggerRight: InputSourceTouch; - private declare _touchButtonThumbStickLeft: InputSourceTouch; - private declare _touchButtonThumbStickRight: InputSourceTouch; - - private _nativeButtonState: NativeButtonState = { - [Button.BUTTON_SOUTH]: 0, - [Button.BUTTON_EAST]: 0, - [Button.BUTTON_WEST]: 0, - [Button.BUTTON_NORTH]: 0, - [Button.BUTTON_TRIGGER_LEFT]: 0, - [Button.BUTTON_TRIGGER_RIGHT]: 0, - [Button.TRIGGER_LEFT]: 0, - [Button.TRIGGER_RIGHT]: 0, - [Button.GRIP_LEFT]: 0, - [Button.GRIP_RIGHT]: 0, - [Button.LEFT_STICK_UP]: 0, - [Button.LEFT_STICK_DOWN]: 0, - [Button.LEFT_STICK_LEFT]: 0, - [Button.LEFT_STICK_RIGHT]: 0, - [Button.RIGHT_STICK_UP]: 0, - [Button.RIGHT_STICK_DOWN]: 0, - [Button.RIGHT_STICK_LEFT]: 0, - [Button.RIGHT_STICK_RIGHT]: 0, - [Button.BUTTON_LEFT_STICK]: 0, - [Button.BUTTON_RIGHT_STICK]: 0, - [Button.ROKID_MENU]: 0, - [Button.ROKID_START]: 0, - }; - - private _nativeTouchState: NativeTouchState = { - [StickTouchCode.UNDEFINE]: 0, - [StickTouchCode.A]: 0, - [StickTouchCode.B]: 0, - [StickTouchCode.X]: 0, - [StickTouchCode.Y]: 0, - [StickTouchCode.LEFT_TRIGGER]: 0, - [StickTouchCode.RIGHT_TRIGGER]: 0, - [StickTouchCode.LEFT_THUMBSTICK]: 0, - [StickTouchCode.RIGHT_THUMBSTICK]: 0, - }; - - private _nativePoseState: NativePoseState = { - [Pose.HAND_LEFT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, - [Pose.HAND_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, - [Pose.AIM_LEFT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, - [Pose.AIM_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, - }; - - constructor () { - this._initInputSource(); - this._registerEvent(); - } - - private _registerEvent (): void { - jsb.onHandleInput = (infoList: jsb.ControllerInfo[]): void => { - for (let i = 0; i < infoList.length; ++i) { - const info = infoList[i]; - this._updateNativeButtonState(info); - this._eventTarget.emit(InputEventType.HANDLE_INPUT, new EventHandle(InputEventType.HANDLE_INPUT, this)); - } - }; - - jsb.onHandlePoseInput = (infoList: jsb.PoseInfo[]): void => { - for (let i = 0; i < infoList.length; ++i) { - const info = infoList[i]; - this._updateNativePoseState(info); - } - this._eventTarget.emit(InputEventType.HANDLE_POSE_INPUT, new EventHandle(InputEventType.HANDLE_POSE_INPUT, this)); - }; - } - - /** - * @engineInternal - */ - public _on (eventType: InputEventType, callback: HandleCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - - private _axisToButtons (axisValue: number): IAxisValue { - const value = Math.abs(axisValue); - if (axisValue > 0) { - return { negative: 0, positive: value }; - } else if (axisValue < 0) { - return { negative: value, positive: 0 }; - } else { - return { negative: 0, positive: 0 }; - } - } - - private _updateNativeButtonState (info: jsb.ControllerInfo): void { - const { buttonInfoList, axisInfoList, touchInfoList } = info; - for (let i = 0; i < buttonInfoList.length; ++i) { - const buttonInfo = buttonInfoList[i]; - const button = _nativeButtonMap[buttonInfo.code]; - this._nativeButtonState[button] = buttonInfo.isPressed ? 1 : 0; - } - for (let i = 0; i < axisInfoList.length; ++i) { - const axisInfo = axisInfoList[i]; - const { code, value } = axisInfo; - let negativeButton: Button | undefined; - let positiveButton: Button | undefined; - let axisValue: IAxisValue | undefined; - switch (code) { - case StickAxisCode.LEFT_STICK_X: - negativeButton = Button.LEFT_STICK_LEFT; - positiveButton = Button.LEFT_STICK_RIGHT; - axisValue = this._axisToButtons(value); - break; - case StickAxisCode.LEFT_STICK_Y: - negativeButton = Button.LEFT_STICK_DOWN; - positiveButton = Button.LEFT_STICK_UP; - axisValue = this._axisToButtons(value); - break; - case StickAxisCode.RIGHT_STICK_X: - negativeButton = Button.RIGHT_STICK_LEFT; - positiveButton = Button.RIGHT_STICK_RIGHT; - axisValue = this._axisToButtons(value); - break; - case StickAxisCode.RIGHT_STICK_Y: - negativeButton = Button.RIGHT_STICK_DOWN; - positiveButton = Button.RIGHT_STICK_UP; - axisValue = this._axisToButtons(value); - break; - case StickAxisCode.L2: - this._nativeButtonState[Button.TRIGGER_LEFT] = value; - break; - case StickAxisCode.R2: - this._nativeButtonState[Button.TRIGGER_RIGHT] = value; - break; - case StickAxisCode.LEFT_GRIP: - this._nativeButtonState[Button.GRIP_LEFT] = value; - break; - case StickAxisCode.RIGHT_GRIP: - this._nativeButtonState[Button.GRIP_RIGHT] = value; - break; - default: - break; - } - if (negativeButton && positiveButton && axisValue) { - this._nativeButtonState[negativeButton] = axisValue.negative; - this._nativeButtonState[positiveButton] = axisValue.positive; - } - } - - if (touchInfoList) { - for (let i = 0; i < touchInfoList.length; ++i) { - const touchInfo = touchInfoList[i]; - const { code, value } = touchInfo; - switch (code) { - case StickTouchCode.A: - case StickTouchCode.B: - case StickTouchCode.X: - case StickTouchCode.Y: - case StickTouchCode.LEFT_TRIGGER: - case StickTouchCode.RIGHT_TRIGGER: - case StickTouchCode.LEFT_THUMBSTICK: - case StickTouchCode.RIGHT_THUMBSTICK: - this._nativeTouchState[code] = value; - break; - default: - break; - } - } - } - } - - private _updateNativePoseState (info: jsb.PoseInfo): void { - switch (info.code) { - case 1: - this._nativePoseState[Pose.HAND_LEFT] = { position: new Vec3(info.x, info.y, info.z), - orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; - break; - case 2: - this._nativePoseState[Pose.AIM_LEFT] = { position: new Vec3(info.x, info.y, info.z), - orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; - break; - case 4: - this._nativePoseState[Pose.HAND_RIGHT] = { position: new Vec3(info.x, info.y, info.z), - orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; - break; - case 5: - this._nativePoseState[Pose.AIM_RIGHT] = { position: new Vec3(info.x, info.y, info.z), - orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; - break; - default: - break; - } - } - - private _initInputSource (): void { - this._buttonNorth = new InputSourceButton(); - this._buttonNorth.getValue = (): number => this._nativeButtonState[Button.BUTTON_NORTH]; - this._buttonEast = new InputSourceButton(); - this._buttonEast.getValue = (): number => this._nativeButtonState[Button.BUTTON_EAST]; - this._buttonWest = new InputSourceButton(); - this._buttonWest.getValue = (): number => this._nativeButtonState[Button.BUTTON_WEST]; - this._buttonSouth = new InputSourceButton(); - this._buttonSouth.getValue = (): number => this._nativeButtonState[Button.BUTTON_SOUTH]; - - this._buttonTriggerLeft = new InputSourceButton(); - this._buttonTriggerLeft.getValue = (): number => this._nativeButtonState[Button.BUTTON_TRIGGER_LEFT]; - this._buttonTriggerRight = new InputSourceButton(); - this._buttonTriggerRight.getValue = (): number => this._nativeButtonState[Button.BUTTON_TRIGGER_RIGHT]; - this._triggerLeft = new InputSourceButton(); - this._triggerLeft.getValue = (): number => this._nativeButtonState[Button.TRIGGER_LEFT]; - this._triggerRight = new InputSourceButton(); - this._triggerRight.getValue = (): number => this._nativeButtonState[Button.TRIGGER_RIGHT]; - this._gripLeft = new InputSourceButton(); - this._gripLeft.getValue = (): number => this._nativeButtonState[Button.GRIP_LEFT]; - this._gripRight = new InputSourceButton(); - this._gripRight.getValue = (): number => this._nativeButtonState[Button.GRIP_RIGHT]; - - this._buttonLeftStick = new InputSourceButton(); - this._buttonLeftStick.getValue = (): number => this._nativeButtonState[Button.BUTTON_LEFT_STICK]; - const leftStickUp = new InputSourceButton(); - leftStickUp.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_UP]; - const leftStickDown = new InputSourceButton(); - leftStickDown.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_DOWN]; - const leftStickLeft = new InputSourceButton(); - leftStickLeft.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_LEFT]; - const leftStickRight = new InputSourceButton(); - leftStickRight.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_RIGHT]; - this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); - - this._buttonRightStick = new InputSourceButton(); - this._buttonRightStick.getValue = (): number => this._nativeButtonState[Button.BUTTON_RIGHT_STICK]; - const rightStickUp = new InputSourceButton(); - rightStickUp.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_UP]; - const rightStickDown = new InputSourceButton(); - rightStickDown.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_DOWN]; - const rightStickLeft = new InputSourceButton(); - rightStickLeft.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_LEFT]; - const rightStickRight = new InputSourceButton(); - rightStickRight.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_RIGHT]; - this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); - - this._buttonOptions = new InputSourceButton(); - this._buttonOptions.getValue = (): number => this._nativeButtonState[Button.ROKID_MENU]; - this._buttonStart = new InputSourceButton(); - this._buttonStart.getValue = (): number => this._nativeButtonState[Button.ROKID_START]; - - this._handLeftPosition = new InputSourcePosition(); - this._handLeftPosition.getValue = (): Vec3 => this._nativePoseState[Pose.HAND_LEFT].position; - this._handLeftOrientation = new InputSourceOrientation(); - this._handLeftOrientation.getValue = (): Quat => this._nativePoseState[Pose.HAND_LEFT].orientation; - - this._handRightPosition = new InputSourcePosition(); - this._handRightPosition.getValue = (): Vec3 => this._nativePoseState[Pose.HAND_RIGHT].position; - this._handRightOrientation = new InputSourceOrientation(); - this._handRightOrientation.getValue = (): Quat => this._nativePoseState[Pose.HAND_RIGHT].orientation; - - this._aimLeftPosition = new InputSourcePosition(); - this._aimLeftPosition.getValue = (): Vec3 => this._nativePoseState[Pose.AIM_LEFT].position; - this._aimLeftOrientation = new InputSourceOrientation(); - this._aimLeftOrientation.getValue = (): Quat => this._nativePoseState[Pose.AIM_LEFT].orientation; - - this._aimRightPosition = new InputSourcePosition(); - this._aimRightPosition.getValue = (): Vec3 => this._nativePoseState[Pose.AIM_RIGHT].position; - this._aimRightOrientation = new InputSourceOrientation(); - this._aimRightOrientation.getValue = (): Quat => this._nativePoseState[Pose.AIM_RIGHT].orientation; - this._touchButtonA = new InputSourceTouch(); - this._touchButtonA.getValue = (): number => this._nativeTouchState[StickTouchCode.A]; - this._touchButtonB = new InputSourceTouch(); - this._touchButtonB.getValue = (): number => this._nativeTouchState[StickTouchCode.B]; - this._touchButtonX = new InputSourceTouch(); - this._touchButtonX.getValue = (): number => this._nativeTouchState[StickTouchCode.X]; - this._touchButtonY = new InputSourceTouch(); - this._touchButtonY.getValue = (): number => this._nativeTouchState[StickTouchCode.Y]; - this._touchButtonTriggerLeft = new InputSourceTouch(); - this._touchButtonTriggerLeft.getValue = (): number => this._nativeTouchState[StickTouchCode.LEFT_TRIGGER]; - this._touchButtonTriggerRight = new InputSourceTouch(); - this._touchButtonTriggerRight.getValue = (): number => this._nativeTouchState[StickTouchCode.RIGHT_TRIGGER]; - this._touchButtonThumbStickLeft = new InputSourceTouch(); - this._touchButtonThumbStickLeft.getValue = (): number => this._nativeTouchState[StickTouchCode.LEFT_THUMBSTICK]; - this._touchButtonThumbStickRight = new InputSourceTouch(); - this._touchButtonThumbStickRight.getValue = (): number => this._nativeTouchState[StickTouchCode.RIGHT_THUMBSTICK]; - } -} diff --git a/pal/input/native/hmd-input.ts b/pal/input/native/hmd-input.ts deleted file mode 100644 index 269b50d1d6..0000000000 --- a/pal/input/native/hmd-input.ts +++ /dev/null @@ -1,123 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { EventHMD } from '../../../cocos/input/types'; -import { InputSourcePosition, InputSourceOrientation } from '../input-source'; -import { Vec3, Quat } from '../../../cocos/core/math'; - -export type HMDCallback = (res: EventHMD) => void; - -enum Pose { - VIEW_LEFT, - VIEW_RIGHT, - HEAD_MIDDLE, -} - -interface IPoseValue { - position: Vec3; - orientation: Quat; -} - -type NativePoseState = Record - -export class HMDInputDevice { - public get viewLeftPosition (): InputSourcePosition { return this._viewLeftPosition; } - public get viewLeftOrientation (): InputSourceOrientation { return this._viewLeftOrientation; } - public get viewRightPosition (): InputSourcePosition { return this._viewRightPosition; } - public get viewRightOrientation (): InputSourceOrientation { return this._viewRightOrientation; } - public get headMiddlePosition (): InputSourcePosition { return this._headMiddlePosition; } - public get headMiddleOrientation (): InputSourceOrientation { return this._headMiddleOrientation; } - - private _eventTarget: EventTarget = new EventTarget(); - - private declare _viewLeftPosition: InputSourcePosition; - private declare _viewLeftOrientation: InputSourceOrientation; - private declare _viewRightPosition: InputSourcePosition; - private declare _viewRightOrientation: InputSourceOrientation; - private declare _headMiddlePosition: InputSourcePosition; - private declare _headMiddleOrientation: InputSourceOrientation; - - private _nativePoseState: NativePoseState = { - [Pose.VIEW_LEFT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, - [Pose.VIEW_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, - [Pose.HEAD_MIDDLE]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, - }; - - constructor () { - this._initInputSource(); - this._registerEvent(); - } - - private _registerEvent (): void { - jsb.onHMDPoseInput = (infoList: jsb.PoseInfo[]): void => { - for (let i = 0; i < infoList.length; ++i) { - const info = infoList[i]; - this._updateNativePoseState(info); - } - this._eventTarget.emit(InputEventType.HMD_POSE_INPUT, new EventHMD(InputEventType.HMD_POSE_INPUT, this)); - }; - } - - /** - * @engineInternal - */ - public _on (eventType: InputEventType, callback: HMDCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - - private _updateNativePoseState (info: jsb.PoseInfo): void { - switch (info.code) { - case 0: - this._nativePoseState[Pose.VIEW_LEFT] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; - break; - case 3: - this._nativePoseState[Pose.VIEW_RIGHT] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; - break; - case 6: - this._nativePoseState[Pose.HEAD_MIDDLE] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; - break; - default: - break; - } - } - - private _initInputSource (): void { - this._viewLeftPosition = new InputSourcePosition(); - this._viewLeftPosition.getValue = (): Vec3 => this._nativePoseState[Pose.VIEW_LEFT].position; - this._viewLeftOrientation = new InputSourceOrientation(); - this._viewLeftOrientation.getValue = (): Quat => this._nativePoseState[Pose.VIEW_LEFT].orientation; - - this._viewRightPosition = new InputSourcePosition(); - this._viewRightPosition.getValue = (): Vec3 => this._nativePoseState[Pose.VIEW_RIGHT].position; - this._viewRightOrientation = new InputSourceOrientation(); - this._viewRightOrientation.getValue = (): Quat => this._nativePoseState[Pose.VIEW_RIGHT].orientation; - - this._headMiddlePosition = new InputSourcePosition(); - this._headMiddlePosition.getValue = (): Vec3 => this._nativePoseState[Pose.HEAD_MIDDLE].position; - this._headMiddleOrientation = new InputSourceOrientation(); - this._headMiddleOrientation.getValue = (): Quat => this._nativePoseState[Pose.HEAD_MIDDLE].orientation; - } -} diff --git a/pal/input/native/index.ts b/pal/input/native/index.ts deleted file mode 100644 index a30638e368..0000000000 --- a/pal/input/native/index.ts +++ /dev/null @@ -1,36 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { checkPalIntegrity, withImpl } from '../../integrity-check'; - -export * from './accelerometer-input'; -export * from './gamepad-input'; -export * from './handle-input'; -export * from './hmd-input'; -export * from './handheld-input'; -export * from './keyboard-input'; -export * from './mouse-input'; -export * from './touch-input'; - -checkPalIntegrity(withImpl()); diff --git a/pal/input/native/keyboard-input.ts b/pal/input/native/keyboard-input.ts deleted file mode 100644 index c36375b7c6..0000000000 --- a/pal/input/native/keyboard-input.ts +++ /dev/null @@ -1,109 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { KeyCode, EventKeyboard } from '../../../cocos/input/types'; -import { EventTarget } from '../../../cocos/core/event'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { code2KeyCode } from '../keycodes'; - -export type KeyboardCallback = (res: EventKeyboard) => void; - -const nativeKeyCode2KeyCode: Record = { - 12: KeyCode.NUM_LOCK, - 10048: KeyCode.NUM_0, - 10049: KeyCode.NUM_1, - 10050: KeyCode.NUM_2, - 10051: KeyCode.NUM_3, - 10052: KeyCode.NUM_4, - 10053: KeyCode.NUM_5, - 10054: KeyCode.NUM_6, - 10055: KeyCode.NUM_7, - 10056: KeyCode.NUM_8, - 10057: KeyCode.NUM_9, - 20013: KeyCode.NUM_ENTER, - 20016: KeyCode.SHIFT_RIGHT, - 20017: KeyCode.CTRL_RIGHT, - 20018: KeyCode.ALT_RIGHT, -}; - -function getKeyCode (event: jsb.KeyboardEvent): KeyCode { - if (event.code) { - if (event.code in code2KeyCode) { - return code2KeyCode[event.code]; - } else { - console.error(`Can not find keyCode for code: ${event.code}`); - } - } - return nativeKeyCode2KeyCode[event.keyCode] || event.keyCode; -} - -export class KeyboardInputSource { - private _eventTarget: EventTarget = new EventTarget(); - - // On native platform, KeyboardEvent.repeat is always false, so we need a map to manage the key state. - private _keyStateMap: Record = {}; - - private _handleKeyboardDown: (event: jsb.KeyboardEvent) => void; - private _handleKeyboardUp: (event: jsb.KeyboardEvent) => void; - - constructor () { - this._handleKeyboardDown = (event: jsb.KeyboardEvent): void => { - const keyCode = getKeyCode(event); - if (!this._keyStateMap[keyCode]) { - const eventKeyDown = this._getInputEvent(event, InputEventType.KEY_DOWN); - this._eventTarget.emit(InputEventType.KEY_DOWN, eventKeyDown); - } else { - const eventKeyPressing = this._getInputEvent(event, InputEventType.KEY_PRESSING); - this._eventTarget.emit(InputEventType.KEY_PRESSING, eventKeyPressing); - } - this._keyStateMap[keyCode] = true; - }; - this._handleKeyboardUp = (event: jsb.KeyboardEvent): void => { - const keyCode = getKeyCode(event); - const eventKeyUp = this._getInputEvent(event, InputEventType.KEY_UP); - this._keyStateMap[keyCode] = false; - this._eventTarget.emit(InputEventType.KEY_UP, eventKeyUp); - }; - this._registerEvent(); - } - - public dispatchKeyboardDownEvent (nativeKeyboardEvent: jsb.KeyboardEvent): void { this._handleKeyboardDown(nativeKeyboardEvent); } - public dispatchKeyboardUpEvent (nativeKeyboardEvent: jsb.KeyboardEvent): void { this._handleKeyboardUp(nativeKeyboardEvent); } - - private _registerEvent (): void { - jsb.onKeyDown = this._handleKeyboardDown; - jsb.onKeyUp = this._handleKeyboardUp; - } - - private _getInputEvent (event: jsb.KeyboardEvent, eventType: InputEventType): EventKeyboard { - const keyCode = getKeyCode(event); - const eventKeyboard = new EventKeyboard(keyCode, eventType); - eventKeyboard.windowId = event.windowId; - return eventKeyboard; - } - - public on (eventType: InputEventType, callback: KeyboardCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } -} diff --git a/pal/input/native/mouse-input.ts b/pal/input/native/mouse-input.ts deleted file mode 100644 index 45e2bfde9c..0000000000 --- a/pal/input/native/mouse-input.ts +++ /dev/null @@ -1,238 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { screenAdapter } from 'pal/screen-adapter'; -import { systemInfo } from 'pal/system-info'; -import { EventMouse } from '../../../cocos/input/types'; -import { EventTarget } from '../../../cocos/core/event'; -import { Vec2 } from '../../../cocos/core/math'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { OS } from '../../system-info/enum-type'; - -export type MouseCallback = (res: EventMouse) => void; - -declare const jsb: any; - -class MouseEventElement { - type: InputEventType | null = null; - mouseEvent = { - x: 0, - y: 0, - xDelta: 0, - yDelta: 0, - button: 0, - windowId: 0, - wheelDeltaX: 0, - wheelDeltaY: 0, - }; -} - -class MouseEventCache { - private _events: MouseEventElement[] = []; - private _length = 0; - - push (eventType: InputEventType, mouseEvent?: any): void { - const events = this._events; - const index = this._length; - if (index >= events.length) { - events.push(new MouseEventElement()); - } - const e = events[index]; - e.type = eventType; - const cachedEvent = e.mouseEvent; - if (mouseEvent) { - Object.assign(cachedEvent, mouseEvent); - } else { - cachedEvent.x = cachedEvent.y = cachedEvent.xDelta = cachedEvent.yDelta = 0; - cachedEvent.button = cachedEvent.windowId = cachedEvent.wheelDeltaX = cachedEvent.wheelDeltaY = 0; - } - - ++this._length; - } - - clear (): void { - this._length = 0; - } - - forEach (cb: ((e: MouseEventElement) => void)): void { - for (let i = 0, len = this._length; i < len; ++i) { - cb(this._events[i]); - } - } -} - -export class MouseInputSource { - private _eventTarget: EventTarget = new EventTarget(); - private _preMousePos: Vec2 = new Vec2(); - private _isPressed = false; - private _windowManager: any; - private _pointLocked = false; - private _cache = new MouseEventCache(); - - private _handleMouseDown: (mouseEvent: jsb.MouseEvent) => void; - private _handleMouseMove: (mouseEvent: jsb.MouseEvent) => void; - private _handleMouseUp: (mouseEvent: jsb.MouseEvent) => void; - private _handleWindowLeave: () => void; - private _handleWindowEnter: () => void; - private _handleMouseWheel: (mouseEvent: jsb.MouseWheelEvent) => void; - - constructor () { - this._handleMouseDown = this._createEventCacheCallback(InputEventType.MOUSE_DOWN); - this._handleMouseMove = this._createEventCacheCallback(InputEventType.MOUSE_MOVE); - this._handleMouseUp = this._createEventCacheCallback(InputEventType.MOUSE_UP); - this._handleWindowLeave = this._createEventCacheCallback(InputEventType.MOUSE_LEAVE); - this._handleWindowEnter = this._createEventCacheCallback(InputEventType.MOUSE_ENTER); - this._handleMouseWheel = this._createEventCacheCallback(InputEventType.MOUSE_WHEEL); - this._registerEvent(); - this._windowManager = jsb.ISystemWindowManager.getInstance(); - } - - public dispatchMouseDownEvent (nativeMouseEvent: any): void { this._handleMouseDown(nativeMouseEvent as jsb.MouseEvent); } - public dispatchMouseMoveEvent (nativeMouseEvent: any): void { this._handleMouseMove(nativeMouseEvent as jsb.MouseEvent); } - public dispatchMouseUpEvent (nativeMouseEvent: any): void { this._handleMouseUp(nativeMouseEvent as jsb.MouseEvent); } - public dispatchScrollEvent (nativeMouseEvent: any): void { this._handleMouseWheel(nativeMouseEvent as jsb.MouseWheelEvent); } - - private _getLocation (event: jsb.MouseEvent): Vec2 { - const window = this._windowManager.getWindow(event.windowId); - const windowSize = window.getViewSize(); - const dpr = screenAdapter.devicePixelRatio; - const x = event.x * dpr; - const y = windowSize.height - event.y * dpr; - return new Vec2(x, y); - } - - private _registerEvent (): void { - jsb.onMouseDown = this._handleMouseDown; - jsb.onMouseMove = this._handleMouseMove; - jsb.onMouseUp = this._handleMouseUp; - jsb.onMouseWheel = this._handleMouseWheel; - jsb.onPointerlockChange = (value: boolean): void => { - this._pointLocked = value; - }; - - // Treat window leave/enter events as mouse events as web. - jsb.onWindowLeave = this._handleWindowLeave; - jsb.onWindowEnter = this._handleWindowEnter; - } - - private _createEventCacheCallback (eventType: InputEventType) { - return (mouseEvent?: jsb.MouseEvent | jsb.MouseWheelEvent): void => { - this._cache.push(eventType, mouseEvent); - }; - } - - public dispatchEventsInCache (): void { - const cache = this._cache; - - cache.forEach((e: MouseEventElement) => { - switch (e.type) { - case InputEventType.MOUSE_LEAVE: - this._dispatchWindowLeave(); - break; - case InputEventType.MOUSE_ENTER: - this._dispatchWindowEnter(); - break; - case InputEventType.MOUSE_WHEEL: - this._dispatchMouseWheel(e.mouseEvent as jsb.MouseWheelEvent); - break; - default: - this._dispatchEvent(e.type!, e.mouseEvent); - break; - } - }); - - cache.clear(); - } - - private _dispatchEvent (eventType: InputEventType, mouseEvent: jsb.MouseEvent): void { - const location = this._getLocation(mouseEvent); - let button = mouseEvent.button; - switch (eventType) { - case InputEventType.MOUSE_DOWN: - this._isPressed = true; - break; - case InputEventType.MOUSE_UP: - this._isPressed = false; - break; - case InputEventType.MOUSE_MOVE: - if (!this._isPressed) { - button = EventMouse.BUTTON_MISSING; - } - break; - default: - break; - } - - const eventMouse = new EventMouse(eventType, false, this._preMousePos, mouseEvent.windowId); - eventMouse.setLocation(location.x, location.y); - eventMouse.setButton(button); - const dpr = screenAdapter.devicePixelRatio; - eventMouse.movementX = typeof mouseEvent.xDelta === 'undefined' ? 0 : mouseEvent.xDelta * dpr; - eventMouse.movementY = typeof mouseEvent.yDelta === 'undefined' ? 0 : mouseEvent.yDelta * dpr; - // update previous mouse position. - this._preMousePos.set(location.x, location.y); - this._eventTarget.emit(eventType, eventMouse); - } - - private _dispatchMouseWheel (mouseEvent: jsb.MouseWheelEvent): void { - const eventType = InputEventType.MOUSE_WHEEL; - const location = this._getLocation(mouseEvent); - const button = mouseEvent.button; - - const eventMouse = new EventMouse(eventType, false, this._preMousePos, mouseEvent.windowId); - eventMouse.setLocation(location.x, location.y); - eventMouse.setButton(button); - eventMouse.movementX = location.x - this._preMousePos.x; - eventMouse.movementY = this._preMousePos.y - location.y; - - let matchStandardFactor = 0; - if (systemInfo.os === OS.OPENHARMONY) { - matchStandardFactor = 5; - eventMouse.setScrollData(mouseEvent.wheelDeltaX, mouseEvent.wheelDeltaY * matchStandardFactor); - } else { - matchStandardFactor = 120; - eventMouse.setScrollData(mouseEvent.wheelDeltaX * matchStandardFactor, mouseEvent.wheelDeltaY * matchStandardFactor); - } - // update previous mouse position. - this._preMousePos.set(location.x, location.y); - this._eventTarget.emit(eventType, eventMouse); - } - - public on (eventType: InputEventType, callback: MouseCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - - // Should include window id if supporting multiple windows. - private _dispatchWindowLeave (): void { - const eventType = InputEventType.MOUSE_LEAVE; - const eventMouse = new EventMouse(eventType, false); - this._eventTarget.emit(eventType, eventMouse); - } - - private _dispatchWindowEnter (): void { - const eventType = InputEventType.MOUSE_ENTER; - const eventMouse = new EventMouse(eventType, false); - this._eventTarget.emit(eventType, eventMouse); - } -} diff --git a/pal/input/native/touch-input.ts b/pal/input/native/touch-input.ts deleted file mode 100644 index 8a2a751f6b..0000000000 --- a/pal/input/native/touch-input.ts +++ /dev/null @@ -1,156 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { screenAdapter } from 'pal/screen-adapter'; -import { Size, Vec2 } from '../../../cocos/core/math'; -import { EventTarget } from '../../../cocos/core/event'; -import { EventTouch, Touch as CCTouch } from '../../../cocos/input/types'; -import { touchManager } from '../touch-manager'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; - -export type TouchCallback = (res: EventTouch) => void; - -declare const jsb: any; - -class TouchEventElement { - type: InputEventType | null = null; - changedTouches: Touch[] = []; - windowId: number = 0; -} - -class TouchEventCache { - private _events: TouchEventElement[] = []; - private _length = 0; - - push (eventType: InputEventType, changedTouches: Touch[], windowId: number): void { - const events = this._events; - const index = this._length; - if (index >= events.length) { - events.push(new TouchEventElement()); - } - const e = events[index]; - const cachedTouches = e.changedTouches; - e.type = eventType; - cachedTouches.length = changedTouches.length; - e.windowId = windowId; - - for (let i = 0, len = changedTouches.length; i < len; ++i) { - const src = changedTouches[i]; - let dst = cachedTouches[i] as any; - if (!dst) { - (cachedTouches[i] as any) = dst = {}; - } - Object.assign(dst, src); - } - - ++this._length; - } - - clear (): void { - this._length = 0; - } - - forEach (cb: ((e: TouchEventElement) => void)): void { - for (let i = 0, len = this._length; i < len; ++i) { - cb(this._events[i]); - } - } -} - -export class TouchInputSource { - private _eventTarget: EventTarget = new EventTarget(); - private _windowManager: any; - - private _cache = new TouchEventCache(); - - constructor () { - this._registerEvent(); - this._windowManager = jsb.ISystemWindowManager.getInstance(); - } - - private _registerEvent (): void { - jsb.onTouchStart = this._createEventCacheCallback(InputEventType.TOUCH_START); - jsb.onTouchMove = this._createEventCacheCallback(InputEventType.TOUCH_MOVE); - jsb.onTouchEnd = this._createEventCacheCallback(InputEventType.TOUCH_END); - jsb.onTouchCancel = this._createEventCacheCallback(InputEventType.TOUCH_CANCEL); - } - - private _createEventCacheCallback (eventType: InputEventType) { - return (changedTouches: Touch[], windowId: number): void => { - this._cache.push(eventType, changedTouches, windowId); - }; - } - - public dispatchEventsInCache (): void { - const cache = this._cache; - cache.forEach((e: TouchEventElement) => { - this._dispatchEvent(e.type!, e.changedTouches, e.windowId); - }); - - cache.clear(); - } - - private _dispatchEvent (eventType: InputEventType, changedTouches: Touch[], windowId: number): void { - const handleTouches: CCTouch[] = []; - const length = changedTouches.length; - const windowSize = this._windowManager.getWindow(windowId).getViewSize() as Size; - for (let i = 0; i < length; ++i) { - const changedTouch = changedTouches[i]; - const touchID = changedTouch.identifier; - if (touchID === null) { - continue; - } - const location = this._getLocation(changedTouch, windowSize); - const touch = touchManager.getOrCreateTouch(touchID, location.x, location.y); - if (!touch) { - continue; - } - if (eventType === InputEventType.TOUCH_END || eventType === InputEventType.TOUCH_CANCEL) { - touchManager.releaseTouch(touchID); - } - handleTouches.push(touch); - } - if (handleTouches.length > 0) { - const eventTouch = new EventTouch( - handleTouches, - false, - eventType, - touchManager.getAllTouches(), - ); - eventTouch.windowId = windowId; - this._eventTarget.emit(eventType, eventTouch); - } - } - - private _getLocation (touch: globalThis.Touch, windowSize: Size): Vec2 { - const dpr = screenAdapter.devicePixelRatio; - const x = touch.clientX * dpr; - const y = windowSize.height - touch.clientY * dpr; - return new Vec2(x, y); - } - - public on (eventType: InputEventType, callback: TouchCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } -} diff --git a/pal/input/nodejs/accelerometer-input.ts b/pal/input/nodejs/accelerometer-input.ts deleted file mode 100644 index 9e8254f621..0000000000 --- a/pal/input/nodejs/accelerometer-input.ts +++ /dev/null @@ -1,49 +0,0 @@ -/* - Copyright (c) 2025 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { EventAcceleration } from '../../../cocos/input/types'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; - -export type AccelerometerCallback = (res: EventAcceleration) => void; - -export class AccelerometerInputSource { - - constructor () { - - } - - - public start (): void { - - } - public stop (): void { - - } - public setInterval (intervalInMileseconds: number): void { - - } - public on (eventType: InputEventType, callback: AccelerometerCallback, target?: any): void { - - } -} diff --git a/pal/input/nodejs/gamepad-input.ts b/pal/input/nodejs/gamepad-input.ts deleted file mode 100644 index a22ad7bc3f..0000000000 --- a/pal/input/nodejs/gamepad-input.ts +++ /dev/null @@ -1,131 +0,0 @@ -/* - Copyright (c) 2025 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -/* eslint-disable brace-style */ -import { systemInfo } from 'pal/system-info'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { Feature } from '../../system-info/enum-type'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { EventGamepad } from '../../../cocos/input/types'; -import { InputSourceButton, InputSourceDpad, InputSourceOrientation, InputSourcePosition, InputSourceStick } from '../input-source'; - -export type GamepadCallback = (res: EventGamepad) => void; - -export class GamepadInputDevice { - public static all: GamepadInputDevice[] = []; - public static xr: (GamepadInputDevice | null) = null; - - public get buttonNorth (): InputSourceButton { return this._buttonNorth; } - public get buttonEast (): InputSourceButton { return this._buttonEast; } - public get buttonWest (): InputSourceButton { return this._buttonWest; } - public get buttonSouth (): InputSourceButton { return this._buttonSouth; } - public get buttonL1 (): InputSourceButton { return this._buttonL1; } - public get buttonL2 (): InputSourceButton { return this._buttonL2; } - public get buttonL3 (): InputSourceButton { return this._buttonL3; } - public get buttonR1 (): InputSourceButton { return this._buttonR1; } - public get buttonR2 (): InputSourceButton { return this._buttonR2; } - public get buttonR3 (): InputSourceButton { return this._buttonR3; } - // public get buttonTouchPad () { return this._buttonTouchPad; } - // public get buttonHome () { return this._buttonHome; } - public get buttonShare (): InputSourceButton { return this._buttonShare; } - public get buttonOptions (): InputSourceButton { return this._buttonOptions; } - public get dpad (): InputSourceDpad { return this._dpad; } - public get leftStick (): InputSourceStick { return this._leftStick; } - public get rightStick (): InputSourceStick { return this._rightStick; } - public get buttonStart (): InputSourceButton { return this._buttonStart; } - public get gripLeft (): InputSourceButton { return this._gripLeft; } - public get gripRight (): InputSourceButton { return this._gripRight; } - public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; } - public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; } - public get handRightPosition (): InputSourcePosition { return this._handRightPosition; } - public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; } - public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; } - public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; } - public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; } - public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; } - - public get deviceId (): number { - return 0; - } - public get connected (): boolean { - return false; - } - - private static _eventTarget: EventTarget = new EventTarget(); - - private declare _buttonNorth: InputSourceButton; - private declare _buttonEast: InputSourceButton; - private declare _buttonWest: InputSourceButton; - private declare _buttonSouth: InputSourceButton; - private declare _buttonL1: InputSourceButton; - private declare _buttonL2: InputSourceButton; - private declare _buttonL3: InputSourceButton; - private declare _buttonR1: InputSourceButton; - private declare _buttonR2: InputSourceButton; - private declare _buttonR3: InputSourceButton; - // private declare buttonTouchPad: InputSourceButton; - // private declare buttonHome: InputSourceButton; - private declare _buttonShare: InputSourceButton; - private declare _buttonOptions: InputSourceButton; - private declare _dpad: InputSourceDpad; - private declare _leftStick: InputSourceStick; - private declare _rightStick: InputSourceStick; - private declare _buttonStart: InputSourceButton; - private declare _gripLeft: InputSourceButton; - private declare _gripRight: InputSourceButton; - private declare _handLeftPosition: InputSourcePosition; - private declare _handLeftOrientation: InputSourceOrientation; - private declare _handRightPosition: InputSourcePosition; - private declare _handRightOrientation: InputSourceOrientation; - private declare _aimLeftPosition: InputSourcePosition; - private declare _aimLeftOrientation: InputSourceOrientation; - private declare _aimRightPosition: InputSourcePosition; - private declare _aimRightOrientation: InputSourceOrientation; - - - constructor (deviceId: number) { - - } - - /** - * @engineInternal - */ - public static _init (): void { - if (!systemInfo.hasFeature(Feature.EVENT_GAMEPAD)) { - return; - } - - } - - /** - * @engineInternal - */ - public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any): void { - GamepadInputDevice._eventTarget.on(eventType, cb, target); - } - - - - -} diff --git a/pal/input/nodejs/handheld-input.ts b/pal/input/nodejs/handheld-input.ts deleted file mode 100644 index 69ba935501..0000000000 --- a/pal/input/nodejs/handheld-input.ts +++ /dev/null @@ -1,54 +0,0 @@ -/* - Copyright (c) 2025 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { EventHandheld } from '../../../cocos/input/types'; -import { InputSourcePosition, InputSourceOrientation } from '../input-source'; -export type HandheldCallback = (res: EventHandheld) => void; - - -export class HandheldInputDevice { - public get handheldPosition (): InputSourcePosition { return this._handheldPosition; } - public get handheldOrientation (): InputSourceOrientation { return this._handheldOrientation; } - - private _eventTarget: EventTarget = new EventTarget(); - - private declare _handheldPosition: InputSourcePosition; - private declare _handheldOrientation: InputSourceOrientation; - - constructor () { - - } - - - - /** - * @engineInternal - */ - public _on (eventType: InputEventType, callback: HandheldCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - -} \ No newline at end of file diff --git a/pal/input/nodejs/handle-input.ts b/pal/input/nodejs/handle-input.ts deleted file mode 100644 index 23aae7ea5e..0000000000 --- a/pal/input/nodejs/handle-input.ts +++ /dev/null @@ -1,113 +0,0 @@ -/* - Copyright (c) 2025 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { EventHandle } from '../../../cocos/input/types'; -import { InputSourceButton, InputSourceStick, InputSourcePosition, InputSourceOrientation, InputSourceTouch } from '../input-source'; - -export type HandleCallback = (res: EventHandle) => void; - - -export class HandleInputDevice { - public get buttonNorth (): InputSourceButton { return this._buttonNorth; } - public get buttonEast (): InputSourceButton { return this._buttonEast; } - public get buttonWest (): InputSourceButton { return this._buttonWest; } - public get buttonSouth (): InputSourceButton { return this._buttonSouth; } - public get buttonTriggerLeft (): InputSourceButton { return this._buttonTriggerLeft; } - public get buttonTriggerRight (): InputSourceButton { return this._buttonTriggerRight; } - public get triggerLeft (): InputSourceButton { return this._triggerLeft; } - public get triggerRight (): InputSourceButton { return this._triggerRight; } - public get gripLeft (): InputSourceButton { return this._gripLeft; } - public get gripRight (): InputSourceButton { return this._gripRight; } - public get leftStick (): InputSourceStick { return this._leftStick; } - public get rightStick (): InputSourceStick { return this._rightStick; } - public get buttonLeftStick (): InputSourceButton { return this._buttonLeftStick; } - public get buttonRightStick (): InputSourceButton { return this._buttonRightStick; } - public get buttonOptions (): InputSourceButton { return this._buttonOptions; } - public get buttonStart (): InputSourceButton { return this._buttonStart; } - public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; } - public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; } - public get handRightPosition (): InputSourcePosition { return this._handRightPosition; } - public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; } - public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; } - public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; } - public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; } - public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; } - public get touchButtonA (): InputSourceTouch { return this._touchButtonA; } - public get touchButtonB (): InputSourceTouch { return this._touchButtonB; } - public get touchButtonX (): InputSourceTouch { return this._touchButtonX; } - public get touchButtonY (): InputSourceTouch { return this._touchButtonY; } - public get touchButtonTriggerLeft (): InputSourceTouch { return this._touchButtonTriggerLeft; } - public get touchButtonTriggerRight (): InputSourceTouch { return this._touchButtonTriggerRight; } - public get touchButtonThumbStickLeft (): InputSourceTouch { return this._touchButtonThumbStickLeft; } - public get touchButtonThumbStickRight (): InputSourceTouch { return this._touchButtonThumbStickRight; } - - private _eventTarget: EventTarget = new EventTarget(); - - private declare _buttonNorth: InputSourceButton; - private declare _buttonEast: InputSourceButton; - private declare _buttonWest: InputSourceButton; - private declare _buttonSouth: InputSourceButton; - private declare _buttonTriggerLeft: InputSourceButton; - private declare _buttonTriggerRight: InputSourceButton; - private declare _triggerLeft: InputSourceButton; - private declare _triggerRight: InputSourceButton; - private declare _gripLeft: InputSourceButton; - private declare _gripRight: InputSourceButton; - private declare _leftStick: InputSourceStick; - private declare _rightStick: InputSourceStick; - private declare _buttonLeftStick: InputSourceButton; - private declare _buttonRightStick: InputSourceButton; - private declare _buttonOptions: InputSourceButton; - private declare _buttonStart: InputSourceButton; - private declare _handLeftPosition: InputSourcePosition; - private declare _handLeftOrientation: InputSourceOrientation; - private declare _handRightPosition: InputSourcePosition; - private declare _handRightOrientation: InputSourceOrientation; - private declare _aimLeftPosition: InputSourcePosition; - private declare _aimLeftOrientation: InputSourceOrientation; - private declare _aimRightPosition: InputSourcePosition; - private declare _aimRightOrientation: InputSourceOrientation; - private declare _touchButtonA: InputSourceTouch; - private declare _touchButtonB: InputSourceTouch; - private declare _touchButtonX: InputSourceTouch; - private declare _touchButtonY: InputSourceTouch; - private declare _touchButtonTriggerLeft: InputSourceTouch; - private declare _touchButtonTriggerRight: InputSourceTouch; - private declare _touchButtonThumbStickLeft: InputSourceTouch; - private declare _touchButtonThumbStickRight: InputSourceTouch; - - constructor () { - - } - - /** - * @engineInternal - */ - public _on (eventType: InputEventType, callback: HandleCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - -} diff --git a/pal/input/nodejs/hmd-input.ts b/pal/input/nodejs/hmd-input.ts deleted file mode 100644 index 5a9c8b0d0f..0000000000 --- a/pal/input/nodejs/hmd-input.ts +++ /dev/null @@ -1,74 +0,0 @@ -/* - Copyright (c) 2025 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { EventHMD } from '../../../cocos/input/types'; -import { InputSourcePosition, InputSourceOrientation } from '../input-source'; -import { Vec3, Quat } from '../../../cocos/core/math'; - -export type HMDCallback = (res: EventHMD) => void; - -enum Pose { - VIEW_LEFT, - VIEW_RIGHT, - HEAD_MIDDLE, -} - -interface IPoseValue { - position: Vec3; - orientation: Quat; -} - -export class HMDInputDevice { - public get viewLeftPosition (): InputSourcePosition { return this._viewLeftPosition; } - public get viewLeftOrientation (): InputSourceOrientation { return this._viewLeftOrientation; } - public get viewRightPosition (): InputSourcePosition { return this._viewRightPosition; } - public get viewRightOrientation (): InputSourceOrientation { return this._viewRightOrientation; } - public get headMiddlePosition (): InputSourcePosition { return this._headMiddlePosition; } - public get headMiddleOrientation (): InputSourceOrientation { return this._headMiddleOrientation; } - - private _eventTarget: EventTarget = new EventTarget(); - - private declare _viewLeftPosition: InputSourcePosition; - private declare _viewLeftOrientation: InputSourceOrientation; - private declare _viewRightPosition: InputSourcePosition; - private declare _viewRightOrientation: InputSourceOrientation; - private declare _headMiddlePosition: InputSourcePosition; - private declare _headMiddleOrientation: InputSourceOrientation; - - constructor () { - - } - - - - /** - * @engineInternal - */ - public _on (eventType: InputEventType, callback: HMDCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - -} diff --git a/pal/input/nodejs/index.ts b/pal/input/nodejs/index.ts deleted file mode 100644 index a30638e368..0000000000 --- a/pal/input/nodejs/index.ts +++ /dev/null @@ -1,36 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { checkPalIntegrity, withImpl } from '../../integrity-check'; - -export * from './accelerometer-input'; -export * from './gamepad-input'; -export * from './handle-input'; -export * from './hmd-input'; -export * from './handheld-input'; -export * from './keyboard-input'; -export * from './mouse-input'; -export * from './touch-input'; - -checkPalIntegrity(withImpl()); diff --git a/pal/input/nodejs/keyboard-input.ts b/pal/input/nodejs/keyboard-input.ts deleted file mode 100644 index 3851f8a023..0000000000 --- a/pal/input/nodejs/keyboard-input.ts +++ /dev/null @@ -1,47 +0,0 @@ -/* - Copyright (c) 2025 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { EventKeyboard } from '../../../cocos/input/types'; -import { EventTarget } from '../../../cocos/core/event'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; - - -export type KeyboardCallback = (res: EventKeyboard) => void; - - -export class KeyboardInputSource { - private _eventTarget: EventTarget = new EventTarget(); - - constructor () { - - } - - public dispatchKeyboardDownEvent (nativeKeyboardEvent: jsb.KeyboardEvent): void { } - public dispatchKeyboardUpEvent (nativeKeyboardEvent: jsb.KeyboardEvent): void { } - - - public on (eventType: InputEventType, callback: KeyboardCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } -} diff --git a/pal/input/nodejs/mouse-input.ts b/pal/input/nodejs/mouse-input.ts deleted file mode 100644 index 4fe2802005..0000000000 --- a/pal/input/nodejs/mouse-input.ts +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright (c) 2025 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { EventMouse } from '../../../cocos/input/types'; -import { EventTarget } from '../../../cocos/core/event'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; - -export type MouseCallback = (res: EventMouse) => void; - -export class MouseInputSource { - private _eventTarget: EventTarget = new EventTarget(); - - constructor () { - - } - - public dispatchMouseDownEvent (nativeMouseEvent: any): void { } - public dispatchMouseMoveEvent (nativeMouseEvent: any): void { } - public dispatchMouseUpEvent (nativeMouseEvent: any): void { } - public dispatchScrollEvent (nativeMouseEvent: any): void { } - - - public dispatchEventsInCache (): void { - - } - - - public on (eventType: InputEventType, callback: MouseCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - -} diff --git a/pal/input/nodejs/touch-input.ts b/pal/input/nodejs/touch-input.ts deleted file mode 100644 index a3162f8614..0000000000 --- a/pal/input/nodejs/touch-input.ts +++ /dev/null @@ -1,45 +0,0 @@ -/* - Copyright (c) 2025 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { EventTarget } from '../../../cocos/core/event'; -import { EventTouch, Touch as CCTouch } from '../../../cocos/input/types'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; - -export type TouchCallback = (res: EventTouch) => void; - -export class TouchInputSource { - private _eventTarget: EventTarget = new EventTarget(); - - constructor () { - } - - - public dispatchEventsInCache (): void { - - } - - public on (eventType: InputEventType, callback: TouchCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } -} diff --git a/pal/input/touch-manager.ts b/pal/input/touch-manager.ts deleted file mode 100644 index 7fec3e6628..0000000000 --- a/pal/input/touch-manager.ts +++ /dev/null @@ -1,159 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { Vec2 } from '../../cocos/core/math/vec2'; -import { logID } from '../../cocos/core/platform/debug'; -import { macro } from '../../cocos/core/platform/macro'; -import { Touch } from '../../cocos/input/types'; - -const tempVec2 = new Vec2(); - -class TouchManager { - /** - * A map from touch ID to touch object. - */ - private _touchMap: Map = new Map(); - private readonly _maxTouches = 8; - - constructor () { - } - - /** - * Create the touch object at the touch start event callback. - * we have some policy to create the touch object: - * - If the number of touches doesn't exceed the max count, we create a touch object. - * - If the number of touches exceeds the max count, we discard the timeout touch to create a new one. - * - If the number of touches exceeds the max count and there is no timeout touch, we can't create any touch object. - * @param touchID The touch identifier - * @param x The x-axis coordinate of the current touch point. - * @param y The y-axis coordinate of the current touch point. - * @return The Touch instance or undefined. - */ - private _createTouch (touchID: number, x: number, y: number): Touch | undefined { - if (this._touchMap.has(touchID)) { - logID(2301); - return undefined; - } - const checkResult = this._checkTouchMapSizeMoreThanMax(touchID); - if (checkResult) { - logID(2300); - return undefined; - } - const touch = new Touch(x, y, touchID); - this._touchMap.set(touchID, touch); - this._updateTouch(touch, x, y); - return touch; - } - - /** - * Release the touch object at the touch end or touch cancel event callback. - * @param touchID - * @returns - */ - public releaseTouch (touchID: number): void { - if (!this._touchMap.has(touchID)) { - return; - } - this._touchMap.delete(touchID); - } - - /** - * Get touch object by touch ID. - * @param touchID - * @returns - */ - public getTouch (touchID: number): Touch | undefined { - return this._touchMap.get(touchID); - } - - /** - * Get or create touch object by touch ID. - * @param touchID - * @returns - */ - public getOrCreateTouch (touchID: number, x: number, y: number): Touch | undefined { - let touch = this.getTouch(touchID); - if (!touch) { - touch = this._createTouch(touchID, x, y); - } else { - this._updateTouch(touch, x, y); - } - return touch; - } - - /** - * Get all the current touches objects. - * @returns - */ - public getAllTouches (): Touch[] { - const touches: Touch[] = []; - this._touchMap.forEach((touch) => { - if (touch) { - touches.push(touch); - } - }); - return touches; - } - - /** - * Get the number of touches. - */ - public getTouchCount (): number { - return this._touchMap.size; - } - - /** - * Update the location and previous location of current touch ID. - * @param touchID - * @param x The current location X - * @param y The current location Y - */ - private _updateTouch (touch: Touch, x: number, y: number): void { - touch.getLocation(tempVec2); - touch.setPrevPoint(tempVec2); - touch.setPoint(x, y); - } - - private _checkTouchMapSizeMoreThanMax (touchID: number): boolean { - if (this._touchMap.has(touchID)) { - return false; - } - const maxSize = macro.ENABLE_MULTI_TOUCH ? this._maxTouches : 1; - if (this._touchMap.size < maxSize) { - return false; - } - // Handle when exceed the max number of touches - const now = performance.now(); - this._touchMap.forEach((touch) => { - if (now - touch.lastModified > macro.TOUCH_TIMEOUT) { - logID(2302, touch.getID()); - // TODO: need to handle touch cancel event when exceed the max number of touches ? - this.releaseTouch(touch.getID()); - } - }); - return maxSize >= this._touchMap.size; - } -} - -export const touchManager = new TouchManager(); diff --git a/pal/input/web/accelerometer-input.ts b/pal/input/web/accelerometer-input.ts deleted file mode 100644 index c29672f302..0000000000 --- a/pal/input/web/accelerometer-input.ts +++ /dev/null @@ -1,145 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { AccelerometerCallback } from 'pal/input'; -import { systemInfo } from 'pal/system-info'; -import { screenAdapter } from 'pal/screen-adapter'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { BrowserType, OS } from '../../system-info/enum-type'; -import { EventAcceleration, Acceleration } from '../../../cocos/input/types'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { warn } from '../../../cocos/core/platform/debug'; - -export class AccelerometerInputSource { - private _intervalInMileSeconds = 200; - private _accelTimer = 0; - private _eventTarget: EventTarget = new EventTarget(); - private declare _deviceEventName: 'devicemotion' |'deviceorientation'; - private declare _globalEventClass: typeof window.DeviceMotionEvent | typeof window.DeviceOrientationEvent; - private declare _didAccelerateFunc: (event: DeviceMotionEvent | DeviceOrientationEvent) => void; - - constructor () { - // init event name - this._globalEventClass = window.DeviceMotionEvent || window.DeviceOrientationEvent; - // TODO fix DeviceMotionEvent bug on QQ Browser version 4.1 and below. - if (systemInfo.browserType === BrowserType.MOBILE_QQ) { - this._globalEventClass = window.DeviceOrientationEvent; - } - this._deviceEventName = this._globalEventClass === window.DeviceMotionEvent ? 'devicemotion' : 'deviceorientation'; - this._didAccelerateFunc = this._didAccelerate.bind(this); - } - - private _registerEvent (): void { - this._accelTimer = performance.now(); - window.addEventListener(this._deviceEventName, this._didAccelerateFunc, false); - } - - private _unregisterEvent (): void { - this._accelTimer = 0; - window.removeEventListener(this._deviceEventName, this._didAccelerateFunc, false); - } - - private _didAccelerate (event: DeviceMotionEvent | DeviceOrientationEvent): void { - const now = performance.now(); - if (now - this._accelTimer < this._intervalInMileSeconds) { - return; - } - this._accelTimer = now; - - let x = 0; - let y = 0; - let z = 0; - if (this._globalEventClass === window.DeviceMotionEvent) { - const deviceMotionEvent = event as DeviceMotionEvent; - const eventAcceleration = deviceMotionEvent.accelerationIncludingGravity; - x = (eventAcceleration?.x || 0) * 0.1; - y = (eventAcceleration?.y || 0) * 0.1; - z = (eventAcceleration?.z || 0) * 0.1; - } else { - const deviceOrientationEvent = event as DeviceOrientationEvent; - x = ((deviceOrientationEvent.gamma || 0) / 90) * 0.981; - y = -((deviceOrientationEvent.beta || 0) / 90) * 0.981; - z = ((deviceOrientationEvent.alpha || 0) / 90) * 0.981; - } - - if (screenAdapter.isFrameRotated) { - const tmp = x; - x = -y; - y = tmp; - } - - // TODO: window.orientation is deprecated: https://developer.mozilla.org/en-US/docs/Web/API/Window/orientation - // try to use experimental screen.orientation: https://developer.mozilla.org/en-US/docs/Web/API/Screen/orientation - const PORTRAIT = 0; - const LANDSCAPE_LEFT = -90; - const PORTRAIT_UPSIDE_DOWN = 180; - const LANDSCAPE_RIGHT = 90; - const tmpX = x; - if (window.orientation === LANDSCAPE_RIGHT) { - x = -y; - y = tmpX; - } else if (window.orientation === LANDSCAPE_LEFT) { - x = y; - y = -tmpX; - } else if (window.orientation === PORTRAIT_UPSIDE_DOWN) { - x = -x; - y = -y; - } - - // fix android acc values are opposite - if (systemInfo.os === OS.ANDROID - && systemInfo.browserType !== BrowserType.MOBILE_QQ) { - x = -x; - y = -y; - } - const timestamp = performance.now(); - const acceleration = new Acceleration(x, y, z, timestamp); - const eventAcceleration = new EventAcceleration(acceleration); - this._eventTarget.emit(InputEventType.DEVICEMOTION, eventAcceleration); - } - - public start (): void { - // for iOS 13+, safari - // NOTE: since TS 4.4, `requestPermission` is not defined in class DeviceMotionEvent in `lib.dom.d.ts`, this should be a breaking change in TS. - // Accessing the `requestPermission` would emit a type error, so we assert `DeviceMotionEvent` as any type to skip the TS type checking. - if (window.DeviceMotionEvent && typeof (DeviceMotionEvent as any).requestPermission === 'function') { - (DeviceMotionEvent as any).requestPermission().then((response) => { - if (response === 'granted') { - this._registerEvent(); - } - }).catch((e) => { warn(e); }); - } else { - this._registerEvent(); - } - } - public stop (): void { - this._unregisterEvent(); - } - public setInterval (intervalInMileSeconds: number): void { - this._intervalInMileSeconds = intervalInMileSeconds; - } - public on (eventType: InputEventType, callback: AccelerometerCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } -} diff --git a/pal/input/web/gamepad-input.ts b/pal/input/web/gamepad-input.ts deleted file mode 100644 index 9a3f4fc854..0000000000 --- a/pal/input/web/gamepad-input.ts +++ /dev/null @@ -1,899 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { GamepadCallback } from 'pal/input'; -import { systemInfo } from 'pal/system-info'; -import { USE_XR } from 'internal:constants'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import legacyCC from '../../../predefine'; -import { Feature } from '../../system-info/enum-type'; -import { InputSourceButton, InputSourceDpad, InputSourceOrientation, InputSourcePosition, InputSourceStick } from '../input-source'; -import { Quat, Vec3, js } from '../../../cocos/core'; -import { EventGamepad } from '../../../cocos/input/types'; - -//#region button index alias -const BUTTON_SOUTH = 0; -const BUTTON_EAST = 1; -const BUTTON_WEST = 2; -const BUTTON_NORTH = 3; -const BUTTON_L1 = 4; -const BUTTON_R1 = 5; -const BUTTON_L2 = 6; -const BUTTON_R2 = 7; -const BUTTON_SHARE = 8; -const BUTTON_OPTIONS = 9; -const BUTTON_L3 = 10; -const BUTTON_R3 = 11; -const BUTTON_DPAD_UP = 12; -const BUTTON_DPAD_DOWN = 13; -const BUTTON_DPAD_LEFT = 14; -const BUTTON_DPAD_RIGHT = 15; -const BUTTON_HOME = 16; -const BUTTON_TOUCH_PAD = 17; -const AXIS_LEFT_STICK_X = 0; -const AXIS_LEFT_STICK_Y = 1; -const AXIS_RIGHT_STICK_X = 2; -const AXIS_RIGHT_STICK_Y = 3; -const XR_TRIGGER = 0; -const XR_GRIP = 1; -const XR_TOUCHPAD = 2; -const XR_STICK = 3; -const XR_BUTTON_1 = 4; -const XR_BUTTON_2 = 5; -const XR_AXIS_TOUCHPAD_X = 0; -const XR_AXIS_TOUCHPAD_Y = 1; -const XR_AXIS_STICK_X = 2; -const XR_AXIS_STICK_Y = 3; -//#endregion button index alias - -const EPSILON = 0.01; -type WebGamepad = Gamepad; -const XRLeftHandedness = 'left'; -const XRRightHandedness = 'right'; - -const devicesTmp: GamepadInputDevice[] = []; - -enum Pose { - HAND_LEFT = 1, - HAND_RIGHT = 4, - AIM_LEFT = 2, - AIM_RIGHT = 5, -} - -interface IPoseValue { - position: Vec3; - orientation: Quat; -} - -interface IPoseInfo { - readonly code: Pose; - readonly position: DOMPointReadOnly; - readonly orientation: DOMPointReadOnly; -} - -type WebPoseState = Record - -interface IAxisValue { - negative: number; - positive: number; -} - -interface IGamepadCacheInfo { - buttons: Array; - axes: Array; -} - -export class GamepadInputDevice { - public static all: GamepadInputDevice[] = []; - public static xr: (GamepadInputDevice | null) = null; - - public get buttonNorth (): InputSourceButton { return this._buttonNorth; } - public get buttonEast (): InputSourceButton { return this._buttonEast; } - public get buttonWest (): InputSourceButton { return this._buttonWest; } - public get buttonSouth (): InputSourceButton { return this._buttonSouth; } - public get buttonL1 (): InputSourceButton { return this._buttonL1; } - public get buttonL2 (): InputSourceButton { return this._buttonL2; } - public get buttonL3 (): InputSourceButton { return this._buttonL3; } - public get buttonR1 (): InputSourceButton { return this._buttonR1; } - public get buttonR2 (): InputSourceButton { return this._buttonR2; } - public get buttonR3 (): InputSourceButton { return this._buttonR3; } - // public get buttonTouchPad () { return this._buttonTouchPad; } - // public get buttonHome () { return this._buttonHome; } - public get buttonShare (): InputSourceButton { return this._buttonShare; } - public get buttonOptions (): InputSourceButton { return this._buttonOptions; } - public get dpad (): InputSourceDpad { return this._dpad; } - public get leftStick (): InputSourceStick { return this._leftStick; } - public get rightStick (): InputSourceStick { return this._rightStick; } - public get buttonStart (): InputSourceButton { return this._buttonStart; } - public get gripLeft (): InputSourceButton { return this._gripLeft; } - public get gripRight (): InputSourceButton { return this._gripRight; } - public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; } - public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; } - public get handRightPosition (): InputSourcePosition { return this._handRightPosition; } - public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; } - public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; } - public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; } - public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; } - public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; } - - public get deviceId (): number { - return this._deviceId; - } - public get connected (): boolean { - return this._connected; - } - - private static _eventTarget: EventTarget = new EventTarget(); - private static _cachedWebGamepads: (WebGamepad | null)[] = []; - private static _cachedWebXRGamepadMap: (Map | null) = null; - private static _intervalId = -1; - - private declare _buttonNorth: InputSourceButton; - private declare _buttonEast: InputSourceButton; - private declare _buttonWest: InputSourceButton; - private declare _buttonSouth: InputSourceButton; - private declare _buttonL1: InputSourceButton; - private declare _buttonL2: InputSourceButton; - private declare _buttonL3: InputSourceButton; - private declare _buttonR1: InputSourceButton; - private declare _buttonR2: InputSourceButton; - private declare _buttonR3: InputSourceButton; - // private declare buttonTouchPad: InputSourceButton; - // private declare buttonHome: InputSourceButton; - private declare _buttonShare: InputSourceButton; - private declare _buttonOptions: InputSourceButton; - private declare _dpad: InputSourceDpad; - private declare _leftStick: InputSourceStick; - private declare _rightStick: InputSourceStick; - private declare _buttonStart: InputSourceButton; - private declare _gripLeft: InputSourceButton; - private declare _gripRight: InputSourceButton; - private declare _handLeftPosition: InputSourcePosition; - private declare _handLeftOrientation: InputSourceOrientation; - private declare _handRightPosition: InputSourcePosition; - private declare _handRightOrientation: InputSourceOrientation; - private declare _aimLeftPosition: InputSourcePosition; - private declare _aimLeftOrientation: InputSourceOrientation; - private declare _aimRightPosition: InputSourcePosition; - private declare _aimRightOrientation: InputSourceOrientation; - - private _deviceId = -1; - private _connected = false; - - private _webPoseState: WebPoseState = { - [Pose.HAND_LEFT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, - [Pose.HAND_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, - [Pose.AIM_LEFT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, - [Pose.AIM_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, - }; - - constructor (deviceId: number) { - this._deviceId = deviceId; - this._initInputSource(); - } - - /** - * @engineInternal - */ - public static _init (): void { - if (!systemInfo.hasFeature(Feature.EVENT_GAMEPAD)) { - return; - } - GamepadInputDevice._registerEvent(); - } - - /** - * @engineInternal - */ - public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any): void { - GamepadInputDevice._eventTarget.on(eventType, cb, target); - } - - private static _removeInputDevice (id: number): void { - const removeIndex = GamepadInputDevice.all.findIndex((device) => device.deviceId === id); - if (removeIndex === -1) { - return; - } - js.array.fastRemoveAt(GamepadInputDevice.all, removeIndex); - } - private static _getOrCreateInputDevice (id: number, connected: boolean): GamepadInputDevice { - let device = GamepadInputDevice.all.find((device) => device.deviceId === id); - if (!device) { - device = new GamepadInputDevice(id); - GamepadInputDevice.all.push(device); - } - device._connected = connected; - return device; - } - - private static _ensureDirectorDefined (callback: () => void): void { - GamepadInputDevice._intervalId = setInterval(() => { - if (legacyCC.director && legacyCC.Director) { - clearInterval(GamepadInputDevice._intervalId); - GamepadInputDevice._intervalId = -1; - callback(); - } - }, 50); - } - - private static _totalGamepadCnt = 0; - private static _updateGamepadCnt (): void { - let cnt = 0; - for (let i = 0, l = GamepadInputDevice._cachedWebGamepads.length; i < l; i++) { - if (GamepadInputDevice._cachedWebGamepads[i]) cnt++; - } - GamepadInputDevice._totalGamepadCnt = cnt; - } - - private static _registerEvent (): void { - GamepadInputDevice._ensureDirectorDefined(() => { - GamepadInputDevice._cachedWebGamepads = GamepadInputDevice._getWebGamePads(); - GamepadInputDevice._updateGamepadCnt(); - legacyCC.director.on(legacyCC.Director.EVENT_BEGIN_FRAME, GamepadInputDevice._scanGamepads); - }); - window.addEventListener('gamepadconnected', (e) => { - GamepadInputDevice._cachedWebGamepads[e.gamepad.index] = e.gamepad; - GamepadInputDevice._updateGamepadCnt(); - const device = GamepadInputDevice._getOrCreateInputDevice(e.gamepad.index, true); - GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device)); - }); - window.addEventListener('gamepaddisconnected', (e) => { - GamepadInputDevice._cachedWebGamepads[e.gamepad.index] = null; - GamepadInputDevice._updateGamepadCnt(); - const device = GamepadInputDevice._getOrCreateInputDevice(e.gamepad.index, false); - GamepadInputDevice._removeInputDevice(e.gamepad.index); - GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device)); - }); - } - - private static _scanWebGamepads (devices: GamepadInputDevice[]): void { - const allDisconnected = GamepadInputDevice._totalGamepadCnt === 0; - if (allDisconnected) return; - - const webGamepads = GamepadInputDevice._getWebGamePads(); - if (!webGamepads) { - return; - } - for (let i = 0; i < webGamepads.length; ++i) { - const webGamepad = webGamepads[i]; - if (!webGamepad) { - continue; - } - const cachedWebGamepad = GamepadInputDevice._cachedWebGamepads[webGamepad.index]; - // TODO: what if cachedWebGamepad is null - if (cachedWebGamepad) { - let device: GamepadInputDevice | undefined; - const cachedButtons = cachedWebGamepad.buttons; - for (let j = 0; j < cachedButtons.length; ++j) { - const cachedButton = cachedButtons[j]; - const button = webGamepad.buttons[j]; - if (Math.abs(cachedButton.value - button.value) > EPSILON) { - device = GamepadInputDevice._getOrCreateInputDevice(webGamepad.index, true); - break; - } - } - if (device) { - devices.push(device); - continue; - } - - const cachedAxes = cachedWebGamepad.axes; - for (let j = 0; j < cachedAxes.length; ++j) { - const cachedAxisValue = cachedAxes[j]; - const axisValue = webGamepad.axes[j]; - if (Math.abs(cachedAxisValue - axisValue) > EPSILON) { - device = GamepadInputDevice._getOrCreateInputDevice(webGamepad.index, true); - break; - } - } - if (device) { - devices.push(device); - continue; - } - } - } - // update cache - GamepadInputDevice._cachedWebGamepads = webGamepads; - } - - private static _scanGamepads (): void { - devicesTmp.length = 0; - GamepadInputDevice._scanWebGamepads(devicesTmp); - GamepadInputDevice._scanWebXRGamepads(devicesTmp); - // emit event - for (let i = 0; i < devicesTmp.length; ++i) { - const device = devicesTmp[i]; - GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_INPUT, new EventGamepad(InputEventType.GAMEPAD_INPUT, device)); - } - GamepadInputDevice._scanWebXRGamepadsPose(); - } - - private static _scanWebXRGamepads (devices: GamepadInputDevice[]): void { - if (!USE_XR) return; - const webxrGamepadMap = GamepadInputDevice._getWebXRGamepadMap(); - if (!webxrGamepadMap) { - // update cache - GamepadInputDevice._cachedWebXRGamepadMap = null; - if (GamepadInputDevice.xr && GamepadInputDevice.xr._connected) { - GamepadInputDevice.xr._connected = false; - GamepadInputDevice._eventTarget.emit( - InputEventType.GAMEPAD_CHANGE, - new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr), - ); - devices.push(GamepadInputDevice.xr); - } - return; - } - - if (!GamepadInputDevice.xr) { - // webxr gamepads index is -1 https://www.w3.org/TR/webxr-gamepads-module-1/#navigator-differences - GamepadInputDevice.xr = new GamepadInputDevice(-1); - } - - const left = webxrGamepadMap.get(XRLeftHandedness); - const right = webxrGamepadMap.get(XRRightHandedness); - if (!left && !right) { - if (GamepadInputDevice.xr._connected) { - GamepadInputDevice.xr._connected = false; - GamepadInputDevice._eventTarget.emit( - InputEventType.GAMEPAD_CHANGE, - new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr), - ); - } - } else if (!GamepadInputDevice.xr._connected) { - GamepadInputDevice.xr._connected = true; - GamepadInputDevice._eventTarget.emit( - InputEventType.GAMEPAD_CHANGE, - new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr), - ); - } - - if (GamepadInputDevice.checkGamepadChanged( - left, - GamepadInputDevice._cachedWebXRGamepadMap?.get(XRLeftHandedness), - )) { - devices.push(GamepadInputDevice.xr); - } else if (GamepadInputDevice.checkGamepadChanged( - right, - GamepadInputDevice._cachedWebXRGamepadMap?.get(XRRightHandedness), - )) { - devices.push(GamepadInputDevice.xr); - } - - // update cache - if (!GamepadInputDevice._cachedWebXRGamepadMap) { - GamepadInputDevice._cachedWebXRGamepadMap = new Map(); - } - - GamepadInputDevice._cachedWebXRGamepadMap.set(XRLeftHandedness, GamepadInputDevice._copyCacheGamepadValue(left)); - GamepadInputDevice._cachedWebXRGamepadMap.set(XRRightHandedness, GamepadInputDevice._copyCacheGamepadValue(right)); - } - - private static checkGamepadChanged (currGamepad: (Gamepad | undefined), cachedGamepad: (IGamepadCacheInfo | undefined)): boolean { - if (!currGamepad && !cachedGamepad) { - return false; - } else if (!currGamepad || !cachedGamepad) { - return true; - } - - const cachedButtons = cachedGamepad.buttons; - for (let j = 0; j < cachedButtons.length; ++j) { - const cachedButton = cachedButtons[j]; - const button = currGamepad.buttons[j]; - if (button.value !== 0 || cachedButton !== 0) { - return true; - } - } - - const cachedAxes = cachedGamepad.axes; - for (let j = 0; j < cachedAxes.length; ++j) { - const cachedAxisValue = cachedAxes[j]; - const axisValue = currGamepad.axes[j]; - if (axisValue !== 0 || cachedAxisValue !== 0) { - return true; - } - } - - return false; - } - - private static _copyCacheGamepadValue (gamepad: Gamepad | undefined): IGamepadCacheInfo | undefined { - if (!gamepad) { - return undefined; - } - - const cacheGamepad: IGamepadCacheInfo = { buttons: new Array(gamepad.buttons.length), axes: new Array(gamepad.axes.length) }; - for (let j = 0; j < gamepad.buttons.length; ++j) { - cacheGamepad.buttons[j] = gamepad.buttons[j].value; - } - for (let j = 0; j < gamepad.axes.length; ++j) { - cacheGamepad.axes[j] = gamepad.axes[j]; - } - - return cacheGamepad; - } - - private static _scanWebXRGamepadsPose (): void { - if (!USE_XR) return; - const infoList = globalThis.__globalXR?.webxrHandlePoseInfos as IPoseInfo[]; - if (!infoList || !GamepadInputDevice.xr) { - return; - } - - for (let i = 0; i < infoList.length; ++i) { - const info = infoList[i]; - GamepadInputDevice.xr._updateWebPoseState(info); - } - GamepadInputDevice._eventTarget.emit( - InputEventType.HANDLE_POSE_INPUT, - new EventGamepad(InputEventType.HANDLE_POSE_INPUT, GamepadInputDevice.xr), - ); - } - - private static _getWebXRGamepadMap (): (Map | undefined) { - return globalThis.__globalXR?.webxrGamepadMap as Map; - } - - private static _getWebGamePads (): (WebGamepad | null)[] { - if (typeof navigator.getGamepads === 'function') { - return navigator.getGamepads(); - } else if (typeof (navigator as any).webkitGetGamepads === 'function') { - // NOTE: 'webkitGetGamepads' is not a standard web interface - return (navigator as any).webkitGetGamepads() as (Gamepad | null)[]; - } - return []; - } - - private static _getWebGamepad (deviceId: number): WebGamepad | undefined { - const webGamepads = GamepadInputDevice._getWebGamePads(); - for (let i = 0; i < webGamepads.length; ++i) { - const webGamepad = webGamepads[i]; - if (webGamepad && webGamepad.index === deviceId) { - return webGamepad; - } - } - return undefined; - } - - private _axisToButtons (axisValue: number): IAxisValue { - const value = Math.abs(axisValue); - if (axisValue > 0) { - return { negative: 0, positive: value }; - } else if (axisValue < 0) { - return { negative: value, positive: 0 }; - } else { - return { negative: 0, positive: 0 }; - } - } - - private _updateWebPoseState (info: IPoseInfo): void { - if (info.code !== Pose.HAND_LEFT && info.code !== Pose.AIM_LEFT - && info.code !== Pose.HAND_RIGHT && info.code !== Pose.AIM_RIGHT) { - return; - } - - this._webPoseState[info.code] = { - position: new Vec3(info.position.x, info.position.y, info.position.z), - orientation: new Quat(info.orientation.x, info.orientation.y, info.orientation.z, info.orientation.w), - }; - } - - private _initInputSource (): void { - this._buttonNorth = new InputSourceButton(); - this._buttonNorth.getValue = (): number => { - if (this.deviceId === -1) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); - if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_2) { - return webxrGamepad.buttons[XR_BUTTON_2].value; - } - return 0; - } - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { return webGamepad.buttons[BUTTON_NORTH].value; } - return 0; - }; - this._buttonEast = new InputSourceButton(); - this._buttonEast.getValue = (): number => { - if (this.deviceId === -1) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); - if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_2) { - return webxrGamepad.buttons[XR_BUTTON_2].value; - } - return 0; - } - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { return webGamepad.buttons[BUTTON_EAST].value; } - return 0; - }; - this._buttonWest = new InputSourceButton(); - this._buttonWest.getValue = (): number => { - if (this.deviceId === -1) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); - if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_1) { - return webxrGamepad.buttons[XR_BUTTON_1].value; - } - return 0; - } - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { return webGamepad.buttons[BUTTON_WEST].value; } - return 0; - }; - this._buttonSouth = new InputSourceButton(); - this._buttonSouth.getValue = (): number => { - if (this.deviceId === -1) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); - if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_1) { - return webxrGamepad.buttons[XR_BUTTON_1].value; - } - return 0; - } - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { return webGamepad.buttons[BUTTON_SOUTH].value; } - return 0; - }; - - this._buttonL1 = new InputSourceButton(); - this._buttonL1.getValue = (): number => { - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { return webGamepad.buttons[BUTTON_L1].value; } - return 0; - }; - this._buttonL2 = new InputSourceButton(); - this._buttonL2.getValue = (): number => { - if (this.deviceId === -1) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); - if (webxrGamepad && webxrGamepad.buttons.length > XR_TRIGGER) { - return webxrGamepad.buttons[XR_TRIGGER].value; - } - return 0; - } - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { return webGamepad.buttons[BUTTON_L2].value; } - return 0; - }; - this._buttonL3 = new InputSourceButton(); - this._buttonL3.getValue = (): number => { - if (this.deviceId === -1) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); - if (webxrGamepad) { - if (webxrGamepad.buttons.length > XR_STICK && webxrGamepad.buttons[XR_STICK].value !== 0) { - return webxrGamepad.buttons[XR_STICK].value; - } else if (webxrGamepad.buttons.length > XR_TOUCHPAD && webxrGamepad.buttons[XR_TOUCHPAD].value !== 0) { - return webxrGamepad.buttons[XR_TOUCHPAD].value; - } - } - return 0; - } - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { return webGamepad.buttons[BUTTON_L3].value; } - return 0; - }; - this._buttonR1 = new InputSourceButton(); - this._buttonR1.getValue = (): number => { - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { return webGamepad.buttons[BUTTON_R1].value; } - return 0; - }; - this._buttonR2 = new InputSourceButton(); - this._buttonR2.getValue = (): number => { - if (this.deviceId === -1) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); - if (webxrGamepad && webxrGamepad.buttons.length > XR_TRIGGER) { - return webxrGamepad.buttons[XR_TRIGGER].value; - } - return 0; - } - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { return webGamepad.buttons[BUTTON_R2].value; } - return 0; - }; - this._buttonR3 = new InputSourceButton(); - this._buttonR3.getValue = (): number => { - if (this.deviceId === -1) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); - if (webxrGamepad) { - if (webxrGamepad.buttons.length > XR_STICK && webxrGamepad.buttons[XR_STICK].value !== 0) { - return webxrGamepad.buttons[XR_STICK].value; - } else if (webxrGamepad.buttons.length > XR_TOUCHPAD && webxrGamepad.buttons[XR_TOUCHPAD].value !== 0) { - return webxrGamepad.buttons[XR_TOUCHPAD].value; - } - } - return 0; - } - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { return webGamepad.buttons[BUTTON_R3].value; } - return 0; - }; - - // this._buttonTouchPad = new InputSourceButton(); - // this._buttonTouchPad.getValue = () => { - // const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - // if (webGamepad) { return webGamepad.buttons[BUTTON_TOUCH_PAD].value; } - // return 0; - // }; - // this._buttonHome = new InputSourceButton(); - // this._buttonHome.getValue = () => { - // const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - // if (webGamepad) { return webGamepad.buttons[BUTTON_HOME].value; } - // return 0; - // }; - this._buttonShare = new InputSourceButton(); - this._buttonShare.getValue = (): number => { - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { return webGamepad.buttons[BUTTON_SHARE].value; } - return 0; - }; - this._buttonOptions = new InputSourceButton(); - this._buttonOptions.getValue = (): number => { - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { return webGamepad.buttons[BUTTON_OPTIONS].value; } - return 0; - }; - - const dpadUp = new InputSourceButton(); - dpadUp.getValue = (): number => { - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { return webGamepad.buttons[BUTTON_DPAD_UP].value; } - return 0; - }; - const dpadDown = new InputSourceButton(); - dpadDown.getValue = (): number => { - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { return webGamepad.buttons[BUTTON_DPAD_DOWN].value; } - return 0; - }; - const dpadLeft = new InputSourceButton(); - dpadLeft.getValue = (): number => { - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { return webGamepad.buttons[BUTTON_DPAD_LEFT].value; } - return 0; - }; - const dpadRight = new InputSourceButton(); - dpadRight.getValue = (): number => { - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { return webGamepad.buttons[BUTTON_DPAD_RIGHT].value; } - return 0; - }; - this._dpad = new InputSourceDpad({ up: dpadUp, down: dpadDown, left: dpadLeft, right: dpadRight }); - - const leftStickUp = new InputSourceButton(); - leftStickUp.getValue = (): number => { - if (this.deviceId === -1) { - if (USE_XR) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); - if (webxrGamepad) { - if (webxrGamepad.axes.length > XR_AXIS_STICK_Y && webxrGamepad.axes[XR_AXIS_STICK_Y] !== 0) { - return this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_Y]).negative; - } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_Y && webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y] !== 0) { - return this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y]).negative; - } - } - } - return 0; - } - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { - return this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_Y]).negative; - } - return 0; - }; - const leftStickDown = new InputSourceButton(); - leftStickDown.getValue = (): number => { - if (this.deviceId === -1) { - if (USE_XR) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); - if (webxrGamepad) { - if (webxrGamepad.axes.length > XR_AXIS_STICK_Y && webxrGamepad.axes[XR_AXIS_STICK_Y] !== 0) { - return this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_Y]).positive; - } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_Y && webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y] !== 0) { - return this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y]).positive; - } - } - } - return 0; - } - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { - return this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_Y]).positive; - } - return 0; - }; - const leftStickLeft = new InputSourceButton(); - leftStickLeft.getValue = (): number => { - if (this.deviceId === -1) { - if (USE_XR) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); - if (webxrGamepad) { - if (webxrGamepad.axes.length > XR_AXIS_STICK_X && webxrGamepad.axes[XR_AXIS_STICK_X] !== 0) { - return this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_X]).negative; - } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_X && webxrGamepad.axes[XR_AXIS_TOUCHPAD_X] !== 0) { - return this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_X]).negative; - } - } - } - return 0; - } - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { - return this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_X]).negative; - } - return 0; - }; - const leftStickRight = new InputSourceButton(); - leftStickRight.getValue = (): number => { - if (this.deviceId === -1) { - if (USE_XR) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); - if (webxrGamepad) { - if (webxrGamepad.axes.length > XR_AXIS_STICK_X && webxrGamepad.axes[XR_AXIS_STICK_X] !== 0) { - return this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_X]).positive; - } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_X && webxrGamepad.axes[XR_AXIS_TOUCHPAD_X] !== 0) { - return this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_X]).positive; - } - } - } - return 0; - } - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { - return this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_X]).positive; - } - return 0; - }; - this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); - - const rightStickUp = new InputSourceButton(); - rightStickUp.getValue = (): number => { - if (this.deviceId === -1) { - if (USE_XR) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); - if (webxrGamepad) { - if (webxrGamepad.axes.length > XR_AXIS_STICK_Y && webxrGamepad.axes[XR_AXIS_STICK_Y] !== 0) { - return this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_Y]).negative; - } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_Y && webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y] !== 0) { - return this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y]).negative; - } - } - } - return 0; - } - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { - return this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_Y]).negative; - } - return 0; - }; - const rightStickDown = new InputSourceButton(); - rightStickDown.getValue = (): number => { - if (this.deviceId === -1) { - if (USE_XR) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); - if (webxrGamepad) { - if (webxrGamepad.axes.length > XR_AXIS_STICK_Y && webxrGamepad.axes[XR_AXIS_STICK_Y] !== 0) { - return this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_Y]).positive; - } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_Y && webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y] !== 0) { - return this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y]).positive; - } - } - } - return 0; - } - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { - return this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_Y]).positive; - } - return 0; - }; - const rightStickLeft = new InputSourceButton(); - rightStickLeft.getValue = (): number => { - if (this.deviceId === -1) { - if (USE_XR) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); - if (webxrGamepad) { - if (webxrGamepad.axes.length > XR_AXIS_STICK_X && webxrGamepad.axes[XR_AXIS_STICK_X] !== 0) { - return this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_X]).negative; - } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_X && webxrGamepad.axes[XR_AXIS_TOUCHPAD_X] !== 0) { - return this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_X]).negative; - } - } - } - return 0; - } - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { - return this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_X]).negative; - } - return 0; - }; - const rightStickRight = new InputSourceButton(); - rightStickRight.getValue = (): number => { - if (this.deviceId === -1) { - if (USE_XR) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); - if (webxrGamepad) { - if (webxrGamepad.axes.length > XR_AXIS_STICK_X && webxrGamepad.axes[XR_AXIS_STICK_X] !== 0) { - return this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_X]).positive; - } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_X && webxrGamepad.axes[XR_AXIS_TOUCHPAD_X] !== 0) { - return this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_X]).positive; - } - } - } - return 0; - } - const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); - if (webGamepad) { - return this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_X]).positive; - } - return 0; - }; - this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); - - this._buttonStart = new InputSourceButton(); - this._buttonStart.getValue = (): number => 0; - - this._gripLeft = new InputSourceButton(); - this._gripLeft.getValue = (): number => { - if (this.deviceId === -1) { - if (USE_XR) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness); - if (webxrGamepad && webxrGamepad.buttons.length > XR_GRIP) { - return webxrGamepad.buttons[XR_GRIP].value; - } - } - } - return 0; - }; - this._gripRight = new InputSourceButton(); - this._gripRight.getValue = (): number => { - if (this.deviceId === -1) { - const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness); - if (webxrGamepad && webxrGamepad.buttons.length > XR_GRIP) { - return webxrGamepad.buttons[XR_GRIP].value; - } - } - return 0; - }; - - this._handLeftPosition = new InputSourcePosition(); - this._handLeftPosition.getValue = (): Vec3 => this._webPoseState[Pose.HAND_LEFT].position; - this._handLeftOrientation = new InputSourceOrientation(); - this._handLeftOrientation.getValue = (): Quat => this._webPoseState[Pose.HAND_LEFT].orientation; - - this._handRightPosition = new InputSourcePosition(); - this._handRightPosition.getValue = (): Vec3 => this._webPoseState[Pose.HAND_RIGHT].position; - this._handRightOrientation = new InputSourceOrientation(); - this._handRightOrientation.getValue = (): Quat => this._webPoseState[Pose.HAND_RIGHT].orientation; - - this._aimLeftPosition = new InputSourcePosition(); - this._aimLeftPosition.getValue = (): Vec3 => this._webPoseState[Pose.AIM_LEFT].position; - this._aimLeftOrientation = new InputSourceOrientation(); - this._aimLeftOrientation.getValue = (): Quat => this._webPoseState[Pose.AIM_LEFT].orientation; - - this._aimRightPosition = new InputSourcePosition(); - this._aimRightPosition.getValue = (): Vec3 => this._webPoseState[Pose.AIM_RIGHT].position; - this._aimRightOrientation = new InputSourceOrientation(); - this._aimRightOrientation.getValue = (): Quat => this._webPoseState[Pose.AIM_RIGHT].orientation; - } -} diff --git a/pal/input/web/handheld-input.ts b/pal/input/web/handheld-input.ts deleted file mode 100644 index e4d2f4e781..0000000000 --- a/pal/input/web/handheld-input.ts +++ /dev/null @@ -1,57 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated 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 { HandheldCallback } from 'pal/input'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { InputSourcePosition, InputSourceOrientation } from '../input-source'; -import { Vec3, Quat } from '../../../cocos/core/math'; - -export class HandheldInputDevice { - public get handheldPosition (): InputSourcePosition { return this._handheldPosition; } - public get handheldOrientation (): InputSourceOrientation { return this._handheldOrientation; } - - private _eventTarget: EventTarget = new EventTarget(); - - private declare _handheldPosition: InputSourcePosition; - private declare _handheldOrientation: InputSourceOrientation; - - constructor () { - this._initInputSource(); - } - - /** - * @engineInternal - */ - public _on (eventType: InputEventType, callback: HandheldCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - - private _initInputSource (): void { - this._handheldPosition = new InputSourcePosition(); - this._handheldPosition.getValue = (): Readonly => Vec3.ZERO; - this._handheldOrientation = new InputSourceOrientation(); - this._handheldOrientation.getValue = (): Readonly => Quat.IDENTITY; - } -} diff --git a/pal/input/web/handle-input.ts b/pal/input/web/handle-input.ts deleted file mode 100644 index f7b879a548..0000000000 --- a/pal/input/web/handle-input.ts +++ /dev/null @@ -1,433 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { HandleCallback } from 'pal/input'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { EventTarget } from '../../../cocos/core/event'; -import { EventHandle } from '../../../cocos/input/types'; -import { InputSourceButton, InputSourceStick, InputSourcePosition, InputSourceOrientation, InputSourceTouch } from '../input-source'; -import { Vec3, Quat } from '../../../cocos/core/math'; - -enum Button { - BUTTON_EAST, - BUTTON_SOUTH, - BUTTON_WEST, - BUTTON_NORTH, - BUTTON_TRIGGER_LEFT, - BUTTON_TRIGGER_RIGHT, - TRIGGER_LEFT, - TRIGGER_RIGHT, - GRIP_LEFT, - GRIP_RIGHT, - BUTTON_LEFT_STICK, - LEFT_STICK_UP, - LEFT_STICK_DOWN, - LEFT_STICK_LEFT, - LEFT_STICK_RIGHT, - BUTTON_RIGHT_STICK, - RIGHT_STICK_UP, - RIGHT_STICK_DOWN, - RIGHT_STICK_LEFT, - RIGHT_STICK_RIGHT, - ROKID_MENU, - ROKID_START, -} - -export enum KeyEventType { - KET_CLICK, - KET_STICK, - KET_GRAB, - KET_TOUCH, -} - -enum StickKeyCode { - UNDEFINE = 0, - A, - B, - X, - Y, - L1, - R1, - MINUS, - PLUS, - L3, - R3, - MENU, - START, - TRIGGER_LEFT, - TRIGGER_RIGHT, -} - -enum StickAxisCode { - UNDEFINE = 0, - X, - Y, - LEFT_STICK_X, - LEFT_STICK_Y, - RIGHT_STICK_X, - RIGHT_STICK_Y, - L2, - R2, - LEFT_GRIP, - RIGHT_GRIP, -} - -enum StickTouchCode { - UNDEFINE = 0, - A, - B, - X, - Y, - LEFT_TRIGGER, - RIGHT_TRIGGER, - LEFT_THUMBSTICK, - RIGHT_THUMBSTICK, -} - -const _nativeButtonMap = { - 1: Button.BUTTON_EAST, - 2: Button.BUTTON_SOUTH, - 3: Button.BUTTON_NORTH, - 4: Button.BUTTON_WEST, - 9: Button.BUTTON_LEFT_STICK, - 10: Button.BUTTON_RIGHT_STICK, - 11: Button.ROKID_MENU, - 12: Button.ROKID_START, - 13: Button.BUTTON_TRIGGER_LEFT, - 14: Button.BUTTON_TRIGGER_RIGHT, -}; - -interface IAxisValue { - negative: number; - positive: number; -} - -type NativeButtonState = Record -type NativeTouchState = Record - -export class HandleInputDevice { - public get buttonNorth (): InputSourceButton { return this._buttonNorth; } - public get buttonEast (): InputSourceButton { return this._buttonEast; } - public get buttonWest (): InputSourceButton { return this._buttonWest; } - public get buttonSouth (): InputSourceButton { return this._buttonSouth; } - public get buttonTriggerLeft (): InputSourceButton { return this._buttonTriggerLeft; } - public get buttonTriggerRight (): InputSourceButton { return this._buttonTriggerRight; } - public get triggerLeft (): InputSourceButton { return this._triggerLeft; } - public get triggerRight (): InputSourceButton { return this._triggerRight; } - public get gripLeft (): InputSourceButton { return this._gripLeft; } - public get gripRight (): InputSourceButton { return this._gripRight; } - public get leftStick (): InputSourceStick { return this._leftStick; } - public get rightStick (): InputSourceStick { return this._rightStick; } - public get buttonLeftStick (): InputSourceButton { return this._buttonLeftStick; } - public get buttonRightStick (): InputSourceButton { return this._buttonRightStick; } - public get buttonOptions (): InputSourceButton { return this._buttonOptions; } - public get buttonStart (): InputSourceButton { return this._buttonStart; } - public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; } - public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; } - public get handRightPosition (): InputSourcePosition { return this._handRightPosition; } - public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; } - public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; } - public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; } - public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; } - public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; } - public get touchButtonA (): InputSourceTouch { return this._touchButtonA; } - public get touchButtonB (): InputSourceTouch { return this._touchButtonB; } - public get touchButtonX (): InputSourceTouch { return this._touchButtonX; } - public get touchButtonY (): InputSourceTouch { return this._touchButtonY; } - public get touchButtonTriggerLeft (): InputSourceTouch { return this._touchButtonTriggerLeft; } - public get touchButtonTriggerRight (): InputSourceTouch { return this._touchButtonTriggerRight; } - public get touchButtonThumbStickLeft (): InputSourceTouch { return this._touchButtonThumbStickLeft; } - public get touchButtonThumbStickRight (): InputSourceTouch { return this._touchButtonThumbStickRight; } - - private _eventTarget: EventTarget = new EventTarget(); - - private declare _buttonNorth: InputSourceButton; - private declare _buttonEast: InputSourceButton; - private declare _buttonWest: InputSourceButton; - private declare _buttonSouth: InputSourceButton; - private declare _buttonTriggerLeft: InputSourceButton; - private declare _buttonTriggerRight: InputSourceButton; - private declare _triggerLeft: InputSourceButton; - private declare _triggerRight: InputSourceButton; - private declare _gripLeft: InputSourceButton; - private declare _gripRight: InputSourceButton; - private declare _leftStick: InputSourceStick; - private declare _rightStick: InputSourceStick; - private declare _buttonLeftStick: InputSourceButton; - private declare _buttonRightStick: InputSourceButton; - private declare _buttonOptions: InputSourceButton; - private declare _buttonStart: InputSourceButton; - private declare _handLeftPosition: InputSourcePosition; - private declare _handLeftOrientation: InputSourceOrientation; - private declare _handRightPosition: InputSourcePosition; - private declare _handRightOrientation: InputSourceOrientation; - private declare _aimLeftPosition: InputSourcePosition; - private declare _aimLeftOrientation: InputSourceOrientation; - private declare _aimRightPosition: InputSourcePosition; - private declare _aimRightOrientation: InputSourceOrientation; - private declare _touchButtonA: InputSourceTouch; - private declare _touchButtonB: InputSourceTouch; - private declare _touchButtonX: InputSourceTouch; - private declare _touchButtonY: InputSourceTouch; - private declare _touchButtonTriggerLeft: InputSourceTouch; - private declare _touchButtonTriggerRight: InputSourceTouch; - private declare _touchButtonThumbStickLeft: InputSourceTouch; - private declare _touchButtonThumbStickRight: InputSourceTouch; - - private _nativeButtonState: NativeButtonState = { - [Button.BUTTON_SOUTH]: 0, - [Button.BUTTON_EAST]: 0, - [Button.BUTTON_WEST]: 0, - [Button.BUTTON_NORTH]: 0, - [Button.BUTTON_TRIGGER_LEFT]: 0, - [Button.BUTTON_TRIGGER_RIGHT]: 0, - [Button.TRIGGER_LEFT]: 0, - [Button.TRIGGER_RIGHT]: 0, - [Button.GRIP_LEFT]: 0, - [Button.GRIP_RIGHT]: 0, - [Button.LEFT_STICK_UP]: 0, - [Button.LEFT_STICK_DOWN]: 0, - [Button.LEFT_STICK_LEFT]: 0, - [Button.LEFT_STICK_RIGHT]: 0, - [Button.RIGHT_STICK_UP]: 0, - [Button.RIGHT_STICK_DOWN]: 0, - [Button.RIGHT_STICK_LEFT]: 0, - [Button.RIGHT_STICK_RIGHT]: 0, - [Button.BUTTON_LEFT_STICK]: 0, - [Button.BUTTON_RIGHT_STICK]: 0, - [Button.ROKID_MENU]: 0, - [Button.ROKID_START]: 0, - }; - - private _nativeTouchState: NativeTouchState = { - [StickTouchCode.UNDEFINE]: 0, - [StickTouchCode.A]: 0, - [StickTouchCode.B]: 0, - [StickTouchCode.X]: 0, - [StickTouchCode.Y]: 0, - [StickTouchCode.LEFT_TRIGGER]: 0, - [StickTouchCode.RIGHT_TRIGGER]: 0, - [StickTouchCode.LEFT_THUMBSTICK]: 0, - [StickTouchCode.RIGHT_THUMBSTICK]: 0, - }; - - constructor () { - this._initInputSource(); - window.addEventListener('xr-remote-input', (evt: Event): void => { - const remoteInputEvent: CustomEvent = evt as CustomEvent; - const keyEventType: KeyEventType = remoteInputEvent.detail.keyEventType; - const stickAxisCode = remoteInputEvent.detail.stickAxisCode as StickAxisCode; - const stickAxisValue = remoteInputEvent.detail.stickAxisValue as number; - const stickKeyCode = remoteInputEvent.detail.stickKeyCode; - const isButtonPressed = remoteInputEvent.detail.isButtonPressed; - const touchCode = remoteInputEvent.detail.touchCode as StickTouchCode; - const touchValue = remoteInputEvent.detail.touchValue as number; - - if (keyEventType === KeyEventType.KET_CLICK) { - const button = _nativeButtonMap[stickKeyCode]; - this._nativeButtonState[button] = isButtonPressed ? 1 : 0; - } else if (keyEventType === KeyEventType.KET_STICK || keyEventType === KeyEventType.KET_GRAB) { - // - let negativeButton: Button|undefined; - let positiveButton: Button|undefined; - let axisValue: IAxisValue|undefined; - switch (stickAxisCode) { - case StickAxisCode.LEFT_STICK_X: - negativeButton = Button.LEFT_STICK_LEFT; - positiveButton = Button.LEFT_STICK_RIGHT; - axisValue = this._axisToButtons(stickAxisValue); - break; - case StickAxisCode.LEFT_STICK_Y: - negativeButton = Button.LEFT_STICK_DOWN; - positiveButton = Button.LEFT_STICK_UP; - axisValue = this._axisToButtons(stickAxisValue); - break; - case StickAxisCode.RIGHT_STICK_X: - negativeButton = Button.RIGHT_STICK_LEFT; - positiveButton = Button.RIGHT_STICK_RIGHT; - axisValue = this._axisToButtons(stickAxisValue); - break; - case StickAxisCode.RIGHT_STICK_Y: - negativeButton = Button.RIGHT_STICK_DOWN; - positiveButton = Button.RIGHT_STICK_UP; - axisValue = this._axisToButtons(stickAxisValue); - break; - case StickAxisCode.L2: - this._nativeButtonState[Button.TRIGGER_LEFT] = stickAxisValue; - break; - case StickAxisCode.R2: - this._nativeButtonState[Button.TRIGGER_RIGHT] = stickAxisValue; - break; - case StickAxisCode.LEFT_GRIP: - this._nativeButtonState[Button.GRIP_LEFT] = stickAxisValue; - break; - case StickAxisCode.RIGHT_GRIP: - this._nativeButtonState[Button.GRIP_RIGHT] = stickAxisValue; - break; - default: - break; - } - - if (negativeButton && positiveButton && axisValue) { - this._nativeButtonState[negativeButton] = axisValue.negative; - this._nativeButtonState[positiveButton] = axisValue.positive; - } - } else if (keyEventType === KeyEventType.KET_TOUCH) { - switch (touchCode) { - case StickTouchCode.A: - case StickTouchCode.B: - case StickTouchCode.X: - case StickTouchCode.Y: - case StickTouchCode.LEFT_TRIGGER: - case StickTouchCode.RIGHT_TRIGGER: - case StickTouchCode.LEFT_THUMBSTICK: - case StickTouchCode.RIGHT_THUMBSTICK: - this._nativeTouchState[touchCode] = touchValue; - break; - default: - break; - } - } - - this._eventTarget.emit(InputEventType.HANDLE_INPUT, new EventHandle(InputEventType.HANDLE_INPUT, this)); - }); - } - - private _axisToButtons (axisValue: number): IAxisValue { - const value = Math.abs(axisValue); - if (axisValue > 0) { - return { negative: 0, positive: value }; - } else if (axisValue < 0) { - return { negative: value, positive: 0 }; - } else { - return { negative: 0, positive: 0 }; - } - } - - /** - * @engineInternal - */ - public _on (eventType: InputEventType, callback: HandleCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - - private _initInputSource (): void { - this._buttonNorth = new InputSourceButton(); - this._buttonNorth.getValue = (): number => this._nativeButtonState[Button.BUTTON_NORTH]; - this._buttonEast = new InputSourceButton(); - this._buttonEast.getValue = (): number => this._nativeButtonState[Button.BUTTON_EAST]; - this._buttonWest = new InputSourceButton(); - this._buttonWest.getValue = (): number => this._nativeButtonState[Button.BUTTON_WEST]; - this._buttonSouth = new InputSourceButton(); - this._buttonSouth.getValue = (): number => this._nativeButtonState[Button.BUTTON_SOUTH]; - - this._buttonTriggerLeft = new InputSourceButton(); - this._buttonTriggerLeft.getValue = (): number => this._nativeButtonState[Button.BUTTON_TRIGGER_LEFT]; - this._buttonTriggerRight = new InputSourceButton(); - this._buttonTriggerRight.getValue = (): number => this._nativeButtonState[Button.BUTTON_TRIGGER_RIGHT]; - this._triggerLeft = new InputSourceButton(); - this._triggerLeft.getValue = (): number => this._nativeButtonState[Button.TRIGGER_LEFT]; - this._triggerRight = new InputSourceButton(); - this._triggerRight.getValue = (): number => this._nativeButtonState[Button.TRIGGER_RIGHT]; - this._gripLeft = new InputSourceButton(); - this._gripLeft.getValue = (): number => this._nativeButtonState[Button.GRIP_LEFT]; - this._gripRight = new InputSourceButton(); - this._gripRight.getValue = (): number => this._nativeButtonState[Button.GRIP_RIGHT]; - - this._buttonLeftStick = new InputSourceButton(); - this._buttonLeftStick.getValue = (): number => this._nativeButtonState[Button.BUTTON_LEFT_STICK]; - const leftStickUp = new InputSourceButton(); - leftStickUp.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_UP]; - const leftStickDown = new InputSourceButton(); - leftStickDown.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_DOWN]; - const leftStickLeft = new InputSourceButton(); - leftStickLeft.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_LEFT]; - const leftStickRight = new InputSourceButton(); - leftStickRight.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_RIGHT]; - this._leftStick = new InputSourceStick({ - up: leftStickUp, - down: leftStickDown, - left: leftStickLeft, - right: leftStickRight, - }); - - this._buttonRightStick = new InputSourceButton(); - this._buttonRightStick.getValue = (): number => this._nativeButtonState[Button.BUTTON_RIGHT_STICK]; - const rightStickUp = new InputSourceButton(); - rightStickUp.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_UP]; - const rightStickDown = new InputSourceButton(); - rightStickDown.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_DOWN]; - const rightStickLeft = new InputSourceButton(); - rightStickLeft.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_LEFT]; - const rightStickRight = new InputSourceButton(); - rightStickRight.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_RIGHT]; - this._rightStick = new InputSourceStick({ - up: rightStickUp, - down: rightStickDown, - left: rightStickLeft, - right: rightStickRight, - }); - - this._buttonOptions = new InputSourceButton(); - this._buttonOptions.getValue = (): number => this._nativeButtonState[Button.ROKID_MENU]; - this._buttonStart = new InputSourceButton(); - this._buttonStart.getValue = (): number => this._nativeButtonState[Button.ROKID_START]; - - this._handLeftPosition = new InputSourcePosition(); - this._handLeftPosition.getValue = (): Readonly => Vec3.ZERO; - this._handLeftOrientation = new InputSourceOrientation(); - this._handLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; - - this._handRightPosition = new InputSourcePosition(); - this._handRightPosition.getValue = (): Readonly => Vec3.ZERO; - this._handRightOrientation = new InputSourceOrientation(); - this._handRightOrientation.getValue = (): Readonly => Quat.IDENTITY; - - this._aimLeftPosition = new InputSourcePosition(); - this._aimLeftPosition.getValue = (): Readonly => Vec3.ZERO; - this._aimLeftOrientation = new InputSourceOrientation(); - this._aimLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; - - this._aimRightPosition = new InputSourcePosition(); - this._aimRightPosition.getValue = (): Readonly => Vec3.ZERO; - this._aimRightOrientation = new InputSourceOrientation(); - this._aimRightOrientation.getValue = (): Readonly => Quat.IDENTITY; - this._touchButtonA = new InputSourceTouch(); - this._touchButtonA.getValue = (): number => this._nativeTouchState[StickTouchCode.A]; - this._touchButtonB = new InputSourceTouch(); - this._touchButtonB.getValue = (): number => this._nativeTouchState[StickTouchCode.B]; - this._touchButtonX = new InputSourceTouch(); - this._touchButtonX.getValue = (): number => this._nativeTouchState[StickTouchCode.X]; - this._touchButtonY = new InputSourceTouch(); - this._touchButtonY.getValue = (): number => this._nativeTouchState[StickTouchCode.Y]; - this._touchButtonTriggerLeft = new InputSourceTouch(); - this._touchButtonTriggerLeft.getValue = (): number => this._nativeTouchState[StickTouchCode.LEFT_TRIGGER]; - this._touchButtonTriggerRight = new InputSourceTouch(); - this._touchButtonTriggerRight.getValue = (): number => this._nativeTouchState[StickTouchCode.RIGHT_TRIGGER]; - this._touchButtonThumbStickLeft = new InputSourceTouch(); - this._touchButtonThumbStickLeft.getValue = (): number => this._nativeTouchState[StickTouchCode.LEFT_THUMBSTICK]; - this._touchButtonThumbStickRight = new InputSourceTouch(); - this._touchButtonThumbStickRight.getValue = (): number => this._nativeTouchState[StickTouchCode.RIGHT_THUMBSTICK]; - } -} diff --git a/pal/input/web/hmd-input.ts b/pal/input/web/hmd-input.ts deleted file mode 100644 index 0feb2fb2a5..0000000000 --- a/pal/input/web/hmd-input.ts +++ /dev/null @@ -1,146 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { HMDCallback } from 'pal/input'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { EventHMD } from '../../../cocos/input/types'; -import { InputSourcePosition, InputSourceOrientation } from '../input-source'; -import { Vec3, Quat } from '../../../cocos/core/math'; -import legacyCC from '../../../predefine'; - -enum Pose { - VIEW_LEFT = 0, - VIEW_RIGHT = 3, - HEAD_MIDDLE = 6, -} - -interface IPoseValue { - position: Vec3; - orientation: Quat; -} - -interface IPoseInfo { - readonly code: number; - readonly position: DOMPointReadOnly; - readonly orientation: DOMPointReadOnly; -} - -type WebPoseState = Record - -export class HMDInputDevice { - public get viewLeftPosition (): InputSourcePosition { return this._viewLeftPosition; } - public get viewLeftOrientation (): InputSourceOrientation { return this._viewLeftOrientation; } - public get viewRightPosition (): InputSourcePosition { return this._viewRightPosition; } - public get viewRightOrientation (): InputSourceOrientation { return this._viewRightOrientation; } - public get headMiddlePosition (): InputSourcePosition { return this._headMiddlePosition; } - public get headMiddleOrientation (): InputSourceOrientation { return this._headMiddleOrientation; } - - private _eventTarget: EventTarget = new EventTarget(); - private _intervalId = -1; - - private declare _viewLeftPosition: InputSourcePosition; - private declare _viewLeftOrientation: InputSourceOrientation; - private declare _viewRightPosition: InputSourcePosition; - private declare _viewRightOrientation: InputSourceOrientation; - private declare _headMiddlePosition: InputSourcePosition; - private declare _headMiddleOrientation: InputSourceOrientation; - - private _webPoseState: WebPoseState = { - [Pose.VIEW_LEFT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, - [Pose.VIEW_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, - [Pose.HEAD_MIDDLE]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, - }; - - constructor () { - this._initInputSource(); - this._registerEvent(); - } - - private _ensureDirectorDefined (): Promise { - return new Promise((resolve) => { - this._intervalId = setInterval(() => { - if (legacyCC.director && legacyCC.Director) { - clearInterval(this._intervalId); - this._intervalId = -1; - resolve(); - } - }, 50); - }); - } - - private _registerEvent (): void { - this._ensureDirectorDefined().then(() => { - legacyCC.director.on(legacyCC.Director.EVENT_BEGIN_FRAME, this._scanHmd, this); - }).catch((e) => {}); - } - - private _scanHmd (): void { - const infoList = globalThis.__globalXR?.webxrHmdPoseInfos as IPoseInfo[]; - if (!infoList) { - return; - } - - for (let i = 0; i < infoList.length; ++i) { - const info = infoList[i]; - this._updateWebPoseState(info); - } - this._eventTarget.emit(InputEventType.HMD_POSE_INPUT, new EventHMD(InputEventType.HMD_POSE_INPUT, this)); - } - - /** - * @engineInternal - */ - public _on (eventType: InputEventType, callback: HMDCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - - private _updateWebPoseState (info: IPoseInfo): void { - if (info.code !== Pose.VIEW_LEFT && info.code !== Pose.VIEW_RIGHT && info.code !== Pose.HEAD_MIDDLE) { - return; - } - - this._webPoseState[info.code] = { - position: new Vec3(info.position.x, info.position.y, info.position.z), - orientation: new Quat(info.orientation.x, info.orientation.y, info.orientation.z, info.orientation.w), - }; - } - - private _initInputSource (): void { - this._viewLeftPosition = new InputSourcePosition(); - this._viewLeftPosition.getValue = (): Vec3 => this._webPoseState[Pose.VIEW_LEFT].position; - this._viewLeftOrientation = new InputSourceOrientation(); - this._viewLeftOrientation.getValue = (): Quat => this._webPoseState[Pose.VIEW_LEFT].orientation; - - this._viewRightPosition = new InputSourcePosition(); - this._viewRightPosition.getValue = (): Vec3 => this._webPoseState[Pose.VIEW_RIGHT].position; - this._viewRightOrientation = new InputSourceOrientation(); - this._viewRightOrientation.getValue = (): Quat => this._webPoseState[Pose.VIEW_RIGHT].orientation; - - this._headMiddlePosition = new InputSourcePosition(); - this._headMiddlePosition.getValue = (): Vec3 => this._webPoseState[Pose.HEAD_MIDDLE].position; - this._headMiddleOrientation = new InputSourceOrientation(); - this._headMiddleOrientation.getValue = (): Quat => this._webPoseState[Pose.HEAD_MIDDLE].orientation; - } -} diff --git a/pal/input/web/index.ts b/pal/input/web/index.ts deleted file mode 100644 index a30638e368..0000000000 --- a/pal/input/web/index.ts +++ /dev/null @@ -1,36 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { checkPalIntegrity, withImpl } from '../../integrity-check'; - -export * from './accelerometer-input'; -export * from './gamepad-input'; -export * from './handle-input'; -export * from './hmd-input'; -export * from './handheld-input'; -export * from './keyboard-input'; -export * from './mouse-input'; -export * from './touch-input'; - -checkPalIntegrity(withImpl()); diff --git a/pal/input/web/keyboard-input.ts b/pal/input/web/keyboard-input.ts deleted file mode 100644 index b69c763af0..0000000000 --- a/pal/input/web/keyboard-input.ts +++ /dev/null @@ -1,79 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { KeyboardCallback } from 'pal/input'; -import { KeyCode, EventKeyboard } from '../../../cocos/input/types'; -import { EventTarget } from '../../../cocos/core/event'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { code2KeyCode } from '../keycodes'; - -function getKeyCode (code: string): KeyCode { - return code2KeyCode[code] || KeyCode.NONE; -} - -export class KeyboardInputSource { - private _eventTarget: EventTarget = new EventTarget(); - - constructor () { - this._registerEvent(); - } - - public dispatchKeyboardDownEvent (nativeKeyboardEvent: KeyboardEvent): void { this._handleKeyboardDown(nativeKeyboardEvent); } - public dispatchKeyboardUpEvent (nativeKeyboardEvent: KeyboardEvent): void { this._handleKeyboardUp(nativeKeyboardEvent); } - - public on (eventType: InputEventType, callback: KeyboardCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - - private _registerEvent (): void { - const canvas = document.getElementById('GameCanvas') as HTMLCanvasElement; - canvas?.addEventListener('keydown', this._handleKeyboardDown.bind(this)); - canvas?.addEventListener('keyup', this._handleKeyboardUp.bind(this)); - } - - private _getInputEvent (event: any, eventType: InputEventType): EventKeyboard { - const keyCode = getKeyCode(event.code); - const eventKeyboard = new EventKeyboard(keyCode, eventType); - return eventKeyboard; - } - - private _handleKeyboardDown (event: KeyboardEvent): void { - event.stopPropagation(); - event.preventDefault(); - if (!event.repeat) { - const keyDownInputEvent = this._getInputEvent(event, InputEventType.KEY_DOWN); - this._eventTarget.emit(InputEventType.KEY_DOWN, keyDownInputEvent); - } else { - const keyPressingInputEvent = this._getInputEvent(event, InputEventType.KEY_PRESSING); - this._eventTarget.emit(InputEventType.KEY_PRESSING, keyPressingInputEvent); - } - } - - private _handleKeyboardUp (event: KeyboardEvent): void { - const inputEvent = this._getInputEvent(event, InputEventType.KEY_UP); - event.stopPropagation(); - event.preventDefault(); - this._eventTarget.emit(InputEventType.KEY_UP, inputEvent); - } -} diff --git a/pal/input/web/mouse-input.ts b/pal/input/web/mouse-input.ts deleted file mode 100644 index d204c99fc2..0000000000 --- a/pal/input/web/mouse-input.ts +++ /dev/null @@ -1,216 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { EDITOR, TEST } from 'internal:constants'; -import { MouseCallback } from 'pal/input'; -import { systemInfo } from 'pal/system-info'; -import { screenAdapter } from 'pal/screen-adapter'; -import { EventMouse } from '../../../cocos/input/types'; -import { EventTarget } from '../../../cocos/core/event'; -import { Rect, Vec2 } from '../../../cocos/core/math'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { Feature } from '../../system-info/enum-type'; -import { warn } from '../../../cocos/core/platform/debug'; - -export class MouseInputSource { - private _canvas?: HTMLCanvasElement; - private _eventTarget: EventTarget = new EventTarget(); - private _pointLocked = false; - private _isPressed = false; - private _preMousePos: Vec2 = new Vec2(); - - private _handleMouseDown!: (event: MouseEvent) => void; - private _handleMouseMove!: (event: MouseEvent) => void; - private _handleMouseUp!: (event: MouseEvent) => void; - - constructor () { - if (systemInfo.hasFeature(Feature.EVENT_MOUSE)) { - this._canvas = document.getElementById('GameCanvas') as HTMLCanvasElement; - if (!this._canvas && !TEST && !EDITOR) { - warn('failed to access canvas'); - } - - this._handleMouseDown = this._createCallback(InputEventType.MOUSE_DOWN); - this._handleMouseMove = this._createCallback(InputEventType.MOUSE_MOVE); - this._handleMouseUp = this._createCallback(InputEventType.MOUSE_UP); - // In Editor, we receive mouse event from manually event dispatching. - if (!EDITOR) { - this._registerEvent(); - } - } - } - - public dispatchMouseDownEvent (nativeMouseEvent: any): void { this._handleMouseDown(nativeMouseEvent as MouseEvent); } - public dispatchMouseMoveEvent (nativeMouseEvent: any): void { this._handleMouseMove(nativeMouseEvent as MouseEvent); } - public dispatchMouseUpEvent (nativeMouseEvent: any): void { this._handleMouseUp(nativeMouseEvent as MouseEvent); } - public dispatchScrollEvent (nativeMouseEvent: WheelEvent): void { this._handleMouseWheel(nativeMouseEvent); } - - public on (eventType: InputEventType, callback: MouseCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - - private _getCanvasRect (): Rect { - const canvas = this._canvas; - const box = canvas?.getBoundingClientRect(); - if (box) { - return new Rect(box.x, box.y, box.width, box.height); - } - return new Rect(0, 0, 0, 0); - } - - private _getLocation (mouseEvent: MouseEvent): Vec2 { - const canvasRect = this._getCanvasRect(); - const dpr = screenAdapter.devicePixelRatio; - let x = this._pointLocked ? (this._preMousePos.x / dpr + mouseEvent.movementX) : (mouseEvent.clientX - canvasRect.x); - let y = this._pointLocked ? (this._preMousePos.y / dpr - mouseEvent.movementY) : (canvasRect.y + canvasRect.height - mouseEvent.clientY); - x *= dpr; - y *= dpr; - return new Vec2(x, y); - } - - private _registerEvent (): void { - // register mouse down event - window.addEventListener('mousedown', () => { - this._isPressed = true; - }); - this._canvas?.addEventListener('mousedown', this._handleMouseDown); - - // register mouse move event - this._canvas?.addEventListener('mousemove', this._handleMouseMove); - - // register mouse up event - window.addEventListener('mouseup', this._handleMouseUp); - this._canvas?.addEventListener('mouseup', this._handleMouseUp); - - // register wheel event - this._canvas?.addEventListener('wheel', this._handleMouseWheel.bind(this)); - this._registerPointerLockEvent(); - - this._canvas?.addEventListener('mouseleave', this._handleMouseLeave.bind(this)); - this._canvas?.addEventListener('mouseenter', this._handleMouseEnter.bind(this)); - } - - // To be removed in the future. - private _registerPointerLockEvent (): void { - const lockChangeAlert = (): void => { - const canvas = this._canvas; - // NOTE: mozPointerLockElement is not a standard web interface - if (document.pointerLockElement === canvas || (document as any).mozPointerLockElement === canvas) { - this._pointLocked = true; - } else { - this._pointLocked = false; - } - }; - if ('onpointerlockchange' in document) { - document.addEventListener('pointerlockchange', lockChangeAlert, false); - } else if ('onmozpointerlockchange' in document) { - // NOTE: handle event compatibility - (document as any).addEventListener('mozpointerlockchange', lockChangeAlert, false); - } - } - - private _createCallback (eventType: InputEventType) { - return (mouseEvent: MouseEvent): void => { - const location = this._getLocation(mouseEvent); - const { button, buttons } = mouseEvent; - let targetButton = button; - switch (eventType) { - case InputEventType.MOUSE_DOWN: - this._canvas?.focus(); - this._isPressed = true; - break; - case InputEventType.MOUSE_UP: - this._isPressed = false; - break; - case InputEventType.MOUSE_MOVE: - // mouseEvent.button doesn't work well in mouse move event - // now we don't support multiple buttons in one mouse event - if (1 & buttons) { - targetButton = EventMouse.BUTTON_LEFT; - } else if (2 & buttons) { - targetButton = EventMouse.BUTTON_RIGHT; - } else if (4 & buttons) { - targetButton = EventMouse.BUTTON_MIDDLE; - } else { - targetButton = EventMouse.BUTTON_MISSING; - } - break; - default: - break; - } - - const eventMouse = new EventMouse(eventType, false, this._preMousePos); - eventMouse.setLocation(location.x, location.y); - eventMouse.setButton(targetButton); - eventMouse.movementX = mouseEvent.movementX; - eventMouse.movementY = mouseEvent.movementY; - - // update previous mouse position. - this._preMousePos.set(location.x, location.y); - mouseEvent.stopPropagation(); - if (mouseEvent.target === this._canvas) { - mouseEvent.preventDefault(); - } - this._eventTarget.emit(eventType, eventMouse); - }; - } - - private _handleMouseWheel (mouseEvent: WheelEvent): void { - const eventType = InputEventType.MOUSE_WHEEL; - const location = this._getLocation(mouseEvent); - const button = mouseEvent.button; - - const eventMouse = new EventMouse(eventType, false, this._preMousePos); - eventMouse.setLocation(location.x, location.y); - eventMouse.setButton(button); - eventMouse.movementX = mouseEvent.movementX; - eventMouse.movementY = mouseEvent.movementY; - - const wheelSensitivityFactor = 5; - eventMouse.setScrollData(mouseEvent.deltaX * wheelSensitivityFactor, -mouseEvent.deltaY * wheelSensitivityFactor); - // update previous mouse position. - this._preMousePos.set(location.x, location.y); - mouseEvent.stopPropagation(); - if (mouseEvent.target === this._canvas) { - mouseEvent.preventDefault(); - } - this._eventTarget.emit(eventType, eventMouse); - } - - private _handleMouseLeave (mouseEvent: MouseEvent): void { - const eventType = InputEventType.MOUSE_LEAVE; - const eventMouse = new EventMouse(eventType, false); - this._eventTarget.emit(eventType, eventMouse); - } - - private _handleMouseEnter (mouseEvent: MouseEvent): void { - const eventType = InputEventType.MOUSE_ENTER; - const eventMouse = new EventMouse(eventType, false); - this._eventTarget.emit(eventType, eventMouse); - } - - public dispatchEventsInCache (): void { - // Do nothing - } -} diff --git a/pal/input/web/touch-input.ts b/pal/input/web/touch-input.ts deleted file mode 100644 index f17c40b469..0000000000 --- a/pal/input/web/touch-input.ts +++ /dev/null @@ -1,138 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { TouchCallback } from 'pal/input'; -import { EDITOR, TEST, USE_XR } from 'internal:constants'; -import { systemInfo } from 'pal/system-info'; -import { screenAdapter } from 'pal/screen-adapter'; -import { Rect, Vec2 } from '../../../cocos/core/math'; -import { EventTarget } from '../../../cocos/core/event'; -import { Touch, EventTouch } from '../../../cocos/input/types'; -import { touchManager } from '../touch-manager'; -import { macro } from '../../../cocos/core/platform/macro'; -import { InputEventType } from '../../../cocos/input/types/event-enum'; -import { Feature } from '../../system-info/enum-type'; -import { warn } from '../../../cocos/core/platform/debug'; - -export class TouchInputSource { - private _canvas?: HTMLCanvasElement; - private _eventTarget: EventTarget = new EventTarget(); - - constructor () { - if (systemInfo.hasFeature(Feature.INPUT_TOUCH)) { - this._canvas = document.getElementById('GameCanvas') as HTMLCanvasElement; - if (!this._canvas && !TEST && !EDITOR) { - warn('failed to access canvas'); - } - // In Editor, we don't receive touch event but maybe receive simulated touch event. - if (!EDITOR) { - this._registerEvent(); - } - } - } - - private _registerEvent (): void { - // IDEA: need to register on window ? - this._canvas?.addEventListener('touchstart', this._createCallback(InputEventType.TOUCH_START)); - this._canvas?.addEventListener('touchmove', this._createCallback(InputEventType.TOUCH_MOVE)); - this._canvas?.addEventListener('touchend', this._createCallback(InputEventType.TOUCH_END)); - this._canvas?.addEventListener('touchcancel', this._createCallback(InputEventType.TOUCH_CANCEL)); - } - - private _createCallback (eventType: InputEventType) { - return (event: TouchEvent): void => { - const canvasRect = this._getCanvasRect(); - const handleTouches: Touch[] = []; - const length = event.changedTouches.length; - for (let i = 0; i < length; ++i) { - const changedTouch = event.changedTouches[i]; - const touchID = changedTouch.identifier; - if (touchID === null) { - continue; - } - const location = this._getLocation(changedTouch, canvasRect); - const touch = touchManager.getOrCreateTouch(touchID, location.x, location.y); - if (!touch) { - continue; - } - if (eventType === InputEventType.TOUCH_END || eventType === InputEventType.TOUCH_CANCEL) { - touchManager.releaseTouch(touchID); - } - handleTouches.push(touch); - } - event.stopPropagation(); - if (event.target === this._canvas) { - event.preventDefault(); - } - if (eventType === InputEventType.TOUCH_START) { - this._canvas?.focus(); - } - if (handleTouches.length > 0) { - const eventTouch = new EventTouch( - handleTouches, - false, - eventType, - touchManager.getAllTouches(), - ); - this._eventTarget.emit(eventType, eventTouch); - } - }; - } - - private _getCanvasRect (): Rect { - const canvas = this._canvas; - const box = canvas?.getBoundingClientRect(); - if (box) { - return new Rect(box.x, box.y, box.width, box.height); - } - return new Rect(0, 0, 0, 0); - } - - private _getLocation (touch: globalThis.Touch, canvasRect: Rect): Vec2 { - // webxr has been converted to screen coordinates via camera - if (USE_XR && globalThis.__globalXR && globalThis.__globalXR.ar && globalThis.__globalXR.ar.isWebXR()) { - return new Vec2(touch.clientX, touch.clientY); - } - - let x = touch.clientX - canvasRect.x; - let y = canvasRect.y + canvasRect.height - touch.clientY; - if (screenAdapter.isFrameRotated) { - const tmp = x; - x = canvasRect.height - y; - y = tmp; - } - const dpr = screenAdapter.devicePixelRatio; - x *= dpr; - y *= dpr; - return new Vec2(x, y); - } - - public on (eventType: InputEventType, callback: TouchCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); - } - - public dispatchEventsInCache (): void { - // Do nothing - } -} diff --git a/pal/integrity-check.ts b/pal/integrity-check.ts deleted file mode 100644 index 8e4597c195..0000000000 --- a/pal/integrity-check.ts +++ /dev/null @@ -1,55 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -declare const guard: unique symbol; - -type Guard = typeof guard; - -/** - * Checks if a PAL implementation module is compatible with its target interface module. - * - * @example - * If you write the following in somewhere: - * - * ```ts - * checkPalIntegrity( - * withImpl()); - * ``` - * - * you will receive a compilation error - * if your implementation module is not fulfil the interface module. - * - * @note This function should be easily tree-shaken. - */ -export function checkPalIntegrity (impl: T & Guard): void { - /* empty */ -} - -/** - * Utility function, see example of `checkPalIntegrity()`. - * - */ -export function withImpl (): T & Guard { - return 0 as unknown as T & Guard; -} diff --git a/pal/minigame/alipay.ts b/pal/minigame/alipay.ts deleted file mode 100644 index 04565ed673..0000000000 --- a/pal/minigame/alipay.ts +++ /dev/null @@ -1,171 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { IMiniGame } from 'pal/minigame'; -import { checkPalIntegrity, withImpl } from '../integrity-check'; -import { Orientation } from '../screen-adapter/enum-type'; -import { cloneObject, createInnerAudioContextPolyfill } from '../utils'; - -declare let my: any; - -const minigame: IMiniGame = {} as IMiniGame; -cloneObject(minigame, my); - -// #region SystemInfo -const systemInfo = minigame.getSystemInfoSync(); -minigame.isDevTool = window.navigator && (/AlipayIDE/.test(window.navigator.userAgent)); - -minigame.isLandscape = systemInfo.screenWidth > systemInfo.screenHeight; -// init landscapeOrientation as LANDSCAPE_RIGHT -const landscapeOrientation = Orientation.LANDSCAPE_RIGHT; -// NOTE: onDeviceOrientationChange is not supported on this platform -// my.onDeviceOrientationChange((res) => { -// if (res.value === 'landscape') { -// landscapeOrientation = Orientation.LANDSCAPE_RIGHT; -// } else if (res.value === 'landscapeReverse') { -// landscapeOrientation = Orientation.LANDSCAPE_LEFT; -// } -// }); -Object.defineProperty(minigame, 'orientation', { - get () { - return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT; - }, -}); -// #endregion SystemInfo - -// #region TouchEvent -// my.onTouchStart register touch event listner on body -// need to register on canvas -minigame.onTouchStart = function (cb): void { - window.canvas.addEventListener('touchstart', (res) => { - cb && cb(res); - }); -}; -minigame.onTouchMove = function (cb): void { - window.canvas.addEventListener('touchmove', (res) => { - cb && cb(res); - }); -}; -minigame.onTouchEnd = function (cb): void { - window.canvas.addEventListener('touchend', (res) => { - cb && cb(res); - }); -}; -minigame.onTouchCancel = function (cb): void { - window.canvas.addEventListener('touchcancel', (res) => { - cb && cb(res); - }); -}; -// #endregion TouchEvent - -// #region Audio -const polyfilledCreateInnerAudio = createInnerAudioContextPolyfill(my, { - onPlay: true, // Fix: onPlay can not be executed at Alipay(Override onPlay method). - onPause: true, // Fix: calling pause twice, onPause won't execute twice.(Override onPause method) - onStop: false, - onSeek: false, -}, true); - -// eslint-disable-next-line func-names -minigame.createInnerAudioContext = function (): InnerAudioContext { - // NOTE: `onCanPlay` and `offCanPlay` is not standard minigame interface, - // so here we mark audio as type of any - const audio: any = polyfilledCreateInnerAudio(); - if (audio.onCanPlay) { - audio.onCanplay = audio.onCanPlay.bind(audio); - delete audio.onCanPlay; - } - if (audio.offCanPlay) { - audio.offCanplay = audio.offCanPlay.bind(audio); - delete audio.offCanPlay; - } - return audio as InnerAudioContext; -}; - -// #region Accelerometer -let _accelerometerCb: AccelerometerChangeCallback | undefined; -minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void { - minigame.offAccelerometerChange(); - // onAccelerometerChange would start accelerometer - // so we won't call this method here - _accelerometerCb = (res: any): void => { - let x = res.x; - let y = res.y; - if (minigame.isLandscape) { - const orientationFactor = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1); - const tmp = x; - x = -y * orientationFactor; - y = tmp * orientationFactor; - } - - const resClone = { - x, - y, - z: res.z, - }; - cb(resClone); - }; -}; -minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void { - if (_accelerometerCb) { - my.offAccelerometerChange(_accelerometerCb); - _accelerometerCb = undefined; - } -}; -minigame.startAccelerometer = function (res: any): void { - if (_accelerometerCb) { - my.onAccelerometerChange(_accelerometerCb); - } else { - // my.startAccelerometer() is not implemented. - console.error('minigame.onAccelerometerChange() should be invoked before minigame.startAccelerometer() on alipay platform'); - } -}; -minigame.stopAccelerometer = function (res: any): void { - // my.stopAccelerometer() is not implemented. - minigame.offAccelerometerChange(); -}; -// #endregion Accelerometer - -// #region SafeArea -minigame.getSafeArea = function (): SafeArea { - if (typeof minigame.getWindowInfo === "function") { - const windowInfo = minigame.getWindowInfo(); - return windowInfo.safeArea; - } - console.warn('getSafeArea is not supported on this platform'); - const systemInfo = minigame.getSystemInfoSync(); - return { - top: 0, - left: 0, - bottom: systemInfo.windowHeight, - right: systemInfo.windowWidth, - width: systemInfo.windowWidth, - height: systemInfo.windowHeight, - }; -}; -// #endregion SafeArea - -export { minigame }; - -checkPalIntegrity(withImpl()); diff --git a/pal/minigame/baidu.ts b/pal/minigame/baidu.ts deleted file mode 100644 index 2f0b86ea66..0000000000 --- a/pal/minigame/baidu.ts +++ /dev/null @@ -1,116 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { IMiniGame } from 'pal/minigame'; -import { checkPalIntegrity, withImpl } from '../integrity-check'; -import { Orientation } from '../screen-adapter/enum-type'; -import { cloneObject, createInnerAudioContextPolyfill } from '../utils'; - -declare let swan: any; - -const minigame: IMiniGame = {} as IMiniGame; -cloneObject(minigame, swan); - -// #region SystemInfo -const systemInfo = minigame.getSystemInfoSync(); -minigame.isDevTool = systemInfo.platform === 'devtools'; - -minigame.isLandscape = systemInfo.screenWidth > systemInfo.screenHeight; -// init landscapeOrientation as LANDSCAPE_RIGHT -let landscapeOrientation = Orientation.LANDSCAPE_RIGHT; -swan.onDeviceOrientationChange((res) => { - if (res.value === 'landscape') { - landscapeOrientation = Orientation.LANDSCAPE_RIGHT; - } else if (res.value === 'landscapeReverse') { - landscapeOrientation = Orientation.LANDSCAPE_LEFT; - } -}); -Object.defineProperty(minigame, 'orientation', { - get () { - return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT; - }, -}); -// #endregion SystemInfo - -// #region Accelerometer -let _customAccelerometerCb: AccelerometerChangeCallback | undefined; -let _innerAccelerometerCb: AccelerometerChangeCallback | undefined; -minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void { - // swan.offAccelerometerChange() is not supported. - // so we can only register AccelerometerChange callback, but can't unregister. - if (!_innerAccelerometerCb) { - _innerAccelerometerCb = (res: any): void => { - let x = res.x; - let y = res.y; - if (minigame.isLandscape) { - const orientationFactor = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1); - const tmp = x; - x = -y * orientationFactor; - y = tmp * orientationFactor; - } - - const resClone = { - x, - y, - z: res.z, - }; - _customAccelerometerCb?.(resClone); - }; - swan.onAccelerometerChange(_innerAccelerometerCb); - // onAccelerometerChange would start accelerometer, need to stop it mannually - swan.stopAccelerometer({}); - } - _customAccelerometerCb = cb; -}; -minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void { - // swan.offAccelerometerChange() is not supported. - _customAccelerometerCb = undefined; -}; -// #endregion Accelerometer - -minigame.createInnerAudioContext = createInnerAudioContextPolyfill(swan, { - onPlay: true, - onPause: true, - onStop: true, - onSeek: false, -}); - -// #region SafeArea -minigame.getSafeArea = function (): SafeArea { - console.warn('getSafeArea is not supported on this platform'); - const systemInfo = minigame.getSystemInfoSync(); - return { - top: 0, - left: 0, - bottom: systemInfo.screenHeight, - right: systemInfo.screenWidth, - width: systemInfo.screenWidth, - height: systemInfo.screenHeight, - }; -}; -// #endregion SafeArea - -export { minigame }; - -checkPalIntegrity(withImpl()); diff --git a/pal/minigame/bytedance.ts b/pal/minigame/bytedance.ts deleted file mode 100644 index 89a7a00ac0..0000000000 --- a/pal/minigame/bytedance.ts +++ /dev/null @@ -1,126 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { IMiniGame, SystemInfo } from 'pal/minigame'; -import { checkPalIntegrity, withImpl } from '../integrity-check'; -import { Orientation } from '../screen-adapter/enum-type'; -import { cloneObject, createInnerAudioContextPolyfill } from '../utils'; - -declare let tt: any; - -const minigame: IMiniGame = {} as IMiniGame; -cloneObject(minigame, tt); - -// #region platform related -minigame.tt = {}; -minigame.tt.getAudioContext = tt.getAudioContext?.bind(tt); -// #endregion platform related - -// #region SystemInfo -const systemInfo = minigame.getSystemInfoSync(); - -minigame.isDevTool = (systemInfo.platform === 'devtools'); - -minigame.isLandscape = systemInfo.screenWidth > systemInfo.screenHeight; -// init landscapeOrientation as LANDSCAPE_RIGHT -let landscapeOrientation = Orientation.LANDSCAPE_RIGHT; -tt.onDeviceOrientationChange((res) => { - if (res.value === 'landscape') { - landscapeOrientation = Orientation.LANDSCAPE_RIGHT; - } else if (res.value === 'landscapeReverse') { - landscapeOrientation = Orientation.LANDSCAPE_LEFT; - } -}); -Object.defineProperty(minigame, 'orientation', { - get () { - return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT; - }, -}); -// #endregion SystemInfo - -// #region Accelerometer -let _accelerometerCb: AccelerometerChangeCallback | undefined; -minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void { - minigame.offAccelerometerChange(); - // onAccelerometerChange would start accelerometer - // so we won't call this method here - _accelerometerCb = (res: any): void => { - let x = res.x; - let y = res.y; - if (minigame.isLandscape) { - const orientationFactor = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1); - const tmp = x; - x = -y * orientationFactor; - y = tmp * orientationFactor; - } - - const resClone = { - x, - y, - z: res.z, - }; - cb(resClone); - }; -}; -minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void { - if (_accelerometerCb) { - tt.offAccelerometerChange(_accelerometerCb); - _accelerometerCb = undefined; - } -}; -minigame.startAccelerometer = function (res: any): void { - if (_accelerometerCb) { - tt.onAccelerometerChange(_accelerometerCb); - } - tt.startAccelerometer(res); -}; -// #endregion Accelerometer - -minigame.createInnerAudioContext = createInnerAudioContextPolyfill(tt, { - onPlay: true, - onPause: true, - onStop: true, - onSeek: true, -}); - -// #region SafeArea -// FIX_ME: wrong safe area when orientation is landscape left -minigame.getSafeArea = function (): SafeArea { - const locSystemInfo = tt.getSystemInfoSync() as SystemInfo; - let { top, left, right } = locSystemInfo.safeArea; - const { bottom, width, height } = locSystemInfo.safeArea; - // HACK: on iOS device, the orientation should mannually rotate - if (locSystemInfo.platform === 'ios' && !minigame.isDevTool && minigame.isLandscape) { - const tmpTop = top; const tmpLeft = left; const tmpBottom = bottom; const tmpRight = right; const tmpWidth = width; const tmpHeight = height; - top = tmpLeft; - left = tmpTop; - right = tmpRight - tmpTop; - } - return { top, left, bottom, right, width, height }; -}; -// #endregion SafeArea - -export { minigame }; - -checkPalIntegrity(withImpl()); diff --git a/pal/minigame/non-minigame.ts b/pal/minigame/non-minigame.ts deleted file mode 100644 index 4e70986d6e..0000000000 --- a/pal/minigame/non-minigame.ts +++ /dev/null @@ -1,30 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { checkPalIntegrity, withImpl } from '../integrity-check'; - -const minigame: any = {}; -export { minigame }; - -checkPalIntegrity(withImpl()); diff --git a/pal/minigame/runtime.ts b/pal/minigame/runtime.ts deleted file mode 100644 index 43d040bdd8..0000000000 --- a/pal/minigame/runtime.ts +++ /dev/null @@ -1,136 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { VIVO } from 'internal:constants'; -import { SystemInfo, IMiniGame } from 'pal/minigame'; -import { checkPalIntegrity, withImpl } from '../integrity-check'; - -import { Orientation } from '../screen-adapter/enum-type'; -import { cloneObject, createInnerAudioContextPolyfill } from '../utils'; - -declare let ral: any; - -const minigame: IMiniGame = {} as IMiniGame; -cloneObject(minigame, ral); -minigame.ral = ral; - -// #region SystemInfo -const systemInfo = minigame.getSystemInfoSync(); -minigame.isDevTool = (systemInfo.platform === 'devtools'); - -// NOTE: size and orientation info is wrong at the init phase, need to define as a getter -Object.defineProperty(minigame, 'isLandscape', { - get () { - if (VIVO) { - return systemInfo.screenWidth > systemInfo.screenHeight; - } else { - const locSysInfo = minigame.getSystemInfoSync(); - return locSysInfo.screenWidth > locSysInfo.screenHeight; - } - }, -}); -// init landscapeOrientation as LANDSCAPE_RIGHT -const landscapeOrientation = Orientation.LANDSCAPE_RIGHT; -// NOTE: onDeviceOrientationChange is not supported on this platform -// ral.onDeviceOrientationChange((res) => { -// if (res.value === 'landscape') { -// landscapeOrientation = Orientation.LANDSCAPE_RIGHT; -// } else if (res.value === 'landscapeReverse') { -// landscapeOrientation = Orientation.LANDSCAPE_LEFT; -// } -// }); -Object.defineProperty(minigame, 'orientation', { - get () { - return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT; - }, -}); - -// #endregion SystemInfo - -// #region Accelerometer -let _customAccelerometerCb: AccelerometerChangeCallback | undefined; -let _innerAccelerometerCb: AccelerometerChangeCallback | undefined; -let _needHandleAccelerometerCb = false; -minigame.onAccelerometerChange = function (cb): void { - if (!_innerAccelerometerCb) { - _innerAccelerometerCb = (res): void => { - if (!_needHandleAccelerometerCb) { - return; - } - let x = res.x; - let y = res.y; - if (minigame.isLandscape) { - const orientationFactor = landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1; - const tmp = x; - x = -y * orientationFactor; - y = tmp * orientationFactor; - } - const resClone = { - x, - y, - z: res.z, - }; - _customAccelerometerCb?.(resClone); - }; - ral.onAccelerometerChange(_innerAccelerometerCb); - } - _needHandleAccelerometerCb = true; - _customAccelerometerCb = cb; -}; -minigame.offAccelerometerChange = function (cb): void { - _needHandleAccelerometerCb = false; - _customAccelerometerCb = undefined; -}; -// #endregion Accelerometer - -minigame.createInnerAudioContext = createInnerAudioContextPolyfill(ral, { - onPlay: true, // polyfill for vivo - onPause: true, - onStop: true, - onSeek: true, -}); - -// #region SafeArea -minigame.getSafeArea = function (): SafeArea { - const locSystemInfo = ral.getSystemInfoSync() as SystemInfo; - if (locSystemInfo.safeArea) { - return locSystemInfo.safeArea; - } else { - console.warn('getSafeArea is not supported on this platform'); - const systemInfo = minigame.getSystemInfoSync(); - return { - top: 0, - left: 0, - bottom: systemInfo.screenHeight, - right: systemInfo.screenWidth, - width: systemInfo.screenWidth, - height: systemInfo.screenHeight, - }; - } -}; -// #endregion SafeArea - -export { minigame }; - -checkPalIntegrity(withImpl()); diff --git a/pal/minigame/taobao.ts b/pal/minigame/taobao.ts deleted file mode 100644 index a3d2a3ec2f..0000000000 --- a/pal/minigame/taobao.ts +++ /dev/null @@ -1,219 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { IMiniGame, SystemInfo } from 'pal/minigame'; -import { Orientation } from '../screen-adapter/enum-type'; -import { cloneObject, createInnerAudioContextPolyfill, versionCompare } from '../utils'; -import { Language } from '../system-info/enum-type'; -import { checkPalIntegrity, withImpl } from '../integrity-check'; - -//taobao IDE language ("Chinese") -//taobao phone language (Andrond: "cn", iPad: 'zh_CN') -const languageMap: Record = { - Chinese: Language.CHINESE, - cn: Language.CHINESE, - zh_CN: Language.CHINESE, -}; - -declare let my: any; - -const minigame: IMiniGame = {} as IMiniGame; -cloneObject(minigame, my); - -// #region SystemInfo -const systemInfo = minigame.getSystemInfoSync(); -systemInfo.language = languageMap[systemInfo.language] || systemInfo.language; - -minigame.isDevTool = my.isIDE; - -Object.defineProperty(minigame, 'isLandscape', { - get () { - const locSystemInfo = minigame.getSystemInfoSync(); - if (typeof locSystemInfo.deviceOrientation === 'string') { - return locSystemInfo.deviceOrientation.startsWith('landscape'); - } else { - return locSystemInfo.screenWidth > locSystemInfo.screenHeight; - } - }, -}); -// init landscapeOrientation as LANDSCAPE_RIGHT -const landscapeOrientation = Orientation.LANDSCAPE_RIGHT; -// NOTE: onDeviceOrientationChange is not supported on this platform -// my.onDeviceOrientationChange((res) => { -// if (res.value === 'landscape') { -// landscapeOrientation = Orientation.LANDSCAPE_RIGHT; -// } else if (res.value === 'landscapeReverse') { -// landscapeOrientation = Orientation.LANDSCAPE_LEFT; -// } -// }); -Object.defineProperty(minigame, 'orientation', { - get () { - return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT; - }, -}); -// #endregion SystemInfo - -function detectLandscapeSupport (): void { - const locSysInfo = minigame.getSystemInfoSync(); - if (typeof locSysInfo.deviceOrientation === 'string' && locSysInfo.deviceOrientation.startsWith('landscape')) { - if (versionCompare(locSysInfo.version, '10.15.10') < 0) { - console.warn('The current Taobao client version does not support Landscape, the minimum requirement is 10.15.10'); - } - } -} -detectLandscapeSupport(); - -// #region Audio -const polyfilledCreateInnerAudio = createInnerAudioContextPolyfill(my, { - onPlay: true, // Fix: onPlay won't execute. - onPause: true, // NOTE: calling pause() twice onPause won't execute twice. - onStop: false, - onSeek: false, -}, true); -minigame.createInnerAudioContext = function (): InnerAudioContext { - // NOTE: `onCanPlay` is not standard minigame interface, - // so here we mark audio as type of any - const audio: any = polyfilledCreateInnerAudio(); - return audio as InnerAudioContext; -}; -// #region Audio - -// #region Font -minigame.loadFont = function (url): string { - // my.loadFont crash when url is not in user data path - return 'Arial'; -}; -// #endregion Font - -// #region Accelerometer -let _accelerometerCb: AccelerometerChangeCallback | undefined; -minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void { - minigame.offAccelerometerChange(); - // onAccelerometerChange would start accelerometer - // so we won't call this method here - _accelerometerCb = (res: any): void => { - let x: number = res.x; - let y: number = res.y; - if (minigame.isLandscape) { - const orientationFactor: number = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1); - x = -res.y * orientationFactor; - y = res.x * orientationFactor; - } - - const resClone = { - x, - y, - z: res.z, - }; - cb(resClone); - }; -}; -minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void { - if (_accelerometerCb) { - my.offAccelerometerChange(_accelerometerCb); - _accelerometerCb = undefined; - } -}; -minigame.startAccelerometer = function (res: any): void { - if (_accelerometerCb) { - my.onAccelerometerChange(_accelerometerCb); - } else { - // my.startAccelerometer() is not implemented. - console.error('minigame.onAccelerometerChange() should be invoked before minigame.startAccelerometer() on taobao platform'); - } -}; -minigame.stopAccelerometer = function (res: any): void { - // my.stopAccelerometer() is not implemented. - minigame.offAccelerometerChange(); -}; -// #endregion Accelerometer - -// #region SafeArea -// It should be a value that is not multiplied by dpr -minigame.getSafeArea = function (): SafeArea { - const systemInfo = minigame.getSystemInfoSync(); - if (typeof systemInfo.safeArea !== 'undefined') { - return systemInfo.safeArea; - } - console.warn('getSafeArea is not supported on this platform'); - return { - top: 0, - left: 0, - bottom: systemInfo.windowHeight, - right: systemInfo.windowWidth, - width: systemInfo.windowWidth, - height: systemInfo.windowHeight, - }; -}; -// #endregion SafeArea - -declare const $global: any; // global variable on Taobao platform. - -// TODO: A filpY operation will be performed after ReadPixels on Taobao. -if (!my.isIDE) { - const locCanvas = $global.screencanvas; - if (locCanvas) { - const originalGetContext = locCanvas.getContext.bind(locCanvas); - locCanvas.getContext = function (name, param): any { - if (typeof name === 'string' && typeof param === 'object' && name.startsWith('webgl')) { - Object.assign(param, { enable_flip_y_after_read_pixels: false }); - const gl = originalGetContext(name, param); - adapterGL(gl); - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return gl; - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return originalGetContext(name, param); - }; - } -} - -let hasAdapter = false; -function adapterGL (gl): void { - if (hasAdapter) { return; } - hasAdapter = true; - - if (!my.isIDE) { - // TODO: Premultiplication is already used on Taobao, do not use premultiplication on the phone. - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); - - // TODO: adapter gl.getUniformLocation - // Android return value: undefined. iOS return value: {ID: -1}. - if (my.getSystemInfoSync().platform.toLocaleLowerCase() === 'ios') { - const originalGetUniformLocation = gl.getUniformLocation.bind(gl); - gl.getUniformLocation = function (program, name): any { - const glLoc = originalGetUniformLocation(program, name); - if (glLoc && glLoc.ID === -1) { - return undefined; - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return originalGetUniformLocation(program, name); - }; - } - } -} - -export { minigame }; - -checkPalIntegrity(withImpl()); diff --git a/pal/minigame/taobao_minigame.ts b/pal/minigame/taobao_minigame.ts deleted file mode 100644 index 7e3b31fc2c..0000000000 --- a/pal/minigame/taobao_minigame.ts +++ /dev/null @@ -1,227 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { IMiniGame, SystemInfo } from 'pal/minigame'; -import { Orientation } from '../screen-adapter/enum-type'; -import { cloneObject, createInnerAudioContextPolyfill, versionCompare } from '../utils'; -import { Language } from '../system-info/enum-type'; -import { checkPalIntegrity, withImpl } from '../integrity-check'; - -//taobao IDE language ("Chinese") -//taobao phone language (Andrond: "cn", iPad: 'zh_CN') -const languageMap: Record = { - Chinese: Language.CHINESE, - cn: Language.CHINESE, - zh_CN: Language.CHINESE, -}; - -declare let my: any; - -const minigame: IMiniGame = {} as IMiniGame; -cloneObject(minigame, my); - -// #region SystemInfo -const systemInfo = minigame.getSystemInfoSync(); -systemInfo.language = languageMap[systemInfo.language] || systemInfo.language; - -minigame.isDevTool = my.isIDE; - -Object.defineProperty(minigame, 'isLandscape', { - get () { - const windowInfo = my.getWindowInfoSync(); - return windowInfo.windowWidth > windowInfo.windowHeight; - }, -}); -// init landscapeOrientation as LANDSCAPE_RIGHT -const landscapeOrientation = Orientation.LANDSCAPE_RIGHT; -// NOTE: onDeviceOrientationChange is not supported on this platform -// my.onDeviceOrientationChange((res) => { -// if (res.value === 'landscape') { -// landscapeOrientation = Orientation.LANDSCAPE_RIGHT; -// } else if (res.value === 'landscapeReverse') { -// landscapeOrientation = Orientation.LANDSCAPE_LEFT; -// } -// }); -Object.defineProperty(minigame, 'orientation', { - get () { - return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT; - }, -}); -// #endregion SystemInfo - -// eslint-disable-next-line func-names -function detectLandscapeSupport (): void { - const locSysInfo = minigame.getSystemInfoSync(); - if (typeof locSysInfo.deviceOrientation === 'string' && locSysInfo.deviceOrientation.startsWith('landscape')) { - if (versionCompare(locSysInfo.version, '10.15.10') < 0) { - console.warn('The current Taobao client version does not support Landscape, the minimum requirement is 10.15.10'); - } - } -} -detectLandscapeSupport(); - -// #region Audio -const polyfilledCreateInnerAudio = createInnerAudioContextPolyfill(my, { - onPlay: true, // Fix: onPlay won't execute. - onPause: true, // NOTE: calling pause() twice onPause won't execute twice. - onStop: false, - onSeek: false, -}, true); -// eslint-disable-next-line func-names -minigame.createInnerAudioContext = function (): InnerAudioContext { - // NOTE: `onCanPlay` is not standard minigame interface, - // so here we mark audio as type of any - const audio: any = polyfilledCreateInnerAudio(); - return audio as InnerAudioContext; -}; -// #region Audio - -// #region Font -// eslint-disable-next-line func-names -minigame.loadFont = function (url): string { - // my.loadFont crash when url is not in user data path - return 'Arial'; -}; -// #endregion Font - -// #region Accelerometer -let _accelerometerCb: AccelerometerChangeCallback | undefined; -// eslint-disable-next-line func-names -minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void { - minigame.offAccelerometerChange(); - // onAccelerometerChange would start accelerometer - // so we won't call this method here - _accelerometerCb = (res: any): void => { - let x: number = res.x; - let y: number = res.y; - if (minigame.isLandscape) { - const orientationFactor: number = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1); - x = -res.y * orientationFactor; - y = res.x * orientationFactor; - } - - const resClone = { - x, - y, - z: res.z, - }; - cb(resClone); - }; -}; -// eslint-disable-next-line func-names -minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void { - if (_accelerometerCb) { - my.offAccelerometerChange(_accelerometerCb); - _accelerometerCb = undefined; - } -}; -// eslint-disable-next-line func-names -minigame.startAccelerometer = function (res: any): void { - if (_accelerometerCb) { - my.onAccelerometerChange(_accelerometerCb); - } else { - // my.startAccelerometer() is not implemented. - console.error('minigame.onAccelerometerChange() should be invoked before minigame.startAccelerometer() on taobao platform'); - } -}; -// eslint-disable-next-line func-names -minigame.stopAccelerometer = function (res: any): void { - // my.stopAccelerometer() is not implemented. - minigame.offAccelerometerChange(); -}; -// #endregion Accelerometer - -// #region SafeArea -// It should be a value that is not multiplied by dpr -minigame.getSafeArea = function (): any { - const systemInfo = my.getWindowInfoSync(); - if (typeof systemInfo.safeArea !== 'undefined') { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return systemInfo.safeArea; - } - console.warn('getSafeArea is not supported on this platform'); - return { - top: 0, - left: 0, - bottom: systemInfo.windowHeight, - right: systemInfo.windowWidth, - width: systemInfo.windowWidth, - height: systemInfo.windowHeight, - }; -}; -// #endregion SafeArea - -declare const $global: any; // global variable on Taobao platform. - -// TODO: A filpY operation will be performed after ReadPixels on Taobao. -if (!my.isIDE) { - const locCanvas = $global.screencanvas; - if (locCanvas) { - const originalGetContext = locCanvas.getContext.bind(locCanvas); - // eslint-disable-next-line func-names - locCanvas.getContext = function (name, param): any { - if (typeof name === 'string' && typeof param === 'object' && name.startsWith('webgl')) { - Object.assign(param, { enable_flip_y_after_read_pixels: false }); - const gl = originalGetContext(name, param); - adapterGL(gl); - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return gl; - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return originalGetContext(name, param); - }; - } -} - -let hasAdapter = false; -function adapterGL (gl): void { - if (hasAdapter) { return; } - hasAdapter = true; - - if (!my.isIDE) { - // TODO: Premultiplication is already used on Taobao, do not use premultiplication on the phone. - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); - - // TODO: adapter gl.getUniformLocation - // Android return value: undefined. iOS return value: {ID: -1}. - if (my.getSystemInfoSync().platform.toLocaleLowerCase() === 'ios') { - const originalGetUniformLocation = gl.getUniformLocation.bind(gl); - // eslint-disable-next-line func-names - gl.getUniformLocation = function (program, name): any { - const glLoc = originalGetUniformLocation(program, name); - if (glLoc && glLoc.ID === -1) { - return undefined; - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return originalGetUniformLocation(program, name); - }; - } - } -} - -minigame.loadSubpackage = my.loadSubPackage.bind(my); - -export { minigame }; - -checkPalIntegrity(withImpl()); diff --git a/pal/minigame/wechat.ts b/pal/minigame/wechat.ts deleted file mode 100644 index 3fb0faa855..0000000000 --- a/pal/minigame/wechat.ts +++ /dev/null @@ -1,254 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { IMiniGame, SystemInfo, DeviceInfo, WindowInfo, AppBaseInfo, SystemSetting, AppAuthorizeSetting } from 'pal/minigame'; -import { checkPalIntegrity, withImpl } from '../integrity-check'; -import { Orientation } from '../screen-adapter/enum-type'; -import { cloneObject, createInnerAudioContextPolyfill, versionCompare } from '../utils'; -import { sys, systemEvent } from '../../typedoc-index'; - -declare let wx: any; - -const minigame: IMiniGame = {} as IMiniGame; -cloneObject(minigame, wx); - -// #region platform related -minigame.wx = {}; -minigame.wx.onKeyDown = wx.onKeyDown?.bind(wx); -minigame.wx.onKeyUp = wx.onKeyUp?.bind(wx); -minigame.wx.onMouseDown = wx.onMouseDown?.bind(wx); -minigame.wx.onMouseMove = wx.onMouseMove?.bind(wx); -minigame.wx.onMouseUp = wx.onMouseUp?.bind(wx); -minigame.wx.onWheel = wx.onWheel?.bind(wx); -// #endregion platform related - -// This interface is not supported in versions below 2.25.3. -if (minigame.getSystemSetting === undefined) { - minigame.getSystemSetting = function (): SystemSetting { - const systemInfo = minigame.getSystemInfoSync(); - return { - bluetoothEnabled: systemInfo.bluetoothEnabled, - locationEnabled: systemInfo.locationEnabled, - wifiEnabled: systemInfo.wifiEnabled, - deviceOrientation: systemInfo.deviceOrientation, - }; - }; -} - -if (minigame.getAppAuthorizeSetting === undefined) { - minigame.getAppAuthorizeSetting = function (): AppAuthorizeSetting { - const systemInfo = minigame.getSystemInfoSync(); - return { - albumAuthorized: systemInfo.albumAuthorized === undefined ? undefined : ((systemInfo.albumAuthorized) ? 'authorized' : 'denied'), - bluetoothAuthorized: systemInfo.bluetoothAuthorized === undefined ? undefined - : ((systemInfo.bluetoothAuthorized) ? 'authorized' : 'denied'), - cameraAuthorized: systemInfo.cameraAuthorized === undefined ? undefined - : ((systemInfo.cameraAuthorized) ? 'authorized' : 'denied'), - locationAuthorized: systemInfo.locationAuthorized === undefined ? undefined - : ((systemInfo.locationAuthorized) ? 'authorized' : 'denied'), - locationReducedAccuracy: systemInfo.locationReducedAccuracy === undefined ? undefined : (systemInfo.locationReducedAccuracy), - microphoneAuthorized: systemInfo.microphoneAuthorized === undefined ? undefined - : ((systemInfo.microphoneAuthorized) ? 'authorized' : 'denied'), - notificationAuthorized: systemInfo.notificationAuthorized === undefined ? undefined - : ((systemInfo.notificationAuthorized) ? 'authorized' : 'denied'), - notificationAlertAuthorized: systemInfo.notificationAlertAuthorized === undefined ? undefined - : ((systemInfo.notificationAlertAuthorized) ? 'authorized' : 'denied'), - notificationBadgeAuthorized: systemInfo.notificationBadgeAuthorized === undefined ? undefined - : ((systemInfo.notificationBadgeAuthorized) ? 'authorized' : 'denied'), - notificationSoundAuthorized: systemInfo.notificationSoundAuthorized === undefined ? undefined - : ((systemInfo.notificationSoundAuthorized) ? 'authorized' : 'denied'), - phoneCalendarAuthorized: systemInfo.phoneCalendarAuthorized === undefined ? undefined - : ((systemInfo.phoneCalendarAuthorized) ? 'authorized' : 'denied'), - }; - }; -} - -if (minigame.getDeviceInfo === undefined) { - minigame.getDeviceInfo = function (): DeviceInfo { - const systemInfo = minigame.getSystemInfoSync(); - return { - abi: systemInfo.abi, - deviceAbi: systemInfo.deviceAbi, - benchmarkLevel: systemInfo.benchmarkLevel, - brand: systemInfo.brand, - model: systemInfo.model, - system: systemInfo.system, - platform: systemInfo.platform, - cpuType: systemInfo.cpuType, - memorySize: systemInfo.memorySize, - }; - }; -} - -if (minigame.getWindowInfo === undefined) { - minigame.getWindowInfo = function (): WindowInfo { - const systemInfo = minigame.getSystemInfoSync(); - return { - pixelRatio: systemInfo.pixelRatio, - screenWidth: systemInfo.screenWidth, - screenHeight: systemInfo.screenHeight, - windowWidth: systemInfo.windowWidth, - windowHeight: systemInfo.windowHeight, - statusBarHeight: systemInfo.statusBarHeight, - safeArea: systemInfo.safeArea, - screenTop: systemInfo.screenTop, - }; - }; -} - -if (minigame.getAppBaseInfo === undefined) { - minigame.getAppBaseInfo = function (): AppBaseInfo { - const systemInfo = minigame.getSystemInfoSync(); - return { - SDKVersion: systemInfo.SDKVersion, - enableDebug: systemInfo.enableDebug, - host: systemInfo.host, // not - language: systemInfo.language, - version: systemInfo.version, - theme: systemInfo.theme, - mode: systemInfo.mode, - fontSizeScaleFactor: systemInfo.fontSizeScaleFactor, - fontSizeSetting: systemInfo.fontSizeSetting, - }; - }; -} - -const devideInfo = minigame.getDeviceInfo(); - -minigame.isDevTool = (devideInfo.platform === 'devtools'); -// NOTE: size and orientation info is wrong at the init phase, especially on iOS device -Object.defineProperty(minigame, 'isLandscape', { - get () { - const locSystemInfo = wx.getSystemInfoSync() as SystemInfo; - if (typeof locSystemInfo.deviceOrientation === 'string') { - return locSystemInfo.deviceOrientation.startsWith('landscape'); - } else { - return locSystemInfo.screenWidth > locSystemInfo.screenHeight; - } - }, -}); -// init landscapeOrientation as LANDSCAPE_RIGHT -let landscapeOrientation = Orientation.LANDSCAPE_RIGHT; -if (devideInfo.platform.toLocaleLowerCase() !== 'android') { - // onDeviceOrientationChange doesn't work well on Android. - // see this issue: https://developers.weixin.qq.com/community/minigame/doc/000482138dc460e56cfaa5cb15bc00 - wx.onDeviceOrientationChange((res) => { - if (res.value === 'landscape') { - landscapeOrientation = Orientation.LANDSCAPE_RIGHT; - } else if (res.value === 'landscapeReverse') { - landscapeOrientation = Orientation.LANDSCAPE_LEFT; - } - }); -} -Object.defineProperty(minigame, 'orientation', { - get () { - return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT; - }, -}); -// #endregion SystemInfo - -// #region Accelerometer -let _accelerometerCb: AccelerometerChangeCallback | undefined; -minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void { - minigame.offAccelerometerChange(); - // onAccelerometerChange would start accelerometer - // so we won't call this method here - _accelerometerCb = (res: any): void => { - let x = res.x; - let y = res.y; - if (minigame.isLandscape) { - const orientationFactor = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1); - const tmp = x; - x = -y * orientationFactor; - y = tmp * orientationFactor; - } - - const resClone = { - x, - y, - z: res.z, - }; - cb(resClone); - }; -}; -minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void { - if (_accelerometerCb) { - wx.offAccelerometerChange(_accelerometerCb); - _accelerometerCb = undefined; - } -}; -minigame.startAccelerometer = function (res: any): void { - if (_accelerometerCb) { - wx.onAccelerometerChange(_accelerometerCb); - } - wx.startAccelerometer(res); -}; -// #endregion Accelerometer - -minigame.createInnerAudioContext = createInnerAudioContextPolyfill(wx, { - onPlay: true, - onPause: true, - onStop: true, - onSeek: false, -}, true); - -// #region SafeArea -// FIX_ME: wrong safe area when orientation is landscape left -minigame.getSafeArea = function (): SafeArea { - const windowInfo: WindowInfo = minigame.getWindowInfo(); - let safeArea = windowInfo.safeArea; - if (!safeArea) { - safeArea = { - left: 0, - top: 0, - bottom: windowInfo.screenHeight, - right: windowInfo.screenWidth, - width: windowInfo.screenWidth, - height: windowInfo.screenHeight, - }; - } - return safeArea; -}; -// #endregion SafeArea - -declare const canvas: any; // defined in global - -// HACK: adapt GL.useProgram: use program not supported to unbind program on pc end -const appBaseInfo = minigame.getAppBaseInfo(); -if (devideInfo.platform === 'windows' && versionCompare(appBaseInfo.SDKVersion, '2.16.0') < 0) { - const locCanvas = canvas; - if (locCanvas) { - const webglRC = locCanvas.getContext('webgl'); - const originalUseProgram = webglRC.useProgram.bind(webglRC); - webglRC.useProgram = function (program): void { - if (program) { - originalUseProgram(program); - } - }; - } -} - -export { minigame }; - -checkPalIntegrity(withImpl()); diff --git a/pal/minigame/wechat_mini_program.ts b/pal/minigame/wechat_mini_program.ts deleted file mode 100644 index f5d0f69ca8..0000000000 --- a/pal/minigame/wechat_mini_program.ts +++ /dev/null @@ -1,195 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { IMiniGame, SystemInfo } from 'pal/minigame'; -import { checkPalIntegrity, withImpl } from '../integrity-check'; -import { Orientation } from '../screen-adapter/enum-type'; -import { cloneObject, createInnerAudioContextPolyfill, versionCompare } from '../utils'; - -declare let wx: any; -// NOTE: getApp is defined on wechat miniprogram platform -declare const getApp: any; - -// eslint-disable-next-line @typescript-eslint/ban-ts-comment -// @ts-expect-error can't init minigame when it's declared -const minigame: IMiniGame = {}; -cloneObject(minigame, wx); - -// #region platform related -minigame.wx = {}; -minigame.wx.onKeyDown = wx.onKeyDown?.bind(wx); -minigame.wx.onKeyUp = wx.onKeyUp?.bind(wx); -minigame.wx.onMouseDown = wx.onMouseDown?.bind(wx); -minigame.wx.onMouseMove = wx.onMouseMove?.bind(wx); -minigame.wx.onMouseUp = wx.onMouseUp?.bind(wx); -minigame.wx.onWheel = wx.onWheel?.bind(wx); -// #endregion platform related - -const systemInfo = minigame.getSystemInfoSync(); -minigame.isDevTool = (systemInfo.platform === 'devtools'); -// NOTE: size and orientation info is wrong at the init phase, especially on iOS device -Object.defineProperty(minigame, 'isLandscape', { - get () { - const locSystemInfo = wx.getSystemInfoSync() as SystemInfo; - if (typeof locSystemInfo.deviceOrientation === 'string') { - return locSystemInfo.deviceOrientation.startsWith('landscape'); - } else { - return locSystemInfo.screenWidth > locSystemInfo.screenHeight; - } - }, -}); -// init landscapeOrientation as LANDSCAPE_RIGHT -let landscapeOrientation = Orientation.LANDSCAPE_RIGHT; -if (systemInfo.platform.toLocaleLowerCase() !== 'android') { - // onDeviceOrientationChange doesn't work well on Android. - // see this issue: https://developers.weixin.qq.com/community/minigame/doc/000482138dc460e56cfaa5cb15bc00 - wx.onDeviceOrientationChange((res) => { - if (res.value === 'landscape') { - landscapeOrientation = Orientation.LANDSCAPE_RIGHT; - } else if (res.value === 'landscapeReverse') { - landscapeOrientation = Orientation.LANDSCAPE_LEFT; - } - }); -} -Object.defineProperty(minigame, 'orientation', { - get () { - return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT; - }, -}); -// #endregion SystemInfo - -// #region Accelerometer -let _accelerometerCb: AccelerometerChangeCallback | undefined; -minigame.onAccelerometerChange = (cb: AccelerometerChangeCallback): void => { - minigame.offAccelerometerChange(); - // onAccelerometerChange would start accelerometer - // so we won't call this method here - _accelerometerCb = (res: any): void => { - let x = res.x; - let y = res.y; - if (minigame.isLandscape) { - const orientationFactor = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1); - const tmp = x; - x = -y * orientationFactor; - y = tmp * orientationFactor; - } - - const resClone = { - x, - y, - z: res.z, - }; - cb(resClone); - }; -}; -minigame.offAccelerometerChange = (cb?: AccelerometerChangeCallback): void => { - if (_accelerometerCb) { - wx.offAccelerometerChange(_accelerometerCb); - _accelerometerCb = undefined; - } -}; -minigame.startAccelerometer = (res: any): void => { - if (_accelerometerCb) { - wx.onAccelerometerChange(_accelerometerCb); - } - wx.startAccelerometer(res); -}; -// #endregion Accelerometer - -minigame.createInnerAudioContext = createInnerAudioContextPolyfill(wx, { - onPlay: true, - onPause: true, - onStop: true, - onSeek: false, -}, true); - -// #region SafeArea -// FIX_ME: wrong safe area when orientation is landscape left -minigame.getSafeArea = (): SafeArea => { - const locSystemInfo = wx.getSystemInfoSync() as SystemInfo; - let safeArea = locSystemInfo.safeArea; - if (!safeArea) { - safeArea = { - left: 0, - top: 0, - bottom: systemInfo.screenHeight, - right: systemInfo.screenWidth, - width: systemInfo.screenWidth, - height: systemInfo.screenHeight, - }; - } - return safeArea; -}; -// #endregion SafeArea - -// HACK: adapt GL.useProgram: use program not supported to unbind program on pc end -if (systemInfo.platform === 'windows' && versionCompare(systemInfo.SDKVersion, '2.16.0') < 0) { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-expect-error canvas defined in global - const locCanvas = canvas; - if (locCanvas) { - const webglRC = locCanvas.getContext('webgl'); - const originalUseProgram = webglRC.useProgram.bind(webglRC); - webglRC.useProgram = (program): void => { - if (program) { - originalUseProgram(program); - } - }; - } -} - -// HACK: adapt gl.texSubImage2D: gl.texSubImage2D do not support 2d canvas in wechat miniprogram -const gl = getApp().GameGlobal.canvas.getContext('webgl'); -const oldTexSubImage2D = gl.texSubImage2D; -gl.texSubImage2D = (...args: any[]): void => { - if (args.length === 7) { - const canvas = args[6]; - if (typeof canvas.type !== 'undefined' && canvas.type === 'canvas') { - const ctx = canvas.getContext('2d'); - const texOffsetX = args[2]; - const texOffsetY = args[3]; - const imgData = ctx.getImageData(texOffsetX, texOffsetY, canvas.width, canvas.height); - oldTexSubImage2D.call( - gl, - args[0], - args[1], - texOffsetX, - texOffsetY, - canvas.width, - canvas.height, - args[4], - args[5], - new Uint8Array(imgData.data as ArrayBuffer), - ); - } else { - oldTexSubImage2D.apply(gl, args); - } - } else { - oldTexSubImage2D.apply(gl, args); - } -}; - -export { minigame }; - -checkPalIntegrity(withImpl()); diff --git a/pal/minigame/xiaomi.ts b/pal/minigame/xiaomi.ts deleted file mode 100644 index 4ad32f6322..0000000000 --- a/pal/minigame/xiaomi.ts +++ /dev/null @@ -1,156 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { IMiniGame } from 'pal/minigame'; -import { checkPalIntegrity, withImpl } from '../integrity-check'; -import { Orientation } from '../screen-adapter/enum-type'; -import { cloneObject, createInnerAudioContextPolyfill } from '../utils'; -import { warn } from '../../cocos/core/platform/debug'; - -declare let qg: any; - -const minigame: IMiniGame = {} as IMiniGame; -cloneObject(minigame, qg); - -// #region SystemInfo -const systemInfo = minigame.getSystemInfoSync(); -minigame.isDevTool = false; - -minigame.isLandscape = systemInfo.screenWidth > systemInfo.screenHeight; -// init landscapeOrientation as LANDSCAPE_RIGHT -const landscapeOrientation = Orientation.LANDSCAPE_RIGHT; -// NOTE: onDeviceOrientationChange is not supported on this platform -// qg.onDeviceOrientationChange((res) => { -// if (res.value === 'landscape') { -// landscapeOrientation = Orientation.LANDSCAPE_RIGHT; -// } else if (res.value === 'landscapeReverse') { -// landscapeOrientation = Orientation.LANDSCAPE_LEFT; -// } -// }); -Object.defineProperty(minigame, 'orientation', { - get () { - return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT; - }, -}); -// #endregion SystemInfo - -// #region TouchEvent -minigame.onTouchStart = (cb): void => { - window.canvas.ontouchstart = cb; -}; -minigame.onTouchMove = (cb): void => { - window.canvas.ontouchmove = cb; -}; -minigame.onTouchEnd = (cb): void => { - window.canvas.ontouchend = cb; -}; -minigame.onTouchCancel = (cb): void => { - window.canvas.ontouchcancel = cb; -}; -// #endregion TouchEvent - -// // Keyboard -// globalAdapter.showKeyboard = function (res) { -// res.confirmHold = true; // HACK: confirmHold not working on Xiaomi platform -// qg.showKeyboard(res); -// }; - -// #region Accelerometer -let _customAccelerometerCb: AccelerometerChangeCallback | undefined; -let _innerAccelerometerCb: AccelerometerChangeCallback | undefined; -minigame.onAccelerometerChange = (cb: AccelerometerChangeCallback): void => { - // qg.offAccelerometerChange() is not supported. - // so we can only register AccelerometerChange callback, but can't unregister. - if (!_innerAccelerometerCb) { - _innerAccelerometerCb = (res: any): void => { - let x = res.x; - let y = res.y; - if (minigame.isLandscape) { - const orientationFactor = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1); - const tmp = x; - x = -y * orientationFactor; - y = tmp * orientationFactor; - } - - const standardFactor = -0.1; - x *= standardFactor; - y *= standardFactor; - const resClone = { - x, - y, - z: res.z, - }; - _customAccelerometerCb?.(resClone); - }; - qg.onAccelerometerChange(_innerAccelerometerCb); - } - _customAccelerometerCb = cb; -}; -minigame.offAccelerometerChange = (cb?: AccelerometerChangeCallback): void => { - // qg.offAccelerometerChange() is not supported. - _customAccelerometerCb = undefined; -}; -// #endregion Accelerometer - -// #region InnerAudioContext -minigame.createInnerAudioContext = createInnerAudioContextPolyfill(qg, { - onPlay: true, - onPause: true, - onStop: true, - onSeek: false, -}); -const originalCreateInnerAudioContext = minigame.createInnerAudioContext; -minigame.createInnerAudioContext = (): InnerAudioContext => { - const audioContext = originalCreateInnerAudioContext.call(minigame); - const originalStop = audioContext.stop; - Object.defineProperty(audioContext, 'stop', { - configurable: true, - value (): void { - // NOTE: stop won't seek to 0 when audio is paused on Xiaomi platform. - audioContext.seek(0); - originalStop.call(audioContext); - }, - }); - return audioContext; -}; -// #endregion InnerAudioContext - -// #region SafeArea -minigame.getSafeArea = (): SafeArea => { - warn('getSafeArea is not supported on this platform'); - const systemInfo = minigame.getSystemInfoSync(); - return { - top: 0, - left: 0, - bottom: systemInfo.screenHeight, - right: systemInfo.screenWidth, - width: systemInfo.screenWidth, - height: systemInfo.screenHeight, - }; -}; -// #endregion SafeArea - -export { minigame }; - -checkPalIntegrity(withImpl()); diff --git a/pal/pacer/pacer-minigame.ts b/pal/pacer/pacer-minigame.ts deleted file mode 100644 index a3b99ab2fa..0000000000 --- a/pal/pacer/pacer-minigame.ts +++ /dev/null @@ -1,84 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { minigame } from 'pal/minigame'; -import { assertIsTrue } from '../../cocos/core/data/utils/asserts'; -import { checkPalIntegrity, withImpl } from '../integrity-check'; - -export class Pacer { - private _rafHandle = 0; - private _onTick: (() => void) | null = null; - private declare _updateCallback: () => void; - private _targetFrameRate = 60; - private _isPlaying = false; - constructor () { - this._updateCallback = (): void => { - if (this._isPlaying) { - this._rafHandle = requestAnimationFrame(this._updateCallback); - } - if (this._onTick) { - this._onTick(); - } - }; - } - - get targetFrameRate (): number { - return this._targetFrameRate; - } - - set targetFrameRate (val: number) { - if (this._targetFrameRate !== val) { - assertIsTrue(val > 0); - this._targetFrameRate = val; - minigame.setPreferredFramesPerSecond(this._targetFrameRate); - if (this._isPlaying) { - this.stop(); - this.start(); - } - } - } - - set onTick (val: (() => void) | null) { - this._onTick = val; - } - - get onTick (): (() => void) | null { - return this._onTick; - } - - start (): void { - if (this._isPlaying) return; - this._rafHandle = requestAnimationFrame(this._updateCallback); - this._isPlaying = true; - } - - stop (): void { - if (!this._isPlaying) return; - cancelAnimationFrame(this._rafHandle); - this._rafHandle = 0; - this._isPlaying = false; - } -} - -checkPalIntegrity(withImpl()); diff --git a/pal/pacer/pacer-native.ts b/pal/pacer/pacer-native.ts deleted file mode 100644 index 33dcb810d0..0000000000 --- a/pal/pacer/pacer-native.ts +++ /dev/null @@ -1,84 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { assertIsTrue } from '../../cocos/core/data/utils/asserts'; -import { checkPalIntegrity, withImpl } from '../integrity-check'; - -declare const jsb: any; -export class Pacer { - private _rafHandle = 0; - private _onTick: (() => void) | null = null; - private _targetFrameRate = 60; - private _isPlaying = false; - private declare _updateCallback: () => void; - constructor () { - this._updateCallback = (): void => { - if (this._isPlaying) { - this._rafHandle = requestAnimationFrame(this._updateCallback); - } - if (this._onTick) { - this._onTick(); - } - }; - } - - get targetFrameRate (): number { - return this._targetFrameRate; - } - - set targetFrameRate (val: number) { - if (this._targetFrameRate !== val) { - assertIsTrue(val > 0); - this._targetFrameRate = val; - jsb.setPreferredFramesPerSecond(this._targetFrameRate); - if (this._isPlaying) { - this.stop(); - this.start(); - } - } - } - - set onTick (val: (() => void) | null) { - this._onTick = val; - } - - get onTick (): (() => void) | null { - return this._onTick; - } - - start (): void { - if (this._isPlaying) return; - this._rafHandle = requestAnimationFrame(this._updateCallback); - this._isPlaying = true; - } - - stop (): void { - if (!this._isPlaying) return; - cancelAnimationFrame(this._rafHandle); - this._rafHandle = 0; - this._isPlaying = false; - } -} - -checkPalIntegrity(withImpl()); diff --git a/pal/pacer/pacer-nodejs.ts b/pal/pacer/pacer-nodejs.ts deleted file mode 100644 index 53d2f87617..0000000000 --- a/pal/pacer/pacer-nodejs.ts +++ /dev/null @@ -1,99 +0,0 @@ -/* - Copyright (c) 2025 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { checkPalIntegrity, withImpl } from '../integrity-check'; - -const FRAME_RESET_TIME = 2000; - -export class Pacer { - private _stHandle = 0; - private _onTick: (() => void) | null = null; - private _targetFrameRate = 60; - private _frameTime = 0; - private _startTime = 0; - private _isPlaying = false; - - constructor () { - this._isPlaying = false; - } - - get targetFrameRate (): number { - return this._targetFrameRate; - } - - set targetFrameRate (val: number) { - if (this._targetFrameRate !== val) { - this._targetFrameRate = val; - this._frameTime = 1000 / this._targetFrameRate; - if (this._isPlaying) { - this.stop(); - this.start(); - } - } - } - - set onTick (val: (() => void) | null) { - this._onTick = val; - } - - get onTick (): (() => void) | null { - return this._onTick; - } - - start (): void { - if (this._isPlaying) return; - const updateCallback = (): void => { - if (this._isPlaying) { - this._stHandle = this._stTime(updateCallback); - } - if (this._onTick) { - this._onTick(); - } - }; - this._startTime = performance.now(); - this._stHandle = this._stTime(updateCallback); - - this._isPlaying = true; - } - - stop (): void { - if (!this._isPlaying) return; - this._ctTime(this._stHandle); - this._stHandle = 0; - this._isPlaying = false; - } - - private _stTime (callback: () => void): number { - const currTime = performance.now(); - const elapseTime = Math.max(0, currTime - this._startTime); - const timeToCall = Math.max(0, this._frameTime - elapseTime); - return setTimeout(callback, timeToCall); - } - - private _ctTime (id: number | undefined): void { - clearTimeout(id); - } -} - -checkPalIntegrity(withImpl()); diff --git a/pal/pacer/pacer-web.ts b/pal/pacer/pacer-web.ts deleted file mode 100644 index 4496d3589a..0000000000 --- a/pal/pacer/pacer-web.ts +++ /dev/null @@ -1,151 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { EDITOR, USE_XR } from 'internal:constants'; -import { assertIsTrue } from '../../cocos/core/data/utils/asserts'; -import { checkPalIntegrity, withImpl } from '../integrity-check'; - -const FRAME_RESET_TIME = 2000; - -export class Pacer { - private _stHandle = 0; - private _onTick: (() => void) | null = null; - private _targetFrameRate = 60; - private _frameTime = 0; - private _startTime = 0; - private _isPlaying = false; - private _frameCount = 0; - private _callback: (() => void) | null = null; - private _rAF: typeof requestAnimationFrame; - private _cAF: typeof cancelAnimationFrame; - - constructor () { - this._frameTime = 1000 / this._targetFrameRate; - this._rAF = window.requestAnimationFrame - || window.webkitRequestAnimationFrame - || window.mozRequestAnimationFrame - || window.oRequestAnimationFrame - || window.msRequestAnimationFrame; - this._cAF = window.cancelAnimationFrame - || window.cancelRequestAnimationFrame - || window.msCancelRequestAnimationFrame - || window.mozCancelRequestAnimationFrame - || window.oCancelRequestAnimationFrame - || window.webkitCancelRequestAnimationFrame - || window.msCancelAnimationFrame - || window.mozCancelAnimationFrame - || window.webkitCancelAnimationFrame - || window.ocancelAnimationFrame; - } - - get targetFrameRate (): number { - return this._targetFrameRate; - } - - set targetFrameRate (val: number) { - if (this._targetFrameRate !== val) { - assertIsTrue(val > 0); - this._targetFrameRate = val; - this._frameTime = 1000 / this._targetFrameRate; - if (this._isPlaying) { - this.stop(); - this.start(); - } - } - } - - set onTick (val: (() => void) | null) { - this._onTick = val; - } - - get onTick (): (() => void) | null { - return this._onTick; - } - - start (): void { - if (this._isPlaying) return; - const recordStartTime = EDITOR || this._rAF === undefined || (USE_XR && globalThis.__globalXR?.isWebXR); - const updateCallback = (): void => { - if (recordStartTime) this._startTime = performance.now(); - if (this._isPlaying) { - this._stHandle = this._stTime(updateCallback); - } - if (this._onTick) { - this._onTick(); - } - }; - this._startTime = performance.now(); - this._stHandle = this._stTime(updateCallback); - - this._isPlaying = true; - this._frameCount = 0; - } - - stop (): void { - if (!this._isPlaying) return; - this._ctTime(this._stHandle); - this._stHandle = 0; - this._isPlaying = false; - this._frameCount = 0; - } - - _handleRAF = (stamp: number): void => { - const currTime = performance.now(); - const elapseTime = currTime - this._startTime; - const elapseFrame = Math.floor(elapseTime / this._frameTime); - if (elapseFrame < 0) { - this._startTime = currTime; - this._frameCount = 0; - } - if (elapseFrame < this._frameCount) { - this._stHandle = this._rAF.call(window, this._handleRAF); - } else { - this._frameCount = elapseFrame + 1; - if (this._callback) { - this._callback(); - } - } - }; - - private _stTime (callback: () => void): number { - if (EDITOR || this._rAF === undefined || (USE_XR && globalThis.__globalXR?.isWebXR)) { - const currTime = performance.now(); - const elapseTime = Math.max(0, currTime - this._startTime); - const timeToCall = Math.max(0, this._frameTime - elapseTime); - return setTimeout(callback, timeToCall); - } - this._callback = callback; - return this._rAF.call(window, this._handleRAF); - } - - private _ctTime (id: number | undefined): void { - if (EDITOR || this._cAF === undefined || (USE_XR && globalThis.__globalXR?.isWebXR)) { - clearTimeout(id); - } else if (id) { - this._cAF.call(window, id); - } - } -} - -checkPalIntegrity(withImpl()); diff --git a/pal/screen-adapter/enum-type/index.ts b/pal/screen-adapter/enum-type/index.ts deleted file mode 100644 index 36ab0c4cfd..0000000000 --- a/pal/screen-adapter/enum-type/index.ts +++ /dev/null @@ -1,26 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -export * from './orientation'; -export * from './screen-event'; diff --git a/pal/screen-adapter/enum-type/orientation.ts b/pal/screen-adapter/enum-type/orientation.ts deleted file mode 100644 index f1dff3d14f..0000000000 --- a/pal/screen-adapter/enum-type/orientation.ts +++ /dev/null @@ -1,32 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -export enum Orientation { - PORTRAIT = 1, - PORTRAIT_UPSIDE_DOWN = PORTRAIT << 1, - LANDSCAPE_LEFT = PORTRAIT << 2, - LANDSCAPE_RIGHT = PORTRAIT << 3, - LANDSCAPE = LANDSCAPE_LEFT | LANDSCAPE_RIGHT, - AUTO = PORTRAIT | LANDSCAPE, -} diff --git a/pal/screen-adapter/enum-type/screen-event.ts b/pal/screen-adapter/enum-type/screen-event.ts deleted file mode 100644 index d9224f241f..0000000000 --- a/pal/screen-adapter/enum-type/screen-event.ts +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -export type PalScreenEvent = 'window-resize' | 'orientation-change' | 'fullscreen-change'; diff --git a/pal/screen-adapter/minigame/screen-adapter.ts b/pal/screen-adapter/minigame/screen-adapter.ts deleted file mode 100644 index 1cb875dcc6..0000000000 --- a/pal/screen-adapter/minigame/screen-adapter.ts +++ /dev/null @@ -1,183 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { ALIPAY, BYTEDANCE, TAOBAO_MINIGAME, VIVO, WECHAT } from 'internal:constants'; -import { minigame } from 'pal/minigame'; -import { IScreenOptions, SafeAreaEdge } from 'pal/screen-adapter'; -import { systemInfo } from 'pal/system-info'; -import { getError, warnID } from '../../../cocos/core/platform/debug'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { Size } from '../../../cocos/core/math'; -import { OS } from '../../system-info/enum-type'; -import { Orientation } from '../enum-type'; -import { checkPalIntegrity, withImpl } from '../../integrity-check'; - -declare const my: any; - -// HACK: In some platform like CocosPlay or Alipay iOS end -// the windowSize need to rotate when init screenAdapter if it's landscape -let rotateLandscape = false; -try { - if (ALIPAY) { - if (systemInfo.os === OS.IOS && !minigame.isDevTool) { - // TODO: use pal/fs - // issue: https://github.com/cocos/cocos-engine/issues/14647 - const fs = my.getFileSystemManager(); - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - const screenOrientation = JSON.parse(fs.readFileSync({ - filePath: 'game.json', - encoding: 'utf8', - }).data).screenOrientation; - rotateLandscape = (screenOrientation === 'landscape'); - } - } -} catch (e) { - // eslint-disable-next-line no-console - console.error(e); -} - -class ScreenAdapter extends EventTarget { - public isFrameRotated = false; - public handleResizeEvent = true; - - public get supportFullScreen (): boolean { - return false; - } - public get isFullScreen (): boolean { - return false; - } - - public get devicePixelRatio (): number { - if (WECHAT) { - const sysInfo = minigame.getWindowInfo(); - return sysInfo.pixelRatio; - } - const sysInfo = minigame.getSystemInfoSync(); - return sysInfo.pixelRatio; - } - - public get windowSize (): Size { - let sysInfo; - if (WECHAT) { - sysInfo = minigame.getWindowInfo(); - } else { - sysInfo = minigame.getSystemInfoSync(); - } - - const dpr = this.devicePixelRatio; - let screenWidth = sysInfo.windowWidth; - let screenHeight = sysInfo.windowHeight; - if (BYTEDANCE) { - screenWidth = sysInfo.screenWidth; - screenHeight = sysInfo.screenHeight; - } else if (ALIPAY && rotateLandscape && screenWidth < screenHeight) { - const temp = screenWidth; - screenWidth = screenHeight; - screenHeight = temp; - } else if (TAOBAO_MINIGAME) { - const windowInfo = my.getWindowInfoSync(); - if (windowInfo) { - screenWidth = windowInfo.windowWidth; - screenHeight = windowInfo.windowHeight; - } - } - return new Size(screenWidth * dpr, screenHeight * dpr); - } - public set windowSize (size: Size) { - warnID(1221); - } - - public get resolution (): Size { - const windowSize = this.windowSize; - const resolutionScale = this.resolutionScale; - return new Size(windowSize.width * resolutionScale, windowSize.height * resolutionScale); - } - public get resolutionScale (): number { - return this._resolutionScale; - } - public set resolutionScale (value: number) { - if (value === this._resolutionScale) { - return; - } - this._resolutionScale = value; - this._cbToUpdateFrameBuffer?.(); - } - - public get orientation (): Orientation { - return minigame.orientation; - } - public set orientation (value: Orientation) { - warnID(1221); - } - - public get safeAreaEdge (): SafeAreaEdge { - const minigameSafeArea = minigame.getSafeArea(); - const windowSize = this.windowSize; - // NOTE: safe area info on vivo platform is in physical pixel. - // No need to multiply with DPR. - const dpr = VIVO ? 1 : this.devicePixelRatio; - const topEdge = minigameSafeArea.top * dpr; - const bottomEdge = windowSize.height - minigameSafeArea.bottom * dpr; - const leftEdge = minigameSafeArea.left * dpr; - const rightEdge = windowSize.width - minigameSafeArea.right * dpr; - return { - top: topEdge, - bottom: bottomEdge, - left: leftEdge, - right: rightEdge, - }; - } - - public get isProportionalToFrame (): boolean { - return this._isProportionalToFrame; - } - public set isProportionalToFrame (v: boolean) { } - - private _cbToUpdateFrameBuffer?: () => void; - private _resolutionScale = 1; - private _isProportionalToFrame = false; - - constructor () { - super(); - minigame.onWindowResize?.(() => { - this.emit('window-resize', this.windowSize.width, this.windowSize.height); - }); - } - - public init (options: IScreenOptions, cbToRebuildFrameBuffer: () => void): void { - this._cbToUpdateFrameBuffer = cbToRebuildFrameBuffer; - this._cbToUpdateFrameBuffer(); - } - - public requestFullScreen (): Promise { - return Promise.reject(new Error(getError(9008))); - } - public exitFullScreen (): Promise { - return Promise.reject(new Error(getError(9009))); - } -} - -export const screenAdapter = new ScreenAdapter(); - -checkPalIntegrity(withImpl()); diff --git a/pal/screen-adapter/native/screen-adapter.ts b/pal/screen-adapter/native/screen-adapter.ts deleted file mode 100644 index 66c4146526..0000000000 --- a/pal/screen-adapter/native/screen-adapter.ts +++ /dev/null @@ -1,174 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { EDITOR } from 'internal:constants'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { Size } from '../../../cocos/core/math'; -import { checkPalIntegrity, withImpl } from '../../integrity-check'; -import { Orientation } from '../enum-type'; -import { warn, warnID } from '../../../cocos/core/platform/debug'; - -export interface SafeAreaEdge { - top: number; - bottom: number; - left: number; - right: number; -} - -export type ConfigOrientation = 'auto' | 'landscape' | 'portrait'; - -export interface IScreenOptions { - /** - * Orientation options from editor builder. - */ - configOrientation: ConfigOrientation; - /** - * Determine whether the game frame exact fits the screen. - * Now it only works on Web platform. - */ - exactFitScreen: boolean, - /** - * Determine whether use headless renderer, which means do not support some screen operations. - */ - isHeadlessMode: boolean; -} - -// these value is defined in the native layer -const orientationMap: Record = { - 0: Orientation.PORTRAIT, - '-90': Orientation.LANDSCAPE_LEFT, - 90: Orientation.LANDSCAPE_RIGHT, - 180: Orientation.PORTRAIT_UPSIDE_DOWN, -}; - -class ScreenAdapter extends EventTarget { - public isFrameRotated = false; - public handleResizeEvent = true; - - public get supportFullScreen (): boolean { - return false; - } - public get isFullScreen (): boolean { - return false; - } - - public get devicePixelRatio (): number { - return jsb.device.getDevicePixelRatio() || 1; - } - - public get windowSize (): Size { - const dpr = this.devicePixelRatio; - // NOTE: fix precision issue on Metal render end. - const width = jsb.window.innerWidth as number; - const height = jsb.window.innerHeight as number; - // NOTE: fix precision issue on Metal render end. - const roundWidth = Math.round(width); - const roundHeight = Math.round(height); - return new Size(roundWidth * dpr, roundHeight * dpr); - } - public set windowSize (size: Size) { - warn('Setting window size is not supported yet.'); - } - - public get resolution (): Size { - const windowSize = this.windowSize; - const resolutionScale = this.resolutionScale; - return new Size(windowSize.width * resolutionScale, windowSize.height * resolutionScale); - } - public get resolutionScale (): number { - return this._resolutionScale; - } - public set resolutionScale (v: number) { - if (v === this._resolutionScale) { - return; - } - this._resolutionScale = v; - this._cbToUpdateFrameBuffer?.(); - } - - public get orientation (): Orientation { - return orientationMap[jsb.device.getDeviceOrientation()]; - } - public set orientation (value: Orientation) { - warnID(1221); - } - - public get safeAreaEdge (): SafeAreaEdge { - const nativeSafeArea = jsb.device.getSafeAreaEdge(); - const dpr = this.devicePixelRatio; - const topEdge = nativeSafeArea.x * dpr; - const bottomEdge = nativeSafeArea.z * dpr; - const leftEdge = nativeSafeArea.y * dpr; - const rightEdge = nativeSafeArea.w * dpr; - return { - top: topEdge, - bottom: bottomEdge, - left: leftEdge, - right: rightEdge, - }; - } - public get isProportionalToFrame (): boolean { - return this._isProportionalToFrame; - } - public set isProportionalToFrame (v: boolean) { } - - private _cbToUpdateFrameBuffer?: () => void; - private _resolutionScale = 1; - private _isProportionalToFrame = false; - - constructor () { - super(); - this._registerEvent(); - } - - public init (options: IScreenOptions, cbToRebuildFrameBuffer: () => void): void { - this._cbToUpdateFrameBuffer = cbToRebuildFrameBuffer; - if (!EDITOR) { - this._cbToUpdateFrameBuffer(); - } - } - - public requestFullScreen (): Promise { - return Promise.reject(new Error('request fullscreen has not been supported yet on this platform.')); - } - public exitFullScreen (): Promise { - return Promise.reject(new Error('exit fullscreen has not been supported yet on this platform.')); - } - - private _registerEvent (): void { - jsb.onResize = (event: jsb.WindowEvent): void => { - if (event.width === 0 || event.height === 0) return; - // TODO: remove this function calling - window.resize(event.width / this.devicePixelRatio, event.height / this.devicePixelRatio); - this.emit('window-resize', event.width, event.height, event.windowId); - }; - jsb.onOrientationChanged = (event): void => { - this.emit('orientation-change', this.orientation); - }; - } -} - -export const screenAdapter = new ScreenAdapter(); - -checkPalIntegrity(withImpl()); diff --git a/pal/screen-adapter/nodejs/screen-adapter.ts b/pal/screen-adapter/nodejs/screen-adapter.ts deleted file mode 100644 index b51384dcc4..0000000000 --- a/pal/screen-adapter/nodejs/screen-adapter.ts +++ /dev/null @@ -1,139 +0,0 @@ -/* - Copyright (c) 2025 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { Size } from '../../../cocos/core/math'; -import { checkPalIntegrity, withImpl } from '../../integrity-check'; -import { Orientation } from '../enum-type'; -import { warn, warnID } from '../../../cocos/core/platform/debug'; - -export interface SafeAreaEdge { - top: number; - bottom: number; - left: number; - right: number; -} - -export type ConfigOrientation = 'auto' | 'landscape' | 'portrait'; - -export interface IScreenOptions { - /** - * Orientation options from editor builder. - */ - configOrientation: ConfigOrientation; - /** - * Determine whether the game frame exact fits the screen. - * Now it only works on Web platform. - */ - exactFitScreen: boolean, - /** - * Determine whether use headless renderer, which means do not support some screen operations. - */ - isHeadlessMode: boolean; -} - -class ScreenAdapter extends EventTarget { - public isFrameRotated = false; - public handleResizeEvent = false; - - public get supportFullScreen (): boolean { - return false; - } - public get isFullScreen (): boolean { - return false; - } - - public get devicePixelRatio (): number { - return 1; - } - - public get windowSize (): Size { - // Simulate fake window size - return new Size(960, 640); - } - - public set windowSize (size: Size) { - warn('Setting window size is not supported yet.'); - } - - public get resolution (): Size { - const windowSize = this.windowSize; - const resolutionScale = this.resolutionScale; - return new Size(windowSize.width * resolutionScale, windowSize.height * resolutionScale); - } - - public get resolutionScale (): number { - return this._resolutionScale; - } - - public set resolutionScale (v: number) { - if (v === this._resolutionScale) { - return; - } - this._resolutionScale = v; - } - - public get orientation (): Orientation { - return Orientation.PORTRAIT; - } - public set orientation (value: Orientation) { - warnID(1221); - } - - public get safeAreaEdge (): SafeAreaEdge { - return { - top: 0, - bottom: 0, - left: 0, - right: 0, - }; - } - public get isProportionalToFrame (): boolean { - return this._isProportionalToFrame; - } - public set isProportionalToFrame (v: boolean) { } - - private _resolutionScale = 1; - private _isProportionalToFrame = false; - - constructor () { - super(); - } - - public init (options: IScreenOptions, cbToRebuildFrameBuffer: () => void): void { - - } - - public requestFullScreen (): Promise { - return Promise.reject(new Error('request fullscreen has not been supported yet on this platform.')); - } - public exitFullScreen (): Promise { - return Promise.reject(new Error('exit fullscreen has not been supported yet on this platform.')); - } - -} - -export const screenAdapter = new ScreenAdapter(); - -checkPalIntegrity(withImpl()); diff --git a/pal/screen-adapter/web/screen-adapter.ts b/pal/screen-adapter/web/screen-adapter.ts deleted file mode 100644 index 8c06e3aba1..0000000000 --- a/pal/screen-adapter/web/screen-adapter.ts +++ /dev/null @@ -1,663 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { EDITOR, TEST } from 'internal:constants'; -import { ConfigOrientation, IScreenOptions, SafeAreaEdge } from 'pal/screen-adapter'; -import { systemInfo } from 'pal/system-info'; -import { warnID } from '../../../cocos/core/platform/debug'; -import { EventTarget } from '../../../cocos/core/event/event-target'; -import { Size } from '../../../cocos/core/math'; -import { Orientation } from '../enum-type'; -import legacyCC from '../../../predefine'; -import { checkPalIntegrity, withImpl } from '../../integrity-check'; -import { OS } from '../../system-info/enum-type'; - -interface ICachedStyle { - width: string; - height: string; -} - -const EVENT_TIMEOUT = EDITOR ? 5 : 200; -const orientationMap: Record = { - auto: Orientation.AUTO, - landscape: Orientation.LANDSCAPE, - portrait: Orientation.PORTRAIT, -}; - -/** - * On Web platform, the game window may points to different type of window. - */ -enum WindowType { - /** - * Unknown window type. - */ - Unknown, - /** - * A SubFrame in BrowserWindow. - * Need to set the frame size from an external editor option. - * Should only dispatch 'resize' event when the frame size changed. - * Setting window size is supported. - */ - SubFrame, - /** - * The window size is determined by the size of BrowserWindow. - * Should dispatch 'resize' event when the BrowserWindow size changed. - * Setting window size is NOT supported. - */ - BrowserWindow, - /** - * The window size is equal to the size of screen. - * Should dispatch 'resize' event when enter / exit fullscreen or screen resize. - * Setting window size is NOT supported. - */ - Fullscreen, -} - -interface IScreenFunctionName { - requestFullscreen: string, - exitFullscreen: string, - fullscreenchange: string, - fullscreenEnabled: string, - fullscreenElement: string, - fullscreenerror: string, -} - -class ScreenAdapter extends EventTarget { - public isFrameRotated = false; - public handleResizeEvent = true; - - public get supportFullScreen (): boolean { - return this._supportFullScreen; - } - public get isFullScreen (): boolean { - if (!this._supportFullScreen) { - return false; - } - return !!document[this._fn.fullscreenElement]; - } - - public get devicePixelRatio (): number { - // TODO: remove the down sampling operation in DPR after supporting resolutionScale - return Math.min(window.devicePixelRatio ?? 1, 2); - } - - public get windowSize (): Size { - const result = this._windowSizeInCssPixels; - const dpr = this.devicePixelRatio; - result.width *= dpr; - result.height *= dpr; - return result; - } - public set windowSize (size: Size) { - if (this._windowType !== WindowType.SubFrame) { - warnID(9202); - return; - } - this._resizeFrame(this._convertToSizeInCssPixels(size)); - } - - public get resolution (): Size { - const windowSize = this.windowSize; - const resolutionScale = this.resolutionScale; - return new Size(windowSize.width * resolutionScale, windowSize.height * resolutionScale); - } - public get resolutionScale (): number { - return this._resolutionScale; - } - public set resolutionScale (v: number) { - if (v === this._resolutionScale) { - return; - } - this._resolutionScale = v; - this._cbToUpdateFrameBuffer?.(); - } - - public get orientation (): Orientation { - return this._orientation; - } - public set orientation (value: Orientation) { - if (this._orientation === value) { - return; - } - this._orientation = value; - this._updateFrame(); - } - - private _updateFrame (): void { - this._updateFrameState(); - this._resizeFrame(); - } - - public get safeAreaEdge (): SafeAreaEdge { - const dpr = this.devicePixelRatio; - const _top = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--safe-top') || '0') * dpr; - const _bottom = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--safe-bottom') || '0') * dpr; - const _left = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--safe-left') || '0') * dpr; - const _right = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--safe-right') || '0') * dpr; - - return { - top: _top, - bottom: _bottom, - left: _left, - right: _right, - }; - } - public get isProportionalToFrame (): boolean { - return this._isProportionalToFrame; - } - public set isProportionalToFrame (v: boolean) { - if (this._isProportionalToFrame === v) { - return; - } - this._isProportionalToFrame = v; - this._updateContainer(); - } - - private _gameFrame?: HTMLDivElement; - private _gameContainer?: HTMLDivElement; - private _gameCanvas?: HTMLCanvasElement; - private _isProportionalToFrame = false; - private _cachedFrameStyle: ICachedStyle = { width: '0px', height: '0px' }; - private _cachedContainerStyle: ICachedStyle = { width: '0px', height: '0px' }; - private _cbToUpdateFrameBuffer?: () => void; - private _supportFullScreen = false; - private _touchEventName: string; - private _onFullscreenChange?: () => void; - private _onFullscreenError?: () => void; - // We need to set timeout to handle screen event. - private _orientationChangeTimeoutId = -1; - private _cachedFrameSize = new Size(0, 0); // cache before enter fullscreen. - private _exactFitScreen = false; - private _isHeadlessMode = false; - private _fn = {} as IScreenFunctionName; - // Function mapping for cross browser support - private _fnGroup = [ - [ - 'requestFullscreen', - 'exitFullscreen', - 'fullscreenchange', - 'fullscreenEnabled', - 'fullscreenElement', - 'fullscreenerror', - ], - [ - 'requestFullScreen', - 'exitFullScreen', - 'fullScreenchange', - 'fullScreenEnabled', - 'fullScreenElement', - 'fullscreenerror', - ], - [ - 'webkitRequestFullScreen', - 'webkitCancelFullScreen', - 'webkitfullscreenchange', - 'webkitIsFullScreen', - 'webkitCurrentFullScreenElement', - 'webkitfullscreenerror', - ], - [ - 'mozRequestFullScreen', - 'mozCancelFullScreen', - 'mozfullscreenchange', - 'mozFullScreen', - 'mozFullScreenElement', - 'mozfullscreenerror', - ], - [ - 'msRequestFullscreen', - 'msExitFullscreen', - 'MSFullscreenChange', - 'msFullscreenEnabled', - 'msFullscreenElement', - 'msfullscreenerror', - ], - ]; - private get _windowSizeInCssPixels (): Size { - if (TEST) { - return new Size(window.innerWidth, window.innerHeight); - } - if (this.isProportionalToFrame) { - if (!this._gameContainer) { - warnID(9201); - return new Size(0, 0); - } - return new Size(this._gameContainer.clientWidth, this._gameContainer.clientHeight); - } - let fullscreenTarget; - let width: number; - let height: number; - switch (this._windowType) { - case WindowType.SubFrame: - if (!this._gameFrame) { - warnID(9201); - return new Size(0, 0); - } - return new Size(this._gameFrame.clientWidth, this._gameFrame.clientHeight); - case WindowType.Fullscreen: - fullscreenTarget = this._getFullscreenTarget()!; - width = this.isFrameRotated ? fullscreenTarget.clientHeight : fullscreenTarget.clientWidth; - height = this.isFrameRotated ? fullscreenTarget.clientWidth : fullscreenTarget.clientHeight; - return new Size(width, height); - case WindowType.BrowserWindow: - width = this.isFrameRotated ? window.innerHeight : window.innerWidth; - height = this.isFrameRotated ? window.innerWidth : window.innerHeight; - return new Size(width, height); - case WindowType.Unknown: - default: - return new Size(1, 1); - } - } - private get _windowType (): WindowType { - if (this._isHeadlessMode) { - return WindowType.Unknown; - } - if (this.isFullScreen) { - return WindowType.Fullscreen; - } - if (!this._gameFrame) { - warnID(9201); - return WindowType.Unknown; - } - if (this._exactFitScreen) { - // Note: It doesn't work well to determine whether the frame exact fits the screen. - // Need to specify the attribute from Editor. - return WindowType.BrowserWindow; - } - return WindowType.SubFrame; - } - private _resolutionScale = 1; - private _orientation = Orientation.AUTO;//The orientation set by user. - private _orientationDevice = Orientation.AUTO;//Store the device's orientation. - - constructor () { - super(); - // TODO: need to access frame from 'pal/launcher' module - this._gameFrame = document.getElementById('GameDiv') as HTMLDivElement; - this._gameContainer = document.getElementById('Cocos3dGameContainer') as HTMLDivElement; - this._gameCanvas = document.getElementById('GameCanvas') as HTMLCanvasElement; - // Compability with old preview or build template in Editor. - if (!TEST && !EDITOR) { - if (!this._gameFrame) { - this._gameFrame = document.createElement<'div'>('div'); - this._gameFrame.setAttribute('id', 'GameDiv'); - this._gameCanvas?.parentNode?.insertBefore(this._gameFrame, this._gameCanvas); - this._gameFrame.appendChild(this._gameCanvas); - } - if (!this._gameContainer) { - this._gameContainer = document.createElement<'div'>('div'); - this._gameContainer.setAttribute('id', 'Cocos3dGameContainer'); - this._gameCanvas?.parentNode?.insertBefore(this._gameContainer, this._gameCanvas); - this._gameContainer.appendChild(this._gameCanvas); - } - } - - let fnList: Array; - const fnGroup = this._fnGroup; - for (let i = 0; i < fnGroup.length; i++) { - fnList = fnGroup[i]; - // detect event support - if (typeof document[fnList[1]] !== 'undefined') { - for (let i = 0; i < fnList.length; i++) { - this._fn[fnGroup[0][i]] = fnList[i]; - } - break; - } - } - - this._supportFullScreen = (this._fn.requestFullscreen !== undefined); - this._touchEventName = ('ontouchstart' in window) ? 'touchend' : 'mousedown'; - this._registerEvent(); - } - - public init (options: IScreenOptions, cbToRebuildFrameBuffer: () => void): void { - this._cbToUpdateFrameBuffer = cbToRebuildFrameBuffer; - this.orientation = orientationMap[options.configOrientation]; - this._exactFitScreen = options.exactFitScreen; - this._isHeadlessMode = options.isHeadlessMode; - this._resizeFrame(); - } - - public requestFullScreen (): Promise { - return new Promise((resolve, reject) => { - if (this.isFullScreen) { - resolve(); - return; - } - this._cachedFrameSize = this.windowSize; - this._doRequestFullScreen().then(() => { - resolve(); - }).catch(() => { - const fullscreenTarget = this._getFullscreenTarget(); - if (!fullscreenTarget) { - reject(new Error('Cannot access fullscreen target')); - return; - } - fullscreenTarget.addEventListener(this._touchEventName, () => { - this._doRequestFullScreen().then(() => { - resolve(); - }).catch(reject); - }, { once: true, capture: true }); - }); - }); - } - public exitFullScreen (): Promise { - return new Promise((resolve, reject) => { - const requestPromise = document[this._fn.exitFullscreen](); - if (window.Promise && requestPromise instanceof Promise) { - requestPromise.then(() => { - this.windowSize = this._cachedFrameSize; - resolve(); - }).catch(reject); - return; - } - this.windowSize = this._cachedFrameSize; - resolve(); - }); - } - - private _registerEvent (): void { - document.addEventListener(this._fn.fullscreenerror, (): void => { - this._onFullscreenError?.(); - }); - - window.addEventListener('resize', (): void => { - // if (!this.handleResizeEvent) { - // return; - // } - this._updateFrame(); - }); - - const notifyOrientationChange = (orientation): void => { - if (orientation === this._orientationDevice) { - return; - } - this._orientationDevice = orientation; - this._updateFrame(); - this.emit('orientation-change', orientation); - }; - - const getOrientation = (): Orientation => { - let tmpOrientation = Orientation.PORTRAIT; - switch (window.orientation) { - case 0: - tmpOrientation = Orientation.PORTRAIT; - break; - case 90: - // Handle landscape orientation, top side facing to the right - tmpOrientation = Orientation.LANDSCAPE_RIGHT; - break; - case -90: - // Handle landscape orientation, top side facing to the left - tmpOrientation = Orientation.LANDSCAPE_LEFT; - break; - case 180: - tmpOrientation = Orientation.PORTRAIT_UPSIDE_DOWN; - break; - default: - tmpOrientation = this._orientationDevice; - break; - } - return tmpOrientation; - }; - /*After receive orientation-change event, window.innerWidth & innerHeight may not change immediately, - so we delay EVENT_TIMEOUT to handle orientation-change.*/ - let handleOrientationChange; - const orientationChangeCallback = (): void => { - if (this._orientationChangeTimeoutId !== -1) { - clearTimeout(this._orientationChangeTimeoutId); - } - this._orientationChangeTimeoutId = setTimeout((): void => { - handleOrientationChange(); - }, EVENT_TIMEOUT); - }; - if (typeof window.matchMedia === 'function') { - const updateDPRChangeListener = (): void => { - const dpr = this.devicePixelRatio; - // NOTE: some browsers especially on iPhone doesn't support MediaQueryList - const mediaQueryResolution = window.matchMedia(`(resolution: ${dpr}dppx)`); - if (mediaQueryResolution.addEventListener) { - mediaQueryResolution.addEventListener('change', (): void => { - this.emit('window-resize', this.windowSize.width, this.windowSize.height); - updateDPRChangeListener(); - }, { once: true }); - } else if (mediaQueryResolution.addListener) { - mediaQueryResolution.addListener((): void => { - this.emit('window-resize', this.windowSize.width, this.windowSize.height); - }); - } - }; - updateDPRChangeListener(); - - const mediaQueryPortrait = window.matchMedia('(orientation: portrait)'); - const mediaQueryLandscape = window.matchMedia('(orientation: landscape)'); - // eslint-disable-next-line no-restricted-globals - const hasScreeOrientation = screen.orientation; - handleOrientationChange = (): void => { - let tmpOrientation: Orientation = this._orientationDevice; - if (mediaQueryPortrait.matches) { - tmpOrientation = Orientation.PORTRAIT; - if (hasScreeOrientation) { - // eslint-disable-next-line no-restricted-globals - const orientationType = screen.orientation.type; - if (orientationType === 'portrait-primary') { - tmpOrientation = Orientation.PORTRAIT; - } else { - tmpOrientation = Orientation.PORTRAIT_UPSIDE_DOWN; - } - } - } else if (mediaQueryLandscape.matches) { - tmpOrientation = Orientation.LANDSCAPE; - if (hasScreeOrientation) { - // eslint-disable-next-line no-restricted-globals - const orientationType = screen.orientation.type; - if (orientationType === 'landscape-primary') { - tmpOrientation = Orientation.LANDSCAPE_LEFT; - } else { - tmpOrientation = Orientation.LANDSCAPE_RIGHT; - } - } - } - notifyOrientationChange(tmpOrientation); - }; - if (mediaQueryPortrait.addEventListener) { - mediaQueryPortrait.addEventListener('change', orientationChangeCallback); - mediaQueryLandscape.addEventListener('change', orientationChangeCallback); - } else if (mediaQueryPortrait.addListener) { - mediaQueryPortrait.addListener(orientationChangeCallback); - mediaQueryLandscape.addListener(orientationChangeCallback); - } - } else { - handleOrientationChange = (): void => { - const tmpOrientation = getOrientation(); - notifyOrientationChange(tmpOrientation); - }; - window.addEventListener('orientationchange', orientationChangeCallback); - } - document.addEventListener(this._fn.fullscreenchange, () => { - this._onFullscreenChange?.(); - this.emit('fullscreen-change', this.windowSize.width, this.windowSize.height); - }); - } - private _convertToSizeInCssPixels (size: Size): Size { - const clonedSize = size.clone(); - const dpr = this.devicePixelRatio; - clonedSize.width /= dpr; - clonedSize.height /= dpr; - return clonedSize; - } - - /** - * The frame size may be from screen size or an external editor options by setting screen.windowSize. - * @param sizeInCssPixels you need to specify this size when the windowType is SubFrame. - */ - private _resizeFrame (sizeInCssPixels?: Size): void { - if (!this._gameFrame) { - return; - } - // Center align the canvas - this._gameFrame.style.display = 'flex'; - this._gameFrame.style['justify-content'] = 'center'; - this._gameFrame.style['align-items'] = 'center'; - if (this._windowType === WindowType.SubFrame) { - if (!sizeInCssPixels) { - this._updateContainer(); - return; - } - this._gameFrame.style.width = `${sizeInCssPixels.width}px`; - this._gameFrame.style.height = `${sizeInCssPixels.height}px`; - } else { - const winWidth = window.innerWidth; - let winHeight = window.innerHeight; - //On certain android devices, window.innerHeight may not account for the height of the virtual keyboard, so dynamic calculation is necessary. - const inputHeight = document.body.scrollHeight - winHeight; - if (systemInfo.os === OS.ANDROID && winHeight < inputHeight) { - winHeight += inputHeight; - } - if (this.isFrameRotated) { - this._gameFrame.style['-webkit-transform'] = 'rotate(90deg)'; - this._gameFrame.style.transform = 'rotate(90deg)'; - this._gameFrame.style['-webkit-transform-origin'] = '0px 0px 0px'; - this._gameFrame.style.transformOrigin = '0px 0px 0px'; - this._gameFrame.style.margin = `0 0 0 ${winWidth}px`; - this._gameFrame.style.width = `${winHeight}px`; - this._gameFrame.style.height = `${winWidth}px`; - } else { - this._gameFrame.style['-webkit-transform'] = 'rotate(0deg)'; - this._gameFrame.style.transform = 'rotate(0deg)'; - // TODO - // this._gameFrame.style['-webkit-transform-origin'] = '0px 0px 0px'; - // this._gameFrame.style.transformOrigin = '0px 0px 0px'; - this._gameFrame.style.margin = '0px auto'; - this._gameFrame.style.width = `${winWidth}px`; - this._gameFrame.style.height = `${winHeight}px`; - } - } - - this._updateContainer(); - } - - private _getFullscreenTarget (): HTMLElement | undefined { - const windowType = this._windowType; - if (windowType === WindowType.Fullscreen) { - return document[this._fn.fullscreenElement] as HTMLElement; - } - if (windowType === WindowType.SubFrame) { - return this._gameFrame; - } - // On web mobile, the transform of game frame doesn't work when it's on fullscreen. - // So we need to make the body fullscreen. - return document.body; - } - private _doRequestFullScreen (): Promise { - return new Promise((resolve, reject) => { - if (!this._supportFullScreen) { - reject(new Error('fullscreen is not supported')); - return; - } - const fullscreenTarget = this._getFullscreenTarget(); - if (!fullscreenTarget) { - reject(new Error('Cannot access fullscreen target')); - return; - } - this._onFullscreenChange = undefined; - this._onFullscreenError = undefined; - const requestPromise = fullscreenTarget[this._fn.requestFullscreen]() as Promise | undefined; - if (window.Promise && requestPromise instanceof Promise) { - requestPromise.then(resolve).catch(reject); - } else { - this._onFullscreenChange = resolve; - this._onFullscreenError = reject; - } - }); - } - private _updateFrameState (): void { - const orientation = this.orientation; - const width = window.innerWidth; - const height = window.innerHeight; - const isBrowserLandscape = width > height; - this.isFrameRotated = systemInfo.isMobile - && ((isBrowserLandscape && orientation === Orientation.PORTRAIT) - || (!isBrowserLandscape && orientation === Orientation.LANDSCAPE)); - } - private _updateContainer (): void { - if (!this._gameContainer) { - warnID(9201); - return; - } - if (this.isProportionalToFrame) { - if (!this._gameFrame) { - warnID(9201); - return; - } - // TODO: access designedResolution from Launcher module. - const designedResolution = legacyCC.view.getDesignResolutionSize() as Size; - const frame = this._gameFrame; - const frameW = frame.clientWidth; - const frameH = frame.clientHeight; - const designW = designedResolution.width; - const designH = designedResolution.height; - const scaleX = frameW / designW; - const scaleY = frameH / designH; - const containerStyle = this._gameContainer.style; - let containerW: number; - let containerH: number; - - if (scaleX < scaleY) { - containerW = frameW; - containerH = designH * scaleX; - } else { - containerW = designW * scaleY; - containerH = frameH; - } - // Set window size on game container - containerStyle.width = `${containerW}px`; - containerStyle.height = `${containerH}px`; - } else { - const containerStyle = this._gameContainer.style; - // game container exact fit game frame. - containerStyle.width = '100%'; - containerStyle.height = '100%'; - } - - // Cache Test - if (this._gameFrame - && (this._cachedFrameStyle.width !== this._gameFrame.style.width - || this._cachedFrameStyle.height !== this._gameFrame.style.height - || this._cachedContainerStyle.width !== this._gameContainer.style.width - || this._cachedContainerStyle.height !== this._gameContainer.style.height)) { - this.emit('window-resize', this.windowSize.width, this.windowSize.height); - - // Update Cache - this._cachedFrameStyle.width = this._gameFrame.style.width; - this._cachedFrameStyle.height = this._gameFrame.style.height; - this._cachedContainerStyle.width = this._gameContainer.style.width; - this._cachedContainerStyle.height = this._gameContainer.style.height; - } - } -} - -export const screenAdapter = new ScreenAdapter(); - -checkPalIntegrity(withImpl()); diff --git a/pal/system-info/enum-type/browser-type.ts b/pal/system-info/enum-type/browser-type.ts deleted file mode 100644 index 6437093d26..0000000000 --- a/pal/system-info/enum-type/browser-type.ts +++ /dev/null @@ -1,141 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -export enum BrowserType { - /** - * @en Browser Type - Unknown - * @zh 浏览器类型 - 未知 - */ - UNKNOWN = 'unknown', - /** - * @en Browser Type - WeChat inner browser - * @zh 浏览器类型 - 微信内置浏览器 - */ - WECHAT = 'wechat', - /** - * @en Browser Type - Android Browser - * @zh 浏览器类型 - 安卓浏览器 - */ - ANDROID = 'androidbrowser', - /** - * @en Browser Type - Internet Explorer - * @zh 浏览器类型 - 微软 IE - */ - IE = 'ie', - /** - * @en Browser Type - Microsoft Edge - * @zh 浏览器类型 - 微软 Edge - */ - EDGE = 'edge', - /** - * @en Browser Type - QQ Browser - * @zh 浏览器类型 - QQ 浏览器 - */ - QQ = 'qqbrowser', - /** - * @en Browser Type - Mobile QQ Browser - * @zh 浏览器类型 - 手机 QQ 浏览器 - */ - MOBILE_QQ = 'mqqbrowser', - /** - * @en Browser Type - UC Browser - * @zh 浏览器类型 - UC 浏览器 - */ - UC = 'ucbrowser', - /** - * @en Browser Type - Third party integrated UC browser - * @zh 浏览器类型 - 第三方应用中集成的 UC 浏览器 - */ - UCBS = 'ucbs', - /** - * @en Browser Type - 360 Browser - * @zh 浏览器类型 - 360 浏览器 - */ - BROWSER_360 = '360browser', - /** - * @en Browser Type - Baidu Box App - * @zh 浏览器类型 - Baidu Box App - */ - BAIDU_APP = 'baiduboxapp', - /** - * @en Browser Type - Baidu Browser - * @zh 浏览器类型 - 百度浏览器 - */ - BAIDU = 'baidubrowser', - /** - * @en Browser Type - Maxthon Browser - * @zh 浏览器类型 - 傲游浏览器 - */ - MAXTHON = 'maxthon', - /** - * @en Browser Type - Opera Browser - * @zh 浏览器类型 - Opera 浏览器 - */ - OPERA = 'opera', - /** - * @en Browser Type - Oupeng Browser - * @zh 浏览器类型 - 欧朋浏览器 - */ - OUPENG = 'oupeng', - /** - * @en Browser Type - MI UI Browser - * @zh 浏览器类型 - MIUI 内置浏览器 - */ - MIUI = 'miuibrowser', - /** - * @en Browser Type - Firefox Browser - * @zh 浏览器类型 - Firefox 浏览器 - */ - FIREFOX = 'firefox', - /** - * @en Browser Type - Safari Browser - * @zh 浏览器类型 - Safari 浏览器 - */ - SAFARI = 'safari', - /** - * @en Browser Type - Chrome Browser - * @zh 浏览器类型 - Chrome 浏览器 - */ - CHROME = 'chrome', - /** - * @en Browser Type - Cheetah Browser - * @zh 浏览器类型 - 猎豹浏览器 - */ - LIEBAO = 'liebao', - /** - * @en Browser Type - QZone Inner Browser - * @zh 浏览器类型 - QZone 内置浏览器 - */ - QZONE = 'qzone', - /** - * @en Browser Type - Sogou Browser - * @zh 浏览器类型 - 搜狗浏览器 - */ - SOUGOU = 'sogou', - /** - * @en Browser Type - Huawei Browser - * @zh 浏览器类型 - 华为浏览器 - */ - HUAWEI = 'huawei', -} diff --git a/pal/system-info/enum-type/event.ts b/pal/system-info/enum-type/event.ts deleted file mode 100644 index aadc531552..0000000000 --- a/pal/system-info/enum-type/event.ts +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -export type PalSystemEvent = 'hide' | 'show' | 'close'; diff --git a/pal/system-info/enum-type/feature.ts b/pal/system-info/enum-type/feature.ts deleted file mode 100644 index 43aeefc19a..0000000000 --- a/pal/system-info/enum-type/feature.ts +++ /dev/null @@ -1,115 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -export enum Feature { - /** - * @en Feature to support Webp. - * @zh 是否支持 Webp 特性。 - */ - WEBP = 'WEBP', - /** - * @en Feature to support Image Bitmap. - * @zh 是否支持 Image Bitmap 特性。 - */ - IMAGE_BITMAP = 'IMAGE_BITMAP', - /** - * @en Feature to support Web View. - * @zh 是否支持 Web View 特性。 - */ - WEB_VIEW = 'WEB_VIEW', - /** - * @en Feature to support Video Player. - * @zh 是否支持 Video Player 特性。 - */ - VIDEO_PLAYER = 'VIDEO_PLAYER', - /** - * @en Feature to support Safe Area. - * @zh 是否支持 Safe Area 特性。 - */ - SAFE_AREA = 'SAFE_AREA', - - /** - * @en Feature to support HPE (high performance emulator) platforms, such as Google Play Games For PC. - * @zh 是否支持 HPE 平台, 比如: Android 的 Google Play Games 在 PC 上的模拟器. - */ - HPE = 'HPE', - - /** - * @en Feature to support Touch Input. - * Touch Input is only supported on some devices with touch screen. - * This feature tells that whether the device has a touch screen. - * @zh 是否支持触摸输入。 - * 触摸输入只在一些带触摸屏的设备上支持。 - * 这个特性旨在说明设备上是否带触摸屏。 - */ - INPUT_TOUCH = 'INPUT_TOUCH', - /** - * @en Feature to support dispatching EventKeyboard. - * @zh 是否支持派发 EventKeyboard。 - */ - EVENT_KEYBOARD = 'EVENT_KEYBOARD', - /** - * @en Feature to support dispatching EventMouse. - * @zh 是否支持派发 EventMouse。 - */ - EVENT_MOUSE = 'EVENT_MOUSE', - /** - * @en Feature to support dispatching EventTouch. - * On some devices without touch screen, we still can simulate dispatching EventTouch from EventMouse. - * @zh 是否支持派发 EventTouch。 - * 在一些不带触摸屏的设备上,我们仍然会从 EventMouse 模拟派发 EventTouch。 - */ - EVENT_TOUCH = 'EVENT_TOUCH', - /** - * @en Feature to support dispatching EventAcceleration. - * @zh 是否支持派发 EventAcceleration。 - */ - EVENT_ACCELEROMETER = 'EVENT_ACCELEROMETER', - /** - * @en Feature to support dispatching EventGamepad. - * @zh 是否支持派发 EventGamepad. - */ - EVENT_GAMEPAD = 'EVENT_GAMEPAD', - /** - * @en Feature to support dispatching EventHandle. - * @zh 是否支持派发 EventHandle - */ - EVENT_HANDLE = 'EVENT_HANDLE', - /** - * @en Feature to support dispatching EventHMD. - * @zh 是否支持派发 EventHMD - */ - EVENT_HMD = 'EVENT_HMD', - /** - * @en Feature to support dispatching EventHandheld. - * @zh 是否支持派发 EventHandheld - */ - EVENT_HANDHELD = 'EVENT_HANDHELD', - /** - * @en Check whether Webassembly is supported at runtime. Generally, it needs to be checked when the constant `NATIVE_CODE_BUNDLE_MODE` is 2. - * If it is not supported, you need to fallback to the Asm solution. - * @zh 运行时检测是否支持 Webassembly,一般在宏 `NATIVE_CODE_BUNDLE_MODE` 为 2 时需要检测,如果不支持,需要回滚到 Asm 方案 - */ - WASM = 'WASM', -} diff --git a/pal/system-info/enum-type/index.ts b/pal/system-info/enum-type/index.ts deleted file mode 100644 index 9c79deb649..0000000000 --- a/pal/system-info/enum-type/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -export * from './browser-type'; -export * from './event'; -export * from './language'; -export * from './network-type'; -export * from './operating-system'; -export * from './platform'; -export * from './feature'; diff --git a/pal/system-info/enum-type/language.ts b/pal/system-info/enum-type/language.ts deleted file mode 100644 index 4ae71fb08a..0000000000 --- a/pal/system-info/enum-type/language.ts +++ /dev/null @@ -1,151 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -export enum Language { - /** - * @en Unknown language code - * @zh 语言代码 - 未知 - */ - UNKNOWN = 'unknown', - - /** - * @en English language code - * @zh 语言代码 - 英语 - */ - ENGLISH = 'en', - - /** - * @en Chinese language code - * @zh 语言代码 - 中文 - */ - CHINESE = 'zh', - - /** - * @en French language code - * @zh 语言代码 - 法语 - */ - FRENCH = 'fr', - - /** - * @en Italian language code - * @zh 语言代码 - 意大利语 - */ - ITALIAN = 'it', - - /** - * @en German language code - * @zh 语言代码 - 德语 - */ - GERMAN = 'de', - - /** - * @en Spanish language code - * @zh 语言代码 - 西班牙语 - */ - SPANISH = 'es', - - /** - * @en Spanish language code - * @zh 语言代码 - 荷兰语 - */ - DUTCH = 'du', - - /** - * @en Russian language code - * @zh 语言代码 - 俄罗斯语 - */ - RUSSIAN = 'ru', - - /** - * @en Korean language code - * @zh 语言代码 - 韩语 - */ - KOREAN = 'ko', - - /** - * @en Japanese language code - * @zh 语言代码 - 日语 - */ - JAPANESE = 'ja', - - /** - * @en Hungarian language code - * @zh 语言代码 - 匈牙利语 - */ - HUNGARIAN = 'hu', - - /** - * @en Portuguese language code - * @zh 语言代码 - 葡萄牙语 - */ - PORTUGUESE = 'pt', - - /** - * @en Arabic language code - * @zh 语言代码 - 阿拉伯语 - */ - ARABIC = 'ar', - - /** - * @en Norwegian language code - * @zh 语言代码 - 挪威语 - */ - NORWEGIAN = 'no', - - /** - * @en Polish language code - * @zh 语言代码 - 波兰语 - */ - POLISH = 'pl', - - /** - * @en Turkish language code - * @zh 语言代码 - 土耳其语 - */ - TURKISH = 'tr', - - /** - * @en Ukrainian language code - * @zh 语言代码 - 乌克兰语 - */ - UKRAINIAN = 'uk', - - /** - * @en Romanian language code - * @zh 语言代码 - 罗马尼亚语 - */ - ROMANIAN = 'ro', - - /** - * @en Bulgarian language code - * @zh 语言代码 - 保加利亚语 - */ - BULGARIAN = 'bg', - - /** - * @en Hindi language code - * @zh 语言代码 - 印度语 - */ - HINDI = 'hi', -} diff --git a/pal/system-info/enum-type/network-type.ts b/pal/system-info/enum-type/network-type.ts deleted file mode 100644 index 45ad52704f..0000000000 --- a/pal/system-info/enum-type/network-type.ts +++ /dev/null @@ -1,41 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -export enum NetworkType { - /** - * @en Network is unreachable. - * @zh 网络不通 - */ - NONE, - /** - * @en Network is reachable via WiFi or cable. - * @zh 通过无线或者有线本地网络连接因特网 - */ - LAN, - /** - * @en Network is reachable via Wireless Wide Area Network - * @zh 通过蜂窝移动网络连接因特网 - */ - WWAN, -} diff --git a/pal/system-info/enum-type/operating-system.ts b/pal/system-info/enum-type/operating-system.ts deleted file mode 100644 index 128c6b77a5..0000000000 --- a/pal/system-info/enum-type/operating-system.ts +++ /dev/null @@ -1,66 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -export enum OS { - /** - * @en Operating System - Unknown - * @zh 操作系统 - 未知 - */ - UNKNOWN = 'Unknown', - /** - * @en Operating System - iOS - * @zh 操作系统 - iOS - */ - IOS = 'iOS', - /** - * @en Operating System - Android - * @zh 操作系统 - 安卓 - */ - ANDROID = 'Android', - /** - * @en Operating System - Windows - * @zh 操作系统 - Windows - */ - WINDOWS = 'Windows', - /** - * @en Operating System - Linux - * @zh 操作系统 - Linux - */ - LINUX = 'Linux', - /** - * @en Operating System - Mac OS X - * @zh 操作系统 - Mac OS X - */ - OSX = 'OS X', - /** - * @en Operating System - HarmonyOS - * @zh 操作系统 - 鸿蒙 - */ - OHOS = 'OHOS', - /** - * @en Operating System - OpenHarmony - * @zh 操作系统 - OpenHarmony - */ - OPENHARMONY = 'OpenHarmony', -} diff --git a/pal/system-info/enum-type/platform.ts b/pal/system-info/enum-type/platform.ts deleted file mode 100644 index 3905ea228e..0000000000 --- a/pal/system-info/enum-type/platform.ts +++ /dev/null @@ -1,56 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -export enum Platform { - UNKNOWN = 'UNKNOWN', - // Web Based - EDITOR_PAGE = 'EDITOR_PAGE', - EDITOR_CORE = 'EDITOR_CORE', - NODEJS_PAGE = 'NODEJS_PAGE', - MOBILE_BROWSER = 'MOBILE_BROWSER', - DESKTOP_BROWSER = 'DESKTOP_BROWSER', - // Native - WIN32 = 'WIN32', - ANDROID = 'ANDROID', - IOS = 'IOS', - MACOS = 'MACOS', - OHOS = 'OHOS', - OPENHARMONY = 'OPENHARMONY', - // Minigame - WECHAT_GAME = 'WECHAT_GAME', - WECHAT_MINI_PROGRAM = 'WECHAT_MINI_PROGRAM', - XIAOMI_QUICK_GAME = 'XIAOMI_QUICK_GAME', - ALIPAY_MINI_GAME = 'ALIPAY_MINI_GAME', - TAOBAO_CREATIVE_APP = 'TAOBAO_CREATIVE_APP', - TAOBAO_MINI_GAME = 'TAOBAO_MINI_GAME', - BYTEDANCE_MINI_GAME = 'BYTEDANCE_MINI_GAME', - // Runtime Based - OPPO_MINI_GAME = 'OPPO_MINI_GAME', - VIVO_MINI_GAME = 'VIVO_MINI_GAME', - HUAWEI_QUICK_GAME = 'HUAWEI_QUICK_GAME', - MIGU_MINI_GAME = 'MIGU_MINI_GAME', - HONOR_MINI_GAME = 'HONOR_MINI_GAME', - SUD_MINI_GAME = 'SUD_MINI_GAME', - SUDV2_MINI_GAME = 'SUDV2_MINI_GAME', -} diff --git a/pal/system-info/minigame/system-info.ts b/pal/system-info/minigame/system-info.ts deleted file mode 100644 index 70b50beaa2..0000000000 --- a/pal/system-info/minigame/system-info.ts +++ /dev/null @@ -1,385 +0,0 @@ -/* eslint-disable @typescript-eslint/unbound-method */ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { ALIPAY, BYTEDANCE, HUAWEI, OPPO, RUNTIME_BASED, SUD, SUDV2, VIVO, MIGU, HONOR, WECHAT, XIAOMI, DEBUG, TEST, TAOBAO, TAOBAO_MINIGAME, WECHAT_MINI_PROGRAM } from 'internal:constants'; -import { minigame, SystemInfo as MinigameSystemInfo, WindowInfo } from 'pal/minigame'; -import { IFeatureMap } from 'pal/system-info'; -import { EventTarget } from '../../../cocos/core/event'; -import { checkPalIntegrity, withImpl } from '../../integrity-check'; -import { BrowserType, NetworkType, OS, Platform, Language, Feature } from '../enum-type'; -import { warn } from '../../../cocos/core/platform/debug'; -import { versionCompare } from '../../utils'; - -// NOTE: register minigame platform here -let currentPlatform: Platform; -if (WECHAT) { - currentPlatform = Platform.WECHAT_GAME; -} else if (WECHAT_MINI_PROGRAM) { - currentPlatform = Platform.WECHAT_MINI_PROGRAM; -} else if (XIAOMI) { - currentPlatform = Platform.XIAOMI_QUICK_GAME; -} else if (ALIPAY) { - currentPlatform = Platform.ALIPAY_MINI_GAME; -} else if (TAOBAO) { - currentPlatform = Platform.TAOBAO_CREATIVE_APP; -} else if (TAOBAO_MINIGAME) { - currentPlatform = Platform.TAOBAO_MINI_GAME; -} else if (BYTEDANCE) { - currentPlatform = Platform.BYTEDANCE_MINI_GAME; -} else if (OPPO) { - currentPlatform = Platform.OPPO_MINI_GAME; -} else if (VIVO) { - currentPlatform = Platform.VIVO_MINI_GAME; -} else if (HUAWEI) { - currentPlatform = Platform.HUAWEI_QUICK_GAME; -} else if (MIGU) { - currentPlatform = Platform.MIGU_MINI_GAME; -} else if (HONOR) { - currentPlatform = Platform.HONOR_MINI_GAME; -} else if (SUD) { - currentPlatform = Platform.SUD_MINI_GAME; -} else if (SUDV2) { - currentPlatform = Platform.SUDV2_MINI_GAME; -} - -let isVersionGreaterOrEqualTo; -if (BYTEDANCE) { - isVersionGreaterOrEqualTo = function isVersionGreaterOrEqualTo (versionA: string, versionB: string): boolean { - if (!versionA || !versionB) { - return false; - } - // Split the version number string into an array of integers - function parseVersion (version: string): number[] { - return version.split('.').map((part: string) => parseInt(part, 10)); - } - - // Parse the version number strings into arrays - const versionArrayA = parseVersion(versionA); - const versionArrayB = parseVersion(versionB); - - if (versionArrayA.length !== versionArrayB.length) { - return false; - } - - // Compare versions level by level - for (let i = 0; i < versionArrayA.length; i++) { - if (versionArrayA[i] > versionArrayB[i]) { - // versionA > versionB - return true; - } else if (versionArrayA[i] < versionArrayB[i]) { - // versionA < versionB - return false; - } - } - - // versionA === versionB - return true; - }; -} - -const originalGetSystemInfoSync = minigame.getSystemInfoSync; -// Some platforms may not have this interface(getWindowInfo). -const originalGetWindowInfo = minigame.getWindowInfo; -let _cachedSystemInfo: MinigameSystemInfo = originalGetSystemInfoSync.call(minigame); -let _cachedWindowInfo: WindowInfo | undefined = originalGetWindowInfo?.call(minigame); - -function testAndUpdateSystemInfoCache (testAmount: number, testInterval: number): void { - let successfullyTestTimes = 0; - let intervalTimer: number | null = null; - function testCachedSystemInfo (): void { - const currentSystemInfo = originalGetSystemInfoSync.call(minigame); - if (_cachedSystemInfo.screenWidth === currentSystemInfo.screenWidth && _cachedSystemInfo.screenHeight === currentSystemInfo.screenHeight) { - if (++successfullyTestTimes >= testAmount && intervalTimer !== null) { - clearInterval(intervalTimer); - intervalTimer = null; - } - } else { - successfullyTestTimes = 0; - } - _cachedSystemInfo = currentSystemInfo; - } - intervalTimer = setInterval(testCachedSystemInfo, testInterval); -} - -if (WECHAT && versionCompare(minigame.getAppBaseInfo().SDKVersion, '2.25.3') < 0) { - testAndUpdateSystemInfoCache(10, 500); -} - -minigame.onWindowResize?.(() => { - // update cached system info - _cachedSystemInfo = originalGetSystemInfoSync.call(minigame); - _cachedWindowInfo = originalGetWindowInfo?.call(minigame); -}); - -minigame.getSystemInfoSync = function (): MinigameSystemInfo { - return _cachedSystemInfo; -}; - -if (originalGetWindowInfo !== undefined) { - minigame.getWindowInfo = function (): WindowInfo { - return _cachedWindowInfo!; - }; -} - -class SystemInfo extends EventTarget { - public declare readonly networkType: NetworkType; - public declare readonly isNative: boolean; - public declare readonly isBrowser: boolean; - public declare readonly isMobile: boolean; - public declare readonly isLittleEndian: boolean; - public declare readonly platform: Platform; - public declare readonly language: Language; - public declare readonly nativeLanguage: string; - public declare readonly os: OS; - public declare readonly osVersion: string; - public declare readonly osMainVersion: number; - public declare readonly browserType: BrowserType; - public declare readonly browserVersion: string; - public declare readonly isXR: boolean; - private declare _featureMap: IFeatureMap; - private _initPromise: Promise[] = []; - - constructor () { - super(); - const minigameSysInfo = minigame.getSystemInfoSync(); - this.networkType = NetworkType.LAN; // TODO - this.isNative = false; - this.isBrowser = false; - - // init isLittleEndian - this.isLittleEndian = ((): boolean => { - const buffer = new ArrayBuffer(2); - new DataView(buffer).setInt16(0, 256, true); - // Int16Array uses the platform's endianness. - return new Int16Array(buffer)[0] === 256; - })(); - - // init languageCode and language - this.nativeLanguage = minigameSysInfo.language; - this.language = minigameSysInfo.language.substring(0, 2) as Language; - - // init os, osVersion and osMainVersion - const minigamePlatform = minigameSysInfo.platform.toLocaleLowerCase(); - switch (minigamePlatform) { - case 'android': - this.os = OS.ANDROID; - break; - case 'ios': - this.os = OS.IOS; - break; - case 'windows': - this.os = OS.WINDOWS; - break; - case 'mac': - this.os = OS.OSX; - break; - default: - this.os = OS.UNKNOWN; - break; - } - - let minigameSystem = minigameSysInfo.system.toLowerCase(); - // Adaptation to Android P - if (minigameSystem === 'android p') { - minigameSystem = 'android p 9.0'; - } - const version = /[\d.]+/.exec(minigameSystem); - this.osVersion = version ? version[0] : minigameSystem; - this.osMainVersion = parseInt(this.osVersion); - - // init isMobile and platform - this.platform = currentPlatform; - // Some minigame platforms don't support getting the platform, such as runtime and Xiaomi, so this.os returns UNKNOWN. - // Most platforms are mobile, so set UNKNOWN to mobile. - this.isMobile = this.os === OS.ANDROID || this.os === OS.IOS || this.os === OS.UNKNOWN; - - // init browserType and browserVersion - this.browserType = BrowserType.UNKNOWN; - this.browserVersion = ''; - - this.isXR = false; - - const isPCWechat = WECHAT && this.os === OS.WINDOWS && !minigame.isDevTool; - - const supportWasm = ((): boolean => { - if (WECHAT) { - return true; - } - - if (BYTEDANCE) { - let minSDKVersionSupportWasm = ''; - if (this.os === OS.ANDROID) { - minSDKVersionSupportWasm = '3.9.0'; - } else if (this.os === OS.IOS) { - minSDKVersionSupportWasm = '3.8.0'; - } - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-expect-error TTWebAssembly is defined if bytedance client supports wasm. - if (isVersionGreaterOrEqualTo(minigameSysInfo.SDKVersion, minSDKVersionSupportWasm) && typeof TTWebAssembly === 'object') { - return true; - } - } - - if (RUNTIME_BASED) { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-expect-error ral.WebAssembly is defined if runtime based platform supports wasm. - if (typeof ral.WebAssembly === 'object') { - return true; - } - } - - return false; - })(); - - this._featureMap = { - [Feature.WEBP]: false, // Initialize in Promise, - [Feature.IMAGE_BITMAP]: false, - [Feature.WEB_VIEW]: false, - [Feature.VIDEO_PLAYER]: WECHAT || WECHAT_MINI_PROGRAM || OPPO, - [Feature.SAFE_AREA]: WECHAT || WECHAT_MINI_PROGRAM || BYTEDANCE, - [Feature.HPE]: false, - - [Feature.INPUT_TOUCH]: !isPCWechat, - [Feature.EVENT_KEYBOARD]: isPCWechat, - [Feature.EVENT_MOUSE]: isPCWechat, - [Feature.EVENT_TOUCH]: true, - [Feature.EVENT_ACCELEROMETER]: !isPCWechat, - [Feature.EVENT_GAMEPAD]: false, - [Feature.EVENT_HANDLE]: this.isXR, - [Feature.EVENT_HMD]: this.isXR, - [Feature.EVENT_HANDHELD]: false, - [Feature.WASM]: supportWasm, - }; - - this._initPromise.push(this._supportsWebpPromise()); - - this._registerEvent(); - } - - private _supportsWebpPromise (): Promise { - if (!TEST) { - return this._supportsWebp().then((isSupport) => { - this._setFeature(Feature.WEBP, isSupport); - }); - } - return Promise.resolve(); - } - - private _supportsWebp (): Promise { - return new Promise((resolve, reject) => { - if (WECHAT_MINI_PROGRAM) { - resolve(true); - return; - } - // HACK: webp base64 doesn't support on Wechat Android, which reports some internal error log. - if (WECHAT && this.os === OS.ANDROID) { - resolve(false); - return; - } - try { - const img = document.createElement('img'); - const timer = setTimeout((): void => { - resolve(false); - }, 500); - img.onload = function onload (): void { - clearTimeout(timer); - const result = (img.width > 0) && (img.height > 0); - resolve(result); - }; - img.onerror = function onerror (err): void { - clearTimeout(timer); - if (DEBUG) { - // eslint-disable-next-line @typescript-eslint/no-base-to-string - warn('Create Webp image failed, message: '.concat(err.toString())); - } - resolve(false); - }; - img.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA'; - } catch (error) { - resolve(false); - } - }); - } - - private _registerEvent (): void { - minigame.onHide((): void => { - this.emit('hide'); - }); - minigame.onShow((): void => { - this.emit('show'); - }); - } - - private _setFeature (feature: Feature, value: boolean): boolean { - return this._featureMap[feature] = value; - } - - public init (): Promise { - return Promise.all(this._initPromise); - } - - public hasFeature (feature: Feature): boolean { - return this._featureMap[feature]; - } - - public getBatteryLevel (): number { - return minigame.getBatteryInfoSync().level / 100; - } - public triggerGC (): void { - minigame.triggerGC?.(); - } - public openURL (url: string): void { - if (DEBUG) { - warn('openURL is not supported'); - } - } - public now (): number { - if (Date.now) { - return Date.now(); - } - - return +(new Date()); - } - public restartJSVM (): void { - if (DEBUG) { - warn('restartJSVM is not supported.'); - } - } - - public exit (): void { - minigame.exitMiniProgram?.(); - } - - public close (): void { - // TODO(qgh):The minigame platform does not have an exit interface, - // so there is no need to send a close message to the engine to release resources. - // this.emit('close'); - this.exit(); - } -} - -export const systemInfo = new SystemInfo(); - -checkPalIntegrity(withImpl()); diff --git a/pal/system-info/native/system-info.ts b/pal/system-info/native/system-info.ts deleted file mode 100644 index 97f3a101cb..0000000000 --- a/pal/system-info/native/system-info.ts +++ /dev/null @@ -1,199 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { OPEN_HARMONY, IOS } from 'internal:constants'; -import { EventTarget } from '../../../cocos/core/event'; -import { checkPalIntegrity, withImpl } from '../../integrity-check'; -import { BrowserType, NetworkType, OS, Platform, Language, Feature } from '../enum-type'; - -type IFeatureMap = { - [feature in Feature]: boolean; -}; - -// NOTE: these methods are implemented on native. -declare function __getPlatform(): string; -declare function __getCurrentLanguageCode(): string; -declare function __getCurrentLanguage(): Language; -declare function __getOS(): OS; -declare function __getOSVersion(): string; -declare const __supportHPE: (() => boolean) | undefined; -declare function __restartVM(): void; -declare function __close(): void; -declare function __exit(): void; - -const networkTypeMap: Record = { - 0: NetworkType.NONE, - 1: NetworkType.LAN, - 2: NetworkType.WWAN, -}; -const platformMap: Record = { - 0: Platform.WIN32, - // 1 is Linux platform in native engine - 2: Platform.MACOS, - 3: Platform.ANDROID, - // 4 is IPHONE - 4: Platform.IOS, - // 5 is IPAD - 5: Platform.IOS, - 6: Platform.OHOS, - 7: Platform.OPENHARMONY, -}; - -class SystemInfo extends EventTarget { - public declare readonly isNative: boolean; - public declare readonly isBrowser: boolean; - public declare readonly isMobile: boolean; - public declare readonly isLittleEndian: boolean; - public declare readonly platform: Platform; - public declare readonly language: Language; - public declare readonly nativeLanguage: string; - public declare readonly os: OS; - public declare readonly osVersion: string; - public declare readonly osMainVersion: number; - public declare readonly browserType: BrowserType; - public declare readonly browserVersion: string; - public declare readonly isXR: boolean; - private declare _featureMap: IFeatureMap; - private _initPromise: Promise[] = []; - // TODO: need to wrap the function __isObjectValid() - - public get networkType (): NetworkType { - return networkTypeMap[jsb.device.getNetworkType()]; - } - - constructor () { - super(); - this.isNative = true; - this.isBrowser = false; - - this.platform = platformMap[__getPlatform()]; - // eslint-disable-next-line max-len - this.isMobile = this.platform === Platform.ANDROID || this.platform === Platform.IOS || this.platform === Platform.OHOS || this.platform === Platform.OPENHARMONY; - - // init isLittleEndian - this.isLittleEndian = ((): boolean => { - const buffer = new ArrayBuffer(2); - new DataView(buffer).setInt16(0, 256, true); - // Int16Array uses the platform's endianness. - return new Int16Array(buffer)[0] === 256; - })(); - - // init languageCode and language - const currLanguage = __getCurrentLanguageCode(); - this.nativeLanguage = currLanguage ? currLanguage.toLowerCase() : Language.UNKNOWN; - this.language = __getCurrentLanguage(); - - this.os = __getOS(); - this.osVersion = __getOSVersion(); - this.osMainVersion = parseInt(this.osVersion); - - // init browserType and browserVersion - this.browserType = BrowserType.UNKNOWN; - this.browserVersion = ''; - - this.isXR = (typeof xr !== 'undefined' && typeof xr.XrEntry !== 'undefined'); - - const isHPE: boolean = typeof __supportHPE === 'function' ? __supportHPE() : false; - const isHarmonyOSNext = this.platform === Platform.OPENHARMONY; - - this._featureMap = { - [Feature.WEBP]: true, - [Feature.IMAGE_BITMAP]: false, - [Feature.WEB_VIEW]: this.isMobile, - [Feature.VIDEO_PLAYER]: this.isMobile, - [Feature.SAFE_AREA]: this.isMobile, - [Feature.HPE]: isHPE, - - [Feature.INPUT_TOUCH]: this.isMobile, - [Feature.EVENT_KEYBOARD]: true, - [Feature.EVENT_MOUSE]: isHPE || !this.isMobile || isHarmonyOSNext, - [Feature.EVENT_TOUCH]: true, - [Feature.EVENT_ACCELEROMETER]: this.isMobile, - [Feature.EVENT_GAMEPAD]: true, - [Feature.EVENT_HANDLE]: this.isXR, - [Feature.EVENT_HMD]: this.isXR, - [Feature.EVENT_HANDHELD]: (typeof xr !== 'undefined' && typeof xr.ARModule !== 'undefined'), - // Although the iOS OS supports WASM, the engine does not yet support loading WASM on this platform. - [Feature.WASM]: !OPEN_HARMONY && !IOS, - }; - - this._registerEvent(); - } - - private _registerEvent (): void { - jsb.onPause = (): void => { - this.emit('hide'); - }; - jsb.onResume = (): void => { - this.emit('show'); - }; - jsb.onClose = (): void => { - this.emit('close'); - }; - } - - private _setFeature (feature: Feature, value: boolean): boolean { - return this._featureMap[feature] = value; - } - - public init (): Promise { - return Promise.all(this._initPromise); - } - - public hasFeature (feature: Feature): boolean { - return this._featureMap[feature]; - } - - public getBatteryLevel (): number { - return jsb.device.getBatteryLevel(); - } - public triggerGC (): void { - jsb.garbageCollect(); - } - public openURL (url: string): void { - jsb.openURL(url); - } - public now (): number { - if (Date.now) { - return Date.now(); - } - - return +(new Date()); - } - public restartJSVM (): void { - __restartVM(); - } - - public close (): void { - __close(); - } - - public exit (): void { - __exit(); - } -} - -export const systemInfo = new SystemInfo(); - -checkPalIntegrity(withImpl()); diff --git a/pal/system-info/nodejs/system-info.ts b/pal/system-info/nodejs/system-info.ts deleted file mode 100644 index d4b42eccbb..0000000000 --- a/pal/system-info/nodejs/system-info.ts +++ /dev/null @@ -1,164 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ -import { DEBUG } from 'internal:constants'; -import { IFeatureMap } from 'pal/system-info'; -import { EventTarget } from '../../../cocos/core/event'; -import { checkPalIntegrity, withImpl } from '../../integrity-check'; -import { BrowserType, NetworkType, OS, Platform, Language, Feature } from '../enum-type'; -import { warn } from '../../../cocos/core/platform/debug'; - -class SystemInfo extends EventTarget { - public declare readonly networkType: NetworkType; - public declare readonly isNative: boolean; - public declare readonly isBrowser: boolean; - public declare readonly isMobile: boolean; - public declare readonly isLittleEndian: boolean; - public declare readonly platform: Platform; - public declare readonly language: Language; - public declare readonly nativeLanguage: string; - public declare readonly os: OS; - public declare readonly osVersion: string; - public declare readonly osMainVersion: number; - public declare readonly browserType: BrowserType; - public declare readonly browserVersion: string; - public declare readonly isXR: boolean; - private declare _featureMap: IFeatureMap; - private _initPromise: Promise[] = []; - - constructor () { - super(); - - this.networkType = NetworkType.LAN; // TODO - this.isNative = false; - this.isBrowser = false; - - this.isMobile = false; - this.platform = Platform.NODEJS_PAGE; // TODO - - this.browserType = BrowserType.UNKNOWN; - this.browserVersion = ''; - - const osInfo = globalThis.nodeEnv.require('os'); - let osName = OS.UNKNOWN; - if (osInfo.type().indexOf('wiWindows_NTn') !== -1) { - osName = OS.WINDOWS; - } else if (osInfo.type().indexOf('Darwin') !== -1) { - osName = OS.OSX; - } else if (osInfo.type().indexOf('Linux') !== -1) { - osName = OS.LINUX; - } - this.os = osName; - this.osVersion = osInfo.release(); - this.osMainVersion = parseInt(this.osVersion); - - // init isLittleEndian - this.isLittleEndian = ((): boolean => { - const buffer = new ArrayBuffer(2); - new DataView(buffer).setInt16(0, 256, true); - // Int16Array uses the platform's endianness. - return new Int16Array(buffer)[0] === 256; - })(); - - // init languageCode and language - let currLanguage = globalThis.nodeEnv.systemLanguage; - this.nativeLanguage = currLanguage.toLowerCase(); - currLanguage = currLanguage ? currLanguage.split('-')[0] : Language.ENGLISH; - this.language = currLanguage as Language; - - this.isXR = false; - this._featureMap = { - [Feature.WEBP]: true, - [Feature.IMAGE_BITMAP]: false, - [Feature.WEB_VIEW]: false, - [Feature.VIDEO_PLAYER]: false, - [Feature.SAFE_AREA]: false, - [Feature.HPE]: false, - - [Feature.INPUT_TOUCH]: false, - [Feature.EVENT_KEYBOARD]: false, - [Feature.EVENT_MOUSE]: false, - [Feature.EVENT_TOUCH]: false, - [Feature.EVENT_ACCELEROMETER]: false, - // NOTE: webkitGetGamepads is not standard web interface - [Feature.EVENT_GAMEPAD]: false, - [Feature.EVENT_HANDLE]: false, - [Feature.EVENT_HMD]: false, - [Feature.EVENT_HANDHELD]: false, - [Feature.WASM]: true, - }; - - } - - public init (): Promise { - return Promise.all(this._initPromise); - } - - public hasFeature (feature: Feature): boolean { - return this._featureMap[feature]; - } - - public getBatteryLevel (): number { - if (DEBUG) { - warn("getBatteryLevel is not supported."); - } - return 1; - } - - public triggerGC (): void { - if (global.gc) { - global.gc(); - } - } - - public openURL (url: string): void { - var open = globalThis.nodeEnv.require('open'); - open(url); - } - - public now (): number { - if (Date.now) { - return Date.now(); - } - - return +(new Date()); - } - - public restartJSVM (): void { - if (DEBUG) { - warn('restartJSVM is not supported.'); - } - } - - public exit (): void { - globalThis.nodeEnv.process.exit(); - } - - public close (): void { - this.emit('close'); - } -} - -export const systemInfo = new SystemInfo(); - -checkPalIntegrity(withImpl()); diff --git a/pal/system-info/web/system-info.ts b/pal/system-info/web/system-info.ts deleted file mode 100644 index 7047883474..0000000000 --- a/pal/system-info/web/system-info.ts +++ /dev/null @@ -1,401 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { DEBUG, EDITOR, PREVIEW, TEST } from 'internal:constants'; -import { IFeatureMap } from 'pal/system-info'; -import { EventTarget } from '../../../cocos/core/event'; -import { checkPalIntegrity, withImpl } from '../../integrity-check'; -import { BrowserType, NetworkType, OS, Platform, Language, Feature } from '../enum-type'; -import { warn } from '../../../cocos/core/platform/debug'; - -class SystemInfo extends EventTarget { - public declare readonly networkType: NetworkType; - public declare readonly isNative: boolean; - public declare readonly isBrowser: boolean; - public declare readonly isMobile: boolean; - public declare readonly isLittleEndian: boolean; - public declare readonly platform: Platform; - public declare readonly language: Language; - public declare readonly nativeLanguage: string; - public declare readonly os: OS; - public declare readonly osVersion: string; - public declare readonly osMainVersion: number; - public declare readonly browserType: BrowserType; - public declare readonly browserVersion: string; - public declare readonly isXR: boolean; - private _battery: any = null; - private declare _featureMap: IFeatureMap; - private _initPromise: Promise[] = []; - - constructor () { - super(); - const nav = window.navigator; - const ua = nav.userAgent.toLowerCase(); - // NOTE: getBattery is not totally supported on Web standard - (nav as any).getBattery?.().then((battery) => { - this._battery = battery; - }); - - this.networkType = NetworkType.LAN; // TODO - this.isNative = false; - this.isBrowser = true; - - // init isMobile and platform - if (EDITOR) { - this.isMobile = false; - this.platform = Platform.EDITOR_PAGE; // TODO - } else { - this.isMobile = /mobile|android|iphone|ipad/.test(ua); - this.platform = this.isMobile ? Platform.MOBILE_BROWSER : Platform.DESKTOP_BROWSER; - } - - // init isLittleEndian - this.isLittleEndian = ((): boolean => { - const buffer = new ArrayBuffer(2); - new DataView(buffer).setInt16(0, 256, true); - // Int16Array uses the platform's endianness. - return new Int16Array(buffer)[0] === 256; - })(); - - // init languageCode and language - let currLanguage = nav.language; - this.nativeLanguage = currLanguage.toLowerCase(); - currLanguage = currLanguage || (nav as any).browserLanguage; - currLanguage = currLanguage ? currLanguage.split('-')[0] : Language.ENGLISH; - this.language = currLanguage as Language; - - // init os, osVersion and osMainVersion - let isAndroid = false; let iOS = false; let osVersion = ''; let osMajorVersion = 0; - let uaResult = /android\s*(\d+(?:\.\d+)*)/i.exec(ua) || /android\s*(\d+(?:\.\d+)*)/i.exec(nav.platform); - if (uaResult) { - isAndroid = true; - osVersion = uaResult[1] || ''; - osMajorVersion = parseInt(osVersion) || 0; - } - uaResult = /(iPad|iPhone|iPod).*OS ((\d+_?){2,3})/i.exec(ua); - if (uaResult) { - iOS = true; - osVersion = uaResult[2] || ''; - osMajorVersion = parseInt(osVersion) || 0; - // refer to https://github.com/cocos-creator/engine/pull/5542 , thanks for contribition from @krapnikkk - // ipad OS 13 safari identifies itself as "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko)" - // so use maxTouchPoints to check whether it's desktop safari or not. - // reference: https://stackoverflow.com/questions/58019463/how-to-detect-device-name-in-safari-on-ios-13-while-it-doesnt-show-the-correct - // FIXME: should remove it when touch-enabled mac are available - // TODO: due to compatibility issues, it is still determined to be ios, and a new operating system type ipados may be added later? - } else if (/(iPhone|iPad|iPod)/.exec(nav.platform) || (nav.platform === 'MacIntel' && nav.maxTouchPoints && nav.maxTouchPoints > 1)) { - iOS = true; - osVersion = ''; - osMajorVersion = 0; - } - - let osName = OS.UNKNOWN; - if (nav.appVersion.indexOf('Win') !== -1) { - osName = OS.WINDOWS; - } else if (iOS) { - osName = OS.IOS; - } else if (nav.appVersion.indexOf('Mac') !== -1) { - osName = OS.OSX; - } else if (nav.appVersion.indexOf('X11') !== -1 && nav.appVersion.indexOf('Linux') === -1) { - osName = OS.LINUX; - } else if (isAndroid) { - osName = OS.ANDROID; - } else if (nav.appVersion.indexOf('Linux') !== -1 || ua.indexOf('ubuntu') !== -1) { - osName = OS.LINUX; - } - - this.os = osName; - this.osVersion = osVersion; - this.osMainVersion = osMajorVersion; - - // TODO: use dack-type to determine the browserType - // init browserType and browserVersion - this.browserType = BrowserType.UNKNOWN; - const typeReg0 = /wechat|weixin|micromessenger/i; - const typeReg1 = /mqqbrowser|micromessenger|qqbrowser|sogou|qzone|liebao|maxthon|ucbs|360 aphone|360browser|baiduboxapp|baidubrowser|maxthon|mxbrowser|miuibrowser/i; - const typeReg2 = /qq|qqbrowser|ucbrowser|ubrowser|edge|HuaweiBrowser/i; - const typeReg3 = /chrome|safari|firefox|trident|opera|opr\/|oupeng/i; - const browserTypes = typeReg0.exec(ua) || typeReg1.exec(ua) || typeReg2.exec(ua) || typeReg3.exec(ua); - - let browserType = browserTypes ? browserTypes[0].toLowerCase() : OS.UNKNOWN; - if (browserType === 'safari' && isAndroid) { - browserType = BrowserType.ANDROID; - } else if (browserType === 'qq' && /android.*applewebkit/i.test(ua)) { - browserType = BrowserType.ANDROID; - } - const typeMap = { - micromessenger: BrowserType.WECHAT, - wechat: BrowserType.WECHAT, - weixin: BrowserType.WECHAT, - trident: BrowserType.IE, - edge: BrowserType.EDGE, - '360 aphone': BrowserType.BROWSER_360, - mxbrowser: BrowserType.MAXTHON, - 'opr/': BrowserType.OPERA, - ubrowser: BrowserType.UC, - huaweibrowser: BrowserType.HUAWEI, - }; - - this.browserType = typeMap[browserType] || browserType; - - // init browserVersion - this.browserVersion = ''; - const versionReg1 = /(mqqbrowser|micromessenger|qqbrowser|sogou|qzone|liebao|maxthon|uc|ucbs|360 aphone|360|baiduboxapp|baidu|maxthon|mxbrowser|miui(?:.hybrid)?)(mobile)?(browser)?\/?([\d.]+)/i; - const versionReg2 = /(qq|chrome|safari|firefox|trident|opera|opr\/|oupeng)(mobile)?(browser)?\/?([\d.]+)/i; - let tmp = versionReg1.exec(ua); - if (!tmp) { - tmp = versionReg2.exec(ua); - } - this.browserVersion = tmp ? tmp[4] : ''; - - this.isXR = false; - - // init capability - const _tmpCanvas1 = document.createElement('canvas'); - const supportCanvas = TEST ? false : !!_tmpCanvas1.getContext('2d'); - let supportWebGL = false; - if (TEST) { - supportWebGL = false; - } else if (window.WebGLRenderingContext) { - supportWebGL = true; - } - let supportWebp; - try { - supportWebp = TEST ? false : _tmpCanvas1.toDataURL('image/webp').startsWith('data:image/webp'); - } catch (e) { - supportWebp = false; - } - if (this.os === OS.IOS) { - // if we're on iOS all major browsers will identify as BrowserType.SAFARI but Chrome and Firefox DO NOT have the - // version in the browser identifier, using "applewebkit" solves this issue for all browsers on iOS - const result = / applewebkit\/(\d+)/.exec(ua)?.[1]; - if (typeof result === 'string') { - if (Number.parseInt(result) >= 604) { - // safari 14+ support webp, but canvas.toDataURL is not supported by default - supportWebp = true; - } - } - } else if (this.browserType === BrowserType.SAFARI) { - //non-ios safari (desktop) - const result = / version\/(\d+)/.exec(ua)?.[1]; - if (typeof result === 'string') { - if (Number.parseInt(result) >= 14) { - // safari 14+ support webp, but canvas.toDataURL is not supported by default - supportWebp = true; - } - } - } - - const supportTouch = (document.documentElement.ontouchstart !== undefined || document.ontouchstart !== undefined || EDITOR); - const supportMouse = document.documentElement.onmouseup !== undefined || EDITOR; - // NOTE: xr is not totally supported on web - const supportXR = typeof (navigator as any).xr !== 'undefined'; - // refer https://stackoverflow.com/questions/47879864/how-can-i-check-if-a-browser-supports-webassembly - const supportWasm = ((): boolean => { - // NOTE: safari on iOS 15.4 and MacOS 15.4 has some wasm memory issue, can not use wasm for bullet - const isSafari_15_4 = (this.os === OS.IOS || this.os === OS.OSX) && /(OS 15_4)|(Version\/15.4)/.test(window.navigator.userAgent); - if (isSafari_15_4) { - return false; - } - try { - if (typeof WebAssembly === 'object' - && typeof WebAssembly.instantiate === 'function') { - const module = new WebAssembly.Module(new Uint8Array([0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00])); - if (module instanceof WebAssembly.Module) { - return new WebAssembly.Instance(module) instanceof WebAssembly.Instance; - } - } - } catch (e) { - return false; - } - return false; - })(); - this._featureMap = { - [Feature.WEBP]: supportWebp, - [Feature.IMAGE_BITMAP]: false, // Initialize in Promise - [Feature.WEB_VIEW]: true, - [Feature.VIDEO_PLAYER]: true, - [Feature.SAFE_AREA]: false, - [Feature.HPE]: false, - - [Feature.INPUT_TOUCH]: supportTouch, - [Feature.EVENT_KEYBOARD]: document.documentElement.onkeyup !== undefined || EDITOR, - [Feature.EVENT_MOUSE]: supportMouse, - [Feature.EVENT_TOUCH]: supportTouch || supportMouse, - [Feature.EVENT_ACCELEROMETER]: (window.DeviceMotionEvent !== undefined || window.DeviceOrientationEvent !== undefined), - // NOTE: webkitGetGamepads is not standard web interface - [Feature.EVENT_GAMEPAD]: (navigator.getGamepads !== undefined || (navigator as any).webkitGetGamepads !== undefined || supportXR), - [Feature.EVENT_HANDLE]: EDITOR || PREVIEW, - [Feature.EVENT_HMD]: supportXR, - [Feature.EVENT_HANDHELD]: supportXR, - [Feature.WASM]: supportWasm, - }; - - this._initPromise.push(this._supportsImageBitmapPromise()); - - this._registerEvent(); - } - - private _supportsImageBitmapPromise (): Promise { - if (!TEST && typeof createImageBitmap !== 'undefined' && typeof Blob !== 'undefined') { - const canvas = document.createElement('canvas'); - canvas.width = canvas.height = 2; - const promise = createImageBitmap(canvas); - if (promise instanceof Promise) { - return promise.then((imageBitmap) => { - if (imageBitmap && imageBitmap.close) { - this._setFeature(Feature.IMAGE_BITMAP, true); - imageBitmap.close(); - } - }); - } else if (DEBUG) { - warn('The return value of createImageBitmap is not Promise.'); - } - } - return Promise.resolve(); - } - - private _registerEvent (): void { - let hiddenPropName: string; - if (typeof document.hidden !== 'undefined') { - hiddenPropName = 'hidden'; - } else if (typeof document.mozHidden !== 'undefined') { - hiddenPropName = 'mozHidden'; - } else if (typeof document.msHidden !== 'undefined') { - hiddenPropName = 'msHidden'; - } else if (typeof document.webkitHidden !== 'undefined') { - hiddenPropName = 'webkitHidden'; - } else { - hiddenPropName = 'hidden'; - } - - let hidden = false; - const onHidden = (): void => { - if (!hidden) { - hidden = true; - this.emit('hide'); - } - }; - // In order to adapt the most of platforms the onshow API. - const onShown = (arg0?, arg1?, arg2?, arg3?, arg4?): void => { - if (hidden) { - hidden = false; - this.emit('show', arg0, arg1, arg2, arg3, arg4); - } - }; - - if (hiddenPropName) { - const changeList = [ - 'visibilitychange', - 'mozvisibilitychange', - 'msvisibilitychange', - 'webkitvisibilitychange', - 'qbrowserVisibilityChange', - ]; - - for (let i = 0; i < changeList.length; i++) { - document.addEventListener(changeList[i], (event) => { - let visible = document[hiddenPropName]; - // NOTE: QQ App need hidden property - visible = visible || (event as any).hidden; - if (visible) { - onHidden(); - } else { - onShown(); - } - }); - } - } else { - window.addEventListener('blur', onHidden); - window.addEventListener('focus', onShown); - } - - if (window.navigator.userAgent.indexOf('MicroMessenger') > -1) { - window.onfocus = onShown; - } - - if ('onpageshow' in window && 'onpagehide' in window) { - window.addEventListener('pagehide', onHidden); - window.addEventListener('pageshow', onShown); - // Taobao UIWebKit - document.addEventListener('pagehide', onHidden); - document.addEventListener('pageshow', onShown); - } - } - - private _setFeature (feature: Feature, value: boolean): boolean { - return this._featureMap[feature] = value; - } - - public init (): Promise { - return Promise.all(this._initPromise); - } - - public hasFeature (feature: Feature): boolean { - return this._featureMap[feature]; - } - - public getBatteryLevel (): number { - if (this._battery) { - return this._battery.level as number; - } else { - if (DEBUG) { - warn('getBatteryLevel is not supported'); - } - return 1; - } - } - public triggerGC (): void { - if (DEBUG) { - warn('triggerGC is not supported.'); - } - } - public openURL (url: string): void { - window.open(url); - } - public now (): number { - if (Date.now) { - return Date.now(); - } - - return +(new Date()); - } - public restartJSVM (): void { - if (DEBUG) { - warn('restartJSVM is not supported.'); - } - } - - public exit (): void { - window.close(); - } - - public close (): void { - this.emit('close'); - } -} - -export const systemInfo = new SystemInfo(); - -checkPalIntegrity(withImpl()); diff --git a/pal/utils.ts b/pal/utils.ts deleted file mode 100644 index cc25ebce0e..0000000000 --- a/pal/utils.ts +++ /dev/null @@ -1,242 +0,0 @@ -/* - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { EDITOR, NODEJS, USE_XR } from 'internal:constants'; -import { warnID } from '../cocos/core/platform/debug'; - -/** - * This method clones methods in minigame environment, sub as `wx`, `swan` etc. to a module called minigame. - * @param targetObject Usually it's specified as the minigame module. - * @param originObj Original minigame environment such as `wx`, `swan` etc. - */ -export function cloneObject (targetObject: T, originObj: T): void { - Object.keys(originObj).forEach((key) => { - if (typeof originObj[key] === 'function') { - targetObject[key] = originObj[key].bind(originObj); - return; - } - targetObject[key] = originObj[key]; - }); -} - -type MiningameAudioCallbackName = 'onPlay' | 'onPause' | 'onStop' | 'onSeek'; -type InnerAudioContextPolyfillConfig = { - [CallbackName in MiningameAudioCallbackName]: boolean; -}; -/** - * This method is to create a polyfill on minigame platform when the innerAudioContext callback doesn't work. - * @param minigameEnv Specify the minigame enviroment such as `wx`, `swan` etc. - * @param polyfillConfig Specify the field, if it's true, the polyfill callback will be applied. - * @param isAsynchronous Specify whether the callback is called asynchronous. - * @returns A polyfilled createInnerAudioContext method. - */ -export function createInnerAudioContextPolyfill (minigameEnv: any, polyfillConfig: InnerAudioContextPolyfillConfig, isAsynchronous = false) { - return (): InnerAudioContext => { - const audioContext: InnerAudioContext = minigameEnv.createInnerAudioContext(); - - // add polyfill if onPlay method doesn't work this platform - if (polyfillConfig.onPlay) { - const originalPlay = audioContext.play; - let _onPlayCB: (() => void) | null = null; - Object.defineProperty(audioContext, 'onPlay', { - configurable: true, - value (cb: () => void) { - _onPlayCB = cb; - }, - }); - Object.defineProperty(audioContext, 'play', { - configurable: true, - value () { - originalPlay.call(audioContext); - if (_onPlayCB) { - if (isAsynchronous) { - setTimeout(_onPlayCB, 0); - } else { - _onPlayCB(); - } - } - }, - }); - } - - // add polyfill if onPause method doesn't work this platform - if (polyfillConfig.onPause) { - const originalPause = audioContext.pause; - let _onPauseCB: (() => void) | null = null; - Object.defineProperty(audioContext, 'onPause', { - configurable: true, - value (cb: () => void) { - _onPauseCB = cb; - }, - }); - Object.defineProperty(audioContext, 'pause', { - configurable: true, - value () { - originalPause.call(audioContext); - if (_onPauseCB) { - if (isAsynchronous) { - setTimeout(_onPauseCB, 0); - } else { - _onPauseCB(); - } - } - }, - }); - } - - // add polyfill if onStop method doesn't work on this platform - if (polyfillConfig.onStop) { - const originalStop = audioContext.stop; - let _onStopCB: (() => void) | null = null; - Object.defineProperty(audioContext, 'onStop', { - configurable: true, - value (cb: () => void) { - _onStopCB = cb; - }, - }); - Object.defineProperty(audioContext, 'stop', { - configurable: true, - value () { - originalStop.call(audioContext); - if (_onStopCB) { - if (isAsynchronous) { - setTimeout(_onStopCB, 0); - } else { - _onStopCB(); - } - } - }, - }); - } - - // add polyfill if onSeeked method doesn't work on this platform - if (polyfillConfig.onSeek) { - const originalSeek = audioContext.seek; - let _onSeekCB: (() => void) | null = null; - Object.defineProperty(audioContext, 'onSeeked', { - configurable: true, - value (cb: () => void) { - _onSeekCB = cb; - }, - }); - Object.defineProperty(audioContext, 'seek', { - configurable: true, - value (time: number) { - originalSeek.call(audioContext, time); - if (_onSeekCB) { - if (isAsynchronous) { - setTimeout(_onSeekCB, 0); - } else { - _onSeekCB(); - } - } - }, - }); - } - - return audioContext; - }; -} - -/** - * Compare two version, version should in pattern like 3.0.0. - * If versionA > versionB, return number larger than 0. - * If versionA = versionB, return number euqal to 0. - * If versionA < versionB, return number smaller than 0. - * @param versionA - * @param versionB - */ -export function versionCompare (versionA: string, versionB: string): number { - const versionRegExp = /\d+\.\d+\.\d+/; - if (!(versionRegExp.test(versionA) && versionRegExp.test(versionB))) { - warnID(16356); - return 0; - } - const versionNumbersA = versionA.split('.').map((num: string) => Number.parseInt(num)); - const versionNumbersB = versionB.split('.').map((num: string) => Number.parseInt(num)); - for (let i = 0; i < 3; ++i) { - const numberA = versionNumbersA[i]; - const numberB = versionNumbersB[i]; - if (numberA !== numberB) { - return numberA - numberB; - } - } - return 0; -} - -/** - * A custom implementation of setTimeout that uses requestAnimationFrame. - * @param callback The function to be executed after a delay. - * @param delay The delay time in milliseconds. - * @param args The arguments to be passed to the callback function. - * @returns A unique identifier for the timer. - */ -export function setTimeoutRAF (callback: (...args: T) => void, delay: number, ...args: T): number { - const start = performance.now(); - - const raf = requestAnimationFrame - || window.requestAnimationFrame - || window.webkitRequestAnimationFrame - || window.mozRequestAnimationFrame - || window.oRequestAnimationFrame - || window.msRequestAnimationFrame; - - if (EDITOR || NODEJS || raf === undefined || (USE_XR && globalThis.__globalXR?.isWebXR)) { - return setTimeout(callback, delay, ...args); - } - - const handleRAF = (): void => { - if (performance.now() - start < delay) { - raf(handleRAF); - } else { - callback(...args); - } - }; - - return raf(handleRAF); -} - -/** - * Cancels a timer that was created using the rafTimeout function. - * @param id A numeric ID that represents the timer to be canceled. - * @returns Nothing. - */ -export function clearTimeoutRAF (id: number): void { - const caf = cancelAnimationFrame - || window.cancelAnimationFrame - || window.cancelRequestAnimationFrame - || window.msCancelRequestAnimationFrame - || window.mozCancelRequestAnimationFrame - || window.oCancelRequestAnimationFrame - || window.webkitCancelRequestAnimationFrame - || window.msCancelAnimationFrame - || window.mozCancelAnimationFrame - || window.webkitCancelAnimationFrame - || window.ocancelAnimationFrame; - if (EDITOR || caf === undefined || (USE_XR && globalThis.__globalXR?.isWebXR)) { - clearTimeout(id); - } else { - caf(id); - } -} diff --git a/pal/wasm/wasm-minigame.ts b/pal/wasm/wasm-minigame.ts deleted file mode 100644 index 6068640e85..0000000000 --- a/pal/wasm/wasm-minigame.ts +++ /dev/null @@ -1,129 +0,0 @@ -/* - Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { HUAWEI, TAOBAO_MINIGAME, WASM_SUBPACKAGE, XIAOMI } from 'internal:constants'; -import { minigame } from 'pal/minigame'; -import { basename } from '../../cocos/core/utils/path'; -import { checkPalIntegrity, withImpl } from '../integrity-check'; -import { log } from '../../cocos/core/platform/debug'; - -// NOTE: The global variable `CCWebAssembly` is assigned in platforms/(bytedance|wechat)/wrapper/builtin/index.js -declare namespace CCWebAssembly { - // The first argument of `instantiate` function in mini-game platforms is always a wasm url. - function instantiate(url: string, importObject?: WebAssembly.Imports): Promise; -} - -export function instantiateWasm (wasmUrl: string, importObject: WebAssembly.Imports): Promise { - return getPlatformBinaryUrl(wasmUrl).then((url: string) => CCWebAssembly.instantiate(url, importObject)); -} - -export function fetchBuffer (binaryUrl: string): Promise { - return new Promise((resolve, reject) => { - getPlatformBinaryUrl(binaryUrl).then((url) => { - // NOTE: fsUtils is defined in engine-adapter, we need to access globalThis explicitly for Taobao platform - globalThis.fsUtils.readArrayBuffer(url, (err, arrayBuffer: ArrayBuffer) => { - if (err) { - reject(err); - return; - } - resolve(arrayBuffer); - }); - // eslint-disable-next-line @typescript-eslint/no-empty-function - }).catch((e) => {}); - }); -} - -export function fetchUrl (binaryUrl: string): Promise { - return new Promise((resolve, reject) => { - getPlatformBinaryUrl(binaryUrl).then((url) => { - resolve(url); - // eslint-disable-next-line @typescript-eslint/no-empty-function - }).catch((e) => { - reject(e); - }); - }); -} - -function loadSubpackage (name: string): Promise { - return new Promise((resolve, reject) => { - if (minigame.loadSubpackage) { - minigame.loadSubpackage({ - name, - success () { - resolve(); - }, - fail (err) { - log(`Load subpacakge '${name}' failed, maybe we don't need this subpacakge or it's an engine build issue, for detailed: `, err); - resolve(); - }, - }); - } else { - reject(new Error(`Subpackage is not supported on this platform`)); - } - }); -} - -let promiseToLoadWasmModule: Promise | undefined; - -export function ensureWasmModuleReady (): Promise { - if (promiseToLoadWasmModule) { - return promiseToLoadWasmModule; - } - return promiseToLoadWasmModule = new Promise((resolve, reject) => { - if (WASM_SUBPACKAGE) { - if (HUAWEI) { - // NOTE: huawei quick game doesn't support concurrent loading subpackage. - loadSubpackage('__ccWasmAssetSubpkg__').then(() => loadSubpackage('__ccWasmChunkSubpkg__')).then(() => { - resolve(); - }).catch(reject); - } else { - Promise.all(['__ccWasmAssetSubpkg__', '__ccWasmChunkSubpkg__'].map((pkgName) => loadSubpackage(pkgName))) - .then(() => { - resolve(); - }).catch(reject); - } - } else { - resolve(); - } - }); -} - -/** - * The binary url can be different on different platforms. - * @param binaryUrl the basic build output binary url - * @returns the real binary url on the exact platform - */ -function getPlatformBinaryUrl (binaryUrl: string): Promise { - return new Promise((resolve) => { - if (XIAOMI) { - resolve(`src/cocos-js/${binaryUrl}`); - } if (TAOBAO_MINIGAME && WASM_SUBPACKAGE) { - resolve(`__ccWasmAssetSubpkg__/${basename(binaryUrl)}`); - } else { - resolve(`cocos-js/${binaryUrl}`); - } - }); -} - -checkPalIntegrity(withImpl()); diff --git a/pal/wasm/wasm-native.ts b/pal/wasm/wasm-native.ts deleted file mode 100644 index 8a02da18c7..0000000000 --- a/pal/wasm/wasm-native.ts +++ /dev/null @@ -1,78 +0,0 @@ -/* - Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ -import { EDITOR } from 'internal:constants'; -import { native } from '../../cocos/native-binding/index'; -import { checkPalIntegrity, withImpl } from '../integrity-check'; - -export function instantiateWasm (wasmUrl: string, importObject: WebAssembly.Imports): Promise { - return fetchBuffer(wasmUrl).then((arrayBuffer) => WebAssembly.instantiate(arrayBuffer, importObject)); -} - -export function fetchBuffer (binaryUrl: string): Promise { - return new Promise((resolve, reject) => { - try { - // NOTE: when it's in EDITOR, binaryUrl is a url with `external:` protocol. - if (EDITOR) { - Editor.Message.request('engine', 'query-engine-info').then((info) => { - const externalRoot = `${info.native.path}/external/`; - binaryUrl = binaryUrl.replace('external:', externalRoot); - const arrayBuffer = native.fileUtils.getDataFromFile(binaryUrl); - resolve(arrayBuffer); - }); - return; - } - binaryUrl = `src/cocos-js/${binaryUrl}`; - const arrayBuffer = native.fileUtils.getDataFromFile(binaryUrl); - resolve(arrayBuffer); - } catch (e) { - reject(e); - } - }); -} - -export function fetchUrl (binaryUrl: string): Promise { - return new Promise((resolve, reject) => { - try { - // NOTE: when it's in EDITOR, binaryUrl is a url with `external:` protocol. - if (EDITOR) { - Editor.Message.request('engine', 'query-engine-info').then((info) => { - const externalRoot = `${info.native.path}/external/`; - binaryUrl = binaryUrl.replace('external:', externalRoot); - resolve(binaryUrl); - }); - return; - } - binaryUrl = `src/cocos-js/${binaryUrl}`; - resolve(binaryUrl); - } catch (e) { - reject(e); - } - }); -} - -export function ensureWasmModuleReady (): Promise { - return Promise.resolve(); -} - -checkPalIntegrity(withImpl()); diff --git a/pal/wasm/wasm-nodejs.ts b/pal/wasm/wasm-nodejs.ts deleted file mode 100644 index 78acbdd65b..0000000000 --- a/pal/wasm/wasm-nodejs.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* - Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ -import { checkPalIntegrity, withImpl } from '../integrity-check'; - -export function instantiateWasm (wasmUrl: string, importObject: WebAssembly.Imports): Promise { - return fetchBuffer(wasmUrl).then((arrayBuffer) => WebAssembly.instantiate(arrayBuffer, importObject)); -} - -export function fetchBuffer (binaryUrl: string): Promise { - return new Promise((resolve, reject) => { - try { - const externalRoot = `${globalThis.nodeEnv.enginePath}/native/external/`; - binaryUrl = binaryUrl.replace('external:', externalRoot); - const fs = globalThis.nodeEnv.require('fs-extra'); - const arrayBuffer = fs.readFileSync(binaryUrl) as ArrayBuffer; - resolve(arrayBuffer); - } catch (e) { - reject(e); - } - }); -} - -export function fetchUrl(binaryUrl: string): Promise { - return new Promise((resolve, reject) => { - try { - const externalRoot = `${globalThis.nodeEnv.enginePath}/native/external/`; - binaryUrl = binaryUrl.replace('external:', externalRoot); - resolve(binaryUrl); - } catch (e) { - reject(e); - } - }); -} - -export function ensureWasmModuleReady (): Promise { - return Promise.resolve(); -} - -checkPalIntegrity(withImpl()); diff --git a/pal/wasm/wasm-web.ts b/pal/wasm/wasm-web.ts deleted file mode 100644 index 9eeb6fb24d..0000000000 --- a/pal/wasm/wasm-web.ts +++ /dev/null @@ -1,105 +0,0 @@ -/* - Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { EDITOR, PREVIEW } from 'internal:constants'; -import { checkPalIntegrity, withImpl } from '../integrity-check'; - -declare const require: any; - -export function instantiateWasm (wasmUrl: string, importObject: WebAssembly.Imports): Promise { - return fetchBuffer(wasmUrl).then((arrayBuffer) => WebAssembly.instantiate(arrayBuffer, importObject)); -} - -export function fetchBuffer (binaryUrl: string): Promise { - return new Promise((resolve, reject) => { - try { - // NOTE: when it's in EDITOR or PREVIEW, binaryUrl is a url with `external:` protocol. - if (EDITOR) { - Editor.Message.request('engine', 'query-engine-info').then((info) => { - const externalRoot = `${info.native.path}/external/`; - binaryUrl = binaryUrl.replace('external:', externalRoot); - // IDEA: it's better we implement another PAL for nodejs platform. - // eslint-disable-next-line @typescript-eslint/no-var-requires - const fs = require('fs'); - const arrayBuffer = fs.readFileSync(binaryUrl) as ArrayBuffer; - resolve(arrayBuffer); - }); - return; - } else if (PREVIEW) { - // NOTE: we resolve '/engine_external/' in editor preview server. - fetch(`/engine_external/?url=${binaryUrl}`).then((response) => response.arrayBuffer().then(resolve)).catch((e) => { - // noop - }); - return; - } - // here is in the BUILD mode - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore NOTE: we need to use 'import.meta' here, but the tsc won't allow this, so we need to force ignoring this error here. - binaryUrl = new URL(binaryUrl, import.meta.url).href; - fetch(binaryUrl).then((response) => response.arrayBuffer().then(resolve)).catch((e) => { - // noop - }); - } catch (e) { - reject(e); - } - }); -} - -/** - * @en Translate virtual addresses within the engine to actual addresses of paths, such as external:emscripten/webgpu/glslang.wasm - * @zh 把引擎内部的虚拟地址转为路径的实际地址,如external:emscripten/webgpu/glslang.wasm - */ -export function fetchUrl (binaryUrl: string): Promise { - return new Promise((resolve, reject) => { - try { - // NOTE: when it's in EDITOR or PREVIEW, binaryUrl is a url with `external:` protocol. - if (EDITOR) { - Editor.Message.request('engine', 'query-engine-info').then((info) => { - const externalRoot = `${info.native.path}/external/`; - binaryUrl = binaryUrl.replace('external:', externalRoot); - // IDEA: it's better we implement another PAL for nodejs platform. - // eslint-disable-next-line @typescript-eslint/no-var-requires - resolve(binaryUrl); - }); - return; - } else if (PREVIEW) { - resolve(`/engine_external/?url=${binaryUrl}`); - return; - } - // here is in the BUILD mode - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore NOTE: we need to use 'import.meta' here, but the tsc won't allow this, so we need to force ignoring this error here. - binaryUrl = new URL(binaryUrl, import.meta.url).href; - resolve(binaryUrl); - } catch (e) { - reject(e); - } - }); -} - -export function ensureWasmModuleReady (): Promise { - return Promise.resolve(); -} - -checkPalIntegrity(withImpl()); diff --git a/platforms/.eslintrc.yaml b/platforms/.eslintrc.yaml deleted file mode 100644 index bb9f03c008..0000000000 --- a/platforms/.eslintrc.yaml +++ /dev/null @@ -1,77 +0,0 @@ -root: true - -extends: - - eslint:recommended - - airbnb-base - -env: - browser: true - node: true - es6: true - jest: true - -globals: - cc: readonly - -rules: - # https://eslint.org/docs/rules/ - # https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin - - # !!!!!!!!!!!!!!!!!!!!!!!!! - # BEFORE ADDING ANY RULES - # PLEASE EXPLAIN THE REASON IN THE COMMENT. - - ##### RECOMMENDED RULE OVERRIDES ##### - - camelcase: off # underscores may come in handy in some cases - eqeqeq: warn # important check missing from recommended - keyword-spacing: warn # we require this explicitly - no-multi-spaces: off # useful for manually align some expression across lines - prefer-rest-params: off # we need ES5 to be fast too - prefer-spread: off # we need ES5 to be fast too - space-before-function-paren: [warn, always] # we require this explicitly - radix: off # we sometimes do not need to pass a second parameter - # allow underscores, we still widely use pre-dangle naming in our naming convention - # e.g. private properties, private functions, module scope shared variables etc. - no-underscore-dangle: off - quotes: [warn, single, { allowTemplateLiterals: true }] # force single, but allow template literal - no-else-return: off # else-return is a common pattern which clearly expresses the control flow - no-unused-expressions: off # taken over by '@typescript-eslint/no-unused-expressions' - - ##### AIRBNB-SPECIFIC RULE OVERRIDES ##### - - class-methods-use-this: off # so empty functions could work - guard-for-in: off # for-in is a efficient choice for plain objects - import/export: off # so export declare namespace could work - import/extensions: off # typescript doesn't support this - import/no-unresolved: off # TODO: fix internal modules - import/prefer-default-export: off # prefer named exports - indent: off # use @typescript-eslint/indent instead for better compatibility - - lines-between-class-members: off # be more lenient on member declarations - max-classes-per-file: off # helper classes are common - max-len: [warn, 150] # more lenient on max length per line - no-console: off # this is just too much work, cc.warn is still too much pain to use - no-plusplus: off # allow increment/decrement operators - no-continue: off # allow unlabeled continues - no-mixed-operators: off # this is just cumbersome - no-multi-assign: off # it is handy sometimes - no-nested-ternary: off # it is handy sometimes - no-param-reassign: off # the output object is passed as parameters all the time - no-restricted-syntax: off # for-in is a efficient choice for plain objects - no-return-assign: off # it is handy sometimes - no-shadow: off # TODO: this throws false-positives? - no-sequences: off # it is handy sometimes - no-bitwise: off # we use this extensively - no-use-before-define: off # just too much work - no-useless-constructor: off # gives false-positives for empty constructor with parameter properties - object-curly-newline: off # we want manual control over this - one-var-declaration-per-line: off # auto-fix has order issues with `one-var` - prefer-destructuring: off # auto-fix is not smart enough to merge different instances - linebreak-style: off # we don't enforce this on everyone's dev environment for now - spaced-comment: off # for license declarations - - ##### JS SPECIFIC OVERRIDES ##### - - global-require: off # may require different files based on global environment - func-names: off # overriding existing functions are common diff --git a/platforms/minigame/README.md b/platforms/minigame/README.md deleted file mode 100644 index 1fcfe4e997..0000000000 --- a/platforms/minigame/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Adapter for MiniGame platform -included platforms: -- WeChat -- Xiaomi -- Alipay -- ByteDance -- Taobao diff --git a/platforms/minigame/common/engine/AssetManager.js b/platforms/minigame/common/engine/AssetManager.js deleted file mode 100644 index d50ec79fa4..0000000000 --- a/platforms/minigame/common/engine/AssetManager.js +++ /dev/null @@ -1,465 +0,0 @@ -/**************************************************************************** - Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of cache-manager 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 cache-manager 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. - ****************************************************************************/ - -/* eslint-disable no-global-assign */ -/* eslint-disable no-undef */ -/* eslint-disable import/no-dynamic-require */ -const cacheManager = require('./cache-manager'); - -const { fs, downloadFile, readText, readArrayBuffer, readJson, loadSubpackage, getUserDataPath, exists } = window.fsUtils; - -const REGEX = /^https?:\/\/.*/; - -const downloader = cc.assetManager.downloader; -const parser = cc.assetManager.parser; -const presets = cc.assetManager.presets; -downloader.maxConcurrency = 12; -downloader.maxRequestsPerFrame = 64; -presets.scene.maxConcurrency = 12; -presets.scene.maxRequestsPerFrame = 64; - -const subpackages = {}; - -const sys = cc.sys; -if (sys.platform === sys.Platform.TAOBAO_MINI_GAME) { - require = globalThis.__taobaoRequire; -} - -function downloadScript (url, options, onComplete) { - if (REGEX.test(url)) { - onComplete && onComplete(new Error('Can not load remote scripts')); - } else { - if (sys.platform !== sys.Platform.TAOBAO_CREATIVE_APP) { //Can't load scripts dynamically on Taobao platform - require(`../../../${url}`); - } - onComplete && onComplete(null); - } -} - -function handleZip (url, options, onComplete) { - const cachedUnzip = cacheManager.cachedFiles.get(url); - if (cachedUnzip) { - cacheManager.updateLastTime(url); - onComplete && onComplete(null, cachedUnzip.url); - } else if (REGEX.test(url)) { - downloadFile(url, null, options.header, options.onFileProgress, (err, downloadedZipPath) => { - if (err) { - onComplete && onComplete(err); - return; - } - cacheManager.unzipAndCacheBundle(url, downloadedZipPath, options.__cacheBundleRoot__, onComplete); - }); - } else { - cacheManager.unzipAndCacheBundle(url, url, options.__cacheBundleRoot__, onComplete); - } -} - -function loadAudioPlayer (url, options, onComplete) { - cc.AudioPlayer.load(url).then((player) => { - const audioMeta = { - player, - url, - duration: player.duration, - type: player.type, - }; - onComplete(null, audioMeta); - }).catch((err) => { - onComplete(err); - }); -} - -function download (url, func, options, onFileProgress, onComplete) { - const result = transformUrl(url, options); - if (result.inLocal) { - func(result.url, options, onComplete); - } else if (result.inCache) { - cacheManager.updateLastTime(url); - func(result.url, options, (err, data) => { - if (err) { - cacheManager.removeCache(url); - } - onComplete(err, data); - }); - } else { - downloadFile(url, null, options.header, onFileProgress, (err, path) => { - if (err) { - onComplete(err, null); - return; - } - func(path, options, (err, data) => { - if (!err) { - cacheManager.tempFiles.add(url, path); - cacheManager.cacheFile(url, path, options.cacheEnabled, options.__cacheBundleRoot__, true); - } - onComplete(err, data); - }); - }); - } -} - -function parseArrayBuffer (url, options, onComplete) { - readArrayBuffer(url, onComplete); -} - -function parseText (url, options, onComplete) { - readText(url, onComplete); -} - -function parseJson (url, options, onComplete) { - readJson(url, onComplete); -} - -function downloadText (url, options, onComplete) { - download(url, parseText, options, options.onFileProgress, onComplete); -} - -function downloadJson (url, options, onComplete) { - download(url, parseJson, options, options.onFileProgress, onComplete); -} - -function downloadArrayBuffer (url, options, onComplete) { - download(url, parseArrayBuffer, options, options.onFileProgress, onComplete); -} - -function loadFont (url, options, onComplete) { - const fontFamily = __globalAdapter.loadFont(url); - onComplete(null, fontFamily || 'Arial'); -} - -function doNothing (content, options, onComplete) { - exists(content, (existence) => { - if (existence) { - onComplete(null, content); - } else { - onComplete(new Error(`file ${content} does not exist!`)); - } - }); -} - -function downloadAsset (url, options, onComplete) { - download(url, doNothing, options, options.onFileProgress, onComplete); -} - -function downloadBundle (nameOrUrl, options, onComplete) { - const bundleName = cc.path.basename(nameOrUrl); - const version = options.version || cc.assetManager.downloader.bundleVers[bundleName]; - const suffix = version ? `${version}.` : ''; - - function getConfigPathForSubPackage () { - if (sys.platform === sys.Platform.TAOBAO_MINI_GAME) { - return `${bundleName}/config.${suffix}json`; - } - return `subpackages/${bundleName}/config.${suffix}json`; - } - - function appendBaseToJsonData (data) { - if (!data) return; - - if (sys.platform === sys.Platform.TAOBAO_MINI_GAME) { - data.base = `${bundleName}/`; - } else { - data.base = `subpackages/${bundleName}/`; - } - } - - if (subpackages[bundleName]) { - const config = getConfigPathForSubPackage(); - loadSubpackage(bundleName, options.onFileProgress, (err) => { - if (err) { - onComplete(err, null); - return; - } - downloadJson(config, options, (err, data) => { - appendBaseToJsonData(data); - onComplete(err, data); - }); - }); - } else { - let js; let url; - if (REGEX.test(nameOrUrl) || nameOrUrl.startsWith(getUserDataPath())) { - url = nameOrUrl; - js = `src/bundle-scripts/${bundleName}/index.${suffix}js`; - cacheManager.makeBundleFolder(bundleName); - } else if (downloader.remoteBundles.indexOf(bundleName) !== -1) { - url = `${downloader.remoteServerAddress}remote/${bundleName}`; - js = `src/bundle-scripts/${bundleName}/index.${suffix}js`; - cacheManager.makeBundleFolder(bundleName); - } else { - url = `assets/${bundleName}`; - js = `assets/${bundleName}/index.${suffix}js`; - } - if (sys.platform === sys.Platform.TAOBAO_MINI_GAME) { - require(js); - } else if (sys.platform !== sys.Platform.TAOBAO_CREATIVE_APP) { // Can't load scripts dynamically on Taobao platform - require(`./${js}`); - } - options.__cacheBundleRoot__ = bundleName; - const config = `${url}/config.${suffix}json`; - downloadJson(config, options, (err, data) => { - if (err) { - onComplete && onComplete(err); - return; - } - if (data.isZip) { - const zipVersion = data.zipVersion; - const zipUrl = `${url}/res.${zipVersion ? `${zipVersion}.` : ''}zip`; - handleZip(zipUrl, options, (err, unzipPath) => { - if (err) { - onComplete && onComplete(err); - return; - } - data.base = `${unzipPath}/res/`; - // PATCH: for android alipay version before v10.1.95 (v10.1.95 included) - // to remove in the future - if (sys.platform === sys.Platform.ALIPAY_MINI_GAME && sys.os === sys.OS.ANDROID) { - const resPath = `${unzipPath}res/`; - if (fs.accessSync({ path: resPath }).success) { - data.base = resPath; - } - } - onComplete && onComplete(null, data); - }); - } else { - data.base = `${url}/`; - onComplete && onComplete(null, data); - } - }); - } -} - -const originParsePVRTex = parser.parsePVRTex; -const parsePVRTex = function (file, options, onComplete) { - readArrayBuffer(file, (err, data) => { - if (err) { - onComplete(err); - return; - } - originParsePVRTex(data, options, onComplete); - }); -}; - -const originParsePKMTex = parser.parsePKMTex; -const parsePKMTex = function (file, options, onComplete) { - readArrayBuffer(file, (err, data) => { - if (err) { - onComplete(err); - return; - } - originParsePKMTex(data, options, onComplete); - }); -}; - -const originParseASTCTex = parser.parseASTCTex; -const parseASTCTex = function (file, options, onComplete) { - readArrayBuffer(file, (err, data) => { - if (err) { - onComplete(err); - return; - } - originParseASTCTex(data, options, onComplete); - }); -}; - -const originParsePlist = parser.parsePlist; -const parsePlist = function (url, options, onComplete) { - readText(url, (err, file) => { - if (err) { - onComplete(err); - return; - } - originParsePlist(file, options, onComplete); - }); -}; - -downloader.downloadScript = downloadScript; -downloader._downloadArrayBuffer = downloadArrayBuffer; -downloader._downloadJson = downloadJson; -parser.parsePVRTex = parsePVRTex; -parser.parsePKMTex = parsePKMTex; -parser.parseASTCTex = parseASTCTex; -parser.parsePlist = parsePlist; - -downloader.register({ - '.js': downloadScript, - - // Audio - '.mp3': downloadAsset, - '.ogg': downloadAsset, - '.wav': downloadAsset, - '.m4a': downloadAsset, - - // Image - '.png': downloadAsset, - '.jpg': downloadAsset, - '.bmp': downloadAsset, - '.jpeg': downloadAsset, - '.gif': downloadAsset, - '.ico': downloadAsset, - '.tiff': downloadAsset, - '.image': downloadAsset, - '.webp': downloadAsset, - '.pvr': downloadAsset, - '.pkm': downloadAsset, - '.astc': downloadAsset, - - '.font': downloadAsset, - '.eot': downloadAsset, - '.ttf': downloadAsset, - '.woff': downloadAsset, - '.svg': downloadAsset, - '.ttc': downloadAsset, - - // Txt - '.txt': downloadAsset, - '.xml': downloadAsset, - '.vsh': downloadAsset, - '.fsh': downloadAsset, - '.atlas': downloadAsset, - - '.tmx': downloadAsset, - '.tsx': downloadAsset, - '.plist': downloadAsset, - '.fnt': downloadAsset, - - '.json': downloadJson, - '.ExportJson': downloadAsset, - - '.binary': downloadAsset, - '.bin': downloadAsset, - '.dbbin': downloadAsset, - '.skel': downloadAsset, - - '.mp4': downloadAsset, - '.avi': downloadAsset, - '.mov': downloadAsset, - '.mpg': downloadAsset, - '.mpeg': downloadAsset, - '.rm': downloadAsset, - '.rmvb': downloadAsset, - - bundle: downloadBundle, - - default: downloadText, -}); - -parser.register({ - '.png': downloader.downloadDomImage, - '.jpg': downloader.downloadDomImage, - '.bmp': downloader.downloadDomImage, - '.jpeg': downloader.downloadDomImage, - '.gif': downloader.downloadDomImage, - '.ico': downloader.downloadDomImage, - '.tiff': downloader.downloadDomImage, - '.image': downloader.downloadDomImage, - '.webp': downloader.downloadDomImage, - '.pvr': parsePVRTex, - '.pkm': parsePKMTex, - '.astc': parseASTCTex, - - '.font': loadFont, - '.eot': loadFont, - '.ttf': loadFont, - '.woff': loadFont, - '.svg': loadFont, - '.ttc': loadFont, - - // Audio - '.mp3': loadAudioPlayer, - '.ogg': loadAudioPlayer, - '.wav': loadAudioPlayer, - '.m4a': loadAudioPlayer, - - // Txt - '.txt': parseText, - '.xml': parseText, - '.vsh': parseText, - '.fsh': parseText, - '.atlas': parseText, - - '.tmx': parseText, - '.tsx': parseText, - '.fnt': parseText, - '.plist': parsePlist, - - '.binary': parseArrayBuffer, - '.bin': parseArrayBuffer, - '.dbbin': parseArrayBuffer, - '.skel': parseArrayBuffer, - - '.ExportJson': parseJson, -}); - -function transformUrl (url, options) { - let inLocal = false; - let inCache = false; - const isInUserDataPath = url.startsWith(getUserDataPath()); - if (isInUserDataPath) { - inLocal = true; - } else if (REGEX.test(url)) { - if (!options.reload) { - const cache = cacheManager.cachedFiles.get(url); - if (cache) { - inCache = true; - url = cache.url; - } else { - const tempUrl = cacheManager.tempFiles.get(url); - if (tempUrl) { - inLocal = true; - url = tempUrl; - } - } - } - } else { - inLocal = true; - } - return { url, inLocal, inCache }; -} - -cc.assetManager.transformPipeline.append((task) => { - const input = task.output = task.input; - for (let i = 0, l = input.length; i < l; i++) { - const item = input[i]; - const options = item.options; - if (!item.config) { - if (item.ext === 'bundle') continue; - options.cacheEnabled = options.cacheEnabled !== undefined ? options.cacheEnabled : false; - } else { - options.__cacheBundleRoot__ = item.config.name; - } - if (item.ext === '.cconb') { - item.url = item.url.replace(item.ext, '.bin'); - } else if (item.ext === '.ccon') { - item.url = item.url.replace(item.ext, '.json'); - } - } -}); - -const originInit = cc.assetManager.init; -cc.assetManager.init = function (options) { - originInit.call(cc.assetManager, options); - const subpacks = cc.settings.querySettings('assets', 'subpackages'); - subpacks && subpacks.forEach((x) => subpackages[x] = `subpackages/${x}`); - cacheManager.init(); -}; diff --git a/platforms/minigame/common/engine/Editbox.js b/platforms/minigame/common/engine/Editbox.js deleted file mode 100644 index 8bd0372f26..0000000000 --- a/platforms/minigame/common/engine/Editbox.js +++ /dev/null @@ -1,178 +0,0 @@ -(function () { - if (!(cc && cc.internal && cc.internal.EditBox)) { - return; - } - - const EditBoxComp = cc.internal.EditBox; - const js = cc.js; - const KeyboardReturnType = EditBoxComp.KeyboardReturnType; - const MAX_VALUE = 65535; - const KEYBOARD_HIDE_TIME = 600; - let _hideKeyboardTimeout = null; - let _currentEditBoxImpl = null; - - function getKeyboardReturnType (type) { - switch (type) { - case KeyboardReturnType.DEFAULT: - case KeyboardReturnType.DONE: - return 'done'; - case KeyboardReturnType.SEND: - return 'send'; - case KeyboardReturnType.SEARCH: - return 'search'; - case KeyboardReturnType.GO: - return 'go'; - case KeyboardReturnType.NEXT: - return 'next'; - default: - return 'done'; - } - } - - function MiniGameEditBoxImpl () { - this._delegate = null; - this._editing = false; - - this._eventListeners = { - onKeyboardInput: null, - onKeyboardConfirm: null, - onKeyboardComplete: null, - }; - } - - js.extend(MiniGameEditBoxImpl, EditBoxComp._EditBoxImpl); - EditBoxComp._EditBoxImpl = MiniGameEditBoxImpl; - - Object.assign(MiniGameEditBoxImpl.prototype, { - init (delegate) { - if (!delegate) { - cc.error('EditBox init failed'); - return; - } - this._delegate = delegate; - }, - - beginEditing () { - // In case multiply register events - if (this._editing) { - return; - } - this._ensureKeyboardHide(() => { - const delegate = this._delegate; - this._showKeyboard(); - this._registerKeyboardEvent(); - this._editing = true; - _currentEditBoxImpl = this; - delegate._editBoxEditingDidBegan(); - }); - }, - - endEditing () { - this._hideKeyboard(); - const cbs = this._eventListeners; - cbs.onKeyboardComplete && cbs.onKeyboardComplete(); - }, - - _registerKeyboardEvent () { - const self = this; - const delegate = this._delegate; - const cbs = this._eventListeners; - - cbs.onKeyboardInput = function (res) { - if (delegate._string !== res.value) { - delegate._editBoxTextChanged(res.value); - } - }; - - cbs.onKeyboardConfirm = function (res) { - res && res.value ? delegate._editBoxEditingReturn(res.value) : delegate._editBoxEditingReturn(); - const cbs = self._eventListeners; - cbs.onKeyboardComplete && cbs.onKeyboardComplete(res); - }; - - cbs.onKeyboardComplete = function (res) { - self._editing = false; - _currentEditBoxImpl = null; - // wechat program do not have offKeyboard related callback - if (cc.sys.platform !== cc.sys.Platform.WECHAT_MINI_PROGRAM) { - self._unregisterKeyboardEvent(); - } - if (res && res.value && res.value !== delegate.string) { - delegate._editBoxTextChanged(res.value); - } - res && res.value ? delegate._editBoxEditingDidEnded(res.value) : delegate._editBoxEditingDidEnded(); - }; - - __globalAdapter.onKeyboardInput(cbs.onKeyboardInput); - __globalAdapter.onKeyboardConfirm(cbs.onKeyboardConfirm); - __globalAdapter.onKeyboardComplete(cbs.onKeyboardComplete); - }, - - _unregisterKeyboardEvent () { - const cbs = this._eventListeners; - - if (cbs.onKeyboardInput) { - __globalAdapter.offKeyboardInput(cbs.onKeyboardInput); - cbs.onKeyboardInput = null; - } - if (cbs.onKeyboardConfirm) { - __globalAdapter.offKeyboardConfirm(cbs.onKeyboardConfirm); - cbs.onKeyboardConfirm = null; - } - if (cbs.onKeyboardComplete) { - __globalAdapter.offKeyboardComplete(cbs.onKeyboardComplete); - cbs.onKeyboardComplete = null; - } - }, - - _otherEditing () { - return !!_currentEditBoxImpl && _currentEditBoxImpl !== this && _currentEditBoxImpl._editing; - }, - - _ensureKeyboardHide (cb) { - const otherEditing = this._otherEditing(); - if (!otherEditing && !_hideKeyboardTimeout) { - return cb(); - } - if (_hideKeyboardTimeout) { - clearTimeout(_hideKeyboardTimeout); - } - if (otherEditing) { - _currentEditBoxImpl.endEditing(); - } - _hideKeyboardTimeout = setTimeout(() => { - _hideKeyboardTimeout = null; - cb(); - }, KEYBOARD_HIDE_TIME); - }, - - _showKeyboard () { - const delegate = this._delegate; - const multiline = (delegate.inputMode === EditBoxComp.InputMode.ANY); - __globalAdapter.showKeyboard({ - defaultValue: delegate.string, - maxLength: delegate.maxLength < 0 ? MAX_VALUE : delegate.maxLength, - multiple: multiline, - confirmHold: false, - confirmType: getKeyboardReturnType(delegate.returnType), - success (res) { - - }, - fail (res) { - cc.warn(res.errMsg); - }, - }); - }, - - _hideKeyboard () { - __globalAdapter.hideKeyboard({ - success (res) { - - }, - fail (res) { - cc.warn(res.errMsg); - }, - }); - }, - }); -}()); diff --git a/platforms/minigame/common/engine/cache-manager.js b/platforms/minigame/common/engine/cache-manager.js deleted file mode 100644 index 8a9749670d..0000000000 --- a/platforms/minigame/common/engine/cache-manager.js +++ /dev/null @@ -1,300 +0,0 @@ -/**************************************************************************** - Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of cache-manager 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 cache-manager 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. - ****************************************************************************/ -const { - getUserDataPath, readJsonSync, makeDirSync, - writeFileSync, writeFile, copyFile, downloadFile, deleteFile, - rmdirSync, unzip, isOutOfStorage, -} = window.fsUtils; - -let checkNextPeriod = false; -let writeCacheFileList = null; -let startWrite = false; -let nextCallbacks = []; -let callbacks = []; -let cleaning = false; -let suffix = 0; -const REGEX = /^https?:\/\/.*/; - -const cacheManager = { - - cacheDir: 'gamecaches', - - cachedFileName: 'cacheList.json', - - // whether or not cache asset into user's storage space - cacheEnabled: true, - - // whether or not auto clear cache when storage ran out - autoClear: true, - - // cache one per cycle - cacheInterval: 500, - - deleteInterval: 500, - - writeFileInterval: 2000, - - // whether or not storage space has run out - outOfStorage: false, - - tempFiles: null, - - cachedFiles: null, - - cacheQueue: {}, - - version: '1.0', - - getCache (url) { - return this.cachedFiles.has(url) ? this.cachedFiles.get(url).url : ''; - }, - - getTemp (url) { - return this.tempFiles.has(url) ? this.tempFiles.get(url) : ''; - }, - - init () { - this.cacheDir = `${getUserDataPath()}/${this.cacheDir}`; - const cacheFilePath = `${this.cacheDir}/${this.cachedFileName}`; - const result = readJsonSync(cacheFilePath); - if (result instanceof Error || !result.version) { - if (!(result instanceof Error)) rmdirSync(this.cacheDir, true); - this.cachedFiles = new cc.AssetManager.Cache(); - makeDirSync(this.cacheDir, true); - writeFileSync(cacheFilePath, JSON.stringify({ files: this.cachedFiles._map, version: this.version }), 'utf8'); - } else { - this.cachedFiles = new cc.AssetManager.Cache(result.files); - } - this.tempFiles = new cc.AssetManager.Cache(); - }, - - updateLastTime (url) { - if (this.cachedFiles.has(url)) { - const cache = this.cachedFiles.get(url); - cache.lastTime = Date.now(); - } - }, - - _write () { - writeCacheFileList = null; - startWrite = true; - writeFile(this.cacheDir + '/' + this.cachedFileName, JSON.stringify({ files: this.cachedFiles._map, version: this.version }), 'utf8', function () { - startWrite = false; - for (let i = 0, j = callbacks.length; i < j; i++) { - callbacks[i](); - } - callbacks.length = 0; - callbacks.push.apply(callbacks, nextCallbacks); - nextCallbacks.length = 0; - }); - }, - - writeCacheFile (cb) { - if (!writeCacheFileList) { - writeCacheFileList = setTimeout(this._write.bind(this), this.writeFileInterval); - if (startWrite === true) { - cb && nextCallbacks.push(cb); - } - else { - cb && callbacks.push(cb); - } - } else { - cb && callbacks.push(cb); - } - }, - - _cache () { - const self = this; - for (const id in this.cacheQueue) { - const { srcUrl, isCopy, cacheBundleRoot } = this.cacheQueue[id]; - const time = Date.now().toString(); - - let localPath = ''; - - if (cacheBundleRoot) { - localPath = `${this.cacheDir}/${cacheBundleRoot}/${time}${suffix++}${cc.path.extname(id)}`; - } - else { - localPath = `${this.cacheDir}/${time}${suffix++}${cc.path.extname(id)}`; - } - - function callback (err) { - checkNextPeriod = false; - if (err) { - if (isOutOfStorage(err.message)) { - self.outOfStorage = true; - self.autoClear && self.clearLRU(); - return; - } - } else { - self.cachedFiles.add(id, { bundle: cacheBundleRoot, url: localPath, lastTime: time }); - delete self.cacheQueue[id]; - self.writeCacheFile(); - } - if (!cc.js.isEmptyObject(self.cacheQueue)) { - checkNextPeriod = true; - setTimeout(self._cache.bind(self), self.cacheInterval); - } - } - if (!isCopy) { - downloadFile(srcUrl, localPath, null, callback); - } - else { - copyFile(srcUrl, localPath, callback); - } - return; - } - checkNextPeriod = false; - }, - - cacheFile (id, srcUrl, cacheEnabled, cacheBundleRoot, isCopy) { - cacheEnabled = cacheEnabled !== undefined ? cacheEnabled : this.cacheEnabled; - if (!cacheEnabled || this.cacheQueue[id] || this.cachedFiles.has(id)) return; - - this.cacheQueue[id] = { srcUrl, cacheBundleRoot, isCopy }; - if (!checkNextPeriod) { - checkNextPeriod = true; - if (!this.outOfStorage) { - setTimeout(this._cache.bind(this), this.cacheInterval); - } - else { - checkNextPeriod = false; - } - } - }, - - clearCache () { - rmdirSync(this.cacheDir, true); - this.cachedFiles = new cc.AssetManager.Cache(); - makeDirSync(this.cacheDir, true); - const cacheFilePath = this.cacheDir + '/' + this.cachedFileName; - this.outOfStorage = false; - clearTimeout(writeCacheFileList); - writeCacheFileList = null; - writeFileSync(cacheFilePath, JSON.stringify({ files: this.cachedFiles._map, version: this.version }), 'utf8'); - cc.assetManager.bundles.forEach(bundle => { - if (REGEX.test(bundle.base)) this.makeBundleFolder(bundle.name); - }); - }, - - clearLRU () { - if (cleaning) return; - cleaning = true; - const caches = []; - const self = this; - this.cachedFiles.forEach((val, key) => { - if (self._isZipFile(key) && cc.assetManager.bundles.find((bundle) => bundle.base.indexOf(val.url) !== -1)) return; - caches.push({ originUrl: key, url: val.url, lastTime: val.lastTime }); - }); - caches.sort((a, b) => a.lastTime - b.lastTime); - // cache length above 3 then clear 1/3, or clear all caches - if (caches.length < 3) { - console.warn('Insufficient storage, cleaning now'); - } else { - caches.length = Math.floor(caches.length / 3); - } - for (let i = 0, l = caches.length; i < l; i++) { - const cacheKey = `${cc.assetManager.utils.getUuidFromURL(caches[i].originUrl)}@native`; - cc.assetManager.files.remove(cacheKey); - this.cachedFiles.remove(caches[i].originUrl); - } - - clearTimeout(writeCacheFileList); - writeCacheFileList = null; - this.writeCacheFile(function () { - function deferredDelete () { - const item = caches.pop(); - self._removePathOrFile(item.originUrl, item.url); - if (caches.length > 0) { - setTimeout(deferredDelete, self.deleteInterval); - } - else { - cleaning = false; - } - } - setTimeout(deferredDelete, self.deleteInterval); - }); - }, - - removeCache (url) { - if (this.cachedFiles.has(url)) { - const self = this; - const path = this.cachedFiles.remove(url).url; - clearTimeout(writeCacheFileList); - writeCacheFileList = null; - this.writeCacheFile(function () { - self._removePathOrFile(url, path); - }); - } - }, - - _removePathOrFile (url, path) { - if (this._isZipFile(url)) { - if (this._isZipFile(path)) { - deleteFile(path, this._deleteFileCB.bind(this)); - } else { - rmdirSync(path, true); - this._deleteFileCB(); - } - } else { - deleteFile(path, this._deleteFileCB.bind(this)); - } - }, - - _deleteFileCB (err) { - if (!err) this.outOfStorage = false; - }, - - makeBundleFolder (bundleName) { - makeDirSync(`${this.cacheDir}/${bundleName}`, true); - }, - - unzipAndCacheBundle (id, zipFilePath, cacheBundleRoot, onComplete) { - const time = Date.now().toString(); - const targetPath = `${this.cacheDir}/${cacheBundleRoot}/${time}${suffix++}`; - const self = this; - makeDirSync(targetPath, true); - unzip(zipFilePath, targetPath, (err) => { - if (err) { - rmdirSync(targetPath, true); - if (isOutOfStorage(err.message)) { - self.outOfStorage = true; - self.autoClear && self.clearLRU(); - } - onComplete && onComplete(err); - return; - } - self.cachedFiles.add(id, { bundle: cacheBundleRoot, url: targetPath, lastTime: time }); - self.writeCacheFile(); - onComplete && onComplete(null, targetPath); - }); - }, - - _isZipFile (url) { - return url.slice(-4) === '.zip'; - }, -}; - -cc.assetManager.cacheManager = module.exports = cacheManager; diff --git a/platforms/minigame/common/engine/index.js b/platforms/minigame/common/engine/index.js deleted file mode 100644 index 36c1cbb1c8..0000000000 --- a/platforms/minigame/common/engine/index.js +++ /dev/null @@ -1,2 +0,0 @@ -require('./Editbox'); -require('./AssetManager'); diff --git a/platforms/minigame/common/xmldom/dom-parser.js b/platforms/minigame/common/xmldom/dom-parser.js deleted file mode 100644 index 5260db5891..0000000000 --- a/platforms/minigame/common/xmldom/dom-parser.js +++ /dev/null @@ -1,254 +0,0 @@ -function DOMParser(options){ - this.options = options ||{locator:{}}; - -} - -DOMParser.prototype.parseFromString = function(source,mimeType){ - var options = this.options; - var sax = new XMLReader(); - var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler - var errorHandler = options.errorHandler; - var locator = options.locator; - var defaultNSMap = options.xmlns||{}; - var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1; - var entityMap = isHTML?htmlEntity.entityMap:{'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"}; - if(locator){ - domBuilder.setDocumentLocator(locator) - } - - sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator); - sax.domBuilder = options.domBuilder || domBuilder; - if(isHTML){ - defaultNSMap['']= 'http://www.w3.org/1999/xhtml'; - } - defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace'; - if(source){ - sax.parse(source,defaultNSMap,entityMap); - }else{ - sax.errorHandler.error("invalid doc source"); - } - return domBuilder.doc; -} -function buildErrorHandler(errorImpl,domBuilder,locator){ - if(!errorImpl){ - if(domBuilder instanceof DOMHandler){ - return domBuilder; - } - errorImpl = domBuilder ; - } - var errorHandler = {} - var isCallback = errorImpl instanceof Function; - locator = locator||{} - function build(key){ - var fn = errorImpl[key]; - if(!fn && isCallback){ - fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl; - } - errorHandler[key] = fn && function(msg){ - fn('[xmldom '+key+']\t'+msg+_locator(locator)); - }||function(){}; - } - build('warning'); - build('error'); - build('fatalError'); - return errorHandler; -} - -//console.log('#\n\n\n\n\n\n\n####') -/** - * +ContentHandler+ErrorHandler - * +LexicalHandler+EntityResolver2 - * -DeclHandler-DTDHandler - * - * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler - * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2 - * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html - */ -function DOMHandler() { - this.cdata = false; -} -function position(locator,node){ - node.lineNumber = locator.lineNumber; - node.columnNumber = locator.columnNumber; -} -/** - * @see org.xml.sax.ContentHandler#startDocument - * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html - */ -DOMHandler.prototype = { - startDocument : function() { - this.doc = new DOMImplementation().createDocument(null, null, null); - if (this.locator) { - this.doc.documentURI = this.locator.systemId; - } - }, - startElement:function(namespaceURI, localName, qName, attrs) { - var doc = this.doc; - var el = doc.createElementNS(namespaceURI, qName||localName); - var len = attrs.length; - appendElement(this, el); - this.currentElement = el; - - this.locator && position(this.locator,el) - for (var i = 0 ; i < len; i++) { - var namespaceURI = attrs.getURI(i); - var value = attrs.getValue(i); - var qName = attrs.getQName(i); - var attr = doc.createAttributeNS(namespaceURI, qName); - this.locator &&position(attrs.getLocator(i),attr); - attr.value = attr.nodeValue = value; - el.setAttributeNode(attr) - } - }, - endElement:function(namespaceURI, localName, qName) { - var current = this.currentElement - var tagName = current.tagName; - this.currentElement = current.parentNode; - }, - startPrefixMapping:function(prefix, uri) { - }, - endPrefixMapping:function(prefix) { - }, - processingInstruction:function(target, data) { - var ins = this.doc.createProcessingInstruction(target, data); - this.locator && position(this.locator,ins) - appendElement(this, ins); - }, - ignorableWhitespace:function(ch, start, length) { - }, - characters:function(chars, start, length) { - chars = _toString.apply(this,arguments) - //console.log(chars) - if(chars){ - if (this.cdata) { - var charNode = this.doc.createCDATASection(chars); - } else { - var charNode = this.doc.createTextNode(chars); - } - if(this.currentElement){ - this.currentElement.appendChild(charNode); - }else if(/^\s*$/.test(chars)){ - this.doc.appendChild(charNode); - //process xml - } - this.locator && position(this.locator,charNode) - } - }, - skippedEntity:function(name) { - }, - endDocument:function() { - this.doc.normalize(); - }, - setDocumentLocator:function (locator) { - if(this.locator = locator){// && !('lineNumber' in locator)){ - locator.lineNumber = 0; - } - }, - //LexicalHandler - comment:function(chars, start, length) { - chars = _toString.apply(this,arguments) - var comm = this.doc.createComment(chars); - this.locator && position(this.locator,comm) - appendElement(this, comm); - }, - - startCDATA:function() { - //used in characters() methods - this.cdata = true; - }, - endCDATA:function() { - this.cdata = false; - }, - - startDTD:function(name, publicId, systemId) { - var impl = this.doc.implementation; - if (impl && impl.createDocumentType) { - var dt = impl.createDocumentType(name, publicId, systemId); - this.locator && position(this.locator,dt) - appendElement(this, dt); - } - }, - /** - * @see org.xml.sax.ErrorHandler - * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html - */ - warning:function(error) { - console.warn('[xmldom warning]\t'+error,_locator(this.locator)); - }, - error:function(error) { - console.error('[xmldom error]\t'+error,_locator(this.locator)); - }, - fatalError:function(error) { - console.error('[xmldom fatalError]\t'+error,_locator(this.locator)); - throw error; - } -} -function _locator(l){ - if(l){ - return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']' - } -} -function _toString(chars,start,length){ - if(typeof chars == 'string'){ - return chars.substr(start,length) - }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)") - if(chars.length >= start+length || start){ - return new java.lang.String(chars,start,length)+''; - } - return chars; - } -} - -/* - * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html - * used method of org.xml.sax.ext.LexicalHandler: - * #comment(chars, start, length) - * #startCDATA() - * #endCDATA() - * #startDTD(name, publicId, systemId) - * - * - * IGNORED method of org.xml.sax.ext.LexicalHandler: - * #endDTD() - * #startEntity(name) - * #endEntity(name) - * - * - * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html - * IGNORED method of org.xml.sax.ext.DeclHandler - * #attributeDecl(eName, aName, type, mode, value) - * #elementDecl(name, model) - * #externalEntityDecl(name, publicId, systemId) - * #internalEntityDecl(name, value) - * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html - * IGNORED method of org.xml.sax.EntityResolver2 - * #resolveEntity(String name,String publicId,String baseURI,String systemId) - * #resolveEntity(publicId, systemId) - * #getExternalSubset(name, baseURI) - * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html - * IGNORED method of org.xml.sax.DTDHandler - * #notationDecl(name, publicId, systemId) {}; - * #unparsedEntityDecl(name, publicId, systemId, notationName) {}; - */ -"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){ - DOMHandler.prototype[key] = function(){return null} -}) - -/* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */ -function appendElement (hander,node) { - if (!hander.currentElement) { - hander.doc.appendChild(node); - } else { - hander.currentElement.appendChild(node); - } -}//appendChild and setAttributeNS are preformance key - -//if(typeof require == 'function'){ -var htmlEntity = require('./entities'); -var XMLReader = require('./sax').XMLReader; -var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation; -exports.XMLSerializer = require('./dom').XMLSerializer ; -exports.DOMParser = DOMParser; - -window.DOMParser = DOMParser; -//} diff --git a/platforms/minigame/common/xmldom/dom.js b/platforms/minigame/common/xmldom/dom.js deleted file mode 100755 index 935531b385..0000000000 --- a/platforms/minigame/common/xmldom/dom.js +++ /dev/null @@ -1,1246 +0,0 @@ -/* - * DOM Level 2 - * Object DOMException - * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html - * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - */ - -function copy(src,dest){ - for(var p in src){ - dest[p] = src[p]; - } -} -/** -^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));? -^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));? - */ -function _extends(Class,Super){ - var pt = Class.prototype; - if(!(pt instanceof Super)){ - function t(){}; - t.prototype = Super.prototype; - t = new t(); - // copy(pt,t); - for(var p in pt){ - t[p] = pt[p]; - } - Class.prototype = pt = t; - } - if(pt.constructor != Class){ - if(typeof Class != 'function'){ - console.error("unknow Class:"+Class) - } - pt.constructor = Class - } -} -var htmlns = 'http://www.w3.org/1999/xhtml' ; -// Node Types -var NodeType = {} -var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1; -var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2; -var TEXT_NODE = NodeType.TEXT_NODE = 3; -var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4; -var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5; -var ENTITY_NODE = NodeType.ENTITY_NODE = 6; -var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7; -var COMMENT_NODE = NodeType.COMMENT_NODE = 8; -var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9; -var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10; -var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11; -var NOTATION_NODE = NodeType.NOTATION_NODE = 12; - -// ExceptionCode -var ExceptionCode = {} -var ExceptionMessage = {}; -var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1); -var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2); -var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3); -var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4); -var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5); -var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6); -var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7); -var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8); -var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9); -var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10); -//level2 -var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11); -var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12); -var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13); -var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14); -var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15); - - -function DOMException(code, message) { - if(message instanceof Error){ - var error = message; - }else{ - error = this; - Error.call(this, ExceptionMessage[code]); - this.message = ExceptionMessage[code]; - if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException); - } - error.code = code; - if(message) this.message = this.message + ": " + message; - return error; -}; -DOMException.prototype = Error.prototype; -copy(ExceptionCode,DOMException) -/** - * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177 - * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live. - * The items in the NodeList are accessible via an integral index, starting from 0. - */ -function NodeList() { -}; -NodeList.prototype = { - /** - * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive. - * @standard level1 - */ - length:0, - /** - * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null. - * @standard level1 - * @param index unsigned long - * Index into the collection. - * @return Node - * The node at the indexth position in the NodeList, or null if that is not a valid index. - */ - item: function(index) { - return this[index] || null; - }, - toString:function(isHTML,nodeFilter){ - for(var buf = [], i = 0;i=0){ - var lastIndex = list.length-1 - while(i0 || key == 'xmlns'){ -// return null; -// } - //console.log() - var i = this.length; - while(i--){ - var attr = this[i]; - //console.log(attr.nodeName,key) - if(attr.nodeName == key){ - return attr; - } - } - }, - setNamedItem: function(attr) { - var el = attr.ownerElement; - if(el && el!=this._ownerElement){ - throw new DOMException(INUSE_ATTRIBUTE_ERR); - } - var oldAttr = this.getNamedItem(attr.nodeName); - _addNamedNode(this._ownerElement,this,attr,oldAttr); - return oldAttr; - }, - /* returns Node */ - setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR - var el = attr.ownerElement, oldAttr; - if(el && el!=this._ownerElement){ - throw new DOMException(INUSE_ATTRIBUTE_ERR); - } - oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName); - _addNamedNode(this._ownerElement,this,attr,oldAttr); - return oldAttr; - }, - - /* returns Node */ - removeNamedItem: function(key) { - var attr = this.getNamedItem(key); - _removeNamedNode(this._ownerElement,this,attr); - return attr; - - - },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR - - //for level2 - removeNamedItemNS:function(namespaceURI,localName){ - var attr = this.getNamedItemNS(namespaceURI,localName); - _removeNamedNode(this._ownerElement,this,attr); - return attr; - }, - getNamedItemNS: function(namespaceURI, localName) { - var i = this.length; - while(i--){ - var node = this[i]; - if(node.localName == localName && node.namespaceURI == namespaceURI){ - return node; - } - } - return null; - } -}; -/** - * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490 - */ -function DOMImplementation(/* Object */ features) { - this._features = {}; - if (features) { - for (var feature in features) { - this._features = features[feature]; - } - } -}; - -DOMImplementation.prototype = { - hasFeature: function(/* string */ feature, /* string */ version) { - var versions = this._features[feature.toLowerCase()]; - if (versions && (!version || version in versions)) { - return true; - } else { - return false; - } - }, - // Introduced in DOM Level 2: - createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR - var doc = new Document(); - doc.implementation = this; - doc.childNodes = new NodeList(); - doc.doctype = doctype; - if(doctype){ - doc.appendChild(doctype); - } - if(qualifiedName){ - var root = doc.createElementNS(namespaceURI,qualifiedName); - doc.appendChild(root); - } - return doc; - }, - // Introduced in DOM Level 2: - createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR - var node = new DocumentType(); - node.name = qualifiedName; - node.nodeName = qualifiedName; - node.publicId = publicId; - node.systemId = systemId; - // Introduced in DOM Level 2: - //readonly attribute DOMString internalSubset; - - //TODO:.. - // readonly attribute NamedNodeMap entities; - // readonly attribute NamedNodeMap notations; - return node; - } -}; - - -/** - * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 - */ - -function Node() { -}; - -Node.prototype = { - firstChild : null, - lastChild : null, - previousSibling : null, - nextSibling : null, - attributes : null, - parentNode : null, - childNodes : null, - ownerDocument : null, - nodeValue : null, - namespaceURI : null, - prefix : null, - localName : null, - // Modified in DOM Level 2: - insertBefore:function(newChild, refChild){//raises - return _insertBefore(this,newChild,refChild); - }, - replaceChild:function(newChild, oldChild){//raises - this.insertBefore(newChild,oldChild); - if(oldChild){ - this.removeChild(oldChild); - } - }, - removeChild:function(oldChild){ - return _removeChild(this,oldChild); - }, - appendChild:function(newChild){ - return this.insertBefore(newChild,null); - }, - hasChildNodes:function(){ - return this.firstChild != null; - }, - cloneNode:function(deep){ - return cloneNode(this.ownerDocument||this,this,deep); - }, - // Modified in DOM Level 2: - normalize:function(){ - var child = this.firstChild; - while(child){ - var next = child.nextSibling; - if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){ - this.removeChild(next); - child.appendData(next.data); - }else{ - child.normalize(); - child = next; - } - } - }, - // Introduced in DOM Level 2: - isSupported:function(feature, version){ - return this.ownerDocument.implementation.hasFeature(feature,version); - }, - // Introduced in DOM Level 2: - hasAttributes:function(){ - return this.attributes.length>0; - }, - lookupPrefix:function(namespaceURI){ - var el = this; - while(el){ - var map = el._nsMap; - //console.dir(map) - if(map){ - for(var n in map){ - if(map[n] == namespaceURI){ - return n; - } - } - } - el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode; - } - return null; - }, - // Introduced in DOM Level 3: - lookupNamespaceURI:function(prefix){ - var el = this; - while(el){ - var map = el._nsMap; - //console.dir(map) - if(map){ - if(prefix in map){ - return map[prefix] ; - } - } - el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode; - } - return null; - }, - // Introduced in DOM Level 3: - isDefaultNamespace:function(namespaceURI){ - var prefix = this.lookupPrefix(namespaceURI); - return prefix == null; - } -}; - - -function _xmlEncoder(c){ - return c == '<' && '<' || - c == '>' && '>' || - c == '&' && '&' || - c == '"' && '"' || - '&#'+c.charCodeAt()+';' -} - - -copy(NodeType,Node); -copy(NodeType,Node.prototype); - -/** - * @param callback return true for continue,false for break - * @return boolean true: break visit; - */ -function _visitNode(node,callback){ - if(callback(node)){ - return true; - } - if(node = node.firstChild){ - do{ - if(_visitNode(node,callback)){return true} - }while(node=node.nextSibling) - } -} - - - -function Document(){ -} -function _onAddAttribute(doc,el,newAttr){ - doc && doc._inc++; - var ns = newAttr.namespaceURI ; - if(ns == 'http://www.w3.org/2000/xmlns/'){ - //update namespace - el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value - } -} -function _onRemoveAttribute(doc,el,newAttr,remove){ - doc && doc._inc++; - var ns = newAttr.namespaceURI ; - if(ns == 'http://www.w3.org/2000/xmlns/'){ - //update namespace - delete el._nsMap[newAttr.prefix?newAttr.localName:''] - } -} -function _onUpdateChild(doc,el,newChild){ - if(doc && doc._inc){ - doc._inc++; - //update childNodes - var cs = el.childNodes; - if(newChild){ - cs[cs.length++] = newChild; - }else{ - //console.log(1) - var child = el.firstChild; - var i = 0; - while(child){ - cs[i++] = child; - child =child.nextSibling; - } - cs.length = i; - } - } -} - -/** - * attributes; - * children; - * - * writeable properties: - * nodeValue,Attr:value,CharacterData:data - * prefix - */ -function _removeChild(parentNode,child){ - var previous = child.previousSibling; - var next = child.nextSibling; - if(previous){ - previous.nextSibling = next; - }else{ - parentNode.firstChild = next - } - if(next){ - next.previousSibling = previous; - }else{ - parentNode.lastChild = previous; - } - _onUpdateChild(parentNode.ownerDocument,parentNode); - return child; -} -/** - * preformance key(refChild == null) - */ -function _insertBefore(parentNode,newChild,nextChild){ - var cp = newChild.parentNode; - if(cp){ - cp.removeChild(newChild);//remove and update - } - if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){ - var newFirst = newChild.firstChild; - if (newFirst == null) { - return newChild; - } - var newLast = newChild.lastChild; - }else{ - newFirst = newLast = newChild; - } - var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild; - - newFirst.previousSibling = pre; - newLast.nextSibling = nextChild; - - - if(pre){ - pre.nextSibling = newFirst; - }else{ - parentNode.firstChild = newFirst; - } - if(nextChild == null){ - parentNode.lastChild = newLast; - }else{ - nextChild.previousSibling = newLast; - } - do{ - newFirst.parentNode = parentNode; - }while(newFirst !== newLast && (newFirst= newFirst.nextSibling)) - _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode); - //console.log(parentNode.lastChild.nextSibling == null) - if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) { - newChild.firstChild = newChild.lastChild = null; - } - return newChild; -} -function _appendSingleChild(parentNode,newChild){ - var cp = newChild.parentNode; - if(cp){ - var pre = parentNode.lastChild; - cp.removeChild(newChild);//remove and update - var pre = parentNode.lastChild; - } - var pre = parentNode.lastChild; - newChild.parentNode = parentNode; - newChild.previousSibling = pre; - newChild.nextSibling = null; - if(pre){ - pre.nextSibling = newChild; - }else{ - parentNode.firstChild = newChild; - } - parentNode.lastChild = newChild; - _onUpdateChild(parentNode.ownerDocument,parentNode,newChild); - return newChild; - //console.log("__aa",parentNode.lastChild.nextSibling == null) -} -Document.prototype = { - //implementation : null, - nodeName : '#document', - nodeType : DOCUMENT_NODE, - doctype : null, - documentElement : null, - _inc : 1, - - insertBefore : function(newChild, refChild){//raises - if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){ - var child = newChild.firstChild; - while(child){ - var next = child.nextSibling; - this.insertBefore(child,refChild); - child = next; - } - return newChild; - } - if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){ - this.documentElement = newChild; - } - - return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild; - }, - removeChild : function(oldChild){ - if(this.documentElement == oldChild){ - this.documentElement = null; - } - return _removeChild(this,oldChild); - }, - // Introduced in DOM Level 2: - importNode : function(importedNode,deep){ - return importNode(this,importedNode,deep); - }, - // Introduced in DOM Level 2: - getElementById : function(id){ - var rtv = null; - _visitNode(this.documentElement,function(node){ - if(node.nodeType == ELEMENT_NODE){ - if(node.getAttribute('id') == id){ - rtv = node; - return true; - } - } - }) - return rtv; - }, - - //document factory method: - createElement : function(tagName){ - var node = new Element(); - node.ownerDocument = this; - node.nodeName = tagName; - node.tagName = tagName; - node.childNodes = new NodeList(); - var attrs = node.attributes = new NamedNodeMap(); - attrs._ownerElement = node; - return node; - }, - createDocumentFragment : function(){ - var node = new DocumentFragment(); - node.ownerDocument = this; - node.childNodes = new NodeList(); - return node; - }, - createTextNode : function(data){ - var node = new Text(); - node.ownerDocument = this; - node.appendData(data) - return node; - }, - createComment : function(data){ - var node = new Comment(); - node.ownerDocument = this; - node.appendData(data) - return node; - }, - createCDATASection : function(data){ - var node = new CDATASection(); - node.ownerDocument = this; - node.appendData(data) - return node; - }, - createProcessingInstruction : function(target,data){ - var node = new ProcessingInstruction(); - node.ownerDocument = this; - node.tagName = node.target = target; - node.nodeValue= node.data = data; - return node; - }, - createAttribute : function(name){ - var node = new Attr(); - node.ownerDocument = this; - node.name = name; - node.nodeName = name; - node.localName = name; - node.specified = true; - return node; - }, - createEntityReference : function(name){ - var node = new EntityReference(); - node.ownerDocument = this; - node.nodeName = name; - return node; - }, - // Introduced in DOM Level 2: - createElementNS : function(namespaceURI,qualifiedName){ - var node = new Element(); - var pl = qualifiedName.split(':'); - var attrs = node.attributes = new NamedNodeMap(); - node.childNodes = new NodeList(); - node.ownerDocument = this; - node.nodeName = qualifiedName; - node.tagName = qualifiedName; - node.namespaceURI = namespaceURI; - if(pl.length == 2){ - node.prefix = pl[0]; - node.localName = pl[1]; - }else{ - //el.prefix = null; - node.localName = qualifiedName; - } - attrs._ownerElement = node; - return node; - }, - // Introduced in DOM Level 2: - createAttributeNS : function(namespaceURI,qualifiedName){ - var node = new Attr(); - var pl = qualifiedName.split(':'); - node.ownerDocument = this; - node.nodeName = qualifiedName; - node.name = qualifiedName; - node.namespaceURI = namespaceURI; - node.specified = true; - if(pl.length == 2){ - node.prefix = pl[0]; - node.localName = pl[1]; - }else{ - //el.prefix = null; - node.localName = qualifiedName; - } - return node; - } -}; -_extends(Document,Node); - - -function Element() { - this._nsMap = {}; -}; -Element.prototype = { - nodeType : ELEMENT_NODE, - hasAttribute : function(name){ - return this.getAttributeNode(name)!=null; - }, - getAttribute : function(name){ - var attr = this.getAttributeNode(name); - return attr && attr.value || ''; - }, - getAttributeNode : function(name){ - return this.attributes.getNamedItem(name); - }, - setAttribute : function(name, value){ - var attr = this.ownerDocument.createAttribute(name); - attr.value = attr.nodeValue = "" + value; - this.setAttributeNode(attr) - }, - removeAttribute : function(name){ - var attr = this.getAttributeNode(name) - attr && this.removeAttributeNode(attr); - }, - - //four real opeartion method - appendChild:function(newChild){ - if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){ - return this.insertBefore(newChild,null); - }else{ - return _appendSingleChild(this,newChild); - } - }, - setAttributeNode : function(newAttr){ - return this.attributes.setNamedItem(newAttr); - }, - setAttributeNodeNS : function(newAttr){ - return this.attributes.setNamedItemNS(newAttr); - }, - removeAttributeNode : function(oldAttr){ - //console.log(this == oldAttr.ownerElement) - return this.attributes.removeNamedItem(oldAttr.nodeName); - }, - //get real attribute name,and remove it by removeAttributeNode - removeAttributeNS : function(namespaceURI, localName){ - var old = this.getAttributeNodeNS(namespaceURI, localName); - old && this.removeAttributeNode(old); - }, - - hasAttributeNS : function(namespaceURI, localName){ - return this.getAttributeNodeNS(namespaceURI, localName)!=null; - }, - getAttributeNS : function(namespaceURI, localName){ - var attr = this.getAttributeNodeNS(namespaceURI, localName); - return attr && attr.value || ''; - }, - setAttributeNS : function(namespaceURI, qualifiedName, value){ - var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName); - attr.value = attr.nodeValue = "" + value; - this.setAttributeNode(attr) - }, - getAttributeNodeNS : function(namespaceURI, localName){ - return this.attributes.getNamedItemNS(namespaceURI, localName); - }, - - getElementsByTagName : function(tagName){ - return new LiveNodeList(this,function(base){ - var ls = []; - _visitNode(base,function(node){ - if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){ - ls.push(node); - } - }); - return ls; - }); - }, - getElementsByTagNameNS : function(namespaceURI, localName){ - return new LiveNodeList(this,function(base){ - var ls = []; - _visitNode(base,function(node){ - if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){ - ls.push(node); - } - }); - return ls; - - }); - } -}; -Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName; -Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS; - - -_extends(Element,Node); -function Attr() { -}; -Attr.prototype.nodeType = ATTRIBUTE_NODE; -_extends(Attr,Node); - - -function CharacterData() { -}; -CharacterData.prototype = { - data : '', - substringData : function(offset, count) { - return this.data.substring(offset, offset+count); - }, - appendData: function(text) { - text = this.data+text; - this.nodeValue = this.data = text; - this.length = text.length; - }, - insertData: function(offset,text) { - this.replaceData(offset,0,text); - - }, - appendChild:function(newChild){ - throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]) - }, - deleteData: function(offset, count) { - this.replaceData(offset,count,""); - }, - replaceData: function(offset, count, text) { - var start = this.data.substring(0,offset); - var end = this.data.substring(offset+count); - text = start + text + end; - this.nodeValue = this.data = text; - this.length = text.length; - } -} -_extends(CharacterData,Node); -function Text() { -}; -Text.prototype = { - nodeName : "#text", - nodeType : TEXT_NODE, - splitText : function(offset) { - var text = this.data; - var newText = text.substring(offset); - text = text.substring(0, offset); - this.data = this.nodeValue = text; - this.length = text.length; - var newNode = this.ownerDocument.createTextNode(newText); - if(this.parentNode){ - this.parentNode.insertBefore(newNode, this.nextSibling); - } - return newNode; - } -} -_extends(Text,CharacterData); -function Comment() { -}; -Comment.prototype = { - nodeName : "#comment", - nodeType : COMMENT_NODE -} -_extends(Comment,CharacterData); - -function CDATASection() { -}; -CDATASection.prototype = { - nodeName : "#cdata-section", - nodeType : CDATA_SECTION_NODE -} -_extends(CDATASection,CharacterData); - - -function DocumentType() { -}; -DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE; -_extends(DocumentType,Node); - -function Notation() { -}; -Notation.prototype.nodeType = NOTATION_NODE; -_extends(Notation,Node); - -function Entity() { -}; -Entity.prototype.nodeType = ENTITY_NODE; -_extends(Entity,Node); - -function EntityReference() { -}; -EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE; -_extends(EntityReference,Node); - -function DocumentFragment() { -}; -DocumentFragment.prototype.nodeName = "#document-fragment"; -DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE; -_extends(DocumentFragment,Node); - - -function ProcessingInstruction() { -} -ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE; -_extends(ProcessingInstruction,Node); -function XMLSerializer(){} -XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){ - return nodeSerializeToString.call(node,isHtml,nodeFilter); -} -Node.prototype.toString = nodeSerializeToString; -function nodeSerializeToString(isHtml,nodeFilter){ - var buf = []; - var refNode = this.nodeType == 9 && this.documentElement || this; - var prefix = refNode.prefix; - var uri = refNode.namespaceURI; - - if(uri && prefix == null){ - //console.log(prefix) - var prefix = refNode.lookupPrefix(uri); - if(prefix == null){ - //isHTML = true; - var visibleNamespaces=[ - {namespace:uri,prefix:null} - //{namespace:uri,prefix:''} - ] - } - } - serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces); - //console.log('###',this.nodeType,uri,prefix,buf.join('')) - return buf.join(''); -} -function needNamespaceDefine(node,isHTML, visibleNamespaces) { - var prefix = node.prefix||''; - var uri = node.namespaceURI; - if (!prefix && !uri){ - return false; - } - if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace" - || uri == 'http://www.w3.org/2000/xmlns/'){ - return false; - } - - var i = visibleNamespaces.length - //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces) - while (i--) { - var ns = visibleNamespaces[i]; - // get namespace prefix - //console.log(node.nodeType,node.tagName,ns.prefix,prefix) - if (ns.prefix == prefix){ - return ns.namespace != uri; - } - } - //console.log(isHTML,uri,prefix=='') - //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){ - // return false; - //} - //node.flag = '11111' - //console.error(3,true,node.flag,node.prefix,node.namespaceURI) - return true; -} -function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){ - if(nodeFilter){ - node = nodeFilter(node); - if(node){ - if(typeof node == 'string'){ - buf.push(node); - return; - } - }else{ - return; - } - //buf.sort.apply(attrs, attributeSorter); - } - switch(node.nodeType){ - case ELEMENT_NODE: - if (!visibleNamespaces) visibleNamespaces = []; - var startVisibleNamespaces = visibleNamespaces.length; - var attrs = node.attributes; - var len = attrs.length; - var child = node.firstChild; - var nodeName = node.tagName; - - isHTML = (htmlns === node.namespaceURI) ||isHTML - buf.push('<',nodeName); - - - - for(var i=0;i'); - //if is cdata child node - if(isHTML && /^script$/i.test(nodeName)){ - while(child){ - if(child.data){ - buf.push(child.data); - }else{ - serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); - } - child = child.nextSibling; - } - }else - { - while(child){ - serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); - child = child.nextSibling; - } - } - buf.push(''); - }else{ - buf.push('/>'); - } - // remove added visible namespaces - //visibleNamespaces.length = startVisibleNamespaces; - return; - case DOCUMENT_NODE: - case DOCUMENT_FRAGMENT_NODE: - var child = node.firstChild; - while(child){ - serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); - child = child.nextSibling; - } - return; - case ATTRIBUTE_NODE: - return buf.push(' ',node.name,'="',node.value.replace(/[<&"]/g,_xmlEncoder),'"'); - case TEXT_NODE: - return buf.push(node.data.replace(/[<&]/g,_xmlEncoder)); - case CDATA_SECTION_NODE: - return buf.push( ''); - case COMMENT_NODE: - return buf.push( ""); - case DOCUMENT_TYPE_NODE: - var pubid = node.publicId; - var sysid = node.systemId; - buf.push(''); - }else if(sysid && sysid!='.'){ - buf.push(' SYSTEM "',sysid,'">'); - }else{ - var sub = node.internalSubset; - if(sub){ - buf.push(" [",sub,"]"); - } - buf.push(">"); - } - return; - case PROCESSING_INSTRUCTION_NODE: - return buf.push( ""); - case ENTITY_REFERENCE_NODE: - return buf.push( '&',node.nodeName,';'); - //case ENTITY_NODE: - //case NOTATION_NODE: - default: - buf.push('??',node.nodeName); - } -} -function importNode(doc,node,deep){ - var node2; - switch (node.nodeType) { - case ELEMENT_NODE: - node2 = node.cloneNode(false); - node2.ownerDocument = doc; - //var attrs = node2.attributes; - //var len = attrs.length; - //for(var i=0;i', - amp: '&', - quot: '"', - apos: "'", - Agrave: "À", - Aacute: "Á", - Acirc: "Â", - Atilde: "Ã", - Auml: "Ä", - Aring: "Å", - AElig: "Æ", - Ccedil: "Ç", - Egrave: "È", - Eacute: "É", - Ecirc: "Ê", - Euml: "Ë", - Igrave: "Ì", - Iacute: "Í", - Icirc: "Î", - Iuml: "Ï", - ETH: "Ð", - Ntilde: "Ñ", - Ograve: "Ò", - Oacute: "Ó", - Ocirc: "Ô", - Otilde: "Õ", - Ouml: "Ö", - Oslash: "Ø", - Ugrave: "Ù", - Uacute: "Ú", - Ucirc: "Û", - Uuml: "Ü", - Yacute: "Ý", - THORN: "Þ", - szlig: "ß", - agrave: "à", - aacute: "á", - acirc: "â", - atilde: "ã", - auml: "ä", - aring: "å", - aelig: "æ", - ccedil: "ç", - egrave: "è", - eacute: "é", - ecirc: "ê", - euml: "ë", - igrave: "ì", - iacute: "í", - icirc: "î", - iuml: "ï", - eth: "ð", - ntilde: "ñ", - ograve: "ò", - oacute: "ó", - ocirc: "ô", - otilde: "õ", - ouml: "ö", - oslash: "ø", - ugrave: "ù", - uacute: "ú", - ucirc: "û", - uuml: "ü", - yacute: "ý", - thorn: "þ", - yuml: "ÿ", - nbsp: " ", - iexcl: "¡", - cent: "¢", - pound: "£", - curren: "¤", - yen: "¥", - brvbar: "¦", - sect: "§", - uml: "¨", - copy: "©", - ordf: "ª", - laquo: "«", - not: "¬", - shy: "­­", - reg: "®", - macr: "¯", - deg: "°", - plusmn: "±", - sup2: "²", - sup3: "³", - acute: "´", - micro: "µ", - para: "¶", - middot: "·", - cedil: "¸", - sup1: "¹", - ordm: "º", - raquo: "»", - frac14: "¼", - frac12: "½", - frac34: "¾", - iquest: "¿", - times: "×", - divide: "÷", - forall: "∀", - part: "∂", - exist: "∃", - empty: "∅", - nabla: "∇", - isin: "∈", - notin: "∉", - ni: "∋", - prod: "∏", - sum: "∑", - minus: "−", - lowast: "∗", - radic: "√", - prop: "∝", - infin: "∞", - ang: "∠", - and: "∧", - or: "∨", - cap: "∩", - cup: "∪", - 'int': "∫", - there4: "∴", - sim: "∼", - cong: "≅", - asymp: "≈", - ne: "≠", - equiv: "≡", - le: "≤", - ge: "≥", - sub: "⊂", - sup: "⊃", - nsub: "⊄", - sube: "⊆", - supe: "⊇", - oplus: "⊕", - otimes: "⊗", - perp: "⊥", - sdot: "⋅", - Alpha: "Α", - Beta: "Β", - Gamma: "Γ", - Delta: "Δ", - Epsilon: "Ε", - Zeta: "Ζ", - Eta: "Η", - Theta: "Θ", - Iota: "Ι", - Kappa: "Κ", - Lambda: "Λ", - Mu: "Μ", - Nu: "Ν", - Xi: "Ξ", - Omicron: "Ο", - Pi: "Π", - Rho: "Ρ", - Sigma: "Σ", - Tau: "Τ", - Upsilon: "Υ", - Phi: "Φ", - Chi: "Χ", - Psi: "Ψ", - Omega: "Ω", - alpha: "α", - beta: "β", - gamma: "γ", - delta: "δ", - epsilon: "ε", - zeta: "ζ", - eta: "η", - theta: "θ", - iota: "ι", - kappa: "κ", - lambda: "λ", - mu: "μ", - nu: "ν", - xi: "ξ", - omicron: "ο", - pi: "π", - rho: "ρ", - sigmaf: "ς", - sigma: "σ", - tau: "τ", - upsilon: "υ", - phi: "φ", - chi: "χ", - psi: "ψ", - omega: "ω", - thetasym: "ϑ", - upsih: "ϒ", - piv: "ϖ", - OElig: "Œ", - oelig: "œ", - Scaron: "Š", - scaron: "š", - Yuml: "Ÿ", - fnof: "ƒ", - circ: "ˆ", - tilde: "˜", - ensp: " ", - emsp: " ", - thinsp: " ", - zwnj: "‌", - zwj: "‍", - lrm: "‎", - rlm: "‏", - ndash: "–", - mdash: "—", - lsquo: "‘", - rsquo: "’", - sbquo: "‚", - ldquo: "“", - rdquo: "”", - bdquo: "„", - dagger: "†", - Dagger: "‡", - bull: "•", - hellip: "…", - permil: "‰", - prime: "′", - Prime: "″", - lsaquo: "‹", - rsaquo: "›", - oline: "‾", - euro: "€", - trade: "™", - larr: "←", - uarr: "↑", - rarr: "→", - darr: "↓", - harr: "↔", - crarr: "↵", - lceil: "⌈", - rceil: "⌉", - lfloor: "⌊", - rfloor: "⌋", - loz: "◊", - spades: "♠", - clubs: "♣", - hearts: "♥", - diams: "♦" -}; -//for(var n in exports.entityMap){console.log(exports.entityMap[n].charCodeAt())} \ No newline at end of file diff --git a/platforms/minigame/common/xmldom/sax.js b/platforms/minigame/common/xmldom/sax.js deleted file mode 100644 index f8b494e097..0000000000 --- a/platforms/minigame/common/xmldom/sax.js +++ /dev/null @@ -1,616 +0,0 @@ -//[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] -//[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] -//[5] Name ::= NameStartChar (NameChar)* -var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF -var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"); -var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$'); -//var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/ -//var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',') - -//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE -//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE -var S_TAG = 0;//tag name offerring -var S_ATTR = 1;//attr name offerring -var S_ATTR_SPACE=2;//attr name end and space offer -var S_EQ = 3;//=space? -var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only) -var S_ATTR_END = 5;//attr value end and no space(quot end) -var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer) -var S_TAG_CLOSE = 7;//closed el - -function XMLReader(){ - -} - -XMLReader.prototype = { - parse:function(source,defaultNSMap,entityMap){ - var domBuilder = this.domBuilder; - domBuilder.startDocument(); - _copy(defaultNSMap ,defaultNSMap = {}) - parse(source,defaultNSMap,entityMap, - domBuilder,this.errorHandler); - domBuilder.endDocument(); - } -} -function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){ - function fixedFromCharCode(code) { - // String.prototype.fromCharCode does not supports - // > 2 bytes unicode chars directly - if (code > 0xffff) { - code -= 0x10000; - var surrogate1 = 0xd800 + (code >> 10) - , surrogate2 = 0xdc00 + (code & 0x3ff); - - return String.fromCharCode(surrogate1, surrogate2); - } else { - return String.fromCharCode(code); - } - } - function entityReplacer(a){ - var k = a.slice(1,-1); - if(k in entityMap){ - return entityMap[k]; - }else if(k.charAt(0) === '#'){ - return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x'))) - }else{ - errorHandler.error('entity not found:'+a); - return a; - } - } - function appendText(end){//has some bugs - if(end>start){ - var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer); - locator&&position(start); - domBuilder.characters(xt,0,end-start); - start = end - } - } - function position(p,m){ - while(p>=lineEnd && (m = linePattern.exec(source))){ - lineStart = m.index; - lineEnd = lineStart + m[0].length; - locator.lineNumber++; - //console.log('line++:',locator,startPos,endPos) - } - locator.columnNumber = p-lineStart+1; - } - var lineStart = 0; - var lineEnd = 0; - var linePattern = /.*(?:\r\n?|\n)|.*$/g - var locator = domBuilder.locator; - - var parseStack = [{currentNSMap:defaultNSMapCopy}] - var closeMap = {}; - var start = 0; - while(true){ - try{ - var tagStart = source.indexOf('<',start); - if(tagStart<0){ - if(!source.substr(start).match(/^\s*$/)){ - var doc = domBuilder.doc; - var text = doc.createTextNode(source.substr(start)); - doc.appendChild(text); - domBuilder.currentElement = text; - } - return; - } - if(tagStart>start){ - appendText(tagStart); - } - switch(source.charAt(tagStart+1)){ - case '/': - var end = source.indexOf('>',tagStart+3); - var tagName = source.substring(tagStart+2,end); - var config = parseStack.pop(); - if(end<0){ - - tagName = source.substring(tagStart+2).replace(/[\s<].*/,''); - //console.error('#@@@@@@'+tagName) - errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName); - end = tagStart+1+tagName.length; - }else if(tagName.match(/\s - locator&&position(tagStart); - end = parseInstruction(source,tagStart,domBuilder); - break; - case '!':// start){ - start = end; - }else{ - //TODO: 这里有可能sax回退,有位置错误风险 - appendText(Math.max(tagStart,start)+1); - } - } -} -function copyLocator(f,t){ - t.lineNumber = f.lineNumber; - t.columnNumber = f.columnNumber; - return t; -} - -/** - * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack); - * @return end of the elementStartPart(end of elementEndPart for selfClosed el) - */ -function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){ - var attrName; - var value; - var p = ++start; - var s = S_TAG;//status - while(true){ - var c = source.charAt(p); - switch(c){ - case '=': - if(s === S_ATTR){//attrName - attrName = source.slice(start,p); - s = S_EQ; - }else if(s === S_ATTR_SPACE){ - s = S_EQ; - }else{ - //fatalError: equal must after attrName or space after attrName - throw new Error('attribute equal must after attrName'); - } - break; - case '\'': - case '"': - if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE - ){//equal - if(s === S_ATTR){ - errorHandler.warning('attribute value must after "="') - attrName = source.slice(start,p) - } - start = p+1; - p = source.indexOf(c,start) - if(p>0){ - value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); - el.add(attrName,value,start-1); - s = S_ATTR_END; - }else{ - //fatalError: no end quot match - throw new Error('attribute value no end \''+c+'\' match'); - } - }else if(s == S_ATTR_NOQUOT_VALUE){ - value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); - //console.log(attrName,value,start,p) - el.add(attrName,value,start); - //console.dir(el) - errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!'); - start = p+1; - s = S_ATTR_END - }else{ - //fatalError: no equal before - throw new Error('attribute value must after "="'); - } - break; - case '/': - switch(s){ - case S_TAG: - el.setTagName(source.slice(start,p)); - case S_ATTR_END: - case S_TAG_SPACE: - case S_TAG_CLOSE: - s =S_TAG_CLOSE; - el.closed = true; - case S_ATTR_NOQUOT_VALUE: - case S_ATTR: - case S_ATTR_SPACE: - break; - //case S_EQ: - default: - throw new Error("attribute invalid close char('/')") - } - break; - case ''://end document - //throw new Error('unexpected end of input') - errorHandler.error('unexpected end of input'); - if(s == S_TAG){ - el.setTagName(source.slice(start,p)); - } - return p; - case '>': - switch(s){ - case S_TAG: - el.setTagName(source.slice(start,p)); - case S_ATTR_END: - case S_TAG_SPACE: - case S_TAG_CLOSE: - break;//normal - case S_ATTR_NOQUOT_VALUE://Compatible state - case S_ATTR: - value = source.slice(start,p); - if(value.slice(-1) === '/'){ - el.closed = true; - value = value.slice(0,-1) - } - case S_ATTR_SPACE: - if(s === S_ATTR_SPACE){ - value = attrName; - } - if(s == S_ATTR_NOQUOT_VALUE){ - errorHandler.warning('attribute "'+value+'" missed quot(")!!'); - el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start) - }else{ - if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){ - errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!') - } - el.add(value,value,start) - } - break; - case S_EQ: - throw new Error('attribute value missed!!'); - } -// console.log(tagName,tagNamePattern,tagNamePattern.test(tagName)) - return p; - /*xml space '\x20' | #x9 | #xD | #xA; */ - case '\u0080': - c = ' '; - default: - if(c<= ' '){//space - switch(s){ - case S_TAG: - el.setTagName(source.slice(start,p));//tagName - s = S_TAG_SPACE; - break; - case S_ATTR: - attrName = source.slice(start,p) - s = S_ATTR_SPACE; - break; - case S_ATTR_NOQUOT_VALUE: - var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); - errorHandler.warning('attribute "'+value+'" missed quot(")!!'); - el.add(attrName,value,start) - case S_ATTR_END: - s = S_TAG_SPACE; - break; - //case S_TAG_SPACE: - //case S_EQ: - //case S_ATTR_SPACE: - // void();break; - //case S_TAG_CLOSE: - //ignore warning - } - }else{//not space -//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE -//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE - switch(s){ - //case S_TAG:void();break; - //case S_ATTR:void();break; - //case S_ATTR_NOQUOT_VALUE:void();break; - case S_ATTR_SPACE: - var tagName = el.tagName; - if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){ - errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!') - } - el.add(attrName,attrName,start); - start = p; - s = S_ATTR; - break; - case S_ATTR_END: - errorHandler.warning('attribute space is required"'+attrName+'"!!') - case S_TAG_SPACE: - s = S_ATTR; - start = p; - break; - case S_EQ: - s = S_ATTR_NOQUOT_VALUE; - start = p; - break; - case S_TAG_CLOSE: - throw new Error("elements closed character '/' and '>' must be connected to"); - } - } - }//end outer switch - //console.log('p++',p) - p++; - } -} -/** - * @return true if has new namespace define - */ -function appendElement(el,domBuilder,currentNSMap){ - var tagName = el.tagName; - var localNSMap = null; - //var currentNSMap = parseStack[parseStack.length-1].currentNSMap; - var i = el.length; - while(i--){ - var a = el[i]; - var qName = a.qName; - var value = a.value; - var nsp = qName.indexOf(':'); - if(nsp>0){ - var prefix = a.prefix = qName.slice(0,nsp); - var localName = qName.slice(nsp+1); - var nsPrefix = prefix === 'xmlns' && localName - }else{ - localName = qName; - prefix = null - nsPrefix = qName === 'xmlns' && '' - } - //can not set prefix,because prefix !== '' - a.localName = localName ; - //prefix == null for no ns prefix attribute - if(nsPrefix !== false){//hack!! - if(localNSMap == null){ - localNSMap = {} - //console.log(currentNSMap,0) - _copy(currentNSMap,currentNSMap={}) - //console.log(currentNSMap,1) - } - currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value; - a.uri = 'http://www.w3.org/2000/xmlns/' - domBuilder.startPrefixMapping(nsPrefix, value) - } - } - var i = el.length; - while(i--){ - a = el[i]; - var prefix = a.prefix; - if(prefix){//no prefix attribute has no namespace - if(prefix === 'xml'){ - a.uri = 'http://www.w3.org/XML/1998/namespace'; - }if(prefix !== 'xmlns'){ - a.uri = currentNSMap[prefix || ''] - - //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)} - } - } - } - var nsp = tagName.indexOf(':'); - if(nsp>0){ - prefix = el.prefix = tagName.slice(0,nsp); - localName = el.localName = tagName.slice(nsp+1); - }else{ - prefix = null;//important!! - localName = el.localName = tagName; - } - //no prefix element has default namespace - var ns = el.uri = currentNSMap[prefix || '']; - domBuilder.startElement(ns,localName,tagName,el); - //endPrefixMapping and startPrefixMapping have not any help for dom builder - //localNSMap = null - if(el.closed){ - domBuilder.endElement(ns,localName,tagName); - if(localNSMap){ - for(prefix in localNSMap){ - domBuilder.endPrefixMapping(prefix) - } - } - }else{ - el.currentNSMap = currentNSMap; - el.localNSMap = localNSMap; - //parseStack.push(el); - return true; - } -} -function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){ - if(/^(?:script|textarea)$/i.test(tagName)){ - var elEndStart = source.indexOf('',elStartEnd); - var text = source.substring(elStartEnd+1,elEndStart); - if(/[&<]/.test(text)){ - if(/^script$/i.test(tagName)){ - //if(!/\]\]>/.test(text)){ - //lexHandler.startCDATA(); - domBuilder.characters(text,0,text.length); - //lexHandler.endCDATA(); - return elEndStart; - //} - }//}else{//text area - text = text.replace(/&#?\w+;/g,entityReplacer); - domBuilder.characters(text,0,text.length); - return elEndStart; - //} - - } - } - return elStartEnd+1; -} -function fixSelfClosed(source,elStartEnd,tagName,closeMap){ - //if(tagName in closeMap){ - var pos = closeMap[tagName]; - if(pos == null){ - //console.log(tagName) - pos = source.lastIndexOf('') - if(pos',start+4); - //append comment source.substring(4,end)///g, ''); //Remove comments - - var xmlObj = new xmlNode('!xml'); - var currentNode = xmlObj; - regx = regx.replace(/\[\\w/g, '[' + options.localeRange + '\\w'); - var tagsRegx = new RegExp(regx, 'g'); - var tag = tagsRegx.exec(xmlData); - var nextTag = tagsRegx.exec(xmlData); - - while (tag) { - var tagType = checkForTagType(tag); - - if (tagType === TagType.CLOSING) { - //add parsed data to parent node - if (currentNode.parent && tag[14]) { - currentNode.parent.val = util.getValue(currentNode.parent.val) + '' + processTagValue(tag, options, currentNode.parent.tagname); - } - - if (options.stopNodes.length && options.stopNodes.includes(currentNode.tagname)) { - currentNode.child = []; - - if (currentNode.attrsMap == undefined) { - currentNode.attrsMap = {}; - } - - currentNode.val = xmlData.substr(currentNode.startIndex + 1, tag.index - currentNode.startIndex - 1); - } - - currentNode = currentNode.parent; - } else if (tagType === TagType.CDATA) { - if (options.cdataTagName) { - //add cdata node - var childNode = new xmlNode(options.cdataTagName, currentNode, tag[3]); - childNode.attrsMap = buildAttributesMap(tag[8], options); - currentNode.addChild(childNode); //for backtracking - - currentNode.val = util.getValue(currentNode.val) + options.cdataPositionChar; //add rest value to parent node - - if (tag[14]) { - currentNode.val += processTagValue(tag, options); - } - } else { - currentNode.val = (currentNode.val || '') + (tag[3] || '') + processTagValue(tag, options); - } - } else if (tagType === TagType.SELF) { - if (currentNode && tag[14]) { - currentNode.val = util.getValue(currentNode.val) + '' + processTagValue(tag, options); - } - - var _childNode = new xmlNode(options.ignoreNameSpace ? tag[7] : tag[5], currentNode, ''); - - if (tag[8] && tag[8].length > 0) { - tag[8] = tag[8].substr(0, tag[8].length - 1); - } - - _childNode.attrsMap = buildAttributesMap(tag[8], options); - currentNode.addChild(_childNode); - } else { - //TagType.OPENING - var _childNode2 = new xmlNode(options.ignoreNameSpace ? tag[7] : tag[5], currentNode, processTagValue(tag, options)); - - if (options.stopNodes.length && options.stopNodes.includes(_childNode2.tagname)) { - _childNode2.startIndex = tag.index + tag[1].length; - } - - _childNode2.attrsMap = buildAttributesMap(tag[8], options); - currentNode.addChild(_childNode2); - currentNode = _childNode2; - } - - tag = nextTag; - nextTag = tagsRegx.exec(xmlData); - } - - return xmlObj; -}; - -function processTagValue(parsedTags, options, parentTagName) { - var tagName = parsedTags[7] || parentTagName; - var val = parsedTags[14]; - - if (val) { - if (options.trimValues) { - val = val.trim(); - } - - val = options.tagValueProcessor(val, tagName); - val = parseValue(val, options.parseNodeValue, options.parseTrueNumberOnly); - } - - return val; -} - -function checkForTagType(match) { - if (match[4] === ']]>') { - return TagType.CDATA; - } else if (match[10] === '/') { - return TagType.CLOSING; - } else if (typeof match[8] !== 'undefined' && match[8].substr(match[8].length - 1) === '/') { - return TagType.SELF; - } else { - return TagType.OPENING; - } -} - -function resolveNameSpace(tagname, options) { - if (options.ignoreNameSpace) { - var tags = tagname.split(':'); - var prefix = tagname.charAt(0) === '/' ? '/' : ''; - - if (tags[0] === 'xmlns') { - return ''; - } - - if (tags.length === 2) { - tagname = prefix + tags[1]; - } - } - - return tagname; -} - -function parseValue(val, shouldParse, parseTrueNumberOnly) { - if (shouldParse && typeof val === 'string') { - var parsed; - - if (val.trim() === '' || isNaN(val)) { - parsed = val === 'true' ? true : val === 'false' ? false : val; - } else { - if (val.indexOf('0x') !== -1) { - //support hexa decimal - parsed = Number.parseInt(val, 16); - } else if (val.indexOf('.') !== -1) { - parsed = Number.parseFloat(val); - } else { - parsed = Number.parseInt(val, 10); - } - - if (parseTrueNumberOnly) { - parsed = String(parsed) === val ? parsed : val; - } - } - - return parsed; - } else { - if (util.isExist(val)) { - return val; - } else { - return ''; - } - } -} //TODO: change regex to capture NS -//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm"); - - -var attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])(.*?)\\3)?', 'g'); - -function buildAttributesMap(attrStr, options) { - if (!options.ignoreAttributes && typeof attrStr === 'string') { - attrStr = attrStr.replace(/\r?\n/g, ' '); //attrStr = attrStr || attrStr.trim(); - - var matches = util.getAllMatches(attrStr, attrsRegx); - var len = matches.length; //don't make it inline - - var attrs = {}; - - for (var i = 0; i < len; i++) { - var attrName = resolveNameSpace(matches[i][1], options); - - if (attrName.length) { - if (matches[i][4] !== undefined) { - if (options.trimValues) { - matches[i][4] = matches[i][4].trim(); - } - - matches[i][4] = options.attrValueProcessor(matches[i][4], attrName); - attrs[options.attributeNamePrefix + attrName] = parseValue(matches[i][4], options.parseAttributeValue, options.parseTrueNumberOnly); - } else if (options.allowBooleanAttributes) { - attrs[options.attributeNamePrefix + attrName] = true; - } - } - } - - if (!Object.keys(attrs).length) { - return; - } - - if (options.attrNodeName) { - var attrCollection = {}; - attrCollection[options.attrNodeName] = attrs; - return attrCollection; - } - - return attrs; - } -} - -exports.getTraversalObj = getTraversalObj; - -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -module.exports = function (tagname, parent, val) { - this.tagname = tagname; - this.parent = parent; - this.child = {}; //child tags - - this.attrsMap = {}; //attributes map - - this.children = []; - this.val = val; //text only - - this.addChild = function (child) { - this.children.push(child); - - if (Array.isArray(this.child[child.tagname])) { - //already presents - this.child[child.tagname].push(child); - } else { - this.child[child.tagname] = [child]; - } - }; -}; - -/***/ }), -/* 13 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var util = __webpack_require__(10); - -var defaultOptions = { - allowBooleanAttributes: false, - //A tag can have attributes without any value - localeRange: 'a-zA-Z' -}; -var props = ['allowBooleanAttributes', 'localeRange']; //const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g"); - -exports.validate = function (xmlData, options) { - options = util.buildOptions(options, defaultOptions, props); //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line - //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag - //xmlData = xmlData.replace(/()/g,"");//Remove DOCTYPE - - var tags = []; - var tagFound = false; - - if (xmlData[0] === "\uFEFF") { - // check for byte order mark (BOM) - xmlData = xmlData.substr(1); - } - - var regxAttrName = new RegExp('^[_w][\\w\\-.:]*$'.replace('_w', '_' + options.localeRange)); - var regxTagName = new RegExp('^([w]|_)[\\w.\\-_:]*'.replace('([w', '([' + options.localeRange)); - - for (var i = 0; i < xmlData.length; i++) { - if (xmlData[i] === '<') { - //starting of tag - //read until you reach to '>' avoiding any '>' in attribute value - i++; - - if (xmlData[i] === '?') { - i = readPI(xmlData, ++i); - - if (i.err) { - return i; - } - } else if (xmlData[i] === '!') { - i = readCommentAndCDATA(xmlData, i); - continue; - } else { - var closingTag = false; - - if (xmlData[i] === '/') { - //closing tag - closingTag = true; - i++; - } //read tagname - - - var tagName = ''; - - for (; i < xmlData.length && xmlData[i] !== '>' && xmlData[i] !== ' ' && xmlData[i] !== '\t' && xmlData[i] !== '\n' && xmlData[i] !== '\r'; i++) { - tagName += xmlData[i]; - } - - tagName = tagName.trim(); //console.log(tagName); - - if (tagName[tagName.length - 1] === '/') { - //self closing tag without attributes - tagName = tagName.substring(0, tagName.length - 1); - continue; - } - - if (!validateTagName(tagName, regxTagName)) { - return { - err: { - code: 'InvalidTag', - msg: 'Tag ' + tagName + ' is an invalid name.' - } - }; - } - - var result = readAttributeStr(xmlData, i); - - if (result === false) { - return { - err: { - code: 'InvalidAttr', - msg: 'Attributes for "' + tagName + '" have open quote.' - } - }; - } - - var attrStr = result.value; - i = result.index; - - if (attrStr[attrStr.length - 1] === '/') { - //self closing tag - attrStr = attrStr.substring(0, attrStr.length - 1); - var isValid = validateAttributeString(attrStr, options, regxAttrName); - - if (isValid === true) { - tagFound = true; //continue; //text may presents after self closing tag - } else { - return isValid; - } - } else if (closingTag) { - if (!result.tagClosed) { - return { - err: { - code: 'InvalidTag', - msg: 'closing tag "' + tagName + "\" don't have proper closing." - } - }; - } else if (attrStr.trim().length > 0) { - return { - err: { - code: 'InvalidTag', - msg: 'closing tag "' + tagName + "\" can't have attributes or invalid starting." - } - }; - } else { - var otg = tags.pop(); - - if (tagName !== otg) { - return { - err: { - code: 'InvalidTag', - msg: 'closing tag ' + otg + ' is expected inplace of ' + tagName + '.' - } - }; - } - } - } else { - var _isValid = validateAttributeString(attrStr, options, regxAttrName); - - if (_isValid !== true) { - return _isValid; - } - - tags.push(tagName); - tagFound = true; - } //skip tag text value - //It may include comments and CDATA value - - - for (i++; i < xmlData.length; i++) { - if (xmlData[i] === '<') { - if (xmlData[i + 1] === '!') { - //comment or CADATA - i++; - i = readCommentAndCDATA(xmlData, i); - continue; - } else { - break; - } - } - } //end of reading tag text value - - - if (xmlData[i] === '<') { - i--; - } - } - } else { - if (xmlData[i] === ' ' || xmlData[i] === '\t' || xmlData[i] === '\n' || xmlData[i] === '\r') { - continue; - } - - return { - err: { - code: 'InvalidChar', - msg: 'char ' + xmlData[i] + ' is not expected .' - } - }; - } - } - - if (!tagFound) { - return { - err: { - code: 'InvalidXml', - msg: 'Start tag expected.' - } - }; - } else if (tags.length > 0) { - return { - err: { - code: 'InvalidXml', - msg: 'Invalid ' + JSON.stringify(tags, null, 4).replace(/\r?\n/g, '') + ' found.' - } - }; - } - - return true; -}; -/** - * Read Processing insstructions and skip - * @param {*} xmlData - * @param {*} i - */ - - -function readPI(xmlData, i) { - var start = i; - - for (; i < xmlData.length; i++) { - if (xmlData[i] == '?' || xmlData[i] == ' ') { - //tagname - var tagname = xmlData.substr(start, i - start); - - if (i > 5 && tagname === 'xml') { - return { - err: { - code: 'InvalidXml', - msg: 'XML declaration allowed only at the start of the document.' - } - }; - } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') { - //check if valid attribut string - i++; - break; - } else { - continue; - } - } - } - - return i; -} - -function readCommentAndCDATA(xmlData, i) { - if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') { - //comment - for (i += 3; i < xmlData.length; i++) { - if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') { - i += 2; - break; - } - } - } else if (xmlData.length > i + 8 && xmlData[i + 1] === 'D' && xmlData[i + 2] === 'O' && xmlData[i + 3] === 'C' && xmlData[i + 4] === 'T' && xmlData[i + 5] === 'Y' && xmlData[i + 6] === 'P' && xmlData[i + 7] === 'E') { - var angleBracketsCount = 1; - - for (i += 8; i < xmlData.length; i++) { - if (xmlData[i] === '<') { - angleBracketsCount++; - } else if (xmlData[i] === '>') { - angleBracketsCount--; - - if (angleBracketsCount === 0) { - break; - } - } - } - } else if (xmlData.length > i + 9 && xmlData[i + 1] === '[' && xmlData[i + 2] === 'C' && xmlData[i + 3] === 'D' && xmlData[i + 4] === 'A' && xmlData[i + 5] === 'T' && xmlData[i + 6] === 'A' && xmlData[i + 7] === '[') { - for (i += 8; i < xmlData.length; i++) { - if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') { - i += 2; - break; - } - } - } - - return i; -} - -var doubleQuote = '"'; -var singleQuote = "'"; -/** - * Keep reading xmlData until '<' is found outside the attribute value. - * @param {string} xmlData - * @param {number} i - */ - -function readAttributeStr(xmlData, i) { - var attrStr = ''; - var startChar = ''; - var tagClosed = false; - - for (; i < xmlData.length; i++) { - if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) { - if (startChar === '') { - startChar = xmlData[i]; - } else if (startChar !== xmlData[i]) { - //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa - continue; - } else { - startChar = ''; - } - } else if (xmlData[i] === '>') { - if (startChar === '') { - tagClosed = true; - break; - } - } - - attrStr += xmlData[i]; - } - - if (startChar !== '') { - return false; - } - - return { - value: attrStr, - index: i, - tagClosed: tagClosed - }; -} -/** - * Select all the attributes whether valid or invalid. - */ - - -var validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g'); //attr, ="sd", a="amit's", a="sd"b="saf", ab cd="" - -function validateAttributeString(attrStr, options, regxAttrName) { - //console.log("start:"+attrStr+":end"); - //if(attrStr.trim().length === 0) return true; //empty string - var matches = util.getAllMatches(attrStr, validAttrStrRegxp); - var attrNames = {}; - - for (var i = 0; i < matches.length; i++) { - //console.log(matches[i]); - if (matches[i][1].length === 0) { - //nospace before attribute name: a="sd"b="saf" - return { - err: { - code: 'InvalidAttr', - msg: 'attribute ' + matches[i][2] + ' has no space in starting.' - } - }; - } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) { - //independent attribute: ab - return { - err: { - code: 'InvalidAttr', - msg: 'boolean attribute ' + matches[i][2] + ' is not allowed.' - } - }; - } - /* else if(matches[i][6] === undefined){//attribute without value: ab= - return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}}; - } */ - - - var attrName = matches[i][2]; - - if (!validateAttrName(attrName, regxAttrName)) { - return { - err: { - code: 'InvalidAttr', - msg: 'attribute ' + attrName + ' is an invalid name.' - } - }; - } - /*if (!attrNames.hasOwnProperty(attrName)) {*/ - - - if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) { - //check for duplicate attribute. - attrNames[attrName] = 1; - } else { - return { - err: { - code: 'InvalidAttr', - msg: 'attribute ' + attrName + ' is repeated.' - } - }; - } - } - - return true; -} // const validAttrRegxp = /^[_a-zA-Z][\w\-.:]*$/; - - -function validateAttrName(attrName, regxAttrName) { - // const validAttrRegxp = new RegExp(regxAttrName); - return util.doesMatch(attrName, regxAttrName); -} //const startsWithXML = new RegExp("^[Xx][Mm][Ll]"); -// startsWith = /^([a-zA-Z]|_)[\w.\-_:]*/; - - -function validateTagName(tagname, regxTagName) { - /*if(util.doesMatch(tagname,startsWithXML)) return false; - else*/ - return !util.doesNotMatch(tagname, regxTagName); -} - -/***/ }), -/* 14 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BitMapFont; }); -/* harmony import */ var _imageManager__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15); -/* harmony import */ var _pool__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - - - -var bitMapPool = new _pool__WEBPACK_IMPORTED_MODULE_1__["default"]('bitMapPool'); - -var Emitter = __webpack_require__(4); -/** - * http://www.angelcode.com/products/bmfont/doc/file_format.html - */ - - -var BitMapFont = /*#__PURE__*/function () { - function BitMapFont(name, src, config) { - var _this = this; - - _classCallCheck(this, BitMapFont); - - var cache = bitMapPool.get(name); - - if (cache) { - return cache; - } - - this.config = config; - this.chars = this.parseConfig(config); - this.ready = false; - this.event = new Emitter(); - this.texture = _imageManager__WEBPACK_IMPORTED_MODULE_0__["default"].loadImage(src, function (texture, fromCache) { - if (fromCache) { - _this.texture = texture; - } - - _this.ready = true; - - _this.event.emit('text__load__done'); - }); - bitMapPool.set(name, this); - } - - _createClass(BitMapFont, [{ - key: "parseConfig", - value: function parseConfig(fntText) { - fntText = fntText.split("\r\n").join("\n"); - var lines = fntText.split("\n"); - var charsCount = this.getConfigByKey(lines[3], "count"); - this.lineHeight = this.getConfigByKey(lines[1], 'lineHeight'); - this.fontSize = this.getConfigByKey(lines[0], 'size'); - var chars = {}; - - for (var i = 4; i < 4 + charsCount; i++) { - var charText = lines[i]; - var letter = String.fromCharCode(this.getConfigByKey(charText, "id")); - var c = {}; - chars[letter] = c; - c["x"] = this.getConfigByKey(charText, "x"); - c["y"] = this.getConfigByKey(charText, "y"); - c["w"] = this.getConfigByKey(charText, "width"); - c["h"] = this.getConfigByKey(charText, "height"); - c["offX"] = this.getConfigByKey(charText, "xoffset"); - c["offY"] = this.getConfigByKey(charText, "yoffset"); - c["xadvance"] = this.getConfigByKey(charText, "xadvance"); - } - - return chars; - } - }, { - key: "getConfigByKey", - value: function getConfigByKey(configText, key) { - var itemConfigTextList = configText.split(" "); - - for (var i = 0, length = itemConfigTextList.length; i < length; i++) { - var itemConfigText = itemConfigTextList[i]; - - if (key === itemConfigText.substring(0, key.length)) { - var value = itemConfigText.substring(key.length + 1); - return parseInt(value); - } - } - - return 0; - } - }]); - - return BitMapFont; -}(); - - - -/***/ }), -/* 15 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _pool__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); -/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - - - -var imgPool = new _pool__WEBPACK_IMPORTED_MODULE_0__["default"]('imgPool'); - -var ImageManager = /*#__PURE__*/function () { - function ImageManager() { - _classCallCheck(this, ImageManager); - } - - _createClass(ImageManager, [{ - key: "getRes", - value: function getRes(src) { - return imgPool.get(src); - } - }, { - key: "loadImage", - value: function loadImage(src) { - var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _util__WEBPACK_IMPORTED_MODULE_1__["none"]; - var img = null; - var cache = this.getRes(src); - - if (!src) { - return img; - } // 图片已经被加载过,直接返回图片并且执行回调 - - - if (cache && cache.loadDone) { - img = cache; - callback(img, true); - } else if (cache && !cache.loadDone) { - // 图片正在加载过程中,返回图片并且等待图片加载完成执行回调 - img = cache; - cache.onloadcbks.push(callback); - } else { - // 创建图片,将回调函数推入回调函数栈 - img = Object(_util__WEBPACK_IMPORTED_MODULE_1__["createImage"])(); - img.onloadcbks = [callback]; - imgPool.set(src, img); - - img.onload = function () { - img.onloadcbks.forEach(function (fn) { - return fn(img, false); - }); - img.onloadcbks = []; - img.loadDone = true; - }; - - img.onerror = function (e) { - console.log('img load error', e); - }; - - img.src = src; - } - - return img; - } - }]); - - return ImageManager; -}(); - -/* harmony default export */ __webpack_exports__["default"] = (new ImageManager()); - -/***/ }), -/* 16 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _view_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "View", function() { return _view_js__WEBPACK_IMPORTED_MODULE_0__["default"]; }); - -/* harmony import */ var _image_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(18); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Image", function() { return _image_js__WEBPACK_IMPORTED_MODULE_1__["default"]; }); - -/* harmony import */ var _text_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(19); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Text", function() { return _text_js__WEBPACK_IMPORTED_MODULE_2__["default"]; }); - -/* harmony import */ var _scrollview_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(20); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScrollView", function() { return _scrollview_js__WEBPACK_IMPORTED_MODULE_3__["default"]; }); - -/* harmony import */ var _bitmaptext_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(22); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BitMapText", function() { return _bitmaptext_js__WEBPACK_IMPORTED_MODULE_4__["default"]; }); - - - - - - - - -/***/ }), -/* 17 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return View; }); -/* harmony import */ var _elements_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } - -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } - -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - - - -var View = /*#__PURE__*/function (_Element) { - _inherits(View, _Element); - - var _super = _createSuper(View); - - function View(_ref) { - var _this; - - var _ref$style = _ref.style, - style = _ref$style === void 0 ? {} : _ref$style, - _ref$props = _ref.props, - props = _ref$props === void 0 ? {} : _ref$props, - _ref$idName = _ref.idName, - idName = _ref$idName === void 0 ? '' : _ref$idName, - _ref$className = _ref.className, - className = _ref$className === void 0 ? '' : _ref$className; - - _classCallCheck(this, View); - - _this = _super.call(this, { - props: props, - idName: idName, - className: className, - style: style - }); - _this.type = 'View'; - _this.ctx = null; - _this.renderBoxes = []; - return _this; - } - - _createClass(View, [{ - key: "destroySelf", - value: function destroySelf() { - this.isDestroyed = true; - this.children = null; - this.root = null; - } // 有些节点仅仅作为容器,实际上不需要任何渲染逻辑,这里加个判断可以提高性能 - - }, { - key: "checkNeedRender", - value: function checkNeedRender() { - var style = this.style || {}; - var borderColor = style.borderColor; - return !!(style.backgroundColor || style.borderWidth && borderColor || style.borderTopWidth && (borderColor || style.borderTopColor) || style.borderBottomWidth && (borderColor || style.borderBottomColor) || style.borderLeftWidth && (borderColor || style.borderLeftColor) || style.borderRightWidth && (borderColor || style.borderRightColor)); - } - }, { - key: "render", - value: function render(ctx, layoutBox) { - var style = this.style || {}; - var box = layoutBox || this.layoutBox; - ctx.save(); - var borderWidth = style.borderWidth || 0; - var drawX = box.absoluteX; - var drawY = box.absoluteY; - var borderLeftWidth = style.borderLeftWidth || borderWidth; - var borderRightWidth = style.borderRightWidth || borderWidth; - var borderTopWidth = style.borderTopWidth || borderWidth; - var borderBottomWidth = style.borderBottomWidth || borderWidth; - this.renderBorder(ctx, layoutBox); - - if (style.backgroundColor) { - ctx.fillStyle = style.backgroundColor; - ctx.fillRect(drawX + borderLeftWidth, drawY + borderRightWidth, box.width - (borderLeftWidth + borderRightWidth), box.height - (borderTopWidth + borderBottomWidth)); - } - - ctx.restore(); - } - }, { - key: "insert", - value: function insert(ctx, box) { - this.ctx = ctx; - - if (!box) { - box = this.layoutBox; - } - - this.renderBoxes.push({ - ctx: ctx, - box: box - }); - this.render(ctx, box); - } - }, { - key: "repaint", - value: function repaint() { - var _this2 = this; - - this.renderBoxes.forEach(function (item) { - _this2.render(item.ctx, item.box); - }); - } - }]); - - return View; -}(_elements_js__WEBPACK_IMPORTED_MODULE_0__["default"]); - - - -/***/ }), -/* 18 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Image; }); -/* harmony import */ var _elements_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var _common_imageManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(15); -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } - -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } - -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - - - - -var Image = /*#__PURE__*/function (_Element) { - _inherits(Image, _Element); - - var _super = _createSuper(Image); - - function Image(opts) { - var _this; - - _classCallCheck(this, Image); - - var _opts$style = opts.style, - style = _opts$style === void 0 ? {} : _opts$style, - _opts$props = opts.props, - props = _opts$props === void 0 ? {} : _opts$props, - _opts$idName = opts.idName, - idName = _opts$idName === void 0 ? '' : _opts$idName, - _opts$className = opts.className, - className = _opts$className === void 0 ? '' : _opts$className, - _opts$src = opts.src, - src = _opts$src === void 0 ? '' : _opts$src; - _this = _super.call(this, { - props: props, - idName: idName, - className: className, - style: style - }); - _this.imgsrc = src; - Object.defineProperty(_assertThisInitialized(_this), "src", { - get: function get() { - return this.imgsrc; - }, - set: function set(newValue) { - var _this2 = this; - - if (newValue !== this.imgsrc) { - this.imgsrc = newValue; - _common_imageManager__WEBPACK_IMPORTED_MODULE_1__["default"].loadImage(this.src, function (img) { - _this2.img = img; - /*this.repaint();*/ - - _this2.emit('repaint'); - }); - } - }, - enumerable: true, - configurable: true - }); - _this.type = 'Image'; - _this.renderBoxes = []; - return _this; - } - - _createClass(Image, [{ - key: "repaint", - value: function repaint() { - var _this3 = this; - - this.renderBoxes.forEach(function (item) { - _this3.renderImg(item.ctx, item.box, false); - }); - } // 子类填充实现 - - }, { - key: "destroySelf", - value: function destroySelf() { - this.isDestroyed = true; - this.img = null; - delete this.src; - this.root = null; - } - }, { - key: "renderImg", - value: function renderImg(ctx, layoutBox) { - var needEmitEvent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; - - if (!this.img) { - return; - } - - var style = this.style || {}; - var box = layoutBox || this.layoutBox; - ctx.save(); - - if (style.borderColor) { - ctx.strokeStyle = style.borderColor; - } - - ctx.lineWidth = style.borderWidth || 0; - var drawX = box.absoluteX; - var drawY = box.absoluteY; - this.renderBorder(ctx, layoutBox); - ctx.drawImage(this.img, drawX, drawY, box.width, box.height); - ctx.restore(); - } - }, { - key: "insert", - value: function insert(ctx, box) { - var _this4 = this; - - this.renderBoxes.push({ - ctx: ctx, - box: box - }); - this.img = _common_imageManager__WEBPACK_IMPORTED_MODULE_1__["default"].loadImage(this.src, function (img, fromCache) { - // 来自缓存的,还没返回img就会执行回调函数 - if (fromCache) { - _this4.img = img; - - _this4.renderImg(ctx, box, false); - } else { - // 当图片加载完成,实例可能已经被销毁了 - if (_this4.img) { - var eventName = _this4.isScrollViewChild ? 'image__render__done' : 'one__image__render__done'; - - _this4.EE.emit(eventName, _this4); - } - } - }); - } - }, { - key: "isScrollViewChild", - get: function get() { - var flag = false; - var parent = this.parent; - - while (parent && !flag) { - if (parent.type === 'ScrollView') { - flag = true; - } else { - parent = parent.parent; - } - } - - return flag; - } - }]); - - return Image; -}(_elements_js__WEBPACK_IMPORTED_MODULE_0__["default"]); - - - -/***/ }), -/* 19 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Text; }); -/* harmony import */ var _elements_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var _common_util_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7); -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } - -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } - -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - - - -var DEFAULT_FONT_FAMILY = 'PingFangSC-Regular, sans-serif'; -var context = null; - -var getContext = function getContext() { - if (context) { - return context; - } - - var canvas = Object(_common_util_js__WEBPACK_IMPORTED_MODULE_1__["createCanvas"])(); - canvas.width = 1; - canvas.height = 1; - context = canvas.getContext('2d'); - return context; -}; - -function getTextWidth(style, value) { - var context = getContext(); - context.font = "".concat(style.fontWeight || 'normal', " ").concat(style.fontSize || 12, "px ").concat(style.fontFamily || DEFAULT_FONT_FAMILY); - return context.measureText(value).width || 0; -} - -function getTextWidthWithoutSetFont(value) { - return getContext().measureText(value).width || 0; -} - -function parseText(style, value) { - value = String(value); - var maxWidth = style.width; - var wordWidth = getTextWidth(style, value); // 对文字溢出的处理,默认用... - - var textOverflow = style.textOverflow || 'ellipsis'; // 文字最大长度不超限制 - - if (wordWidth <= maxWidth) { - return value; - } // 对于用点点点处理的情况,先将最大宽度减去...的宽度 - - - if (textOverflow === 'ellipsis') { - maxWidth -= getTextWidthWithoutSetFont('...'); - } - - var length = value.length - 1; - var str = value.substring(0, length); - - while (getTextWidthWithoutSetFont(str) > maxWidth && length > 0) { - length--; - str = value.substring(0, length); - } - - return length && textOverflow === 'ellipsis' ? str + '...' : str; -} - -var Text = /*#__PURE__*/function (_Element) { - _inherits(Text, _Element); - - var _super = _createSuper(Text); - - function Text(_ref) { - var _this; - - var _ref$style = _ref.style, - style = _ref$style === void 0 ? {} : _ref$style, - _ref$props = _ref.props, - props = _ref$props === void 0 ? {} : _ref$props, - _ref$idName = _ref.idName, - idName = _ref$idName === void 0 ? '' : _ref$idName, - _ref$className = _ref.className, - className = _ref$className === void 0 ? '' : _ref$className, - _ref$value = _ref.value, - value = _ref$value === void 0 ? '' : _ref$value; - - _classCallCheck(this, Text); - - // 没有设置宽度的时候通过canvas计算出文字宽度 - if (style.width === undefined) { - style.width = getTextWidth(style, value); - } else if (style.textOverflow === 'ellipsis') { - value = parseText(style, value); - } - - _this = _super.call(this, { - props: props, - idName: idName, - className: className, - style: style - }); - _this.type = 'Text'; - _this.ctx = null; - _this.valuesrc = value; - _this.renderBoxes = []; - Object.defineProperty(_assertThisInitialized(_this), "value", { - get: function get() { - return this.valuesrc; - }, - set: function set(newValue) { - if (newValue !== this.valuesrc) { - this.valuesrc = newValue; - this.emit('repaint'); - } - }, - enumerable: true, - configurable: true - }); - return _this; - } - - _createClass(Text, [{ - key: "toCanvasData", - value: function toCanvasData() { - var style = this.style || {}; - this.fontSize = style.fontSize || 12; - this.textBaseline = 'top'; - this.font = "".concat(style.fontWeight || '', " ").concat(style.fontSize || 12, "px ").concat(DEFAULT_FONT_FAMILY); - this.textAlign = style.textAlign || 'left'; - this.fillStyle = style.color || '#000'; - } - }, { - key: "insert", - value: function insert(ctx, box) { - this.renderBoxes.push({ - ctx: ctx, - box: box - }); - this.render(ctx, box); - } - }, { - key: "repaint", - value: function repaint() { - var _this2 = this; - - this.renderBoxes.forEach(function (item) { - _this2.render(item.ctx, item.box); - }); - } - }, { - key: "destroySelf", - value: function destroySelf() { - this.root = null; - } - }, { - key: "render", - value: function render(ctx, layoutBox) { - this.toCanvasData(); - ctx.save(); - var box = layoutBox || this.layoutBox; - var style = this.style; - ctx.textBaseline = this.textBaseline; - ctx.font = this.font; - ctx.textAlign = this.textAlign; - var drawX = box.absoluteX; - var drawY = box.absoluteY; - this.renderBorder(ctx, layoutBox); - - if (style.backgroundColor) { - ctx.fillStyle = style.backgroundColor; - ctx.fillRect(drawX, drawY, box.width, box.height); - } - - ctx.fillStyle = this.fillStyle; - - if (this.textAlign === 'center') { - drawX += box.width / 2; - } else if (this.textAlign === 'right') { - drawX += box.width; - } - - if (style.lineHeight) { - ctx.textBaseline = 'middle'; - drawY += style.lineHeight / 2; - } - - ctx.fillText(this.value, drawX, drawY); - ctx.restore(); - } - }]); - - return Text; -}(_elements_js__WEBPACK_IMPORTED_MODULE_0__["default"]); - - - -/***/ }), -/* 20 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ScrollView; }); -/* harmony import */ var _view_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); -/* harmony import */ var _common_pool_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); -/* harmony import */ var _common_touch_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(21); -/* harmony import */ var _common_util_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7); -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } - -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } - -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - - - - - -var id = 0; -var canvasPool = new _common_pool_js__WEBPACK_IMPORTED_MODULE_1__["default"]('canvasPool'); - -var ScrollView = /*#__PURE__*/function (_View) { - _inherits(ScrollView, _View); - - var _super = _createSuper(ScrollView); - - function ScrollView(_ref) { - var _this; - - var _ref$style = _ref.style, - style = _ref$style === void 0 ? {} : _ref$style, - _ref$props = _ref.props, - props = _ref$props === void 0 ? {} : _ref$props, - _ref$name = _ref.name, - name = _ref$name === void 0 ? '' : _ref$name; - - _classCallCheck(this, ScrollView); - - _this = _super.call(this, { - props: props, - name: name, - style: style - }); - _this.type = 'ScrollView'; // 当前列表滚动的值 - - _this.top = 0; // 滚动处理器 - - _this.touch = new _common_touch_js__WEBPACK_IMPORTED_MODULE_2__["default"](); // canvas高度不能过高,在小游戏里面,对canvas尺寸是有限制的 - - _this.pageHeight = 2000; // 根据列表总高度和单页高度计算的分页数量 - - _this.pageCount = 1; - _this.canvasMap = {}; // 图片加载完成之后会触发scrollView的重绘函数,当图片过多的时候用节流提升性能 - - _this.throttleRepaint = Object(_common_util_js__WEBPACK_IMPORTED_MODULE_3__["throttle"])(_this.clipRepaint, 16, _assertThisInitialized(_this)); - _this.throttleImageLoadDone = Object(_common_util_js__WEBPACK_IMPORTED_MODULE_3__["throttle"])(_this.childImageLoadDoneCbk, 32, _assertThisInitialized(_this)); - _this.renderTimers = []; - _this.requestID = null; - return _this; - } - /** - * 获取滚动列表内所有元素的高度和 - * 这里不能简单将所有子元素的高度累加,因为每个元素之间可能是有空隙的 - */ - - - _createClass(ScrollView, [{ - key: "repaint", - value: function repaint() { - var _this2 = this; - - this.clear(); - this.renderBoxes.forEach(function (item) { - _this2.render(item.ctx, item.box); - }); - } - /** - * 列表子元素重绘之前先将所有的canvas擦除 - */ - - }, { - key: "clear", - value: function clear() { - var _this3 = this; - - Object.keys(this.canvasMap).forEach(function (key) { - var item = _this3.canvasMap[key]; - item.context && item.context.clearRect(0, 0, item.canvas.width, item.canvas.height); - }); - } // 与主canvas的尺寸保持一致 - - }, { - key: "updateRenderPort", - value: function updateRenderPort(renderport) { - this.renderport = renderport; - } - /** - * 计算分页数据 - * 小游戏的canvas对尺寸有要求,如果如果高度过高,可能出现渲染不出来的情况 - * 因此需要手动分页,列表过长的时候将数据绘制到几个canvas上面,这里预创建几个canvas - */ - - }, { - key: "calPageData", - value: function calPageData() { - this.pageCount = Math.ceil((this.scrollHeight + this.layoutBox.absoluteY) / this.pageHeight); - - for (var i = 0; i < this.pageCount; i++) { - var cache = canvasPool.get(i); - - if (cache) { - cache.context && cache.context.clearRect(0, 0, cache.canvas.width, cache.canvas.height); - cache.elements = []; - this.canvasMap[i] = cache; - } else { - this.canvasMap[i] = { - elements: [] - }; - canvasPool.set(i, this.canvasMap[i]); - } - } - } - }, { - key: "destroySelf", - value: function destroySelf() { - this.touch = null; - this.isDestroyed = true; - this.throttleRepaint = null; - this.renderTimers.forEach(function (timer) { - clearTimeout(timer); - }); - this.root.off('repaint__done'); - this.renderTimers = []; - this.canvasMap = {}; - this.ctx = null; - this.children = null; - this.requestID && cancelAnimationFrame(this.requestID); - this.root = null; - } - /** - * 滚动列表重绘逻辑 - * 将分页canvas按照滚动裁剪绘制到主canvas上面 - */ - - }, { - key: "clipRepaint", - value: function clipRepaint(top) { - var _this4 = this; - - if (this.isDestroyed) { - return; - } - - this.requestID = requestAnimationFrame(function () { - top = -top; - _this4.top = top; - var box = _this4.layoutBox; - var abY = box.absoluteY; - - if (_this4.isDestroyed || _this4.root.state === _common_util_js__WEBPACK_IMPORTED_MODULE_3__["STATE"].CLEAR) { - return; - } // 在主canvas上面将滚动列表区域擦除 - - - _this4.ctx.clearRect(box.absoluteX, abY, box.width, box.height); // 背景填充 - - - _this4.ctx.fillStyle = _this4.parent.style.backgroundColor || '#ffffff'; - - _this4.ctx.fillRect(box.absoluteX, abY, box.width, box.height); - - for (var i = 0; i < _this4.pageCount; i++) { - var canvas = _this4.canvasMap[i].canvas; // 根据滚动值获取裁剪区域 - - var startY = abY + top; - var endY = abY + top + box.height; // 计算在裁剪区域内的canvas - - if (startY < _this4.pageHeight * (i + 1) && endY > _this4.pageHeight * i) { - /** - * 这里不能按照box.width * box.height的区域去裁剪 - * 在浏览器里面正常,但是在小游戏里面会出现诡异的渲染出错,所以裁剪canvas真实有效的区域 - */ - var clipY = abY + top - _this4.pageHeight * i; - var clipH = box.height; - var renderY = abY; - - if (clipY > 0 && _this4.pageHeight - clipY < box.height) { - clipH = _this4.pageHeight - clipY; - } else if (clipY < 0) { - clipH = clipY + box.height; - renderY = renderY - clipY; - clipY = 0; - } - - _this4.ctx.drawImage(canvas, box.absoluteX, clipY, box.width, clipH, box.absoluteX, renderY, box.width, clipH); - } - } - }); - } - }, { - key: "renderChildren", - value: function renderChildren(tree) { - var _this5 = this; - - var children = tree.children; - var height = this.pageHeight; - Object.keys(children).forEach(function (id) { - var child = children[id]; - var originY = child.layoutBox.originalAbsoluteY; - var pageIndex = Math.floor(originY / height); - var nextPage = pageIndex + 1; - child.layoutBox.absoluteY -= _this5.pageHeight * pageIndex; - - if (child.checkNeedRender()) { - _this5.canvasMap[pageIndex].elements.push({ - element: child, - box: child.layoutBox - }); - } // 对于跨界的元素,两边都绘制下 - - - if (originY + child.layoutBox.height > height * nextPage) { - var tmpBox = Object.assign({}, child.layoutBox); - tmpBox.absoluteY = originY - _this5.pageHeight * nextPage; - - if (child.checkNeedRender()) { - _this5.canvasMap[nextPage].elements.push({ - element: child, - box: tmpBox - }); - } - } - - _this5.renderChildren(child); - }); - } - }, { - key: "insertElements", - value: function insertElements(pageIndex) { - var _this6 = this; - - var can = Object(_common_util_js__WEBPACK_IMPORTED_MODULE_3__["createCanvas"])(); - var ctx = can.getContext('2d'); - can.width = this.renderport.width; - can.height = this.pageHeight; - ctx.id = ++id; - this.canvasMap[pageIndex].canvas = can; - this.canvasMap[pageIndex].context = ctx; - this.canvasMap[pageIndex].elements.forEach(function (ele) { - ele.element.insert(ctx, ele.box); - }); - - if (pageIndex < this.pageCount - 1) { - var timer = setTimeout(function () { - _this6.insertElements(++pageIndex); - }, 250); - this.renderTimers.push(timer); - } - } - }, { - key: "childImageLoadDoneCbk", - value: function childImageLoadDoneCbk(img) { - var start = new Date(); - var list = Object.values(this.canvasMap); - var pageIndex = -1; - - for (var i = 0; i < list.length; i++) { - if (list[i].elements.find(function (item) { - return item.element === img; - })) { - pageIndex = i; - break; - } - } - - if (pageIndex > -1) { - var _start = new Date(); - - var canItem = this.canvasMap[pageIndex]; - var canvas = canItem.canvas; - var ctx = canItem.context; - ctx.clearRect(0, 0, canvas.width, canvas.height); - this.canvasMap[pageIndex].elements.forEach(function (ele) { - Object(_common_util_js__WEBPACK_IMPORTED_MODULE_3__["repaintTree"])(ele.element); - }); - } - /*this.throttleRepaint(-this.top || 0);*/ - - - this.clipRepaint(-this.top); - } - }, { - key: "insertScrollView", - value: function insertScrollView(context) { - var _this7 = this; - - // 绘制容器 - this.insert(context); - this.root.on('repaint__done', function () { - _this7.clipRepaint(-_this7.top); - }); // 计算列表应该分割成几页 - - this.calPageData(); // 计算分页数据:每个元素应该坐落在哪个canvas - - this.renderChildren(this); - this.insertElements(0); - this.clipRepaint(-this.top); // 图片加载可能是异步的,监听图片加载完成事件完成列表重绘逻辑 - - this.EE.on('image__render__done', function (img) { - _this7.throttleImageLoadDone(img); - }); - - if (this.scrollHeight > this.layoutBox.height) { - this.touch.setTouchRange(-(this.scrollHeight - this.layoutBox.height), 0, this.clipRepaint.bind(this)); // 监听触摸相关事件,将滚动处理逻辑交给相应的处理器处理 - - this.on('touchstart', this.touch.startFunc); - this.on('touchmove', this.touch.moveFunc); - this.on('touchend', this.touch.endFunc); - } - } - }, { - key: "scrollHeight", - get: function get() { - // scrollview为空的情况 - if (!this.children.length) { - return 0; - } - - var last = this.children[this.children.length - 1]; - return last.layoutBox.top + last.layoutBox.height; - } - }]); - - return ScrollView; -}(_view_js__WEBPACK_IMPORTED_MODULE_0__["default"]); - - - -/***/ }), -/* 21 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Touch; }); -/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - - - -var Touch = /*#__PURE__*/function () { - function Touch() { - _classCallCheck(this, Touch); - - this.needProcess = false; - this.startFunc = this.touchStartHandler.bind(this); - this.endFunc = this.touchEndHandler.bind(this); - this.moveFunc = this.touchMoveHandler.bind(this); - } - - _createClass(Touch, [{ - key: "reset", - value: function reset() { - this.touchTime = new Date(); - this.touchStartX = 0; - this.touchStartY = 0; // 滚动区间 - - this.start = 0; - this.end = 0; // 当前位置 - - this.move = 0; // 目标位置 - - this.target = 0; // 滚动回调函数 - - this.scroll = null; // for istanbul - - /* istanbul ignore if*/ - - if (typeof cancelAnimationFrame !== 'undefined') { - cancelAnimationFrame(this.animate); - } - } - }, { - key: "enable", - value: function enable() { - this.reset(); - this.needProcess = true; - } - }, { - key: "disable", - value: function disable() { - this.needProcess = false; - } // 设置滚动区间,比如一个排行榜的滚动区间可能是[-300, 0] - - }, { - key: "setTouchRange", - value: function setTouchRange(start, end, scroll) { - // 考虑到切换游戏的场景,每次设置的时候重置所有变量 - this.enable(); - this.start = start; - this.end = end; - - if (start === 0 && end === 0) { - return; - } - - this.scroll = scroll; // this.animate = requestAnimationFrame(this.loop.bind(this)); - } // 保证滚动目标位置在滚动区间内 - - }, { - key: "limitTarget", - value: function limitTarget(target) { - var result = target; - - if (target > this.end) { - result = this.end; - } else if (target < this.start) { - result = this.start; - } - - return result; - } - }, { - key: "touchStartHandler", - value: function touchStartHandler(e) { - var touch = e.touches && e.touches[0] || e.changedTouches && e.changedTouches[0] || e; - - if (!touch || !touch.pageX || !touch.pageY) { - return; - } - - var dpr = Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["getDpr"])(); - this.touchStartX = touch.clientX * dpr; - this.touchStartY = touch.clientY * dpr; - this.touchTime = new Date(); - this.isMoving = true; - this.needProcess = true; - this.animate = requestAnimationFrame(this.loop.bind(this)); - } - }, { - key: "touchMoveHandler", - value: function touchMoveHandler(e) { - if (!this.isMoving) { - return; - } - - var touch = e.touches && e.touches[0] || e.changedTouches && e.changedTouches[0] || e; - - if (!touch || !touch.pageX || !touch.pageY) { - return; - } - - var dpr = Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["getDpr"])(); - var currY = touch.clientY * dpr; - - if (this.touchStartY - currY > 2 || this.touchStartY - currY < -2) { - this.target -= this.touchStartY - currY; - } - - this.target = this.limitTarget(this.target); - this.touchStartY = currY; - } - }, { - key: "touchEndHandler", - value: function touchEndHandler() { - this.isMoving = false; - var timeInS = (Date.now() - this.touchTime) / 1000; - /*console.log(Date.now(), this.touchTime.getTime(), Date.now() - this.touchTime);*/ - - if (timeInS < 0.9) { - /*console.log(1, timeInS, this.target, this.move);*/ - this.target += (this.target - this.move) * 0.6 / (timeInS * 5); - /*console.log(2, this.target)*/ - - this.target = this.limitTarget(this.target); - /*console.log(3, this.target)*/ - } - } - }, { - key: "loop", - value: function loop() { - if (this.needProcess) { - if (this.isMoving) { - if (this.move !== this.target) { - // 手指移动可能过快,切片以使得滑动流畅 - if (Math.abs(this.target - this.move) > 1) { - this.move += (this.target - this.move) * 0.4; - } else { - this.move = this.target; - } - - this.scroll && this.scroll(this.move); - } - } else { - if (this.move !== this.target) { - /** - * 如果滑动很快,为了滚动流畅,需要将滑动过程切片 - */ - if (Math.abs(this.target - this.move) > 1) { - this.move += (this.target - this.move) * 0.3; - } else { - this.move = this.target; - } - - this.scroll && this.scroll(this.move); - } else { - // 滑动结束,停止动画 - this.needProcess = false; - } - } - - this.animate = requestAnimationFrame(this.loop.bind(this)); - } else if (typeof cancelAnimationFrame !== 'undefined') { - cancelAnimationFrame(this.animate); - } - } - }]); - - return Touch; -}(); - - - -/***/ }), -/* 22 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BitMapText; }); -/* harmony import */ var _elements_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var _common_pool_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } - -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } - -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - - - -var bitMapPool = new _common_pool_js__WEBPACK_IMPORTED_MODULE_1__["default"]('bitMapPool'); - -var BitMapText = /*#__PURE__*/function (_Element) { - _inherits(BitMapText, _Element); - - var _super = _createSuper(BitMapText); - - function BitMapText(opts) { - var _this; - - _classCallCheck(this, BitMapText); - - var _opts$style = opts.style, - style = _opts$style === void 0 ? {} : _opts$style, - _opts$props = opts.props, - props = _opts$props === void 0 ? {} : _opts$props, - _opts$idName = opts.idName, - idName = _opts$idName === void 0 ? '' : _opts$idName, - _opts$className = opts.className, - className = _opts$className === void 0 ? '' : _opts$className, - _opts$value = opts.value, - value = _opts$value === void 0 ? '' : _opts$value, - _opts$font = opts.font, - font = _opts$font === void 0 ? '' : _opts$font; - _this = _super.call(this, { - props: props, - idName: idName, - className: className, - style: style - }); - _this.type = "BitMapText"; - _this.ctx = null; - _this.valuesrc = value; - _this.renderBoxes = []; - Object.defineProperty(_assertThisInitialized(_this), "value", { - get: function get() { - return this.valuesrc; - }, - set: function set(newValue) { - if (newValue !== this.valuesrc) { - this.valuesrc = newValue; - this.emit('repaint'); - } - }, - enumerable: true, - configurable: true - }); - _this.font = bitMapPool.get(font); - - if (!_this.font) { - console.error('Please invoke API `registBitMapFont` before using `BitMapText`'); - } - - return _this; - } - - _createClass(BitMapText, [{ - key: "insert", - value: function insert(ctx, box) { - this.renderBoxes.push({ - ctx: ctx, - box: box - }); - this.render(ctx, box); - } - }, { - key: "repaint", - value: function repaint() { - var _this2 = this; - - this.renderBoxes.forEach(function (item) { - _this2.render(item.ctx, item.box); - }); - } - }, { - key: "destroySelf", - value: function destroySelf() { - this.root = null; - } - }, { - key: "render", - value: function render(ctx, layoutBox) { - var _this3 = this; - - if (!this.font) { - return; - } - - if (this.font.ready) { - this.renderText(ctx, layoutBox); - } else { - this.font.event.on('text__load__done', function () { - if (!_this3.isDestroyed) { - _this3.renderText(ctx, layoutBox); - } - }); - } - } - }, { - key: "getTextBounds", - value: function getTextBounds() { - var style = this.style; - var _style$letterSpacing = style.letterSpacing, - letterSpacing = _style$letterSpacing === void 0 ? 0 : _style$letterSpacing; - var width = 0; - - for (var i = 0, len = this.value.length; i < len; i++) { - var _char = this.value[i]; - var cfg = this.font.chars[_char]; - - if (cfg) { - width += cfg.w; - - if (i < len - 1) { - width += letterSpacing; - } - } - } - - return { - width: width, - height: this.font.lineHeight - }; - } - }, { - key: "renderText", - value: function renderText(ctx, layoutBox) { - var bounds = this.getTextBounds(); - var defaultLineHeight = this.font.lineHeight; - ctx.save(); - this.renderBorder(ctx, layoutBox); - var box = layoutBox || this.layoutBox; - var style = this.style; - var width = style.width, - height = style.height, - _style$lineHeight = style.lineHeight, - lineHeight = _style$lineHeight === void 0 ? defaultLineHeight : _style$lineHeight, - textAlign = style.textAlign, - verticalAlign = style.verticalAlign; // 元素包围盒的左上角坐标 - - var x = box.absoluteX; - var y = box.absoluteY; - var scaleY = lineHeight / defaultLineHeight; - var realWidth = scaleY * bounds.width; // 如果文字的渲染区域高度小于盒子高度,采用对齐方式 - - if (lineHeight < height) { - if (verticalAlign === 'middle') { - y += (height - lineHeight) / 2; - } else if (verticalAlign === 'bottom') { - y = y + height - lineHeight; - } - } - - if (width > realWidth) { - if (textAlign === 'center') { - x += (width - realWidth) / 2; - } else if (textAlign === 'right') { - x += width - realWidth; - } - } - - for (var i = 0; i < this.value.length; i++) { - var _char2 = this.value[i]; - var cfg = this.font.chars[_char2]; - - if (cfg) { - ctx.drawImage(this.font.texture, cfg.x, cfg.y, cfg.w, cfg.h, x + cfg.offX * scaleY, y + cfg.offY * scaleY, cfg.w * scaleY, cfg.h * scaleY); - x += cfg.w * scaleY; - } - } - } - }]); - - return BitMapText; -}(_elements_js__WEBPACK_IMPORTED_MODULE_0__["default"]); - - - -/***/ }) -/******/ ]); \ No newline at end of file diff --git a/platforms/minigame/openDataContext/index.js b/platforms/minigame/openDataContext/index.js deleted file mode 100644 index d64d0eb571..0000000000 --- a/platforms/minigame/openDataContext/index.js +++ /dev/null @@ -1,28 +0,0 @@ -const style = require('./render/style') -const template = require('./render/template') -const Layout = require('./engine').default; - -let __env = GameGlobal.wx || GameGlobal.tt || GameGlobal.swan; -let sharedCanvas = __env.getSharedCanvas(); -let sharedContext = sharedCanvas.getContext('2d'); -function draw() { - Layout.clear(); - Layout.init(template, style); - Layout.layout(sharedContext); -} - -function updateViewPort(data) { - Layout.updateViewPort({ - x: data.x, - y: data.y, - width: data.width, - height: data.height, - }); -} - -__env.onMessage(data => { - if ( data.type === 'engine' && data.event === 'viewport' ) { - updateViewPort(data); - draw(); - } -}); diff --git a/platforms/minigame/openDataContext/render/avatar.png b/platforms/minigame/openDataContext/render/avatar.png deleted file mode 100644 index 2613e52d59459f58659a3c443d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7c+6QdbKR0a52|QO!ct;|?=8O*>a%m(aldG6(f5L28E97+4cf>AY;__NmW0?$b zzgXXR04`(wIxuK&wr@5GJ%y#j6*DecXj|B2tN^yxZ>1P$87y{wg7(fO2Epo@r>A0_ z7Xn|+MTU6rzC{KZo!160^xxy9_dYC&O3}$MNaPQU$cm;ng;#!BlV|f;Dx_~dW2QOfEwcMq0$n4adn2xEI+W1i0bXMjf( zIAgS!ej9l>Zux(ICwy@6dmzW`YTQ=sBd(Yy%up{Q!n_fJReVe#H|d+2{hq}CHO$A~ zPU59(7Qs#)39^r7zR$_V#?==_{$9GCvonhE!9m3+?AAmm(tL^zG<`q;v(=D#g6Osb z;ynz*(*H_M??uO)xSn=qJYmk~)xihy21CkEo$%{qKcp#T7|%I|GVgg5XazQYhz~h) z4o+JSjyt=t#-F@gol(Twzd+jS?66e`PHyzY&8sI<+@R?hBAhXB!`0kMAmD)4|3LO~ zhj+eQGVyc9$R$W- zxC*`KVQk!4<6Px48F zP${sY+(y4z0-Om6Pxi%AQMi<^i)l9iN_ef(HZOh#5rtnH8d(*Hx?;pOP+9PL!xJ$5 vuLoll-d&dx;F(-NaM}U@wzIwf?UCjRhFKM#b diff --git a/platforms/minigame/openDataContext/render/dataDemo.js b/platforms/minigame/openDataContext/render/dataDemo.js deleted file mode 100644 index 854d5d4a65..0000000000 --- a/platforms/minigame/openDataContext/render/dataDemo.js +++ /dev/null @@ -1,23 +0,0 @@ -let dataDemo = { - data: [ - /* - { - rankScore: 0, - avatarUrl: '', - nickname: '', - }, - */ - ], -}; - -const maxCount = 30; -for (let i = 0; i < maxCount; ++i) { - let item = {}; - item.rankScore = Math.floor((Math.random() * 500)); - item.avatarUrl = 'openDataContext/render/avatar.png'; - item.nickname = 'Player_' + i; - dataDemo.data.push(item); -} -dataDemo.data.sort((a, b) => b.rankScore - a.rankScore); - -module.exports = dataDemo; \ No newline at end of file diff --git a/platforms/minigame/openDataContext/render/style.js b/platforms/minigame/openDataContext/render/style.js deleted file mode 100644 index 34ff72346e..0000000000 --- a/platforms/minigame/openDataContext/render/style.js +++ /dev/null @@ -1,109 +0,0 @@ -module.exports = { - container: { - width: '100%', - height: '100%', - borderRadius: 12, - }, - - header: { - width: '100%', - height: '10%', - flexDirection: 'column', - alignItems: 'center', - backgroundColor: '#ffffff', - borderBottomWidth: 0.5, - borderColor: 'rgba(0, 0, 0, 0.3)', - }, - - title: { - width: '10%', - height: '100%', - fontSize: 35, - lineHeight: 80, - textAlign: 'center', - fontWeight: 'bold', - borderBottomWidth: 6, - borderColor: '#000000', - }, - - rankList: { - width: '100%', - height: '90%', - backgroundColor: '#ffffff', - }, - - list: { - width: '100%', - height: '88%', - backgroundColor: '#ffffff', - marginTop: 30, - }, - - listTips: { - width: '100%', - height: '12%', - lineHeight: 90, - textAlign: 'center', - fontSize: 25, - color: 'rgba(0,0,0,0.5)', - backgroundColor: '#ffffff', - borderRadius: 10, - borderWidth: 1, - borderColor: 'rgba(0, 0, 0, 1)', - }, - - listItem: { - backgroundColor: '#F7F7F7', - width: '100%', - height: '10%', - flexDirection: 'row', - alignItems: 'center', - justifyContent: 'space-between', - }, - - listItemOld: { - backgroundColor: '#ffffff', - }, - - listItemUserData: { - width: '75%', - height: '100%', - flexDirection: 'row', - alignItems: 'center', - justifyContent: 'flex-start', - }, - - listItemScore: { - width: '25%', - height: 100, - fontSize: 33, - fontWeight: 'bold', - paddingRight: 200, - lineHeight: 100, - textAlign: 'center', - }, - - listItemNum: { - width: 100, - height: 80, - fontSize: 30, - fontWeight: 'bold', - color: '#452E27', - lineHeight: 100, - textAlign: 'center', - }, - - listHeadImg: { - borderRadius: 6, - width: 70, - height: 70, - }, - - listItemName: { - width: 210, - height: 100, - fontSize: 30, - lineHeight: 100, - marginLeft: 30, - }, -}; diff --git a/platforms/minigame/openDataContext/render/template.js b/platforms/minigame/openDataContext/render/template.js deleted file mode 100644 index 707646c7f2..0000000000 --- a/platforms/minigame/openDataContext/render/template.js +++ /dev/null @@ -1,33 +0,0 @@ -const dataDemo = require('./dataDemo') - -/* - - - - - - - {{~it.data :item:index}} - {{? index % 2 === 1 }} - - {{?}} - {{? index % 2 === 0 }} - - {{?}} - - - - - - - - {{~}} - - - - -*/ - -// 上述模板经过模板引擎编译成版本函数,可通过 olado.github.io/doT/index.html 在线获得 -function anonymous(it ) { var out=' ';var arr1=it.data;if(arr1){var item,index=-1,l1=arr1.length-1;while(index ';} } out+=' ';return out; } -module.exports = anonymous(dataDemo); \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/Audio.js b/platforms/minigame/platforms/alipay/wrapper/builtin/Audio.js deleted file mode 100644 index c388949a2f..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/Audio.js +++ /dev/null @@ -1,215 +0,0 @@ -import HTMLAudioElement from './HTMLAudioElement' - -const _innerAudioContextMap = new WeakMap(); - -const HAVE_NOTHING = 0 -const HAVE_METADATA = 1 -const HAVE_CURRENT_DATA = 2 -const HAVE_FUTURE_DATA = 3 -const HAVE_ENOUGH_DATA = 4 - -export default class Audio extends HTMLAudioElement { - - constructor(url) { - super() - - this.readyState = HAVE_NOTHING; - - const innerAudioContext = my.createInnerAudioContext() - _innerAudioContextMap.set(this, innerAudioContext); - - this._canplayEvents = [ - 'load', - 'loadend', - 'canplay', - 'canplaythrough', - 'loadedmetadata' - ]; - - innerAudioContext.onCanPlay(() => { - this._loaded = true - this.readyState = HAVE_CURRENT_DATA - - this._canplayEvents.forEach((type) => { - this.dispatchEvent({ type: type }) - }) - - if(typeof this.oncanplay === "function") { - this.oncanplay(); - } - }); - - innerAudioContext.onPlay(() => { - // this._paused = _innerAudioContextMap.get(this).paused - this._paused = false; - this.dispatchEvent({ type: 'play' }) - if(typeof this.onplay === "function") { - this.onplay(); - } - }); - - innerAudioContext.onPause(() => { - this._paused = true; - this.dispatchEvent({ type: 'pause' }) - if(typeof this.onpause === "function") { - this.onpause(); - } - }); - - innerAudioContext.onEnded(() => { - // this._paused = _innerAudioContextMap.get(this).paused - this._paused = false; - this.dispatchEvent({ type: 'ended' }) - this.readyState = HAVE_ENOUGH_DATA - - if(typeof this.onended === "function") { - this.onended(); - - } - }); - - innerAudioContext.onError(() => { - // this._paused = _innerAudioContextMap.get(this).paused - this._paused = true; - this.dispatchEvent({ type: 'error' }); - if(typeof this.onerror === "function") { - this.onerror(); - } - }); - - if (url) { - this.src = url - } else { - this._src = '' - } - - this._loop = innerAudioContext.loop - this._autoplay = innerAudioContext.autoplay - this._paused = innerAudioContext.paused - this._volume = innerAudioContext.volume - this._muted = false - } - - addEventListener(type, listener, options = {}) { - type = String(type).toLowerCase() - - super.addEventListener(type, listener, options) - - if (this._loaded && this._canplayEvents.indexOf(type) !== -1) { - this.dispatchEvent({ type: type }) - } - } - - load() { - // console.warn('HTMLAudioElement.load() is not implemented.') - // weixin doesn't need call load() manually - } - - play() { - _innerAudioContextMap.get(this).play() - } - - resume() { - _innerAudioContextMap.get(this).play() - } - - pause() { - _innerAudioContextMap.get(this).pause() - } - - destroy() { - console.log("destory: " + typeof _innerAudioContextMap.get(this).destroy); - _innerAudioContextMap.get(this).destroy() - } - - canPlayType(mediaType = '') { - if (typeof mediaType !== 'string') { - return '' - } - - if (mediaType.indexOf('audio/mpeg') > -1 || mediaType.indexOf('audio/mp4')) { - return 'probably' - } - return '' - } - - get currentTime() { - return _innerAudioContextMap.get(this).currentTime - } - - set currentTime(value) { - _innerAudioContextMap.get(this).seek(value) - } - - get duration() { - return _innerAudioContextMap.get(this).duration - } - - get src() { - return this._src - } - - set src(value) { - this._src = value - this._loaded = false - this.readyState = HAVE_NOTHING - - const innerAudioContext = _innerAudioContextMap.get(this) - - innerAudioContext.src = value - } - - get loop() { - return this._loop - } - - set loop(value) { - this._loop = value - _innerAudioContextMap.get(this).loop = value - } - - get autoplay() { - return this._autoplay - } - - set autoplay(value) { - this._autoplay = value - _innerAudioContextMap.get(this).autoplay = value - } - - get paused() { - return this._paused - } - - get volume() { - return this._volume - } - - set volume(value) { - this._volume = value - if (!this._muted) { - _innerAudioContextMap.get(this).volume = value - } - } - - get muted() { - return this._muted - } - - set muted(value) { - this._muted = value - if (value) { - _innerAudioContextMap.get(this).volume = 0 - } else { - _innerAudioContextMap.get(this).volume = this._volume - } - } - - cloneNode() { - const newAudio = new Audio() - newAudio.loop = this.loop - newAudio.autoplay = this.autoplay - newAudio.src = this.src - return newAudio - } -} \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/Base64.js b/platforms/minigame/platforms/alipay/wrapper/builtin/Base64.js deleted file mode 100644 index 198862b47b..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/Base64.js +++ /dev/null @@ -1,55 +0,0 @@ -let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; -function InvalidCharacterError(message) { - this.message = message; -} -InvalidCharacterError.prototype = new Error; -InvalidCharacterError.prototype.name = 'InvalidCharacterError'; - -// encoder -// [https://gist.github.com/999166] by [https://github.com/nignag] - -function btoa(input) { - let str = String(input); - let output = ''; - for ( - // initialize result and counter - let block, charCode, idx = 0, map = chars; - // if the next str index does not exist: - // change the mapping table to "=" - // check if d has no fractional digits - str.charAt(idx | 0) || (map = '=', idx % 1); - // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8 - output += map.charAt(63 & block >> 8 - idx % 1 * 8) - ) { - charCode = str.charCodeAt(idx += 3 / 4); - if (charCode > 0xFF) { - throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."); - } - block = block << 8 | charCode; - } - return output; -} - -// decoder -// [https://gist.github.com/1020396] by [https://github.com/atk] -function atob(input) { - let str = String(input).replace(/[=]+$/, ''); - let output = ''; - for ( - // initialize result and counters - let bc = 0, bs, buffer, idx = 0; - // get next character - buffer = str.charAt(idx++); - // character found in table? initialize bit storage and add its ascii value; - ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, - // and if not first of each 4 characters, - // convert the first 8 bits to one ascii character - bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 - ) { - // try to find character in table (0-63, not found => -1) - buffer = chars.indexOf(buffer); - } - return output; -} - -export { btoa, atob } diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/Canvas.js b/platforms/minigame/platforms/alipay/wrapper/builtin/Canvas.js deleted file mode 100644 index d58d0461db..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/Canvas.js +++ /dev/null @@ -1,17 +0,0 @@ -import HTMLCanvasElement from "./HTMLCanvasElement" -import { isIDE } from "./utils/util"; - -export default function Canvas() { - const canvas = my.createCanvas(); - - if(!isIDE) { - if (!('tagName' in canvas)) { - canvas.tagName = 'canvas' - } - - canvas.__proto__.__proto__ = new HTMLCanvasElement() - } - - return canvas; - -} diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/Element.js b/platforms/minigame/platforms/alipay/wrapper/builtin/Element.js deleted file mode 100644 index f4451e1bf8..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/Element.js +++ /dev/null @@ -1,29 +0,0 @@ -import Node from "./Node"; -import { noop } from "./utils/noop"; - -export default class Element extends Node { - constructor() { - super(); - - this.className = ''; - this.children = []; - - this.remove = noop; - } - - setAttribute(name, value) { - this[name] = value - } - - getAttribute(name) { - return this[name] - } - - setAttributeNS(name, value) { - this[name] = value - } - - getAttributeNS(name) { - return this[name] - } -} \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/Event.js b/platforms/minigame/platforms/alipay/wrapper/builtin/Event.js deleted file mode 100644 index 35675b6835..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/Event.js +++ /dev/null @@ -1,17 +0,0 @@ -import { noop } from "./utils/noop"; - -class Event { - constructor(type) { - - this.cancelBubble = false; - this.cacelable = false; - this.target = null; - this.timestampe = Date.now(); - this.preventDefault = noop; - this.stopPropagation = noop; - - this.type = type; - } -} - -export default Event; \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/EventIniter/MouseEvent.js b/platforms/minigame/platforms/alipay/wrapper/builtin/EventIniter/MouseEvent.js deleted file mode 100644 index a8b23f9ef1..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/EventIniter/MouseEvent.js +++ /dev/null @@ -1,3 +0,0 @@ -export default class MouseEvent { - -} \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/EventIniter/TouchEvent.js b/platforms/minigame/platforms/alipay/wrapper/builtin/EventIniter/TouchEvent.js deleted file mode 100644 index 0b226ab499..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/EventIniter/TouchEvent.js +++ /dev/null @@ -1,35 +0,0 @@ -import Event from '../Event' -import document from '../document' -import { isIDE } from '../utils/util'; - -export default class TouchEvent extends Event { - - constructor(type) { - super(type) - - this.touches = [] - this.targetTouches = [] - this.changedTouches = [] - - this.target = window.canvas - this.currentTarget = window.canvas - } -} - -function eventHandlerFactory(type) { - return (rawEvent) => { - if(isIDE) return; - const event = new TouchEvent(type); - - event.changedTouches = rawEvent.touches; - event.touches = rawEvent.touches; - event.targetTouches = Array.prototype.slice.call(rawEvent.touches); - // event.timeStamp = rawEvent.timeStamp - document.dispatchEvent(event) - } -} - -my.onTouchStart(eventHandlerFactory('touchstart')) -my.onTouchMove(eventHandlerFactory('touchmove')) -my.onTouchEnd(eventHandlerFactory('touchend')) -my.onTouchCancel(eventHandlerFactory('touchcancel')) diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/EventIniter/index.js b/platforms/minigame/platforms/alipay/wrapper/builtin/EventIniter/index.js deleted file mode 100644 index 559c46aee0..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/EventIniter/index.js +++ /dev/null @@ -1,2 +0,0 @@ -export { default as TouchEvent } from './TouchEvent' -export { default as MouseEvent } from './MouseEvent' diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/EventTarget.js b/platforms/minigame/platforms/alipay/wrapper/builtin/EventTarget.js deleted file mode 100644 index b1692ac6e2..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/EventTarget.js +++ /dev/null @@ -1,56 +0,0 @@ -const _events = new WeakMap(); - -export default class EventTarget { - constructor() { - _events.set(this, {}); - } - - addEventListener(type, listener, options = {}) { - let events = _events.get(this); - - if(!events) { - events = {}; - _events.set(this, events); - } - - if (!events[type]) { - events[type] = []; - } - events[type].push(listener); - - } - - removeEventListener(type, listener) { - const events = _events.get(this); - if (events) { - const listeners = events[type]; - if (listeners && listeners.length > 0) { - for (var i = listeners.length; i--; i > 0) { - if (listeners[i] === listener) { - listeners.splice(i, 1); - break; - } - } - } - } - } - - dispatchEvent(event = {}) { - if(typeof event.type !== "string") { - return; - } - - if (!_events.get(this)) { - return ; - } - - const listeners = _events.get(this)[event.type]; - if (listeners) { - for (var i = 0; i < listeners.length; i++) { - var listener = listeners[i]; - listener.call(this, event); - - } - } - } -} \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/FileReader.js b/platforms/minigame/platforms/alipay/wrapper/builtin/FileReader.js deleted file mode 100644 index 97d00ab3c4..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/FileReader.js +++ /dev/null @@ -1,3 +0,0 @@ -export default class FileReader { - construct() {} -} diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLAudioElement.js b/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLAudioElement.js deleted file mode 100644 index d5a6e78503..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLAudioElement.js +++ /dev/null @@ -1,7 +0,0 @@ -import HTMLMediaElement from "./HTMLMediaElement"; - -export default class HTMLAudioElement extends HTMLMediaElement { - constructor() { - super("audio"); - } -} \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLCanvasElement.js b/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLCanvasElement.js deleted file mode 100644 index a8558f178f..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLCanvasElement.js +++ /dev/null @@ -1,8 +0,0 @@ -import HTMLElement from './HTMLElement'; - -export default class HTMLCanvasElement extends HTMLElement -{ - constructor(){ - super('canvas') - } -}; \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLElement.js b/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLElement.js deleted file mode 100644 index 2e4e6dc977..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLElement.js +++ /dev/null @@ -1,25 +0,0 @@ -import Element from "./Element"; -import { noop } from "./utils/noop"; -import { innerWidth, innerHeight } from "./WindowProperties"; - -export default class HTMLElement extends Element { - constructor(tagName = "") { - super() - - this.className = ''; - this.childern = []; - - this.style = { - width: innerWidth + 'px', - height: innerHeight + 'px' - }; - - this.focus = noop; - this.blur = noop; - - this.innerHTML = ''; - - this.tagName = tagName.toUpperCase(); - } - -} \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLImageElement.js b/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLImageElement.js deleted file mode 100644 index 8c4231d8df..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLImageElement.js +++ /dev/null @@ -1,8 +0,0 @@ -import HTMLElement from './HTMLElement'; - -export default class HTMLImageElement extends HTMLElement -{ - constructor() { - super("img"); - } -}; \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLMediaElement.js b/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLMediaElement.js deleted file mode 100644 index 782c3347fa..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLMediaElement.js +++ /dev/null @@ -1,22 +0,0 @@ -import HTMLElement from "./HTMLElement" - -export default class HTMLMediaElement extends HTMLElement { - - constructor(tagName) { - return super(tagName) - } - - addTextTrack() {} - - capureStream() {} - - fastSeek() {} - - load() {} - - pause() {} - - play() {} - - canPlayType() {} -} \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLVideoElement.js b/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLVideoElement.js deleted file mode 100644 index 79be0e019a..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/HTMLVideoElement.js +++ /dev/null @@ -1,8 +0,0 @@ -import HTMLMediaElement from './HTMLMediaElement'; - -export default class HTMLVideoElement extends HTMLMediaElement -{ - constructor(){ - super('video') - } -}; diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/Image.js b/platforms/minigame/platforms/alipay/wrapper/builtin/Image.js deleted file mode 100644 index 4f9c164b07..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/Image.js +++ /dev/null @@ -1,28 +0,0 @@ -import HTMLImageElement from "./HTMLImageElement"; -import { isIDE } from "./utils/util"; - -export default function Image(){ - const image = my.createImage(); - if(!isIDE) { - image.__proto__ = new HTMLImageElement() - if(image.tagName === undefined) { - image.tagName = "IMG"; - } - - image.onload = () => { - image.dispatchEvent({ - type: "load", - }); - } - - image.onerror = () => { - image.dispatchEvent({ - type: "error" - }); - } - - } - - - return image; -} \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/ImageBitmap.js b/platforms/minigame/platforms/alipay/wrapper/builtin/ImageBitmap.js deleted file mode 100644 index 94be70a760..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/ImageBitmap.js +++ /dev/null @@ -1,5 +0,0 @@ -export default class ImageBitmap { - constructor() { - // TODO - } -} diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/Node.js b/platforms/minigame/platforms/alipay/wrapper/builtin/Node.js deleted file mode 100644 index 010a3b4832..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/Node.js +++ /dev/null @@ -1,37 +0,0 @@ -import EventTarget from './EventTarget' -import { noop } from './utils/noop'; - -export default class Node extends EventTarget { - constructor() { - super(); - - this.childNodes = []; - - this.insertBefor = noop; - } - - appendChild(node) { - if (node instanceof Node || node instanceof window.Node) { - this.childNodes.push(node) - } else { - throw new TypeError(`Failed to executed 'appendChild' on 'Node': parameter 1 is not of type 'Node'.`) - } - } - - cloneNode() { - var copyNode = Object.create(this); - - return Object.assign(copyNode, this); - } - - removeChild(node) { - var index = this.childNodes.findIndex((child) => { - return child === node; - }); - - if (index > -1) { - return this.childNodes.splice(index, 1); - } - return null; - } -} \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/WebGLRenderingContext.js b/platforms/minigame/platforms/alipay/wrapper/builtin/WebGLRenderingContext.js deleted file mode 100644 index bc62da5f49..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/WebGLRenderingContext.js +++ /dev/null @@ -1,5 +0,0 @@ -export default class WebGLRenderingContext { - constructor() { - // TODO - } -} diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/WebSocket.js b/platforms/minigame/platforms/alipay/wrapper/builtin/WebSocket.js deleted file mode 100644 index 15cf96d4b9..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/WebSocket.js +++ /dev/null @@ -1,112 +0,0 @@ -import { transformArrayBufferToBase64, base64ToArrayBuffer } from "./utils/util"; - -const _taskMap = new WeakMap(); - -class WebSocket { - - static CONNECTING = 0; - static OPEN = 1; - static CLOSING = 2; - static CLOSED = 3; - - constructor(url, protocols = []) { - this.OPEN = WebSocket.OPEN; - this.CONNECTING = WebSocket.CONNECTING; - this.CLOSING = WebSocket.CLOSING; - this.CLOSED = WebSocket.CLOSED; - - - this.binaryType = ''; - this.bufferedAmount = 0; - this.extensions = ''; - - this.onclose = null; - this.onerror = null; - this.onmessage = null; - this.onopen = null; - - this.protocol = ''; - this.readyState = this.CLOSED; - - if (typeof url !== 'string' || !/(^ws:\/\/)|(^wss:\/\/)/.test(url)) { - throw new TypeError(`Failed to construct 'WebSocket': The URL='${url}' is invalid`); - } - - this.url = url; - this.readyState = this.CONNECTING; - - var task = my.connectSocket({ - url: url, - multiple: true, - protocols: Array.isArray(protocols) ? protocols : [protocols], - fail: (res) => { - if (typeof this.onerror === 'function') { - this.onerror(new Error(res.errorMessage)) - } - }, - }); - _taskMap.set(this, task); - - task.onOpen((res) => { - this.readyState = this.OPEN; - if (typeof this.onopen === 'function') { - this.onopen(res) - } - }); - - task.onError(res => { - if (typeof this.onerror === 'function') { - this.onerror(new Error(res.errorMessage)) - } - }); - - task.onMessage(res => { - if (typeof this.onmessage === 'function') { - if(res.data) { - var data = res.data; - if (data.isBuffer) { - // 对齐web转成arrayBuffer; - data.data = base64ToArrayBuffer(data.data); - } - this.onmessage(data); - } else { - this.onmessage(null); - } - } - }); - - task.onClose((res) => { - this.readyState = this.CLOSED; - if (typeof this.onclose === 'function') { - this.onclose(res); - } - }) - } - - send(data) { - if (typeof data !== 'string' && !(data instanceof ArrayBuffer)) { - throw new TypeError('Failed to send message: The data ' + data + ' is invalid'); - } - let p = {} - if (data instanceof ArrayBuffer) { - data = transformArrayBufferToBase64(data); - p.isBuffer = true; - } - p.data = data; - p.fail = (res) => { - if (typeof this.onerror === 'function') { - this.onerror(new Error(res.errorMessage)) - } - }; - const task = _taskMap.get(this); - task.send(p); - } - - close() { - this.readyState = this.CLOSING; - const task = _taskMap.get(this); - task.close(); - } -} - -export default WebSocket; \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/WindowProperties.js b/platforms/minigame/platforms/alipay/wrapper/builtin/WindowProperties.js deleted file mode 100644 index c4ef59c304..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/WindowProperties.js +++ /dev/null @@ -1,14 +0,0 @@ - -var { screenWidth, screenHeight, pixelRatio, windowHeight, windowWidth} = my.getSystemInfoSync(); - -export var innerHeight = windowHeight; -export var innerWidth = windowWidth; -export var devicePixelRatio = pixelRatio; -export var screen = { - width: screenWidth, - height: screenHeight, - availWidth: innerWidth, - availHeight: innerHeight, - availLeft: 0, - availTop: 0 -}; diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/XMLHttpRequest.js b/platforms/minigame/platforms/alipay/wrapper/builtin/XMLHttpRequest.js deleted file mode 100644 index f4be4af1af..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/XMLHttpRequest.js +++ /dev/null @@ -1,153 +0,0 @@ -import EventTarget from "./EventTarget"; - -let _url = new WeakMap() -let _method = new WeakMap() -let _requestHeader = new WeakMap() -let _responseHeader = new WeakMap() -let _requestTask = new WeakMap() - -function _triggerEvent(type, event={}) { - event.target = event.target || this; - if (typeof this['on' + type] === 'function') { - this['on' + type].apply(this, event); - } -} - - -function _changeReadyState(readyState, event={}) { - this.readyState = readyState; - event.readyState = readyState; - _triggerEvent.call(this, 'readystatechange', event); -} - -const UNSEND = 0; -const OPENED = 1; -const HEADERS_RECEIVED = 2; -const LOADING = 3; -const DONE = 4; - -class XMLHttpRequest extends EventTarget{ - - constructor() { - super() - this.onabort = null; - this.onerror = null; - this.onload = null; - this.onloadstart = null; - this.onprogress = null; - this.ontimeout = null; - this.onloadend = null; - - this.onreadystatechange = null; - this.readyState = 0; - this.response = null; - this.responseText = null; - this.responseType = ''; - this.dataType = 'string'; - this.responseXML = null; - this.status = 0; - this.statusText = ''; - this.upload = {}; - this.withCredentials = false; - this.timeout = 0; - - _requestHeader.set(this, { - 'content-type': 'application/x-www-form-urlencoded' - }) - _responseHeader.set(this, {}) - } - - abort() { - const myRequestTask = _requestTask.get(this); - - if (myRequestTask) { - myRequestTask.abort(); - } - } - - getAllResponseHeaders() { - const responseHeader = _responseHeader.get(this); - - return Object.keys(responseHeader).map((header) => { - return header + ': ' + responseHeader[header]; - }).join('\n'); - } - - /* async, user, password 这几个参数在小程序内不支持*/ - open(method, url) { - _method.set(this, method) - _url.set(this, url) - _changeReadyState.call(this, OPENED); - } - - overrideMimeType() {} - - send(data = "") { - - if (this.readyState !== OPENED) { - throw new Error("Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED."); - } else { - // https://opendocs.alipay.com/mini-game/08uy1c?pathHash=79945623 - var task = my.request({ - data: data, - url: _url.get(this), - method: _method.get(this), - headers: _requestHeader.get(this), - timeout: this.timeout, - dataType: this.responseType || 'text', - success: (res) => { - var { data, status, headers } = res; - - this.status = status; - _responseHeader.set(this, headers || {}); - _triggerEvent.call(this, 'loadstart'); - _changeReadyState.call(this, HEADERS_RECEIVED); - _changeReadyState.call(this, LOADING); - - this.response = data; - this.responseText = !this.responseType || this.responseType === 'text' ? data : ''; - _changeReadyState.call(this, DONE); - _triggerEvent.call(this, 'load'); - _triggerEvent.call(this, 'loadend'); - }, - - fail: (res) => { - var { errorMessage = "", error = -1 } = res; - if (error === 9) { - _triggerEvent.call(this, 'abort'); - } else if (errorMessage.includes("超时") || error === 13) { - _triggerEvent.call(this, 'timeout'); - } else { - _triggerEvent.call(this, 'error'); - } - _triggerEvent.call(this, 'loadend'); - } - }); - - _requestTask.set(this, task) - } - } - - setRequestHeader(header, value) { - const myHeader = _requestHeader.get(this); - myHeader[header] = value; - _requestHeader.set(this, myHeader); - } - - addEventListener(type, listener) { - if (typeof listener === 'function') { - this['on' + type] = (event = {}) => { - event.target = event.target || this; - listener.call(this, event); - }; - } - } - - removeEventListener(type, listener) { - if(this['on' + type] === listener) { - this['on' + type] = null; - } - } -} - -export default XMLHttpRequest; \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/document.js b/platforms/minigame/platforms/alipay/wrapper/builtin/document.js deleted file mode 100644 index 0a9a591e6c..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/document.js +++ /dev/null @@ -1,191 +0,0 @@ -import Event from './Event' -import HTMLElement from './HTMLElement' -import HTMLVideoElement from './HTMLVideoElement' -import Image from './Image' -import Audio from './Audio' -import Canvas from './Canvas' -import './EventIniter/index.js' -import { screen } from './WindowProperties' - -const events = {} - -var getElementsByTagName_; -if(window.document && window.document.getElementsByTagName) { - getElementsByTagName_ = window.document.getElementsByTagName.bind(window.document); -} - -const document = { - readyState: 'complete', - visibilityState: 'visible', // 'visible' , 'hidden' - fullscreen: true, - hidden: false, - style: {}, - scripts: [], - - location: window.location, - - ontouchstart: null, - ontouchmove: null, - ontouchend: null, - onvisibilitychange: null, - - head: new HTMLElement("head"), - body: new HTMLElement("body"), - - documentElement: { - clientWidth: screen.width, - clientHight: screen.height, - clientLeft: 0, - clientTop: 0, - scrollLeft: 0, - scrollTop: 0 - }, - - createElement(tagName) { - tagName = tagName.toLowerCase(); - if (tagName === 'canvas') { - return new Canvas() - } else if (tagName === 'audio') { - return new Audio() - } else if (tagName === 'img') { - return new Image() - } else if (tagName === 'video') { - return new HTMLVideoElement() - } - - return new HTMLElement(tagName) - }, - - createElementNS(nameSpace, tagName) { - return this.createElement(tagName); - }, - - getElementById(id) { - if (id === window.canvas.id) { - return window.canvas - } - return null - }, - - getElementsByTagName(tagName) { - if(getElementsByTagName_) { - return getElementsByTagName_(tagName); - } - - tagName = tagName.toLowerCase(); - if (tagName === 'head') { - return [document.head] - } else if (tagName === 'body') { - return [document.body] - } else if (tagName === 'canvas') { - return [window.canvas] - } - return [] - }, - - getElementsByTagNameNS(nameSpace, tagName) { - return this.getElementsByTagName(tagName); - }, - - getElementsByName(tagName) { - if (tagName === 'head') { - return [document.head] - } else if (tagName === 'body') { - return [document.body] - } else if (tagName === 'canvas') { - return [window.canvas] - } - return [] - }, - - querySelector(query) { - if (query === 'head') { - return document.head - } else if (query === 'body') { - return document.body - } else if (query === 'canvas') { - return window.canvas - } else if (query === `#${window.canvas.id}`) { - return window.canvas - } - return null - }, - - querySelectorAll(query) { - if (query === 'head') { - return [document.head] - } else if (query === 'body') { - return [document.body] - } else if (query === 'canvas') { - return [window.canvas] - } - return [] - }, - - addEventListener(type, listener) { - if (!events[type]) { - events[type] = [] - } - events[type].push(listener) - }, - - removeEventListener(type, listener) { - const listeners = events[type] - - if (listeners && listeners.length > 0) { - for (let i = listeners.length; i--; i > 0) { - if (listeners[i] === listener) { - listeners.splice(i, 1) - break - } - } - } - }, - - dispatchEvent(event) { - const type = event.type; - const listeners = events[type] - - if (listeners) { - for (let i = 0; i < listeners.length; i++) { - listeners[i](event) - } - } - - window.canvas.dispatchEvent(event); - - if (event.target && typeof event.target['on' + type] === 'function') { - event.target['on' + type](event) - } - } -} - -function onVisibilityChange(visible) { - - return function() { - - document.visibilityState = visible ? 'visible' : 'hidden'; - - const hidden = !visible; - if (document.hidden === hidden) { - return; - } - document.hidden = hidden; - - const event = new Event('visibilitychange'); - - event.target = document; - event.timeStamp = Date.now(); - - document.dispatchEvent(event); - } -} - -if (my.onHide) { - my.onHide(onVisibilityChange(false)); -} -if (my.onShow) { - my.onShow(onVisibilityChange(true)); -} - -export default document diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/index.js b/platforms/minigame/platforms/alipay/wrapper/builtin/index.js deleted file mode 100644 index b7e9efa7b7..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/index.js +++ /dev/null @@ -1,51 +0,0 @@ -import * as _window from './window'; -import document from './document'; -import { isIDE } from './utils/util'; - -function inject () { - _window.document = document; - - _window.addEventListener = (type, listener) => { - _window.document.addEventListener(type, listener); - }; - _window.removeEventListener = (type, listener) => { - _window.document.removeEventListener(type, listener); - }; - _window.dispatchEvent = function (event = {}) { - console.log('window.dispatchEvent', event.type, event); - }; - - if (isIDE) { - for (const key in _window) { - const descriptor = Object.getOwnPropertyDescriptor(window, key); - - if (!descriptor || descriptor.configurable === true) { - Object.defineProperty(window, key, { - value: _window[key], - }); - } - } - - for (const key in _window.document) { - const descriptor = Object.getOwnPropertyDescriptor(window.document, key); - - if (!descriptor || descriptor.configurable === true) { - Object.defineProperty(window.document, key, { - value: _window.document[key], - }); - } - } - window.parent = window; - window.my = my; - } else { - _window.my = my; - for (const key in _window) { - window[key] = _window[key]; - } - } -} - -inject(); - -require('../../../../common/xmldom/dom-parser'); -require('../unify'); diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/localStorage.js b/platforms/minigame/platforms/alipay/wrapper/builtin/localStorage.js deleted file mode 100644 index 619336262a..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/localStorage.js +++ /dev/null @@ -1,46 +0,0 @@ -const localStorage = { - get length() { - const { keys } = my.getStorageInfoSync() - console.log("getStorageInfoSync: " + JSON.stringify(my.getStorageInfoSync())); - return keys.length - }, - - key(n) { - const { keys } = my.getStorageInfoSync() - - return keys[n] - }, - - getItem(key) { - const value = my.getStorageSync({key}); - return value.data === null ? null : value.data; - }, - - setItem(key, value) { - if (window.asyncStorage) { - return my.setStorage({ - key: key, - data: value - }) - } - return my.setStorageSync({key, data: value}) - }, - - removeItem(key) { - if (window.asyncStorage) { - return my.removeStorage({ - key - }) - } - return my.removeStorageSync({key}) - }, - - clear() { - if (window.asyncStorage) { - return my.clearStorage() - } - return my.clearStorageSync() - } -} - -export default localStorage diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/location.js b/platforms/minigame/platforms/alipay/wrapper/builtin/location.js deleted file mode 100644 index 0f1ab92869..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/location.js +++ /dev/null @@ -1,13 +0,0 @@ -const location = { - href: 'game.js', - hostname: "alipay.com", - - reload() { - }, - - replace() { - - }, -} - -export default location diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/navigator.js b/platforms/minigame/platforms/alipay/wrapper/builtin/navigator.js deleted file mode 100644 index 968ad745f6..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/navigator.js +++ /dev/null @@ -1,52 +0,0 @@ -import { noop } from "./utils/noop"; - -var systemInfo = my.getSystemInfoSync(); - -const { system, platform = "android", language } = systemInfo || {}; -const android = platform.toLowerCase().indexOf('android') !== -1; - -if(my.onNetworkStatusChange){ - my.onNetworkStatusChange((res) => { - navigator.onLine = res.isConnected ? true : false; - }); -} - -function getCurrentPosition(cb) { - if(typeof cb !== "function") { - throw new TypeError("Failed to execute 'getCurrentPosition' on 'Geolocation': 1 argument required, but only 0 present."); - } - - my.getLocation({ - success(res) { - var { accuracy, latitude, longitude } = res; - cb({ - coords: { - accuracy, - latitude, - longitude - }, - timestamp: (new Date()).valueOf() - }) - } - }) -} - -var uaDesc = android ? 'Android; CPU ' + system : 'iPhone; CPU iPhone OS ' + system + ' like Mac OS X'; -var userAgent = `Mozilla/5.0 (${uaDesc}) AliApp(AP/${systemInfo.version}) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E8301 AlipayMiniGame NetType/WIFI Language/${language}`; -if(window.navigator) { - userAgent = window.navigator.userAgent + " AlipayMiniGame"; -} - -var navigator = { - platform, - language, - userAgent, - appVersion: '5.0 (' + uaDesc + ') AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1', - geolocation: { - getCurrentPosition, - watchPositon: noop, - clearWatch: noop - } -} - -export default navigator; \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/utils/noop.js b/platforms/minigame/platforms/alipay/wrapper/builtin/utils/noop.js deleted file mode 100644 index 4a54bb28d2..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/utils/noop.js +++ /dev/null @@ -1,3 +0,0 @@ -export function noop() { - -}; \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/utils/util.js b/platforms/minigame/platforms/alipay/wrapper/builtin/utils/util.js deleted file mode 100644 index 2fc7891e4c..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/utils/util.js +++ /dev/null @@ -1,80 +0,0 @@ -import { btoa } from "../Base64"; - -export function transformArrayBufferToBase64 (buffer) { - var binary = ''; - var bytes = new Uint8Array(buffer); - for (var len = bytes.byteLength, i = 0; i < len; i++) { - binary += String.fromCharCode(bytes[i]); - } - return btoa(binary); -} - -function encode(str) { - let encodings = - 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - const string = String(str); - let result = ''; - let currentIndex = 0; - let sum; - while ( - string.charAt(0 | currentIndex) || - ((encodings = '='), currentIndex % 1) - ) { - currentIndex += 0.75; // 每次移动3/4个位置 - let currentCode = string.charCodeAt(currentIndex); // 获取code point - if (currentCode > 255) { - // 大于255无法处理 - throw new Error('"btoa" failed'); - } - sum = (sum << 8) | currentCode; // 每次在上次的基础上左移8位再加上当前code point - const encodeIndex = 63 & (sum >> (8 - (currentIndex % 1) * 8)); // 去除多余的位数,再去最后6位 - result += encodings.charAt(encodeIndex); - } - - return result; - } - - function decode(str) { - const encodings = - 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - let res = ''; - const string = String(str).replace(/[=]+$/, ''); - var o, - r, - i = 0, - currentIndex = 0; - while ((r = string.charAt(currentIndex))) { - currentIndex = currentIndex + 1; - r = encodings.indexOf(r); - if (~r) { - o = i % 4 ? 64 * o + r : r; - if (i++ % 4) { - res += String.fromCharCode(255 & (o >> ((-2 * i) & 6))); - } - } - } - - return res; - } - - export function arrayBufferToBase64(buffer) { - let result = ''; - const uintArray = new Uint8Array(buffer); - const byteLength = uintArray.byteLength; - for (let i = 0; i < byteLength; i++) { - result += String.fromCharCode(uintArray[i]); - } - return encode(result); - } - - export function base64ToArrayBuffer(base64) { - const string = decode(base64); - const length = string.length; - let uintArray = new Uint8Array(length); - for (let i = 0; i < length; i++) { - uintArray[i] = string.charCodeAt(i); - } - return uintArray.buffer; - } - -export let isIDE = window.navigator && /AlipayIDE/.test(window.navigator.userAgent); diff --git a/platforms/minigame/platforms/alipay/wrapper/builtin/window.js b/platforms/minigame/platforms/alipay/wrapper/builtin/window.js deleted file mode 100644 index 0a810173c6..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/builtin/window.js +++ /dev/null @@ -1,38 +0,0 @@ -export { default as navigator } from './navigator' -export { default as XMLHttpRequest } from './XMLHttpRequest' -export { default as WebSocket } from './WebSocket' -export { default as Image } from './Image' -export { default as ImageBitmap } from './ImageBitmap' -export { default as Audio } from './Audio' -export { default as FileReader } from './FileReader' -export { default as Element } from './Element' -export { default as HTMLElement } from './HTMLElement' -export { default as HTMLImageElement } from './HTMLImageElement' -export { default as HTMLCanvasElement } from './HTMLCanvasElement' -export { default as HTMLMediaElement } from './HTMLMediaElement' -export { default as HTMLAudioElement } from './HTMLAudioElement' -import Canvas from './Canvas' - -export { default as HTMLVideoElement } from './HTMLVideoElement' -export { default as WebGLRenderingContext } from './WebGLRenderingContext' -export { TouchEvent, MouseEvent } from './EventIniter/index.js' -export { default as localStorage } from './localStorage' -export { btoa, atob } from './Base64' -export * from './WindowProperties' -import location_ from './location' -export const location = location_ - -// 暴露全局的 canvas -window.screencanvas = window.screencanvas || new Canvas(); -window.self = window; -export const canvas = window.screencanvas; - -export function alert(msg) { - my.alert({ - content: msg - }); -} - -export function focus() {} - -export function blur() {} \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/engine/AudioPlayer.js b/platforms/minigame/platforms/alipay/wrapper/engine/AudioPlayer.js deleted file mode 100644 index 954cb4b2cc..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/engine/AudioPlayer.js +++ /dev/null @@ -1,3 +0,0 @@ -if (cc.internal.AudioManager) { - cc.internal.AudioManager.maxAudioChannel = 6; -} \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/engine/Console.js b/platforms/minigame/platforms/alipay/wrapper/engine/Console.js deleted file mode 100644 index 96480caa10..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/engine/Console.js +++ /dev/null @@ -1,12 +0,0 @@ -// Alipay console.time have some error ,hack here -let Timer = window.performance; -let _timerTable = Object.create(null); - -console.time = function(label) { - _timerTable[label] = Timer.now(); -} -console.timeEnd = function(label) { - let startTime = _timerTable[label]; - let duration = Timer.now() - startTime; - console.log(`${label}: ${duration}ms`); -} diff --git a/platforms/minigame/platforms/alipay/wrapper/engine/Label.js b/platforms/minigame/platforms/alipay/wrapper/engine/Label.js deleted file mode 100644 index ef753f9a31..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/engine/Label.js +++ /dev/null @@ -1,24 +0,0 @@ -if (cc && cc.Label) { - // const gfx = cc.gfx; - const Label = cc.Label; - const isDevTool = __globalAdapter.isDevTool; - // shared label canvas - let _sharedLabelCanvas = document.createElement('canvas'); - let _sharedLabelCanvasCtx = _sharedLabelCanvas.getContext('2d'); - let canvasData = { - canvas: _sharedLabelCanvas, - context: _sharedLabelCanvasCtx, - }; - - cc.game.on(cc.Game.EVENT_ENGINE_INITED, function () { - Object.assign(Label._canvasPool, { - get() { - return canvasData; - }, - - put() { - // do nothing - } - }); - }); -} diff --git a/platforms/minigame/platforms/alipay/wrapper/engine/index.js b/platforms/minigame/platforms/alipay/wrapper/engine/index.js deleted file mode 100644 index 9c7f3c909a..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/engine/index.js +++ /dev/null @@ -1,5 +0,0 @@ -require('../fs-utils'); -require('../../../../common/engine/index'); -require('./Label'); -require('./Console'); -require('./AudioPlayer'); \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/fs-utils.js b/platforms/minigame/platforms/alipay/wrapper/fs-utils.js deleted file mode 100644 index 84acd20952..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/fs-utils.js +++ /dev/null @@ -1,284 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2019 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated 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. - ****************************************************************************/ -/* eslint-disable no-undef */ -const fs = my.getFileSystemManager ? my.getFileSystemManager() : null; -const outOfStorageRegExp = /the maximum size of the file storage/; // not exactly right - -const fsUtils = { - - fs, - - isOutOfStorage (errMsg) { - return outOfStorageRegExp.test(errMsg); - }, - - getUserDataPath () { - return my.env.USER_DATA_PATH; - }, - - checkFsValid () { - if (!fs) { - console.warn('Can not get the file system!'); - return false; - } - return true; - }, - - deleteFile (filePath, onComplete) { - fs.unlink({ - filePath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Delete file failed: path: ${filePath} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.errorMessage)); - }, - }); - }, - - downloadFile (remoteUrl, filePath, header, onProgress, onComplete) { - const options = { - url: remoteUrl, - success (res) { - if (!filePath) { - onComplete && onComplete(null, res.apFilePath); - } else { - fsUtils.copyFile(res.apFilePath, filePath, (err) => { - if (err) { - onComplete && onComplete(err); - } else { - onComplete && onComplete(null, filePath); - } - }); - } - }, - fail (res) { - console.warn(`Download file failed: path: ${remoteUrl} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.errorMessage), null); - }, - }; - if (header) options.header = header; - const task = my.downloadFile(options); - onProgress && task.onProgressUpdate(onProgress); - }, - - saveFile (srcPath, destPath, onComplete) { - // Hack, seems like my.saveFile dose not work - fsUtils.copyFile(srcPath, destPath, onComplete); - }, - - copyFile (srcPath, destPath, onComplete) { - fs.copyFile({ - srcPath, - destPath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Copy file failed: path: ${srcPath} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.errorMessage)); - }, - }); - }, - - writeFile (path, data, encoding, onComplete) { - fs.writeFile({ - filePath: path, - encoding, - data, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Write file failed: path: ${path} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.errorMessage)); - }, - }); - }, - - writeFileSync (path, data, encoding) { - try { - const resp = fs.writeFileSync({ - filePath: path, - data, - encoding, - }); - if (resp.success) { - return null; - } else { - console.warn(`Write file failed: path: ${path} message: ${resp.errorMessage}`); - return new Error(resp.errorMessage); - } - } catch (e) { - console.warn(`Write file failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - readFile (filePath, encoding, onComplete) { - fs.readFile({ - filePath, - encoding, - success (res) { - onComplete && onComplete(null, res.data); - }, - fail (res) { - console.warn(`Read file failed: path: ${filePath} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.errorMessage), null); - }, - }); - }, - - readDir (filePath, onComplete) { - fs.readdir({ - dirPath: filePath, - success (res) { - onComplete && onComplete(null, res.files); - }, - fail (res) { - console.warn(`Read directory failed: path: ${filePath} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.errorMessage), null); - }, - }); - }, - - readText (filePath, onComplete) { - fsUtils.readFile(filePath, 'utf8', onComplete); - }, - - readArrayBuffer (filePath, onComplete) { - fsUtils.readFile(filePath, '', onComplete); - }, - - readJson (filePath, onComplete) { - fsUtils.readFile(filePath, 'utf8', (err, text) => { - let out = null; - if (!err) { - try { - out = JSON.parse(text); - } catch (e) { - console.warn(`Read json failed: path: ${filePath} message: ${e.message}`); - err = new Error(e.message); - } - } - onComplete && onComplete(err, out); - }); - }, - - readJsonSync (path) { - try { - const res = fs.readFileSync({ - filePath: path, - encoding: 'utf8', - }); - if (res.success) { - return JSON.parse(res.data); - } else { - console.warn(`Read json failed: path: ${path} message: ${res.errorMessage}`); - return new Error(res.errorMessage); - } - } catch (e) { - console.warn(`Read json failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - makeDirSync (path, recursive) { - try { - const resp = fs.mkdirSync({ - dirPath: path, - recursive, - }); - if (resp.success) { - return null; - } else { - console.warn(`Make directory failed: path: ${path} message: ${resp.errorMessage}`); - return new Error(resp.errorMessage); - } - } catch (e) { - console.warn(`Make directory failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - rmdirSync (dirPath, recursive) { - try { - const resp = fs.rmdirSync({ dirPath, recursive }); - if (resp.success) { - return null; - } else { - console.warn(`rm directory failed: path: ${dirPath} message: ${resp.errorMessage}`); - return new Error(resp.errorMessage); - } - } catch (e) { - console.warn(`rm directory failed: path: ${dirPath} message: ${e.message}`); - return new Error(e.message); - } - }, - - exists (filePath, onComplete) { - fs.access({ - path: filePath, - success () { - onComplete && onComplete(true); - }, - fail () { - onComplete && onComplete(false); - }, - }); - }, - - loadSubpackage (name, onProgress, onComplete) { - const task = my.loadSubpackage({ - name, - success: () => { - onComplete && onComplete(); - }, - fail: (res) => { - console.warn(`Load Subpackage failed: path: ${name} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(`Failed to load subpackage ${name}: ${res.errorMessage}`)); - }, - }); - onProgress && task.onProgressUpdate(onProgress); - return task; - }, - - unzip (zipFilePath, targetPath, onComplete) { - fs.unzip({ - zipFilePath, - targetPath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`unzip failed: path: ${zipFilePath} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(`unzip failed: ${res.errorMessage}`)); - }, - }); - }, -}; - -window.fsUtils = module.exports = fsUtils; diff --git a/platforms/minigame/platforms/alipay/wrapper/unify.js b/platforms/minigame/platforms/alipay/wrapper/unify.js deleted file mode 100644 index f881d199bd..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/unify.js +++ /dev/null @@ -1,108 +0,0 @@ -const utils = require('./utils'); - -window.__globalAdapter = window.__globalAdapter || {}; -if (window.__globalAdapter) { - let globalAdapter = window.__globalAdapter; - // SystemInfo - globalAdapter.isSubContext = false; // sub context not supported - globalAdapter.isDevTool = window.navigator && (/AlipayIDE/.test(window.navigator.userAgent)); - utils.cloneMethod(globalAdapter, my, 'getSystemInfoSync'); - - // TouchEvent - // my.onTouchStart register touch event listner on body - // need to register on canvas - globalAdapter.onTouchStart = function (cb) { - window.canvas.addEventListener('touchstart', function (res) { - cb && cb(res); - }); - }; - globalAdapter.onTouchMove = function (cb) { - window.canvas.addEventListener('touchmove', function (res) { - cb && cb(res); - }); - }; - globalAdapter.onTouchEnd = function (cb) { - window.canvas.addEventListener('touchend', function (res) { - cb && cb(res); - }); - }; - globalAdapter.onTouchCancel = function (cb) { - window.canvas.addEventListener('touchcancel', function (res) { - cb && cb(res); - }); - }; - - // Audio - globalAdapter.createInnerAudioContext = function () { - let audio = my.createInnerAudioContext(); - audio.onCanplay = audio.onCanPlay.bind(audio); - audio.offCanplay = audio.offCanPlay.bind(audio); - return audio; - }; - - // FrameRate - utils.cloneMethod(globalAdapter, my, 'setPreferredFramesPerSecond'); - - // Keyboard - utils.cloneMethod(globalAdapter, my, 'showKeyboard'); - utils.cloneMethod(globalAdapter, my, 'hideKeyboard'); - utils.cloneMethod(globalAdapter, my, 'updateKeyboard'); - utils.cloneMethod(globalAdapter, my, 'onKeyboardInput'); - utils.cloneMethod(globalAdapter, my, 'onKeyboardConfirm'); - utils.cloneMethod(globalAdapter, my, 'onKeyboardComplete'); - utils.cloneMethod(globalAdapter, my, 'offKeyboardInput'); - utils.cloneMethod(globalAdapter, my, 'offKeyboardConfirm'); - utils.cloneMethod(globalAdapter, my, 'offKeyboardComplete'); - - // Message - utils.cloneMethod(globalAdapter, my, 'getOpenDataContext'); - utils.cloneMethod(globalAdapter, my, 'onMessage'); - - // Subpackage not supported - // utils.cloneMethod(globalAdapter, my, 'loadSubpackage'); - - // SharedCanvas - utils.cloneMethod(globalAdapter, my, 'getSharedCanvas'); - - // Font - utils.cloneMethod(globalAdapter, my, 'loadFont'); - - // hide show Event - utils.cloneMethod(globalAdapter, my, 'onShow'); - utils.cloneMethod(globalAdapter, my, 'onHide'); - - // Accelerometer - let accelerometerCallback = null; - let systemInfo = my.getSystemInfoSync(); - let windowWidth = systemInfo.windowWidth; - let windowHeight = systemInfo.windowHeight; - let isLandscape = windowWidth > windowHeight; - - function accelerometerChangeCallback(res, cb) { - let resClone = {}; - - let x = res.x; - let y = res.y; - - if (isLandscape) { - let tmp = x; - x = -y; - y = tmp; - } - - resClone.x = x; - resClone.y = y; - resClone.z = res.z; - accelerometerCallback && accelerometerCallback(resClone); - } - Object.assign(globalAdapter, { - startAccelerometer(cb) { - accelerometerCallback = cb; - my.onAccelerometerChange && my.onAccelerometerChange(accelerometerChangeCallback); - }, - - stopAccelerometer() { - my.offAccelerometerChange && my.offAccelerometerChange(accelerometerChangeCallback); - }, - }); -} \ No newline at end of file diff --git a/platforms/minigame/platforms/alipay/wrapper/utils.js b/platforms/minigame/platforms/alipay/wrapper/utils.js deleted file mode 100644 index 947fc06958..0000000000 --- a/platforms/minigame/platforms/alipay/wrapper/utils.js +++ /dev/null @@ -1,16 +0,0 @@ -let utils = { - /** - * @param {Object} target - * @param {Object} origin - * @param {String} methodName - * @param {String} targetMethodName - */ - cloneMethod (target, origin, methodName, targetMethodName) { - if (origin[methodName]) { - targetMethodName = targetMethodName || methodName; - target[targetMethodName] = origin[methodName].bind(origin); - } - } -}; - -module.exports = utils; \ No newline at end of file diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/Audio.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/Audio.js deleted file mode 100644 index 7337c09892..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/Audio.js +++ /dev/null @@ -1,205 +0,0 @@ -import HTMLAudioElement from './HTMLAudioElement' - -const HAVE_NOTHING = 0 -const HAVE_METADATA = 1 -const HAVE_CURRENT_DATA = 2 -const HAVE_FUTURE_DATA = 3 -const HAVE_ENOUGH_DATA = 4 - -let SN_SEED = 1 - -const _innerAudioContextMap = {} - -export default class Audio extends HTMLAudioElement { - - constructor(url) { - super() - - this._$sn = SN_SEED++; - - this.HAVE_NOTHING = HAVE_NOTHING - this.HAVE_METADATA = HAVE_METADATA - this.HAVE_CURRENT_DATA = HAVE_CURRENT_DATA - this.HAVE_FUTURE_DATA = HAVE_FUTURE_DATA - this.HAVE_ENOUGH_DATA = HAVE_ENOUGH_DATA - - this.readyState = HAVE_NOTHING - - const innerAudioContext = tt.createInnerAudioContext() - - _innerAudioContextMap[this._$sn] = innerAudioContext - - this._canplayEvents = [ - 'load', - 'loadend', - 'canplay', - 'canplaythrough', - 'loadedmetadata' - ] - - innerAudioContext.onCanplay(() => { - this._loaded = true - this.readyState = this.HAVE_CURRENT_DATA - this._canplayEvents.forEach((type) => { - this.dispatchEvent({ type: type }) - }) - }) - innerAudioContext.onPlay(() => { - this._paused = _innerAudioContextMap[this._$sn].paused - this.dispatchEvent({ type: 'play' }) - }) - innerAudioContext.onPause(() => { - this._paused = _innerAudioContextMap[this._$sn].paused - this.dispatchEvent({ type: 'pause' }) - }) - innerAudioContext.onEnded(() => { - this._paused = _innerAudioContextMap[this._$sn].paused - if (_innerAudioContextMap[this._$sn].loop === false) { - this.dispatchEvent({ type: 'ended' }) - } - this.readyState = HAVE_ENOUGH_DATA - }) - innerAudioContext.onError(() => { - this._paused = _innerAudioContextMap[this._$sn].paused - this.dispatchEvent({ type: 'error' }) - }) - - if (url) { - this.src = url - } else { - this._src = '' - } - - this._loop = innerAudioContext.loop - this._autoplay = innerAudioContext.autoplay - this._paused = innerAudioContext.paused - this._volume = innerAudioContext.volume - this._muted = false; - } - - addEventListener(type, listener, options = {}) { - super.addEventListener(type, listener, options) - - type = String(type).toLowerCase() - - if (this._loaded && this._canplayEvents.indexOf(type) !== -1) { - this.dispatchEvent({ type: type }) - } - } - - load() { - // console.warn('HTMLAudioElement.load() is not implemented.') - // weixin doesn't need call load() manually - } - - play() { - _innerAudioContextMap[this._$sn].play() - } - - resume() { - _innerAudioContextMap[this._$sn].resume() - } - - pause() { - _innerAudioContextMap[this._$sn].pause() - } - - stop() { - _innerAudioContextMap[this._$sn].stop() - } - - destroy() { - _innerAudioContextMap[this._$sn].destroy() - } - - canPlayType(mediaType = '') { - if (typeof mediaType !== 'string') { - return '' - } - - if (mediaType.indexOf('audio/mpeg') > -1 || mediaType.indexOf('audio/mp4')) { - return 'probably' - } - return '' - } - - get currentTime() { - return _innerAudioContextMap[this._$sn].currentTime - } - - set currentTime(value) { - _innerAudioContextMap[this._$sn].seek(value) - } - - get duration () { - return _innerAudioContextMap[this._$sn].duration - } - - get src() { - return this._src - } - - set src(value) { - this._src = value - this._loaded = false - this.readyState = this.HAVE_NOTHING - - const innerAudioContext = _innerAudioContextMap[this._$sn] - - innerAudioContext.src = value - } - - get loop() { - return this._loop - } - - set loop(value) { - this._loop = value - _innerAudioContextMap[this._$sn].loop = value - } - - get autoplay() { - return this.autoplay - } - - set autoplay(value) { - this._autoplay = value - _innerAudioContextMap[this._$sn].autoplay = value - } - - get paused() { - return this._paused; - } - - get volume() { - return this._volume; - } - - set volume(value) { - this._volume = value; - if (!this._muted) { - _innerAudioContextMap[this._$sn].volume = value; - } - } - - get muted() { - return this._muted; - } - - set muted(value) { - this._muted = value; - if (value) { - _innerAudioContextMap[this._$sn].volume = 0; - } else { - _innerAudioContextMap[this._$sn].volume = this._volume; - } - } - - cloneNode() { - const newAudio = new Audio() - newAudio.loop = this.loop - newAudio.autoplay = this.autoplay - newAudio.src = this.src - return newAudio - } -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/Canvas.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/Canvas.js deleted file mode 100644 index 051f099855..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/Canvas.js +++ /dev/null @@ -1,64 +0,0 @@ -// import HTMLCanvasElement from './HTMLCanvasElement' -import { innerWidth, innerHeight } from './WindowProperties' - -let hasModifiedCanvasPrototype = false -let hasInit2DContextConstructor = false -let hasInitWebGLContextConstructor = false - -export default function Canvas() { - const canvas = tt.createCanvas() - - canvas.type = 'canvas' - - // canvas.__proto__.__proto__.__proto__ = new HTMLCanvasElement() - - const _getContext = canvas.getContext - - canvas.getBoundingClientRect = () => { - const ret = { - top: 0, - left: 0, - width: window.innerWidth, - height: window.innerHeight - } - return ret - } - - canvas.style = { - top: '0px', - left: '0px', - width: innerWidth + 'px', - height: innerHeight + 'px', - } - - canvas.addEventListener = function (type, listener, options = {}) { - // console.log('canvas.addEventListener', type); - document.addEventListener(type, listener, options); - } - - canvas.removeEventListener = function (type, listener) { - // console.log('canvas.removeEventListener', type); - document.removeEventListener(type, listener); - } - - canvas.dispatchEvent = function (event = {}) { - console.log('canvas.dispatchEvent' , event.type, event); - // nothing to do - } - - Object.defineProperty(canvas, 'clientWidth', { - enumerable: true, - get: function get() { - return innerWidth - } - }) - - Object.defineProperty(canvas, 'clientHeight', { - enumerable: true, - get: function get() { - return innerHeight - } - }) - - return canvas -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/Element.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/Element.js deleted file mode 100644 index 965cd80d17..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/Element.js +++ /dev/null @@ -1,10 +0,0 @@ -import Node from './Node' - -export default class Element extends Node { - className = '' - children = [] - - constructor() { - super() - } -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/Event.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/Event.js deleted file mode 100644 index a7adc6a57b..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/Event.js +++ /dev/null @@ -1,14 +0,0 @@ -import {noop} from './util' - -export default class Event { - cancelBubble = false - cancelable = false - target = null - timestampe = Date.now() - preventDefault = noop - stopPropagation = noop - - constructor(type) { - this.type = type - } -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/EventIniter/MouseEvent.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/EventIniter/MouseEvent.js deleted file mode 100644 index 4a81e54c75..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/EventIniter/MouseEvent.js +++ /dev/null @@ -1,5 +0,0 @@ -export default class MouseEvent { - constructor() { - - } -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/EventIniter/TouchEvent.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/EventIniter/TouchEvent.js deleted file mode 100644 index d00dc5e1fc..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/EventIniter/TouchEvent.js +++ /dev/null @@ -1,32 +0,0 @@ -import { noop } from '../util/index.js' - -export default class TouchEvent { - touches = [] - targetTouches = [] - changedTouches = [] - preventDefault = noop - stopPropagation = noop - - constructor(type) { - this.type = type - this.target = window.canvas - this.currentTarget = window.canvas - } -} - -function touchEventHandlerFactory(type) { - return (event) => { - const touchEvent = new TouchEvent(type) - - touchEvent.touches = event.touches - touchEvent.targetTouches = Array.prototype.slice.call(event.touches) - touchEvent.changedTouches = event.changedTouches - touchEvent.timeStamp = event.timeStamp - document.dispatchEvent(touchEvent) - } -} - -tt.onTouchStart(touchEventHandlerFactory('touchstart')) -tt.onTouchMove(touchEventHandlerFactory('touchmove')) -tt.onTouchEnd(touchEventHandlerFactory('touchend')) -tt.onTouchCancel(touchEventHandlerFactory('touchcancel')) diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/EventIniter/index.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/EventIniter/index.js deleted file mode 100644 index 5b5ffd24ff..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/EventIniter/index.js +++ /dev/null @@ -1,2 +0,0 @@ -export TouchEvent from './TouchEvent' -export MouseEvent from './MouseEvent' \ No newline at end of file diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/EventTarget.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/EventTarget.js deleted file mode 100644 index 573c3dbc9e..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/EventTarget.js +++ /dev/null @@ -1,57 +0,0 @@ -const _events = new WeakMap() - -export default class EventTarget { - constructor() { - _events.set(this, {}) - } - - addEventListener(type, listener, options = {}) { - let events = _events.get(this) - - if (!events) { - events = {} - _events.set(this, events) - } - if (!events[type]) { - events[type] = [] - } - events[type].push(listener) - - if (options.capture) { - // console.warn('EventTarget.addEventListener: options.capture is not implemented.') - } - if (options.once) { - // console.warn('EventTarget.addEventListener: options.once is not implemented.') - } - if (options.passive) { - // console.warn('EventTarget.addEventListener: options.passive is not implemented.') - } - } - - removeEventListener(type, listener) { - const events = _events.get(this) - - if (events) { - const listeners = events[type] - - if (listeners && listeners.length > 0) { - for (let i = listeners.length; i--; i > 0) { - if (listeners[i] === listener) { - listeners.splice(i, 1) - break - } - } - } - } - } - - dispatchEvent(event = {}) { - const listeners = _events.get(this)[event.type] - - if (listeners) { - for (let i = 0; i < listeners.length; i++) { - listeners[i](event) - } - } - } -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/FileReader.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/FileReader.js deleted file mode 100644 index 375184a007..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/FileReader.js +++ /dev/null @@ -1,7 +0,0 @@ -/* - * TODO 使用 tt.readFile 来封装 FileReader - */ -export default class FileReader { - construct() { - } -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLAudioElement.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLAudioElement.js deleted file mode 100644 index c6facfba2d..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLAudioElement.js +++ /dev/null @@ -1,7 +0,0 @@ -import HTMLMediaElement from './HTMLMediaElement' - -export default class HTMLAudioElement extends HTMLMediaElement { - constructor() { - super('audio') - } -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLCanvasElement.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLCanvasElement.js deleted file mode 100644 index b4b9c9c1db..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLCanvasElement.js +++ /dev/null @@ -1,20 +0,0 @@ -// import HTMLElement from './HTMLElement'; - -// export default class HTMLCanvasElement extends HTMLElement -// { -// constructor(){ -// super('canvas') -// } -// }; - -import Canvas from './Canvas' -import HTMLElement from './HTMLElement' - -GameGlobal.screencanvas = GameGlobal.screencanvas || new Canvas(); -const canvas = GameGlobal.screencanvas; - -const canvasConstructor = canvas.constructor; - -// canvasConstructor.__proto__.__proto__ = new HTMLElement(); - -export default canvasConstructor; diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLElement.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLElement.js deleted file mode 100644 index 51040f3c6e..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLElement.js +++ /dev/null @@ -1,54 +0,0 @@ -import Element from './Element' -import { noop } from './util/index.js' -import { innerWidth, innerHeight } from './WindowProperties' - -export default class HTMLElement extends Element { - className = '' - childern = [] - style = { - width: `${innerWidth}px`, - height: `${innerHeight}px` - } - - insertBefore = noop - - innerHTML = '' - - constructor(tagName = '') { - super() - this.tagName = tagName.toUpperCase() - } - - setAttribute(name, value) { - this[name] = value - } - - getAttribute(name) { - return this[name] - } - - get clientWidth() { - const ret = parseInt(this.style.fontSize, 10) * this.innerHTML.length - - return Number.isNaN(ret) ? 0 : ret - } - - get clientHeight() { - const ret = parseInt(this.style.fontSize, 10) - - return Number.isNaN(ret) ? 0 : ret - } - - getBoundingClientRect() { - return { - top: 0, - left: 0, - width: innerWidth, - height: innerHeight - } - } - - focus() { - - } -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLImageElement.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLImageElement.js deleted file mode 100644 index 6630450685..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLImageElement.js +++ /dev/null @@ -1,16 +0,0 @@ -// import HTMLElement from './HTMLElement'; - -// export default class HTMLImageElement extends HTMLElement -// { -// constructor(){ -// super('img') -// } -// }; - -import HTMLElement from './HTMLElement' - -const imageConstructor = tt.createImage().constructor; - -// imageConstructor.__proto__.__proto__ = new HTMLElement(); - -export default imageConstructor; diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLMediaElement.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLMediaElement.js deleted file mode 100644 index a4b39a5445..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLMediaElement.js +++ /dev/null @@ -1,25 +0,0 @@ -import HTMLElement from './HTMLElement' - -export default class HTMLMediaElement extends HTMLElement { - constructor(type) { - super(type) - } - - addTextTrack() { - } - - captureStream() { - } - - fastSeek() { - } - - load() { - } - - pause() { - } - - play() { - } -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLVideoElement.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLVideoElement.js deleted file mode 100644 index 79be0e019a..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/HTMLVideoElement.js +++ /dev/null @@ -1,8 +0,0 @@ -import HTMLMediaElement from './HTMLMediaElement'; - -export default class HTMLVideoElement extends HTMLMediaElement -{ - constructor(){ - super('video') - } -}; diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/Image.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/Image.js deleted file mode 100644 index 4ced0c1e48..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/Image.js +++ /dev/null @@ -1,9 +0,0 @@ -import HTMLImageElement from './HTMLImageElement' - -export default function() { - const image = tt.createImage(); - - // image.__proto__.__proto__.__proto__ = new HTMLImageElement(); - - return image; -}; diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/ImageBitmap.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/ImageBitmap.js deleted file mode 100644 index 94be70a760..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/ImageBitmap.js +++ /dev/null @@ -1,5 +0,0 @@ -export default class ImageBitmap { - constructor() { - // TODO - } -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/Node.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/Node.js deleted file mode 100644 index 6ebcbdc234..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/Node.js +++ /dev/null @@ -1,34 +0,0 @@ -import EventTarget from './EventTarget.js' - -export default class Node extends EventTarget { - constructor() { - super() - } - - childNodes = [] - - appendChild(node) { - this.childNodes.push(node) - // if (node instanceof Node) { - // this.childNodes.push(node) - // } else { - // throw new TypeError('Failed to executed \'appendChild\' on \'Node\': parameter 1 is not of type \'Node\'.') - // } - } - - cloneNode() { - const copyNode = Object.create(this) - - Object.assign(copyNode, this) - return copyNode - } - - removeChild(node) { - const index = this.childNodes.findIndex((child) => child === node) - - if (index > -1) { - return this.childNodes.splice(index, 1) - } - return null - } -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/WebGLRenderingContext.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/WebGLRenderingContext.js deleted file mode 100644 index bc62da5f49..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/WebGLRenderingContext.js +++ /dev/null @@ -1,5 +0,0 @@ -export default class WebGLRenderingContext { - constructor() { - // TODO - } -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/WebSocket.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/WebSocket.js deleted file mode 100644 index 6339fece14..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/WebSocket.js +++ /dev/null @@ -1,87 +0,0 @@ -const _socketTask = new WeakMap() - -export default class WebSocket { - static CONNECTING = 0 // The connection is not yet open. - static OPEN = 1 // The connection is open and ready to communicate. - static CLOSING = 2 // The connection is in the process of closing. - static CLOSED = 3 // The connection is closed or couldn't be opened. - - binaryType = '' // TODO 更新 binaryType - bufferedAmount = 0 // TODO 更新 bufferedAmount - extensions = '' - - onclose = null - onerror = null - onmessage = null - onopen = null - - protocol = '' // TODO 小程序内目前获取不到,实际上需要根据服务器选择的 sub-protocol 返回 - readyState = 3 - - constructor(url, protocols = []) { - if (typeof url !== 'string' || !(/(^ws:\/\/)|(^wss:\/\/)/).test(url)) { - throw new TypeError(`Failed to construct 'WebSocket': The URL '${url}' is invalid`) - } - - this.url = url - this.readyState = WebSocket.CONNECTING - - const socketTask = tt.connectSocket({ - url, - protocols: Array.isArray(protocols) ? protocols : [protocols], - tcpNoDelay: true - }) - - _socketTask.set(this, socketTask) - - socketTask.onClose((res) => { - this.readyState = WebSocket.CLOSED - if (typeof this.onclose === 'function') { - this.onclose(res) - } - }) - - socketTask.onMessage((res) => { - if (typeof this.onmessage === 'function') { - this.onmessage(res) - } - }) - - socketTask.onOpen(() => { - this.readyState = WebSocket.OPEN - if (typeof this.onopen === 'function') { - this.onopen() - } - }) - - socketTask.onError((res) => { - if (typeof this.onerror === 'function') { - this.onerror(new Error(res.errMsg)) - } - }) - - return this - } - - close(code, reason) { - this.readyState = WebSocket.CLOSING - const socketTask = _socketTask.get(this) - - socketTask.close({ - code, - reason - }) - } - - send(data) { - if (typeof data !== 'string' && !(data instanceof ArrayBuffer) && !ArrayBuffer.isView(data)) { - throw new TypeError(`Failed to send message: The data ${data} is invalid`) - } - - const socketTask = _socketTask.get(this) - - socketTask.send({ - data - }) - } -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/WindowProperties.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/WindowProperties.js deleted file mode 100644 index ecf5067fa7..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/WindowProperties.js +++ /dev/null @@ -1,21 +0,0 @@ -const { screenWidth, screenHeight, devicePixelRatio } = tt.getSystemInfoSync() - -export const innerWidth = screenWidth -export const innerHeight = screenHeight -export { devicePixelRatio } -export const screen = { - width: screenWidth, - height: screenHeight, - availWidth: innerWidth, - availHeight: innerHeight, - availLeft: 0, - availTop: 0, -} - -export const performance = { - now: Date.now -}; - -export const ontouchstart = null; -export const ontouchmove = null; -export const ontouchend = null; \ No newline at end of file diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/Worker.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/Worker.js deleted file mode 100644 index 299bc417b3..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/Worker.js +++ /dev/null @@ -1,5 +0,0 @@ -export default function(file) { - const worker = tt.createWorker(file); - - return worker; -}; diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/XMLHttpRequest.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/XMLHttpRequest.js deleted file mode 100644 index d166f12b60..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/XMLHttpRequest.js +++ /dev/null @@ -1,170 +0,0 @@ -import EventTarget from './EventTarget.js' - -const _url = new WeakMap() -const _method = new WeakMap() -const _requestHeader = new WeakMap() -const _responseHeader = new WeakMap() -const _requestTask = new WeakMap() - -function _triggerEvent(type, ...args) { - if (typeof this[`on${type}`] === 'function') { - this[`on${type}`].apply(this, args) - } -} - -function _changeReadyState(readyState) { - this.readyState = readyState - _triggerEvent.call(this, 'readystatechange') -} - -export default class XMLHttpRequest extends EventTarget { - // TODO 没法模拟 HEADERS_RECEIVED 和 LOADING 两个状态 - static UNSEND = 0 - static OPENED = 1 - static HEADERS_RECEIVED = 2 - static LOADING = 3 - static DONE = 4 - - /* - * TODO 这一批事件应该是在 XMLHttpRequestEventTarget.prototype 上面的 - */ - onabort = null - onerror = null - onload = null - onloadstart = null - onprogress = null - ontimeout = null - onloadend = null - - onreadystatechange = null - readyState = 0 - response = null - responseText = null - responseType = '' - responseXML = null - status = 0 - statusText = '' - upload = {} - withCredentials = false - - constructor() { - super(); - - _requestHeader.set(this, { - 'content-type': 'application/x-www-form-urlencoded' - }) - _responseHeader.set(this, {}) - } - - abort() { - const myRequestTask = _requestTask.get(this) - - if (myRequestTask) { - myRequestTask.abort() - } - } - - getAllResponseHeaders() { - const responseHeader = _responseHeader.get(this) - - return Object.keys(responseHeader).map((header) => { - return `${header}: ${responseHeader[header]}` - }).join('\n') - } - - getResponseHeader(header) { - return _responseHeader.get(this)[header] - } - - open(method, url/* async, user, password 这几个参数在小程序内不支持*/) { - _method.set(this, method) - _url.set(this, url) - _changeReadyState.call(this, XMLHttpRequest.OPENED) - } - - overrideMimeType() { - } - - send(data = '') { - if (this.readyState !== XMLHttpRequest.OPENED) { - throw new Error("Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.") - } else { - let myRequestTask = tt.request({ - data, - url: _url.get(this), - method: _method.get(this), - header: _requestHeader.get(this), - dataType: 'other', - responseType: this.responseType === 'arraybuffer' ? 'arraybuffer' : 'text', - success: ({ data, statusCode, header }) => { - this.status = statusCode - _responseHeader.set(this, header) - _triggerEvent.call(this, 'loadstart') - _changeReadyState.call(this, XMLHttpRequest.HEADERS_RECEIVED) - _changeReadyState.call(this, XMLHttpRequest.LOADING) - - switch (this.responseType) { - case 'json': - this.responseText = data; - try { - this.response = JSON.parse(data); - } - catch (e) { - this.response = null; - } - break; - case '': - case 'text': - this.responseText = this.response = data; - break; - case 'arraybuffer': - this.response = data; - this.responseText = ''; - var bytes = new Uint8Array(data); - var len = bytes.byteLength; - - for (var i = 0; i < len; i++) { - this.responseText += String.fromCharCode(bytes[i]); - } - break; - default: - this.response = null; - } - _changeReadyState.call(this, XMLHttpRequest.DONE) - _triggerEvent.call(this, 'load') - _triggerEvent.call(this, 'loadend') - }, - fail: ({ errMsg }) => { - // TODO 规范错误 - if (errMsg.indexOf('abort') !== -1) { - _triggerEvent.call(this, 'abort') - } else if (errMsg.indexOf('timeout') !== -1) { - _triggerEvent.call(this, 'timeout') - } else { - _triggerEvent.call(this, 'error', errMsg) - } - _triggerEvent.call(this, 'loadend') - } - }) - - _requestTask.set(this, myRequestTask); - } - } - - setRequestHeader(header, value) { - const myHeader = _requestHeader.get(this) - - myHeader[header] = value - _requestHeader.set(this, myHeader) - } - - addEventListener(type, listener) { - if (typeof listener === 'function') { - let _this = this - let event = { target: _this } - this['on' + type] = function (event) { - listener.call(_this, event) - } - } - } -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/document.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/document.js deleted file mode 100644 index 9f8f0dc96b..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/document.js +++ /dev/null @@ -1,127 +0,0 @@ -import * as window from './window' -import HTMLElement from './HTMLElement' -import HTMLVideoElement from './HTMLVideoElement' -import Image from './Image' -import Audio from './Audio' -import Canvas from './Canvas' -import './EventIniter/index.js' - -const events = {} - -const document = { - readyState: 'complete', - visibilityState: 'visible', - documentElement: window, - hidden: false, - style: {}, - location: window.location, - ontouchstart: null, - ontouchmove: null, - ontouchend: null, - - head: new HTMLElement('head'), - body: new HTMLElement('body'), - - createElement(tagName) { - if (tagName === 'canvas') { - return new Canvas() - } else if (tagName === 'audio') { - return new Audio() - } else if (tagName === 'img') { - return new Image() - }else if (tagName === 'video') { - return new HTMLVideoElement() - } - - return new HTMLElement(tagName) - }, - - createElementNS(nameSpace, tagName) { - return this.createElement(tagName); - }, - - getElementById(id) { - if (id === window.canvas.id) { - return window.canvas - } - return null - }, - - getElementsByTagName(tagName) { - if (tagName === 'head') { - return [document.head] - } else if (tagName === 'body') { - return [document.body] - } else if (tagName === 'canvas') { - return [window.canvas] - } - return [] - }, - - getElementsByName(tagName) { - if (tagName === 'head') { - return [document.head] - } else if (tagName === 'body') { - return [document.body] - } else if (tagName === 'canvas') { - return [window.canvas] - } - return [] - }, - - querySelector(query) { - if (query === 'head') { - return document.head - } else if (query === 'body') { - return document.body - } else if (query === 'canvas') { - return window.canvas - } else if (query === `#${window.canvas.id}`) { - return window.canvas - } - return null - }, - - querySelectorAll(query) { - if (query === 'head') { - return [document.head] - } else if (query === 'body') { - return [document.body] - } else if (query === 'canvas') { - return [window.canvas] - } - return [] - }, - - addEventListener(type, listener) { - if (!events[type]) { - events[type] = [] - } - events[type].push(listener) - }, - - removeEventListener(type, listener) { - const listeners = events[type] - - if (listeners && listeners.length > 0) { - for (let i = listeners.length; i--; i > 0) { - if (listeners[i] === listener) { - listeners.splice(i, 1) - break - } - } - } - }, - - dispatchEvent(event) { - const listeners = events[event.type] - - if (listeners) { - for (let i = 0; i < listeners.length; i++) { - listeners[i](event) - } - } - } -} - -export default document diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/index.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/index.js deleted file mode 100644 index f1dc5822cd..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/index.js +++ /dev/null @@ -1,64 +0,0 @@ -import * as _window from './window'; -import document from './document'; -import HTMLElement from './HTMLElement'; - -const global = GameGlobal; - -function inject () { - _window.document = document; - - _window.addEventListener = (type, listener) => { - _window.document.addEventListener(type, listener); - }; - _window.removeEventListener = (type, listener) => { - _window.document.removeEventListener(type, listener); - }; - _window.dispatchEvent = function (event = {}) { - console.log('window.dispatchEvent', event.type, event); - // nothing to do - }; - - const { platform } = tt.getSystemInfoSync(); - - // 开发者工具无法重定义 window - if (typeof __devtoolssubcontext === 'undefined' && platform === 'devtools') { - for (const key in _window) { - const descriptor = Object.getOwnPropertyDescriptor(global, key); - - if (!descriptor || descriptor.configurable === true) { - Object.defineProperty(window, key, { - value: _window[key], - }); - } - } - - for (const key in _window.document) { - const descriptor = Object.getOwnPropertyDescriptor(global.document, key); - - if (!descriptor || descriptor.configurable === true) { - Object.defineProperty(global.document, key, { - value: _window.document[key], - }); - } - } - window.parent = window; - } else { - for (const key in _window) { - global[key] = _window[key]; - } - global.window = _window; - window = global; - window.top = window.parent = window; - GameGlobal.global = GameGlobal.global || GameGlobal; - } -} - -if (!GameGlobal.__isAdapterInjected) { - GameGlobal.__isAdapterInjected = true; - inject(); -} - -global.WebAssembly = global.CCWebAssembly = global.TTWebAssembly; - -require('../../../../common/xmldom/dom-parser'); -require('../unify'); diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/localStorage.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/localStorage.js deleted file mode 100644 index 7b89915f6f..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/localStorage.js +++ /dev/null @@ -1,31 +0,0 @@ -const localStorage = { - get length() { - const { keys } = tt.getStorageInfoSync() - - return keys.length - }, - - key(n) { - const { keys } = tt.getStorageInfoSync() - - return keys[n] - }, - - getItem(key) { - return tt.getStorageSync(key) - }, - - setItem(key, value) { - return tt.setStorageSync(key, value) - }, - - removeItem(key) { - tt.removeStorageSync(key) - }, - - clear() { - tt.clearStorageSync() - } -} - -export default localStorage diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/location.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/location.js deleted file mode 100644 index b1da72019f..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/location.js +++ /dev/null @@ -1,8 +0,0 @@ -const location = { - href: 'game.js', - protocol: '', - reload() { - } -} - -export default location diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/navigator.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/navigator.js deleted file mode 100644 index 26c6556b37..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/navigator.js +++ /dev/null @@ -1,38 +0,0 @@ -import { noop } from './util/index.js' - -// TODO 需要 tt.getSystemInfo 获取更详细信息 -const systemInfo = tt.getSystemInfoSync() -console.log(systemInfo) - -const system = systemInfo.system; -const platform = systemInfo.platform; -const language = systemInfo.language; -const wechatVersioin = systemInfo.version; - -const android = system.toLowerCase().indexOf('android') !== -1; - -const uaDesc = android ? `Android; CPU ${system}` : `iPhone; CPU iPhone OS ${system} like Mac OS X`; -const ua = `Mozilla/5.0 (${uaDesc}) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E8301 MicroMessenger/${wechatVersioin} MiniGame NetType/WIFI Language/${language}`; - -const navigator = { - platform, - language: language, - appVersion: `5.0 (${uaDesc}) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1`, - userAgent: ua, - onLine: true, // TODO 用 tt.getNetworkStateChange 和 tt.onNetworkStateChange 来返回真实的状态 - - // TODO 用 tt.getLocation 来封装 geolocation - geolocation: { - getCurrentPosition: noop, - watchPosition: noop, - clearWatch: noop - } -} - -if (tt.onNetworkStatusChange) { - tt.onNetworkStatusChange(function(event){ - navigator.onLine = event.isConnected; - }); -} - -export default navigator diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/util/index.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/util/index.js deleted file mode 100644 index 177804c7ab..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/util/index.js +++ /dev/null @@ -1 +0,0 @@ -export function noop() {} diff --git a/platforms/minigame/platforms/bytedance/wrapper/builtin/window.js b/platforms/minigame/platforms/bytedance/wrapper/builtin/window.js deleted file mode 100644 index 20c49aa2bb..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/builtin/window.js +++ /dev/null @@ -1,41 +0,0 @@ -import Canvas from './Canvas' - -export navigator from './navigator' -export XMLHttpRequest from './XMLHttpRequest' -export WebSocket from './WebSocket' -export Image from './Image' -export ImageBitmap from './ImageBitmap' -export Audio from './Audio' -export FileReader from './FileReader' -export HTMLElement from './HTMLElement' -export HTMLImageElement from './HTMLImageElement' -export HTMLCanvasElement from './HTMLCanvasElement' -export HTMLMediaElement from './HTMLMediaElement' -export HTMLAudioElement from './HTMLAudioElement' -export HTMLVideoElement from './HTMLVideoElement' -export WebGLRenderingContext from './WebGLRenderingContext' -export { TouchEvent, MouseEvent, DeviceMotionEvent } from './EventIniter/index.js' -export localStorage from './localStorage' -export location from './location' -export * from './WindowProperties' - -// 暴露全局的 canvas -GameGlobal.screencanvas = GameGlobal.screencanvas || new Canvas() -const canvas = GameGlobal.screencanvas; - -const { - setTimeout, - setInterval, - clearTimeout, - clearInterval, - requestAnimationFrame, - cancelAnimationFrame, -} = GameGlobal; - -export { canvas } -export { setTimeout } -export { setInterval } -export { clearTimeout } -export { clearInterval } -export { requestAnimationFrame } -export { cancelAnimationFrame } diff --git a/platforms/minigame/platforms/bytedance/wrapper/engine/Label.js b/platforms/minigame/platforms/bytedance/wrapper/engine/Label.js deleted file mode 100644 index 9dd80290a5..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/engine/Label.js +++ /dev/null @@ -1,24 +0,0 @@ -if (cc && cc.Label) { - // const gfx = cc.gfx; - const Label = cc.Label; - - // shared label canvas - const _sharedLabelCanvas = document.createElement('canvas'); - const _sharedLabelCanvasCtx = _sharedLabelCanvas.getContext('2d'); - const canvasData = { - canvas: _sharedLabelCanvas, - context: _sharedLabelCanvasCtx, - }; - - cc.game.on(cc.Game.EVENT_ENGINE_INITED, () => { - Object.assign(Label._canvasPool, { - get () { - return canvasData; - }, - - put () { - // do nothing - }, - }); - }); -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/engine/VideoPlayer.js b/platforms/minigame/platforms/bytedance/wrapper/engine/VideoPlayer.js deleted file mode 100644 index 16b188c0b8..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/engine/VideoPlayer.js +++ /dev/null @@ -1,364 +0,0 @@ -/**************************************************************************** - Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. - -https://www.cocos.com/ - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated 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. -****************************************************************************/ - -if (cc.internal.VideoPlayer) { - const { EventType } = cc.internal.VideoPlayer; - - const vec3 = cc.Vec3; - const _mat4_temp = cc.mat4(); - - const _topLeft = new vec3(); - const _bottomRight = new vec3(); - - const dpr = tt.getSystemInfoSync().pixelRatio; - - cc.internal.VideoPlayerImplManager.getImpl = function (componenet) { - return new VideoPlayerImplMiniGame(componenet); - }; - - class VideoPlayerImplMiniGame extends cc.internal.VideoPlayerImpl { - constructor (componenet) { - super(componenet); - this.videoNode = new cc.Node(); - this.videoNode.addComponent(cc.Sprite); - this.videoNode.layer = this._node.layer; - this._node.insertChild(this.videoNode, 0); - } - - syncClip (clip) { - this.removeVideoPlayer(); - if (!clip) { - return; - } - this.createVideoPlayer(clip._nativeAsset); - } - - syncURL (url) { - this.removeVideoPlayer(); - if (!url) { - return; - } - this.createVideoPlayer(url); - } - - onCanplay () { - if (this._loaded) { - return; - } - this._loaded = true; - this.setVisible(this._visible); - this.dispatchEvent(EventType.READY_TO_PLAY); - this.delayedPlay(); - } - - _bindEvent () { - const video = this._video; - const self = this; - - if (!video) { - return; - } - video.onCanplay(() => { - if (self._video !== video) return; - self._loaded = true; - self._playing = true; - try { - self.setVisible(self._visible); - self.dispatchEvent(EventType.READY_TO_PLAY); - video.play(); - this.videoTexture = new cc.Texture2D(); - this.videoTexture.reset({ - width: video.width, - height: video.height, - format: cc.Texture2D.PixelFormat.RGBA8888, - }); - const sprite = this.videoNode.getComponent(cc.Sprite); - const spriteFrame = new cc.SpriteFrame(); - spriteFrame.texture = this.videoTexture; - sprite.spriteFrame = spriteFrame; - } catch (err) { - console.error('Video playback error:', err); - } - }); - video.onPlay(() => { - if (self._video !== video) return; - self._playing = true; - self.dispatchEvent(EventType.PLAYING); - }); - video.onEnded(() => { - if (self._video !== video) return; - self._playing = false; - self._currentTime = self._duration; // ensure currentTime is at the end of duration - self.dispatchEvent(EventType.COMPLETED); - }); - video.onPause(() => { - if (self._video !== video) return; - self._playing = false; - self.dispatchEvent(EventType.PAUSED); - }); - video.onTimeUpdate((res) => { - self._duration = res.duration; - self._currentTime = res.position; - }); - video.onStop(() => { - if (self._video !== video) return; - self._playing = false; - self.dispatchEvent(EventType.STOPPED); - }); - } - - _unbindEvent () { - const video = this._video; - if (!video) { - return; - } - - video.offPlay(); - video.offEnded(); - video.offPause(); - video.offTimeUpdate(); - video.offStop(); - } - - createVideoPlayer (url) { - if (!tt.createVideo) { - console.warn('VideoPlayer not supported'); - return; - } - - if (!this._video) { - this._video = tt.createOffscreenVideo(); - this._duration = 0; - this._currentTime = 0; - this._loaded = false; - this.setVisible(this._visible); - this._bindEvent(); - this._forceUpdate = true; - } - - this.setURL(url); - this._forceUpdate = true; - } - - setURL (path) { - const self = this; - const video = self._video; - if (!video || video.src === path) { - return; - } - - if (self._playing) { - video.stop(); - } - self._unbindEvent(); - video.autoplay = true; - video.src = path; - video.muted = true; - - self._loaded = false; - function loadedCallback () { - self._bindEvent(); - video.muted = false; - self._loaded = true; - self.dispatchEvent(EventType.READY_TO_PLAY); - } - function endedCallback () { - video.offPlay(); - video.stop(); - self._playing = false; - self._currentTime = 0; - self.dispatchEvent(EventType.COMPLETED); - } - video.onPlay(loadedCallback); - video.onEnded(endedCallback); - } - - removeVideoPlayer () { - const video = this.video; - if (video) { - video.stop(); - video.destroy(); - this._playing = false; - this._loaded = false; - this._loadedMeta = false; - this._ignorePause = false; - this._cachedCurrentTime = 0; - this._video = null; - } - } - - setVisible (value) { - const video = this._video; - if (!video || this._visible === value) { - return; - } - if (value) { - video.width = this._actualWidth || 0; - } else { - video.width = 0; // hide video - } - this._visible = value; - } - - getDuration () { - return this.duration(); - } - - duration () { - return this._duration; - } - - syncPlaybackRate (value) { - const video = this._video; - if (video && value !== video.playbackRate) { - if (value === 0.5 | value === 0.8 | value === 1.0 | value === 1.25 | value === 1.5) { - video.playbackRate = value; - } else { - console.warn('The platform does not support this PlaybackRate!'); - } - } - } - - syncVolume () { - console.warn('The platform does not support'); - } - - syncMute (enable) { - const video = this._video; - if (video && video.muted !== enable) { - video.muted = enable; - } - } - - syncLoop (enable) { - const video = this._video; - if (video && video.loop !== enable) { - video.loop = enable; - } - } - - syncStayOnBottom () { - console.warn('The platform does not support'); - } - - getCurrentTime () { - if (this.video) { - return this.currentTime(); - } - return -1; - } - - currentTime () { - return this._currentTime; - } - - seekTo (time) { - const video = this._video; - if (!video || !this._loaded) return; - video.seek(time); - } - - disable (noPause) { - if (this._video) { - if (!noPause) { - this._video.pause(); - } - this.setVisible(false); - this._visible = false; - } - } - - enable () { - if (this._video) { - this.setVisible(true); - this._visible = true; - } - } - - canPlay () { - this._playing = true; - this._video.play(); - this.syncCurrentTime(); - } - - resume () { - const video = this._video; - if (this._playing || !video) return; - - video.play(); - } - - pause () { - const video = this._video; - if (!this._playing || !video) return; - - video.pause(); - } - - stop () { - const self = this; - const video = this._video; - if (!video || !this._visible) return; - video.stop().then((res) => { - if (res.errMsg && !res.errMsg.includes('ok')) { - console.error('failed to stop video player'); - return; - } - self._currentTime = 0; - self._playing = false; - self.dispatchEvent(EventType.STOPPED); - }); - } - - canFullScreen (enabled) { - if (this._video) { - this.setFullScreenEnabled(enabled); - } - } - - setFullScreenEnabled (enable) { - const video = this._video; - if (!video || this._fullScreenEnabled === enable) { - return; - } - if (enable) { - video.requestFullScreen(); - } else { - video.exitFullScreen(); - } - this._fullScreenEnabled = enable; - } - - syncKeepAspectRatio (enabled) { - console.warn('On bytedance game videoPlayer is always keep the aspect ratio'); - } - - syncMatrix () { - if (this.videoTexture) { - this.videoTexture.uploadData(this.video); - } - } - } -} diff --git a/platforms/minigame/platforms/bytedance/wrapper/engine/index.js b/platforms/minigame/platforms/bytedance/wrapper/engine/index.js deleted file mode 100644 index df2d40fbc2..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/engine/index.js +++ /dev/null @@ -1,4 +0,0 @@ -require('../fs-utils'); -require('../../../../common/engine/index'); -require('./VideoPlayer'); -require('./Label'); diff --git a/platforms/minigame/platforms/bytedance/wrapper/fs-utils.js b/platforms/minigame/platforms/bytedance/wrapper/fs-utils.js deleted file mode 100644 index c4ed505dcd..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/fs-utils.js +++ /dev/null @@ -1,270 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2019 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of fsUtils 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 fsUtils 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. - ****************************************************************************/ -/* eslint-disable no-undef */ - -const fs = tt.getFileSystemManager ? tt.getFileSystemManager() : null; -const outOfStorageRegExp = /size.*limit.*exceeded/; - -const fsUtils = { - - fs, - - isOutOfStorage (errMsg) { - return outOfStorageRegExp.test(errMsg); - }, - - getUserDataPath () { - return tt.env.USER_DATA_PATH; - }, - - checkFsValid () { - if (!fs) { - console.warn('can not get the file system!'); - return false; - } - return true; - }, - - deleteFile (filePath, onComplete) { - fs.unlink({ - filePath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Delete file failed: path: ${filePath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg)); - }, - }); - }, - - downloadFile (remoteUrl, filePath, header, onProgress, onComplete) { - const options = { - url: remoteUrl, - success (res) { - if (res.statusCode === 200) { - onComplete && onComplete(null, res.tempFilePath || res.filePath); - } else { - if (res.filePath) { - fsUtils.deleteFile(res.filePath); - } - console.warn(`Download file failed: path: ${remoteUrl} message: ${res.statusCode}`); - onComplete && onComplete(new Error(res.statusCode), null); - } - }, - fail (res) { - console.warn(`Download file failed: path: ${remoteUrl} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg), null); - }, - }; - if (filePath) options.filePath = filePath; - if (header) options.header = header; - const task = tt.downloadFile(options); - onProgress && task.onProgressUpdate(onProgress); - }, - - saveFile (srcPath, destPath, onComplete) { - tt.saveFile({ - tempFilePath: srcPath, - filePath: destPath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Save file failed: path: ${srcPath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg)); - }, - }); - }, - - copyFile (srcPath, destPath, onComplete) { - fs.copyFile({ - srcPath, - destPath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Copy file failed: path: ${srcPath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg)); - }, - }); - }, - - writeFile (path, data, encoding, onComplete) { - fs.writeFile({ - filePath: path, - encoding, - data, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Write file failed: path: ${path} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg)); - }, - }); - }, - - writeFileSync (path, data, encoding) { - try { - fs.writeFileSync(path, data, encoding); - return null; - } catch (e) { - console.warn(`Write file failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - readFile (filePath, encoding, onComplete) { - fs.readFile({ - filePath, - encoding, - success (res) { - onComplete && onComplete(null, res.data); - }, - fail (res) { - console.warn(`Read file failed: path: ${filePath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg), null); - }, - }); - }, - - readDir (filePath, onComplete) { - fs.readdir({ - dirPath: filePath, - success (res) { - onComplete && onComplete(null, res.files); - }, - fail (res) { - console.warn(`Read directory failed: path: ${filePath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg), null); - }, - }); - }, - - readText (filePath, onComplete) { - fsUtils.readFile(filePath, 'utf8', onComplete); - }, - - readArrayBuffer (filePath, onComplete) { - fsUtils.readFile(filePath, undefined, onComplete); - }, - - readJson (filePath, onComplete) { - fsUtils.readFile(filePath, 'utf8', (err, text) => { - let out = null; - if (!err) { - try { - out = JSON.parse(text); - } catch (e) { - console.warn(`Read json failed: path: ${filePath} message: ${e.message}`); - err = new Error(e.message); - } - } - onComplete && onComplete(err, out); - }); - }, - - readJsonSync (path) { - try { - const str = fs.readFileSync(path, 'utf8'); - return JSON.parse(str); - } catch (e) { - console.warn(`Read json failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - makeDirSync (path, recursive) { - try { - fs.mkdirSync(path, recursive); - return null; - } catch (e) { - console.warn(`Make directory failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - rmdirSync (dirPath, recursive) { - try { - fs.rmdirSync(dirPath, recursive); - return null; - } catch (e) { - console.warn(`rm directory failed: path: ${dirPath} message: ${e.message}`); - return new Error(e.message); - } - }, - - exists (filePath, onComplete) { - fs.access({ - path: filePath, - success () { - onComplete && onComplete(true); - }, - fail () { - onComplete && onComplete(false); - }, - }); - }, - - loadSubpackage (name, onProgress, onComplete) { - if (!tt.loadSubpackage) { - console.warn('tt.loadSubpackage not supported, fallback to loading bundle'); - // eslint-disable-next-line import/no-dynamic-require - require(`subpackages/${name}/game.js`); - onComplete && onComplete(); - return null; - } - const task = tt.loadSubpackage({ - name, - success () { - onComplete && onComplete(); - }, - fail (res) { - console.warn(`Load Subpackage failed: path: ${name} message: ${res.errMsg}`); - onComplete && onComplete(new Error(`Failed to load subpackage ${name}: ${res.errMsg}`)); - }, - }); - onProgress && task.onProgressUpdate(onProgress); - return task; - }, - - unzip (zipFilePath, targetPath, onComplete) { - fs.unzip({ - zipFilePath, - targetPath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`unzip failed: path: ${zipFilePath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(`unzip failed: ${res.errMsg}`)); - }, - }); - }, -}; - -window.fsUtils = module.exports = fsUtils; diff --git a/platforms/minigame/platforms/bytedance/wrapper/unify.js b/platforms/minigame/platforms/bytedance/wrapper/unify.js deleted file mode 100644 index 3125dcad5e..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/unify.js +++ /dev/null @@ -1,117 +0,0 @@ -const utils = require('./utils'); - -window.__globalAdapter = window.__globalAdapter || {}; -if (window.__globalAdapter) { - let globalAdapter = window.__globalAdapter; - // SystemInfo - let systemInfo = tt.getSystemInfoSync(); - let windowWidth = systemInfo.windowWidth; - let windowHeight = systemInfo.windowHeight; - let isLandscape = windowWidth > windowHeight; - globalAdapter.isSubContext = (tt.getOpenDataContext === undefined); - globalAdapter.isDevTool = (systemInfo.platform === 'devtools'); - utils.cloneMethod(globalAdapter, tt, 'getSystemInfoSync'); - - // TouchEvent - utils.cloneMethod(globalAdapter, tt, 'onTouchStart'); - utils.cloneMethod(globalAdapter, tt, 'onTouchMove'); - utils.cloneMethod(globalAdapter, tt, 'onTouchEnd'); - utils.cloneMethod(globalAdapter, tt, 'onTouchCancel'); - - // Audio - utils.cloneMethod(globalAdapter, tt, 'createInnerAudioContext'); - - // Video - utils.cloneMethod(globalAdapter, tt, 'createVideo'); - - // FrameRate - utils.cloneMethod(globalAdapter, tt, 'setPreferredFramesPerSecond'); - - // Keyboard - utils.cloneMethod(globalAdapter, tt, 'showKeyboard'); - utils.cloneMethod(globalAdapter, tt, 'hideKeyboard'); - utils.cloneMethod(globalAdapter, tt, 'updateKeyboard'); - utils.cloneMethod(globalAdapter, tt, 'onKeyboardInput'); - utils.cloneMethod(globalAdapter, tt, 'onKeyboardConfirm'); - utils.cloneMethod(globalAdapter, tt, 'onKeyboardComplete'); - utils.cloneMethod(globalAdapter, tt, 'offKeyboardInput'); - utils.cloneMethod(globalAdapter, tt, 'offKeyboardConfirm'); - utils.cloneMethod(globalAdapter, tt, 'offKeyboardComplete'); - - // Message - utils.cloneMethod(globalAdapter, tt, 'getOpenDataContext'); - utils.cloneMethod(globalAdapter, tt, 'onMessage'); - - // Subpackage not supported - // utils.cloneMethod(globalAdapter, tt, 'loadSubpackage'); - - // SharedCanvas - utils.cloneMethod(globalAdapter, tt, 'getSharedCanvas'); - - // Font - utils.cloneMethod(globalAdapter, tt, 'loadFont'); - - // hide show Event - utils.cloneMethod(globalAdapter, tt, 'onShow'); - utils.cloneMethod(globalAdapter, tt, 'onHide'); - - // onError - utils.cloneMethod(globalAdapter, tt, 'onError'); - // offError - utils.cloneMethod(globalAdapter, tt, 'offError'); - - // Accelerometer - let isAccelerometerInit = false; - let deviceOrientation = 1; - if (tt.onDeviceOrientationChange) { - tt.onDeviceOrientationChange(function (res) { - if (res.value === 'landscape') { - deviceOrientation = 1; - } - else if (res.value === 'landscapeReverse') { - deviceOrientation = -1; - } - }); - } - Object.assign(globalAdapter, { - startAccelerometer (cb) { - if (!isAccelerometerInit) { - isAccelerometerInit = true; - tt.onAccelerometerChange && tt.onAccelerometerChange(function (res) { - let resClone = {}; - let x = res.x; - let y = res.y; - if (isLandscape) { - let tmp = x; - x = -y; - y = tmp; - } - - resClone.x = x * deviceOrientation; - resClone.y = y * deviceOrientation; - resClone.z = res.z; - cb && cb(resClone); - }); - } - else { - tt.startAccelerometer && tt.startAccelerometer({ - fail (err) { - console.error('start accelerometer failed', err); - }, - // success () {}, - // complete () {}, - }); - } - }, - - stopAccelerometer () { - tt.stopAccelerometer && tt.stopAccelerometer({ - fail (err) { - console.error('stop accelerometer failed', err); - }, - // success () {}, - // complete () {}, - }); - }, - }); -} \ No newline at end of file diff --git a/platforms/minigame/platforms/bytedance/wrapper/utils.js b/platforms/minigame/platforms/bytedance/wrapper/utils.js deleted file mode 100644 index 947fc06958..0000000000 --- a/platforms/minigame/platforms/bytedance/wrapper/utils.js +++ /dev/null @@ -1,16 +0,0 @@ -let utils = { - /** - * @param {Object} target - * @param {Object} origin - * @param {String} methodName - * @param {String} targetMethodName - */ - cloneMethod (target, origin, methodName, targetMethodName) { - if (origin[methodName]) { - targetMethodName = targetMethodName || methodName; - target[targetMethodName] = origin[methodName].bind(origin); - } - } -}; - -module.exports = utils; \ No newline at end of file diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Audio.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Audio.js deleted file mode 100644 index 92ffc210b4..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Audio.js +++ /dev/null @@ -1,205 +0,0 @@ -import HTMLAudioElement from './HTMLAudioElement' - -const HAVE_NOTHING = 0 -const HAVE_METADATA = 1 -const HAVE_CURRENT_DATA = 2 -const HAVE_FUTURE_DATA = 3 -const HAVE_ENOUGH_DATA = 4 - -let SN_SEED = 1 - -const _innerAudioContextMap = {} - -export default class Audio extends HTMLAudioElement { - - constructor(url) { - super() - - this._$sn = SN_SEED++; - - this.HAVE_NOTHING = HAVE_NOTHING - this.HAVE_METADATA = HAVE_METADATA - this.HAVE_CURRENT_DATA = HAVE_CURRENT_DATA - this.HAVE_FUTURE_DATA = HAVE_FUTURE_DATA - this.HAVE_ENOUGH_DATA = HAVE_ENOUGH_DATA - - this.readyState = HAVE_NOTHING - - const innerAudioContext = my.createInnerAudioContext() - - _innerAudioContextMap[this._$sn] = innerAudioContext - - this._canplayEvents = [ - 'load', - 'loadend', - 'canplay', - 'canplaythrough', - 'loadedmetadata' - ] - - innerAudioContext.onCanplay(() => { - this._loaded = true - this.readyState = this.HAVE_CURRENT_DATA - this._canplayEvents.forEach((type) => { - this.dispatchEvent({ type: type }) - }) - }) - innerAudioContext.onPlay(() => { - this._paused = _innerAudioContextMap[this._$sn].paused - this.dispatchEvent({ type: 'play' }) - }) - innerAudioContext.onPause(() => { - this._paused = _innerAudioContextMap[this._$sn].paused - this.dispatchEvent({ type: 'pause' }) - }) - innerAudioContext.onEnded(() => { - this._paused = _innerAudioContextMap[this._$sn].paused - if (_innerAudioContextMap[this._$sn].loop === false) { - this.dispatchEvent({ type: 'ended' }) - } - this.readyState = HAVE_ENOUGH_DATA - }) - innerAudioContext.onError(() => { - this._paused = _innerAudioContextMap[this._$sn].paused - this.dispatchEvent({ type: 'error' }) - }) - - if (url) { - this.src = url - } else { - this._src = '' - } - - this._loop = innerAudioContext.loop - this._autoplay = innerAudioContext.autoplay - this._paused = innerAudioContext.paused - this._volume = innerAudioContext.volume - this._muted = false; - } - - addEventListener(type, listener, options = {}) { - super.addEventListener(type, listener, options) - - type = String(type).toLowerCase() - - if (this._loaded && this._canplayEvents.indexOf(type) !== -1) { - this.dispatchEvent({ type: type }) - } - } - - load() { - // console.warn('HTMLAudioElement.load() is not implemented.') - // weixin doesn't need call load() manually - } - - play() { - _innerAudioContextMap[this._$sn].play() - } - - resume() { - _innerAudioContextMap[this._$sn].resume() - } - - pause() { - _innerAudioContextMap[this._$sn].pause() - } - - stop() { - _innerAudioContextMap[this._$sn].stop() - } - - destroy() { - _innerAudioContextMap[this._$sn].destroy() - } - - canPlayType(mediaType = '') { - if (typeof mediaType !== 'string') { - return '' - } - - if (mediaType.indexOf('audio/mpeg') > -1 || mediaType.indexOf('audio/mp4')) { - return 'probably' - } - return '' - } - - get currentTime() { - return _innerAudioContextMap[this._$sn].currentTime - } - - set currentTime(value) { - _innerAudioContextMap[this._$sn].seek(value) - } - - get duration () { - return _innerAudioContextMap[this._$sn].duration - } - - get src() { - return this._src - } - - set src(value) { - this._src = value - this._loaded = false - this.readyState = this.HAVE_NOTHING - - const innerAudioContext = _innerAudioContextMap[this._$sn] - - innerAudioContext.src = value - } - - get loop() { - return this._loop - } - - set loop(value) { - this._loop = value - _innerAudioContextMap[this._$sn].loop = value - } - - get autoplay() { - return this.autoplay - } - - set autoplay(value) { - this._autoplay = value - _innerAudioContextMap[this._$sn].autoplay = value - } - - get paused() { - return this._paused; - } - - get volume() { - return this._volume; - } - - set volume(value) { - this._volume = value; - if (!this._muted) { - _innerAudioContextMap[this._$sn].volume = value; - } - } - - get muted() { - return this._muted; - } - - set muted(value) { - this._muted = value; - if (value) { - _innerAudioContextMap[this._$sn].volume = 0; - } else { - _innerAudioContextMap[this._$sn].volume = this._volume; - } - } - - cloneNode() { - const newAudio = new Audio() - newAudio.loop = this.loop - newAudio.autoplay = this.autoplay - newAudio.src = this.src - return newAudio - } -} diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Canvas.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Canvas.js deleted file mode 100644 index 76b7096ee1..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Canvas.js +++ /dev/null @@ -1,71 +0,0 @@ -function Canvas () {} - -const CanvasProxy = new Proxy(Canvas, { - construct () { - const canvas = my.createCanvas(); - - canvas.type = 'canvas'; - - // canvas.__proto__.__proto__.__proto__ = new HTMLCanvasElement() - - const _getContext = canvas.getContext; - - canvas.getBoundingClientRect = () => { - const ret = { - top: 0, - left: 0, - width: window.innerWidth, - height: window.innerHeight, - }; - return ret; - }; - - canvas.style = { - top: '0px', - left: '0px', - width: `${window.innerWidth}px`, - height: `${window.innerHeight}px`, - }; - - canvas.addEventListener = function (type, listener, options = {}) { - // console.log('canvas.addEventListener', type); - globalThis.document.addEventListener(type, listener, options); - }; - - canvas.removeEventListener = function (type, listener) { - // console.log('canvas.removeEventListener', type); - globalThis.document.removeEventListener(type, listener); - }; - - canvas.dispatchEvent = function (event = {}) { - console.log('canvas.dispatchEvent', event.type, event); - if (my.isIDE) { - globalThis.document.dispatchEvent(event); - } - }; - - Object.defineProperty(canvas, 'clientWidth', { - enumerable: true, - get: function get () { - return window.innerWidth; - }, - }); - - Object.defineProperty(canvas, 'clientHeight', { - enumerable: true, - get: function get () { - return window.innerHeight; - }, - }); - - return canvas; - }, -}); - -// Expose the global canvas -$global.screencanvas = $global.screencanvas || new CanvasProxy(); - -// NOTE: this is a hack operation -// let canvas = new window.Canvas() -// console.error(canvas instanceof window.Canvas) => false -export default CanvasProxy; diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Element.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Element.js deleted file mode 100644 index 965cd80d17..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Element.js +++ /dev/null @@ -1,10 +0,0 @@ -import Node from './Node' - -export default class Element extends Node { - className = '' - children = [] - - constructor() { - super() - } -} diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Event.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Event.js deleted file mode 100644 index a7adc6a57b..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Event.js +++ /dev/null @@ -1,14 +0,0 @@ -import {noop} from './util' - -export default class Event { - cancelBubble = false - cancelable = false - target = null - timestampe = Date.now() - preventDefault = noop - stopPropagation = noop - - constructor(type) { - this.type = type - } -} diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/EventTarget.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/EventTarget.js deleted file mode 100644 index 573c3dbc9e..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/EventTarget.js +++ /dev/null @@ -1,57 +0,0 @@ -const _events = new WeakMap() - -export default class EventTarget { - constructor() { - _events.set(this, {}) - } - - addEventListener(type, listener, options = {}) { - let events = _events.get(this) - - if (!events) { - events = {} - _events.set(this, events) - } - if (!events[type]) { - events[type] = [] - } - events[type].push(listener) - - if (options.capture) { - // console.warn('EventTarget.addEventListener: options.capture is not implemented.') - } - if (options.once) { - // console.warn('EventTarget.addEventListener: options.once is not implemented.') - } - if (options.passive) { - // console.warn('EventTarget.addEventListener: options.passive is not implemented.') - } - } - - removeEventListener(type, listener) { - const events = _events.get(this) - - if (events) { - const listeners = events[type] - - if (listeners && listeners.length > 0) { - for (let i = listeners.length; i--; i > 0) { - if (listeners[i] === listener) { - listeners.splice(i, 1) - break - } - } - } - } - } - - dispatchEvent(event = {}) { - const listeners = _events.get(this)[event.type] - - if (listeners) { - for (let i = 0; i < listeners.length; i++) { - listeners[i](event) - } - } - } -} diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/HTMLAudioElement.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/HTMLAudioElement.js deleted file mode 100644 index 0f60bd6b91..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/HTMLAudioElement.js +++ /dev/null @@ -1,7 +0,0 @@ -import HTMLElement from './HTMLElement' - -export default class HTMLAudioElement extends HTMLElement { - constructor() { - super('audio') - } -} diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/HTMLCanvasElement.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/HTMLCanvasElement.js deleted file mode 100644 index d9176a0ba8..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/HTMLCanvasElement.js +++ /dev/null @@ -1,10 +0,0 @@ -import Canvas from './Canvas' - -$global.screencanvas = $global.screencanvas || new Canvas(); -const canvas = $global.screencanvas; - -const canvasConstructor = canvas.constructor; - -// canvasConstructor.__proto__.__proto__ = new HTMLElement(); - -export default canvasConstructor; diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/HTMLElement.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/HTMLElement.js deleted file mode 100644 index 51040f3c6e..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/HTMLElement.js +++ /dev/null @@ -1,54 +0,0 @@ -import Element from './Element' -import { noop } from './util/index.js' -import { innerWidth, innerHeight } from './WindowProperties' - -export default class HTMLElement extends Element { - className = '' - childern = [] - style = { - width: `${innerWidth}px`, - height: `${innerHeight}px` - } - - insertBefore = noop - - innerHTML = '' - - constructor(tagName = '') { - super() - this.tagName = tagName.toUpperCase() - } - - setAttribute(name, value) { - this[name] = value - } - - getAttribute(name) { - return this[name] - } - - get clientWidth() { - const ret = parseInt(this.style.fontSize, 10) * this.innerHTML.length - - return Number.isNaN(ret) ? 0 : ret - } - - get clientHeight() { - const ret = parseInt(this.style.fontSize, 10) - - return Number.isNaN(ret) ? 0 : ret - } - - getBoundingClientRect() { - return { - top: 0, - left: 0, - width: innerWidth, - height: innerHeight - } - } - - focus() { - - } -} diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/HTMLImageElement.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/HTMLImageElement.js deleted file mode 100644 index f8096680c7..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/HTMLImageElement.js +++ /dev/null @@ -1,6 +0,0 @@ -import './Canvas' - -var screencanvas = $global.screencanvas; -let HTMLImageElement = screencanvas.createImage().constructor; - -export default HTMLImageElement; \ No newline at end of file diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Image.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Image.js deleted file mode 100644 index f693bfb28d..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Image.js +++ /dev/null @@ -1,7 +0,0 @@ -import './Canvas' - -function Image () { - return $global.screencanvas.createImage(); -} - -export default Image; diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/ImageBitmap.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/ImageBitmap.js deleted file mode 100644 index 1700abfb80..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/ImageBitmap.js +++ /dev/null @@ -1,5 +0,0 @@ -export default class ImageBitmap { - constructor () { - - } -} diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/MultiWebSocket.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/MultiWebSocket.js deleted file mode 100644 index 4be039cacb..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/MultiWebSocket.js +++ /dev/null @@ -1,91 +0,0 @@ -const _utils = require('../utils'); - -export default class MultiWebSocket { - static CONNECTING = 0 // The connection is not yet open. - static OPEN = 1 // The connection is open and ready to communicate. - static CLOSING = 2 // The connection is in the process of closing. - static CLOSED = 3 // The connection is closed or couldn't be opened. - - binaryType = '' // TODO: update binaryType - bufferedAmount = 0 // TODO: update bufferedAmount - extensions = '' - - onclose = null - onerror = null - onmessage = null - onopen = null - - protocol = '' // TODO: It is not currently available within the applet, but actually needs to be returned according to the sub-protocol selected by the server - readyState = 3 - - constructor(url, protocols = []) { - if (typeof url !== 'string' || !(/(^ws:\/\/)|(^wss:\/\/)/).test(url)) { - throw new TypeError(`Failed to construct 'WebSocket': The URL '${url}' is invalid`) - } - - this.url = url - this.readyState = MultiWebSocket.CONNECTING - - const socketTask = my.connectSocket({ - url, - multiple: true - }) - - this._socketTask = socketTask; - - socketTask.onClose((res) => { - this.readyState = MultiWebSocket.CLOSED - if (typeof this.onclose === 'function') { - this.onclose(res) - } - }) - - socketTask.onMessage((res) => { - if (typeof this.onmessage === 'function') { - if (res && res.data && res.data.data && res.data.isBuffer) { - res.isBuffer = res.data.isBuffer; - res.data = _utils.base64ToArrayBuffer(res.data.data); - } - this.onmessage(res) - } - }) - - socketTask.onOpen((res) => { - this.readyState = MultiWebSocket.OPEN - if (typeof this.onopen === 'function') { - this.onopen(res) - } - }) - - socketTask.onError((res) => { - if (typeof this.onerror === 'function') { - this.onerror(new Error(res.errMsg)) - } - }) - } - - close(code, reason) { - this.readyState = MultiWebSocket.CLOSING - - this._socketTask.close({ - code, - reason - }) - } - - send(data) { - if (typeof data !== 'string' && !(data instanceof ArrayBuffer) && !ArrayBuffer.isView(data)) { - throw new TypeError(`Failed to send message: The data ${data} is invalid`) - } - var isBuffer = false; - if (data instanceof ArrayBuffer) { - data = _utils.arrayBufferToBase64(data) - isBuffer = true - } - - this._socketTask.send({ - data, - isBuffer - }) - } -} \ No newline at end of file diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Node.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Node.js deleted file mode 100644 index 6ebcbdc234..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/Node.js +++ /dev/null @@ -1,34 +0,0 @@ -import EventTarget from './EventTarget.js' - -export default class Node extends EventTarget { - constructor() { - super() - } - - childNodes = [] - - appendChild(node) { - this.childNodes.push(node) - // if (node instanceof Node) { - // this.childNodes.push(node) - // } else { - // throw new TypeError('Failed to executed \'appendChild\' on \'Node\': parameter 1 is not of type \'Node\'.') - // } - } - - cloneNode() { - const copyNode = Object.create(this) - - Object.assign(copyNode, this) - return copyNode - } - - removeChild(node) { - const index = this.childNodes.findIndex((child) => child === node) - - if (index > -1) { - return this.childNodes.splice(index, 1) - } - return null - } -} diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/WebGLRenderingContext.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/WebGLRenderingContext.js deleted file mode 100644 index 7c4d15ed27..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/WebGLRenderingContext.js +++ /dev/null @@ -1,5 +0,0 @@ -export default class WebGLRenderingContext { - constructor() { - - } -} diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/WebSocket.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/WebSocket.js deleted file mode 100644 index d7bb82d3f8..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/WebSocket.js +++ /dev/null @@ -1,155 +0,0 @@ -const _utils = require('../utils'); - -const MAX_AMOUNT_WEBSOCKET = 1 // The maximum number of WEBSOCKET -let CURR_AMOUNT_WEBSOCKET = 0 // The current number of WEBSOCKET - -export default class WebSocket { - static CONNECTING = 0 // The connection is not yet open. - static OPEN = 1 // The connection is open and ready to communicate. - static CLOSING = 2 // The connection is in the process of closing. - static CLOSED = 3 // The connection is closed or couldn't be opened. - - binaryType = '' // TODO: update binaryType - bufferedAmount = 0 // TODO: update bufferedAmount - extensions = '' - - onopen = null - onmessage = null - onerror = null - onclose = null - - _onMessage = null - _onOpen = null - _onError = null - _onClose = null - _isReduced = false - - protocol = '' // TODO: It is not currently available within the applet, but actually needs to be returned according to the sub-protocol selected by the server - readyState = 3 - - constructor(url, protocols = []) { - if(this._isMaxCount()){ - console.warn(`Failed to construct 'WebSocket': Only ${CURR_AMOUNT_WEBSOCKET} WebSocket can be created at the same time on TaoBao.`); - return this; - } - - if (typeof url !== 'string' || !(/(^ws:\/\/)|(^wss:\/\/)/).test(url)) { - throw new TypeError(`Failed to construct 'WebSocket': The URL '${url}' is invalid`) - } - - this.url = url - this.readyState = WebSocket.CONNECTING - this._increaseCount(); - - my.connectSocket({ - url, - fail: (res) => { - this._triggerEvent('error', res) - } - }) - - this._onOpen = (res) => { - this.readyState = WebSocket.OPEN - this._triggerEvent('open') - } - my.onSocketOpen(this._onOpen) - - this._onMessage = (res) => { - function deepCopy(obj) { - if (typeof obj !== 'object' || obj == null) { - return obj; - } - - const copiedObj = {}; - - for (const key in obj) { - if (obj.hasOwnProperty(key)) { - copiedObj[key] = deepCopy(obj[key]); - } - } - - return copiedObj; - } - let tmp = deepCopy(res); - if (tmp && tmp.data && tmp.isBuffer) { - tmp.data = _utils.base64ToArrayBuffer(tmp.data) - } - this._triggerEvent('message', tmp) - } - my.onSocketMessage(this._onMessage) - - this._onError = (res) => { - this._triggerEvent('error', res) - this._decreaseCount(); - } - my.onSocketError(this._onError) - - this._onClose = (res) => { - this.readyState = WebSocket.CLOSED; - this._decreaseCount(); - this._removeAllSocketListener(); - this._triggerEvent('close'); - } - my.onSocketClose(this._onClose) - - return this - } - - close() { - this.readyState = WebSocket.CLOSING - my.closeSocket() - } - - send(data) { - if (typeof data !== 'string' && !(data instanceof ArrayBuffer) && !ArrayBuffer.isView(data)) { - throw new TypeError(`Failed to send message: The data ${data} is invalid`) - }else{ - var isBuffer = false; - if (data instanceof ArrayBuffer) { - data = _utils.arrayBufferToBase64(data) - isBuffer = true - } - - my.sendSocketMessage({ - data, - isBuffer, - fail: (res) => { - this._triggerEvent('error', res) - } - }); - } - } - - _triggerEvent(type, ...args) { - if (typeof this[`on${type}`] === 'function') { - this[`on${type}`].apply(this, args) - } - } - - _removeAllSocketListener(){ - my.offSocketOpen(this._onOpen) - my.offSocketMessage(this._onMessage) - my.offSocketError(this._onError) - my.offSocketClose(this._onClose) - - this._onOpen = null - this._onMessage = null - this._onError = null - this._onClose = null - } - - _increaseCount(){ - CURR_AMOUNT_WEBSOCKET += 1 - } - - _decreaseCount(){ - if(!this._isReduced){ - CURR_AMOUNT_WEBSOCKET -= 1 - this._isReduced = true - } - } - - _isMaxCount(){ - return CURR_AMOUNT_WEBSOCKET >= MAX_AMOUNT_WEBSOCKET - } -} diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/WindowProperties.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/WindowProperties.js deleted file mode 100644 index dbae81eeae..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/WindowProperties.js +++ /dev/null @@ -1,26 +0,0 @@ -const { pixelRatio, windowWidth, windowHeight } = my.getWindowInfoSync() -const devicePixelRatio = pixelRatio; - -let width, height; -{ - width = windowWidth; - height = windowHeight; -} - -export { devicePixelRatio } -export const screen = { - width, - height, - availWidth: width, - availHeight: height, - availLeft: 0, - availTop: 0, -} - -export const performance = { - now: Date.now -}; - -export const ontouchstart = null; -export const ontouchmove = null; -export const ontouchend = null; diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/XMLHttpRequest.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/XMLHttpRequest.js deleted file mode 100644 index 5198ef3156..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/XMLHttpRequest.js +++ /dev/null @@ -1,136 +0,0 @@ -import EventTarget from './EventTarget.js' - -const _url = new WeakMap() -const _method = new WeakMap() -const _requestHeader = new WeakMap() -const _responseHeader = new WeakMap() -const _requestTask = new WeakMap() - -function _triggerEvent(type, ...args) { - if (typeof this[`on${type}`] === 'function') { - this[`on${type}`].apply(this, args) - } -} - -function _changeReadyState(readyState) { - this.readyState = readyState - _triggerEvent.call(this, 'readystatechange') -} - -export default class XMLHttpRequest extends EventTarget { - // TODO: No way to simulate HEADERS_RECEIVED and LOADING states - static UNSEND = 0 - static OPENED = 1 - static HEADERS_RECEIVED = 2 - static LOADING = 3 - static DONE = 4 - - timeout = 0; - /* - * TODO: This batch of events should be on top of the XMLHttpRequestEventTarget.prototype - */ - onabort = null - onerror = null - onload = null - onloadstart = null - onprogress = null - ontimeout = null - onloadend = null - - onreadystatechange = null - readyState = 0 - response = null - responseText = null - responseType = '' - responseXML = null - status = 0 - statusText = '' - upload = {} - withCredentials = false - - constructor() { - super(); - - _requestHeader.set(this, { - 'content-type': 'application/json' - }) - _responseHeader.set(this, {}) - } - - abort() { - const myRequestTask = _requestTask.get(this) - - if (myRequestTask) { - myRequestTask.abort() - } - } - - getAllResponseHeaders() { - const responseHeader = _responseHeader.get(this) - - return Object.keys(responseHeader).map((header) => { - return `${header}: ${responseHeader[header]}` - }).join('\n') - } - - getResponseHeader(header) { - return _responseHeader.get(this)[header] - } - - open(method, url/* async, user, password. These parameters are not supported within the applet*/) { - _method.set(this, method) - _url.set(this, url) - _changeReadyState.call(this, XMLHttpRequest.OPENED) - } - - overrideMimeType() { - } - - send(data = '') { - if (this.readyState !== XMLHttpRequest.OPENED) { - throw new Error("Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.") - } else { - let myRequestTask = my.tb.request({ - body: JSON.stringify(data), - url: _url.get(this), - method: _method.get(this), - headers: _requestHeader.get(this), - options: {timeout: this.timeout, enableSystemParams: true}, - success: (res) => { - this.status = res.code; - this.responseText = this.response = res.content; - _responseHeader.set(this, _requestHeader.get(this)) - _triggerEvent.call(this, 'loadstart') - _changeReadyState.call(this, XMLHttpRequest.HEADERS_RECEIVED) - _changeReadyState.call(this, XMLHttpRequest.LOADING) - _changeReadyState.call(this, XMLHttpRequest.DONE) - _triggerEvent.call(this, 'load') - _triggerEvent.call(this, 'loadend') - }, - fail: (res) => { - _triggerEvent.call(this, 'error', res) - _triggerEvent.call(this, 'loadend') - } - }) - - _requestTask.set(this, myRequestTask); - } - } - - setRequestHeader(header, value) { - const myHeader = _requestHeader.get(this) - - myHeader[header] = value - _requestHeader.set(this, myHeader) - } - - addEventListener(type, listener) { - if (typeof listener === 'function') { - let _this = this - let event = { target: _this } - this['on' + type] = function (event) { - listener.call(_this, event) - } - } - } -} diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/cancelAnimationFrame.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/cancelAnimationFrame.js deleted file mode 100644 index c688495901..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/cancelAnimationFrame.js +++ /dev/null @@ -1,4 +0,0 @@ -let screencanvas = $global.screencanvas; -let cancelAnimationFrame = screencanvas.cancelAnimationFrame.bind(screencanvas); - -export default cancelAnimationFrame; \ No newline at end of file diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/document.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/document.js deleted file mode 100644 index 7a3cadfbf8..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/document.js +++ /dev/null @@ -1,124 +0,0 @@ -import * as _window from './window' -import HTMLElement from './HTMLElement' -import Image from './Image' -import Canvas from './Canvas' -import Audio from './Audio' - -const events = {} - -var document = { - readyState: 'complete', - visibilityState: 'visible', - documentElement: _window, - hidden: false, - style: {}, - location: _window.location, - ontouchstart: null, - ontouchmove: null, - ontouchend: null, - - head: new HTMLElement('head'), - body: new HTMLElement('body'), - - createElement(tagName) { - tagName = tagName.toLowerCase(); - if (tagName === 'canvas') { - return new Canvas() - } else if (tagName === 'audio') { - return new Audio() - } else if (tagName === 'img') { - return new Image() - } - - return new HTMLElement(tagName) - }, - - createElementNS(nameSpace, tagName) { - return this.createElement(tagName); - }, - - getElementById(id) { - if (id === _window.canvas.id) { - return _window.canvas - } - return null - }, - - getElementsByTagName(tagName) { - if (tagName === 'head') { - return [document.head] - } else if (tagName === 'body') { - return [document.body] - } else if (tagName === 'canvas') { - return [_window.canvas] - } - return [] - }, - - getElementsByName(tagName) { - if (tagName === 'head') { - return [document.head] - } else if (tagName === 'body') { - return [document.body] - } else if (tagName === 'canvas') { - return [_window.canvas] - } - return [] - }, - - querySelector(query) { - if (query === 'head') { - return document.head - } else if (query === 'body') { - return document.body - } else if (query === 'canvas') { - return _window.canvas - } else if (query === `#${_window.canvas.id}`) { - return _window.canvas - } - return null - }, - - querySelectorAll(query) { - if (query === 'head') { - return [document.head] - } else if (query === 'body') { - return [document.body] - } else if (query === 'canvas') { - return [_window.canvas] - } - return [] - }, - - addEventListener(type, listener) { - if (!events[type]) { - events[type] = [] - } - events[type].push(listener) - }, - - removeEventListener(type, listener) { - const listeners = events[type] - - if (listeners && listeners.length > 0) { - for (let i = listeners.length; i--; i > 0) { - if (listeners[i] === listener) { - listeners.splice(i, 1) - break - } - } - } - }, - - dispatchEvent(event) { - const listeners = events[event.type] - - if (listeners) { - for (let i = 0; i < listeners.length; i++) { - listeners[i](event) - } - } - } -} - -export { document } diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/index.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/index.js deleted file mode 100644 index e9e8182237..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/index.js +++ /dev/null @@ -1,90 +0,0 @@ -import * as _window from './window'; -import { document } from './document'; - -const global = $global; - -function inject () { - // Expose the global canvas - _window.canvas = $global.screencanvas; - _window.document = document; - - _window.addEventListener = (type, listener) => { - _window.document.addEventListener(type, listener); - }; - _window.removeEventListener = (type, listener) => { - _window.document.removeEventListener(type, listener); - }; - _window.dispatchEvent = _window.document.dispatchEvent; - - const { platform } = my.getSystemInfoSync(); - - // Developer tools cannot redefine window - if (my.isIDE) { - for (const key in _window) { - const descriptor = Object.getOwnPropertyDescriptor(window, key); - - if (!descriptor || descriptor.configurable === true) { - Object.defineProperty(window, key, { - value: _window[key], - }); - } - } - - for (const key in _window.document) { - const descriptor = Object.getOwnPropertyDescriptor(window.document, key); - - if (!descriptor || descriptor.configurable === true) { - Object.defineProperty(window.document, key, { - value: _window.document[key], - }); - } - } - window.parent = window; - window.my = my; - } else { - for (const key in _window) { - window[key] = _window[key]; - } - } - - const windowInfo = my.getWindowInfoSync(); - let _innerHeight = windowInfo.windowHeight; - let _innerWidth = windowInfo.windowWidth; - Object.defineProperty(window, 'innerWidth', { - configurable: true, - enumerable: true, - get() { - return _innerWidth; - } - }); - Object.defineProperty(window, 'innerHeight', { - configurable: true, - enumerable: true, - get() { - return _innerHeight; - } - }); - - my.onWindowResize((res) => { - _innerWidth = res.windowWidth; - _innerHeight = res.windowHeight; - const screen = window.screen; - screen.width = _innerWidth; - screen.height = _innerHeight; - screen.availWidth = _innerWidth; - screen.availHeight = _innerHeight; - }); - - global.setTimeout = setTimeout; - global.clearTimeout = clearTimeout; - global.setInterval = setInterval; - global.clearInterval = clearInterval; -} - -if (!global.__isAdapterInjected) { - global.__isAdapterInjected = true; - inject(); -} - -require('../../../../common/xmldom/dom-parser'); -require('../unify'); diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/localStorage.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/localStorage.js deleted file mode 100644 index 700d3be730..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/localStorage.js +++ /dev/null @@ -1,37 +0,0 @@ -const localStorage = { - get length() { - const { keys } = my.getStorageInfoSync() - - return keys.length - }, - - key(n) { - const { keys } = my.getStorageInfoSync() - - return keys[n] - }, - - getItem(key) { - let ret = my.getStorageSync({ - key, - }); - return ret && ret.data; - }, - - setItem(key, data) { - return my.setStorageSync({ - key, - data, - }); - }, - - removeItem(key) { - my.removeStorageSync({ key }) - }, - - clear() { - my.clearStorageSync() - } -} - -export default localStorage diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/location.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/location.js deleted file mode 100644 index 010f31bbac..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/location.js +++ /dev/null @@ -1,8 +0,0 @@ -const location = { - href: 'game.js', - protocol: '', - reload () { - }, -}; - -export default location; diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/navigator.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/navigator.js deleted file mode 100644 index 7a0990afaf..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/navigator.js +++ /dev/null @@ -1,38 +0,0 @@ -import { noop } from './util/index.js' - -// TODO: Need my.getSystemInfo for more details -const systemInfo = my.getSystemInfoSync() -console.log(systemInfo) - -const system = systemInfo.system; -const platform = systemInfo.platform; -const language = systemInfo.language; -const version = systemInfo.version; - -const android = system ? system.toLowerCase().indexOf('android') !== -1 : false; - -const uaDesc = android ? `Android; CPU ${system}` : `iPhone; CPU iPhone OS ${system} like Mac OS X`; -const ua = `Mozilla/5.0 (${uaDesc}) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E8301 MicroMessenger/${version} MiniGame NetType/WIFI Language/${language}`; - -const navigator = { - platform, - language: language, - appVersion: `5.0 (${uaDesc}) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1`, - userAgent: ua, - onLine: true, // TODO: Use my.getNetworkStateChange and my.onNetworkStateChange to return the real state - - // TODO: Wrap the geolocation with my.getLocation - geolocation: { - getCurrentPosition: noop, - watchPosition: noop, - clearWatch: noop - } -} - -if (my.onNetworkStatusChange) { - my.onNetworkStatusChange(function(event){ - navigator.onLine = event.isConnected; - }); -} - -export default navigator diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/requestAnimationFrame.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/requestAnimationFrame.js deleted file mode 100644 index d6f8366904..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/requestAnimationFrame.js +++ /dev/null @@ -1,4 +0,0 @@ -let screencanvas = $global.screencanvas; -let requestAnimationFrame = screencanvas.requestAnimationFrame.bind(screencanvas); - -export default requestAnimationFrame; \ No newline at end of file diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/util/index.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/util/index.js deleted file mode 100644 index 177804c7ab..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/util/index.js +++ /dev/null @@ -1 +0,0 @@ -export function noop() {} diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/window.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/window.js deleted file mode 100644 index 113592a974..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/builtin/window.js +++ /dev/null @@ -1,23 +0,0 @@ -export navigator from './navigator' -export XMLHttpRequest from './XMLHttpRequest' -export Image from './Image' -export ImageBitmap from './ImageBitmap' -export HTMLElement from './HTMLElement' -export HTMLCanvasElement from './HTMLCanvasElement' -export HTMLImageElement from './HTMLImageElement' -export WebGLRenderingContext from './WebGLRenderingContext' -export localStorage from './localStorage' -export location from './location' -export requestAnimationFrame from './requestAnimationFrame' -export cancelAnimationFrame from './cancelAnimationFrame' -export * from './WindowProperties' - - -import MultiWebSocket from './MultiWebSocket' -import WebSocket from './WebSocket' -const systemInfo = my.getSystemInfoSync(); -if (typeof my !== 'undefined' && my && my.canIUse && my.canIUse('connectSocket.object.multiple')) { - $global.WebSocket = MultiWebSocket; -} else { - $global.WebSocket = WebSocket; -} \ No newline at end of file diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/AssetManager.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/AssetManager.js deleted file mode 100644 index d7e5745a98..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/AssetManager.js +++ /dev/null @@ -1,72 +0,0 @@ -const parser = cc.assetManager.parser; -const downloader = cc.assetManager.downloader; -const debug = cc.debug; - -function doNothing (url, options, onComplete) { - onComplete(null, url); -} - -// TODO: Image can't load from cached downloaded file on Taobao IDE -if (my.isIDE) { - downloader.register({ - '.png': doNothing, - '.jpg': doNothing, - '.bmp': doNothing, - '.jpeg': doNothing, - '.gif': doNothing, - '.ico': doNothing, - '.tiff': doNothing, - '.image': doNothing, - '.webp': doNothing, - }); -} - -// TODO: Audio can't load from cached downloaded file onTaoBao -downloader.register({ - '.mp3': doNothing, - '.ogg': doNothing, - '.wav': doNothing, - '.m4a': doNothing, -}); - -function loadImage (url, options, onComplete) { - const img = $global.screencanvas.createImage(); - - function loadCallback () { - img.onload = null; - img.onerror = null; - - if (onComplete) { - onComplete(null, img); - } - } - - function errorCallback () { - img.onload = null; - img.onerror = null; - - if (onComplete) { - onComplete(new Error(debug.getError(4930, url))); - } - } - - img.onload = loadCallback; - img.onerror = errorCallback; - img.src = url; - return img; -} - -downloader.downloadDomImage = loadImage; - -parser.register({ - // Image - '.png': loadImage, - '.jpg': loadImage, - '.bmp': loadImage, - '.jpeg': loadImage, - '.gif': loadImage, - '.ico': loadImage, - '.tiff': loadImage, - '.image': loadImage, - '.webp': loadImage, -}); diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/Console.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/Console.js deleted file mode 100644 index 96480caa10..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/Console.js +++ /dev/null @@ -1,12 +0,0 @@ -// Alipay console.time have some error ,hack here -let Timer = window.performance; -let _timerTable = Object.create(null); - -console.time = function(label) { - _timerTable[label] = Timer.now(); -} -console.timeEnd = function(label) { - let startTime = _timerTable[label]; - let duration = Timer.now() - startTime; - console.log(`${label}: ${duration}ms`); -} diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/Editbox.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/Editbox.js deleted file mode 100644 index 530133d6db..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/Editbox.js +++ /dev/null @@ -1,91 +0,0 @@ -(function () { - if (!(cc && cc.internal && cc.internal.EditBox)) { - return; - } - - const EditBox = cc.internal.EditBox; - const js = cc.js; - const KeyboardReturnType = EditBox.KeyboardReturnType; - const MAX_VALUE = 65535; - - function getKeyboardReturnType (type) { - switch (type) { - case KeyboardReturnType.DEFAULT: - case KeyboardReturnType.DONE: - return 'done'; - case KeyboardReturnType.SEND: - return 'send'; - case KeyboardReturnType.SEARCH: - return 'search'; - case KeyboardReturnType.GO: - return 'go'; - case KeyboardReturnType.NEXT: - return 'next'; - } - return 'done'; - } - - const BaseClass = EditBox._EditBoxImpl; - function MiniGameEditBoxImpl () { - BaseClass.call(this); - } - - js.extend(MiniGameEditBoxImpl, BaseClass); - EditBox._EditBoxImpl = MiniGameEditBoxImpl; - - Object.assign(MiniGameEditBoxImpl.prototype, { - init (delegate) { - if (!delegate) { - cc.error('EditBox init failed'); - return; - } - this._delegate = delegate; - }, - - beginEditing () { - // In case multiply register events - if (this._editing) { - return; - } - const delegate = this._delegate; - this._showPrompt(); - this._editing = true; - delegate._editBoxEditingDidBegan(); - }, - - endEditing () { - cc.warn(`Can't support to end editing.`); - }, - - _showPrompt () { - const self = this; - const delegate = this._delegate; - const multiline = (delegate.inputMode === EditBox.InputMode.ANY); - const maxLength = (delegate.maxLength < 0 ? MAX_VALUE : delegate.maxLength); - - if (multiline) { - cc.warn(`Multiline editing is not supported`); - } - - my.prompt({ - title: '', - message: delegate.placeholder, - // placeholder: delegate.placeholder, - okButtonText: getKeyboardReturnType(delegate.returnType), - cancelButtonText: 'cancel', - success: (result) => { - if (result.ok) { - let inputValue = result.inputValue; - inputValue = (maxLength <= inputValue.length) ? inputValue.substring(0, maxLength) : inputValue; - if (delegate._string !== inputValue) { - delegate._editBoxTextChanged(inputValue); - } - delegate._editBoxEditingReturn(); - } - self._editing = false; - delegate._editBoxEditingDidEnded(); - }, - }); - }, - }); -}()); diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/Label.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/Label.js deleted file mode 100644 index 9c31490faa..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/Label.js +++ /dev/null @@ -1,22 +0,0 @@ -if (cc && cc.Label) { - const Label = cc.Label; - - // shared label canvas - const _sharedLabelCanvas = my.createCanvas(); - const _sharedLabelCanvasCtx = _sharedLabelCanvas.getContext('2d'); - const canvasData = { - canvas: _sharedLabelCanvas, - context: _sharedLabelCanvasCtx, - }; - cc.game.on(cc.game.EVENT_ENGINE_INITED, () => { - Object.assign(Label._canvasPool, { - get () { - return canvasData; - }, - - put () { - // do nothing - }, - }); - }); -} diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/cache-manager.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/cache-manager.js deleted file mode 100644 index da7d1799d1..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/cache-manager.js +++ /dev/null @@ -1,53 +0,0 @@ -/**************************************************************************** - Copyright (c) 2019 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of cache-manager 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 cache-manager 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. - ****************************************************************************/ - const { rmdirSync, unzip, isOutOfStorage } = require('../fs-utils'); - - (function () { - let unzipSuffix = 0; - if (!(cc && cc.assetManager && cc.assetManager.cacheManager)) { - return; - } - - const cacheManager = cc.assetManager.cacheManager; - cacheManager.unzipAndCacheBundle = function (id, zipFilePath, cacheBundleRoot, onComplete) { - const time = Date.now().toString(); - const targetPath = `${this.cacheDir}/${cacheBundleRoot}/${time}${unzipSuffix++}`; - const self = this; - unzip(zipFilePath, targetPath, (err) => { - if (err) { - rmdirSync(targetPath, true); - if (isOutOfStorage(err.message)) { - self.outOfStorage = true; - self.autoClear && self.clearLRU(); - } - onComplete && onComplete(err); - return; - } - self.cachedFiles.add(id, { bundle: cacheBundleRoot, url: targetPath, lastTime: time }); - self.writeCacheFile(); - onComplete && onComplete(null, targetPath); - }); - }; -}()); diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/index.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/index.js deleted file mode 100644 index 5e1b616313..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/engine/index.js +++ /dev/null @@ -1,6 +0,0 @@ -require('../fs-utils'); -require('../../../../common/engine/index'); -require('./AssetManager.js'); -require('./Label.js'); -require('./Console'); -require('./Editbox.js'); diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/fs-utils.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/fs-utils.js deleted file mode 100644 index 34687738aa..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/fs-utils.js +++ /dev/null @@ -1,275 +0,0 @@ -/**************************************************************************** - Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated 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. - ****************************************************************************/ -/* eslint-disable no-undef */ - -const fs = my.getFileSystemManager ? my.getFileSystemManager() : null; -const outOfStorageErrorCode = '10028'; // not exactly right - -const fsUtils = { - fs, - - isOutOfStorage (errorCode) { - return errorCode != null && String(errorCode) === outOfStorageErrorCode; - }, - - getUserDataPath () { - return my.env.USER_DATA_PATH; - }, - - checkFsValid () { - if (!fs) { - console.warn('Can not get the file system!'); - return false; - } - return true; - }, - - deleteFile (filePath, onComplete) { - fs.unlink({ - filePath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Delete file failed: path: ${filePath} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.errorMessage)); - }, - }); - }, - - downloadFile (remoteUrl, filePath, header, onProgress, onComplete) { - const options = { - url: remoteUrl, - success (res) { - if (!filePath) { - onComplete && onComplete(null, res.apFilePath); - } else { - fsUtils.copyFile(res.apFilePath, filePath, onComplete); - } - }, - fail (res) { - if (fsUtils.isOutOfStorage(res.error)) { - cc.assetManager.cacheManager.clearLRU(); - } - console.warn(`Download file failed: path: ${remoteUrl} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.error), null); - }, - }; - if (header) options.header = header; - const task = my.downloadFile(options); - onProgress && task.onProgressUpdate(onProgress); - }, - - saveFile (srcPath, destPath, onComplete) { - // Hack, seems like my.saveFile dose not work - fsUtils.copyFile(srcPath, destPath, onComplete); - }, - - copyFile (srcPath, destPath, onComplete) { - fs.copyFile({ - srcPath, - destPath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Copy file failed: path: ${srcPath} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.error)); - }, - }); - }, - - writeFile (path, data, encoding, onComplete) { - fs.writeFile({ - filePath: path, - encoding, - data, - success () { - onComplete && onComplete(null); - }, - fail (res) { - if (fsUtils.isOutOfStorage(res.error)) { - cc.assetManager.cacheManager.clearLRU(); - } - console.warn(`Write file failed: path: ${path} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.error)); - }, - }); - }, - - writeFileSync (path, data, encoding) { - try { - fs.writeFileSync({ - filePath: path, - data, - encoding, - }); - return null; - } catch (e) { - console.warn(`Write file failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - readFile (filePath, encoding, onComplete) { - fs.readFile({ - filePath, - encoding, - success (res) { - onComplete && onComplete(null, res.data); - }, - fail (res) { - console.warn(`Read file failed: path: ${filePath} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.errorMessage), null); - }, - }); - }, - - readDir (filePath, onComplete) { - fs.readdir({ - dirPath: filePath, - success (res) { - onComplete && onComplete(null, res.files); - }, - fail (res) { - console.warn(`Read directory failed: path: ${filePath} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.errorMessage), null); - }, - }); - }, - - readText (filePath, onComplete) { - fsUtils.readFile(filePath, 'utf8', onComplete); - }, - - readArrayBuffer (filePath, onComplete) { - fsUtils.readFile(filePath, '', onComplete); - }, - - readJson (filePath, onComplete) { - fsUtils.readFile(filePath, 'utf8', (err, text) => { - let out = null; - if (!err) { - try { - out = JSON.parse(text); - } catch (e) { - console.warn(`Read json failed: path: ${filePath} message: ${e.message}`); - err = new Error(e.message); - } - } - onComplete && onComplete(err, out); - }); - }, - - readJsonSync (path) { - try { - const res = fs.readFileSync({ - filePath: path, - encoding: 'utf8', - }); - return JSON.parse(res.data); - } catch (e) { - console.warn(`Read json failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - makeDirSync (path, recursive) { - try { - fs.mkdirSync({ - dirPath: path, - recursive, - }); - return null; - } catch (e) { - console.warn(`Make directory failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - rmdirSync (dirPath, recursive) { - try { - fs.rmdirSync({ dirPath, recursive }); - return null; - } catch (e) { - console.warn(`rm directory failed: path: ${dirPath} message: ${e.message}`); - return new Error(e.message); - } - }, - - exists (filePath, onComplete) { - // fs.access is not supported. - // fs.access({ - // path: filePath, - // success: function () { - // onComplete && onComplete(true); - // }, - // fail: function () { - // onComplete && onComplete(false); - // } - // }); - fs.readFile({ - filePath, - success () { - onComplete && onComplete(true); - }, - fail () { - onComplete && onComplete(false); - }, - }); - }, - - loadSubpackage (name, onProgress, onComplete) { - // const task = - my.loadSubPackage({ - name, - success () { - onComplete && onComplete(); - }, - fail (res) { - console.warn(`Load Subpackage failed: path: ${name} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(`Failed to load subpackage ${name}: ${res.errorMessage}`)); - }, - }); - // onProgress && task.onProgressUpdate(onProgress); - return {}; - }, - - unzip (zipFilePath, targetPath, onComplete) { - fs.unzip({ - zipFilePath, - targetPath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`unzip failed: path: ${zipFilePath} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.error)); - }, - }); - }, -}; - -window.fsUtils = module.exports = fsUtils; diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/unify.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/unify.js deleted file mode 100644 index 79f07ac42b..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/unify.js +++ /dev/null @@ -1,128 +0,0 @@ -const utils = require('./utils'); - -window.__globalAdapter = window.__globalAdapter || {}; -if (window.__globalAdapter) { - const globalAdapter = window.__globalAdapter; - // SystemInfo - globalAdapter.isSubContext = false; // sub context not supported - globalAdapter.isDevTool = my.isIDE; - utils.cloneMethod(globalAdapter, my, 'getSystemInfoSync'); - - // Audio - globalAdapter.createInnerAudioContext = function () { - const audio = my.createInnerAudioContext(); - if (my.getSystemInfoSync().platform === 'iOS') { - let currentTime = 0; - const originalSeek = audio.seek; - audio.seek = function (time) { - // need to access audio.paused in the next tick - setTimeout(() => { - if (audio.paused) { - currentTime = time; - } else { - originalSeek.call(audio, time); - } - }, 50); - }; - - const originalPlay = audio.play; - audio.play = function () { - if (currentTime !== 0) { - audio.seek(currentTime); - currentTime = 0; // clear cached currentTime - } - originalPlay.call(audio); - }; - } - return audio; - }; - - // TouchEvent - utils.cloneMethod(globalAdapter, my, 'onTouchStart'); - utils.cloneMethod(globalAdapter, my, 'onTouchMove'); - utils.cloneMethod(globalAdapter, my, 'onTouchEnd'); - utils.cloneMethod(globalAdapter, my, 'onTouchCancel'); - - // Audio - // utils.cloneMethod(globalAdapter, my, 'createInnerAudioContext'); - - // AudioInterruption Evnet - utils.cloneMethod(globalAdapter, my, 'onAudioInterruptionEnd'); - utils.cloneMethod(globalAdapter, my, 'onAudioInterruptionBegin'); - - // Video - utils.cloneMethod(globalAdapter, my, 'createVideo'); - - // FrameRate - utils.cloneMethod(globalAdapter, my, 'setPreferredFramesPerSecond'); - - // Keyboard - utils.cloneMethod(globalAdapter, my, 'showKeyboard'); - utils.cloneMethod(globalAdapter, my, 'hideKeyboard'); - utils.cloneMethod(globalAdapter, my, 'updateKeyboard'); - utils.cloneMethod(globalAdapter, my, 'onKeyboardInput'); - utils.cloneMethod(globalAdapter, my, 'onKeyboardConfirm'); - utils.cloneMethod(globalAdapter, my, 'onKeyboardComplete'); - utils.cloneMethod(globalAdapter, my, 'offKeyboardInput'); - utils.cloneMethod(globalAdapter, my, 'offKeyboardConfirm'); - utils.cloneMethod(globalAdapter, my, 'offKeyboardComplete'); - - // Message - utils.cloneMethod(globalAdapter, my, 'getOpenDataContext'); - utils.cloneMethod(globalAdapter, my, 'onMessage'); - - // Subpackage - utils.cloneMethod(globalAdapter, my, 'loadSubpackage'); - - // SharedCanvas - utils.cloneMethod(globalAdapter, my, 'getSharedCanvas'); - - // Font - utils.cloneMethod(globalAdapter, my, 'loadFont'); - - // hide show Event - utils.cloneMethod(globalAdapter, my, 'onShow'); - utils.cloneMethod(globalAdapter, my, 'onHide'); - - // onError - utils.cloneMethod(globalAdapter, my, 'onError'); - // offError - utils.cloneMethod(globalAdapter, my, 'offError'); - - // Font - globalAdapter.loadFont = function (url) { - // my.loadFont crash when url is not in user data path - return 'Arial'; - }; - - // Accelerometer - let accelerometerCallback = null; - function accelerometerChangeCallback (res, cb) { - const resClone = {}; - - let x = res.x; - let y = res.y; - - const windowInfo = my.getWindowInfoSync(); - if (windowInfo.windowWidth > windowInfo.windowHeight) { - const tmp = x; - x = -y; - y = tmp; - } - - resClone.x = x; - resClone.y = y; - resClone.z = res.z; - accelerometerCallback && accelerometerCallback(resClone); - } - Object.assign(globalAdapter, { - startAccelerometer (cb) { - accelerometerCallback = cb; - my.onAccelerometerChange && my.onAccelerometerChange(accelerometerChangeCallback); - }, - - stopAccelerometer () { - my.offAccelerometerChange && my.offAccelerometerChange(accelerometerChangeCallback); - }, - }); -} diff --git a/platforms/minigame/platforms/taobao-mini-game/wrapper/utils.js b/platforms/minigame/platforms/taobao-mini-game/wrapper/utils.js deleted file mode 100644 index 3ead0b6528..0000000000 --- a/platforms/minigame/platforms/taobao-mini-game/wrapper/utils.js +++ /dev/null @@ -1,111 +0,0 @@ -const utils = { - /** - * @param {Object} target - * @param {Object} origin - * @param {String} methodName - * @param {String} targetMethodName - */ - cloneMethod (target, origin, methodName, targetMethodName) { - if (origin[methodName]) { - targetMethodName = targetMethodName || methodName; - target[targetMethodName] = origin[methodName].bind(origin); - } - }, - - /** - * - * @param {String} str - * @returns - */ - encode (str) { - let encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - const string = String(str); - let result = ''; - let currentIndex = 0; - let sum = void 0; - while (string.charAt(0 | currentIndex) || (encodings = '=', currentIndex % 1)) { - currentIndex += 0.75; - const currentCode = string.charCodeAt(currentIndex); - if (currentCode > 255) { - // Cannot handle when it is greater than 255 - throw new Error('"btoa" failed'); - } - sum = sum << 8 | currentCode; - const encodeIndex = 63 & sum >> 8 - currentIndex % 1 * 8; - result += encodings.charAt(encodeIndex); - } - - return result; - }, - - /** - * - * @param {String} str - */ - decode (str) { - const encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - let res = ''; - const string = String(str).replace(/[=]+$/, ''); - let o; - let r; - let i = 0; - let currentIndex = 0; - while (r = string.charAt(currentIndex)) { - currentIndex += 1; - r = encodings.indexOf(r); - if (~r) { - o = i % 4 ? 64 * o + r : r; - if (i++ % 4) { - res += String.fromCharCode(255 & o >> (-2 * i & 6)); - } - } - } - - return res; - }, - - /** - * - * @param {ArrayBuffer} buffer - */ - arrayBufferToBase64 (buffer) { - return utils.encode(utils.arrayBufferToString(buffer)); - }, - - /** - * - * @param {String} base64 - */ - base64ToArrayBuffer (base64) { - return utils.stringToArrayBuffer(utils.decode(base64)); - }, - - /** - * - * @param {ArrayBuffer} buffer - */ - arrayBufferToString (buffer) { - let result = ''; - const uintArray = new Uint8Array(buffer); - const byteLength = uintArray.byteLength; - for (let i = 0; i < byteLength; i++) { - result += String.fromCharCode(uintArray[i]); - } - return result; - }, - - /** - * - * @param {String} string - */ - stringToArrayBuffer (string) { - const length = string.length; - const uintArray = new Uint8Array(length); - for (let i = 0; i < length; i++) { - uintArray[i] = string.charCodeAt(i); - } - return uintArray.buffer; - }, -}; - -module.exports = utils; diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/Audio.js b/platforms/minigame/platforms/taobao/wrapper/builtin/Audio.js deleted file mode 100644 index 92ffc210b4..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/Audio.js +++ /dev/null @@ -1,205 +0,0 @@ -import HTMLAudioElement from './HTMLAudioElement' - -const HAVE_NOTHING = 0 -const HAVE_METADATA = 1 -const HAVE_CURRENT_DATA = 2 -const HAVE_FUTURE_DATA = 3 -const HAVE_ENOUGH_DATA = 4 - -let SN_SEED = 1 - -const _innerAudioContextMap = {} - -export default class Audio extends HTMLAudioElement { - - constructor(url) { - super() - - this._$sn = SN_SEED++; - - this.HAVE_NOTHING = HAVE_NOTHING - this.HAVE_METADATA = HAVE_METADATA - this.HAVE_CURRENT_DATA = HAVE_CURRENT_DATA - this.HAVE_FUTURE_DATA = HAVE_FUTURE_DATA - this.HAVE_ENOUGH_DATA = HAVE_ENOUGH_DATA - - this.readyState = HAVE_NOTHING - - const innerAudioContext = my.createInnerAudioContext() - - _innerAudioContextMap[this._$sn] = innerAudioContext - - this._canplayEvents = [ - 'load', - 'loadend', - 'canplay', - 'canplaythrough', - 'loadedmetadata' - ] - - innerAudioContext.onCanplay(() => { - this._loaded = true - this.readyState = this.HAVE_CURRENT_DATA - this._canplayEvents.forEach((type) => { - this.dispatchEvent({ type: type }) - }) - }) - innerAudioContext.onPlay(() => { - this._paused = _innerAudioContextMap[this._$sn].paused - this.dispatchEvent({ type: 'play' }) - }) - innerAudioContext.onPause(() => { - this._paused = _innerAudioContextMap[this._$sn].paused - this.dispatchEvent({ type: 'pause' }) - }) - innerAudioContext.onEnded(() => { - this._paused = _innerAudioContextMap[this._$sn].paused - if (_innerAudioContextMap[this._$sn].loop === false) { - this.dispatchEvent({ type: 'ended' }) - } - this.readyState = HAVE_ENOUGH_DATA - }) - innerAudioContext.onError(() => { - this._paused = _innerAudioContextMap[this._$sn].paused - this.dispatchEvent({ type: 'error' }) - }) - - if (url) { - this.src = url - } else { - this._src = '' - } - - this._loop = innerAudioContext.loop - this._autoplay = innerAudioContext.autoplay - this._paused = innerAudioContext.paused - this._volume = innerAudioContext.volume - this._muted = false; - } - - addEventListener(type, listener, options = {}) { - super.addEventListener(type, listener, options) - - type = String(type).toLowerCase() - - if (this._loaded && this._canplayEvents.indexOf(type) !== -1) { - this.dispatchEvent({ type: type }) - } - } - - load() { - // console.warn('HTMLAudioElement.load() is not implemented.') - // weixin doesn't need call load() manually - } - - play() { - _innerAudioContextMap[this._$sn].play() - } - - resume() { - _innerAudioContextMap[this._$sn].resume() - } - - pause() { - _innerAudioContextMap[this._$sn].pause() - } - - stop() { - _innerAudioContextMap[this._$sn].stop() - } - - destroy() { - _innerAudioContextMap[this._$sn].destroy() - } - - canPlayType(mediaType = '') { - if (typeof mediaType !== 'string') { - return '' - } - - if (mediaType.indexOf('audio/mpeg') > -1 || mediaType.indexOf('audio/mp4')) { - return 'probably' - } - return '' - } - - get currentTime() { - return _innerAudioContextMap[this._$sn].currentTime - } - - set currentTime(value) { - _innerAudioContextMap[this._$sn].seek(value) - } - - get duration () { - return _innerAudioContextMap[this._$sn].duration - } - - get src() { - return this._src - } - - set src(value) { - this._src = value - this._loaded = false - this.readyState = this.HAVE_NOTHING - - const innerAudioContext = _innerAudioContextMap[this._$sn] - - innerAudioContext.src = value - } - - get loop() { - return this._loop - } - - set loop(value) { - this._loop = value - _innerAudioContextMap[this._$sn].loop = value - } - - get autoplay() { - return this.autoplay - } - - set autoplay(value) { - this._autoplay = value - _innerAudioContextMap[this._$sn].autoplay = value - } - - get paused() { - return this._paused; - } - - get volume() { - return this._volume; - } - - set volume(value) { - this._volume = value; - if (!this._muted) { - _innerAudioContextMap[this._$sn].volume = value; - } - } - - get muted() { - return this._muted; - } - - set muted(value) { - this._muted = value; - if (value) { - _innerAudioContextMap[this._$sn].volume = 0; - } else { - _innerAudioContextMap[this._$sn].volume = this._volume; - } - } - - cloneNode() { - const newAudio = new Audio() - newAudio.loop = this.loop - newAudio.autoplay = this.autoplay - newAudio.src = this.src - return newAudio - } -} diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/Canvas.js b/platforms/minigame/platforms/taobao/wrapper/builtin/Canvas.js deleted file mode 100644 index cdff09936d..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/Canvas.js +++ /dev/null @@ -1,69 +0,0 @@ -import { innerWidth, innerHeight } from './WindowProperties' - -function Canvas () {} - -let CanvasProxy = new Proxy(Canvas, { - construct () { - - const canvas = my.createOffscreenCanvas() - - canvas.type = 'canvas' - - // canvas.__proto__.__proto__.__proto__ = new HTMLCanvasElement() - - const _getContext = canvas.getContext - - canvas.getBoundingClientRect = () => { - const ret = { - top: 0, - left: 0, - width: window.innerWidth, - height: window.innerHeight - } - return ret - } - - canvas.style = { - top: '0px', - left: '0px', - width: innerWidth + 'px', - height: innerHeight + 'px', - } - - canvas.addEventListener = function (type, listener, options = {}) { - // console.log('canvas.addEventListener', type); - document.addEventListener(type, listener, options); - } - - canvas.removeEventListener = function (type, listener) { - // console.log('canvas.removeEventListener', type); - document.removeEventListener(type, listener); - } - - canvas.dispatchEvent = function (event = {}) { - console.log('canvas.dispatchEvent' , event.type, event); - // nothing to do - } - - Object.defineProperty(canvas, 'clientWidth', { - enumerable: true, - get: function get() { - return innerWidth - } - }) - - Object.defineProperty(canvas, 'clientHeight', { - enumerable: true, - get: function get() { - return innerHeight - } - }) - - return canvas - }, -}); - -// NOTE: this is a hack operation -// let canvas = new window.Canvas() -// console.error(canvas instanceof window.Canvas) => false -export default CanvasProxy; diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/Element.js b/platforms/minigame/platforms/taobao/wrapper/builtin/Element.js deleted file mode 100644 index 965cd80d17..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/Element.js +++ /dev/null @@ -1,10 +0,0 @@ -import Node from './Node' - -export default class Element extends Node { - className = '' - children = [] - - constructor() { - super() - } -} diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/Event.js b/platforms/minigame/platforms/taobao/wrapper/builtin/Event.js deleted file mode 100644 index a7adc6a57b..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/Event.js +++ /dev/null @@ -1,14 +0,0 @@ -import {noop} from './util' - -export default class Event { - cancelBubble = false - cancelable = false - target = null - timestampe = Date.now() - preventDefault = noop - stopPropagation = noop - - constructor(type) { - this.type = type - } -} diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/EventTarget.js b/platforms/minigame/platforms/taobao/wrapper/builtin/EventTarget.js deleted file mode 100644 index 573c3dbc9e..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/EventTarget.js +++ /dev/null @@ -1,57 +0,0 @@ -const _events = new WeakMap() - -export default class EventTarget { - constructor() { - _events.set(this, {}) - } - - addEventListener(type, listener, options = {}) { - let events = _events.get(this) - - if (!events) { - events = {} - _events.set(this, events) - } - if (!events[type]) { - events[type] = [] - } - events[type].push(listener) - - if (options.capture) { - // console.warn('EventTarget.addEventListener: options.capture is not implemented.') - } - if (options.once) { - // console.warn('EventTarget.addEventListener: options.once is not implemented.') - } - if (options.passive) { - // console.warn('EventTarget.addEventListener: options.passive is not implemented.') - } - } - - removeEventListener(type, listener) { - const events = _events.get(this) - - if (events) { - const listeners = events[type] - - if (listeners && listeners.length > 0) { - for (let i = listeners.length; i--; i > 0) { - if (listeners[i] === listener) { - listeners.splice(i, 1) - break - } - } - } - } - } - - dispatchEvent(event = {}) { - const listeners = _events.get(this)[event.type] - - if (listeners) { - for (let i = 0; i < listeners.length; i++) { - listeners[i](event) - } - } - } -} diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/HTMLAudioElement.js b/platforms/minigame/platforms/taobao/wrapper/builtin/HTMLAudioElement.js deleted file mode 100644 index 0f60bd6b91..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/HTMLAudioElement.js +++ /dev/null @@ -1,7 +0,0 @@ -import HTMLElement from './HTMLElement' - -export default class HTMLAudioElement extends HTMLElement { - constructor() { - super('audio') - } -} diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/HTMLCanvasElement.js b/platforms/minigame/platforms/taobao/wrapper/builtin/HTMLCanvasElement.js deleted file mode 100644 index 6b5191991c..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/HTMLCanvasElement.js +++ /dev/null @@ -1,3 +0,0 @@ -let HTMLCanvasElement = my.createOffscreenCanvas().constructor; - -export default HTMLCanvasElement; diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/HTMLElement.js b/platforms/minigame/platforms/taobao/wrapper/builtin/HTMLElement.js deleted file mode 100644 index 51040f3c6e..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/HTMLElement.js +++ /dev/null @@ -1,54 +0,0 @@ -import Element from './Element' -import { noop } from './util/index.js' -import { innerWidth, innerHeight } from './WindowProperties' - -export default class HTMLElement extends Element { - className = '' - childern = [] - style = { - width: `${innerWidth}px`, - height: `${innerHeight}px` - } - - insertBefore = noop - - innerHTML = '' - - constructor(tagName = '') { - super() - this.tagName = tagName.toUpperCase() - } - - setAttribute(name, value) { - this[name] = value - } - - getAttribute(name) { - return this[name] - } - - get clientWidth() { - const ret = parseInt(this.style.fontSize, 10) * this.innerHTML.length - - return Number.isNaN(ret) ? 0 : ret - } - - get clientHeight() { - const ret = parseInt(this.style.fontSize, 10) - - return Number.isNaN(ret) ? 0 : ret - } - - getBoundingClientRect() { - return { - top: 0, - left: 0, - width: innerWidth, - height: innerHeight - } - } - - focus() { - - } -} diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/HTMLImageElement.js b/platforms/minigame/platforms/taobao/wrapper/builtin/HTMLImageElement.js deleted file mode 100644 index d53052ee3c..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/HTMLImageElement.js +++ /dev/null @@ -1,4 +0,0 @@ -var screencanvas = $global.screencanvas; -let HTMLImageElement = screencanvas.createImage().constructor; - -export default HTMLImageElement; \ No newline at end of file diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/Image.js b/platforms/minigame/platforms/taobao/wrapper/builtin/Image.js deleted file mode 100644 index 7eb1b07bb4..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/Image.js +++ /dev/null @@ -1,7 +0,0 @@ -// var screencanvas = $global.screencanvas; - -function Image () { - return $global.screencanvas.createImage(); -} - -export default Image; diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/ImageBitmap.js b/platforms/minigame/platforms/taobao/wrapper/builtin/ImageBitmap.js deleted file mode 100644 index 1700abfb80..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/ImageBitmap.js +++ /dev/null @@ -1,5 +0,0 @@ -export default class ImageBitmap { - constructor () { - - } -} diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/Node.js b/platforms/minigame/platforms/taobao/wrapper/builtin/Node.js deleted file mode 100644 index 6ebcbdc234..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/Node.js +++ /dev/null @@ -1,34 +0,0 @@ -import EventTarget from './EventTarget.js' - -export default class Node extends EventTarget { - constructor() { - super() - } - - childNodes = [] - - appendChild(node) { - this.childNodes.push(node) - // if (node instanceof Node) { - // this.childNodes.push(node) - // } else { - // throw new TypeError('Failed to executed \'appendChild\' on \'Node\': parameter 1 is not of type \'Node\'.') - // } - } - - cloneNode() { - const copyNode = Object.create(this) - - Object.assign(copyNode, this) - return copyNode - } - - removeChild(node) { - const index = this.childNodes.findIndex((child) => child === node) - - if (index > -1) { - return this.childNodes.splice(index, 1) - } - return null - } -} diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/WebGLRenderingContext.js b/platforms/minigame/platforms/taobao/wrapper/builtin/WebGLRenderingContext.js deleted file mode 100644 index 7c4d15ed27..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/WebGLRenderingContext.js +++ /dev/null @@ -1,5 +0,0 @@ -export default class WebGLRenderingContext { - constructor() { - - } -} diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/WebSocket.js b/platforms/minigame/platforms/taobao/wrapper/builtin/WebSocket.js deleted file mode 100644 index 825b333502..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/WebSocket.js +++ /dev/null @@ -1,139 +0,0 @@ -const _utils = require('../utils'); - -const MAX_AMOUNT_WEBSOCKET = 1 // The maximum number of WEBSOCKET -let CURR_AMOUNT_WEBSOCKET = 0 // The current number of WEBSOCKET - -export default class WebSocket { - static CONNECTING = 0 // The connection is not yet open. - static OPEN = 1 // The connection is open and ready to communicate. - static CLOSING = 2 // The connection is in the process of closing. - static CLOSED = 3 // The connection is closed or couldn't be opened. - - binaryType = '' // TODO: update binaryType - bufferedAmount = 0 // TODO: update bufferedAmount - extensions = '' - - onopen = null - onmessage = null - onerror = null - onclose = null - - _onMessage = null - _onOpen = null - _onError = null - _onClose = null - _isReduced = false - - protocol = '' // TODO: It is not currently available within the applet, but actually needs to be returned according to the sub-protocol selected by the server - readyState = 3 - - constructor(url, protocols = []) { - if(this._isMaxCount()){ - console.warn(`Failed to construct 'WebSocket': Only ${CURR_AMOUNT_WEBSOCKET} WebSocket can be created at the same time on TaoBao.`); - return this; - } - - if (typeof url !== 'string' || !(/(^ws:\/\/)|(^wss:\/\/)/).test(url)) { - throw new TypeError(`Failed to construct 'WebSocket': The URL '${url}' is invalid`) - } - - this.url = url - this.readyState = WebSocket.CONNECTING - this._increaseCount(); - - my.connectSocket({ - url, - fail: function fail(res) { - this._triggerEvent('error', res) - } - }) - - this._onOpen = (res) => { - this.readyState = WebSocket.OPEN - this._triggerEvent('open') - } - my.onSocketOpen(this._onOpen) - - this._onMessage = (res) => { - if (res && res.data && res.isBuffer) { - res.data = _utils.base64ToArrayBuffer(res.data) - } - this._triggerEvent('message', res) - } - my.onSocketMessage(this._onMessage) - - this._onError = (res) => { - this._triggerEvent('error', res) - this._decreaseCount(); - } - my.onSocketError(this._onError) - - this._onClose = (res) => { - this.readyState = WebSocket.CLOSED - this._triggerEvent('close') - this._removeAllSocketListenr() - this._decreaseCount(); - } - my.onSocketClose(this._onClose) - - return this - } - - close() { - this.readyState = WebSocket.CLOSING - my.closeSocket() - } - - send(data) { - if (typeof data !== 'string' && !(data instanceof ArrayBuffer) && !ArrayBuffer.isView(data)) { - throw new TypeError(`Failed to send message: The data ${data} is invalid`) - }else{ - var isBuffer = false; - if (data instanceof ArrayBuffer) { - data = _utils.arrayBufferToBase64(data) - isBuffer = true - } - - my.sendSocketMessage({ - data, - isBuffer, - fail: function (res) { - this._triggerEvent('error', res) - } - }); - } - } - - _triggerEvent(type, ...args) { - if (typeof this[`on${type}`] === 'function') { - this[`on${type}`].apply(this, args) - } - } - - _removeAllSocketListenr(){ - my.offSocketOpen(this._onOpen) - my.offSocketMessage(this._onMessage) - my.offSocketError(this._onError) - my.offSocketClose(this._onClose) - - this._onOpen = null - this._onMessage = null - this._onError = null - this._onClose = null - } - - _increaseCount(){ - CURR_AMOUNT_WEBSOCKET += 1 - } - - _decreaseCount(){ - if(!this._isReduced){ - CURR_AMOUNT_WEBSOCKET -= 1 - this._isReduced = true - } - } - - _isMaxCount(){ - return CURR_AMOUNT_WEBSOCKET >= MAX_AMOUNT_WEBSOCKET - } -} diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/WindowProperties.js b/platforms/minigame/platforms/taobao/wrapper/builtin/WindowProperties.js deleted file mode 100644 index 7160e83b87..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/WindowProperties.js +++ /dev/null @@ -1,31 +0,0 @@ -const { pixelRatio, windowWidth, windowHeight } = my.getSystemInfoSync() -const devicePixelRatio = pixelRatio; - -let width, height; -if ($global.screencanvas.getBoundingClientRect) { - let rect = $global.screencanvas.getBoundingClientRect(); - width = rect.width; - height = rect.height; -} else { - width = windowWidth; - height = windowHeight; -} -export const innerWidth = width; -export const innerHeight = height; -export { devicePixelRatio } -export const screen = { - width, - height, - availWidth: innerWidth, - availHeight: innerHeight, - availLeft: 0, - availTop: 0, -} - -export const performance = { - now: Date.now -}; - -export const ontouchstart = null; -export const ontouchmove = null; -export const ontouchend = null; \ No newline at end of file diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/XMLHttpRequest.js b/platforms/minigame/platforms/taobao/wrapper/builtin/XMLHttpRequest.js deleted file mode 100644 index 018ad79ff7..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/XMLHttpRequest.js +++ /dev/null @@ -1,172 +0,0 @@ -import EventTarget from './EventTarget.js' - -const _url = new WeakMap() -const _method = new WeakMap() -const _requestHeader = new WeakMap() -const _responseHeader = new WeakMap() -const _requestTask = new WeakMap() - -function _triggerEvent(type, ...args) { - if (typeof this[`on${type}`] === 'function') { - this[`on${type}`].apply(this, args) - } -} - -function _changeReadyState(readyState) { - this.readyState = readyState - _triggerEvent.call(this, 'readystatechange') -} - -export default class XMLHttpRequest extends EventTarget { - // TODO: No way to simulate HEADERS_RECEIVED and LOADING states - static UNSEND = 0 - static OPENED = 1 - static HEADERS_RECEIVED = 2 - static LOADING = 3 - static DONE = 4 - - timeout = 0; - /* - * TODO: This batch of events should be on top of the XMLHttpRequestEventTarget.prototype - */ - onabort = null - onerror = null - onload = null - onloadstart = null - onprogress = null - ontimeout = null - onloadend = null - - onreadystatechange = null - readyState = 0 - response = null - responseText = null - responseType = '' - responseXML = null - status = 0 - statusText = '' - upload = {} - withCredentials = false - - constructor() { - super(); - - _requestHeader.set(this, { - 'content-type': 'application/json' - }) - _responseHeader.set(this, {}) - } - - abort() { - const myRequestTask = _requestTask.get(this) - - if (myRequestTask) { - myRequestTask.abort() - } - } - - getAllResponseHeaders() { - const responseHeader = _responseHeader.get(this) - - return Object.keys(responseHeader).map((header) => { - return `${header}: ${responseHeader[header]}` - }).join('\n') - } - - getResponseHeader(header) { - return _responseHeader.get(this)[header] - } - - open(method, url/* async, user, password. These parameters are not supported within the applet*/) { - _method.set(this, method) - _url.set(this, url) - _changeReadyState.call(this, XMLHttpRequest.OPENED) - } - - overrideMimeType() { - } - - send(data = '') { - if (this.readyState !== XMLHttpRequest.OPENED) { - throw new Error("Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.") - } else { - let myRequestTask = my.request({ - data, - url: _url.get(this), - method: _method.get(this), - headers: _requestHeader.get(this), - dataType: 'other', - responseType: this.responseType === 'arraybuffer' ? 'arraybuffer' : 'text', - timeout: this.timeout || undefined, - success: ({ data, status, headers }) => { - this.status = status - _responseHeader.set(this, headers) - _triggerEvent.call(this, 'loadstart') - _changeReadyState.call(this, XMLHttpRequest.HEADERS_RECEIVED) - _changeReadyState.call(this, XMLHttpRequest.LOADING) - - switch (this.responseType) { - case 'json': - this.responseText = data; - try { - this.response = JSON.parse(data); - } - catch (e) { - this.response = null; - } - break; - case '': - case 'text': - this.responseText = this.response = data; - break; - case 'arraybuffer': - this.response = data; - this.responseText = ''; - var bytes = new Uint8Array(data); - var len = bytes.byteLength; - - for (var i = 0; i < len; i++) { - this.responseText += String.fromCharCode(bytes[i]); - } - break; - default: - this.response = null; - } - _changeReadyState.call(this, XMLHttpRequest.DONE) - _triggerEvent.call(this, 'load') - _triggerEvent.call(this, 'loadend') - }, - fail: ({ error, errorMessage }) => { - // TODO 规范错误 - if (9 === error || errorMessage.indexOf('abort') !== -1) { - _triggerEvent.call(this, 'abort') - } else if (13 === error || errorMessage.indexOf('超时') !== -1) { - _triggerEvent.call(this, 'timeout') - } else { - _triggerEvent.call(this, 'error', errorMessage) - } - _triggerEvent.call(this, 'loadend') - } - }) - - _requestTask.set(this, myRequestTask); - } - } - - setRequestHeader(header, value) { - const myHeader = _requestHeader.get(this) - - myHeader[header] = value - _requestHeader.set(this, myHeader) - } - - addEventListener(type, listener) { - if (typeof listener === 'function') { - let _this = this - let event = { target: _this } - this['on' + type] = function (event) { - listener.call(_this, event) - } - } - } -} diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/cancelAnimationFrame.js b/platforms/minigame/platforms/taobao/wrapper/builtin/cancelAnimationFrame.js deleted file mode 100644 index c688495901..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/cancelAnimationFrame.js +++ /dev/null @@ -1,4 +0,0 @@ -let screencanvas = $global.screencanvas; -let cancelAnimationFrame = screencanvas.cancelAnimationFrame.bind(screencanvas); - -export default cancelAnimationFrame; \ No newline at end of file diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/document.js b/platforms/minigame/platforms/taobao/wrapper/builtin/document.js deleted file mode 100644 index 7a3cadfbf8..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/document.js +++ /dev/null @@ -1,124 +0,0 @@ -import * as _window from './window' -import HTMLElement from './HTMLElement' -import Image from './Image' -import Canvas from './Canvas' -import Audio from './Audio' - -const events = {} - -var document = { - readyState: 'complete', - visibilityState: 'visible', - documentElement: _window, - hidden: false, - style: {}, - location: _window.location, - ontouchstart: null, - ontouchmove: null, - ontouchend: null, - - head: new HTMLElement('head'), - body: new HTMLElement('body'), - - createElement(tagName) { - tagName = tagName.toLowerCase(); - if (tagName === 'canvas') { - return new Canvas() - } else if (tagName === 'audio') { - return new Audio() - } else if (tagName === 'img') { - return new Image() - } - - return new HTMLElement(tagName) - }, - - createElementNS(nameSpace, tagName) { - return this.createElement(tagName); - }, - - getElementById(id) { - if (id === _window.canvas.id) { - return _window.canvas - } - return null - }, - - getElementsByTagName(tagName) { - if (tagName === 'head') { - return [document.head] - } else if (tagName === 'body') { - return [document.body] - } else if (tagName === 'canvas') { - return [_window.canvas] - } - return [] - }, - - getElementsByName(tagName) { - if (tagName === 'head') { - return [document.head] - } else if (tagName === 'body') { - return [document.body] - } else if (tagName === 'canvas') { - return [_window.canvas] - } - return [] - }, - - querySelector(query) { - if (query === 'head') { - return document.head - } else if (query === 'body') { - return document.body - } else if (query === 'canvas') { - return _window.canvas - } else if (query === `#${_window.canvas.id}`) { - return _window.canvas - } - return null - }, - - querySelectorAll(query) { - if (query === 'head') { - return [document.head] - } else if (query === 'body') { - return [document.body] - } else if (query === 'canvas') { - return [_window.canvas] - } - return [] - }, - - addEventListener(type, listener) { - if (!events[type]) { - events[type] = [] - } - events[type].push(listener) - }, - - removeEventListener(type, listener) { - const listeners = events[type] - - if (listeners && listeners.length > 0) { - for (let i = listeners.length; i--; i > 0) { - if (listeners[i] === listener) { - listeners.splice(i, 1) - break - } - } - } - }, - - dispatchEvent(event) { - const listeners = events[event.type] - - if (listeners) { - for (let i = 0; i < listeners.length; i++) { - listeners[i](event) - } - } - } -} - -export { document } diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/index.js b/platforms/minigame/platforms/taobao/wrapper/builtin/index.js deleted file mode 100644 index 4af45c9326..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/index.js +++ /dev/null @@ -1,64 +0,0 @@ -import * as _window from './window' -import { document } from './document' - -var global = $global; - -function inject () { - // Expose the global canvas - _window.canvas = $global.screencanvas; - _window.document = document; - - _window.addEventListener = (type, listener) => { - _window.document.addEventListener(type, listener) - } - _window.removeEventListener = (type, listener) => { - _window.document.removeEventListener(type, listener) - } - _window.dispatchEvent = _window.document.dispatchEvent; - - const { platform } = my.getSystemInfoSync() - - // Developer tools cannot redefine window - if (typeof __devtoolssubcontext === 'undefined' && platform === 'devtools') { - for (const key in _window) { - const descriptor = Object.getOwnPropertyDescriptor(global, key) - - if (!descriptor || descriptor.configurable === true) { - Object.defineProperty(window, key, { - value: _window[key] - }) - } - } - - for (const key in _window.document) { - const descriptor = Object.getOwnPropertyDescriptor(global.document, key) - - if (!descriptor || descriptor.configurable === true) { - Object.defineProperty(global.document, key, { - value: _window.document[key] - }) - } - } - window.parent = window - } else { - for (const key in _window) { - global[key] = _window[key] - } - // global.window = _window - // window = global - // window.top = window.parent = window - } - - global.setTimeout = setTimeout; - global.clearTimeout = clearTimeout; - global.setInterval = setInterval; - global.clearInterval = clearInterval; -} - -if (!global.__isAdapterInjected) { - global.__isAdapterInjected = true - inject() -} - -require('../../../../common/xmldom/dom-parser'); -require('../unify'); diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/localStorage.js b/platforms/minigame/platforms/taobao/wrapper/builtin/localStorage.js deleted file mode 100644 index 7f4ed0de2d..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/localStorage.js +++ /dev/null @@ -1,37 +0,0 @@ -const localStorage = { - get length() { - const { keys } = my.getStorageInfoSync() - - return keys.length - }, - - key(n) { - const { keys } = my.getStorageInfoSync() - - return keys[n] - }, - - getItem(key) { - let ret = my.getStorageSync({ - key, - }); - return ret && ret.data; - }, - - setItem(key, data) { - return my.setStorageSync({ - key, - data, - }); - }, - - removeItem(key) { - my.removeStorageSync(key) - }, - - clear() { - my.clearStorageSync() - } -} - -export default localStorage diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/location.js b/platforms/minigame/platforms/taobao/wrapper/builtin/location.js deleted file mode 100644 index 010f31bbac..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/location.js +++ /dev/null @@ -1,8 +0,0 @@ -const location = { - href: 'game.js', - protocol: '', - reload () { - }, -}; - -export default location; diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/navigator.js b/platforms/minigame/platforms/taobao/wrapper/builtin/navigator.js deleted file mode 100644 index 7a0990afaf..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/navigator.js +++ /dev/null @@ -1,38 +0,0 @@ -import { noop } from './util/index.js' - -// TODO: Need my.getSystemInfo for more details -const systemInfo = my.getSystemInfoSync() -console.log(systemInfo) - -const system = systemInfo.system; -const platform = systemInfo.platform; -const language = systemInfo.language; -const version = systemInfo.version; - -const android = system ? system.toLowerCase().indexOf('android') !== -1 : false; - -const uaDesc = android ? `Android; CPU ${system}` : `iPhone; CPU iPhone OS ${system} like Mac OS X`; -const ua = `Mozilla/5.0 (${uaDesc}) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E8301 MicroMessenger/${version} MiniGame NetType/WIFI Language/${language}`; - -const navigator = { - platform, - language: language, - appVersion: `5.0 (${uaDesc}) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1`, - userAgent: ua, - onLine: true, // TODO: Use my.getNetworkStateChange and my.onNetworkStateChange to return the real state - - // TODO: Wrap the geolocation with my.getLocation - geolocation: { - getCurrentPosition: noop, - watchPosition: noop, - clearWatch: noop - } -} - -if (my.onNetworkStatusChange) { - my.onNetworkStatusChange(function(event){ - navigator.onLine = event.isConnected; - }); -} - -export default navigator diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/requestAnimationFrame.js b/platforms/minigame/platforms/taobao/wrapper/builtin/requestAnimationFrame.js deleted file mode 100644 index d6f8366904..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/requestAnimationFrame.js +++ /dev/null @@ -1,4 +0,0 @@ -let screencanvas = $global.screencanvas; -let requestAnimationFrame = screencanvas.requestAnimationFrame.bind(screencanvas); - -export default requestAnimationFrame; \ No newline at end of file diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/util/index.js b/platforms/minigame/platforms/taobao/wrapper/builtin/util/index.js deleted file mode 100644 index 177804c7ab..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/util/index.js +++ /dev/null @@ -1 +0,0 @@ -export function noop() {} diff --git a/platforms/minigame/platforms/taobao/wrapper/builtin/window.js b/platforms/minigame/platforms/taobao/wrapper/builtin/window.js deleted file mode 100644 index b014eb920c..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/builtin/window.js +++ /dev/null @@ -1,15 +0,0 @@ -export navigator from './navigator' -export XMLHttpRequest from './XMLHttpRequest' -export WebSocket from './WebSocket' -export Image from './Image' -export ImageBitmap from './ImageBitmap' -export HTMLElement from './HTMLElement' -export HTMLImageElement from './HTMLImageElement' -export HTMLCanvasElement from './HTMLCanvasElement' -export WebGLRenderingContext from './WebGLRenderingContext' -export localStorage from './localStorage' -export location from './location' -export requestAnimationFrame from './requestAnimationFrame' -export cancelAnimationFrame from './cancelAnimationFrame' -export * from './WindowProperties' - diff --git a/platforms/minigame/platforms/taobao/wrapper/engine/AssetManager.js b/platforms/minigame/platforms/taobao/wrapper/engine/AssetManager.js deleted file mode 100644 index 27007db0e1..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/engine/AssetManager.js +++ /dev/null @@ -1,72 +0,0 @@ -const parser = cc.assetManager.parser; -const downloader = cc.assetManager.downloader; -const debug = cc.debug; - -function doNothing (url, options, onComplete) { - onComplete(null, url); -} - -// TODO: Image can't load from cached downloaded file on Taobao IDE -if (my.isIDE) { - downloader.register({ - '.png': doNothing, - '.jpg': doNothing, - '.bmp': doNothing, - '.jpeg': doNothing, - '.gif': doNothing, - '.ico': doNothing, - '.tiff': doNothing, - '.image': doNothing, - '.webp': doNothing, - }); -} - -// TODO: Audio can't load from cached downloaded file onTaoBao -downloader.register({ - '.mp3': doNothing, - '.ogg': doNothing, - '.wav': doNothing, - '.m4a': doNothing, -}); - -function loadImage (url, options, onComplete) { - const img = window.screencanvas.createImage(); - - function loadCallback () { - img.onload = null; - img.onerror = null; - - if (onComplete) { - onComplete(null, img); - } - } - - function errorCallback () { - img.onload = null; - img.onerror = null; - - if (onComplete) { - onComplete(new Error(debug.getError(4930, url))); - } - } - - img.onload = loadCallback; - img.onerror = errorCallback; - img.src = url; - return img; -} - -downloader.downloadDomImage = loadImage; - -parser.register({ - // Image - '.png': loadImage, - '.jpg': loadImage, - '.bmp': loadImage, - '.jpeg': loadImage, - '.gif': loadImage, - '.ico': loadImage, - '.tiff': loadImage, - '.image': loadImage, - '.webp': loadImage, -}); diff --git a/platforms/minigame/platforms/taobao/wrapper/engine/Editbox.js b/platforms/minigame/platforms/taobao/wrapper/engine/Editbox.js deleted file mode 100644 index 530133d6db..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/engine/Editbox.js +++ /dev/null @@ -1,91 +0,0 @@ -(function () { - if (!(cc && cc.internal && cc.internal.EditBox)) { - return; - } - - const EditBox = cc.internal.EditBox; - const js = cc.js; - const KeyboardReturnType = EditBox.KeyboardReturnType; - const MAX_VALUE = 65535; - - function getKeyboardReturnType (type) { - switch (type) { - case KeyboardReturnType.DEFAULT: - case KeyboardReturnType.DONE: - return 'done'; - case KeyboardReturnType.SEND: - return 'send'; - case KeyboardReturnType.SEARCH: - return 'search'; - case KeyboardReturnType.GO: - return 'go'; - case KeyboardReturnType.NEXT: - return 'next'; - } - return 'done'; - } - - const BaseClass = EditBox._EditBoxImpl; - function MiniGameEditBoxImpl () { - BaseClass.call(this); - } - - js.extend(MiniGameEditBoxImpl, BaseClass); - EditBox._EditBoxImpl = MiniGameEditBoxImpl; - - Object.assign(MiniGameEditBoxImpl.prototype, { - init (delegate) { - if (!delegate) { - cc.error('EditBox init failed'); - return; - } - this._delegate = delegate; - }, - - beginEditing () { - // In case multiply register events - if (this._editing) { - return; - } - const delegate = this._delegate; - this._showPrompt(); - this._editing = true; - delegate._editBoxEditingDidBegan(); - }, - - endEditing () { - cc.warn(`Can't support to end editing.`); - }, - - _showPrompt () { - const self = this; - const delegate = this._delegate; - const multiline = (delegate.inputMode === EditBox.InputMode.ANY); - const maxLength = (delegate.maxLength < 0 ? MAX_VALUE : delegate.maxLength); - - if (multiline) { - cc.warn(`Multiline editing is not supported`); - } - - my.prompt({ - title: '', - message: delegate.placeholder, - // placeholder: delegate.placeholder, - okButtonText: getKeyboardReturnType(delegate.returnType), - cancelButtonText: 'cancel', - success: (result) => { - if (result.ok) { - let inputValue = result.inputValue; - inputValue = (maxLength <= inputValue.length) ? inputValue.substring(0, maxLength) : inputValue; - if (delegate._string !== inputValue) { - delegate._editBoxTextChanged(inputValue); - } - delegate._editBoxEditingReturn(); - } - self._editing = false; - delegate._editBoxEditingDidEnded(); - }, - }); - }, - }); -}()); diff --git a/platforms/minigame/platforms/taobao/wrapper/engine/Label.js b/platforms/minigame/platforms/taobao/wrapper/engine/Label.js deleted file mode 100644 index a03cd8c263..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/engine/Label.js +++ /dev/null @@ -1,22 +0,0 @@ -if (cc && cc.Label) { - const Label = cc.Label; - - // shared label canvas - const _sharedLabelCanvas = my.createOffscreenCanvas(); - const _sharedLabelCanvasCtx = _sharedLabelCanvas.getContext('2d'); - const canvasData = { - canvas: _sharedLabelCanvas, - context: _sharedLabelCanvasCtx, - }; - cc.game.on(cc.game.EVENT_ENGINE_INITED, () => { - Object.assign(Label._canvasPool, { - get () { - return canvasData; - }, - - put () { - // do nothing - }, - }); - }); -} diff --git a/platforms/minigame/platforms/taobao/wrapper/engine/index.js b/platforms/minigame/platforms/taobao/wrapper/engine/index.js deleted file mode 100644 index 563320cd45..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/engine/index.js +++ /dev/null @@ -1,5 +0,0 @@ -require('../fs-utils'); -require('../../../../common/engine/index'); -require('./AssetManager.js'); -require('./Label.js'); -require('./Editbox.js'); diff --git a/platforms/minigame/platforms/taobao/wrapper/fs-utils.js b/platforms/minigame/platforms/taobao/wrapper/fs-utils.js deleted file mode 100644 index 59d9fd0fe7..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/fs-utils.js +++ /dev/null @@ -1,259 +0,0 @@ -/**************************************************************************** - Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated 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. - ****************************************************************************/ -/* eslint-disable no-undef */ - -const fs = my.getFileSystemManager ? my.getFileSystemManager() : null; -const outOfStorageRegExp = /the maximum size of the file storage/; // not exactly right - -const fsUtils = { - - fs, - - isOutOfStorage (errMsg) { - return outOfStorageRegExp.test(errMsg); - }, - - getUserDataPath () { - return my.env.USER_DATA_PATH; - }, - - checkFsValid () { - if (!fs) { - console.warn('Can not get the file system!'); - return false; - } - return true; - }, - - deleteFile (filePath, onComplete) { - fs.unlink({ - filePath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Delete file failed: path: ${filePath} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.errorMessage)); - }, - }); - }, - - downloadFile (remoteUrl, filePath, header, onProgress, onComplete) { - const options = { - url: remoteUrl, - success (res) { - if (!filePath) { - onComplete && onComplete(null, res.apFilePath); - } else { - fsUtils.copyFile(res.apFilePath, filePath, onComplete); - } - }, - fail (res) { - console.warn(`Download file failed: path: ${remoteUrl} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.errorMessage), null); - }, - }; - if (header) options.header = header; - const task = my.downloadFile(options); - onProgress && task.onProgressUpdate(onProgress); - }, - - saveFile (srcPath, destPath, onComplete) { - // Hack, seems like my.saveFile dose not work - fsUtils.copyFile(srcPath, destPath, onComplete); - }, - - copyFile (srcPath, destPath, onComplete) { - fs.copyFile({ - srcPath, - destPath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Copy file failed: path: ${srcPath} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.errorMessage)); - }, - }); - }, - - writeFile (path, data, encoding, onComplete) { - fs.writeFile({ - filePath: path, - encoding, - data, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Write file failed: path: ${path} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.errorMessage)); - }, - }); - }, - - writeFileSync (path, data, encoding) { - try { - fs.writeFileSync({ - filePath: path, - data, - encoding, - }); - return null; - } catch (e) { - console.warn(`Write file failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - readFile (filePath, encoding, onComplete) { - fs.readFile({ - filePath, - encoding, - success (res) { - onComplete && onComplete(null, res.data); - }, - fail (res) { - console.warn(`Read file failed: path: ${filePath} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.errorMessage), null); - }, - }); - }, - - readDir (filePath, onComplete) { - fs.readdir({ - dirPath: filePath, - success (res) { - onComplete && onComplete(null, res.files); - }, - fail (res) { - console.warn(`Read directory failed: path: ${filePath} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(res.errorMessage), null); - }, - }); - }, - - readText (filePath, onComplete) { - fsUtils.readFile(filePath, 'utf8', onComplete); - }, - - readArrayBuffer (filePath, onComplete) { - fsUtils.readFile(filePath, '', onComplete); - }, - - readJson (filePath, onComplete) { - fsUtils.readFile(filePath, 'utf8', (err, text) => { - let out = null; - if (!err) { - try { - out = JSON.parse(text); - } catch (e) { - console.warn(`Read json failed: path: ${filePath} message: ${e.message}`); - err = new Error(e.message); - } - } - onComplete && onComplete(err, out); - }); - }, - - readJsonSync (path) { - try { - const res = fs.readFileSync({ - filePath: path, - encoding: 'utf8', - }); - return JSON.parse(res.data); - } catch (e) { - console.warn(`Read json failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - makeDirSync (path, recursive) { - try { - fs.mkdirSync({ - dirPath: path, - recursive, - }); - return null; - } catch (e) { - console.warn(`Make directory failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - rmdirSync (dirPath, recursive) { - try { - fs.rmdirSync({ dirPath, recursive }); - return null; - } catch (e) { - console.warn(`rm directory failed: path: ${dirPath} message: ${e.message}`); - return new Error(e.message); - } - }, - - exists (filePath, onComplete) { - // fs.access is not supported. - // fs.access({ - // path: filePath, - // success: function () { - // onComplete && onComplete(true); - // }, - // fail: function () { - // onComplete && onComplete(false); - // } - // }); - fs.readFile({ - filePath, - success () { - onComplete && onComplete(true); - }, - fail () { - onComplete && onComplete(false); - }, - }); - }, - - // eslint-disable-next-line no-unused-vars - loadSubpackage (name, onProgress, onComplete) { - throw new Error('Not Implemented'); - }, - - unzip (zipFilePath, targetPath, onComplete) { - fs.unzip({ - zipFilePath, - targetPath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`unzip failed: path: ${zipFilePath} message: ${res.errorMessage}`); - onComplete && onComplete(new Error(`unzip failed: ${res.errorMessage}`)); - }, - }); - }, -}; - -window.fsUtils = module.exports = fsUtils; diff --git a/platforms/minigame/platforms/taobao/wrapper/unify.js b/platforms/minigame/platforms/taobao/wrapper/unify.js deleted file mode 100644 index aba15f3950..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/unify.js +++ /dev/null @@ -1,149 +0,0 @@ -const utils = require('./utils'); - -function handleTouchEvent (event) { - let changedTouches = event.changedTouches; - if (changedTouches) { - for (let touch of changedTouches) { - touch.clientX = touch.x; - touch.clientY = touch.y; - } - } -} - -my.onTouchStart = function (cb) { - $global._touchstartCB = function (event) { - handleTouchEvent(event); - cb(event); - }; -}; -my.onTouchCancel = function (cb) { - $global._touchcancelCB = function (event) { - handleTouchEvent(event); - cb(event); - }; -}; -my.onTouchEnd = function (cb) { - $global._touchendCB = function (event) { - handleTouchEvent(event); - cb(event); - }; -}; -my.onTouchMove = function (cb) { - $global._touchmoveCB = function (event) { - handleTouchEvent(event); - cb(event); - }; -}; - -my.onShow = function (cb) { - $global._onShowCB = cb; -}; -my.onHide = function (cb) { - $global._onHideCB = cb; -}; - -window.__globalAdapter = window.__globalAdapter || {}; -if (window.__globalAdapter) { - let globalAdapter = window.__globalAdapter; - // SystemInfo - globalAdapter.isSubContext = false; // sub context not supported - globalAdapter.isDevTool = my.isIDE; - utils.cloneMethod(globalAdapter, my, 'getSystemInfoSync'); - - // Audio - globalAdapter.createInnerAudioContext = function () { - let audio = my.createInnerAudioContext(); - if (my.getSystemInfoSync().platform === 'iOS') { - let currentTime = 0; - let originalSeek = audio.seek; - audio.seek = function (time) { - // need to access audio.paused in the next tick - setTimeout(() => { - if (audio.paused) { - currentTime = time; - } else { - originalSeek.call(audio, time); - } - }, 50); - }; - - let originalPlay = audio.play; - audio.play = function () { - if (currentTime !== 0) { - audio.seek(currentTime); - currentTime = 0; // clear cached currentTime - } - originalPlay.call(audio); - }; - } - return audio; - }; - - // FrameRate - // utils.cloneMethod(globalAdapter, my, 'setPreferredFramesPerSecond'); - - // Keyboard - globalAdapter.showKeyboard = () => console.warn('showKeyboard not supported.'); - globalAdapter.hideKeyboard = () => console.warn('hideKeyboard not supported.'); - globalAdapter.updateKeyboard = () => console.warn('updateKeyboard not supported.'); - globalAdapter.onKeyboardInput = () => console.warn('onKeyboardInput not supported.'); - globalAdapter.onKeyboardConfirm = () => console.warn('onKeyboardConfirm not supported.'); - globalAdapter.onKeyboardComplete = () => console.warn('onKeyboardComplete not supported.'); - globalAdapter.offKeyboardInput = () => console.warn('offKeyboardInput not supported.'); - globalAdapter.offKeyboardConfirm = () => console.warn('offKeyboardConfirm not supported.'); - globalAdapter.offKeyboardComplete = () => console.warn('offKeyboardComplete not supported.'); - - // Message - utils.cloneMethod(globalAdapter, my, 'getOpenDataContext'); - utils.cloneMethod(globalAdapter, my, 'onMessage'); - - // Subpackage not supported - // utils.cloneMethod(globalAdapter, my, 'loadSubpackage'); - - // SharedCanvas - utils.cloneMethod(globalAdapter, my, 'getSharedCanvas'); - - // Font - globalAdapter.loadFont = function (url) { - // my.loadFont crash when url is not in user data path - return "Arial"; - }; - - // hide show Event - utils.cloneMethod(globalAdapter, my, 'onShow'); - utils.cloneMethod(globalAdapter, my, 'onHide'); - - // Accelerometer - let accelerometerCallback = null; - let systemInfo = my.getSystemInfoSync(); - let windowWidth = systemInfo.windowWidth; - let windowHeight = systemInfo.windowHeight; - let isLandscape = windowWidth > windowHeight; - function accelerometerChangeCallback (res, cb) { - let resClone = {}; - - let x = res.x; - let y = res.y; - - if (isLandscape) { - let tmp = x; - x = -y; - y = tmp; - } - - resClone.x = x; - resClone.y = y; - resClone.z = res.z; - accelerometerCallback && accelerometerCallback(resClone); - } - Object.assign(globalAdapter, { - startAccelerometer (cb) { - accelerometerCallback = cb; - my.onAccelerometerChange && my.onAccelerometerChange(accelerometerChangeCallback); - }, - - stopAccelerometer () { - my.offAccelerometerChange && my.offAccelerometerChange(accelerometerChangeCallback); - }, - }); -} \ No newline at end of file diff --git a/platforms/minigame/platforms/taobao/wrapper/utils.js b/platforms/minigame/platforms/taobao/wrapper/utils.js deleted file mode 100644 index 3ead0b6528..0000000000 --- a/platforms/minigame/platforms/taobao/wrapper/utils.js +++ /dev/null @@ -1,111 +0,0 @@ -const utils = { - /** - * @param {Object} target - * @param {Object} origin - * @param {String} methodName - * @param {String} targetMethodName - */ - cloneMethod (target, origin, methodName, targetMethodName) { - if (origin[methodName]) { - targetMethodName = targetMethodName || methodName; - target[targetMethodName] = origin[methodName].bind(origin); - } - }, - - /** - * - * @param {String} str - * @returns - */ - encode (str) { - let encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - const string = String(str); - let result = ''; - let currentIndex = 0; - let sum = void 0; - while (string.charAt(0 | currentIndex) || (encodings = '=', currentIndex % 1)) { - currentIndex += 0.75; - const currentCode = string.charCodeAt(currentIndex); - if (currentCode > 255) { - // Cannot handle when it is greater than 255 - throw new Error('"btoa" failed'); - } - sum = sum << 8 | currentCode; - const encodeIndex = 63 & sum >> 8 - currentIndex % 1 * 8; - result += encodings.charAt(encodeIndex); - } - - return result; - }, - - /** - * - * @param {String} str - */ - decode (str) { - const encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - let res = ''; - const string = String(str).replace(/[=]+$/, ''); - let o; - let r; - let i = 0; - let currentIndex = 0; - while (r = string.charAt(currentIndex)) { - currentIndex += 1; - r = encodings.indexOf(r); - if (~r) { - o = i % 4 ? 64 * o + r : r; - if (i++ % 4) { - res += String.fromCharCode(255 & o >> (-2 * i & 6)); - } - } - } - - return res; - }, - - /** - * - * @param {ArrayBuffer} buffer - */ - arrayBufferToBase64 (buffer) { - return utils.encode(utils.arrayBufferToString(buffer)); - }, - - /** - * - * @param {String} base64 - */ - base64ToArrayBuffer (base64) { - return utils.stringToArrayBuffer(utils.decode(base64)); - }, - - /** - * - * @param {ArrayBuffer} buffer - */ - arrayBufferToString (buffer) { - let result = ''; - const uintArray = new Uint8Array(buffer); - const byteLength = uintArray.byteLength; - for (let i = 0; i < byteLength; i++) { - result += String.fromCharCode(uintArray[i]); - } - return result; - }, - - /** - * - * @param {String} string - */ - stringToArrayBuffer (string) { - const length = string.length; - const uintArray = new Uint8Array(length); - for (let i = 0; i < length; i++) { - uintArray[i] = string.charCodeAt(i); - } - return uintArray.buffer; - }, -}; - -module.exports = utils; diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/Audio.js b/platforms/minigame/platforms/wechat/wrapper/builtin/Audio.js deleted file mode 100644 index a96fffa0b0..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/Audio.js +++ /dev/null @@ -1,205 +0,0 @@ -import HTMLAudioElement from './HTMLAudioElement' - -const HAVE_NOTHING = 0 -const HAVE_METADATA = 1 -const HAVE_CURRENT_DATA = 2 -const HAVE_FUTURE_DATA = 3 -const HAVE_ENOUGH_DATA = 4 - -let SN_SEED = 1 - -const _innerAudioContextMap = {} - -export default class Audio extends HTMLAudioElement { - - constructor(url) { - super() - - this._$sn = SN_SEED++; - - this.HAVE_NOTHING = HAVE_NOTHING - this.HAVE_METADATA = HAVE_METADATA - this.HAVE_CURRENT_DATA = HAVE_CURRENT_DATA - this.HAVE_FUTURE_DATA = HAVE_FUTURE_DATA - this.HAVE_ENOUGH_DATA = HAVE_ENOUGH_DATA - - this.readyState = HAVE_NOTHING - - const innerAudioContext = wx.createInnerAudioContext() - - _innerAudioContextMap[this._$sn] = innerAudioContext - - this._canplayEvents = [ - 'load', - 'loadend', - 'canplay', - 'canplaythrough', - 'loadedmetadata' - ] - - innerAudioContext.onCanplay(() => { - this._loaded = true - this.readyState = this.HAVE_CURRENT_DATA - this._canplayEvents.forEach((type) => { - this.dispatchEvent({ type: type }) - }) - }) - innerAudioContext.onPlay(() => { - this._paused = _innerAudioContextMap[this._$sn].paused - this.dispatchEvent({ type: 'play' }) - }) - innerAudioContext.onPause(() => { - this._paused = _innerAudioContextMap[this._$sn].paused - this.dispatchEvent({ type: 'pause' }) - }) - innerAudioContext.onEnded(() => { - this._paused = _innerAudioContextMap[this._$sn].paused - if (_innerAudioContextMap[this._$sn].loop === false) { - this.dispatchEvent({ type: 'ended' }) - } - this.readyState = HAVE_ENOUGH_DATA - }) - innerAudioContext.onError(() => { - this._paused = _innerAudioContextMap[this._$sn].paused - this.dispatchEvent({ type: 'error' }) - }) - - if (url) { - this.src = url - } else { - this._src = '' - } - - this._loop = innerAudioContext.loop - this._autoplay = innerAudioContext.autoplay - this._paused = innerAudioContext.paused - this._volume = innerAudioContext.volume - this._muted = false; - } - - addEventListener(type, listener, options = {}) { - super.addEventListener(type, listener, options) - - type = String(type).toLowerCase() - - if (this._loaded && this._canplayEvents.indexOf(type) !== -1) { - this.dispatchEvent({ type: type }) - } - } - - load() { - // console.warn('HTMLAudioElement.load() is not implemented.') - // weixin doesn't need call load() manually - } - - play() { - _innerAudioContextMap[this._$sn].play() - } - - resume() { - _innerAudioContextMap[this._$sn].resume() - } - - pause() { - _innerAudioContextMap[this._$sn].pause() - } - - stop() { - _innerAudioContextMap[this._$sn].stop() - } - - destroy() { - _innerAudioContextMap[this._$sn].destroy() - } - - canPlayType(mediaType = '') { - if (typeof mediaType !== 'string') { - return '' - } - - if (mediaType.indexOf('audio/mpeg') > -1 || mediaType.indexOf('audio/mp4')) { - return 'probably' - } - return '' - } - - get currentTime() { - return _innerAudioContextMap[this._$sn].currentTime - } - - set currentTime(value) { - _innerAudioContextMap[this._$sn].seek(value) - } - - get duration () { - return _innerAudioContextMap[this._$sn].duration - } - - get src() { - return this._src - } - - set src(value) { - this._src = value - this._loaded = false - this.readyState = this.HAVE_NOTHING - - const innerAudioContext = _innerAudioContextMap[this._$sn] - - innerAudioContext.src = value - } - - get loop() { - return this._loop - } - - set loop(value) { - this._loop = value - _innerAudioContextMap[this._$sn].loop = value - } - - get autoplay() { - return this.autoplay - } - - set autoplay(value) { - this._autoplay = value - _innerAudioContextMap[this._$sn].autoplay = value - } - - get paused() { - return this._paused; - } - - get volume() { - return this._volume; - } - - set volume(value) { - this._volume = value; - if (!this._muted) { - _innerAudioContextMap[this._$sn].volume = value; - } - } - - get muted() { - return this._muted; - } - - set muted(value) { - this._muted = value; - if (value) { - _innerAudioContextMap[this._$sn].volume = 0; - } else { - _innerAudioContextMap[this._$sn].volume = this._volume; - } - } - - cloneNode() { - const newAudio = new Audio() - newAudio.loop = this.loop - newAudio.autoplay = this.autoplay - newAudio.src = this.src - return newAudio - } -} diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/Canvas.js b/platforms/minigame/platforms/wechat/wrapper/builtin/Canvas.js deleted file mode 100644 index e03474db03..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/Canvas.js +++ /dev/null @@ -1,74 +0,0 @@ -// import HTMLCanvasElement from './HTMLCanvasElement' -import { innerWidth, innerHeight } from './WindowProperties'; - -const hasModifiedCanvasPrototype = false; -const hasInit2DContextConstructor = false; -const hasInitWebGLContextConstructor = false; - -export default function Canvas () { - const canvas = wx.createCanvas(); - - canvas.type = 'canvas'; - - // canvas.__proto__.__proto__.__proto__ = new HTMLCanvasElement() - - const _getContext = canvas.getContext; - - canvas.getBoundingClientRect = () => { - const ret = { - top: 0, - left: 0, - width: window.innerWidth, - height: window.innerHeight, - }; - return ret; - }; - - canvas.style = { - top: '0px', - left: '0px', - width: `${innerWidth}px`, - height: `${innerHeight}px`, - }; - - canvas.addEventListener = function (type, listener, options = {}) { - if (typeof getApp === 'function') { - // for wechat miniprogram - GameGlobal.document.addEventListener(type, listener, options); - } else { - // for wechat minigame - document.addEventListener(type, listener, options); - } - }; - - canvas.removeEventListener = function (type, listener) { - if (typeof getApp === 'function') { - // for wechat miniprogram - GameGlobal.document.removeEventListener(type, listener); - } else { - // for wechat minigame - document.removeEventListener(type, listener); - } - }; - - canvas.dispatchEvent = function (event = {}) { - console.log('canvas.dispatchEvent', event.type, event); - // nothing to do - }; - - Object.defineProperty(canvas, 'clientWidth', { - enumerable: true, - get: function get () { - return innerWidth; - }, - }); - - Object.defineProperty(canvas, 'clientHeight', { - enumerable: true, - get: function get () { - return innerHeight; - }, - }); - - return canvas; -} diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/Element.js b/platforms/minigame/platforms/wechat/wrapper/builtin/Element.js deleted file mode 100644 index 965cd80d17..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/Element.js +++ /dev/null @@ -1,10 +0,0 @@ -import Node from './Node' - -export default class Element extends Node { - className = '' - children = [] - - constructor() { - super() - } -} diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/Event.js b/platforms/minigame/platforms/wechat/wrapper/builtin/Event.js deleted file mode 100644 index a7adc6a57b..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/Event.js +++ /dev/null @@ -1,14 +0,0 @@ -import {noop} from './util' - -export default class Event { - cancelBubble = false - cancelable = false - target = null - timestampe = Date.now() - preventDefault = noop - stopPropagation = noop - - constructor(type) { - this.type = type - } -} diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/EventIniter/MouseEvent.js b/platforms/minigame/platforms/wechat/wrapper/builtin/EventIniter/MouseEvent.js deleted file mode 100644 index 4a81e54c75..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/EventIniter/MouseEvent.js +++ /dev/null @@ -1,5 +0,0 @@ -export default class MouseEvent { - constructor() { - - } -} diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/EventIniter/TouchEvent.js b/platforms/minigame/platforms/wechat/wrapper/builtin/EventIniter/TouchEvent.js deleted file mode 100644 index 54e0aab281..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/EventIniter/TouchEvent.js +++ /dev/null @@ -1,38 +0,0 @@ -import { noop } from '../util/index.js' - -export default class TouchEvent { - touches = [] - targetTouches = [] - changedTouches = [] - preventDefault = noop - stopPropagation = noop - - constructor(type) { - this.type = type - this.target = window.canvas - this.currentTarget = window.canvas - } -} - -function touchEventHandlerFactory(type) { - return (event) => { - const touchEvent = new TouchEvent(type) - - touchEvent.touches = event.touches - touchEvent.targetTouches = Array.prototype.slice.call(event.touches) - touchEvent.changedTouches = event.changedTouches - touchEvent.timeStamp = event.timeStamp - if (typeof getApp === 'function') { - // for wechat miniprogram - GameGlobal.document.dispatchEvent(touchEvent) - } else { - // for wechat minigame - document.dispatchEvent(touchEvent) - } - } -} - -wx.onTouchStart(touchEventHandlerFactory('touchstart')) -wx.onTouchMove(touchEventHandlerFactory('touchmove')) -wx.onTouchEnd(touchEventHandlerFactory('touchend')) -wx.onTouchCancel(touchEventHandlerFactory('touchcancel')) diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/EventIniter/index.js b/platforms/minigame/platforms/wechat/wrapper/builtin/EventIniter/index.js deleted file mode 100644 index 5b5ffd24ff..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/EventIniter/index.js +++ /dev/null @@ -1,2 +0,0 @@ -export TouchEvent from './TouchEvent' -export MouseEvent from './MouseEvent' \ No newline at end of file diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/EventTarget.js b/platforms/minigame/platforms/wechat/wrapper/builtin/EventTarget.js deleted file mode 100644 index 573c3dbc9e..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/EventTarget.js +++ /dev/null @@ -1,57 +0,0 @@ -const _events = new WeakMap() - -export default class EventTarget { - constructor() { - _events.set(this, {}) - } - - addEventListener(type, listener, options = {}) { - let events = _events.get(this) - - if (!events) { - events = {} - _events.set(this, events) - } - if (!events[type]) { - events[type] = [] - } - events[type].push(listener) - - if (options.capture) { - // console.warn('EventTarget.addEventListener: options.capture is not implemented.') - } - if (options.once) { - // console.warn('EventTarget.addEventListener: options.once is not implemented.') - } - if (options.passive) { - // console.warn('EventTarget.addEventListener: options.passive is not implemented.') - } - } - - removeEventListener(type, listener) { - const events = _events.get(this) - - if (events) { - const listeners = events[type] - - if (listeners && listeners.length > 0) { - for (let i = listeners.length; i--; i > 0) { - if (listeners[i] === listener) { - listeners.splice(i, 1) - break - } - } - } - } - } - - dispatchEvent(event = {}) { - const listeners = _events.get(this)[event.type] - - if (listeners) { - for (let i = 0; i < listeners.length; i++) { - listeners[i](event) - } - } - } -} diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/FileReader.js b/platforms/minigame/platforms/wechat/wrapper/builtin/FileReader.js deleted file mode 100644 index aeabcda24b..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/FileReader.js +++ /dev/null @@ -1,7 +0,0 @@ -/* - * TODO 使用 wx.readFile 来封装 FileReader - */ -export default class FileReader { - construct() { - } -} diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLAudioElement.js b/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLAudioElement.js deleted file mode 100644 index c6facfba2d..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLAudioElement.js +++ /dev/null @@ -1,7 +0,0 @@ -import HTMLMediaElement from './HTMLMediaElement' - -export default class HTMLAudioElement extends HTMLMediaElement { - constructor() { - super('audio') - } -} diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLCanvasElement.js b/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLCanvasElement.js deleted file mode 100644 index b4b9c9c1db..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLCanvasElement.js +++ /dev/null @@ -1,20 +0,0 @@ -// import HTMLElement from './HTMLElement'; - -// export default class HTMLCanvasElement extends HTMLElement -// { -// constructor(){ -// super('canvas') -// } -// }; - -import Canvas from './Canvas' -import HTMLElement from './HTMLElement' - -GameGlobal.screencanvas = GameGlobal.screencanvas || new Canvas(); -const canvas = GameGlobal.screencanvas; - -const canvasConstructor = canvas.constructor; - -// canvasConstructor.__proto__.__proto__ = new HTMLElement(); - -export default canvasConstructor; diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLElement.js b/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLElement.js deleted file mode 100644 index 51040f3c6e..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLElement.js +++ /dev/null @@ -1,54 +0,0 @@ -import Element from './Element' -import { noop } from './util/index.js' -import { innerWidth, innerHeight } from './WindowProperties' - -export default class HTMLElement extends Element { - className = '' - childern = [] - style = { - width: `${innerWidth}px`, - height: `${innerHeight}px` - } - - insertBefore = noop - - innerHTML = '' - - constructor(tagName = '') { - super() - this.tagName = tagName.toUpperCase() - } - - setAttribute(name, value) { - this[name] = value - } - - getAttribute(name) { - return this[name] - } - - get clientWidth() { - const ret = parseInt(this.style.fontSize, 10) * this.innerHTML.length - - return Number.isNaN(ret) ? 0 : ret - } - - get clientHeight() { - const ret = parseInt(this.style.fontSize, 10) - - return Number.isNaN(ret) ? 0 : ret - } - - getBoundingClientRect() { - return { - top: 0, - left: 0, - width: innerWidth, - height: innerHeight - } - } - - focus() { - - } -} diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLImageElement.js b/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLImageElement.js deleted file mode 100644 index 8c2590b3d8..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLImageElement.js +++ /dev/null @@ -1,16 +0,0 @@ -// import HTMLElement from './HTMLElement'; - -// export default class HTMLImageElement extends HTMLElement -// { -// constructor(){ -// super('img') -// } -// }; - -import HTMLElement from './HTMLElement' - -const imageConstructor = wx.createImage().constructor; - -// imageConstructor.__proto__.__proto__ = new HTMLElement(); - -export default imageConstructor; diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLMediaElement.js b/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLMediaElement.js deleted file mode 100644 index a4b39a5445..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLMediaElement.js +++ /dev/null @@ -1,25 +0,0 @@ -import HTMLElement from './HTMLElement' - -export default class HTMLMediaElement extends HTMLElement { - constructor(type) { - super(type) - } - - addTextTrack() { - } - - captureStream() { - } - - fastSeek() { - } - - load() { - } - - pause() { - } - - play() { - } -} diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLVideoElement.js b/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLVideoElement.js deleted file mode 100644 index 79be0e019a..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/HTMLVideoElement.js +++ /dev/null @@ -1,8 +0,0 @@ -import HTMLMediaElement from './HTMLMediaElement'; - -export default class HTMLVideoElement extends HTMLMediaElement -{ - constructor(){ - super('video') - } -}; diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/Image.js b/platforms/minigame/platforms/wechat/wrapper/builtin/Image.js deleted file mode 100644 index 7e2defc7cb..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/Image.js +++ /dev/null @@ -1,10 +0,0 @@ -import HTMLImageElement from './HTMLImageElement' - -export default function() { - const image = wx.createImage(); - - // image.__proto__.__proto__.__proto__ = new HTMLImageElement(); - - image.premultiplyAlpha = false; - return image; -}; diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/ImageBitmap.js b/platforms/minigame/platforms/wechat/wrapper/builtin/ImageBitmap.js deleted file mode 100644 index 94be70a760..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/ImageBitmap.js +++ /dev/null @@ -1,5 +0,0 @@ -export default class ImageBitmap { - constructor() { - // TODO - } -} diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/Node.js b/platforms/minigame/platforms/wechat/wrapper/builtin/Node.js deleted file mode 100644 index 6ebcbdc234..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/Node.js +++ /dev/null @@ -1,34 +0,0 @@ -import EventTarget from './EventTarget.js' - -export default class Node extends EventTarget { - constructor() { - super() - } - - childNodes = [] - - appendChild(node) { - this.childNodes.push(node) - // if (node instanceof Node) { - // this.childNodes.push(node) - // } else { - // throw new TypeError('Failed to executed \'appendChild\' on \'Node\': parameter 1 is not of type \'Node\'.') - // } - } - - cloneNode() { - const copyNode = Object.create(this) - - Object.assign(copyNode, this) - return copyNode - } - - removeChild(node) { - const index = this.childNodes.findIndex((child) => child === node) - - if (index > -1) { - return this.childNodes.splice(index, 1) - } - return null - } -} diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/WebGLRenderingContext.js b/platforms/minigame/platforms/wechat/wrapper/builtin/WebGLRenderingContext.js deleted file mode 100644 index 1cc97ea4b8..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/WebGLRenderingContext.js +++ /dev/null @@ -1,302 +0,0 @@ -export default class WebGLRenderingContext { - constructor() { - // TODO - } -} - -WebGLRenderingContext.ACTIVE_ATTRIBUTES = 35721; -WebGLRenderingContext.ACTIVE_TEXTURE = 34016; -WebGLRenderingContext.ACTIVE_UNIFORMS = 35718; -WebGLRenderingContext.ALIASED_LINE_WIDTH_RANGE = 33902; -WebGLRenderingContext.ALIASED_POINT_SIZE_RANGE = 33901; -WebGLRenderingContext.ALPHA = 6406; -WebGLRenderingContext.ALPHA_BITS = 3413; -WebGLRenderingContext.ALWAYS = 519; -WebGLRenderingContext.ARRAY_BUFFER = 34962; -WebGLRenderingContext.ARRAY_BUFFER_BINDING = 34964; -WebGLRenderingContext.ATTACHED_SHADERS = 35717; -WebGLRenderingContext.BACK = 1029; -WebGLRenderingContext.BLEND = 3042; -WebGLRenderingContext.BLEND_COLOR = 32773; -WebGLRenderingContext.BLEND_DST_ALPHA = 32970; -WebGLRenderingContext.BLEND_DST_RGB = 32968; -WebGLRenderingContext.BLEND_EQUATION = 32777; -WebGLRenderingContext.BLEND_EQUATION_ALPHA = 34877; -WebGLRenderingContext.BLEND_EQUATION_RGB = 32777; -WebGLRenderingContext.BLEND_SRC_ALPHA = 32971; -WebGLRenderingContext.BLEND_SRC_RGB = 32969; -WebGLRenderingContext.BLUE_BITS = 3412; -WebGLRenderingContext.BOOL = 35670; -WebGLRenderingContext.BOOL_VEC2 = 35671; -WebGLRenderingContext.BOOL_VEC3 = 35672; -WebGLRenderingContext.BOOL_VEC4 = 35673; -WebGLRenderingContext.BROWSER_DEFAULT_WEBGL = 37444; -WebGLRenderingContext.BUFFER_SIZE = 34660; -WebGLRenderingContext.BUFFER_USAGE = 34661; -WebGLRenderingContext.BYTE = 5120; -WebGLRenderingContext.CCW = 2305; -WebGLRenderingContext.CLAMP_TO_EDGE = 33071; -WebGLRenderingContext.COLOR_ATTACHMENT0 = 36064; -WebGLRenderingContext.COLOR_BUFFER_BIT = 16384; -WebGLRenderingContext.COLOR_CLEAR_VALUE = 3106; -WebGLRenderingContext.COLOR_WRITEMASK = 3107; -WebGLRenderingContext.COMPILE_STATUS = 35713; -WebGLRenderingContext.COMPRESSED_TEXTURE_FORMATS = 34467; -WebGLRenderingContext.CONSTANT_ALPHA = 32771; -WebGLRenderingContext.CONSTANT_COLOR = 32769; -WebGLRenderingContext.CONTEXT_LOST_WEBGL = 37442; -WebGLRenderingContext.CULL_FACE = 2884; -WebGLRenderingContext.CULL_FACE_MODE = 2885; -WebGLRenderingContext.CURRENT_PROGRAM = 35725; -WebGLRenderingContext.CURRENT_VERTEX_ATTRIB = 34342; -WebGLRenderingContext.CW = 2304; -WebGLRenderingContext.DECR = 7683; -WebGLRenderingContext.DECR_WRAP = 34056; -WebGLRenderingContext.DELETE_STATUS = 35712; -WebGLRenderingContext.DEPTH_ATTACHMENT = 36096; -WebGLRenderingContext.DEPTH_BITS = 3414; -WebGLRenderingContext.DEPTH_BUFFER_BIT = 256; -WebGLRenderingContext.DEPTH_CLEAR_VALUE = 2931; -WebGLRenderingContext.DEPTH_COMPONENT = 6402; -WebGLRenderingContext.DEPTH_COMPONENT16 = 33189; -WebGLRenderingContext.DEPTH_FUNC = 2932; -WebGLRenderingContext.DEPTH_RANGE = 2928; -WebGLRenderingContext.DEPTH_STENCIL = 34041; -WebGLRenderingContext.DEPTH_STENCIL_ATTACHMENT = 33306; -WebGLRenderingContext.DEPTH_TEST = 2929; -WebGLRenderingContext.DEPTH_WRITEMASK = 2930; -WebGLRenderingContext.DITHER = 3024; -WebGLRenderingContext.DONT_CARE = 4352; -WebGLRenderingContext.DST_ALPHA = 772; -WebGLRenderingContext.DST_COLOR = 774; -WebGLRenderingContext.DYNAMIC_DRAW = 35048; -WebGLRenderingContext.ELEMENT_ARRAY_BUFFER = 34963; -WebGLRenderingContext.ELEMENT_ARRAY_BUFFER_BINDING = 34965; -WebGLRenderingContext.EQUAL = 514; -WebGLRenderingContext.FASTEST = 4353; -WebGLRenderingContext.FLOAT = 5126; -WebGLRenderingContext.FLOAT_MAT2 = 35674; -WebGLRenderingContext.FLOAT_MAT3 = 35675; -WebGLRenderingContext.FLOAT_MAT4 = 35676; -WebGLRenderingContext.FLOAT_VEC2 = 35664; -WebGLRenderingContext.FLOAT_VEC3 = 35665; -WebGLRenderingContext.FLOAT_VEC4 = 35666; -WebGLRenderingContext.FRAGMENT_SHADER = 35632; -WebGLRenderingContext.FRAMEBUFFER = 36160; -WebGLRenderingContext.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 36049; -WebGLRenderingContext.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 36048; -WebGLRenderingContext.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 36051; -WebGLRenderingContext.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 36050; -WebGLRenderingContext.FRAMEBUFFER_BINDING = 36006; -WebGLRenderingContext.FRAMEBUFFER_COMPLETE = 36053; -WebGLRenderingContext.FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 36054; -WebGLRenderingContext.FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 36057; -WebGLRenderingContext.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 36055; -WebGLRenderingContext.FRAMEBUFFER_UNSUPPORTED = 36061; -WebGLRenderingContext.FRONT = 1028; -WebGLRenderingContext.FRONT_AND_BACK = 1032; -WebGLRenderingContext.FRONT_FACE = 2886; -WebGLRenderingContext.FUNC_ADD = 32774; -WebGLRenderingContext.FUNC_REVERSE_SUBTRACT = 32779; -WebGLRenderingContext.FUNC_SUBTRACT = 32778; -WebGLRenderingContext.GENERATE_MIPMAP_HINT = 33170; -WebGLRenderingContext.GEQUAL = 518; -WebGLRenderingContext.GREATER = 516; -WebGLRenderingContext.GREEN_BITS = 3411; -WebGLRenderingContext.HIGH_FLOAT = 36338; -WebGLRenderingContext.HIGH_INT = 36341; -WebGLRenderingContext.IMPLEMENTATION_COLOR_READ_FORMAT = 35739; -WebGLRenderingContext.IMPLEMENTATION_COLOR_READ_TYPE = 35738; -WebGLRenderingContext.INCR = 7682; -WebGLRenderingContext.INCR_WRAP = 34055; -WebGLRenderingContext.INT = 5124; -WebGLRenderingContext.INT_VEC2 = 35667; -WebGLRenderingContext.INT_VEC3 = 35668; -WebGLRenderingContext.INT_VEC4 = 35669; -WebGLRenderingContext.INVALID_ENUM = 1280; -WebGLRenderingContext.INVALID_FRAMEBUFFER_OPERATION = 1286; -WebGLRenderingContext.INVALID_OPERATION = 1282; -WebGLRenderingContext.INVALID_VALUE = 1281; -WebGLRenderingContext.INVERT = 5386; -WebGLRenderingContext.KEEP = 7680; -WebGLRenderingContext.LEQUAL = 515; -WebGLRenderingContext.LESS = 513; -WebGLRenderingContext.LINEAR = 9729; -WebGLRenderingContext.LINEAR_MIPMAP_LINEAR = 9987; -WebGLRenderingContext.LINEAR_MIPMAP_NEAREST = 9985; -WebGLRenderingContext.LINES = 1; -WebGLRenderingContext.LINE_LOOP = 2; -WebGLRenderingContext.LINE_STRIP = 3; -WebGLRenderingContext.LINE_WIDTH = 2849; -WebGLRenderingContext.LINK_STATUS = 35714; -WebGLRenderingContext.LOW_FLOAT = 36336; -WebGLRenderingContext.LOW_INT = 36339; -WebGLRenderingContext.LUMINANCE = 6409; -WebGLRenderingContext.LUMINANCE_ALPHA = 6410; -WebGLRenderingContext.MAX_COMBINED_TEXTURE_IMAGE_UNITS = 35661; -WebGLRenderingContext.MAX_CUBE_MAP_TEXTURE_SIZE = 34076; -WebGLRenderingContext.MAX_FRAGMENT_UNIFORM_VECTORS = 36349; -WebGLRenderingContext.MAX_RENDERBUFFER_SIZE = 34024; -WebGLRenderingContext.MAX_TEXTURE_IMAGE_UNITS = 34930; -WebGLRenderingContext.MAX_TEXTURE_SIZE = 3379; -WebGLRenderingContext.MAX_VARYING_VECTORS = 36348; -WebGLRenderingContext.MAX_VERTEX_ATTRIBS = 34921; -WebGLRenderingContext.MAX_VERTEX_TEXTURE_IMAGE_UNITS = 35660; -WebGLRenderingContext.MAX_VERTEX_UNIFORM_VECTORS = 36347; -WebGLRenderingContext.MAX_VIEWPORT_DIMS = 3386; -WebGLRenderingContext.MEDIUM_FLOAT = 36337; -WebGLRenderingContext.MEDIUM_INT = 36340; -WebGLRenderingContext.MIRRORED_REPEAT = 33648; -WebGLRenderingContext.NEAREST = 9728; -WebGLRenderingContext.NEAREST_MIPMAP_LINEAR = 9986; -WebGLRenderingContext.NEAREST_MIPMAP_NEAREST = 9984; -WebGLRenderingContext.NEVER = 512; -WebGLRenderingContext.NICEST = 4354; -WebGLRenderingContext.NONE = 0; -WebGLRenderingContext.NOTEQUAL = 517; -WebGLRenderingContext.NO_ERROR = 0; -WebGLRenderingContext.ONE = 1; -WebGLRenderingContext.ONE_MINUS_CONSTANT_ALPHA = 32772; -WebGLRenderingContext.ONE_MINUS_CONSTANT_COLOR = 32770; -WebGLRenderingContext.ONE_MINUS_DST_ALPHA = 773; -WebGLRenderingContext.ONE_MINUS_DST_COLOR = 775; -WebGLRenderingContext.ONE_MINUS_SRC_ALPHA = 771; -WebGLRenderingContext.ONE_MINUS_SRC_COLOR = 769; -WebGLRenderingContext.OUT_OF_MEMORY = 1285; -WebGLRenderingContext.PACK_ALIGNMENT = 3333; -WebGLRenderingContext.POINTS = 0; -WebGLRenderingContext.POLYGON_OFFSET_FACTOR = 32824; -WebGLRenderingContext.POLYGON_OFFSET_FILL = 32823; -WebGLRenderingContext.POLYGON_OFFSET_UNITS = 10752; -WebGLRenderingContext.RED_BITS = 3410; -WebGLRenderingContext.RENDERBUFFER = 36161; -WebGLRenderingContext.RENDERBUFFER_ALPHA_SIZE = 36179; -WebGLRenderingContext.RENDERBUFFER_BINDING = 36007; -WebGLRenderingContext.RENDERBUFFER_BLUE_SIZE = 36178; -WebGLRenderingContext.RENDERBUFFER_DEPTH_SIZE = 36180; -WebGLRenderingContext.RENDERBUFFER_GREEN_SIZE = 36177; -WebGLRenderingContext.RENDERBUFFER_HEIGHT = 36163; -WebGLRenderingContext.RENDERBUFFER_INTERNAL_FORMAT = 36164; -WebGLRenderingContext.RENDERBUFFER_RED_SIZE = 36176; -WebGLRenderingContext.RENDERBUFFER_STENCIL_SIZE = 36181; -WebGLRenderingContext.RENDERBUFFER_WIDTH = 36162; -WebGLRenderingContext.RENDERER = 7937; -WebGLRenderingContext.REPEAT = 10497; -WebGLRenderingContext.REPLACE = 7681; -WebGLRenderingContext.RGB = 6407; -WebGLRenderingContext.RGB5_A1 = 32855; -WebGLRenderingContext.RGB565 = 36194; -WebGLRenderingContext.RGBA = 6408; -WebGLRenderingContext.RGBA4 = 32854; -WebGLRenderingContext.SAMPLER_2D = 35678; -WebGLRenderingContext.SAMPLER_CUBE = 35680; -WebGLRenderingContext.SAMPLES = 32937; -WebGLRenderingContext.SAMPLE_ALPHA_TO_COVERAGE = 32926; -WebGLRenderingContext.SAMPLE_BUFFERS = 32936; -WebGLRenderingContext.SAMPLE_COVERAGE = 32928; -WebGLRenderingContext.SAMPLE_COVERAGE_INVERT = 32939; -WebGLRenderingContext.SAMPLE_COVERAGE_VALUE = 32938; -WebGLRenderingContext.SCISSOR_BOX = 3088; -WebGLRenderingContext.SCISSOR_TEST = 3089; -WebGLRenderingContext.SHADER_TYPE = 35663; -WebGLRenderingContext.SHADING_LANGUAGE_VERSION = 35724; -WebGLRenderingContext.SHORT = 5122; -WebGLRenderingContext.SRC_ALPHA = 770; -WebGLRenderingContext.SRC_ALPHA_SATURATE = 776; -WebGLRenderingContext.SRC_COLOR = 768; -WebGLRenderingContext.STATIC_DRAW = 35044; -WebGLRenderingContext.STENCIL_ATTACHMENT = 36128; -WebGLRenderingContext.STENCIL_BACK_FAIL = 34817; -WebGLRenderingContext.STENCIL_BACK_FUNC = 34816; -WebGLRenderingContext.STENCIL_BACK_PASS_DEPTH_FAIL = 34818; -WebGLRenderingContext.STENCIL_BACK_PASS_DEPTH_PASS = 34819; -WebGLRenderingContext.STENCIL_BACK_REF = 36003; -WebGLRenderingContext.STENCIL_BACK_VALUE_MASK = 36004; -WebGLRenderingContext.STENCIL_BACK_WRITEMASK = 36005; -WebGLRenderingContext.STENCIL_BITS = 3415; -WebGLRenderingContext.STENCIL_BUFFER_BIT = 1024; -WebGLRenderingContext.STENCIL_CLEAR_VALUE = 2961; -WebGLRenderingContext.STENCIL_FAIL = 2964; -WebGLRenderingContext.STENCIL_FUNC = 2962; -WebGLRenderingContext.STENCIL_INDEX8 = 36168; -WebGLRenderingContext.STENCIL_PASS_DEPTH_FAIL = 2965; -WebGLRenderingContext.STENCIL_PASS_DEPTH_PASS = 2966; -WebGLRenderingContext.STENCIL_REF = 2967; -WebGLRenderingContext.STENCIL_TEST = 2960; -WebGLRenderingContext.STENCIL_VALUE_MASK = 2963; -WebGLRenderingContext.STENCIL_WRITEMASK = 2968; -WebGLRenderingContext.STREAM_DRAW = 35040; -WebGLRenderingContext.SUBPIXEL_BITS = 3408; -WebGLRenderingContext.TEXTURE = 5890; -WebGLRenderingContext.TEXTURE0 = 33984; -WebGLRenderingContext.TEXTURE1 = 33985; -WebGLRenderingContext.TEXTURE2 = 33986; -WebGLRenderingContext.TEXTURE3 = 33987; -WebGLRenderingContext.TEXTURE4 = 33988; -WebGLRenderingContext.TEXTURE5 = 33989; -WebGLRenderingContext.TEXTURE6 = 33990; -WebGLRenderingContext.TEXTURE7 = 33991; -WebGLRenderingContext.TEXTURE8 = 33992; -WebGLRenderingContext.TEXTURE9 = 33993; -WebGLRenderingContext.TEXTURE10 = 33994; -WebGLRenderingContext.TEXTURE11 = 33995; -WebGLRenderingContext.TEXTURE12 = 33996; -WebGLRenderingContext.TEXTURE13 = 33997; -WebGLRenderingContext.TEXTURE14 = 33998; -WebGLRenderingContext.TEXTURE15 = 33999; -WebGLRenderingContext.TEXTURE16 = 34000; -WebGLRenderingContext.TEXTURE17 = 34001; -WebGLRenderingContext.TEXTURE18 = 34002; -WebGLRenderingContext.TEXTURE19 = 34003; -WebGLRenderingContext.TEXTURE20 = 34004; -WebGLRenderingContext.TEXTURE21 = 34005; -WebGLRenderingContext.TEXTURE22 = 34006; -WebGLRenderingContext.TEXTURE23 = 34007; -WebGLRenderingContext.TEXTURE24 = 34008; -WebGLRenderingContext.TEXTURE25 = 34009; -WebGLRenderingContext.TEXTURE26 = 34010; -WebGLRenderingContext.TEXTURE27 = 34011; -WebGLRenderingContext.TEXTURE28 = 34012; -WebGLRenderingContext.TEXTURE29 = 34013; -WebGLRenderingContext.TEXTURE30 = 34014; -WebGLRenderingContext.TEXTURE31 = 34015; -WebGLRenderingContext.TEXTURE_2D = 3553; -WebGLRenderingContext.TEXTURE_BINDING_2D = 32873; -WebGLRenderingContext.TEXTURE_BINDING_CUBE_MAP = 34068; -WebGLRenderingContext.TEXTURE_CUBE_MAP = 34067; -WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X = 34070; -WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_Y = 34072; -WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_Z = 34074; -WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X = 34069; -WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_Y = 34071; -WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_Z = 34073; -WebGLRenderingContext.TEXTURE_MAG_FILTER = 10240; -WebGLRenderingContext.TEXTURE_MIN_FILTER = 10241; -WebGLRenderingContext.TEXTURE_WRAP_S = 10242; -WebGLRenderingContext.TEXTURE_WRAP_T = 10243; -WebGLRenderingContext.TRIANGLES = 4; -WebGLRenderingContext.TRIANGLE_FAN = 6; -WebGLRenderingContext.TRIANGLE_STRIP = 5; -WebGLRenderingContext.UNPACK_ALIGNMENT = 3317; -WebGLRenderingContext.UNPACK_COLORSPACE_CONVERSION_WEBGL = 37443; -WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL = 37440; -WebGLRenderingContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL = 37441; -WebGLRenderingContext.UNSIGNED_BYTE = 5121; -WebGLRenderingContext.UNSIGNED_INT = 5125; -WebGLRenderingContext.UNSIGNED_SHORT = 5123; -WebGLRenderingContext.UNSIGNED_SHORT_4_4_4_4 = 32819; -WebGLRenderingContext.UNSIGNED_SHORT_5_5_5_1 = 32820; -WebGLRenderingContext.UNSIGNED_SHORT_5_6_5 = 33635; -WebGLRenderingContext.VALIDATE_STATUS = 35715; -WebGLRenderingContext.VENDOR = 7936; -WebGLRenderingContext.VERSION = 7938; -WebGLRenderingContext.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 34975; -WebGLRenderingContext.VERTEX_ATTRIB_ARRAY_ENABLED = 34338; -WebGLRenderingContext.VERTEX_ATTRIB_ARRAY_NORMALIZED = 34922; -WebGLRenderingContext.VERTEX_ATTRIB_ARRAY_POINTER = 34373; -WebGLRenderingContext.VERTEX_ATTRIB_ARRAY_SIZE = 34339; -WebGLRenderingContext.VERTEX_ATTRIB_ARRAY_STRIDE = 34340; -WebGLRenderingContext.VERTEX_ATTRIB_ARRAY_TYPE = 34341; -WebGLRenderingContext.VERTEX_SHADER = 35633; -WebGLRenderingContext.VIEWPORT = 2978; -WebGLRenderingContext.ZERO = 0; \ No newline at end of file diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/WebSocket.js b/platforms/minigame/platforms/wechat/wrapper/builtin/WebSocket.js deleted file mode 100644 index afe2e087ad..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/WebSocket.js +++ /dev/null @@ -1,87 +0,0 @@ -const _socketTask = new WeakMap() - -export default class WebSocket { - static CONNECTING = 0 // The connection is not yet open. - static OPEN = 1 // The connection is open and ready to communicate. - static CLOSING = 2 // The connection is in the process of closing. - static CLOSED = 3 // The connection is closed or couldn't be opened. - - binaryType = '' // TODO 更新 binaryType - bufferedAmount = 0 // TODO 更新 bufferedAmount - extensions = '' - - onclose = null - onerror = null - onmessage = null - onopen = null - - protocol = '' // TODO 小程序内目前获取不到,实际上需要根据服务器选择的 sub-protocol 返回 - readyState = 3 - - constructor(url, protocols = []) { - if (typeof url !== 'string' || !(/(^ws:\/\/)|(^wss:\/\/)/).test(url)) { - throw new TypeError(`Failed to construct 'WebSocket': The URL '${url}' is invalid`) - } - - this.url = url - this.readyState = WebSocket.CONNECTING - - const socketTask = wx.connectSocket({ - url, - protocols: Array.isArray(protocols) ? protocols : [protocols], - tcpNoDelay: true - }) - - _socketTask.set(this, socketTask) - - socketTask.onClose((res) => { - this.readyState = WebSocket.CLOSED - if (typeof this.onclose === 'function') { - this.onclose(res) - } - }) - - socketTask.onMessage((res) => { - if (typeof this.onmessage === 'function') { - this.onmessage(res) - } - }) - - socketTask.onOpen(() => { - this.readyState = WebSocket.OPEN - if (typeof this.onopen === 'function') { - this.onopen() - } - }) - - socketTask.onError((res) => { - if (typeof this.onerror === 'function') { - this.onerror(new Error(res.errMsg)) - } - }) - - return this - } - - close(code, reason) { - this.readyState = WebSocket.CLOSING - const socketTask = _socketTask.get(this) - - socketTask.close({ - code, - reason - }) - } - - send(data) { - if (typeof data !== 'string' && !(data instanceof ArrayBuffer) && !ArrayBuffer.isView(data)) { - throw new TypeError(`Failed to send message: The data ${data} is invalid`) - } - - const socketTask = _socketTask.get(this) - - socketTask.send({ - data - }) - } -} diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/WindowProperties.js b/platforms/minigame/platforms/wechat/wrapper/builtin/WindowProperties.js deleted file mode 100644 index 3a6bdd5804..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/WindowProperties.js +++ /dev/null @@ -1,21 +0,0 @@ -const { screenWidth, screenHeight, devicePixelRatio } = wx.getSystemInfoSync() - -export const innerWidth = screenWidth -export const innerHeight = screenHeight -export { devicePixelRatio } -export const screen = { - width: screenWidth, - height: screenHeight, - availWidth: innerWidth, - availHeight: innerHeight, - availLeft: 0, - availTop: 0, -} - -export const performance = { - now: Date.now -}; - -export const ontouchstart = null; -export const ontouchmove = null; -export const ontouchend = null; \ No newline at end of file diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/Worker.js b/platforms/minigame/platforms/wechat/wrapper/builtin/Worker.js deleted file mode 100644 index c670948bf6..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/Worker.js +++ /dev/null @@ -1,5 +0,0 @@ -export default function(file) { - const worker = wx.createWorker(file); - - return worker; -}; diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/XMLHttpRequest.js b/platforms/minigame/platforms/wechat/wrapper/builtin/XMLHttpRequest.js deleted file mode 100644 index d7be6892e0..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/XMLHttpRequest.js +++ /dev/null @@ -1,172 +0,0 @@ -import EventTarget from './EventTarget.js' - -const _url = new WeakMap() -const _method = new WeakMap() -const _requestHeader = new WeakMap() -const _responseHeader = new WeakMap() -const _requestTask = new WeakMap() - -function _triggerEvent(type, ...args) { - if (typeof this[`on${type}`] === 'function') { - this[`on${type}`].apply(this, args) - } -} - -function _changeReadyState(readyState) { - this.readyState = readyState - _triggerEvent.call(this, 'readystatechange') -} - -export default class XMLHttpRequest extends EventTarget { - // TODO 没法模拟 HEADERS_RECEIVED 和 LOADING 两个状态 - static UNSEND = 0 - static OPENED = 1 - static HEADERS_RECEIVED = 2 - static LOADING = 3 - static DONE = 4 - - timeout = 0; - /* - * TODO 这一批事件应该是在 XMLHttpRequestEventTarget.prototype 上面的 - */ - onabort = null - onerror = null - onload = null - onloadstart = null - onprogress = null - ontimeout = null - onloadend = null - - onreadystatechange = null - readyState = 0 - response = null - responseText = null - responseType = '' - responseXML = null - status = 0 - statusText = '' - upload = {} - withCredentials = false - - constructor() { - super(); - - _requestHeader.set(this, { - 'content-type': 'application/x-www-form-urlencoded' - }) - _responseHeader.set(this, {}) - } - - abort() { - const myRequestTask = _requestTask.get(this) - - if (myRequestTask) { - myRequestTask.abort() - } - } - - getAllResponseHeaders() { - const responseHeader = _responseHeader.get(this) - - return Object.keys(responseHeader).map((header) => { - return `${header}: ${responseHeader[header]}` - }).join('\n') - } - - getResponseHeader(header) { - return _responseHeader.get(this)[header] - } - - open(method, url/* async, user, password 这几个参数在小程序内不支持*/) { - _method.set(this, method) - _url.set(this, url) - _changeReadyState.call(this, XMLHttpRequest.OPENED) - } - - overrideMimeType() { - } - - send(data = '') { - if (this.readyState !== XMLHttpRequest.OPENED) { - throw new Error("Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.") - } else { - let myRequestTask = wx.request({ - data, - url: _url.get(this), - method: _method.get(this), - header: _requestHeader.get(this), - dataType: 'other', - responseType: this.responseType === 'arraybuffer' ? 'arraybuffer' : 'text', - timeout: this.timeout || undefined, - success: ({ data, statusCode, header }) => { - this.status = statusCode - _responseHeader.set(this, header) - _triggerEvent.call(this, 'loadstart') - _changeReadyState.call(this, XMLHttpRequest.HEADERS_RECEIVED) - _changeReadyState.call(this, XMLHttpRequest.LOADING) - - switch (this.responseType) { - case 'json': - this.responseText = data; - try { - this.response = JSON.parse(data); - } - catch (e) { - this.response = null; - } - break; - case '': - case 'text': - this.responseText = this.response = data; - break; - case 'arraybuffer': - this.response = data; - this.responseText = ''; - var bytes = new Uint8Array(data); - var len = bytes.byteLength; - - for (var i = 0; i < len; i++) { - this.responseText += String.fromCharCode(bytes[i]); - } - break; - default: - this.response = null; - } - _changeReadyState.call(this, XMLHttpRequest.DONE) - _triggerEvent.call(this, 'load') - _triggerEvent.call(this, 'loadend') - }, - fail: ({ errMsg }) => { - // TODO 规范错误 - if (errMsg.indexOf('abort') !== -1) { - _triggerEvent.call(this, 'abort') - } else if (errMsg.indexOf('timeout') !== -1) { - _triggerEvent.call(this, 'timeout') - } else { - _triggerEvent.call(this, 'error', errMsg) - } - _triggerEvent.call(this, 'loadend') - } - }) - - _requestTask.set(this, myRequestTask); - } - } - - setRequestHeader(header, value) { - const myHeader = _requestHeader.get(this) - - myHeader[header] = value - _requestHeader.set(this, myHeader) - } - - addEventListener(type, listener) { - if (typeof listener === 'function') { - let _this = this - let event = { target: _this } - this['on' + type] = function (event) { - listener.call(_this, event) - } - } - } -} diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/document.js b/platforms/minigame/platforms/wechat/wrapper/builtin/document.js deleted file mode 100644 index 0e30c2580b..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/document.js +++ /dev/null @@ -1,127 +0,0 @@ -import * as window from './window' -import HTMLElement from './HTMLElement' -import HTMLVideoElement from './HTMLVideoElement' -import Image from './Image' -import Audio from './Audio' -import Canvas from './Canvas' -import './EventIniter/index.js' - -const events = {}; - -const document = { - readyState: 'complete', - visibilityState: 'visible', - documentElement: window, - hidden: false, - style: {}, - location: window.location, - ontouchstart: null, - ontouchmove: null, - ontouchend: null, - - head: new HTMLElement('head'), - body: new HTMLElement('body'), - - createElement(tagName) { - if (tagName === 'canvas') { - return new Canvas() - } else if (tagName === 'audio') { - return new Audio() - } else if (tagName === 'img') { - return new Image() - }else if (tagName === 'video') { - return new HTMLVideoElement() - } - - return new HTMLElement(tagName) - }, - - createElementNS(nameSpace, tagName) { - return this.createElement(tagName); - }, - - getElementById(id) { - if (id === window.canvas.id) { - return window.canvas - } - return null - }, - - getElementsByTagName(tagName) { - if (tagName === 'head') { - return [document.head] - } else if (tagName === 'body') { - return [document.body] - } else if (tagName === 'canvas') { - return [window.canvas] - } - return [] - }, - - getElementsByName(tagName) { - if (tagName === 'head') { - return [document.head] - } else if (tagName === 'body') { - return [document.body] - } else if (tagName === 'canvas') { - return [window.canvas] - } - return [] - }, - - querySelector(query) { - if (query === 'head') { - return document.head - } else if (query === 'body') { - return document.body - } else if (query === 'canvas') { - return window.canvas - } else if (query === `#${window.canvas.id}`) { - return window.canvas - } - return null - }, - - querySelectorAll(query) { - if (query === 'head') { - return [document.head] - } else if (query === 'body') { - return [document.body] - } else if (query === 'canvas') { - return [window.canvas] - } - return [] - }, - - addEventListener(type, listener) { - if (!events[type]) { - events[type] = [] - } - events[type].push(listener) - }, - - removeEventListener(type, listener) { - const listeners = events[type] - - if (listeners && listeners.length > 0) { - for (let i = listeners.length; i--; i > 0) { - if (listeners[i] === listener) { - listeners.splice(i, 1) - break - } - } - } - }, - - dispatchEvent(event) { - const listeners = events[event.type] - - if (listeners) { - for (let i = 0; i < listeners.length; i++) { - listeners[i](event) - } - } - } -} - -export default document diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/index.js b/platforms/minigame/platforms/wechat/wrapper/builtin/index.js deleted file mode 100644 index 83c8c9f021..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/index.js +++ /dev/null @@ -1,65 +0,0 @@ -import * as _window from './window'; -import document from './document'; -import HTMLElement from './HTMLElement'; - -const global = GameGlobal; - -function inject () { - _window.document = document; - - _window.addEventListener = (type, listener) => { - _window.document.addEventListener(type, listener); - }; - _window.removeEventListener = (type, listener) => { - _window.document.removeEventListener(type, listener); - }; - _window.dispatchEvent = function (event = {}) { - console.log('window.dispatchEvent', event.type, event); - // nothing to do - }; - - const { platform } = wx.getSystemInfoSync(); - - // 开发者工具无法重定义 window - if (typeof __devtoolssubcontext === 'undefined' && platform === 'devtools') { - for (const key in _window) { - const descriptor = Object.getOwnPropertyDescriptor(global, key); - - if (!descriptor || descriptor.configurable === true) { - Object.defineProperty(window, key, { - value: _window[key], - }); - } - } - - for (const key in _window.document) { - const descriptor = Object.getOwnPropertyDescriptor(global.document, key); - - if (!descriptor || descriptor.configurable === true) { - Object.defineProperty(global.document, key, { - value: _window.document[key], - }); - } - } - window.parent = window; - } else { - for (const key in _window) { - global[key] = _window[key]; - } - global.window = _window; - window = global; - window.top = window.parent = window; - } -} - -if (!GameGlobal.__isAdapterInjected) { - GameGlobal.__isAdapterInjected = true; - inject(); -} - -// overwrite global WebAssembly -global.CCWebAssembly = global.WebAssembly = global.WXWebAssembly; - -require('../../../../common/xmldom/dom-parser'); -require('../unify'); -require('../fs-utils'); diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/localStorage.js b/platforms/minigame/platforms/wechat/wrapper/builtin/localStorage.js deleted file mode 100644 index 84acaf9ee6..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/localStorage.js +++ /dev/null @@ -1,31 +0,0 @@ -const localStorage = { - get length() { - const { keys } = wx.getStorageInfoSync() - - return keys.length - }, - - key(n) { - const { keys } = wx.getStorageInfoSync() - - return keys[n] - }, - - getItem(key) { - return wx.getStorageSync(key) - }, - - setItem(key, value) { - return wx.setStorageSync(key, value) - }, - - removeItem(key) { - wx.removeStorageSync(key) - }, - - clear() { - wx.clearStorageSync() - } -} - -export default localStorage diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/location.js b/platforms/minigame/platforms/wechat/wrapper/builtin/location.js deleted file mode 100644 index b1da72019f..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/location.js +++ /dev/null @@ -1,8 +0,0 @@ -const location = { - href: 'game.js', - protocol: '', - reload() { - } -} - -export default location diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/navigator.js b/platforms/minigame/platforms/wechat/wrapper/builtin/navigator.js deleted file mode 100644 index 99e27c034a..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/navigator.js +++ /dev/null @@ -1,38 +0,0 @@ -import { noop } from './util/index.js' - -// TODO 需要 wx.getSystemInfo 获取更详细信息 -const systemInfo = wx.getSystemInfoSync() -console.log(systemInfo) - -const system = systemInfo.system; -const platform = systemInfo.platform; -const language = systemInfo.language; -const wechatVersioin = systemInfo.version; - -const android = system.toLowerCase().indexOf('android') !== -1; - -const uaDesc = android ? `Android; CPU ${system}` : `iPhone; CPU iPhone OS ${system} like Mac OS X`; -const ua = `Mozilla/5.0 (${uaDesc}) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E8301 MicroMessenger/${wechatVersioin} MiniGame NetType/WIFI Language/${language}`; - -const navigator = { - platform, - language: language, - appVersion: `5.0 (${uaDesc}) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1`, - userAgent: ua, - onLine: true, // TODO 用 wx.getNetworkStateChange 和 wx.onNetworkStateChange 来返回真实的状态 - - // TODO 用 wx.getLocation 来封装 geolocation - geolocation: { - getCurrentPosition: noop, - watchPosition: noop, - clearWatch: noop - } -} - -if (wx.onNetworkStatusChange) { - wx.onNetworkStatusChange(function(event){ - navigator.onLine = event.isConnected; - }); -} - -export default navigator diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/util/index.js b/platforms/minigame/platforms/wechat/wrapper/builtin/util/index.js deleted file mode 100644 index 177804c7ab..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/util/index.js +++ /dev/null @@ -1 +0,0 @@ -export function noop() {} diff --git a/platforms/minigame/platforms/wechat/wrapper/builtin/window.js b/platforms/minigame/platforms/wechat/wrapper/builtin/window.js deleted file mode 100644 index 911115cdb4..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/builtin/window.js +++ /dev/null @@ -1,41 +0,0 @@ -import Canvas from './Canvas' - -export navigator from './navigator' -export XMLHttpRequest from './XMLHttpRequest' -export WebSocket from './WebSocket' -export Image from './Image' -export ImageBitmap from './ImageBitmap' -export Audio from './Audio' -export FileReader from './FileReader' -export HTMLElement from './HTMLElement' -export HTMLImageElement from './HTMLImageElement' -export HTMLCanvasElement from './HTMLCanvasElement' -export HTMLMediaElement from './HTMLMediaElement' -export HTMLAudioElement from './HTMLAudioElement' -export HTMLVideoElement from './HTMLVideoElement' -export WebGLRenderingContext from './WebGLRenderingContext' -export { TouchEvent, MouseEvent, DeviceMotionEvent } from './EventIniter/index.js' -export localStorage from './localStorage' -export location from './location' -export * from './WindowProperties' - -// 暴露全局的 canvas -GameGlobal.screencanvas = GameGlobal.screencanvas || new Canvas() -const canvas = GameGlobal.screencanvas; - -const { - setTimeout, - setInterval, - clearTimeout, - clearInterval, - requestAnimationFrame, - cancelAnimationFrame, -} = GameGlobal; - -export { canvas } -export { setTimeout } -export { setInterval } -export { clearTimeout } -export { clearInterval } -export { requestAnimationFrame } -export { cancelAnimationFrame } \ No newline at end of file diff --git a/platforms/minigame/platforms/wechat/wrapper/engine/VideoPlayer.js b/platforms/minigame/platforms/wechat/wrapper/engine/VideoPlayer.js deleted file mode 100644 index 745c29b57e..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/engine/VideoPlayer.js +++ /dev/null @@ -1,384 +0,0 @@ -/**************************************************************************** - Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - -https://www.cocos.com/ - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated 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. -****************************************************************************/ - -if (cc.internal.VideoPlayer) { - const { EventType } = cc.internal.VideoPlayer; - - const _mat4_temp = cc.mat4(); - - const _topLeft = new cc.Vec3(); - const _bottomRight = new cc.Vec3(); - - // eslint-disable-next-line no-undef - const dpr = wx.getSystemInfoSync().pixelRatio; - - cc.internal.VideoPlayerImplManager.getImpl = function (componenet) { - return new VideoPlayerImplMiniGame(componenet); - }; - - class VideoPlayerImplMiniGame extends cc.internal.VideoPlayerImpl { - constructor (componenet) { - super(componenet); - } - - syncClip (clip) { - this.removeVideoPlayer(); - if (!clip) { - return; - } - this.createVideoPlayer(clip._nativeAsset); - } - - syncURL (url) { - this.removeVideoPlayer(); - if (!url) { - return; - } - this.createVideoPlayer(url); - } - - onCanplay () { - if (this._loaded) { - return; - } - this._loaded = true; - this.setVisible(this._visible); - this.dispatchEvent(EventType.READY_TO_PLAY); - this.delayedPlay(); - } - - _bindEvent () { - const video = this._video; - const self = this; - - if (!video) { - return; - } - - video.onPlay(() => { - if (self._video !== video) return; - self._playing = true; - self.dispatchEvent(EventType.PLAYING); - }); - video.onEnded(() => { - if (self._video !== video) return; - self._playing = false; - self._currentTime = self._duration; // ensure currentTime is at the end of duration - self.dispatchEvent(EventType.COMPLETED); - }); - video.onPause(() => { - if (self._video !== video) return; - self._playing = false; - self.dispatchEvent(EventType.PAUSED); - }); - video.onTimeUpdate((res) => { - self._duration = res.duration; - self._currentTime = res.position; - }); - // onStop not supported, implemented in promise returned by video.stop call. - } - - _unbindEvent () { - const video = this._video; - if (!video) { - return; - } - - // BUG: video.offPlay(cb) is invalid - video.offPlay(); - video.offEnded(); - video.offPause(); - video.offTimeUpdate(); - // offStop not supported - } - - createVideoPlayer (url) { - // eslint-disable-next-line no-undef - if (!__globalAdapter.createVideo) { - console.warn('VideoPlayer not supported'); - return; - } - - if (!this._video) { - // eslint-disable-next-line no-undef - this._video = __globalAdapter.createVideo(); - this._video.showCenterPlayBtn = false; - this._video.controls = false; - this._duration = 0; - this._currentTime = 0; - this._loaded = false; - this.setVisible(this._visible); - this._bindEvent(); - this._forceUpdate = true; - } - - this.setURL(url); - this._forceUpdate = true; - } - - setURL (path) { - const video = this._video; - if (!video || video.src === path) { - return; - } - video.stop(); - this._unbindEvent(); - video.autoplay = true; // HACK: to implement onCanplay callback - video.src = path; - video.muted = true; - const self = this; - this._loaded = false; - function loadedCallback () { - video.offPlay(); - self._bindEvent(); - video.stop(); - video.muted = false; - self._loaded = true; - self._playing = false; - self._currentTime = 0; - self.dispatchEvent(EventType.READY_TO_PLAY); - video.autoplay = false; - } - video.onPlay(loadedCallback); - } - - removeVideoPlayer () { - const video = this.video; - if (video) { - video.stop(); - video.destroy(); - this._playing = false; - this._loaded = false; - this._loadedMeta = false; - this._ignorePause = false; - this._cachedCurrentTime = 0; - this._video = null; - } - } - - setVisible (value) { - const video = this._video; - if (!video || this._visible === value) { - return; - } - if (value) { - video.width = this._actualWidth || 0; - } else { - video.width = 0; // hide video - } - this._visible = value; - } - - getDuration () { - return this.duration(); - } - - duration () { - return this._duration; - } - - syncPlaybackRate (value) { - const video = this._video; - if (video && value !== video.playbackRate) { - if (value === 0.5 | value === 0.8 | value === 1.0 | value === 1.25 | value === 1.5) { - video.playbackRate = value; - } else { - console.warn('The platform does not support this PlaybackRate!'); - } - } - } - - syncVolume () { - console.warn('The platform does not support'); - } - - syncMute (enable) { - const video = this._video; - if (video && video.muted !== enable) { - video.muted = enable; - } - } - - syncLoop (enable) { - const video = this._video; - if (video && video.loop !== enable) { - video.loop = enable; - } - } - - syncStayOnBottom () { - console.warn('The platform does not support'); - } - - getCurrentTime () { - if (this.video) { - return this.currentTime(); - } - return -1; - } - - currentTime () { - return this._currentTime; - } - - seekTo (time) { - const video = this._video; - if (!video || !this._loaded) return; - video.seek(time); - } - - disable (noPause) { - if (this._video) { - if (!noPause) { - this._video.pause(); - } - this.setVisible(false); - this._visible = false; - } - } - - enable () { - if (this._video) { - this.setVisible(true); - this._visible = true; - } - } - - canPlay () { - this._video.play(); - this.syncCurrentTime(); - } - - resume () { - const video = this._video; - if (this._playing || !video) return; - - video.play(); - } - - pause () { - const video = this._video; - if (!this._playing || !video) return; - - video.pause(); - } - - stop () { - const self = this; - const video = this._video; - if (!video || !this._visible) return; - // HACK: this is to unify inconsistent behavior (on Android, video won't play from begin if called pause() before called stop(). - // but if called play() before stop(), video will play from begin.) of wechat official interface on Android & iOS. - if (!this._playing) { - video.play(); - } - video.stop().then((res) => { - if (res.errMsg && !res.errMsg.includes('ok')) { - console.error('failed to stop video player'); - return; - } - self._currentTime = 0; - self._playing = false; - self.dispatchEvent(EventType.STOPPED); - }); - } - - canFullScreen (enabled) { - if (this._video) { - this.setFullScreenEnabled(enabled); - } - } - - setFullScreenEnabled (enable) { - const video = this._video; - if (!video || this._fullScreenEnabled === enable) { - return; - } - if (enable) { - video.requestFullScreen(); - } else { - video.exitFullScreen(); - } - this._fullScreenEnabled = enable; - } - - // eslint-disable-next-line no-unused-vars - syncKeepAspectRatio (enabled) { - console.warn('On wechat game videoPlayer is always keep the aspect ratio'); - } - - syncMatrix () { - if (!this._video || !this._component || !this._uiTrans) return; - - const camera = this.UICamera; - if (!camera) { - return; - } - - this._component.node.getWorldMatrix(_mat4_temp); - const { width, height } = this._uiTrans.contentSize; - if (!this._forceUpdate - && this._m00 === _mat4_temp.m00 && this._m01 === _mat4_temp.m01 - && this._m04 === _mat4_temp.m04 && this._m05 === _mat4_temp.m05 - && this._m12 === _mat4_temp.m12 && this._m13 === _mat4_temp.m13 - && this._w === width && this._h === height) { - return; - } - - // update matrix cache - this._m00 = _mat4_temp.m00; - this._m01 = _mat4_temp.m01; - this._m04 = _mat4_temp.m04; - this._m05 = _mat4_temp.m05; - this._m12 = _mat4_temp.m12; - this._m13 = _mat4_temp.m13; - this._w = width; - this._h = height; - - // const canvasWidth = cc.game.canvas.width; - const canvasHeight = cc.game.canvas.height; - - const ap = this._uiTrans.anchorPoint; - // Vectors in node space - cc.Vec3.set(_topLeft, -ap.x * this._w, (1.0 - ap.y) * this._h, 0); - cc.Vec3.set(_bottomRight, (1 - ap.x) * this._w, -ap.y * this._h, 0); - // Convert to world space - cc.Vec3.transformMat4(_topLeft, _topLeft, _mat4_temp); - cc.Vec3.transformMat4(_bottomRight, _bottomRight, _mat4_temp); - // Convert to Screen space - camera.worldToScreen(_topLeft, _topLeft); - camera.worldToScreen(_bottomRight, _bottomRight); - - const finalWidth = _bottomRight.x - _topLeft.x; - const finalHeight = _topLeft.y - _bottomRight.y; - - this._video.x = _topLeft.x / dpr; - this._video.y = (canvasHeight - _topLeft.y) / dpr; - this._actualWidth = this._video.width = finalWidth / dpr; - this._video.height = finalHeight / dpr; - this._forceUpdate = false; - } - } -} diff --git a/platforms/minigame/platforms/wechat/wrapper/engine/index.js b/platforms/minigame/platforms/wechat/wrapper/engine/index.js deleted file mode 100644 index 2008afdd1b..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/engine/index.js +++ /dev/null @@ -1,4 +0,0 @@ -// require('../fs-utils'); -require('../../../../common/engine/index'); -require('./VideoPlayer'); -require('./sprite-frame'); \ No newline at end of file diff --git a/platforms/minigame/platforms/wechat/wrapper/engine/sprite-frame.js b/platforms/minigame/platforms/wechat/wrapper/engine/sprite-frame.js deleted file mode 100644 index 9b20d35ff7..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/engine/sprite-frame.js +++ /dev/null @@ -1,25 +0,0 @@ -if(cc.SpriteFrame) { - cc.SpriteFrame.prototype._checkPackable = function () { - const dynamicAtlas = cc.internal.dynamicAtlasManager; - if (!dynamicAtlas) return; - const texture = this._texture; - - if (!(texture instanceof cc.Texture2D) || texture.isCompressed) { - this._packable = false; - return; - } - - const w = this.width; - const h = this.height; - if (!texture.image - || w > dynamicAtlas.maxFrameSize || h > dynamicAtlas.maxFrameSize) { - this._packable = false; - return; - } - - // HACK: Can't tell if it's a Canvas or an Image by instanceof on WeChat. - if (texture.image && texture.image.getContext) { - this._packable = true; - } - } -} \ No newline at end of file diff --git a/platforms/minigame/platforms/wechat/wrapper/fs-utils.js b/platforms/minigame/platforms/wechat/wrapper/fs-utils.js deleted file mode 100644 index f17bbff436..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/fs-utils.js +++ /dev/null @@ -1,279 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2019 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of fsUtils 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 fsUtils 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. - ****************************************************************************/ -/* eslint-disable no-undef */ - -const fs = wx.getFileSystemManager ? wx.getFileSystemManager() : null; -const outOfStorageRegExp = /the maximum size of the file storage/; - -const fsUtils = { - fs, - - isOutOfStorage (errMsg) { - return outOfStorageRegExp.test(errMsg); - }, - - getUserDataPath () { - return wx.env.USER_DATA_PATH; - }, - - checkFsValid () { - if (!fs) { - console.warn('can not get the file system!'); - return false; - } - return true; - }, - - deleteFile (filePath, onComplete) { - fs.unlink({ - filePath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Delete file failed: path: ${filePath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg)); - }, - }); - }, - - downloadFile (remoteUrl, filePath, header, onProgress, onComplete) { - const options = { - url: remoteUrl, - success (res) { - if (res.statusCode === 200) { - onComplete && onComplete(null, res.tempFilePath || res.filePath); - } else { - if (res.filePath) { - fsUtils.deleteFile(res.filePath); - } - console.warn(`Download file failed: path: ${remoteUrl} message: ${res.statusCode}`); - onComplete && onComplete(new Error(res.statusCode), null); - } - }, - fail (res) { - console.warn(`Download file failed: path: ${remoteUrl} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg), null); - }, - }; - if (filePath) options.filePath = filePath; - if (header) options.header = header; - const task = wx.downloadFile(options); - onProgress && task.onProgressUpdate(onProgress); - }, - - saveFile (srcPath, destPath, onComplete) { - wx.saveFile({ - tempFilePath: srcPath, - filePath: destPath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Save file failed: path: ${srcPath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg)); - }, - }); - }, - - copyFile (srcPath, destPath, onComplete) { - fs.copyFile({ - srcPath, - destPath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Copy file failed: path: ${srcPath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg)); - }, - }); - }, - - writeFile (path, data, encoding, onComplete) { - fs.writeFile({ - filePath: path, - encoding, - data, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Write file failed: path: ${path} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg)); - }, - }); - }, - - writeFileSync (path, data, encoding) { - try { - fs.writeFileSync(path, data, encoding); - return null; - } catch (e) { - console.warn(`Write file failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - readFile (filePath, encoding, onComplete) { - fs.readFile({ - filePath, - encoding, - success (res) { - onComplete && onComplete(null, res.data); - }, - fail (res) { - console.warn(`Read file failed: path: ${filePath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg), null); - }, - }); - }, - - readDir (filePath, onComplete) { - fs.readdir({ - dirPath: filePath, - success (res) { - onComplete && onComplete(null, res.files); - }, - fail (res) { - console.warn(`Read directory failed: path: ${filePath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg), null); - }, - }); - }, - - readText (filePath, onComplete) { - fsUtils.readFile(filePath, 'utf8', onComplete); - }, - - readArrayBuffer (filePath, onComplete) { - // Should pass undefined to 'encoding' parameter instead of passing an empty string, - // otherwise, the new version of WeChat mini-game IDE will report an error: - // - // Error: readFile:fail Parameter check error: - // parameter.encoding 字段需为 'ascii' | 'base64' | 'binary' | 'hex' | 'latin1' | 'ucs-2' | 'ucs2' | 'utf-16le' | 'utf-8' | 'utf16le' | 'utf8' - // at Object.fail (web-adapter.js? [sm]:1) - // at Object.t (VM31 WAGameSubContext.js:1) - // at Function.C.forEach.v. (VM20 WAGame.js:1) - // at p (VM20 WAGame.js:1) - // at Object.fail (VM20 WAGame.js:1) - // at VM20 WAGame.js:1 - // at oe (VM20 WAGame.js:1) - // at VM20 WAGame.js:1 - // at r (VM20 WAGame.js:1) - // at s (VM20 WAGame.js:1) - // - // API Reference: https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.readFile.html - fsUtils.readFile(filePath, undefined, onComplete); - }, - - readJson (filePath, onComplete) { - fsUtils.readFile(filePath, 'utf8', (err, text) => { - let out = null; - if (!err) { - try { - out = JSON.parse(text); - } catch (e) { - console.warn(`Read json failed: path: ${filePath} message: ${e.message}`); - err = new Error(e.message); - } - } - onComplete && onComplete(err, out); - }); - }, - - readJsonSync (path) { - try { - const str = fs.readFileSync(path, 'utf8'); - return JSON.parse(str); - } catch (e) { - console.warn(`Read json failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - makeDirSync (path, recursive) { - try { - fs.mkdirSync(path, recursive); - return null; - } catch (e) { - console.warn(`Make directory failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - rmdirSync (dirPath, recursive) { - try { - fs.rmdirSync(dirPath, recursive); - return null; - } catch (e) { - console.warn(`rm directory failed: path: ${dirPath} message: ${e.message}`); - return new Error(e.message); - } - }, - - exists (filePath, onComplete) { - fs.access({ - path: filePath, - success () { - onComplete && onComplete(true); - }, - fail () { - onComplete && onComplete(false); - }, - }); - }, - - loadSubpackage (name, onProgress, onComplete) { - const task = wx.loadSubpackage({ - name, - success () { - onComplete && onComplete(); - }, - fail (res) { - console.warn(`Load Subpackage failed: path: ${name} message: ${res.errMsg}`); - onComplete && onComplete(new Error(`Failed to load subpackage ${name}: ${res.errMsg}`)); - }, - }); - onProgress && task.onProgressUpdate(onProgress); - return task; - }, - - unzip (zipFilePath, targetPath, onComplete) { - fs.unzip({ - zipFilePath, - targetPath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`unzip failed: path: ${zipFilePath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(`unzip failed: ${res.errMsg}`)); - }, - }); - }, -}; - -window.fsUtils = module.exports = fsUtils; diff --git a/platforms/minigame/platforms/wechat/wrapper/unify.js b/platforms/minigame/platforms/wechat/wrapper/unify.js deleted file mode 100644 index df0e6b36dc..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/unify.js +++ /dev/null @@ -1,125 +0,0 @@ -const utils = require('./utils'); - -window.__globalAdapter = window.__globalAdapter || {}; -if (window.__globalAdapter) { - const globalAdapter = window.__globalAdapter; - // SystemInfo - const systemInfo = wx.getSystemInfoSync(); - const windowWidth = systemInfo.windowWidth; - const windowHeight = systemInfo.windowHeight; - const isLandscape = windowWidth > windowHeight; - globalAdapter.isSubContext = (wx.getOpenDataContext === undefined); - globalAdapter.isDevTool = (systemInfo.platform === 'devtools'); - utils.cloneMethod(globalAdapter, wx, 'getSystemInfoSync'); - - // TouchEvent - utils.cloneMethod(globalAdapter, wx, 'onTouchStart'); - utils.cloneMethod(globalAdapter, wx, 'onTouchMove'); - utils.cloneMethod(globalAdapter, wx, 'onTouchEnd'); - utils.cloneMethod(globalAdapter, wx, 'onTouchCancel'); - - // Audio - utils.cloneMethod(globalAdapter, wx, 'createInnerAudioContext'); - - // AudioInterruption Evnet - utils.cloneMethod(globalAdapter, wx, 'onAudioInterruptionEnd'); - utils.cloneMethod(globalAdapter, wx, 'onAudioInterruptionBegin'); - - // Video - utils.cloneMethod(globalAdapter, wx, 'createVideo'); - - // FrameRate - utils.cloneMethod(globalAdapter, wx, 'setPreferredFramesPerSecond'); - - // Keyboard - utils.cloneMethod(globalAdapter, wx, 'showKeyboard'); - utils.cloneMethod(globalAdapter, wx, 'hideKeyboard'); - utils.cloneMethod(globalAdapter, wx, 'updateKeyboard'); - utils.cloneMethod(globalAdapter, wx, 'onKeyboardInput'); - utils.cloneMethod(globalAdapter, wx, 'onKeyboardConfirm'); - utils.cloneMethod(globalAdapter, wx, 'onKeyboardComplete'); - utils.cloneMethod(globalAdapter, wx, 'offKeyboardInput'); - utils.cloneMethod(globalAdapter, wx, 'offKeyboardConfirm'); - utils.cloneMethod(globalAdapter, wx, 'offKeyboardComplete'); - - // Message - utils.cloneMethod(globalAdapter, wx, 'getOpenDataContext'); - utils.cloneMethod(globalAdapter, wx, 'onMessage'); - - // Subpackage - utils.cloneMethod(globalAdapter, wx, 'loadSubpackage'); - - // SharedCanvas - utils.cloneMethod(globalAdapter, wx, 'getSharedCanvas'); - - // Font - utils.cloneMethod(globalAdapter, wx, 'loadFont'); - - // hide show Event - utils.cloneMethod(globalAdapter, wx, 'onShow'); - utils.cloneMethod(globalAdapter, wx, 'onHide'); - - // wechat program use onAppShow/onAppHide - if (typeof getApp === 'function') { - wx.onShow = wx.onAppShow; - wx.onHide = wx.onAppHide; - } - - // onError - utils.cloneMethod(globalAdapter, wx, 'onError'); - // offError - utils.cloneMethod(globalAdapter, wx, 'offError'); - - // Accelerometer - let isAccelerometerInit = false; - let deviceOrientation = 1; - if (wx.onDeviceOrientationChange) { - wx.onDeviceOrientationChange((res) => { - if (res.value === 'landscape') { - deviceOrientation = 1; - } else if (res.value === 'landscapeReverse') { - deviceOrientation = -1; - } - }); - } - Object.assign(globalAdapter, { - startAccelerometer (cb) { - if (!isAccelerometerInit) { - isAccelerometerInit = true; - wx.onAccelerometerChange && wx.onAccelerometerChange((res) => { - const resClone = {}; - let x = res.x; - let y = res.y; - if (isLandscape) { - const tmp = x; - x = -y; - y = tmp; - } - - resClone.x = x * deviceOrientation; - resClone.y = y * deviceOrientation; - resClone.z = res.z; - cb && cb(resClone); - }); - } else { - wx.startAccelerometer && wx.startAccelerometer({ - fail (err) { - console.error('start accelerometer failed', err); - }, - // success () {}, - // complete () {}, - }); - } - }, - - stopAccelerometer () { - wx.stopAccelerometer && wx.stopAccelerometer({ - fail (err) { - console.error('stop accelerometer failed', err); - }, - // success () {}, - // complete () {}, - }); - }, - }); -} diff --git a/platforms/minigame/platforms/wechat/wrapper/utils.js b/platforms/minigame/platforms/wechat/wrapper/utils.js deleted file mode 100644 index 947fc06958..0000000000 --- a/platforms/minigame/platforms/wechat/wrapper/utils.js +++ /dev/null @@ -1,16 +0,0 @@ -let utils = { - /** - * @param {Object} target - * @param {Object} origin - * @param {String} methodName - * @param {String} targetMethodName - */ - cloneMethod (target, origin, methodName, targetMethodName) { - if (origin[methodName]) { - targetMethodName = targetMethodName || methodName; - target[targetMethodName] = origin[methodName].bind(origin); - } - } -}; - -module.exports = utils; \ No newline at end of file diff --git a/platforms/minigame/platforms/xiaomi/wrapper/builtin.js b/platforms/minigame/platforms/xiaomi/wrapper/builtin.js deleted file mode 100644 index 3d8c58f3c8..0000000000 --- a/platforms/minigame/platforms/xiaomi/wrapper/builtin.js +++ /dev/null @@ -1,1168 +0,0 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; - -/******/ // The require function -/******/ function __webpack_require__(moduleId) { - -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) -/******/ return installedModules[moduleId].exports; - -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ exports: {}, -/******/ id: moduleId, -/******/ loaded: false -/******/ }; - -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - -/******/ // Flag the module as loaded -/******/ module.loaded = true; - -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } - - -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; - -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; - -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; - -/******/ // Load entry module and return exports -/******/ return __webpack_require__(0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var _window2 = __webpack_require__(1); - - var _window = _interopRequireWildcard(_window2); - - var _HTMLElement = __webpack_require__(5); - - var _HTMLElement2 = _interopRequireDefault(_HTMLElement); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - - function inject() { - var global = GameGlobal; - - _window.addEventListener = function (type, listener) { - _window.document.addEventListener(type, listener); - }; - _window.removeEventListener = function (type, listener) { - _window.document.removeEventListener(type, listener); - }; - - if (_window.canvas) { - _window.canvas.addEventListener = _window.addEventListener; - _window.canvas.removeEventListener = _window.removeEventListener; - } - - var sysInfo = qg.getSystemInfoSync(); - var platform = sysInfo.platformVersionName || sysInfo.platform; - - // 旧版无法重定义 window - var docDescriptor = Object.getOwnPropertyDescriptor(window, 'document'); - - if (platform === 'devtools' || !docDescriptor.configurable) { - for (var key in _window) { - var descriptor = Object.getOwnPropertyDescriptor(global, key); - - if (!descriptor || descriptor.configurable === true) { - Object.defineProperty(window, key, { - value: _window[key] - }); - } - } - - for (var _key in _window.document) { - var _descriptor = Object.getOwnPropertyDescriptor(global.document, _key); - - if (!_descriptor || _descriptor.configurable === true) { - Object.defineProperty(global.document, _key, { - value: _window.document[_key] - }); - } - } - window.parent = window; - } else { - for (var _key2 in _window) { - global[_key2] = _window[_key2]; - } - global.window = _window; - window = global; - window.top = window.parent = window; - } - } - - if (window.GameGlobal && !GameGlobal.__isAdapterInjected) { - GameGlobal.__isAdapterInjected = true; - inject(); - } - -/***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.canvas = exports.location = exports.HTMLElement = exports.FileReader = exports.Audio = exports.navigator = exports.document = undefined; - - var _WindowProperties = __webpack_require__(2); - - Object.keys(_WindowProperties).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _WindowProperties[key]; - } - }); - }); - - var _constructor = __webpack_require__(4); - - Object.keys(_constructor).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _constructor[key]; - } - }); - }); - - var _Canvas = __webpack_require__(10); - - var _Canvas2 = _interopRequireDefault(_Canvas); - - var _document2 = __webpack_require__(11); - - var _document3 = _interopRequireDefault(_document2); - - var _navigator2 = __webpack_require__(15); - - var _navigator3 = _interopRequireDefault(_navigator2); - - var _Audio2 = __webpack_require__(12); - - var _Audio3 = _interopRequireDefault(_Audio2); - - var _FileReader2 = __webpack_require__(16); - - var _FileReader3 = _interopRequireDefault(_FileReader2); - - var _HTMLElement2 = __webpack_require__(5); - - var _HTMLElement3 = _interopRequireDefault(_HTMLElement2); - - var _location2 = __webpack_require__(17); - - var _location3 = _interopRequireDefault(_location2); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - exports.document = _document3.default; - exports.navigator = _navigator3.default; - // export XMLHttpRequest from './XMLHttpRequest' - // export WebSocket from './WebSocket' - // export Image from './Image' - - exports.Audio = _Audio3.default; - exports.FileReader = _FileReader3.default; - exports.HTMLElement = _HTMLElement3.default; - // export localStorage from './localStorage' - - exports.location = _location3.default; - - - // 暴露全局的 canvas - var canvas = new _Canvas2.default(); - - exports.canvas = canvas; - // export { setTimeout } - // export { setInterval } - // export { clearTimeout } - // export { clearInterval } - // export { requestAnimationFrame } - // export { cancelAnimationFrame } - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.performance = exports.ontouchend = exports.ontouchmove = exports.ontouchstart = exports.screen = exports.devicePixelRatio = exports.innerHeight = exports.innerWidth = undefined; - - var _performance2 = __webpack_require__(3); - - var _performance3 = _interopRequireDefault(_performance2); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - var _window = window; - - var _qg$getSystemInfoSync = qg.getSystemInfoSync(), - devicePixelRatio = _qg$getSystemInfoSync.pixelRatio; - - var innerWidth = exports.innerWidth = _window.innerWidth; - var innerHeight = exports.innerHeight = _window.innerHeight; - exports.devicePixelRatio = devicePixelRatio; - var screen = exports.screen = { - availWidth: innerWidth, - availHeight: innerHeight - }; - var ontouchstart = exports.ontouchstart = null; - var ontouchmove = exports.ontouchmove = null; - var ontouchend = exports.ontouchend = null; - - exports.performance = _performance3.default; - -/***/ }), -/* 3 */ -/***/ (function(module, exports) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - var performance = void 0; - - if (qg.getPerformance) { - var sysInfo = qg.getSystemInfoSync(); - var platform = sysInfo.platformVersionName || sysInfo.platform; - var qgPerf = qg.getPerformance(); - var initTime = qgPerf.now(); - - var clientPerfAdapter = Object.assign({}, qgPerf, { - now: function now() { - return (qgPerf.now() - initTime) / 1000; - } - }); - - performance = platform === 'devtools' ? qgPerf : clientPerfAdapter; - } - - exports.default = performance; - -/***/ }), -/* 4 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.HTMLCanvasElement = exports.HTMLImageElement = undefined; - - var _HTMLElement3 = __webpack_require__(5); - - var _HTMLElement4 = _interopRequireDefault(_HTMLElement3); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - - var HTMLImageElement = exports.HTMLImageElement = function (_HTMLElement) { - _inherits(HTMLImageElement, _HTMLElement); - - function HTMLImageElement() { - _classCallCheck(this, HTMLImageElement); - - return _possibleConstructorReturn(this, (HTMLImageElement.__proto__ || Object.getPrototypeOf(HTMLImageElement)).call(this, 'img')); - } - - return HTMLImageElement; - }(_HTMLElement4.default); - - var HTMLCanvasElement = exports.HTMLCanvasElement = function (_HTMLElement2) { - _inherits(HTMLCanvasElement, _HTMLElement2); - - function HTMLCanvasElement() { - _classCallCheck(this, HTMLCanvasElement); - - return _possibleConstructorReturn(this, (HTMLCanvasElement.__proto__ || Object.getPrototypeOf(HTMLCanvasElement)).call(this, 'canvas')); - } - - return HTMLCanvasElement; - }(_HTMLElement4.default); - -/***/ }), -/* 5 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - var _Element2 = __webpack_require__(6); - - var _Element3 = _interopRequireDefault(_Element2); - - var _util = __webpack_require__(9); - - var _WindowProperties = __webpack_require__(2); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - - var HTMLElement = function (_Element) { - _inherits(HTMLElement, _Element); - - function HTMLElement() { - var tagName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; - - _classCallCheck(this, HTMLElement); - - var _this = _possibleConstructorReturn(this, (HTMLElement.__proto__ || Object.getPrototypeOf(HTMLElement)).call(this)); - - _this.className = ''; - _this.childern = []; - _this.style = { - width: _WindowProperties.innerWidth + 'px', - height: _WindowProperties.innerHeight + 'px' - }; - _this.insertBefore = _util.noop; - _this.innerHTML = ''; - - _this.tagName = tagName.toUpperCase(); - return _this; - } - - _createClass(HTMLElement, [{ - key: 'setAttribute', - value: function setAttribute(name, value) { - this[name] = value; - } - }, { - key: 'getAttribute', - value: function getAttribute(name) { - return this[name]; - } - }, { - key: 'getBoundingClientRect', - value: function getBoundingClientRect() { - return { - top: 0, - left: 0, - width: _WindowProperties.innerWidth, - height: _WindowProperties.innerHeight - }; - } - }, { - key: 'focus', - value: function focus() {} - }, { - key: 'clientWidth', - get: function get() { - var ret = parseInt(this.style.fontSize, 10) * this.innerHTML.length; - - return Number.isNaN(ret) ? 0 : ret; - } - }, { - key: 'clientHeight', - get: function get() { - var ret = parseInt(this.style.fontSize, 10); - - return Number.isNaN(ret) ? 0 : ret; - } - }]); - - return HTMLElement; - }(_Element3.default); - - exports.default = HTMLElement; - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _Node2 = __webpack_require__(7); - - var _Node3 = _interopRequireDefault(_Node2); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - - var ELement = function (_Node) { - _inherits(ELement, _Node); - - function ELement() { - _classCallCheck(this, ELement); - - var _this = _possibleConstructorReturn(this, (ELement.__proto__ || Object.getPrototypeOf(ELement)).call(this)); - - _this.className = ''; - _this.children = []; - return _this; - } - - return ELement; - }(_Node3.default); - - exports.default = ELement; - -/***/ }), -/* 7 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - var _EventTarget2 = __webpack_require__(8); - - var _EventTarget3 = _interopRequireDefault(_EventTarget2); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - - var Node = function (_EventTarget) { - _inherits(Node, _EventTarget); - - function Node() { - _classCallCheck(this, Node); - - var _this = _possibleConstructorReturn(this, (Node.__proto__ || Object.getPrototypeOf(Node)).call(this)); - - _this.childNodes = []; - return _this; - } - - _createClass(Node, [{ - key: 'appendChild', - value: function appendChild(node) { - if (node instanceof Node) { - this.childNodes.push(node); - } else { - throw new TypeError('Failed to executed \'appendChild\' on \'Node\': parameter 1 is not of type \'Node\'.'); - } - } - }, { - key: 'cloneNode', - value: function cloneNode() { - var copyNode = Object.create(this); - - Object.assign(copyNode, this); - return copyNode; - } - }, { - key: 'removeChild', - value: function removeChild(node) { - var index = this.childNodes.findIndex(function (child) { - return child === node; - }); - - if (index > -1) { - return this.childNodes.splice(index, 1); - } - return null; - } - }]); - - return Node; - }(_EventTarget3.default); - - exports.default = Node; - -/***/ }), -/* 8 */ -/***/ (function(module, exports) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - var _events = new WeakMap(); - - var EventTarget = function () { - function EventTarget() { - _classCallCheck(this, EventTarget); - - _events.set(this, {}); - } - - _createClass(EventTarget, [{ - key: 'addEventListener', - value: function addEventListener(type, listener) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - - var events = _events.get(this); - - if (!events) { - events = {}; - _events.set(this, events); - } - if (!events[type]) { - events[type] = []; - } - events[type].push(listener); - - if (options.capture) { - console.warn('EventTarget.addEventListener: options.capture is not implemented.'); - } - if (options.once) { - console.warn('EventTarget.addEventListener: options.once is not implemented.'); - } - if (options.passive) { - console.warn('EventTarget.addEventListener: options.passive is not implemented.'); - } - } - }, { - key: 'removeEventListener', - value: function removeEventListener(type, listener) { - var listeners = _events.get(this)[type]; - - if (listeners && listeners.length > 0) { - for (var i = listeners.length; i--; i > 0) { - if (listeners[i] === listener) { - listeners.splice(i, 1); - break; - } - } - } - } - }, { - key: 'dispatchEvent', - value: function dispatchEvent() { - var event = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - var listeners = _events.get(this)[event.type]; - - if (listeners) { - for (var i = 0; i < listeners.length; i++) { - listeners[i](event); - } - } - } - }]); - - return EventTarget; - }(); - - exports.default = EventTarget; - -/***/ }), -/* 9 */ -/***/ (function(module, exports) { - - "use strict"; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.noop = noop; - function noop() {} - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = Canvas; - - var _HTMLElement = __webpack_require__(5); - - var _HTMLElement2 = _interopRequireDefault(_HTMLElement); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - var _document = window.document; - - var isGetCanvas = true; - function createCanvas() { - if (isGetCanvas) { - isGetCanvas = false; - return _document.getElementById('canvas'); - } - return _document.createElement('canvas'); - } - function Canvas() { - - var canvas = createCanvas(); - - canvas.type = 'canvas'; - - canvas.__proto__.__proto__ = new _HTMLElement2.default('canvas'); - - var _getContext = canvas.getContext; - - canvas.getBoundingClientRect = function () { - var ret = { - top: 0, - left: 0, - width: window.innerWidth, - height: window.innerHeight - }; - return ret; - }; - - return canvas; - } - -/***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _window2 = __webpack_require__(1); - - var _window = _interopRequireWildcard(_window2); - - var _HTMLElement = __webpack_require__(5); - - var _HTMLElement2 = _interopRequireDefault(_HTMLElement); - - var _Audio = __webpack_require__(12); - - var _Audio2 = _interopRequireDefault(_Audio); - - var _Canvas = __webpack_require__(10); - - var _Canvas2 = _interopRequireDefault(_Canvas); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - - // import './EventIniter/' - - // import Image from './Image' - var events = {}; - var nativeEvents = ['touchstart', 'touchmove', 'touchend', 'touchcancel']; - var _addEventListener = window.addEventListener; - var _removeEventListener = window.removeEventListener; - - var document = { - readyState: 'complete', - visibilityState: 'visible', - documentElement: _window, - hidden: false, - style: {}, - location: _window.location, - ontouchstart: null, - ontouchmove: null, - ontouchend: null, - - head: new _HTMLElement2.default('head'), - body: new _HTMLElement2.default('body'), - - createElement: function createElement(tagName) { - if (tagName === 'canvas') { - return new _Canvas2.default(); - } else if (tagName === 'audio') { - return new _Audio2.default(); - } else if (tagName === 'img') { - return new Image(); - } - - return new _HTMLElement2.default(tagName); - }, - getElementById: function getElementById(id) { - if (id === 'canvas') { - return _window.canvas; - } - return null; - }, - getElementsByTagName: function getElementsByTagName(tagName) { - if (tagName === 'head') { - return [document.head]; - } else if (tagName === 'body') { - return [document.body]; - } else if (tagName === 'canvas') { - return [_window.canvas]; - } - return []; - }, - getElementsByName: function getElementsByName(tagName) { - if (tagName === 'head') { - return [document.head]; - } else if (tagName === 'body') { - return [document.body]; - } else if (tagName === 'canvas') { - return [_window.canvas]; - } - return []; - }, - querySelector: function querySelector(query) { - if (query === 'head') { - return document.head; - } else if (query === 'body') { - return document.body; - } else if (query === 'canvas') { - return _window.canvas; - } else if (query === '#' + _window.canvas.id) { - return _window.canvas; - } - return null; - }, - querySelectorAll: function querySelectorAll(query) { - if (query === 'head') { - return [document.head]; - } else if (query === 'body') { - return [document.body]; - } else if (query === 'canvas') { - return [_window.canvas]; - } - return []; - }, - addEventListener: function addEventListener(type, listener) { - if (nativeEvents.indexOf(type) > -1 && _addEventListener) { - _addEventListener(type, listener); - return; - } - if (!events[type]) { - events[type] = []; - } - events[type].push(listener); - }, - removeEventListener: function removeEventListener(type, listener) { - var listeners = events[type]; - - if (nativeEvents.indexOf(type) > -1 && _removeEventListener) { - _removeEventListener(type, listener); - return; - } - if (listeners && listeners.length > 0) { - for (var i = listeners.length; i--; i > 0) { - if (listeners[i] === listener) { - listeners.splice(i, 1); - break; - } - } - } - }, - dispatchEvent: function dispatchEvent(event) { - var listeners = events[event.type]; - - if (listeners) { - for (var i = 0; i < listeners.length; i++) { - listeners[i](event); - } - } - } - }; - - exports.default = document; - -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - var _HTMLAudioElement2 = __webpack_require__(13); - - var _HTMLAudioElement3 = _interopRequireDefault(_HTMLAudioElement2); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - - var HAVE_NOTHING = 0; - var HAVE_METADATA = 1; - var HAVE_CURRENT_DATA = 2; - var HAVE_FUTURE_DATA = 3; - var HAVE_ENOUGH_DATA = 4; - - var _innerAudioContext = new WeakMap(); - var _src = new WeakMap(); - var _loop = new WeakMap(); - var _autoplay = new WeakMap(); - - var Audio = function (_HTMLAudioElement) { - _inherits(Audio, _HTMLAudioElement); - - function Audio(url) { - _classCallCheck(this, Audio); - - var _this = _possibleConstructorReturn(this, (Audio.__proto__ || Object.getPrototypeOf(Audio)).call(this)); - - _this.HAVE_NOTHING = HAVE_NOTHING; - _this.HAVE_METADATA = HAVE_METADATA; - _this.HAVE_CURRENT_DATA = HAVE_CURRENT_DATA; - _this.HAVE_FUTURE_DATA = HAVE_FUTURE_DATA; - _this.HAVE_ENOUGH_DATA = HAVE_ENOUGH_DATA; - _this.readyState = HAVE_NOTHING; - - - _src.set(_this, ''); - - var innerAudioContext = qg.createInnerAudioContext(); - - _innerAudioContext.set(_this, innerAudioContext); - - innerAudioContext.onCanplay(function () { - _this.dispatchEvent({ type: 'load' }); - _this.dispatchEvent({ type: 'loadend' }); - _this.dispatchEvent({ type: 'canplay' }); - _this.dispatchEvent({ type: 'canplaythrough' }); - _this.dispatchEvent({ type: 'loadedmetadata' }); - _this.readyState = HAVE_CURRENT_DATA; - }); - innerAudioContext.onPlay(function () { - _this.dispatchEvent({ type: 'play' }); - }); - innerAudioContext.onPause(function () { - _this.dispatchEvent({ type: 'pause' }); - }); - innerAudioContext.onEnded(function () { - _this.dispatchEvent({ type: 'ended' }); - _this.readyState = HAVE_ENOUGH_DATA; - }); - innerAudioContext.onError(function () { - _this.dispatchEvent({ type: 'error' }); - }); - - if (url) { - _innerAudioContext.get(_this).src = url; - } - return _this; - } - - _createClass(Audio, [{ - key: 'load', - value: function load() { - console.warn('HTMLAudioElement.load() is not implemented.'); - } - }, { - key: 'play', - value: function play() { - _innerAudioContext.get(this).play(); - } - }, { - key: 'pause', - value: function pause() { - _innerAudioContext.get(this).pause(); - } - }, { - key: 'canPlayType', - value: function canPlayType() { - var mediaType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; - - if (typeof mediaType !== 'string') { - return ''; - } - - if (mediaType.indexOf('audio/mpeg') > -1 || mediaType.indexOf('audio/mp4')) { - return 'probably'; - } - return ''; - } - }, { - key: 'cloneNode', - value: function cloneNode() { - var newAudio = new Audio(); - newAudio.loop = _innerAudioContext.get(this).loop; - newAudio.autoplay = _innerAudioContext.get(this).autoplay; - newAudio.src = this.src; - return newAudio; - } - }, { - key: 'currentTime', - get: function get() { - return _innerAudioContext.get(this).currentTime; - }, - set: function set(value) { - _innerAudioContext.get(this).seek(value); - } - }, { - key: 'src', - get: function get() { - return _src.get(this); - }, - set: function set(value) { - _src.set(this, value); - _innerAudioContext.get(this).src = value; - } - }, { - key: 'loop', - get: function get() { - return _innerAudioContext.get(this).loop; - }, - set: function set(value) { - _innerAudioContext.get(this).loop = value; - } - }, { - key: 'autoplay', - get: function get() { - return _innerAudioContext.get(this).autoplay; - }, - set: function set(value) { - _innerAudioContext.get(this).autoplay = value; - } - }, { - key: 'paused', - get: function get() { - return _innerAudioContext.get(this).paused; - } - }]); - - return Audio; - }(_HTMLAudioElement3.default); - - exports.default = Audio; - -/***/ }), -/* 13 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _HTMLMediaElement2 = __webpack_require__(14); - - var _HTMLMediaElement3 = _interopRequireDefault(_HTMLMediaElement2); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - - var HTMLAudioElement = function (_HTMLMediaElement) { - _inherits(HTMLAudioElement, _HTMLMediaElement); - - function HTMLAudioElement() { - _classCallCheck(this, HTMLAudioElement); - - return _possibleConstructorReturn(this, (HTMLAudioElement.__proto__ || Object.getPrototypeOf(HTMLAudioElement)).call(this, 'audio')); - } - - return HTMLAudioElement; - }(_HTMLMediaElement3.default); - - exports.default = HTMLAudioElement; - -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - var _HTMLElement2 = __webpack_require__(5); - - var _HTMLElement3 = _interopRequireDefault(_HTMLElement2); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - - var HTMLMediaElement = function (_HTMLElement) { - _inherits(HTMLMediaElement, _HTMLElement); - - function HTMLMediaElement(type) { - _classCallCheck(this, HTMLMediaElement); - - return _possibleConstructorReturn(this, (HTMLMediaElement.__proto__ || Object.getPrototypeOf(HTMLMediaElement)).call(this, type)); - } - - _createClass(HTMLMediaElement, [{ - key: 'addTextTrack', - value: function addTextTrack() {} - }, { - key: 'captureStream', - value: function captureStream() {} - }, { - key: 'fastSeek', - value: function fastSeek() {} - }, { - key: 'load', - value: function load() {} - }, { - key: 'pause', - value: function pause() {} - }, { - key: 'play', - value: function play() {} - }]); - - return HTMLMediaElement; - }(_HTMLElement3.default); - - exports.default = HTMLMediaElement; - -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _util = __webpack_require__(9); - - // TODO 需要 qg.getSystemInfo 获取更详细信息 - var sysInfo = qg.getSystemInfoSync(); - var platform = sysInfo.platformVersionName || sysInfo.platform; - var navigator = { - platform: platform, - language: 'zh-cn', - appVersion: '5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1', - // userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E8301 MicroMessenger/6.6.0 QuickGame NetType/WIFI Language/zh_CN', - userAgent: 'Mozilla/5.0 (Linux; Android 7.0; Redmi Note 4X Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/61.0.3163.128 Mobile Safari/537.36 QuickGame Language/zh_CN', - onLine: true, // TODO 用 qg.getNetworkStateChange 和 qg.onNetworkStateChange 来返回真实的状态 - - // TODO 用 qg.getLocation 来封装 geolocation - geolocation: { - getCurrentPosition: _util.noop, - watchPosition: _util.noop, - clearWatch: _util.noop - } - }; - - exports.default = navigator; - -/***/ }), -/* 16 */ -/***/ (function(module, exports) { - - "use strict"; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - /* - * TODO 使用 qg.readFile 来封装 FileReader - */ - var FileReader = function () { - function FileReader() { - _classCallCheck(this, FileReader); - } - - _createClass(FileReader, [{ - key: "construct", - value: function construct() {} - }]); - - return FileReader; - }(); - - exports.default = FileReader; - -/***/ }), -/* 17 */ -/***/ (function(module, exports) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - var location = { - href: 'game.js', - protocol: '', - reload: function reload() {} - }; - - exports.default = location; - -/***/ }) -/******/ ]); - -require('../../../common/xmldom/dom-parser'); -require('./unify'); \ No newline at end of file diff --git a/platforms/minigame/platforms/xiaomi/wrapper/engine/Editbox.js b/platforms/minigame/platforms/xiaomi/wrapper/engine/Editbox.js deleted file mode 100644 index 8f13a0f5dd..0000000000 --- a/platforms/minigame/platforms/xiaomi/wrapper/engine/Editbox.js +++ /dev/null @@ -1,180 +0,0 @@ -(function () { - if (!(cc && cc.EditBoxComponent)) { - return; - } - - const EditBoxComp = cc.EditBoxComponent; - const js = cc.js; - const KeyboardReturnType = EditBoxComp.KeyboardReturnType; - const MAX_VALUE = 65535; - const KEYBOARD_HIDE_TIME = 600; - let _hideKeyboardTimeout = null; - let _currentEditBoxImpl = null; - - function getKeyboardReturnType (type) { - switch (type) { - case KeyboardReturnType.DEFAULT: - case KeyboardReturnType.DONE: - return 'done'; - case KeyboardReturnType.SEND: - return 'send'; - case KeyboardReturnType.SEARCH: - return 'search'; - case KeyboardReturnType.GO: - return 'go'; - case KeyboardReturnType.NEXT: - return 'next'; - } - return 'done'; - } - - function MiniGameEditBoxImpl () { - this._delegate = null; - this._editing = false; - - this._eventListeners = { - onKeyboardInput: null, - onKeyboardConfirm: null, - onKeyboardComplete: null, - }; - } - - js.extend(MiniGameEditBoxImpl, EditBoxComp._EditBoxImpl); - EditBoxComp._EditBoxImpl = MiniGameEditBoxImpl; - - Object.assign(MiniGameEditBoxImpl.prototype, { - init (delegate) { - if (!delegate) { - cc.error('EditBox init failed'); - return; - } - this._delegate = delegate; - }, - - beginEditing () { - // In case multiply register events - if (this._editing) { - return; - } - this._ensureKeyboardHide(() => { - let delegate = this._delegate; - this._showKeyboard(() => { - // NOTE: pass defaultValue when showKeyboard is invalid on Xiaomi platform - // need to manually update the value - __globalAdapter.updateKeyboard({ - value: delegate.string, - }); - // NOTE: need to delay the event registering on Xiaomi platform - // the input event callback is invoked twice when show keyboard. - this._registerKeyboardEvent(); - this._editing = true; - _currentEditBoxImpl = this; - delegate._editBoxEditingDidBegan(); - }); - }); - }, - - endEditing () { - this._hideKeyboard(); - let cbs = this._eventListeners; - cbs.onKeyboardComplete && cbs.onKeyboardComplete(); - }, - - _registerKeyboardEvent () { - let self = this; - let delegate = this._delegate; - let cbs = this._eventListeners; - - cbs.onKeyboardInput = function (res) { - if (delegate._string !== res.value) { - delegate._editBoxTextChanged(res.value); - } - } - - cbs.onKeyboardConfirm = function (res) { - delegate._editBoxEditingReturn(); - let cbs = self._eventListeners; - cbs.onKeyboardComplete && cbs.onKeyboardComplete(); - } - - cbs.onKeyboardComplete = function () { - self._editing = false; - _currentEditBoxImpl = null; - self._unregisterKeyboardEvent(); - delegate._editBoxEditingDidEnded(); - } - - __globalAdapter.onKeyboardInput(cbs.onKeyboardInput); - __globalAdapter.onKeyboardConfirm(cbs.onKeyboardConfirm); - __globalAdapter.onKeyboardComplete(cbs.onKeyboardComplete); - }, - - _unregisterKeyboardEvent () { - let cbs = this._eventListeners; - - if (cbs.onKeyboardInput) { - __globalAdapter.offKeyboardInput(cbs.onKeyboardInput); - cbs.onKeyboardInput = null; - } - if (cbs.onKeyboardConfirm) { - __globalAdapter.offKeyboardConfirm(cbs.onKeyboardConfirm); - cbs.onKeyboardConfirm = null; - } - if (cbs.onKeyboardComplete) { - __globalAdapter.offKeyboardComplete(cbs.onKeyboardComplete); - cbs.onKeyboardComplete = null; - } - }, - - _otherEditing () { - return !!_currentEditBoxImpl && _currentEditBoxImpl !== this && _currentEditBoxImpl._editing; - }, - - _ensureKeyboardHide (cb) { - let otherEditing = this._otherEditing(); - if (!otherEditing && !_hideKeyboardTimeout) { - return cb(); - } - if (_hideKeyboardTimeout) { - clearTimeout(_hideKeyboardTimeout); - } - if (otherEditing) { - _currentEditBoxImpl.endEditing(); - } - _hideKeyboardTimeout = setTimeout(() => { - _hideKeyboardTimeout = null; - cb(); - }, KEYBOARD_HIDE_TIME); - }, - - _showKeyboard (successCB) { - let delegate = this._delegate; - let multiline = (delegate.inputMode === EditBoxComp.InputMode.ANY); - __globalAdapter.showKeyboard({ - defaultValue: delegate.string, - maxLength: delegate.maxLength < 0 ? MAX_VALUE : delegate.maxLength, - multiple: multiline, - confirmHold: false, - confirmType: getKeyboardReturnType(delegate.returnType), - success (res) { - successCB && successCB(); - }, - fail (res) { - cc.warn(res.errMsg); - } - }); - }, - - _hideKeyboard () { - __globalAdapter.hideKeyboard({ - success (res) { - - }, - fail (res) { - cc.warn(res.errMsg); - }, - }); - }, - }); -})(); - diff --git a/platforms/minigame/platforms/xiaomi/wrapper/engine/download-ttf.js b/platforms/minigame/platforms/xiaomi/wrapper/engine/download-ttf.js deleted file mode 100644 index 8c7c3d064c..0000000000 --- a/platforms/minigame/platforms/xiaomi/wrapper/engine/download-ttf.js +++ /dev/null @@ -1,12 +0,0 @@ -const downloader = cc.assetManager.downloader; -const originalDownloadTTF = downloader.handlers['.ttf']; - -function downloadTTF (url, options, onComplete) { - // can't use cached ttf on Xiaomi platform - options.cacheEnabled = false; - originalDownloadTTF(url, options, onComplete); -} - -downloader.register({ - '.ttf': downloadTTF, -}); diff --git a/platforms/minigame/platforms/xiaomi/wrapper/engine/index.js b/platforms/minigame/platforms/xiaomi/wrapper/engine/index.js deleted file mode 100644 index 1c6ef7b5de..0000000000 --- a/platforms/minigame/platforms/xiaomi/wrapper/engine/index.js +++ /dev/null @@ -1,4 +0,0 @@ -require('../fs-utils'); -require('../../../../common/engine/index'); -require('./download-ttf'); -require('./Editbox'); diff --git a/platforms/minigame/platforms/xiaomi/wrapper/fs-utils.js b/platforms/minigame/platforms/xiaomi/wrapper/fs-utils.js deleted file mode 100644 index 6f226b84d1..0000000000 --- a/platforms/minigame/platforms/xiaomi/wrapper/fs-utils.js +++ /dev/null @@ -1,262 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2019 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated 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. - ****************************************************************************/ -const fs = qg.getFileSystemManager ? qg.getFileSystemManager() : null; -const outOfStorageRegExp = /the maximum size of the file storage/; // not exactly right - -const fsUtils = { - - fs, - - isOutOfStorage (errMsg) { - return outOfStorageRegExp.test(errMsg); - }, - - getUserDataPath () { - return qg.env.USER_DATA_PATH; - }, - - checkFsValid () { - if (!fs) { - console.warn('can not get the file system!'); - return false; - } - return true; - }, - - deleteFile (filePath, onComplete) { - fs.unlink({ - filePath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Delete file failed: path: ${filePath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg)); - }, - }); - }, - - downloadFile (remoteUrl, filePath, header, onProgress, onComplete) { - const options = { - url: remoteUrl, - success (res) { - if (res.statusCode === 200) { - onComplete && onComplete(null, res.tempFilePath || res.filePath); - } else { - if (res.filePath) { - fsUtils.deleteFile(res.filePath); - } - console.warn(`Download file failed: path: ${remoteUrl} message: ${res.statusCode}`); - onComplete && onComplete(new Error(res.statusCode), null); - } - }, - fail (res) { - console.warn(`Download file failed: path: ${remoteUrl} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg), null); - }, - }; - if (filePath) options.filePath = filePath; - if (header) options.header = header; - const task = qg.downloadFile(options); - onProgress && task.onProgressUpdate(onProgress); - }, - - saveFile (srcPath, destPath, onComplete) { - qg.saveFile({ - tempFilePath: srcPath, - filePath: destPath, - success (res) { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Save file failed: path: ${srcPath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg)); - }, - }); - }, - - copyFile (srcPath, destPath, onComplete) { - fs.copyFile({ - srcPath, - destPath, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Copy file failed: path: ${srcPath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg)); - }, - }); - }, - - writeFile (path, data, encoding, onComplete) { - fs.writeFile({ - filePath: path, - encoding, - data, - success () { - onComplete && onComplete(null); - }, - fail (res) { - console.warn(`Write file failed: path: ${path} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg)); - }, - }); - }, - - writeFileSync (path, data, encoding) { - try { - fs.writeFileSync(path, data, encoding); - return null; - } catch (e) { - console.warn(`Write file failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - readFile (filePath, encoding, onComplete) { - fs.readFile({ - filePath, - encoding, - success (res) { - onComplete && onComplete(null, res.data); - }, - fail (res) { - console.warn(`Read file failed: path: ${filePath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg), null); - }, - }); - }, - - readDir (filePath, onComplete) { - fs.readdir({ - dirPath: filePath, - success (res) { - onComplete && onComplete(null, res.files); - }, - fail (res) { - console.warn(`Read directory failed: path ${filePath} message: ${res.errMsg}`); - onComplete && onComplete(new Error(res.errMsg), null); - }, - }); - }, - - readText (filePath, onComplete) { - fsUtils.readFile(filePath, 'utf8', onComplete); - }, - - readArrayBuffer (filePath, onComplete) { - fsUtils.readFile(filePath, '', onComplete); - }, - - readJson (filePath, onComplete) { - fsUtils.readFile(filePath, 'utf8', (err, text) => { - let out = null; - if (!err) { - try { - out = JSON.parse(text); - } catch (e) { - console.warn(`Read json failed: path: ${filePath} message: ${e.message}`); - err = new Error(e.message); - } - } - onComplete && onComplete(err, out); - }); - }, - - readJsonSync (path) { - try { - const str = fs.readFileSync(path, 'utf8'); - return JSON.parse(str.data); - } catch (e) { - console.warn(`Read json failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - makeDirSync (path, recursive) { - try { - fs.mkdirSync(path, recursive); - return null; - } catch (e) { - console.warn(`Make directory failed: path: ${path} message: ${e.message}`); - return new Error(e.message); - } - }, - - rmdirSync (dirPath, recursive) { - try { - fs.rmdirSync(dirPath, recursive); - return null; - } catch (e) { - console.warn(`rm directory failed: path: ${dirPath} message: ${e.message}`); - return new Error(e.message); - } - }, - - exists (filePath, onComplete) { - fs.access({ - path: filePath, - success () { - onComplete && onComplete(true); - }, - fail () { - onComplete && onComplete(false); - }, - }); - }, - - loadSubpackage (name, onProgress, onComplete) { - name = `usr_${name}`; // prevention of name conflicts with platform - const task = qg.loadSubpackage({ - name, - success () { - onComplete && onComplete(); - }, - fail (res) { - console.warn(`Load Subpackage failed: name: ${name} message: ${res.errMsg}`); - onComplete && onComplete(new Error(`Failed to load subpackage ${name}: ${res.errMsg}`)); - }, - }); - onProgress && task.onProgressUpdate(onProgress); - return task; - }, - - unzip (zipFilePath, targetPath, onComplete) { - fs.unzip({ - zipFilePath, - targetPath, - success () { - onComplete && onComplete(null); - }, - fail (errMsg) { - console.warn(`unzip failed: path: ${zipFilePath} message: ${errMsg}`); - onComplete && onComplete(new Error(`unzip failed: ${errMsg}`)); - }, - }); - }, -}; - -window.fsUtils = module.exports = fsUtils; diff --git a/platforms/minigame/platforms/xiaomi/wrapper/unify.js b/platforms/minigame/platforms/xiaomi/wrapper/unify.js deleted file mode 100644 index 3a641f2a69..0000000000 --- a/platforms/minigame/platforms/xiaomi/wrapper/unify.js +++ /dev/null @@ -1,123 +0,0 @@ -const utils = require('./utils'); - -window.__globalAdapter = window.__globalAdapter || {}; -if (window.__globalAdapter) { - let globalAdapter = window.__globalAdapter; - // SystemInfo - globalAdapter.isSubContext = false; // sub context not supported - globalAdapter.isDevTool = false; - utils.cloneMethod(globalAdapter, qg, 'getSystemInfoSync'); - - // TouchEvent - globalAdapter.onTouchStart = function (cb) { - window.canvas.ontouchstart = cb; - }; - globalAdapter.onTouchMove = function (cb) { - window.canvas.ontouchmove = cb; - }; - globalAdapter.onTouchEnd = function (cb) { - window.canvas.ontouchend = cb; - }; - globalAdapter.onTouchCancel = function (cb) { - window.canvas.ontouchcancel = cb; - }; - - // Audio - utils.cloneMethod(globalAdapter, qg, 'createInnerAudioContext'); - - // FrameRate - utils.cloneMethod(globalAdapter, qg, 'setPreferredFramesPerSecond'); - - // Keyboard - globalAdapter.showKeyboard = function (res) { - res.confirmHold = true; // HACK: confirmHold not working on Xiaomi platform - qg.showKeyboard(res); - }; - utils.cloneMethod(globalAdapter, qg, 'hideKeyboard'); - utils.cloneMethod(globalAdapter, qg, 'updateKeyboard'); - utils.cloneMethod(globalAdapter, qg, 'onKeyboardInput'); - utils.cloneMethod(globalAdapter, qg, 'onKeyboardConfirm'); - utils.cloneMethod(globalAdapter, qg, 'onKeyboardComplete'); - utils.cloneMethod(globalAdapter, qg, 'offKeyboardInput'); - utils.cloneMethod(globalAdapter, qg, 'offKeyboardConfirm'); - utils.cloneMethod(globalAdapter, qg, 'offKeyboardComplete'); - - // Message - utils.cloneMethod(globalAdapter, qg, 'getOpenDataContext'); - utils.cloneMethod(globalAdapter, qg, 'onMessage'); - - // Subpackage - utils.cloneMethod(globalAdapter, qg, 'loadSubpackage'); - - // SharedCanvas - utils.cloneMethod(globalAdapter, qg, 'getSharedCanvas'); - - // Font - utils.cloneMethod(globalAdapter, qg, 'loadFont'); - - // hide show Event - utils.cloneMethod(globalAdapter, qg, 'onShow'); - utils.cloneMethod(globalAdapter, qg, 'onHide'); - - // Accelerometer - // NOTE: There is no LANDSCAPE_LEFT on Xiaomi platform - // const LANDSCAPE_LEFT = -90; - const LANDSCAPE_RIGHT = 90; - // NOTE: the data in callback registered on onAccelerometerChange is 10 times than the standard data - // Need to be scaled by 0.1 - const accelerometerFactor = -0.1; - let isAccelerometerInit = false; - let deviceOrientation = 1; - let isLandscape = window.orientation === LANDSCAPE_RIGHT; - if (qg.onDeviceOrientationChange) { - qg.onDeviceOrientationChange(function (res) { - if (res.value === 'landscape') { - deviceOrientation = 1; - } - else if (res.value === 'landscapeReverse') { - deviceOrientation = -1; - } - }); - } - Object.assign(globalAdapter, { - startAccelerometer (cb) { - if (!isAccelerometerInit) { - isAccelerometerInit = true; - qg.onAccelerometerChange && qg.onAccelerometerChange(function (res) { - let resClone = {}; - let x = res.x; - let y = res.y; - if (isLandscape) { - let tmp = x; - x = -y; - y = tmp; - } - - resClone.x = x * accelerometerFactor; - resClone.y = y * accelerometerFactor; - resClone.z = res.z; - cb && cb(resClone); - }); - } - else { - qg.startAccelerometer && qg.startAccelerometer({ - fail (err) { - console.error('start accelerometer failed', err); - }, - // success () {}, - // complete () {}, - }); - } - }, - - stopAccelerometer () { - qg.stopAccelerometer && qg.stopAccelerometer({ - fail (err) { - console.error('stop accelerometer failed', err); - }, - // success () {}, - // complete () {}, - }); - }, - }); -} \ No newline at end of file diff --git a/platforms/minigame/platforms/xiaomi/wrapper/utils.js b/platforms/minigame/platforms/xiaomi/wrapper/utils.js deleted file mode 100644 index 947fc06958..0000000000 --- a/platforms/minigame/platforms/xiaomi/wrapper/utils.js +++ /dev/null @@ -1,16 +0,0 @@ -let utils = { - /** - * @param {Object} target - * @param {Object} origin - * @param {String} methodName - * @param {String} targetMethodName - */ - cloneMethod (target, origin, methodName, targetMethodName) { - if (origin[methodName]) { - targetMethodName = targetMethodName || methodName; - target[targetMethodName] = origin[methodName].bind(origin); - } - } -}; - -module.exports = utils; \ No newline at end of file diff --git a/platforms/native/README.md b/platforms/native/README.md deleted file mode 100644 index fea3169f92..0000000000 --- a/platforms/native/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# Adapter for Native platform -included platforms: -- Android -- iOS -- Mac -- win32 \ No newline at end of file diff --git a/platforms/native/builtin/Blob.js b/platforms/native/builtin/Blob.js deleted file mode 100644 index 80e3234a53..0000000000 --- a/platforms/native/builtin/Blob.js +++ /dev/null @@ -1,223 +0,0 @@ -/* Blob.js - * A Blob implementation. - * 2017-11-15 - * - * By Eli Grey, http://eligrey.com - * By Devin Samarin, https://github.com/dsamarin - * License: MIT - * See https://github.com/eligrey/Blob.js/blob/master/LICENSE.md - */ - -/*global self, unescape */ -/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true, - plusplus: true */ - -/*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */ - -(function (global) { -(function (factory) { - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define(['exports'], factory); - } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') { - // CommonJS - factory(exports); - } else { - // Browser globals - factory(global); - } -}((exports) => { - exports.URL = global.URL || global.webkitURL; - - if (global.Blob && global.URL) { - try { - new Blob(); - return; - } catch (e) {} - } - - // Internally we use a BlobBuilder implementation to base Blob off of - // in order to support older browsers that only have BlobBuilder - const BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder || global.MozBlobBuilder || (function () { - const - get_class = function (object) { - return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1]; - }; - const FakeBlobBuilder = function BlobBuilder () { - this.data = []; - }; - const FakeBlob = function Blob (data, type, encoding) { - this.data = data; - this.size = data.length; - this.type = type; - this.encoding = encoding; - }; - const FBB_proto = FakeBlobBuilder.prototype; - const FB_proto = FakeBlob.prototype; - const FileReaderSync = global.FileReaderSync; - const FileException = function (type) { - this.code = this[this.name = type]; - }; - const file_ex_codes = ( - 'NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR ' - + 'NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR' - ).split(' '); - let file_ex_code = file_ex_codes.length; - const real_URL = global.URL || global.webkitURL || exports; - const real_create_object_URL = real_URL.createObjectURL; - const real_revoke_object_URL = real_URL.revokeObjectURL; - let URL = real_URL; - const btoa = global.btoa; - const atob = global.atob; - - const ArrayBuffer = global.ArrayBuffer; - const Uint8Array = global.Uint8Array; - - const origin = /^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/; -FakeBlob.fake = FB_proto.fake = true; - while (file_ex_code--) { - FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1; - } - // Polyfill URL - if (!real_URL.createObjectURL) { - URL = exports.URL = function (uri) { - const - uri_info = document.createElementNS('http://www.w3.org/1999/xhtml', 'a'); - let uri_origin; -uri_info.href = uri; - if (!('origin' in uri_info)) { - if (uri_info.protocol.toLowerCase() === 'data:') { - uri_info.origin = null; - } else { - uri_origin = uri.match(origin); - uri_info.origin = uri_origin && uri_origin[1]; - } - } - return uri_info; - }; - } - URL.createObjectURL = function (blob) { - let - type = blob.type; - let data_URI_header; -if (type === null) { - type = 'application/octet-stream'; - } - if (blob instanceof FakeBlob) { - data_URI_header = `data:${type}`; - if (blob.encoding === 'base64') { - return `${data_URI_header};base64,${blob.data}`; - } else if (blob.encoding === 'URI') { - return `${data_URI_header},${decodeURIComponent(blob.data)}`; - } if (btoa) { - return `${data_URI_header};base64,${btoa(blob.data)}`; - } else { - return `${data_URI_header},${encodeURIComponent(blob.data)}`; - } - } else if (real_create_object_URL) { - return real_create_object_URL.call(real_URL, blob); - } - }; - URL.revokeObjectURL = function (object_URL) { - if (object_URL.substring(0, 5) !== 'data:' && real_revoke_object_URL) { - real_revoke_object_URL.call(real_URL, object_URL); - } - }; - FBB_proto.append = function (data/*, endings*/) { - const bb = this.data; - // decode data to a binary string - if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) { - let - str = ''; -const buf = new Uint8Array(data); -let i = 0; -const buf_len = buf.length; -for (; i < buf_len; i++) { - str += String.fromCharCode(buf[i]); - } - bb.push(str); - } else if (get_class(data) === 'Blob' || get_class(data) === 'File') { - if (FileReaderSync) { - const fr = new FileReaderSync(); - bb.push(fr.readAsBinaryString(data)); - } else { - // async FileReader won't work as BlobBuilder is sync - throw new FileException('NOT_READABLE_ERR'); - } - } else if (data instanceof FakeBlob) { - if (data.encoding === 'base64' && atob) { - bb.push(atob(data.data)); - } else if (data.encoding === 'URI') { - bb.push(decodeURIComponent(data.data)); - } else if (data.encoding === 'raw') { - bb.push(data.data); - } - } else { - if (typeof data !== 'string') { - data += ''; // convert unsupported types to strings - } - // decode UTF-16 to binary string - bb.push(unescape(encodeURIComponent(data))); - } - }; - FBB_proto.getBlob = function (type) { - if (!arguments.length) { - type = null; - } - return new FakeBlob(this.data.join(''), type, 'raw'); - }; - FBB_proto.toString = function () { - return '[object BlobBuilder]'; - }; - FB_proto.slice = function (start, end, type) { - const args = arguments.length; - if (args < 3) { - type = null; - } - return new FakeBlob( - this.data.slice(start, args > 1 ? end : this.data.length), - type, - this.encoding, - ); - }; - FB_proto.toString = function () { - return '[object Blob]'; - }; - FB_proto.close = function () { - this.size = 0; - delete this.data; - }; - return FakeBlobBuilder; - }()); - - exports.Blob = function (blobParts, options) { - const type = options ? (options.type || '') : ''; - const builder = new BlobBuilder(); - if (blobParts) { - for (let i = 0, len = blobParts.length; i < len; i++) { - if (Uint8Array && blobParts[i] instanceof Uint8Array) { - builder.append(blobParts[i].buffer); - } else { - builder.append(blobParts[i]); - } - } - } - const blob = builder.getBlob(type); - if (!blob.slice && blob.webkitSlice) { - blob.slice = blob.webkitSlice; - } - return blob; - }; - - const getPrototypeOf = Object.getPrototypeOf || function (object) { - return object.__proto__; - }; - exports.Blob.prototype = getPrototypeOf(new exports.Blob()); -})); -}( - typeof self !== 'undefined' && self - || typeof window !== 'undefined' && window - || typeof global !== 'undefined' && global - || typeof globalThis !== 'undefined' && globalThis - || this.content || this, -)); diff --git a/platforms/native/builtin/base64/base64.min.js b/platforms/native/builtin/base64/base64.min.js deleted file mode 100644 index 3b8a4c70a0..0000000000 --- a/platforms/native/builtin/base64/base64.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(){function e(e){this.message=e}var t="undefined"!=typeof exports?exports:"undefined"!=typeof self?self:$.global,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";e.prototype=new Error,e.prototype.name="InvalidCharacterError",t.btoa||(t.btoa=function(t){for(var o,n,a=String(t),i=0,f=r,c="";a.charAt(0|i)||(f="=",i%1);c+=f.charAt(63&o>>8-i%1*8)){if(n=a.charCodeAt(i+=.75),n>255)throw new e("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|n}return c}),t.atob||(t.atob=function(t){var o=String(t).replace(/[=]+$/,"");if(o.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,a,i=0,f=0,c="";a=o.charAt(f++);~a&&(n=i%4?64*n+a:a,i++%4)?c+=String.fromCharCode(255&n>>(-2*i&6)):0)a=r.indexOf(a);return c})}(); diff --git a/platforms/native/builtin/index.js b/platforms/native/builtin/index.js deleted file mode 100644 index 46130a11b3..0000000000 --- a/platforms/native/builtin/index.js +++ /dev/null @@ -1,225 +0,0 @@ -globalThis.__EDITOR__ = globalThis.process && ('electron' in globalThis.process.versions); - -require('./wasm'); -const jsbWindow = require('../jsbWindow'); - -jsb.device = jsb.Device; // cc namespace will be reset to {} in creator, use jsb namespace instead. - -const { btoa, atob } = require('./base64/base64.min'); - -jsbWindow.btoa = btoa; -jsbWindow.atob = atob; -const { Blob, URL } = require('./Blob'); - -jsbWindow.Blob = Blob; -jsbWindow.URL = URL; -jsbWindow.DOMParser = require('./xmldom/dom-parser').DOMParser; - -jsbWindow.XMLHttpRequest = jsb.XMLHttpRequest; -jsbWindow.SocketIO = jsb.SocketIO; -jsbWindow.WebSocket = jsb.WebSocket; - -require('./jsb_prepare'); -require('./jsb-adapter'); -require('./jsb_audioengine'); -require('./jsb_input'); - -let _oldRequestFrameCallback = null; -let _requestAnimationFrameID = 0; -const _requestAnimationFrameCallbacks = {}; -let _firstTick = true; - -jsbWindow.requestAnimationFrame = function (cb) { - const id = ++_requestAnimationFrameID; - _requestAnimationFrameCallbacks[id] = cb; - return id; -}; - -jsbWindow.cancelAnimationFrame = function (id) { - delete _requestAnimationFrameCallbacks[id]; -}; - -function tick (nowMilliSeconds) { - if (_firstTick) { - _firstTick = false; - if (jsbWindow.onload) { - const event = new Event('load'); - event._target = globalThis; - jsbWindow.onload(event); - } - } - fireTimeout(nowMilliSeconds); - - for (const id in _requestAnimationFrameCallbacks) { - _oldRequestFrameCallback = _requestAnimationFrameCallbacks[id]; - if (_oldRequestFrameCallback) { - delete _requestAnimationFrameCallbacks[id]; - _oldRequestFrameCallback(nowMilliSeconds); - } - } -} - -let _timeoutIDIndex = 0; - -class TimeoutInfo { - constructor (cb, delay, isRepeat, target, args) { - this.cb = cb; - this.id = ++_timeoutIDIndex; - this.start = performance.now(); - this.delay = delay; - this.isRepeat = isRepeat; - this.target = target; - this.args = args; - } -} - -const _timeoutInfos = {}; - -function fireTimeout (nowMilliSeconds) { - let info; - for (const id in _timeoutInfos) { - info = _timeoutInfos[id]; - if (info && info.cb) { - if ((nowMilliSeconds - info.start) >= info.delay) { - // console.log(`fireTimeout: id ${id}, start: ${info.start}, delay: ${info.delay}, now: ${nowMilliSeconds}`); - if (info.isRepeat) { - info.start = nowMilliSeconds; - } else { - // The delete operation should be performed before the timeout callback. - // This is because if an error occurs during the timeout callback, - // it could be triggered indefinitely, leading to a game freeze. - delete _timeoutInfos[id]; - } - - if (typeof info.cb === 'string') { - Function(info.cb)(); - } else if (typeof info.cb === 'function') { - info.cb.apply(info.target, info.args); - } - } - } - } -} - -function createTimeoutInfo (prevFuncArgs, isRepeat) { - const cb = prevFuncArgs[0]; - if (!cb) { - console.error('createTimeoutInfo doesn\'t pass a callback ...'); - return 0; - } - - const delay = prevFuncArgs.length > 1 ? prevFuncArgs[1] : 0; - let args; - - if (prevFuncArgs.length > 2) { - args = Array.prototype.slice.call(prevFuncArgs, 2); - } - - const info = new TimeoutInfo(cb, delay, isRepeat, this, args); - _timeoutInfos[info.id] = info; - return info.id; -} - -if (window.oh && window.scriptEngineType === 'napi') { - console.log(`Openharmony with napi has alreay implemented setTimeout/setInterval`); -} else { - // In openharmony, the setTimeout function will conflict with the timer of the worker thread and cause a crash, - // so you need to use the default timer - jsbWindow.setTimeout = function (cb) { - return createTimeoutInfo(arguments, false); - }; - - jsbWindow.clearTimeout = function (id) { - delete _timeoutInfos[id]; - }; - - jsbWindow.setInterval = function (cb) { - return createTimeoutInfo(arguments, true); - }; - - jsbWindow.clearInterval = jsbWindow.clearTimeout; -} - -jsbWindow.alert = console.error.bind(console); - -// File utils (Temporary, won't be accessible) -if (typeof jsb.FileUtils !== 'undefined') { - jsb.fileUtils = jsb.FileUtils.getInstance(); - delete jsb.FileUtils; -} - -jsbWindow.XMLHttpRequest.prototype.addEventListener = function (eventName, listener, options) { - this[`on${eventName}`] = listener; -}; - -jsbWindow.XMLHttpRequest.prototype.removeEventListener = function (eventName, listener, options) { - this[`on${eventName}`] = null; -}; - -// SocketIO -if (jsbWindow.SocketIO) { - jsbWindow.io = jsbWindow.SocketIO; - jsbWindow.SocketIO.prototype._Emit = jsbWindow.SocketIO.prototype.emit; - jsbWindow.SocketIO.prototype.emit = function (uri, delegate) { - if (typeof delegate === 'object') { - delegate = JSON.stringify(delegate); - } - this._Emit(uri, delegate); - }; -} - -jsbWindow.gameTick = tick; - -// generate get set function -jsb.generateGetSet = function (moduleObj) { - for (const classKey in moduleObj) { - const classProto = moduleObj[classKey] && moduleObj[classKey].prototype; - if (!classProto) continue; - for (const getName in classProto) { - const getPos = getName.search(/^get/); - if (getPos == -1) continue; - let propName = getName.replace(/^get/, ''); - const nameArr = propName.split(''); - const lowerFirst = nameArr[0].toLowerCase(); - const upperFirst = nameArr[0].toUpperCase(); - nameArr.splice(0, 1); - const left = nameArr.join(''); - propName = lowerFirst + left; - const setName = `set${upperFirst}${left}`; - if (classProto.hasOwnProperty(propName)) continue; - const setFunc = classProto[setName]; - const hasSetFunc = typeof setFunc === 'function'; - if (hasSetFunc) { - Object.defineProperty(classProto, propName, { - get () { - return this[getName](); - }, - set (val) { - this[setName](val); - }, - configurable: true, - }); - } else { - Object.defineProperty(classProto, propName, { - get () { - return this[getName](); - }, - configurable: true, - }); - } - } - } -}; - -for (const key in jsbWindow) { - if (globalThis[key] === undefined) { - globalThis[key] = jsbWindow[key]; - } -} - -if (typeof globalThis.window === 'undefined') { - globalThis.window = globalThis; -} - -// promise polyfill relies on setTimeout implementation -require('./promise.min'); diff --git a/platforms/native/builtin/jsb-adapter/Audio.js b/platforms/native/builtin/jsb-adapter/Audio.js deleted file mode 100755 index f17470d706..0000000000 --- a/platforms/native/builtin/jsb-adapter/Audio.js +++ /dev/null @@ -1,8 +0,0 @@ -const HTMLAudioElement = require('./HTMLAudioElement'); - -function Audio(url) { - return new HTMLAudioElement(url); -} - -module.exports = Audio; - diff --git a/platforms/native/builtin/jsb-adapter/CanvasRenderingContext2D.js b/platforms/native/builtin/jsb-adapter/CanvasRenderingContext2D.js deleted file mode 100644 index d087e17ff2..0000000000 --- a/platforms/native/builtin/jsb-adapter/CanvasRenderingContext2D.js +++ /dev/null @@ -1,155 +0,0 @@ -const ImageData = require('./ImageData'); - -class Context2DAttribute { - constructor () { - this.lineWidth = undefined; - this.lineJoin = undefined; - this.fillStyle = undefined; - this.font = undefined; - this.lineCap = undefined; - this.textAlign = undefined; - this.textBaseline = undefined; - this.strokeStyle = undefined; - this.globalCompositeOperation = undefined; - this.shadowBlur = undefined; - this.shadowColor = undefined; - this.shadowOffsetX = undefined; - this.shadowOffsetY = undefined; - } -} - -jsb.CanvasRenderingContext2D.prototype._ctor = function () { - this.__nativeRefs = {}; -}; - -class CanvasRenderingContext2D { - constructor (width, height) { - this._nativeObj = new jsb.CanvasRenderingContext2D(width, height); - this._attris = new Context2DAttribute(); - } - - // Do not cache width and height, as they will change buffer and sync to JS. - get width () { return this._nativeObj.width; } - set width (val) { this._nativeObj.width = val; } - get height () { return this._nativeObj.height; } - set height (val) { this._nativeObj.height = val; } - get lineWidth () { return this._attris.lineWidth; } - set lineWidth (val) { this._attris.lineWidth = val; } - get lineJoin () { return this._attris.lineJoin; } - set lineJoin (val) { this._attris.lineJoin = val; } - get fillStyle () { return this._attris.fillStyle; } - set fillStyle (val) { this._attris.fillStyle = val; } - get font () { return this._attris.font; } - set font (val) { this._attris.font = val; } - get lineCap () { return this._attris.lineCap; } - set lineCap (val) { this._attris.lineCap = val; } - get textAlign () { return this._attris.textAlign; } - set textAlign (val) { this._attris.textAlign = val; } - get textBaseline () { return this._attris.textBaseline; } - set textBaseline (val) { this._attris.textBaseline = val; } - get strokeStyle () { return this._attris.strokeStyle; } - set strokeStyle (val) { this._attris.strokeStyle = val; } - get globalCompositeOperation () { return this._attris.globalCompositeOperation; } - set globalCompositeOperation (val) { this._attris.globalCompositeOperation = val; } - get shadowBlur () { return this._attris.shadowBlur; } - set shadowBlur (val) { this._attris.shadowBlur = val; } - get shadowColor () { return this._attris.shadowColor; } - set shadowColor (val) { this._attris.shadowColor = val; } - get shadowOffsetX () { return this._attris.shadowOffsetX; } - set shadowOffsetX (val) { this._attris.shadowOffsetX = val; } - get shadowOffsetY () { return this._attris.shadowOffsetY; } - set shadowOffsetY (val) { this._attris.shadowOffsetY = val; } - - restore () { this._nativeObj.restore(); } - moveTo (x, y) { this._nativeObj.moveTo(x, y); } - lineTo (x, y) { this._nativeObj.lineTo(x, y); } - setTransform (a, b, c, d, e, f) { this._nativeObj.setTransform(a, b, c, d, e, f); } - stroke () { - this._canvas._dataInner = null; - this._nativeObj.stroke(); - } - measureText (text) { return this._nativeObj.measureText(text, this._attris); } - fill () { - this._canvas._dataInner = null; - this._nativeObj.fill(); - } - _fillImageData (data, width, height, offsetX, offsetY) { - this._canvas._dataInner = null; - this._nativeObj._fillImageData(data, width, height, offsetX, offsetY); - } - scale (x, y) { this._nativeObj.scale(x, y); } - clearRect (x, y, width, height) { - this._canvas._dataInner = null; - this._nativeObj.clearRect(x, y, width, height); - } - transform (a, b, c, d, e, f) { this._nativeObj.transform(a, b, c, d, e, f); } - fillText (text, x, y, maxWidth) { - this._canvas._dataInner = null; - this._nativeObj.fillText(text, x, y, maxWidth, this._attris); - } - strokeText (text, x, y, maxWidth) { - this._canvas._dataInner = null; - this._nativeObj.strokeText(text, x, y, maxWidth, this._attris); - } - save () { this._nativeObj.save(); } - fillRect (x, y, width, height) { - this._canvas._dataInner = null; - this._nativeObj.fillRect(x, y, width, height, this._attris); - } - fetchData () { - if ((typeof this._nativeObj.fetchData) !== 'undefined') { - this._nativeObj.fetchData(); - } - } - rotate (angle) { this._nativeObj.rotate(angle); } - beginPath () { this._nativeObj.beginPath(); } - rect (x, y, width, height) { this._nativeObj.rect(x, y, width, height); } - translate (x, y) { this._nativeObj.translate(x, y); } - createLinearGradient (x0, y0, x1, y1) { return this._nativeObj.createLinearGradient(x0, y0, x1, y1); } - closePath () { this._nativeObj.closePath(); } - - // void ctx.putImageData(imagedata, dx, dy); - // void ctx.putImageData(imagedata, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight); - putImageData (imageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight) { - this._canvas._data = imageData; - } - - // ImageData ctx.createImageData(imagedata); - // ImageData ctx.createImageData(width, height); - createImageData (args1, args2) { - if (typeof args1 === 'number' && typeof args2 === 'number') { - return new ImageData(args1, args2); - } else if (args1 instanceof ImageData) { - return new ImageData(args1.data, args1.width, args1.height); - } - } - - // Comment it seems it is not used. - // // ImageData ctx.getImageData(sx, sy, sw, sh); - // getImageData (sx, sy, sw, sh) { - // var canvasWidth = this._canvas._width; - // var canvasHeight = this._canvas._height; - // var canvasBuffer = this._canvas._data.data; - // // image rect may bigger that canvas rect - // var maxValidSH = (sh + sy) < canvasHeight ? sh : (canvasHeight - sy); - // var maxValidSW = (sw + sx) < canvasWidth ? sw : (canvasWidth - sx); - // var imgBuffer = new Uint8ClampedArray(sw * sh * 4); - // for (var y = 0; y < maxValidSH; y++) { - // for (var x = 0; x < maxValidSW; x++) { - // var canvasPos = (y + sy) * canvasWidth + (x + sx); - // var imgPos = y * sw + x; - // imgBuffer[imgPos * 4 + 0] = canvasBuffer[canvasPos * 4 + 0]; - // imgBuffer[imgPos * 4 + 1] = canvasBuffer[canvasPos * 4 + 1]; - // imgBuffer[imgPos * 4 + 2] = canvasBuffer[canvasPos * 4 + 2]; - // imgBuffer[imgPos * 4 + 3] = canvasBuffer[canvasPos * 4 + 3]; - // } - // } - // return new ImageData(imgBuffer, sw, sh); - // } - - _setCanvasBufferUpdatedCallback (func) { - this._nativeObj._setCanvasBufferUpdatedCallback(func); - } -} - -module.exports = CanvasRenderingContext2D; diff --git a/platforms/native/builtin/jsb-adapter/DOMRect.js b/platforms/native/builtin/jsb-adapter/DOMRect.js deleted file mode 100644 index 3741454f9d..0000000000 --- a/platforms/native/builtin/jsb-adapter/DOMRect.js +++ /dev/null @@ -1,14 +0,0 @@ -class DOMRect { - constructor(x, y, width, height) { - this.x = x ? x : 0; - this.y = y ? y : 0; - this.width = width ? width : 0; - this.height = height ? height : 0; - this.left = this.x; - this.top = this.y; - this.right = this.x + this.width; - this.bottom = this.y + this.height; - } -} - -module.exports = DOMRect; diff --git a/platforms/native/builtin/jsb-adapter/DeviceMotionEvent.js b/platforms/native/builtin/jsb-adapter/DeviceMotionEvent.js deleted file mode 100644 index 4318dc5e01..0000000000 --- a/platforms/native/builtin/jsb-adapter/DeviceMotionEvent.js +++ /dev/null @@ -1,37 +0,0 @@ -const Event = require('./Event') - -class DeviceMotionEvent extends Event { - constructor(initArgs) { - super('devicemotion'); - if (initArgs) { - this._acceleration = initArgs.acceleration ? initArgs.acceleration : {x: 0, y: 0, z: 0}; - this._accelerationIncludingGravity = initArgs.accelerationIncludingGravity ? initArgs.accelerationIncludingGravity : {x: 0, y: 0, z: 0}; - this._rotationRate = initArgs.rotationRate ? initArgs.rotationRate : {alpha: 0, beta: 0, gamma: 0}; - this._interval = initArgs.interval; - } - else { - this._acceleration = {x: 0, y: 0, z: 0}; - this._accelerationIncludingGravity = {x: 0, y: 0, z: 0}; - this._rotationRate = {alpha: 0, beta: 0, gamma: 0}; - this._interval = 0; - } - } - - get acceleration() { - return this._acceleration; - } - - get accelerationIncludingGravity() { - return this._accelerationIncludingGravity; - } - - get rotationRate() { - return this._rotationRate; - } - - get interval() { - return this._interval; - } -} - -module.exports = DeviceMotionEvent; diff --git a/platforms/native/builtin/jsb-adapter/Element.js b/platforms/native/builtin/jsb-adapter/Element.js deleted file mode 100755 index 65d7df9f37..0000000000 --- a/platforms/native/builtin/jsb-adapter/Element.js +++ /dev/null @@ -1,34 +0,0 @@ -const Node = require('./Node'); -const DOMRect = require('./DOMRect'); -const jsbWindow = require('../../jsbWindow'); - -class Element extends Node { - constructor () { - super(); - this.className = ''; - this.children = []; - this.clientLeft = 0; - this.clientTop = 0; - this.scrollLeft = 0; - this.scrollTop = 0; - } - - get clientWidth () { - return 0; - } - - get clientHeight () { - return 0; - } - - getBoundingClientRect () { - return new DOMRect(0, 0, jsbWindow.innerWidth, jsbWindow.innerHeight); - } - - // attrName is a string that names the attribute to be removed from element. - removeAttribute (attrName) { - - } -} - -module.exports = Element; diff --git a/platforms/native/builtin/jsb-adapter/Event.js b/platforms/native/builtin/jsb-adapter/Event.js deleted file mode 100644 index 39d6e198fe..0000000000 --- a/platforms/native/builtin/jsb-adapter/Event.js +++ /dev/null @@ -1,174 +0,0 @@ -/** - * @see https://dom.spec.whatwg.org/#interface-event - * @private - */ -/** - * The event wrapper. - * @constructor - * @param {EventTarget} eventTarget The event target of this dispatching. - * @param {Event|{type:string}} event The original event to wrap. - */ -class Event { - - constructor(type, eventInit) { - this._type = type - this._target = null - this._eventPhase = 2 - this._currentTarget = null - this._canceled = false - this._stopped = false // The flag to stop propagation immediately. - this._passiveListener = null - this._timeStamp = Date.now() - } - - /** - * The type of this event. - * @type {string} - */ - get type() { - return this._type - } - - /** - * The target of this event. - * @type {EventTarget} - */ - get target() { - return this._target - } - - /** - * The target of this event. - * @type {EventTarget} - */ - get currentTarget() { - return this._currentTarget - } - - get isTrusted() { - // https://heycam.github.io/webidl/#Unforgeable - return false - } - - get timeStamp() { - return this._timeStamp - } - - /** - * @returns {EventTarget[]} The composed path of this event. - */ - composedPath() { - const currentTarget = this._currentTarget - if (currentTarget === null) { - return [] - } - return [currentTarget] - } - - /** - * The target of this event. - * @type {number} - */ - get eventPhase() { - return this._eventPhase - } - - /** - * Stop event bubbling. - * @returns {void} - */ - stopPropagation() { - - } - - /** - * Stop event bubbling. - * @returns {void} - */ - stopImmediatePropagation() { - this._stopped = true - } - - /** - * The flag to be bubbling. - * @type {boolean} - */ - get bubbles() { - return false - } - - /** - * The flag to be cancelable. - * @type {boolean} - */ - get cancelable() { - return true - } - - /** - * Cancel this event. - * @returns {void} - */ - preventDefault() { - if (this._passiveListener !== null) { - console.warn("Event#preventDefault() was called from a passive listener:", this._passiveListener) - return - } - if (!this.cancelable) { - return - } - - this._canceled = true - } - - /** - * The flag to indicate cancellation state. - * @type {boolean} - */ - get defaultPrevented() { - return this._canceled - } - - /** - * The flag to be composed. - * @type {boolean} - */ - get composed() { - return false - } - - /** - * The unix time of this event. - * @type {number} - */ - get timeStamp() { - return this._timeStamp - } -} - -/** - * Constant of NONE. - * @type {number} - */ -Event.NONE = 0 - -/** - * Constant of CAPTURING_PHASE. - * @type {number} - */ -Event.CAPTURING_PHASE = 1 - -/** - * Constant of AT_TARGET. - * @type {number} - */ -Event.AT_TARGET = 2 - -/** - * Constant of BUBBLING_PHASE. - * @type {number} - */ -Event.BUBBLING_PHASE = 3 - - -module.exports = Event diff --git a/platforms/native/builtin/jsb-adapter/EventTarget.js b/platforms/native/builtin/jsb-adapter/EventTarget.js deleted file mode 100644 index dacec6fc5d..0000000000 --- a/platforms/native/builtin/jsb-adapter/EventTarget.js +++ /dev/null @@ -1,289 +0,0 @@ -var __targetID = 0; - -var __listenerMap = { - touch: {}, - mouse: {}, - keyboard: {}, - devicemotion: {} -}; - -var __listenerCountMap = { - touch: 0, - mouse: 0, - keyboard: 0, - devicemotion: 0 -}; - -var __enableCallbackMap = { - touch: null, - mouse: null, - keyboard: null, - //FIXME: Cocos Creator invokes addEventListener('devicemotion') when engine initializes, it will active sensor hardware. - // In that case, CPU and temperature cost will increase. Therefore, we require developer to invoke 'jsb.device.setMotionEnabled(true)' - // on native platforms since most games will not listen motion event. - devicemotion: null - // devicemotion: function() { - // jsb.device.setMotionEnabled(true); - // } -}; - -var __disableCallbackMap = { - touch: null, - mouse: null, - //FIXME: Cocos Creator invokes addEventListener('devicemotion') when engine initializes, it will active sensor hardware. - // In that case, CPU and temperature cost will increase. Therefore, we require developer to invoke 'jsb.device.setMotionEnabled(true)' - // on native platforms since most games will not listen motion event. - keyboard: null, - devicemotion: null - // devicemotion: function() { - // jsb.device.setMotionEnabled(false); - // } -}; - -const __handleEventNames = { - touch: ['touchstart', 'touchmove', 'touchend', 'touchcancel'], - mouse: ['mousedown', 'mousemove', 'mouseup', 'mousewheel'], - keyboard: ['keydown', 'keyup', 'keypress'], - devicemotion: ['devicemotion'] -} - -// Listener types -const CAPTURE = 1 -const BUBBLE = 2 -const ATTRIBUTE = 3 - -/** - * Check whether a given value is an object or not. - * @param {any} x The value to check. - * @returns {boolean} `true` if the value is an object. - */ -function isObject(x) { - return x && typeof x === "object" //eslint-disable-line no-restricted-syntax -} - -/** - * EventTarget. - * - * - This is constructor if no arguments. - * - This is a function which returns a CustomEventTarget constructor if there are arguments. - * - * For example: - * - * class A extends EventTarget {} - */ -class EventTarget { - constructor() { - this._targetID = ++__targetID; - this._listenerCount = { - touch: 0, - mouse: 0, - keyboard: 0, - devicemotion: 0 - }; - this._listeners = new Map(); - } - - _associateSystemEventListener(eventName) { - var handleEventNames; - for (var key in __handleEventNames) { - handleEventNames = __handleEventNames[key]; - if (handleEventNames.indexOf(eventName) > -1) { - if (__enableCallbackMap[key] && __listenerCountMap[key] === 0) { - __enableCallbackMap[key](); - } - - if (this._listenerCount[key] === 0) - __listenerMap[key][this._targetID] = this; - ++this._listenerCount[key]; - ++__listenerCountMap[key]; - break; - } - } - } - - _dissociateSystemEventListener(eventName) { - var handleEventNames; - for (var key in __handleEventNames) { - handleEventNames = __handleEventNames[key]; - if (handleEventNames.indexOf(eventName) > -1) { - if (this._listenerCount[key] <= 0) - delete __listenerMap[key][this._targetID]; - --__listenerCountMap[key]; - - if (__disableCallbackMap[key] && __listenerCountMap[key] === 0) { - __disableCallbackMap[key](); - } - break; - } - } - } - - /** - * Add a given listener to this event target. - * @param {string} eventName The event name to add. - * @param {Function} listener The listener to add. - * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. - * @returns {boolean} `true` if the listener was added actually. - */ - addEventListener(eventName, listener, options) { - if (!listener) { - return false - } - if (typeof listener !== "function" && !isObject(listener)) { - throw new TypeError("'listener' should be a function or an object.") - } - - const listeners = this._listeners - const optionsIsObj = isObject(options) - const capture = optionsIsObj ? Boolean(options.capture) : Boolean(options) - const listenerType = (capture ? CAPTURE : BUBBLE) - const newNode = { - listener, - listenerType, - passive: optionsIsObj && Boolean(options.passive), - once: optionsIsObj && Boolean(options.once), - next: null, - } - - // Set it as the first node if the first node is null. - let node = listeners.get(eventName) - if (node === undefined) { - listeners.set(eventName, newNode) - this._associateSystemEventListener(eventName); - return true - } - - // Traverse to the tail while checking duplication.. - let prev = null - while (node) { - if (node.listener === listener && node.listenerType === listenerType) { - // Should ignore duplication. - return false - } - prev = node - node = node.next - } - - // Add it. - prev.next = newNode - this._associateSystemEventListener(eventName); - return true - } - - /** - * Remove a given listener from this event target. - * @param {string} eventName The event name to remove. - * @param {Function} listener The listener to remove. - * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. - * @returns {boolean} `true` if the listener was removed actually. - */ - removeEventListener(eventName, listener, options) { - if (!listener) { - return false - } - - const listeners = this._listeners - const capture = isObject(options) ? Boolean(options.capture) : Boolean(options) - const listenerType = (capture ? CAPTURE : BUBBLE) - - let prev = null - let node = listeners.get(eventName) - while (node) { - if (node.listener === listener && node.listenerType === listenerType) { - if (prev) { - prev.next = node.next - } - else if (node.next) { - listeners.set(eventName, node.next) - } - else { - listeners.delete(eventName) - } - - this._dissociateSystemEventListener(eventName); - - return true - } - - prev = node - node = node.next - } - - return false - } - - /** - * Dispatch a given event. - * @param {Event|{type:string}} event The event to dispatch. - * @returns {boolean} `false` if canceled. - */ - dispatchEvent(event) { - if (!event || typeof event.type !== "string") { - throw new TypeError("\"event.type\" should be a string.") - } - - const eventName = event.type - var onFunc = this['on' + eventName]; - if (onFunc && typeof onFunc === 'function') { - event._target = event._currentTarget = this; - onFunc.call(this, event); - event._target = event._currentTarget = null - event._eventPhase = 0 - event._passiveListener = null - - if (event.defaultPrevented) - return false; - } - - // If listeners aren't registered, terminate. - const listeners = this._listeners - - let node = listeners.get(eventName) - if (!node) { - return true - } - - event._target = event._currentTarget = this; - - // This doesn't process capturing phase and bubbling phase. - // This isn't participating in a tree. - let prev = null - while (node) { - // Remove this listener if it's once - if (node.once) { - if (prev) { - prev.next = node.next - } - else if (node.next) { - listeners.set(eventName, node.next) - } - else { - listeners.delete(eventName) - } - } - else { - prev = node - } - - // Call this listener - event._passiveListener = node.passive ? node.listener : null - if (typeof node.listener === "function") { - node.listener.call(this, event) - } - - // Break if `event.stopImmediatePropagation` was called. - if (event._stopped) { - break - } - - node = node.next - } - event._target = event._currentTarget = null - event._eventPhase = 0 - event._passiveListener = null - - return !event.defaultPrevented - } -} - -module.exports = EventTarget diff --git a/platforms/native/builtin/jsb-adapter/FileReader.js b/platforms/native/builtin/jsb-adapter/FileReader.js deleted file mode 100755 index c53aebadf7..0000000000 --- a/platforms/native/builtin/jsb-adapter/FileReader.js +++ /dev/null @@ -1,31 +0,0 @@ -const EventTarget = require('./EventTarget'); -const Event = require('./Event'); -const jsbWindow = require('../../jsbWindow'); - -class FileReader extends EventTarget { - construct () { - this.result = null; - } - - // Aborts the read operation. Upon return, the readyState will be DONE. - abort () {} - - // Starts reading the contents of the specified Blob, once finished, the result attribute contains an ArrayBuffer representing the file's data. - readAsArrayBuffer () { - - } - - // Starts reading the contents of the specified Blob, once finished, the result attribute contains a data: URL representing the file's data. - readAsDataURL (blob) { - this.result = `data:image/png;base64,${jsbWindow.btoa(blob)}`; - const event = new Event('load'); - this.dispatchEvent(event); - } - - // Starts reading the contents of the specified Blob, once finished, the result attribute contains the contents of the file as a text string. - readAsText () { - - } -} - -module.exports = FileReader; diff --git a/platforms/native/builtin/jsb-adapter/FontFace.js b/platforms/native/builtin/jsb-adapter/FontFace.js deleted file mode 100644 index d86e483679..0000000000 --- a/platforms/native/builtin/jsb-adapter/FontFace.js +++ /dev/null @@ -1,28 +0,0 @@ -class FontFace { - constructor(family, source, descriptors) { - this.family = family - this.source = source - this.descriptors = descriptors - - this._status = 'unloaded' - - this._loaded = new Promise((resolve, reject) => { - this._resolveCB = resolve - this._rejectCB = reject - }) - } - - load() { - // class FontFaceSet, add(fontFace) have done the load work - } - - get status() { - return this._status; - } - - get loaded() { - return this._loaded; - } -} - -module.exports = FontFace; diff --git a/platforms/native/builtin/jsb-adapter/FontFaceSet.js b/platforms/native/builtin/jsb-adapter/FontFaceSet.js deleted file mode 100644 index a40e103407..0000000000 --- a/platforms/native/builtin/jsb-adapter/FontFaceSet.js +++ /dev/null @@ -1,62 +0,0 @@ -const EventTarget = require('./EventTarget') -const Event = require('./Event') - -class FontFaceSet extends EventTarget { - constructor() { - super() - this._status = 'loading' - } - - get status() { - return this._status - } - - set onloading(listener) { - this.addEventListener('loading', listener) - } - - set onloadingdone(listener) { - this.addEventListener('loadingdone', listener) - } - - set onloadingerror(listener) { - this.addEventListener('loadingerror', listener) - } - - add(fontFace) { - this._status = fontFace._status = 'loading' - this.dispatchEvent(new Event('loading')) - // Call native binding method to set the ttf font to native platform. - let family = jsb.loadFont(fontFace.family, fontFace.source) - setTimeout(() => { - if (family) { - fontFace._status = this._status = 'loaded' - fontFace._resolveCB() - this.dispatchEvent(new Event('loadingdone')) - } - else { - fontFace._status = this._status = 'error' - fontFace._rejectCB() - this.dispatchEvent(new Event('loadingerror')) - } - }, 0) - } - - clear() { - - } - - delete() { - - } - - load() { - - } - - ready() { - - } -} - -module.exports = FontFaceSet diff --git a/platforms/native/builtin/jsb-adapter/HTMLAudioElement.js b/platforms/native/builtin/jsb-adapter/HTMLAudioElement.js deleted file mode 100755 index 1ac791b24e..0000000000 --- a/platforms/native/builtin/jsb-adapter/HTMLAudioElement.js +++ /dev/null @@ -1,87 +0,0 @@ -const HTMLMediaElement = require('./HTMLMediaElement'); - -const HAVE_NOTHING = 0 -const HAVE_METADATA = 1 -const HAVE_CURRENT_DATA = 2 -const HAVE_FUTURE_DATA = 3 -const HAVE_ENOUGH_DATA = 4 - -const _innerAudioContext = new WeakMap() -const _src = new WeakMap() -const _loop = new WeakMap() -const _autoplay = new WeakMap() - -class HTMLAudioElement extends HTMLMediaElement { - constructor(url) { - super('audio') - - _src.set(this, '') - - //TODO: - } - - load() { - console.warn('HTMLAudioElement.load() is not implemented.') - } - - play() { - - } - - pause() { - - } - - canPlayType(mediaType = '') { - if (typeof mediaType !== 'string') { - return '' - } - - if (mediaType.indexOf('audio/mpeg') > -1 || mediaType.indexOf('audio/mp4')) { - return 'probably' - } - return '' - } - - get currentTime() { - - } - - set currentTime(value) { - - } - - get src() { - - } - - set src(value) { - - } - - get loop() { - - } - - set loop(value) { - - } - - get autoplay() { - - } - - set autoplay(value) { - - } - - get paused() { - - } - - cloneNode() { - - } -} - -module.exports = HTMLAudioElement; diff --git a/platforms/native/builtin/jsb-adapter/HTMLCanvasElement.js b/platforms/native/builtin/jsb-adapter/HTMLCanvasElement.js deleted file mode 100644 index 4a28f6cff2..0000000000 --- a/platforms/native/builtin/jsb-adapter/HTMLCanvasElement.js +++ /dev/null @@ -1,140 +0,0 @@ -const HTMLElement = require('./HTMLElement'); -const ImageData = require('./ImageData'); -const DOMRect = require('./DOMRect'); -const CanvasRenderingContext2D = require('./CanvasRenderingContext2D'); -const jsbWindow = require('../../jsbWindow'); - -const clamp = function (value) { - value = Math.round(value); - return value < 0 ? 0 : value < 255 ? value : 255; -}; - -class CanvasGradient { - constructor () { - console.log('==> CanvasGradient constructor'); - } - - addColorStop (offset, color) { - console.log('==> CanvasGradient addColorStop'); - } -} - -class TextMetrics { - constructor (width) { - this._width = width; - } - - get width () { - return this._width; - } -} - -class HTMLCanvasElement extends HTMLElement { - constructor (width, height) { - super('canvas'); - - this.id = 'glcanvas'; - this.type = 'canvas'; - - this.top = 0; - this.left = 0; - this._width = width ? Math.ceil(width) : 0; - this._height = height ? Math.ceil(height) : 0; - this._context2D = null; - this._dataInner = null; - } - - //REFINE: implement opts. - getContext (name, opts) { - const self = this; - if (name === '2d') { - if (!this._context2D) { - this._context2D = new CanvasRenderingContext2D(this._width, this._height); - this._context2D._canvas = this; - this._context2D._setCanvasBufferUpdatedCallback((data) => { - // FIXME: Canvas's data will take 2x memory size, one in C++, another is obtained by Uint8Array here. - self._dataInner = new ImageData(data, self._width, self._height); - }); - } - return this._context2D; - } - - return null; - } - - get _data () { - if (this._context2D === null) { - return null; - } - if (!this._dataInner) { - this._context2D.fetchData(); - } - return this._dataInner; - } - - set _data (data) { - this._dataInner = data; - } - - set width (width) { - width = Math.ceil(width); - if (this._width !== width) { - this._dataInner = null; - this._width = width; - if (this._context2D) { - this._context2D.width = width; - } - } - } - - get width () { - return this._width; - } - - set height (height) { - height = Math.ceil(height); - if (this._height !== height) { - this._dataInner = null; - this._height = height; - if (this._context2D) { - this._context2D.height = height; - } - } - } - - get height () { - return this._height; - } - - get clientWidth () { - return jsbWindow.innerWidth; - } - - get clientHeight () { - return jsbWindow.innerHeight; - } - - get data () { - if (this._data) { - return this._data.data; - } - return null; - } - - getBoundingClientRect () { - return new DOMRect(0, 0, jsbWindow.innerWidth, jsbWindow.innerHeight); - } - - requestPointerLock () { - jsb.setCursorEnabled(false); - } - - _destroy () { - if (this._context2D) { - this._context2D._setCanvasBufferUpdatedCallback(null); - this._context2D = null; - } - } -} - -module.exports = HTMLCanvasElement; diff --git a/platforms/native/builtin/jsb-adapter/HTMLElement.js b/platforms/native/builtin/jsb-adapter/HTMLElement.js deleted file mode 100755 index f39bbd63ab..0000000000 --- a/platforms/native/builtin/jsb-adapter/HTMLElement.js +++ /dev/null @@ -1,34 +0,0 @@ -const Element = require('./Element'); -const { noop } = require('./util'); -const jsbWindow = require('../../jsbWindow'); - -class HTMLElement extends Element { - constructor (tagName = '') { - super(); - this.tagName = tagName.toUpperCase(); - - this.className = ''; - this.children = []; - this.style = { - width: `${jsbWindow.innerWidth}px`, - height: `${jsbWindow.innerHeight}px`, - }; - - this.innerHTML = ''; - this.parentElement = jsbWindow.__canvas; - } - - setAttribute (name, value) { - this[name] = value; - } - - getAttribute (name) { - return this[name]; - } - - focus () { - - } -} - -module.exports = HTMLElement; diff --git a/platforms/native/builtin/jsb-adapter/HTMLImageElement.js b/platforms/native/builtin/jsb-adapter/HTMLImageElement.js deleted file mode 100755 index 4648fcbc40..0000000000 --- a/platforms/native/builtin/jsb-adapter/HTMLImageElement.js +++ /dev/null @@ -1,66 +0,0 @@ -const HTMLElement = require('./HTMLElement'); -const Event = require('./Event'); - -class HTMLImageElement extends HTMLElement { - constructor(width, height, isCalledFromImage) { - if (!isCalledFromImage) { - throw new TypeError("Illegal constructor, use 'new Image(w, h); instead!'"); - } - super('img') - this.width = width ? width : 0; - this.height = height ? height : 0; - this._data = null; - this._src = null; - this.complete = false; - this.crossOrigin = null; - this._mipmapLevelDataSize = []; - } - - destroy() { - if (this._data) { - jsb.destroyImage(this._data); - this._data = null; - } - this._src = null; - } - - set src(src) { - this._src = src; - if (src === '') return; - jsb.loadImage(src, (info) => { - if (!info) { - this._data = null; - var event = new Event('error'); - this.dispatchEvent(event); - return; - } - this.width = this.naturalWidth = info.width; - this.height = this.naturalHeight = info.height; - this._data = info.data; - this.format = info.format; - this.complete = true; - this._mipmapLevelDataSize = info.mipmapLevelDataSize; - - var event = new Event('load'); - this.dispatchEvent(event); - }); - } - - get src() { - return this._src; - } - - get clientWidth() { - return this.width; - } - - get clientHeight() { - return this.height; - } - - getBoundingClientRect() { - return new DOMRect(0, 0, this.width, this.height); - } -} - -module.exports = HTMLImageElement; diff --git a/platforms/native/builtin/jsb-adapter/HTMLMediaElement.js b/platforms/native/builtin/jsb-adapter/HTMLMediaElement.js deleted file mode 100755 index 0739f0a41b..0000000000 --- a/platforms/native/builtin/jsb-adapter/HTMLMediaElement.js +++ /dev/null @@ -1,70 +0,0 @@ -const HTMLElement = require('./HTMLElement'); -const MediaError = require('./MediaError'); - -const HAVE_NOTHING = 0; -const HAVE_METADATA = 1; -const HAVE_CURRENT_DATA = 2; -const HAVE_FUTURE_DATA = 3; -const HAVE_ENOUGH_DATA = 4; - -class HTMLMediaElement extends HTMLElement { - constructor(type) { - super(type) - this._volume = 1.0; - this._duration = 0; - this._isEnded = false; - this._isMute = false; - this._readyState = HAVE_NOTHING; - this._error = new MediaError(); - } - - addTextTrack() {} - - captureStream() {} - - fastSeek() {} - - load() {} - - pause() {} - - play() {} - - canPlayType(mediaType) { - return ''; - } - - set volume(volume) { - this._volume = volume; - } - - get volume() { - return this._volume; - } - - get duration() { - return this._duration; - } - - get ended() { - return this._isEnded; - } - - get muted() { - return this._isMute; - } - - get readyState() { - return this._readyState; - } - - get error() { - return this._error; - } - - get currentTime() { - return 0; - } -} - -module.exports = HTMLMediaElement; diff --git a/platforms/native/builtin/jsb-adapter/HTMLScriptElement.js b/platforms/native/builtin/jsb-adapter/HTMLScriptElement.js deleted file mode 100644 index 8c4a9c881e..0000000000 --- a/platforms/native/builtin/jsb-adapter/HTMLScriptElement.js +++ /dev/null @@ -1,31 +0,0 @@ -const HTMLElement = require('./HTMLElement'); -const Event = require('./Event'); - -const _importmaps = []; - -class HTMLScriptElement extends HTMLElement { - constructor(width, height) { - super('script'); - } - - set type (type) { - if (type === "systemjs-importmap") { - if (_importmaps.indexOf(this) === -1) { - _importmaps.push(this); - } - } - } - - set src(url) { - setTimeout(()=>{ - require(url); - this.dispatchEvent(new Event('load')); - }, 0); - } -} - -HTMLScriptElement._getAllScriptElementsSystemJSImportType = function () { - return _importmaps; -} - -module.exports = HTMLScriptElement; diff --git a/platforms/native/builtin/jsb-adapter/HTMLVideoElement.js b/platforms/native/builtin/jsb-adapter/HTMLVideoElement.js deleted file mode 100644 index a65599ea31..0000000000 --- a/platforms/native/builtin/jsb-adapter/HTMLVideoElement.js +++ /dev/null @@ -1,15 +0,0 @@ -const HTMLMediaElement = require('./HTMLMediaElement'); - -class HTMLVideoElement extends HTMLMediaElement { - constructor() { - super('video') - } - - canPlayType(type) { - if (type === 'video/mp4') - return true; - return false; - } -} - -module.exports = HTMLVideoElement; diff --git a/platforms/native/builtin/jsb-adapter/Image.js b/platforms/native/builtin/jsb-adapter/Image.js deleted file mode 100755 index 1bebd4e8e2..0000000000 --- a/platforms/native/builtin/jsb-adapter/Image.js +++ /dev/null @@ -1,9 +0,0 @@ -let HTMLImageElement = require('./HTMLImageElement'); - -class Image extends HTMLImageElement { - constructor(width, height) { - super(width, height, true) - } -} - -module.exports = Image; diff --git a/platforms/native/builtin/jsb-adapter/ImageData.js b/platforms/native/builtin/jsb-adapter/ImageData.js deleted file mode 100644 index 3697510ae3..0000000000 --- a/platforms/native/builtin/jsb-adapter/ImageData.js +++ /dev/null @@ -1,36 +0,0 @@ -class ImageData { - - // var imageData = new ImageData(array, width, height); - // var imageData = new ImageData(width, height); - constructor(array, width, height) { - if (typeof array === 'number' && typeof width == 'number') { - height = width; - width = array; - array = null; - } - if (array === null) { - this._data = new Uint8ClampedArray(width * height * 4); - } - else { - this._data = array; - } - this._width = width; - this._height = height; - } - - - get data() { - return this._data; - } - - get width() { - return this._width; - } - - get height() { - return this._height; - } - -} - -module.exports = ImageData; diff --git a/platforms/native/builtin/jsb-adapter/KeyboardEvent.js b/platforms/native/builtin/jsb-adapter/KeyboardEvent.js deleted file mode 100644 index c1449408bc..0000000000 --- a/platforms/native/builtin/jsb-adapter/KeyboardEvent.js +++ /dev/null @@ -1,289 +0,0 @@ -const Event = require('./Event') - -const __numberShiftMap = { - '48': ')', // 0 - '49': '!', // 1 - '50': '@', // 2 - '51': '#', // 3 - '52': '$', // 4 - '53': '%', // 5 - '54': '^', // 6 - '55': '&', // 7 - '56': '*', // 8 - '57': '(', // 9 -}; - -var __capsLockActive = false; - -class KeyboardEvent extends Event { - constructor(type, KeyboardEventInit) { - super(type) - if (typeof KeyboardEventInit === 'object') { - this._altKeyActive = KeyboardEventInit.altKey ? KeyboardEventInit.altKey : false; - this._ctrlKeyActive = KeyboardEventInit.ctrlKey ? KeyboardEventInit.ctrlKey : false; - this._metaKeyActive = KeyboardEventInit.metaKey ? KeyboardEventInit.metaKey : false; - this._shiftKeyActive = KeyboardEventInit.shiftKey ? KeyboardEventInit.shiftKey : false; - this._keyCode = KeyboardEventInit.keyCode ? KeyboardEventInit.keyCode : -1; - this._repeat = KeyboardEventInit.repeat ? KeyboardEventInit.repeat : false; - } - else { - this._altKeyActive = false; - this._ctrlKeyActive = false; - this._metaKeyActive = false; - this._shiftKeyActive = false; - this._keyCode = -1; - this._repeat = false; - } - - var keyCode = this._keyCode; - if (keyCode >= 48 && keyCode <= 57) { // 0 ~ 9 - var number = (keyCode - 48); - this._code = 'Digit' + number; - this._key = this._shiftKeyActive ? __numberShiftMap[keyCode] : ('' + number); - } - else if (keyCode >= 10048 && keyCode <= 10057) { // Numberpad 0 ~ 9 - // reset to web keyCode since it's a hack in C++ for distinguish numbers in Numberpad. - keyCode = this._keyCode = keyCode - 10000; - var number = (keyCode - 48); - this._code = 'Numpad' + number; - this._key = '' + number; - } - else if (keyCode >= 65 && keyCode <= 90) { // A ~ Z - var charCode = String.fromCharCode(keyCode); - this._code = 'Key' + charCode; - this._key = (this._shiftKeyActive ^ __capsLockActive) ? charCode : charCode.toLowerCase(); - } - else if (keyCode >= 97 && keyCode <= 122) { // a ~ z - var charCode = String.fromCharCode(keyCode); - this._keyCode = keyCode - (97 - 65); // always return uppercase keycode for backward-compatibility - this._code = 'Key' + charCode; - this._key = (this._shiftKeyActive ^ __capsLockActive) ? charCode.toUpperCase() : charCode; - } - else if (keyCode >= 112 && keyCode <= 123) { // F1 ~ F12 - this._code = this._key = 'F' + (keyCode - 111); - } - else if (keyCode === 27) { - this._code = this._key = 'Escape'; - } - else if (keyCode === 189) { - this._code = 'Minus'; - this._key = this._shiftKeyActive ? '_' : '-'; - } - else if (keyCode === 187) { - this._code = 'Equal'; - this._key = this._shiftKeyActive ? '+' : '='; - } - else if (keyCode === 220) { - this._code = 'Backslash'; - this._key = this._shiftKeyActive ? '|' : '\\'; - } - else if (keyCode === 192) { - this._code = 'Backquote'; - this._key = this._shiftKeyActive ? '~' : '`'; - } - else if (keyCode === 8) { - this._code = this._key = 'Backspace'; - } - else if (keyCode === 13) { - this._code = this._key = 'Enter'; - } - else if (keyCode === 219) { - this._code = 'BracketLeft'; - this._key = this._shiftKeyActive ? '{' : '['; - } - else if (keyCode === 221) { - this._code = 'BracketRight'; - this._key = this._shiftKeyActive ? '}' : ']'; - } - else if (keyCode === 186) { - this._code = 'Semicolon'; - this._key = this._shiftKeyActive ? ':' : ';'; - } - else if (keyCode === 222) { - this._code = 'Quote'; - this._key = this._shiftKeyActive ? '"' : "'"; - } - else if (keyCode === 9) { - this._code = this._key = 'Tab'; - } - else if (keyCode === 17) { - this._code = 'ControlLeft'; - this._key = 'Control'; - } - else if (keyCode === 20017) { - this._keyCode = 17; // Reset to the real value. - this._code = 'ControlRight'; - this._key = 'Control'; - } - else if (keyCode === 16) { - this._code = 'ShiftLeft'; - this._key = 'Shift'; - } - else if (keyCode === 20016) { - this._keyCode = 16; // Reset to the real value. - this._code = 'ShiftRight'; - this._key = 'Shift'; - } - else if (keyCode === 18) { - this._code = 'AltLeft'; - this._key = 'Alt'; - } - else if (keyCode === 20018) { - this._keyCode = 18; // Reset to the real value. - this._code = 'AltRight'; - this._key = 'Alt'; - } - else if (keyCode === 91) { - this._code = 'MetaLeft'; - this._key = 'Meta'; - } - else if (keyCode === 93) { - this._code = 'MetaRight'; - this._key = 'Meta'; - } - else if (keyCode === 37) { - this._code = this._key = 'ArrowLeft'; - } - else if (keyCode === 38) { - this._code = this._key = 'ArrowUp'; - } - else if (keyCode === 39) { - this._code = this._key = 'ArrowRight'; - } - else if (keyCode === 40) { - this._code = this._key = 'ArrowDown'; - } - else if (keyCode === 20093) { - this._keyCode = 93; // Bug of brower since its keycode is the same as MetaRight. - this._code = this._key = 'ContextMenu'; - } - else if (keyCode === 20013) { - this._keyCode = 13; - this._code = 'NumpadEnter'; - this._key = 'Enter'; - } - else if (keyCode === 107) { - this._code = 'NumpadAdd'; - this._key = '+'; - } - else if (keyCode === 109) { - this._code = 'NumpadSubtract'; - this._key = '-'; - } - else if (keyCode === 106) { - this._code = 'NumpadMultiply'; - this._key = '*'; - } - else if (keyCode === 111) { - this._code = 'NumpadDivide'; - this._key = '/'; - } - else if (keyCode === 12) { - this._code = 'NumLock'; - this._key = 'Clear'; - } - else if (keyCode === 124) { - this._code = this._key = 'F13'; - } - else if (keyCode === 36) { - this._code = this._key = 'Home'; - } - else if (keyCode === 33) { - this._code = this._key = 'PageUp'; - } - else if (keyCode === 34) { - this._code = this._key = 'PageDown'; - } - else if (keyCode === 35) { - this._code = this._key = 'End'; - } - else if (keyCode === 188) { - this._code = 'Comma'; - this._key = this._shiftKeyActive ? '<' : ','; - } - else if (keyCode === 190) { - this._code = 'Period'; - this._key = this._shiftKeyActive ? '>' : '.'; - } - else if (keyCode === 191) { - this._code = 'Slash'; - this._key = this._shiftKeyActive ? '?' : '/'; - } - else if (keyCode === 32) { - this._code = 'Space'; - this._key = ' '; - } - else if (keyCode === 46) { - this._code = this._key = 'Delete'; - } - else if (keyCode === 110) { - this._code = 'NumpadDecimal'; - this._key = '.'; - } - else if (keyCode === 20) { - this._code = this._key = 'CapsLock'; - if (type === 'keyup') { - __capsLockActive = !__capsLockActive; - } - } - else { - console.log("Unknown keyCode: " + this._keyCode); - } - } - - // Returns a Boolean indicating if the modifier key, like Alt, Shift, Ctrl, or Meta, was pressed when the event was created. - getModifierState() { - return false; - } - - // Returns a Boolean that is true if the Alt ( Option or ⌥ on OS X) key was active when the key event was generated. - get altKey() { - return this._altKeyActive; - } - - // Returns a DOMString with the code value of the key represented by the event. - get code() { - return this._code; - } - - // Returns a Boolean that is true if the Ctrl key was active when the key event was generated. - get ctrlKey() { - return this._ctrlKeyActive; - } - - // Returns a Boolean that is true if the event is fired between after compositionstart and before compositionend. - get isComposing() { - return false; - } - - // Returns a DOMString representing the key value of the key represented by the event. - get key() { - return this._key; - } - - get keyCode() { - return this._keyCode; - } - - // Returns a Number representing the location of the key on the keyboard or other input device. - get location() { - return 0; - } - - // Returns a Boolean that is true if the Meta key (on Mac keyboards, the ⌘ Command key; on Windows keyboards, the Windows key (⊞)) was active when the key event was generated. - get metaKey() { - return this._metaKeyActive; - } - - // Returns a Boolean that is true if the key is being held down such that it is automatically repeating. - get repeat() { - return this._repeat; - } - - // Returns a Boolean that is true if the Shift key was active when the key event was generated. - get shiftKey() { - return this._shiftKeyActive; - } -} - -module.exports = KeyboardEvent diff --git a/platforms/native/builtin/jsb-adapter/MediaError.js b/platforms/native/builtin/jsb-adapter/MediaError.js deleted file mode 100644 index 0712f273cb..0000000000 --- a/platforms/native/builtin/jsb-adapter/MediaError.js +++ /dev/null @@ -1,20 +0,0 @@ -const MEDIA_ERR_ABORTED = 1; -const MEDIA_ERR_NETWORK = 2; -const MEDIA_ERR_DECODE = 3; -const MEDIA_ERR_SRC_NOT_SUPPORTED = 4; - -class MediaError { - constructor() { - - } - - get code() { - return MEDIA_ERR_ABORTED - } - - get message() { - return "" - } -} - -module.exports = MediaError; diff --git a/platforms/native/builtin/jsb-adapter/MouseEvent.js b/platforms/native/builtin/jsb-adapter/MouseEvent.js deleted file mode 100644 index 915c49f6a4..0000000000 --- a/platforms/native/builtin/jsb-adapter/MouseEvent.js +++ /dev/null @@ -1,54 +0,0 @@ -const Event = require('./Event') - -class MouseEvent extends Event { - constructor(type, initArgs) { - super(type) - this._button = initArgs.button; - this._which = initArgs.which; - this._wheelDelta = initArgs.wheelDelta; - this._clientX = initArgs.clientX; - this._clientY = initArgs.clientY; - this._screenX = initArgs.screenX; - this._screenY = initArgs.screenY; - this._pageX = initArgs.pageX; - this._pageY = initArgs.pageY; - } - - get button() { - return this._button; - } - - get which() { - return this._which; - } - - get wheelDelta() { - return this._wheelDelta; - } - - get clientX() { - return this._clientX; - } - - get clientY() { - return this._clientY; - } - - get screenX() { - return this._screenX; - } - - get screenY() { - return this._screenY; - } - - get pageX() { - return this._pageX; - } - - get pageY() { - return this._pageY; - } -} - -module.exports = MouseEvent diff --git a/platforms/native/builtin/jsb-adapter/Node.js b/platforms/native/builtin/jsb-adapter/Node.js deleted file mode 100755 index 9e01e8cf77..0000000000 --- a/platforms/native/builtin/jsb-adapter/Node.js +++ /dev/null @@ -1,50 +0,0 @@ -const EventTarget = require('./EventTarget'); -const jsbWindow = require('../../jsbWindow'); - -class Node extends EventTarget { - constructor () { - super(); - this.childNodes = []; - this.parentNode = jsbWindow.__canvas; - } - - appendChild (node) { - if (node instanceof Node) { - this.childNodes.push(node); - } else { - throw new TypeError('Failed to executed \'appendChild\' on \'Node\': parameter 1 is not of type \'Node\'.'); - } - } - - insertBefore (newNode, referenceNode) { - //REFINE: - return newNode; - } - - replaceChild (newChild, oldChild) { - //REFINE: - return oldChild; - } - - cloneNode () { - const copyNode = Object.create(this); - - Object.assign(copyNode, this); - return copyNode; - } - - removeChild (node) { - const index = this.childNodes.findIndex((child) => child === node); - - if (index > -1) { - return this.childNodes.splice(index, 1); - } - return null; - } - - contains (node) { - return this.childNodes.indexOf(node) > -1; - } -} - -module.exports = Node; diff --git a/platforms/native/builtin/jsb-adapter/TouchEvent.js b/platforms/native/builtin/jsb-adapter/TouchEvent.js deleted file mode 100755 index 364c634b4c..0000000000 --- a/platforms/native/builtin/jsb-adapter/TouchEvent.js +++ /dev/null @@ -1,12 +0,0 @@ -const Event = require('./Event') - -class TouchEvent extends Event { - constructor(type, touchEventInit) { - super(type) - this.touches = [] - this.targetTouches = [] - this.changedTouches = [] - } -} - -module.exports = TouchEvent diff --git a/platforms/native/builtin/jsb-adapter/document.js b/platforms/native/builtin/jsb-adapter/document.js deleted file mode 100755 index 973d53a2c0..0000000000 --- a/platforms/native/builtin/jsb-adapter/document.js +++ /dev/null @@ -1,125 +0,0 @@ -const HTMLElement = require('./HTMLElement'); -const Image = require('./Image'); -const HTMLCanvasElement = require('./HTMLCanvasElement'); -const HTMLVideoElement = require('./HTMLVideoElement'); -const HTMLScriptElement = require('./HTMLScriptElement'); -const Node = require('./Node'); -const FontFaceSet = require('./FontFaceSet'); - -const jsbWindow = require('../../jsbWindow'); - -class Document extends Node { - constructor () { - super(); - - this.readyState = 'complete'; - this.visibilityState = 'visible'; - this.documentElement = globalThis; - this.hidden = false; - this.style = {}; - this.location = require('./location'); - - this.head = new HTMLElement('head'); - this.body = new HTMLElement('body'); - - this.fonts = new FontFaceSet(); - - this.scripts = []; - } - - createElementNS (namespaceURI, qualifiedName, options) { - return this.createElement(qualifiedName); - } - - createElement (tagName) { - if (tagName === 'canvas') { - return new HTMLCanvasElement(1, 1); - } else if (tagName === 'img') { - return new Image(); - } else if (tagName === 'video') { - return new HTMLVideoElement(); - } else if (tagName === 'script') { - return new HTMLScriptElement(); - } - - return new HTMLElement(tagName); - } - - getElementById (id) { - if (id === jsbWindow.__canvas.id || id === 'canvas') { - return jsbWindow.__canvas; - } - return new HTMLElement(id); - } - - getElementsByTagName (tagName) { - if (tagName === 'head') { - return [document.head]; - } else if (tagName === 'body') { - return [document.body]; - } else if (tagName === 'canvas') { - return [jsbWindow.__canvas]; - } - return [new HTMLElement(tagName)]; - } - - getElementsByName (tagName) { - if (tagName === 'head') { - return [document.head]; - } else if (tagName === 'body') { - return [document.body]; - } else if (tagName === 'canvas') { - return [jsbWindow.__canvas]; - } - return [new HTMLElement(tagName)]; - } - - querySelector (query) { - if (query === 'head') { - return document.head; - } else if (query === 'body') { - return document.body; - } else if (query === 'canvas') { - return jsbWindow.__canvas; - } else if (query === `#${jsbWindow.__canvas.id}`) { - return jsbWindow.__canvas; - } - return new HTMLElement(query); - } - - querySelectorAll (query) { - if (query === 'head') { - return [document.head]; - } else if (query === 'body') { - return [document.body]; - } else if (query === 'canvas') { - return [jsbWindow.__canvas]; - } else if (query.startsWith('script[type="systemjs-importmap"]')) { - return HTMLScriptElement._getAllScriptElementsSystemJSImportType(); - } - return [new HTMLElement(query)]; - } - - createTextNode () { - return new HTMLElement('text'); - } - - elementFromPoint () { - return jsbWindow.canvas; - } - - createEvent (type) { - if (jsbWindow[type]) { - return new jsbWindow[type](); - } - return null; - } - - exitPointerLock () { - jsb.setCursorEnabled(true); - } -} - -let document = new Document(); - -module.exports = document; diff --git a/platforms/native/builtin/jsb-adapter/fetch.js b/platforms/native/builtin/jsb-adapter/fetch.js deleted file mode 100644 index e776a89f9e..0000000000 --- a/platforms/native/builtin/jsb-adapter/fetch.js +++ /dev/null @@ -1,499 +0,0 @@ -const self = globalThis; -const support = { - searchParams: 'URLSearchParams' in self, - iterable: 'Symbol' in self && 'iterator' in Symbol, - blob: false, // do not support blob in native - formData: 'FormData' in self, - arrayBuffer: 'ArrayBuffer' in self, -}; - -function isDataView (obj) { - return obj && DataView.prototype.isPrototypeOf(obj); -} - -if (support.arrayBuffer) { - const viewClasses = [ - '[object Int8Array]', - '[object Uint8Array]', - '[object Uint8ClampedArray]', - '[object Int16Array]', - '[object Uint16Array]', - '[object Int32Array]', - '[object Uint32Array]', - '[object Float32Array]', - '[object Float64Array]', - ]; - - var isArrayBufferView = ArrayBuffer.isView - || function (obj) { - return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1; - }; -} - -function normalizeName (name) { - if (typeof name !== 'string') { - name = String(name); - } - if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name) || name === '') { - throw new TypeError('Invalid character in header field name'); - } - return name.toLowerCase(); -} - -function normalizeValue (value) { - if (typeof value !== 'string') { - value = String(value); - } - return value; -} - -// Build a destructive iterator for the value list -function iteratorFor (items) { - const iterator = { - next () { - const value = items.shift(); - return { done: value === undefined, value }; - }, - }; - - if (support.iterable) { - iterator[Symbol.iterator] = function () { - return iterator; - }; - } - - return iterator; -} - -export function Headers (headers) { - this.map = {}; - - if (headers instanceof Headers) { - headers.forEach(function (value, name) { - this.append(name, value); - }, this); - } else if (Array.isArray(headers)) { - headers.forEach(function (header) { - this.append(header[0], header[1]); - }, this); - } else if (headers) { - Object.getOwnPropertyNames(headers).forEach(function (name) { - this.append(name, headers[name]); - }, this); - } -} - -Headers.prototype.append = function (name, value) { - name = normalizeName(name); - value = normalizeValue(value); - const oldValue = this.map[name]; - this.map[name] = oldValue ? `${oldValue}, ${value}` : value; -}; - -Headers.prototype.delete = function (name) { - delete this.map[normalizeName(name)]; -}; - -Headers.prototype.get = function (name) { - name = normalizeName(name); - return this.has(name) ? this.map[name] : null; -}; - -Headers.prototype.has = function (name) { - return this.map.hasOwnProperty(normalizeName(name)); -}; - -Headers.prototype.set = function (name, value) { - this.map[normalizeName(name)] = normalizeValue(value); -}; - -Headers.prototype.forEach = function (callback, thisArg) { - for (const name in this.map) { - if (this.map.hasOwnProperty(name)) { - callback.call(thisArg, this.map[name], name, this); - } - } -}; - -Headers.prototype.keys = function () { - const items = []; - this.forEach((value, name) => { - items.push(name); - }); - return iteratorFor(items); -}; - -Headers.prototype.values = function () { - const items = []; - this.forEach((value) => { - items.push(value); - }); - return iteratorFor(items); -}; - -Headers.prototype.entries = function () { - const items = []; - this.forEach((value, name) => { - items.push([name, value]); - }); - return iteratorFor(items); -}; - -if (support.iterable) { - Headers.prototype[Symbol.iterator] = Headers.prototype.entries; -} - -function consumed (body) { - if (body.bodyUsed) { - return Promise.reject(new TypeError('Already read')); - } - body.bodyUsed = true; -} - -function fileReaderReady (reader) { - return new Promise((resolve, reject) => { - reader.onload = function () { - resolve(reader.result); - }; - reader.onerror = function () { - reject(reader.error); - }; - }); -} - -function readBlobAsArrayBuffer (blob) { - const reader = new FileReader(); - const promise = fileReaderReady(reader); - reader.readAsArrayBuffer(blob); - return promise; -} - -function readBlobAsText (blob) { - const reader = new FileReader(); - const promise = fileReaderReady(reader); - reader.readAsText(blob); - return promise; -} - -function readArrayBufferAsText (buf) { - const view = new Uint8Array(buf); - const chars = new Array(view.length); - - for (let i = 0; i < view.length; i++) { - chars[i] = String.fromCharCode(view[i]); - } - return chars.join(''); -} - -function bufferClone (buf) { - if (buf.slice) { - return buf.slice(0); - } else { - const view = new Uint8Array(buf.byteLength); - view.set(new Uint8Array(buf)); - return view.buffer; - } -} - -function Body () { - this.bodyUsed = false; - - this._initBody = function (body) { - this._bodyInit = body; - if (!body) { - this._bodyText = ''; - } else if (typeof body === 'string') { - this._bodyText = body; - } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { - this._bodyBlob = body; - } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { - this._bodyFormData = body; - } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { - this._bodyText = body.toString(); - } else if (support.arrayBuffer && support.blob && isDataView(body)) { - this._bodyArrayBuffer = bufferClone(body.buffer); - // IE 10-11 can't handle a DataView body. - this._bodyInit = new Blob([this._bodyArrayBuffer]); - } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { - this._bodyArrayBuffer = bufferClone(body); - } else { - this._bodyText = body = Object.prototype.toString.call(body); - } - - if (!this.headers.get('content-type')) { - if (typeof body === 'string') { - this.headers.set('content-type', 'text/plain;charset=UTF-8'); - } else if (this._bodyBlob && this._bodyBlob.type) { - this.headers.set('content-type', this._bodyBlob.type); - } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { - this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); - } - } - }; - - if (support.blob) { - this.blob = function () { - const rejected = consumed(this); - if (rejected) { - return rejected; - } - - if (this._bodyBlob) { - return Promise.resolve(this._bodyBlob); - } else if (this._bodyArrayBuffer) { - return Promise.resolve(new Blob([this._bodyArrayBuffer])); - } else if (this._bodyFormData) { - throw new Error('could not read FormData body as blob'); - } else { - return Promise.resolve(new Blob([this._bodyText])); - } - }; - - this.arrayBuffer = function () { - if (this._bodyArrayBuffer) { - return consumed(this) || Promise.resolve(this._bodyArrayBuffer); - } else { - return this.blob().then(readBlobAsArrayBuffer); - } - }; - } - - this.text = function () { - const rejected = consumed(this); - if (rejected) { - return rejected; - } - - if (this._bodyBlob) { - return readBlobAsText(this._bodyBlob); - } else if (this._bodyArrayBuffer) { - return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)); - } else if (this._bodyFormData) { - throw new Error('could not read FormData body as text'); - } else { - return Promise.resolve(this._bodyText); - } - }; - - if (support.formData) { - this.formData = function () { - return this.text().then(decode); - }; - } - - this.json = function () { - return this.text().then(JSON.parse); - }; - - return this; -} - -// HTTP methods whose capitalization should be normalized -const methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'PATCH']; - -function normalizeMethod (method) { - const upcased = method.toUpperCase(); - return methods.indexOf(upcased) > -1 ? upcased : method; -} - -export function Request (input, options) { - options = options || {}; - let body = options.body; - - if (input instanceof Request) { - if (input.bodyUsed) { - throw new TypeError('Already read'); - } - this.url = input.url; - this.credentials = input.credentials; - if (!options.headers) { - this.headers = new Headers(input.headers); - } - this.method = input.method; - this.mode = input.mode; - this.signal = input.signal; - if (!body && input._bodyInit != null) { - body = input._bodyInit; - input.bodyUsed = true; - } - } else { - this.url = String(input); - } - - this.credentials = options.credentials || this.credentials || 'same-origin'; - if (options.headers || !this.headers) { - this.headers = new Headers(options.headers); - } - this.method = normalizeMethod(options.method || this.method || 'GET'); - this.mode = options.mode || this.mode || null; - this.signal = options.signal || this.signal; - this.referrer = null; - - if ((this.method === 'GET' || this.method === 'HEAD') && body) { - throw new TypeError('Body not allowed for GET or HEAD requests'); - } - this._initBody(body); -} - -Request.prototype.clone = function () { - return new Request(this, { body: this._bodyInit }); -}; - -function decode (body) { - const form = new FormData(); - body - .trim() - .split('&') - .forEach((bytes) => { - if (bytes) { - const split = bytes.split('='); - const name = split.shift().replace(/\+/g, ' '); - const value = split.join('=').replace(/\+/g, ' '); - form.append(decodeURIComponent(name), decodeURIComponent(value)); - } - }); - return form; -} - -function parseHeaders (rawHeaders) { - const headers = new Headers(); - // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space - // https://tools.ietf.org/html/rfc7230#section-3.2 - const preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' '); - preProcessedHeaders.split(/\r?\n/).forEach((line) => { - const parts = line.split(':'); - const key = parts.shift().trim(); - if (key) { - const value = parts.join(':').trim(); - headers.append(key, value); - } - }); - return headers; -} - -Body.call(Request.prototype); - -export function Response (bodyInit, options) { - if (!options) { - options = {}; - } - - this.type = 'default'; - this.status = options.status === undefined ? 200 : options.status; - this.ok = this.status >= 200 && this.status < 300; - this.statusText = 'statusText' in options ? options.statusText : 'OK'; - this.headers = new Headers(options.headers); - this.url = options.url || ''; - this._initBody(bodyInit); -} - -Body.call(Response.prototype); - -Response.prototype.clone = function () { - return new Response(this._bodyInit, { - status: this.status, - statusText: this.statusText, - headers: new Headers(this.headers), - url: this.url, - }); -}; - -Response.error = function () { - const response = new Response(null, { status: 0, statusText: '' }); - response.type = 'error'; - return response; -}; - -const redirectStatuses = [301, 302, 303, 307, 308]; - -Response.redirect = function (url, status) { - if (redirectStatuses.indexOf(status) === -1) { - throw new RangeError('Invalid status code'); - } - - return new Response(null, { status, headers: { location: url } }); -}; - -export var DOMException = self.DOMException; -try { - new DOMException(); -} catch (err) { - DOMException = function (message, name) { - this.message = message; - this.name = name; - const error = Error(message); - this.stack = error.stack; - }; - DOMException.prototype = Object.create(Error.prototype); - DOMException.prototype.constructor = DOMException; -} - -export function fetch (input, init) { - return new Promise((resolve, reject) => { - const request = new Request(input, init); - - if (request.signal && request.signal.aborted) { - return reject(new DOMException('Aborted', 'AbortError')); - } - - const xhr = new XMLHttpRequest(); - - function abortXhr () { - xhr.abort(); - } - - xhr.onload = function () { - const options = { - status: xhr.status, - statusText: xhr.statusText, - headers: parseHeaders(xhr.getAllResponseHeaders() || ''), - }; - options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL'); - const body = 'response' in xhr ? xhr.response : xhr.responseText; - resolve(new Response(body, options)); - }; - - xhr.onerror = function () { - reject(new TypeError('Network request failed')); - }; - - xhr.ontimeout = function () { - reject(new TypeError('Network request failed')); - }; - - xhr.onabort = function () { - reject(new DOMException('Aborted', 'AbortError')); - }; - - xhr.open(request.method, request.url, true); - - if (request.credentials === 'include') { - xhr.withCredentials = true; - } else if (request.credentials === 'omit') { - xhr.withCredentials = false; - } - - if ('responseType' in xhr && support.blob) { - xhr.responseType = 'blob'; - } - - request.headers.forEach((value, name) => { - xhr.setRequestHeader(name, value); - }); - - if (request.signal) { - request.signal.addEventListener('abort', abortXhr); - - xhr.onreadystatechange = function () { - // DONE (success or failure) - if (xhr.readyState === 4) { - request.signal.removeEventListener('abort', abortXhr); - } - }; - } - - xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit); - }); -} - -fetch.polyfill = true; diff --git a/platforms/native/builtin/jsb-adapter/index.js b/platforms/native/builtin/jsb-adapter/index.js deleted file mode 100755 index 6109fdeb4e..0000000000 --- a/platforms/native/builtin/jsb-adapter/index.js +++ /dev/null @@ -1,2 +0,0 @@ -require('./window') - diff --git a/platforms/native/builtin/jsb-adapter/location.js b/platforms/native/builtin/jsb-adapter/location.js deleted file mode 100755 index bca4fe4a20..0000000000 --- a/platforms/native/builtin/jsb-adapter/location.js +++ /dev/null @@ -1,11 +0,0 @@ -const location = { - href: 'game.js', - pathname: 'game.js', - search: '', - hash: '', - protocol: '', - reload() { - } -} - -module.exports = location; diff --git a/platforms/native/builtin/jsb-adapter/navigator.js b/platforms/native/builtin/jsb-adapter/navigator.js deleted file mode 100755 index 1f26d61bda..0000000000 --- a/platforms/native/builtin/jsb-adapter/navigator.js +++ /dev/null @@ -1,19 +0,0 @@ -let { noop } = require('./util'); - -const navigator = { - platform: __getOS(), - language: __getCurrentLanguage(), - appVersion: '5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1', - userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E8301 NetType/WIFI Language/zh_CN', - onLine: true, //FIXME: - - geolocation: { - getCurrentPosition: noop, - watchPosition: noop, - clearWatch: noop - }, - - maxTouchPoints: 10 //FIXME: getting the number from OS. -} - -module.exports = navigator; diff --git a/platforms/native/builtin/jsb-adapter/util/index.js b/platforms/native/builtin/jsb-adapter/util/index.js deleted file mode 100755 index 7916832360..0000000000 --- a/platforms/native/builtin/jsb-adapter/util/index.js +++ /dev/null @@ -1,3 +0,0 @@ -function noop() {} - -module.exports = noop; diff --git a/platforms/native/builtin/jsb-adapter/window.js b/platforms/native/builtin/jsb-adapter/window.js deleted file mode 100755 index 7c520b4ad4..0000000000 --- a/platforms/native/builtin/jsb-adapter/window.js +++ /dev/null @@ -1,137 +0,0 @@ -const jsbWindow = require('../../jsbWindow'); - -function inject () { - jsbWindow.ontouchstart = null; - jsbWindow.ontouchmove = null; - jsbWindow.ontouchend = null; - jsbWindow.ontouchcancel = null; - - jsbWindow.pageXOffset = jsbWindow.pageYOffset = jsbWindow.clientTop = jsbWindow.clientLeft = 0; - jsbWindow.outerWidth = jsbWindow.innerWidth; - jsbWindow.outerHeight = jsbWindow.innerHeight; - jsbWindow.clientWidth = jsbWindow.innerWidth; - jsbWindow.clientHeight = jsbWindow.innerHeight; - // if (!__EDITOR__) { - jsbWindow.top = jsbWindow.parent = jsbWindow; - jsbWindow.location = require('./location'); - jsbWindow.document = require('./document'); - jsbWindow.navigator = require('./navigator'); - // } - - jsbWindow.CanvasRenderingContext2D = require('./CanvasRenderingContext2D'); - jsbWindow.Element = require('./Element'); - jsbWindow.HTMLElement = require('./HTMLElement'); - jsbWindow.HTMLCanvasElement = require('./HTMLCanvasElement'); - jsbWindow.HTMLImageElement = require('./HTMLImageElement'); - jsbWindow.HTMLMediaElement = require('./HTMLMediaElement'); - jsbWindow.HTMLVideoElement = require('./HTMLVideoElement'); - jsbWindow.HTMLScriptElement = require('./HTMLScriptElement'); - jsbWindow.__canvas = new jsbWindow.HTMLCanvasElement(); - jsbWindow.__canvas._width = jsbWindow.innerWidth; - jsbWindow.__canvas._height = jsbWindow.innerHeight; - - jsbWindow.Image = require('./Image'); - jsbWindow.FileReader = require('./FileReader'); - jsbWindow.FontFace = require('./FontFace'); - jsbWindow.FontFaceSet = require('./FontFaceSet'); - jsbWindow.EventTarget = require('./EventTarget'); - jsbWindow.Event = jsbWindow.Event || require('./Event'); - jsbWindow.TouchEvent = require('./TouchEvent'); - jsbWindow.MouseEvent = require('./MouseEvent'); - jsbWindow.KeyboardEvent = require('./KeyboardEvent'); - jsbWindow.DeviceMotionEvent = require('./DeviceMotionEvent'); - - // ES6 - const m_fetch = require('./fetch'); - jsbWindow.fetch = m_fetch.fetch; - jsbWindow.Headers = m_fetch.Headers; - jsbWindow.Request = m_fetch.Request; - jsbWindow.Response = m_fetch.Response; - - // const PORTRAIT = 0; - // const LANDSCAPE_LEFT = -90; - // const PORTRAIT_UPSIDE_DOWN = 180; - // const LANDSCAPE_RIGHT = 90; - jsbWindow.orientation = jsb.device.getDeviceOrientation(); - - // jsb.window.devicePixelRatio is readonly - if (!__EDITOR__) { - Object.defineProperty(jsbWindow, 'devicePixelRatio', { - get () { - return jsb.device.getDevicePixelRatio ? jsb.device.getDevicePixelRatio() : 1; - }, - set (_dpr) { /* ignore */ }, - enumerable: true, - configurable: true, - }); - } - - jsbWindow.screen = { - availTop: 0, - availLeft: 0, - availHeight: jsbWindow.innerWidth, - availWidth: jsbWindow.innerHeight, - colorDepth: 8, - pixelDepth: 8, - left: 0, - top: 0, - width: jsbWindow.innerWidth, - height: jsbWindow.innerHeight, - orientation: { //FIXME:cjh - type: 'portrait-primary', // portrait-primary, portrait-secondary, landscape-primary, landscape-secondary - }, - onorientationchange (event) {}, - }; - - jsbWindow.addEventListener = function (eventName, listener, options) { - jsbWindow.__canvas.addEventListener(eventName, listener, options); - }; - - jsbWindow.removeEventListener = function (eventName, listener, options) { - jsbWindow.__canvas.removeEventListener(eventName, listener, options); - }; - - jsbWindow.dispatchEvent = function (event) { - jsbWindow.__canvas.dispatchEvent(event); - }; - - jsbWindow.getComputedStyle = function (element) { - return { - position: 'absolute', - left: '0px', - top: '0px', - height: '0px', - }; - }; - - jsbWindow.resize = function (width, height) { - jsbWindow.innerWidth = width; - jsbWindow.innerHeight = height; - jsbWindow.outerWidth = jsbWindow.innerWidth; - jsbWindow.outerHeight = jsbWindow.innerHeight; - jsbWindow.__canvas._width = jsbWindow.innerWidth; - jsbWindow.__canvas._height = jsbWindow.innerHeight; - jsbWindow.screen.availWidth = jsbWindow.innerWidth; - jsbWindow.screen.availHeight = jsbWindow.innerHeight; - jsbWindow.screen.width = jsbWindow.innerWidth; - jsbWindow.screen.height = jsbWindow.innerHeight; - jsbWindow.clientWidth = jsbWindow.innerWidth; - jsbWindow.clientHeight = jsbWindow.innerHeight; - // emit resize consistent with web behavior - const resizeEvent = new jsbWindow.Event('resize'); - resizeEvent._target = jsbWindow; - jsbWindow.dispatchEvent(resizeEvent); - }; - - jsbWindow.focus = function () {}; - jsbWindow.scroll = function () {}; - - jsbWindow._isInjected = true; -} - -if (!jsbWindow._isInjected) { - inject(); -} -if (!__EDITOR__) { - jsbWindow.localStorage = sys.localStorage; -} diff --git a/platforms/native/builtin/jsb_audioengine.js b/platforms/native/builtin/jsb_audioengine.js deleted file mode 100644 index 62bc0d3963..0000000000 --- a/platforms/native/builtin/jsb_audioengine.js +++ /dev/null @@ -1,21 +0,0 @@ -(function (jsb) { - -if (!jsb || !jsb.AudioEngine) - return - -jsb.AudioEngine.AudioState = { - ERROR: -1, - INITIALZING: 0, - PLAYING: 1, - PAUSED: 2, - STOPPED: 3, -} - -jsb.AudioEngine.INVALID_AUDIO_ID = -1 -jsb.AudioEngine.TIME_UNKNOWN = -1 - -// Adapt to normal runtime based API -jsb.AudioEngine.play = jsb.AudioEngine.play2d; -jsb.AudioEngine.setErrorCallback = () => {}; - -})(jsb) diff --git a/platforms/native/builtin/jsb_input.js b/platforms/native/builtin/jsb_input.js deleted file mode 100644 index 6b94bd75a1..0000000000 --- a/platforms/native/builtin/jsb_input.js +++ /dev/null @@ -1,99 +0,0 @@ -const EventTarget = require('./jsb-adapter/EventTarget'); -const Event = require('./jsb-adapter/Event'); - -const eventTarget = new EventTarget(); - -const callbackWrappers = {}; -const callbacks = {}; -let index = 1; -const callbackWrapper = function (cb) { - if (!cb) { return null; } - - const func = function (event) { - cb({ value: event.text }); - }; - cb.___index = index++; - callbackWrappers[cb.___index] = func; - - return func; -}; -const getCallbackWrapper = function (cb) { - if (cb && cb.___index) { - const ret = callbackWrappers[cb.___index]; - delete callbackWrappers[cb.___index]; - return ret; - } else { return null; } -}; -const removeListener = function (name, cb) { - if (cb) { - eventTarget.removeEventListener(name, getCallbackWrapper(cb)); - } else { - // remove all listeners of name - const cbs = callbacks[name]; - if (!cbs) { return; } - - for (let i = 0, len = cbs.length; i < len; ++i) { eventTarget.removeEventListener(name, cbs[i]); } - - delete callbacks[name]; - } -}; -const recordCallback = function (name, cb) { - if (!cb || !name || name === '') { return; } - - if (!callbacks[name]) { callbacks[name] = []; } - - callbacks[name].push(cb); -}; - -jsb.inputBox = { - onConfirm (cb) { - const newCb = callbackWrapper(cb); - eventTarget.addEventListener('confirm', newCb); - recordCallback('confirm', newCb); - }, - offConfirm (cb) { - removeListener('confirm', cb); - }, - - onComplete (cb) { - const newCb = callbackWrapper(cb); - eventTarget.addEventListener('complete', newCb); - recordCallback('complete', newCb); - }, - offComplete (cb) { - removeListener('complete', cb); - }, - - onInput (cb) { - const newCb = callbackWrapper(cb); - eventTarget.addEventListener('input', newCb); - recordCallback('input', newCb); - }, - offInput (cb) { - removeListener('input', cb); - }, - - /** - * @param {string} options.defaultValue - * @param {number} options.maxLength - * @param {bool} options.multiple - * @param {bool} options.confirmHold - * @param {string} options.confirmType - * @param {string} options.inputType - * - * Values of options.confirmType can be [done|next|search|go|send]. - * Values of options.inputType can be [text|email|number|phone|password]. - */ - show (options) { - jsb.showInputBox(options); - }, - hide () { - jsb.hideInputBox(); - }, -}; - -jsb.onTextInput = function (eventName, text) { - const event = new Event(eventName); - event.text = text; - eventTarget.dispatchEvent(event); -}; diff --git a/platforms/native/builtin/jsb_prepare.js b/platforms/native/builtin/jsb_prepare.js deleted file mode 100644 index f5cffa26ab..0000000000 --- a/platforms/native/builtin/jsb_prepare.js +++ /dev/null @@ -1,48 +0,0 @@ -jsb.__obj_ref_id = 0; - -jsb.registerNativeRef = function (owner, target) { - if (owner && target && owner !== target) { - let targetID = target.__jsb_ref_id; - if (targetID === undefined) - targetID = target.__jsb_ref_id = jsb.__obj_ref_id++; - - let refs = owner.__nativeRefs; - if (!refs) { - refs = owner.__nativeRefs = {}; - } - - refs[targetID] = target; - } -}; - -jsb.unregisterNativeRef = function (owner, target) { - if (owner && target && owner !== target) { - let targetID = target.__jsb_ref_id; - if (targetID === undefined) - return; - - let refs = owner.__nativeRefs; - if (!refs) { - return; - } - - delete refs[targetID]; - } -}; - -jsb.unregisterAllNativeRefs = function (owner) { - if (!owner) return; - delete owner.__nativeRefs; -}; - -jsb.unregisterChildRefsForNode = function (node, recursive) { - recursive = !!recursive; - let children = node.getChildren(), i, l, child; - for (i = 0, l = children.length; i < l; ++i) { - child = children[i]; - jsb.unregisterNativeRef(node, child); - if (recursive) { - jsb.unregisterChildRefsForNode(child, recursive); - } - } -}; diff --git a/platforms/native/builtin/promise.min.js b/platforms/native/builtin/promise.min.js deleted file mode 100644 index 4c481f29b6..0000000000 --- a/platforms/native/builtin/promise.min.js +++ /dev/null @@ -1,13 +0,0 @@ -/* promise.min.js - * A Promise polyfill implementation. - * 2018-11-16 - * - * By taylorhakes, https://github.com/taylorhakes - * License: MIT - * See https://github.com/taylorhakes/promise-polyfill/blob/master/LICENSE - */ - -/*! @source https://cdn.jsdelivr.net/npm/promise-polyfill@8/dist/polyfill.js */ -!(function (e, n) { typeof exports === 'object' && typeof module !== 'undefined' ? n() : typeof define === 'function' && define.amd ? define(n) : n(); }(0, () => { -function e (e) { const n = this.constructor; return this.then((t) => n.resolve(e()).then(() => t), (t) => n.resolve(e()).then(() => n.reject(t))); } function n () {} function t (e) { if (!(this instanceof t)) throw new TypeError('Promises must be constructed via new'); if (typeof e !== 'function') throw new TypeError('not a function'); this._state = 0, this._handled = !1, this._value = undefined, this._deferreds = [], u(e, this); } function o (e, n) { for (;e._state === 3;)e = e._value; e._state !== 0 ? (e._handled = !0, t._immediateFn(() => { const t = e._state === 1 ? n.onFulfilled : n.onRejected; if (t !== null) { let o; try { o = t(e._value); } catch (f) { return void i(n.promise, f); }r(n.promise, o); } else (e._state === 1 ? r : i)(n.promise, e._value); })) : e._deferreds.push(n); } function r (e, n) { try { if (n === e) throw new TypeError('A promise cannot be resolved with itself.'); if (n && (typeof n === 'object' || typeof n === 'function')) { const o = n.then; if (n instanceof t) return e._state = 3, e._value = n, void f(e); if (typeof o === 'function') return void u((function (e, n) { return function () { e.apply(n, arguments); }; }(o, n)), e); }e._state = 1, e._value = n, f(e); } catch (r) { i(e, r); } } function i (e, n) { e._state = 2, e._value = n, f(e); } function f (e) { e._state === 2 && e._deferreds.length === 0 && t._immediateFn(() => { e._handled || t._unhandledRejectionFn(e._value); }); for (let n = 0, r = e._deferreds.length; r > n; n++)o(e, e._deferreds[n]); e._deferreds = null; } function u (e, n) { let t = !1; try { e((e) => { t || (t = !0, r(n, e)); }, (e) => { t || (t = !0, i(n, e)); }); } catch (o) { if (t) return; t = !0, i(n, o); } } const c = setTimeout; t.prototype.catch = function (e) { return this.then(null, e); }, t.prototype.then = function (e, t) { const r = new this.constructor(n); return o(this, new function (e, n, t) { this.onFulfilled = typeof e === 'function' ? e : null, this.onRejected = typeof n === 'function' ? n : null, this.promise = t; }(e, t, r)), r; }, t.prototype.finally = e, t.all = function (e) { return new t((n, t) => { function o (e, f) { try { if (f && (typeof f === 'object' || typeof f === 'function')) { const u = f.then; if (typeof u === 'function') return void u.call(f, (n) => { o(e, n); }, t); }r[e] = f, --i == 0 && n(r); } catch (c) { t(c); } } if (!e || typeof e.length === 'undefined') throw new TypeError('Promise.all accepts an array'); var r = Array.prototype.slice.call(e); if (r.length === 0) return n([]); for (var i = r.length, f = 0; r.length > f; f++)o(f, r[f]); }); }, t.resolve = function (e) { return e && typeof e === 'object' && e.constructor === t ? e : new t((n) => { n(e); }); }, t.reject = function (e) { return new t((n, t) => { t(e); }); }, t.race = function (e) { return new t((n, t) => { for (let o = 0, r = e.length; r > o; o++)e[o].then(n, t); }); }, t._immediateFn = typeof setImmediate === 'function' && function (e) { setImmediate(e); } || function (e) { c(e, 0); }, t._unhandledRejectionFn = function (e) { void 0 !== console && console && console.warn('Possible Unhandled Promise Rejection:', e); }; const l = (function () { if (typeof self !== 'undefined') return self; if (typeof window !== 'undefined') return window; if (typeof global !== 'undefined') return global; throw Error('unable to locate global object'); }()); 'Promise' in l ? l.Promise.prototype.finally || (l.Promise.prototype.finally = e) : l.Promise = t; -})); diff --git a/platforms/native/builtin/wasm.js b/platforms/native/builtin/wasm.js deleted file mode 100644 index 633500c103..0000000000 --- a/platforms/native/builtin/wasm.js +++ /dev/null @@ -1,75 +0,0 @@ -/* - Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated 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. - */ - -// fix: WebAssembly.instantiate not working well on V8. -(function injectWebAssembly() { - if (!globalThis.WebAssembly) { - console.warn('WebAssembly is not supported!'); - return; - } - - console.info('injectWebAssembly ...'); - - const oldWebAssemblyInstantiate = WebAssembly.instantiate; - const oldWebAssemblyCompile = WebAssembly.compile; - - WebAssembly.compile = function(bufferSource) { - return new Promise((resolve, reject)=>{ - if (!bufferSource) { - reject('WebAssembly.compile: Invalid buffer source!'); - } else if (CC_EDITOR) { - // FIX EDITOR ERROR: WebAssembly.Compile is disallowed on the main thread, if the buffer size is larger than 4KB. Use WebAssembly.compile, or compile on a worker thread. - resolve(oldWebAssemblyCompile.call(WebAssembly, bufferSource)); - } else { - resolve(new WebAssembly.Module(bufferSource)); - } - }); - } - - WebAssembly.instantiate = function(bufferSourceOrModule, importObject) { - let ret; - if (bufferSourceOrModule instanceof WebAssembly.Module) { - ret = oldWebAssemblyInstantiate(bufferSourceOrModule, importObject); - } - else { - ret = new Promise((resolve, reject)=>{ - WebAssembly.compile(bufferSourceOrModule) - .then((mod)=>{ - oldWebAssemblyInstantiate(mod, importObject) - .then((instance)=>{ - resolve({ - instance: instance, - module: mod - }); - }) - .catch(reject); - }) - .catch(reject); - }); - } - - return ret; - }; -})(); diff --git a/platforms/native/builtin/xmldom/dom-parser.js b/platforms/native/builtin/xmldom/dom-parser.js deleted file mode 100644 index e45dd476f1..0000000000 --- a/platforms/native/builtin/xmldom/dom-parser.js +++ /dev/null @@ -1,252 +0,0 @@ -function DOMParser(options){ - this.options = options ||{locator:{}}; - -} - -DOMParser.prototype.parseFromString = function(source,mimeType){ - var options = this.options; - var sax = new XMLReader(); - var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler - var errorHandler = options.errorHandler; - var locator = options.locator; - var defaultNSMap = options.xmlns||{}; - var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1; - var entityMap = isHTML?htmlEntity.entityMap:{'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"}; - if(locator){ - domBuilder.setDocumentLocator(locator) - } - - sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator); - sax.domBuilder = options.domBuilder || domBuilder; - if(isHTML){ - defaultNSMap['']= 'http://www.w3.org/1999/xhtml'; - } - defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace'; - if(source){ - sax.parse(source,defaultNSMap,entityMap); - }else{ - sax.errorHandler.error("invalid doc source"); - } - return domBuilder.doc; -} -function buildErrorHandler(errorImpl,domBuilder,locator){ - if(!errorImpl){ - if(domBuilder instanceof DOMHandler){ - return domBuilder; - } - errorImpl = domBuilder ; - } - var errorHandler = {} - var isCallback = errorImpl instanceof Function; - locator = locator||{} - function build(key){ - var fn = errorImpl[key]; - if(!fn && isCallback){ - fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl; - } - errorHandler[key] = fn && function(msg){ - fn('[xmldom '+key+']\t'+msg+_locator(locator)); - }||function(){}; - } - build('warning'); - build('error'); - build('fatalError'); - return errorHandler; -} - -//console.log('#\n\n\n\n\n\n\n####') -/** - * +ContentHandler+ErrorHandler - * +LexicalHandler+EntityResolver2 - * -DeclHandler-DTDHandler - * - * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler - * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2 - * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html - */ -function DOMHandler() { - this.cdata = false; -} -function position(locator,node){ - node.lineNumber = locator.lineNumber; - node.columnNumber = locator.columnNumber; -} -/** - * @see org.xml.sax.ContentHandler#startDocument - * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html - */ -DOMHandler.prototype = { - startDocument : function() { - this.doc = new DOMImplementation().createDocument(null, null, null); - if (this.locator) { - this.doc.documentURI = this.locator.systemId; - } - }, - startElement:function(namespaceURI, localName, qName, attrs) { - var doc = this.doc; - var el = doc.createElementNS(namespaceURI, qName||localName); - var len = attrs.length; - appendElement(this, el); - this.currentElement = el; - - this.locator && position(this.locator,el) - for (var i = 0 ; i < len; i++) { - var namespaceURI = attrs.getURI(i); - var value = attrs.getValue(i); - var qName = attrs.getQName(i); - var attr = doc.createAttributeNS(namespaceURI, qName); - this.locator &&position(attrs.getLocator(i),attr); - attr.value = attr.nodeValue = value; - el.setAttributeNode(attr) - } - }, - endElement:function(namespaceURI, localName, qName) { - var current = this.currentElement - var tagName = current.tagName; - this.currentElement = current.parentNode; - }, - startPrefixMapping:function(prefix, uri) { - }, - endPrefixMapping:function(prefix) { - }, - processingInstruction:function(target, data) { - var ins = this.doc.createProcessingInstruction(target, data); - this.locator && position(this.locator,ins) - appendElement(this, ins); - }, - ignorableWhitespace:function(ch, start, length) { - }, - characters:function(chars, start, length) { - chars = _toString.apply(this,arguments) - //console.log(chars) - if(chars){ - if (this.cdata) { - var charNode = this.doc.createCDATASection(chars); - } else { - var charNode = this.doc.createTextNode(chars); - } - if(this.currentElement){ - this.currentElement.appendChild(charNode); - }else if(/^\s*$/.test(chars)){ - this.doc.appendChild(charNode); - //process xml - } - this.locator && position(this.locator,charNode) - } - }, - skippedEntity:function(name) { - }, - endDocument:function() { - this.doc.normalize(); - }, - setDocumentLocator:function (locator) { - if(this.locator = locator){// && !('lineNumber' in locator)){ - locator.lineNumber = 0; - } - }, - //LexicalHandler - comment:function(chars, start, length) { - chars = _toString.apply(this,arguments) - var comm = this.doc.createComment(chars); - this.locator && position(this.locator,comm) - appendElement(this, comm); - }, - - startCDATA:function() { - //used in characters() methods - this.cdata = true; - }, - endCDATA:function() { - this.cdata = false; - }, - - startDTD:function(name, publicId, systemId) { - var impl = this.doc.implementation; - if (impl && impl.createDocumentType) { - var dt = impl.createDocumentType(name, publicId, systemId); - this.locator && position(this.locator,dt) - appendElement(this, dt); - } - }, - /** - * @see org.xml.sax.ErrorHandler - * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html - */ - warning:function(error) { - console.warn('[xmldom warning]\t'+error,_locator(this.locator)); - }, - error:function(error) { - console.error('[xmldom error]\t'+error,_locator(this.locator)); - }, - fatalError:function(error) { - console.error('[xmldom fatalError]\t'+error,_locator(this.locator)); - throw error; - } -} -function _locator(l){ - if(l){ - return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']' - } -} -function _toString(chars,start,length){ - if(typeof chars == 'string'){ - return chars.substr(start,length) - }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)") - if(chars.length >= start+length || start){ - return new java.lang.String(chars,start,length)+''; - } - return chars; - } -} - -/* - * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html - * used method of org.xml.sax.ext.LexicalHandler: - * #comment(chars, start, length) - * #startCDATA() - * #endCDATA() - * #startDTD(name, publicId, systemId) - * - * - * IGNORED method of org.xml.sax.ext.LexicalHandler: - * #endDTD() - * #startEntity(name) - * #endEntity(name) - * - * - * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html - * IGNORED method of org.xml.sax.ext.DeclHandler - * #attributeDecl(eName, aName, type, mode, value) - * #elementDecl(name, model) - * #externalEntityDecl(name, publicId, systemId) - * #internalEntityDecl(name, value) - * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html - * IGNORED method of org.xml.sax.EntityResolver2 - * #resolveEntity(String name,String publicId,String baseURI,String systemId) - * #resolveEntity(publicId, systemId) - * #getExternalSubset(name, baseURI) - * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html - * IGNORED method of org.xml.sax.DTDHandler - * #notationDecl(name, publicId, systemId) {}; - * #unparsedEntityDecl(name, publicId, systemId, notationName) {}; - */ -"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){ - DOMHandler.prototype[key] = function(){return null} -}) - -/* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */ -function appendElement (hander,node) { - if (!hander.currentElement) { - hander.doc.appendChild(node); - } else { - hander.currentElement.appendChild(node); - } -}//appendChild and setAttributeNS are preformance key - -//if(typeof require == 'function'){ -var htmlEntity = require('./entities'); -var XMLReader = require('./sax').XMLReader; -var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation; -exports.XMLSerializer = require('./dom').XMLSerializer ; -exports.DOMParser = DOMParser; -//} diff --git a/platforms/native/builtin/xmldom/dom.js b/platforms/native/builtin/xmldom/dom.js deleted file mode 100644 index 8955614d27..0000000000 --- a/platforms/native/builtin/xmldom/dom.js +++ /dev/null @@ -1,1240 +0,0 @@ -/* - * DOM Level 2 - * Object DOMException - * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html - * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - */ - -function copy(src,dest){ - for(var p in src){ - dest[p] = src[p]; - } -} -/** -^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));? -^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));? - */ -function _extends(Class,Super){ - var pt = Class.prototype; - if(!(pt instanceof Super)){ - function t(){}; - t.prototype = Super.prototype; - t = new t(); - copy(pt,t); - Class.prototype = pt = t; - } - if(pt.constructor != Class){ - if(typeof Class != 'function'){ - console.error("unknow Class:"+Class) - } - pt.constructor = Class - } -} -var htmlns = 'http://www.w3.org/1999/xhtml' ; -// Node Types -var NodeType = {} -var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1; -var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2; -var TEXT_NODE = NodeType.TEXT_NODE = 3; -var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4; -var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5; -var ENTITY_NODE = NodeType.ENTITY_NODE = 6; -var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7; -var COMMENT_NODE = NodeType.COMMENT_NODE = 8; -var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9; -var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10; -var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11; -var NOTATION_NODE = NodeType.NOTATION_NODE = 12; - -// ExceptionCode -var ExceptionCode = {} -var ExceptionMessage = {}; -var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1); -var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2); -var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3); -var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4); -var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5); -var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6); -var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7); -var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8); -var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9); -var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10); -//level2 -var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11); -var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12); -var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13); -var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14); -var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15); - - -function DOMException(code, message) { - if(message instanceof Error){ - var error = message; - }else{ - error = this; - Error.call(this, ExceptionMessage[code]); - this.message = ExceptionMessage[code]; - if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException); - } - error.code = code; - if(message) this.message = this.message + ": " + message; - return error; -}; -DOMException.prototype = Error.prototype; -copy(ExceptionCode,DOMException) -/** - * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177 - * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live. - * The items in the NodeList are accessible via an integral index, starting from 0. - */ -function NodeList() { -}; -NodeList.prototype = { - /** - * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive. - * @standard level1 - */ - length:0, - /** - * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null. - * @standard level1 - * @param index unsigned long - * Index into the collection. - * @return Node - * The node at the indexth position in the NodeList, or null if that is not a valid index. - */ - item: function(index) { - return this[index] || null; - }, - toString:function(isHTML,nodeFilter){ - for(var buf = [], i = 0;i=0){ - var lastIndex = list.length-1 - while(i0 || key == 'xmlns'){ -// return null; -// } - //console.log() - var i = this.length; - while(i--){ - var attr = this[i]; - //console.log(attr.nodeName,key) - if(attr.nodeName == key){ - return attr; - } - } - }, - setNamedItem: function(attr) { - var el = attr.ownerElement; - if(el && el!=this._ownerElement){ - throw new DOMException(INUSE_ATTRIBUTE_ERR); - } - var oldAttr = this.getNamedItem(attr.nodeName); - _addNamedNode(this._ownerElement,this,attr,oldAttr); - return oldAttr; - }, - /* returns Node */ - setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR - var el = attr.ownerElement, oldAttr; - if(el && el!=this._ownerElement){ - throw new DOMException(INUSE_ATTRIBUTE_ERR); - } - oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName); - _addNamedNode(this._ownerElement,this,attr,oldAttr); - return oldAttr; - }, - - /* returns Node */ - removeNamedItem: function(key) { - var attr = this.getNamedItem(key); - _removeNamedNode(this._ownerElement,this,attr); - return attr; - - - },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR - - //for level2 - removeNamedItemNS:function(namespaceURI,localName){ - var attr = this.getNamedItemNS(namespaceURI,localName); - _removeNamedNode(this._ownerElement,this,attr); - return attr; - }, - getNamedItemNS: function(namespaceURI, localName) { - var i = this.length; - while(i--){ - var node = this[i]; - if(node.localName == localName && node.namespaceURI == namespaceURI){ - return node; - } - } - return null; - } -}; -/** - * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490 - */ -function DOMImplementation(/* Object */ features) { - this._features = {}; - if (features) { - for (var feature in features) { - this._features = features[feature]; - } - } -}; - -DOMImplementation.prototype = { - hasFeature: function(/* string */ feature, /* string */ version) { - var versions = this._features[feature.toLowerCase()]; - if (versions && (!version || version in versions)) { - return true; - } else { - return false; - } - }, - // Introduced in DOM Level 2: - createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR - var doc = new Document(); - doc.implementation = this; - doc.childNodes = new NodeList(); - doc.doctype = doctype; - if(doctype){ - doc.appendChild(doctype); - } - if(qualifiedName){ - var root = doc.createElementNS(namespaceURI,qualifiedName); - doc.appendChild(root); - } - return doc; - }, - // Introduced in DOM Level 2: - createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR - var node = new DocumentType(); - node.name = qualifiedName; - node.nodeName = qualifiedName; - node.publicId = publicId; - node.systemId = systemId; - // Introduced in DOM Level 2: - //readonly attribute DOMString internalSubset; - - //REFINE:.. - // readonly attribute NamedNodeMap entities; - // readonly attribute NamedNodeMap notations; - return node; - } -}; - - -/** - * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 - */ - -function Node() { -}; - -Node.prototype = { - firstChild : null, - lastChild : null, - previousSibling : null, - nextSibling : null, - attributes : null, - parentNode : null, - childNodes : null, - ownerDocument : null, - nodeValue : null, - namespaceURI : null, - prefix : null, - localName : null, - // Modified in DOM Level 2: - insertBefore:function(newChild, refChild){//raises - return _insertBefore(this,newChild,refChild); - }, - replaceChild:function(newChild, oldChild){//raises - this.insertBefore(newChild,oldChild); - if(oldChild){ - this.removeChild(oldChild); - } - }, - removeChild:function(oldChild){ - return _removeChild(this,oldChild); - }, - appendChild:function(newChild){ - return this.insertBefore(newChild,null); - }, - hasChildNodes:function(){ - return this.firstChild != null; - }, - cloneNode:function(deep){ - return cloneNode(this.ownerDocument||this,this,deep); - }, - // Modified in DOM Level 2: - normalize:function(){ - var child = this.firstChild; - while(child){ - var next = child.nextSibling; - if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){ - this.removeChild(next); - child.appendData(next.data); - }else{ - child.normalize(); - child = next; - } - } - }, - // Introduced in DOM Level 2: - isSupported:function(feature, version){ - return this.ownerDocument.implementation.hasFeature(feature,version); - }, - // Introduced in DOM Level 2: - hasAttributes:function(){ - return this.attributes.length>0; - }, - lookupPrefix:function(namespaceURI){ - var el = this; - while(el){ - var map = el._nsMap; - //console.dir(map) - if(map){ - for(var n in map){ - if(map[n] == namespaceURI){ - return n; - } - } - } - el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode; - } - return null; - }, - // Introduced in DOM Level 3: - lookupNamespaceURI:function(prefix){ - var el = this; - while(el){ - var map = el._nsMap; - //console.dir(map) - if(map){ - if(prefix in map){ - return map[prefix] ; - } - } - el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode; - } - return null; - }, - // Introduced in DOM Level 3: - isDefaultNamespace:function(namespaceURI){ - var prefix = this.lookupPrefix(namespaceURI); - return prefix == null; - } -}; - - -function _xmlEncoder(c){ - return c == '<' && '<' || - c == '>' && '>' || - c == '&' && '&' || - c == '"' && '"' || - '&#'+c.charCodeAt()+';' -} - - -copy(NodeType,Node); -copy(NodeType,Node.prototype); - -/** - * @param callback return true for continue,false for break - * @return boolean true: break visit; - */ -function _visitNode(node,callback){ - if(callback(node)){ - return true; - } - if(node = node.firstChild){ - do{ - if(_visitNode(node,callback)){return true} - }while(node=node.nextSibling) - } -} - - - -function Document(){ -} -function _onAddAttribute(doc,el,newAttr){ - doc && doc._inc++; - var ns = newAttr.namespaceURI ; - if(ns == 'http://www.w3.org/2000/xmlns/'){ - //update namespace - el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value - } -} -function _onRemoveAttribute(doc,el,newAttr,remove){ - doc && doc._inc++; - var ns = newAttr.namespaceURI ; - if(ns == 'http://www.w3.org/2000/xmlns/'){ - //update namespace - delete el._nsMap[newAttr.prefix?newAttr.localName:''] - } -} -function _onUpdateChild(doc,el,newChild){ - if(doc && doc._inc){ - doc._inc++; - //update childNodes - var cs = el.childNodes; - if(newChild){ - cs[cs.length++] = newChild; - }else{ - //console.log(1) - var child = el.firstChild; - var i = 0; - while(child){ - cs[i++] = child; - child =child.nextSibling; - } - cs.length = i; - } - } -} - -/** - * attributes; - * children; - * - * writeable properties: - * nodeValue,Attr:value,CharacterData:data - * prefix - */ -function _removeChild(parentNode,child){ - var previous = child.previousSibling; - var next = child.nextSibling; - if(previous){ - previous.nextSibling = next; - }else{ - parentNode.firstChild = next - } - if(next){ - next.previousSibling = previous; - }else{ - parentNode.lastChild = previous; - } - _onUpdateChild(parentNode.ownerDocument,parentNode); - return child; -} -/** - * preformance key(refChild == null) - */ -function _insertBefore(parentNode,newChild,nextChild){ - var cp = newChild.parentNode; - if(cp){ - cp.removeChild(newChild);//remove and update - } - if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){ - var newFirst = newChild.firstChild; - if (newFirst == null) { - return newChild; - } - var newLast = newChild.lastChild; - }else{ - newFirst = newLast = newChild; - } - var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild; - - newFirst.previousSibling = pre; - newLast.nextSibling = nextChild; - - - if(pre){ - pre.nextSibling = newFirst; - }else{ - parentNode.firstChild = newFirst; - } - if(nextChild == null){ - parentNode.lastChild = newLast; - }else{ - nextChild.previousSibling = newLast; - } - do{ - newFirst.parentNode = parentNode; - }while(newFirst !== newLast && (newFirst= newFirst.nextSibling)) - _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode); - //console.log(parentNode.lastChild.nextSibling == null) - if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) { - newChild.firstChild = newChild.lastChild = null; - } - return newChild; -} -function _appendSingleChild(parentNode,newChild){ - var cp = newChild.parentNode; - if(cp){ - var pre = parentNode.lastChild; - cp.removeChild(newChild);//remove and update - var pre = parentNode.lastChild; - } - var pre = parentNode.lastChild; - newChild.parentNode = parentNode; - newChild.previousSibling = pre; - newChild.nextSibling = null; - if(pre){ - pre.nextSibling = newChild; - }else{ - parentNode.firstChild = newChild; - } - parentNode.lastChild = newChild; - _onUpdateChild(parentNode.ownerDocument,parentNode,newChild); - return newChild; - //console.log("__aa",parentNode.lastChild.nextSibling == null) -} -Document.prototype = { - //implementation : null, - nodeName : '#document', - nodeType : DOCUMENT_NODE, - doctype : null, - documentElement : null, - _inc : 1, - - insertBefore : function(newChild, refChild){//raises - if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){ - var child = newChild.firstChild; - while(child){ - var next = child.nextSibling; - this.insertBefore(child,refChild); - child = next; - } - return newChild; - } - if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){ - this.documentElement = newChild; - } - - return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild; - }, - removeChild : function(oldChild){ - if(this.documentElement == oldChild){ - this.documentElement = null; - } - return _removeChild(this,oldChild); - }, - // Introduced in DOM Level 2: - importNode : function(importedNode,deep){ - return importNode(this,importedNode,deep); - }, - // Introduced in DOM Level 2: - getElementById : function(id){ - var rtv = null; - _visitNode(this.documentElement,function(node){ - if(node.nodeType == ELEMENT_NODE){ - if(node.getAttribute('id') == id){ - rtv = node; - return true; - } - } - }) - return rtv; - }, - - //document factory method: - createElement : function(tagName){ - var node = new Element(); - node.ownerDocument = this; - node.nodeName = tagName; - node.tagName = tagName; - node.childNodes = new NodeList(); - var attrs = node.attributes = new NamedNodeMap(); - attrs._ownerElement = node; - return node; - }, - createDocumentFragment : function(){ - var node = new DocumentFragment(); - node.ownerDocument = this; - node.childNodes = new NodeList(); - return node; - }, - createTextNode : function(data){ - var node = new Text(); - node.ownerDocument = this; - node.appendData(data) - return node; - }, - createComment : function(data){ - var node = new Comment(); - node.ownerDocument = this; - node.appendData(data) - return node; - }, - createCDATASection : function(data){ - var node = new CDATASection(); - node.ownerDocument = this; - node.appendData(data) - return node; - }, - createProcessingInstruction : function(target,data){ - var node = new ProcessingInstruction(); - node.ownerDocument = this; - node.tagName = node.target = target; - node.nodeValue= node.data = data; - return node; - }, - createAttribute : function(name){ - var node = new Attr(); - node.ownerDocument = this; - node.name = name; - node.nodeName = name; - node.localName = name; - node.specified = true; - return node; - }, - createEntityReference : function(name){ - var node = new EntityReference(); - node.ownerDocument = this; - node.nodeName = name; - return node; - }, - // Introduced in DOM Level 2: - createElementNS : function(namespaceURI,qualifiedName){ - var node = new Element(); - var pl = qualifiedName.split(':'); - var attrs = node.attributes = new NamedNodeMap(); - node.childNodes = new NodeList(); - node.ownerDocument = this; - node.nodeName = qualifiedName; - node.tagName = qualifiedName; - node.namespaceURI = namespaceURI; - if(pl.length == 2){ - node.prefix = pl[0]; - node.localName = pl[1]; - }else{ - //el.prefix = null; - node.localName = qualifiedName; - } - attrs._ownerElement = node; - return node; - }, - // Introduced in DOM Level 2: - createAttributeNS : function(namespaceURI,qualifiedName){ - var node = new Attr(); - var pl = qualifiedName.split(':'); - node.ownerDocument = this; - node.nodeName = qualifiedName; - node.name = qualifiedName; - node.namespaceURI = namespaceURI; - node.specified = true; - if(pl.length == 2){ - node.prefix = pl[0]; - node.localName = pl[1]; - }else{ - //el.prefix = null; - node.localName = qualifiedName; - } - return node; - } -}; -_extends(Document,Node); - - -function Element() { - this._nsMap = {}; -}; -Element.prototype = { - nodeType : ELEMENT_NODE, - hasAttribute : function(name){ - return this.getAttributeNode(name)!=null; - }, - getAttribute : function(name){ - var attr = this.getAttributeNode(name); - return attr && attr.value || ''; - }, - getAttributeNode : function(name){ - return this.attributes.getNamedItem(name); - }, - setAttribute : function(name, value){ - var attr = this.ownerDocument.createAttribute(name); - attr.value = attr.nodeValue = "" + value; - this.setAttributeNode(attr) - }, - removeAttribute : function(name){ - var attr = this.getAttributeNode(name) - attr && this.removeAttributeNode(attr); - }, - - //four real opeartion method - appendChild:function(newChild){ - if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){ - return this.insertBefore(newChild,null); - }else{ - return _appendSingleChild(this,newChild); - } - }, - setAttributeNode : function(newAttr){ - return this.attributes.setNamedItem(newAttr); - }, - setAttributeNodeNS : function(newAttr){ - return this.attributes.setNamedItemNS(newAttr); - }, - removeAttributeNode : function(oldAttr){ - //console.log(this == oldAttr.ownerElement) - return this.attributes.removeNamedItem(oldAttr.nodeName); - }, - //get real attribute name,and remove it by removeAttributeNode - removeAttributeNS : function(namespaceURI, localName){ - var old = this.getAttributeNodeNS(namespaceURI, localName); - old && this.removeAttributeNode(old); - }, - - hasAttributeNS : function(namespaceURI, localName){ - return this.getAttributeNodeNS(namespaceURI, localName)!=null; - }, - getAttributeNS : function(namespaceURI, localName){ - var attr = this.getAttributeNodeNS(namespaceURI, localName); - return attr && attr.value || ''; - }, - setAttributeNS : function(namespaceURI, qualifiedName, value){ - var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName); - attr.value = attr.nodeValue = "" + value; - this.setAttributeNode(attr) - }, - getAttributeNodeNS : function(namespaceURI, localName){ - return this.attributes.getNamedItemNS(namespaceURI, localName); - }, - - getElementsByTagName : function(tagName){ - return new LiveNodeList(this,function(base){ - var ls = []; - _visitNode(base,function(node){ - if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){ - ls.push(node); - } - }); - return ls; - }); - }, - getElementsByTagNameNS : function(namespaceURI, localName){ - return new LiveNodeList(this,function(base){ - var ls = []; - _visitNode(base,function(node){ - if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){ - ls.push(node); - } - }); - return ls; - - }); - } -}; -Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName; -Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS; - - -_extends(Element,Node); -function Attr() { -}; -Attr.prototype.nodeType = ATTRIBUTE_NODE; -_extends(Attr,Node); - - -function CharacterData() { -}; -CharacterData.prototype = { - data : '', - substringData : function(offset, count) { - return this.data.substring(offset, offset+count); - }, - appendData: function(text) { - text = this.data+text; - this.nodeValue = this.data = text; - this.length = text.length; - }, - insertData: function(offset,text) { - this.replaceData(offset,0,text); - - }, - appendChild:function(newChild){ - throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]) - }, - deleteData: function(offset, count) { - this.replaceData(offset,count,""); - }, - replaceData: function(offset, count, text) { - var start = this.data.substring(0,offset); - var end = this.data.substring(offset+count); - text = start + text + end; - this.nodeValue = this.data = text; - this.length = text.length; - } -} -_extends(CharacterData,Node); -function Text() { -}; -Text.prototype = { - nodeName : "#text", - nodeType : TEXT_NODE, - splitText : function(offset) { - var text = this.data; - var newText = text.substring(offset); - text = text.substring(0, offset); - this.data = this.nodeValue = text; - this.length = text.length; - var newNode = this.ownerDocument.createTextNode(newText); - if(this.parentNode){ - this.parentNode.insertBefore(newNode, this.nextSibling); - } - return newNode; - } -} -_extends(Text,CharacterData); -function Comment() { -}; -Comment.prototype = { - nodeName : "#comment", - nodeType : COMMENT_NODE -} -_extends(Comment,CharacterData); - -function CDATASection() { -}; -CDATASection.prototype = { - nodeName : "#cdata-section", - nodeType : CDATA_SECTION_NODE -} -_extends(CDATASection,CharacterData); - - -function DocumentType() { -}; -DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE; -_extends(DocumentType,Node); - -function Notation() { -}; -Notation.prototype.nodeType = NOTATION_NODE; -_extends(Notation,Node); - -function Entity() { -}; -Entity.prototype.nodeType = ENTITY_NODE; -_extends(Entity,Node); - -function EntityReference() { -}; -EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE; -_extends(EntityReference,Node); - -function DocumentFragment() { -}; -DocumentFragment.prototype.nodeName = "#document-fragment"; -DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE; -_extends(DocumentFragment,Node); - - -function ProcessingInstruction() { -} -ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE; -_extends(ProcessingInstruction,Node); -function XMLSerializer(){} -XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){ - return nodeSerializeToString.call(node,isHtml,nodeFilter); -} -Node.prototype.toString = nodeSerializeToString; -function nodeSerializeToString(isHtml,nodeFilter){ - var buf = []; - var refNode = this.nodeType == 9 && this.documentElement || this; - var prefix = refNode.prefix; - var uri = refNode.namespaceURI; - - if(uri && prefix == null){ - //console.log(prefix) - var prefix = refNode.lookupPrefix(uri); - if(prefix == null){ - //isHTML = true; - var visibleNamespaces=[ - {namespace:uri,prefix:null} - //{namespace:uri,prefix:''} - ] - } - } - serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces); - //console.log('###',this.nodeType,uri,prefix,buf.join('')) - return buf.join(''); -} -function needNamespaceDefine(node,isHTML, visibleNamespaces) { - var prefix = node.prefix||''; - var uri = node.namespaceURI; - if (!prefix && !uri){ - return false; - } - if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace" - || uri == 'http://www.w3.org/2000/xmlns/'){ - return false; - } - - var i = visibleNamespaces.length - //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces) - while (i--) { - var ns = visibleNamespaces[i]; - // get namespace prefix - //console.log(node.nodeType,node.tagName,ns.prefix,prefix) - if (ns.prefix == prefix){ - return ns.namespace != uri; - } - } - //console.log(isHTML,uri,prefix=='') - //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){ - // return false; - //} - //node.flag = '11111' - //console.error(3,true,node.flag,node.prefix,node.namespaceURI) - return true; -} -function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){ - if(nodeFilter){ - node = nodeFilter(node); - if(node){ - if(typeof node == 'string'){ - buf.push(node); - return; - } - }else{ - return; - } - //buf.sort.apply(attrs, attributeSorter); - } - switch(node.nodeType){ - case ELEMENT_NODE: - if (!visibleNamespaces) visibleNamespaces = []; - var startVisibleNamespaces = visibleNamespaces.length; - var attrs = node.attributes; - var len = attrs.length; - var child = node.firstChild; - var nodeName = node.tagName; - - isHTML = (htmlns === node.namespaceURI) ||isHTML - buf.push('<',nodeName); - - - - for(var i=0;i'); - //if is cdata child node - if(isHTML && /^script$/i.test(nodeName)){ - while(child){ - if(child.data){ - buf.push(child.data); - }else{ - serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); - } - child = child.nextSibling; - } - }else - { - while(child){ - serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); - child = child.nextSibling; - } - } - buf.push(''); - }else{ - buf.push('/>'); - } - // remove added visible namespaces - //visibleNamespaces.length = startVisibleNamespaces; - return; - case DOCUMENT_NODE: - case DOCUMENT_FRAGMENT_NODE: - var child = node.firstChild; - while(child){ - serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); - child = child.nextSibling; - } - return; - case ATTRIBUTE_NODE: - return buf.push(' ',node.name,'="',node.value.replace(/[<&"]/g,_xmlEncoder),'"'); - case TEXT_NODE: - return buf.push(node.data.replace(/[<&]/g,_xmlEncoder)); - case CDATA_SECTION_NODE: - return buf.push( ''); - case COMMENT_NODE: - return buf.push( ""); - case DOCUMENT_TYPE_NODE: - var pubid = node.publicId; - var sysid = node.systemId; - buf.push(''); - }else if(sysid && sysid!='.'){ - buf.push(' SYSTEM "',sysid,'">'); - }else{ - var sub = node.internalSubset; - if(sub){ - buf.push(" [",sub,"]"); - } - buf.push(">"); - } - return; - case PROCESSING_INSTRUCTION_NODE: - return buf.push( ""); - case ENTITY_REFERENCE_NODE: - return buf.push( '&',node.nodeName,';'); - //case ENTITY_NODE: - //case NOTATION_NODE: - default: - buf.push('??',node.nodeName); - } -} -function importNode(doc,node,deep){ - var node2; - switch (node.nodeType) { - case ELEMENT_NODE: - node2 = node.cloneNode(false); - node2.ownerDocument = doc; - //var attrs = node2.attributes; - //var len = attrs.length; - //for(var i=0;i', - amp: '&', - quot: '"', - apos: "'", - Agrave: "À", - Aacute: "Á", - Acirc: "Â", - Atilde: "Ã", - Auml: "Ä", - Aring: "Å", - AElig: "Æ", - Ccedil: "Ç", - Egrave: "È", - Eacute: "É", - Ecirc: "Ê", - Euml: "Ë", - Igrave: "Ì", - Iacute: "Í", - Icirc: "Î", - Iuml: "Ï", - ETH: "Ð", - Ntilde: "Ñ", - Ograve: "Ò", - Oacute: "Ó", - Ocirc: "Ô", - Otilde: "Õ", - Ouml: "Ö", - Oslash: "Ø", - Ugrave: "Ù", - Uacute: "Ú", - Ucirc: "Û", - Uuml: "Ü", - Yacute: "Ý", - THORN: "Þ", - szlig: "ß", - agrave: "à", - aacute: "á", - acirc: "â", - atilde: "ã", - auml: "ä", - aring: "å", - aelig: "æ", - ccedil: "ç", - egrave: "è", - eacute: "é", - ecirc: "ê", - euml: "ë", - igrave: "ì", - iacute: "í", - icirc: "î", - iuml: "ï", - eth: "ð", - ntilde: "ñ", - ograve: "ò", - oacute: "ó", - ocirc: "ô", - otilde: "õ", - ouml: "ö", - oslash: "ø", - ugrave: "ù", - uacute: "ú", - ucirc: "û", - uuml: "ü", - yacute: "ý", - thorn: "þ", - yuml: "ÿ", - nbsp: " ", - iexcl: "¡", - cent: "¢", - pound: "£", - curren: "¤", - yen: "¥", - brvbar: "¦", - sect: "§", - uml: "¨", - copy: "©", - ordf: "ª", - laquo: "«", - not: "¬", - shy: "­­", - reg: "®", - macr: "¯", - deg: "°", - plusmn: "±", - sup2: "²", - sup3: "³", - acute: "´", - micro: "µ", - para: "¶", - middot: "·", - cedil: "¸", - sup1: "¹", - ordm: "º", - raquo: "»", - frac14: "¼", - frac12: "½", - frac34: "¾", - iquest: "¿", - times: "×", - divide: "÷", - forall: "∀", - part: "∂", - exist: "∃", - empty: "∅", - nabla: "∇", - isin: "∈", - notin: "∉", - ni: "∋", - prod: "∏", - sum: "∑", - minus: "−", - lowast: "∗", - radic: "√", - prop: "∝", - infin: "∞", - ang: "∠", - and: "∧", - or: "∨", - cap: "∩", - cup: "∪", - 'int': "∫", - there4: "∴", - sim: "∼", - cong: "≅", - asymp: "≈", - ne: "≠", - equiv: "≡", - le: "≤", - ge: "≥", - sub: "⊂", - sup: "⊃", - nsub: "⊄", - sube: "⊆", - supe: "⊇", - oplus: "⊕", - otimes: "⊗", - perp: "⊥", - sdot: "⋅", - Alpha: "Α", - Beta: "Β", - Gamma: "Γ", - Delta: "Δ", - Epsilon: "Ε", - Zeta: "Ζ", - Eta: "Η", - Theta: "Θ", - Iota: "Ι", - Kappa: "Κ", - Lambda: "Λ", - Mu: "Μ", - Nu: "Ν", - Xi: "Ξ", - Omicron: "Ο", - Pi: "Π", - Rho: "Ρ", - Sigma: "Σ", - Tau: "Τ", - Upsilon: "Υ", - Phi: "Φ", - Chi: "Χ", - Psi: "Ψ", - Omega: "Ω", - alpha: "α", - beta: "β", - gamma: "γ", - delta: "δ", - epsilon: "ε", - zeta: "ζ", - eta: "η", - theta: "θ", - iota: "ι", - kappa: "κ", - lambda: "λ", - mu: "μ", - nu: "ν", - xi: "ξ", - omicron: "ο", - pi: "π", - rho: "ρ", - sigmaf: "ς", - sigma: "σ", - tau: "τ", - upsilon: "υ", - phi: "φ", - chi: "χ", - psi: "ψ", - omega: "ω", - thetasym: "ϑ", - upsih: "ϒ", - piv: "ϖ", - OElig: "Œ", - oelig: "œ", - Scaron: "Š", - scaron: "š", - Yuml: "Ÿ", - fnof: "ƒ", - circ: "ˆ", - tilde: "˜", - ensp: " ", - emsp: " ", - thinsp: " ", - zwnj: "‌", - zwj: "‍", - lrm: "‎", - rlm: "‏", - ndash: "–", - mdash: "—", - lsquo: "‘", - rsquo: "’", - sbquo: "‚", - ldquo: "“", - rdquo: "”", - bdquo: "„", - dagger: "†", - Dagger: "‡", - bull: "•", - hellip: "…", - permil: "‰", - prime: "′", - Prime: "″", - lsaquo: "‹", - rsaquo: "›", - oline: "‾", - euro: "€", - trade: "™", - larr: "←", - uarr: "↑", - rarr: "→", - darr: "↓", - harr: "↔", - crarr: "↵", - lceil: "⌈", - rceil: "⌉", - lfloor: "⌊", - rfloor: "⌋", - loz: "◊", - spades: "♠", - clubs: "♣", - hearts: "♥", - diams: "♦" -}; -//for(var n in exports.entityMap){console.log(exports.entityMap[n].charCodeAt())} \ No newline at end of file diff --git a/platforms/native/builtin/xmldom/sax.js b/platforms/native/builtin/xmldom/sax.js deleted file mode 100644 index ee8118b720..0000000000 --- a/platforms/native/builtin/xmldom/sax.js +++ /dev/null @@ -1,616 +0,0 @@ -//[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] -//[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] -//[5] Name ::= NameStartChar (NameChar)* -var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF -var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"); -var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$'); -//var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/ -//var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',') - -//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE -//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE -var S_TAG = 0;//tag name offerring -var S_ATTR = 1;//attr name offerring -var S_ATTR_SPACE=2;//attr name end and space offer -var S_EQ = 3;//=space? -var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only) -var S_ATTR_END = 5;//attr value end and no space(quot end) -var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer) -var S_TAG_CLOSE = 7;//closed el - -function XMLReader(){ - -} - -XMLReader.prototype = { - parse:function(source,defaultNSMap,entityMap){ - var domBuilder = this.domBuilder; - domBuilder.startDocument(); - _copy(defaultNSMap ,defaultNSMap = {}) - parse(source,defaultNSMap,entityMap, - domBuilder,this.errorHandler); - domBuilder.endDocument(); - } -} -function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){ - function fixedFromCharCode(code) { - // String.prototype.fromCharCode does not supports - // > 2 bytes unicode chars directly - if (code > 0xffff) { - code -= 0x10000; - var surrogate1 = 0xd800 + (code >> 10) - , surrogate2 = 0xdc00 + (code & 0x3ff); - - return String.fromCharCode(surrogate1, surrogate2); - } else { - return String.fromCharCode(code); - } - } - function entityReplacer(a){ - var k = a.slice(1,-1); - if(k in entityMap){ - return entityMap[k]; - }else if(k.charAt(0) === '#'){ - return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x'))) - }else{ - errorHandler.error('entity not found:'+a); - return a; - } - } - function appendText(end){//has some bugs - if(end>start){ - var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer); - locator&&position(start); - domBuilder.characters(xt,0,end-start); - start = end - } - } - function position(p,m){ - while(p>=lineEnd && (m = linePattern.exec(source))){ - lineStart = m.index; - lineEnd = lineStart + m[0].length; - locator.lineNumber++; - //console.log('line++:',locator,startPos,endPos) - } - locator.columnNumber = p-lineStart+1; - } - var lineStart = 0; - var lineEnd = 0; - var linePattern = /.*(?:\r\n?|\n)|.*$/g - var locator = domBuilder.locator; - - var parseStack = [{currentNSMap:defaultNSMapCopy}] - var closeMap = {}; - var start = 0; - while(true){ - try{ - var tagStart = source.indexOf('<',start); - if(tagStart<0){ - if(!source.substr(start).match(/^\s*$/)){ - var doc = domBuilder.doc; - var text = doc.createTextNode(source.substr(start)); - doc.appendChild(text); - domBuilder.currentElement = text; - } - return; - } - if(tagStart>start){ - appendText(tagStart); - } - switch(source.charAt(tagStart+1)){ - case '/': - var end = source.indexOf('>',tagStart+3); - var tagName = source.substring(tagStart+2,end); - var config = parseStack.pop(); - if(end<0){ - - tagName = source.substring(tagStart+2).replace(/[\s<].*/,''); - //console.error('#@@@@@@'+tagName) - errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName); - end = tagStart+1+tagName.length; - }else if(tagName.match(/\s - locator&&position(tagStart); - end = parseInstruction(source,tagStart,domBuilder); - break; - case '!':// start){ - start = end; - }else{ - //REFINE: 这里有可能sax回退,有位置错误风险 - appendText(Math.max(tagStart,start)+1); - } - } -} -function copyLocator(f,t){ - t.lineNumber = f.lineNumber; - t.columnNumber = f.columnNumber; - return t; -} - -/** - * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack); - * @return end of the elementStartPart(end of elementEndPart for selfClosed el) - */ -function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){ - var attrName; - var value; - var p = ++start; - var s = S_TAG;//status - while(true){ - var c = source.charAt(p); - switch(c){ - case '=': - if(s === S_ATTR){//attrName - attrName = source.slice(start,p); - s = S_EQ; - }else if(s === S_ATTR_SPACE){ - s = S_EQ; - }else{ - //fatalError: equal must after attrName or space after attrName - throw new Error('attribute equal must after attrName'); - } - break; - case '\'': - case '"': - if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE - ){//equal - if(s === S_ATTR){ - errorHandler.warning('attribute value must after "="') - attrName = source.slice(start,p) - } - start = p+1; - p = source.indexOf(c,start) - if(p>0){ - value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); - el.add(attrName,value,start-1); - s = S_ATTR_END; - }else{ - //fatalError: no end quot match - throw new Error('attribute value no end \''+c+'\' match'); - } - }else if(s == S_ATTR_NOQUOT_VALUE){ - value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); - //console.log(attrName,value,start,p) - el.add(attrName,value,start); - //console.dir(el) - errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!'); - start = p+1; - s = S_ATTR_END - }else{ - //fatalError: no equal before - throw new Error('attribute value must after "="'); - } - break; - case '/': - switch(s){ - case S_TAG: - el.setTagName(source.slice(start,p)); - case S_ATTR_END: - case S_TAG_SPACE: - case S_TAG_CLOSE: - s =S_TAG_CLOSE; - el.closed = true; - case S_ATTR_NOQUOT_VALUE: - case S_ATTR: - case S_ATTR_SPACE: - break; - //case S_EQ: - default: - throw new Error("attribute invalid close char('/')") - } - break; - case ''://end document - //throw new Error('unexpected end of input') - errorHandler.error('unexpected end of input'); - if(s == S_TAG){ - el.setTagName(source.slice(start,p)); - } - return p; - case '>': - switch(s){ - case S_TAG: - el.setTagName(source.slice(start,p)); - case S_ATTR_END: - case S_TAG_SPACE: - case S_TAG_CLOSE: - break;//normal - case S_ATTR_NOQUOT_VALUE://Compatible state - case S_ATTR: - value = source.slice(start,p); - if(value.slice(-1) === '/'){ - el.closed = true; - value = value.slice(0,-1) - } - case S_ATTR_SPACE: - if(s === S_ATTR_SPACE){ - value = attrName; - } - if(s == S_ATTR_NOQUOT_VALUE){ - errorHandler.warning('attribute "'+value+'" missed quot(")!!'); - el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start) - }else{ - if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){ - errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!') - } - el.add(value,value,start) - } - break; - case S_EQ: - throw new Error('attribute value missed!!'); - } -// console.log(tagName,tagNamePattern,tagNamePattern.test(tagName)) - return p; - /*xml space '\x20' | #x9 | #xD | #xA; */ - case '\u0080': - c = ' '; - default: - if(c<= ' '){//space - switch(s){ - case S_TAG: - el.setTagName(source.slice(start,p));//tagName - s = S_TAG_SPACE; - break; - case S_ATTR: - attrName = source.slice(start,p) - s = S_ATTR_SPACE; - break; - case S_ATTR_NOQUOT_VALUE: - var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); - errorHandler.warning('attribute "'+value+'" missed quot(")!!'); - el.add(attrName,value,start) - case S_ATTR_END: - s = S_TAG_SPACE; - break; - //case S_TAG_SPACE: - //case S_EQ: - //case S_ATTR_SPACE: - // void();break; - //case S_TAG_CLOSE: - //ignore warning - } - }else{//not space -//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE -//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE - switch(s){ - //case S_TAG:void();break; - //case S_ATTR:void();break; - //case S_ATTR_NOQUOT_VALUE:void();break; - case S_ATTR_SPACE: - var tagName = el.tagName; - if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){ - errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!') - } - el.add(attrName,attrName,start); - start = p; - s = S_ATTR; - break; - case S_ATTR_END: - errorHandler.warning('attribute space is required"'+attrName+'"!!') - case S_TAG_SPACE: - s = S_ATTR; - start = p; - break; - case S_EQ: - s = S_ATTR_NOQUOT_VALUE; - start = p; - break; - case S_TAG_CLOSE: - throw new Error("elements closed character '/' and '>' must be connected to"); - } - } - }//end outer switch - //console.log('p++',p) - p++; - } -} -/** - * @return true if has new namespace define - */ -function appendElement(el,domBuilder,currentNSMap){ - var tagName = el.tagName; - var localNSMap = null; - //var currentNSMap = parseStack[parseStack.length-1].currentNSMap; - var i = el.length; - while(i--){ - var a = el[i]; - var qName = a.qName; - var value = a.value; - var nsp = qName.indexOf(':'); - if(nsp>0){ - var prefix = a.prefix = qName.slice(0,nsp); - var localName = qName.slice(nsp+1); - var nsPrefix = prefix === 'xmlns' && localName - }else{ - localName = qName; - prefix = null - nsPrefix = qName === 'xmlns' && '' - } - //can not set prefix,because prefix !== '' - a.localName = localName ; - //prefix == null for no ns prefix attribute - if(nsPrefix !== false){//hack!! - if(localNSMap == null){ - localNSMap = {} - //console.log(currentNSMap,0) - _copy(currentNSMap,currentNSMap={}) - //console.log(currentNSMap,1) - } - currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value; - a.uri = 'http://www.w3.org/2000/xmlns/' - domBuilder.startPrefixMapping(nsPrefix, value) - } - } - var i = el.length; - while(i--){ - a = el[i]; - var prefix = a.prefix; - if(prefix){//no prefix attribute has no namespace - if(prefix === 'xml'){ - a.uri = 'http://www.w3.org/XML/1998/namespace'; - }if(prefix !== 'xmlns'){ - a.uri = currentNSMap[prefix || ''] - - //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)} - } - } - } - var nsp = tagName.indexOf(':'); - if(nsp>0){ - prefix = el.prefix = tagName.slice(0,nsp); - localName = el.localName = tagName.slice(nsp+1); - }else{ - prefix = null;//important!! - localName = el.localName = tagName; - } - //no prefix element has default namespace - var ns = el.uri = currentNSMap[prefix || '']; - domBuilder.startElement(ns,localName,tagName,el); - //endPrefixMapping and startPrefixMapping have not any help for dom builder - //localNSMap = null - if(el.closed){ - domBuilder.endElement(ns,localName,tagName); - if(localNSMap){ - for(prefix in localNSMap){ - domBuilder.endPrefixMapping(prefix) - } - } - }else{ - el.currentNSMap = currentNSMap; - el.localNSMap = localNSMap; - //parseStack.push(el); - return true; - } -} -function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){ - if(/^(?:script|textarea)$/i.test(tagName)){ - var elEndStart = source.indexOf('',elStartEnd); - var text = source.substring(elStartEnd+1,elEndStart); - if(/[&<]/.test(text)){ - if(/^script$/i.test(tagName)){ - //if(!/\]\]>/.test(text)){ - //lexHandler.startCDATA(); - domBuilder.characters(text,0,text.length); - //lexHandler.endCDATA(); - return elEndStart; - //} - }//}else{//text area - text = text.replace(/&#?\w+;/g,entityReplacer); - domBuilder.characters(text,0,text.length); - return elEndStart; - //} - - } - } - return elStartEnd+1; -} -function fixSelfClosed(source,elStartEnd,tagName,closeMap){ - //if(tagName in closeMap){ - var pos = closeMap[tagName]; - if(pos == null){ - //console.log(tagName) - pos = source.lastIndexOf('') - if(pos',start+4); - //append comment source.substring(4,end)//"); - case DOCUMENT_TYPE_NODE: - var pubid = node.publicId; - var sysid = node.systemId; - buf.push(''); - }else if(sysid && sysid!='.'){ - buf.push(' SYSTEM "',sysid,'">'); - }else{ - var sub = node.internalSubset; - if(sub){ - buf.push(" [",sub,"]"); - } - buf.push(">"); - } - return; - case PROCESSING_INSTRUCTION_NODE: - return buf.push( ""); - case ENTITY_REFERENCE_NODE: - return buf.push( '&',node.nodeName,';'); - //case ENTITY_NODE: - //case NOTATION_NODE: - default: - buf.push('??',node.nodeName); - } -} -function importNode(doc,node,deep){ - var node2; - switch (node.nodeType) { - case ELEMENT_NODE: - node2 = node.cloneNode(false); - node2.ownerDocument = doc; - //var attrs = node2.attributes; - //var len = attrs.length; - //for(var i=0;i', - amp: '&', - quot: '"', - apos: "'", - Agrave: "À", - Aacute: "Á", - Acirc: "Â", - Atilde: "Ã", - Auml: "Ä", - Aring: "Å", - AElig: "Æ", - Ccedil: "Ç", - Egrave: "È", - Eacute: "É", - Ecirc: "Ê", - Euml: "Ë", - Igrave: "Ì", - Iacute: "Í", - Icirc: "Î", - Iuml: "Ï", - ETH: "Ð", - Ntilde: "Ñ", - Ograve: "Ò", - Oacute: "Ó", - Ocirc: "Ô", - Otilde: "Õ", - Ouml: "Ö", - Oslash: "Ø", - Ugrave: "Ù", - Uacute: "Ú", - Ucirc: "Û", - Uuml: "Ü", - Yacute: "Ý", - THORN: "Þ", - szlig: "ß", - agrave: "à", - aacute: "á", - acirc: "â", - atilde: "ã", - auml: "ä", - aring: "å", - aelig: "æ", - ccedil: "ç", - egrave: "è", - eacute: "é", - ecirc: "ê", - euml: "ë", - igrave: "ì", - iacute: "í", - icirc: "î", - iuml: "ï", - eth: "ð", - ntilde: "ñ", - ograve: "ò", - oacute: "ó", - ocirc: "ô", - otilde: "õ", - ouml: "ö", - oslash: "ø", - ugrave: "ù", - uacute: "ú", - ucirc: "û", - uuml: "ü", - yacute: "ý", - thorn: "þ", - yuml: "ÿ", - nbsp: " ", - iexcl: "¡", - cent: "¢", - pound: "£", - curren: "¤", - yen: "¥", - brvbar: "¦", - sect: "§", - uml: "¨", - copy: "©", - ordf: "ª", - laquo: "«", - not: "¬", - shy: "­­", - reg: "®", - macr: "¯", - deg: "°", - plusmn: "±", - sup2: "²", - sup3: "³", - acute: "´", - micro: "µ", - para: "¶", - middot: "·", - cedil: "¸", - sup1: "¹", - ordm: "º", - raquo: "»", - frac14: "¼", - frac12: "½", - frac34: "¾", - iquest: "¿", - times: "×", - divide: "÷", - forall: "∀", - part: "∂", - exist: "∃", - empty: "∅", - nabla: "∇", - isin: "∈", - notin: "∉", - ni: "∋", - prod: "∏", - sum: "∑", - minus: "−", - lowast: "∗", - radic: "√", - prop: "∝", - infin: "∞", - ang: "∠", - and: "∧", - or: "∨", - cap: "∩", - cup: "∪", - 'int': "∫", - there4: "∴", - sim: "∼", - cong: "≅", - asymp: "≈", - ne: "≠", - equiv: "≡", - le: "≤", - ge: "≥", - sub: "⊂", - sup: "⊃", - nsub: "⊄", - sube: "⊆", - supe: "⊇", - oplus: "⊕", - otimes: "⊗", - perp: "⊥", - sdot: "⋅", - Alpha: "Α", - Beta: "Β", - Gamma: "Γ", - Delta: "Δ", - Epsilon: "Ε", - Zeta: "Ζ", - Eta: "Η", - Theta: "Θ", - Iota: "Ι", - Kappa: "Κ", - Lambda: "Λ", - Mu: "Μ", - Nu: "Ν", - Xi: "Ξ", - Omicron: "Ο", - Pi: "Π", - Rho: "Ρ", - Sigma: "Σ", - Tau: "Τ", - Upsilon: "Υ", - Phi: "Φ", - Chi: "Χ", - Psi: "Ψ", - Omega: "Ω", - alpha: "α", - beta: "β", - gamma: "γ", - delta: "δ", - epsilon: "ε", - zeta: "ζ", - eta: "η", - theta: "θ", - iota: "ι", - kappa: "κ", - lambda: "λ", - mu: "μ", - nu: "ν", - xi: "ξ", - omicron: "ο", - pi: "π", - rho: "ρ", - sigmaf: "ς", - sigma: "σ", - tau: "τ", - upsilon: "υ", - phi: "φ", - chi: "χ", - psi: "ψ", - omega: "ω", - thetasym: "ϑ", - upsih: "ϒ", - piv: "ϖ", - OElig: "Œ", - oelig: "œ", - Scaron: "Š", - scaron: "š", - Yuml: "Ÿ", - fnof: "ƒ", - circ: "ˆ", - tilde: "˜", - ensp: " ", - emsp: " ", - thinsp: " ", - zwnj: "‌", - zwj: "‍", - lrm: "‎", - rlm: "‏", - ndash: "–", - mdash: "—", - lsquo: "‘", - rsquo: "’", - sbquo: "‚", - ldquo: "“", - rdquo: "”", - bdquo: "„", - dagger: "†", - Dagger: "‡", - bull: "•", - hellip: "…", - permil: "‰", - prime: "′", - Prime: "″", - lsaquo: "‹", - rsaquo: "›", - oline: "‾", - euro: "€", - trade: "™", - larr: "←", - uarr: "↑", - rarr: "→", - darr: "↓", - harr: "↔", - crarr: "↵", - lceil: "⌈", - rceil: "⌉", - lfloor: "⌊", - rfloor: "⌋", - loz: "◊", - spades: "♠", - clubs: "♣", - hearts: "♥", - diams: "♦" -}; -//for(var n in exports.entityMap){console.log(exports.entityMap[n].charCodeAt())} \ No newline at end of file diff --git a/platforms/nodejs/builtin/xmldom/sax.js b/platforms/nodejs/builtin/xmldom/sax.js deleted file mode 100644 index ee8118b720..0000000000 --- a/platforms/nodejs/builtin/xmldom/sax.js +++ /dev/null @@ -1,616 +0,0 @@ -//[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] -//[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] -//[5] Name ::= NameStartChar (NameChar)* -var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF -var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"); -var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$'); -//var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/ -//var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',') - -//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE -//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE -var S_TAG = 0;//tag name offerring -var S_ATTR = 1;//attr name offerring -var S_ATTR_SPACE=2;//attr name end and space offer -var S_EQ = 3;//=space? -var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only) -var S_ATTR_END = 5;//attr value end and no space(quot end) -var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer) -var S_TAG_CLOSE = 7;//closed el - -function XMLReader(){ - -} - -XMLReader.prototype = { - parse:function(source,defaultNSMap,entityMap){ - var domBuilder = this.domBuilder; - domBuilder.startDocument(); - _copy(defaultNSMap ,defaultNSMap = {}) - parse(source,defaultNSMap,entityMap, - domBuilder,this.errorHandler); - domBuilder.endDocument(); - } -} -function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){ - function fixedFromCharCode(code) { - // String.prototype.fromCharCode does not supports - // > 2 bytes unicode chars directly - if (code > 0xffff) { - code -= 0x10000; - var surrogate1 = 0xd800 + (code >> 10) - , surrogate2 = 0xdc00 + (code & 0x3ff); - - return String.fromCharCode(surrogate1, surrogate2); - } else { - return String.fromCharCode(code); - } - } - function entityReplacer(a){ - var k = a.slice(1,-1); - if(k in entityMap){ - return entityMap[k]; - }else if(k.charAt(0) === '#'){ - return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x'))) - }else{ - errorHandler.error('entity not found:'+a); - return a; - } - } - function appendText(end){//has some bugs - if(end>start){ - var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer); - locator&&position(start); - domBuilder.characters(xt,0,end-start); - start = end - } - } - function position(p,m){ - while(p>=lineEnd && (m = linePattern.exec(source))){ - lineStart = m.index; - lineEnd = lineStart + m[0].length; - locator.lineNumber++; - //console.log('line++:',locator,startPos,endPos) - } - locator.columnNumber = p-lineStart+1; - } - var lineStart = 0; - var lineEnd = 0; - var linePattern = /.*(?:\r\n?|\n)|.*$/g - var locator = domBuilder.locator; - - var parseStack = [{currentNSMap:defaultNSMapCopy}] - var closeMap = {}; - var start = 0; - while(true){ - try{ - var tagStart = source.indexOf('<',start); - if(tagStart<0){ - if(!source.substr(start).match(/^\s*$/)){ - var doc = domBuilder.doc; - var text = doc.createTextNode(source.substr(start)); - doc.appendChild(text); - domBuilder.currentElement = text; - } - return; - } - if(tagStart>start){ - appendText(tagStart); - } - switch(source.charAt(tagStart+1)){ - case '/': - var end = source.indexOf('>',tagStart+3); - var tagName = source.substring(tagStart+2,end); - var config = parseStack.pop(); - if(end<0){ - - tagName = source.substring(tagStart+2).replace(/[\s<].*/,''); - //console.error('#@@@@@@'+tagName) - errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName); - end = tagStart+1+tagName.length; - }else if(tagName.match(/\s - locator&&position(tagStart); - end = parseInstruction(source,tagStart,domBuilder); - break; - case '!':// start){ - start = end; - }else{ - //REFINE: 这里有可能sax回退,有位置错误风险 - appendText(Math.max(tagStart,start)+1); - } - } -} -function copyLocator(f,t){ - t.lineNumber = f.lineNumber; - t.columnNumber = f.columnNumber; - return t; -} - -/** - * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack); - * @return end of the elementStartPart(end of elementEndPart for selfClosed el) - */ -function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){ - var attrName; - var value; - var p = ++start; - var s = S_TAG;//status - while(true){ - var c = source.charAt(p); - switch(c){ - case '=': - if(s === S_ATTR){//attrName - attrName = source.slice(start,p); - s = S_EQ; - }else if(s === S_ATTR_SPACE){ - s = S_EQ; - }else{ - //fatalError: equal must after attrName or space after attrName - throw new Error('attribute equal must after attrName'); - } - break; - case '\'': - case '"': - if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE - ){//equal - if(s === S_ATTR){ - errorHandler.warning('attribute value must after "="') - attrName = source.slice(start,p) - } - start = p+1; - p = source.indexOf(c,start) - if(p>0){ - value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); - el.add(attrName,value,start-1); - s = S_ATTR_END; - }else{ - //fatalError: no end quot match - throw new Error('attribute value no end \''+c+'\' match'); - } - }else if(s == S_ATTR_NOQUOT_VALUE){ - value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); - //console.log(attrName,value,start,p) - el.add(attrName,value,start); - //console.dir(el) - errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!'); - start = p+1; - s = S_ATTR_END - }else{ - //fatalError: no equal before - throw new Error('attribute value must after "="'); - } - break; - case '/': - switch(s){ - case S_TAG: - el.setTagName(source.slice(start,p)); - case S_ATTR_END: - case S_TAG_SPACE: - case S_TAG_CLOSE: - s =S_TAG_CLOSE; - el.closed = true; - case S_ATTR_NOQUOT_VALUE: - case S_ATTR: - case S_ATTR_SPACE: - break; - //case S_EQ: - default: - throw new Error("attribute invalid close char('/')") - } - break; - case ''://end document - //throw new Error('unexpected end of input') - errorHandler.error('unexpected end of input'); - if(s == S_TAG){ - el.setTagName(source.slice(start,p)); - } - return p; - case '>': - switch(s){ - case S_TAG: - el.setTagName(source.slice(start,p)); - case S_ATTR_END: - case S_TAG_SPACE: - case S_TAG_CLOSE: - break;//normal - case S_ATTR_NOQUOT_VALUE://Compatible state - case S_ATTR: - value = source.slice(start,p); - if(value.slice(-1) === '/'){ - el.closed = true; - value = value.slice(0,-1) - } - case S_ATTR_SPACE: - if(s === S_ATTR_SPACE){ - value = attrName; - } - if(s == S_ATTR_NOQUOT_VALUE){ - errorHandler.warning('attribute "'+value+'" missed quot(")!!'); - el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start) - }else{ - if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){ - errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!') - } - el.add(value,value,start) - } - break; - case S_EQ: - throw new Error('attribute value missed!!'); - } -// console.log(tagName,tagNamePattern,tagNamePattern.test(tagName)) - return p; - /*xml space '\x20' | #x9 | #xD | #xA; */ - case '\u0080': - c = ' '; - default: - if(c<= ' '){//space - switch(s){ - case S_TAG: - el.setTagName(source.slice(start,p));//tagName - s = S_TAG_SPACE; - break; - case S_ATTR: - attrName = source.slice(start,p) - s = S_ATTR_SPACE; - break; - case S_ATTR_NOQUOT_VALUE: - var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); - errorHandler.warning('attribute "'+value+'" missed quot(")!!'); - el.add(attrName,value,start) - case S_ATTR_END: - s = S_TAG_SPACE; - break; - //case S_TAG_SPACE: - //case S_EQ: - //case S_ATTR_SPACE: - // void();break; - //case S_TAG_CLOSE: - //ignore warning - } - }else{//not space -//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE -//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE - switch(s){ - //case S_TAG:void();break; - //case S_ATTR:void();break; - //case S_ATTR_NOQUOT_VALUE:void();break; - case S_ATTR_SPACE: - var tagName = el.tagName; - if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){ - errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!') - } - el.add(attrName,attrName,start); - start = p; - s = S_ATTR; - break; - case S_ATTR_END: - errorHandler.warning('attribute space is required"'+attrName+'"!!') - case S_TAG_SPACE: - s = S_ATTR; - start = p; - break; - case S_EQ: - s = S_ATTR_NOQUOT_VALUE; - start = p; - break; - case S_TAG_CLOSE: - throw new Error("elements closed character '/' and '>' must be connected to"); - } - } - }//end outer switch - //console.log('p++',p) - p++; - } -} -/** - * @return true if has new namespace define - */ -function appendElement(el,domBuilder,currentNSMap){ - var tagName = el.tagName; - var localNSMap = null; - //var currentNSMap = parseStack[parseStack.length-1].currentNSMap; - var i = el.length; - while(i--){ - var a = el[i]; - var qName = a.qName; - var value = a.value; - var nsp = qName.indexOf(':'); - if(nsp>0){ - var prefix = a.prefix = qName.slice(0,nsp); - var localName = qName.slice(nsp+1); - var nsPrefix = prefix === 'xmlns' && localName - }else{ - localName = qName; - prefix = null - nsPrefix = qName === 'xmlns' && '' - } - //can not set prefix,because prefix !== '' - a.localName = localName ; - //prefix == null for no ns prefix attribute - if(nsPrefix !== false){//hack!! - if(localNSMap == null){ - localNSMap = {} - //console.log(currentNSMap,0) - _copy(currentNSMap,currentNSMap={}) - //console.log(currentNSMap,1) - } - currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value; - a.uri = 'http://www.w3.org/2000/xmlns/' - domBuilder.startPrefixMapping(nsPrefix, value) - } - } - var i = el.length; - while(i--){ - a = el[i]; - var prefix = a.prefix; - if(prefix){//no prefix attribute has no namespace - if(prefix === 'xml'){ - a.uri = 'http://www.w3.org/XML/1998/namespace'; - }if(prefix !== 'xmlns'){ - a.uri = currentNSMap[prefix || ''] - - //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)} - } - } - } - var nsp = tagName.indexOf(':'); - if(nsp>0){ - prefix = el.prefix = tagName.slice(0,nsp); - localName = el.localName = tagName.slice(nsp+1); - }else{ - prefix = null;//important!! - localName = el.localName = tagName; - } - //no prefix element has default namespace - var ns = el.uri = currentNSMap[prefix || '']; - domBuilder.startElement(ns,localName,tagName,el); - //endPrefixMapping and startPrefixMapping have not any help for dom builder - //localNSMap = null - if(el.closed){ - domBuilder.endElement(ns,localName,tagName); - if(localNSMap){ - for(prefix in localNSMap){ - domBuilder.endPrefixMapping(prefix) - } - } - }else{ - el.currentNSMap = currentNSMap; - el.localNSMap = localNSMap; - //parseStack.push(el); - return true; - } -} -function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){ - if(/^(?:script|textarea)$/i.test(tagName)){ - var elEndStart = source.indexOf('',elStartEnd); - var text = source.substring(elStartEnd+1,elEndStart); - if(/[&<]/.test(text)){ - if(/^script$/i.test(tagName)){ - //if(!/\]\]>/.test(text)){ - //lexHandler.startCDATA(); - domBuilder.characters(text,0,text.length); - //lexHandler.endCDATA(); - return elEndStart; - //} - }//}else{//text area - text = text.replace(/&#?\w+;/g,entityReplacer); - domBuilder.characters(text,0,text.length); - return elEndStart; - //} - - } - } - return elStartEnd+1; -} -function fixSelfClosed(source,elStartEnd,tagName,closeMap){ - //if(tagName in closeMap){ - var pos = closeMap[tagName]; - if(pos == null){ - //console.log(tagName) - pos = source.lastIndexOf('') - if(pos',start+4); - //append comment source.substring(4,end)//