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,104 @@
1
+ # Tasks: Preserve Music When Changing Time Signature
2
+
3
+ **Input**: Design documents from `/specs/042-preserve-music-time-signature/`
4
+ **Prerequisites**: [plan.md](plan.md), [spec.md](spec.md), [research.md](research.md), [data-model.md](data-model.md), [contracts/rebar-api.md](contracts/rebar-api.md), [quickstart.md](quickstart.md)
5
+
6
+ **Tests**: Included. The constitution (Principle #2) requires regression tests for transformation logic, and the plan names `tests/rebarMeasures.ts`. The view and the Vue component are checked by `tsc`, the SFC compiler and the manual quickstart, not by headless tests.
7
+
8
+ **Format**: `- [ ] [ID] [P?] [Story] Description with file path`. `[P]` means a different file with no dependency on an unfinished task.
9
+
10
+ ## Phase 1: Setup
11
+
12
+ - [X] T001 Create the headless test harness `tests/rebarMeasures.ts` (same shape as `tests/measureFill.ts`: register the `*ModifierDynamicCtorInit` functions, a `check` helper, builders for a score of N measures of 4/4 with a given list of note lengths, one or two staves, optional second voice). Add `"test:rebar-measures": "ts-node -P tests/tsconfig.json tests/rebarMeasures.ts"` to `package.json` after `test:measure-fill`.
13
+
14
+ ## Phase 2: Foundational (blocks all stories)
15
+
16
+ - [X] T002 Add an optional `prototypeIndex?: number` argument to `SmoScore.addMeasure(measureIndex, prototypeIndex?)` and `SmoScore.getPrototypeMeasure(measureIndex, staffIndex, prototypeIndex?)` in `src/smo/data/score.ts`. When given, that measure is the prototype; without it nothing changes. Update `types/src/smo/data/score.d.ts`.
17
+ - [X] T003 Create `src/smo/xform/rebar.ts` with the shapes from the data model (`RebarResult`, layout unit, placement map) and the measure-length helper: for the k-th measure of a range, the ticks of the part at `(startIndex + k) mod times.length` of the new `SmoTimeSignature`, with `startIndex` taken from the measure before the range when it has an equal signature ([research.md](research.md) R4). No UI or renderer imports.
18
+
19
+ **Checkpoint**: the pieces the stories share exist; `npx tsc --noEmit -p .` is clean.
20
+
21
+ ## Phase 3: User Story 1 - Change the meter without losing notes (Priority: P1)
22
+
23
+ **Goal**: With Preserve music, the music of a range of measures is re-barred into the new meter, in order, adding measures as needed ([spec.md](spec.md) Story 1, FR-006 to FR-013, FR-017).
24
+
25
+ **Independent Test**: `npm run test:rebar-measures`, cases B1 to B16 and B19 to B21 and B23 pass; in particular two 4/4 measures of eight quarters become three 3/4 measures (B1).
26
+
27
+ ### Tests for User Story 1
28
+
29
+ - [X] T004 [US1] Write cases B1 to B6 in `tests/rebarMeasures.ts`: the spec's 4/4 to 3/4 example, 3/4 to 4/4, 4/4 to 6/8 and 5/8, a note and a dotted whole note crossing bar lines (tied pieces), rests crossing bar lines (no ties). Assert the pitch sequence with tied pieces joined, the measure count and the total ticks.
30
+ - [X] T005 [US1] Write cases B7 to B9 in `tests/rebarMeasures.ts`: a tuplet that fits, one that straddles the new bar line (rest fill, starts the next measure, all notes kept), one longer than the new measure (plain notes, all kept).
31
+ - [X] T006 [US1] Write cases B10 to B13 in `tests/rebarMeasures.ts`: two voices, two staves with different rhythms (same measure count in both), markings on a split note (first piece only), and slurs, ties and hairpins whose end selectors must point at the same notes afterwards.
32
+ - [X] T007 [US1] Write cases B14, B16, B19, B20, B21 and B23 in `tests/rebarMeasures.ts`: alternating 3/4+2/4, added measures copy the old last measure's settings, no measure removed when fewer are needed, serialize and reload, invalid range, and the copy buffer untouched.
33
+
34
+ ### Implementation for User Story 1
35
+
36
+ - [X] T008 [US1] In `src/smo/xform/rebar.ts`, implement the per-voice layout: flatten the voice of the range into units (a note, a rest, or a whole tuplet tree), then place them measure by measure by the rules in [research.md](research.md) R2 (split with `SmoMusic.gcdMap` and `SmoNote.cloneWithDuration`, pitches only on later pieces, tuplet whole or moved to the next measure, unmake when longer than a measure, rest fill at the end). The layout produces new voices, the new tuplet trees (indices adjusted with `SmoTupletTree`), the placement map, the list of ties to add, and the count of measures filled.
37
+ - [X] T009 [US1] In `src/smo/xform/rebar.ts`, implement `rebarMeasures(score, firstMeasure, lastMeasure, timeSignature)`: lay out every staff and voice, take `needed` as the maximum count, add `max(existing, needed) - existing` measures after `lastMeasure` with `score.addMeasure(lastMeasure + 1, lastMeasure)` (R3, R5), set a copy of the time signature on every measure of the range, write the new voices (rest-filling measures the layout does not reach and voices a measure lacks), call `score.updateCompoundTimeSignature()`, and return a `RebarResult`. An invalid range returns `added: 0` and changes nothing.
38
+ - [X] T010 [US1] In `src/smo/xform/rebar.ts`, remap the staff modifiers ([research.md](research.md) R6): before the measures are inserted, rewrite the start and end selectors of every modifier with an end in the range from the placement map (starts use `firstPiece`, ends `lastPiece`, a `SmoTie` start `lastPiece` and end `firstPiece`), then add the new ties for split notes with `SmoOperation.createTie`-style parameters, and move ends after the range later by `added`.
39
+ - [X] T011 [US1] Add `SmoOperation.rebarMeasures`, `SmoOperation.timeSignatureChanges` and `SmoOperation.timeSignatureKeepsLength` to `src/smo/xform/operations.ts` as described in [contracts/rebar-api.md](contracts/rebar-api.md). The first calls `rebarMeasures`; the others only read.
40
+ - [X] T012 [US1] Run `npm run test:rebar-measures` and fix `rebar.ts` until B1 to B16, B19 to B21 and B23 pass.
41
+
42
+ **Checkpoint**: the transform works and is tested without any UI.
43
+
44
+ ## Phase 4: User Story 2 - Change takes effect only on OK (Priority: P1)
45
+
46
+ **Goal**: The dialog changes nothing until OK, then applies everything as one undo step ([spec.md](spec.md) Story 2, FR-001 to FR-005).
47
+
48
+ **Independent Test**: Quickstart steps 2 to 5 and 11 to 13.
49
+
50
+ - [X] T013 [US2] In `src/render/sui/scoreViewOperations.ts`, add `TimeSignatureApplyTo` and `SetTimeSignatureOptions` and change `setTimeSignature(timeSignature, options?)`. With no options, keep the old behavior unchanged. With options: work out the range from `options.applyTo` and the tracker's selections (data model table), return with no change, undo step or redraw when `SmoOperation.timeSignatureChanges` is false, use the old path when `preserveMusic` is not true or `timeSignatureKeepsLength` is true, otherwise call `_undoScore('Set time signature')`, run `SmoOperation.rebarMeasures` on `this.score` and on `this.storeScore` with the same range, then `renderer.rerenderAll()` and `await renderer.updatePromise()`. Update `types/src/render/sui/scoreViewOperations.d.ts`.
51
+ - [X] T014 [US2] Rewrite `src/ui/dialogs/timeSignature.ts`: hold `timeSignature`, `applyTo` and `preserveMusic` as local state; `updateTimeSignatureCb`, `updateApplyTo` and a new `updatePreserve` only store values (no score change, no `tracker.selections` change, no backup); `commitCb` calls `parameters.view.setTimeSignature(timeSignature.value, { applyTo, preserveMusic })` once; `cancelCb` does nothing.
52
+ - [X] T015 [US2] In `src/ui/components/dialogs/timeSignature.vue`, add the **Preserve music** `toggle` (ticked at first, calling the new `updatePreserve` prop) and add the prop to `Props`; make sure no watcher calls anything that changes the score (they now only update the local signature), and remove the leftover `console.log('changed!')` watcher.
53
+ - [X] T016 [US2] Compile `timeSignature.vue` with `@vue/compiler-sfc` (a scratchpad script like the one used for `deleteSpecial.vue`): parse errors 0, template errors 0.
54
+
55
+ **Checkpoint**: the dialog is commit-on-OK with Preserve music wired through.
56
+
57
+ ## Phase 5: User Story 3 - Keep only what fits, as it is today (Priority: P2)
58
+
59
+ **Goal**: Unticking Preserve music gives exactly the old result ([spec.md](spec.md) Story 3, FR-014, FR-018, FR-019).
60
+
61
+ **Independent Test**: Quickstart step 6; `npm run test:rebar-measures` B17, B18, B22.
62
+
63
+ - [X] T017 [US3] Write cases B17, B18 and B22 in `tests/rebarMeasures.ts`: `timeSignatureKeepsLength` for 4/4 to 2/2, `timeSignatureChanges` false for an equal signature and true when only a display option differs, and a regression that `SmoOperation.setTimeSignature` 4/4 to 3/4 on two measures of quarters still keeps what fits (two measures, three quarters each).
64
+ - [X] T018 [US3] Confirm in `src/render/sui/scoreViewOperations.ts` (from T013) that the unticked path and the same-length path call the unchanged `SmoOperation.setTimeSignature` on both scores, with `_undoScore`, and add a one-line comment saying why. Run the new cases.
65
+
66
+ ## Phase 6: User Story 4 - Choose which measures change (Priority: P2)
67
+
68
+ **Goal**: Apply To (Selected, Remaining, Score) decides the range for both settings of Preserve music, and what follows the range is kept ([spec.md](spec.md) Story 4, FR-015, FR-016).
69
+
70
+ **Independent Test**: Quickstart step 8; B15.
71
+
72
+ - [X] T019 [US4] Write case B15 in `tests/rebarMeasures.ts`: a six-measure score re-barred over measures 2 to 3, over 2 to the end, and over the whole score. Measures outside the range keep their notes, signatures and settings; modifiers that start or end after the range move later by `added`.
73
+ - [X] T020 [US4] Make the range calculation a small exported pure function (placed in `src/smo/xform/rebar.ts`, not the view file, so the headless test can import it without the renderer) (`timeSignatureRange(applyTo, selections, measureCount)`) and add cases for it to `tests/rebarMeasures.ts` (Selected: lowest to highest selected measure; Remaining: lowest to the end; Score: whole score; non-contiguous selections span the lowest to the highest). Keep it free of DOM use so the test can import it.
74
+
75
+ ## Phase 7: Polish and cross-cutting
76
+
77
+ - [X] T021 [P] Export the new module: add `export * from '../smo/xform/rebar';` to `src/application/exports.ts` and the matching export line in `typedoc.ts` and `types/typedoc.d.ts`.
78
+ - [X] T022 [P] Hand-write `types/src/smo/xform/rebar.d.ts` and update `types/src/smo/xform/operations.d.ts` and `types/src/application/exports.d.ts` for the new members.
79
+ - [X] T023 [P] Add the release note to `changes.md` under a new `11-24-2026` heading: the dialog applies on OK, the Preserve music checkbox, what it does, the unticked behavior, and the library additions.
80
+ - [X] T024 Run `npx tsc --noEmit -p .` and fix errors. Run `npm run test:rebar-measures` and the suites that share code: `test:paste-special`, `test:voice-copy-paste`, `test:measure-fill`, `test:beam-groups`, `test:score-archive`, `test:time-signature-display`, `test:delete-special`, `test:time-range-select`.
81
+ - [ ] T025 Walk through [quickstart.md](quickstart.md) section 4 in the running application (manual; cannot be done headless) and record any finding.
82
+
83
+ ## Dependencies and order
84
+
85
+ - Phase 1 then Phase 2, then the stories.
86
+ - US1 (T004 to T012) needs T002 and T003. T004 to T007 can be written before T008 to T011, and T012 runs them.
87
+ - US2 needs US1's `SmoOperation` members (T011).
88
+ - US3 and US4 need T013. US3's tests (T017) can be written after T011.
89
+ - Polish T021 to T023 can run once the API is stable (after T011); T024 and T025 are last.
90
+ - Within `rebar.ts`: T003, then T008, then T009, then T010. They are in one file, so they are sequential.
91
+
92
+ ## Parallel opportunities
93
+
94
+ - T004, T005, T006 and T007 add separate groups of cases to one file; write them one after another, but they do not depend on the implementation.
95
+ - T021, T022 and T023 touch different files and can run together.
96
+
97
+ ## Implementation strategy
98
+
99
+ - **MVP**: Phases 1 to 3 (the transform and its tests) plus T013 with a hard-coded call. That already proves the hard part.
100
+ - Then Phase 4 for the user-visible dialog, then 5 and 6, then Polish. Stop and check `tsc` and the suite after each phase.
101
+
102
+ ## Format check
103
+
104
+ All 25 tasks begin with a checkbox and an ID, user-story phases carry `[US1]` to `[US4]`, setup, foundational and polish tasks carry none, and every task names a file.
@@ -217,6 +217,7 @@ export * from '../smo/mxml/xmlToSmo';
217
217
  export * from '../smo/xform/beamers';
218
218
  export * from '../smo/xform/copypaste';
219
219
  export * from '../smo/xform/operations';
220
+ export * from '../smo/xform/rebar';
220
221
  export * from '../smo/xform/selections';
221
222
  export * from '../smo/xform/tickDuration';
222
223
  export * from '../smo/xform/tickMap';
@@ -260,13 +260,13 @@ export class SuiRenderState implements SuiRendererBase {
260
260
  if (!this.renderer.viewportChanged) {
261
261
  this.preserveScroll();
262
262
  }
263
- this.render();
263
+ await this.render();
264
264
  }
265
265
  } else {
266
266
  this.idleLayoutTimer = Date.now();
267
267
  this.undoStatus = this.undoBuffer.opCount;
268
268
  if (this.replaceQ.length > 0) {
269
- this.render();
269
+ await this.render();
270
270
  }
271
271
  }
