forked from sugarlabs/musicblocks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterface.js
More file actions
641 lines (606 loc) · 22.7 KB
/
interface.js
File metadata and controls
641 lines (606 loc) · 22.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
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
/**
* @file This contains the utilities for the interface between Music Blocks blocks and JavaScript
* based Music Blocks API.
* @author Anindya Kundu
*
* @copyright 2020 Anindya Kundu
*
* @license
* This program is free software; you can redistribute it and/or modify it under the terms of the
* The GNU Affero General Public License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* You should have received a copy of the GNU Affero General Public License along with this
* library; if not, write to the Free Software Foundation, 51 Franklin Street, Suite 500 Boston,
* MA 02110-1335 USA.
*
* Private members' names begin with underscore '_".
*/
/* global JSEditor, SHARP, FLAT, NATURAL, DOUBLESHARP, DOUBLEFLAT, DEFAULTVOICE */
/* exported JSInterface */
/**
* @class
* @classdesc contains the lists and lookups for relevant blocks, and utility methods to access them.
*/
class JSInterface {
/**
* @static
* list of clamp block names
*/
static _clampBlocks = [
// Rhythm blocks
"newnote",
"osctime",
"rhythmicdot2",
"tie",
"multiplybeatfactor",
"newswing2",
// Meter blocks
"drift",
// Pitch blocks
"accidental",
"setscalartransposition",
"settransposition",
"invert1",
// Intervals blocks
"definemode",
"interval",
"semitoneinterval",
// Tone blocks
"settimbre",
"vibrato",
"chorus",
"phaser",
"tremolo",
"dis",
"harmonic2",
// Ornament blocks
"newstaccato",
"newslur",
"neighbor2",
// Volume blocks
"crescendo",
"decrescendo",
"articulation",
// Drum blocks
"setdrum",
"mapdrum"
];
/**
* @static
* list of methods having a return value
*/
static _returningMethods = ["getDict", "getDict2", "dictionary"];
/**
* @static
* lookup table for block names to setter names
*/
static _setterNameLookup = {
// Meter blocks
pickup: "PICKUP",
// Intervals blocks
moveble: "MOVABLE",
// Volume blocks
setnotevolume: "MASTERVOLUME",
setpanning: "PANNING"
};
/**
* @static
* lookup table for block names to getter names
*/
static _getterNameLookup = {
// Rhythm blocks
mynotevalue: "NOTEVALUE",
// Meter blocks
elapsednotes: "WHOLENOTESPLAYED",
beatvalue: "BEATCOUNT",
measurevalue: "MEASURECOUNT",
bpmfactor: "BPM",
beatfactor: "BEATFACTOR",
currentmeter: "CURRENTMETER",
// Pitch blocks
deltapitch2: "SCALARCHANGEINPITCH",
deltapitch: "CHANGEINPITCH",
consonantstepsizeup: "SCALARSTEPUP",
consonantstepsizedown: "SCALARSTEPDOWN",
// Intervals blocks
key: "CURRENTKEY",
currentmode: "CURRENTMODE",
modelength: "MODELENGTH",
// Volume blocks
notevolumefactor: "MASTERVOLUME",
// Graphics blocks
x: "X",
y: "Y",
heading: "HEADING",
// Pen blocks
pensize: "PENSIZE",
color: "COLOR",
shade: "SHADE",
grey: "GREY"
};
/**
* @static
* lookup table for block names to API method names
*/
static _methodNameLookup = {
// Rhythm blocks
newnote: "playNote",
osctime: "playNoteMillis",
rest2: "playRest",
rhythmicdot2: "dot",
tie: "tie",
multiplybeatfactor: "multiplyNoteValue",
newswing2: "swing",
// Meter blocks
meter: "setMeter",
setbpm3: "setBPM",
setmasterbpm2: "setMasterBPM",
everybeatdo: "onEveryNoteDo",
everybeatdonew: "onEveryBeatDo",
onbeatdo: "onStrongBeatDo",
offbeatdo: "onWeakBeatDo",
drift: "setNoClock",
elapsednotes2: "getNotesPlayed",
// Pitch blocks
pitch: "playPitch",
steppitch: "stepPitch",
nthmodalpitch: "playNthModalPitch",
pitchnumber: "playPitchNumber",
hertz: "playHertz",
accidental: "setAccidental",
setscalartransposition: "setScalarTranspose",
settransposition: "setSemitoneTranspose",
register: "setRegister",
invert1: "invert",
setpitchnumberoffset: "setPitchNumberOffset",
number2pitch: "numToPitch",
number2octave: "numToOctave",
// Intervals blocks
setkey2: "setKey",
// "definemode": "defineMode",
interval: "setScalarInterval",
semitoneinterval: "setSemitoneInterval",
settemperament: "setTemperament",
// Tone blocks
settimbre: "setInstrument",
vibrato: "doVibrato",
chorus: "doChorus",
phaser: "doPhaser",
tremolo: "doTremolo",
dis: "doDistortion",
harmonic2: "doHarmonic",
// Ornament blocks
newstaccato: "setStaccato",
newslur: "setSlur",
neighbor2: "doNeighbor",
// Volume blocks
crescendo: "doCrescendo",
decrescendo: "doDecrescendo",
articulation: "setRelativeVolume",
setsynthvolume: "setSynthVolume",
synthvolumefactor: "getSynthVolume",
// Drum blocks
playdrum: "playDrum",
setdrum: "setDrum",
mapdrum: "mapPitchToDrum",
playnoise: "playNoise",
// Number blocks
random: "MathUtility.doRandom",
oneOf: "MathUtility.doOneOf",
distance: "MathUtility.doCalculateDistance",
// Graphics blocks
forward: "goForward",
back: "goBackward",
right: "turnRight",
left: "turnLeft",
setxy: "setXY",
setheading: "setHeading",
arc: "drawArc",
bezier: "drawBezier",
controlpoint1: "setBezierControlPoint1",
controlpoint2: "setBezierControlPoint2",
clear: "clear",
scrollxy: "scrollXY",
// Pen blocks
setcolor: "setColor",
setgrey: "setGrey",
setshade: "setShade",
sethue: "setHue",
settranslucency: "setTranslucency",
setpensize: "setPensize",
penup: "penUp",
pendown: "penDown",
// "": "doStartFill",
// "": "doStartHollowLine",
background: "fillBackground",
setfont: "setFont",
// Dictionary blocks
dictionary: "getDict",
setDict: "setValue",
getDict: "getValue",
setDict2: "setValue",
getDict2: "getValue",
// Extras
print: "print"
};
/**
* @static
* maps block name to corresponding API args order
*/
static _rearrangeArgsLookup = {
setDict: [1, 2, 0],
getDict: [1, 0]
};
/**
* Returns whether passed argument is the name of a clamp block.
*
* @param {String} blockName
* @returns {Boolean}
*/
static isClampBlock(blockName) {
return JSInterface._clampBlocks.includes(blockName);
}
/**
* Returns whether passed argument corresponds to a setter.
*
* @param {String} blockName
* @returns {Boolean}
*/
static isSetter(blockName) {
return blockName in JSInterface._setterNameLookup;
}
/**
* Returns whether passed argument corresponds to a getter.
*
* @param {String} blockName
* @returns {Boolean}
*/
static isGetter(blockName) {
return blockName in JSInterface._getterNameLookup;
}
/**
* Returns whether passed argument corresponds to a method.
*
* @param {String} blockName
* @returns {Boolean}
*/
static isMethod(blockName) {
return blockName in JSInterface._methodNameLookup;
}
/**
* Returns whether passed argument corresponds to a method.
*
* @param {String} blockName
* @returns {Boolean}
*/
static methodReturns(blockName) {
return JSInterface._returningMethods.includes(blockName);
}
/**
* Returns the setter name corresponding to the blockname, returns "null" if doesn't exist.
*
* @param {String} blockName
* @returns {String}
*/
static getSetterName(blockName) {
return JSInterface.isSetter(blockName) ? JSInterface._setterNameLookup[blockName] : null;
}
/**
* Returns the getter name corresponding to the blockname, returns "null" if doesn't exist.
*
* @param {String} blockName
* @returns {String}
*/
static getGetterName(blockName) {
return JSInterface.isGetter(blockName) ? JSInterface._getterNameLookup[blockName] : null;
}
/**
* Returns the method name corresponding to the blockname, returns "null" if doesn't exist.
*
* @param {String} blockName
* @returns {String}
*/
static getMethodName(blockName) {
return JSInterface.isMethod(blockName) ? JSInterface._methodNameLookup[blockName] : null;
}
/**
* Rearranges the method arguments as required by the API.
*
* @param {String} methodName
* @param {[*]} args
* @returns {[*]}
*/
static rearrangeMethodArgs(methodName, args) {
if (methodName in JSInterface._rearrangeArgsLookup) {
args = JSInterface._rearrangeArgsLookup[methodName].map((index) => args[index]);
}
return args;
}
// ========= Parameter Validation ==============================================================
/**
* Validates arguments passed to API methods.
* In case of invalidity, defaults to acceptable value if possible, else throws error message.
*
* @static
* @param {String} methodName - API method name
* @param {[*]} args - list of arguments
* @returns {[*]} - list of valid arguments
*/
static validateArgs(methodName, args) {
// JSInterface._methodArgConstraints is defined in ./constraints.js
if (!(methodName in JSInterface._methodArgConstraints)) return args;
const constraints = JSInterface._methodArgConstraints[methodName];
const finalArgs = [];
for (const i in constraints) {
let [arg, props] = [args[i], constraints[i]];
// for multiple types
if (Array.isArray(props)) {
for (const prop of props) {
if (typeof arg === prop["type"]) {
props = prop;
break;
}
}
if (Array.isArray(props)) {
const error = `TypeMismatch error: expected one of "${props
.map((prop) => prop["type"])
.toString()}" but found "${typeof arg}"`;
JSEditor.logConsole(error, "maroon");
throw error;
}
}
if (typeof arg !== props["type"]) {
if (typeof arg === "string" && props["type"] === "number") {
if (!isNaN(Number(arg))) {
arg = Number(arg);
} else {
const error = 'TypeMismatch error: expected "number" but found "string"';
JSEditor.logConsole(error, "maroon");
throw error;
}
} else if (typeof arg === "string" && props["type"] === "boolean") {
if (arg.toLowerCase() === "true") {
arg = true;
} else if (arg.toLowerCase() === "false") {
arg = false;
} else {
JSEditor.logConsole(`${arg} in "${methodName}" reset to ${true}`);
arg = true;
}
} else {
const error = `TypeMismatch error: expected "${
props["type"]
}" but found "${typeof arg}"`;
JSEditor.logConsole(error, "maroon");
throw error;
}
}
switch (props["type"]) {
case "number":
if (arg < props["constraints"]["min"]) {
JSEditor.logConsole(
`${arg} in "${methodName}" reset to ${props["constraints"]["min"]}`
);
arg = props["constraints"]["min"];
} else if (arg > props["constraints"]["max"]) {
JSEditor.logConsole(
`${arg} in "${methodName}" reset to ${props["constraints"]["max"]}`
);
arg = props["constraints"]["max"];
}
if (props["constraints"]["integer"] && !Number.isInteger(arg)) {
JSEditor.logConsole(
`${arg} in "${methodName}" reset to ${Math.floor(arg)}`
);
arg = Math.floor(arg);
}
break;
case "function":
if (
props["constraints"]["async"] &&
arg[Symbol.toStringTag] !== "AsyncFunction"
) {
const error = `${args[0]} error: expected "async" function`;
JSEditor.logConsole(error, "maroon");
throw error;
}
break;
case "string":
if (props["constraints"]["type"] === "solfegeorletter") {
const strs = arg.split(" ");
const solfeges = ["do", "re", "mi", "fa", "sol", "la", "ti"];
const letters = ["c", "d", "e", "f", "g", "a", "b"];
if (
solfeges.includes(strs[0].toLowerCase()) ||
letters.includes(strs[0].toLowerCase())
) {
if (solfeges.includes(strs[0].toLowerCase())) {
arg = strs[0].toLowerCase();
} else {
arg = strs[0].toUpperCase();
}
if (strs.length > 1) {
const accidentals = [SHARP, FLAT, NATURAL, DOUBLESHARP, DOUBLEFLAT];
const accidentals2 = {
sharp: SHARP,
flat: FLAT,
doublesharp: DOUBLESHARP,
doubleflat: DOUBLEFLAT
};
if (accidentals.includes(strs[1])) {
arg += strs[1];
} else if (strs[1].toLowerCase() in accidentals2) {
arg += accidentals2[strs[1].toLowerCase()];
}
}
} else {
JSEditor.logConsole(`${arg} in "${methodName}" reset to ${"sol"}`);
arg = "sol";
}
} else if (props["constraints"]["type"] === "accidental") {
const accidentalOuts = [
`sharp ${SHARP}`,
`flat ${FLAT}`,
`natural ${NATURAL}`,
`double sharp ${DOUBLESHARP}`,
`double flat ${DOUBLEFLAT}`
];
const accidentals = [SHARP, FLAT, NATURAL, DOUBLESHARP, DOUBLEFLAT];
const accidentals2 = [
"sharp",
"flat",
"natural",
"doublesharp",
"doubleflat"
];
if (accidentals.includes(arg)) {
arg = accidentalOuts[accidentals.indexOf(arg)];
} else if (accidentals2.includes(arg.toLowerCase())) {
arg = accidentalOuts[accidentals2.indexOf(arg.toLowerCase())];
}
} else if (props["constraints"]["type"] === "oneof") {
let index = -1;
for (const i in props["constraints"]["values"]) {
if (
props["constraints"]["values"][i].toLowerCase() ===
arg.toLowerCase()
) {
index = i;
break;
}
}
if (index !== -1) {
arg = props["constraints"]["values"][index];
} else {
JSEditor.logConsole(
`${arg} in "${methodName}" reset to ${
props["constraints"]["values"][
props["constraints"]["defaultIndex"]
]
}`
);
arg =
props["constraints"]["values"][
props["constraints"]["defaultIndex"]
];
}
} else if (props["constraints"]["type"] === "synth") {
const instruments = [
"piano",
"harmonuium",
"mandolin",
"violin",
"viola",
"cello",
"bass",
"double bass",
"sitar",
"guitar",
"acoustic guitar",
"flute",
"clarinet",
"saxophone",
"tuba",
"trumpet",
"oboe",
"trombone",
"banjo",
"koto",
"dulcimer",
"electric guitar",
"bassoon",
"celeste",
"xylophone",
"electronic synth",
"sine",
"square",
"sawtooth",
"triangle",
"vibraphone"
];
if (instruments.includes(arg)) {
arg = arg.toLowerCase();
} else {
JSEditor.logConsole(
`${arg} in "${methodName}" reset to ${DEFAULTVOICE}`
);
arg = DEFAULTVOICE;
}
} else if (props["constraints"]["type"] === "drum") {
const drums = [
"snare drum",
"kick drum",
"tom tom",
"floor tom tom",
"cup drum",
"darbuka drum",
"japanese drum",
"hi hat",
"ride bell",
"cow bell",
"triangle bell",
"finger cymbals",
"chime",
"gong",
"clang",
"crash",
"clap",
"slap",
"raindrop"
];
if (drums.includes(arg)) {
arg = arg.toLowerCase();
} else {
JSEditor.logConsole(
`${arg} in "${methodName}" reset to ${"kick drum"}`
);
arg = "kick drum";
}
} else if (props["constraints"]["type"] === "noise") {
if (arg.toLowerCase() === "white noise") {
arg = "noise1";
} else if (arg.toLowerCase() === "brown noise") {
arg = "noise2";
} else if (arg.toLowerCase() === "pink noise") {
arg = "noise3";
} else {
JSEditor.logConsole(
`${arg} in "${methodName}" reset to ${"white noise"}`
);
arg = "noise1";
}
} else if (props["constraints"]["type"] === "letterkey") {
const strs = arg.split(" ");
const letters = ["c", "d", "e", "f", "g", "a", "b"];
if (letters.includes(strs[0].toLowerCase())) {
arg = strs[0].toUpperCase();
if (strs.length > 1) {
const accidentals = [SHARP, FLAT, NATURAL, DOUBLESHARP, DOUBLEFLAT];
const accidentals2 = {
sharp: SHARP,
flat: FLAT,
doublesharp: DOUBLESHARP,
doubleflat: DOUBLEFLAT
};
if (accidentals.includes(strs[1])) {
arg += strs[1];
} else if (strs[1].toLowerCase() in accidentals2) {
arg += accidentals2[strs[1].toLowerCase()];
}
}
} else {
JSEditor.logConsole(`${arg} in "${methodName}" reset to ${"C"}`);
arg = "C";
}
}
break;
}
finalArgs.push(arg);
}
return finalArgs;
}
}
if (typeof module !== "undefined" && module.exports) {
module.exports = JSInterface;
}