smoosic 2.0.4 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/build/smoosic.js +23 -12
  2. package/changes.md +10 -0
  3. package/package.json +100 -98
  4. package/release/smoosic.js +23 -12
  5. package/specs/042-preserve-music-time-signature/checklists/requirements.md +35 -0
  6. package/specs/042-preserve-music-time-signature/contracts/rebar-api.md +66 -0
  7. package/specs/042-preserve-music-time-signature/data-model.md +73 -0
  8. package/specs/042-preserve-music-time-signature/plan.md +93 -0
  9. package/specs/042-preserve-music-time-signature/quickstart.md +37 -0
  10. package/specs/042-preserve-music-time-signature/research.md +102 -0
  11. package/specs/042-preserve-music-time-signature/spec.md +153 -0
  12. package/specs/042-preserve-music-time-signature/tasks.md +104 -0
  13. package/src/application/exports.ts +1 -0
  14. package/src/render/sui/renderState.ts +4 -4
  15. package/src/render/sui/scoreViewOperations.ts +58 -3
  16. package/src/render/sui/tracker.ts +18 -23
  17. package/src/smo/data/score.ts +12 -5
  18. package/src/smo/xform/operations.ts +49 -0
  19. package/src/smo/xform/rebar.ts +490 -0
  20. package/src/smo/xform/selections.ts +66 -0
  21. package/src/ui/components/dialogs/timeSignature.vue +13 -3
  22. package/src/ui/dialogs/timeSignature.ts +27 -39
  23. package/tests/rebarMeasures.ts +492 -0
  24. package/tests/timeRangeSelect.ts +111 -0
  25. package/typedoc.ts +1 -0
  26. package/types/src/application/exports.d.ts +1 -0
  27. package/types/src/render/sui/scoreViewOperations.d.ts +19 -2
  28. package/types/src/smo/data/score.d.ts +5 -2
  29. package/types/src/smo/xform/operations.d.ts +24 -0
  30. package/types/src/smo/xform/rebar.d.ts +53 -0
  31. package/types/src/smo/xform/selections.d.ts +14 -0
  32. package/types/typedoc.d.ts +1 -0
