smoosic 2.0.2 → 2.0.3

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 (126) hide show
  1. package/build/smoosic.js +167 -74
  2. package/package.json +82 -77
  3. package/release/smoosic.js +171 -78
  4. package/release/styles/menus.css +26 -0
  5. package/specs/022-text-reposition-on-resize/spec.md +1 -0
  6. package/specs/027-fix-bottom-modifier-lookup/checklists/requirements.md +38 -0
  7. package/specs/027-fix-bottom-modifier-lookup/contracts/division-lookup-contract.md +51 -0
  8. package/specs/027-fix-bottom-modifier-lookup/data-model.md +43 -0
  9. package/specs/027-fix-bottom-modifier-lookup/plan.md +77 -0
  10. package/specs/027-fix-bottom-modifier-lookup/quickstart.md +36 -0
  11. package/specs/027-fix-bottom-modifier-lookup/research.md +58 -0
  12. package/specs/027-fix-bottom-modifier-lookup/spec.md +105 -0
  13. package/specs/027-fix-bottom-modifier-lookup/tasks.md +167 -0
  14. package/specs/028-unsaved-changes-indicator/checklists/requirements.md +39 -0
  15. package/specs/028-unsaved-changes-indicator/contracts/score-change-contract.md +44 -0
  16. package/specs/028-unsaved-changes-indicator/data-model.md +64 -0
  17. package/specs/028-unsaved-changes-indicator/plan.md +96 -0
  18. package/specs/028-unsaved-changes-indicator/quickstart.md +54 -0
  19. package/specs/028-unsaved-changes-indicator/research.md +68 -0
  20. package/specs/028-unsaved-changes-indicator/spec.md +135 -0
  21. package/specs/028-unsaved-changes-indicator/tasks.md +173 -0
  22. package/specs/029-remove-promise-helpers/checklists/requirements.md +39 -0
  23. package/specs/029-remove-promise-helpers/contracts/public-api-contract.md +32 -0
  24. package/specs/029-remove-promise-helpers/data-model.md +45 -0
  25. package/specs/029-remove-promise-helpers/plan.md +86 -0
  26. package/specs/029-remove-promise-helpers/quickstart.md +53 -0
  27. package/specs/029-remove-promise-helpers/research.md +71 -0
  28. package/specs/029-remove-promise-helpers/spec.md +107 -0
  29. package/specs/029-remove-promise-helpers/tasks.md +164 -0
  30. package/specs/030-copy-paste-voices/checklists/requirements.md +39 -0
  31. package/specs/030-copy-paste-voices/contracts/voice-copy-paste-contract.md +47 -0
  32. package/specs/030-copy-paste-voices/data-model.md +63 -0
  33. package/specs/030-copy-paste-voices/plan.md +80 -0
  34. package/specs/030-copy-paste-voices/quickstart.md +50 -0
  35. package/specs/030-copy-paste-voices/research.md +80 -0
  36. package/specs/030-copy-paste-voices/spec.md +124 -0
  37. package/specs/030-copy-paste-voices/tasks.md +183 -0
  38. package/specs/031-select-voice/checklists/requirements.md +39 -0
  39. package/specs/031-select-voice/contracts/select-voice-contract.md +43 -0
  40. package/specs/031-select-voice/data-model.md +47 -0
  41. package/specs/031-select-voice/plan.md +79 -0
  42. package/specs/031-select-voice/quickstart.md +43 -0
  43. package/specs/031-select-voice/research.md +55 -0
  44. package/specs/031-select-voice/spec.md +113 -0
  45. package/specs/031-select-voice/tasks.md +171 -0
  46. package/src/application/application.ts +464 -459
  47. package/src/common/promiseHelpers.ts +2 -2
  48. package/src/render/audio/samples.ts +117 -118
  49. package/src/render/sui/pageDivisions.ts +58 -0
  50. package/src/render/sui/renderState.ts +469 -464
  51. package/src/render/sui/scoreChangeState.ts +62 -0
  52. package/src/render/sui/scoreView.ts +30 -0
  53. package/src/render/sui/scoreViewOperations.ts +2555 -2380
  54. package/src/render/sui/svgPageMap.ts +16 -17
  55. package/src/render/sui/textEdit.ts +310 -311
  56. package/src/render/sui/tracker.ts +40 -0
  57. package/src/render/vex/vxNote.ts +3 -1
  58. package/src/smo/xform/copypaste.ts +304 -4
  59. package/src/smo/xform/selections.ts +68 -0
  60. package/src/smo/xform/undo.ts +9 -0
  61. package/src/styles/menus.css +26 -0
  62. package/src/ui/buttons/ribbon.ts +3 -1
  63. package/src/ui/components/buttons/sidebar.vue +15 -6
  64. package/src/ui/components/dialogs/library.vue +3 -1
  65. package/src/ui/components/dialogs/unsavedChanges.vue +44 -0
  66. package/src/ui/dialogs/adapter.ts +181 -183
  67. package/src/ui/dialogs/addMeasure.ts +97 -97
  68. package/src/ui/dialogs/annotationVue.ts +56 -56
  69. package/src/ui/dialogs/audioSettings.ts +121 -123
  70. package/src/ui/dialogs/chordChangeVue.ts +46 -46
  71. package/src/ui/dialogs/clefChange.ts +53 -53
  72. package/src/ui/dialogs/customTuplets.ts +95 -96
  73. package/src/ui/dialogs/customTupletsVue.ts +47 -47
  74. package/src/ui/dialogs/dialog.ts +627 -620
  75. package/src/ui/dialogs/durations.ts +34 -34
  76. package/src/ui/dialogs/dynamics.ts +140 -142
  77. package/src/ui/dialogs/factory.ts +198 -198
  78. package/src/ui/dialogs/fileDialogs.ts +245 -179
  79. package/src/ui/dialogs/fonts.ts +93 -93
  80. package/src/ui/dialogs/globalLayout.ts +40 -40
  81. package/src/ui/dialogs/gracenote.ts +31 -31
  82. package/src/ui/dialogs/hairpin.ts +108 -110
  83. package/src/ui/dialogs/hairpinVue.ts +51 -51
  84. package/src/ui/dialogs/instrument.ts +111 -111
  85. package/src/ui/dialogs/keySignature.ts +175 -176
  86. package/src/ui/dialogs/keySignatureVue.ts +47 -47
  87. package/src/ui/dialogs/library.ts +207 -207
  88. package/src/ui/dialogs/libraryVue.ts +62 -48
  89. package/src/ui/dialogs/lyricVue.ts +46 -46
  90. package/src/ui/dialogs/measureFormat.ts +78 -78
  91. package/src/ui/dialogs/microtones.ts +147 -147
  92. package/src/ui/dialogs/noteHead.ts +319 -319
  93. package/src/ui/dialogs/pageLayout.ts +61 -61
  94. package/src/ui/dialogs/partInfo.ts +60 -60
  95. package/src/ui/dialogs/pedalMarking.ts +117 -117
  96. package/src/ui/dialogs/pedalMarkingVue.ts +73 -73
  97. package/src/ui/dialogs/pitch.ts +352 -352
  98. package/src/ui/dialogs/preferences.ts +40 -40
  99. package/src/ui/dialogs/rehearsalMark.ts +64 -64
  100. package/src/ui/dialogs/rehearsalMarkVue.ts +57 -57
  101. package/src/ui/dialogs/scoreId.ts +35 -36
  102. package/src/ui/dialogs/scoreView.ts +42 -42
  103. package/src/ui/dialogs/slur.ts +308 -310
  104. package/src/ui/dialogs/slurVue.ts +91 -91
  105. package/src/ui/dialogs/staffGroup.ts +112 -112
  106. package/src/ui/dialogs/tabNote.ts +84 -84
  107. package/src/ui/dialogs/tabStave.ts +182 -182
  108. package/src/ui/dialogs/tempo.ts +261 -263
  109. package/src/ui/dialogs/tempoVue.ts +73 -73
  110. package/src/ui/dialogs/textBlockVue.ts +127 -127
  111. package/src/ui/dialogs/textBracket.ts +114 -116
  112. package/src/ui/dialogs/textBracketVue.ts +56 -56
  113. package/src/ui/dialogs/tie.ts +140 -142
  114. package/src/ui/dialogs/timeSignature.ts +65 -66
  115. package/src/ui/dialogs/transposeScore.ts +39 -39
  116. package/src/ui/dialogs/unsavedChanges.ts +43 -0
  117. package/src/ui/dialogs/volta.ts +120 -122
  118. package/src/ui/dialogs/voltaVue.ts +51 -51
  119. package/src/ui/fileio/library.ts +110 -111
  120. package/src/ui/menus/edit.ts +100 -1
  121. package/src/ui/menus/file.ts +19 -3
  122. package/tests/pageDivisions.ts +156 -0
  123. package/tests/promiseHelpersUsage.ts +142 -0
  124. package/tests/scoreChangeState.ts +102 -0
  125. package/tests/selectVoice.ts +189 -0
  126. package/tests/voiceCopyPaste.ts +417 -0
