forked from cocos/cocos4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystem-info.ts
More file actions
371 lines (325 loc) · 13.3 KB
/
Copy pathsystem-info.ts
File metadata and controls
371 lines (325 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/* 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, HONOR, WECHAT, 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';
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 (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 (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;
let _cachedSystemInfo: MinigameSystemInfo = originalGetSystemInfoSync.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);
});
minigame.getSystemInfoSync = function (): MinigameSystemInfo {
return _cachedSystemInfo;
};
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<void>[] = [];
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, 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<void> {
if (!TEST) {
return this._supportsWebp().then((isSupport) => {
this._setFeature(Feature.WEBP, isSupport);
});
}
return Promise.resolve();
}
private _supportsWebp (): Promise<boolean> {
return new Promise<boolean>((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<void[]> {
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<typeof import('pal/system-info')>(withImpl<typeof import('./system-info')>());