-
Notifications
You must be signed in to change notification settings - Fork 14
/
measure.ts
1319 lines (1255 loc) · 38.4 KB
/
measure.ts
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
// [Smoosic](https://github.com/AaronDavidNewman/Smoosic)
// Copyright (c) Aaron David Newman 2021.
/**
* Contains definition and supporting classes for {@link SmoMeasure}.
* Most of the engraving is done at the measure level. Measure contains multiple (at least 1)
* voices, which in turn contain notes. Each measure also contains formatting information. This
* is mostly serialized outside of measure (in score), since columns and often an entire region
* share measure formatting. Measures also contain modifiers like barlines. Tuplets and beam groups
* are contained at the measure level.
* @module /smo/data/measure
*/
import { smoSerialize } from '../../common/serializationHelpers';
import { SmoMusic } from './music';
import {
SmoBarline, SmoMeasureModifierBase, SmoRepeatSymbol, SmoTempoText, SmoMeasureFormat,
SmoVolta, SmoRehearsalMarkParams, SmoRehearsalMark, SmoTempoTextParams, TimeSignature
} from './measureModifiers';
import { SmoNote, NoteType } from './note';
import { SmoTuplet } from './tuplet';
import { layoutDebug } from '../../render/sui/layoutDebug';
import { SvgHelpers } from '../../render/sui/svgHelpers';
import { TickMap, TickAccidental } from '../xform/tickMap';
import { MeasureNumber, SvgBox, SmoAttrs, Pitch, PitchLetter, Clef, FontInfo } from './common';
import { SmoSelector } from '../xform/selections';
/**
* Voice is just a container for {@link SmoNote}
*/
export interface SmoVoice {
notes: SmoNote[]
}
/**
* TickMappable breaks up a circular dependency on modifiers
* like @SmoDuration
*/
export interface TickMappable {
voices: SmoVoice[],
keySignature: string
}
export interface MeasureTick {
voiceIndex: number,
tickIndex: number
}
// @internal
const VF = eval('Vex.Flow');
/**
* Break up a circlar dependency with {@link SmoBeamGroup}
*/
export interface ISmoBeamGroup {
notes: SmoNote[],
voice: number,
attrs: SmoAttrs
}
/**
* geometry information about the current measure for rendering and
* score layout.
* @internal
*/
export interface MeasureSvg {
staffWidth: number,
unjustifiedWidth: number,
adjX: number, // The start point of the music in the stave (after time sig, etc)
staffX: number, // The left-most x position of the staff
staffY: number,
logicalBox: SvgBox,
yTop: number,
adjRight: number,
history: string[],
lineIndex: number,
pageIndex: number,
rowInSystem: number,
forceClef: boolean,
forceKeySignature: boolean,
forceTimeSignature: boolean,
forceTempo: boolean,
hideMultimeasure: boolean,
multimeasureLength: number,
multimeasureEndBarline: number,
element: SVGSVGElement | null
}
/**
* Interface for a {@link TickMap} for each voice
* for formatting
*/
export interface MeasureTickmaps {
tickmaps: TickMap[],
accidentalMap: Record<string | number, Record<string, TickAccidental>>,
accidentalArray: AccidentalArray[]
}
/**
* Column-mapped modifiers, managed by the {@link SmoScore}
*/
export interface ColumnMappedParams {
// ['timeSignature', 'keySignature', 'tempo']
timeSignature: any,
keySignature: string,
tempo: any
}
// @internal
export type SmoMeasureNumberParam = 'padRight' | 'transposeIndex' | 'activeVoice' | 'lines';
// @internal
export const SmoMeasureNumberParams: SmoMeasureNumberParam[] = ['padRight', 'transposeIndex', 'activeVoice', 'lines'];
// @internal
export type SmoMeasureStringParam = 'timeSignatureString' | 'keySignature';
// @internal
export const SmoMeasureStringParams: SmoMeasureStringParam[] = ['timeSignatureString', 'keySignature'];
/**
* constructor parameters for a {@link SmoMeasure}. Usually you will call
* {@link SmoMeasure.defaults}, and modify the parameters you need to change.
*
* @param timeSignature
* @param timeSignatureString for pickups, the displayed time signature might be different than the actual
* @param keySignature
* @param padRight configured offset from previous measure
* @param tuplets
* @param transposeIndex calculated from {@link SmoPartInfo} for non-concert-key instruments
* @param lines number of lines in the stave
* @param staffY Y coordinate (UL corner) of the measure stave
* @param measureNumber combination configured/calculated measure number
* @param clef
* @param voices
* @param activeVoice the active voice in the editor
* @param tempo
* @param format measure format, is managed by the score
* @param modifiers All measure modifiers that5 aren't format, timeSignature or tempo
* @category SmoParameters
*/
export interface SmoMeasureParams {
timeSignature: TimeSignature,
timeSignatureString: string,
keySignature: string,
padRight: number,
tuplets: SmoTuplet[],
transposeIndex: number,
lines: number,
staffY: number,
// bars: [1, 1], // follows enumeration in VF.Barline
measureNumber: MeasureNumber,
clef: Clef,
voices: SmoVoice[],
activeVoice: number,
tempo: SmoTempoText,
format: SmoMeasureFormat | null,
modifiers: SmoMeasureModifierBase[]
}
/**
* Used to create {@link MeasureTickmaps}
*/
export interface AccidentalArray {
duration: string | number,
pitches: Record<string, TickAccidental>
}
/**
* Data for a measure of music. Many rules of musical engraving are
* enforced at a measure level: the duration of notes, accidentals, etc.
*
* Measures contain {@link SmoNote}, {@link SmoTuplet}, and {@link SmoBeamGroup}
* Measures are contained in {@link SmoSystemStaff}
* @category SmoObject
*/
export class SmoMeasure implements SmoMeasureParams, TickMappable {
static get timeSignatureDefault(): TimeSignature {
return new TimeSignature({
actualBeats: 4,
beatDuration: 4,
useSymbol: false,
display: true
});
}
static defaultDupleDuration: number = 4096;
static defaultTripleDuration: number = 2048 * 3;
// @internal
static readonly _defaults: SmoMeasureParams = {
timeSignature: SmoMeasure.timeSignatureDefault,
timeSignatureString: '',
keySignature: 'C',
padRight: 10,
tuplets: [],
transposeIndex: 0,
modifiers: [],
staffY: 40,
// bars: [1, 1], // follows enumeration in VF.Barline
measureNumber: {
localIndex: 0,
systemIndex: 0,
measureIndex: 0,
staffId: 0
},
clef: 'treble',
lines: 5,
voices: [],
format: new SmoMeasureFormat(SmoMeasureFormat.defaults),
activeVoice: 0,
tempo: new SmoTempoText(SmoTempoText.defaults)
}
/**
* Default constructor parameters. Defaults are always copied so the
* caller can modify them to create a new measure.
* @returns constructor params for a new measure
*/
static get defaults(): SmoMeasureParams {
const proto: any = JSON.parse(JSON.stringify(SmoMeasure._defaults));
proto.format = new SmoMeasureFormat(SmoMeasureFormat.defaults);
proto.tempo = new SmoTempoText(SmoTempoText.defaults);
proto.modifiers.push(new SmoBarline({
position: SmoBarline.positions.start,
barline: SmoBarline.barlines.singleBar
}));
proto.modifiers.push(new SmoBarline({
position: SmoBarline.positions.end,
barline: SmoBarline.barlines.singleBar
}));
return proto;
}
// @ignore
static convertLegacyTimeSignature(ts: string) {
const rv = new TimeSignature(TimeSignature.defaults);
rv.timeSignature = ts;
return rv;
}
timeSignature: TimeSignature = SmoMeasure.timeSignatureDefault;
/**
* Overrides display of actual time signature, in the case of
* pick-up notes where the actual and displayed durations are different
*/
timeSignatureString: string = '';
keySignature: string = '';
canceledKeySignature: string = '';
padRight: number = 10;
tuplets: SmoTuplet[] = [];
/**
* Adjust for non-concert pitch intstruments
*/
transposeIndex: number = 0;
modifiers: SmoMeasureModifierBase[] = [];
/**
* Row, column, and custom numbering information about this measure.
*/
measureNumber: MeasureNumber = {
localIndex: 0,
systemIndex: 0,
measureIndex: 0,
staffId: 0
};
clef: Clef = 'treble';
voices: SmoVoice[] = [];
/**
* the active voice in the editor, if there are multiple voices
* */
activeVoice: number = 0;
tempo: SmoTempoText;
beamGroups: ISmoBeamGroup[] = [];
lines: number = 5;
/**
* Runtime information about rendering
*/
svg: MeasureSvg;
/**
* Measure-specific formatting parameters.
*/
format: SmoMeasureFormat;
/**
* Information for identifying this object
*/
attrs: SmoAttrs;
/**
* Fill in components. We assume the modifiers are already constructed,
* e.g. by deserialize or the calling function.
* @param params
*/
constructor(params: SmoMeasureParams) {
this.tempo = new SmoTempoText(SmoTempoText.defaults);
this.svg = {
staffWidth: 0,
unjustifiedWidth: 0,
staffX: 0,
staffY: 0,
logicalBox: {
x: 0, y: 0, width: 0, height: 0
},
yTop: 0,
adjX: 0,
adjRight: 0,
history: [],
lineIndex: 0,
pageIndex: 0,
rowInSystem: 0,
forceClef: false,
forceKeySignature: false,
forceTimeSignature: false,
forceTempo: false,
hideMultimeasure: false,
multimeasureLength: 0,
multimeasureEndBarline: SmoBarline.barlines['singleBar'],
element: null
};
const defaults = SmoMeasure.defaults;
SmoMeasureNumberParams.forEach((param) => {
if (typeof (params[param]) !== 'undefined') {
this[param] = params[param];
}
});
SmoMeasureStringParams.forEach((param) => {
this[param] = params[param] ? params[param] : defaults[param];
});
this.clef = params.clef;
this.measureNumber = JSON.parse(JSON.stringify(params.measureNumber));
if (params.tempo) {
this.tempo = new SmoTempoText(params.tempo);
}
// Handle legacy time signature format
if (params.timeSignature) {
const tsAny = params.timeSignature as any;
if (typeof (tsAny) === 'string') {
this.timeSignature = SmoMeasure.convertLegacyTimeSignature(tsAny);
} else {
this.timeSignature = new TimeSignature(tsAny);
}
}
this.voices = params.voices ? params.voices : [];
this.tuplets = params.tuplets ? params.tuplets : [];
this.modifiers = params.modifiers ? params.modifiers : defaults.modifiers;
this.setDefaultBarlines();
this.keySignature = SmoMusic.vexKeySigWithOffset(this.keySignature, this.transposeIndex);
if (!(params.format)) {
this.format = new SmoMeasureFormat(SmoMeasureFormat.defaults);
this.format.measureIndex = this.measureNumber.measureIndex;
} else {
this.format = new SmoMeasureFormat(params.format);
}
this.attrs = {
id: VF.Element.newID(),
type: 'SmoMeasure'
};
}
// @internal
// used for serialization
static get defaultAttributes() {
return [
'keySignature', 'timeSignatureString',
'measureNumber',
'activeVoice', 'clef', 'transposeIndex',
'format', 'rightMargin', 'lines'
];
}
// @internal
// used for serialization
static get formattingOptions() {
return ['customStretch', 'customProportion', 'autoJustify', 'systemBreak',
'pageBreak', 'padLeft'];
}
// @internal
// used for serialization
static get columnMappedAttributes() {
return ['timeSignature', 'keySignature', 'tempo'];
}
static get serializableAttributes() {
const rv: any = [];
SmoMeasure.defaultAttributes.forEach((attr) => {
if (SmoMeasure.columnMappedAttributes.indexOf(attr) < 0) {
rv.push(attr);
}
});
return rv;
}
/**
// Return true if the time signatures are the same, for display purposes (e.g. if a time sig change
// is required)
*/
static timeSigEqual(o1: TimeSignature, o2: TimeSignature) {
return o1.timeSignature === o2.timeSignature && o1.useSymbol === o2.useSymbol;
}
/**
* @internal
* @returns column mapped parameters, serialized. caller will
* decide if the parameters need to be persisted
*/
serializeColumnMapped(): ColumnMappedParams {
//
return {
timeSignature: this.timeSignature.serialize(),
keySignature: this.keySignature,
tempo: this.tempo.serialize()
};
}
/**
* Convert this measure object to a JSON object, recursively serializing all the notes,
* note modifiers, etc.
*/
serialize(): any {
const params: any = {};
let ser = true;
const defaults = SmoMeasure.defaults;
smoSerialize.serializedMergeNonDefault(SmoMeasure.defaults, SmoMeasure.serializableAttributes, this, params);
// measure number can't be defaulted b/c tempos etc. can map to default measure
params.measureNumber = JSON.parse(JSON.stringify(this.measureNumber));
params.tuplets = [];
params.voices = [];
params.modifiers = [];
this.tuplets.forEach((tuplet) => {
params.tuplets.push(tuplet.serialize());
});
this.voices.forEach((voice) => {
const obj: any = {
notes: []
};
voice.notes.forEach((note) => {
obj.notes.push(note.serialize());
});
params.voices.push(obj);
});
this.modifiers.forEach((modifier) => {
ser = true;
/* don't serialize default modifiers */
if (modifier.ctor === 'SmoBarline' && (modifier as SmoBarline).position === SmoBarline.positions.start &&
(modifier as SmoBarline).barline === SmoBarline.barlines.singleBar) {
ser = false;
} else if (modifier.ctor === 'SmoBarline' && (modifier as SmoBarline).position === SmoBarline.positions.end
&& (modifier as SmoBarline).barline === SmoBarline.barlines.singleBar) {
ser = false;
} else if (modifier.ctor === 'SmoTempoText') {
// we don't save tempo text as a modifier anymore
ser = false;
} else if ((modifier as SmoRepeatSymbol).ctor === 'SmoRepeatSymbol' && (modifier as SmoRepeatSymbol).position === SmoRepeatSymbol.positions.start
&& (modifier as SmoRepeatSymbol).symbol === SmoRepeatSymbol.symbols.None) {
ser = false;
}
if (ser) {
params.modifiers.push(modifier.serialize());
}
});
// ['timeSignature', 'keySignature', 'tempo']
return params;
}
/**
* restore a serialized measure object. Usually called as part of deserializing a score,
* but can also be used to restore a measure due to an undo operation. Recursively
* deserialize all the notes and modifiers to construct a new measure.
* @param jsonObj the serialized SmoMeasure
* @returns
*/
static deserialize(jsonObj: any): SmoMeasure {
let j = 0;
let i = 0;
const voices = [];
const noteSum = [];
for (j = 0; j < jsonObj.voices.length; ++j) {
const voice = jsonObj.voices[j];
const notes: any = [];
voices.push({
notes
});
for (i = 0; i < voice.notes.length; ++i) {
const noteParams = voice.notes[i];
const smoNote = SmoNote.deserialize(noteParams);
notes.push(smoNote);
noteSum.push(smoNote);
}
}
const tuplets = [];
for (j = 0; j < jsonObj.tuplets.length; ++j) {
const tupJson = jsonObj.tuplets[j];
const noteAr = noteSum.filter((nn: any) =>
nn.isTuplet && nn.tuplet.id === tupJson.attrs.id);
// Bug fix: A tuplet with no notes may be been overwritten
// in a copy/paste operation
if (noteAr.length > 0) {
tupJson.notes = noteAr;
const tuplet = new SmoTuplet(tupJson);
tuplets.push(tuplet);
}
}
const modifiers: SmoMeasureModifierBase[] = [];
jsonObj.modifiers.forEach((modParams: any) => {
const modifier: SmoMeasureModifierBase = SmoMeasureModifierBase.deserialize(modParams);
modifiers.push(modifier);
});
const params: SmoMeasureParams = SmoMeasure.defaults;
smoSerialize.serializedMerge(SmoMeasure.defaultAttributes, jsonObj, params);
// explode column-mapped
params.tempo = jsonObj.tempo;
params.timeSignature = jsonObj.timeSignature;
params.keySignature = jsonObj.keySignature;
params.voices = voices;
params.tuplets = tuplets;
params.modifiers = modifiers;
const rv = new SmoMeasure(params);
// Handle migration for measure-mapped parameters
rv.modifiers.forEach((mod) => {
if (mod.ctor === 'SmoTempoText') {
rv.tempo = (mod as SmoTempoText);
}
});
if (!rv.tempo) {
rv.tempo = new SmoTempoText(SmoTempoText.defaults);
}
return rv;
}
/**
* When creating a new measure, the 'default' settings can vary depending on
* what comes before/after the measure. This determines the default pitch
* for a clef (appears on 3rd line)
*/
static get defaultPitchForClef(): Record<Clef, Pitch> {
return {
'treble': {
letter: 'b',
accidental: 'n',
octave: 4
},
'bass': {
letter: 'd',
accidental: 'n',
octave: 3
},
'tenor': {
letter: 'a',
accidental: 'n',
octave: 3
},
'alto': {
letter: 'c',
accidental: 'n',
octave: 4
},
'soprano': {
letter: 'b',
accidental: 'n',
octave: 4
},
'percussion': {
letter: 'b',
accidental: 'n',
octave: 4
},
'mezzo-soprano': {
letter: 'b',
accidental: 'n',
octave: 4
},
'baritone-c': {
letter: 'b',
accidental: 'n',
octave: 3
},
'baritone-f': {
letter: 'e',
accidental: 'n',
octave: 3
},
'subbass': {
letter: 'd',
accidental: '',
octave: 2
},
'french': {
letter: 'b',
accidental: '',
octave: 4
} // no idea
};
}
static _emptyMeasureNoteType: NoteType = 'r';
static set emptyMeasureNoteType(tt: NoteType) {
SmoMeasure._emptyMeasureNoteType = tt;
}
static get emptyMeasureNoteType(): NoteType {
return SmoMeasure._emptyMeasureNoteType;
}
static timeSignatureNotes(timeSignature: TimeSignature, clef: Clef) {
const pitch = SmoMeasure.defaultPitchForClef[clef];
const maxTicks = SmoMusic.timeSignatureToTicks(timeSignature.timeSignature);
const noteTick = 8192 / (timeSignature.beatDuration / 2);
let ticks = 0;
let beamBeats = 2;
if (timeSignature.beatDuration === 8 && (timeSignature.actualBeats % 3 === 0 || timeSignature.actualBeats % 2 !== 0)) {
beamBeats = 3;
}
if (timeSignature.beatDuration === 16) {
beamBeats = 4;
}
const pnotes: SmoNote[] = [];
while (ticks < maxTicks) {
const nextNote = SmoNote.defaults;
nextNote.pitches = [JSON.parse(JSON.stringify(pitch))];
nextNote.noteType = 'r';
nextNote.ticks.numerator = noteTick;
pnotes.push(new SmoNote(nextNote));
ticks += noteTick;
}
if (timeSignature.beatDuration === 8 && (timeSignature.actualBeats % 3 === 0 || timeSignature.actualBeats % 2 !== 0)) {
let ix = 0;
pnotes.forEach((pnote) => {
if ((ix + 1) % 3 === 0) {
pnote.endBeam = true;
}
pnote.beamBeats = 2048 * 3;
ix += 1;
});
}
return pnotes;
}
/**
* Get a measure full of default notes for a given timeSignature/clef.
* returns 8th notes for triple-time meters, etc.
* @param params
* @returns
*/
static getDefaultNotes(params: SmoMeasureParams): SmoNote[] {
return SmoMeasure.timeSignatureNotes(new TimeSignature(params.timeSignature), params.clef);
}
/**
* When creating a new measure, the 'default' settings can vary depending on
* what comes before/after the measure. This determines the defaults from the
* parameters that are passed in, which could be another measure in the score.
* This version returns params with no notes, for callers that want to use their own notes.
* If you want the default notes, see {@link getDefaultMeasureWithNotes}
*
* @param params
* @returns
*/
static getDefaultMeasure(params: SmoMeasureParams): SmoMeasure {
const obj: any = {};
smoSerialize.serializedMerge(SmoMeasure.defaultAttributes, SmoMeasure.defaults, obj);
smoSerialize.serializedMerge(SmoMeasure.defaultAttributes, params, obj);
// Don't copy column-formatting options to new measure in new column
smoSerialize.serializedMerge(SmoMeasure.formattingOptions, SmoMeasure.defaults, obj);
obj.timeSignature = new TimeSignature(params.timeSignature);
// The measure expects to get concert KS in constructor and adjust for instrument. So do the
// opposite.
obj.keySignature = SmoMusic.vexKeySigWithOffset(obj.keySignature, -1 * obj.transposeIndex);
// Don't redisplay tempo for a new measure
const rv = new SmoMeasure(obj);
if (rv.tempo && rv.tempo.display) {
rv.tempo.display = false;
}
return rv;
}
/**
* When creating a new measure, the 'default' settings can vary depending on
* what comes before/after the measure. This determines the defaults from the
* parameters that are passed in, which could be another measure in the score.
*
* @param params
* @returns
*/
static getDefaultMeasureWithNotes(params: SmoMeasureParams): SmoMeasure {
var measure = SmoMeasure.getDefaultMeasure(params);
measure.voices.push({
notes: SmoMeasure.getDefaultNotes(params)
});
// fix a bug.
// new measures only have 1 voice, make sure active voice is 0
measure.activeVoice = 0;
return measure;
}
/**
* used by xml export
* @internal
* @param val
*/
getForceSystemBreak() {
return this.format.systemBreak;
}
// @internal
setDefaultBarlines() {
if (!this.getStartBarline()) {
this.modifiers.push(new SmoBarline({
position: SmoBarline.positions.start,
barline: SmoBarline.barlines.singleBar
}));
}
if (!this.getEndBarline()) {
this.modifiers.push(new SmoBarline({
position: SmoBarline.positions.end,
barline: SmoBarline.barlines.singleBar
}));
}
}
get containsSound(): boolean {
let i = 0;
for (i = 0; i < this.voices.length; ++i) {
let j = 0;
const voice = this.voices[i];
for (j = 0; j < this.voices.length; ++j) {
if (voice.notes[j].noteType === 'n') {
return true;
}
}
}
return false;
}
/**
* The rendered width of the measure, or estimate of same
*/
get staffWidth() {
return this.svg.staffWidth;
}
/**
* set the rendered width of the measure, or estimate of same
*/
setWidth(width: number, description: string) {
if (layoutDebug.flagSet(layoutDebug.values.measureHistory)) {
this.svg.history.push('setWidth ' + this.staffWidth + '=> ' + width + ' ' + description);
}
if (isNaN(width)) {
throw ('NAN in setWidth');
}
this.svg.staffWidth = width;
}
/**
* Get rendered or estimated start x
*/
get staffX(): number {
return this.svg.staffX;
}
/**
* Set rendered or estimated start x
*/
setX(x: number, description: string) {
if (isNaN(x)) {
throw ('NAN in setX');
}
layoutDebug.measureHistory(this, 'staffX', x, description);
this.svg.staffX = Math.round(x);
}
/**
* Get rendered or estimated start y
*/
get staffY(): number {
return this.svg.staffY;
}
/**
* Set rendered or estimated start y
*/
setY(y: number, description: string) {
if (isNaN(y)) {
throw ('NAN in setY');
}
layoutDebug.measureHistory(this, 'staffY', y, description);
this.svg.staffY = Math.round(y);
}
/**
* Return actual or estimated highest point in score
*/
get yTop(): number {
return this.svg.yTop;
}
/**
* WHen setting an instrument, offset the pitches to match the instrument key
* @param offset
* @param newClef
*/
transposeToOffset(offset: number, targetKey: string, newClef?: Clef) {
const diff = offset - this.transposeIndex;
this.voices.forEach((voice) => {
voice.notes.forEach((note) => {
const pitches: number[] = [...Array(note.pitches.length).keys()];
// when the note is a rest, preserve the rest but match the new clef.
if (newClef && note.noteType === 'r') {
const defp = JSON.parse(JSON.stringify(SmoMeasure.defaultPitchForClef[newClef]));
note.pitches = [defp];
} else {
note.transpose(pitches, diff, this.keySignature, targetKey);
note.getGraceNotes().forEach((gn) => {
const gpitch: number[] = [...Array(gn.pitches.length).keys()];
const xpose = SmoNote.transpose(gn, gpitch, diff, this.keySignature, targetKey);
gn.pitches = xpose.pitches;
});
}
});
});
}
/**
* Return actual or estimated highest point in score
*/
setYTop(y: number, description: string) {
layoutDebug.measureHistory(this, 'yTop', y, description);
this.svg.yTop = y;
}
/**
* Return actual or estimated bounding box
*/
setBox(box: SvgBox, description: string) {
layoutDebug.measureHistory(this, 'logicalBox', box, description);
this.svg.logicalBox = SvgHelpers.smoBox(box);
}
/**
* @returns the DOM identifier for this measure when rendered
*/
getClassId() {
return 'mm-' + this.measureNumber.staffId + '-' + this.measureNumber.measureIndex;
}
/**
*
* @param id
* @returns
*/
getRenderedNote(id: string) {
let j = 0;
let i = 0;
for (j = 0; j < this.voices.length; ++j) {
const voice = this.voices[j];
for (i = 0; i < voice.notes.length; ++i) {
const note = voice.notes[i];
if (note.renderId === id) {
return {
smoNote: note,
voice: j,
tick: i
};
}
}
}
return null;
}
getNotes() {
return this.voices[this.activeVoice].notes;
}
getActiveVoice() {
return this.activeVoice;
}
setActiveVoice(vix: number) {
if (vix >= 0 && vix < this.voices.length) {
this.activeVoice = vix;
}
}
tickmapForVoice(voiceIx: number) {
return new TickMap(this, voiceIx);
}
// ### createMeasureTickmaps
// A tickmap is a map of notes to ticks for the measure. It is speciifc per-voice
// since each voice may have different numbers of ticks. The accidental map is
// overall since accidentals in one voice apply to accidentals in the other
// voices. So we return the tickmaps and the overall accidental map.
createMeasureTickmaps(): MeasureTickmaps {
let i = 0;
const tickmapArray: TickMap[] = [];
const accidentalMap: Record<string | number, Record<string, TickAccidental>> =
{} as Record<string | number, Record<PitchLetter, TickAccidental>>;
for (i = 0; i < this.voices.length; ++i) {
tickmapArray.push(this.tickmapForVoice(i));
}
for (i = 0; i < this.voices.length; ++i) {
const tickmap: TickMap = tickmapArray[i];
const durationKeys: string[] = Object.keys((tickmap.durationAccidentalMap));
durationKeys.forEach((durationKey: string) => {
if (!accidentalMap[durationKey]) {
accidentalMap[durationKey] = tickmap.durationAccidentalMap[durationKey];
} else {
const amap = accidentalMap[durationKey];
const tickable: Record<PitchLetter, TickAccidental> = tickmap.durationAccidentalMap[durationKey];
const letterKeys: PitchLetter[] = Object.keys(tickable) as Array<PitchLetter>;
letterKeys.forEach((pitchKey) => {
if (!amap[pitchKey]) {
amap[pitchKey] = tickmap.durationAccidentalMap[durationKey][pitchKey];
}
});
}
});
}
// duration: duration, pitches: Record<PitchLetter,TickAccidental>
const accidentalArray: AccidentalArray[] = [];
Object.keys(accidentalMap).forEach((durationKey) => {
accidentalArray.push({ duration: durationKey, pitches: accidentalMap[durationKey] });
});
return {
tickmaps: tickmapArray,
accidentalMap,
accidentalArray
};
}
// ### createRestNoteWithDuration
// pad some duration of music with rests.
static createRestNoteWithDuration(duration: number, clef: Clef): SmoNote {
const pitch: Pitch = JSON.parse(JSON.stringify(
SmoMeasure.defaultPitchForClef[clef]));
const note = new SmoNote(SmoNote.defaults);
note.pitches = [pitch];
note.noteType = 'r';
note.hidden = true;
note.ticks = { numerator: duration, denominator: 1, remainder: 0 };
return note;
}
/**
* Count the number of ticks in each voice and return max
* @returns
*/
getMaxTicksVoice() {
let i = 0;
let max = 0;
for (i = 0; i < this.voices.length; ++i) {
const voiceTicks = this.getTicksFromVoice(i);
max = Math.max(voiceTicks, max);
}
return max;
}
/**
* Count the number of ticks in a specific voice
* @param voiceIndex
* @returns
*/
getTicksFromVoice(voiceIndex: number): number {
let ticks = 0;
this.voices[voiceIndex].notes.forEach((note) => {
ticks += note.tickCount;
});
return ticks;
}
getClosestTickCountIndex(voiceIndex: number, tickCount: number): number {
let i = 0;
let rv = 0;
for (i = 0; i < this.voices[voiceIndex].notes.length; ++i) {
const note = this.voices[voiceIndex].notes[i];
if (note.tickCount + rv > tickCount) {
return rv;
}
rv += note.tickCount;
}
return rv;
}
isPickup(): boolean {
const ticks = this.getTicksFromVoice(0);
const goal = SmoMusic.timeSignatureToTicks(this.timeSignature.timeSignature);
return (ticks < goal);
}
clearBeamGroups() {
this.beamGroups = [];
}
// ### updateLyricFont
// Update the lyric font, which is the same for all lyrics.
setLyricFont(fontInfo: FontInfo) {
this.voices.forEach((voice) => {
voice.notes.forEach((note) => {
note.setLyricFont(fontInfo);
});
});
}
setLyricAdjustWidth(adjustNoteWidth: boolean) {
this.voices.forEach((voice) => {
voice.notes.forEach((note) => {
note.setLyricAdjustWidth(adjustNoteWidth);
});
});
}
setChordAdjustWidth(adjustNoteWidth: boolean) {
this.voices.forEach((voice) => {
voice.notes.forEach((note) => {
note.setChordAdjustWidth(adjustNoteWidth);
});
});
}
// ### updateLyricFont