forked from microsoft/pxt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmds.ts
More file actions
416 lines (392 loc) · 17.1 KB
/
cmds.ts
File metadata and controls
416 lines (392 loc) · 17.1 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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/// <reference path="../../built/pxtlib.d.ts"/>
import * as core from "./core";
import * as electron from "./electron";
import * as pkg from "./package";
import * as hidbridge from "./hidbridge";
import Cloud = pxt.Cloud;
function browserDownloadAsync(text: string, name: string, contentType: string): Promise<void> {
pxt.BrowserUtils.browserDownloadBinText(
text,
name,
contentType,
undefined,
e => core.errorNotification(lf("saving file failed..."))
);
return Promise.resolve();
}
export function browserDownloadDeployCoreAsync(resp: pxtc.CompileResult): Promise<void> {
let url = ""
const ext = pxt.outputName().replace(/[^.]*/, "")
const out = resp.outfiles[pxt.outputName()]
const fn = pkg.genFileName(ext);
const userContext = pxt.BrowserUtils.isBrowserDownloadWithinUserContext();
if (userContext) {
url = pxt.BrowserUtils.toDownloadDataUri(pxt.isOutputText() ? ts.pxtc.encodeBase64(out) : out, pxt.appTarget.compile.hexMimeType);
} else if (!pxt.isOutputText()) {
pxt.debug('saving ' + fn)
url = pxt.BrowserUtils.browserDownloadBase64(
out,
fn,
"application/x-uf2",
resp.userContextWindow,
e => core.errorNotification(lf("saving file failed..."))
);
} else {
pxt.debug('saving ' + fn)
url = pxt.BrowserUtils.browserDownloadBinText(
out,
fn,
pxt.appTarget.compile.hexMimeType,
resp.userContextWindow,
e => core.errorNotification(lf("saving file failed..."))
);
}
if (!resp.success) {
return Promise.resolve();
}
if (resp.saveOnly && userContext) return pxt.commands.showUploadInstructionsAsync(fn, url, core.confirmAsync); // save does the same as download as far iOS is concerned
if (resp.saveOnly || pxt.BrowserUtils.isBrowserDownloadInSameWindow() && !userContext) return Promise.resolve();
else return pxt.commands.showUploadInstructionsAsync(fn, url, core.confirmAsync);
}
function showUploadInstructionsAsync(fn: string, url: string, confirmAsync: (options: any) => Promise<number>): Promise<void> {
const boardName = pxt.appTarget.appTheme.boardName || lf("device");
const boardDriveName = pxt.appTarget.appTheme.driveDisplayName || pxt.appTarget.compile.driveName || "???";
// https://msdn.microsoft.com/en-us/library/cc848897.aspx
// "For security reasons, data URIs are restricted to downloaded resources.
// Data URIs cannot be used for navigation, for scripting, or to populate frame or iframe elements"
const userDownload = pxt.BrowserUtils.isBrowserDownloadWithinUserContext();
const downloadAgain = !pxt.BrowserUtils.isIE() && !pxt.BrowserUtils.isEdge();
const docUrl = pxt.appTarget.appTheme.usbDocs;
const saveAs = pxt.BrowserUtils.hasSaveAs();
const ext = pxt.appTarget.compile.useUF2 ? ".uf2" : ".hex";
const body = userDownload ? lf("Click 'Download' to open the {0} app.", pxt.appTarget.appTheme.boardName) :
saveAs ? lf("Click 'Save As' and save the {0} file to the {1} drive to transfer the code into your {2}.",
ext,
boardDriveName, boardName)
: lf("Move the {0} file to the {1} drive to transfer the code into your {2}.",
ext,
boardDriveName, boardName);
const timeout = pxt.BrowserUtils.isBrowserDownloadWithinUserContext() ? 0 : 10000;
return confirmAsync({
header: userDownload ? lf("Download ready...") : lf("Download completed..."),
body,
hasCloseIcon: true,
hideCancel: true,
hideAgree: true,
buttons: [downloadAgain ? {
label: userDownload ? lf("Download") : fn,
icon: "download",
class: `${userDownload ? "primary" : "lightgrey"}`,
url,
fileName: fn
} : undefined, docUrl ? {
label: lf("Help"),
icon: "help",
class: "lightgrey",
url: docUrl
} : undefined],
timeout
}).then(() => { });
}
export function nativeHostPostMessageFunction(): (msg: pxt.editor.NativeHostMessage) => void {
const webkit = (<any>window).webkit;
if (webkit
&& webkit.messageHandlers
&& webkit.messageHandlers.host
&& webkit.messageHandlers.host.postMessage)
return msg => webkit.messageHandlers.host.postMessage(msg);
const android = (<any>window).android;
if (android && android.postMessage)
return msg => android.postMessage(JSON.stringify(msg));
return undefined;
}
export function isNativeHost(): boolean {
return !!nativeHostPostMessageFunction();
}
function nativeHostDeployCoreAsync(resp: pxtc.CompileResult): Promise<void> {
pxt.debug(`native deploy`)
core.infoNotification(lf("Flashing device..."));
const out = resp.outfiles[pxt.outputName()];
const nativePostMessage = nativeHostPostMessageFunction();
nativePostMessage(<pxt.editor.NativeHostMessage>{
name: resp.downloadFileBaseName,
download: out
})
return Promise.resolve();
}
function nativeHostSaveCoreAsync(resp: pxtc.CompileResult): Promise<void> {
pxt.debug(`native save`)
core.infoNotification(lf("Saving file..."));
const out = resp.outfiles[pxt.outputName()]
const nativePostMessage = nativeHostPostMessageFunction();
nativePostMessage(<pxt.editor.NativeHostMessage>{
name: resp.downloadFileBaseName,
save: out
})
return Promise.resolve();
}
function hidDeployCoreAsync(resp: pxtc.CompileResult, d?: pxt.commands.DeployOptions): Promise<void> {
pxt.tickEvent(`hid.deploy`)
// error message handled in browser download
if (!resp.success)
return browserDownloadDeployCoreAsync(resp);
core.infoNotification(lf("Downloading..."));
let f = resp.outfiles[pxtc.BINARY_UF2]
let blocks = pxtc.UF2.parseFile(pxt.Util.stringToUint8Array(atob(f)))
return hidbridge.initAsync()
.then(dev => dev.reflashAsync(blocks))
.catch((e) => {
const troubleshootDoc = pxt.appTarget && pxt.appTarget.appTheme && pxt.appTarget.appTheme.appFlashingTroubleshoot;
if (e.type === "repairbootloader") {
return pairBootloaderAsync()
.then(() => hidDeployCoreAsync(resp))
}
if (e.type === "devicenotfound" && d.reportDeviceNotFoundAsync && !!troubleshootDoc) {
pxt.tickEvent("hid.flash.devicenotfound");
return d.reportDeviceNotFoundAsync(troubleshootDoc, resp);
} else {
return pxt.commands.saveOnlyAsync(resp);
}
});
}
let askPairingCount = 0;
function askWebUSBPairAsync(resp: pxtc.CompileResult): Promise<void> {
pxt.tickEvent(`webusb.askpair`);
askPairingCount++;
if (askPairingCount > 3) { // looks like this is not working, don't ask anymore
pxt.tickEvent(`webusb.askpaircancel`);
return browserDownloadDeployCoreAsync(resp);
}
const boardName = pxt.appTarget.appTheme.boardName || lf("device");
return core.confirmAsync({
header: lf("No device detected..."),
htmlBody: `
<p><strong>${lf("Do you want to pair your {0} to the editor?", boardName)}</strong>
${lf("You will get instant downloads and data logging.")}</p>
<p class="ui font small">The pairing experience is a one-time process.</p>
`,
}).then(r => r ? showFirmwareUpdateInstructionsAsync(resp) : browserDownloadDeployCoreAsync(resp));
}
function pairBootloaderAsync(): Promise<void> {
return core.confirmAsync({
header: lf("Just one more time..."),
body: lf("You need to pair the board again, now in bootloader mode. We know..."),
agreeLbl: lf("Ok, pair!")
}).then(r => pxt.usb.pairAsync())
}
function showFirmwareUpdateInstructionsAsync(resp: pxtc.CompileResult): Promise<void> {
return pxt.targetConfigAsync()
.then(config => {
const firmwareUrl = (config.firmwareUrls || {})[
pxt.appTarget.simulator.boardDefinition ? pxt.appTarget.simulator.boardDefinition.id
: ""];
if (!firmwareUrl) // skip firmware update
return showWebUSBPairingInstructionsAsync(resp)
pxt.tickEvent(`webusb.upgradefirmware`);
const boardName = pxt.appTarget.appTheme.boardName || lf("device");
const driveName = pxt.appTarget.appTheme.driveDisplayName || "DRIVE";
const htmlBody = `
<div class="ui three column grid stackable">
<div class="column">
<div class="ui">
<div class="content">
<div class="description">
<span class="ui yellow circular label">1</span>
<strong>${lf("Connect {0} to computer with USB cable", boardName)}</strong>
<br/>
</div>
</div>
</div>
</div>
<div class="column">
<div class="ui">
<div class="content">
<div class="description">
<span class="ui blue circular label">2</span>
<strong>${lf("Download the latest firmware")}</strong>
<br/>
<a href="${firmwareUrl}" target="_blank">${lf("Click here to update to latest firmware")}</a>
</div>
</div>
</div>
</div>
<div class="column">
<div class="ui">
<div class="content">
<div class="description">
<span class="ui blue circular label">3</span>
${lf("Move the .uf2 file to your board")}
<br/>
${lf("Locate the downloaded .uf2 file and drag it to the {0} drive", driveName)}
</div>
</div>
</div>
</div>
</div>`;
return core.confirmAsync({
header: lf("Upgrade firmware"),
htmlBody,
agreeLbl: lf("Upgraded!")
})
.then(r => r ? showWebUSBPairingInstructionsAsync(resp) : browserDownloadDeployCoreAsync(resp));
});
}
export function showWebUSBPairingInstructionsAsync(resp: pxtc.CompileResult): Promise<void> {
pxt.tickEvent(`webusb.pair`);
const boardName = pxt.appTarget.appTheme.boardName || lf("device");
const htmlBody = `
<div class="ui three column grid stackable">
<div class="column">
<div class="ui">
<div class="content">
<div class="description">
<span class="ui yellow circular label">1</span>
<strong>${lf("Connect {0} to computer with USB cable", boardName)}</strong>
<br/>
</div>
</div>
</div>
</div>
<div class="column">
<div class="ui">
<div class="content">
<div class="description">
<span class="ui blue circular label">2</span>
${lf("Select the device in the pairing dialog")}
</div>
</div>
</div>
</div>
<div class="column">
<div class="ui">
<div class="content">
<div class="description">
<span class="ui blue circular label">3</span>
${lf("Press \"Connect\"")}
</div>
</div>
</div>
</div>
</div>`;
return core.confirmAsync({
header: lf("Pair your {0}", boardName),
agreeLbl: lf("Let's pair it!"),
htmlBody,
}).then(r => {
if (!r) {
if (resp)
return browserDownloadDeployCoreAsync(resp)
else
pxt.U.userError(pxt.U.lf("Device not paired"))
}
if (!resp)
return pxt.usb.pairAsync()
return pxt.usb.pairAsync()
.then(() => {
pxt.tickEvent(`webusb.pair.success`);
return hidDeployCoreAsync(resp)
})
.catch(e => browserDownloadDeployCoreAsync(resp));
})
}
function webUsbDeployCoreAsync(resp: pxtc.CompileResult): Promise<void> {
pxt.tickEvent(`webusb.deploy`)
return hidDeployCoreAsync(resp)
.catch(e => askWebUSBPairAsync(resp));
}
function winrtDeployCoreAsync(r: pxtc.CompileResult, d: pxt.commands.DeployOptions): Promise<void> {
return hidDeployCoreAsync(r, d)
.timeout(20000)
.catch((e) => {
return hidbridge.disconnectWrapperAsync()
.catch((e) => {
// Best effort disconnect; at this point we don't even know the state of the device
pxt.reportException(e);
})
.then(() => {
return core.confirmAsync({
header: lf("Something went wrong..."),
body: lf("Flashing your {0} took too long. Please disconnect your {0} from your computer and try reconnecting it.", pxt.appTarget.appTheme.boardName || lf("device")),
disagreeLbl: lf("Ok"),
hideAgree: true
});
})
.then(() => {
return pxt.commands.saveOnlyAsync(r);
});
});
}
function localhostDeployCoreAsync(resp: pxtc.CompileResult): Promise<void> {
pxt.debug('local deployment...');
core.infoNotification(lf("Uploading .hex file..."));
let deploy = () => pxt.Util.requestAsync({
url: "/api/deploy",
headers: { "Authorization": Cloud.localToken },
method: "POST",
data: resp,
allowHttpErrors: true // To prevent "Network request failed" warning in case of error. We're not actually doing network requests in localhost scenarios
}).then(r => {
if (r.statusCode !== 200) {
core.errorNotification(lf("There was a problem, please try again"));
} else if (r.json["boardCount"] === 0) {
core.warningNotification(lf("Please connect your {0} to your computer and try again", pxt.appTarget.appTheme.boardName));
}
});
return deploy()
}
export function init(): void {
pxt.onAppTargetChanged = init;
pxt.commands.browserDownloadAsync = browserDownloadAsync;
pxt.commands.saveOnlyAsync = browserDownloadDeployCoreAsync;
pxt.commands.showUploadInstructionsAsync = showUploadInstructionsAsync;
const forceHexDownload = /forceHexDownload/i.test(window.location.href);
if (pxt.usb.isAvailable() && pxt.appTarget.compile.webUSB) {
pxt.debug(`enabled webusb`);
pxt.usb.setEnabled(true);
pxt.HF2.mkPacketIOAsync = pxt.usb.mkPacketIOAsync;
} else {
pxt.debug(`disabled webusb`);
pxt.usb.setEnabled(false);
pxt.HF2.mkPacketIOAsync = hidbridge.mkBridgeAsync;
}
if (isNativeHost()) {
pxt.debug(`deploy/save using webkit host`);
pxt.commands.deployCoreAsync = nativeHostDeployCoreAsync;
pxt.commands.saveOnlyAsync = nativeHostSaveCoreAsync;
} else if (pxt.usb.isEnabled && pxt.appTarget.compile.useUF2) {
pxt.commands.deployCoreAsync = webUsbDeployCoreAsync;
} else if (pxt.winrt.isWinRT()) { // windows app
if (pxt.appTarget.serial && pxt.appTarget.serial.useHF2) {
pxt.winrt.initWinrtHid(() => hidbridge.initAsync(true).then(() => { }), () => hidbridge.disconnectWrapperAsync());
pxt.HF2.mkPacketIOAsync = pxt.winrt.mkPacketIOAsync;
pxt.commands.deployCoreAsync = winrtDeployCoreAsync;
} else {
// If we're not using HF2, then the target is using their own deploy logic in extension.ts, so don't use
// the wrapper callbacks
pxt.winrt.initWinrtHid(null, null);
if (pxt.appTarget.serial && pxt.appTarget.serial.rawHID) {
pxt.HF2.mkPacketIOAsync = pxt.winrt.mkPacketIOAsync;
}
pxt.commands.deployCoreAsync = pxt.winrt.driveDeployCoreAsync;
}
pxt.commands.browserDownloadAsync = pxt.winrt.browserDownloadAsync;
pxt.commands.saveOnlyAsync = (resp: pxtc.CompileResult) => {
return pxt.winrt.saveOnlyAsync(resp)
.then((saved) => {
if (saved) {
core.infoNotification(lf("file saved!"));
}
})
.catch((e) => core.errorNotification(lf("saving file failed...")));
};
} else if (pxt.BrowserUtils.isPxtElectron()) {
pxt.commands.deployCoreAsync = electron.driveDeployAsync;
pxt.commands.electronDeployAsync = electron.driveDeployAsync;
} else if (hidbridge.shouldUse() && !pxt.appTarget.serial.noDeploy && !forceHexDownload) {
pxt.commands.deployCoreAsync = hidDeployCoreAsync;
} else if (pxt.BrowserUtils.isLocalHost() && Cloud.localToken && !forceHexDownload) { // local node.js
pxt.commands.deployCoreAsync = localhostDeployCoreAsync;
} else { // in browser
pxt.commands.deployCoreAsync = browserDownloadDeployCoreAsync;
}
}