smoosic 2.0.1 → 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 (127) hide show
  1. package/build/smoosic.js +171 -78
  2. package/package.json +82 -77
  3. package/release/smoosic.js +171 -78
  4. package/release/styles/fonts/MaterialIconsOutlined-Regular.otf +0 -0
  5. package/release/styles/menus.css +26 -0
  6. package/specs/022-text-reposition-on-resize/spec.md +1 -0
  7. package/specs/027-fix-bottom-modifier-lookup/checklists/requirements.md +38 -0
  8. package/specs/027-fix-bottom-modifier-lookup/contracts/division-lookup-contract.md +51 -0
  9. package/specs/027-fix-bottom-modifier-lookup/data-model.md +43 -0
  10. package/specs/027-fix-bottom-modifier-lookup/plan.md +77 -0
  11. package/specs/027-fix-bottom-modifier-lookup/quickstart.md +36 -0
  12. package/specs/027-fix-bottom-modifier-lookup/research.md +58 -0
  13. package/specs/027-fix-bottom-modifier-lookup/spec.md +105 -0
  14. package/specs/027-fix-bottom-modifier-lookup/tasks.md +167 -0
  15. package/specs/028-unsaved-changes-indicator/checklists/requirements.md +39 -0
  16. package/specs/028-unsaved-changes-indicator/contracts/score-change-contract.md +44 -0
  17. package/specs/028-unsaved-changes-indicator/data-model.md +64 -0
  18. package/specs/028-unsaved-changes-indicator/plan.md +96 -0
  19. package/specs/028-unsaved-changes-indicator/quickstart.md +54 -0
  20. package/specs/028-unsaved-changes-indicator/research.md +68 -0
  21. package/specs/028-unsaved-changes-indicator/spec.md +135 -0
  22. package/specs/028-unsaved-changes-indicator/tasks.md +173 -0
  23. package/specs/029-remove-promise-helpers/checklists/requirements.md +39 -0
  24. package/specs/029-remove-promise-helpers/contracts/public-api-contract.md +32 -0
  25. package/specs/029-remove-promise-helpers/data-model.md +45 -0
  26. package/specs/029-remove-promise-helpers/plan.md +86 -0
  27. package/specs/029-remove-promise-helpers/quickstart.md +53 -0
  28. package/specs/029-remove-promise-helpers/research.md +71 -0
  29. package/specs/029-remove-promise-helpers/spec.md +107 -0
  30. package/specs/029-remove-promise-helpers/tasks.md +164 -0
  31. package/specs/030-copy-paste-voices/checklists/requirements.md +39 -0
  32. package/specs/030-copy-paste-voices/contracts/voice-copy-paste-contract.md +47 -0
  33. package/specs/030-copy-paste-voices/data-model.md +63 -0
  34. package/specs/030-copy-paste-voices/plan.md +80 -0
  35. package/specs/030-copy-paste-voices/quickstart.md +50 -0
  36. package/specs/030-copy-paste-voices/research.md +80 -0
  37. package/specs/030-copy-paste-voices/spec.md +124 -0
  38. package/specs/030-copy-paste-voices/tasks.md +183 -0
  39. package/specs/031-select-voice/checklists/requirements.md +39 -0
  40. package/specs/031-select-voice/contracts/select-voice-contract.md +43 -0
  41. package/specs/031-select-voice/data-model.md +47 -0
  42. package/specs/031-select-voice/plan.md +79 -0
  43. package/specs/031-select-voice/quickstart.md +43 -0
  44. package/specs/031-select-voice/research.md +55 -0
  45. package/specs/031-select-voice/spec.md +113 -0
  46. package/specs/031-select-voice/tasks.md +171 -0
  47. package/src/application/application.ts +464 -459
  48. package/src/common/promiseHelpers.ts +2 -2
  49. package/src/render/audio/samples.ts +117 -118
  50. package/src/render/sui/pageDivisions.ts +58 -0
  51. package/src/render/sui/renderState.ts +469 -464
  52. package/src/render/sui/scoreChangeState.ts +62 -0
  53. package/src/render/sui/scoreView.ts +30 -0
  54. package/src/render/sui/scoreViewOperations.ts +2555 -2380
  55. package/src/render/sui/svgPageMap.ts +16 -17
  56. package/src/render/sui/textEdit.ts +310 -311
  57. package/src/render/sui/tracker.ts +40 -0
  58. package/src/render/vex/vxNote.ts +3 -1
  59. package/src/smo/xform/copypaste.ts +304 -4
  60. package/src/smo/xform/selections.ts +68 -0
  61. package/src/smo/xform/undo.ts +9 -0
  62. package/src/styles/menus.css +26 -0
  63. package/src/ui/buttons/ribbon.ts +3 -1
  64. package/src/ui/components/buttons/sidebar.vue +15 -6
  65. package/src/ui/components/dialogs/library.vue +3 -1
  66. package/src/ui/components/dialogs/unsavedChanges.vue +44 -0
  67. package/src/ui/dialogs/adapter.ts +181 -183
  68. package/src/ui/dialogs/addMeasure.ts +97 -97
  69. package/src/ui/dialogs/annotationVue.ts +56 -56
  70. package/src/ui/dialogs/audioSettings.ts +121 -123
  71. package/src/ui/dialogs/chordChangeVue.ts +46 -46
  72. package/src/ui/dialogs/clefChange.ts +53 -53
  73. package/src/ui/dialogs/customTuplets.ts +95 -96
  74. package/src/ui/dialogs/customTupletsVue.ts +47 -47
  75. package/src/ui/dialogs/dialog.ts +627 -620
  76. package/src/ui/dialogs/durations.ts +34 -34
  77. package/src/ui/dialogs/dynamics.ts +140 -142
  78. package/src/ui/dialogs/factory.ts +198 -198
  79. package/src/ui/dialogs/fileDialogs.ts +245 -179
  80. package/src/ui/dialogs/fonts.ts +93 -93
  81. package/src/ui/dialogs/globalLayout.ts +40 -40
  82. package/src/ui/dialogs/gracenote.ts +31 -31
  83. package/src/ui/dialogs/hairpin.ts +108 -110
  84. package/src/ui/dialogs/hairpinVue.ts +51 -51
  85. package/src/ui/dialogs/instrument.ts +111 -111
  86. package/src/ui/dialogs/keySignature.ts +175 -176
  87. package/src/ui/dialogs/keySignatureVue.ts +47 -47
  88. package/src/ui/dialogs/library.ts +207 -207
  89. package/src/ui/dialogs/libraryVue.ts +62 -48
  90. package/src/ui/dialogs/lyricVue.ts +46 -46
  91. package/src/ui/dialogs/measureFormat.ts +78 -78
  92. package/src/ui/dialogs/microtones.ts +147 -147
  93. package/src/ui/dialogs/noteHead.ts +319 -319
  94. package/src/ui/dialogs/pageLayout.ts +61 -61
  95. package/src/ui/dialogs/partInfo.ts +60 -60
  96. package/src/ui/dialogs/pedalMarking.ts +117 -117
  97. package/src/ui/dialogs/pedalMarkingVue.ts +73 -73
  98. package/src/ui/dialogs/pitch.ts +352 -352
  99. package/src/ui/dialogs/preferences.ts +40 -40
  100. package/src/ui/dialogs/rehearsalMark.ts +64 -64
  101. package/src/ui/dialogs/rehearsalMarkVue.ts +57 -57
  102. package/src/ui/dialogs/scoreId.ts +35 -36
  103. package/src/ui/dialogs/scoreView.ts +42 -42
  104. package/src/ui/dialogs/slur.ts +308 -310
  105. package/src/ui/dialogs/slurVue.ts +91 -91
  106. package/src/ui/dialogs/staffGroup.ts +112 -112
  107. package/src/ui/dialogs/tabNote.ts +84 -84
  108. package/src/ui/dialogs/tabStave.ts +182 -182
  109. package/src/ui/dialogs/tempo.ts +261 -263
  110. package/src/ui/dialogs/tempoVue.ts +73 -73
  111. package/src/ui/dialogs/textBlockVue.ts +127 -127
  112. package/src/ui/dialogs/textBracket.ts +114 -116
  113. package/src/ui/dialogs/textBracketVue.ts +56 -56
  114. package/src/ui/dialogs/tie.ts +140 -142
  115. package/src/ui/dialogs/timeSignature.ts +65 -66
  116. package/src/ui/dialogs/transposeScore.ts +39 -39
  117. package/src/ui/dialogs/unsavedChanges.ts +43 -0
  118. package/src/ui/dialogs/volta.ts +120 -122
  119. package/src/ui/dialogs/voltaVue.ts +51 -51
  120. package/src/ui/fileio/library.ts +110 -111
  121. package/src/ui/menus/edit.ts +100 -1
  122. package/src/ui/menus/file.ts +19 -3
  123. package/tests/pageDivisions.ts +156 -0
  124. package/tests/promiseHelpersUsage.ts +142 -0
  125. package/tests/scoreChangeState.ts +102 -0
  126. package/tests/selectVoice.ts +189 -0
  127. package/tests/voiceCopyPaste.ts +417 -0