@@ -0,0 +1,490 @@
1
+ // [Smoosic](https://github.com/AaronDavidNewman/Smoosic)
2
+ // Copyright (c) Aaron David Newman 2021.
3
+ import { SmoScore } from '../data/score';
4
+ import { SmoMeasure, SmoVoice } from '../data/measure';
5
+ import { SmoNote } from '../data/note';
6
+ import { SmoMusic } from '../data/music';
7
+ import { SmoTimeSignature, SmoBarline } from '../data/measureModifiers';
8
+ import { SmoTupletTree } from '../data/tuplet';
9
+ import { SmoTuplet } from '../data/tuplet';
10
+ import { SmoTie, StaffModifierBase } from '../data/staffModifiers';
11
+ import { SmoSelector } from './selections';
12
+ import { Clef } from '../data/common';
13
+
14
+ /**
15
+ * What {@link rebarMeasures} did
16
+ * @category SmoTransform
17
+ */
18
+ export interface RebarResult {
19
+ /** the first re-barred measure */
20
+ firstMeasure: number,
21
+ /** how many measures are now in the range: the ones it had, plus those that were added */
22
+ measureCount: number,
23
+ /** how many measures were added after the old last measure of the range */
24
+ added: number
25
+ }
26
+
27
+ /**
28
+ * Which measures a time signature change applies to: only the selected ones, from the first selected one to the
29
+ * end of the score, or the whole score.
30
+ * @category SmoTransform
31
+ */
32
+ export type TimeSignatureApplyTo = 'Selected' | 'Remaining' | 'Score';
33
+
34
+ /**
35
+ * The range of measures a time signature change applies to.
36
+ * @param applyTo which measures
37
+ * @param selectedMeasures the measure index of each selected note or measure, in any staff, in any order
38
+ * @param measureCount the number of measures in the score
39
+ * @returns the first and last measure, or null if there is no selection (and the choice is not the whole score) or no measures
40
+ */
41
+ export const timeSignatureRange = (applyTo: TimeSignatureApplyTo, selectedMeasures: number[],
42
+ measureCount: number): { firstMeasure: number, lastMeasure: number } | null => {
43
+ if (measureCount < 1) {
44
+ return null;
45
+ }
46
+ if (applyTo === 'Score') {
47
+ return { firstMeasure: 0, lastMeasure: measureCount - 1 };
48
+ }
49
+ if (selectedMeasures.length < 1) {
50
+ return null;
51
+ }
52
+ const firstMeasure = Math.max(0, Math.min(...selectedMeasures));
53
+ const lastSelected = Math.min(measureCount - 1, Math.max(...selectedMeasures));
54
+ return { firstMeasure, lastMeasure: applyTo === 'Remaining' ? measureCount - 1 : lastSelected };
55
+ }
56
+
57
+ /** A position in the re-barred measures: the measure counted from the start of the range, and the note in the voice */
58
+ interface Pos {
59
+ k: number,
60
+ tick: number
61
+ }
62
+ /** Where a source note went. The same position if the note was not split into tied pieces. */
63
+ interface Placement {
64
+ first: Pos,
65
+ last: Pos
66
+ }
67
+ interface SourceNote {
68
+ note: SmoNote,
69
+ /** the old location of the note, from {@link SmoSelector.getNoteKey} */
70
+ key: string
71
+ }
72
+ /** One thing that is laid out whole: a note or rest, a tuplet, or a stretch of rest for a measure that has no such voice */
73
+ interface LayoutUnit {
74
+ notes: SourceNote[],
75
+ ticks: number,
76
+ tuplet: SmoTupletTree | null,
77
+ filler: boolean
78
+ }
79
+ interface LaidMeasure {
80
+ notes: SmoNote[],
81
+ trees: SmoTupletTree[],
82
+ used: number,
83
+ /** true if any note of the source music is in it, as opposed to only rests added to fill */
84
+ hasSource: boolean
85
+ }
86
+ interface PendingTie {
87
+ from: Pos,
88
+ to: Pos,
89
+ fromNote: SmoNote,
90
+ toNote: SmoNote
91
+ }
92
+ interface VoiceLayout {
93
+ measures: LaidMeasure[],
94
+ placements: Record<string, Placement>,
95
+ ties: PendingTie[]
96
+ }
97
+
98
+ /** Tick totals are sums of note lengths, which can be fractions for tuplets */
99
+ const EPSILON = 0.001;
100
+ const fits = (ticks: number, space: number) => ticks <= space + EPSILON;
101
+
102
+ /**
103
+ * The length in ticks of the measure k places after the first of a range that gets a time signature. A time
104
+ * signature with several parts (3/4+2/4) alternates its parts from measure to measure.
105
+ * @param timeSignature the new time signature
106
+ * @param k how many measures after the first re-barred measure
107
+ * @param startIndex which part the first re-barred measure has
108
+ */
109
+ export const rebarMeasureTicks = (timeSignature: SmoTimeSignature, k: number, startIndex: number): number => {
110
+ const part = timeSignature.times[(startIndex + k) % timeSignature.times.length];
111
+ return SmoMusic.timeSignatureToTicks(part.actualBeats, part.beatDuration);
112
+ }
113
+
114
+ /**
115
+ * Which part of a compound time signature the first re-barred measure has. If the measure before the range has
116
+ * the same time signature, the pattern carries on from it, the way {@link SmoScore.updateCompoundTimeSignature}
117
+ * does; otherwise it starts at the first part.
118
+ */
119
+ const rebarStartIndex = (score: SmoScore, firstMeasure: number, timeSignature: SmoTimeSignature): number => {
120
+ if (firstMeasure < 1 || timeSignature.times.length < 2) {
121
+ return 0;
122
+ }
123
+ const before = score.staves[0].measures[firstMeasure - 1];
124
+ if (before && SmoTimeSignature.equal(before.timeSignature, timeSignature)) {
125
+ return (before.timeSignature.index + 1) % timeSignature.times.length;
126
+ }
127
+ return 0;
128
+ }
129
+
130
+ const makeRest = (ticks: number, clef: Clef): SmoNote => {
131
+ const params = SmoNote.defaults;
132
+ params.pitches = [JSON.parse(JSON.stringify(SmoMeasure.defaultPitchForClef[clef]))];
133
+ params.noteType = 'r';
134
+ params.clef = clef;
135
+ params.ticks.numerator = ticks;
136
+ params.stemTicks = ticks;
137
+ return new SmoNote(params);
138
+ }
139
+
140
+ /** A split-off piece of a note keeps the pitches, not the things attached to the note */
141
+ const stripMarkings = (note: SmoNote) => {
142
+ note.textModifiers = [];
143
+ note.articulations = [];
144
+ note.ornaments = [];
145
+ note.graceNotes = [];
146
+ note.arpeggio = undefined;
147
+ }
148
+
149
+ const shiftTuplet = (tuplet: SmoTuplet, delta: number) => {
150
+ tuplet.startIndex += delta;
151
+ tuplet.endIndex += delta;
152
+ tuplet.childrenTuplets.forEach((child) => shiftTuplet(child, delta));
153
+ }
154
+
155
+ /**
156
+ * Read one voice of the measures in a range as a list of things to lay out, in time order. A measure that
157
+ * has no such voice counts as a stretch of rest the length of the measure, so the voice stays in time with the others.
158
+ */
159
+ const flattenVoice = (score: SmoScore, staffIndex: number, voice: number, firstMeasure: number, lastMeasure: number): LayoutUnit[] => {
160
+ const units: LayoutUnit[] = [];
161
+ const staff = score.staves[staffIndex];
162
+ for (let m = firstMeasure; m <= lastMeasure; ++m) {
163
+ const measure = staff.measures[m];
164
+ if (voice >= measure.voices.length) {
165
+ let ticks = measure.getMaxTicksVoice();
166
+ if (ticks < 1) {
167
+ ticks = SmoMusic.timeSignatureToTicks(measure.timeSignature.actualBeats, measure.timeSignature.beatDuration);
168
+ }
169
+ units.push({ notes: [], ticks, tuplet: null, filler: true });
170
+ continue;
171
+ }
172
+ const notes = measure.voices[voice].notes;
173
+ for (let j = 0; j < notes.length; ++j) {
174
+ const key = SmoSelector.getNoteKey({ staff: staffIndex, measure: m, voice, tick: j, pitches: [] });
175
+ const tree = SmoTupletTree.getTupletTreeForNoteIndex(measure.tupletTrees, voice, j);
176
+ if (tree) {
177
+ if (tree.startIndex !== j) {
178
+ continue; // part of the tuplet that was taken at its first note
179
+ }
180
+ const members: SourceNote[] = [];
181
+ let ticks = 0;
182
+ for (let t = tree.startIndex; t <= tree.endIndex && t < notes.length; ++t) {
183
+ members.push({
184
+ note: notes[t],
185
+ key: SmoSelector.getNoteKey({ staff: staffIndex, measure: m, voice, tick: t, pitches: [] })
186
+ });
187
+ ticks += notes[t].tickCount;
188
+ }
189
+ units.push({ notes: members, ticks, tuplet: tree, filler: false });
190
+ } else {
191
+ units.push({ notes: [{ note: notes[j], key }], ticks: notes[j].tickCount, tuplet: null, filler: false });
192
+ }
193
+ }
194
+ }
195
+ return units;
196
+ }
197
+
198
+ /**
199
+ * Lay the units of one voice out again, measure by measure. See research.md R2 for the rules.
200
+ * @param units from {@link flattenVoice}
201
+ * @param lengthOf the length in ticks of the k-th measure
202
+ * @param clef the clef for any rests that are added
203
+ */
204
+ const layoutVoice = (units: LayoutUnit[], lengthOf: (k: number) => number, clef: Clef): VoiceLayout => {
205
+ const measures: LaidMeasure[] = [];
206
+ const placements: Record<string, Placement> = {};
207
+ const ties: PendingTie[] = [];
208
+ // The measure being filled. A new one is started only when there is something to put in it.
209
+ const current = (): LaidMeasure => {
210
+ let m = measures[measures.length - 1];
211
+ if (!m || m.used >= lengthOf(measures.length - 1) - EPSILON) {
212
+ m = { notes: [], trees: [], used: 0, hasSource: false };
213
+ measures.push(m);
214
+ }
215
+ return m;
216
+ };
217
+ const space = (): number => {
218
+ const m = current();
219
+ return lengthOf(measures.length - 1) - m.used;
220
+ };
221
+ const push = (note: SmoNote, source: boolean): Pos => {
222
+ const m = current();
223
+ m.notes.push(note);
224
+ m.used += note.tickCount;
225
+ if (source) {
226
+ m.hasSource = true;
227
+ }
228
+ return { k: measures.length - 1, tick: m.notes.length - 1 };
229
+ };
230
+ const addRests = (ticks: number) => {
231
+ let remaining = ticks;
232
+ while (remaining > EPSILON) {
233
+ const take = Math.min(space(), remaining);
234
+ SmoMusic.gcdMap(Math.round(take)).forEach((duration) => {
235
+ push(makeRest(duration, clef), false);
236
+ });
237
+ remaining -= take;
238
+ }
239
+ };
240
+ const addNote = (source: SourceNote) => {
241
+ const note = source.note;
242
+ const total = note.tickCount;
243
+ if (fits(total, space())) {
244
+ const pos = push(SmoNote.clone(note), true);
245
+ placements[source.key] = { first: pos, last: pos };
246
+ return;
247
+ }
248
+ // The note crosses a bar line: split it at each one. The pieces of a note are tied.
249
+ const pieces: { pos: Pos, note: SmoNote }[] = [];
250
+ let remaining = total;
251
+ while (remaining > EPSILON) {
252
+ const take = Math.min(space(), remaining);
253
+ SmoMusic.gcdMap(Math.round(take)).forEach((duration) => {
254
+ const piece = SmoNote.cloneWithDuration(note, duration);
255
+ if (pieces.length > 0) {
256
+ stripMarkings(piece);
257
+ }
258
+ pieces.push({ pos: push(piece, true), note: piece });
259
+ });
260
+ remaining -= take;
261
+ }
262
+ placements[source.key] = { first: pieces[0].pos, last: pieces[pieces.length - 1].pos };
263
+ if (note.noteType !== 'r') {
264
+ for (let i = 0; i < pieces.length - 1; ++i) {
265
+ ties.push({ from: pieces[i].pos, to: pieces[i + 1].pos, fromNote: pieces[i].note, toNote: pieces[i + 1].note });
266
+ }
267
+ }
268
+ };
269
+ const addTuplet = (unit: LayoutUnit) => {
270
+ const m = current();
271
+ const base = m.notes.length;
272
+ const k = measures.length - 1;
273
+ const tree = SmoTupletTree.clone(unit.tuplet!);
274
+ shiftTuplet(tree.tuplet, base - tree.startIndex);
275
+ unit.notes.forEach((source, j) => {
276
+ push(SmoNote.clone(source.note), true);
277
+ const pos = { k, tick: base + j };
278
+ placements[source.key] = { first: pos, last: pos };
279
+ });
280
+ m.trees.push(tree);
281
+ };
282
+ // A tuplet longer than a measure cannot be kept: its notes are written out at the lengths they are written with
283
+ const addUnmadeTuplet = (unit: LayoutUnit) => {
284
+ unit.notes.forEach((source) => {
285
+ const length = source.note.stemTicks > 0 ? source.note.stemTicks : Math.round(source.note.tickCount);
286
+ const plain = SmoNote.cloneWithDuration(source.note, length);
287
+ plain.tupletId = null;
288
+ addNote({ note: plain, key: source.key });
289
+ });
290
+ };
291
+ units.forEach((unit) => {
292
+ if (unit.filler) {
293
+ addRests(unit.ticks);
294
+ return;
295
+ }
296
+ if (!unit.tuplet) {
297
+ addNote(unit.notes[0]);
298
+ return;
299
+ }
300
+ const spaceNow = space();
301
+ if (fits(unit.ticks, spaceNow)) {
302
+ addTuplet(unit);
303
+ return;
304
+ }
305
+ const m = current();
306
+ const k = measures.length - 1;
307
+ if (m.used > EPSILON && fits(unit.ticks, lengthOf(k + 1))) {
308
+ // starts the next measure; the rest of this one is rests
309
+ addRests(spaceNow);
310
+ addTuplet(unit);
311
+ } else {
312
+ addUnmadeTuplet(unit);
313
+ }
314
+ });
315
+ // the last measure is filled out with rests
316
+ if (measures.length > 0) {
317
+ const last = measures[measures.length - 1];
318
+ const left = lengthOf(measures.length - 1) - last.used;
319
+ if (left > EPSILON) {
320
+ addRests(left);
321
+ }
322
+ }
323
+ return { measures, placements, ties };
324
+ }
325
+
326
+ /** Move one end of a staff modifier to where its note went */
327
+ const remapSelector = (selector: SmoSelector, firstMeasure: number, lastMeasure: number,
328
+ placements: Record<string, Placement>, which: 'first' | 'last'): SmoSelector => {
329
+ if (selector.measure < firstMeasure || selector.measure > lastMeasure || typeof (selector.tick) !== 'number') {
330
+ return selector;
331
+ }
332
+ const placement = placements[SmoSelector.getNoteKey(selector)];
333
+ if (!placement) {
334
+ return selector;
335
+ }
336
+ const pos = placement[which];
337
+ return { staff: selector.staff, measure: firstMeasure + pos.k, voice: selector.voice, tick: pos.tick, pitches: selector.pitches };
338
+ }
339
+
340
+ /**
341
+ * Re-bar the music of a range of measures into a new time signature, in every staff. The notes keep their order
342
+ * and their lengths. Where the new measures are not long enough, measures are added after the range (in every
343
+ * staff) so that all of the music fits; measures are never removed. A note that crosses a new bar line is split and
344
+ * tied. A tuplet is kept whole, starting the next measure if it does not fit. Things attached to a note stay with
345
+ * it; if the note is split they stay with the first part. Slurs, ties, hairpins and other things between notes
346
+ * follow their notes. Hand-placed beaming in the range is reset to automatic.
347
+ * @param score the score to change
348
+ * @param firstMeasure the first measure of the range
349
+ * @param lastMeasure the last measure of the range
350
+ * @param timeSignature the new time signature
351
+ * @returns what was done. Nothing is changed, and `added` is 0, if the range is not in the score.
352
+ */
353
+ export const rebarMeasures = (score: SmoScore, firstMeasure: number, lastMeasure: number,
354
+ timeSignature: SmoTimeSignature): RebarResult => {
355
+ const nothing: RebarResult = { firstMeasure, measureCount: 0, added: 0 };
356
+ if (score.staves.length < 1 || firstMeasure < 0 || lastMeasure < firstMeasure) {
357
+ return nothing;
358
+ }
359
+ if (score.staves.some((staff) => staff.measures.length <= lastMeasure)) {
360
+ return nothing;
361
+ }
362
+ const existing = lastMeasure - firstMeasure + 1;
363
+ const startIndex = rebarStartIndex(score, firstMeasure, timeSignature);
364
+ const lengthOf = (k: number) => rebarMeasureTicks(timeSignature, k, startIndex);
365
+
366
+ // 1. Lay out every voice of every staff, and count the measures that are needed.
367
+ const layouts: VoiceLayout[][] = [];
368
+ let needed = 0;
369
+ score.staves.forEach((staff, staffIndex) => {
370
+ let voiceCount = 1;
371
+ for (let m = firstMeasure; m <= lastMeasure; ++m) {
372
+ voiceCount = Math.max(voiceCount, staff.measures[m].voices.length);
373
+ }
374
+ const clef = staff.measures[firstMeasure].clef;
375
+ const staffLayouts: VoiceLayout[] = [];
376
+ for (let v = 0; v < voiceCount; ++v) {
377
+ const layout = layoutVoice(flattenVoice(score, staffIndex, v, firstMeasure, lastMeasure), lengthOf, clef);
378
+ needed = Math.max(needed, layout.measures.length);
379
+ staffLayouts.push(layout);
380
+ }
381
+ layouts.push(staffLayouts);
382
+ });
383
+ const size = Math.max(existing, needed);
384
+ const added = size - existing;
385
+
386
+ // 2. Add the measures, after the range, copying the last measure of the range.
387
+ const oldEndBarline = score.staves.map((staff) => staff.measures[lastMeasure].getEndBarline());
388
+ for (let i = 0; i < added; ++i) {
389
+ score.addMeasure(lastMeasure + 1, lastMeasure);
390
+ }
391
+
392
+ // 3. Write the measures. The end barline (repeat, double bar) goes with the end of the range.
393
+ score.staves.forEach((staff, staffIndex) => {
394
+ for (let k = 0; k < size; ++k) {
395
+ const measure = staff.measures[firstMeasure + k];
396
+ measure.timeSignature = new SmoTimeSignature(timeSignature);
397
+ const voices: SmoVoice[] = [];
398
+ const trees: SmoTupletTree[] = [];
399
+ const hasSource: boolean[] = [];
400
+ layouts[staffIndex].forEach((layout) => {
401
+ const laid = layout.measures[k];
402
+ if (laid) {
403
+ voices.push({ notes: laid.notes });
404
+ laid.trees.forEach((tree) => trees.push(tree));
405
+ hasSource.push(laid.hasSource);
406
+ } else {
407
+ const notes: SmoNote[] = [];
408
+ SmoMusic.gcdMap(lengthOf(k)).forEach((duration) => notes.push(makeRest(duration, measure.clef)));
409
+ voices.push({ notes });
410
+ hasSource.push(false);
411
+ }
412
+ });
413
+ // A voice that only has rests added to fill is not kept, unless a later voice is
414
+ while (voices.length > 1 && !hasSource[voices.length - 1]) {
415
+ voices.pop();
416
+ hasSource.pop();
417
+ }
418
+ measure.voices = voices;
419
+ measure.tupletTrees = trees;
420
+ measure.beamGroups = [];
421
+ SmoTupletTree.syncTupletIds(trees, voices);
422
+ if (measure.getActiveVoice() >= voices.length) {
423
+ measure.setActiveVoice(0);
424
+ }
425
+ }
426
+ if (added > 0) {
427
+ const oldLast = staff.measures[lastMeasure];
428
+ const newLast = staff.measures[lastMeasure + added];
429
+ const barline = oldEndBarline[staffIndex];
430
+ if (barline.barline !== SmoBarline.barlines.singleBar) {
431
+ newLast.setBarline(new SmoBarline({ position: SmoBarline.positions.end, barline: barline.barline }));
432
+ oldLast.setBarline(new SmoBarline({ position: SmoBarline.positions.end, barline: SmoBarline.barlines.singleBar }));
433
+ }
434
+ }
435
+ });
436
+ // measure k has part (startIndex + k) of a time signature with several parts
437
+ score.updateCompoundTimeSignature();
438
+ score.staves.forEach((staff) => {
439
+ for (let k = 0; k < size; ++k) {
440
+ const measure = staff.measures[firstMeasure + k];
441
+ const triple = measure.timeSignature.actualBeats % 3 === 0;
442
+ const beamBeats = triple ? score.preferences.defaultTripleDuration : score.preferences.defaultDupleDuration;
443
+ measure.voices.forEach((voice) => {
444
+ voice.notes.forEach((note) => {
445
+ note.beamBeats = beamBeats;
446
+ note.beamState = SmoNote.beamStates.auto;
447
+ note.endBeam = false;
448
+ });
449
+ });
450
+ }
451
+ });
452
+
453
+ // 4. Staff modifiers (slurs, ties, hairpins...). addMeasure has already moved the ones that start after
454
+ // the range. The others are moved here: ends in the range go with their notes, ends after it move later.
455
+ score.staves.forEach((staff, staffIndex) => {
456
+ const placements: Record<string, Placement> = {};
457
+ layouts[staffIndex].forEach((layout) => {
458
+ Object.keys(layout.placements).forEach((key) => {
459
+ placements[key] = layout.placements[key];
460
+ });
461
+ });
462
+ const remap = (mod: StaffModifierBase) => {
463
+ if (mod.startSelector.measure > lastMeasure) {
464
+ return; // moved by addMeasure
465
+ }
466
+ const tie = mod.ctor === 'SmoTie';
467
+ const start = remapSelector(mod.startSelector, firstMeasure, lastMeasure, placements, tie ? 'last' : 'first');
468
+ let end = remapSelector(mod.endSelector, firstMeasure, lastMeasure, placements, tie ? 'first' : 'last');
469
+ if (end === mod.endSelector && end.measure > lastMeasure) {
470
+ end = JSON.parse(JSON.stringify(end));
471
+ end.measure += added;
472
+ }
473
+ mod.startSelector = start;
474
+ mod.endSelector = end;
475
+ };
476
+ staff.modifiers.forEach(remap);
477
+ staff.textBrackets.forEach(remap);
478
+ // the pieces of a split note are tied
479
+ layouts[staffIndex].forEach((layout, voice) => {
480
+ layout.ties.forEach((pending) => {
481
+ const params = SmoTie.defaults;
482
+ params.startSelector = { staff: staffIndex, measure: firstMeasure + pending.from.k, voice, tick: pending.from.tick, pitches: [] };
483
+ params.endSelector = { staff: staffIndex, measure: firstMeasure + pending.to.k, voice, tick: pending.to.tick, pitches: [] };
484
+ params.lines = SmoTie.createLines(pending.fromNote, pending.toNote);
485
+ staff.addStaffModifier(new SmoTie(params));
486
+ });
487
+ });
488
+ });
489
+ return { firstMeasure, measureCount: size, added };
490
+ }
@@ -509,6 +509,72 @@ export class SmoSelection {
509
509
  }
