forked from microsoft/pxt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonaco.tsx
More file actions
2103 lines (1813 loc) · 86.2 KB
/
monaco.tsx
File metadata and controls
2103 lines (1813 loc) · 86.2 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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// <reference path="../../localtypings/monaco.d.ts" />
/// <reference path="../../built/pxteditor.d.ts" />
import * as React from "react";
import * as ReactDOM from "react-dom";
import * as pkg from "./package";
import * as core from "./core";
import * as toolboxeditor from "./toolboxeditor"
import * as compiler from "./compiler"
import * as sui from "./sui";
import * as snippets from "./monacoSnippets"
import * as pyhelper from "./monacopyhelper";
import * as simulator from "./simulator";
import * as toolbox from "./toolbox";
import * as workspace from "./workspace";
import * as blocklyFieldView from "./blocklyFieldView";
import { ViewZoneEditorHost, ModalEditorHost, FieldEditorManager } from "./monacoFieldEditorHost";
import Util = pxt.Util;
import { BreakpointCollection } from "./monacoDebugger";
import { DebuggerCallStack } from "./debuggerCallStack";
import { DebuggerToolbox } from "./debuggerToolbox";
import { amendmentToInsertSnippet, listenForEditAmendments, createLineReplacementPyAmendment } from "./monacoEditAmendments";
import { MonacoFlyout } from "./monacoFlyout";
import { ErrorList } from "./errorList";
const MIN_EDITOR_FONT_SIZE = 10
const MAX_EDITOR_FONT_SIZE = 40
interface TranspileResult {
success: boolean;
outText?: string;
failedResponse?: pxtc.CompileResult;
}
class CompletionProvider implements monaco.languages.CompletionItemProvider {
constructor(public editor: Editor, public python: boolean) {
}
triggerCharacters?: string[] = ["(", "."];
kindMap = {}
private tsKindToMonacoKind(s: pxtc.SymbolKind): monaco.languages.CompletionItemKind {
switch (s) {
case pxtc.SymbolKind.Method: return monaco.languages.CompletionItemKind.Method;
case pxtc.SymbolKind.Property: return monaco.languages.CompletionItemKind.Property;
case pxtc.SymbolKind.Function: return monaco.languages.CompletionItemKind.Function;
case pxtc.SymbolKind.Variable: return monaco.languages.CompletionItemKind.Variable;
case pxtc.SymbolKind.Module: return monaco.languages.CompletionItemKind.Module;
case pxtc.SymbolKind.Enum: return monaco.languages.CompletionItemKind.Class;
case pxtc.SymbolKind.EnumMember: return monaco.languages.CompletionItemKind.Enum;
case pxtc.SymbolKind.Class: return monaco.languages.CompletionItemKind.Class;
case pxtc.SymbolKind.Interface: return monaco.languages.CompletionItemKind.Interface;
default: return monaco.languages.CompletionItemKind.Text;
}
}
/**
* Provide completion items for the given position and document.
*/
provideCompletionItems(model: monaco.editor.IReadOnlyModel, position: monaco.Position, context: monaco.languages.CompletionContext, token: monaco.CancellationToken): monaco.languages.ProviderResult<monaco.languages.CompletionList> {
const offset = model.getOffsetAt(position);
const source = model.getValue();
const fileName = this.editor.currFile.name;
const word = model.getWordUntilPosition(position);
const wordStartOffset = model.getOffsetAt({ lineNumber: position.lineNumber, column: word.startColumn })
const wordEndOffset = model.getOffsetAt({ lineNumber: position.lineNumber, column: word.endColumn })
return compiler.completionsAsync(fileName, offset, wordStartOffset, wordEndOffset, source)
.then(completions => {
function stripLocalNamespace(qName: string): string {
// leave out namespace qualifiers if we're inside a matching namespace
if (!qName)
return qName
for (let ns of completions.namespace) {
if (qName.startsWith(ns + "."))
qName = qName.substr((ns + ".").length)
else
break
}
return qName
}
const items = (completions.entries || []).map((si, i) => {
let insertSnippet = stripLocalNamespace(this.python ? si.pySnippet : si.snippet);
let qName = stripLocalNamespace(this.python ? si.pyQName : si.qName);
let name = this.python ? si.pyName : si.name;
let completionSnippet: string | undefined = undefined;
let isMultiLine = insertSnippet && insertSnippet.indexOf("\n") >= 0
if (this.python && insertSnippet && isMultiLine && pxt.blocks.hasHandler(si)) {
// For python, we want to replace the entire line because when creating
// new functions these need to be placed before the line the user was typing
// unlike with typescript where callbacks use lambdas.
//
// e.g. "player.on_chat"
// becomes:
// def on_chat_handler():
// pass
// player.on_chat(on_chat_handler)
// whereas TS looks like:
// player.onChat(() => {
//
// })
//
// At the time of this writting, Monaco does not support item completions that replace the
// whole line. So we use a custom system of "edit amendments". See monacoEditAmendments.ts
// for more.
completionSnippet = amendmentToInsertSnippet(
createLineReplacementPyAmendment(insertSnippet))
} else {
completionSnippet = insertSnippet || qName
// if we're past the first ".", i.e. we're doing member completion, be sure to
// remove what precedes the "." in the full snippet.
// E.g. if the user is typing "mobs.", we want to complete with "spawn" (name) not "mobs.spawn" (qName)
if (completions.isMemberCompletion && completionSnippet) {
const nameStart = completionSnippet.lastIndexOf(name);
if (nameStart !== -1) {
completionSnippet = completionSnippet.substr(nameStart)
}
}
}
const label = completions.isMemberCompletion ? name : qName
const documentation = pxt.Util.rlf(si.attributes.jsDoc);
const block = pxt.Util.rlf(si.attributes.block);
const word = model.getWordAtPosition(position);
const range: monaco.IRange = {
startLineNumber: position.lineNumber,
startColumn: word ? word.startColumn : position.column,
endColumn: position.column,
endLineNumber: position.lineNumber
}
// Need to take the whitespace out of this string, otherwise monaco
// won't dismiss the suggest widget when the user types a space. Replace
// them with commas so that we don't confuse the fuzzy matcher in monaco
const filterText = `${label},${documentation},${block}`.replace(/\s/g, ",")
let res: monaco.languages.CompletionItem = {
label: label,
range,
kind: this.tsKindToMonacoKind(si.kind),
documentation,
detail: insertSnippet,
// force monaco to use our sorting
sortText: `${tosort(i)} ${insertSnippet}`,
filterText: filterText,
insertText: completionSnippet || undefined,
};
return res
})
return { suggestions: items };
});
function tosort(i: number): string {
return ("000" + i).slice(-4);
}
}
/**
* Given a completion item fill in more data, like [doc-comment](#CompletionItem.documentation)
* or [details](#CompletionItem.detail).
*
* The editor will only resolve a completion item once.
*/
resolveCompletionItem(model: monaco.editor.ITextModel, position: monaco.Position, item: monaco.languages.CompletionItem, token: monaco.CancellationToken): monaco.languages.CompletionItem | monaco.Thenable<monaco.languages.CompletionItem> {
return item
}
}
class SignatureHelper implements monaco.languages.SignatureHelpProvider {
signatureHelpTriggerCharacters: string[] = ["(", ","];
protected isPython: boolean = false;
constructor(public editor: Editor, public python: boolean) {
this.isPython = python;
}
/**
* Provide help for the signature at the given position and document.
*/
provideSignatureHelp(model: monaco.editor.IReadOnlyModel, position: monaco.Position, token: monaco.CancellationToken, context: monaco.languages.SignatureHelpContext): monaco.languages.ProviderResult<monaco.languages.SignatureHelpResult> {
const offset = model.getOffsetAt(position);
const source = model.getValue();
const fileName = this.editor.currFile.name;
return compiler.syntaxInfoAsync("signature", fileName, offset, source)
.then(r => {
let sym = r.symbols ? r.symbols[0] : null
if (!sym || !sym.parameters) return null;
const documentation = pxt.Util.rlf(sym.attributes.jsDoc);
let paramInfo: monaco.languages.ParameterInformation[] =
sym.parameters.map(p => ({
label: `${p.name}: ${this.isPython ? p.pyTypeString : p.type}`,
documentation: pxt.Util.rlf(p.description)
}))
const res: monaco.languages.SignatureHelp = {
signatures: [{
label: `${this.isPython && sym.pyName ? sym.pyName : sym.name}(${paramInfo.map(p => p.label).join(", ")})`,
documentation,
parameters: paramInfo
}],
activeSignature: 0,
activeParameter: r.auxResult
}
return { value: res, dispose: () => { } }
});
}
}
class HoverProvider implements monaco.languages.HoverProvider {
constructor(public editor: Editor, public python: boolean) {
}
/**
* Provide a hover for the given position and document. Multiple hovers at the same
* position will be merged by the editor. A hover can have a range which defaults
* to the word range at the position when omitted.
*/
provideHover(model: monaco.editor.IReadOnlyModel, position: monaco.Position, token: monaco.CancellationToken): monaco.languages.Hover | monaco.Thenable<monaco.languages.Hover> {
// Don't provide hover if currently dragging snippet
if (this.editor.hasInsertionSnippet()) return null;
const offset = model.getOffsetAt(position);
const source = model.getValue();
const fileName = this.editor.currFile.name;
return compiler.syntaxInfoAsync("symbol", fileName, offset, source)
.then(r => {
let sym = r.symbols ? r.symbols[0] : null
let contents: string[];
if (sym) {
const documentation = pxt.Util.rlf(sym.attributes.jsDoc);
contents = [r.auxResult[0], documentation];
}
else if (r.auxResult) {
contents = [r.auxResult.displayString, r.auxResult.documentation];
}
if (contents) {
const res: monaco.languages.Hover = {
contents: contents.map(toMarkdownString),
range: monaco.Range.fromPositions(model.getPositionAt(r.beginPos), model.getPositionAt(r.endPos))
}
return res;
}
return null;
});
}
}
function toMarkdownString(text: string) {
return { value: text };
}
// reference: https://github.com/microsoft/vscode/blob/master/extensions/python/language-configuration.json
// documentation: https://code.visualstudio.com/api/language-extensions/language-configuration-guide
const pythonLanguageConfiguration: monaco.languages.LanguageConfiguration = {
"comments": {
"lineComment": "#",
"blockComment": ["\"\"\"", "\"\"\""]
},
"brackets": [
["{", "}"],
["[", "]"],
["(", ")"]
],
"autoClosingPairs": [
{ "open": "{", "close": "}" },
{ "open": "[", "close": "]" },
{ "open": "(", "close": ")" },
{ "open": "\"", "close": "\"", "notIn": ["string"] },
{ "open": "r\"", "close": "\"", "notIn": ["string", "comment"] },
{ "open": "R\"", "close": "\"", "notIn": ["string", "comment"] },
{ "open": "u\"", "close": "\"", "notIn": ["string", "comment"] },
{ "open": "U\"", "close": "\"", "notIn": ["string", "comment"] },
{ "open": "f\"", "close": "\"", "notIn": ["string", "comment"] },
{ "open": "F\"", "close": "\"", "notIn": ["string", "comment"] },
{ "open": "b\"", "close": "\"", "notIn": ["string", "comment"] },
{ "open": "B\"", "close": "\"", "notIn": ["string", "comment"] },
{ "open": "'", "close": "'", "notIn": ["string", "comment"] },
{ "open": "r'", "close": "'", "notIn": ["string", "comment"] },
{ "open": "R'", "close": "'", "notIn": ["string", "comment"] },
{ "open": "u'", "close": "'", "notIn": ["string", "comment"] },
{ "open": "U'", "close": "'", "notIn": ["string", "comment"] },
{ "open": "f'", "close": "'", "notIn": ["string", "comment"] },
{ "open": "F'", "close": "'", "notIn": ["string", "comment"] },
{ "open": "b'", "close": "'", "notIn": ["string", "comment"] },
{ "open": "B'", "close": "'", "notIn": ["string", "comment"] },
{ "open": "`", "close": "`", "notIn": ["string"] }
],
onEnterRules: [
{
beforeText: /^\s*(?:def|class|for|if|elif|else|while|try|with|finally|except|async).*?:\s*$/,
action: {
indentAction: 1/*IndentAction.Indent*/
}
}
]
}
class FormattingProvider implements monaco.languages.DocumentRangeFormattingEditProvider {
protected isPython: boolean = false;
constructor(public editor: Editor, public python: boolean) {
this.isPython = python;
}
provideDocumentRangeFormattingEdits(model: monaco.editor.IReadOnlyModel, range: monaco.Range, options: monaco.languages.FormattingOptions, token: monaco.CancellationToken): monaco.Thenable<monaco.editor.ISingleEditOperation[]> {
return Promise.resolve().then(p => {
return this.isPython
? pyhelper.provideDocumentRangeFormattingEdits(model, range, options, token)
: null;
});
}
}
const modeMap: pxt.Map<pxt.editor.FileType> = {
"cpp": pxt.editor.FileType.CPP,
"h": pxt.editor.FileType.CPP,
"json": pxt.editor.FileType.JSON,
"md": pxt.editor.FileType.Markdown,
"py": pxt.editor.FileType.Python,
"ts": pxt.editor.FileType.TypeScript,
"js": pxt.editor.FileType.JavaScript,
"svg": pxt.editor.FileType.XML,
"blocks": pxt.editor.FileType.XML,
"asm": pxt.editor.FileType.Asm,
}
export class Editor extends toolboxeditor.ToolboxEditor {
editor: monaco.editor.IStandaloneCodeEditor;
currFile: pkg.File;
fileType: pxt.editor.FileType = pxt.editor.FileType.Text;
extraLibs: pxt.Map<monaco.IDisposable>;
nsMap: pxt.Map<toolbox.BlockDefinition[]>;
giveFocusOnLoading: boolean = false;
protected fieldEditors: FieldEditorManager;
protected feWidget: ViewZoneEditorHost | ModalEditorHost;
protected foldFieldEditorRanges = true;
protected activeRangeID: number;
protected hasFieldEditors = !!(pxt.appTarget.appTheme.monacoFieldEditors && pxt.appTarget.appTheme.monacoFieldEditors.length);
protected callStackView: DebuggerCallStack;
protected breakpoints: BreakpointCollection;
protected debuggerToolbox: DebuggerToolbox;
protected flyout: MonacoFlyout;
protected insertionSnippet: string;
protected mobileKeyboardWidget: ShowKeyboardWidget;
protected pythonSourceMap: pxtc.SourceMapHelpers;
private loadMonacoPromise: Promise<void>;
private diagSnapshot: string[];
private annotationLines: number[];
private editorViewZones: number[];
private highlightDecorations: string[] = [];
private highlightedBreakpoint: number;
private editAmendmentsListener: monaco.IDisposable | undefined;
private errorChangesListeners: pxt.Map<(errors: pxtc.KsDiagnostic[]) => void> = {};
private exceptionChangesListeners: pxt.Map<(exception: pxsim.DebuggerBreakpointMessage, locations: pxtc.LocationInfo[]) => void> = {}
private callLocations: pxtc.LocationInfo[];
private handleFlyoutWheel = (e: WheelEvent) => e.stopPropagation();
private handleFlyoutScroll = (e: WheelEvent) => e.stopPropagation();
constructor(parent: pxt.editor.IProjectView) {
super(parent);
this.setErrorListState = this.setErrorListState.bind(this);
this.listenToErrorChanges = this.listenToErrorChanges.bind(this);
this.listenToExceptionChanges = this.listenToExceptionChanges.bind(this)
this.goToError = this.goToError.bind(this);
this.startDebugger = this.startDebugger.bind(this)
}
hasBlocks() {
if (!this.currFile) return true
let blockFile = this.currFile.getVirtualFileName(pxt.BLOCKS_PROJECT_NAME);
return (blockFile && pkg.mainEditorPkg().files[blockFile] != null)
}
public openBlocks() {
pxt.tickEvent(`typescript.showBlocks`);
let initPromise = Promise.resolve();
if (!this.currFile) {
const mainPkg = pkg.mainEditorPkg();
if (mainPkg && mainPkg.files["main.ts"]) {
initPromise = this.loadFileAsync(mainPkg.files["main.ts"]);
}
else {
return;
}
}
let promise = initPromise.then(() => {
const isPython = this.fileType == pxt.editor.FileType.Python;
const tickLang = isPython ? "python" : "typescript";
pxt.tickEvent(`${tickLang}.convertBlocks`);
const mainPkg = pkg.mainEditorPkg();
if (!this.hasBlocks() && !mainPkg && !mainPkg.files["main.blocks"]) {
pxt.debug(`cancelling convertion to blocks, but main.blocks is missing`);
return undefined;
}
if (this.feWidget) {
this.feWidget.close();
this.activeRangeID = null;
}
let blockFile = this.currFile.getVirtualFileName(pxt.BLOCKS_PROJECT_NAME);
let tsFile = isPython
? this.currFile.getVirtualFileName(pxt.JAVASCRIPT_PROJECT_NAME)
: this.currFile.name;
if (!this.hasBlocks()) {
if (!mainPkg || !mainPkg.files["main.blocks"]) {
// Either the project isn't loaded, or it's ts-only
if (mainPkg) {
this.parent.setFile(mainPkg.files["main.ts"]);
}
return undefined;
}
// The current file doesn't have an associated blocks file, so switch
// to main.ts instead
this.currFile = mainPkg.files["main.ts"];
blockFile = this.currFile.getVirtualFileName(pxt.BLOCKS_PROJECT_NAME);
tsFile = "main.ts";
}
const failedAsync = (file: string, programTooLarge = false) => {
core.cancelAsyncLoading("switchtoblocks");
this.forceDiagnosticsUpdate();
return this.showBlockConversionFailedDialog(file, programTooLarge);
}
// might be undefined
let xml: string;
// it's a bit for a wild round trip:
// 1) convert blocks to js to see if any changes happened, otherwise, just reload blocks
// 2) decompile js -> blocks then take the decompiled blocks -> js
// 3) check that decompiled js == current js % white space
let blocksInfo: pxtc.BlocksInfo;
return this.parent.saveFileAsync()
.then(() => this.parent.saveFileAsync())
.then(() => this.parent.loadBlocklyAsync())
.then(() => this.saveToTypeScriptAsync()) // make sure python gets converted
.then(() => compiler.getBlocksAsync())
.then((bi: pxtc.BlocksInfo) => {
blocksInfo = bi;
pxt.blocks.initializeAndInject(blocksInfo);
const oldWorkspace = pxt.blocks.loadWorkspaceXml(mainPkg.files[blockFile].content);
if (oldWorkspace) {
return pxt.blocks.compileAsync(oldWorkspace, blocksInfo).then((compilationResult) => {
const oldJs = compilationResult.source;
return compiler.formatAsync(oldJs, 0).then((oldFormatted: any) => {
return compiler.formatAsync(this.editor.getValue(), 0).then((newFormatted: any) => {
if (oldFormatted.formatted == newFormatted.formatted) {
pxt.debug(`${tickLang} not changed, skipping decompile`);
pxt.tickEvent(`${tickLang}.noChanges`)
this.parent.setFile(mainPkg.files[blockFile]);
return [oldWorkspace, false]; // return false to indicate we don't want to decompile
} else {
return [oldWorkspace, true];
}
});
});
})
}
return [oldWorkspace, true];
}).then((values) => {
if (!values) return Promise.resolve();
const oldWorkspace = values[0] as Blockly.Workspace;
const shouldDecompile = values[1] as boolean;
if (!shouldDecompile) return Promise.resolve();
return compiler.compileAsync()
.then(resp => {
if (resp.success) {
return this.transpileToBlocksInternalAsync(this.currFile, blocksInfo, oldWorkspace)
.then(resp => {
if (!resp.success) {
const failed = resp.failedResponse;
this.currFile.diagnostics = failed.diagnostics;
let tooLarge = false;
failed.diagnostics.forEach(d => tooLarge = (tooLarge || d.code === 9266 /* error code when script is too large */));
return failedAsync(blockFile, tooLarge);
}
xml = resp.outText;
Util.assert(!!xml);
return mainPkg.setContentAsync(blockFile, xml)
.then(() => this.parent.setFile(mainPkg.files[blockFile]));
})
}
else {
return failedAsync(blockFile, false)
}
})
}).catch(e => {
pxt.reportException(e);
core.errorNotification(lf("Oops, something went wrong trying to convert your code."));
});
});
core.showLoadingAsync("switchtoblocks", lf("switching to blocks..."), promise).done();
}
public showBlockConversionFailedDialog(blockFile: string, programTooLarge: boolean): Promise<void> {
const isPython = this.fileType == pxt.editor.FileType.Python;
const tickLang = isPython ? "python" : "typescript";
let bf = pkg.mainEditorPkg().files[blockFile];
if (programTooLarge) {
pxt.tickEvent(`${tickLang}.programTooLarge`);
}
let body: string;
let disagreeLbl: string;
if (isPython) {
body = programTooLarge ?
lf("Your program is too large to convert into blocks. You can keep working in Python or discard your changes and go back to the previous Blocks version.") :
lf("We are unable to convert your Python code back to blocks. You can keep working in Python or discard your changes and go back to the previous Blocks version.");
disagreeLbl = lf("Stay in Python");
} else {
body = programTooLarge ?
lf("Your program is too large to convert into blocks. You can keep working in JavaScript or discard your changes and go back to the previous Blocks version.") :
lf("We are unable to convert your JavaScript code back to blocks. You can keep working in JavaScript or discard your changes and go back to the previous Blocks version.");
disagreeLbl = lf("Stay in JavaScript");
}
return core.confirmAsync({
header: programTooLarge ? lf("Program too large") : lf("Oops, there is a problem converting your code."),
body,
agreeLbl: lf("Discard and go to Blocks"),
agreeClass: "cancel",
agreeIcon: "cancel",
disagreeLbl: disagreeLbl,
disagreeClass: "positive",
disagreeIcon: "checkmark",
hideCancel: !bf
}).then(b => {
// discard
if (!b) {
pxt.tickEvent(`${tickLang}.keepText`, undefined, { interactiveConsent: true });
} else {
pxt.tickEvent(`${tickLang}.discardText`, undefined, { interactiveConsent: true });
this.parent.saveBlocksToTypeScriptAsync().then((src) => {
this.overrideFile(src);
this.parent.setFile(bf);
})
}
})
}
protected transpileToBlocksInternalAsync(file: pkg.File, blocksInfo: pxtc.BlocksInfo, oldWorkspace: Blockly.Workspace): Promise<TranspileResult> {
const mainPkg = pkg.mainEditorPkg();
const tsFilename = file.getVirtualFileName(pxt.JAVASCRIPT_PROJECT_NAME);
const blocksFilename = file.getVirtualFileName(pxt.BLOCKS_PROJECT_NAME);
const isPython = file.getExtension() === "py";
const fromLanguage: pxtc.CodeLang = isPython ? "py" : "ts";
const fromText = file.content;
const cached = mainPkg.getCachedTranspile(fromLanguage, fromText, "blocks");
if (cached != null) {
return Promise.resolve({
success: true,
outText: cached
});
}
return compiler.decompileAsync(tsFilename, blocksInfo, oldWorkspace, blocksFilename)
.then(resp => {
if (!resp.success) {
return {
success: false,
failedResponse: resp
};
}
const outText = resp.outfiles[blocksFilename];
mainPkg.cacheTranspile(fromLanguage, fromText, "blocks", outText);
return {
success: true,
outText
}
});
}
public decompileAsync(blockFile: string): Promise<pxtc.CompileResult> {
return compiler.decompileAsync(blockFile)
}
display(): JSX.Element {
const showErrorList = pxt.appTarget.appTheme.errorList;
const isAndroid = pxt.BrowserUtils.isAndroid();
return (
<div id="monacoEditorArea" className={`monacoEditorArea ${isAndroid ? "android" : ""}`} style={{ direction: 'ltr' }}>
{this.isVisible && <div className={`monacoToolboxDiv ${(this.toolbox && !this.toolbox.state.visible && !this.isDebugging()) ? 'invisible' : ''}`}>
<toolbox.Toolbox ref={this.handleToolboxRef} editorname="monaco" parent={this} />
<div id="monacoDebuggerToolbox"></div>
</div>}
<div id="monacoEditorRightArea" className="monacoEditorRightArea">
<div id='monacoEditorInner'>
<MonacoFlyout ref={this.handleFlyoutRef} fileType={this.fileType}
blockIdMap={this.blockIdMap}
moveFocusToParent={this.moveFocusToToolbox}
insertSnippet={this.insertSnippet}
setInsertionSnippet={this.setInsertionSnippet}
parent={this.parent} />
</div>
{showErrorList && <ErrorList onSizeChange={this.setErrorListState} listenToErrorChanges={this.listenToErrorChanges}
listenToExceptionChanges={this.listenToExceptionChanges} goToError={this.goToError}
startDebugger={this.startDebugger} />}
</div>
</div>
)
}
listenToExceptionChanges(handlerKey: string, handler: (exception: pxsim.DebuggerBreakpointMessage, locations: pxtc.LocationInfo[]) => void) {
this.exceptionChangesListeners[handlerKey] = handler;
}
public onExceptionDetected(exception: pxsim.DebuggerBreakpointMessage) {
for (let listener of pxt.U.values(this.exceptionChangesListeners)) {
listener(exception, this.callLocations);
}
}
listenToErrorChanges(handlerKey: string, handler: (errors: pxtc.KsDiagnostic[]) => void) {
this.errorChangesListeners[handlerKey] = handler;
}
goToError(error: pxtc.KsDiagnostic) {
// Use endLine and endColumn to position the cursor
// when errors do have them
let line, column;
if (error.endLine && error.endColumn) {
line = error.endLine + 1;
column = error.endColumn + 1;
} else {
line = error.line + 1;
column = error.column + error.length + 1;
}
this.editor.revealLineInCenter(line);
this.editor.setPosition({ column: column, lineNumber: line });
this.editor.focus();
}
startDebugger() {
pxt.tickEvent('errorList.startDebugger', null, { interactiveConsent: true })
this.parent.toggleDebugging()
}
private onErrorChanges(errors: pxtc.KsDiagnostic[]) {
for (let listener of pxt.U.values(this.errorChangesListeners)) {
listener(errors);
}
}
public showPackageDialog() {
pxt.tickEvent("monaco.addpackage", undefined, { interactiveConsent: true });
this.hideFlyout();
this.parent.showPackageDialog();
}
private defineEditorTheme(hc?: boolean, withNamespaces?: boolean) {
const inverted = pxt.appTarget.appTheme.invertedMonaco;
const invertedColorluminosityMultipler = 0.6;
let rules: monaco.editor.ITokenThemeRule[] = [];
if (!hc && withNamespaces) {
const colors: pxt.Map<string> = {};
this.getNamespaces().forEach((ns) => {
const metaData = this.getNamespaceAttrs(ns);
const blocks = snippets.isBuiltin(ns) ?
snippets.getBuiltinCategory(ns).blocks.concat(this.nsMap[ns] || []) : this.nsMap[ns];
if (metaData.color && blocks) {
let hexcolor = fixColor(metaData.color);
blocks.forEach((fn) => {
rules.push({ token: `identifier.ts ${fn.name}`, foreground: hexcolor });
});
rules.push({ token: `identifier.ts ${ns}`, foreground: hexcolor });
colors[ns] = metaData.color;
}
})
rules.push({ token: `identifier.ts if`, foreground: '5B80A5', });
rules.push({ token: `identifier.ts else`, foreground: '5B80A5', });
rules.push({ token: `identifier.ts while`, foreground: '5BA55B', });
rules.push({ token: `identifier.ts for`, foreground: '5BA55B', });
const pauseUntil = pxt.appTarget.runtime && pxt.appTarget.runtime.pauseUntilBlock;
if (pauseUntil) {
const call = pauseUntil.callName || "pauseUntil";
const color = pauseUntil.color || colors[pauseUntil.category];
if (color) {
rules.push({ token: `identifier.ts ${call}`, foreground: fixColor(color) });
}
}
}
const colors = pxt.appTarget.appTheme.monacoColors || {};
monaco.editor.defineTheme('pxtTheme', {
base: hc ? 'hc-black' : (inverted ? 'vs-dark' : 'vs'), // can also be vs-dark or hc-black
inherit: true, // can also be false to completely replace the builtin rules
rules: rules,
colors: hc ? {} : colors
});
monaco.editor.setTheme('pxtTheme');
function fixColor(hexcolor: string) {
hexcolor = pxt.toolbox.convertColor(hexcolor);
return (inverted ? pxt.toolbox.fadeColor(hexcolor, invertedColorluminosityMultipler, true) : hexcolor).replace('#', '');
}
}
saveToTypeScriptAsync() {
if (this.fileType == pxt.editor.FileType.Python)
return this.convertPythonToTypeScriptAsync(this.isDebugging() || this.parent.state.tracing);
return Promise.resolve(undefined)
}
convertPythonToTypeScriptAsync(force = false): Promise<string> {
if (!this.currFile) return Promise.resolve(undefined);
const tsName = this.currFile.getVirtualFileName(pxt.JAVASCRIPT_PROJECT_NAME)
return compiler.py2tsAsync(force)
.then(res => {
if (res.sourceMap) {
const mainPkg = pkg.mainEditorPkg();
const tsFile = res.outfiles[tsName];
const pyFile = mainPkg.files[this.currFile.getFileNameWithExtension("py")]?.content;
if (tsFile && pyFile) {
this.pythonSourceMap = pxtc.BuildSourceMapHelpers(res.sourceMap, tsFile, pyFile);
}
else this.pythonSourceMap = null;
}
// TODO python use success
// any errors?
if (res.diagnostics && res.diagnostics.length)
return undefined;
if (res.outfiles[tsName]) {
return res.outfiles[tsName]
}
return ""
})
}
setHighContrast(hc: boolean) {
if (this.loadMonacoPromise) this.defineEditorTheme(hc, true);
}
beforeCompile() {
// this triggers a text change wich stops the simulator async
//if (this.editor)
// this.editor.getAction('editor.action.formatDocument').run();
}
isIncomplete() {
return this.editor && (this.editor as any)._view ?
(this.editor as any)._view.contentWidgets._widgets["editor.widget.suggestWidget"].isVisible :
false;
}
resize(e?: Event) {
let monacoArea = document.getElementById('monacoEditorArea');
if (!monacoArea) return;
let monacoToolboxDiv = monacoArea.getElementsByClassName('monacoToolboxDiv')[0] as HTMLElement;
if (monacoArea && this.editor) {
const toolboxWidth = monacoToolboxDiv && monacoToolboxDiv.offsetWidth || 0;
const logoHeight = (this.parent.isJavaScriptActive()) ? this.parent.updateEditorLogo(toolboxWidth, this.getEditorColor()) : 0;
this.editor.layout({ width: monacoArea.offsetWidth - toolboxWidth, height: monacoArea.offsetHeight - logoHeight });
blocklyFieldView.setEditorBounds({
top: 0,
left: 0,
width: window.innerWidth,
height: window.innerHeight
});
if (monacoToolboxDiv) monacoToolboxDiv.style.height = `100%`;
}
}
setErrorListState(newState?: pxt.editor.ErrorListState) {
const oldState = this.parent.state.errorListState;
if (oldState != newState) {
this.resize();
this.parent.setState({
errorListState: newState
});
}
}
prepare() {
this.isReady = true
}
public loadMonacoAsync(): Promise<void> {
if (!this.loadMonacoPromise)
this.loadMonacoPromise = this.createLoadMonacoPromise();
return this.loadMonacoPromise;
}
private createLoadMonacoPromise(): Promise<void> {
this.extraLibs = Object.create(null);
let editorArea = document.getElementById("monacoEditorArea");
let editorElement = document.getElementById("monacoEditorInner");
return pxt.vs.initMonacoAsync(editorElement).then((editor) => {
this.editor = editor;
// This is used to detect ios 13 on iPad, which is not properly detected by monaco
if (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1 && !this.mobileKeyboardWidget) {
this.mobileKeyboardWidget = new ShowKeyboardWidget(this.editor);
}
this.editor.updateOptions({ fontSize: this.parent.settings.editorFontSize });
this.editor.addAction({
id: "save",
label: lf("Save"),
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S],
keybindingContext: "!editorReadonly",
precondition: "!editorReadonly",
contextMenuGroupId: "0_pxtnavigation",
contextMenuOrder: 0.2,
run: () => Promise.resolve(this.parent.typecheckNow())
});
this.editor.addAction({
id: "runSimulator",
label: lf("Run Simulator"),
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter],
keybindingContext: "!editorReadonly",
precondition: "!editorReadonly",
contextMenuGroupId: "0_pxtnavigation",
contextMenuOrder: 0.21,
run: () => Promise.resolve(this.parent.runSimulator())
});
if (pxt.appTarget.compile && pxt.appTarget.compile.hasHex) {
this.editor.addAction({
id: "compileHex",
label: lf("Download"),
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Alt | monaco.KeyCode.Enter],
keybindingContext: "!editorReadonly",
precondition: "!editorReadonly",
contextMenuGroupId: "0_pxtnavigation",
contextMenuOrder: 0.22,
run: () => Promise.resolve(this.parent.compile())
});
}
this.editor.addAction({
id: "zoomIn",
label: lf("Zoom In"),
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.NUMPAD_ADD, monaco.KeyMod.CtrlCmd | monaco.KeyCode.US_EQUAL],
run: () => Promise.resolve(this.zoomIn())
});
this.editor.addAction({
id: "zoomOut",
label: lf("Zoom Out"),
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.NUMPAD_SUBTRACT, monaco.KeyMod.CtrlCmd | monaco.KeyCode.US_MINUS],
run: () => Promise.resolve(this.zoomOut())
});
if (pxt.appTarget.appTheme.hasReferenceDocs) {
let referenceContextKey = this.editor.createContextKey("editorHasReference", false)
this.editor.addAction({
id: "reference",
label: lf("Help"),
keybindingContext: "!editorReadonly && editorHasReference",
precondition: "!editorReadonly && editorHasReference",
contextMenuGroupId: "navigation",
contextMenuOrder: 0.1,
run: () => Promise.resolve(this.loadReference())
});
this.editor.onDidChangeCursorPosition((e: monaco.editor.ICursorPositionChangedEvent) => {
let word = this.editor.getModel().getWordUntilPosition(e.position);
if (word && word.word != "") {
referenceContextKey.set(true);
} else {
referenceContextKey.reset()
}
})
}
// Accessibility shortcut, add a way to quickly jump to the monaco toolbox
this.editor.addAction({
id: "jumptoolbox",
label: lf("Jump to Toolbox"),
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Alt | monaco.KeyCode.KEY_T],
keybindingContext: "!editorReadonly",
precondition: "!editorReadonly",
run: () => Promise.resolve(this.moveFocusToToolbox())
});
this.editor.onDidLayoutChange((e: monaco.editor.EditorLayoutInfo) => {
// Update editor font size in settings after a ctrl+scroll zoom
let currentFont = this.getEditorFontSize();
if (this.parent.settings.editorFontSize != currentFont) {
this.parent.settings.editorFontSize = currentFont;
this.forceDiagnosticsUpdate();
}
// Update widgets
const toolbox = document.getElementById('monacoToolboxDiv');
if (toolbox) toolbox.style.height = `${this.editor.getLayoutInfo().contentHeight}px`;
})
const monacoEditorInner = document.getElementById('monacoEditorInner');
if (pxt.BrowserUtils.hasPointerEvents()) {
monacoEditorInner.onpointermove = this.onPointerMove;
monacoEditorInner.onpointerup = this.onPointerUp;
} else {
monacoEditorInner.onmousemove = this.onPointerMove;
monacoEditorInner.onmouseup = this.onPointerUp;
if (pxt.BrowserUtils.isTouchEnabled()) {
// For devices without PointerEvents (iOS < 13.0), use state to
// hide the flyout rather than focusing the editor (onPointerMove)
monacoEditorInner.ontouchend = this.onPointerUp;
}
}
this.editor.onDidFocusEditorText(() => {
this.hideFlyout();
})
monaco.languages.registerCompletionItemProvider("python", new CompletionProvider(this, true));
monaco.languages.registerSignatureHelpProvider("python", new SignatureHelper(this, true));
monaco.languages.registerHoverProvider("python", new HoverProvider(this, true));
monaco.languages.registerDocumentRangeFormattingEditProvider("python", new FormattingProvider(this, true));
monaco.languages.setLanguageConfiguration("python", pythonLanguageConfiguration)
monaco.languages.registerCompletionItemProvider("typescript", new CompletionProvider(this, false));
monaco.languages.registerSignatureHelpProvider("typescript", new SignatureHelper(this, false));
monaco.languages.registerHoverProvider("typescript", new HoverProvider(this, false));
monaco.languages.registerDocumentRangeFormattingEditProvider("typescript", new FormattingProvider(this, false));
this.editorViewZones = [];
this.setupFieldEditors();
this.editor.onMouseDown((e: monaco.editor.IEditorMouseEvent) => {
if (e.target.type !== monaco.editor.MouseTargetType.GUTTER_GLYPH_MARGIN) {
return;
}
this.handleGutterClick(e);
});
editor.onDidChangeModelContent(e => {
// Clear ranges because the model changed
if (this.fieldEditors)
this.fieldEditors.clearRanges(editor);
})
})
}
private insertSnippet = (cursorPos: monaco.Position, insertText: string, inline = false) => {
let currPos = this.editor.getPosition();
let model = this.editor.getModel();
if (!cursorPos) // IE11 fails to locate the mouse
cursorPos = currPos;
if (!cursorPos) {
return
}
let position = cursorPos.clone()
// determine insert mode
type InsertMode = "NewLineBefore" | "NewLineAfter" | "Inline"
let insertMode: InsertMode;
if (inline)
insertMode = "Inline"
else if (cursorPos.column === 1)
insertMode = "NewLineBefore"
else
insertMode = "NewLineAfter"
// determine snippet insert column
if (insertMode === "NewLineAfter") {
// place snippet as if the cursor where at the end of the line
position = position.with(position.lineNumber, model.getLineMaxColumn(cursorPos.lineNumber))
} // else no change
// if not inline, put snippet on a new line