-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
272 lines (255 loc) · 9.26 KB
/
Copy pathindex.js
File metadata and controls
272 lines (255 loc) · 9.26 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
const { View, Property, knownFolders } = require('@nativescript/core');
// Guest bundles ship as `<name>.pocketjs` + `<name>.pak` so the webpack asset
// copy treats the bundle as an opaque asset instead of application source.
const BUNDLE_EXTENSION = '.pocketjs';
const PAK_EXTENSION = '.pak';
const srcProperty = new Property({ name: 'src' });
const viewportWidthProperty = new Property({
name: 'viewportWidth',
defaultValue: 480,
valueConverter: (v) => parseInt(v, 10),
});
const viewportHeightProperty = new Property({
name: 'viewportHeight',
defaultValue: 272,
valueConverter: (v) => parseInt(v, 10),
});
const densityProperty = new Property({
name: 'density',
defaultValue: 0,
valueConverter: (v) => parseInt(v, 10),
});
const tickRateProperty = new Property({
name: 'tickRate',
defaultValue: 60,
valueConverter: (v) => parseInt(v, 10),
});
class PocketView extends View {
createNativeView() {
const scale = UIScreen.mainScreen.scale;
const density = this.density > 0 ? this.density : Math.max(1, Math.min(3, Math.round(scale)));
const view = PocketSurfaceView.surfaceWithLogicalWidthLogicalHeightDensity(
this.viewportWidth,
this.viewportHeight,
density,
);
view.tickRate = this.tickRate > 0 ? this.tickRate : 60;
return view;
}
initNativeView() {
super.initNativeView();
const owner = this;
this.nativeViewProtected.onError = (message) => {
owner.notify({ eventName: 'error', object: owner, message });
};
this.nativeViewProtected.onEffect = (line) => {
let data = line;
try {
data = JSON.parse(line);
} catch (e) {
// Non-JSON lines pass through as strings.
}
owner.notify({ eventName: 'effect', object: owner, data });
};
// Belt and braces: dominative attribute application does not always
// reach the NS property's setNative, so load here too; _loadApp guards
// against running twice.
if (this.src) {
this._loadApp(this.src);
}
}
/** Host -> guest: delivered at the guest's next frame boundary. */
post(message) {
const nativeView = this.nativeViewProtected;
if (!nativeView) {
return;
}
const line = typeof message === 'string' ? message : JSON.stringify(message);
nativeView.postEvent(line);
}
disposeNativeView() {
const nativeView = this.nativeViewProtected;
if (nativeView) {
nativeView.stop();
nativeView.onError = null;
}
super.disposeNativeView();
}
[srcProperty.setNative](value) {
if (value) {
this._loadApp(value);
}
}
_loadApp(src) {
const nativeView = this.nativeViewProtected;
if (!nativeView || this._booted) {
return;
}
this._booted = true;
const base = src.replace(/^~\//, knownFolders.currentApp().path + '/');
const bundlePath = base + BUNDLE_EXTENSION;
const pakPath = base + PAK_EXTENSION;
const pak = NSData.dataWithContentsOfFile(pakPath);
const bundle = NSString.stringWithContentsOfFileEncodingError(
bundlePath,
NSUTF8StringEncoding,
);
if (!pak || !bundle) {
this.notify({
eventName: 'error',
object: this,
message: `pocket app assets not found: ${bundlePath} / ${pakPath}`,
});
return;
}
if (!nativeView.loadPak(pak)) {
return;
}
const label = base.split('/').pop() || 'app';
if (!nativeView.evalBundleLabel(bundle, label)) {
return;
}
nativeView.start();
this.notify({ eventName: 'loaded', object: this });
}
}
srcProperty.register(PocketView);
viewportWidthProperty.register(PocketView);
viewportHeightProperty.register(PocketView);
densityProperty.register(PocketView);
tickRateProperty.register(PocketView);
exports.PocketView = PocketView;
// Direction B: the NativeScript runtime IS the guest engine. The pocket core
// runs native-side; globalThis.ui delegates each op over the bridge, the
// guest bundle evaluates in THIS JS context (so it can reach the whole iOS
// platform through the NativeScript metadata bindings), and the display link
// calls back into globalThis.frame each tick.
class PocketHostView extends PocketView {
createNativeView() {
const scale = UIScreen.mainScreen.scale;
const density = this.density > 0 ? this.density : Math.max(1, Math.min(3, Math.round(scale)));
const view = PocketSurfaceView.externalSurfaceWithLogicalWidthLogicalHeightDensity(
this.viewportWidth,
this.viewportHeight,
density,
);
view.tickRate = this.tickRate > 0 ? this.tickRate : 60;
return view;
}
disposeNativeView() {
const nativeView = this.nativeViewProtected;
if (nativeView) {
nativeView.onTick = null;
}
super.disposeNativeView();
}
// Inherited [srcProperty.setNative] calls _loadApp; external mode boots.
_loadApp(src) {
if (this.nativeViewProtected && !this._booted) {
this._booted = true;
this._boot(src);
}
}
_mountUi(nativeView) {
const textures = {};
const textureTable = nativeView.uiTextures();
const textureKeys = textureTable.allKeys;
for (let i = 0; i < textureKeys.count; i++) {
const key = textureKeys.objectAtIndex(i);
textures[String(key)] = Number(textureTable.objectForKey(key));
}
const sprites = {};
const spriteList = nativeView.uiSprites();
for (let i = 0; i < spriteList.count; i++) {
const record = spriteList.objectAtIndex(i);
sprites[String(record.objectForKey('name'))] = {
handle: Number(record.objectForKey('handle')),
frames: Number(record.objectForKey('frames')),
cols: Number(record.objectForKey('cols')),
step: Number(record.objectForKey('step')),
};
}
globalThis.ui = {
// Platform-contract identity: bundles built from a resolved ios-dev plan
// bake this pair and refuse to mount on a host that publishes anything
// else (framework/src/host.ts assertNativeHostContract in pocketjs).
__host: 'ios-dev',
__hostAbi: 7,
__viewport: { w: this.viewportWidth, h: this.viewportHeight },
__textures: textures,
__sprites: sprites,
createNode: (type) => nativeView.uiCreateNode(type),
destroyNode: (id) => nativeView.uiDestroyNode(id),
insertBefore: (parent, child, anchor) =>
nativeView.uiInsertBeforeChildAnchor(parent, child, anchor),
removeChild: (parent, child) => nativeView.uiRemoveChildChild(parent, child),
setStyle: (id, style) => nativeView.uiSetStyleStyle(id, style),
setProp: (id, prop, value) => nativeView.uiSetPropPropValue(id, prop, value),
setText: (id, text) => nativeView.uiSetTextText(id, String(text)),
replaceText: (id, text) => nativeView.uiReplaceTextText(id, String(text)),
measureText: (text, fontSlot) => nativeView.uiMeasureTextFontSlot(String(text), fontSlot),
uploadTexture: () => -1,
setImage: (id, texture) => nativeView.uiSetImageTexture(id, texture),
setSprite: (id, atlas, frames, cols, step) =>
nativeView.uiSetSpriteAtlasFramesColsStep(id, atlas, frames, cols, step),
animate: (id, prop, to, dur, easing, delay) =>
nativeView.uiAnimatePropToDurEasingDelay(id, prop, to, dur, easing, delay),
cancelAnim: (animId) => nativeView.uiCancelAnim(animId),
setFocus: (id) => nativeView.uiSetFocus(id),
setActive: (id, active) => nativeView.uiSetActiveActive(id, active ? 1 : 0),
hitTest: (x, y) => nativeView.uiHitTestBoundsY(x, y),
hitTestBounds: (x, y) => nativeView.uiHitTestBoundsY(x, y),
svcOpen: (name) => !!nativeView.uiSvcOpen(String(name)),
svcPoll: () => {
const batch = nativeView.uiSvcPoll();
return batch == null ? null : String(batch);
},
svcSend: (line) => nativeView.uiSvcSend(String(line)),
};
}
_boot(src) {
const nativeView = this.nativeViewProtected;
if (!nativeView) {
return;
}
const base = src.replace(/^~\//, knownFolders.currentApp().path + '/');
const pak = NSData.dataWithContentsOfFile(base + PAK_EXTENSION);
const bundle = NSString.stringWithContentsOfFileEncodingError(
base + BUNDLE_EXTENSION,
NSUTF8StringEncoding,
);
if (!pak || !bundle) {
this.notify({ eventName: 'error', object: this, message: `pocket app assets not found at ${base}` });
return;
}
if (!nativeView.loadPak(pak)) {
return;
}
this._mountUi(nativeView);
// The guest bundle evaluates in the NativeScript runtime itself.
new Function(String(bundle))();
if (typeof globalThis.frame !== 'function') {
this.notify({ eventName: 'error', object: this, message: 'bundle installed no frame()' });
return;
}
let tickError = false;
nativeView.onTick = (buttons, analog, touches) => {
const words = [];
for (let i = 0; i < touches.count; i++) {
words.push(Number(touches.objectAtIndex(i)));
}
try {
globalThis.frame(buttons, analog, words);
} catch (error) {
if (!tickError) {
tickError = true;
console.error('[pocket-host] frame() threw:', error && error.message, error && error.stack);
}
}
};
nativeView.start();
console.log('[pocket-host] measureText check:', globalThis.ui.measureText('Ping host', 0));
this.notify({ eventName: 'loaded', object: this });
}
}
exports.PocketHostView = PocketHostView;