-
Notifications
You must be signed in to change notification settings - Fork 0
/
impure_functions.js
719 lines (677 loc) · 30.2 KB
/
impure_functions.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
// from colornotes.qml:
// apply function to notes in selection (or all notes)
function applyToChordsInSelection(fullScoreIfNoSelection, limit, func) {
var cursor = curScore.newCursor();
cursor.rewind(1);
var startStaff;
var endStaff;
var endTick;
var fullScore = false;
if (!cursor.segment) { // no selection
if (!fullScoreIfNoSelection) {
return
}
fullScore = true;
startStaff = 0; // start with 1st staff
endStaff = curScore.nstaves - 1; // and end with last
} else {
startStaff = cursor.staffIdx;
cursor.rewind(2);
if (cursor.tick == 0) {
// this happens when the selection includes
// the last measure of the score.
// rewind(2) goes behind the last segment (where
// there's none) and sets tick=0
endTick = curScore.lastSegment.tick + 1;
} else {
endTick = cursor.tick;
}
endStaff = cursor.staffIdx;
}
console.log(`applyToChordsInSelection: ${startStaff} - ${endStaff} - ${endTick}`)
let counter = 0
for (var staff = startStaff; staff <= endStaff; staff++) {
for (var voice = 0; voice < 4; voice++) {
cursor.rewind(1); // sets voice to 0
cursor.voice = voice; //voice has to be set after goTo
cursor.staffIdx = staff;
if (fullScore)
cursor.rewind(0) // if no selection, beginning of score
while (cursor.segment && (fullScore || cursor.tick < endTick)) {
if (cursor.element && cursor.element.type == Element.CHORD) {
// The chord element includes grace notes
let graceChords = cursor.element.graceNotes;
for (let i = 0; i < graceChords.length; i++) {
func(graceChords[i])
counter++
if (counter >= limit) {
return
}
}
func(cursor.element)
counter++
if (counter >= limit) {
return
}
}
cursor.next();
}
}
}
}
function populateInstrumentList() {
let request = new XMLHttpRequest()
request.onreadystatechange = function() {
if (request.readyState == XMLHttpRequest.DONE) {
if (request.status == 200) {
console.log("Fetched instrument list:\n" + request.responseText)
// request.response is not a JS object for some reason?!
const result = JSON.parse(request.responseText)
const model = comboModel.model
model.clear()
// Populate list; see also nn2gs.qml: comboModel -> ListModel
result.map(i => model.append({ key: i.iModelId.toLowerCase(), value: i.iDescription, tonarten: JSON.stringify(i.iTonarten) }));
comboModel.currentIndex = 0
} else {
console.log("Ignoring HTTP error on fetching instrument list.");
console.log(request.status)
}
}
}
// const url = apiUrl + '/instruments?isGoodForGriffschrift'
const url = apiUrl + '/instruments' // <-- for now, allow all instruments; see https://musescore.org/en/node/318711
console.log('GET ' + url)
request.open('GET', url, true)
request.send()
}
// Adapted from abc import plugin
function callApi(chords, reverse, successCallback) {
let content = JSON.stringify(chordsAsApiInput(chords, reverse))
//console.log("content : " + content)
let queryString = '?' +
// queryStringArg('tonart', spinnerTonart.displayText, true) +
queryStringArg('tonart', tonarten[spinnerTonart.value][1].toLowerCase(), true) +
queryStringArg('model', comboModel.currentKey()) +
(reverse ? queryStringArg('reverse', 'yes') : '') +
(txtLicenseKey.text ? queryStringArg('license', txtLicenseKey.text) : '')
console.log(queryString)
let request = new XMLHttpRequest()
request.onreadystatechange = function() {
if (request.readyState == XMLHttpRequest.DONE) {
console.log("HTTP status: " + request.status)
if (request.status == 200) {
console.log("API response:\n" + request.responseText)
try {
lastResults = JSON.parse(request.responseText)
} catch (e) {
console.error("Invalid JSON response. Could not parse.")
messagePane.showError("Ungültige Antwort vom Server.")
}
successCallback(chords, lastResults)
} else if (request.status >= 500) {
// Server-Fehler.
messagePane.showError(`Fehler beim Server. Funktioniert ${apiUrl}?`)
} else if (request.status >= 400) {
// Fehler bei Kommunikation.
messagePane.showError(`Fehler bei der Kommunikation mit dem Server. Funktioniert ${apiUrl}?`)
} else if (request.status >= 300) {
// Lizenzfehler?
// TODO change error message when authorize system works...
messagePane.showError(`Wahrscheinlich passt die Lizenz nicht oder Sie haben noch eine alte Version dieses Plugins. Überprüfen: ${apiUrl}?license=${txtLicenseKey.text}.`)
} else {
// Netzwerkfehler?
let s = `Request failed with HTTP status ${request.status}\nReceived response headers:\n${request.getAllResponseHeaders()}\nResponse text:\n${request.responseText}`
messagePane.showError(`Unbekannter Netzwerkfehler (HTTP Status Code ${request.status}). Funktioniert das Internet? Funktioniert ${apiUrl}?\n\n${s}`)
console.error(s)
}
} else {
// Netzwerkfehler?
//messagePane.showError(`Wahrscheinlich Netzwerkfehler. Funktioniert das Internet? Funktioniert ${apiUrl}?`)
console.log(`HTTP request ready status: ${request.readyState} (not DONE)`)
}
}
console.log(`Run in shell for testing:
cat <<TEXT > test.json
${content}
TEXT
curl -H "Content-Type: application/json" --data-binary @test.json "${apiUrl + queryString}"
`)
request.open("POST", apiUrl + queryString, true)
request.setRequestHeader("Content-Type", "application/json")
request.send(content)
}
function collectChords() {
// It seems to work: Chords are always associated to a voice.
const selectedVoices = getSelectedVoices()
let chords = []
function chordCollecter(chord) {
if (containsRedNote(chord)) {
console.log(`Collecting chords: Current chord contains a red note. Skipping to next chord.`)
} else if (selectedVoices.includes(chord.voice)) {
chords.push(chord)
}
}
applyToChordsInSelection(false, maxChordLimit + 1, chordCollecter)
return chords
}
function changeNotes(zd, reverse) {
return function(chords, zdResults) {
lastZD = zd
let results = extractZDResults(zd, zdResults)
console.log(zd + ' ' + results)
if (chords.length != results.length) {
console.error(`Length of selected chords (${chords.length}) and translation result (${results.length}) do not match. This is likely a bug. Aborting and invalidating current translation result.`)
invalidateCurrentResults()
return
}
let change = reverse ? changeNotesOfChordReverse : changeNotesOfChord
let invalidNotesCounter = 0
let error = null
curScore.startCmd()
for (let i = 0; i < chords.length; i++) {
let chord = chords[i]
let result = results[i]
// try {
invalidNotesCounter += change(chord, result, zd, i)
// } catch (e) {
// console.error(e.message)
// console.trace()
// error = e
// }
}
curScore.endCmd()
if (error) {
messagePane.showError(`Fehler: ${error.message}`)
}
if (invalidNotesCounter) {
messagePane.showError(`${invalidNotesCounter} Note(n) konnten nicht übersetzt werden und wurden rot markiert.\n\nEntweder existieren sie nicht auf dem Instrument oder sie waren bereits rot markiert. Die Akkorde mit roten Noten wurden bei der Übersetzung übersprungen.`)
}
}
}
function changeNotesOfChordReverse(chord, result, zd, chordIndex) {
let notes = chord.notes
let invalidNotesCounter = 0
if (containsRedNote(notes)) {
console.log(`Current chord ${chordIndex} contains a red note. Leaving it unchanged. Skipping to next chord.`)
invalidNotesCounter++
return invalidNotesCounter
}
if (result.Right) {
let resultr = result.Right
for (let j = 0; j < notes.length; j++) {
let noteName = resultr[j]
let note = notes[j]
if (notes.length != resultr.length) {
console.warn(`Length of current chord (${notes.length}) and translation result (${resultr.length}) do not match in chord ${chordIndex}, note ${j}. Skipping to next chord.`)
break
}
let pitch = getMidiPitch(noteName)
if (pitch === null) {
console.warn(`Invalid note position ${noteName} in translation result in chord ${chordIndex}, note ${j}. Skipping to next note.`)
continue
}
let tpc = lookupTonalPitchClass(noteName)
note.headGroup = NoteHeadGroup.HEAD_NORMAL
removeCrossBeforeHead(note)
note.mirrorHead = 0
console.log(`Changing GS ${note.pitch} (tpc=${note.tpc}) to Nn ${pitch} (tpc=${tpc})`)
note.pitch = pitch
note.tpc1 = tpc
note.tpc2 = tpc
note.visible = true // Manche GS-Varianten machen Notenkopf unsichtbar und verwenden stattdessen ein anderes Symbol
note.headType = NoteHeadType.HEAD_AUTO // Manche GS-Varianten ändern den Typ des Notenkopfes
setAccidentalVisible(note, true)
resetPlayedNotePitch(note)
}
} else if (result.Left) {
let invalidSymbols = result.Left.map(({position, crossed}) => [getMidiPitch(position), crossed])
for (let j = 0; j < notes.length; j++) {
let note = notes[j]
note.visible = true // Manche GS-Varianten machen Notenkopf unsichtbar und verwenden stattdessen ein anderes Symbol
// Taste rot markieren, wenn sie auf Instrument nicht existiert
if (invalidSymbols.some(([p, x]) => p == note.pitch && x == hasCrossedNoteHead(note))) {
//if (invalidSymbols.includes([note.pitch, hasCrossedNoteHead(note)])) { <- doesn't work because it uses === :(
note.color = colorRed
invalidNotesCounter++
}
}
} else {
throw Error(`Invalid result for current chord ${chordIndex}: ${JSON.stringify(result)}`)
}
return invalidNotesCounter
}
function changeNotesOfChord(chord, result, zd, chordIndex) {
let notes = chord.notes
let invalidNotesCounter = 0
if (containsRedNote(notes)) {
console.log(`Current chord ${chordIndex} contains a red note. Leaving it unchanged. Skipping to next chord.`)
invalidNotesCounter++
return invalidNotesCounter
}
if (result.Right) {
for (let j = 0; j < notes.length; j++) {
let resAlternative = result.Right[alternativeIndex % result.Right.length]
let res = resAlternative[j]
let note = notes[j]
if (notes.length != resAlternative.length) {
console.warn(`Length of current chord (${notes.length}) and translation result (${resAlternative.length}) do not match in chord ${chordIndex}, note ${j}. Skipping to next chord.`)
break
}
let pitch = res.pitch
if (pitch === null) {
// Should never happen
console.warn(`Invalid note position ${res.position} in translation result in chord ${chordIndex}, note ${j}. Skipping to next note.`)
continue
}
let tpc = lookupTonalPitchClass(res.position)
colorNoteZugDruck(note, zd, checkBoxColorZug)
console.log(`Changing Nn ${note.pitch} (tpc=${note.tpc}) to GS ${pitch} (tpc=${tpc})`)
note.pitch = pitch
note.tpc1 = tpc
note.tpc2 = tpc
//note.line = 0 // The vertical position counted from top line; but has no effect.
// Reset crossed note heads when cycling through alternatives:
if (res.side === null || !checkBoxSortHeads.checked) {
note.mirrorHead = 0
} else if (res.side === 'Links') {
note.mirrorHead = 1
} else if (res.side === 'Rechts') {
note.mirrorHead = 2
}
note.headGroup = NoteHeadGroup.HEAD_NORMAL
removeCrossBeforeHead(note)
setAccidentalVisible(note, false)
if (res.extra && res.row === 0) {
note.headGroup = NoteHeadGroup.HEAD_TRIANGLE_UP
} else if (res.extra && res.row === 1) {
// How does DIAMOND_OLD looks like?
note.headGroup = NoteHeadGroup.HEAD_DIAMOND
} else if (res.crossed) {
const selectedVariant = comboTabulatureDisplay.currentKey()
console.log(selectedVariant)
switch (selectedVariant) {
case 'klassisch_kreuz':
// No difference between row 3 and 4; all crosses before note head.
addCrossLightBeforeHead(note)
break
case 'klassisch_doppelkreuz':
// No difference between row 3 and 4; all crosses before note head.
addCrossSharp2BeforeHead(note)
break
case 'johannesservi.de':
if (isHalfOrLonger(chord)) {
note.headGroup = NoteHeadGroup.HEAD_WITHX
// Damit die Kreislinie überall gleich dick ist; ansonsten ist es
// einfach eine Halbe/Ganze mit Kreuz, sieht aber blöd aus.
note.headType = NoteHeadType.HEAD_QUARTER
} else {
note.headGroup = NoteHeadGroup.HEAD_CROSS
}
break
case 'johannesservi.de_2':
if (isHalfOrLonger(chord)) {
note.headGroup = NoteHeadGroup.HEAD_XCIRCLE // same as SymId.noteheadVoidWithX?
} else {
note.headGroup = NoteHeadGroup.HEAD_CROSS
}
break
case 'matthiaspuerner.de':
if (isHalfOrLonger(chord)) {
addCrossSharp2BeforeHead(note)
} else {
note.headGroup = NoteHeadGroup.HEAD_CROSS
}
break
case 'knoepferl.at':
// The cross for notes of row 4 are heavier than row 3
if (res.row === 2) {
addCrossLightBeforeHead(note)
} else {
addCrossSharp2BeforeHead(note)
}
break
case 'michlbauer.com':
if (res.row === 2) {
addCrossLightBeforeHead(note)
} else {
addCrossCircledBeforeHead(note) // TODO in Wirklichkeit ist das Symbol noch kleiner
}
break
case 'dickes_kreuz':
// Wie klassisch_kreuz, aber DICKES Kreuz für Tasten in 4. Reihe
if (res.row === 2) {
addCrossLightBeforeHead(note)
} else {
addCrossBoldBeforeHead(note)
}
break
case 'klassisch_kreuz2':
// Wie klassisch_kreuz, aber Kreuz als Notenkopf (nur bei Halben/Ganzen vor dem Notenkopf)
if (isHalfOrLonger(chord)) {
addCrossLightBeforeHead(note)
} else {
note.headGroup = NoteHeadGroup.HEAD_CROSS
}
break
case 'klassisch_doppelkreuz2':
// Wie klassisch_doppelkreuz, aber Doppelkreuz als Notenkopf (nur bei Halben/Ganzen vor dem Notenkopf)
if (isHalfOrLonger(chord)) {
addCrossSharp2BeforeHead(note)
} else {
note.visible = false // note head invisible
// Geht nur in Leland, weil sonst Lücke zwischen Hals und Kopf:
addSymbolToNote(note, SymId.accidentalDoubleSharp, 0.1)
//addSymbolToNote(note, SymId.noteheadXOrnate, 0.1) // je nach Schriftart unterschiedlich zu echtem Doppelkreuz
}
break
default: // 'modern'
note.headGroup = NoteHeadGroup.HEAD_CROSS
break
}
}
fixPlayedNotePitch(note, res.origPitch)
}
} else if (result.Left) {
let invalidPitches = result.Left.map(getMidiPitch)
for (let j = 0; j < notes.length; j++) {
let note = notes[j]
// Ton rot markieren, wenn er auf Instrument nicht existiert
if (invalidPitches.includes(note.pitch)) {
note.color = colorRed
invalidNotesCounter++
}
}
} else {
throw Error(`Invalid result for current chord ${chordIndex}: ${JSON.stringify(result)}`)
}
return invalidNotesCounter
}
function addLyricsToChord(chord, result, zd, chordIndex) {
let notes = chord.notes
let invalidNotesCounter = 0
console.log(`result for chord: ${result}`)
removeAllLyrics(chord)
for (let j = 0; j < notes.length; j++) {
let resNote = result[j]
let buttonName = resNote[alternativeIndex % resNote.length]
let note = notes[j]
if (notes.length != result.length) {
console.warn(`Length of current chord (${notes.length}) and translation result (${result.length}) do not match in chord ${chordIndex}, note ${j}. Skipping to next chord.`)
break
}
colorNoteZugDruck(note, zd, checkBoxColorZug)
if (buttonName) {
let lyrics = newElement(Element.LYRICS)
lyrics.text = buttonName
lyrics.verse = j
chord.add(lyrics)
} else {
note.color = colorRed
invalidNotesCounter++
}
}
return invalidNotesCounter
}
function callBassApi(chords, successCallback) {
let content = JSON.stringify(chordsAsApiInput(chords, false))
//console.log("content : " + content)
const apiUrlBass = apiUrl + '/bass'
let queryString = '?' +
// queryStringArg('tonart', spinnerTonart.displayText, true) +
queryStringArg('tonart', tonarten[spinnerTonart.value][1].toLowerCase(), true) +
queryStringArg('stimmung', comboStimmung.currentKey()) +
queryStringArg('basssystem', comboBasssystem.currentKey()) +
queryStringArg('bassbenennung', comboBassbenennung.currentKey())
console.log(queryString)
let request = new XMLHttpRequest()
request.onreadystatechange = function() {
if (request.readyState == XMLHttpRequest.DONE) {
console.log("HTTP status: " + request.status)
if (request.status == 200) {
console.log("API response:\n" + request.responseText)
try {
lastResults = JSON.parse(request.responseText)
} catch (e) {
console.error("Invalid JSON response. Could not parse.")
messagePane.showError("Ungültige Antwort vom Server.")
}
successCallback(chords, lastResults)
} else if (request.status >= 500) {
// Server-Fehler.
messagePane.showError(`Fehler beim Server. Funktioniert ${apiUrl}?`)
} else if (request.status >= 400) {
// Fehler bei Kommunikation.
messagePane.showError(`Fehler bei der Kommunikation mit dem Server. Funktioniert ${apiUrl}?`)
} else if (request.status >= 300) {
// Lizenzfehler?
// TODO change error message when authorize system works...
messagePane.showError(`Wahrscheinlich passt die Lizenz nicht oder Sie haben noch eine alte Version dieses Plugins. Überprüfen: ${apiUrl}?license=${txtLicenseKey.text}.`)
} else {
// Netzwerkfehler?
let s = `Request failed with HTTP status ${request.status}\nReceived response headers:\n${request.getAllResponseHeaders()}\nResponse text:\n${request.responseText}`
messagePane.showError(`Unbekannter Netzwerkfehler (HTTP Status Code ${request.status}). Funktioniert das Internet? Funktioniert ${apiUrl}?\n\n${s}`)
console.error(s)
}
} else {
// Netzwerkfehler?
//messagePane.showError(`Wahrscheinlich Netzwerkfehler. Funktioniert das Internet? Funktioniert ${apiUrl}?`)
console.log(`HTTP request ready status: ${request.readyState} (not DONE)`)
}
}
console.log(`Run in shell for testing:
cat <<TEXT > test.json
${content}
TEXT
curl -H "Content-Type: application/json" --data-binary @test.json "${apiUrlBass + queryString}"
`)
request.open("POST", apiUrlBass + queryString, true)
request.setRequestHeader("Content-Type", "application/json")
request.send(content)
}
function addLyricsToNotes(zd) {
return function(chords, zdResults) {
lastZD = zd
let results = extractZDResults(zd, zdResults)
console.log(zd + ' ' + results)
if (chords.length != results.length) {
console.warn(`Length of selected chords (${chords.length}) and translation result (${results.length}) do not match. Aborting.`)
return
}
let invalidNotesCounter = 0
let error = null
curScore.startCmd()
for (let i = 0; i < chords.length; i++) {
let chord = chords[i]
let result = results[i]
// try {
invalidNotesCounter += addLyricsToChord(chord, result, zd, i)
// } catch (e) {
// console.error(e.message)
// console.trace()
// error = e
// }
}
curScore.endCmd()
if (error) {
messagePane.showError(`Fehler: ${error.message}`)
}
if (invalidNotesCounter) {
messagePane.showError(`${invalidNotesCounter} Note(n) konnten nicht übersetzt werden und wurden rot markiert.\n\nEntweder existieren sie nicht auf dem Instrument oder sie waren bereits rot markiert. Die Akkorde mit roten Noten wurden bei der Übersetzung übersprungen.`)
}
}
}
function addBassNamesAsLyrics(zd) {
checkVoiceCheckboxesValidity()
console.log(`Starting translation: ${zd}`)
let chords = collectChords()
if (chords.length == 0) {
console.warn("Keine Noten ausgewählt. Abbruch.")
messagePane.showWarning("Es sind keine Noten bzw. Takte ausgewählt.")
return
}
if (chords.length > maxChordLimit) {
console.warn("Zu viele Noten ausgewählt. Abbruch.")
messagePane.showWarning("Es sind zu viele Noten bzw. Takte ausgewählt. Es können immer nur ein paar Takte auf einmal übersetzt werden.")
return
}
if (!isCurrentResultValid()) {
alternativeIndex = 0
callBassApi(chords, addLyricsToNotes(zd))
btnNextAlternative.enabled = true
} else {
// Reuse lastResults
if (zd !== lastZD) {
alternativeIndex = 0
} else {
alternativeIndex += 1
}
addLyricsToNotes(zd)(chords, lastResults)
}
invalidateResultsAfterTimeout()
}
function translateToFromGriffschrift(zd) {
checkVoiceCheckboxesValidity()
checkHasSelectionChanged()
let reverse = isReverseDirection()
console.log(`Starting translation: ${zd}${reverse ? ' reverse' : ''}`)
let chords = collectChords()
if (chords.length == 0) {
console.warn("Keine Noten ausgewählt. Abbruch.")
messagePane.showWarning("Es sind keine Noten bzw. Takte ausgewählt.")
return
}
if (chords.length > maxChordLimit) {
console.warn("Zu viele Noten ausgewählt. Abbruch.")
messagePane.showWarning("Es sind zu viele Noten bzw. Takte ausgewählt. Es können immer nur ein paar Takte auf einmal übersetzt werden.")
return
}
// Sonderfall: Alternative Griffweisen durchzappen
if (btnReverseDirection.state == 1 && !isCurrentResultValid()) {
console.log("Alternative Griffweisen durchzappen")
callApi(chords, /* GS → Nn: reverse = */ true, toGriffschrift(zd))
return
}
if (reverse || !isCurrentResultValid()) {
if (looksLikeGriffschrift(chords) && !reverse) {
console.warn("Markierte Noten sehen nach Griffschrift aus. Abbruch.")
messagePane.showWarning("Markierte Noten sehen nach Griffschrift aus und können daher nicht nochmal nach Griffschrift übersetzt werden.")
return
}
alternativeIndex = 0
callApi(chords, reverse, changeNotes(zd, reverse))
btnNextAlternative.enabled = true
} else {
// Reuse lastResults
if (zd !== lastZD) {
alternativeIndex = 0
} else {
alternativeIndex += 1
}
changeNotes(zd, false)(chords, lastResults)
}
invalidateResultsAfterTimeout()
if (reverse) {
disableZDButtonsForTimeout()
}
}
function makePlayable() {
invalidateCurrentResults()
let chords = collectChords()
if (chords.length == 0) {
console.warn("Keine Noten ausgewählt. Abbruch.")
return
}
if (chords.length > maxChordLimit) {
console.warn("Zu viele Noten ausgewählt. Abbruch.")
return
}
// TODO Look how it's done in handleZug / handleDruck
// Get zd from note color (future: Druckbalken).
// I need a reverse API call but mostly code from changeNotesOfChord.
//callApi(chords, true, (chords, zdResults) => {
// console.log("finished reverse api call to make GS playable")
//})
}
function toGriffschrift(zd) {
return (chords, zdResults) => {
let results = extractZDResults(zd, zdResults)
let constructedChords = constructChordsFromNormalResults(results)
console.log("Aus Normalnoten (die API zurückgeliefert hat) werden jetzt MuseScore Notes erstellt, die dann in GS umgewandelt werden: " + JSON.stringify(constructedChords))
alternativeIndex = 0 // Can we set this to current alternative? Only if originalGSChords are passed to changeNotes.
let reverse = false // Nn → GS
callApi(constructedChords, reverse, changeNotes(zd, reverse))
}
}
function checkVoiceCheckboxesValidity() {
if (!(checkBoxVoice1.checked || checkBoxVoice2.checked || checkBoxVoice3.checked || checkBoxVoice4.checked)) {
messagePane.showWarning("Mindestens eine Stimme muss zum Übersetzen ausgewählt sein.")
}
}
function getSelectedVoices() {
let result = []
checkBoxVoice1.checked && result.push(0)
checkBoxVoice2.checked && result.push(1)
checkBoxVoice3.checked && result.push(2)
checkBoxVoice4.checked && result.push(3)
return result
}
// Implements jsArray.find().map(); if not found, return null.
function find(list, filterFun, mapFun) {
// .find() and .first() are not supported by normal JS arrays...
const result = list.filter(filterFun).map(mapFun)
return result ? result[0] : null;
}
function getGermanNoteNamesFromNotes(noteList) {
let noteNames = []
for (let i = 0; i < noteList.length; i++) {
const note = noteList[i]
const name = find(midiPitchMap, ([_, p]) => note.pitch == p, ([n, _]) => n)
const nameGerman = find(germanNoteNames, ([n, _]) => n === name, ([_, n]) => n)
if (nameGerman) {
noteNames.push(nameGerman)
}
}
return noteNames
}
function openNn2GSBrowser() {
// TODO Directly open first selected chord? note names must be in German for this!
const model = comboModel.currentKey()
const chords = collectChords()
const notes = chords.length > 0 ? chords[0].notes : []
const noteNames = getGermanNoteNamesFromNotes(notes)
const noteNamesJoined = noteNames.join(' ')
console.log(noteNamesJoined)
Qt.openUrlExternally(apiUrl + '?' +
queryStringArg('model', model, true) +
(noteNames.length ? queryStringArg('notes', noteNamesJoined, false) : '') +
(txtLicenseKey.text ? queryStringArg('license', txtLicenseKey.text) : ''))
}
function lblCurrentKeyClick() {
let keysig = curScore.keysig
console.log(`Globale Dur-Tonart: ${keysig}`)
spinnerTonart.value = 8 + keysig
}
function proceedToNextChord() {
cmd('next-chord')
cmd('select-next-chord')
cmd('select-prev-chord')
}
function checkBoxColorZugClick() {
if (!checkBoxColorZug.checked) {
curScore.startCmd()
applyToChordsInSelection(true, 10000, (chord) => {
for (let j = 0; j < chord.notes.length; j++) {
let note = chord.notes[j]
if (note.color == colorBlue) {
note.color = colorBlack
}
}
})
curScore.endCmd()
}
}
function checkMuseScoreVersionSupport() {
if (mscoreMajorVersion < 4 || mscoreMajorVersion >= 4 && mscoreMinorVersion <= 3) {
messagePane.showError(`Diese Version des Plugins funktioniert nur mit MuseScore 4.4 und höher. Sie verwenden gerade MuseScore ${mscoreMajorVersion}.${mscoreMinorVersion}.`)
}
}