@@ -1,465 +1,470 @@
1
- // [Smoosic](https://github.com/AaronDavidNewman/Smoosic)
2
- // Copyright (c) Aaron David Newman 2021.
3
- /**
4
- * Classes to support the state machine associated with background music rendering.
5
- * @module renderState
6
- */
7
- import { SmoMeasure } from '../../smo/data/measure';
8
- import { UndoBuffer, UndoEntry } from '../../smo/xform/undo';
9
- import { SmoRenderConfiguration } from './configuration';
10
- import { PromiseHelpers } from '../../common/promiseHelpers';
11
- import { SmoSelection, SmoSelector } from '../../smo/xform/selections';
12
- import { VxSystem } from '../vex/vxSystem';
13
- import { SmoScore } from '../../smo/data/score';
14
- import { SmoTextGroup } from '../../smo/data/scoreText';
15
- import { displayMode } from '../../smo/data/scoreModifiers';
16
- import { SuiMapper, SuiRendererBase } from './mapper';
17
- import { SmoSystemStaff } from '../../smo/data/systemStaff';
18
- import { SuiScoreRender, ScoreRenderParams } from './scoreRender';
19
- import { SuiExceptionHandler } from '../../ui/exceptions';
20
- import { VexFlow, setFontStack } from '../../common/vex';
21
- import { layoutDebug } from './layoutDebug';
22
- import { SuiNavigation } from './configuration';
23
- declare var $: any;
24
-
25
- export var scoreChangeEvent = 'smoScoreChangeEvent';
26
- /**
27
- * Manage the state of the score rendering. The score can be rendered either completely,
28
- * or partially for editing. This class works with the RenderDemon to decide when to
29
- * render the score after it has been modified, and keeps track of what the current
30
- * render state is (dirty, etc.)
31
- * @category SuiRender
32
- * */
33
- export class SuiRenderState implements SuiRendererBase {
34
- static debugMask: number = 0;
35
- dirty: boolean;
36
- replaceQ: SmoSelection[];
37
- stateRepCount: 0;
38
- viewportChanged: boolean;
39
- _resetViewport: boolean;
40
- measureMapper: SuiMapper | null;
41
- passState: number = SuiRenderState.passStates.initial;
42
- _score: SmoScore | null = null;
43
- _backupZoomScale: number = 0;
44
- backupDisplayMode: displayMode = 'vertical';
45
- renderer: SuiScoreRender;
46
- idleRedrawTime: number;
47
- idleLayoutTimer: number = 0; // how long the score has been idle
48
- demonPollTime: number;
49
- handlingRedraw: boolean = false;
50
- // signal to render demon that we have suspended background
51
- // rendering because we are recording or playing actions.
52
- suspendRendering: boolean = false;
53
- undoBuffer: UndoBuffer;
54
- navigation: SuiNavigation;
55
- undoStatus: number = 0;
56
- debug: layoutDebug;
57
-
58
- constructor(config: ScoreRenderParams) {
59
- this.dirty = true;
60
- this.replaceQ = [];
61
- this.stateRepCount = 0;
62
- this.navigation = config.config.navigation;
63
-
64
- this.setPassState(SuiRenderState.passStates.initial, 'ctor');
65
- this.viewportChanged = false;
66
- this._resetViewport = false;
67
- this.measureMapper = null;
68
- this.debug = config.debug;
69
- this.renderer = new SuiScoreRender(config);
70
- this.idleRedrawTime = config.config.idleRedrawTime;
71
- this.demonPollTime = config.config.demonPollTime;
72
- this.undoBuffer = config.undoBuffer;
73
- }
74
- get elementId() {
75
- return this.renderer.elementId;
76
- }
77
- get pageMap() {
78
- return this.renderer.vexContainers;
79
- }
80
- // ### setMeasureMapper
81
- // DI/notifier pattern. The measure mapper/tracker is updated when the score is rendered
82
- // so the UI stays in sync with the location of elements in the score.
83
- setMeasureMapper(mapper: SuiMapper) {
84
- this.measureMapper = mapper;
85
- this.renderer.measureMapper = mapper;
86
- }
87
- set stepMode(value: boolean) {
88
- this.suspendRendering = value;
89
- this.renderer.autoAdjustRenderTime = !value;
90
- if (this.measureMapper) {
91
- this.measureMapper.deferHighlightMode = !value;
92
- }
93
- }
94
-
95
- static get passStates(): Record<string, number> {
96
- return { initial: 0, clean: 2, replace: 3 };
97
- }
98
- get renderElement(): Element {
99
- return this.elementId;
100
- }
101
- notifyFontChange() {
102
- setFontStack(this.score!.engravingFont);
103
- }
104
- addToReplaceQueue(selection: SmoSelection | SmoSelection[]) {
105
- let selections: SmoSelection[] = [];
106
- if (!Array.isArray(selection)) {
107
- selections = [selection];
108
- } else {
109
- selections = selection;
110
- }
111
- if (this.passState === SuiRenderState.passStates.clean ||
112
- this.passState === SuiRenderState.passStates.replace) {
113
- selections.forEach((selection) => {
114
- const existing = this.replaceQ.find((sel) =>
115
- sel.selector.staff === selection.selector.staff && sel.selector.measure === selection.selector.measure);
116
- if (existing) {
117
- existing._measure = selection._measure;
118
- } else {
119
- this.replaceQ.push(selection);
120
- }
121
- })
122
- this.setDirty();
123
- }
124
- }
125
- addColumnToReplaceQueue(mm: number) {
126
- if (!this.score) {
127
- return;
128
- }
129
- for (let i = 0; i < this.score.staves.length; ++i) {
130
- const selection = SmoSelection.measureSelection(this.score, i, mm);
131
- if (selection) {
132
- this.addToReplaceQueue(selection);
133
- }
134
- }
135
- }
136
- setDirty() {
137
- if (!this.dirty) {
138
- this.dirty = true;
139
- if (this.passState === SuiRenderState.passStates.clean) {
140
- this.setPassState(SuiRenderState.passStates.replace, 'setDirty');
141
- }
142
- }
143
- }
144
- setRefresh() {
145
- this.dirty = true;
146
- this.setPassState(SuiRenderState.passStates.initial, 'setRefresh');
147
- }
148
- rerenderAll() {
149
- this.dirty = true;
150
- this.setPassState(SuiRenderState.passStates.initial, 'rerenderAll');
151
- this._resetViewport = true;
152
- }
153
- clearLine(measure: SmoMeasure) {
154
- const page = measure.svg.pageIndex;
155
- this.renderer.clearRenderedPage(page);
156
- }
157
- get renderStateClean() {
158
- return this.passState === SuiRenderState.passStates.clean && this.renderer.backgroundRender === false;
159
- }
160
- get renderStateRendered() {
161
- return (this.passState === SuiRenderState.passStates.clean && this.renderer.backgroundRender === false) ||
162
- (this.passState === SuiRenderState.passStates.replace && this.replaceQ.length === 0 && this.renderer.backgroundRender === false);
163
- }
164
- /**
165
- * Do a quick re-render of a measure that has changed, defer the whole score.
166
- * @returns
167
- */
168
- replaceMeasures() {
169
- const promise = new Promise<void>((resolve, reject) => {
170
- try {
171
- const staffMap: Record<number | string, { system: VxSystem, staff: SmoSystemStaff }> = {};
172
- if (this.score === null || this.measureMapper === null || this.replaceQ.length === 0) {
173
- resolve();
174
- return;
175
- }
176
- this.replaceQ.forEach((change) => {
177
- this.renderer.replaceSelection(staffMap, change);
178
- });
179
- Object.keys(staffMap).forEach((key) => {
180
- const obj = staffMap[key];
181
- this.renderer.renderModifiers(obj.staff, obj.system);
182
- obj.system.renderEndings(this.measureMapper!.scroller);
183
- obj.system.renderRehearsalMarks();
184
- obj.system.updateLyricOffsets();
185
- });
186
- this.replaceQ = [];
187
- resolve();
188
- } catch (ex) {
189
- console.error(ex);
190
- SuiExceptionHandler.instance.exceptionHandler(ex);
191
- this.handlingRedraw = false;
192
- reject(ex);
193
- }
194
- });
195
- return promise;
196
- }
197
- async preserveScroll() {
198
- const scrollState = this.measureMapper!.scroller.scrollState;
199
- await this.renderPromise();
200
- this.measureMapper!.scroller.restoreScrollState(scrollState);
201
- }
202
-
203
- _renderStatePromise(condition: () => boolean): Promise<void> {
204
- const oldSuspend = this.suspendRendering;
205
- this.suspendRendering = false;
206
- const self = this;
207
- const endAction = () => {
208
- self.suspendRendering = oldSuspend;
209
- };
210
- return PromiseHelpers.makePromise(condition, endAction, null, this.demonPollTime);
211
- }
212
- // ### renderPromise
213
- // return a promise that resolves when the score is in a fully rendered state.
214
- renderPromise(): Promise<void> {
215
- return this._renderStatePromise(() => this.renderStateClean);
216
- }
217
-
218
- // ### renderPromise
219
- // return a promise that resolves when the score is in a fully rendered state.
220
- async updatePromise() {
221
- await this.replaceMeasures();
222
- return this._renderStatePromise(() => this.renderStateRendered);
223
- }
224
- async handleRedrawTimer() {
225
- if (this.handlingRedraw) {
226
- return;
227
- }
228
- if (this.suspendRendering) {
229
- return;
230
- }
231
- this.handlingRedraw = true;
232
- try {
233
- const redrawTime = Math.max(this.renderer.renderTime, this.idleRedrawTime);
234
- // If there has been a change, redraw the score
235
- if (this.passState === SuiRenderState.passStates.initial) {
236
- this.dirty = true;
237
- this.undoStatus = this.undoBuffer.opCount;
238
- this.idleLayoutTimer = Date.now();
239
-
240
- // indicate the display is 'dirty' and we will be refreshing it.
241
- $('body').addClass('refresh-1');
242
- // Sort of a hack. If the viewport changed, the scroll state is already reset
243
- // so we can't preserver the scroll state.
244
- if (!this.renderer.viewportChanged) {
245
- this.preserveScroll();
246
- }
247
- await this.render();
248
- } else if (this.passState === SuiRenderState.passStates.replace && this.undoStatus === this.undoBuffer.opCount) {
249
- // Consider navigation as activity when deciding to refresh
250
- this.idleLayoutTimer = Math.max(this.idleLayoutTimer, this.measureMapper!.getIdleTime());
251
- $('body').addClass('refresh-1');
252
- // Do we need to refresh the score?
253
- if (this.renderer.backgroundRender === false && Date.now() - this.idleLayoutTimer > redrawTime) {
254
- this.passState = SuiRenderState.passStates.initial;
255
- if (!this.renderer.viewportChanged) {
256
- this.preserveScroll();
257
- }
258
- this.render();
259
- }
260
- } else {
261
- this.idleLayoutTimer = Date.now();
262
- this.undoStatus = this.undoBuffer.opCount;
263
- if (this.replaceQ.length > 0) {
264
- this.render();
265
- }
266
- }
267
- if (this.debug.testThrow) {
268
- this.debug.testThrow = false;
269
- throw ('Test throw full render')
270
- }
271
- this.handlingRedraw = false;
272
- } catch (ex) {
273
- console.error(ex);
274
- SuiExceptionHandler.instance.exceptionHandler(ex);
275
- this.handlingRedraw = false;
276
- }
277
- }
278
- delay2 = async () => {
279
- return new Promise<void>((resolve) => {
280
- setTimeout(() => {
281
- resolve();
282
- }, this.demonPollTime);
283
- });
284
- }
285
- async pollRedrawTask() {
286
- while (true) {
287
- await this.handleRedrawTimer();
288
- await this.delay2();
289
- }
290
- }
291
- pollRedraw() {
292
- setTimeout(async () => {
293
- this.pollRedrawTask();
294
- }, 1);
295
- }
296
-
297
- startDemon() {
298
- this.pollRedraw();
299
- }
300
- renderTextGroup(gg: SmoTextGroup) {
301
- this.renderer.renderTextGroup(gg);
302
- }
303
- /**
304
- * Set the SVG viewport
305
- * @param reset whether to re-render the entire SVG DOM
306
- * @returns
307
- */
308
- setViewport() {
309
- if (!this.score || !this.renderer) {
310
- return;
311
- }
312
-
313
- this.renderer.setViewport();
314
- const displayMode = this.score.layoutManager!.getGlobalLayout().displayMode;
315
- this.navigation.displayMode = displayMode;
316
- this.score!.staves.forEach((staff) => {
317
- staff.measures.forEach((measure) => {
318
- if (measure.svg.logicalBox) {
319
- measure.svg.history = ['reset'];
320
- }
321
- });
322
- });
323
- }
324
- async renderForPrintPromise(): Promise<any> {
325
- $('body').addClass('print-render');
326
- const self = this;
327
- if (!this.score) {
328
- return;
329
- }
330
- const layoutMgr = this.score!.layoutManager!;
331
- const layout = layoutMgr.getGlobalLayout();
332
- const originalDisplayMode = layout.displayMode;
333
- const originalZoomScale = layout.zoomScale;
334
- this._backupZoomScale = layout.zoomScale;
335
- this.backupDisplayMode = layout.displayMode;
336
- layout.zoomScale = 1.0;
337
- layout.displayMode = 'vertical';
338
- layoutMgr.updateGlobalLayout(layout);
339
- this.setViewport();
340
- this.setRefresh();
341
-
342
- const promise = new Promise<void>((resolve) => {
343
- const poll = () => {
344
- setTimeout(() => {
345
- if (!self.dirty && !self.renderer.backgroundRender) {
346
- // tracker.highlightSelection();
347
- $('body').removeClass('print-render');
348
- $('.vf-selection').remove();
349
- $('body').addClass('printing');
350
- $(this.navigation.scrollContainer).css('height', '');
351
- layout.displayMode = originalDisplayMode;
352
- layout.zoomScale = originalZoomScale;
353
- layoutMgr.updateGlobalLayout(layout);
354
- resolve();
355
- } else {
356
- poll();
357
- }
358
- }, 500);
359
- };
360
- poll();
361
- });
362
- return promise;
363
- }
364
-
365
- restoreLayoutAfterPrint() {
366
- const layout = this.score!.layoutManager!.getGlobalLayout();
367
- layout.zoomScale = this._backupZoomScale;
368
- layout.displayMode = this.backupDisplayMode;
369
- this.score!.layoutManager!.updateGlobalLayout(layout);
370
- this.setViewport();
371
- this.setRefresh();
372
- }
373
-
374
- setPassState(st: number, location: string) {
375
- const oldState = this.passState;
376
- let msg = '';
377
- if (oldState !== st) {
378
- this.stateRepCount = 0;
379
- } else {
380
- this.stateRepCount += 1;
381
- }
382
-
383
- msg = location + ': passState ' + this.passState + '=>' + st;
384
- if (this.stateRepCount > 0) {
385
- msg += ' (' + this.stateRepCount + ')';
386
- }
387
- if (SuiRenderState.debugMask) {
388
- console.log(msg);
389
- }
390
- this.passState = st;
391
- }
392
-
393
- get score(): SmoScore | null {
394
- return this._score;
395
- }
396
-
397
- // used for debugging and drawing dots.
398
- dbgDrawDot(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise: boolean) {
399
- const context = this.renderer.getRenderer({ x, y });
400
- if (context) {
401
- context.getContext().beginPath();
402
- context.getContext().arc(x, y, radius, startAngle, endAngle, counterclockwise);
403
- context.getContext().closePath();
404
- context.getContext().fill();
405
- }
406
- }
407
- set score(score: SmoScore | null) {
408
- if (score === null) {
409
- return;
410
- }
411
- /* if (this._score) {
412
- shouldReset = true;
413
- } */
414
- this.setPassState(SuiRenderState.passStates.initial, 'load score');
415
- const font = score.engravingFont;
416
- this.dirty = true;
417
- this._score = score;
418
- this.renderer.score = score;
419
- this.notifyFontChange();
420
- // if (shouldReset) {
421
- this.setViewport();
422
- if (this.measureMapper) {
423
- this.measureMapper.loadScore();
424
- }
425
- }
426
-
427
- unrenderColumn(measure: SmoMeasure) {
428
- this.score!.staves.forEach((staff) => {
429
- this.renderer.unrenderMeasure(staff.measures[measure.measureNumber.measureIndex]);
430
- });
431
- }
432
-
433
- // ### forceRender
434
- // For unit test applictions that want to render right-away
435
- forceRender() {
436
- this.setRefresh();
437
- this.render();
438
- }
439
- unrenderMeasure(measure: SmoMeasure) {
440
- this.renderer.unrenderMeasure(measure);
441
- }
442
- async rerenderTextGroups() {
443
- await this.renderer.rerenderTextGroups();
444
- }
445
- async unrenderTextGroups() {
446
- this.renderer.unrenderTextGroups();
447
- }
448
- async render(): Promise<any> {
449
- if (this._resetViewport) {
450
- this.setViewport();
451
- this._resetViewport = false;
452
- }
453
- if (SuiRenderState.passStates.replace === this.passState) {
454
- await this.replaceMeasures();
455
- } else if (SuiRenderState.passStates.initial === this.passState) {
456
- if (this.renderer.backgroundRender) {
457
- return;
458
- }
459
- this.renderer.layout();
460
- this.renderer.drawPageLines();
461
- this.setPassState(SuiRenderState.passStates.clean, 'rs: complete render');
462
- }
463
- this.dirty = false;
464
- }
1
+ // [Smoosic](https://github.com/AaronDavidNewman/Smoosic)
2
+ // Copyright (c) Aaron David Newman 2021.
3
+ /**
4
+ * Classes to support the state machine associated with background music rendering.
5
+ * @module renderState
6
+ */
7
+ import { SmoMeasure } from '../../smo/data/measure';
8
+ import { UndoBuffer, UndoEntry } from '../../smo/xform/undo';
9
+ import { SmoRenderConfiguration } from './configuration';
10
+ import { SmoSelection, SmoSelector } from '../../smo/xform/selections';
11
+ import { VxSystem } from '../vex/vxSystem';
12
+ import { SmoScore } from '../../smo/data/score';
13
+ import { SmoTextGroup } from '../../smo/data/scoreText';
14
+ import { displayMode } from '../../smo/data/scoreModifiers';
15
+ import { SuiMapper, SuiRendererBase } from './mapper';
16
+ import { SmoSystemStaff } from '../../smo/data/systemStaff';
17
+ import { SuiScoreRender, ScoreRenderParams } from './scoreRender';
18
+ import { SuiExceptionHandler } from '../../ui/exceptions';
19
+ import { VexFlow, setFontStack } from '../../common/vex';
20
+ import { layoutDebug } from './layoutDebug';
21
+ import { SuiNavigation } from './configuration';
22
+ declare var $: any;
23
+
24
+ export var scoreChangeEvent = 'smoScoreChangeEvent';
25
+ /**
26
+ * Manage the state of the score rendering. The score can be rendered either completely,
27
+ * or partially for editing. This class works with the RenderDemon to decide when to
28
+ * render the score after it has been modified, and keeps track of what the current
29
+ * render state is (dirty, etc.)
30
+ * @category SuiRender
31
+ * */
32
+ export class SuiRenderState implements SuiRendererBase {
33
+ static debugMask: number = 0;
34
+ dirty: boolean;
35
+ replaceQ: SmoSelection[];
36
+ stateRepCount: 0;
37
+ viewportChanged: boolean;
38
+ _resetViewport: boolean;
39
+ measureMapper: SuiMapper | null;
40
+ passState: number = SuiRenderState.passStates.initial;
41
+ _score: SmoScore | null = null;
42
+ _backupZoomScale: number = 0;
43
+ backupDisplayMode: displayMode = 'vertical';
44
+ renderer: SuiScoreRender;
45
+ idleRedrawTime: number;
46
+ idleLayoutTimer: number = 0; // how long the score has been idle
47
+ demonPollTime: number;
48
+ handlingRedraw: boolean = false;
49
+ // signal to render demon that we have suspended background
50
+ // rendering because we are recording or playing actions.
51
+ suspendRendering: boolean = false;
52
+ undoBuffer: UndoBuffer;
53
+ navigation: SuiNavigation;
54
+ undoStatus: number = 0;
55
+ debug: layoutDebug;
56
+
57
+ constructor(config: ScoreRenderParams) {
58
+ this.dirty = true;
59
+ this.replaceQ = [];
60
+ this.stateRepCount = 0;
61
+ this.navigation = config.config.navigation;
62
+
63
+ this.setPassState(SuiRenderState.passStates.initial, 'ctor');
64
+ this.viewportChanged = false;
65
+ this._resetViewport = false;
66
+ this.measureMapper = null;
67
+ this.debug = config.debug;
68
+ this.renderer = new SuiScoreRender(config);
69
+ this.idleRedrawTime = config.config.idleRedrawTime;
70
+ this.demonPollTime = config.config.demonPollTime;
71
+ this.undoBuffer = config.undoBuffer;
72
+ }
73
+ get elementId() {
74
+ return this.renderer.elementId;
75
+ }
76
+ get pageMap() {
77
+ return this.renderer.vexContainers;
78
+ }
79
+ // ### setMeasureMapper
80
+ // DI/notifier pattern. The measure mapper/tracker is updated when the score is rendered
81
+ // so the UI stays in sync with the location of elements in the score.
82
+ setMeasureMapper(mapper: SuiMapper) {
83
+ this.measureMapper = mapper;
84
+ this.renderer.measureMapper = mapper;
85
+ }
86
+ set stepMode(value: boolean) {
87
+ this.suspendRendering = value;
88
+ this.renderer.autoAdjustRenderTime = !value;
89
+ if (this.measureMapper) {
90
+ this.measureMapper.deferHighlightMode = !value;
91
+ }
92
+ }
93
+
94
+ static get passStates(): Record<string, number> {
95
+ return { initial: 0, clean: 2, replace: 3 };
96
+ }
97
+ get renderElement(): Element {
98
+ return this.elementId;
99
+ }
100
+ notifyFontChange() {
101
+ setFontStack(this.score!.engravingFont);
102
+ }
103
+ addToReplaceQueue(selection: SmoSelection | SmoSelection[]) {
104
+ let selections: SmoSelection[] = [];
105
+ if (!Array.isArray(selection)) {
106
+ selections = [selection];
107
+ } else {
108
+ selections = selection;
109
+ }
110
+ if (this.passState === SuiRenderState.passStates.clean ||
111
+ this.passState === SuiRenderState.passStates.replace) {
112
+ selections.forEach((selection) => {
113
+ const existing = this.replaceQ.find((sel) =>
114
+ sel.selector.staff === selection.selector.staff && sel.selector.measure === selection.selector.measure);
115
+ if (existing) {
116
+ existing._measure = selection._measure;
117
+ } else {
118
+ this.replaceQ.push(selection);
119
+ }
120
+ })
121
+ this.setDirty();
122
+ }
123
+ }
124
+ addColumnToReplaceQueue(mm: number) {
125
+ if (!this.score) {
126
+ return;
127
+ }
128
+ for (let i = 0; i < this.score.staves.length; ++i) {
129
+ const selection = SmoSelection.measureSelection(this.score, i, mm);
130
+ if (selection) {
131
+ this.addToReplaceQueue(selection);
132
+ }
133
+ }
134
+ }
135
+ setDirty() {
136
+ if (!this.dirty) {
137
+ this.dirty = true;
138
+ if (this.passState === SuiRenderState.passStates.clean) {
139
+ this.setPassState(SuiRenderState.passStates.replace, 'setDirty');
140
+ }
141
+ }
142
+ }
143
+ setRefresh() {
144
+ this.dirty = true;
145
+ this.setPassState(SuiRenderState.passStates.initial, 'setRefresh');
146
+ }
147
+ rerenderAll() {
148
+ this.dirty = true;
149
+ this.setPassState(SuiRenderState.passStates.initial, 'rerenderAll');
150
+ this._resetViewport = true;
151
+ }
152
+ clearLine(measure: SmoMeasure) {
153
+ const page = measure.svg.pageIndex;
154
+ this.renderer.clearRenderedPage(page);
155
+ }
156
+ get renderStateClean() {
157
+ return this.passState === SuiRenderState.passStates.clean && this.renderer.backgroundRender === false;
158
+ }
159
+ get renderStateRendered() {
160
+ return (this.passState === SuiRenderState.passStates.clean && this.renderer.backgroundRender === false) ||
161
+ (this.passState === SuiRenderState.passStates.replace && this.replaceQ.length === 0 && this.renderer.backgroundRender === false);
162
+ }
163
+ /**
164
+ * Do a quick re-render of a measure that has changed, defer the whole score.
165
+ * @returns
166
+ */
167
+ replaceMeasures() {
168
+ const promise = new Promise<void>((resolve, reject) => {
169
+ try {
170
+ const staffMap: Record<number | string, { system: VxSystem, staff: SmoSystemStaff }> = {};
171
+ if (this.score === null || this.measureMapper === null || this.replaceQ.length === 0) {
172
+ resolve();
173
+ return;
174
+ }
175
+ this.replaceQ.forEach((change) => {
176
+ this.renderer.replaceSelection(staffMap, change);
177
+ });
178
+ Object.keys(staffMap).forEach((key) => {
179
+ const obj = staffMap[key];
180
+ this.renderer.renderModifiers(obj.staff, obj.system);
181
+ obj.system.renderEndings(this.measureMapper!.scroller);
182
+ obj.system.renderRehearsalMarks();
183
+ obj.system.updateLyricOffsets();
184
+ });
185
+ this.replaceQ = [];
186
+ resolve();
187
+ } catch (ex) {
188
+ console.error(ex);
189
+ SuiExceptionHandler.instance.exceptionHandler(ex);
190
+ this.handlingRedraw = false;
191
+ reject(ex);
192
+ }
193
+ });
194
+ return promise;
195
+ }
196
+ async preserveScroll() {
197
+ const scrollState = this.measureMapper!.scroller.scrollState;
198
+ await this.renderPromise();
199
+ this.measureMapper!.scroller.restoreScrollState(scrollState);
200
+ }
201
+
202
+ /**
203
+ * Wait until `condition` is true, polling at the demon poll interval. The redraw demon
204
+ * (see pollRedrawTask) advances the render state on its own timer, so there is nothing to
205
+ * await directly. Rendering is un-suspended during the wait and restored afterwards.
206
+ * The condition is first tested after one interval, not immediately.
207
+ * @param condition the render state to wait for
208
+ */
209
+ async _renderStatePromise(condition: () => boolean): Promise<void> {
210
+ const oldSuspend = this.suspendRendering;
211
+ this.suspendRendering = false;
212
+ do {
213
+ await this.delay2();
214
+ } while (!condition());
215
+ this.suspendRendering = oldSuspend;
216
+ }
217
+ // ### renderPromise
218
+ // return a promise that resolves when the score is in a fully rendered state.
219
+ renderPromise(): Promise<void> {
220
+ return this._renderStatePromise(() => this.renderStateClean);
221
+ }
222
+
223
+ // ### renderPromise
224
+ // return a promise that resolves when the score is in a fully rendered state.
225
+ async updatePromise() {
226
+ await this.replaceMeasures();
227
+ return this._renderStatePromise(() => this.renderStateRendered);
228
+ }
229
+ async handleRedrawTimer() {
230
+ if (this.handlingRedraw) {
231
+ return;
232
+ }
233
+ if (this.suspendRendering) {
234
+ return;
235
+ }
236
+ this.handlingRedraw = true;
237
+ try {
238
+ const redrawTime = Math.max(this.renderer.renderTime, this.idleRedrawTime);
239
+ // If there has been a change, redraw the score
240
+ if (this.passState === SuiRenderState.passStates.initial) {
241
+ this.dirty = true;
242
+ this.undoStatus = this.undoBuffer.opCount;
243
+ this.idleLayoutTimer = Date.now();
244
+
245
+ // indicate the display is 'dirty' and we will be refreshing it.
246
+ $('body').addClass('refresh-1');
247
+ // Sort of a hack. If the viewport changed, the scroll state is already reset
248
+ // so we can't preserver the scroll state.
249
+ if (!this.renderer.viewportChanged) {
250
+ this.preserveScroll();
251
+ }
252
+ await this.render();
253
+ } else if (this.passState === SuiRenderState.passStates.replace && this.undoStatus === this.undoBuffer.opCount) {
254
+ // Consider navigation as activity when deciding to refresh
255
+ this.idleLayoutTimer = Math.max(this.idleLayoutTimer, this.measureMapper!.getIdleTime());
256
+ $('body').addClass('refresh-1');
257
+ // Do we need to refresh the score?
258
+ if (this.renderer.backgroundRender === false && Date.now() - this.idleLayoutTimer > redrawTime) {
259
+ this.passState = SuiRenderState.passStates.initial;
260
+ if (!this.renderer.viewportChanged) {
261
+ this.preserveScroll();
262
+ }
263
+ this.render();
264
+ }
265
+ } else {
266
+ this.idleLayoutTimer = Date.now();
267
+ this.undoStatus = this.undoBuffer.opCount;
268
+ if (this.replaceQ.length > 0) {
269
+ this.render();
270
+ }
271
+ }
272
+ if (this.debug.testThrow) {
273
+ this.debug.testThrow = false;
274
+ throw ('Test throw full render')
275
+ }
276
+ this.handlingRedraw = false;
277
+ } catch (ex) {
278
+ console.error(ex);
279
+ SuiExceptionHandler.instance.exceptionHandler(ex);
280
+ this.handlingRedraw = false;
281
+ }
282
+ }
283
+ delay2 = async () => {
284
+ return new Promise<void>((resolve) => {
285
+ setTimeout(() => {
286
+ resolve();
287
+ }, this.demonPollTime);
288
+ });
289
+ }
290
+ async pollRedrawTask() {
291
+ while (true) {
292
+ await this.handleRedrawTimer();
293
+ await this.delay2();
294
+ }
295
+ }
296
+ pollRedraw() {
297
+ setTimeout(async () => {
298
+ this.pollRedrawTask();
299
+ }, 1);
300
+ }
301
+
302
+ startDemon() {
303
+ this.pollRedraw();
304
+ }
305
+ renderTextGroup(gg: SmoTextGroup) {
306
+ this.renderer.renderTextGroup(gg);
307
+ }
308
+ /**
309
+ * Set the SVG viewport
310
+ * @param reset whether to re-render the entire SVG DOM
311
+ * @returns
312
+ */
313
+ setViewport() {
314
+ if (!this.score || !this.renderer) {
315
+ return;
316
+ }
317
+
318
+ this.renderer.setViewport();
319
+ const displayMode = this.score.layoutManager!.getGlobalLayout().displayMode;
320
+ this.navigation.displayMode = displayMode;
321
+ this.score!.staves.forEach((staff) => {
322
+ staff.measures.forEach((measure) => {
323
+ if (measure.svg.logicalBox) {
324
+ measure.svg.history = ['reset'];
325
+ }
326
+ });
327
+ });
328
+ }
329
+ async renderForPrintPromise(): Promise<any> {
330
+ $('body').addClass('print-render');
331
+ const self = this;
332
+ if (!this.score) {
333
+ return;
334
+ }
335
+ const layoutMgr = this.score!.layoutManager!;
336
+ const layout = layoutMgr.getGlobalLayout();
337
+ const originalDisplayMode = layout.displayMode;
338
+ const originalZoomScale = layout.zoomScale;
339
+ this._backupZoomScale = layout.zoomScale;
340
+ this.backupDisplayMode = layout.displayMode;
341
+ layout.zoomScale = 1.0;
342
+ layout.displayMode = 'vertical';
343
+ layoutMgr.updateGlobalLayout(layout);
344
+ this.setViewport();
345
+ this.setRefresh();
346
+
347
+ const promise = new Promise<void>((resolve) => {
348
+ const poll = () => {
349
+ setTimeout(() => {
350
+ if (!self.dirty && !self.renderer.backgroundRender) {
351
+ // tracker.highlightSelection();
352
+ $('body').removeClass('print-render');
353
+ $('.vf-selection').remove();
354
+ $('body').addClass('printing');
355
+ $(this.navigation.scrollContainer).css('height', '');
356
+ layout.displayMode = originalDisplayMode;
357
+ layout.zoomScale = originalZoomScale;
358
+ layoutMgr.updateGlobalLayout(layout);
359
+ resolve();
360
+ } else {
361
+ poll();
362
+ }
363
+ }, 500);
364
+ };
365
+ poll();
366
+ });
367
+ return promise;
368
+ }
369
+
370
+ restoreLayoutAfterPrint() {
371
+ const layout = this.score!.layoutManager!.getGlobalLayout();
372
+ layout.zoomScale = this._backupZoomScale;
373
+ layout.displayMode = this.backupDisplayMode;
374
+ this.score!.layoutManager!.updateGlobalLayout(layout);
375
+ this.setViewport();
376
+ this.setRefresh();
377
+ }
378
+
379
+ setPassState(st: number, location: string) {
380
+ const oldState = this.passState;
381
+ let msg = '';
382
+ if (oldState !== st) {
383
+ this.stateRepCount = 0;
384
+ } else {
385
+ this.stateRepCount += 1;
386
+ }
387
+
388
+ msg = location + ': passState ' + this.passState + '=>' + st;
389
+ if (this.stateRepCount > 0) {
390
+ msg += ' (' + this.stateRepCount + ')';
391
+ }
392
+ if (SuiRenderState.debugMask) {
393
+ console.log(msg);
394
+ }
395
+ this.passState = st;
396
+ }
397
+
398
+ get score(): SmoScore | null {
399
+ return this._score;
400
+ }
401
+
402
+ // used for debugging and drawing dots.
403
+ dbgDrawDot(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise: boolean) {
404
+ const context = this.renderer.getRenderer({ x, y });
405
+ if (context) {
406
+ context.getContext().beginPath();
407
+ context.getContext().arc(x, y, radius, startAngle, endAngle, counterclockwise);
408
+ context.getContext().closePath();
409
+ context.getContext().fill();
410
+ }
411
+ }
412
+ set score(score: SmoScore | null) {
413
+ if (score === null) {
414
+ return;
415
+ }
416
+ /* if (this._score) {
417
+ shouldReset = true;
418
+ } */
419
+ this.setPassState(SuiRenderState.passStates.initial, 'load score');
420
+ const font = score.engravingFont;
421
+ this.dirty = true;
422
+ this._score = score;
423
+ this.renderer.score = score;
424
+ this.notifyFontChange();
425
+ // if (shouldReset) {
426
+ this.setViewport();
427
+ if (this.measureMapper) {
428
+ this.measureMapper.loadScore();
429
+ }
430
+ }
431
+
432
+ unrenderColumn(measure: SmoMeasure) {
433
+ this.score!.staves.forEach((staff) => {
434
+ this.renderer.unrenderMeasure(staff.measures[measure.measureNumber.measureIndex]);
435
+ });
436
+ }
437
+
438
+ // ### forceRender
439
+ // For unit test applictions that want to render right-away
440
+ forceRender() {
441
+ this.setRefresh();
442
+ this.render();
443
+ }
444
+ unrenderMeasure(measure: SmoMeasure) {
445
+ this.renderer.unrenderMeasure(measure);
446
+ }
447
+ async rerenderTextGroups() {
448
+ await this.renderer.rerenderTextGroups();
449
+ }
450
+ async unrenderTextGroups() {
451
+ this.renderer.unrenderTextGroups();
452
+ }
453
+ async render(): Promise<any> {
454
+ if (this._resetViewport) {
455
+ this.setViewport();
456
+ this._resetViewport = false;
457
+ }
458
+ if (SuiRenderState.passStates.replace === this.passState) {
459
+ await this.replaceMeasures();
460
+ } else if (SuiRenderState.passStates.initial === this.passState) {
461
+ if (this.renderer.backgroundRender) {
462
+ return;
463
+ }
464
+ this.renderer.layout();
465
+ this.renderer.drawPageLines();
466
+ this.setPassState(SuiRenderState.passStates.clean, 'rs: complete render');
467
+ }
468
+ this.dirty = false;
469
+ }
465
470
  }