-
Notifications
You must be signed in to change notification settings - Fork 1
/
notesFromChordTexts.qml
2674 lines (2444 loc) · 96.5 KB
/
notesFromChordTexts.qml
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
//=============================================================================
// vim: ft=javascript
//
// MuseScore - Chord texts to playable Chord and bass notes
//
// Copyright (C) 2019 PerD - https://github.com/per-d/notes-from-chord-texts
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2
// as published by the Free Software Foundation and appearing in
// the file LICENCE.GPL
//
// documentation: https://github.com/per-d/notes-from-chord-texts
// support: https://github.com/per-d/notes-from-chord-texts
//
//=============================================================================
/*******************************************************************************
* Vocabulary in variable names and comments.
* - tick The position for a Segment or current Cursor.
* - harmony The written chord, e.g. "Dmaj7", also MS Harmony object.
* - chord Notes for a harmony, also MS Chord object.
* - rest A rest (instead of a chord), also MS Rest object.
* - duration, durationType, ticks
* The length (ticks) for a Chord/Rest. MS#duration is another
* thing, it's an object for the duration of the Chord/Rest.
* - note Most often MS Note object, the representation in a Score.
* - tone The "musical" term for the pitch,
* in C-scale: 1 = C, 2 = D, 3 = E, 4 = F etc.
* - pitch The pitch, here "half-tones" over the root, in MS it's counting
* from a low low C increasing by 12 for every octave.
* in C-scale: 0 = C, 1 = C#/Db, 2 = D, 3 = D#/Eb, 4 = E, 5 = F etc.
* - semitones "Half step" or "half tone". The diff between 'pitch' for a tone
* and the 'pitch' for the root of the chord.
* - tpc tpc is ...TPC. Using TPC is a way of specifying how the tone should
* be represented as note. E.g. the pitch 3 (C-scale) can mean both
* D# and Eb, but in TPC they have different representations.
*
* The parsing of chords (written chords, in the code called harmonies) is based on:
* [r]:
* https://en.wikipedia.org/wiki/Chord_names_and_symbols_(popular_music)
* https://en.wikipedia.org/wiki/Chord_(music)
* (there is a fault in the above page I think, "C-(b5)" resolves to "C Eb Gb Bb"
* but should be "C Eb Gb" according to other rules in the page)
* https://en.wikipedia.org/wiki/Suspended_chord
* [r2]:
* http://www.musikipedia.se/ackord
* etc.
* [r] and [r2] in comments means rules that I found on these pages.
* It's my own understanding of all different variants of writing a harmony,
* and not necessarily how it should be.
* Same harmony variant can be written in many different ways, depending on the
* music style (e.g. jazz). And also played in different ways depending on the
* instrument it is played on, for some instruments some of the notes that
* should be included according to the rules are just ignored (I think).
*
* "seventh chords" and other twists:
* This is kind of confusing, and may be up to the player to interpret it correct.
* Here I use the definitions in [r]-first, both real definitions and from
* examples, all examples in C-scale.
* - "C^" (C with Unicode 0394 or 2206) is usually interpreted as "C^7" ("Cmaj7"),
* but some will mean "Cmaj" ("C").
* I use "C^" = "C^7".
* - Straight tones (not sharp nor flat) is called different for different tones:
* major 2nd, perfect 4th, perfect 5th, major 6th, major 9th, perfect 11th
* and major 13th.
* They are all "straight", so e.g. "major 6" = only "6" (= A) and not equal
* to "#6" (= A#), "minor 6" is however equal to "b6" (= Ab).
* For 7th it's different (according to examples in [r]). "major 7" = B,
* "#7" is also = B (not B# or C). Only "7" is = Bb, the same as "minor 7"
* and "b7". "7" in a "dim" chord means Bbb (= A).
* - I'm using "A" instead of "Bbb" for "diminished seventh". Also other
* is treated the same way, e.g. "bb6" (Abb) in "Cm(bb6)" is changed to "5" (G),
* if that for some reason is used.
*
* - "sus". "sus"/"4" means "sus4", "2" means "sus2", both if that is the main
* extension. Some may mean that e.g. "C2" should mean "Cmaj2" (or "Cadd2"),
* but as I understand it the most common is that it means "Csus2". Just
* use "Cadd2"/"Cmaj2"/"Cdom2"/"C(2)" if it shouldn't mean "Csus2". The same
* with "4".
*
* "alt" in e.g. "C7alt" is not implemented here, "alt" is just ignored. The
* reason is that this is mostly(?) used in jazz and is up to the player what
* alterations that should be played:
* https://en.wikipedia.org/wiki/Altered_chord
* "neutral chords", e.g. "Cn", are either not implemented, just ignored.
*
* See the generated notes as a suggestion. Depending on what instrument for
* the chords it can sound better if some of the generated notes are removed,
* or moved up or down one octave.
*******************************************************************************/
import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Dialogs 1.2
import QtQuick.Layouts 1.1
import QtQuick.Controls.Styles 1.3
import MuseScore 1.0
MuseScore {
version: "1.0"
description: "This plugin expands harmonies into chord and bass notes in" +
" added staves, playable by MuseScore."
menuPath: "Plugins.Chords.Notes from Chord texts"
//requiresScore: true //not supported before 2.1.0, manual checking in mainObject.initLg
/***
* Main object.
*/
property var mainObject: function() {
//xxxMainxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
var mo = this;
var staffObj, elemDo;
var gStaff = {
main: 0,
mid: 1,
bass: 2
};
mo.gStaff = gStaff;
var glb = {
// What should be written by console.log
// 0: basic
// 1: basic+
// 2: adding semitone/note
// 4: write chord
// 10: harmony -> chord notes, details
// 15: harmony, line with result
// etc. (look in code for first parameter to 'conLog')
//debugLevels: [ 0, 4, 41, 42 ],
debugLevels: [ 0, 1, 4, 10, 11, 15, 41, 42, 43, 44 ],
//debugLevels: [ 0, 1, 2, 4, 10, 11, 15, 44 ],
//debugLevels: [ 0, 1, 15 ],
//debugLevels: [ 0, 1, 44 ],
// Name for the debug file, set it to falsy ("", null, false, 0...) or just
// comment it out if not logging to file
//debugFile: "debug_notes_from_chord_texts",
// If settings dialog should be shown, can be annoying with the dialog when debugging
// (normally true)
swUseDialog: true,
// If dialog to adding staves should be shown, otherwise adding without question
// (normally true)
swAskStaffAdd: true,
// Decides if ok message should be shown after successful run
// (normally true)
swShowOk: true,
// Decides if close document dialog should be shown when the plugin finish
// also 'swShowOk' must be true
// (normally true)
swAskClose: true,
// instrument for staves that are added if only one staff in the Score
// NB! must be present in [MuseScore program folder]/instruments/instruments.xml
addStavesInstrument: "piano",
/// Defaults for Settings box, and as settings for the code ///
// Octave for the notes in the chord
// for Settings box (1 = 0)
octaveRootDefaultIndex: 1,
// for the code, gets value from the Settings box if used
octaveRoot: 0,
// Octave for the bass note from the chord
// for Settings box (3 = -2, 0 = No bass)
octaveBassDefaultIndex: 3,
// for the code, gets value from the Settings box if used
octaveBass: -2,
// Max pitch for the chord's root, above will add notes one octave down (from
// 'octaveRoot'), set it to falsy to not use it (0 is also falsy)
// for Settings box (4 = G)
rootMaxDefaultIndex: 4,
// for the code, gets value from the Settings box if used (7 = G)
rootMaxPitch: 7,
// Min pitch for the chord's bass note, below will add the note one octave up
// (from 'octaveBass'), set it to falsy to not use it (0 is also falsy)
// for Settings box (2 = E)
bassMinDefaultIndex: 2,
// for the code, gets value from the Settings box if used (4 = E)
bassMinPitch: 4,
// If reducing notes in extended chords should be done.
// It's done according to [r] in that case. Two levels, 1 and 2:
// 0/falsy: nothing reduced.
// 1: 11th chord, remove 3rd if that is major (not sharp nor flat).
// 13th chord, remove 5th if that is perfect (major),
// remove 11th if that is perfect (major),
// the same with 4th (1 octave under 11th) if that is perfect.
// 2: same as "level 1" plus:
// 9th chord, remove 5th if that is perfect (major).
// 13th chord, remove 9th if that is major,
// the same with 2th (1 octave under 9th) if that is major
// - and not a sus2 chord.
// used in code and as default in Settings box if used (0 = None)
reduceChordsLevel: 1,
// If 9th chord should imply 7th, 11th imply 9th and 7th etc.
// used in code and as default in Settings box if used
extImpliesLower: true,
// Lower case letters means minor harmonies
// used in code and as default in Settings box if used
lowIsMinor: false,
// Allow harmony notation to add to last harmony (experimental)
// used in code and as default in Settings box if used
allowAddToLast: false,
// show in Settings box
allowAddToLastShow: true,
// Write the parsed Harmony text as Staff Text
// used in code and as default in Settings box if used
writeParsed: false,
// Write Chord note letters in, 1 = yes, 2 = in C-scale, as Staff Text
// used in code and as default in Settings box if used (0 = No)
writeChordNotes: 0,
/// Used internally: ///
swQuit: false,
alwaysTranspose: true,
// tone: 1 2 3 4 5 6 7
toneToSemiPitch: [ 0, 2, 4, 5, 7, 9, 11 ],
toneLetters: [ 'C','D','E','F','G','A','B' ],
tpcLetters: [ 'F', 'C', 'G', 'D', 'A', 'E', 'B' ],
tpcAlts: [ 'bb', 'b', '', '#', '##' ],
tpcToneC: 14,
tpcAlterFact: 7,
// pitch is 60 for C in octave 0, incr/decr by 12 for each octave up/down.
pitchCinOctave0: 60,
pitchOctave: 12,
crochetTicks: 480, // ticks for 1/4 note
harmonyNbr: 0,
lyricsNbr: 0,
// undef: <- don't define it's used as "undefined" value
resultText: "",
resultInfoText: "",
resultIcon: StandardIcon.Information,
resultButtons: StandardButton.Ok,
// ignore harmonies that starts with "(" or "[", or ends with ")" (without
// any earlier "("), parentheses can span over two harmonies.
ignoreHarmonyRegx: /^((\(|\[)|[^(]*\)$)/,
// [r] "N.C." means "no chord", should be a rest instead
noChordRegx: /^\s*(N\.C\.?)\s*$/i
};
mo.glb = glb;
/***
* Staff object. Methods/properties for handle staves.
*/
mo.staffObject = function() {
var st = this;
var cursor, curTick,
chordCursor = [],
nextCursor = [],
staffDebName = [],
lastChord = [];
/***
* Init the Staff object.
* @param {MS Cursor} inCursor
*/
st.init = function(inCursor) {
// set all involved cursors
for (var staffKey in gStaff) {
var staff = gStaff[staffKey];
if (staff < 1) continue;
chordCursor[staff] = curScore.newCursor();
nextCursor[staff] = curScore.newCursor();
}
// debug names
staffDebName[gStaff.mid] = "Mid";
if (gStaff.bass) staffDebName[gStaff.bass] = "Bass";
// init cursors
st.initCursors(inCursor);
st.measureNbr = 0;
};
/***
* Reinit the cursors.
* @param {MS Cursor} inCursor
*/
st.initCursors = function(inCursor) {
cursor = inCursor;
cursor.rewind(0);
// init all involved cursors
for (var staffKey in gStaff) {
var staff = gStaff[staffKey];
if (staff < 1) continue;
// beginning of score for all of them
chordCursor[staff].rewind(0);
nextCursor[staff].rewind(0);
// and set Staff id
chordCursor[staff].staffIdx = staff;
nextCursor[staff].staffIdx = staff;
}
st.measureNbr = 0;
};
/***
* "Translates" 'curTick' to human string, see #ticksToStr.
*/
st.curTickToStr = function(debT, addToStep, showMeasures) {
return st.ticksToStr(curTick, debT, addToStep, showMeasures);
};
/***
* "Translates" <ticks> to human string, steps and ticks.
* @param {Number} <ticks> 'tick' from cursor or "duration".
* @param {String} <debT> opt. Pre text for debug. If includes "@"
* <showMeasures> is considered true.
* @param {Number} <addToStep> opt. Add this to steps (can be useful when it's
* a cursor.tick, first note in system is
* otherwise as step 0.
* @param {Bool|String} <showMeasures> opt.
* If <ticks> ('tick') also should be "translated"
* to measure number and step within the measure.
* If {String} it will be as pre text.
* @return {String} "[steps] ([ticks])"
* ticksToStr(2880) //=> "6 (2880)"
* ticksToStr(2880, "Hey ") //=> "Hey 6 (2880)"
* ticksToStr(2880, "Hey @", 1) //=> "Hey @7 (2880) - 2:4 (1440)" (if only 3 steps in measure 1)
*/
st.ticksToStr = function(ticks, debT, addToStep, showMeasures) {
if (! debT) debT = "";
var showAt = /@/.test(debT),
text = st.ticksToSteps(ticks, debT, addToStep);
if (showMeasures || showAt) {
text += " - ";
if (typeof(showMeasures) === "string") text += showMeasures;
text += st.measureNbrFromTick(ticks, "");
}
return text;
};
/***
* "Translates" <ticks> to "measure steps" {Number or String} depending on <debT>,
* see also #ticksToStr.
* @param {Number} <ticks> 'tick' from cursor or "duration".
* @param {String} <debT> opt. Pre text for debug. If String/true it will
* return a String, otherwise a Number.
* @param {Number} <addToStep> opt. Add this to steps.
* @return {Number|String}
*/
st.ticksToSteps = function(ticks, debT, addToStep) {
var steps = (ticks ? ticks / glb.crochetTicks : 0);
if (truthy(debT, "")) {
if (addToStep) steps += addToStep;
// add " " if debT and not "@" as last character
if (debT && ! /@$/.test(debT)) debT += " ";
steps = debT + steps + " (" + ticks + ")";
}
return steps;
};
/***
* "Translates" 'tick' to measure number.
* @param {Number} <tick> The tick.
* @param {String} <debT> opt. If String it returns a String, but <debT>
* is not included.
* @param {Number} <denominator> opt.(4) the measure denominator.
* @return {Number|String} String if debT is a String with 'tick' in parentheses.
*/
st.measureNbrFromTick = function(tick, debT, denominator) {
// secure 0 if nothing (or 0)
if (! tick) tick = 0;
var mNbr, step, wholeSteps, measureTick,
wholeTicks = tick - st.firstMeasureTicks;
mNbr = 1;
if (wholeTicks < 0) {
step = st.ticksToSteps(tick) + 1;
} else {
if (! denominator) denominator = 4;
wholeSteps = st.ticksToSteps(wholeTicks);
step = (wholeSteps % denominator);
wholeSteps -= step;
mNbr += (wholeSteps / denominator) + 1;
wholeSteps ++;
step ++;
}
measureTick = (step - 1) * glb.crochetTicks;
if (truthy(debT, "")) mNbr = "" + mNbr + ":" + step + " (" + measureTick + ")";
return mNbr;
};
/***
* Inits a lap (new Segment) in main loop.
*/
st.initLap = function() {
var measureStep,
measureStartTick = cursor.measure.firstSegment.tick;
curTick = cursor.tick;
measureStep = (st.ticksToSteps(glb.crochetTicks + (curTick - measureStartTick)));
if (measureStep === 1) {
st.measureNbr ++;
if (st.measureNbr === 1) {
st.firstMeasureTicks = cursor.measure.lastSegment.tick - measureStartTick;
}
}
st.segmentS = "Segment@" + st.measureNbr + ":" + measureStep + " (" + curTick + ")";
};
/***
* Fixes the last measure. Replacing last Rests with Chords and adjusting durations.
*/
st.finishUp = function() {
var chordLast = lastChord[gStaff.mid];
if (! chordLast) return;
conLog(0);
conLog(0, "----- Adjusting last measure ------------------------------------");
// sheet with 'curTick' to fix Rests in last measure
curTick += lastChord[gStaff.mid].durationType;
var text = "last measure, cursorChord.tick -> End";
st.advanceCursor(text, gStaff.mid, curTick, true);
if (gStaff.bass) st.advanceCursor(text, gStaff.bass, curTick, true);
};
/***
* Changes the root and bass (if any) tone to upper case.
* @param {String} <harmonyText> The Harmony text.
* @return {String}
*/
st.harmonyTextNice = function(harmonyText) {
// securing String
if (! harmonyText) harmonyText = "";
var strM, key, bass;
if ((strM = harmonyText.match(glb.noChordRegx))) return strM[1].toUpperCase();
if ((strM = harmonyText.match(/^(([a-g])(([^/]|\/(?![a-g]))*))?((\/)([a-g])(.*))?$/i))) {
key = strM[2] || "";
bass = strM[7] || "";
if (! glb.lowIsMinor) {
key = key.toUpperCase();
bass = bass.toUpperCase();
}
return key + (strM[3] || "") + (strM[6] || "") + bass + (strM[8] || "");
}
return harmonyText;
};
/***
* Creates a Text object, and adds it to <parent> if value.
* @param {MS type} <type> MuseScore element type.
* @param {String} <text> The text.
* @param {Int} <track> opt. Staff id, where to add Text object.
* @param {Number} <posX> opt. Position x.
* @param {Number} <posY> opt. Position y.
* @param {MS element} <parent> opt. Object to add created Text object to.
* @return {Text object|Boolean} Boolean if <parent>
*/
st.addText = function(type, text, staffId, posX, posY, parent, color) {
var textObj;
textObj = newElement(type);
textObj.text = text;
if (truthy(staffId, 0)) textObj.track = staffId * 4;
if (truthy(posX, 0)) textObj.pos.x = posX;
if (truthy(posY, 0)) textObj.pos.y = posY;
if (color) textObj.color = color;
if (! parent) return textObj;
parent.add(textObj);
return true;
};
/***
* Adds a Chord to 'cursor'.
* @param {MS Cursor} <cursor>
* @param {MS Chord} <chord>
*/
st.cursorAddChord = function(cursor, chord, staff) {
var posX, posY,
harmonyObj = chord.ctnHarmonyObj,
harmonyText = chord.ctnHarmonyText || (harmonyObj ? harmonyObj.harmonyOrig : ""),
text = st.isRest(chord) ? 'rest' : 'chord';
cursor.add(chord);
conLog(4,
"'>' AddCh, Added ", text, " \"", harmonyText,
"\" dur: ", st.ticksToStr(chord.durationType), ", at: ", st.ticksToStr(cursor.tick, "", 1, "@")
);
if (staff === gStaff.mid && harmonyObj) {
if (glb.writeParsed && harmonyObj.parsedHarmonyS()) {
// write the Harmony text as both Harmony and Staff Text, to get it nicely
// shown and to show the real value
var harmText = harmonyObj.parsedHarmonyS();
posY = -0.5;
st.addText(Element.HARMONY, harmText, cursor.staffIdx, 0, posY, cursor);
harmText = harmonyObj.parsedHarmonyS(false, true);
posX = 0;
if (glb.harmonyNbr === 1) {
st.addText(Element.STAFF_TEXT, "Formatted: ", cursor.staffIdx, -10, posY - 0.5, cursor);
harmText = "Real: " + harmText;
posX = -5;
}
posY += 1.5;
var color = (/ignore/.test(harmText) ? "red" : "");
st.addText(Element.STAFF_TEXT, harmText, cursor.staffIdx, posX, posY, cursor, color);
}
if (glb.writeChordNotes && harmonyObj.chordLettersNice) {
posY = (glb.lyricsNbr++ % 2) * 1.5;
st.addText(Element.LYRICS, harmonyObj.chordLettersNice, cursor.staffIdx, 0, posY, chord);
}
}
};
/***
* Sets duration for Chord and writes it to <staff>. Also adjusting last Chord.
* @param {Number} <staff> Staff id.
* @param {MS Chord} <chord> opt. Chord, see <color>.
* @param {String} <color> opt. Colorizes the Harmony text with <color> at
* the current Segment if value, can be used without
* <chord>.
* @return {Bool|undef} returns 'false' if some error.
*/
st.writeChord = function(staff, chord, color, errorMessage) {
var currentChordObj, harmonyObj, ignore, harmonyElem,
errorPosY = glb.writeParsed ? 2.5 : -0.5;
conLog(4);
conLog(4, "WriteCh, curTick: ", st.curTickToStr("", 1, "@"), " '", staffDebName[staff], "' -----");
// add the new chord
if (chord && (st.isRest(chord) || chord.notes && chord.notes.length)) {
conLog(4, "--- Write new chord ---");
currentChordObj = (new st.elemObject).init(cursor.element, "current Chord");
if (currentChordObj.errorMessage) {
errorWithColorChord(currentChordObj.errorMessage, currentChordObj.errorInfo);
conLog(4, "---");
return false;
}
conLog(4, "WriteCh, remain ticks in measure: ", st.ticksToStr(currentChordObj.measureRemain));
// write the chord
chord.visible = true;
chord.durationType = currentChordObj.ticks;
cursor.staffIdx = staff;
st.cursorAddChord(cursor, chord, staff);
// write "ignore error" if any
if (! glb.writeParsed && (harmonyObj = chord.ctnHarmonyObj)) {
ignore = (staff === gStaff.bass ? harmonyObj.bassRemain : harmonyObj.rootRemain);
if (ignore) {
st.addText(Element.STAFF_TEXT, "ignored: " + ignore, staff, 0, errorPosY, cursor, "red");
errorPosY += 1.5;
}
}
cursor.staffIdx = gStaff.main;
}
// adjust last chords (now when we know the tick for the new)
if (currentChordObj || lastChord[staff]) {
st.advanceCursor("cursorChord.tick -> curTick", staff, curTick, true);
}
// color the harmony text
if (color) {
if ((harmonyElem = getSegmentHarmony(cursor.segment))) harmonyElem.color = color;
}
// add error message as Staff Text
if (errorMessage) {
cursor.staffIdx = staff;
st.addText(Element.STAFF_TEXT, errorMessage, staff, 0, errorPosY, cursor, color || "red");
cursor.staffIdx = gStaff.main;
}
// remember these
lastChord[staff] = chord;
conLog(4, "--- WriteCh, -----------");
};
/***
* Advance the "Staff cursor", adjusting Chords/Rests on the way.
* @param {String} <debT> Debug text.
* @param {Number} <staff> Staff id.
* @param {Number} <toTick> Until it's that tick.
* @param {Bool} <cleanRemaining> If adjust found element's duration when advancing.
*/
st.advanceCursor = function(debT, staff, toTick, cleanRemaining) {
var lastChordO, elemObj, newChord, segment,
cursorChord = chordCursor[staff],
cursorNext = nextCursor[staff];
debT += ": " + cursorChord.tick;
// return if already at "to tick"
if (cursorChord.tick >= toTick) return;
conLog(41, "-");
conLog(41,
"Adv, useCursor.staffIdx: ", staffDebName[cursorChord.staffIdx],
", @tick: ", cursorChord.tick
);
// init values for "clean remaining"
if (cleanRemaining) {
conLog(42, "");
conLog(41, "Adv-Clean, get Last Chord ", st.ticksToStr(cursorChord.tick, "", 1, "@"));
lastChordO = (new st.elemObject).init(cursorChord.element, "last Chord/Rest");
if (st.stepToNextChordRest("", staff, toTick)) {
lastChordO.nextChordTick = cursorNext.segment.tick;
}
// setting durationType if beyond max
lastChordO.maxTicks(true, cursorChord, "(Adv-Clean) last Chord init");
}
while (truthy(cursorChord.tick, 0) && (cursorChord.tick < toTick)) {
st.doNext("", cursorChord);
// break if "bad cursor" or same as or past 'toTick'
if ( ! cursorChord.tick || cursorChord.tick < 0 || cursorChord.tick >= toTick) break;
conLog(42, "");
conLog(41, "Adv, .next(), new tick: ", st.ticksToStr(cursorChord.tick, "", 1, "@"));
if (! cleanRemaining) continue;
segment = cursorChord.segment;
conLog(41,
"Adv-Clean, segment: ", segment, ", .segmentType: ", segment.segmentType);
elemObj = (new st.elemObject).init(cursorChord.element, "next Chord");
// only if Chord or Rest
if (! elemObj.isChordRest) continue;
conLog(41, "Adv-Clean, element: ", elemObj.self, ", duration: ", st.ticksToStr(elemObj.ticks));
if (st.stepToNextChordRest("", staff, toTick)) {
elemObj.nextChordTick = cursorNext.segment.tick;
}
if (elemObj.isChord || ! lastChordO.isChord) {
// just set durationType
if (elemObj.maxTicks(true, cursorChord, "(Adv-Clean, in loop) adjusting Chord/Rest"))
conLog(41, "Adv-Clean, element.durationType set to maxTicks: ", lastChordO.ticks);
} else {
// replace the Rest with a new Chord to extend last Chord over the Rest
// The Rest is probably there because it wasn't a "whole" Rest for
// the Measure before the plugin started
// (Muse's '.clone()' causes the app to crash)
newChord = st.cloneChord(lastChordO.self, elemObj.maxTicks());
newChord.ctnHarmonyText = "cloned";
st.cursorAddChord(cursorChord, newChord, staff);
st.setPlayAndChordDuration(
"(Adv-Clean) chord to fill a Rest", newChord, cursorChord, newChord.durationType
);
elemObj = (new st.elemObject).init(newChord, "\"cloned\" Chord");
conLog(41,
"Adv-Clean, " +
"replaced the Rest with new Chord to extend last Chord over the Rest"
);
}
if (elemObj.isChord) lastChordO = elemObj;
}
conLog(4, "Adv, ", debT, " -> " + cursorChord.tick);
conLog(41, "-");
};
/***
* Look up next Chord/Rest.
* @param {String} <debT> Debug text.
* @param {Number} <staff> Staff id.
* @param {Number} <toTick> Until it's that tick.
*/
st.stepToNextChordRest = function(debT, staff, toTick) {
var swChord = null,
cursorNext = nextCursor[staff];
if (debT === "") debT = "cursorNext.tick -> curTick:: " + cursorNext.tick;
while (truthy(cursorNext.tick, 0) && (cursorNext.tick < toTick)) {
st.doNext("", cursorNext);
// break if "bad cursor" or past 'toTick'
if ( ! cursorNext.tick || cursorNext.tick < 0 || cursorNext.tick > toTick) break;
conLog(41, "- AdvNextCh/Rst, .next(), new tick: ", st.ticksToStr(cursorNext.tick, "", 1, "@"));
conLog(41, "- AdvNextCh/Rst, element: ", cursorNext.element);
if ((swChord = st.isChordRest(cursorNext.segment))) {
conLog(41, "- AdvNextCh/Rst, got Chord/Rest: ", st.ticksToStr(cursorNext.tick, "", 1, "@"));
break;
}
}
if (swChord === null) swChord = st.isChordRest(cursorNext.segment);
conLog(4, "- AdvNextCh/Rst, ", debT, " -> " + cursorNext.tick);
return swChord;
};
/***
* Do 'cursor.next()' for <cursor>.
* @param {String} <debT> Debug text.
* @param {Cursor} <cursor> The cursor.
* (This function was made when some problem with getting info for the measure,
* to do all 'next' in one function and do the logging.)
*/
st.doNext = function(debT, cursor) {
if (debT === "") debT = "cursor.tick -> curTick:: " + cursor.tick;
cursor.next();
conLog(46, "- doNext, ", debT, " -> " + cursor.tick);
};
/***
* Sets "play" and Chord duration.
* @param {String} <debT> Name for the chord in debug text.
* @param {MS Chord} <chord> Chord.
* @param {MS Cursor} <useCursor> Cursor.
* @param {Number} <duration> Duration for the Chord.
* @param {Number} <denominator> opt.(4) the measure denominator.
*/
st.setPlayAndChordDuration = function(debT, chord, useCursor, duration, denominator) {
// set "play duration"
if (! denominator) denominator = 4;
conLog(4, debT + ".setDuration: ", st.ticksToStr(duration), "/", denominator);
useCursor.setDuration(st.ticksToSteps(duration), denominator);
// set "note duration"
chord.durationType = duration;
conLog(4, "set ", debT, ".duration to: ", st.ticksToStr(chord.durationType),
", (in)duration: ", duration
);
};
/***
* Clone a Chord. (Muse's 'clone()' doesn't seem to work)
* @param {MS Chord} <chord> The Chord to clone.
* @param {Number} <durationType> opt. Duration for the new Chord, default
* is Duration for <chord>.
* @return {MS Chord} the new cloned Chord.
*/
st.cloneChord = function(chord, durationType) {
var k, note, newChord;
if (st.isRest(chord)) {
newChord = newElement(Element.REST);
} else {
newChord = newElement(Element.CHORD);
for (k in chord.notes) {
note = chord.notes[k];
newChord.add(createNote(note.pitch, note.tpc1, note.tpc2));
}
}
newChord.durationType = durationType ? durationType : chord.durationType;
return newChord;
};
/***
* Determine if Segment has a Chord or Rest.
* @param {MS Segment} <object> The segment to determine.
* @return {Bool} If the element is a Rest.
*/
st.isChordRest = function(object) {
if (! object) return false;
if (object.type === Element.SEGMENT) {
return (object.segmentType === Segment.ChordRest);
} else {
return (st.isChord(object) || st.isRest(object));
}
};
/***
* Determine if Element is a Chord. (Muse's 'isChord()' doesn't seem to work)
* @param {MS Element} <element> The element to determine.
* @return {Bool} If the element is a Chord.
*/
st.isChord = function(element) {
return (element && element.type === Element.CHORD);
};
/***
* Determine if Element is a Rest. (Muse's 'isRest()' doesn't seem to work)
* @param {MS Element} <element> The element to determine.
* @return {Bool} If the element is a Rest.
*/
st.isRest = function(element) {
return (element && element.type === Element.REST);
};
//////////////////////////////////////////////////////////////////////////////
/***
* Object for Chord/Rest.
*/
st.elemObject = function () {
var el = this;
var element;
/***
* Sets some useful values for a Measure, Segment, Chord or Rest.
* @param {MS Element} <inElement> Element to be examined.
* @param {String} <debT> opt. Debug test.
* @return {elemObject} self
*/
el.init = function(inElement, debT) {
element = inElement;
el.self = element;
var tick = element.parent && element.parent.tick;
// secure blank
if (! debT) { debT = ""; } else { debT += " "; }
// (for some reason I must add "" as last argument, otherwise it will be "undefined" as last - strange...)
conLog(42, "ElObj, ", debT, "element: ", element, ", @", tick, " ---", "");
if (! element) return null;
el.isMeasure = (element.type === Element.MEASURE);
el.isSegment = (element.type === Element.SEGMENT);
el.isChord = (element.type === Element.CHORD);
el.isRest = (element.type === Element.REST);
el.isChordRest = (el.isChord || el.isRest ||
el.segmentType && el.segmentType === Segment.ChordRest);
el.measureRemain = null;
el.nextChordTick = null;
var firstSeg, lastSeg, text, swOk,
okBit = 0,
elm = element;
while (elm) {
conLog(43, "ElObj, elm: ", elm);
if (elm.type === Element.SYSTEM) break;
if (elm.type === Element.CHORD || elm.type === Element.REST) {
el.ticks = elm.durationType;
conLog(42, "ElObj, elm Chord/Rest.duration: ", st.ticksToStr(el.ticks));
okBit |= 0x1;
} else if (elm.type === Element.SEGMENT) {
el.tick = elm.tick;
// (.next is the next global segment)
// (.nextInMeasure is null if last Segment)
el.nextSeg = elm.nextInMeasure;
el.nextTick = el.nextSeg && el.nextSeg.tick;
if (! el.ticks && elm.element) el.ticks = elm.element.durationType;
conLog(43, "ElObj, elm Segment.tick: ", el.tick);
if (truthy(el.ticks, 0)) {
okBit |= 0x2;
} else {
conLog(42, "ElObj, elm Segment can't set el.ticks (duration)");
}
} else if (elm.type === Element.MEASURE) {
firstSeg = elm.firstSegment;
lastSeg = elm.lastSegment;
swOk = true;
if (lastSeg.segmentType === Segment.EndBarLine) {
text = "Segment.EndBarLine";
} else if (lastSeg.segmentType === Segment.KeySigAnnounce) {
text = "Segment.KeySigAnnounce";
} else {
swOk = false;
text = "" + lastSeg.segmentType +
" (Segment.EndBarLine = " + Segment.EndBarLine +
", Segment.KeySigAnnounce = " + Segment.KeySigAnnounce + ")";
}
conLog(43, "ElObj, last Segment.segmentType: ", text);
if (truthy(el.tick, 0) && swOk) {
// NB 'measureRemain' is including elements durationType
el.measureRemain = lastSeg.tick - el.tick;
if (! el.measureRemain || el.measureRemain < 0) el.measureRemain = 0;
el.measureTicks = lastSeg.tick - firstSeg.tick;
conLog(42,
"ElObj, elm Measure.duration: ", st.ticksToStr(el.measureTicks),
", .ticks remain: ", st.ticksToStr(el.measureRemain)
);
} else {
// (prepared for debugging...)
if (false) {
conLog(99, "Segment.All: " + Segment.All);
conLog(99, "Segment.Ambitus: " + Segment.Ambitus);
conLog(99, "Segment.BarLine: " + Segment.BarLine);
conLog(99, "Segment.Breath: " + Segment.Breath);
conLog(99, "Segment.ChordRest: " + Segment.ChordRest);
conLog(99, "Segment.Clef: " + Segment.Clef);
conLog(99, "Segment.EndBarLine: " + Segment.EndBarLine);
conLog(99, "Segment.Invalid: " + Segment.Invalid);
conLog(99, "Segment.KeySig: " + Segment.KeySig);
conLog(99, "Segment.KeySigAnnounce: " + Segment.KeySigAnnounce);
conLog(99, "Segment.StartRepeatBarLine: " + Segment.StartRepeatBarLine);
conLog(99, "Segment.TimeSig: " + Segment.TimeSig);
conLog(99, "Segment.TimeSigAnnounce: " + Segment.TimeSigAnnounce);
}
el.errorMessage = "Can't get tick after last element of the measure";
el.errorInfo = "\"last element\" of the measure isn't a Bar Line";
break;
}
el.measureTick = firstSeg.tick;
if (el.measureTicks) okBit |= 0x4;
}
elm = elm.parent;
}
if (okBit === (0x1 | 0x2 | 0x4)) {
el.ok = true;
} else {
el.ok = false;
var text = conLog(42, "ElObj, NO success! okBit: ", okBit);
if (! el.errorMessage) el.errorMessage = conLog(42, "ElObj, NO success! okBit: ", okBit);
}
return el;
};
/***
* Gets max possible duration for 'self', setting it if <swSet> and over max.
* @param {Bool} <swSet> If max duration should be set for 'self'.
* @param {MS Cursor} <cursor> opt. Needed if setting the duration.
* @param {String} <debT> opt. Debug text.
* @return {Number|Bool} max duration unless <swSet> otherwise if duration is changed
*/
el.maxTicks = function(swSet, cursor, debT) {
if (! el.nextChordTick) el.nextChordTick = el.tick + el.measureRemain;
var ticksMax = Math.min(el.measureRemain, el.nextChordTick - el.tick);
conLog(42,
"Math.min(el.measureRemain: ", st.ticksToStr(el.measureRemain),
", el.nextTick - el.tick: ", st.ticksToStr(el.nextChordTick, "", +1),
" - ", st.ticksToStr(el.tick, "", +1), " )",
" = ", st.ticksToStr(ticksMax, "")
);
if (! swSet) return ticksMax;
if (! debT) debT = "";
if (debT) debT += " ";
if (el.ticks === ticksMax) {
conLog(42, debT + "(already max ticks ", st.ticksToStr(el.ticks), ")");
return false;
}
if (debT) debT += "set to maxTicks";
el.setDurationType(ticksMax, null, cursor, debT);
return true;
};
/***
* Calling 'setDuration' and sets the duration for 'self'.
* @param {Number} <durationType> Duration to be set (or increase or decrease, see <type>).
* @param {String} <type> opt. "+"/"-" if duration should be increased
* or decreased instead of absolut value.
* @param {MS Cursor} <cursor> Cursor.
* @param {String} <debT> Debug text.
* @return {Number} the new duration
*/
el.setDurationType = function(durationType, type, cursor, debT) {
var ticks = element.durationType, debType = type;
switch (type) {
case '+': ticks += durationType; break;
case '-': ticks -= durationType; break;
default:
debType = "";
ticks = durationType;
}
if (cursor) {
st.setPlayAndChordDuration(debT, element, cursor, ticks);
} else {
element.durationType = ticks;
}
el.ticks = element.durationType;
if (! debT) { debT = ""; } else { debT += " "; };
conLog(42, "ElObj, " + debT + "set durationType in: ", debType, st.ticksToStr(durationType),
", (and element has now: ", st.ticksToStr(element.durationType), ")"
);
return el.ticks;
};
el.debugNoteTpcs = function(chord, harmonyObj) {
var note, noteInd = 0;
while ((note = chord.notes[noteInd++])) {
if (noteInd === 1) conLog(45, { obj: note });
conLog(44, "Note, pitch: ", note.pitch,
", tpc: ", note.tpc, ", tpc1: ", note.tpc1, ", tpc2: ", note.tpc2,
", tpcL: ", harmonyObj.tpcInfo(note.tpc ).letterAlt,
", tpc1L: ", harmonyObj.tpcInfo(note.tpc1).letterAlt,
", tpc2L: ", harmonyObj.tpcInfo(note.tpc2).letterAlt
);
}
};
};
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
/***
* Object for parsing a Harmony text.
*/
st.harmonyObject = function () {
var ho = this;
// (not necessary to init these, only for clarity)
ho.errorMessage = null;
ho.ok = null;
ho.error = null;
ho.noChord = null;
ho.root = null;
ho.bass = null;
ho.tFlt2 = -2;
ho.tFlt = -1;
ho.tStr = 0;