272
272
  if (this.debug.testThrow) {
@@ -295,7 +295,7 @@ export class SuiRenderState implements SuiRendererBase {
295
295
  }
296
296
  pollRedraw() {
297
297
  setTimeout(async () => {
298
- this.pollRedrawTask();
298
+ await this.pollRedrawTask();
299
299
  }, 1);
300
300
  }
301
301
 
@@ -461,7 +461,7 @@ export class SuiRenderState implements SuiRendererBase {
461
461
  if (this.renderer.backgroundRender) {
462
462
  return;
463
463
  }
464
- this.renderer.layout();
464
+ await this.renderer.layout();
465
465
  this.renderer.drawPageLines();
466
466
  this.setPassState(SuiRenderState.passStates.clean, 'rs: complete render');
467
467
  }
@@ -24,6 +24,7 @@ import {
24
24
  } from '../../smo/xform/operations';
25
25
  import { BatchSelectionOperation, AddPartParams, DeleteAttributeKind } from '../../smo/xform/operations';
26
26
  import { MeasureFillType } from '../../smo/xform/measureFill';
27
+ import { TimeSignatureApplyTo, timeSignatureRange } from '../../smo/xform/rebar';
27
28
  import { smoSerialize } from '../../common/serializationHelpers';
28
29
  import { FontInfo } from '../../common/vex';
29
30
  import { SmoMusic } from '../../smo/data/music';
@@ -45,9 +46,20 @@ declare var $: any;
45
46
  declare var SmoConfig: SmoRenderConfiguration;
46
47
 
47
48
 
49
+ /**
50
+ * How {@link SuiScoreViewOperations.setTimeSignature} chooses the measures and treats their music
51
+ * @category SuiRender
52
+ */
53
+ export interface SetTimeSignatureOptions {
54
+ /** which measures to change. Default is the selected measures */
55
+ applyTo?: TimeSignatureApplyTo,
56
+ /** re-bar the music into the new time signature, adding measures if needed. Otherwise the music that fits is kept. */
57
+ preserveMusic?: boolean
58
+ }
59
+
48
60
  /**
49
61
  * MVVM-like operations on the displayed score.
50
- *
62
+ *
51
63
  * All operations that can be performed on a 'live' score go through this
52
64
  * module. It maps the score view to the actual score and makes sure the
53
65
  * model and view stay in sync.
@@ -580,10 +592,18 @@ export class SuiScoreViewOperations extends SuiScoreView {
580
592
  await this.renderer.updatePromise();
581
593
  }
582
594
  /**
583
- * Set the time signature for a selection
595
+ * Set the time signature, in every staff. With no options, it is set on the selected measures and the music
596
+ * that fits in the new length is kept. With options, the measures are chosen by `applyTo`, and with
597
+ * `preserveMusic` the music of those measures is re-barred into the new time signature, adding measures if
598
+ * the new one holds less time, so that no music is lost. Nothing happens, and no undo step is made, if the
599
+ * measures already have this time signature. It is one undo step.
584
600
  * @param timeSignature actual time signature
601
+ * @param options which measures, and whether to preserve the music
585
602
  */
586
- async setTimeSignature(timeSignature: SmoTimeSignature): Promise<void> {
603
+ async setTimeSignature(timeSignature: SmoTimeSignature, options?: SetTimeSignatureOptions): Promise<void> {
604
+ if (options) {
605
+ return this._setTimeSignatureInRange(timeSignature, options);
606
+ }
587
607
  this._undoScore('Set time signature');
588
608
  const selections = this.tracker.selections;
589
609
  const altSelections = this._getEquivalentSelections(selections);
@@ -592,6 +612,41 @@ export class SuiScoreViewOperations extends SuiScoreView {
592
612
  this._renderChangedMeasures(SmoSelection.getMeasureList(this.tracker.selections));
593
613
  return this.renderer.updatePromise();
594
614
  }
615
+ private async _setTimeSignatureInRange(timeSignature: SmoTimeSignature, options: SetTimeSignatureOptions): Promise<void> {
616
+ const selected = this.tracker.selections.map((sel) => sel.selector.measure);
617
+ const range = timeSignatureRange(options.applyTo ?? 'Selected', selected, this.score.staves[0].measures.length);
618
+ if (!range) {
619
+ return;
620
+ }
621
+ const { firstMeasure, lastMeasure } = range;
622
+ if (!SmoOperation.timeSignatureChanges(this.score, firstMeasure, lastMeasure, timeSignature)) {
623
+ return;
624
+ }
625
+ const staffIndex = this.tracker.selections.length > 0 ? this.tracker.selections[0].selector.staff : 0;
626
+ this._undoScore('Set time signature');
627
+ if (options.preserveMusic === true && !SmoOperation.timeSignatureKeepsLength(this.score, firstMeasure, lastMeasure, timeSignature)) {
628
+ // The measure count can change, so redraw everything
629
+ SmoOperation.rebarMeasures(this.score, firstMeasure, lastMeasure, timeSignature);
630
+ SmoOperation.rebarMeasures(this.storeScore, firstMeasure, lastMeasure, timeSignature);
631
+ this.renderer.rerenderAll();
632
+ await this.renderer.updatePromise();
633
+ this.tracker.replaceSelection({ staff: staffIndex, measure: firstMeasure, voice: 0, tick: 0, pitches: [] }, true);
634
+ return;
635
+ }
636
+ // Keep what fits: the music is not moved, so only the changed measures are redrawn. This is also what
637
+ // happens if only a display option changed, or the new time signature is as long as the old.
638
+ const selections: SmoSelection[] = [];
639
+ for (let m = firstMeasure; m <= lastMeasure; ++m) {
640
+ const selection = SmoSelection.measureSelection(this.score, staffIndex, m);
641
+ if (selection) {
642
+ selections.push(selection);
643
+ }
644
+ }
645
+ SmoOperation.setTimeSignature(this.score, selections, timeSignature);
646
+ SmoOperation.setTimeSignature(this.storeScore, this._getEquivalentSelections(selections), timeSignature);
647
+ this._renderChangedMeasures(selections);
648
+ await this.renderer.updatePromise();
649
+ }
595
650
  /**
596
651
  * Move selected staff up or down in the score.
597
652
  * @param index direction to move
@@ -631,31 +631,26 @@ export class SuiTracker extends SuiMapper implements TrackerKeyHandler {
631
631
  const staffMin = Math.min(s1o.selector.staff, s2o.selector.staff);
632
632
  const staffMax = Math.max(s1o.selector.staff, s2o.selector.staff);
633
633
  this.selections = [];
634
+ let fallback: SmoSelection | null = null;
634
635
  for (let i = staffMin; i <= staffMax; ++i) {
635
- const s1 = JSON.parse(JSON.stringify(s1o.selector));
636
- s1.staff = i;
637
- const s2 = JSON.parse(JSON.stringify(s2o.selector));
638
- s2.staff = i;
639
- const s1s = SmoSelection.selectionFromSelector(this.score!, s1);
640
- const s2s = SmoSelection.selectionFromSelector(this.score!, s2);
641
- if (s1s && s2s) {
642
- const min = SmoSelector.gt(s1s.selector, s2s.selector) ? s2s : s1s;
643
- const max = SmoSelector.lt(min.selector, s2s.selector) ? s2s : s1s;
644
- const selections = SmoSelection.innerSelections(score, min.selector, max.selector);
645
- // Get the actual selections from our map, since the client bounding boxes are already computed
646
- selections.forEach((sel) => {
647
- const key = SmoSelector.getNoteKey(sel.selector);
648
- sel.measure.setActiveVoice(sel.selector.voice);
649
- // Skip measures that are not rendered because they are part of a multi-rest
650
- if (this.measureNoteMap && this.measureNoteMap[key]) {
651
- this.selections.push(this.measureNoteMap[key]);
652
- }
653
- });
654
-
655
- if (this.selections.length === 0) {
656
- this.selections = [min];
657
- }
636
+ // The staves can have different numbers of notes, so the range is found by elapsed time in each staff,
637
+ // not by the note index of the selected notes.
638
+ const selections = SmoSelection.timeRangeSelections(score, i, s1o.selector, s2o.selector);
639
+ if (fallback === null && selections.length > 0) {
640
+ fallback = selections[0];
658
641
  }
642
+ // Get the actual selections from our map, since the client bounding boxes are already computed
643
+ selections.forEach((sel) => {
644
+ const key = SmoSelector.getNoteKey(sel.selector);
645
+ sel.measure.setActiveVoice(sel.selector.voice);
646
+ // Skip measures that are not rendered because they are part of a multi-rest
647
+ if (this.measureNoteMap && this.measureNoteMap[key]) {
648
+ this.selections.push(this.measureNoteMap[key]);
649
+ }
650
+ });
651
+ }
652
+ if (this.selections.length === 0 && fallback) {
653
+ this.selections = [fallback];
659
654
  }
660
655
  this._createLocalModifiersList();
661
656
  this.highlightQueue.selectionCount = this.selections.length;
@@ -1173,13 +1173,18 @@ export class SmoScore {
1173
1173
  * @param staffIndex
1174
1174
  * @returns
1175
1175
  */
1176
- getPrototypeMeasure(measureIndex: number, staffIndex: number) {
1176
+ getPrototypeMeasure(measureIndex: number, staffIndex: number, prototypeIndex?: number) {
1177
1177
  const staff = this.staves[staffIndex];
1178
1178
  let protomeasure: SmoMeasureParams = {} as SmoMeasureParams;
1179
1179
 
1180
1180
  // Since this staff may already have instrument settings, use the
1181
1181
  // immediately preceeding or post-ceding measure if it exists.
1182
- if (measureIndex < staff.measures.length) {
1182
+ if (typeof (prototypeIndex) === 'number' && prototypeIndex >= 0 && prototypeIndex < staff.measures.length) {
1183
+ // the caller says which measure the new one should copy
1184
+ protomeasure = staff.measures[prototypeIndex];
1185
+ const instrument = staff.getStaffInstrument(prototypeIndex);
1186
+ protomeasure.lines = instrument.lines;
1187
+ } else if (measureIndex < staff.measures.length) {
1183
1188
  protomeasure = staff.measures[measureIndex];
1184
1189
  const instrument = staff.getStaffInstrument(measureIndex);
1185
1190
  protomeasure.lines = instrument.lines;
@@ -1196,13 +1201,15 @@ export class SmoScore {
1196
1201
  /**
1197
1202
  * Give a measure prototype, create a new measure and add it to each staff, with the
1198
1203
  * correct settings for current time signature/clef.
1199
- * @param measureIndex
1204
+ * @param measureIndex
1205
+ * @param prototypeIndex the measure the new one copies its settings from. By default, the measure
1206
+ * that is at measureIndex now (or the last measure, if there is none).
1200
1207
  */
1201
- addMeasure(measureIndex: number) {
1208
+ addMeasure(measureIndex: number, prototypeIndex?: number) {
1202
1209
  let i = 0;
1203
1210
  for (i = 0; i < this.staves.length; ++i) {
1204
1211
  const staff = this.staves[i];
1205
- const nmeasure = this.getPrototypeMeasure(measureIndex, i);
1212
+ const nmeasure = this.getPrototypeMeasure(measureIndex, i, prototypeIndex);
1206
1213
  if (nmeasure.voices.length <= nmeasure.getActiveVoice()) {
1207
1214
  nmeasure.setActiveVoice(0);
1208
1215
  }
@@ -23,6 +23,7 @@ import { SmoSelection, SmoSelector, ModifierTab } from './selections';
23
23
  import { SmoContractNoteActor, SmoStretchNoteActor, SmoMakeTupletActor, SmoUnmakeTupletActor, SmoStretchNoteParams, SmoContractNoteParams, SmoMakeTupletParams} from './tickDuration';
24
24
  import { SmoBeamer } from './beamers';
25
25
  import { fillRestDurations, MeasureFillType } from './measureFill';
26
+ import { rebarMeasures, RebarResult } from './rebar';
26
27
  import { SmoTupletTree } from '../data/tuplet';
27
28
  /**
28
29
  * supported operations for {@link SmoOperation.batchSelectionOperation} to change a note's duration
@@ -300,6 +301,54 @@ export class SmoOperation {
300
301
  score.staves[tabStaves[0].startSelector.staff].removeTabStaves(tabStaves);
301
302
  }
302
303
  }
304
+ /**
305
+ * Re-bar the music of measures firstMeasure to lastMeasure (all staves) into a new time signature, adding
306
+ * measures if the new one holds less time. See {@link rebarMeasures}. Unlike {@link setTimeSignature}, no
307
+ * music is lost.
308
+ * @param score the score to change
309
+ * @param firstMeasure the first measure of the range
310
+ * @param lastMeasure the last measure of the range
311
+ * @param timeSignature the new time signature
312
+ */
313
+ static rebarMeasures(score: SmoScore, firstMeasure: number, lastMeasure: number, timeSignature: SmoTimeSignature): RebarResult {
314
+ return rebarMeasures(score, firstMeasure, lastMeasure, timeSignature);
315
+ }
316
+ /**
317
+ * Would setting this time signature on measures firstMeasure to lastMeasure change anything? True if any
318
+ * of those measures, in any staff, has a time signature that is not equal to this one, display options included.
319
+ * Reads only.
320
+ */
321
+ static timeSignatureChanges(score: SmoScore, firstMeasure: number, lastMeasure: number, timeSignature: SmoTimeSignature): boolean {
322
+ return SmoOperation.rangeMeasures(score, firstMeasure, lastMeasure).some((measure) =>
323
+ !SmoTimeSignature.equalIncludeAttributes(measure.timeSignature, timeSignature));
324
+ }
325
+ /**
326
+ * Is every measure in the range, in every staff, already as long as the new time signature would make it?
327
+ * (2/2 for 4/4, or only a display option changed). If so the music does not need to move. The measure
328
+ * k places after the first has part k of a time signature that has several parts. Reads only.
329
+ */
330
+ static timeSignatureKeepsLength(score: SmoScore, firstMeasure: number, lastMeasure: number, timeSignature: SmoTimeSignature): boolean {
331
+ const measures = SmoOperation.rangeMeasures(score, firstMeasure, lastMeasure);
332
+ if (measures.length < 1) {
333
+ return true;
334
+ }
335
+ const perStaff = lastMeasure - firstMeasure + 1;
336
+ return measures.every((measure, ix) => {
337
+ const k = ix % perStaff;
338
+ const part = timeSignature.times[k % timeSignature.times.length];
339
+ const oldTicks = SmoMusic.timeSignatureToTicks(measure.timeSignature.actualBeats, measure.timeSignature.beatDuration);
340
+ return oldTicks === SmoMusic.timeSignatureToTicks(part.actualBeats, part.beatDuration);
341
+ });
342
+ }
343
+ private static rangeMeasures(score: SmoScore, firstMeasure: number, lastMeasure: number): SmoMeasure[] {
344
+ const rv: SmoMeasure[] = [];
345
+ score.staves.forEach((staff) => {
346
+ for (let m = Math.max(firstMeasure, 0); m <= lastMeasure && m < staff.measures.length; ++m) {
347
+ rv.push(staff.measures[m]);
348
+ }
349
+ });
350
+ return rv;
351
+ }
303
352
  static setTimeSignature(score: SmoScore, selections: SmoSelection[], timeSignature: SmoTimeSignature) {
304
353
  const selectors: SmoSelector[] = [];
305
354
  let i = 0;