@@ -1,2380 +1,2555 @@
1
- // [Smoosic](https://github.com/AaronDavidNewman/Smoosic)
2
- // Copyright (c) Aaron David Newman 2021.
3
- import { SuiScoreView, updateStaffModifierFunc } from './scoreView';
4
- import { SmoScore, engravingFontType } from '../../smo/data/score';
5
- import { SmoSystemStaffParams, SmoSystemStaff } from '../../smo/data/systemStaff';
6
- import { SmoPartInfo } from '../../smo/data/partInfo';
7
- import { SmoMeasure } from '../../smo/data/measure';
8
- import { SmoNote } from '../../smo/data/note';
9
- import { KeyEvent, SvgBox, Pitch, PitchLetter, RemoveElementLike, ElementLike } from '../../smo/data/common';
10
- import { SmoRenderConfiguration } from './configuration';
11
- import { SmoSystemGroup, SmoPageLayout, SmoGlobalLayout, SmoLayoutManager, SmoAudioPlayerSettings,
12
- SmoScorePreferences, SmoScoreInfo } from '../../smo/data/scoreModifiers';
13
- import { SmoTextGroup } from '../../smo/data/scoreText';
14
- import { SmoDynamicText, SmoNoteModifierBase, SmoGraceNote, SmoArticulation,
15
- SmoOrnament, SmoLyric, SmoMicrotone, SmoArpeggio, SmoArpeggioType, SmoClefChange,
16
- SmoTabNote} from '../../smo/data/noteModifiers';
17
- import { SmoTempo, SmoVolta, SmoBarline, SmoRepeatSymbol,
18
- SmoRehearsalMark, SmoMeasureFormat, SmoTimeSignature } from '../../smo/data/measureModifiers';
19
- import { UndoBuffer } from '../../smo/xform/undo';
20
- import {
21
- SmoOperation, createStaffModifierType, MakeTupletOperation
22
- } from '../../smo/xform/operations';
23
- import { BatchSelectionOperation } from '../../smo/xform/operations';
24
- import { smoSerialize } from '../../common/serializationHelpers';
25
- import { FontInfo } from '../../common/vex';
26
- import { SmoMusic } from '../../smo/data/music';
27
- import { SuiOscillator } from '../audio/oscillator';
28
- import { XmlToSmo } from '../../smo/mxml/xmlToSmo';
29
- import { SuiAudioPlayer } from '../audio/player';
30
- import { SuiXhrLoader } from '../../ui/fileio/xhrLoader';
31
- import { SmoSelection, SmoSelector } from '../../smo/xform/selections';
32
- import { StaffModifierBase,
33
- SmoInstrument, SmoInstrumentParams, SmoStaffTextBracket, SmoTabStave } from '../../smo/data/staffModifiers';
34
- import { SuiPiano } from './piano';
35
- import { SvgHelpers } from './svgHelpers';
36
- import { PromiseHelpers } from '../../common/promiseHelpers';
37
- import { parseJsonText } from 'typescript';
38
- import {NoteEntryCaret} from "./NoteEntryCaret";
39
- declare var $: any;
40
- declare var SmoConfig: SmoRenderConfiguration;
41
-
42
-
43
- /**
44
- * MVVM-like operations on the displayed score.
45
- *
46
- * All operations that can be performed on a 'live' score go through this
47
- * module. It maps the score view to the actual score and makes sure the
48
- * model and view stay in sync.
49
- *
50
- * Because this object operates on the current selections,
51
- * all operations return promise so applications can wait for the
52
- * operation to complete and update the selection list.
53
- * @category SuiRender
54
- */
55
- export class SuiScoreViewOperations extends SuiScoreView {
56
- constructor(config: SmoRenderConfiguration, score: SmoScore, undoBuffer: UndoBuffer) {
57
- super(config, score, undoBuffer);
58
- }
59
-
60
- /**
61
- * Add a new text group to the score
62
- * @param textGroup a new text group
63
- * @returns
64
- */
65
- async addTextGroup(textGroup: SmoTextGroup): Promise<void> {
66
- const altNew = SmoTextGroup.deserializePreserveId(textGroup.serialize());
67
- const isPartExposed = this.isPartExposed();
68
- let selector = textGroup.selector ?? SmoSelector.default;
69
- const partInfo = this.score.staves[0].partInfo;
70
- const bufType = isPartExposed && partInfo.preserveTextGroups
71
- ? UndoBuffer.bufferTypes.PART_MODIFIER : UndoBuffer.bufferTypes.SCORE_MODIFIER;
72
- if (bufType === UndoBuffer.bufferTypes.PART_MODIFIER) {
73
- selector.staff = this.staffMap[0];
74
- }
75
- this.storeUndo.addBuffer('remove text group', bufType,
76
- selector, textGroup, UndoBuffer.bufferSubtypes.ADD);
77
- if (isPartExposed && partInfo.preserveTextGroups) {
78
- this.score.staves[0].partInfo.updateTextGroup(textGroup, true);
79
- const partInfo = this.storeScore.staves[this._getEquivalentStaff(0)].partInfo;
80
- partInfo.updateTextGroup(altNew, true);
81
- } else {
82
- this.score.updateTextGroup(textGroup, true);
83
- this.storeScore.updateTextGroup(altNew, true);
84
- }
85
- await this.renderer.rerenderTextGroups();
86
- }
87
-
88
- /**
89
- * Remove the text group from the score
90
- * @param textGroup
91
- * @returns
92
- */
93
- async removeTextGroup(textGroup: SmoTextGroup): Promise<void> {
94
- let selector = textGroup.selector ?? SmoSelector.default;
95
- let altSelector = JSON.parse(JSON.stringify(selector));
96
- const partInfo = this.score.staves[0].partInfo;
97
- const isPartExposed = this.isPartExposed();
98
- const bufType = isPartExposed && partInfo.preserveTextGroups
99
- ? UndoBuffer.bufferTypes.PART_MODIFIER : UndoBuffer.bufferTypes.SCORE_MODIFIER;
100
- let ogText = this.storeScore.textGroups.find((tg) => tg.attrs.id === textGroup.attrs.id);
101
- if (isPartExposed && partInfo.preserveTextGroups) {
102
- ogText = partInfo.textGroups.find((tg) => tg.attrs.id === textGroup.attrs.id);
103
- }
104
- if (bufType === UndoBuffer.bufferTypes.PART_MODIFIER) {
105
- selector.staff = this.staffMap[0];
106
- } else {
107
- altSelector.staff = this.staffMap[selector.staff];
108
- }
109
- if (!ogText) {
110
- return;
111
- }
112
- // We undo buffer using the score location, not the group location
113
- this.storeUndo.addBuffer('remove text group', bufType,
114
- altSelector, ogText, UndoBuffer.bufferSubtypes.REMOVE);
115
- const altGroup = SmoTextGroup.deserializePreserveId(textGroup.serialize());
116
- if (altGroup.selector) {
117
- altGroup.selector.staff = altSelector.staff;
118
- }
119
- textGroup.elements.forEach((el: ElementLike) => RemoveElementLike(el));
120
- textGroup.elements = [];
121
- if (isPartExposed && partInfo.preserveTextGroups) {
122
- partInfo.updateTextGroup(textGroup, false);
123
- this.storeScore.staves[this._getEquivalentStaff(0)].partInfo.updateTextGroup(altGroup, false);
124
- } else {
125
- this.score.updateTextGroup(textGroup, false);
126
- this.storeScore.updateTextGroup(altGroup, false);
127
- }
128
- await this.renderer.rerenderTextGroups();
129
- }
130
-
131
- /**
132
- * UPdate an existing text group. The original is passed in, because since TG not tied to a musical
133
- * element, we need to find the one we're updating.
134
- * @param oldVersion
135
- * @param newVersion
136
- * @returns
137
- */
138
- async updateTextGroup(newVersion: SmoTextGroup): Promise<void> {
139
- const selector = newVersion.selector ?? SmoSelector.default; // for score view
140
- const altSelector = JSON.parse(JSON.stringify(selector)); // for full score
141
- const isPartExposed = this.isPartExposed();
142
- const partInfo = this.score.staves[0].partInfo;
143
-
144
- // If this text was attached to a staff that is not in the part, ignore the update
145
- if (newVersion.selector && newVersion.selector.staff >= this.score.staves.length) {
146
- return;
147
- }
148
- // Back up the original score text
149
- let ogtg = this.storeScore.textGroups.find((tg) => tg.attrs.id === newVersion.attrs.id);
150
- if (isPartExposed && partInfo.preserveTextGroups) {
151
- ogtg = partInfo.textGroups.find((tg) => tg.attrs.id === newVersion.attrs.id);
152
- }
153
- if (!ogtg) {
154
- // there is nothing to update, return.
155
- return;
156
- }
157
- if (ogtg) {
158
- const bufType = isPartExposed && partInfo.preserveTextGroups
159
- ? UndoBuffer.bufferTypes.PART_MODIFIER : UndoBuffer.bufferTypes.SCORE_MODIFIER;
160
- // if this is part text, make sure the undo buffer is associated with the part stave
161
- // in the full score, so undo works properly
162
- if (bufType === UndoBuffer.bufferTypes.PART_MODIFIER) {
163
- altSelector.staff = this.staffMap[0];
164
- } else {
165
- altSelector.staff = this.staffMap[selector.staff];
166
- }
167
- this.storeUndo.addBuffer('modify text',
168
- bufType, altSelector, ogtg, UndoBuffer.bufferSubtypes.UPDATE);
169
- }
170
- const altNew = SmoTextGroup.deserializePreserveId(newVersion.serialize());
171
- if (altNew.selector) {
172
- altNew.selector.staff = altSelector.staff;
173
- }
174
- this.score.updateTextGroup(newVersion, true);
175
- // If this is part text and part-specific text is set,
176
- // only set the partInfo for the stored score, but don't add to
177
- // global text.
178
- if (isPartExposed) {
179
- // Update the full score copy for this part
180
- const partInfo = this.storeScore.staves[altSelector.staff].partInfo;
181
- partInfo.updateTextGroup(altNew, true);
182
- const displayPartInfo = this.score.staves[0].partInfo;
183
- displayPartInfo.updateTextGroup(newVersion, true);
184
- } else {
185
- this.storeScore.updateTextGroup(altNew, true);
186
- }
187
- // TODO: only render the one TG.
188
- await this.renderer.rerenderTextGroups();
189
- // return this.renderer.updatePromise();
190
- }
191
- /**
192
- * load an mxml score remotely, return a promise that
193
- * completes when the file is loaded
194
- * @param url where to find the xml file
195
- * @returns
196
- */
197
- async loadRemoteXml(url: string): Promise<any> {
198
- const req = new SuiXhrLoader(url);
199
- const self = this;
200
- // Shouldn't we return promise of actually displaying the score?
201
- await req.loadAsync();
202
- const parser = new DOMParser();
203
- const xml = parser.parseFromString(req.value, 'text/xml');
204
- const score = XmlToSmo.convert(xml);
205
- score.layoutManager!.zoomToWidth($('body').width());
206
- await self.changeScore(score);
207
- }
208
- /**
209
- * load a remote score in SMO format
210
- * @param url url to find the score
211
- * @returns
212
- */
213
- async loadRemoteJson(url: string) : Promise<any> {
214
- const req = new SuiXhrLoader(url);
215
- await req.loadAsync();
216
- const score = SmoScore.deserialize(req.value);
217
- await this.changeScore(score);
218
- }
219
- /**
220
- * Load a remote score, return promise when it's been loaded
221
- * from afar.
222
- * @param pref
223
- * @returns
224
- */
225
- async loadRemoteScore(url: string): Promise<any> {
226
- if (url.endsWith('xml') || url.endsWith('mxl')) {
227
- return this.loadRemoteXml(url);
228
- } else {
229
- return this.loadRemoteJson(url);
230
- }
231
- }
232
- async updateAudioSettings(pref: SmoAudioPlayerSettings) {
233
- this._undoScorePreferences('Update preferences');
234
- this.score.audioSettings = pref;
235
- this.storeScore.audioSettings = new SmoAudioPlayerSettings(pref);
236
- // No rendering to be done
237
- return this.renderer.updatePromise();
238
- }
239
- /**
240
- * Global settings that control how the score editor behaves
241
- * @param pref
242
- * @returns
243
- */
244
- async updateScorePreferences(pref: SmoScorePreferences): Promise<void> {
245
- this._undoScorePreferences('Update preferences');
246
- const oldXpose = this.score.preferences.transposingScore;
247
- const curXpose = pref.transposingScore;
248
- const currentLayout = this.score.layoutManager?.getGlobalLayout();
249
- const oldDisplayMode = currentLayout ? currentLayout.displayMode : 'vertical';
250
- this.score.updateScorePreferences(new SmoScorePreferences(pref));
251
- this.storeScore.updateScorePreferences(new SmoScorePreferences(pref));
252
- const newLayout = this.score.layoutManager?.getGlobalLayout();
253
- const displayMode = newLayout ? newLayout.displayMode : 'vertical';
254
- if (oldDisplayMode !== displayMode) {
255
- this.renderer.setViewport();
256
- }
257
- if (curXpose === false && oldXpose === true) {
258
- this.score.setNonTransposing();
259
- this.storeScore.setNonTransposing();
260
- } else if (curXpose === true && oldXpose === false) {
261
- this.score.setTransposing();
262
- this.storeScore.setTransposing();
263
- }
264
- this.renderer.setDirty();
265
- return this.renderer.updatePromise();
266
- }
267
- /**
268
- * Update information about the score, composer etc.
269
- * @param scoreInfo
270
- * @returns
271
- */
272
- async updateScoreInfo(scoreInfo: SmoScoreInfo): Promise<void> {
273
- this._undoScorePreferences('Update preferences');
274
- this.score.scoreInfo = scoreInfo;
275
- this.storeScore.scoreInfo = JSON.parse(JSON.stringify(scoreInfo));
276
- return this.renderer.updatePromise()
277
- }
278
- async addRemoveArpeggio(code: SmoArpeggioType) {
279
- await this.modifyCurrentSelections('add/remove addRemoveArpeggio',
280
- (score, selections) => {
281
- selections.forEach((sel) => {
282
- if (sel.note) {
283
- if (code === 'none') {
284
- sel.note.arpeggio = undefined;
285
- } else {
286
- sel.note.arpeggio = new SmoArpeggio({ type: code });
287
- }
288
- }
289
- });
290
- });
291
- }
292
- /**
293
- * A clef change mid-measure (clefNote)
294
- * @param clef
295
- */
296
- async addRemoveClefChange(clef: SmoClefChange) {
297
- await this.modifyCurrentSelections('add/remove addRemoveClefChange',
298
- (score, selections) => {
299
- selections.forEach((sel) => {
300
- const measureClef = sel.measure.clef;
301
- if (sel.note) {
302
- if (measureClef === clef.clef) {
303
- sel.note.clefNote = null;
304
- } else {
305
- sel.note.clefNote = clef;
306
- }
307
- }
308
- });
309
- });
310
- // Make sure all the notes in the measure after the change are updated.
311
- // We only need to do this for the displayed score, not the storeScore.
312
- SmoSelection.getMeasureList(this.tracker.selections).forEach((ms) => {
313
- ms.measure.updateClefChangeNotes();
314
- })
315
- }
316
- /**
317
- * Modify the dynamics assoicated with the specific selection
318
- * @param selection
319
- * @param dynamic
320
- * @returns
321
- */
322
- async addDynamic(selection: SmoSelection, dynamic: SmoDynamicText): Promise<void> {
323
- await this.modifySelection('add dynamic', selection, (score, selections) => {
324
- SmoOperation.addDynamic(selections[0], dynamic);
325
- });
326
- }
327
-
328
- /**
329
- * Remove dynamics from the current selection
330
- * @param dynamic
331
- * @returns
332
- */
333
- async removeDynamic(dynamic: SmoDynamicText): Promise<void> {
334
- const measures = SmoSelection.getMeasureList(this.tracker.selections);
335
- for (let j = 0; j < this.tracker.selections.length; ++j) {
336
- const selection = this.tracker.selections[j];
337
- if (selection) {
338
- const equiv = this._getEquivalentSelection(selection);
339
- if (equiv?.note && selection.note) {
340
- const altModifiers = equiv.note.getModifiers('SmoDynamicText');
341
- SmoOperation.removeDynamic(selection, dynamic);
342
- if (altModifiers.length) {
343
- SmoOperation.removeDynamic(equiv, altModifiers[0] as SmoDynamicText);
344
- }
345
- }
346
- }
347
- }
348
- this._renderChangedMeasures(measures);
349
- await this.renderer.updatePromise()
350
- }
351
- /**
352
- * we never really delete a note, but we will convert it into a rest and if it's
353
- * already a rest we will try to hide it.
354
- * Operates on current selections
355
- * */
356
- async deleteNote(): Promise<void> {
357
- const measureSelections = this.undoTrackerMeasureSelections('delete note');
358
- this.tracker.selections.forEach((sel) => {
359
- if (sel.note) {
360
-
361
- const altSel = this._getEquivalentSelection(sel);
362
-
363
- // If this is a chord and a specific pitch is selected, just remove that pitch
364
- const pitchIndex = this.tracker.getPitchIndex();
365
- if (sel.note.pitches.length > 1 && pitchIndex >= 0 && pitchIndex < sel.note.pitches.length) {
366
- sel.note.pitches.splice(pitchIndex, 1);
367
- altSel!.note!.pitches.splice(pitchIndex, 1);
368
- SmoNote.sortPitches(sel.note);
369
- SmoNote.sortPitches(altSel!.note! as SmoNote);
370
- this.tracker.clearPitchIndex();
371
- return; // skip rest/hide logic for this selection
372
- }
373
-
374
- // set the pitch to be a good position for the rest
375
- const pitch = JSON.parse(JSON.stringify(
376
- SmoMeasure.defaultPitchForClef[sel.measure.clef]));
377
- const altPitch = JSON.parse(JSON.stringify(
378
- SmoMeasure.defaultPitchForClef[altSel!.measure.clef]));
379
- sel.note.pitches = [pitch];
380
- altSel!.note!.pitches = [altPitch];
381
-
382
- // If the note is a note, make it into a rest. If the note is a rest already,
383
- // make it invisible. If it is invisible already, make it back into a rest.
384
- if (sel.note.isRest() && !sel.note.isHidden()) {
385
- sel.note.makeHidden(true);
386
- altSel!.note!.makeHidden(true);
387
- } else {
388
- sel.note.clearArticulations();
389
- sel.note.makeRest();
390
- altSel!.note!.makeRest();
391
- altSel!.note!.clearArticulations();
392
- sel.note.makeHidden(false);
393
- altSel!.note!.makeHidden(false);
394
- }
395
- }
396
- });
397
- this._renderChangedMeasures(measureSelections);
398
- await this.renderer.updatePromise()
399
- }
400
- /**
401
- * The lyric editor moves around, so we can't depend on the tracker for the
402
- * correct selection. We get it directly from the editor.
403
- *
404
- * @param selector - the selector of the note with the lyric to remove
405
- * @param lyric - a copy of the lyric to remove. We use the verse, parser to identify it
406
- * @returns render promise
407
- */
408
- async removeLyric(selector: SmoSelector, lyric: SmoLyric): Promise<void> {
409
- const selection = SmoSelection.noteFromSelector(this.score, selector);
410
- if (selection === null) {
411
- return PromiseHelpers.emptyPromise();
412
- }
413
- this._undoSelection('remove lyric', selection);
414
- selection.note!.removeLyric(lyric);
415
- const equiv = this._getEquivalentSelection(selection);
416
- const storeLyric = equiv!.note!.getLyricForVerse(lyric.verse, lyric.parser);
417
- if (typeof (storeLyric) !== 'undefined') {
418
- equiv!.note!.removeLyric(lyric);
419
- }
420
- this.renderer.addToReplaceQueue(selection);
421
- lyric.deleted = true;
422
- await this.renderer.updatePromise();
423
- }
424
-
425
- /**
426
- * @param selector where to add or update the lyric
427
- * @param lyric a copy of the lyric to remove
428
- * @returns
429
- */
430
- async addOrUpdateLyric(selector: SmoSelector, lyric: SmoLyric): Promise<void> {
431
- const selection = SmoSelection.noteFromSelector(this.score, selector);
432
- if (selection === null) {
433
- return;
434
- }
435
- this._undoSelection('update lyric', selection);
436
- selection.note!.addLyric(lyric);
437
- const equiv = this._getEquivalentSelection(selection);
438
- const altLyric = SmoNoteModifierBase.deserialize(lyric.serialize() as any) as SmoLyric;
439
- equiv!.note!.addLyric(altLyric);
440
- this.renderer.addToReplaceQueue(selection);
441
- await this.renderer.updatePromise();
442
- }
443
-
444
- /**
445
- * @param selector the selector of the note with the annotation to remove
446
- * @param annotation a copy of the annotation to remove. We use the verse, parser to identify it
447
- * @returns render promise
448
- */
449
- async removeAnnotation(selector: SmoSelector, annotation: SmoLyric): Promise<void> {
450
- const selection = SmoSelection.noteFromSelector(this.score, selector);
451
- if (selection === null) {
452
- return PromiseHelpers.emptyPromise();
453
- }
454
- this._undoSelection('remove annotation', selection);
455
- selection.note!.removeAnnotations(annotation);
456
- const equiv = this._getEquivalentSelection(selection);
457
- const storeAnnotation = equiv!.note!.getLyricForVerse(annotation.verse, annotation.parser);
458
- if (typeof (storeAnnotation) !== 'undefined') {
459
- equiv!.note!.removeAnnotations(annotation);
460
- }
461
- this.renderer.addToReplaceQueue(selection);
462
- annotation.deleted = true;
463
- await this.renderer.updatePromise();
464
- }
465
-
466
- /**
467
- * @param selector where to add or update the annotation
468
- * @param annotation a copy of the annotation to add/update
469
- * @returns
470
- */
471
- async addOrUpdateAnnotation(selector: SmoSelector, annotation: SmoLyric): Promise<void> {
472
- const selection = SmoSelection.noteFromSelector(this.score, selector);
473
- if (selection === null) {
474
- return;
475
- }
476
- this._undoSelection('update annotation', selection);
477
- selection.note!.addAnnotation(annotation);
478
- const equiv = this._getEquivalentSelection(selection);
479
- const altAnnotation = SmoNoteModifierBase.deserialize(annotation.serialize() as any) as SmoLyric;
480
- equiv!.note!.addAnnotation(altAnnotation);
481
- this.renderer.addToReplaceQueue(selection);
482
- await this.renderer.updatePromise();
483
- }
484
-
485
- /**
486
- * Delete all the notes for the currently selected voice
487
- * @returns
488
- */
489
- async depopulateVoice(): Promise<void> {
490
- const measureSelections = this.undoTrackerMeasureSelections('depopulate voice');
491
- measureSelections.forEach((selection) => {
492
- const ix = selection.measure.getActiveVoice();
493
- if (ix !== 0) {
494
- SmoOperation.depopulateVoice(selection, ix);
495
- const equiv = this._getEquivalentSelection(selection);
496
- SmoOperation.depopulateVoice(equiv!, ix);
497
- }
498
- });
499
- SmoOperation.setActiveVoice(this.score, 0);
500
- this._renderChangedMeasures(measureSelections);
501
- await this.renderer.updatePromise();
502
- }
503
- /**
504
- * Change the active voice in a multi-voice measure.
505
- * @param index
506
- * @returns
507
- */
508
- _changeActiveVoice(index: number): SmoSelection[] {
509
- const measuresToAdd: SmoSelection[] = [];
510
- const measureSelections = SmoSelection.getMeasureList(this.tracker.selections);
511
- measureSelections.forEach((measureSelection) => {
512
- if (index === measureSelection.measure.voices.length) {
513
- measuresToAdd.push(measureSelection);
514
- }
515
- });
516
- return measuresToAdd;
517
- }
518
- /**
519
- * Populate a new voice with default notes
520
- * @param index the voice to populate
521
- * @returns
522
- */
523
- async populateVoice(index: number): Promise<void> {
524
- const measuresToAdd = this._changeActiveVoice(index);
525
- if (measuresToAdd.length === 0) {
526
- SmoOperation.setActiveVoice(this.score, index);
527
- this.tracker.selectActiveVoice();
528
- return this.renderer.updatePromise();
529
- }
530
- measuresToAdd.forEach((selection) => {
531
- this._undoSelection('popualteVoice', selection);
532
- SmoOperation.populateVoice(selection, index);
533
- const equiv = this._getEquivalentSelection(selection);
534
- SmoOperation.populateVoice(equiv!, index);
535
- });
536
- SmoOperation.setActiveVoice(this.score, index);
537
- this._renderChangedMeasures(measuresToAdd);
538
- await this.renderer.updatePromise();
539
- this.tracker.selectActiveVoice();
540
- }
541
- async swapVoices(voice1: number, voice2: number): Promise<void> {
542
- const selections = this.tracker.getSelectedMeasures();
543
- const altSelections = this._getEquivalentSelections(selections);
544
- SmoOperation.swapVoice(selections, voice1, voice2);
545
- SmoOperation.swapVoice(altSelections, voice1, voice2);
546
- this._renderChangedMeasures(selections);
547
- }
548
- /**
549
- * Assign an instrument to a set of measures
550
- * @param instrument the instrument to assign to the selections
551
- * @param selections
552
- * @returns
553
- */
554
- async changeInstrument(instrument: SmoInstrument, selections: SmoSelection[]): Promise<void> {
555
- if (typeof (selections) === 'undefined') {
556
- selections = this.tracker.selections;
557
- }
558
- this._undoSelections('change instrument', selections);
559
- const altSelections = this._getEquivalentSelections(selections);
560
- SmoOperation.changeInstrument(instrument, this.score, selections);
561
- SmoOperation.changeInstrument(instrument, this.storeScore, altSelections);
562
- this._renderChangedMeasures(selections);
563
- await this.renderer.updatePromise();
564
- }
565
- /**
566
- * Set the time signature for a selection
567
- * @param timeSignature actual time signature
568
- */
569
- async setTimeSignature(timeSignature: SmoTimeSignature): Promise<void> {
570
- this._undoScore('Set time signature');
571
- const selections = this.tracker.selections;
572
- const altSelections = this._getEquivalentSelections(selections);
573
- SmoOperation.setTimeSignature(this.score, selections, timeSignature);
574
- SmoOperation.setTimeSignature(this.storeScore, altSelections, timeSignature);
575
- this._renderChangedMeasures(SmoSelection.getMeasureList(this.tracker.selections));
576
- return this.renderer.updatePromise();
577
- }
578
- /**
579
- * Move selected staff up or down in the score.
580
- * @param index direction to move
581
- * @returns
582
- */
583
- async moveStaffUpDown(index: number): Promise<void> {
584
- this._undoScore('re-order staves');
585
- // Get staff to move
586
- const selection = this._getEquivalentSelection(this.tracker.selections[0]);
587
- // Make the move in the model, and reset the view so we can see the new
588
- // arrangement
589
- SmoOperation.moveStaffUpDown(this.storeScore, selection!, index);
590
- this.viewAll();
591
- await this.renderer.updatePromise();
592
- }
593
- /**
594
- * Update the staff group for a score, which determines how the staves
595
- * are justified and bracketed
596
- * @param staffGroup
597
- */
598
- async addOrUpdateStaffGroup(staffGroup: SmoSystemGroup): Promise<void> {
599
- this._undoScore('group staves');
600
- // Assume that the view is now set to full score
601
- this.score.addOrReplaceSystemGroup(staffGroup);
602
- this.storeScore.addOrReplaceSystemGroup(staffGroup);
603
- this.renderer.setDirty();
604
- await this.renderer.updatePromise();
605
- }
606
- async removeStaffGroup(staffGroup: SmoSystemGroup):Promise<void> {
607
- this._undoScore('ungroup staves');
608
- this.score.removeSystemGroup(staffGroup);
609
- this.storeScore.removeSystemGroup(staffGroup);
610
- this.renderer.setDirty();
611
- await this.renderer.updatePromise();
612
- }
613
- async clearSystemGroups(): Promise<void>{
614
- this._undoScore('clear staff groups');
615
- this.score.clearSystemGroups();
616
- this.storeScore.clearSystemGroups();
617
- this.renderer.setDirty();
618
- await this.renderer.updatePromise();
619
- }
620
- async updateTabStave(tabStave: SmoTabStave) {
621
- const selections = SmoSelection.getMeasuresBetween(this.score, tabStave.startSelector, tabStave.endSelector);
622
- const altSelections = this._getEquivalentSelections(selections);
623
- if (selections.length === 0) {
624
- return;
625
- }
626
- this._undoSelections('updateTabStave', selections);
627
- const staff: number = selections[0].selector.staff;
628
- const altStaff = altSelections[0].selector.staff;
629
- const altTabStave = new SmoTabStave(tabStave.serialize());
630
- altTabStave.startSelector.staff = altStaff;
631
- altTabStave.endSelector.staff = altStaff;
632
- altTabStave.attrs.id = tabStave.attrs.id;
633
- this.score.staves[staff].updateTabStave(tabStave);
634
- this.storeScore.staves[altStaff].updateTabStave(altTabStave);
635
- this._renderChangedMeasures(SmoSelection.getMeasureList(this.tracker.selections));
636
- await this.renderer.updatePromise();
637
- }
638
- async removeTabStave() {
639
- const selections = this.tracker.selections;
640
- const altSelections = this._getEquivalentSelections(selections);
641
- if (selections.length === 0) {
642
- return;
643
- }
644
- this._undoSelections('updateTabStave', selections);
645
- const stavesToRemove: SmoTabStave[] = [];
646
- const altStavesToRemove: SmoTabStave[] = [];
647
- const added: Record<string, SmoTabStave> = {};
648
- selections.forEach((sel, ix) => {
649
- const altSel = altSelections[ix];
650
- const tabStave = sel.staff.getTabStaveForMeasure(sel.selector);
651
- const altTabStave = altSel.staff.getTabStaveForMeasure(altSel.selector);
652
- if (tabStave && altTabStave) {
653
- if (!added[tabStave.attrs.id]) {
654
- added[tabStave.attrs.id] = tabStave;
655
- stavesToRemove.push(tabStave);
656
- altStavesToRemove.push(altTabStave);
657
- }
658
- }
659
- });
660
- selections[0].staff.removeTabStaves(stavesToRemove);
661
- altSelections[0].staff.removeTabStaves(altStavesToRemove);
662
- this._renderChangedMeasures(SmoSelection.getMeasureList(this.tracker.selections));
663
- await this.renderer.updatePromise();
664
- }
665
- /**
666
- * Update tempo for all or part of the score
667
- * @param measure the measure with the tempo. Tempo is measure-wide parameter
668
- * @param scoreMode if true, update whole score. Else selections
669
- * @returns
670
- */
671
- async updateTempoScore(measure: SmoMeasure, tempo: SmoTempo, scoreMode: boolean, selectionMode: boolean): Promise<void> {
672
- let measureIndex = 0;
673
- const originalTempo = new SmoTempo(measure.tempo);
674
- this._undoColumn('update tempo', measure.measureNumber.measureIndex);
675
- let startMeasure = measure.measureNumber.measureIndex;
676
- let endMeasure = this.score.staves[0].measures.length;
677
- let displayed = false;
678
- if (selectionMode) {
679
- const endSel = this.tracker.getExtremeSelection(1);
680
- if (endSel.selector.measure > startMeasure) {
681
- endMeasure = endSel.selector.measure;
682
- }
683
- }
684
- // If we are only changing the position of the text, it only affects the tempo measure.
685
- if (SmoTempo.eq(originalTempo, tempo) && tempo.yOffset !== originalTempo.yOffset && endMeasure > startMeasure) {
686
- endMeasure = startMeasure + 1;
687
- }
688
- for (measureIndex = startMeasure; measureIndex < endMeasure; ++measureIndex) {
689
- if (!scoreMode && !selectionMode) {
690
- // If not whole score or selections, change until the tempo doesn't match previous measure's tempo (next tempo change)
691
- const compMeasure = this.score.staves[0].measures[measureIndex];
692
- if (SmoTempo.eq(originalTempo, compMeasure.tempo) || displayed === false) {
693
- const sel = SmoSelection.measureSelection(this.score, 0, measureIndex);
694
- const altSel = SmoSelection.measureSelection(this.storeScore, 0, measureIndex);
695
- if (sel && sel.measure.tempo.display && !displayed) {
696
- this.renderer.addToReplaceQueue(sel);
697
- displayed = true;
698
- }
699
- if (sel) {
700
- SmoOperation.addTempo(this.score, sel, tempo);
701
- }
702
- if (altSel) {
703
- SmoOperation.addTempo(this.storeScore, altSel, tempo);
704
- }
705
- } else {
706
- break;
707
- }
708
- } else {
709
- const sel = SmoSelection.measureSelection(this.score, 0, measureIndex);
710
- const altSel = SmoSelection.measureSelection(this.storeScore, 0, measureIndex);
711
- if (sel) {
712
- SmoOperation.addTempo(this.score, sel, tempo);
713
- if (!displayed) {
714
- this.renderer.addToReplaceQueue(sel);
715
- displayed = true;
716
- }
717
- }
718
- if (altSel) {
719
- SmoOperation.addTempo(this.storeScore, altSel, tempo);
720
- }
721
- }
722
- }
723
- await this.renderer.updatePromise();
724
- }
725
- async updateTabNote(tabNote: SmoTabNote) {
726
- const selections = SmoSelection.getMeasuresBetween(this.score,
727
- this.tracker.getExtremeSelection(-1).selector, this.tracker.getExtremeSelection(1).selector);
728
- const altSelections = this._getEquivalentSelections(selections);
729
- this._undoSelections('updateTabNote', selections);
730
- SmoOperation.updateTabNote(selections, tabNote);
731
- SmoOperation.updateTabNote(altSelections, tabNote);
732
- this.renderer.addToReplaceQueue(selections);
733
- await this.renderer.updatePromise();
734
- }
735
- async removeTabNote() {
736
- const selections = SmoSelection.getMeasuresBetween(this.score,
737
- this.tracker.getExtremeSelection(-1).selector, this.tracker.getExtremeSelection(1).selector);
738
- const altSelections = this._getEquivalentSelections(selections);
739
- this._undoSelections('updateTabNote', selections);
740
- SmoOperation.removeTabNote(selections);
741
- SmoOperation.removeTabNote(altSelections);
742
- this.renderer.addToReplaceQueue(selections);
743
- await this.renderer.updatePromise();
744
- }
745
- /**
746
- * 'remove' tempo, which means either setting the bars to the
747
- * default tempo, or the previously-set tempo.
748
- * @param scoreMode whether to reset entire score
749
- */
750
- async removeTempo(measure: SmoMeasure, tempo: SmoTempo, scoreMode: boolean, selectionMode: boolean): Promise<void> {
751
- const startSelection = this.tracker.selections[0];
752
- if (startSelection.selector.measure > 0) {
753
- const measureIx = startSelection.selector.measure - 1;
754
- const target = startSelection.staff.measures[measureIx];
755
- const tempo = target.getTempo();
756
- const newTempo = new SmoTempo(tempo);
757
- newTempo.display = false;
758
- this.updateTempoScore(measure, newTempo, scoreMode, selectionMode);
759
- } else {
760
- this.updateTempoScore(measure, new SmoTempo(SmoTempo.defaults), scoreMode, selectionMode);
761
- }
762
- await this.renderer.updatePromise();
763
- }
764
- /**
765
- * Add a grace note to the selected real notes.
766
- */
767
- async addGraceNote(): Promise<void> {
768
- const selections = this.tracker.selections;
769
- const measureSelections = this.undoTrackerMeasureSelections('add grace note');
770
- selections.forEach((selection) => {
771
- const index = selection.note!.getGraceNotes().length;
772
- const pitches = JSON.parse(JSON.stringify(selection.note!.pitches));
773
- const grace = new SmoGraceNote({
774
- pitches, ticks:
775
- { numerator: 2048, denominator: 1, remainder: 0 }
776
- });
777
- SmoOperation.addGraceNote(selection, grace, index);
778
-
779
- const altPitches = JSON.parse(JSON.stringify(selection.note!.pitches));
780
- const altGrace = new SmoGraceNote({
781
- pitches: altPitches, ticks:
782
- { numerator: 2048, denominator: 1, remainder: 0 }
783
- });
784
- altGrace.attrs.id = grace.attrs.id;
785
- const altSelection = this._getEquivalentSelection(selection);
786
- SmoOperation.addGraceNote(altSelection!, altGrace, index);
787
- });
788
- this._renderChangedMeasures(measureSelections);
789
- await this.renderer.updatePromise();
790
- }
791
-
792
- /**
793
- * remove selected grace note
794
- * @returns
795
- */
796
- async removeGraceNote(): Promise<void> {
797
- const selections = this.tracker.selections;
798
- const measureSelections = this.undoTrackerMeasureSelections('remove grace note');
799
- selections.forEach((selection) => {
800
- // TODO: get the correct offset
801
- SmoOperation.removeGraceNote(selection, 0);
802
- const altSel = (this._getEquivalentSelection(selection));
803
- SmoOperation.removeGraceNote(altSel!, 0);
804
- });
805
- this._renderChangedMeasures(measureSelections);
806
- await this.renderer.updatePromise();
807
- }
808
- /**
809
- * Toggle slash in stem of grace note
810
- */
811
- async slashGraceNotes(): Promise<void> {
812
- const grace = this.tracker.getSelectedGraceNotes();
813
- const measureSelections = this.undoTrackerMeasureSelections('slash grace note toggle');
814
- grace.forEach((gn) => {
815
- SmoOperation.slashGraceNotes(gn);
816
- if (gn.selection !== null) {
817
- const altSelection = this._getEquivalentSelection(gn.selection);
818
- const altGn = this._getEquivalentGraceNote(altSelection!, gn.modifier as SmoGraceNote);
819
- SmoOperation.slashGraceNotes({
820
- selection: altSelection, modifier: altGn as any,
821
- box: SvgBox.default, index: 0
822
- });
823
- }
824
- });
825
- this._renderChangedMeasures(measureSelections);
826
- await this.renderer.updatePromise();
827
- }
828
- async transposeScore(offset: number): Promise<void> {
829
- this._undoScore('transpose score');
830
- SmoOperation.transposeScore(this.score, offset);
831
- SmoOperation.transposeScore(this.storeScore, offset);
832
- this.renderer.rerenderAll();
833
- await this.renderer.updatePromise();
834
- }
835
- /**
836
- * transpose selected notes
837
- * @param offset 1/2 steps
838
- * @returns
839
- */
840
- async transposeSelections(offset: number): Promise<void> {
841
- const selections = this.tracker.selections;
842
- const measureSelections = this.undoTrackerMeasureSelections('transpose');
843
- const grace = this.tracker.getSelectedGraceNotes();
844
- if (grace.length) {
845
- grace.forEach((artifact) => {
846
- if (artifact.selection !== null && artifact.selection.note !== null) {
847
- const gn1 = artifact.modifier as SmoGraceNote;
848
- const index = artifact.selection.note.graceNotes.findIndex((x) => x.attrs.id === gn1.attrs.id);
849
- const altSelection = this._getEquivalentSelection(artifact.selection);
850
- if (altSelection && altSelection.note !== null) {
851
- const gn2 = altSelection.note.graceNotes[index];
852
- SmoOperation.transposeGraceNotes(altSelection!, [gn2], offset);
853
- }
854
- SmoOperation.transposeGraceNotes(artifact.selection, [gn1], offset);
855
- }
856
- });
857
-
858
- } else {
859
- let isPercussion = false;
860
- selections.forEach((selected) => {
861
- SmoOperation.transpose(selected, offset);
862
- if (selected.staff.getStaffInstrument(selected.selector.measure).isPercussion) {
863
- isPercussion = true;
864
- }
865
- const altSel = this._getEquivalentSelection(selected);
866
- SmoOperation.transpose(altSel!, offset);
867
- });
868
- // if this is percussion, set that property
869
- if (isPercussion) {
870
- this.score.setNoteInstrumentProperties();
871
- this.storeScore.setNoteInstrumentProperties()
872
- }
873
- if (selections.length === 1 && this.score.preferences.autoPlay) {
874
- SuiOscillator.playSelectionNow(selections[0], this.score, 1);
875
- }
876
- }
877
- this._renderChangedMeasures(measureSelections);
878
- await this.renderer.updatePromise();
879
- }
880
- /**
881
- * toggle the accidental spelling of the selected notes
882
- * @returns
883
- */
884
- async toggleEnharmonic(): Promise<void> {
885
- const selections = this.tracker.selections;
886
- const measureSelections = this.undoTrackerMeasureSelections('toggle enharmonic');
887
- const grace = this.tracker.getSelectedGraceNotes();
888
- if (grace.length) {
889
- grace.forEach((artifact) => {
890
- SmoOperation.toggleGraceNoteEnharmonic(artifact.selection!, [artifact.modifier as SmoGraceNote]);
891
- const altSelection = this._getEquivalentSelection(artifact.selection!);
892
- const altGr = this._getEquivalentGraceNote(altSelection!, artifact.modifier as SmoGraceNote);
893
- SmoOperation.toggleGraceNoteEnharmonic(altSelection!,
894
- [altGr]);
895
- });
896
- } else {
897
- selections.forEach((selected) => {
898
- if (typeof (selected.selector.pitches) === 'undefined') {
899
- selected.selector.pitches = [];
900
- }
901
- SmoOperation.toggleEnharmonic(selected);
902
- const altSel = this._getEquivalentSelection(selected);
903
- SmoOperation.toggleEnharmonic(altSel!);
904
- });
905
- }
906
- this._renderChangedMeasures(measureSelections);
907
- await this.renderer.updatePromise();
908
- }
909
-
910
- /**
911
- * Toggle cautionary/courtesy accidentals
912
- */
913
- async toggleCourtesyAccidentals(): Promise<void> {
914
- const selections = this.tracker.selections;
915
- const measureSelections = this.undoTrackerMeasureSelections('toggle courtesy accidental');
916
- const grace = this.tracker.getSelectedGraceNotes();
917
- if (grace.length) {
918
- grace.forEach((artifact) => {
919
- const gn1 = [artifact.modifier] as SmoGraceNote[];
920
- SmoOperation.toggleGraceNoteCourtesy(artifact.selection, gn1);
921
- const altSel = this._getEquivalentSelection(artifact.selection!);
922
- const gn2 = this._getEquivalentGraceNote(altSel!, gn1[0]);
923
- SmoOperation.toggleGraceNoteCourtesy(altSel!, [gn2]);
924
- });
925
- } else {
926
- selections.forEach((selection) => {
927
- SmoOperation.toggleCourtesyAccidental(selection);
928
- const altSel = this._getEquivalentSelection(selection);
929
- SmoOperation.toggleCourtesyAccidental(altSel!);
930
- });
931
- }
932
- this._renderChangedMeasures(measureSelections);
933
- await this.renderer.updatePromise();
934
- }
935
-
936
- /**
937
- * change the duration of notes for selected, creating more
938
- * or fewer notes.
939
- * After the change, reset the selection so it's as close as possible
940
- * to the original length
941
- * @param operation
942
- * @returns
943
- */
944
- async batchDurationOperation(operation: BatchSelectionOperation): Promise<void> {
945
- const selections = this.tracker.selections;
946
- const measureSelections = this.undoTrackerMeasureSelections('change duration');
947
- const grace = this.tracker.getSelectedGraceNotes();
948
- const graceMap: Record<string, BatchSelectionOperation> = {
949
- doubleDuration: 'doubleGraceNoteDuration',
950
- halveDuration: 'halveGraceNoteDuration'
951
- };
952
- if (grace.length && typeof (graceMap[operation]) !== 'undefined') {
953
- operation = graceMap[operation];
954
- grace.forEach((artifact) => {
955
- (SmoOperation as any)[operation](artifact.selection, artifact.modifier);
956
- const altSelection = this._getEquivalentSelection(artifact.selection!);
957
- const gn2 = this._getEquivalentGraceNote(altSelection!, artifact.modifier as SmoGraceNote);
958
- (SmoOperation as any)[operation](altSelection!, gn2);
959
- });
960
- } else {
961
- const altAr = this._getEquivalentSelections(selections);
962
- SmoOperation.batchSelectionOperation(this.score, selections, operation);
963
- SmoOperation.batchSelectionOperation(this.storeScore, altAr, operation);
964
- }
965
- this._renderChangedMeasures(measureSelections);
966
- await this.renderer.updatePromise();
967
- }
968
- /**
969
- * Toggle selected modifier on selected notes
970
- * @param modifier
971
- * @param ctor parent class constructor (e.g. SmoOrnament)
972
- * @returns
973
- */
974
- async toggleArticulation(modifier: string, ctor: string): Promise<void> {
975
- const measureSelections = this.undoTrackerMeasureSelections('toggle articulation');
976
- this.tracker.selections.forEach((sel) => {
977
- if (ctor === 'SmoArticulation') {
978
- const aa = new SmoArticulation({ articulation: modifier });
979
- const altAa = new SmoArticulation({ articulation: modifier });
980
- altAa.attrs.id = aa.attrs.id;
981
- if (sel.note) {
982
- sel.note.toggleArticulation(aa);
983
- }
984
- const altSelection = this._getEquivalentSelection(sel);
985
- if (altSelection && altSelection.note) {
986
- altSelection.note.toggleArticulation(altAa);
987
- }
988
- } else {
989
- const aa = new SmoOrnament({ ornament: modifier });
990
- const altAa = new SmoOrnament({ ornament: modifier });
991
- altAa.attrs.id = aa.attrs.id;
992
- const altSelection = this._getEquivalentSelection(sel!);
993
- if (sel.note) {
994
- sel.note.toggleOrnament(aa);
995
- }
996
- if (altSelection && altSelection.note) {
997
- altSelection.note.toggleOrnament(altAa);
998
- }
999
- }
1000
- });
1001
- this._renderChangedMeasures(measureSelections);
1002
- await this.renderer.updatePromise();
1003
- }
1004
- async setArticulation(modifier: SmoArticulation, set: boolean): Promise<void> {
1005
- const measureSelections = this.undoTrackerMeasureSelections('set articulation');
1006
- this.tracker.selections.forEach((sel) => {
1007
- const altAa = new SmoArticulation(modifier);
1008
- if (sel.note) {
1009
- sel.note.setArticulation(modifier, set);
1010
- }
1011
- const altSelection = this._getEquivalentSelection(sel);
1012
- if (altSelection && altSelection.note) {
1013
- altSelection.note.toggleArticulation(altAa);
1014
- }
1015
- });
1016
- this._renderChangedMeasures(measureSelections);
1017
- await this.renderer.updatePromise();
1018
- }
1019
- async setOrnament(modifier: SmoOrnament, set: boolean): Promise<void> {
1020
- const measureSelections = this.undoTrackerMeasureSelections('set articulation');
1021
- this.tracker.selections.forEach((sel) => {
1022
- const altAa = new SmoOrnament(modifier);
1023
- if (sel.note) {
1024
- sel.note.setOrnament(modifier, set);
1025
- }
1026
- const altSelection = this._getEquivalentSelection(sel);
1027
- if (altSelection && altSelection.note) {
1028
- altSelection.note.setOrnament(altAa, set);
1029
- }
1030
- });
1031
- this._renderChangedMeasures(measureSelections);
1032
- await this.renderer.updatePromise();
1033
- }
1034
- /**
1035
- * convert non-tuplet not to a tuplet
1036
- * @param params
1037
- */
1038
- async makeTuplet(params: MakeTupletOperation): Promise<void> {
1039
- const selection = this.tracker.selections[0];
1040
- const measureSelections = this.undoTrackerMeasureSelections('make tuplet');
1041
- SmoOperation.makeTuplet(selection, params);
1042
- const altSelection = this._getEquivalentSelection(selection!);
1043
- SmoOperation.makeTuplet(altSelection!, params);
1044
- this._renderChangedMeasures(measureSelections);
1045
- await this.renderer.updatePromise();
1046
- }
1047
- /**
1048
- * Convert selected tuplet to a single (if possible) non-tuplet
1049
- */
1050
- async unmakeTuplet(): Promise<void> {
1051
- const selection = this.tracker.selections[0];
1052
- const measureSelections = this.undoTrackerMeasureSelections('unmake tuplet');
1053
- SmoOperation.unmakeTuplet(selection);
1054
- const altSelection = this._getEquivalentSelection(selection);
1055
- SmoOperation.unmakeTuplet(altSelection!);
1056
- this._renderChangedMeasures(measureSelections);
1057
- await this.renderer.updatePromise();
1058
- }
1059
-
1060
- /**
1061
- * Create a chord by adding an interval to selected note
1062
- * @param interval 1/2 steps
1063
- * @returns
1064
- */
1065
- async setInterval(interval: number): Promise<void> {
1066
- const selections = this.tracker.selections;
1067
- const measureSelections = this.undoTrackerMeasureSelections('set interval');
1068
- selections.forEach((selected) => {
1069
- SmoOperation.interval(selected, interval);
1070
- const altSelection = this._getEquivalentSelection(selected);
1071
- SmoOperation.interval(altSelection!, interval);
1072
- });
1073
- this._renderChangedMeasures(measureSelections);
1074
- await this.renderer.updatePromise();
1075
- }
1076
-
1077
- /**
1078
- * change the selected chord into a single note
1079
- * @returns
1080
- */
1081
- async collapseChord(): Promise<void> {
1082
- const selections = this.tracker.selections;
1083
- const measureSelections = this.undoTrackerMeasureSelections('collapse chord');
1084
- selections.forEach((selected) => {
1085
- const note: SmoNote | null = selected.note;
1086
- if (note) {
1087
- const pp = JSON.parse(JSON.stringify(note.pitches[0]));
1088
- const altpp = JSON.parse(JSON.stringify(note.pitches[0]));
1089
- // No operation for this?
1090
- note.pitches = [pp];
1091
- const altSelection = this._getEquivalentSelection(selected);
1092
- altSelection!.note!.pitches = [altpp];
1093
- }
1094
- });
1095
- this._renderChangedMeasures(measureSelections);
1096
- await this.renderer.updatePromise();
1097
- }
1098
- /**
1099
- * Toggle chicken-scratches, for jazz improv, comping etc.
1100
- */
1101
- async toggleSlash(): Promise<void> {
1102
- const selections = this.tracker.selections;
1103
- const measureSelections = this.undoTrackerMeasureSelections('make slash');
1104
- selections.forEach((selection) => {
1105
- SmoOperation.toggleSlash(selection);
1106
- const altSel = this._getEquivalentSelection(selection);
1107
- SmoOperation.toggleSlash(altSel!);
1108
- });
1109
- this._renderChangedMeasures(measureSelections);
1110
- await this.renderer.updatePromise();
1111
- }
1112
- /**
1113
- * make selected notes into a rest, or visa-versa
1114
- * @returns
1115
- */
1116
- async makeRest(): Promise<void> {
1117
- const selections = this.tracker.selections;
1118
- const measureSelections = this.undoTrackerMeasureSelections('make rest');
1119
- selections.forEach((selection) => {
1120
- SmoOperation.toggleRest(selection);
1121
- const altSel = this._getEquivalentSelection(selection);
1122
- SmoOperation.toggleRest(altSel!);
1123
- });
1124
- this._renderChangedMeasures(measureSelections);
1125
- await this.renderer.updatePromise();
1126
- }
1127
- async clearAllBeams(): Promise<void> {
1128
- this._undoScore('clearAllBeams');
1129
- SmoOperation.clearAllBeamGroups(this.score);
1130
- SmoOperation.clearAllBeamGroups(this.storeScore);
1131
- await this.awaitRender();
1132
- }
1133
- async clearSelectedBeams() {
1134
- const selections = this.tracker.selections;
1135
- const measures = SmoSelection.getMeasureList(selections);
1136
- const altSelections = this._getEquivalentSelections(selections);
1137
- SmoOperation.clearBeamGroups(this.score, selections);
1138
- SmoOperation.clearBeamGroups(this.storeScore, altSelections);
1139
- this._renderChangedMeasures(measures);
1140
- await this.renderer.updatePromise();
1141
- }
1142
- /**
1143
- * toggle the 'end beam' flag for selected notes
1144
- * @returns
1145
- */
1146
- async unbeamSelections(): Promise<void> {
1147
- const selections = this.tracker.selections;
1148
- const measureSelections = this.undoTrackerMeasureSelections('toggle beam group');
1149
- selections.forEach((selection) => {
1150
- SmoOperation.unbeamSelections(selection);
1151
- const altSel = this._getEquivalentSelection(selection);
1152
- SmoOperation.unbeamSelections(altSel!);
1153
- });
1154
- this._renderChangedMeasures(measureSelections);
1155
- await this.renderer.updatePromise();
1156
- }
1157
- async toggleCue() {
1158
- const measureSelections = this.undoTrackerMeasureSelections('toggle note cue');
1159
- this.tracker.selections.forEach((selection) => {
1160
- const altSelection = this._getEquivalentSelection(selection);
1161
- if (selection.note && selection.note.isRest() === false) {
1162
- selection.note.isCue = !selection.note.isCue;
1163
- if (altSelection && altSelection.note) {
1164
- altSelection.note.isCue = selection.note.isCue;
1165
- }
1166
- }
1167
- });
1168
- this._renderChangedMeasures(measureSelections);
1169
- await this.renderer.updatePromise();
1170
- }
1171
- /**
1172
- * up or down
1173
- * @returns
1174
- */
1175
- async toggleBeamDirection(): Promise<void> {
1176
- const selections = this.tracker.selections;
1177
- if (selections.length < 1) {
1178
- return PromiseHelpers.emptyPromise();
1179
- }
1180
- const measureSelections = this.undoTrackerMeasureSelections('toggle beam direction');
1181
- SmoOperation.toggleBeamDirection(selections);
1182
- SmoOperation.toggleBeamDirection(this._getEquivalentSelections(selections));
1183
- this._renderChangedMeasures(measureSelections);
1184
- await this.renderer.updatePromise();
1185
- }
1186
- /**
1187
- * Add the selected notes to a beam group
1188
- */
1189
- async beamSelections(): Promise<void> {
1190
- const selections = this.tracker.selections;
1191
- const measureSelections = this.undoTrackerMeasureSelections('beam selections');
1192
- SmoOperation.beamSelections(this.score, selections);
1193
- SmoOperation.beamSelections(this.storeScore, this._getEquivalentSelections(selections));
1194
- this._renderChangedMeasures(measureSelections);
1195
- await this.renderer.updatePromise();
1196
- }
1197
- /**
1198
- * change key signature for selected measures
1199
- * @param keySignature vex key signature
1200
- */
1201
- async addKeySignature(keySignature: string): Promise<void> {
1202
- const measureSelections = this.undoTrackerMeasureSelections('set key signature ' + keySignature);
1203
- measureSelections.forEach((sel) => {
1204
- SmoOperation.addKeySignature(this.score, sel, keySignature);
1205
- const altSel = this._getEquivalentSelection(sel);
1206
- SmoOperation.addKeySignature(this.storeScore, altSel!, keySignature);
1207
- });
1208
- this._renderChangedMeasures(measureSelections);
1209
- await this.renderer.updatePromise();
1210
- }
1211
- /**
1212
- * Sets a pitch from the piano widget.
1213
- * @param pitch {Pitch}
1214
- * @param chordPedal {boolean} - indicates we are adding to a chord
1215
- */
1216
- async setPitchPiano(pitch: Pitch, chordPedal: boolean): Promise<void> {
1217
- const measureSelections = this.undoTrackerMeasureSelections(
1218
- 'setAbsolutePitch ' + pitch.letter + '/' + pitch.accidental);
1219
- this.tracker.selections.forEach((selected) => {
1220
- const npitch: Pitch = {
1221
- letter: pitch.letter,
1222
- accidental: pitch.accidental, octave: pitch.octave
1223
- };
1224
- const octave = SmoMeasure.defaultPitchForClef[selected.measure.clef].octave;
1225
- npitch.octave += octave;
1226
- const altSel = this._getEquivalentSelection(selected);
1227
- if (chordPedal && selected.note) {
1228
- selected.note.toggleAddPitch(npitch);
1229
- altSel!.note!.toggleAddPitch(npitch);
1230
- } else {
1231
- SmoOperation.setPitch(selected, [npitch]);
1232
- SmoOperation.setPitch(altSel!, [npitch]);
1233
- }
1234
- });
1235
- this._renderChangedMeasures(measureSelections);
1236
- await this.renderer.updatePromise();
1237
- }
1238
- /**
1239
- * show or hide the piano widget
1240
- * @param value to show it
1241
- */
1242
- async showPiano(value: boolean): Promise<void> {
1243
- this.score.preferences.showPiano = value;
1244
- this.storeScore.preferences.showPiano = value;
1245
- if (value) {
1246
- SuiPiano.showPiano();
1247
- } else {
1248
- SuiPiano.hidePiano();
1249
- }
1250
- await this.renderer.updatePromise();
1251
- }
1252
- /**
1253
- * Render a pitch for each letter name-pitch in the string,
1254
- * @param pitches letter names for pitches
1255
- * @returns promise, resolved when all pitches rendered
1256
- * @see setPitch
1257
- */
1258
- async setPitchesPromise(pitches: PitchLetter[]): Promise<any> {
1259
- const self = this;
1260
- const promise = new Promise((resolve: any) => {
1261
- const fc = async (index: number) => {
1262
- if (index >= pitches.length) {
1263
- resolve();
1264
- } else {
1265
- await self.setPitch(pitches[index]);
1266
- fc(index + 1);
1267
- }
1268
- };
1269
- fc(0);
1270
- });
1271
- await promise;
1272
- }
1273
-
1274
- async setPitches(pitches: Pitch[]): Promise<void> {
1275
- const selections = this.tracker.selections;
1276
- const measureSelections = this.undoTrackerMeasureSelections('set pitches');
1277
- const graceNotes = this.tracker.getSelectedGraceNotes();
1278
- if (graceNotes.length === 1 && graceNotes[0].selection !== null && graceNotes[0].selection?.note !== null) {
1279
- const grace1 = graceNotes[0].modifier as SmoGraceNote;
1280
- const index = graceNotes[0].selection.note.graceNotes.findIndex((x) => x.attrs.id === grace1.attrs.id);
1281
-
1282
- const altSel = this._getEquivalentSelection(graceNotes[0].selection);
1283
- if (altSel && altSel.note !== null) {
1284
- const grace2 = altSel.note.graceNotes[index];
1285
- grace2.pitches = pitches;
1286
- }
1287
- grace1.pitches = pitches;
1288
- } else if( selections.length === 1) {
1289
- const selected = selections[0];
1290
- SmoOperation.setPitch(selected, pitches);
1291
- const altSel = this._getEquivalentSelection(selected);
1292
- SmoOperation.setPitch(altSel!, pitches);
1293
- if (this.score.preferences.autoAdvance) {
1294
- // Don't play the next note and the added pitch at the same time.
1295
- this.tracker.deferNextAutoPlay();
1296
- this.tracker.moveSelectionRight();
1297
- }
1298
- SuiOscillator.playSelectionNow(selected, this.score, 1);
1299
- }
1300
-
1301
- this._renderChangedMeasures(measureSelections);
1302
- await this.renderer.updatePromise();
1303
- }
1304
- /**
1305
- * Add a pitch to the score at the cursor. This tries to find the best pitch
1306
- * to match the letter key (F vs F# for instance) based on key and surrounding notes
1307
- * @param letter string
1308
- */
1309
- async setPitch(letter: PitchLetter): Promise<void> {
1310
- const selections = this.tracker.selections;
1311
- const measureSelections = this.undoTrackerMeasureSelections('set pitch ' + letter);
1312
- let isPercussion = false;
1313
- selections.forEach((selected) => {
1314
- const selector = selected.selector;
1315
- if (selected.staff.getStaffInstrument(selected.selector.measure).isPercussion) {
1316
- isPercussion = true;
1317
- }
1318
- let hintSel = SmoSelection.lastNoteSelectionNonRest(this.score,
1319
- selector.staff, selector.measure, selector.voice, selector.tick);
1320
- if (!hintSel) {
1321
- hintSel = SmoSelection.nextNoteSelectionNonRest(this.score,
1322
- selector.staff, selector.measure, selector.voice, selector.tick);
1323
- }
1324
- // The selection no longer exists, possibly deleted
1325
- if (hintSel === null || hintSel.note === null) {
1326
- return PromiseHelpers.emptyPromise();
1327
- }
1328
- const pitch = SmoMusic.getLetterNotePitch(hintSel.note.pitches[0],
1329
- letter, hintSel.measure.keySignature);
1330
- SmoOperation.setPitch(selected, [pitch]);
1331
- const altSel = this._getEquivalentSelection(selected);
1332
- SmoOperation.setPitch(altSel!, [pitch]);
1333
- if (this.score.preferences.autoAdvance) {
1334
- // Don't play the next note and the added pitch at the same time.
1335
- this.tracker.deferNextAutoPlay();
1336
- this.tracker.moveSelectionRight();
1337
- }
1338
- });
1339
- if (isPercussion) {
1340
- this.score.setNoteInstrumentProperties();
1341
- this.storeScore.setNoteInstrumentProperties()
1342
- }
1343
- if (selections.length === 1 && this.score.preferences.autoPlay) {
1344
- SuiOscillator.playSelectionNow(selections[0], this.score, 1);
1345
- }
1346
- this._renderChangedMeasures(measureSelections);
1347
- await this.renderer.updatePromise();
1348
- }
1349
- /**
1350
- * Generic clipboard copy action
1351
- */
1352
- async copy(): Promise<void> {
1353
- const altAr: SmoSelection[] = [];
1354
- this.tracker.selections.forEach((sel) => {
1355
- const noteSelection = this._getEquivalentSelection(sel);
1356
- if (noteSelection !== null) {
1357
- altAr.push(noteSelection);
1358
- }
1359
- });
1360
- this.storePaste.setSelections(this.storeScore, altAr);
1361
- await this.renderer.updatePromise();
1362
- }
1363
- /**
1364
- * clipboard paste action
1365
- * @returns
1366
- */
1367
- async paste(): Promise<void> {
1368
- // We undo the whole score on a paste, since we don't yet know the
1369
- // extent of the overlap
1370
- this.renderer.preserveScroll();
1371
- const selections: SmoSelection[] = this.getPasteMeasureList();
1372
- const firstSelection = selections[0];
1373
- const measureEnd = selections[selections.length - 1].selector.measure;
1374
- const measureRange = [firstSelection.selector.measure, measureEnd];
1375
- this.storeUndo.grouping = true;
1376
- // Undo the paste by selecting all the affected measures
1377
- for (let i = measureRange[0]; i <= measureRange[1]; ++i) {
1378
- this._undoColumn('paste', i);
1379
- this.renderer.unrenderColumn(this.score.staves[0].measures[i]);
1380
- }
1381
- this.storeUndo.grouping = false;
1382
- const altSelection = this._getEquivalentSelection(firstSelection);
1383
- const altTarget = altSelection!.selector;
1384
- altTarget.tick = this.tracker.selections[0].selector.tick;
1385
- // paste the clipboard into the destination
1386
- this.storePaste.pasteSelections(altTarget);
1387
- // Refresh those measures.
1388
- this.replaceMeasureView(measureRange);
1389
- await this.renderer.updatePromise();
1390
- }
1391
- /**
1392
- * Paste only the chords.
1393
- */
1394
- async pasteChords(): Promise<void> {
1395
- // We undo the whole score on a paste, since we don't yet know the
1396
- // extent of the overlap
1397
- this.renderer.preserveScroll();
1398
- const selections: SmoSelection[] = this.getPasteMeasureList();
1399
- const firstSelection = selections[0];
1400
- const measureEnd = selections[selections.length - 1].selector.measure;
1401
- const measureRange = [firstSelection.selector.measure, measureEnd];
1402
- this.storeUndo.grouping = true;
1403
- // Undo the paste by selecting all the affected measures
1404
- for (let i = measureRange[0]; i <= measureRange[1]; ++i) {
1405
- this._undoColumn('paste', i);
1406
- this.renderer.unrenderColumn(this.score.staves[0].measures[i]);
1407
- }
1408
- this.storeUndo.grouping = false;
1409
- const altSelection = this._getEquivalentSelection(firstSelection);
1410
- const altTarget = altSelection!.selector;
1411
- altTarget.tick = this.tracker.selections[0].selector.tick;
1412
- this.storePaste.pasteChords(altTarget);
1413
- // Refresh those measures.
1414
- this.replaceMeasureView(measureRange);
1415
- await this.renderer.updatePromise();
1416
- }
1417
- /**
1418
- * specify a note head other than the default for the duration
1419
- * @param head
1420
- */
1421
- async setNoteHead(head: string): Promise<void> {
1422
- await this.modifyCurrentSelections('set note head', (score, selections) => {
1423
- SmoOperation.setNoteHead(selections, head);
1424
- });
1425
- }
1426
-
1427
- /**
1428
- * Add a volta for selected measures
1429
- */
1430
- async addEnding(): Promise<void> {
1431
- // TODO: we should have undo for columns
1432
- this._undoScore('Add Volta');
1433
- const ft = this.tracker.getExtremeSelection(-1);
1434
- const tt = this.tracker.getExtremeSelection(1);
1435
- const params = SmoVolta.defaults;
1436
- params.startBar = ft.selector.measure;
1437
- params.endBar = tt.selector.measure;
1438
- params.number = 1;
1439
- const volta = new SmoVolta(params);
1440
- const altVolta = new SmoVolta(params);
1441
- this._renderChangedMeasures([ft, tt]);
1442
- SmoOperation.addEnding(this.storeScore, altVolta);
1443
- SmoOperation.addEnding(this.score, volta);
1444
- this.renderer.setRefresh();
1445
- return this.renderer.updatePromise();
1446
- }
1447
- /**
1448
- * @param ending volta settings
1449
- * @returns
1450
- */
1451
- async updateEnding(ending: SmoVolta): Promise<void> {
1452
- this._undoScore('Change Volta');
1453
- ending.elements.forEach((el) => {
1454
- $(el).find('g.' + ending.attrs.id).remove();
1455
- });
1456
- ending.elements = [];
1457
- SmoOperation.removeEnding(this.storeScore, ending);
1458
- SmoOperation.removeEnding(this.score, ending);
1459
- const altVolta = new SmoVolta(ending);
1460
- SmoOperation.addEnding(this.storeScore, altVolta);
1461
- SmoOperation.addEnding(this.score, ending);
1462
- this.renderer.setRefresh();
1463
- return this.renderer.updatePromise();
1464
- }
1465
- /**
1466
- *
1467
- * @param ending volta to remove
1468
- * @returns
1469
- */
1470
- async removeEnding(ending: SmoVolta): Promise<void> {
1471
- this._undoScore('Remove Volta');
1472
- ending.elements.forEach((el) => {
1473
- $(el).find('g.' + ending.attrs.id).remove();
1474
- });
1475
- ending.elements = [];
1476
- SmoOperation.removeEnding(this.storeScore, ending);
1477
- SmoOperation.removeEnding(this.score, ending);
1478
- this.renderer.setRefresh();
1479
- return this.renderer.updatePromise();
1480
- }
1481
- /**
1482
- *
1483
- * @param position begin or end
1484
- * @param barline barline type
1485
- * @returns
1486
- */
1487
- async setBarline(position: number, barline: number, bracket: number): Promise<void> {
1488
- const obj = new SmoBarline({ position, barline, repeatBracket: bracket });
1489
- const altObj = new SmoBarline({ position, barline, repeatBracket: bracket });
1490
- const selection = this.tracker.selections[0];
1491
- this._undoColumn('set barline', selection.selector.measure);
1492
- SmoOperation.setMeasureBarline(this.score, selection, obj);
1493
- const altSel = this._getEquivalentSelection(selection);
1494
- SmoOperation.setMeasureBarline(this.storeScore, altSel!, altObj);
1495
- this._renderChangedMeasures([selection]);
1496
- return this.renderer.updatePromise();
1497
- }
1498
- /**
1499
- *
1500
- * @param position start or end
1501
- * @param symbol coda, etc.
1502
- */
1503
- async setRepeatSymbol(position: number, symbol: number): Promise<void> {
1504
- const params = SmoRepeatSymbol.defaults;
1505
- params.position = position;
1506
- params.symbol = symbol;
1507
- const obj = new SmoRepeatSymbol(params);
1508
- const altObj = new SmoRepeatSymbol(params);
1509
- const selection = this.tracker.selections[0];
1510
- this._undoColumn('set repeat symbol', selection.selector.measure);
1511
- SmoOperation.setRepeatSymbol(this.score, selection, obj);
1512
- const altSel = this._getEquivalentSelection(selection);
1513
- SmoOperation.setRepeatSymbol(this.storeScore, altSel!, altObj);
1514
- this._renderChangedMeasures([selection]);
1515
- return this.renderer.updatePromise();
1516
- }
1517
- /**
1518
- * toggle rehearsal mark on first selected measure
1519
- * @returns
1520
- */
1521
- async toggleRehearsalMark(): Promise<void> {
1522
- const selection = this.tracker.getExtremeSelection(-1);
1523
- const altSelection = this._getEquivalentSelection(selection);
1524
- const cmd = selection.measure.getRehearsalMark() ? 'removeRehearsalMark' : 'addRehearsalMark';
1525
- SmoOperation[cmd](this.score, selection, new SmoRehearsalMark(SmoRehearsalMark.defaults));
1526
- SmoOperation[cmd](this.storeScore, altSelection!, new SmoRehearsalMark(SmoRehearsalMark.defaults));
1527
- this._renderChangedMeasures([selection]);
1528
- return this.renderer.updatePromise();
1529
- }
1530
- /**
1531
- * Finds the measure whose rehearsal mark has the given id, as a selection on the live score.
1532
- * Rehearsal marks are column-wide, so the first staff holding it identifies the measure.
1533
- * See specs/025-rehearsal-mark-dialog.
1534
- */
1535
- _findRehearsalMarkSelection(id: string): SmoSelection | null {
1536
- for (let i = 0; i < this.score.staves.length; ++i) {
1537
- const staff = this.score.staves[i];
1538
- for (let j = 0; j < staff.measures.length; ++j) {
1539
- const measure = staff.measures[j];
1540
- if (measure.getRehearsalMark()?.attrs.id === id) {
1541
- return SmoSelection.measureSelection(this.score, staff.staffId, measure.measureNumber.measureIndex);
1542
- }
1543
- }
1544
- }
1545
- return null;
1546
- }
1547
- /**
1548
- * Replaces an existing rehearsal mark's settings on its measure, on every staff and in the
1549
- * undo-copy store. Does nothing if the mark is no longer present (e.g. removed while its dialog
1550
- * was open). See specs/025-rehearsal-mark-dialog.
1551
- * @param mark the edited rehearsal mark
1552
- */
1553
- async updateRehearsalMark(mark: SmoRehearsalMark): Promise<void> {
1554
- const selection = this._findRehearsalMarkSelection(mark.attrs.id);
1555
- if (!selection) {
1556
- return;
1557
- }
1558
- const altSelection = this._getEquivalentSelection(selection);
1559
- this._undoColumn('Change Rehearsal Mark', selection.selector.measure);
1560
- SmoOperation.removeRehearsalMark(this.score, selection);
1561
- SmoOperation.addRehearsalMark(this.score, selection, mark);
1562
- SmoOperation.removeRehearsalMark(this.storeScore, altSelection!);
1563
- SmoOperation.addRehearsalMark(this.storeScore, altSelection!, mark);
1564
- this._renderChangedMeasures([selection]);
1565
- return this.renderer.updatePromise();
1566
- }
1567
- /**
1568
- * Removes an existing rehearsal mark from its measure on every staff and in the undo-copy store.
1569
- * Does nothing if the mark is no longer present. See specs/025-rehearsal-mark-dialog.
1570
- * @param mark the rehearsal mark to remove
1571
- */
1572
- async removeRehearsalMark(mark: SmoRehearsalMark): Promise<void> {
1573
- const selection = this._findRehearsalMarkSelection(mark.attrs.id);
1574
- if (!selection) {
1575
- return;
1576
- }
1577
- const altSelection = this._getEquivalentSelection(selection);
1578
- this._undoColumn('Remove Rehearsal Mark', selection.selector.measure);
1579
- SmoOperation.removeRehearsalMark(this.score, selection);
1580
- SmoOperation.removeRehearsalMark(this.storeScore, altSelection!);
1581
- this._renderChangedMeasures([selection]);
1582
- return this.renderer.updatePromise();
1583
- }
1584
- _removeStaffModifier(modifier: StaffModifierBase) {
1585
- this.score.staves[modifier.associatedStaff].removeStaffModifier(modifier);
1586
- const altModifier = StaffModifierBase.deserialize(modifier.serialize());
1587
- altModifier.attrs.id = modifier.attrs.id;
1588
- altModifier.startSelector = this._getEquivalentSelector(altModifier.startSelector);
1589
- altModifier.endSelector = this._getEquivalentSelector(altModifier.endSelector);
1590
- this.storeScore.staves[this._getEquivalentStaff(modifier.associatedStaff)].removeStaffModifier(altModifier);
1591
- }
1592
- /**
1593
- * Remove selected modifier
1594
- * @param modifier slur, hairpin, etc.
1595
- * @returns
1596
- */
1597
- async removeStaffModifier(modifier: StaffModifierBase): Promise<void> {
1598
- this.undoStaffModifier('Set measure proportion', modifier,
1599
- UndoBuffer.bufferSubtypes.REMOVE);
1600
- this._removeStaffModifier(modifier);
1601
- this._renderRectangle(modifier.startSelector, modifier.endSelector);
1602
- return this.renderer.updatePromise();
1603
- }
1604
- /**
1605
- * Change a staff modifier
1606
- * @param original original version
1607
- * @param modifier modified version
1608
- * @returns
1609
- */
1610
- async addOrUpdateStaffModifier(original: StaffModifierBase, modifier: StaffModifierBase): Promise<void> {
1611
- if (!modifier) {
1612
- if (original) {
1613
- // Handle legacy API changed
1614
- modifier = StaffModifierBase.deserialize(original);
1615
- } else {
1616
- console.warn('update modifier: bad modifier');
1617
- return PromiseHelpers.emptyPromise();
1618
- }
1619
- }
1620
- const existing = this.score.staves[modifier.startSelector.staff]
1621
- .getModifier(modifier);
1622
- const subtype = existing === null ? UndoBuffer.bufferSubtypes.ADD :
1623
- UndoBuffer.bufferSubtypes.UPDATE;
1624
- this.undoStaffModifier('Set measure proportion', original,
1625
- subtype);
1626
- this._removeStaffModifier(modifier);
1627
- const copy = StaffModifierBase.deserialize(modifier.serialize());
1628
- copy.startSelector = this._getEquivalentSelector(copy.startSelector);
1629
- copy.endSelector = this._getEquivalentSelector(copy.endSelector);
1630
- const sel = SmoSelection.noteFromSelector(this.score, modifier.startSelector);
1631
- if (sel !== null) {
1632
- const altSel = this._getEquivalentSelection(sel);
1633
- SmoOperation.addStaffModifier(sel, modifier);
1634
- SmoOperation.addStaffModifier(altSel!, copy);
1635
- const modId = 'mod-' + sel.selector.staff + '-' + sel.selector.measure;
1636
- const context = this.renderer.renderer.getRenderer(sel.measure.svg.logicalBox);
1637
- if (context) {
1638
- SvgHelpers.removeElementsByClass(context.svg, modId);
1639
- }
1640
- }
1641
- this._renderRectangle(modifier.startSelector, modifier.endSelector);
1642
- return this.renderer.updatePromise();
1643
- }
1644
- lineOperation(op: createStaffModifierType<StaffModifierBase>) {
1645
- // if (this.tracker.selections.length < 2) {
1646
- // return;
1647
- // }
1648
- const measureSelections = this.undoTrackerMeasureSelections('create staff modifier');
1649
- const ft = this.tracker.getExtremeSelection(-1);
1650
- const tt = this.tracker.getExtremeSelection(1);
1651
- const ftAlt = this._getEquivalentSelection(ft);
1652
- const ttAlt = this._getEquivalentSelection(tt);
1653
- const modifier = op(ft, tt);
1654
- const altModifier = op(ftAlt!, ttAlt!);
1655
- altModifier.attrs.id = modifier.attrs.id;
1656
- ft.staff.addStaffModifier(modifier);
1657
- ftAlt?.staff.addStaffModifier(altModifier);
1658
- this.undoStaffModifier('add ' + op, modifier, UndoBuffer.bufferSubtypes.ADD);
1659
- this._renderChangedMeasures(measureSelections);
1660
- }
1661
- /**
1662
- * Add crescendo to selection
1663
- */
1664
- async crescendo(): Promise<void> {
1665
- this.lineOperation(SmoOperation.createCrescendo);
1666
- return this.renderer.updatePromise();
1667
- }
1668
- /**
1669
- * Add crescendo to selection
1670
- */
1671
- async crescendoBracket(): Promise<void> {
1672
- this.lineOperation(SmoOperation.createCrescendoBracket);
1673
- return this.renderer.updatePromise();
1674
- }
1675
- /**
1676
- * Add crescendo to selection
1677
- */
1678
- async dimenuendo(): Promise<void> {
1679
- this.lineOperation(SmoOperation.createDimenuendoBracket);
1680
- return this.renderer.updatePromise();
1681
- }
1682
- /**
1683
- * Add crescendo to selection
1684
- */
1685
- async accelerando(): Promise<void> {
1686
- this.lineOperation(SmoOperation.createAccelerandoBracket);
1687
- return this.renderer.updatePromise();
1688
- }
1689
- /**
1690
- * Add crescendo to selection
1691
- */
1692
- async ritard(): Promise<void> {
1693
- this.lineOperation(SmoOperation.createRitardBracket);
1694
- return this.renderer.updatePromise();
1695
- }
1696
- /**
1697
- * diminuendo hairpin
1698
- * @returns
1699
- */
1700
- async decrescendo(): Promise<void> {
1701
- this.lineOperation(SmoOperation.createDecrescendo);
1702
- return this.renderer.updatePromise();
1703
- }
1704
- async removeTextBracket(bracket: SmoStaffTextBracket): Promise<void> {
1705
- return this.removeStaffModifier(bracket);
1706
- }
1707
- async addOrReplaceStaffModifier(callback: updateStaffModifierFunc, modifier: StaffModifierBase): Promise<void> {
1708
- const from1 = SmoSelection.noteFromSelector(this.score, modifier.startSelector);
1709
- const to1 = SmoSelection.noteFromSelector(this.score, modifier.endSelector);
1710
- if (from1 === null || to1 === null) {
1711
- return;
1712
- }
1713
- const altFrom = this._getEquivalentSelection(from1);
1714
- const altTo = this._getEquivalentSelection(to1);
1715
- if (altFrom === null || altTo === null) {
1716
- return;
1717
- }
1718
- callback(this.score, from1, to1);
1719
- callback(this.storeScore, altFrom, altTo);
1720
- const redraw = SmoSelection.getMeasuresBetween(this.score, from1.selector, to1.selector);
1721
- this.undoStaffModifier('add repl text bracket', modifier, UndoBuffer.bufferSubtypes.ADD);
1722
- this._renderChangedMeasures(redraw);
1723
- return this.renderer.updatePromise();
1724
- }
1725
- async addOrReplaceTextBracket(modifier: SmoStaffTextBracket) {
1726
- const from1 = SmoSelection.noteFromSelector(this.score, modifier.startSelector);
1727
- const to1 = SmoSelection.noteFromSelector(this.score, modifier.endSelector);
1728
- if (from1 === null || to1 === null) {
1729
- return;
1730
- }
1731
- const altFrom = this._getEquivalentSelection(from1);
1732
- const altTo = this._getEquivalentSelection(to1);
1733
- if (altFrom === null || altTo === null) {
1734
- return;
1735
- }
1736
- SmoOperation.addOrReplaceBracket(modifier, from1, to1);
1737
- SmoOperation.addOrReplaceBracket(modifier, altFrom, altTo);
1738
- const redraw = SmoSelection.getMeasuresBetween(this.score, from1.selector, to1.selector);
1739
- this.undoStaffModifier('add repl text bracket', modifier, UndoBuffer.bufferSubtypes.ADD);
1740
- this._renderChangedMeasures(redraw);
1741
- return this.renderer.updatePromise();
1742
- }
1743
- /**
1744
- * Slur selected notes
1745
- * @returns
1746
- */
1747
- async addSlur(): Promise<void> {
1748
- const measureSelections = SmoSelection.getMeasureList(this.tracker.selections);
1749
- const ft = this.tracker.getExtremeSelection(-1);
1750
- const tt = this.tracker.getExtremeSelection(1);
1751
- const ftAlt = this._getEquivalentSelection(ft);
1752
- const ttAlt = this._getEquivalentSelection(tt);
1753
- const modifier = SmoOperation.createSlur(this.score, ft, tt);
1754
- ft.staff.addStaffModifier(modifier);
1755
- // make sure score and backup have same ID for undo.
1756
- const altModifier = SmoOperation.createSlur(this.storeScore, ftAlt!, ttAlt!);
1757
- altModifier.attrs.id = modifier.attrs.id;
1758
- ftAlt?.staff.addStaffModifier(altModifier);
1759
- this.undoStaffModifier('add slur', modifier, UndoBuffer.bufferSubtypes.ADD);
1760
- this._renderChangedMeasures(measureSelections);
1761
- return this.renderer.updatePromise();
1762
- }
1763
- /**
1764
- * tie selected notes
1765
- * @returns
1766
- */
1767
- async tie(): Promise<void> {
1768
- this.lineOperation(SmoOperation.createTie);
1769
- return this.renderer.updatePromise();
1770
- }
1771
- async updateZoom(zoomFactor: number): Promise<void> {
1772
- const original = this.score.layoutManager!.getGlobalLayout();
1773
- original.zoomScale = zoomFactor;
1774
- this.score.layoutManager!.globalLayout.zoomScale = zoomFactor;
1775
- this.renderer.pageMap.updateZoom(zoomFactor);
1776
- this.renderer.pageMap.updateContainerOffset(this.scroller.scrollState);
1777
- }
1778
- /**
1779
- * set global page for score, zoom etc.
1780
- * @param layout global SVG settings
1781
- * @param previousLayout the layout as it was immediately before this change. Callers must
1782
- * pass a snapshot taken before `layout` was mutated -- `this.score.layoutManager`'s current
1783
- * value cannot be used for this, because dialogs (e.g. globalLayout.ts) bind directly to that
1784
- * live object, so by the time this method runs it may already equal `layout`.
1785
- * @returns
1786
- */
1787
- async setGlobalLayout(layout: SmoGlobalLayout, previousLayout: SmoGlobalLayout): Promise<void> {
1788
- const scaleChanged = previousLayout.svgScale !== layout.svgScale;
1789
- const widthChanged = previousLayout.pageWidth !== layout.pageWidth;
1790
- const heightChanged = previousLayout.pageHeight !== layout.pageHeight;
1791
- if (!scaleChanged && !widthChanged && !heightChanged) {
1792
- return;
1793
- }
1794
- this._undoScore('Set Global Layout');
1795
- const scaleRatio = previousLayout.svgScale / layout.svgScale;
1796
- const widthRatio = widthChanged ? layout.pageWidth / previousLayout.pageWidth : 1;
1797
- const heightRatio = heightChanged ? layout.pageHeight / previousLayout.pageHeight : 1;
1798
- const repositionGroups = (textGroups: SmoTextGroup[]) => {
1799
- if (scaleChanged) {
1800
- textGroups.forEach((tg) => tg.scaleText(scaleRatio));
1801
- }
1802
- if (widthChanged || heightChanged) {
1803
- textGroups.forEach((tg) => tg.rescalePosition(widthRatio, heightRatio));
1804
- }
1805
- };
1806
- if (this.isPartExposed()) {
1807
- // A part has its own layoutManager/textGroups (see SuiScoreView._mapPartFormatting,
1808
- // which aliases this.score.layoutManager/textGroups to staves[0].partInfo's copies), so
1809
- // only the exposed part's text is repositioned here -- the score's own text groups and
1810
- // other parts' text groups are untouched.
1811
- this.score.staves.forEach((staff, staffIx) => {
1812
- staff.partInfo.layoutManager.updateGlobalLayout(layout);
1813
- repositionGroups(staff.partInfo.textGroups);
1814
- const altStaff = this.storeScore.staves[this.staffMap[staffIx]];
1815
- altStaff.partInfo.layoutManager.updateGlobalLayout(layout);
1816
- repositionGroups(altStaff.partInfo.textGroups);
1817
- });
1818
- } else {
1819
- this.score.layoutManager!.updateGlobalLayout(layout);
1820
- repositionGroups(this.score.textGroups);
1821
- this.storeScore.layoutManager!.updateGlobalLayout(layout);
1822
- repositionGroups(this.storeScore.textGroups);
1823
- }
1824
- this.renderer.rerenderAll();
1825
- return this.renderer.preserveScroll();
1826
- }
1827
- /**
1828
- * Set the layout of a single page
1829
- * @param layout page layout
1830
- * @param pageIndex which page to change
1831
- * @returns
1832
- */
1833
- async setPageLayout(layout: SmoPageLayout, pageIndex: number) {
1834
- this.score.layoutManager!.updatePage(layout, pageIndex);
1835
- this.storeScore.layoutManager!.updatePage(layout, pageIndex);
1836
- // If we are in part mode, save the page layout in the part so it is there next time
1837
- // the part is exposed.
1838
- if (this.isPartExposed()) {
1839
- this.score.staves.forEach((staff, staffIx) => {
1840
- staff.partInfo.layoutManager.updatePage(layout, pageIndex);
1841
- const altStaff = this.storeScore.staves[this.staffMap[staffIx]];
1842
- altStaff.partInfo.layoutManager.updatePage(layout, pageIndex);
1843
- });
1844
- }
1845
- await this.refreshViewport();
1846
- }
1847
- async setPageLayouts(layout: SmoPageLayout, startIndex: number, endIndex: number) {
1848
- this._undoScore('Set Page Layout');
1849
- let i = 0;
1850
- for (i = startIndex; i <= endIndex; ++i) {
1851
- this.setPageLayout(layout, i);
1852
- }
1853
- this.renderer.rerenderAll();
1854
- return this.renderer.updatePromise();
1855
- }
1856
- /**
1857
- * Update the music font
1858
- * @param family
1859
- * @returns
1860
- */
1861
- async setEngravingFontFamily(family: engravingFontType): Promise<void> {
1862
- this.score.engravingFont = family;
1863
- this.storeScore.engravingFont = family;
1864
- this.renderer.notifyFontChange();
1865
- this.renderer.setRefresh();
1866
- return this.renderer.updatePromise();
1867
- }
1868
- /**
1869
- * Upate global font used for chord changes
1870
- * @param fontInfo
1871
- * @returns
1872
- */
1873
- async setChordFont(fontInfo: FontInfo): Promise<void> {
1874
- this._undoScore('Set Chord Font');
1875
- this.score.setChordFont(fontInfo);
1876
- this.storeScore.setChordFont(fontInfo);
1877
- this.renderer.setRefresh();
1878
- return this.renderer.updatePromise();
1879
- }
1880
- /**
1881
- * Update font used for lyrics
1882
- * @param fontInfo
1883
- * @returns
1884
- */
1885
- async setLyricFont(fontInfo: FontInfo): Promise<void> {
1886
- this._undoScore('Set Lyric Font');
1887
- this.score.setLyricFont(fontInfo);
1888
- this.storeScore.setLyricFont(fontInfo);
1889
- this.renderer.setRefresh();
1890
- return this.renderer.updatePromise();
1891
- }
1892
- /**
1893
- * @param value if false, lyric widths don't affect measure width
1894
- * @returns
1895
- */
1896
- async setLyricAdjustWidth(value: boolean): Promise<void> {
1897
- this._undoScore('Set Lyric Adj Width');
1898
- this.score.setLyricAdjustWidth(value);
1899
- this.storeScore.setLyricAdjustWidth(value);
1900
- this.renderer.setRefresh();
1901
- return this.renderer.updatePromise();
1902
- }
1903
- /**
1904
- * delete selected measures
1905
- * @returns
1906
- */
1907
- async deleteMeasure(): Promise<void> {
1908
- this._undoScore('Delete Measure');
1909
- if (this.storeScore.staves[0].measures.length < 2) {
1910
- return PromiseHelpers.emptyPromise();
1911
- }
1912
- const selections = SmoSelection.getMeasureList(this.tracker.selections);
1913
- // THe measures get renumbered, so keep the index at 0
1914
- const index = selections[0].selector.measure;
1915
- for (var i = 0; i < selections.length; ++i) {
1916
- // Unrender the deleted measure
1917
- this.score.staves.forEach((staff) => {
1918
- this.tracker.clearMeasureMap(staff.measures[index]);
1919
- this.renderer.unrenderMeasure(staff.measures[index]);
1920
- this.renderer.unrenderMeasure(staff.measures[staff.measures.length - 1]);
1921
- // A little hacky - delete the modifiers if they start or end on
1922
- // the measure
1923
- staff.renderableModifiers.forEach((modifier) => {
1924
- if (modifier.startSelector.measure === index || modifier.endSelector.measure === index) {
1925
- if (modifier.logicalBox) {
1926
- const context = this.renderer.renderer.getRenderer(modifier.logicalBox);
1927
- if (context) {
1928
- $(context.svg).find('g.' + modifier.attrs.id).remove();
1929
- }
1930
- }
1931
- }
1932
- });
1933
- });
1934
- // Remove the SVG artifacts mapped to this measure.
1935
- this.score.deleteMeasure(index);
1936
- this.storeScore.deleteMeasure(index);
1937
- // Note: index doesn't increment since there are now 1 fewer measures
1938
- };
1939
- this.renderer.setRefresh();
1940
- return this.renderer.updatePromise();
1941
- }
1942
- /**
1943
- * add number of measures, with default notes selections
1944
- * @param append
1945
- * @param numberToAdd
1946
- * @returns
1947
- */
1948
- async addMeasures(append: boolean, numberToAdd: number): Promise<void> {
1949
- let pos = 0;
1950
- let ix = 0;
1951
- this._undoScore('Add Measure');
1952
- for (ix = 0; ix < numberToAdd; ++ix) {
1953
- const measure = this.tracker.getFirstMeasureOfSelection();
1954
- if (measure) {
1955
- const nmeasure = SmoMeasure.getDefaultMeasureWithNotes(measure);
1956
- pos = measure.measureNumber.measureIndex;
1957
- if (append) {
1958
- pos += 1;
1959
- }
1960
- nmeasure.measureNumber.measureIndex = pos;
1961
- nmeasure.setActiveVoice(0);
1962
- this.score.addMeasure(pos);
1963
- this.storeScore.addMeasure(pos);
1964
- }
1965
- }
1966
- const startMeasure = Math.max(pos - (ix - 1), 0);
1967
- const startSelector = SmoSelector.default;
1968
- const endSelector = SmoSelector.default;
1969
- startSelector.measure = startMeasure;
1970
- endSelector.measure = pos;
1971
- this._renderRectangle(startSelector, endSelector);
1972
- this.renderer.setRefresh();
1973
- return this.renderer.updatePromise();
1974
- }
1975
- /**
1976
- * add a single measure before or after selection
1977
- * @param append
1978
- * @returns
1979
- */
1980
- async addMeasure(append: boolean): Promise<void> {
1981
- this._undoScore('Add Measure');
1982
- let pos = 0;
1983
- const measure = this.tracker.getFirstMeasureOfSelection();
1984
- if (!measure) {
1985
- return;
1986
- }
1987
- const nmeasure = SmoMeasure.getDefaultMeasureWithNotes(measure);
1988
- pos = measure.measureNumber.measureIndex;
1989
- if (append) {
1990
- pos += 1;
1991
- }
1992
- nmeasure.measureNumber.measureIndex = pos;
1993
- nmeasure.setActiveVoice(0);
1994
- this.score.addMeasure(pos);
1995
- this.storeScore.addMeasure(pos);
1996
- this.renderer.clearLine(measure);
1997
- this.renderer.setRefresh();
1998
- return this.renderer.updatePromise();
1999
- }
2000
- /**
2001
- * remove an entire line of music
2002
- * @returns
2003
- */
2004
- async removeStaff(): Promise<void> {
2005
- this._undoScore('Remove Instrument');
2006
- if (this.storeScore.staves.length < 2 || this.score.staves.length < 2) {
2007
- return PromiseHelpers.emptyPromise();
2008
- }
2009
- // if we are looking at a subset of the score,
2010
- // revert to the full score view before removing the staff.
2011
- const toRemove: number[] = [];
2012
- const selectedStaves: Record<number, boolean> = {};
2013
- this.tracker.selections.forEach((sel) => {
2014
- const scoreSel = this._getEquivalentSelection(sel);
2015
- if (!selectedStaves[scoreSel!.selector.staff]) {
2016
- selectedStaves[scoreSel!.selector.staff] = true;
2017
- toRemove.push(scoreSel!.selector.staff);
2018
- }
2019
- });
2020
- // Sort in descending order so we don't mess up the staff indices as we remove
2021
- toRemove.sort((a, b) => b - a);
2022
- toRemove.forEach((staffIndex) => {
2023
- SmoOperation.removeStaff(this.storeScore, staffIndex);
2024
- });
2025
- this.viewAll();
2026
- this.renderer.setRefresh();
2027
- return this.renderer.updatePromise();
2028
- }
2029
- /**
2030
- * Add a new staff to an existing score, with default instrument for the staff part.
2031
- * We base the staff parameters on a stave that currently exists in the score.
2032
- * @param instrument
2033
- * @returns
2034
- */
2035
- async addStaff(instrument: SmoSystemStaffParams): Promise<void> {
2036
- this._undoScore('Add Instrument');
2037
- // if we are looking at a subset of the score, we won't see the new staff. So
2038
- // revert to the full view
2039
- const entry = instrument.measureInstrumentMap[0];
2040
- entry.startSelector.measure = 0;
2041
- entry.endSelector.measure = this.storeScore.staves[0].measures.length - 1;
2042
- const staff = SmoOperation.addStaff(this.storeScore, instrument);
2043
- staff.updateInstrumentOffsets();
2044
- this.storeScore.setNoteInstrumentProperties();
2045
-
2046
- if (instrument.staffId > 0) {
2047
- const selection = SmoSelection.measureSelection(this.storeScore, instrument.staffId - 1, 0);
2048
- const sel = SmoSelector.default;
2049
- sel.staff = instrument.staffId - 1;
2050
- if (selection) {
2051
- let grp = this.storeScore.getSystemGroupForStaff(selection);
2052
- if (grp) {
2053
- grp.endSelector.staff = instrument.staffId;
2054
- } else {
2055
- let grp = new SmoSystemGroup(SmoSystemGroup.defaults);
2056
- grp.startSelector.staff = instrument.staffId - 1;
2057
- grp.endSelector.staff = instrument.staffId;
2058
- this.storeScore.systemGroups.push(grp);
2059
- }
2060
- }
2061
- }
2062
- this.viewAll();
2063
- return this.renderer.updatePromise();
2064
- }
2065
- /**
2066
- * Update part info assumes that the part is currently exposed - that
2067
- * staff 0 is the first staff in the part prior to editing.
2068
- * @param info
2069
- */
2070
- async updatePartInfo(info: SmoPartInfo): Promise<void> {
2071
- let i: number = 0;
2072
- this._undoScore('Update part info');
2073
- const storeStaff = this.staffMap[0] - info.stavesBefore;
2074
- const partLength = info.stavesBefore + info.stavesAfter + 1;
2075
- const resetView = !SmoLayoutManager.areLayoutsEqual(info.layoutManager.getGlobalLayout(), this.score.layoutManager!.getGlobalLayout());
2076
- const restChange = this.score.staves[0].partInfo.expandMultimeasureRests != info.expandMultimeasureRests;
2077
- const stavesChange = this.score.staves[0].partInfo.stavesAfter !== info.stavesAfter;
2078
- this.PartName.value = info.partName;
2079
- for (i = 0; i < partLength; ++i) {
2080
- const nStaffIndex = storeStaff + i;
2081
- const nInfo = new SmoPartInfo(info);
2082
- nInfo.stavesBefore = i;
2083
- nInfo.stavesAfter = partLength - i - 1;
2084
- this.storeScore.staves[nStaffIndex].partInfo = nInfo;
2085
- // Make sure that the next stave in the score has the correct 'staves before' setting
2086
- if (this.storeScore.staves.length > nStaffIndex + 1) {
2087
- if (nInfo.stavesAfter === 0) {
2088
- const nextStaff = this.storeScore.staves[nStaffIndex + 1];
2089
- nextStaff.partInfo.stavesBefore = 0;
2090
- const nextStaffDisplayIndex = this.staffMap.findIndex((x) => x === nStaffIndex + 1);
2091
- if (nextStaffDisplayIndex >= 0) {
2092
- this.score.staves[nextStaffDisplayIndex].partInfo =
2093
- new SmoPartInfo(nextStaff.partInfo);
2094
- }
2095
- }
2096
- }
2097
- // If the staff index is currently displayed,
2098
- const displayedIndex = this.staffMap.findIndex((x) => x === nStaffIndex);
2099
- if (displayedIndex >= 0) {
2100
- this.score.staves[displayedIndex].partInfo = new SmoPartInfo(nInfo);
2101
- this.score.layoutManager = nInfo.layoutManager;
2102
- }
2103
- }
2104
- if (resetView || restChange || stavesChange) {
2105
- SmoOperation.computeMultipartRest(this.score);
2106
- // this.resetPartView();
2107
- this.renderer.rerenderAll()
2108
- }
2109
- return this.renderer.updatePromise();
2110
- }
2111
- /**
2112
- * A simpler API for applications to add a new staff to the score.
2113
- * @param params - the instrument, which determines clef, etc.
2114
- * @returns
2115
- */
2116
- async addStaffSimple(params: Partial<SmoInstrumentParams>): Promise<void> {
2117
- const instrumentParams = SmoInstrument.defaults;
2118
- instrumentParams.startSelector.staff = instrumentParams.endSelector.staff = this.score.staves.length;
2119
- instrumentParams.clef = params.clef ?? instrumentParams.clef;
2120
-
2121
- const staffParams = SmoSystemStaff.defaults;
2122
- staffParams.staffId = this.storeScore.staves.length; // add a staff
2123
- staffParams.measureInstrumentMap[0] = new SmoInstrument(instrumentParams);
2124
- this.addStaff(staffParams);
2125
- return this.renderer.updatePromise();
2126
- }
2127
- /**
2128
- * Save the score to local storage.
2129
- */
2130
- quickSave() {
2131
- const scoreStr = JSON.stringify(this.storeScore.serialize());
2132
- localStorage.setItem(smoSerialize.localScore, scoreStr);
2133
- }
2134
- updateRepeatCount(count: number) {
2135
- const measureSelections = this.undoTrackerMeasureSelections('repeat bar');
2136
- const symbol = count > 0 ? true : false;
2137
- measureSelections.forEach((ms) => {
2138
- const store = this._getEquivalentSelection(ms);
2139
- ms.measure.repeatCount = count;
2140
- ms.measure.repeatSymbol = symbol;
2141
- if (store) {
2142
- store.measure.repeatCount = count;
2143
- store.measure.repeatSymbol = symbol;
2144
- }
2145
- });
2146
- this._renderChangedMeasures(measureSelections);
2147
- return this.updatePromise();
2148
- }
2149
- /**
2150
- * Update the measure formatting parameters for the current selection
2151
- * @param format generic measure formatting parameters
2152
- * @returns
2153
- */
2154
- setMeasureFormat(format: SmoMeasureFormat): Promise<any> {
2155
- const label = 'set measure format';
2156
- const fromSelector = this.tracker.getExtremeSelection(-1).selector;
2157
- const toSelector = this.tracker.getExtremeSelection(1).selector;
2158
- const measureSelections = this.tracker.getSelectedMeasures();
2159
- // If the formatting is on a part, preserve it in the part's info
2160
- const isPart = this.isPartExposed();
2161
- measureSelections.forEach((m) => {
2162
- this._undoColumn(label, m.selector.measure);
2163
- SmoOperation.setMeasureFormat(this.score, m, format);
2164
- if (isPart) {
2165
- m.staff.partInfo.measureFormatting[m.measure.measureNumber.measureIndex] = new SmoMeasureFormat(format);
2166
- const alt = this._getEquivalentSelection(m);
2167
- SmoOperation.setMeasureFormat(this.storeScore, alt!, format);
2168
- } else {
2169
- // If we are seeing some set of staves that is not a part, make sure the whole column in the
2170
- // score is updated.
2171
- const firstRow = SmoSelection.selectionFromSelector(
2172
- this.storeScore, {
2173
- staff: 0, measure: m.selector.measure, voice: m.selector.voice, tick: m.selector.tick, pitches: [] }
2174
- )
2175
- SmoOperation.setMeasureFormat(this.storeScore, firstRow!, format);
2176
- }
2177
- const alt = this._getEquivalentSelection(m);
2178
- SmoOperation.setMeasureFormat(this.storeScore, alt!, format);
2179
- if (isPart) {
2180
- alt!.staff.partInfo.measureFormatting[m.measure.measureNumber.measureIndex] = new SmoMeasureFormat(format);
2181
- }
2182
- });
2183
- this._renderRectangle(fromSelector, toSelector);
2184
- return this.renderer.updatePromise();
2185
- }
2186
- /**
2187
- * Remove system breaks from the measure formatting for selected measures
2188
- * @returns
2189
- */
2190
- removeSystemBreaks(): Promise<any> {
2191
- const label = 'set measure format';
2192
- const fromSelector = this.tracker.getExtremeSelection(-1).selector;
2193
- const toSelector = this.tracker.getExtremeSelection(1).selector;
2194
- const measureSelections = this.tracker.getSelectedMeasures();
2195
- // If the formatting is on a part, preserve it in the part's info
2196
- const isPart = this.isPartExposed();
2197
- measureSelections.forEach((m) => {
2198
- this._undoColumn(label, m.selector.measure);
2199
- const format = new SmoMeasureFormat(m.measure.format);
2200
- format.systemBreak = false;
2201
- SmoOperation.setMeasureFormat(this.score, m, format);
2202
- if (isPart) {
2203
- m.staff.partInfo.measureFormatting[m.measure.measureNumber.measureIndex] = new SmoMeasureFormat(format);
2204
- }
2205
- const alt = this._getEquivalentSelection(m);
2206
- SmoOperation.setMeasureFormat(this.storeScore, alt!, format);
2207
- if (isPart) {
2208
- alt!.staff.partInfo.measureFormatting[m.measure.measureNumber.measureIndex] = new SmoMeasureFormat(format);
2209
- }
2210
- });
2211
- this._renderRectangle(fromSelector, toSelector);
2212
- return this.renderer.updatePromise();
2213
- }
2214
- renumberMeasures(measureIndex: number, displayIndex: number) {
2215
- this.score.updateRenumberingMap(measureIndex, displayIndex);
2216
- this.storeScore.updateRenumberingMap(measureIndex, displayIndex);
2217
- const mmsel = SmoSelection.measureSelection(this.score, 0, measureIndex);
2218
- if (mmsel) {
2219
- this._renderChangedMeasures([mmsel]);
2220
- }
2221
- return this.renderer.updatePromise();
2222
- }
2223
- /**
2224
- * Play the music from the starting selection
2225
- * @returns
2226
- */
2227
- async playFromSelection() {
2228
- var mm = this.tracker.getExtremeSelection(-1);
2229
- if (SuiAudioPlayer.playingInstance && SuiAudioPlayer.playingInstance.paused) {
2230
- SuiAudioPlayer.playingInstance.play();
2231
- return;
2232
- }
2233
- if (SuiAudioPlayer.playing) {
2234
- return;
2235
- }
2236
- new SuiAudioPlayer({ audioAnimation: this.audioAnimation, score: this.score, startIndex: mm.selector.measure, view: this }).play();
2237
- }
2238
- stopPlayer() {
2239
- SuiAudioPlayer.stopPlayer();
2240
- }
2241
- pausePlayer() {
2242
- SuiAudioPlayer.pausePlayer();
2243
- }
2244
-
2245
- /**
2246
- * Proxy calls to move the tracker parameters according to the
2247
- * rules of the 'Home' key (depending on shift/ctrl/alt)
2248
- * @param ev
2249
- * @returns
2250
- */
2251
- async moveHome(ev: KeyEvent): Promise<any> {
2252
- this.tracker.moveHome(ev);
2253
- await this.renderer.updatePromise();
2254
- }
2255
- /**
2256
- * Proxy calls to move the tracker parameters according to the
2257
- * rules of the 'End' key (depending on shift/ctrl/alt)
2258
- * @param ev
2259
- * @returns
2260
- */
2261
- async moveEnd(ev: KeyEvent): Promise<any> {
2262
- this.tracker.moveEnd(ev);
2263
- await this.renderer.updatePromise();
2264
- }
2265
- /**
2266
- * Grow the current selection by one to the left, if possible
2267
- * @param ev
2268
- * @returns
2269
- */
2270
- async growSelectionLeft(): Promise<any> {
2271
- this.tracker.growSelectionLeft();
2272
- await this.renderer.updatePromise();
2273
- }
2274
- /**
2275
- * Grow the current selection by one to the right, if possible
2276
- * @param ev
2277
- * @returns
2278
- */
2279
- async growSelectionRight(): Promise<any> {
2280
- this.tracker.growSelectionRight();
2281
- await this.renderer.updatePromise();
2282
- }
2283
- /**
2284
- * Select the next tabbable modifier near one of the selected notes
2285
- * @param keyEv
2286
- * @returns
2287
- */
2288
- async advanceModifierSelection(keyEv: KeyEvent): Promise<any> {
2289
- this.tracker.advanceModifierSelection(keyEv);
2290
- await this.renderer.updatePromise();
2291
- }
2292
- /**
2293
- * Select the next entire measure, if possible
2294
- * @returns
2295
- */
2296
- async growSelectionRightMeasure(): Promise<any> {
2297
- this.tracker.growSelectionRightMeasure();
2298
- await this.renderer.updatePromise();
2299
- }
2300
- /**
2301
- * Advance cursor forwards, if possible
2302
- * @param ev
2303
- * @returns
2304
- */
2305
- async moveSelectionRight(): Promise<any> {
2306
- this.tracker.moveSelectionRight();
2307
- await this.renderer.updatePromise();
2308
- }
2309
- /**
2310
- * Advance cursor backwards, if possible
2311
- * @param ev
2312
- * @returns
2313
- */
2314
- async moveSelectionLeft(): Promise<any> {
2315
- this.tracker.moveSelectionLeft();
2316
- await this.renderer.updatePromise();
2317
- }
2318
- /**
2319
- * Advance cursor back entire measure, if possible
2320
- * @returns
2321
- */
2322
- async moveSelectionLeftMeasure(): Promise<any> {
2323
- this.tracker.moveSelectionLeftMeasure();
2324
- await this.renderer.updatePromise();
2325
- }
2326
- /**
2327
- * Advance cursor forward one measure, if possible
2328
- * @returns
2329
- */
2330
- async moveSelectionRightMeasure(): Promise<any> {
2331
- this.tracker.moveSelectionRightMeasure();
2332
- await this.renderer.updatePromise();
2333
- }
2334
- /**
2335
- * Move cursor to a higher pitch in the current chord, with wrap
2336
- * @returns
2337
- */
2338
- async moveSelectionPitchUp(): Promise<any> {
2339
- this.tracker.moveSelectionPitchUp();
2340
- await this.renderer.updatePromise();
2341
- }
2342
- /**
2343
- * Move cursor to a lower pitch in the current chord, with wrap
2344
- */
2345
- async moveSelectionPitchDown(): Promise<any> {
2346
- this.tracker.moveSelectionPitchDown();
2347
- await this.renderer.updatePromise();
2348
- }
2349
- /**
2350
- * Move cursor up a staff in the system, if possible
2351
- * @returns
2352
- */
2353
- async moveSelectionUp(): Promise<any> {
2354
- this.tracker.moveSelectionUp();
2355
- await this.renderer.updatePromise();
2356
- }
2357
- /**
2358
- * Move cursor down a staff in the system, if possible
2359
- * @returns
2360
- */
2361
- async moveSelectionDown(): Promise<any> {
2362
- this.tracker.moveSelectionDown();
2363
- await this.renderer.updatePromise();
2364
- }
2365
- /**
2366
- * Set the current suggestions (hover element) as the selection
2367
- * @returns
2368
- */
2369
- async selectSuggestion(evData: KeyEvent): Promise<any> {
2370
- this.tracker.selectSuggestion(evData);
2371
- await this.renderer.updatePromise();
2372
- }
2373
- /**
2374
- * Find an element at the given box, and make it the current selection
2375
- * */
2376
- async intersectingArtifact(evData: SvgBox): Promise<any> {
2377
- this.tracker.intersectingArtifact(evData);
2378
- await this.renderer.updatePromise();
2379
- }
2380
- }
1
+ // [Smoosic](https://github.com/AaronDavidNewman/Smoosic)
2
+ // Copyright (c) Aaron David Newman 2021.
3
+ import { toRaw } from 'vue';
4
+ import { isFullSaveFormat } from './scoreChangeState';
5
+ import { SuiScoreView, updateStaffModifierFunc } from './scoreView';
6
+ import { SmoScore, engravingFontType } from '../../smo/data/score';
7
+ import { SmoSystemStaffParams, SmoSystemStaff } from '../../smo/data/systemStaff';
8
+ import { SmoPartInfo } from '../../smo/data/partInfo';
9
+ import { SmoMeasure } from '../../smo/data/measure';
10
+ import { SmoNote } from '../../smo/data/note';
11
+ import { KeyEvent, SvgBox, Pitch, PitchLetter, RemoveElementLike, ElementLike } from '../../smo/data/common';
12
+ import { SmoRenderConfiguration } from './configuration';
13
+ import { SmoSystemGroup, SmoPageLayout, SmoGlobalLayout, SmoLayoutManager, SmoAudioPlayerSettings,
14
+ SmoScorePreferences, SmoScoreInfo } from '../../smo/data/scoreModifiers';
15
+ import { SmoTextGroup } from '../../smo/data/scoreText';
16
+ import { SmoDynamicText, SmoNoteModifierBase, SmoGraceNote, SmoArticulation,
17
+ SmoOrnament, SmoLyric, SmoMicrotone, SmoArpeggio, SmoArpeggioType, SmoClefChange,
18
+ SmoTabNote} from '../../smo/data/noteModifiers';
19
+ import { SmoTempo, SmoVolta, SmoBarline, SmoRepeatSymbol,
20
+ SmoRehearsalMark, SmoMeasureFormat, SmoTimeSignature } from '../../smo/data/measureModifiers';
21
+ import { UndoBuffer } from '../../smo/xform/undo';
22
+ import {
23
+ SmoOperation, createStaffModifierType, MakeTupletOperation
24
+ } from '../../smo/xform/operations';
25
+ import { BatchSelectionOperation } from '../../smo/xform/operations';
26
+ import { smoSerialize } from '../../common/serializationHelpers';
27
+ import { FontInfo } from '../../common/vex';
28
+ import { SmoMusic } from '../../smo/data/music';
29
+ import { SuiOscillator } from '../audio/oscillator';
30
+ import { XmlToSmo } from '../../smo/mxml/xmlToSmo';
31
+ import { SuiAudioPlayer } from '../audio/player';
32
+ import { SuiXhrLoader } from '../../ui/fileio/xhrLoader';
33
+ import { SmoSelection, SmoSelector } from '../../smo/xform/selections';
34
+ import { StaffModifierBase,
35
+ SmoInstrument, SmoInstrumentParams, SmoStaffTextBracket, SmoTabStave } from '../../smo/data/staffModifiers';
36
+ import { SuiPiano } from './piano';
37
+ import { SvgHelpers } from './svgHelpers';
38
+ import { parseJsonText } from 'typescript';
39
+ import {NoteEntryCaret} from "./NoteEntryCaret";
40
+ declare var $: any;
41
+ declare var SmoConfig: SmoRenderConfiguration;
42
+
43
+
44
+ /**
45
+ * MVVM-like operations on the displayed score.
46
+ *
47
+ * All operations that can be performed on a 'live' score go through this
48
+ * module. It maps the score view to the actual score and makes sure the
49
+ * model and view stay in sync.
50
+ *
51
+ * Because this object operates on the current selections,
52
+ * all operations return promise so applications can wait for the
53
+ * operation to complete and update the selection list.
54
+ * @category SuiRender
55
+ */
56
+ export class SuiScoreViewOperations extends SuiScoreView {
57
+ constructor(config: SmoRenderConfiguration, score: SmoScore, undoBuffer: UndoBuffer) {
58
+ super(config, score, undoBuffer);
59
+ }
60
+
61
+ /**
62
+ * Add a new text group to the score
63
+ * @param textGroup a new text group
64
+ * @returns
65
+ */
66
+ async addTextGroup(textGroup: SmoTextGroup): Promise<void> {
67
+ const altNew = SmoTextGroup.deserializePreserveId(textGroup.serialize());
68
+ const isPartExposed = this.isPartExposed();
69
+ let selector = textGroup.selector ?? SmoSelector.default;
70
+ const partInfo = this.score.staves[0].partInfo;
71
+ const bufType = isPartExposed && partInfo.preserveTextGroups
72
+ ? UndoBuffer.bufferTypes.PART_MODIFIER : UndoBuffer.bufferTypes.SCORE_MODIFIER;
73
+ if (bufType === UndoBuffer.bufferTypes.PART_MODIFIER) {
74
+ selector.staff = this.staffMap[0];
75
+ }
76
+ this.storeUndo.addBuffer('remove text group', bufType,
77
+ selector, textGroup, UndoBuffer.bufferSubtypes.ADD);
78
+ if (isPartExposed && partInfo.preserveTextGroups) {
79
+ this.score.staves[0].partInfo.updateTextGroup(textGroup, true);
80
+ const partInfo = this.storeScore.staves[this._getEquivalentStaff(0)].partInfo;
81
+ partInfo.updateTextGroup(altNew, true);
82
+ } else {
83
+ this.score.updateTextGroup(textGroup, true);
84
+ this.storeScore.updateTextGroup(altNew, true);
85
+ }
86
+ await this.renderer.rerenderTextGroups();
87
+ }
88
+
89
+ /**
90
+ * Remove the text group from the score
91
+ * @param textGroup
92
+ * @returns
93
+ */
94
+ async removeTextGroup(textGroup: SmoTextGroup): Promise<void> {
95
+ let selector = textGroup.selector ?? SmoSelector.default;
96
+ let altSelector = JSON.parse(JSON.stringify(selector));
97
+ const partInfo = this.score.staves[0].partInfo;
98
+ const isPartExposed = this.isPartExposed();
99
+ const bufType = isPartExposed && partInfo.preserveTextGroups
100
+ ? UndoBuffer.bufferTypes.PART_MODIFIER : UndoBuffer.bufferTypes.SCORE_MODIFIER;
101
+ let ogText = this.storeScore.textGroups.find((tg) => tg.attrs.id === textGroup.attrs.id);
102
+ if (isPartExposed && partInfo.preserveTextGroups) {
103
+ ogText = partInfo.textGroups.find((tg) => tg.attrs.id === textGroup.attrs.id);
104
+ }
105
+ if (bufType === UndoBuffer.bufferTypes.PART_MODIFIER) {
106
+ selector.staff = this.staffMap[0];
107
+ } else {
108
+ altSelector.staff = this.staffMap[selector.staff];
109
+ }
110
+ if (!ogText) {
111
+ return;
112
+ }
113
+ // We undo buffer using the score location, not the group location
114
+ this.storeUndo.addBuffer('remove text group', bufType,
115
+ altSelector, ogText, UndoBuffer.bufferSubtypes.REMOVE);
116
+ const altGroup = SmoTextGroup.deserializePreserveId(textGroup.serialize());
117
+ if (altGroup.selector) {
118
+ altGroup.selector.staff = altSelector.staff;
119
+ }
120
+ textGroup.elements.forEach((el: ElementLike) => RemoveElementLike(el));
121
+ textGroup.elements = [];
122
+ if (isPartExposed && partInfo.preserveTextGroups) {
123
+ partInfo.updateTextGroup(textGroup, false);
124
+ this.storeScore.staves[this._getEquivalentStaff(0)].partInfo.updateTextGroup(altGroup, false);
125
+ } else {
126
+ this.score.updateTextGroup(textGroup, false);
127
+ this.storeScore.updateTextGroup(altGroup, false);
128
+ }
129
+ await this.renderer.rerenderTextGroups();
130
+ }
131
+
132
+ /**
133
+ * UPdate an existing text group. The original is passed in, because since TG not tied to a musical
134
+ * element, we need to find the one we're updating.
135
+ * @param oldVersion
136
+ * @param newVersion
137
+ * @returns
138
+ */
139
+ async updateTextGroup(newVersion: SmoTextGroup): Promise<void> {
140
+ const selector = newVersion.selector ?? SmoSelector.default; // for score view
141
+ const altSelector = JSON.parse(JSON.stringify(selector)); // for full score
142
+ const isPartExposed = this.isPartExposed();
143
+ const partInfo = this.score.staves[0].partInfo;
144
+
145
+ // If this text was attached to a staff that is not in the part, ignore the update
146
+ if (newVersion.selector && newVersion.selector.staff >= this.score.staves.length) {
147
+ return;
148
+ }
149
+ // Back up the original score text
150
+ let ogtg = this.storeScore.textGroups.find((tg) => tg.attrs.id === newVersion.attrs.id);
151
+ if (isPartExposed && partInfo.preserveTextGroups) {
152
+ ogtg = partInfo.textGroups.find((tg) => tg.attrs.id === newVersion.attrs.id);
153
+ }
154
+ if (!ogtg) {
155
+ // there is nothing to update, return.
156
+ return;
157
+ }
158
+ if (ogtg) {
159
+ const bufType = isPartExposed && partInfo.preserveTextGroups
160
+ ? UndoBuffer.bufferTypes.PART_MODIFIER : UndoBuffer.bufferTypes.SCORE_MODIFIER;
161
+ // if this is part text, make sure the undo buffer is associated with the part stave
162
+ // in the full score, so undo works properly
163
+ if (bufType === UndoBuffer.bufferTypes.PART_MODIFIER) {
164
+ altSelector.staff = this.staffMap[0];
165
+ } else {
166
+ altSelector.staff = this.staffMap[selector.staff];
167
+ }
168
+ this.storeUndo.addBuffer('modify text',
169
+ bufType, altSelector, ogtg, UndoBuffer.bufferSubtypes.UPDATE);
170
+ }
171
+ const altNew = SmoTextGroup.deserializePreserveId(newVersion.serialize());
172
+ if (altNew.selector) {
173
+ altNew.selector.staff = altSelector.staff;
174
+ }
175
+ this.score.updateTextGroup(newVersion, true);
176
+ // If this is part text and part-specific text is set,
177
+ // only set the partInfo for the stored score, but don't add to
178
+ // global text.
179
+ if (isPartExposed) {
180
+ // Update the full score copy for this part
181
+ const partInfo = this.storeScore.staves[altSelector.staff].partInfo;
182
+ partInfo.updateTextGroup(altNew, true);
183
+ const displayPartInfo = this.score.staves[0].partInfo;
184
+ displayPartInfo.updateTextGroup(newVersion, true);
185
+ } else {
186
+ this.storeScore.updateTextGroup(altNew, true);
187
+ }
188
+ // TODO: only render the one TG.
189
+ await this.renderer.rerenderTextGroups();
190
+ // return this.renderer.updatePromise();
191
+ }
192
+ /**
193
+ * load an mxml score remotely, return a promise that
194
+ * completes when the file is loaded
195
+ * @param url where to find the xml file
196
+ * @returns
197
+ */
198
+ async loadRemoteXml(url: string): Promise<any> {
199
+ const req = new SuiXhrLoader(url);
200
+ const self = this;
201
+ // Shouldn't we return promise of actually displaying the score?
202
+ await req.loadAsync();
203
+ const parser = new DOMParser();
204
+ const xml = parser.parseFromString(req.value, 'text/xml');
205
+ const score = XmlToSmo.convert(xml);
206
+ score.layoutManager!.zoomToWidth($('body').width());
207
+ await self.changeScore(score);
208
+ }
209
+ /**
210
+ * load a remote score in SMO format
211
+ * @param url url to find the score
212
+ * @returns
213
+ */
214
+ async loadRemoteJson(url: string) : Promise<any> {
215
+ const req = new SuiXhrLoader(url);
216
+ await req.loadAsync();
217
+ const score = SmoScore.deserialize(req.value);
218
+ await this.changeScore(score);
219
+ }
220
+ /**
221
+ * Load a remote score, return promise when it's been loaded
222
+ * from afar.
223
+ * @param pref
224
+ * @returns
225
+ */
226
+ async loadRemoteScore(url: string): Promise<any> {
227
+ if (url.endsWith('xml') || url.endsWith('mxl')) {
228
+ return this.loadRemoteXml(url);
229
+ } else {
230
+ return this.loadRemoteJson(url);
231
+ }
232
+ }
233
+ async updateAudioSettings(pref: SmoAudioPlayerSettings) {
234
+ this._undoScorePreferences('Update preferences');
235
+ this.score.audioSettings = pref;
236
+ this.storeScore.audioSettings = new SmoAudioPlayerSettings(pref);
237
+ // No rendering to be done
238
+ return this.renderer.updatePromise();
239
+ }
240
+ /**
241
+ * Global settings that control how the score editor behaves
242
+ * @param pref
243
+ * @returns
244
+ */
245
+ async updateScorePreferences(pref: SmoScorePreferences): Promise<void> {
246
+ this._undoScorePreferences('Update preferences');
247
+ const oldXpose = this.score.preferences.transposingScore;
248
+ const curXpose = pref.transposingScore;
249
+ const currentLayout = this.score.layoutManager?.getGlobalLayout();
250
+ const oldDisplayMode = currentLayout ? currentLayout.displayMode : 'vertical';
251
+ this.score.updateScorePreferences(new SmoScorePreferences(pref));
252
+ this.storeScore.updateScorePreferences(new SmoScorePreferences(pref));
253
+ const newLayout = this.score.layoutManager?.getGlobalLayout();
254
+ const displayMode = newLayout ? newLayout.displayMode : 'vertical';
255
+ if (oldDisplayMode !== displayMode) {
256
+ this.renderer.setViewport();
257
+ }
258
+ if (curXpose === false && oldXpose === true) {
259
+ this.score.setNonTransposing();
260
+ this.storeScore.setNonTransposing();
261
+ } else if (curXpose === true && oldXpose === false) {
262
+ this.score.setTransposing();
263
+ this.storeScore.setTransposing();
264
+ }
265
+ this.renderer.setDirty();
266
+ return this.renderer.updatePromise();
267
+ }
268
+ /**
269
+ * Update information about the score, composer etc.
270
+ * @param scoreInfo
271
+ * @returns
272
+ */
273
+ async updateScoreInfo(scoreInfo: SmoScoreInfo): Promise<void> {
274
+ this._undoScorePreferences('Update preferences');
275
+ this.score.scoreInfo = scoreInfo;
276
+ this.storeScore.scoreInfo = JSON.parse(JSON.stringify(scoreInfo));
277
+ this.refreshScoreName();
278
+ return this.renderer.updatePromise()
279
+ }
280
+ async addRemoveArpeggio(code: SmoArpeggioType) {
281
+ await this.modifyCurrentSelections('add/remove addRemoveArpeggio',
282
+ (score, selections) => {
283
+ selections.forEach((sel) => {
284
+ if (sel.note) {
285
+ if (code === 'none') {
286
+ sel.note.arpeggio = undefined;
287
+ } else {
288
+ sel.note.arpeggio = new SmoArpeggio({ type: code });
289
+ }
290
+ }
291
+ });
292
+ });
293
+ }
294
+ /**
295
+ * A clef change mid-measure (clefNote)
296
+ * @param clef
297
+ */
298
+ async addRemoveClefChange(clef: SmoClefChange) {
299
+ await this.modifyCurrentSelections('add/remove addRemoveClefChange',
300
+ (score, selections) => {
301
+ selections.forEach((sel) => {
302
+ const measureClef = sel.measure.clef;
303
+ if (sel.note) {
304
+ if (measureClef === clef.clef) {
305
+ sel.note.clefNote = null;
306
+ } else {
307
+ sel.note.clefNote = clef;
308
+ }
309
+ }
310
+ });
311
+ });
312
+ // Make sure all the notes in the measure after the change are updated.
313
+ // We only need to do this for the displayed score, not the storeScore.
314
+ SmoSelection.getMeasureList(this.tracker.selections).forEach((ms) => {
315
+ ms.measure.updateClefChangeNotes();
316
+ })
317
+ }
318
+ /**
319
+ * Modify the dynamics assoicated with the specific selection
320
+ * @param selection
321
+ * @param dynamic
322
+ * @returns
323
+ */
324
+ async addDynamic(selection: SmoSelection, dynamic: SmoDynamicText): Promise<void> {
325
+ await this.modifySelection('add dynamic', selection, (score, selections) => {
326
+ SmoOperation.addDynamic(selections[0], dynamic);
327
+ });
328
+ }
329
+
330
+ /**
331
+ * Remove dynamics from the current selection
332
+ * @param dynamic
333
+ * @returns
334
+ */
335
+ async removeDynamic(dynamic: SmoDynamicText): Promise<void> {
336
+ const measures = SmoSelection.getMeasureList(this.tracker.selections);
337
+ for (let j = 0; j < this.tracker.selections.length; ++j) {
338
+ const selection = this.tracker.selections[j];
339
+ if (selection) {
340
+ const equiv = this._getEquivalentSelection(selection);
341
+ if (equiv?.note && selection.note) {
342
+ const altModifiers = equiv.note.getModifiers('SmoDynamicText');
343
+ SmoOperation.removeDynamic(selection, dynamic);
344
+ if (altModifiers.length) {
345
+ SmoOperation.removeDynamic(equiv, altModifiers[0] as SmoDynamicText);
346
+ }
347
+ }
348
+ }
349
+ }
350
+ this._renderChangedMeasures(measures);
351
+ await this.renderer.updatePromise()
352
+ }
353
+ /**
354
+ * we never really delete a note, but we will convert it into a rest and if it's
355
+ * already a rest we will try to hide it.
356
+ * Operates on current selections
357
+ * */
358
+ async deleteNote(): Promise<void> {
359
+ const measureSelections = this.undoTrackerMeasureSelections('delete note');
360
+ this.tracker.selections.forEach((sel) => {
361
+ if (sel.note) {
362
+
363
+ const altSel = this._getEquivalentSelection(sel);
364
+
365
+ // If this is a chord and a specific pitch is selected, just remove that pitch
366
+ const pitchIndex = this.tracker.getPitchIndex();
367
+ if (sel.note.pitches.length > 1 && pitchIndex >= 0 && pitchIndex < sel.note.pitches.length) {
368
+ sel.note.pitches.splice(pitchIndex, 1);
369
+ altSel!.note!.pitches.splice(pitchIndex, 1);
370
+ SmoNote.sortPitches(sel.note);
371
+ SmoNote.sortPitches(altSel!.note! as SmoNote);
372
+ this.tracker.clearPitchIndex();
373
+ return; // skip rest/hide logic for this selection
374
+ }
375
+
376
+ // set the pitch to be a good position for the rest
377
+ const pitch = JSON.parse(JSON.stringify(
378
+ SmoMeasure.defaultPitchForClef[sel.measure.clef]));
379
+ const altPitch = JSON.parse(JSON.stringify(
380
+ SmoMeasure.defaultPitchForClef[altSel!.measure.clef]));
381
+ sel.note.pitches = [pitch];
382
+ altSel!.note!.pitches = [altPitch];
383
+
384
+ // If the note is a note, make it into a rest. If the note is a rest already,
385
+ // make it invisible. If it is invisible already, make it back into a rest.
386
+ if (sel.note.isRest() && !sel.note.isHidden()) {
387
+ sel.note.makeHidden(true);
388
+ altSel!.note!.makeHidden(true);
389
+ } else {
390
+ sel.note.clearArticulations();
391
+ sel.note.makeRest();
392
+ altSel!.note!.makeRest();
393
+ altSel!.note!.clearArticulations();
394
+ sel.note.makeHidden(false);
395
+ altSel!.note!.makeHidden(false);
396
+ }
397
+ }
398
+ });
399
+ this._renderChangedMeasures(measureSelections);
400
+ await this.renderer.updatePromise()
401
+ }
402
+ /**
403
+ * The lyric editor moves around, so we can't depend on the tracker for the
404
+ * correct selection. We get it directly from the editor.
405
+ *
406
+ * @param selector - the selector of the note with the lyric to remove
407
+ * @param lyric - a copy of the lyric to remove. We use the verse, parser to identify it
408
+ * @returns render promise
409
+ */
410
+ async removeLyric(selector: SmoSelector, lyric: SmoLyric): Promise<void> {
411
+ const selection = SmoSelection.noteFromSelector(this.score, selector);
412
+ if (selection === null) {
413
+ return;
414
+ }
415
+ this._undoSelection('remove lyric', selection);
416
+ selection.note!.removeLyric(lyric);
417
+ const equiv = this._getEquivalentSelection(selection);
418
+ const storeLyric = equiv!.note!.getLyricForVerse(lyric.verse, lyric.parser);
419
+ if (typeof (storeLyric) !== 'undefined') {
420
+ equiv!.note!.removeLyric(lyric);
421
+ }
422
+ this.renderer.addToReplaceQueue(selection);
423
+ lyric.deleted = true;
424
+ await this.renderer.updatePromise();
425
+ }
426
+
427
+ /**
428
+ * @param selector where to add or update the lyric
429
+ * @param lyric a copy of the lyric to remove
430
+ * @returns
431
+ */
432
+ async addOrUpdateLyric(selector: SmoSelector, lyric: SmoLyric): Promise<void> {
433
+ const selection = SmoSelection.noteFromSelector(this.score, selector);
434
+ if (selection === null) {
435
+ return;
436
+ }
437
+ this._undoSelection('update lyric', selection);
438
+ selection.note!.addLyric(lyric);
439
+ const equiv = this._getEquivalentSelection(selection);
440
+ const altLyric = SmoNoteModifierBase.deserialize(lyric.serialize() as any) as SmoLyric;
441
+ equiv!.note!.addLyric(altLyric);
442
+ this.renderer.addToReplaceQueue(selection);
443
+ await this.renderer.updatePromise();
444
+ }
445
+
446
+ /**
447
+ * @param selector the selector of the note with the annotation to remove
448
+ * @param annotation a copy of the annotation to remove. We use the verse, parser to identify it
449
+ * @returns render promise
450
+ */
451
+ async removeAnnotation(selector: SmoSelector, annotation: SmoLyric): Promise<void> {
452
+ const selection = SmoSelection.noteFromSelector(this.score, selector);
453
+ if (selection === null) {
454
+ return;
455
+ }
456
+ this._undoSelection('remove annotation', selection);
457
+ selection.note!.removeAnnotations(annotation);
458
+ const equiv = this._getEquivalentSelection(selection);
459
+ const storeAnnotation = equiv!.note!.getLyricForVerse(annotation.verse, annotation.parser);
460
+ if (typeof (storeAnnotation) !== 'undefined') {
461
+ equiv!.note!.removeAnnotations(annotation);
462
+ }
463
+ this.renderer.addToReplaceQueue(selection);
464
+ annotation.deleted = true;
465
+ await this.renderer.updatePromise();
466
+ }
467
+
468
+ /**
469
+ * @param selector where to add or update the annotation
470
+ * @param annotation a copy of the annotation to add/update
471
+ * @returns
472
+ */
473
+ async addOrUpdateAnnotation(selector: SmoSelector, annotation: SmoLyric): Promise<void> {
474
+ const selection = SmoSelection.noteFromSelector(this.score, selector);
475
+ if (selection === null) {
476
+ return;
477
+ }
478
+ this._undoSelection('update annotation', selection);
479
+ selection.note!.addAnnotation(annotation);
480
+ const equiv = this._getEquivalentSelection(selection);
481
+ const altAnnotation = SmoNoteModifierBase.deserialize(annotation.serialize() as any) as SmoLyric;
482
+ equiv!.note!.addAnnotation(altAnnotation);
483
+ this.renderer.addToReplaceQueue(selection);
484
+ await this.renderer.updatePromise();
485
+ }
486
+
487
+ /**
488
+ * Delete all the notes for the currently selected voice
489
+ * @returns
490
+ */
491
+ async depopulateVoice(): Promise<void> {
492
+ const measureSelections = this.undoTrackerMeasureSelections('depopulate voice');
493
+ measureSelections.forEach((selection) => {
494
+ const ix = selection.measure.getActiveVoice();
495
+ if (ix !== 0) {
496
+ SmoOperation.depopulateVoice(selection, ix);
497
+ const equiv = this._getEquivalentSelection(selection);
498
+ SmoOperation.depopulateVoice(equiv!, ix);
499
+ }
500
+ });
501
+ SmoOperation.setActiveVoice(this.score, 0);
502
+ this._renderChangedMeasures(measureSelections);
503
+ await this.renderer.updatePromise();
504
+ }
505
+ /**
506
+ * Change the active voice in a multi-voice measure.
507
+ * @param index
508
+ * @returns
509
+ */
510
+ _changeActiveVoice(index: number): SmoSelection[] {
511
+ const measuresToAdd: SmoSelection[] = [];
512
+ const measureSelections = SmoSelection.getMeasureList(this.tracker.selections);
513
+ measureSelections.forEach((measureSelection) => {
514
+ if (index === measureSelection.measure.voices.length) {
515
+ measuresToAdd.push(measureSelection);
516
+ }
517
+ });
518
+ return measuresToAdd;
519
+ }
520
+ /**
521
+ * Populate a new voice with default notes
522
+ * @param index the voice to populate
523
+ * @returns
524
+ */
525
+ async populateVoice(index: number): Promise<void> {
526
+ const measuresToAdd = this._changeActiveVoice(index);
527
+ if (measuresToAdd.length === 0) {
528
+ SmoOperation.setActiveVoice(this.score, index);
529
+ this.tracker.selectActiveVoice();
530
+ return this.renderer.updatePromise();
531
+ }
532
+ measuresToAdd.forEach((selection) => {
533
+ this._undoSelection('popualteVoice', selection);
534
+ SmoOperation.populateVoice(selection, index);
535
+ const equiv = this._getEquivalentSelection(selection);
536
+ SmoOperation.populateVoice(equiv!, index);
537
+ });
538
+ SmoOperation.setActiveVoice(this.score, index);
539
+ this._renderChangedMeasures(measuresToAdd);
540
+ await this.renderer.updatePromise();
541
+ this.tracker.selectActiveVoice();
542
+ }
543
+ async swapVoices(voice1: number, voice2: number): Promise<void> {
544
+ const selections = this.tracker.getSelectedMeasures();
545
+ const altSelections = this._getEquivalentSelections(selections);
546
+ SmoOperation.swapVoice(selections, voice1, voice2);
547
+ SmoOperation.swapVoice(altSelections, voice1, voice2);
548
+ this._renderChangedMeasures(selections);
549
+ }
550
+ /**
551
+ * Assign an instrument to a set of measures
552
+ * @param instrument the instrument to assign to the selections
553
+ * @param selections
554
+ * @returns
555
+ */
556
+ async changeInstrument(instrument: SmoInstrument, selections: SmoSelection[]): Promise<void> {
557
+ if (typeof (selections) === 'undefined') {
558
+ selections = this.tracker.selections;
559
+ }
560
+ this._undoSelections('change instrument', selections);
561
+ const altSelections = this._getEquivalentSelections(selections);
562
+ SmoOperation.changeInstrument(instrument, this.score, selections);
563
+ SmoOperation.changeInstrument(instrument, this.storeScore, altSelections);
564
+ this._renderChangedMeasures(selections);
565
+ await this.renderer.updatePromise();
566
+ }
567
+ /**
568
+ * Set the time signature for a selection
569
+ * @param timeSignature actual time signature
570
+ */
571
+ async setTimeSignature(timeSignature: SmoTimeSignature): Promise<void> {
572
+ this._undoScore('Set time signature');
573
+ const selections = this.tracker.selections;
574
+ const altSelections = this._getEquivalentSelections(selections);
575
+ SmoOperation.setTimeSignature(this.score, selections, timeSignature);
576
+ SmoOperation.setTimeSignature(this.storeScore, altSelections, timeSignature);
577
+ this._renderChangedMeasures(SmoSelection.getMeasureList(this.tracker.selections));
578
+ return this.renderer.updatePromise();
579
+ }
580
+ /**
581
+ * Move selected staff up or down in the score.
582
+ * @param index direction to move
583
+ * @returns
584
+ */
585
+ async moveStaffUpDown(index: number): Promise<void> {
586
+ this._undoScore('re-order staves');
587
+ // Get staff to move
588
+ const selection = this._getEquivalentSelection(this.tracker.selections[0]);
589
+ // Make the move in the model, and reset the view so we can see the new
590
+ // arrangement
591
+ SmoOperation.moveStaffUpDown(this.storeScore, selection!, index);
592
+ this.viewAll();
593
+ await this.renderer.updatePromise();
594
+ }
595
+ /**
596
+ * Update the staff group for a score, which determines how the staves
597
+ * are justified and bracketed
598
+ * @param staffGroup
599
+ */
600
+ async addOrUpdateStaffGroup(staffGroup: SmoSystemGroup): Promise<void> {
601
+ this._undoScore('group staves');
602
+ // Assume that the view is now set to full score
603
+ this.score.addOrReplaceSystemGroup(staffGroup);
604
+ this.storeScore.addOrReplaceSystemGroup(staffGroup);
605
+ this.renderer.setDirty();
606
+ await this.renderer.updatePromise();
607
+ }
608
+ async removeStaffGroup(staffGroup: SmoSystemGroup):Promise<void> {
609
+ this._undoScore('ungroup staves');
610
+ this.score.removeSystemGroup(staffGroup);
611
+ this.storeScore.removeSystemGroup(staffGroup);
612
+ this.renderer.setDirty();
613
+ await this.renderer.updatePromise();
614
+ }
615
+ async clearSystemGroups(): Promise<void>{
616
+ this._undoScore('clear staff groups');
617
+ this.score.clearSystemGroups();
618
+ this.storeScore.clearSystemGroups();
619
+ this.renderer.setDirty();
620
+ await this.renderer.updatePromise();
621
+ }
622
+ async updateTabStave(tabStave: SmoTabStave) {
623
+ const selections = SmoSelection.getMeasuresBetween(this.score, tabStave.startSelector, tabStave.endSelector);
624
+ const altSelections = this._getEquivalentSelections(selections);
625
+ if (selections.length === 0) {
626
+ return;
627
+ }
628
+ this._undoSelections('updateTabStave', selections);
629
+ const staff: number = selections[0].selector.staff;
630
+ const altStaff = altSelections[0].selector.staff;
631
+ const altTabStave = new SmoTabStave(tabStave.serialize());
632
+ altTabStave.startSelector.staff = altStaff;
633
+ altTabStave.endSelector.staff = altStaff;
634
+ altTabStave.attrs.id = tabStave.attrs.id;
635
+ this.score.staves[staff].updateTabStave(tabStave);
636
+ this.storeScore.staves[altStaff].updateTabStave(altTabStave);
637
+ this._renderChangedMeasures(SmoSelection.getMeasureList(this.tracker.selections));
638
+ await this.renderer.updatePromise();
639
+ }
640
+ async removeTabStave() {
641
+ const selections = this.tracker.selections;
642
+ const altSelections = this._getEquivalentSelections(selections);
643
+ if (selections.length === 0) {
644
+ return;
645
+ }
646
+ this._undoSelections('updateTabStave', selections);
647
+ const stavesToRemove: SmoTabStave[] = [];
648
+ const altStavesToRemove: SmoTabStave[] = [];
649
+ const added: Record<string, SmoTabStave> = {};
650
+ selections.forEach((sel, ix) => {
651
+ const altSel = altSelections[ix];
652
+ const tabStave = sel.staff.getTabStaveForMeasure(sel.selector);
653
+ const altTabStave = altSel.staff.getTabStaveForMeasure(altSel.selector);
654
+ if (tabStave && altTabStave) {
655
+ if (!added[tabStave.attrs.id]) {
656
+ added[tabStave.attrs.id] = tabStave;
657
+ stavesToRemove.push(tabStave);
658
+ altStavesToRemove.push(altTabStave);
659
+ }
660
+ }
661
+ });
662
+ selections[0].staff.removeTabStaves(stavesToRemove);
663
+ altSelections[0].staff.removeTabStaves(altStavesToRemove);
664
+ this._renderChangedMeasures(SmoSelection.getMeasureList(this.tracker.selections));
665
+ await this.renderer.updatePromise();
666
+ }
667
+ /**
668
+ * Update tempo for all or part of the score
669
+ * @param measure the measure with the tempo. Tempo is measure-wide parameter
670
+ * @param scoreMode if true, update whole score. Else selections
671
+ * @returns
672
+ */
673
+ async updateTempoScore(measure: SmoMeasure, tempo: SmoTempo, scoreMode: boolean, selectionMode: boolean): Promise<void> {
674
+ let measureIndex = 0;
675
+ const originalTempo = new SmoTempo(measure.tempo);
676
+ this._undoColumn('update tempo', measure.measureNumber.measureIndex);
677
+ let startMeasure = measure.measureNumber.measureIndex;
678
+ let endMeasure = this.score.staves[0].measures.length;
679
+ let displayed = false;
680
+ if (selectionMode) {
681
+ const endSel = this.tracker.getExtremeSelection(1);
682
+ if (endSel.selector.measure > startMeasure) {
683
+ endMeasure = endSel.selector.measure;
684
+ }
685
+ }
686
+ // If we are only changing the position of the text, it only affects the tempo measure.
687
+ if (SmoTempo.eq(originalTempo, tempo) && tempo.yOffset !== originalTempo.yOffset && endMeasure > startMeasure) {
688
+ endMeasure = startMeasure + 1;
689
+ }
690
+ for (measureIndex = startMeasure; measureIndex < endMeasure; ++measureIndex) {
691
+ if (!scoreMode && !selectionMode) {
692
+ // If not whole score or selections, change until the tempo doesn't match previous measure's tempo (next tempo change)
693
+ const compMeasure = this.score.staves[0].measures[measureIndex];
694
+ if (SmoTempo.eq(originalTempo, compMeasure.tempo) || displayed === false) {
695
+ const sel = SmoSelection.measureSelection(this.score, 0, measureIndex);
696
+ const altSel = SmoSelection.measureSelection(this.storeScore, 0, measureIndex);
697
+ if (sel && sel.measure.tempo.display && !displayed) {
698
+ this.renderer.addToReplaceQueue(sel);
699
+ displayed = true;
700
+ }
701
+ if (sel) {
702
+ SmoOperation.addTempo(this.score, sel, tempo);
703
+ }
704
+ if (altSel) {
705
+ SmoOperation.addTempo(this.storeScore, altSel, tempo);
706
+ }
707
+ } else {
708
+ break;
709
+ }
710
+ } else {
711
+ const sel = SmoSelection.measureSelection(this.score, 0, measureIndex);
712
+ const altSel = SmoSelection.measureSelection(this.storeScore, 0, measureIndex);
713
+ if (sel) {
714
+ SmoOperation.addTempo(this.score, sel, tempo);
715
+ if (!displayed) {
716
+ this.renderer.addToReplaceQueue(sel);
717
+ displayed = true;
718
+ }
719
+ }
720
+ if (altSel) {
721
+ SmoOperation.addTempo(this.storeScore, altSel, tempo);
722
+ }
723
+ }
724
+ }
725
+ await this.renderer.updatePromise();
726
+ }
727
+ async updateTabNote(tabNote: SmoTabNote) {
728
+ const selections = SmoSelection.getMeasuresBetween(this.score,
729
+ this.tracker.getExtremeSelection(-1).selector, this.tracker.getExtremeSelection(1).selector);
730
+ const altSelections = this._getEquivalentSelections(selections);
731
+ this._undoSelections('updateTabNote', selections);
732
+ SmoOperation.updateTabNote(selections, tabNote);
733
+ SmoOperation.updateTabNote(altSelections, tabNote);
734
+ this.renderer.addToReplaceQueue(selections);
735
+ await this.renderer.updatePromise();
736
+ }
737
+ async removeTabNote() {
738
+ const selections = SmoSelection.getMeasuresBetween(this.score,
739
+ this.tracker.getExtremeSelection(-1).selector, this.tracker.getExtremeSelection(1).selector);
740
+ const altSelections = this._getEquivalentSelections(selections);
741
+ this._undoSelections('updateTabNote', selections);
742
+ SmoOperation.removeTabNote(selections);
743
+ SmoOperation.removeTabNote(altSelections);
744
+ this.renderer.addToReplaceQueue(selections);
745
+ await this.renderer.updatePromise();
746
+ }
747
+ /**
748
+ * 'remove' tempo, which means either setting the bars to the
749
+ * default tempo, or the previously-set tempo.
750
+ * @param scoreMode whether to reset entire score
751
+ */
752
+ async removeTempo(measure: SmoMeasure, tempo: SmoTempo, scoreMode: boolean, selectionMode: boolean): Promise<void> {
753
+ const startSelection = this.tracker.selections[0];
754
+ if (startSelection.selector.measure > 0) {
755
+ const measureIx = startSelection.selector.measure - 1;
756
+ const target = startSelection.staff.measures[measureIx];
757
+ const tempo = target.getTempo();
758
+ const newTempo = new SmoTempo(tempo);
759
+ newTempo.display = false;
760
+ this.updateTempoScore(measure, newTempo, scoreMode, selectionMode);
761
+ } else {
762
+ this.updateTempoScore(measure, new SmoTempo(SmoTempo.defaults), scoreMode, selectionMode);
763
+ }
764
+ await this.renderer.updatePromise();
765
+ }
766
+ /**
767
+ * Add a grace note to the selected real notes.
768
+ */
769
+ async addGraceNote(): Promise<void> {
770
+ const selections = this.tracker.selections;
771
+ const measureSelections = this.undoTrackerMeasureSelections('add grace note');
772
+ selections.forEach((selection) => {
773
+ const index = selection.note!.getGraceNotes().length;
774
+ const pitches = JSON.parse(JSON.stringify(selection.note!.pitches));
775
+ const grace = new SmoGraceNote({
776
+ pitches, ticks:
777
+ { numerator: 2048, denominator: 1, remainder: 0 }
778
+ });
779
+ SmoOperation.addGraceNote(selection, grace, index);
780
+
781
+ const altPitches = JSON.parse(JSON.stringify(selection.note!.pitches));
782
+ const altGrace = new SmoGraceNote({
783
+ pitches: altPitches, ticks:
784
+ { numerator: 2048, denominator: 1, remainder: 0 }
785
+ });
786
+ altGrace.attrs.id = grace.attrs.id;
787
+ const altSelection = this._getEquivalentSelection(selection);
788
+ SmoOperation.addGraceNote(altSelection!, altGrace, index);
789
+ });
790
+ this._renderChangedMeasures(measureSelections);
791
+ await this.renderer.updatePromise();
792
+ }
793
+
794
+ /**
795
+ * remove selected grace note
796
+ * @returns
797
+ */
798
+ async removeGraceNote(): Promise<void> {
799
+ const selections = this.tracker.selections;
800
+ const measureSelections = this.undoTrackerMeasureSelections('remove grace note');
801
+ selections.forEach((selection) => {
802
+ // TODO: get the correct offset
803
+ SmoOperation.removeGraceNote(selection, 0);
804
+ const altSel = (this._getEquivalentSelection(selection));
805
+ SmoOperation.removeGraceNote(altSel!, 0);
806
+ });
807
+ this._renderChangedMeasures(measureSelections);
808
+ await this.renderer.updatePromise();
809
+ }
810
+ /**
811
+ * Toggle slash in stem of grace note
812
+ */
813
+ async slashGraceNotes(): Promise<void> {
814
+ const grace = this.tracker.getSelectedGraceNotes();
815
+ const measureSelections = this.undoTrackerMeasureSelections('slash grace note toggle');
816
+ grace.forEach((gn) => {
817
+ SmoOperation.slashGraceNotes(gn);
818
+ if (gn.selection !== null) {
819
+ const altSelection = this._getEquivalentSelection(gn.selection);
820
+ const altGn = this._getEquivalentGraceNote(altSelection!, gn.modifier as SmoGraceNote);
821
+ SmoOperation.slashGraceNotes({
822
+ selection: altSelection, modifier: altGn as any,
823
+ box: SvgBox.default, index: 0
824
+ });
825
+ }
826
+ });
827
+ this._renderChangedMeasures(measureSelections);
828
+ await this.renderer.updatePromise();
829
+ }
830
+ async transposeScore(offset: number): Promise<void> {
831
+ this._undoScore('transpose score');
832
+ SmoOperation.transposeScore(this.score, offset);
833
+ SmoOperation.transposeScore(this.storeScore, offset);
834
+ this.renderer.rerenderAll();
835
+ await this.renderer.updatePromise();
836
+ }
837
+ /**
838
+ * transpose selected notes
839
+ * @param offset 1/2 steps
840
+ * @returns
841
+ */
842
+ async transposeSelections(offset: number): Promise<void> {
843
+ const selections = this.tracker.selections;
844
+ const measureSelections = this.undoTrackerMeasureSelections('transpose');
845
+ const grace = this.tracker.getSelectedGraceNotes();
846
+ if (grace.length) {
847
+ grace.forEach((artifact) => {
848
+ if (artifact.selection !== null && artifact.selection.note !== null) {
849
+ const gn1 = artifact.modifier as SmoGraceNote;
850
+ const index = artifact.selection.note.graceNotes.findIndex((x) => x.attrs.id === gn1.attrs.id);
851
+ const altSelection = this._getEquivalentSelection(artifact.selection);
852
+ if (altSelection && altSelection.note !== null) {
853
+ const gn2 = altSelection.note.graceNotes[index];
854
+ SmoOperation.transposeGraceNotes(altSelection!, [gn2], offset);
855
+ }
856
+ SmoOperation.transposeGraceNotes(artifact.selection, [gn1], offset);
857
+ }
858
+ });
859
+
860
+ } else {
861
+ let isPercussion = false;
862
+ selections.forEach((selected) => {
863
+ SmoOperation.transpose(selected, offset);
864
+ if (selected.staff.getStaffInstrument(selected.selector.measure).isPercussion) {
865
+ isPercussion = true;
866
+ }
867
+ const altSel = this._getEquivalentSelection(selected);
868
+ SmoOperation.transpose(altSel!, offset);
869
+ });
870
+ // if this is percussion, set that property
871
+ if (isPercussion) {
872
+ this.score.setNoteInstrumentProperties();
873
+ this.storeScore.setNoteInstrumentProperties()
874
+ }
875
+ if (selections.length === 1 && this.score.preferences.autoPlay) {
876
+ SuiOscillator.playSelectionNow(selections[0], this.score, 1);
877
+ }
878
+ }
879
+ this._renderChangedMeasures(measureSelections);
880
+ await this.renderer.updatePromise();
881
+ }
882
+ /**
883
+ * toggle the accidental spelling of the selected notes
884
+ * @returns
885
+ */
886
+ async toggleEnharmonic(): Promise<void> {
887
+ const selections = this.tracker.selections;
888
+ const measureSelections = this.undoTrackerMeasureSelections('toggle enharmonic');
889
+ const grace = this.tracker.getSelectedGraceNotes();
890
+ if (grace.length) {
891
+ grace.forEach((artifact) => {
892
+ SmoOperation.toggleGraceNoteEnharmonic(artifact.selection!, [artifact.modifier as SmoGraceNote]);
893
+ const altSelection = this._getEquivalentSelection(artifact.selection!);
894
+ const altGr = this._getEquivalentGraceNote(altSelection!, artifact.modifier as SmoGraceNote);
895
+ SmoOperation.toggleGraceNoteEnharmonic(altSelection!,
896
+ [altGr]);
897
+ });
898
+ } else {
899
+ selections.forEach((selected) => {
900
+ if (typeof (selected.selector.pitches) === 'undefined') {
901
+ selected.selector.pitches = [];
902
+ }
903
+ SmoOperation.toggleEnharmonic(selected);
904
+ const altSel = this._getEquivalentSelection(selected);
905
+ SmoOperation.toggleEnharmonic(altSel!);
906
+ });
907
+ }
908
+ this._renderChangedMeasures(measureSelections);
909
+ await this.renderer.updatePromise();
910
+ }
911
+
912
+ /**
913
+ * Toggle cautionary/courtesy accidentals
914
+ */
915
+ async toggleCourtesyAccidentals(): Promise<void> {
916
+ const selections = this.tracker.selections;
917
+ const measureSelections = this.undoTrackerMeasureSelections('toggle courtesy accidental');
918
+ const grace = this.tracker.getSelectedGraceNotes();
919
+ if (grace.length) {
920
+ grace.forEach((artifact) => {
921
+ const gn1 = [artifact.modifier] as SmoGraceNote[];
922
+ SmoOperation.toggleGraceNoteCourtesy(artifact.selection, gn1);
923
+ const altSel = this._getEquivalentSelection(artifact.selection!);
924
+ const gn2 = this._getEquivalentGraceNote(altSel!, gn1[0]);
925
+ SmoOperation.toggleGraceNoteCourtesy(altSel!, [gn2]);
926
+ });
927
+ } else {
928
+ selections.forEach((selection) => {
929
+ SmoOperation.toggleCourtesyAccidental(selection);
930
+ const altSel = this._getEquivalentSelection(selection);
931
+ SmoOperation.toggleCourtesyAccidental(altSel!);
932
+ });
933
+ }
934
+ this._renderChangedMeasures(measureSelections);
935
+ await this.renderer.updatePromise();
936
+ }
937
+
938
+ /**
939
+ * change the duration of notes for selected, creating more
940
+ * or fewer notes.
941
+ * After the change, reset the selection so it's as close as possible
942
+ * to the original length
943
+ * @param operation
944
+ * @returns
945
+ */
946
+ async batchDurationOperation(operation: BatchSelectionOperation): Promise<void> {
947
+ const selections = this.tracker.selections;
948
+ const measureSelections = this.undoTrackerMeasureSelections('change duration');
949
+ const grace = this.tracker.getSelectedGraceNotes();
950
+ const graceMap: Record<string, BatchSelectionOperation> = {
951
+ doubleDuration: 'doubleGraceNoteDuration',
952
+ halveDuration: 'halveGraceNoteDuration'
953
+ };
954
+ if (grace.length && typeof (graceMap[operation]) !== 'undefined') {
955
+ operation = graceMap[operation];
956
+ grace.forEach((artifact) => {
957
+ (SmoOperation as any)[operation](artifact.selection, artifact.modifier);
958
+ const altSelection = this._getEquivalentSelection(artifact.selection!);
959
+ const gn2 = this._getEquivalentGraceNote(altSelection!, artifact.modifier as SmoGraceNote);
960
+ (SmoOperation as any)[operation](altSelection!, gn2);
961
+ });
962
+ } else {
963
+ const altAr = this._getEquivalentSelections(selections);
964
+ SmoOperation.batchSelectionOperation(this.score, selections, operation);
965
+ SmoOperation.batchSelectionOperation(this.storeScore, altAr, operation);
966
+ }
967
+ this._renderChangedMeasures(measureSelections);
968
+ await this.renderer.updatePromise();
969
+ }
970
+ /**
971
+ * Toggle selected modifier on selected notes
972
+ * @param modifier
973
+ * @param ctor parent class constructor (e.g. SmoOrnament)
974
+ * @returns
975
+ */
976
+ async toggleArticulation(modifier: string, ctor: string): Promise<void> {
977
+ const measureSelections = this.undoTrackerMeasureSelections('toggle articulation');
978
+ this.tracker.selections.forEach((sel) => {
979
+ if (ctor === 'SmoArticulation') {
980
+ const aa = new SmoArticulation({ articulation: modifier });
981
+ const altAa = new SmoArticulation({ articulation: modifier });
982
+ altAa.attrs.id = aa.attrs.id;
983
+ if (sel.note) {
984
+ sel.note.toggleArticulation(aa);
985
+ }
986
+ const altSelection = this._getEquivalentSelection(sel);
987
+ if (altSelection && altSelection.note) {
988
+ altSelection.note.toggleArticulation(altAa);
989
+ }
990
+ } else {
991
+ const aa = new SmoOrnament({ ornament: modifier });
992
+ const altAa = new SmoOrnament({ ornament: modifier });
993
+ altAa.attrs.id = aa.attrs.id;
994
+ const altSelection = this._getEquivalentSelection(sel!);
995
+ if (sel.note) {
996
+ sel.note.toggleOrnament(aa);
997
+ }
998
+ if (altSelection && altSelection.note) {
999
+ altSelection.note.toggleOrnament(altAa);
1000
+ }
1001
+ }
1002
+ });
1003
+ this._renderChangedMeasures(measureSelections);
1004
+ await this.renderer.updatePromise();
1005
+ }
1006
+ async setArticulation(modifier: SmoArticulation, set: boolean): Promise<void> {
1007
+ const measureSelections = this.undoTrackerMeasureSelections('set articulation');
1008
+ this.tracker.selections.forEach((sel) => {
1009
+ const altAa = new SmoArticulation(modifier);
1010
+ if (sel.note) {
1011
+ sel.note.setArticulation(modifier, set);
1012
+ }
1013
+ const altSelection = this._getEquivalentSelection(sel);
1014
+ if (altSelection && altSelection.note) {
1015
+ altSelection.note.toggleArticulation(altAa);
1016
+ }
1017
+ });
1018
+ this._renderChangedMeasures(measureSelections);
1019
+ await this.renderer.updatePromise();
1020
+ }
1021
+ async setOrnament(modifier: SmoOrnament, set: boolean): Promise<void> {
1022
+ const measureSelections = this.undoTrackerMeasureSelections('set articulation');
1023
+ this.tracker.selections.forEach((sel) => {
1024
+ const altAa = new SmoOrnament(modifier);
1025
+ if (sel.note) {
1026
+ sel.note.setOrnament(modifier, set);
1027
+ }
1028
+ const altSelection = this._getEquivalentSelection(sel);
1029
+ if (altSelection && altSelection.note) {
1030
+ altSelection.note.setOrnament(altAa, set);
1031
+ }
1032
+ });
1033
+ this._renderChangedMeasures(measureSelections);
1034
+ await this.renderer.updatePromise();
1035
+ }
1036
+ /**
1037
+ * convert non-tuplet not to a tuplet
1038
+ * @param params
1039
+ */
1040
+ async makeTuplet(params: MakeTupletOperation): Promise<void> {
1041
+ const selection = this.tracker.selections[0];
1042
+ const measureSelections = this.undoTrackerMeasureSelections('make tuplet');
1043
+ SmoOperation.makeTuplet(selection, params);
1044
+ const altSelection = this._getEquivalentSelection(selection!);
1045
+ SmoOperation.makeTuplet(altSelection!, params);
1046
+ this._renderChangedMeasures(measureSelections);
1047
+ await this.renderer.updatePromise();
1048
+ }
1049
+ /**
1050
+ * Convert selected tuplet to a single (if possible) non-tuplet
1051
+ */
1052
+ async unmakeTuplet(): Promise<void> {
1053
+ const selection = this.tracker.selections[0];
1054
+ const measureSelections = this.undoTrackerMeasureSelections('unmake tuplet');
1055
+ SmoOperation.unmakeTuplet(selection);
1056
+ const altSelection = this._getEquivalentSelection(selection);
1057
+ SmoOperation.unmakeTuplet(altSelection!);
1058
+ this._renderChangedMeasures(measureSelections);
1059
+ await this.renderer.updatePromise();
1060
+ }
1061
+
1062
+ /**
1063
+ * Create a chord by adding an interval to selected note
1064
+ * @param interval 1/2 steps
1065
+ * @returns
1066
+ */
1067
+ async setInterval(interval: number): Promise<void> {
1068
+ const selections = this.tracker.selections;
1069
+ const measureSelections = this.undoTrackerMeasureSelections('set interval');
1070
+ selections.forEach((selected) => {
1071
+ SmoOperation.interval(selected, interval);
1072
+ const altSelection = this._getEquivalentSelection(selected);
1073
+ SmoOperation.interval(altSelection!, interval);
1074
+ });
1075
+ this._renderChangedMeasures(measureSelections);
1076
+ await this.renderer.updatePromise();
1077
+ }
1078
+
1079
+ /**
1080
+ * change the selected chord into a single note
1081
+ * @returns
1082
+ */
1083
+ async collapseChord(): Promise<void> {
1084
+ const selections = this.tracker.selections;
1085
+ const measureSelections = this.undoTrackerMeasureSelections('collapse chord');
1086
+ selections.forEach((selected) => {
1087
+ const note: SmoNote | null = selected.note;
1088
+ if (note) {
1089
+ const pp = JSON.parse(JSON.stringify(note.pitches[0]));
1090
+ const altpp = JSON.parse(JSON.stringify(note.pitches[0]));
1091
+ // No operation for this?
1092
+ note.pitches = [pp];
1093
+ const altSelection = this._getEquivalentSelection(selected);
1094
+ altSelection!.note!.pitches = [altpp];
1095
+ }
1096
+ });
1097
+ this._renderChangedMeasures(measureSelections);
1098
+ await this.renderer.updatePromise();
1099
+ }
1100
+ /**
1101
+ * Toggle chicken-scratches, for jazz improv, comping etc.
1102
+ */
1103
+ async toggleSlash(): Promise<void> {
1104
+ const selections = this.tracker.selections;
1105
+ const measureSelections = this.undoTrackerMeasureSelections('make slash');
1106
+ selections.forEach((selection) => {
1107
+ SmoOperation.toggleSlash(selection);
1108
+ const altSel = this._getEquivalentSelection(selection);
1109
+ SmoOperation.toggleSlash(altSel!);
1110
+ });
1111
+ this._renderChangedMeasures(measureSelections);
1112
+ await this.renderer.updatePromise();
1113
+ }
1114
+ /**
1115
+ * make selected notes into a rest, or visa-versa
1116
+ * @returns
1117
+ */
1118
+ async makeRest(): Promise<void> {
1119
+ const selections = this.tracker.selections;
1120
+ const measureSelections = this.undoTrackerMeasureSelections('make rest');
1121
+ selections.forEach((selection) => {
1122
+ SmoOperation.toggleRest(selection);
1123
+ const altSel = this._getEquivalentSelection(selection);
1124
+ SmoOperation.toggleRest(altSel!);
1125
+ });
1126
+ this._renderChangedMeasures(measureSelections);
1127
+ await this.renderer.updatePromise();
1128
+ }
1129
+ async clearAllBeams(): Promise<void> {
1130
+ this._undoScore('clearAllBeams');
1131
+ SmoOperation.clearAllBeamGroups(this.score);
1132
+ SmoOperation.clearAllBeamGroups(this.storeScore);
1133
+ await this.awaitRender();
1134
+ }
1135
+ async clearSelectedBeams() {
1136
+ const selections = this.tracker.selections;
1137
+ const measures = SmoSelection.getMeasureList(selections);
1138
+ const altSelections = this._getEquivalentSelections(selections);
1139
+ SmoOperation.clearBeamGroups(this.score, selections);
1140
+ SmoOperation.clearBeamGroups(this.storeScore, altSelections);
1141
+ this._renderChangedMeasures(measures);
1142
+ await this.renderer.updatePromise();
1143
+ }
1144
+ /**
1145
+ * toggle the 'end beam' flag for selected notes
1146
+ * @returns
1147
+ */
1148
+ async unbeamSelections(): Promise<void> {
1149
+ const selections = this.tracker.selections;
1150
+ const measureSelections = this.undoTrackerMeasureSelections('toggle beam group');
1151
+ selections.forEach((selection) => {
1152
+ SmoOperation.unbeamSelections(selection);
1153
+ const altSel = this._getEquivalentSelection(selection);
1154
+ SmoOperation.unbeamSelections(altSel!);
1155
+ });
1156
+ this._renderChangedMeasures(measureSelections);
1157
+ await this.renderer.updatePromise();
1158
+ }
1159
+ async toggleCue() {
1160
+ const measureSelections = this.undoTrackerMeasureSelections('toggle note cue');
1161
+ this.tracker.selections.forEach((selection) => {
1162
+ const altSelection = this._getEquivalentSelection(selection);
1163
+ if (selection.note && selection.note.isRest() === false) {
1164
+ selection.note.isCue = !selection.note.isCue;
1165
+ if (altSelection && altSelection.note) {
1166
+ altSelection.note.isCue = selection.note.isCue;
1167
+ }
1168
+ }
1169
+ });
1170
+ this._renderChangedMeasures(measureSelections);
1171
+ await this.renderer.updatePromise();
1172
+ }
1173
+ /**
1174
+ * up or down
1175
+ * @returns
1176
+ */
1177
+ async toggleBeamDirection(): Promise<void> {
1178
+ const selections = this.tracker.selections;
1179
+ if (selections.length < 1) {
1180
+ return;
1181
+ }
1182
+ const measureSelections = this.undoTrackerMeasureSelections('toggle beam direction');
1183
+ SmoOperation.toggleBeamDirection(selections);
1184
+ SmoOperation.toggleBeamDirection(this._getEquivalentSelections(selections));
1185
+ this._renderChangedMeasures(measureSelections);
1186
+ await this.renderer.updatePromise();
1187
+ }
1188
+ /**
1189
+ * Add the selected notes to a beam group
1190
+ */
1191
+ async beamSelections(): Promise<void> {
1192
+ const selections = this.tracker.selections;
1193
+ const measureSelections = this.undoTrackerMeasureSelections('beam selections');
1194
+ SmoOperation.beamSelections(this.score, selections);
1195
+ SmoOperation.beamSelections(this.storeScore, this._getEquivalentSelections(selections));
1196
+ this._renderChangedMeasures(measureSelections);
1197
+ await this.renderer.updatePromise();
1198
+ }
1199
+ /**
1200
+ * change key signature for selected measures
1201
+ * @param keySignature vex key signature
1202
+ */
1203
+ async addKeySignature(keySignature: string): Promise<void> {
1204
+ const measureSelections = this.undoTrackerMeasureSelections('set key signature ' + keySignature);
1205
+ measureSelections.forEach((sel) => {
1206
+ SmoOperation.addKeySignature(this.score, sel, keySignature);
1207
+ const altSel = this._getEquivalentSelection(sel);
1208
+ SmoOperation.addKeySignature(this.storeScore, altSel!, keySignature);
1209
+ });
1210
+ this._renderChangedMeasures(measureSelections);
1211
+ await this.renderer.updatePromise();
1212
+ }
1213
+ /**
1214
+ * Sets a pitch from the piano widget.
1215
+ * @param pitch {Pitch}
1216
+ * @param chordPedal {boolean} - indicates we are adding to a chord
1217
+ */
1218
+ async setPitchPiano(pitch: Pitch, chordPedal: boolean): Promise<void> {
1219
+ const measureSelections = this.undoTrackerMeasureSelections(
1220
+ 'setAbsolutePitch ' + pitch.letter + '/' + pitch.accidental);
1221
+ this.tracker.selections.forEach((selected) => {
1222
+ const npitch: Pitch = {
1223
+ letter: pitch.letter,
1224
+ accidental: pitch.accidental, octave: pitch.octave
1225
+ };
1226
+ const octave = SmoMeasure.defaultPitchForClef[selected.measure.clef].octave;
1227
+ npitch.octave += octave;
1228
+ const altSel = this._getEquivalentSelection(selected);
1229
+ if (chordPedal && selected.note) {
1230
+ selected.note.toggleAddPitch(npitch);
1231
+ altSel!.note!.toggleAddPitch(npitch);
1232
+ } else {
1233
+ SmoOperation.setPitch(selected, [npitch]);
1234
+ SmoOperation.setPitch(altSel!, [npitch]);
1235
+ }
1236
+ });
1237
+ this._renderChangedMeasures(measureSelections);
1238
+ await this.renderer.updatePromise();
1239
+ }
1240
+ /**
1241
+ * show or hide the piano widget
1242
+ * @param value to show it
1243
+ */
1244
+ async showPiano(value: boolean): Promise<void> {
1245
+ this.score.preferences.showPiano = value;
1246
+ this.storeScore.preferences.showPiano = value;
1247
+ if (value) {
1248
+ SuiPiano.showPiano();
1249
+ } else {
1250
+ SuiPiano.hidePiano();
1251
+ }
1252
+ await this.renderer.updatePromise();
1253
+ }
1254
+ /**
1255
+ * Render a pitch for each letter name-pitch in the string,
1256
+ * @param pitches letter names for pitches
1257
+ * @returns promise, resolved when all pitches rendered
1258
+ * @see setPitch
1259
+ */
1260
+ async setPitchesPromise(pitches: PitchLetter[]): Promise<any> {
1261
+ const self = this;
1262
+ const promise = new Promise((resolve: any) => {
1263
+ const fc = async (index: number) => {
1264
+ if (index >= pitches.length) {
1265
+ resolve();
1266
+ } else {
1267
+ await self.setPitch(pitches[index]);
1268
+ fc(index + 1);
1269
+ }
1270
+ };
1271
+ fc(0);
1272
+ });
1273
+ await promise;
1274
+ }
1275
+
1276
+ async setPitches(pitches: Pitch[]): Promise<void> {
1277
+ const selections = this.tracker.selections;
1278
+ const measureSelections = this.undoTrackerMeasureSelections('set pitches');
1279
+ const graceNotes = this.tracker.getSelectedGraceNotes();
1280
+ if (graceNotes.length === 1 && graceNotes[0].selection !== null && graceNotes[0].selection?.note !== null) {
1281
+ const grace1 = graceNotes[0].modifier as SmoGraceNote;
1282
+ const index = graceNotes[0].selection.note.graceNotes.findIndex((x) => x.attrs.id === grace1.attrs.id);
1283
+
1284
+ const altSel = this._getEquivalentSelection(graceNotes[0].selection);
1285
+ if (altSel && altSel.note !== null) {
1286
+ const grace2 = altSel.note.graceNotes[index];
1287
+ grace2.pitches = pitches;
1288
+ }
1289
+ grace1.pitches = pitches;
1290
+ } else if( selections.length === 1) {
1291
+ const selected = selections[0];
1292
+ SmoOperation.setPitch(selected, pitches);
1293
+ const altSel = this._getEquivalentSelection(selected);
1294
+ SmoOperation.setPitch(altSel!, pitches);
1295
+ if (this.score.preferences.autoAdvance) {
1296
+ // Don't play the next note and the added pitch at the same time.
1297
+ this.tracker.deferNextAutoPlay();
1298
+ this.tracker.moveSelectionRight();
1299
+ }
1300
+ SuiOscillator.playSelectionNow(selected, this.score, 1);
1301
+ }
1302
+
1303
+ this._renderChangedMeasures(measureSelections);
1304
+ await this.renderer.updatePromise();
1305
+ }
1306
+ /**
1307
+ * Add a pitch to the score at the cursor. This tries to find the best pitch
1308
+ * to match the letter key (F vs F# for instance) based on key and surrounding notes
1309
+ * @param letter string
1310
+ */
1311
+ async setPitch(letter: PitchLetter): Promise<void> {
1312
+ const selections = this.tracker.selections;
1313
+ const measureSelections = this.undoTrackerMeasureSelections('set pitch ' + letter);
1314
+ let isPercussion = false;
1315
+ selections.forEach((selected) => {
1316
+ const selector = selected.selector;
1317
+ if (selected.staff.getStaffInstrument(selected.selector.measure).isPercussion) {
1318
+ isPercussion = true;
1319
+ }
1320
+ let hintSel = SmoSelection.lastNoteSelectionNonRest(this.score,
1321
+ selector.staff, selector.measure, selector.voice, selector.tick);
1322
+ if (!hintSel) {
1323
+ hintSel = SmoSelection.nextNoteSelectionNonRest(this.score,
1324
+ selector.staff, selector.measure, selector.voice, selector.tick);
1325
+ }
1326
+ // The selection no longer exists, possibly deleted
1327
+ if (hintSel === null || hintSel.note === null) {
1328
+ return;
1329
+ }
1330
+ const pitch = SmoMusic.getLetterNotePitch(hintSel.note.pitches[0],
1331
+ letter, hintSel.measure.keySignature);
1332
+ SmoOperation.setPitch(selected, [pitch]);
1333
+ const altSel = this._getEquivalentSelection(selected);
1334
+ SmoOperation.setPitch(altSel!, [pitch]);
1335
+ if (this.score.preferences.autoAdvance) {
1336
+ // Don't play the next note and the added pitch at the same time.
1337
+ this.tracker.deferNextAutoPlay();
1338
+ this.tracker.moveSelectionRight();
1339
+ }
1340
+ });
1341
+ if (isPercussion) {
1342
+ this.score.setNoteInstrumentProperties();
1343
+ this.storeScore.setNoteInstrumentProperties()
1344
+ }
1345
+ if (selections.length === 1 && this.score.preferences.autoPlay) {
1346
+ SuiOscillator.playSelectionNow(selections[0], this.score, 1);
1347
+ }
1348
+ this._renderChangedMeasures(measureSelections);
1349
+ await this.renderer.updatePromise();
1350
+ }
1351
+ /**
1352
+ * Generic clipboard copy action
1353
+ */
1354
+ async copy(): Promise<void> {
1355
+ const altAr: SmoSelection[] = [];
1356
+ this.tracker.selections.forEach((sel) => {
1357
+ const noteSelection = this._getEquivalentSelection(sel);
1358
+ if (noteSelection !== null) {
1359
+ altAr.push(noteSelection);
1360
+ }
1361
+ });
1362
+ this.storePaste.setSelections(this.storeScore, altAr);
1363
+ await this.renderer.updatePromise();
1364
+ }
1365
+ /**
1366
+ * The voices that Select Voice can offer for the current selection: empty unless some selected
1367
+ * measure has more than one voice.
1368
+ */
1369
+ getSelectVoiceChoices(): number[] {
1370
+ return SmoSelection.voiceChoices(this.score, this.tracker.selections);
1371
+ }
1372
+ /**
1373
+ * Select all the notes of a voice in the measures that currently have a selection. Only the
1374
+ * selection changes: no edit is made and no undo is recorded.
1375
+ * @param voice the voice to select (0-3)
1376
+ */
1377
+ async selectVoice(voice: number): Promise<void> {
1378
+ this.tracker.selectVoice(voice);
1379
+ }
1380
+ /**
1381
+ * The most voices any of the selected measures has, for the Copy Voices menu
1382
+ */
1383
+ getSelectionVoiceCount(): number {
1384
+ let rv = 0;
1385
+ this.tracker.getSelectedMeasures().forEach((sel) => {
1386
+ rv = Math.max(rv, sel.measure.voices.length);
1387
+ });
1388
+ return rv;
1389
+ }
1390
+ /**
1391
+ * Where a voice paste would go, in the full score: the selected staff and measure, and the
1392
+ * measures from there that the copied voices cover (adding up measure lengths until the copy fits,
1393
+ * but not past the last measure). Null if nothing is selected or no voices are copied.
1394
+ */
1395
+ private _getVoicePasteRange(): { staff: number, firstMeasure: number, lastMeasure: number } | null {
1396
+ if (!this.storePaste.hasVoiceCopy() || this.tracker.selections.length < 1) {
1397
+ return null;
1398
+ }
1399
+ const altSelection = this._getEquivalentSelection(this.tracker.selections[0]);
1400
+ if (altSelection === null) {
1401
+ return null;
1402
+ }
1403
+ const staff = altSelection.selector.staff;
1404
+ const measures = this.storeScore.staves[staff].measures;
1405
+ const firstMeasure = altSelection.selector.measure;
1406
+ const ticksToPaste = this.storePaste.getVoiceCopyTickCount();
1407
+ let lastMeasure = firstMeasure;
1408
+ let covered = measures[firstMeasure].getTicksFromThisOrAnyVoice(0);
1409
+ while (covered < ticksToPaste && lastMeasure + 1 < measures.length) {
1410
+ lastMeasure += 1;
1411
+ covered += measures[lastMeasure].getTicksFromThisOrAnyVoice(0);
1412
+ }
1413
+ return { staff, firstMeasure, lastMeasure };
1414
+ }
1415
+ /**
1416
+ * The number of voices at the paste destination, for the Paste Voice menu: the most voices in
1417
+ * any measure the paste would cover, on the staves it would cover. A voice number at or above
1418
+ * this count is empty everywhere in the destination.
1419
+ */
1420
+ getDestinationVoiceCount(): number {
1421
+ const range = this._getVoicePasteRange();
1422
+ if (range === null) {
1423
+ const measures = this.tracker.getSelectedMeasures();
1424
+ return measures.length > 0 ? measures[0].measure.voices.length : 0;
1425
+ }
1426
+ const copy = this.storePaste.voiceCopy!;
1427
+ let rv = 0;
1428
+ for (let k = 0; k < copy.staffCount; ++k) {
1429
+ const staff = this.storeScore.staves[range.staff + k];
1430
+ if (!staff) {
1431
+ break;
1432
+ }
1433
+ for (let m = range.firstMeasure; m <= range.lastMeasure; ++m) {
1434
+ rv = Math.max(rv, staff.measures[m].voices.length);
1435
+ }
1436
+ }
1437
+ return rv;
1438
+ }
1439
+ /**
1440
+ * Copy a voice, or all the voices, of the selected measures. The copy always covers whole
1441
+ * measures, from the start of the first selected measure to the end of the last.
1442
+ * @param voice the voice to copy (0-3), or 'all'
1443
+ */
1444
+ async copyVoices(voice: number | 'all'): Promise<void> {
1445
+ const altAr: SmoSelection[] = [];
1446
+ this.tracker.selections.forEach((sel) => {
1447
+ const noteSelection = this._getEquivalentSelection(sel);
1448
+ if (noteSelection !== null) {
1449
+ altAr.push(noteSelection);
1450
+ }
1451
+ });
1452
+ this.storePaste.setVoiceSelections(this.storeScore, altAr, voice);
1453
+ await this.renderer.updatePromise();
1454
+ }
1455
+ /**
1456
+ * Paste the voices copied with copyVoices, starting at the beginning of the first selected
1457
+ * measure. A voice that doesn't exist in a measure is created there first.
1458
+ * @param voice the voice to paste into (0-3) for a single copied voice; 'new' to paste a single
1459
+ * copied voice into a new voice after the existing ones; or 'all' to paste every copied voice
1460
+ * into the voice with the same number
1461
+ */
1462
+ async pasteVoices(voice: number | 'all' | 'new'): Promise<void> {
1463
+ const range = this._getVoicePasteRange();
1464
+ if (range === null) {
1465
+ return;
1466
+ }
1467
+ let destVoice: number | 'all' = voice === 'new' ? this.getDestinationVoiceCount() : voice;
1468
+ if (destVoice !== 'all' && (destVoice < 0 || destVoice > 3)) {
1469
+ // 'new' with all the voices already in use
1470
+ return;
1471
+ }
1472
+ this.renderer.preserveScroll();
1473
+ // The paste always begins at the start of the measure
1474
+ const target: SmoSelector = { staff: range.staff, measure: range.firstMeasure, voice: 0, tick: 0, pitches: [] };
1475
+ const measureRange = [range.firstMeasure, range.lastMeasure];
1476
+ // One undo for the whole paste, including any voices it creates
1477
+ this.storeUndo.grouping = true;
1478
+ for (let i = measureRange[0]; i <= measureRange[1]; ++i) {
1479
+ this._undoColumn('paste voices', i);
1480
+ this.renderer.unrenderColumn(this.score.staves[0].measures[i]);
1481
+ }
1482
+ this.storeUndo.grouping = false;
1483
+ if (destVoice === 'all') {
1484
+ this.storePaste.pasteAllVoices(target);
1485
+ } else {
1486
+ this.storePaste.pasteVoice(target, destVoice);
1487
+ }
1488
+ this.replaceMeasureView(measureRange);
1489
+ await this.renderer.updatePromise();
1490
+ }
1491
+ /**
1492
+ * clipboard paste action
1493
+ * @returns
1494
+ */
1495
+ async paste(): Promise<void> {
1496
+ // We undo the whole score on a paste, since we don't yet know the
1497
+ // extent of the overlap
1498
+ this.renderer.preserveScroll();
1499
+ const selections: SmoSelection[] = this.getPasteMeasureList();
1500
+ const firstSelection = selections[0];
1501
+ const measureEnd = selections[selections.length - 1].selector.measure;
1502
+ const measureRange = [firstSelection.selector.measure, measureEnd];
1503
+ this.storeUndo.grouping = true;
1504
+ // Undo the paste by selecting all the affected measures
1505
+ for (let i = measureRange[0]; i <= measureRange[1]; ++i) {
1506
+ this._undoColumn('paste', i);
1507
+ this.renderer.unrenderColumn(this.score.staves[0].measures[i]);
1508
+ }
1509
+ this.storeUndo.grouping = false;
1510
+ const altSelection = this._getEquivalentSelection(firstSelection);
1511
+ const altTarget = altSelection!.selector;
1512
+ altTarget.tick = this.tracker.selections[0].selector.tick;
1513
+ // paste the clipboard into the destination
1514
+ this.storePaste.pasteSelections(altTarget);
1515
+ // Refresh those measures.
1516
+ this.replaceMeasureView(measureRange);
1517
+ await this.renderer.updatePromise();
1518
+ }
1519
+ /**
1520
+ * Paste only the chords.
1521
+ */
1522
+ async pasteChords(): Promise<void> {
1523
+ // We undo the whole score on a paste, since we don't yet know the
1524
+ // extent of the overlap
1525
+ this.renderer.preserveScroll();
1526
+ const selections: SmoSelection[] = this.getPasteMeasureList();
1527
+ const firstSelection = selections[0];
1528
+ const measureEnd = selections[selections.length - 1].selector.measure;
1529
+ const measureRange = [firstSelection.selector.measure, measureEnd];
1530
+ this.storeUndo.grouping = true;
1531
+ // Undo the paste by selecting all the affected measures
1532
+ for (let i = measureRange[0]; i <= measureRange[1]; ++i) {
1533
+ this._undoColumn('paste', i);
1534
+ this.renderer.unrenderColumn(this.score.staves[0].measures[i]);
1535
+ }
1536
+ this.storeUndo.grouping = false;
1537
+ const altSelection = this._getEquivalentSelection(firstSelection);
1538
+ const altTarget = altSelection!.selector;
1539
+ altTarget.tick = this.tracker.selections[0].selector.tick;
1540
+ this.storePaste.pasteChords(altTarget);
1541
+ // Refresh those measures.
1542
+ this.replaceMeasureView(measureRange);
1543
+ await this.renderer.updatePromise();
1544
+ }
1545
+ /**
1546
+ * specify a note head other than the default for the duration
1547
+ * @param head
1548
+ */
1549
+ async setNoteHead(head: string): Promise<void> {
1550
+ await this.modifyCurrentSelections('set note head', (score, selections) => {
1551
+ SmoOperation.setNoteHead(selections, head);
1552
+ });
1553
+ }
1554
+
1555
+ /**
1556
+ * Add a volta for selected measures
1557
+ */
1558
+ async addEnding(): Promise<void> {
1559
+ // TODO: we should have undo for columns
1560
+ this._undoScore('Add Volta');
1561
+ const ft = this.tracker.getExtremeSelection(-1);
1562
+ const tt = this.tracker.getExtremeSelection(1);
1563
+ const params = SmoVolta.defaults;
1564
+ params.startBar = ft.selector.measure;
1565
+ params.endBar = tt.selector.measure;
1566
+ params.number = 1;
1567
+ const volta = new SmoVolta(params);
1568
+ const altVolta = new SmoVolta(params);
1569
+ this._renderChangedMeasures([ft, tt]);
1570
+ SmoOperation.addEnding(this.storeScore, altVolta);
1571
+ SmoOperation.addEnding(this.score, volta);
1572
+ this.renderer.setRefresh();
1573
+ return this.renderer.updatePromise();
1574
+ }
1575
+ /**
1576
+ * @param ending volta settings
1577
+ * @returns
1578
+ */
1579
+ async updateEnding(ending: SmoVolta): Promise<void> {
1580
+ this._undoScore('Change Volta');
1581
+ ending.elements.forEach((el) => {
1582
+ $(el).find('g.' + ending.attrs.id).remove();
1583
+ });
1584
+ ending.elements = [];
1585
+ SmoOperation.removeEnding(this.storeScore, ending);
1586
+ SmoOperation.removeEnding(this.score, ending);
1587
+ const altVolta = new SmoVolta(ending);
1588
+ SmoOperation.addEnding(this.storeScore, altVolta);
1589
+ SmoOperation.addEnding(this.score, ending);
1590
+ this.renderer.setRefresh();
1591
+ return this.renderer.updatePromise();
1592
+ }
1593
+ /**
1594
+ *
1595
+ * @param ending volta to remove
1596
+ * @returns
1597
+ */
1598
+ async removeEnding(ending: SmoVolta): Promise<void> {
1599
+ this._undoScore('Remove Volta');
1600
+ ending.elements.forEach((el) => {
1601
+ $(el).find('g.' + ending.attrs.id).remove();
1602
+ });
1603
+ ending.elements = [];
1604
+ SmoOperation.removeEnding(this.storeScore, ending);
1605
+ SmoOperation.removeEnding(this.score, ending);
1606
+ this.renderer.setRefresh();
1607
+ return this.renderer.updatePromise();
1608
+ }
1609
+ /**
1610
+ *
1611
+ * @param position begin or end
1612
+ * @param barline barline type
1613
+ * @returns
1614
+ */
1615
+ async setBarline(position: number, barline: number, bracket: number): Promise<void> {
1616
+ const obj = new SmoBarline({ position, barline, repeatBracket: bracket });
1617
+ const altObj = new SmoBarline({ position, barline, repeatBracket: bracket });
1618
+ const selection = this.tracker.selections[0];
1619
+ this._undoColumn('set barline', selection.selector.measure);
1620
+ SmoOperation.setMeasureBarline(this.score, selection, obj);
1621
+ const altSel = this._getEquivalentSelection(selection);
1622
+ SmoOperation.setMeasureBarline(this.storeScore, altSel!, altObj);
1623
+ this._renderChangedMeasures([selection]);
1624
+ return this.renderer.updatePromise();
1625
+ }
1626
+ /**
1627
+ *
1628
+ * @param position start or end
1629
+ * @param symbol coda, etc.
1630
+ */
1631
+ async setRepeatSymbol(position: number, symbol: number): Promise<void> {
1632
+ const params = SmoRepeatSymbol.defaults;
1633
+ params.position = position;
1634
+ params.symbol = symbol;
1635
+ const obj = new SmoRepeatSymbol(params);
1636
+ const altObj = new SmoRepeatSymbol(params);
1637
+ const selection = this.tracker.selections[0];
1638
+ this._undoColumn('set repeat symbol', selection.selector.measure);
1639
+ SmoOperation.setRepeatSymbol(this.score, selection, obj);
1640
+ const altSel = this._getEquivalentSelection(selection);
1641
+ SmoOperation.setRepeatSymbol(this.storeScore, altSel!, altObj);
1642
+ this._renderChangedMeasures([selection]);
1643
+ return this.renderer.updatePromise();
1644
+ }
1645
+ /**
1646
+ * toggle rehearsal mark on first selected measure
1647
+ * @returns
1648
+ */
1649
+ async toggleRehearsalMark(): Promise<void> {
1650
+ const selection = this.tracker.getExtremeSelection(-1);
1651
+ const altSelection = this._getEquivalentSelection(selection);
1652
+ const cmd = selection.measure.getRehearsalMark() ? 'removeRehearsalMark' : 'addRehearsalMark';
1653
+ SmoOperation[cmd](this.score, selection, new SmoRehearsalMark(SmoRehearsalMark.defaults));
1654
+ SmoOperation[cmd](this.storeScore, altSelection!, new SmoRehearsalMark(SmoRehearsalMark.defaults));
1655
+ this._renderChangedMeasures([selection]);
1656
+ return this.renderer.updatePromise();
1657
+ }
1658
+ /**
1659
+ * Finds the measure whose rehearsal mark has the given id, as a selection on the live score.
1660
+ * Rehearsal marks are column-wide, so the first staff holding it identifies the measure.
1661
+ * See specs/025-rehearsal-mark-dialog.
1662
+ */
1663
+ _findRehearsalMarkSelection(id: string): SmoSelection | null {
1664
+ for (let i = 0; i < this.score.staves.length; ++i) {
1665
+ const staff = this.score.staves[i];
1666
+ for (let j = 0; j < staff.measures.length; ++j) {
1667
+ const measure = staff.measures[j];
1668
+ if (measure.getRehearsalMark()?.attrs.id === id) {
1669
+ return SmoSelection.measureSelection(this.score, staff.staffId, measure.measureNumber.measureIndex);
1670
+ }
1671
+ }
1672
+ }
1673
+ return null;
1674
+ }
1675
+ /**
1676
+ * Replaces an existing rehearsal mark's settings on its measure, on every staff and in the
1677
+ * undo-copy store. Does nothing if the mark is no longer present (e.g. removed while its dialog
1678
+ * was open). See specs/025-rehearsal-mark-dialog.
1679
+ * @param mark the edited rehearsal mark
1680
+ */
1681
+ async updateRehearsalMark(mark: SmoRehearsalMark): Promise<void> {
1682
+ const selection = this._findRehearsalMarkSelection(mark.attrs.id);
1683
+ if (!selection) {
1684
+ return;
1685
+ }
1686
+ const altSelection = this._getEquivalentSelection(selection);
1687
+ this._undoColumn('Change Rehearsal Mark', selection.selector.measure);
1688
+ SmoOperation.removeRehearsalMark(this.score, selection);
1689
+ SmoOperation.addRehearsalMark(this.score, selection, mark);
1690
+ SmoOperation.removeRehearsalMark(this.storeScore, altSelection!);
1691
+ SmoOperation.addRehearsalMark(this.storeScore, altSelection!, mark);
1692
+ this._renderChangedMeasures([selection]);
1693
+ return this.renderer.updatePromise();
1694
+ }
1695
+ /**
1696
+ * Removes an existing rehearsal mark from its measure on every staff and in the undo-copy store.
1697
+ * Does nothing if the mark is no longer present. See specs/025-rehearsal-mark-dialog.
1698
+ * @param mark the rehearsal mark to remove
1699
+ */
1700
+ async removeRehearsalMark(mark: SmoRehearsalMark): Promise<void> {
1701
+ const selection = this._findRehearsalMarkSelection(mark.attrs.id);
1702
+ if (!selection) {
1703
+ return;
1704
+ }
1705
+ const altSelection = this._getEquivalentSelection(selection);
1706
+ this._undoColumn('Remove Rehearsal Mark', selection.selector.measure);
1707
+ SmoOperation.removeRehearsalMark(this.score, selection);
1708
+ SmoOperation.removeRehearsalMark(this.storeScore, altSelection!);
1709
+ this._renderChangedMeasures([selection]);
1710
+ return this.renderer.updatePromise();
1711
+ }
1712
+ _removeStaffModifier(modifier: StaffModifierBase) {
1713
+ this.score.staves[modifier.associatedStaff].removeStaffModifier(modifier);
1714
+ const altModifier = StaffModifierBase.deserialize(modifier.serialize());
1715
+ altModifier.attrs.id = modifier.attrs.id;
1716
+ altModifier.startSelector = this._getEquivalentSelector(altModifier.startSelector);
1717
+ altModifier.endSelector = this._getEquivalentSelector(altModifier.endSelector);
1718
+ this.storeScore.staves[this._getEquivalentStaff(modifier.associatedStaff)].removeStaffModifier(altModifier);
1719
+ }
1720
+ /**
1721
+ * Remove selected modifier
1722
+ * @param modifier slur, hairpin, etc.
1723
+ * @returns
1724
+ */
1725
+ async removeStaffModifier(modifier: StaffModifierBase): Promise<void> {
1726
+ this.undoStaffModifier('Set measure proportion', modifier,
1727
+ UndoBuffer.bufferSubtypes.REMOVE);
1728
+ this._removeStaffModifier(modifier);
1729
+ this._renderRectangle(modifier.startSelector, modifier.endSelector);
1730
+ return this.renderer.updatePromise();
1731
+ }
1732
+ /**
1733
+ * Change a staff modifier
1734
+ * @param original original version
1735
+ * @param modifier modified version
1736
+ * @returns
1737
+ */
1738
+ async addOrUpdateStaffModifier(original: StaffModifierBase, modifier: StaffModifierBase): Promise<void> {
1739
+ if (!modifier) {
1740
+ if (original) {
1741
+ // Handle legacy API changed
1742
+ modifier = StaffModifierBase.deserialize(original);
1743
+ } else {
1744
+ console.warn('update modifier: bad modifier');
1745
+ return;
1746
+ }
1747
+ }
1748
+ const existing = this.score.staves[modifier.startSelector.staff]
1749
+ .getModifier(modifier);
1750
+ const subtype = existing === null ? UndoBuffer.bufferSubtypes.ADD :
1751
+ UndoBuffer.bufferSubtypes.UPDATE;
1752
+ this.undoStaffModifier('Set measure proportion', original,
1753
+ subtype);
1754
+ this._removeStaffModifier(modifier);
1755
+ const copy = StaffModifierBase.deserialize(modifier.serialize());
1756
+ copy.startSelector = this._getEquivalentSelector(copy.startSelector);
1757
+ copy.endSelector = this._getEquivalentSelector(copy.endSelector);
1758
+ const sel = SmoSelection.noteFromSelector(this.score, modifier.startSelector);
1759
+ if (sel !== null) {
1760
+ const altSel = this._getEquivalentSelection(sel);
1761
+ SmoOperation.addStaffModifier(sel, modifier);
1762
+ SmoOperation.addStaffModifier(altSel!, copy);
1763
+ const modId = 'mod-' + sel.selector.staff + '-' + sel.selector.measure;
1764
+ const context = this.renderer.renderer.getRenderer(sel.measure.svg.logicalBox);
1765
+ if (context) {
1766
+ SvgHelpers.removeElementsByClass(context.svg, modId);
1767
+ }
1768
+ }
1769
+ this._renderRectangle(modifier.startSelector, modifier.endSelector);
1770
+ return this.renderer.updatePromise();
1771
+ }
1772
+ lineOperation(op: createStaffModifierType<StaffModifierBase>) {
1773
+ // if (this.tracker.selections.length < 2) {
1774
+ // return;
1775
+ // }
1776
+ const measureSelections = this.undoTrackerMeasureSelections('create staff modifier');
1777
+ const ft = this.tracker.getExtremeSelection(-1);
1778
+ const tt = this.tracker.getExtremeSelection(1);
1779
+ const ftAlt = this._getEquivalentSelection(ft);
1780
+ const ttAlt = this._getEquivalentSelection(tt);
1781
+ const modifier = op(ft, tt);
1782
+ const altModifier = op(ftAlt!, ttAlt!);
1783
+ altModifier.attrs.id = modifier.attrs.id;
1784
+ ft.staff.addStaffModifier(modifier);
1785
+ ftAlt?.staff.addStaffModifier(altModifier);
1786
+ this.undoStaffModifier('add ' + op, modifier, UndoBuffer.bufferSubtypes.ADD);
1787
+ this._renderChangedMeasures(measureSelections);
1788
+ }
1789
+ /**
1790
+ * Add crescendo to selection
1791
+ */
1792
+ async crescendo(): Promise<void> {
1793
+ this.lineOperation(SmoOperation.createCrescendo);
1794
+ return this.renderer.updatePromise();
1795
+ }
1796
+ /**
1797
+ * Add crescendo to selection
1798
+ */
1799
+ async crescendoBracket(): Promise<void> {
1800
+ this.lineOperation(SmoOperation.createCrescendoBracket);
1801
+ return this.renderer.updatePromise();
1802
+ }
1803
+ /**
1804
+ * Add crescendo to selection
1805
+ */
1806
+ async dimenuendo(): Promise<void> {
1807
+ this.lineOperation(SmoOperation.createDimenuendoBracket);
1808
+ return this.renderer.updatePromise();
1809
+ }
1810
+ /**
1811
+ * Add crescendo to selection
1812
+ */
1813
+ async accelerando(): Promise<void> {
1814
+ this.lineOperation(SmoOperation.createAccelerandoBracket);
1815
+ return this.renderer.updatePromise();
1816
+ }
1817
+ /**
1818
+ * Add crescendo to selection
1819
+ */
1820
+ async ritard(): Promise<void> {
1821
+ this.lineOperation(SmoOperation.createRitardBracket);
1822
+ return this.renderer.updatePromise();
1823
+ }
1824
+ /**
1825
+ * diminuendo hairpin
1826
+ * @returns
1827
+ */
1828
+ async decrescendo(): Promise<void> {
1829
+ this.lineOperation(SmoOperation.createDecrescendo);
1830
+ return this.renderer.updatePromise();
1831
+ }
1832
+ async removeTextBracket(bracket: SmoStaffTextBracket): Promise<void> {
1833
+ return this.removeStaffModifier(bracket);
1834
+ }
1835
+ async addOrReplaceStaffModifier(callback: updateStaffModifierFunc, modifier: StaffModifierBase): Promise<void> {
1836
+ const from1 = SmoSelection.noteFromSelector(this.score, modifier.startSelector);
1837
+ const to1 = SmoSelection.noteFromSelector(this.score, modifier.endSelector);
1838
+ if (from1 === null || to1 === null) {
1839
+ return;
1840
+ }
1841
+ const altFrom = this._getEquivalentSelection(from1);
1842
+ const altTo = this._getEquivalentSelection(to1);
1843
+ if (altFrom === null || altTo === null) {
1844
+ return;
1845
+ }
1846
+ callback(this.score, from1, to1);
1847
+ callback(this.storeScore, altFrom, altTo);
1848
+ const redraw = SmoSelection.getMeasuresBetween(this.score, from1.selector, to1.selector);
1849
+ this.undoStaffModifier('add repl text bracket', modifier, UndoBuffer.bufferSubtypes.ADD);
1850
+ this._renderChangedMeasures(redraw);
1851
+ return this.renderer.updatePromise();
1852
+ }
1853
+ async addOrReplaceTextBracket(modifier: SmoStaffTextBracket) {
1854
+ const from1 = SmoSelection.noteFromSelector(this.score, modifier.startSelector);
1855
+ const to1 = SmoSelection.noteFromSelector(this.score, modifier.endSelector);
1856
+ if (from1 === null || to1 === null) {
1857
+ return;
1858
+ }
1859
+ const altFrom = this._getEquivalentSelection(from1);
1860
+ const altTo = this._getEquivalentSelection(to1);
1861
+ if (altFrom === null || altTo === null) {
1862
+ return;
1863
+ }
1864
+ SmoOperation.addOrReplaceBracket(modifier, from1, to1);
1865
+ SmoOperation.addOrReplaceBracket(modifier, altFrom, altTo);
1866
+ const redraw = SmoSelection.getMeasuresBetween(this.score, from1.selector, to1.selector);
1867
+ this.undoStaffModifier('add repl text bracket', modifier, UndoBuffer.bufferSubtypes.ADD);
1868
+ this._renderChangedMeasures(redraw);
1869
+ return this.renderer.updatePromise();
1870
+ }
1871
+ /**
1872
+ * Slur selected notes
1873
+ * @returns
1874
+ */
1875
+ async addSlur(): Promise<void> {
1876
+ const measureSelections = SmoSelection.getMeasureList(this.tracker.selections);
1877
+ const ft = this.tracker.getExtremeSelection(-1);
1878
+ const tt = this.tracker.getExtremeSelection(1);
1879
+ const ftAlt = this._getEquivalentSelection(ft);
1880
+ const ttAlt = this._getEquivalentSelection(tt);
1881
+ const modifier = SmoOperation.createSlur(this.score, ft, tt);
1882
+ ft.staff.addStaffModifier(modifier);
1883
+ // make sure score and backup have same ID for undo.
1884
+ const altModifier = SmoOperation.createSlur(this.storeScore, ftAlt!, ttAlt!);
1885
+ altModifier.attrs.id = modifier.attrs.id;
1886
+ ftAlt?.staff.addStaffModifier(altModifier);
1887
+ this.undoStaffModifier('add slur', modifier, UndoBuffer.bufferSubtypes.ADD);
1888
+ this._renderChangedMeasures(measureSelections);
1889
+ return this.renderer.updatePromise();
1890
+ }
1891
+ /**
1892
+ * tie selected notes
1893
+ * @returns
1894
+ */
1895
+ async tie(): Promise<void> {
1896
+ this.lineOperation(SmoOperation.createTie);
1897
+ return this.renderer.updatePromise();
1898
+ }
1899
+ async updateZoom(zoomFactor: number): Promise<void> {
1900
+ const original = this.score.layoutManager!.getGlobalLayout();
1901
+ original.zoomScale = zoomFactor;
1902
+ this.score.layoutManager!.globalLayout.zoomScale = zoomFactor;
1903
+ this.renderer.pageMap.updateZoom(zoomFactor);
1904
+ this.renderer.pageMap.updateContainerOffset(this.scroller.scrollState);
1905
+ }
1906
+ /**
1907
+ * Keep text groups in the same visual position when a layout changes: rescale by the
1908
+ * svg scale ratio, and by the page width/height ratios. Groups are de-duplicated by
1909
+ * identity, since a part's staves (and the view and store copies, after a part update)
1910
+ * can share the same text group objects, and scaling one twice would double-apply it.
1911
+ * @param textGroups groups to adjust
1912
+ * @param previousLayout layout before the change
1913
+ * @param layout layout after the change
1914
+ */
1915
+ static repositionTextGroups(textGroups: SmoTextGroup[], previousLayout: SmoGlobalLayout, layout: SmoGlobalLayout) {
1916
+ const scaleChanged = previousLayout.svgScale !== layout.svgScale;
1917
+ const widthChanged = previousLayout.pageWidth !== layout.pageWidth;
1918
+ const heightChanged = previousLayout.pageHeight !== layout.pageHeight;
1919
+ const scaleRatio = previousLayout.svgScale / layout.svgScale;
1920
+ const widthRatio = widthChanged ? layout.pageWidth / previousLayout.pageWidth : 1;
1921
+ const heightRatio = heightChanged ? layout.pageHeight / previousLayout.pageHeight : 1;
1922
+ const unique = new Set<SmoTextGroup>();
1923
+ textGroups.forEach((tg) => unique.add(toRaw(tg)));
1924
+ unique.forEach((tg) => {
1925
+ if (scaleChanged) {
1926
+ tg.scaleText(scaleRatio);
1927
+ }
1928
+ if (widthChanged || heightChanged) {
1929
+ tg.rescalePosition(widthRatio, heightRatio);
1930
+ }
1931
+ });
1932
+ }
1933
+ /**
1934
+ * set global page for score, zoom etc.
1935
+ * @param layout global SVG settings
1936
+ * @param previousLayout the layout as it was immediately before this change. Callers must
1937
+ * pass a snapshot taken before `layout` was mutated -- `this.score.layoutManager`'s current
1938
+ * value cannot be used for this, because dialogs (e.g. globalLayout.ts) bind directly to that
1939
+ * live object, so by the time this method runs it may already equal `layout`.
1940
+ * @returns
1941
+ */
1942
+ async setGlobalLayout(layout: SmoGlobalLayout, previousLayout: SmoGlobalLayout): Promise<void> {
1943
+ const scaleChanged = previousLayout.svgScale !== layout.svgScale;
1944
+ const widthChanged = previousLayout.pageWidth !== layout.pageWidth;
1945
+ const heightChanged = previousLayout.pageHeight !== layout.pageHeight;
1946
+ if (!scaleChanged && !widthChanged && !heightChanged) {
1947
+ return;
1948
+ }
1949
+ this._undoScore('Set Global Layout');
1950
+ const repositionGroups = (textGroups: SmoTextGroup[]) => {
1951
+ SuiScoreViewOperations.repositionTextGroups(textGroups, previousLayout, layout);
1952
+ };
1953
+ if (this.isPartExposed()) {
1954
+ // A part has its own layoutManager/textGroups (see SuiScoreView._mapPartFormatting,
1955
+ // which aliases this.score.layoutManager/textGroups to staves[0].partInfo's copies), so
1956
+ // only the exposed part's text is repositioned here -- the score's own text groups and
1957
+ // other parts' text groups are untouched.
1958
+ this.score.staves.forEach((staff, staffIx) => {
1959
+ staff.partInfo.layoutManager.updateGlobalLayout(layout);
1960
+ repositionGroups(staff.partInfo.textGroups);
1961
+ const altStaff = this.storeScore.staves[this.staffMap[staffIx]];
1962
+ altStaff.partInfo.layoutManager.updateGlobalLayout(layout);
1963
+ repositionGroups(altStaff.partInfo.textGroups);
1964
+ });
1965
+ } else {
1966
+ this.score.layoutManager!.updateGlobalLayout(layout);
1967
+ repositionGroups(this.score.textGroups);
1968
+ this.storeScore.layoutManager!.updateGlobalLayout(layout);
1969
+ repositionGroups(this.storeScore.textGroups);
1970
+ }
1971
+ this.renderer.rerenderAll();
1972
+ return this.renderer.preserveScroll();
1973
+ }
1974
+ /**
1975
+ * Set the layout of a single page
1976
+ * @param layout page layout
1977
+ * @param pageIndex which page to change
1978
+ * @returns
1979
+ */
1980
+ async setPageLayout(layout: SmoPageLayout, pageIndex: number) {
1981
+ this.score.layoutManager!.updatePage(layout, pageIndex);
1982
+ this.storeScore.layoutManager!.updatePage(layout, pageIndex);
1983
+ // If we are in part mode, save the page layout in the part so it is there next time
1984
+ // the part is exposed.
1985
+ if (this.isPartExposed()) {
1986
+ this.score.staves.forEach((staff, staffIx) => {
1987
+ staff.partInfo.layoutManager.updatePage(layout, pageIndex);
1988
+ const altStaff = this.storeScore.staves[this.staffMap[staffIx]];
1989
+ altStaff.partInfo.layoutManager.updatePage(layout, pageIndex);
1990
+ });
1991
+ }
1992
+ await this.refreshViewport();
1993
+ }
1994
+ async setPageLayouts(layout: SmoPageLayout, startIndex: number, endIndex: number) {
1995
+ this._undoScore('Set Page Layout');
1996
+ let i = 0;
1997
+ for (i = startIndex; i <= endIndex; ++i) {
1998
+ this.setPageLayout(layout, i);
1999
+ }
2000
+ this.renderer.rerenderAll();
2001
+ return this.renderer.updatePromise();
2002
+ }
2003
+ /**
2004
+ * Update the music font
2005
+ * @param family
2006
+ * @returns
2007
+ */
2008
+ async setEngravingFontFamily(family: engravingFontType): Promise<void> {
2009
+ this.score.engravingFont = family;
2010
+ this.storeScore.engravingFont = family;
2011
+ this.renderer.notifyFontChange();
2012
+ this.renderer.setRefresh();
2013
+ return this.renderer.updatePromise();
2014
+ }
2015
+ /**
2016
+ * Upate global font used for chord changes
2017
+ * @param fontInfo
2018
+ * @returns
2019
+ */
2020
+ async setChordFont(fontInfo: FontInfo): Promise<void> {
2021
+ this._undoScore('Set Chord Font');
2022
+ this.score.setChordFont(fontInfo);
2023
+ this.storeScore.setChordFont(fontInfo);
2024
+ this.renderer.setRefresh();
2025
+ return this.renderer.updatePromise();
2026
+ }
2027
+ /**
2028
+ * Update font used for lyrics
2029
+ * @param fontInfo
2030
+ * @returns
2031
+ */
2032
+ async setLyricFont(fontInfo: FontInfo): Promise<void> {
2033
+ this._undoScore('Set Lyric Font');
2034
+ this.score.setLyricFont(fontInfo);
2035
+ this.storeScore.setLyricFont(fontInfo);
2036
+ this.renderer.setRefresh();
2037
+ return this.renderer.updatePromise();
2038
+ }
2039
+ /**
2040
+ * @param value if false, lyric widths don't affect measure width
2041
+ * @returns
2042
+ */
2043
+ async setLyricAdjustWidth(value: boolean): Promise<void> {
2044
+ this._undoScore('Set Lyric Adj Width');
2045
+ this.score.setLyricAdjustWidth(value);
2046
+ this.storeScore.setLyricAdjustWidth(value);
2047
+ this.renderer.setRefresh();
2048
+ return this.renderer.updatePromise();
2049
+ }
2050
+ /**
2051
+ * delete selected measures
2052
+ * @returns
2053
+ */
2054
+ async deleteMeasure(): Promise<void> {
2055
+ this._undoScore('Delete Measure');
2056
+ if (this.storeScore.staves[0].measures.length < 2) {
2057
+ return;
2058
+ }
2059
+ const selections = SmoSelection.getMeasureList(this.tracker.selections);
2060
+ // THe measures get renumbered, so keep the index at 0
2061
+ const index = selections[0].selector.measure;
2062
+ for (var i = 0; i < selections.length; ++i) {
2063
+ // Unrender the deleted measure
2064
+ this.score.staves.forEach((staff) => {
2065
+ this.tracker.clearMeasureMap(staff.measures[index]);
2066
+ this.renderer.unrenderMeasure(staff.measures[index]);
2067
+ this.renderer.unrenderMeasure(staff.measures[staff.measures.length - 1]);
2068
+ // A little hacky - delete the modifiers if they start or end on
2069
+ // the measure
2070
+ staff.renderableModifiers.forEach((modifier) => {
2071
+ if (modifier.startSelector.measure === index || modifier.endSelector.measure === index) {
2072
+ if (modifier.logicalBox) {
2073
+ const context = this.renderer.renderer.getRenderer(modifier.logicalBox);
2074
+ if (context) {
2075
+ $(context.svg).find('g.' + modifier.attrs.id).remove();
2076
+ }
2077
+ }
2078
+ }
2079
+ });
2080
+ });
2081
+ // Remove the SVG artifacts mapped to this measure.
2082
+ this.score.deleteMeasure(index);
2083
+ this.storeScore.deleteMeasure(index);
2084
+ // Note: index doesn't increment since there are now 1 fewer measures
2085
+ };
2086
+ this.renderer.setRefresh();
2087
+ return this.renderer.updatePromise();
2088
+ }
2089
+ /**
2090
+ * add number of measures, with default notes selections
2091
+ * @param append
2092
+ * @param numberToAdd
2093
+ * @returns
2094
+ */
2095
+ async addMeasures(append: boolean, numberToAdd: number): Promise<void> {
2096
+ let pos = 0;
2097
+ let ix = 0;
2098
+ this._undoScore('Add Measure');
2099
+ for (ix = 0; ix < numberToAdd; ++ix) {
2100
+ const measure = this.tracker.getFirstMeasureOfSelection();
2101
+ if (measure) {
2102
+ const nmeasure = SmoMeasure.getDefaultMeasureWithNotes(measure);
2103
+ pos = measure.measureNumber.measureIndex;
2104
+ if (append) {
2105
+ pos += 1;
2106
+ }
2107
+ nmeasure.measureNumber.measureIndex = pos;
2108
+ nmeasure.setActiveVoice(0);
2109
+ this.score.addMeasure(pos);
2110
+ this.storeScore.addMeasure(pos);
2111
+ }
2112
+ }
2113
+ const startMeasure = Math.max(pos - (ix - 1), 0);
2114
+ const startSelector = SmoSelector.default;
2115
+ const endSelector = SmoSelector.default;
2116
+ startSelector.measure = startMeasure;
2117
+ endSelector.measure = pos;
2118
+ this._renderRectangle(startSelector, endSelector);
2119
+ this.renderer.setRefresh();
2120
+ return this.renderer.updatePromise();
2121
+ }
2122
+ /**
2123
+ * add a single measure before or after selection
2124
+ * @param append
2125
+ * @returns
2126
+ */
2127
+ async addMeasure(append: boolean): Promise<void> {
2128
+ this._undoScore('Add Measure');
2129
+ let pos = 0;
2130
+ const measure = this.tracker.getFirstMeasureOfSelection();
2131
+ if (!measure) {
2132
+ return;
2133
+ }
2134
+ const nmeasure = SmoMeasure.getDefaultMeasureWithNotes(measure);
2135
+ pos = measure.measureNumber.measureIndex;
2136
+ if (append) {
2137
+ pos += 1;
2138
+ }
2139
+ nmeasure.measureNumber.measureIndex = pos;
2140
+ nmeasure.setActiveVoice(0);
2141
+ this.score.addMeasure(pos);
2142
+ this.storeScore.addMeasure(pos);
2143
+ this.renderer.clearLine(measure);
2144
+ this.renderer.setRefresh();
2145
+ return this.renderer.updatePromise();
2146
+ }
2147
+ /**
2148
+ * remove an entire line of music
2149
+ * @returns
2150
+ */
2151
+ async removeStaff(): Promise<void> {
2152
+ this._undoScore('Remove Instrument');
2153
+ if (this.storeScore.staves.length < 2 || this.score.staves.length < 2) {
2154
+ return;
2155
+ }
2156
+ // if we are looking at a subset of the score,
2157
+ // revert to the full score view before removing the staff.
2158
+ const toRemove: number[] = [];
2159
+ const selectedStaves: Record<number, boolean> = {};
2160
+ this.tracker.selections.forEach((sel) => {
2161
+ const scoreSel = this._getEquivalentSelection(sel);
2162
+ if (!selectedStaves[scoreSel!.selector.staff]) {
2163
+ selectedStaves[scoreSel!.selector.staff] = true;
2164
+ toRemove.push(scoreSel!.selector.staff);
2165
+ }
2166
+ });
2167
+ // Sort in descending order so we don't mess up the staff indices as we remove
2168
+ toRemove.sort((a, b) => b - a);
2169
+ toRemove.forEach((staffIndex) => {
2170
+ SmoOperation.removeStaff(this.storeScore, staffIndex);
2171
+ });
2172
+ this.viewAll();
2173
+ this.renderer.setRefresh();
2174
+ return this.renderer.updatePromise();
2175
+ }
2176
+ /**
2177
+ * Add a new staff to an existing score, with default instrument for the staff part.
2178
+ * We base the staff parameters on a stave that currently exists in the score.
2179
+ * @param instrument
2180
+ * @returns
2181
+ */
2182
+ async addStaff(instrument: SmoSystemStaffParams): Promise<void> {
2183
+ this._undoScore('Add Instrument');
2184
+ // if we are looking at a subset of the score, we won't see the new staff. So
2185
+ // revert to the full view
2186
+ const entry = instrument.measureInstrumentMap[0];
2187
+ entry.startSelector.measure = 0;
2188
+ entry.endSelector.measure = this.storeScore.staves[0].measures.length - 1;
2189
+ const staff = SmoOperation.addStaff(this.storeScore, instrument);
2190
+ staff.updateInstrumentOffsets();
2191
+ this.storeScore.setNoteInstrumentProperties();
2192
+
2193
+ if (instrument.staffId > 0) {
2194
+ const selection = SmoSelection.measureSelection(this.storeScore, instrument.staffId - 1, 0);
2195
+ const sel = SmoSelector.default;
2196
+ sel.staff = instrument.staffId - 1;
2197
+ if (selection) {
2198
+ let grp = this.storeScore.getSystemGroupForStaff(selection);
2199
+ if (grp) {
2200
+ grp.endSelector.staff = instrument.staffId;
2201
+ } else {
2202
+ let grp = new SmoSystemGroup(SmoSystemGroup.defaults);
2203
+ grp.startSelector.staff = instrument.staffId - 1;
2204
+ grp.endSelector.staff = instrument.staffId;
2205
+ this.storeScore.systemGroups.push(grp);
2206
+ }
2207
+ }
2208
+ }
2209
+ this.viewAll();
2210
+ return this.renderer.updatePromise();
2211
+ }
2212
+ /**
2213
+ * Update part info assumes that the part is currently exposed - that
2214
+ * staff 0 is the first staff in the part prior to editing.
2215
+ * @param info
2216
+ */
2217
+ async updatePartInfo(info: SmoPartInfo): Promise<void> {
2218
+ let i: number = 0;
2219
+ this._undoScore('Update part info');
2220
+ const storeStaff = this.staffMap[0] - info.stavesBefore;
2221
+ const partLength = info.stavesBefore + info.stavesAfter + 1;
2222
+ const resetView = !SmoLayoutManager.areLayoutsEqual(info.layoutManager.getGlobalLayout(), this.score.layoutManager!.getGlobalLayout());
2223
+ const restChange = this.score.staves[0].partInfo.expandMultimeasureRests != info.expandMultimeasureRests;
2224
+ const stavesChange = this.score.staves[0].partInfo.stavesAfter !== info.stavesAfter;
2225
+ // The displayed part's layout has not been replaced yet, so it is the 'before' value.
2226
+ // Reposition the part's text groups the same way setGlobalLayout does for the score.
2227
+ const previousLayout = this.score.layoutManager!.getGlobalLayout();
2228
+ const newLayout = info.layoutManager.getGlobalLayout();
2229
+ if (previousLayout.svgScale !== newLayout.svgScale || previousLayout.pageWidth !== newLayout.pageWidth ||
2230
+ previousLayout.pageHeight !== newLayout.pageHeight) {
2231
+ const partText: SmoTextGroup[] = [];
2232
+ for (i = 0; i < partLength; ++i) {
2233
+ partText.push(...(this.storeScore.staves[storeStaff + i]?.partInfo.textGroups ?? []));
2234
+ partText.push(...(this.score.staves[i]?.partInfo.textGroups ?? []));
2235
+ }
2236
+ SuiScoreViewOperations.repositionTextGroups(partText, previousLayout, newLayout);
2237
+ }
2238
+ this.PartName.value = info.partName;
2239
+ for (i = 0; i < partLength; ++i) {
2240
+ const nStaffIndex = storeStaff + i;
2241
+ const nInfo = new SmoPartInfo(info);
2242
+ nInfo.stavesBefore = i;
2243
+ nInfo.stavesAfter = partLength - i - 1;
2244
+ this.storeScore.staves[nStaffIndex].partInfo = nInfo;
2245
+ // Make sure that the next stave in the score has the correct 'staves before' setting
2246
+ if (this.storeScore.staves.length > nStaffIndex + 1) {
2247
+ if (nInfo.stavesAfter === 0) {
2248
+ const nextStaff = this.storeScore.staves[nStaffIndex + 1];
2249
+ nextStaff.partInfo.stavesBefore = 0;
2250
+ const nextStaffDisplayIndex = this.staffMap.findIndex((x) => x === nStaffIndex + 1);
2251
+ if (nextStaffDisplayIndex >= 0) {
2252
+ this.score.staves[nextStaffDisplayIndex].partInfo =
2253
+ new SmoPartInfo(nextStaff.partInfo);
2254
+ }
2255
+ }
2256
+ }
2257
+ // If the staff index is currently displayed,
2258
+ const displayedIndex = this.staffMap.findIndex((x) => x === nStaffIndex);
2259
+ if (displayedIndex >= 0) {
2260
+ this.score.staves[displayedIndex].partInfo = new SmoPartInfo(nInfo);
2261
+ this.score.layoutManager = nInfo.layoutManager;
2262
+ }
2263
+ }
2264
+ if (resetView || restChange || stavesChange) {
2265
+ SmoOperation.computeMultipartRest(this.score);
2266
+ // this.resetPartView();
2267
+ this.renderer.rerenderAll()
2268
+ }
2269
+ return this.renderer.updatePromise();
2270
+ }
2271
+ /**
2272
+ * A simpler API for applications to add a new staff to the score.
2273
+ * @param params - the instrument, which determines clef, etc.
2274
+ * @returns
2275
+ */
2276
+ async addStaffSimple(params: Partial<SmoInstrumentParams>): Promise<void> {
2277
+ const instrumentParams = SmoInstrument.defaults;
2278
+ instrumentParams.startSelector.staff = instrumentParams.endSelector.staff = this.score.staves.length;
2279
+ instrumentParams.clef = params.clef ?? instrumentParams.clef;
2280
+
2281
+ const staffParams = SmoSystemStaff.defaults;
2282
+ staffParams.staffId = this.storeScore.staves.length; // add a staff
2283
+ staffParams.measureInstrumentMap[0] = new SmoInstrument(instrumentParams);
2284
+ this.addStaff(staffParams);
2285
+ return this.renderer.updatePromise();
2286
+ }
2287
+ /**
2288
+ * Save the score to local storage.
2289
+ */
2290
+ quickSave() {
2291
+ const scoreStr = JSON.stringify(this.storeScore.serialize());
2292
+ localStorage.setItem(smoSerialize.localScore, scoreStr);
2293
+ this.markScoreSaved();
2294
+ }
2295
+ /**
2296
+ * Called when the user has saved the score to a file. Only a save in the full Smoosic
2297
+ * format counts: other formats (MusicXML, MIDI...) lose information, so the score still
2298
+ * has unsaved changes. The save dialog doesn't know which formats are lossy; we do.
2299
+ * @param extension the extension of the file that was saved, e.g. '.json'
2300
+ * @returns true if the score is now considered saved
2301
+ */
2302
+ recordSave(extension: string): boolean {
2303
+ if (!isFullSaveFormat(extension)) {
2304
+ return false;
2305
+ }
2306
+ this.markScoreSaved();
2307
+ return true;
2308
+ }
2309
+ updateRepeatCount(count: number) {
2310
+ const measureSelections = this.undoTrackerMeasureSelections('repeat bar');
2311
+ const symbol = count > 0 ? true : false;
2312
+ measureSelections.forEach((ms) => {
2313
+ const store = this._getEquivalentSelection(ms);
2314
+ ms.measure.repeatCount = count;
2315
+ ms.measure.repeatSymbol = symbol;
2316
+ if (store) {
2317
+ store.measure.repeatCount = count;
2318
+ store.measure.repeatSymbol = symbol;
2319
+ }
2320
+ });
2321
+ this._renderChangedMeasures(measureSelections);
2322
+ return this.updatePromise();
2323
+ }
2324
+ /**
2325
+ * Update the measure formatting parameters for the current selection
2326
+ * @param format generic measure formatting parameters
2327
+ * @returns
2328
+ */
2329
+ setMeasureFormat(format: SmoMeasureFormat): Promise<any> {
2330
+ const label = 'set measure format';
2331
+ const fromSelector = this.tracker.getExtremeSelection(-1).selector;
2332
+ const toSelector = this.tracker.getExtremeSelection(1).selector;
2333
+ const measureSelections = this.tracker.getSelectedMeasures();
2334
+ // If the formatting is on a part, preserve it in the part's info
2335
+ const isPart = this.isPartExposed();
2336
+ measureSelections.forEach((m) => {
2337
+ this._undoColumn(label, m.selector.measure);
2338
+ SmoOperation.setMeasureFormat(this.score, m, format);
2339
+ if (isPart) {
2340
+ m.staff.partInfo.measureFormatting[m.measure.measureNumber.measureIndex] = new SmoMeasureFormat(format);
2341
+ const alt = this._getEquivalentSelection(m);
2342
+ SmoOperation.setMeasureFormat(this.storeScore, alt!, format);
2343
+ } else {
2344
+ // If we are seeing some set of staves that is not a part, make sure the whole column in the
2345
+ // score is updated.
2346
+ const firstRow = SmoSelection.selectionFromSelector(
2347
+ this.storeScore, {
2348
+ staff: 0, measure: m.selector.measure, voice: m.selector.voice, tick: m.selector.tick, pitches: [] }
2349
+ )
2350
+ SmoOperation.setMeasureFormat(this.storeScore, firstRow!, format);
2351
+ }
2352
+ const alt = this._getEquivalentSelection(m);
2353
+ SmoOperation.setMeasureFormat(this.storeScore, alt!, format);
2354
+ if (isPart) {
2355
+ alt!.staff.partInfo.measureFormatting[m.measure.measureNumber.measureIndex] = new SmoMeasureFormat(format);
2356
+ }
2357
+ });
2358
+ this._renderRectangle(fromSelector, toSelector);
2359
+ return this.renderer.updatePromise();
2360
+ }
2361
+ /**
2362
+ * Remove system breaks from the measure formatting for selected measures
2363
+ * @returns
2364
+ */
2365
+ removeSystemBreaks(): Promise<any> {
2366
+ const label = 'set measure format';
2367
+ const fromSelector = this.tracker.getExtremeSelection(-1).selector;
2368
+ const toSelector = this.tracker.getExtremeSelection(1).selector;
2369
+ const measureSelections = this.tracker.getSelectedMeasures();
2370
+ // If the formatting is on a part, preserve it in the part's info
2371
+ const isPart = this.isPartExposed();
2372
+ measureSelections.forEach((m) => {
2373
+ this._undoColumn(label, m.selector.measure);
2374
+ const format = new SmoMeasureFormat(m.measure.format);
2375
+ format.systemBreak = false;
2376
+ SmoOperation.setMeasureFormat(this.score, m, format);
2377
+ if (isPart) {
2378
+ m.staff.partInfo.measureFormatting[m.measure.measureNumber.measureIndex] = new SmoMeasureFormat(format);
2379
+ }
2380
+ const alt = this._getEquivalentSelection(m);
2381
+ SmoOperation.setMeasureFormat(this.storeScore, alt!, format);
2382
+ if (isPart) {
2383
+ alt!.staff.partInfo.measureFormatting[m.measure.measureNumber.measureIndex] = new SmoMeasureFormat(format);
2384
+ }
2385
+ });
2386
+ this._renderRectangle(fromSelector, toSelector);
2387
+ return this.renderer.updatePromise();
2388
+ }
2389
+ renumberMeasures(measureIndex: number, displayIndex: number) {
2390
+ this.score.updateRenumberingMap(measureIndex, displayIndex);
2391
+ this.storeScore.updateRenumberingMap(measureIndex, displayIndex);
2392
+ const mmsel = SmoSelection.measureSelection(this.score, 0, measureIndex);
2393
+ if (mmsel) {
2394
+ this._renderChangedMeasures([mmsel]);
2395
+ }
2396
+ return this.renderer.updatePromise();
2397
+ }
2398
+ /**
2399
+ * Play the music from the starting selection
2400
+ * @returns
2401
+ */
2402
+ async playFromSelection() {
2403
+ var mm = this.tracker.getExtremeSelection(-1);
2404
+ if (SuiAudioPlayer.playingInstance && SuiAudioPlayer.playingInstance.paused) {
2405
+ SuiAudioPlayer.playingInstance.play();
2406
+ return;
2407
+ }
2408
+ if (SuiAudioPlayer.playing) {
2409
+ return;
2410
+ }
2411
+ new SuiAudioPlayer({ audioAnimation: this.audioAnimation, score: this.score, startIndex: mm.selector.measure, view: this }).play();
2412
+ }
2413
+ stopPlayer() {
2414
+ SuiAudioPlayer.stopPlayer();
2415
+ }
2416
+ pausePlayer() {
2417
+ SuiAudioPlayer.pausePlayer();
2418
+ }
2419
+
2420
+ /**
2421
+ * Proxy calls to move the tracker parameters according to the
2422
+ * rules of the 'Home' key (depending on shift/ctrl/alt)
2423
+ * @param ev
2424
+ * @returns
2425
+ */
2426
+ async moveHome(ev: KeyEvent): Promise<any> {
2427
+ this.tracker.moveHome(ev);
2428
+ await this.renderer.updatePromise();
2429
+ }
2430
+ /**
2431
+ * Proxy calls to move the tracker parameters according to the
2432
+ * rules of the 'End' key (depending on shift/ctrl/alt)
2433
+ * @param ev
2434
+ * @returns
2435
+ */
2436
+ async moveEnd(ev: KeyEvent): Promise<any> {
2437
+ this.tracker.moveEnd(ev);
2438
+ await this.renderer.updatePromise();
2439
+ }
2440
+ /**
2441
+ * Grow the current selection by one to the left, if possible
2442
+ * @param ev
2443
+ * @returns
2444
+ */
2445
+ async growSelectionLeft(): Promise<any> {
2446
+ this.tracker.growSelectionLeft();
2447
+ await this.renderer.updatePromise();
2448
+ }
2449
+ /**
2450
+ * Grow the current selection by one to the right, if possible
2451
+ * @param ev
2452
+ * @returns
2453
+ */
2454
+ async growSelectionRight(): Promise<any> {
2455
+ this.tracker.growSelectionRight();
2456
+ await this.renderer.updatePromise();
2457
+ }
2458
+ /**
2459
+ * Select the next tabbable modifier near one of the selected notes
2460
+ * @param keyEv
2461
+ * @returns
2462
+ */
2463
+ async advanceModifierSelection(keyEv: KeyEvent): Promise<any> {
2464
+ this.tracker.advanceModifierSelection(keyEv);
2465
+ await this.renderer.updatePromise();
2466
+ }
2467
+ /**
2468
+ * Select the next entire measure, if possible
2469
+ * @returns
2470
+ */
2471
+ async growSelectionRightMeasure(): Promise<any> {
2472
+ this.tracker.growSelectionRightMeasure();
2473
+ await this.renderer.updatePromise();
2474
+ }
2475
+ /**
2476
+ * Advance cursor forwards, if possible
2477
+ * @param ev
2478
+ * @returns
2479
+ */
2480
+ async moveSelectionRight(): Promise<any> {
2481
+ this.tracker.moveSelectionRight();
2482
+ await this.renderer.updatePromise();
2483
+ }
2484
+ /**
2485
+ * Advance cursor backwards, if possible
2486
+ * @param ev
2487
+ * @returns
2488
+ */
2489
+ async moveSelectionLeft(): Promise<any> {
2490
+ this.tracker.moveSelectionLeft();
2491
+ await this.renderer.updatePromise();
2492
+ }
2493
+ /**
2494
+ * Advance cursor back entire measure, if possible
2495
+ * @returns
2496
+ */
2497
+ async moveSelectionLeftMeasure(): Promise<any> {
2498
+ this.tracker.moveSelectionLeftMeasure();
2499
+ await this.renderer.updatePromise();
2500
+ }
2501
+ /**
2502
+ * Advance cursor forward one measure, if possible
2503
+ * @returns
2504
+ */
2505
+ async moveSelectionRightMeasure(): Promise<any> {
2506
+ this.tracker.moveSelectionRightMeasure();
2507
+ await this.renderer.updatePromise();
2508
+ }
2509
+ /**
2510
+ * Move cursor to a higher pitch in the current chord, with wrap
2511
+ * @returns
2512
+ */
2513
+ async moveSelectionPitchUp(): Promise<any> {
2514
+ this.tracker.moveSelectionPitchUp();
2515
+ await this.renderer.updatePromise();
2516
+ }
2517
+ /**
2518
+ * Move cursor to a lower pitch in the current chord, with wrap
2519
+ */
2520
+ async moveSelectionPitchDown(): Promise<any> {
2521
+ this.tracker.moveSelectionPitchDown();
2522
+ await this.renderer.updatePromise();
2523
+ }
2524
+ /**
2525
+ * Move cursor up a staff in the system, if possible
2526
+ * @returns
2527
+ */
2528
+ async moveSelectionUp(): Promise<any> {
2529
+ this.tracker.moveSelectionUp();
2530
+ await this.renderer.updatePromise();
2531
+ }
2532
+ /**
2533
+ * Move cursor down a staff in the system, if possible
2534
+ * @returns
2535
+ */
2536
+ async moveSelectionDown(): Promise<any> {
2537
+ this.tracker.moveSelectionDown();
2538
+ await this.renderer.updatePromise();
2539
+ }
2540
+ /**
2541
+ * Set the current suggestions (hover element) as the selection
2542
+ * @returns
2543
+ */
2544
+ async selectSuggestion(evData: KeyEvent): Promise<any> {
2545
+ this.tracker.selectSuggestion(evData);
2546
+ await this.renderer.updatePromise();
2547
+ }
2548
+ /**
2549
+ * Find an element at the given box, and make it the current selection
2550
+ * */
2551
+ async intersectingArtifact(evData: SvgBox): Promise<any> {
2552
+ this.tracker.intersectingArtifact(evData);
2553
+ await this.renderer.updatePromise();
2554
+ }
2555
+ }