@aiot-toolkit/emulator 2.0.6-beta.27 → 2.0.6-beta.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,11 +4,82 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.VelaMiwear5 = void 0;
7
+ var adbMiwt = _interopRequireWildcard(require("@aiot-toolkit/adb"));
7
8
  var _Vvd = require("../typing/Vvd");
9
+ var _utils = require("../utils");
8
10
  var _miwear = _interopRequireDefault(require("./miwear"));
9
11
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
12
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
10
13
  class VelaMiwear5 extends _miwear.default {
11
- imageType = (() => _Vvd.VelaImageType.VELA_MIWEAR_WATCH_5)();
14
+ imageType = _Vvd.VelaImageType.VELA_MIWEAR_WATCH_5;
12
15
  appDir = '/data/app';
16
+
17
+ /**
18
+ * 使用 am start 启动快应用
19
+ *
20
+ * 应用在运行时 am start 不会重新拉起它:重新安装的 rpk 不生效,跑的还是旧包。所以先停掉再启动
21
+ */
22
+ async startApp(packageName, debug = false) {
23
+ await this.xmsStatus.promise;
24
+ await stopRunningApp(this, packageName);
25
+ return super.startApp(packageName, debug);
26
+ }
13
27
  }
14
- exports.VelaMiwear5 = VelaMiwear5;
28
+
29
+ /**
30
+ * am stop 并等应用退到 [stopped]
31
+ *
32
+ * 正在运行的应用在 am stop 之后依次经过 [toBG]、[background]、[closing]、[stopped],miwear-watch-5 上约 120ms;
33
+ * 没在运行时 am stop 不会打这些状态。命令返回后 1s 内没看到它开始退出就当没在运行,已经开始退出的最多等 5s。
34
+ * 还在启动中([launching])的应用收到的 am stop 会推迟到启动完成后才执行,这种情况不处理。
35
+ * 放在类外面:私有成员会让类按名义比较类型,ide-core 里响应式的设备条目就不能赋给 SelectedDevice 了
36
+ */
37
+ exports.VelaMiwear5 = VelaMiwear5;
38
+ function stopRunningApp(instance, packageName) {
39
+ const {
40
+ sn,
41
+ vvdName,
42
+ logger,
43
+ stdoutReadline
44
+ } = instance;
45
+ const stateFlag = new RegExp(`quickapp_state_trans: ${(0, _utils.escapeRegExp)(packageName)}: \\[\\w+\\]-->\\[(\\w+)\\]`);
46
+ return new Promise(resolve => {
47
+ let quietTimer;
48
+ let maxTimer;
49
+ let finished = false;
50
+ const done = () => {
51
+ if (finished) return;
52
+ finished = true;
53
+ clearTimeout(quietTimer);
54
+ clearTimeout(maxTimer);
55
+ stdoutReadline.off('line', func);
56
+ resolve();
57
+ };
58
+ const func = msg => {
59
+ const state = msg.match(stateFlag)?.[1];
60
+ if (!state) return;
61
+ if (state === 'stopped') {
62
+ logger(`${packageName} stopped on ${vvdName}`);
63
+ done();
64
+ return;
65
+ }
66
+ // 已经开始退出,等到 [stopped]
67
+ clearTimeout(quietTimer);
68
+ if (!maxTimer) {
69
+ maxTimer = setTimeout(() => {
70
+ logger(`${packageName} not stopped on ${vvdName} in 5s, start it anyway`);
71
+ done();
72
+ }, 5 * 1000);
73
+ }
74
+ };
75
+ stdoutReadline.on('line', func);
76
+ const stopCmd = `adb -s ${sn} shell am stop ${packageName}`;
77
+ logger(`Excuting: ${stopCmd}`);
78
+ adbMiwt.execAdbCmdAsync(stopCmd).then(() => {
79
+ if (!finished && !maxTimer) quietTimer = setTimeout(done, 1000);
80
+ }).catch(e => {
81
+ logger(`${stopCmd} failed: ${e}`);
82
+ done();
83
+ });
84
+ });
85
+ }
@@ -7,12 +7,11 @@ exports.OpenSmartspeaker5 = void 0;
7
7
  var _Vvd = require("../typing/Vvd");
8
8
  var _utils = require("../utils");
9
9
  var _miwear = require("./miwear5");
