-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsimulator.js
2040 lines (1852 loc) · 68.1 KB
/
simulator.js
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
// This file emulates a hardware board with an MCU and a set of external
// devices (LEDs etc.).
export { Simulator };
// The number of CSS pixels in a CSS millimeter. Yes, this is a constant,
// defined by the CSS specification. This doesn't correspond exactly to
// real-world pixels and millimeters, but millimeters should be pretty close.
// For more information:
// https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units
const pixelsPerMillimeter = 96 / 25.4;
const inputCompileDelay = 1000;
// All the features supported in the 'features' config key.
const allFeatures = ['zoom', 'pan'];
// Encapsulate a single simulator HTML node. Handles starting/stopping the
// worker, refresh the schematic as needed, etc.
class Simulator {
constructor(config) {
// Store configuration.
this.root = config.root;
this.editor = config.editor;
this.firmwareButton = config.firmwareButton;
this.baseURL = config.baseURL || document.baseURI;
this.apiURL = config.apiURL;
this.features = new Set(config.features || allFeatures);
this.schematicURL = config.schematicURL || new URL('./worker/webworker.js', this.baseURL);
this.runnerURL = config.runnerURL || new URL('./worker/runner.js', this.baseURL);
this.saveState = config.saveState || (() => {});
// Initialize member variables.
this.worker = null;
this.workerUpdate = null;
this._schematicRect = null;
// Initialize root element.
this.schematicElement = this.root.querySelector('.schematic');
this.schematicWrapperElement = this.root.querySelector('.schematic-wrapper');
this.tooltip = new Tooltip(this.root.querySelector('.schematic-tooltip'), this);
this.#setupRoot();
// Listen to changes from editor.
if (this.editor) {
this.#setupEditor();
}
// Make sure the 'download firmware' button works.
if (this.firmwareButton) {
this.firmwareButton.addEventListener('click', (e) => this.#flashFirmware(e));
}
// Start loading the parts panel (without blocking further initialization).
this.#loadPartsPanel();
}
// Set the project state. This must be done at load, and when the schematic is
// switched for another. It does _not_ need to happen on each input: that's
// something the simulator already takes care of.
async setState(state) {
// Don't allow downloading the firmware while switching the state out.
if (this.firmwareButton) {
this.firmwareButton.disabled = true;
}
upgradeOldState(state);
// Redraw the schematic SVG.
try {
await this.refresh(state);
} catch (e) {
// Something went wrong. Instead of an endless "Restarting simulation..."
// message, show it as an error.
// This can happen for example when one of the SVGs cannot be loaded.
console.error(e);
this.terminal.appendError(`failed to refresh schematic: ${e}`);
return;
}
// Start first compile.
if (this.apiURL) {
// Run the code in a web worker.
this.#runWithAPI();
}
}
// Return getBoundingClientRect for schematicElement. The value is cached and
// cleared when scrolling (to make sure it is always up-to-date).
get schematicRect() {
if (this._schematicRect === null) {
this._schematicRect = this.schematicElement.getBoundingClientRect();
}
return this._schematicRect;
}
// Configure the editor to listen to modifications.
#setupEditor() {
// Compile the code after a certain delay of inactivity.
let inputCompileTimeout = null;
this.editor.setModifyCallback(() => {
// This callback is called with every input.
if (inputCompileTimeout !== null) {
clearTimeout(inputCompileTimeout);
}
inputCompileTimeout = setTimeout(async () => {
inputCompileTimeout = null;
this.schematic.state.code = this.editor.text();
this.saveState();
await this.refresh();
this.#runWithAPI();
}, inputCompileDelay);
});
}
// Start a firmware file download. This can be used for drag-and-drop
// programming supported by many modern development boards.
#flashFirmware(e) {
e.preventDefault();
// Create a hidden form with the correct values that sends back the file with
// the correct headers to make this a download:
// Content-Disposition: attachment; filename=firmware.hex
let form = document.createElement('form');
form.setAttribute('method', 'POST');
form.setAttribute('action', `${this.apiURL}/compile?target=${this.schematic.parts.get('main').config.name}&format=${this.schematic.parts.get('main').config.firmwareFormat}`);
form.classList.add('d-none');
let input = document.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('name', 'code');
input.value = this.editor.text();
form.appendChild(input);
document.body.appendChild(form);
form.submit();
form.remove();
}
// Initialize this simulator by setting up events etc.
#setupRoot() {
this.root.querySelector('.schematic-button-pause').addEventListener('click', e => {
e.target.disabled = true; // disable until there's a reply from the worker
e.stopPropagation();
this.worker.postMessage({
type: 'playpause',
});
});
if (this.features.has('zoom')) {
// Zoom using the scroll wheel.
// Disable the default wheel event: this would result in a bounce effect
// on Safari and make the scrolling a lot less smooth.
// TODO: pinch to zoom? (e.g. with a trackpad)
this.schematicElement.addEventListener('wheel', e => {
e.preventDefault();
let [positionX, positionY] = this.schematic.cursorPosition(e);
let factor = 1 + (e.deltaY * -0.0005);
this.schematic.zoom(factor, positionX, positionY);
}, {passive: false});
}
if (this.features.has('pan')) {
// Pan using the secondary (usually right) mouse button.
this.schematicElement.addEventListener('contextmenu', e => {
// The default action is a context menu, which we don't want.
// Firefox allows overriding this using shift (which is good, we don't
// want to prevent the context menu entirely) while Chromium doesn't.
e.preventDefault();
})
this.schematicElement.addEventListener('mousedown', e => {
if (e.buttons === 2) {
// Secondary button pressed (only). Start panning (dragging).
let [cursorX, cursorY] = this.schematic.cursorPosition(e);
schematicPan = {
schematic: this.schematic,
initialCursorX: cursorX,
initialCursorY: cursorY,
initialTranslateX: this.schematic.translateX,
initialTranslateY: this.schematic.translateY,
};
}
})
this.schematicElement.addEventListener('mouseup', e => {
// Stop panning the schematic (no matter which way it ended).
schematicPan = null;
})
}
// Listen for keyboard events, to simulate button presses.
this.schematicElement.addEventListener('keydown', e => {
this.schematic.handleKey(e, true);
});
this.schematicElement.addEventListener('keyup', e => {
this.schematic.handleKey(e, false);
});
this.schematicElement.addEventListener('blur', e => {
// Lost focus, so un-press all pressed keys.
this.schematic.handleBlur();
})
this.terminal = new Terminal(this.root.querySelector('.terminal'));
// Switch active panel tab on click of a tab title.
// This is only for the vscode theme.
let tabs = this.root.querySelectorAll('.panels > .tabbar > .tab');
for (let i=0; i<tabs.length; i++) {
let tab = tabs[i];
let panel = this.root.querySelectorAll('.panels > .tabcontent')[i];
tab.addEventListener('click', e => {
// Update active tab.
let tabbar = tab.parentNode;
tabbar.querySelector(':scope > .tab.active').classList.remove('active');
tab.classList.add('active');
// Update active tab content.
let parent = tabbar.parentNode;
parent.querySelector(':scope > .tabcontent.active').classList.remove('active');
panel.classList.add('active');
});
}
window.addEventListener('load', () => this.fixPartsLocation());
window.addEventListener('resize', () => this.fixPartsLocation());
window.addEventListener('scroll', () => {
// Note: this is a passive event so that it won't reduce scrolling
// performance.
this._schematicRect = null;
}, {passive: true});
// Track whether the power tab is visible.
// This is to avoid updating it continuously if not needed.
(new IntersectionObserver((entries) => {
this.powerTabVisible = entries[0].isIntersecting;
if (this.worker) {
this.worker.postMessage({
type: 'powerTabVisible',
visible: this.powerTabVisible,
});
}
})).observe(this.root.querySelector('.panel-power .power-table'));
}
// Initialize the parts panel at the bottom, from where new parts can be
// added.
async #loadPartsPanel() {
let panel = this.root.querySelector('.panel-add .content');
let partsURI = new URL('parts/parts.json', this.baseURL)
let response = await fetch(partsURI);
let json = await response.json();
panel.innerHTML = '';
for (let part of json.parts) {
let config = {};
// Show small image of the part.
let image = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
image.setAttribute('width', '10mm');
image.setAttribute('height', '10mm');
image.classList.add('part-image');
panel.appendChild(image);
let svgPromise = loadSVG(new URL(part.config.svg, this.baseURL))
svgPromise.then((svg) => {
// If needed, shrink the image to fit the available space.
let width = svg.getAttribute('width').replace('mm', '');
let height = svg.getAttribute('height').replace('mm', '');
let wrapper = document.createElementNS('http://www.w3.org/2000/svg', 'g');
wrapper.style.transform = `scale(min(1, min(calc(10 / ${width}), calc(10 / ${height}))))`;
wrapper.appendChild(svg);
image.appendChild(wrapper);
applyOptions();
});
// Make sure the image looks as specified in the options (changeable via
// dropdowns).
let applyOptions = () => {
if (config.color) {
let color = 'rgb(' + config.color[0] + ',' + config.color[1] + ',' + config.color[2] + ')';
image.style.setProperty('--plastic', color);
image.style.setProperty('--shadow', color);
}
};
// Part title.
let titleDiv = document.createElement('div');
titleDiv.textContent = part.config.humanName;
panel.appendChild(titleDiv);
// Options, such as color.
let optionsDiv = document.createElement('div');
for (let [optionKey, optionValues] of Object.entries(part.options || {})) {
let select = this.root.querySelector('.templates > .panel-add-select').cloneNode(true);
for (let [name, value] of Object.entries(optionValues)) {
if (!(optionKey in config)) {
// First option, add it to the config object as default.
config[optionKey] = value;
}
let option = document.createElement('option');
option.textContent = name;
option.value = JSON.stringify(value);
select.appendChild(option);
}
select.addEventListener('change', e => {
let value = JSON.parse(e.target.value);
config[optionKey] = value;
applyOptions();
});
optionsDiv.appendChild(select);
}
panel.appendChild(optionsDiv);
// Button to add the part to the schematic.
let buttonDiv = document.createElement('div');
let button = this.root.querySelector('.templates > .panel-add-button').cloneNode(true);
buttonDiv.appendChild(button);
panel.appendChild(buttonDiv);
// Start adding a part to the schematic when clicking the button.
button.addEventListener('click', async e => {
// Add the part to the UI schematic - but don't really make it part of the
// running circuit yet. Imagine picking up a part and hovering just above
// where you want to put it down.
this.root.classList.add('adding-part');
let id = Math.random().toString(36).slice(2);
let data = {
x: e.pageX - this.schematicRect.width/2 - this.schematicRect.x,
y: e.pageY - this.schematicRect.height/2 - this.schematicRect.y,
};
if (part.location) {
data.location = part.location;
} else {
data.config = Object.assign({}, part.config, config, {
id: id,
});
}
newPart = await Part.load(id, data, this.schematic);
this.schematic.addPart(newPart);
// Truly add the part to the circuit when clicking on it.
let onclick = e => {
let [parts, wires] = newPart.workerConfigRecursive();
this.worker.postMessage({
type: 'add',
parts: parts,
wires: wires,
});
newPart.rootElement.removeEventListener('click', onclick);
newPart = null;
this.root.classList.remove('adding-part');
this.schematic.state.parts[id] = data;
this.saveState();
};
newPart.rootElement.addEventListener('click', onclick);
});
}
}
// Work around a rendering bug in Firefox. Without it, parts of the SVG might
// disappear. It is caused by "transform: translate(50%, 50%)".
// It might be possible to remove this code once this bug is fixed.
// https://bugzilla.mozilla.org/show_bug.cgi?id=1747238
fixPartsLocation() {
this._schematicRect = this.schematicElement.getBoundingClientRect();
this.schematicWrapperElement.style.transform = `translate(${this.schematicRect.width/2}px, ${this.schematicRect.height/2}px)`;
}
#stopWorker() {
if (this.worker) {
this.worker.terminate();
this.worker = null;
if (this.workerUpdate !== null) {
cancelAnimationFrame(this.workerUpdate);
this.workerUpdate = null;
}
}
}
// Refresh simulator. This needs to be called before calling run().
// It also needs to be called before running new code (by calling run()
// again).
// The newState paramter can be provided if the board/schematic will change in
// the next run.
async refresh(newState) {
// Kill previous worker, if it is running.
this.#stopWorker();
// If there was a new state (for example, when switching to a different
// board), restart the Schematic.
if (newState) {
this.schematic = new Schematic(this, this.root, newState);
}
// Redraw screen.
this.schematic.root.classList.add('compiling');
this.terminal.clear('Restarting simulation...');
await this.schematic.refresh();
// Only set the firmware button as enabled when supported by the main part.
if (this.firmwareButton) {
this.firmwareButton.disabled = this.schematic.parts.get('main').config.firmwareFormat === undefined;
}
// Start new worker.
this.worker = new Worker(this.schematicURL);
this.worker.onmessage = (e) => {
this.#workerMessage(e.target, e.data);
};
}
#runWithAPI() {
let compiler = this.schematic.state.compiler || 'tinygo'; // fallback to tinygo
this.run({
url: `${this.apiURL}/compile?compiler=${compiler}&format=wasi&target=${this.schematic.parts.get('main').config.name}`,
method: 'POST',
body: this.editor.text(),
});
}
// Run a new binary. The `refresh` method must have been called before to stop
// the previous run.
// The binary can either be a Uint8Array or an object with parameters 'url',
// 'method' and 'body' that can be used in a fetch() call.
run(binary) {
this.worker.postMessage({
type: 'start',
config: this.schematic.configForWorker(),
binary: binary,
runnerURL: this.runnerURL.toString(),
powerTabVisible: this.powerTabVisible,
});
}
// Show a compiler error. This can be called instead of run() to show the
// compiler error in the output view.
showCompilerError(msg) {
this.terminal.appendError(msg);
}
#workerMessage(worker, msg) {
// Perhaps this worker exited and had some queued messages?
if (worker !== this.worker) {
return;
}
if (msg.type === 'connections') {
this.schematic.updateConnections(msg.pinLists);
} else if (msg.type === 'properties') {
// Set properties in the properties panel at the bottom.
this.schematic.setProperties(msg.properties);
} else if (msg.type === 'power') {
// Set power consumption in the panel at the bottom.
this.schematic.setPower(msg.powerTree);
} else if (msg.type === 'compiling') {
// POST request has been sent, waiting for compilation to finish.
this.terminal.clear('Compiling...');
} else if (msg.type == 'loading') {
// Code has started loading in the worker.
this.terminal.clear('Loading...');
// Request an update.
worker.postMessage({
type: 'getUpdate',
});
// Clear diagnostics left over from a previous compile.
if (this.editor) {
this.editor.setDiagnostics([]);
}
} else if (msg.type === 'started') {
// WebAssembly code was loaded and will start now.
this.schematic.root.classList.remove('compiling');
this.terminal.clear('Running...');
} else if (msg.type === 'exited') {
// Signal to the user that the program has exited.
let text = 'Exited';
if (msg.exitCode) {
text = `Exited (exitcode: ${msg.exitCode})`;
}
this.terminal.appendMessage(text);
} else if (msg.type == 'notifyUpdate') {
// The web worker is signalling that there are updates.
// It won't repeat this message until the updates have been read using
// getUpdate.
// Request the updates in a requestAnimationFrame: this makes sure
// updates are only pushed when needed.
this.workerUpdate = requestAnimationFrame(() => {
this.workerUpdate = null;
// Now request these updates.
worker.postMessage({
type: 'getUpdate',
});
});
} else if (msg.type == 'update') {
// Received updates (such as LED state changes) from the web worker after
// a getUpdate message.
// Update the UI with the new state.
this.schematic.update(msg.updates);
} else if (msg.type === 'powerUpdates') {
for (let [id, update] of Object.entries(msg.updates)) {
this.schematic.updatePower(id, update);
}
} else if (msg.type === 'speed') {
// Change speed, also used to pause the worker.
this.schematic.setSpeed(msg.speed);
} else if (msg.type == 'error') {
// There was an error. Terminate the worker, it has no more work to do.
this.#stopWorker();
this.terminal.appendError(msg.message);
if (msg.source === 'compiler') {
if (this.editor) {
this.editor.setDiagnostics(parseCompilerErrors(msg.message));
}
}
} else if (msg.type === 'stdout') {
this.terminal.write(msg.data);
} else {
console.warn('unknown worker message:', msg.type, msg);
}
}
// Share the code in the editor. Returns the share ID, which can be used as
// part of a URL.
async share() {
// Get the current state.
this.schematic.state.code = this.editor.text();
this.saveState();
// Save this snippet.
let response = await fetch(`${this.apiURL}/share`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(this.schematic.state),
});
let data = await response.json();
// The caller can decide what to do with this, like updating the current URL
// or open tinygo.org/play/s/<id>
return data.id;
}
}
class Schematic {
constructor(simulator, root, state) {
this.simulator = simulator;
this.root = root;
this.state = state;
this.schematic = root.querySelector('.schematic');
this.propertiesContainer = root.querySelector('.panel-properties .content');
this.powerContainer = root.querySelector('.panel-power .power-table');
this.setSpeed(1);
this.scale = 1; // initial scale (1mm in SVG is ~1mm on screen)
this.translateX = 0; // initial translation (before scaling)
this.translateY = 0;
this.pressedKeys = {};
}
// getPin returns a pin object based on a given ID (such as main.D13).
getPin(id) {
let pos = id.lastIndexOf('.');
if (pos < 0) {
throw new Error('invalid pin ID');
}
return this.parts.get(id.slice(0, pos)).pins[id.slice(pos+1)];
}
// Remove and redraw all the SVG parts from scratch.
async refresh() {
// Load all the parts in parallel!
let promises = [];
for (let [id, data] of Object.entries(this.state.parts)) {
promises.push(Part.load(id, data, this));
}
let parts = await Promise.all(promises);
// Remove existing SVG elements.
let partsGroup = this.schematic.querySelector('.schematic-parts');
let wireGroup = this.schematic.querySelector('.schematic-wires');
partsGroup.innerHTML = '';
wireGroup.innerHTML = '';
// Put SVGs in the schematic.
this.parts = new Map();
let hasParts = false;
let top = 0;
let bottom = 0;
for (let part of parts) {
this.addPart(part);
// Calculate the minimum area needed for all the parts in the schematic to
// be visible.
// Add a spacing of 2.5mm (~10px) so that the board has a bit of spacing
// around it.
if (part.rootElement) {
hasParts = true;
let height = parseUnitMM(part.height);
top = Math.min(top, part.data.y-height/2 - 2.5);
bottom = Math.max(bottom, part.data.y+height/2 + 2.5);
}
}
// Set the height of the schematic.
this.root.classList.toggle('no-schematic', !hasParts);
if (hasParts) {
let distance = Math.max(bottom*2, -top*2);
this.schematic.style.height = distance + 'mm';
} else {
this.simulator.root.querySelector('.panel-tab-terminal').click();
}
// Workaround for Chrome positioning bug and Firefox rendering bug.
this.simulator.fixPartsLocation();
// Create wires.
this.wires = [];
for (let config of this.state.wires) {
let from = this.getPin(config.from);
let to = this.getPin(config.to);
if (!from) {
console.error('could not find "from" pin for wire:', config.from);
continue;
}
if (!to) {
console.error('could not find "to" pin for wire:', config.to);
continue;
}
let wire = new Wire(this, from, to);
this.wires.push(wire);
wireGroup.appendChild(wire.line);
wire.updateFrom();
wire.updateTo();
}
}
addPart(part) {
this.parts.set(part.id, part);
part.createSubParts();
for (let [id, subpart] of Object.entries(part.subparts)) {
this.parts.set(id, subpart);
}
if (part.rootElement) {
let partsGroup = this.schematic.querySelector('.schematic-parts');
partsGroup.appendChild(part.createElement(this.schematic));
}
}
// Handle keyboard input and emulate these keys as physical keys.
handleKey(e, pressed) {
let key = e.key;
if (key.length === 1) {
key = key.toUpperCase(); // probably a key like 'A'
}
for (let part of this.parts.values()) {
if (part.config.type === 'pushbutton' && part.config.key === key) {
if (pressed && this.pressedKeys[key] === part.id) {
// Repeat key (held down), ignore this event.
return;
}
this.simulator.worker.postMessage({
type: 'input',
id: part.id,
event: pressed ? 'press' : 'release',
});
if (pressed) {
this.pressedKeys[key] = part.id;
} else {
delete this.pressedKeys[key];
}
return;
}
}
}
// Release all pressed keys when the schematic loses focus.
handleBlur() {
for (let [key, partId] of Object.entries(this.pressedKeys)) {
this.simulator.worker.postMessage({
type: 'input',
id: partId,
event: 'released',
});
delete this.pressedKeys[key];
}
}
// Convert a mouse event into a logical cursor position (in millimeters from
// the center of the schematic view, before translating/scaling).
cursorPosition(e) {
let schematicRect = this.simulator.schematicRect;
let cursorX = ((e.clientX - schematicRect.left) - schematicRect.width/2) / pixelsPerMillimeter;
let cursorY = ((e.clientY - schematicRect.top) - schematicRect.height/2) / pixelsPerMillimeter;
return [cursorX, cursorY];
}
// Increase or decrease the scale factor with the given amount.
zoom(factor, cursorX, cursorY) {
let newScale = this.scale * factor; // apply scale
newScale = Math.min(Math.max(this.scale * factor, 0.1), 50); // limit zoom amount
if (newScale !== this.scale) {
// Calculate distance between schematic center point and cursor, in
// pre-scaled millimeters.
let cursorDiffX = cursorX - this.translateX;
let cursorDiffY = cursorY - this.translateY;
// Calculate the change in distance between the schematic center point and
// the cursor, before and after zooming.
let diffX = ((cursorDiffX * this.scale) - (cursorDiffX * newScale)) / this.scale;
let diffY = ((cursorDiffY * this.scale) - (cursorDiffY * newScale)) / this.scale;
// Apply the new scale (pan+zoom).
this.translateX += diffX;
this.translateY += diffY;
this.scale = newScale;
this.#repositionParts();
}
}
// Move (pan) the schematic to the new location.
moveTo(translateX, translateY) {
this.translateX = translateX;
this.translateY = translateY;
this.#repositionParts();
}
// Move parts to a new location if needed.
#repositionParts() {
// Update all parts (except for subparts).
// This is done all at once (without updating wires for each part) so that
// we don't force a reflow.
for (let part of this.parts.values()) {
if (!part.parent) {
part.updatePosition();
}
}
// Calculate new wire locations. This forces a single reflow.
for (let part of this.parts.values()) {
if (!part.parent) {
part.calculateWires();
}
}
// Calculate tooltip location (if visible).
this.simulator.tooltip.calculatePosition();
// Apply new wire locations. This only sets properties, so doesn't cause a
// reflow.
for (let part of this.parts.values()) {
if (!part.parent) {
part.applyWires();
}
}
// Update tooltip location (if visible).
this.simulator.tooltip.updatePosition();
}
// Create a 'config' struct with a flattened view of the schematic, to be sent
// to the worker.
configForWorker() {
let config = {
parts: [],
wires: [],
};
for (let [id, part] of this.parts.entries()) {
// The main part is the part running the code.
if (id === 'main') {
config.mainPart = 'main.' + part.config.mainPart;
}
// Add this part.
config.parts.push(part.workerConfig());
// Add internal wires. Think of them as copper traces on a board.
for (let wire of part.config.wires || []) {
config.wires.push({
from: id + '.' + wire.from,
to: id + '.' + wire.to,
});
}
}
// Wires manually added in the schematic.
for (let wire of this.wires) {
config.wires.push({
from: wire.from.id,
to: wire.to.id,
});
}
return config;
}
// setProperties sets the list of part properties to the bottom "properties"
// panel.
setProperties(properties) {
this.propertiesContainer.innerHTML = '';
this.propertyElements = {};
for (let property of properties) {
// Add property name (usually the device name).
let nameEl = document.createElement('div');
this.propertiesContainer.appendChild(nameEl);
nameEl.textContent = property.humanName + ':';
// Add value of property.
let valueEl = document.createElement('div');
this.propertiesContainer.appendChild(valueEl);
if (property.type === 'text') {
// Simple text property.
this.propertyElements[property.id] = {text: valueEl};
} else if (property.type === 'ledstrip') {
// Display the colors of this LED strip.
let header = document.createElement('div');
valueEl.classList.add('ledstrip');
valueEl.appendChild(header);
for (let color of property.colors) {
let colorHeader = document.createElement('div');
colorHeader.textContent = color.title+':';
header.appendChild(colorHeader);
}
// Add information for each LED.
let stripElements = [];
for (let i=0; i<property.length; i++) {
let el = document.createElement('div');
valueEl.appendChild(el);
let ledElements = [];
for (let color of property.colors) {
let channelEl = document.createElement('div');
channelEl.classList.add('ledstrip-channel');
el.appendChild(channelEl);
ledElements.push(channelEl);
}
stripElements.push(ledElements);
}
this.propertyElements[property.id] = {
colors: property.colors,
ledstrip: stripElements,
};
} else {
console.warn('unknown property type:', property.type);
}
}
}
// Update the power tab at the bottom, replace all values with the new tree.
setPower(tree) {
this.powerContainer.innerHTML = '<div></div><div>now</div><div>maximum</div><div>average</div>';
this.powerElements = {};
this.#addPowerNodes(tree, null, 0);
}
// Recursively add data rows to the power consumption tree view.
#addPowerNodes(tree, parent, indent) {
let rows = [];
for (let i=0; i < tree.length; i++) {
// Calculate some hacky tree symbols. This probably needs to be replaced
// with a nice CSS tree view at some point.
let node = tree[i];
let prefix = '';
if (indent > 0) {
prefix = i == tree.length-1 ? '└ ' : '├ ';
}
// Add name.
let nameEl = document.createElement('div');
nameEl.textContent = prefix + node.node.humanName + ':';
this.powerContainer.appendChild(nameEl);
// Add current power consumption.
let valueEl = document.createElement('div');
valueEl.textContent = '?';
this.powerContainer.appendChild(valueEl);
// Add maximum power consumption since start.
let maxEl = document.createElement('div');
maxEl.textContent = '?';
this.powerContainer.appendChild(maxEl);
// Add average power consumption since start.
let avgEl = document.createElement('div');
avgEl.textContent = '?';
this.powerContainer.appendChild(avgEl);
// Keep track of them so we can show new values coming from the
// simulation.
let row = {
parent: parent,
element: valueEl,
elementMax: maxEl,
elementAvg: avgEl,
};
this.powerElements[node.node.id] = row;
rows.push(row)
// Put children in the tree view.
if (node.children) {
row.children = this.#addPowerNodes(node.children, row, indent+1);
}
}
return rows;
}
// Update a (sub)part in the UI with the given updates coming from the web
// worker that's running the simulated program.
update(updates) {
for (let update of updates) {
let part = this.parts.get(update.id);
// LED strips, like typical WS2812 strips.
if (update.ledstrip) {
for (let i=0; i<part.leds.length; i++) {
let properties = update.ledstrip[i];
part.leds[i].style.setProperty('--color', properties.color);
part.leds[i].style.setProperty('--shadow', properties.shadow);
}
}
// Displays of various sorts that render to a canvas element.
if (update.canvas) {
// TODO: do the createImageBitmap in the web worker.
let imageData = new ImageData(update.canvas, part.config.width, part.config.height);
createImageBitmap(imageData).then(bitmap => {
part.context.drawImage(bitmap, 0, 0);
bitmap.close();
});
}
// Simple devices (like LEDs) that only need to change some CSS properties.
for (let [key, value] of Object.entries(update.cssProperties || {})) {
if (!part.rootElement)
throw `part ${part.id} has no root element`;
part.rootElement.style.setProperty('--' + key, value);
}
// Update the properties panel at the bottom if needed.
// TODO: use IntersectionObserver to only update these properties when
// visible! That should reduce CPU usage for fast-changing properties.
if (update.properties) {
let prop = this.propertyElements[update.id];
if (!prop) {
console.error('properties not defined for ' + update.id);
} else if (prop.text) {
// Simple text-based property.
prop.text.textContent = update.properties;
} else if (prop.ledstrip) {
// LED strip in various color combinations.
for (let i=0; i<prop.ledstrip.length; i++) {
let ledElements = prop.ledstrip[i];
let values = update.properties[i];
for (let j=0; j<ledElements.length; j++) {
let channel = ledElements[j];
let value = values[j];
channel.textContent = value;
let color = { // use the theme's ANSI colors on VS Code
'red': 'var(--vscode-terminal-ansiRed, #f00)',
'green': 'var(--vscode-terminal-ansiGreen, #0f0)',
'blue': 'var(--vscode-terminal-ansiBlue, #00f)',
}[prop.colors[j].color];
channel.style.backgroundImage = 'linear-gradient(to left, '+color+' '+(value/255*75)+'%, transparent 0%)';
}
}
} else {
console.warn('unknown property:', update.properties);
}
}
// Add the current consumption to the power panel at the bottom.
if ('power' in update) {
this.updatePower(update.id, update.power);
}
}
}
updatePower(id, power) {
let row = this.powerElements[id];
if (power.current !== row.current || power.maxCurrent !== row.maxCurrent || power.avgCurrent !== row.avgCurrent) {
row.current = power.current;
row.maxCurrent = power.maxCurrent;
row.avgCurrent = power.avgCurrent;
while (row) {
if (row.children.length) {
row.element.textContent = formatCurrent(sumCurrentChildren(row, 'current'));
row.elementMax.textContent = formatCurrent(sumCurrentChildren(row, 'maxCurrent'));
row.elementAvg.textContent = formatCurrent(sumCurrentChildren(row, 'avgCurrent'));
} else {
row.element.textContent = formatCurrent(row.current);
row.elementMax.textContent = formatCurrent(row.maxCurrent);
row.elementAvg.textContent = formatCurrent(row.avgCurrent);
}
row = row.parent;
}
}
}
// findWire returns the index for the first wire between the given two pins,
// or -1 if no such wire exists.
findWire(from, to) {
for (let i=0; i<this.state.wires.length; i++) {
let wire = this.state.wires[i];
if (wire.from === from && wire.to === to || wire.from === to && wire.to === from) {
return i;
}
}
return -1;
}
// removeWire removes the given wire from the schematic state. It does not
// remove the wire from the UI.