510
510
  return rv;
511
511
  }
512
+ /**
513
+ * Select the notes of one staff that sound between two notes, which may be in any staff. The notes are
514
+ * found by elapsed time within each measure, not by their index in the measure, so a staff with a
515
+ * different number of notes (or a different rhythm) than the staff of the selectors is selected correctly.
516
+ * A note is included if it sounds at any time from the start of the earlier note to the end of the later note.
517
+ * Measures are matched by index. The voice of the earlier selector is used, or the first voice if the
518
+ * measure has no such voice.
519
+ * @param score
520
+ * @param staffIndex the staff to select from
521
+ * @param s1 one end of the range
522
+ * @param s2 the other end of the range
523
+ * @returns the notes in the staff, in order. Empty if the selectors are not in the score.
524
+ */
525
+ static timeRangeSelections(score: SmoScore, staffIndex: number, s1: SmoSelector, s2: SmoSelector): SmoSelection[] {
526
+ const rv: SmoSelection[] = [];
527
+ const staff = score.staves[staffIndex];
528
+ if (!staff) {
529
+ return rv;
530
+ }
531
+ // ticks from the start of the measure to the start of the note, in its voice
532
+ const offsetOf = (selector: SmoSelector): number | null => {
533
+ const measure = score.staves[selector.staff]?.measures[selector.measure];
534
+ const voice = measure?.voices[selector.voice];
535
+ if (!voice || voice.notes.length <= selector.tick) {
536
+ return null;
537
+ }
538
+ let offset = 0;
539
+ for (let i = 0; i < selector.tick; ++i) {
540
+ offset += voice.notes[i].tickCount;
541
+ }
542
+ return offset;
543
+ };
544
+ const o1 = offsetOf(s1);
545
+ const o2 = offsetOf(s2);
546
+ if (o1 === null || o2 === null) {
547
+ return rv;
548
+ }
549
+ const lastNote = score.staves[s2.staff].measures[s2.measure].voices[s2.voice].notes[s2.tick];
550
+ const firstNote = score.staves[s1.staff].measures[s1.measure].voices[s1.voice].notes[s1.tick];
551
+ // order by measure, then time
552
+ const first = (s1.measure < s2.measure || (s1.measure === s2.measure && o1 <= o2)) ?
553
+ { measure: s1.measure, voice: s1.voice, start: o1 } : { measure: s2.measure, voice: s2.voice, start: o2 };
554
+ const last = (s1.measure < s2.measure || (s1.measure === s2.measure && o1 <= o2)) ?
555
+ { measure: s2.measure, end: o2 + lastNote.tickCount } : { measure: s1.measure, end: o1 + firstNote.tickCount };
556
+ for (let m = first.measure; m <= last.measure && m < staff.measures.length; ++m) {
557
+ const measure = staff.measures[m];
558
+ const voiceIx = first.voice < measure.voices.length ? first.voice : 0;
559
+ const notes = measure.voices[voiceIx].notes;
560
+ let offset = 0;
561
+ for (let t = 0; t < notes.length; ++t) {
562
+ const noteStart = offset;
563
+ const noteEnd = offset + notes[t].tickCount;
564
+ offset = noteEnd;
565
+ // Notes that end before the range starts, or start after it ends, are outside of it.
566
+ const beforeStart = m === first.measure && noteEnd <= first.start;
567
+ const afterEnd = m === last.measure && noteStart >= last.end;
568
+ if (!beforeStart && !afterEnd) {
569
+ const sel = SmoSelection.noteSelection(score, staffIndex, m, voiceIx, t);
570
+ if (sel) {
571
+ rv.push(sel);
572
+ }
573
+ }
574
+ }
575
+ }
576
+ return rv;
577
+ }
512
578
  static nextNoteSelectionFromSelector(score: SmoScore, selector: SmoSelector): SmoSelection | null {
513
579
  return SmoSelection.nextNoteSelection(score, selector.staff, selector.measure, selector.voice, selector.tick);
514
580
  }
