From 4a6f83bd6dc05beb24238a0a78c65d3c70ffca69 Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Tue, 28 Apr 2026 23:12:10 +0800 Subject: [PATCH] Revert "refactor platforms (#126)" (#128) --- cc.config.json | 18 +- .../asset/asset-manager/download-dom-image.ts | 4 +- cocos/asset/assets/image-asset.jsb.ts | 4 +- cocos/asset/assets/image-asset.ts | 4 +- cocos/core/platform/deprecated.ts | 2 +- pal/env/minigame/env.ts | 5 +- pal/minigame/xiaomi.ts | 156 +++ pal/system-info/enum-type/platform.ts | 2 + pal/system-info/minigame/system-info.ts | 8 +- pal/wasm/wasm-minigame.ts | 6 +- platforms/minigame/README.md | 1 + .../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/runtime/README.md | 3 +- scripts/build-adapter.js | 8 +- templates/xiaomi-quick-game/babel.config.js | 8 + .../certificate/certificate.pem | 20 + .../xiaomi-quick-game/certificate/private.pem | 28 + templates/xiaomi-quick-game/game.ejs | 39 + templates/xiaomi-quick-game/manifest.json | 13 + templates/xiaomi-quick-game/package.json | 21 + tests/constants-for-test.ts | 1 + 27 files changed, 2100 insertions(+), 16 deletions(-) create mode 100644 pal/minigame/xiaomi.ts create mode 100644 platforms/minigame/platforms/xiaomi/wrapper/builtin.js create mode 100644 platforms/minigame/platforms/xiaomi/wrapper/engine/Editbox.js create mode 100644 platforms/minigame/platforms/xiaomi/wrapper/engine/download-ttf.js create mode 100644 platforms/minigame/platforms/xiaomi/wrapper/engine/index.js create mode 100644 platforms/minigame/platforms/xiaomi/wrapper/fs-utils.js create mode 100644 platforms/minigame/platforms/xiaomi/wrapper/unify.js create mode 100644 platforms/minigame/platforms/xiaomi/wrapper/utils.js create mode 100644 templates/xiaomi-quick-game/babel.config.js create mode 100644 templates/xiaomi-quick-game/certificate/certificate.pem create mode 100644 templates/xiaomi-quick-game/certificate/private.pem create mode 100644 templates/xiaomi-quick-game/game.ejs create mode 100644 templates/xiaomi-quick-game/manifest.json create mode 100644 templates/xiaomi-quick-game/package.json diff --git a/cc.config.json b/cc.config.json index 061a4267d0..b1a9c8caae 100644 --- a/cc.config.json +++ b/cc.config.json @@ -577,6 +577,13 @@ "value": false, "internal": false }, + "XIAOMI": { + "comment": "Running in the xiaomi's quick game.", + "type": "boolean", + "value": false, + "ccGlobal": true, + "internal": false + }, "ALIPAY": { "comment": "Running in the alipay's mini game.", "type": "boolean", @@ -624,6 +631,13 @@ "ccGlobal": true, "internal": false }, + "MIGU": { + "comment": "Running in the migu's quick game.", + "type": "boolean", + "value": false, + "ccGlobal": true, + "internal": false + }, "HONOR": { "comment": "Running in the honor's quick game.", "type": "boolean", @@ -724,14 +738,14 @@ "MINIGAME": { "comment": "Running in mini game.", "type": "boolean", - "value": "$WECHAT || $WECHAT_MINI_PROGRAM || $ALIPAY || $TAOBAO || $TAOBAO_MINIGAME || $BYTEDANCE", + "value": "$WECHAT || $WECHAT_MINI_PROGRAM || $XIAOMI || $ALIPAY || $TAOBAO || $TAOBAO_MINIGAME || $BYTEDANCE", "ccGlobal": true, "internal": false }, "RUNTIME_BASED": { "comment": "Running in runtime based environment.", "type": "boolean", - "value": "$OPPO || $VIVO || $HUAWEI || $HONOR || $COCOS_RUNTIME || $SUD || $SUDV2", + "value": "$OPPO || $VIVO || $HUAWEI || $MIGU || $HONOR || $COCOS_RUNTIME || $SUD || $SUDV2", "ccGlobal": true, "internal": false }, diff --git a/cocos/asset/asset-manager/download-dom-image.ts b/cocos/asset/asset-manager/download-dom-image.ts index c203420f70..f9d235bf55 100644 --- a/cocos/asset/asset-manager/download-dom-image.ts +++ b/cocos/asset/asset-manager/download-dom-image.ts @@ -23,6 +23,7 @@ THE SOFTWARE. */ +import { XIAOMI } from 'internal:constants'; import { getError } from '../../core'; import { ccwindow } from '../../core/global-exports'; @@ -33,7 +34,8 @@ export default function downloadDomImage ( ): HTMLImageElement { const img = new ccwindow.Image(); - if (ccwindow.location.protocol !== 'file:') { + // NOTE: on xiaomi platform, we need to force setting img.crossOrigin as 'anonymous' + if (ccwindow.location.protocol !== 'file:' || XIAOMI) { img.crossOrigin = 'anonymous'; } diff --git a/cocos/asset/assets/image-asset.jsb.ts b/cocos/asset/assets/image-asset.jsb.ts index 6448ffd8ad..48ff96afe3 100644 --- a/cocos/asset/assets/image-asset.jsb.ts +++ b/cocos/asset/assets/image-asset.jsb.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { ALIPAY, JSB, TEST, EDITOR, NODEJS } from 'internal:constants'; +import { ALIPAY, XIAOMI, JSB, TEST, EDITOR, NODEJS } from 'internal:constants'; import { Format, FormatFeatureBit, deviceManager } from '../../gfx'; import { PixelFormat } from './asset-enum'; import { sys, macro, warnID, cclegacy } from '../../core'; @@ -54,7 +54,7 @@ function isImageBitmap (imageSource: any): boolean { } function isNativeImage (imageSource: ImageSource): imageSource is (HTMLImageElement | HTMLCanvasElement | ImageBitmap) { - if (ALIPAY) { + if (ALIPAY || XIAOMI) { // We're unable to grab the constructors of Alipay native image or canvas object. return !('_data' in imageSource); } diff --git a/cocos/asset/assets/image-asset.ts b/cocos/asset/assets/image-asset.ts index 81e3508b18..82289373d4 100644 --- a/cocos/asset/assets/image-asset.ts +++ b/cocos/asset/assets/image-asset.ts @@ -24,7 +24,7 @@ // @ts-check import { ccclass, override } from 'cc.decorator'; -import { EDITOR, NODEJS, ALIPAY, JSB, TEST, TAOBAO, TAOBAO_MINIGAME, WECHAT_MINI_PROGRAM, BYTEDANCE } from 'internal:constants'; +import { EDITOR, NODEJS, ALIPAY, XIAOMI, JSB, TEST, TAOBAO, TAOBAO_MINIGAME, WECHAT_MINI_PROGRAM, BYTEDANCE } from 'internal:constants'; import { Device, Format, FormatFeatureBit, deviceManager } from '../../gfx'; import { Asset } from './asset'; import { PixelFormat } from './asset-enum'; @@ -163,7 +163,7 @@ function fetchImageSource (imageSource: ImageSource): HTMLCanvasElement | HTMLIm // 返回该图像源是否是平台提供的图像对象。 function isNativeImage (imageSource: ImageSource): imageSource is (HTMLImageElement | HTMLCanvasElement | ImageBitmap) { - if (ALIPAY || TAOBAO || TAOBAO_MINIGAME || WECHAT_MINI_PROGRAM || BYTEDANCE) { + if (ALIPAY || TAOBAO || TAOBAO_MINIGAME || XIAOMI || WECHAT_MINI_PROGRAM || BYTEDANCE) { // We're unable to grab the constructors of Alipay native image or canvas object. return !('_data' in imageSource); } diff --git a/cocos/core/platform/deprecated.ts b/cocos/core/platform/deprecated.ts index 8b5b17c1de..7ad79fbeda 100644 --- a/cocos/core/platform/deprecated.ts +++ b/cocos/core/platform/deprecated.ts @@ -97,7 +97,7 @@ replaceProperty( sys, 'sys', ['UNKNOWN', 'EDITOR_PAGE', 'EDITOR_CORE', 'MOBILE_BROWSER', 'DESKTOP_BROWSER', 'WIN32', 'MACOS', 'IOS', 'ANDROID', 'OHOS', - 'WECHAT_GAME', 'ALIPAY_MINI_GAME', 'BYTEDANCE_MINI_GAME', + 'WECHAT_GAME', 'XIAOMI_QUICK_GAME', 'ALIPAY_MINI_GAME', 'BYTEDANCE_MINI_GAME', 'OPPO_MINI_GAME', 'VIVO_MINI_GAME', 'HUAWEI_QUICK_GAME'].map((item) => ({ name: item, target: sys.Platform, diff --git a/pal/env/minigame/env.ts b/pal/env/minigame/env.ts index 7aff9f3c83..9f29c09e48 100644 --- a/pal/env/minigame/env.ts +++ b/pal/env/minigame/env.ts @@ -23,7 +23,7 @@ */ /* eslint-disable import/no-dynamic-require */ -import { TAOBAO, TAOBAO_MINIGAME, WECHAT, WECHAT_MINI_PROGRAM } from 'internal:constants'; +import { TAOBAO, TAOBAO_MINIGAME, WECHAT, WECHAT_MINI_PROGRAM, XIAOMI } from 'internal:constants'; import { checkPalIntegrity, withImpl } from '../../integrity-check'; declare const require: (path: string) => any; @@ -37,6 +37,9 @@ export function findCanvas (): { frame: HTMLDivElement, container: HTMLDivElemen } export function loadJsFile (path: string): any { + if (XIAOMI) { + return require(`../../${path}`); + } if (WECHAT || WECHAT_MINI_PROGRAM) { return __wxRequire(path); } diff --git a/pal/minigame/xiaomi.ts b/pal/minigame/xiaomi.ts new file mode 100644 index 0000000000..4ad32f6322 --- /dev/null +++ b/pal/minigame/xiaomi.ts @@ -0,0 +1,156 @@ +/* + 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/system-info/enum-type/platform.ts b/pal/system-info/enum-type/platform.ts index 888b23260f..3905ea228e 100644 --- a/pal/system-info/enum-type/platform.ts +++ b/pal/system-info/enum-type/platform.ts @@ -40,6 +40,7 @@ export enum Platform { // 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', @@ -48,6 +49,7 @@ export enum Platform { 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 index 2769dd294e..4bb6d5d45f 100644 --- a/pal/system-info/minigame/system-info.ts +++ b/pal/system-info/minigame/system-info.ts @@ -23,7 +23,7 @@ THE SOFTWARE. */ -import { ALIPAY, BYTEDANCE, HUAWEI, OPPO, RUNTIME_BASED, SUD, SUDV2, VIVO, HONOR, WECHAT, DEBUG, TEST, TAOBAO, TAOBAO_MINIGAME, WECHAT_MINI_PROGRAM } from 'internal:constants'; +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 } from 'pal/minigame'; import { IFeatureMap } from 'pal/system-info'; import { EventTarget } from '../../../cocos/core/event'; @@ -38,6 +38,8 @@ 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) { @@ -52,6 +54,8 @@ if (WECHAT) { 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) { @@ -197,7 +201,7 @@ class SystemInfo extends EventTarget { // init isMobile and platform this.platform = currentPlatform; - // Some minigame platforms don't support getting the platform, such as runtime, so this.os returns UNKNOWN. + // 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; diff --git a/pal/wasm/wasm-minigame.ts b/pal/wasm/wasm-minigame.ts index 51c72b1f6e..6068640e85 100644 --- a/pal/wasm/wasm-minigame.ts +++ b/pal/wasm/wasm-minigame.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { HUAWEI, TAOBAO_MINIGAME, WASM_SUBPACKAGE } from 'internal:constants'; +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'; @@ -116,7 +116,9 @@ export function ensureWasmModuleReady (): Promise { */ function getPlatformBinaryUrl (binaryUrl: string): Promise { return new Promise((resolve) => { - if (TAOBAO_MINIGAME && WASM_SUBPACKAGE) { + if (XIAOMI) { + resolve(`src/cocos-js/${binaryUrl}`); + } if (TAOBAO_MINIGAME && WASM_SUBPACKAGE) { resolve(`__ccWasmAssetSubpkg__/${basename(binaryUrl)}`); } else { resolve(`cocos-js/${binaryUrl}`); diff --git a/platforms/minigame/README.md b/platforms/minigame/README.md index ce936dca25..1fcfe4e997 100644 --- a/platforms/minigame/README.md +++ b/platforms/minigame/README.md @@ -1,6 +1,7 @@ # Adapter for MiniGame platform included platforms: - WeChat +- Xiaomi - Alipay - ByteDance - Taobao diff --git a/platforms/minigame/platforms/xiaomi/wrapper/builtin.js b/platforms/minigame/platforms/xiaomi/wrapper/builtin.js new file mode 100644 index 0000000000..3d8c58f3c8 --- /dev/null +++ b/platforms/minigame/platforms/xiaomi/wrapper/builtin.js @@ -0,0 +1,1168 @@ +/******/ (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 new file mode 100644 index 0000000000..8f13a0f5dd --- /dev/null +++ b/platforms/minigame/platforms/xiaomi/wrapper/engine/Editbox.js @@ -0,0 +1,180 @@ +(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 new file mode 100644 index 0000000000..8c7c3d064c --- /dev/null +++ b/platforms/minigame/platforms/xiaomi/wrapper/engine/download-ttf.js @@ -0,0 +1,12 @@ +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 new file mode 100644 index 0000000000..1c6ef7b5de --- /dev/null +++ b/platforms/minigame/platforms/xiaomi/wrapper/engine/index.js @@ -0,0 +1,4 @@ +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 new file mode 100644 index 0000000000..6f226b84d1 --- /dev/null +++ b/platforms/minigame/platforms/xiaomi/wrapper/fs-utils.js @@ -0,0 +1,262 @@ +/**************************************************************************** + 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 new file mode 100644 index 0000000000..3a641f2a69 --- /dev/null +++ b/platforms/minigame/platforms/xiaomi/wrapper/unify.js @@ -0,0 +1,123 @@ +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 new file mode 100644 index 0000000000..947fc06958 --- /dev/null +++ b/platforms/minigame/platforms/xiaomi/wrapper/utils.js @@ -0,0 +1,16 @@ +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/runtime/README.md b/platforms/runtime/README.md index d0dae3c06c..d2756b699a 100644 --- a/platforms/runtime/README.md +++ b/platforms/runtime/README.md @@ -2,4 +2,5 @@ included platforms: - vivo - OPPO -- huawei \ No newline at end of file +- huawei +- Migu \ No newline at end of file diff --git a/scripts/build-adapter.js b/scripts/build-adapter.js index 3166541950..1d0666d92e 100644 --- a/scripts/build-adapter.js +++ b/scripts/build-adapter.js @@ -56,7 +56,7 @@ async function bundleMinigameAdapter () { for (const platform of platforms) { console.log(`handle platform: ${green(platform)}`); - const needUglify = true; + const needUglify = (platform !== 'xiaomi'); // uglify conflicts with the webpack tool on xiaomi platform // bundle engine-adapter.js const engineEntry = normalizePath(ps.join(engineRoot, `platforms/minigame/platforms/${platform}/wrapper/engine/index.js`)); @@ -64,7 +64,10 @@ async function bundleMinigameAdapter () { await bundle(engineEntry, engineOutput, needUglify); // bundle web-adapter.js - const builtinEntry = normalizePath(ps.join(engineRoot, `platforms/minigame/platforms/${platform}/wrapper/builtin/index.js`)); + let builtinEntry = normalizePath(ps.join(engineRoot, `platforms/minigame/platforms/${platform}/wrapper/builtin/index.js`)); + if (platform === 'xiaomi') { + builtinEntry = normalizePath(ps.join(engineRoot, `platforms/minigame/platforms/${platform}/wrapper/builtin.js`)); + } const builtinOutput = normalizePath(ps.join(engineRoot, `bin/adapter/minigame/${platform}/web-adapter.js`)); await bundle(builtinEntry, builtinOutput, needUglify); } @@ -93,6 +96,7 @@ async function bundleNodejsAdapter () { const webAdapterEntry = normalizePath(ps.join(engineRoot, 'platforms/nodejs/builtin/index.js')); const webAdapterOutput = normalizePath(ps.join(engineRoot, 'bin/adapter/nodejs/web-adapter.js')); await bundle(webAdapterEntry, webAdapterOutput, true); + } function normalizePath (path) { diff --git a/templates/xiaomi-quick-game/babel.config.js b/templates/xiaomi-quick-game/babel.config.js new file mode 100644 index 0000000000..1af3ae2db1 --- /dev/null +++ b/templates/xiaomi-quick-game/babel.config.js @@ -0,0 +1,8 @@ +module.exports = function(api) { + api.cache(true); + return { + presets: ["@babel/preset-env"], + plugins: ["@babel/plugin-transform-modules-commonjs"], + babelrcRoots: [".", "node_modules"] + }; +} \ No newline at end of file diff --git a/templates/xiaomi-quick-game/certificate/certificate.pem b/templates/xiaomi-quick-game/certificate/certificate.pem new file mode 100644 index 0000000000..fe635b145e --- /dev/null +++ b/templates/xiaomi-quick-game/certificate/certificate.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDMTCCAhmgAwIBAgIJAMKpjyszxkDpMA0GCSqGSIb3DQEBCwUAMC4xCzAJBgNV +BAYTAkNOMQwwCgYDVQQKDANSUEsxETAPBgNVBAMMCFJQS0RlYnVnMCAXDTE3MDQx +OTAyMzE0OVoYDzIxMTYwMzI2MDIzMTQ5WjAuMQswCQYDVQQGEwJDTjEMMAoGA1UE +CgwDUlBLMREwDwYDVQQDDAhSUEtEZWJ1ZzCCASIwDQYJKoZIhvcNAQEBBQADggEP +ADCCAQoCggEBAK3kPd9jzvTctTIA3XNZVv9cHHDbAc6nTBfdZp9mtPOTkXFpvyCb +kL0QjOog0+1pv8D7dFeP4ptWXU5CT3ImvaPR+16dAtMRcsxEr5q4zieJzx3O6huL +UBa1k+xrzjXpRzkcOysmc8fTxt0tAwbDgJ2AA5TlXLTcVyb7GmJ+hl5CjnhoG5NN +LrkqI7S29c1U3uokj8Q7hzaj0TURu/uB5ZIMCLZY9KFDugqaEcvmUyJiD0fuV6sA +O/4kpiZUOnhV8/xWpRbMI4WFQsfgLOCV+X9uzUa29D677y//46t/EDSuQTHyBZbl +AcNMENkpMWZsH7J/+F19+U0/Hd5bJgneVRkCAwEAAaNQME4wHQYDVR0OBBYEFKDN +SZtt47ttOBDQzIchFYyxsg3mMB8GA1UdIwQYMBaAFKDNSZtt47ttOBDQzIchFYyx +sg3mMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBABaZctNrn4gLmNf/ +eNJ3x5CJIPjPwm6j9nwKhtadJ6BF+TIzSkJuHSgxULjW436F37otv94NPzT5PCBF +WxgXoqgLqnWwvsaqC4LUEjsZviWW4CB824YDUquEUVGFLE/U5KTZ7Kh1ceyUk4N8 ++mtkXkanWoBBk0OF24lNrAsNLB63yTLr9HxEe75+kmvxf1qVJUGtaOEWIhiFMiAB +5D4w/j2EFWktumjuy5TTwU0zhl52bc8V9SNixM1IaqzNrVPrdjv8viUX548pU3WT +xZ5ylDsxhMC1q4BXQVeIY8C0cMEX+WHOmOCvWrkxCkP91pKsSPkuVrWlzrkn8Ojo +swP6sBw= +-----END CERTIFICATE----- diff --git a/templates/xiaomi-quick-game/certificate/private.pem b/templates/xiaomi-quick-game/certificate/private.pem new file mode 100644 index 0000000000..50d0707f36 --- /dev/null +++ b/templates/xiaomi-quick-game/certificate/private.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCt5D3fY8703LUy +AN1zWVb/XBxw2wHOp0wX3WafZrTzk5Fxab8gm5C9EIzqINPtab/A+3RXj+KbVl1O +Qk9yJr2j0ftenQLTEXLMRK+auM4nic8dzuobi1AWtZPsa8416Uc5HDsrJnPH08bd +LQMGw4CdgAOU5Vy03Fcm+xpifoZeQo54aBuTTS65KiO0tvXNVN7qJI/EO4c2o9E1 +Ebv7geWSDAi2WPShQ7oKmhHL5lMiYg9H7lerADv+JKYmVDp4VfP8VqUWzCOFhULH +4Czglfl/bs1GtvQ+u+8v/+OrfxA0rkEx8gWW5QHDTBDZKTFmbB+yf/hdfflNPx3e +WyYJ3lUZAgMBAAECggEBAJTnCBBdUB+fSs1prjeS/gsmnfgJoY+K9H7PCIxgj3yw +FXAvZAmRDKzJGlF2EOOQlTG0YNiGDj6EAtv7rjoKcINyULSg8IU6wLmn61MrAuUa +fa+Bujgh4E/B5swhOHAztNhzkzsM70Hi17wXSislh+HWd7qteOgqcbqgdOR4gaj+ +HUqtcxG3H3hCL3dWugnjLZMtestLKGHSSZvbQNjYM3kKy2LvO8NpxmDE4a+TXygK +qhaZjmS/dc/nJBJzOfkzby58RvGbzlJflfW/Uu3/gizj13GFQKWonq1xh630RAhv +xX5ySok2aAx/+/SiJSpNXvM09grQuoORSr7D1tm+5rECgYEA3vf0hRfua0XAOu6f +pyzNvLRRJ/pEew7XpNPCyS2TuMTd1yvXjGVxQfP46N6x1IM3SRU0zE+LSk80EF7l +u1Or7GyCEhabYNe/7P2F8ENP73Do0HwvcI1jGrgr6r9oK0J27Xei+f6Q0bgJOPI2 +qaLj+V37cOjkNSM1mhTjtDwK8k0CgYEAx6cMrkjHl1+lDIIOc3qAEL3jb3xQveYk +WrMF/B+j048k6boU4VvFJAIyQxOxMNxLjw3/9+zXCFJT4WaZK3TMXlg614ASGx3H +tKjJM9O07ywwMq1gbutFS4nHCg3L3Os6esL0SPwMdATR3Yh22n5OGI9o+/aURulL +GPEXef1Z2/0CgYEAgmwp5LxV4vu+8Pnp+4DSq4ISQr861XyeGTUhKEp3sUm+tgFY +KTChakHKpHS3Mqa6bQ5xft08je/8dWL9IHFWDIqAHxKIOsKY6oh1k0/cbyPtmx45 +Ja4efV+jmMHzrfJH3KnxdCg7D+GFy4CrBtlYXuJhlO81pft9fC6h7yh8ArUCgYBq +gvkl5Zftbs4rnRq+iqTVyagTKvwcQzIz3PwdZHfO/rfPpUFMdNv4eN99n3zRN0Vs +HSjoiEazntA3GLgwUdBRqLpDi4SdSMbo337vkksdqbJQ5uPiaMuAIBG6kF+pDSkW +ovkWErlGD+gySoI10FozihaVDRhPuFgjB0PiBcIxtQKBgGNSzX+Bx5+ux1Qny0Sn +SUcBtepLnO8M8wafoGNyehbMnLzfuMbaDiJOdozGlBNHZTtPB3r4AYb8WnltdKW0 +7i3fk26YZGiMVeUJvewA6/LOBEaqMdwoNwnoptvbR6ehHeE/PPtRtge2cD3bPIM7 +U9VlWgfgj9Dxfwhslqb9hmyp +-----END PRIVATE KEY----- diff --git a/templates/xiaomi-quick-game/game.ejs b/templates/xiaomi-quick-game/game.ejs new file mode 100644 index 0000000000..ac5eba0ade --- /dev/null +++ b/templates/xiaomi-quick-game/game.ejs @@ -0,0 +1,39 @@ +require('./web-adapter'); + +<% if(polyfillsBundleFile) { %> +// Polyfills bundle. +require("<%= polyfillsBundleFile %>"); +<% } %> + +// SystemJS support. +require("<%= systemJsBundleFile %>"); + +// hack for Xiaomi havent screen; +screen = window.screen; + +// Adjust initial canvas size +if (canvas && window.devicePixelRatio >= 2) {canvas.width *= 2; canvas.height *= 2;} + +const importMap = require("./<%= importMapFile%>").default; +System.warmup({ + importMap, + importMapUrl: '<%= importMapFile%>', + defaultHandler: (urlNoSchema) => { + require('.' + urlNoSchema); + }, +}); + +System.import('<%= applicationJs %>').then(({ Application }) => { + return new Application(); +}).then((application) => { + return onApplicationCreated(application); +}).catch((err) => { + console.error(err); +}); + +function onApplicationCreated(application) { + return System.import('cc').then((cc) => { + require('./engine-adapter'); + return application.init(cc); + }).then(() => application.start()); +} diff --git a/templates/xiaomi-quick-game/manifest.json b/templates/xiaomi-quick-game/manifest.json new file mode 100644 index 0000000000..89881cd0d5 --- /dev/null +++ b/templates/xiaomi-quick-game/manifest.json @@ -0,0 +1,13 @@ +{ + "package": "", + "name": "", + "versionName": "1.0.0", + "versionCode": 1201, + "minPlatformVersion": 1056, + "icon": "/image/icon.png", + "orientation": "portrait", + "type": "game", + "config": {}, + "display": {}, + "subpackages": [] +} \ No newline at end of file diff --git a/templates/xiaomi-quick-game/package.json b/templates/xiaomi-quick-game/package.json new file mode 100644 index 0000000000..bd6f186065 --- /dev/null +++ b/templates/xiaomi-quick-game/package.json @@ -0,0 +1,21 @@ +{ + "name": "xiaomi-adapter", + "version": "1.0.0", + "build-template": "xiaomigame", + "scripts": { + "build": "quickgame build --cocos-wx-game --include-file-ext .pem,.pkm,.webp,.astc", + "build-ignore-res": "quickgame build --cocos-wx-game --include-file-ext .pem,.pkm,.webp,.astc --ignore remote,res", + "release": "quickgame release --cocos-wx-game --include-file-ext .pem,.pkm,.webp,.astc", + "release-ignore-res": "quickgame release --cocos-wx-game --include-file-ext .pem,.pkm,.webp,.astc --ignore remote,res", + "server": "quickgame server", + "debug": "quickgame debug" + }, + "babel": { + "plugins": [ + "babel-plugin-transform-remove-strict-mode" + ] + }, + "dependencies": { + "quickgame-cli": "^0.1.19" + } +} diff --git a/tests/constants-for-test.ts b/tests/constants-for-test.ts index 7173f41b16..5c165ddc29 100644 --- a/tests/constants-for-test.ts +++ b/tests/constants-for-test.ts @@ -31,6 +31,7 @@ export const WECHAT = tryDefineGlobal('CC_WECHAT', !!(defined('wx') && (wx.getSy export const MINIGAME = tryDefineGlobal('CC_MINIGAME', false); export const RUNTIME_BASED = tryDefineGlobal('CC_RUNTIME_BASED', false); export const ALIPAY = tryDefineGlobal('CC_ALIPAY', false); +export const XIAOMI = tryDefineGlobal('CC_XIAOMI', false); export const BYTEDANCE = tryDefineGlobal('CC_BYTEDANCE', false); export const HUAWEI = tryDefineGlobal('CC_HUAWEI', false); export const OPPO = tryDefineGlobal('CC_OPPO', false);