10
- var adbMiwt = _interopRequireWildcard(require("@miwt/adb"));
10
+ var adbMiwt = _interopRequireWildcard(require("@aiot-toolkit/adb"));
11
11
  var _util = require("util");
12
- function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
13
- function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
12
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
14
13
  class OpenSmartspeaker5 extends _miwear.VelaMiwear5 {
15
- imageType = (() => _Vvd.VelaImageType.OPENVELA_SMARTSPEAKER_5)();
14
+ imageType = _Vvd.VelaImageType.OPENVELA_SMARTSPEAKER_5;
16
15
  appDir = '/data/app';
17
16
  xmsInitedFlag = /AMS/;
18
17
  static appStartedFlag = /Start main loop/;
@@ -4,17 +4,16 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
- var adbMiwt = _interopRequireWildcard(require("@miwt/adb"));
7
+ var adbMiwt = _interopRequireWildcard(require("@aiot-toolkit/adb"));
8
8
  var _Vvd = require("../typing/Vvd");
9
9
  var _common = _interopRequireDefault(require("./common"));
10
10
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
11
- function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
12
- function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
11
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
13
12
  /**
14
13
  * 不带 miwear 的 4.0 镜像
15
14
  */
16
15
  class PreInstance extends _common.default {
17
- imageType = (() => _Vvd.VelaImageType.PRE)();
16
+ imageType = _Vvd.VelaImageType.PRE;
18
17
  appDir = '/data/quickapp/app';
19
18
  xmsInitedFlag = /(NSH)/;
20
19
  async install(rpkPath, opt) {
@@ -43,8 +42,7 @@ class PreInstance extends _common.default {
43
42
  * 通过vapp命令启动,调试时需额外配置--jsdebugger参数
44
43
  * @param options
45
44
  */
46
- async startApp(packageName) {
47
- let debug = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
45
+ async startApp(packageName, debug = false) {
48
46
  try {
49
47
  let vappCmd = `adb -s ${this.sn} shell vapp app/${packageName} &`;
50
48
  if (debug) {
@@ -62,8 +60,7 @@ class PreInstance extends _common.default {
62
60
  async closeApp() {
63
61
  await this.reboot();
64
62
  }
65
- async reloadApp(appName) {
66
- let debug = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
63
+ async reloadApp(appName, debug = false) {
67
64
  await this.reboot();
68
65
  this.startApp(appName, debug);
69
66
  }
@@ -10,8 +10,33 @@ export declare class Vela5Instance extends MiwearInstance {
10
10
  * @param targeRpk 快应用的rpk文件路径
11
11
  */
12
12
  install(targeRpk: string): Promise<void>;
13
- /** 使用 am start 启动快应用 */
13
+ /**
14
+ * 使用 pm 卸载快应用
15
+ *
16
+ * 不能沿用 MiwearInstance 等 `uninstalled app:` 日志的做法:vela 5 镜像卸载时不打印这行,
17
+ * 会一直等到 2 分钟超时。卸载结果直接在 pm 的返回里:
18
+ * onUninstallResult: com.application.watch.demo(success 0)
19
+ * @param packageName 快应用的包名
20
+ */
21
+ uninstall(packageName: string): Promise<void>;
22
+ /**
23
+ * 使用 am start 启动快应用
24
+ *
25
+ * 应用已经在运行时(刚在前台跑过,又装了一次),am start 只把它的任务切到前台(switchTaskToActive),
26
+ * 不会重新拉起,也不再打 [resumed]:刚装的 rpk 不生效,这里还要等满 15s 报 Timeout。
27
+ * 这时先 am stop,等旧实例 [destroyed] 再启动一次。
28
+ * 旧实例正在退出时(刚 am stop、刚覆盖安装)执行的 am start 会被它带走:随后打出 [destroyed]、回到主界面,
29
+ * 应用没起来。这种情况也在 [destroyed] 之后再启动一次
30
+ */
14
31
  startApp(packageName: string): Promise<void>;
32
+ /**
33
+ * 重新启动快应用
34
+ *
35
+ * 不能沿用 MiwearInstance 的 am stop、等 500ms、再 am start:vela-watch-6 上 am stop 之后约 1.4s
36
+ * 旧实例才 [destroyed],500ms 后的 am start 会被它带走,应用反而被关掉。startApp 遇到应用在运行会先停再启动。
37
+ * 和 MiwearInstance 一样不往外抛错,只记日志
38
+ */
39
+ reloadApp(packageName: string): Promise<void>;
15
40
  /** 重启模拟器 */
16
41
  reboot(): Promise<void>;
17
42
  closeApp(appName: string): Promise<void>;
@@ -6,17 +6,17 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.Vela5Instance = void 0;
7
7
  var _shared = require("../shared");
8
8
  var _Vvd = require("../typing/Vvd");
9
+ var _utils = require("../utils");
9
10
  var _logcat = require("../vvd/logcat");
10
11
  var _miwear = _interopRequireDefault(require("./miwear"));
11
- var adbMiwt = _interopRequireWildcard(require("@miwt/adb"));
12
+ var adbMiwt = _interopRequireWildcard(require("@aiot-toolkit/adb"));
12
13
  var _util = require("util");
13
- function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
14
- function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
14
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
15
15
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
16
16
  class Vela5Instance extends _miwear.default {
17
17
  xmsInitedFlag = /booting completed|Boot completed/;
18
18
  static appStartedFlag = /Start main loop|reportActivityStatus called by .+? \[resumed\]/;
19
- imageType = (() => _Vvd.VelaImageType.VELA_WATCH_5)();
19
+ imageType = _Vvd.VelaImageType.VELA_WATCH_5;
20
20
  appDir = '/data/app';
21
21
 
22
22
  /**
@@ -39,40 +39,134 @@ class Vela5Instance extends _miwear.default {
39
39
  }
40
40
  }
41
41
 
42
- /** 使用 am start 启动快应用 */
42
+ /**
43
+ * 使用 pm 卸载快应用
44
+ *
45
+ * 不能沿用 MiwearInstance 等 `uninstalled app:` 日志的做法:vela 5 镜像卸载时不打印这行,
46
+ * 会一直等到 2 分钟超时。卸载结果直接在 pm 的返回里:
47
+ * onUninstallResult: com.application.watch.demo(success 0)
48
+ * @param packageName 快应用的包名
49
+ */
50
+ async uninstall(packageName) {
51
+ await this.xmsStatus.promise;
52
+ const uninstallCmd = `adb -s ${this.sn} shell pm uninstall ${packageName}`;
53
+ this.logger(`Excuting: ${uninstallCmd}`);
54
+ const res = await adbMiwt.execAdbCmdAsync(uninstallCmd, {
55
+ encoding: 'utf-8',
56
+ timeoutMs: 30 * 1000
57
+ });
58
+ this.logger(`Uninstall result: ${res}`);
59
+ if (res.includes('(success 0)')) {
60
+ return Promise.resolve();
61
+ } else {
62
+ return Promise.reject(res);
63
+ }
64
+ }
65
+
66
+ /**
67
+ * 使用 am start 启动快应用
68
+ *
69
+ * 应用已经在运行时(刚在前台跑过,又装了一次),am start 只把它的任务切到前台(switchTaskToActive),
70
+ * 不会重新拉起,也不再打 [resumed]:刚装的 rpk 不生效,这里还要等满 15s 报 Timeout。
71
+ * 这时先 am stop,等旧实例 [destroyed] 再启动一次。
72
+ * 旧实例正在退出时(刚 am stop、刚覆盖安装)执行的 am start 会被它带走:随后打出 [destroyed]、回到主界面,
73
+ * 应用没起来。这种情况也在 [destroyed] 之后再启动一次
74
+ */
43
75
  async startApp(packageName) {
76
+ const escapedPackageName = (0, _utils.escapeRegExp)(packageName);
77
+ // 只认这个应用自己的 [resumed]:监听比以前开始得早,别的界面(如表盘)的 [resumed] 不能算数
78
+ const startedFlag = new RegExp(`Start main loop|reportActivityStatus called by ${escapedPackageName}/\\S+ \\[resumed\\]`);
79
+ const switchedFlag = new RegExp(`switchTaskToActive taskTag:${escapedPackageName}(\\s|$)`);
80
+ const destroyedFlag = new RegExp(`reportActivityStatus called by ${escapedPackageName}/\\S+ \\[destroyed\\]`);
81
+ const manifestFailedFlag = new RegExp(`Failed to open: .+?/${escapedPackageName}/manifest\\.json`);
44
82
  return new Promise(async (resolve, reject) => {
45
- let timer = setTimeout(() => {
46
- this.stdoutReadline.off('line', func);
47
- this.logger(`Start ${packageName} for ${this.vvdName} timeout`);
48
- reject('Timeout');
49
- }, 15 * 1000);
50
- await this.xmsStatus.promise;
51
- const startCmd = `adb -s ${this.sn} shell am start ${packageName}`;
52
- this.logger(`Excuting: ${startCmd}`);
53
- await adbMiwt.execAdbCmdAsync(startCmd);
83
+ let timer;
84
+ // 在等旧实例退出:am stop 之后它会先暂停又恢复一下,打一次 [resumed],不能当成启动成功
85
+ let stopping = false;
86
+ // 只重新启动一次,还不行就等超时
87
+ let restarted = false;
54
88
  const clearFn = () => {
55
89
  clearTimeout(timer);
56
90
  this.stdoutReadline.off('line', func);
57
91
  };
92
+ const armTimer = () => {
93
+ clearTimeout(timer);
94
+ timer = setTimeout(() => {
95
+ clearFn();
96
+ this.logger(`Start ${packageName} for ${this.vvdName} timeout`);
97
+ reject('Timeout');
98
+ }, 15 * 1000);
99
+ };
100
+ const exec = cmd => {
101
+ this.logger(`Excuting: ${cmd}`);
102
+ adbMiwt.execAdbCmdAsync(cmd).catch(error => {
103
+ // 命令本身失败就直接报出来,不用再等超时
104
+ clearFn();
105
+ reject(error);
106
+ });
107
+ };
108
+ const startAgain = reason => {
109
+ restarted = true;
110
+ this.logger(`${packageName} ${reason} on ${this.vvdName}, start it again`);
111
+ armTimer();
112
+ exec(`adb -s ${this.sn} shell am start ${packageName}`);
113
+ };
58
114
  const func = msg => {
59
- if (Vela5Instance.appStartedFlag.test(msg)) {
115
+ if (stopping) {
116
+ if (destroyedFlag.test(msg)) {
117
+ stopping = false;
118
+ startAgain('stopped');
119
+ }
120
+ return;
121
+ }
122
+ if (startedFlag.test(msg)) {
60
123
  this.logger(`Start ${packageName} for ${this.vvdName} successfully`);
61
124
  clearFn();
62
125
  resolve();
126
+ return;
63
127
  }
64
- const escapedPackageName = packageName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
65
- const reg = new RegExp(`Failed to open: .+?/${escapedPackageName}/manifest\.json`);
66
- if (reg.test(msg)) {
128
+ if (manifestFailedFlag.test(msg)) {
67
129
  this.logger(`Failed Start ${packageName} for ${this.vvdName}`);
68
130
  clearFn();
69
131
  reject(_shared.RpkStartFailedReason.getManifestFailed);
132
+ return;
133
+ }
134
+ if (restarted) return;
135
+ if (switchedFlag.test(msg)) {
136
+ this.logger(`${packageName} is already running on ${this.vvdName}, stop it first`);
137
+ stopping = true;
138
+ armTimer();
139
+ exec(`adb -s ${this.sn} shell am stop ${packageName}`);
140
+ } else if (destroyedFlag.test(msg)) {
141
+ startAgain('exited right after am start');
70
142
  }
71
143
  };
144
+ armTimer();
145
+ await this.xmsStatus.promise;
146
+
147
+ // 必须在执行 am start 之前开始监听:启动完成的日志和 am start 返回几乎同时到达,
148
+ // vela-watch-6 上实测只比命令返回晚 20ms 左右。以前等命令返回才开始监听,
149
+ // Windows 上 adb 返回得慢,这行日志先到就错过了,应用明明已经运行,还要等到 15s 报超时
72
150
  this.stdoutReadline.on('line', func);
151
+ exec(`adb -s ${this.sn} shell am start ${packageName}`);
73
152
  });
74
153
  }
75
154
 
155
+ /**
156
+ * 重新启动快应用
157
+ *
158
+ * 不能沿用 MiwearInstance 的 am stop、等 500ms、再 am start:vela-watch-6 上 am stop 之后约 1.4s
159
+ * 旧实例才 [destroyed],500ms 后的 am start 会被它带走,应用反而被关掉。startApp 遇到应用在运行会先停再启动。
160
+ * 和 MiwearInstance 一样不往外抛错,只记日志
161
+ */
162
+ async reloadApp(packageName) {
163
+ try {
164
+ await this.startApp(packageName);
165
+ } catch (e) {
166
+ this.logger(`Reload ${packageName} for ${this.vvdName} failed: ${e}`);
167
+ }
168
+ }
169
+
76
170
  /** 重启模拟器 */
77
171
  async reboot() {
78
172
  const rebootCmd = `adb -s ${this.sn} shell reboot`;
@@ -6,6 +6,14 @@ import { VelaImageType } from '../typing/Vvd';
6
6
  export declare function isVelaImageType(value: any): value is VelaImageType;
7
7
  export declare function isMiwearImageType(val: VelaImageType): boolean;
8
8
  export declare function getDefaultImage(): VelaImageType;
9
+ /**
10
+ * 皮肤能否用于该镜像
11
+ * @param skinName 皮肤名称(皮肤目录名)
12
+ * @param imageType 镜像类型;不知道镜像类型时,只适配部分镜像的皮肤一律不可用
13
+ */
14
+ export declare function isSkinAvailableForImage(skinName: string, imageType?: VelaImageType): boolean;
15
+ /** 皮肤在界面上显示的名字;没登记的就是皮肤名本身 */
16
+ export declare function getSkinDisplayName(skinName: string): string;
9
17
  export declare enum RpkStartFailedReason {
10
18
  getManifestFailed = "Get app manifest.json failed"
11
19
  }
@@ -5,7 +5,9 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.RpkStartFailedReason = exports.RpkInstallFailedReason = void 0;
7
7
  exports.getDefaultImage = getDefaultImage;
8
+ exports.getSkinDisplayName = getSkinDisplayName;
8
9
  exports.isMiwearImageType = isMiwearImageType;
10
+ exports.isSkinAvailableForImage = isSkinAvailableForImage;
9
11
  exports.isVelaImageType = isVelaImageType;
10
12
  var _Vvd = require("../typing/Vvd");
11
13
  /**
@@ -22,6 +24,37 @@ function isMiwearImageType(val) {
22
24
  function getDefaultImage() {
23
25
  return _Vvd.VelaImageType.VELA_MIWEAR_WATCH_5;
24
26
  }
27
+
28
+ /**
29
+ * 只适配部分镜像的皮肤:皮肤名(皮肤目录名)-> 可以使用它的镜像
30
+ *
31
+ * 皮肤资源是所有镜像共用的一个包,更新后新皮肤会出现在所有列皮肤的地方。
32
+ * 只适配特定镜像的皮肤登记在这里,列皮肤时按镜像过滤;没登记的皮肤不限制镜像
33
+ */
34
+ const skinImageTypes = new Map([['q64', [_Vvd.VelaImageType.VELA_WATCH_6]]]);
35
+
36
+ /**
37
+ * 皮肤能否用于该镜像
38
+ * @param skinName 皮肤名称(皮肤目录名)
39
+ * @param imageType 镜像类型;不知道镜像类型时,只适配部分镜像的皮肤一律不可用
40
+ */
41
+ function isSkinAvailableForImage(skinName, imageType) {
42
+ const imageTypes = skinImageTypes.get(skinName);
43
+ return !imageTypes || !!imageType && imageTypes.includes(imageType);
44
+ }
45
+
46
+ /**
47
+ * 界面上显示的皮肤名:皮肤名(皮肤目录名)-> 显示名
48
+ *
49
+ * 皮肤包里的目录名不一定适合直接给用户看(如 q64),在这里登记对外显示的名字。只改显示:
50
+ * config.ini 的 skin.name、skin.path 和上面按镜像过滤都还用目录名,已经建好的模拟器不受影响
51
+ */
52
+ const skinDisplayNames = new Map([['q64', 'xiaomi_watch_6']]);
53
+
54
+ /** 皮肤在界面上显示的名字;没登记的就是皮肤名本身 */
55
+ function getSkinDisplayName(skinName) {
56
+ return skinDisplayNames.get(skinName) ?? skinName;
57
+ }
25
58
  let RpkStartFailedReason = exports.RpkStartFailedReason = /*#__PURE__*/function (RpkStartFailedReason) {
26
59
  RpkStartFailedReason["getManifestFailed"] = "Get app manifest.json failed";
27
60
  return RpkStartFailedReason;
@@ -11,6 +11,7 @@ export declare enum VelaImageType {
11
11
  OPENVELA_SMARTSPEAKER_5 = "openvela-smartspeaker-5.0",
12
12
  VELA_MIWEAR_MINISOUND_5 = "vela-miwear-minisound-5.0",
13
13
  VELA_MIWEAR_WATCH_5 = "vela-miwear-watch-5.0",
14
+ VELA_WATCH_6 = "vela-watch-6.0",
14
15
  VELA_WATCH_5 = "vela-watch-5.0",
15
16
  REL = "vela-release-4.0",
16
17
  PRE = "vela-pre-4.0",
@@ -114,4 +115,5 @@ export type SDKDownloadOpt = {
114
115
  force?: boolean;
115
116
  parallelStreams?: number;
116
117
  imageTypeArr?: VelaImageType[];
118
+ onExtract?: (name: string) => void;
117
119
  } & Parameters<typeof import('ipull').downloadSequence>[0];
package/lib/typing/Vvd.js CHANGED
@@ -13,6 +13,7 @@ let VelaImageType = exports.VelaImageType = /*#__PURE__*/function (VelaImageType
13
13
  VelaImageType["OPENVELA_SMARTSPEAKER_5"] = "openvela-smartspeaker-5.0";
14
14
  VelaImageType["VELA_MIWEAR_MINISOUND_5"] = "vela-miwear-minisound-5.0";
15
15
  VelaImageType["VELA_MIWEAR_WATCH_5"] = "vela-miwear-watch-5.0";
16
+ VelaImageType["VELA_WATCH_6"] = "vela-watch-6.0";
16
17
  VelaImageType["VELA_WATCH_5"] = "vela-watch-5.0";
17
18
  VelaImageType["REL"] = "vela-release-4.0";
18
19
  VelaImageType["PRE"] = "vela-pre-4.0";
@@ -7,8 +7,31 @@ export declare function getSystemArch(): string | void;
7
7
  export declare function killProcessByPid(pid: string): void;
8
8
  /**
9
9
  * 根据命令杀死进程
10
+ *
11
+ * @deprecated 会杀掉命令行里任何位置含有 cmd 的进程(find-process 按子串匹配完整命令行),
12
+ * 结束模拟器请用 killEmulatorProcess
10
13
  */
11
14
  export declare function killProcessByCmd(cmd: string): Promise<void>;
15
+ /** 转义成正则里的字面量 */
16
+ export declare function escapeRegExp(text: string): string;
17
+ /**
18
+ * 是不是模拟器 vvdName 自己的进程:可执行文件是 emulator 或 qemu-system-*,
19
+ * 命令行里有完整的 `-avd <vvdName>` 参数
20
+ */
21
+ export declare function isEmulatorProcessOf(proc: {
22
+ name?: string;
23
+ bin?: string;
24
+ cmd?: string;
25
+ }, vvdName: string): boolean;
26
+ /**
27
+ * 强制结束模拟器 vvdName 的进程(poweroff 失败或超时后的兜底)
28
+ *
29
+ * 以前用 killProcessByCmd(vvdName):命令行里任何位置含有这个名字的进程都会被强杀,Windows 上还连子进程一起杀。
30
+ * 一台的名字包含在另一台的名字里时(watch5 / watch50),关一台会把另一台也杀掉;名字短到会出现在 IDE 进程的
31
+ * 命令行里时(例如纯数字),IDE 自己的进程也会被杀,弹「共享后台进程意外终止」后整个 IDE 退出。
32
+ * 现在只结束 isEmulatorProcessOf 认定的进程
33
+ */
34
+ export declare function killEmulatorProcess(vvdName: string): Promise<void>;
12
35
  /** 延迟函数 */
13
36
  export declare function sleep(time: number): Promise<void>;
14
37
  /**
@@ -4,8 +4,11 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.delayRun = delayRun;
7
+ exports.escapeRegExp = escapeRegExp;
7
8
  exports.getEvenPort = getEvenPort;
8
9
  exports.getSystemArch = getSystemArch;
10
+ exports.isEmulatorProcessOf = isEmulatorProcessOf;
11
+ exports.killEmulatorProcess = killEmulatorProcess;
9
12
  exports.killProcessByCmd = killProcessByCmd;
10
13
  exports.killProcessByPid = killProcessByPid;
11
14
  exports.sleep = sleep;
@@ -58,6 +61,9 @@ function killProcessByPid(pid) {
58
61
 
59
62
  /**
60
63
  * 根据命令杀死进程
64
+ *
65
+ * @deprecated 会杀掉命令行里任何位置含有 cmd 的进程(find-process 按子串匹配完整命令行),
66
+ * 结束模拟器请用 killEmulatorProcess
61
67
  */
62
68
  async function killProcessByCmd(cmd) {
63
69
  if (!cmd) return;
@@ -71,6 +77,40 @@ async function killProcessByCmd(cmd) {
71
77
  }
72
78
  }
73
79
 
80
+ /** 转义成正则里的字面量 */
81
+ function escapeRegExp(text) {
82
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
83
+ }
84
+
85
+ /**
86
+ * 是不是模拟器 vvdName 自己的进程:可执行文件是 emulator 或 qemu-system-*,
87
+ * 命令行里有完整的 `-avd <vvdName>` 参数
88
+ */
89
+ function isEmulatorProcessOf(proc, vvdName) {
90
+ // 去掉目录只留文件名,Windows 路径也一样处理
91
+ const exe = String(proc.bin || proc.name || '').replace(/^.*[\\/]/, '');
92
+ if (!/^(emulator|qemu-system)/i.test(exe)) return false;
93
+ return new RegExp(`(^|\\s)-avd\\s+"?${escapeRegExp(vvdName)}"?(\\s|$)`).test(proc.cmd || '');
94
+ }
95
+
96
+ /**
97
+ * 强制结束模拟器 vvdName 的进程(poweroff 失败或超时后的兜底)
98
+ *
99
+ * 以前用 killProcessByCmd(vvdName):命令行里任何位置含有这个名字的进程都会被强杀,Windows 上还连子进程一起杀。
100
+ * 一台的名字包含在另一台的名字里时(watch5 / watch50),关一台会把另一台也杀掉;名字短到会出现在 IDE 进程的
101
+ * 命令行里时(例如纯数字),IDE 自己的进程也会被杀,弹「共享后台进程意外终止」后整个 IDE 退出。
102
+ * 现在只结束 isEmulatorProcessOf 认定的进程
103
+ */
104
+ async function killEmulatorProcess(vvdName) {
105
+ if (!vvdName) return;
106
+ try {
107
+ const list = await (0, _findProcess.default)('name', escapeRegExp(vvdName));
108
+ list.filter(item => isEmulatorProcessOf(item, vvdName)).forEach(item => killProcessByPid(item.pid.toString()));
109
+ } catch (e) {
110
+ console.error(`kill emulator ${vvdName} get error: ${e}`);
111
+ }
112
+ }
113
+
74
114
  /** 延迟函数 */
75
115
  async function sleep(time) {
76
116
  return new Promise(resolve => setTimeout(resolve, time));
@@ -82,10 +122,7 @@ async function sleep(time) {
82
122
  * @param {Number=} maxCount 最大重试次数
83
123
  * @param {number=} duration 每次重试的间隔
84
124
  */
85
- async function tryRun(task) {
86
- let maxCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 5;
87
- let duration = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1000;
88
- let currentCount = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
125
+ async function tryRun(task, maxCount = 5, duration = 1000, currentCount = 0) {
89
126
  if (currentCount > maxCount) return false;
90
127
  return Boolean(await task()) || (await delayRun(() => tryRun(task, maxCount, duration, currentCount + 1), duration));
91
128
  }
@@ -96,8 +133,7 @@ async function tryRun(task) {
96
133
  * @param duration
97
134
  * @returns
98
135
  */
99
- async function delayRun(task) {
100
- let duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;
136
+ async function delayRun(task, duration = 1000) {
101
137
  return new Promise(resolve => {
102
138
  setTimeout(async () => {
103
139
  return resolve(task());
@@ -23,7 +23,7 @@ export declare class GrpcEmulator {
23
23
  getAuthMeta(): Metadata;
24
24
  waitForReady(): Promise<boolean>;
25
25
  streamScreenshot(imageFormat?: ImageFormat): Promise<Readable>;
26
- getScreenshot(): Promise<Buffer>;
26
+ getScreenshot(): Promise<Buffer<ArrayBufferLike>>;
27
27
  getStatus(): Promise<unknown>;
28
28
  sendMouse(message: MouseEvent): void;
29
29
  sendKey(data: KeyboardEvent): void;
@@ -18,8 +18,7 @@ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e
18
18
  const AuthorizationKey = exports.AuthorizationKey = 'Authorization';
19
19
  class GrpcEmulator {
20
20
  connected = false;
21
- constructor(eConf, protoPath) {
22
- let ip = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '127.0.0.1';
21
+ constructor(eConf, protoPath, ip = '127.0.0.1') {
23
22
  this.eConf = eConf;
24
23
  this.protoPath = protoPath;
25
24
  this.ip = ip;
@@ -155,8 +154,7 @@ class GrpcEmulator {
155
154
  if (err) console.error(err);
156
155
  });
157
156
  }
158
- showExtendedControls() {
159
- let paneIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
157
+ showExtendedControls(paneIndex = 0) {
160
158
  if (!this.uiClient) return Promise.reject('UiController not available');
161
159
  return new Promise((resolve, reject) => {
162
160
  this.uiClient.showExtendedControls({
@@ -43,8 +43,14 @@ let KeyCodeType = exports.KeyCodeType = /*#__PURE__*/function (KeyCodeType) {
43
43
  return KeyCodeType;
44
44
  }({});
45
45
  let ImageFormatType = exports.ImageFormatType = /*#__PURE__*/function (ImageFormatType) {
46
+ // Portable Network Graphics format
47
+ // (https://en.wikipedia.org/wiki/Portable_Network_Graphics)
46
48
  ImageFormatType[ImageFormatType["PNG"] = 0] = "PNG";
49
+ // Three-channel RGB color model supplemented with a fourth alpha
50
+ // channel. https://en.wikipedia.org/wiki/RGBA_color_model
51
+ // Each pixel consists of 4 bytes.
47
52
  ImageFormatType[ImageFormatType["RGBA8888"] = 1] = "RGBA8888";
53
+ // Three-channel RGB color model, each pixel consists of 3 bytes
48
54
  ImageFormatType[ImageFormatType["RGB888"] = 2] = "RGB888";
49
55
  return ImageFormatType;
50
56
  }({});
@@ -3,7 +3,7 @@ import { IVvdParams, IVvdResourcePaths, SDKParts, SDKDownloadOpt, SkinInfo, Vela
3
3
  import { IStartOptions, IStartWithSerialPort } from '../typing/Instance';
4
4
  import { EmulatorConfig } from '../emulatorutil';
5
5
  import { findInstance } from '../instance';
6
- import type { DownloadFileOptions } from 'ipull';
6
+ import type { BaseDownloadEngine, DownloadEngineMultiDownload, DownloadEngineNodejs, DownloadFileOptions } from 'ipull';
7
7
  import { GrpcEmulator } from './grpc';
8
8
  export declare const isHeadlessEnvironment: () => boolean;
9
9
  export interface StartVvdRes {
@@ -35,8 +35,12 @@ export declare class VvdManager {
35
35
  getVvdDir(vvdName: string): any;
36
36
  /** 根据AVD名字获取模拟器的详细信息 */
37
37
  getVvdInfo(vvdName: string): IVvdParams;
38
- /** 根据名字删除AVD */
39
- deleteVvd(vvdName: string): boolean;
38
+ /**
39
+ * 根据名字删除AVD
40
+ * @param vvdName 模拟器名称
41
+ * @param onError 删除失败时回调失败原因,返回值仍是 false
42
+ */
43
+ deleteVvd(vvdName: string, onError?: (error: unknown) => void): boolean;
40
44
  /** 获取已经创建的模拟器列表 */
41
45
  getVvdList(): IVvdParams[];
42
46
  /** 获取 SDK 子目录 */
@@ -112,11 +116,13 @@ export declare class VvdManager {
112
116
  * console.log('download success')
113
117
  * }
114
118
  */
115
- downloadSDK(opt: SDKDownloadOpt): Promise<import("ipull").DownloadEngineMultiDownload<import("ipull").BaseDownloadEngine> & {
119
+ downloadSDK(opt: SDKDownloadOpt): Promise<DownloadEngineMultiDownload<BaseDownloadEngine> & {
116
120
  downlodPromise: Promise<void>;
117
121
  }>;
118
122
  /** 下载vela系统镜像 */
119
- downloadImage(imageId: VelaImageType, opt?: Partial<DownloadFileOptions>): Promise<import("ipull").DownloadEngineNodejs<import("ipull/dist/download/download-engine/streams/download-engine-write-stream/download-engine-write-stream-nodejs").default> & {
123
+ downloadImage(imageId: VelaImageType, opt?: Partial<DownloadFileOptions>, hooks?: {
124
+ onExtract?: (name: string) => void;
125
+ }): Promise<DownloadEngineNodejs & {
120
126
  downlodPromise: Promise<void>;
121
127
  }>;
122
128
  }