@@ -15,16 +15,22 @@ interface Props {
15
15
  timeSignature: Ref<SmoTimeSignature>,
16
16
  updateTimeSignatureCb: (mf: SmoTimeSignature) => Promise<void>,
17
17
  updateApplyTo: (value: string) => Promise<void>,
18
+ updatePreserve: (value: boolean) => Promise<void>,
18
19
  commitCb: () => Promise<void>,
19
20
  cancelCb: () => Promise<void>
20
21
  }
21
22
  const props = defineProps<Props>();
22
23
  const { domId, label, commitCb, cancelCb, } = { ...props };
23
24
 
25
+ // None of the fields change the score. The dialog applies them all when OK is clicked.
24
26
  const timeSignature = props.timeSignature;
25
- watch(timeSignature, () => {
26
- console.log('changed!');
27
- })
27
+ const preserveMusic: Ref<boolean> = ref(true);
28
+ watch(preserveMusic, async (newValue: boolean, oldValue: boolean) => {
29
+ if (newValue === oldValue) {
30
+ return;
31
+ }
32
+ await props.updatePreserve(newValue);
33
+ });
28
34
  const isCompound: Ref<boolean> = ref(false);
29
35
  isCompound.value = timeSignature.value.times.length > 1;
30
36
  watch(isCompound, async (newValue, oldValue) => {
@@ -135,6 +141,10 @@ const getId = (str: string) => {
135
141
  <toggle :domId="getId('display-compound')" :label="'Compound Time Signature'" :initialValue="isCompound"
136
142
  :changeCb="(value: boolean) => { isCompound = value }" />
137
143
  </div>
144
+ <div class="tgl-row">
145
+ <toggle :domId="getId('preserve-music')" :label="'Preserve music'" :initialValue="preserveMusic"
146
+ :changeCb="(value: boolean) => { preserveMusic = value }" />
147
+ </div>
138
148
  </div>
139
149
  <div class="row justify-content-center">
140
150
  <div class="col col-2" v-for="(time, index) in timeSignature.times">
@@ -1,59 +1,47 @@
1
1
  // [Smoosic](https://github.com/AaronDavidNewman/Smoosic)
2
2
  // Copyright (c) Aaron David Newman 2021.
3
- import { SmoMeasure } from '../../smo/data/measure';
4
3
  import { SmoTimeSignature } from '../../smo/data/measureModifiers';
5
- import { SmoSelection } from '../../smo/xform/selections';
4
+ import { TimeSignatureApplyTo } from '../../smo/xform/rebar';
6
5
  import { SuiDialogParams, InstallDialog } from './dialog';
7
6
  import timeSignatureComp from '../components/dialogs/timeSignature.vue';
8
- import { SuiScoreViewOperations } from '../../render/sui/scoreViewOperations';
9
7
  import { replaceVueRoot, modalContainerId } from '../common';
10
- import { SuiComponentAdapter, SuiDialogAdapterBase } from './adapter';
11
8
  import { ref } from 'vue';
12
9
  declare var $: any;
10
+ /**
11
+ * The Time Signature dialog. Editing the fields, Apply To and Preserve music only collects choices: the score is
12
+ * not touched until OK is clicked, and then everything is applied together as one undo step. Cancel changes nothing.
13
+ * @category SuiDialog
14
+ */
13
15
  export const SuiTimeSignatureDialogVue = (parameters: SuiDialogParams) => {
14
16
  const rootId = replaceVueRoot(modalContainerId);
15
17
  const measure = parameters.view.tracker.selections[0].measure;
16
- const backup = new SmoTimeSignature(measure.timeSignature);
17
- let changed = false;
18
- let timeSignatureVal = new SmoTimeSignature(measure.timeSignature);
19
- let timeSignature = ref(timeSignatureVal);
20
- const updateTimeSignatureCb = async (mf: SmoTimeSignature):Promise<void> => {
21
- if (!SmoTimeSignature.equalIncludeAttributes(mf, timeSignature.value)) {
22
- changed = true;
23
- await parameters.view.setTimeSignature(mf);
24
- timeSignature.value.times = mf.times;
25
- timeSignature.value.display=mf.display;
26
- timeSignature.value.displayString = mf.displayString;
27
- timeSignature.value.useSymbol = mf.useSymbol;
28
- }
18
+ const timeSignature = ref(new SmoTimeSignature(measure.timeSignature));
19
+ let applies: TimeSignatureApplyTo = 'Selected';
20
+ let preserveMusic = true;
21
+ const updateTimeSignatureCb = async (mf: SmoTimeSignature): Promise<void> => {
22
+ timeSignature.value.times = mf.times;
23
+ timeSignature.value.display = mf.display;
24
+ timeSignature.value.displayString = mf.displayString;
25
+ timeSignature.value.useSymbol = mf.useSymbol;
29
26
  }
30
- let applies = 'Selected';
31
- const updateApplyTo = async (value: string) => {
32
- if (applies === value) {
33
- return;
34
- }
35
- applies = value;
36
- if (value === 'Score') {
37
- parameters.view.tracker.selections = SmoSelection.selectionsToEnd(parameters.view.score, parameters.view.tracker.selections[0].selector.staff, 0);
38
- } else if (applies === 'Remaining') {
39
- parameters.view.tracker.selections = SmoSelection.selectionsToEnd(parameters.view.score, parameters.view.tracker.selections[0].selector.staff, parameters.view.tracker.selections[0].selector.measure);
40
- } else {
41
- parameters.view.tracker.selections = parameters.view.tracker.selections;
42
- }
43
- await parameters.view.setTimeSignature(timeSignature.value);
27
+ const updateApplyTo = async (value: string): Promise<void> => {
28
+ applies = value as TimeSignatureApplyTo;
29
+ }
30
+ const updatePreserve = async (value: boolean): Promise<void> => {
31
+ preserveMusic = value;
44
32
  }
45
33
  const commitCb = async () => {
34
+ await parameters.view.setTimeSignature(new SmoTimeSignature(timeSignature.value), {
35
+ applyTo: applies,
36
+ preserveMusic
37
+ });
46
38
  }
47
39
  const cancelCb = async () => {
48
- if (!changed) {
49
- return;
50
- }
51
- await parameters.view.setTimeSignature(backup);
52
40
  }
53
-
54
- const appParams = { domId: rootId, timeSignature, label: "Time Signature",
55
- updateTimeSignatureCb, updateApplyTo };
56
-
41
+
42
+ const appParams = { domId: rootId, timeSignature, label: "Time Signature",
43
+ updateTimeSignatureCb, updateApplyTo, updatePreserve };
44
+
57
45
  InstallDialog({
58
46
  root: rootId,
59
47
  app: timeSignatureComp,