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
304 lines (282 loc) · 12.7 KB
/
cmds.ts
File metadata and controls
304 lines (282 loc) · 12.7 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
/// <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 * as webusb from "./webusb";
import * as compiler from "./compiler";
import Cloud = pxt.Cloud;
let tryPairedDevice = false;
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") : lf("Click to download again"),
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();
}
export 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);
}
});
}
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 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..."));
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 = () => {
pxt.debug('app target changed')
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;
}
const shouldUseWebUSB = pxt.usb.isEnabled && pxt.appTarget.compile.useUF2;
if (isNativeHost()) {
pxt.debug(`deploy: webkit host`);
pxt.commands.deployFallbackAsync = nativeHostDeployCoreAsync;
pxt.commands.saveOnlyAsync = nativeHostSaveCoreAsync;
} else if (shouldUseWebUSB && pxt.appTarget.appTheme.autoWebUSBDownload) {
pxt.debug(`deploy: webusb`);
pxt.commands.deployFallbackAsync = webusb.webUsbDeployCoreAsync;
} else if (pxt.winrt.isWinRT()) { // windows app
if (pxt.appTarget.serial && pxt.appTarget.serial.useHF2) {
pxt.debug(`deploy: winrt`);
pxt.winrt.initWinrtHid(() => hidbridge.initAsync(true).then(() => { }), () => hidbridge.disconnectWrapperAsync());
pxt.HF2.mkPacketIOAsync = pxt.winrt.mkPacketIOAsync;
pxt.commands.deployFallbackAsync = 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.debug(`deploy: winrt + custom deploy`);
pxt.winrt.initWinrtHid(null, null);
if (pxt.appTarget.serial && pxt.appTarget.serial.rawHID) {
pxt.HF2.mkPacketIOAsync = pxt.winrt.mkPacketIOAsync;
}
pxt.commands.deployFallbackAsync = 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.debug(`deploy: electron`);
pxt.commands.deployCoreAsync = electron.driveDeployAsync;
pxt.commands.electronDeployAsync = electron.driveDeployAsync;
} else if ((tryPairedDevice && shouldUseWebUSB) || !shouldUseWebUSB && hidbridge.shouldUse() && !pxt.appTarget.serial.noDeploy && !forceHexDownload) {
pxt.debug(`deploy: hid`);
pxt.commands.deployFallbackAsync = hidDeployCoreAsync;
} else if (pxt.BrowserUtils.isLocalHost() && Cloud.localToken && !forceHexDownload) { // local node.js
pxt.debug(`deploy: localhost`);
pxt.commands.deployFallbackAsync = localhostDeployCoreAsync;
} else { // in browser
pxt.debug(`deploy: browser`);
pxt.commands.deployFallbackAsync = shouldUseWebUSB ? checkWebUSBThenDownloadAsync : browserDownloadDeployCoreAsync;
}
}
export function setWebUSBPaired(enabled: boolean) {
if (tryPairedDevice === enabled) return;
tryPairedDevice = enabled;
init();
}
function checkWebUSBThenDownloadAsync(resp: pxtc.CompileResult) {
return pxt.usb.isPairedAsync().then(paired => {
if (paired) {
setWebUSBPaired(true);
return hidDeployCoreAsync(resp);
}
return browserDownloadDeployCoreAsync(resp);
});
}