VexFlowMeasure.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. import Vex = require("vexflow");
  2. import {GraphicalMeasure} from "../GraphicalMeasure";
  3. import {SourceMeasure} from "../../VoiceData/SourceMeasure";
  4. import {Staff} from "../../VoiceData/Staff";
  5. import {StaffLine} from "../StaffLine";
  6. import {SystemLinesEnum} from "../SystemLinesEnum";
  7. import {ClefInstruction} from "../../VoiceData/Instructions/ClefInstruction";
  8. import {KeyInstruction} from "../../VoiceData/Instructions/KeyInstruction";
  9. import {RhythmInstruction} from "../../VoiceData/Instructions/RhythmInstruction";
  10. import {VexFlowConverter, VexFlowRepetitionType, VexFlowBarlineType} from "./VexFlowConverter";
  11. import {VexFlowStaffEntry} from "./VexFlowStaffEntry";
  12. import {Beam} from "../../VoiceData/Beam";
  13. import {GraphicalNote} from "../GraphicalNote";
  14. import {GraphicalStaffEntry} from "../GraphicalStaffEntry";
  15. import StaveConnector = Vex.Flow.StaveConnector;
  16. import StaveNote = Vex.Flow.StaveNote;
  17. import StemmableNote = Vex.Flow.StemmableNote;
  18. import NoteSubGroup = Vex.Flow.NoteSubGroup;
  19. import * as log from "loglevel";
  20. import {unitInPixels} from "./VexFlowMusicSheetDrawer";
  21. import {Tuplet} from "../../VoiceData/Tuplet";
  22. import { RepetitionInstructionEnum, RepetitionInstruction, AlignmentType } from "../../VoiceData/Instructions/RepetitionInstruction";
  23. import {SystemLinePosition} from "../SystemLinePosition";
  24. import {StemDirectionType} from "../../VoiceData/VoiceEntry";
  25. import {GraphicalVoiceEntry} from "../GraphicalVoiceEntry";
  26. import {VexFlowVoiceEntry} from "./VexFlowVoiceEntry";
  27. import {Fraction} from "../../../Common/DataObjects/Fraction";
  28. import { Voice } from "../../VoiceData/Voice";
  29. import { VexFlowInstantaneousDynamicExpression } from "./VexFlowInstantaneousDynamicExpression";
  30. import { LinkedVoice } from "../../VoiceData/LinkedVoice";
  31. export class VexFlowMeasure extends GraphicalMeasure {
  32. constructor(staff: Staff, staffLine: StaffLine = undefined, sourceMeasure: SourceMeasure = undefined) {
  33. super(staff, sourceMeasure, staffLine);
  34. this.minimumStaffEntriesWidth = -1;
  35. this.resetLayout();
  36. }
  37. /** octaveOffset according to active clef */
  38. public octaveOffset: number = 3;
  39. /** The VexFlow Voices in the measure */
  40. public vfVoices: { [voiceID: number]: Vex.Flow.Voice; } = {};
  41. /** Call this function (if present) to x-format all the voices in the measure */
  42. public formatVoices: (width: number) => void;
  43. /** The VexFlow Ties in the measure */
  44. public vfTies: Vex.Flow.StaveTie[] = [];
  45. /** The repetition instructions given as words or symbols (coda, dal segno..) */
  46. public vfRepetitionWords: Vex.Flow.Repetition[] = [];
  47. /** Instant dynamics */
  48. public instantaneousDynamics: VexFlowInstantaneousDynamicExpression[] = [];
  49. /** The VexFlow Stave (= one measure in a staffline) */
  50. private stave: Vex.Flow.Stave;
  51. /** VexFlow StaveConnectors (vertical lines) */
  52. private connectors: Vex.Flow.StaveConnector[] = [];
  53. /** Intermediate object to construct beams */
  54. private beams: { [voiceID: number]: [Beam, VexFlowVoiceEntry[]][]; } = {};
  55. /** VexFlow Beams */
  56. private vfbeams: { [voiceID: number]: Vex.Flow.Beam[]; };
  57. /** Intermediate object to construct tuplets */
  58. private tuplets: { [voiceID: number]: [Tuplet, VexFlowVoiceEntry[]][]; } = {};
  59. /** VexFlow Tuplets */
  60. private vftuplets: { [voiceID: number]: Vex.Flow.Tuplet[]; } = {};
  61. // Sets the absolute coordinates of the VFStave on the canvas
  62. public setAbsoluteCoordinates(x: number, y: number): void {
  63. this.stave.setX(x).setY(y);
  64. }
  65. /**
  66. * Reset all the geometric values and parameters of this measure and put it in an initialized state.
  67. * This is needed to evaluate a measure a second time by system builder.
  68. */
  69. public resetLayout(): void {
  70. // Take into account some space for the begin and end lines of the stave
  71. // Will be changed when repetitions will be implemented
  72. //this.beginInstructionsWidth = 20 / UnitInPixels;
  73. //this.endInstructionsWidth = 20 / UnitInPixels;
  74. this.stave = new Vex.Flow.Stave(0, 0, 0, {
  75. space_above_staff_ln: 0,
  76. space_below_staff_ln: 0,
  77. });
  78. this.updateInstructionWidth();
  79. }
  80. public clean(): void {
  81. this.vfTies.length = 0;
  82. this.connectors = [];
  83. // Clean up instructions
  84. this.resetLayout();
  85. this.instantaneousDynamics = [];
  86. }
  87. /**
  88. * returns the x-width (in units) of a given measure line {SystemLinesEnum}.
  89. * @param line
  90. * @returns the x-width in osmd units
  91. */
  92. public getLineWidth(line: SystemLinesEnum): number {
  93. switch (line) {
  94. // return 0 for the normal lines, as the line width will be considered at the updateInstructionWidth() method using the stavemodifiers.
  95. // case SystemLinesEnum.SingleThin:
  96. // return 5.0 / unitInPixels;
  97. // case SystemLinesEnum.DoubleThin:
  98. // return 5.0 / unitInPixels;
  99. // case SystemLinesEnum.ThinBold:
  100. // return 5.0 / unitInPixels;
  101. // but just add a little extra space for repetitions (cosmetics):
  102. case SystemLinesEnum.BoldThinDots:
  103. case SystemLinesEnum.DotsThinBold:
  104. return 10.0 / unitInPixels;
  105. case SystemLinesEnum.DotsBoldBoldDots:
  106. return 10.0 / unitInPixels;
  107. default:
  108. return 0;
  109. }
  110. }
  111. /**
  112. * adds the given clef to the begin of the measure.
  113. * This has to update/increase BeginInstructionsWidth.
  114. * @param clef
  115. */
  116. public addClefAtBegin(clef: ClefInstruction): void {
  117. this.octaveOffset = clef.OctaveOffset;
  118. const vfclef: { type: string, size: string, annotation: string } = VexFlowConverter.Clef(clef, "default");
  119. this.stave.addClef(vfclef.type, vfclef.size, vfclef.annotation, Vex.Flow.Modifier.Position.BEGIN);
  120. this.updateInstructionWidth();
  121. }
  122. /**
  123. * adds the given key to the begin of the measure.
  124. * This has to update/increase BeginInstructionsWidth.
  125. * @param currentKey the new valid key.
  126. * @param previousKey the old cancelled key. Needed to show which accidentals are not valid any more.
  127. * @param currentClef the valid clef. Needed to put the accidentals on the right y-positions.
  128. */
  129. public addKeyAtBegin(currentKey: KeyInstruction, previousKey: KeyInstruction, currentClef: ClefInstruction): void {
  130. this.stave.setKeySignature(
  131. VexFlowConverter.keySignature(currentKey),
  132. VexFlowConverter.keySignature(previousKey),
  133. undefined
  134. );
  135. this.updateInstructionWidth();
  136. }
  137. /**
  138. * adds the given rhythm to the begin of the measure.
  139. * This has to update/increase BeginInstructionsWidth.
  140. * @param rhythm
  141. */
  142. public addRhythmAtBegin(rhythm: RhythmInstruction): void {
  143. const timeSig: Vex.Flow.TimeSignature = VexFlowConverter.TimeSignature(rhythm);
  144. this.stave.addModifier(
  145. timeSig,
  146. Vex.Flow.Modifier.Position.BEGIN
  147. );
  148. this.updateInstructionWidth();
  149. }
  150. /**
  151. * adds the given clef to the end of the measure.
  152. * This has to update/increase EndInstructionsWidth.
  153. * @param clef
  154. */
  155. public addClefAtEnd(clef: ClefInstruction): void {
  156. const vfclef: { type: string, size: string, annotation: string } = VexFlowConverter.Clef(clef, "small");
  157. this.stave.setEndClef(vfclef.type, vfclef.size, vfclef.annotation);
  158. this.updateInstructionWidth();
  159. }
  160. public addMeasureLine(lineType: SystemLinesEnum, linePosition: SystemLinePosition): void {
  161. switch (linePosition) {
  162. case SystemLinePosition.MeasureBegin:
  163. switch (lineType) {
  164. case SystemLinesEnum.BoldThinDots:
  165. this.stave.setBegBarType(VexFlowBarlineType.REPEAT_BEGIN);
  166. break;
  167. default:
  168. break;
  169. }
  170. break;
  171. case SystemLinePosition.MeasureEnd:
  172. switch (lineType) {
  173. case SystemLinesEnum.DotsBoldBoldDots:
  174. this.stave.setEndBarType(VexFlowBarlineType.REPEAT_BOTH);
  175. break;
  176. case SystemLinesEnum.DotsThinBold:
  177. this.stave.setEndBarType(VexFlowBarlineType.REPEAT_END);
  178. break;
  179. case SystemLinesEnum.DoubleThin:
  180. this.stave.setEndBarType(VexFlowBarlineType.DOUBLE);
  181. break;
  182. case SystemLinesEnum.ThinBold:
  183. this.stave.setEndBarType(VexFlowBarlineType.END);
  184. break;
  185. default:
  186. break;
  187. }
  188. break;
  189. default:
  190. break;
  191. }
  192. }
  193. /**
  194. * Adds a measure number to the top left corner of the measure
  195. * This method is not used currently in favor of the calculateMeasureNumberPlacement
  196. * method in the MusicSheetCalculator.ts
  197. */
  198. public addMeasureNumber(): void {
  199. const text: string = this.MeasureNumber.toString();
  200. const position: number = StavePositionEnum.ABOVE; //Vex.Flow.StaveModifier.Position.ABOVE;
  201. const options: any = {
  202. justification: 1,
  203. shift_x: 0,
  204. shift_y: 0,
  205. };
  206. this.stave.setText(text, position, options);
  207. }
  208. public addWordRepetition(repetitionInstruction: RepetitionInstruction): void {
  209. let instruction: VexFlowRepetitionType = undefined;
  210. let position: any = Vex.Flow.Modifier.Position.END;
  211. switch (repetitionInstruction.type) {
  212. case RepetitionInstructionEnum.Segno:
  213. // create Segno Symbol:
  214. instruction = VexFlowRepetitionType.SEGNO_LEFT;
  215. position = Vex.Flow.Modifier.Position.BEGIN;
  216. break;
  217. case RepetitionInstructionEnum.Coda:
  218. // create Coda Symbol:
  219. instruction = VexFlowRepetitionType.CODA_LEFT;
  220. position = Vex.Flow.Modifier.Position.BEGIN;
  221. break;
  222. case RepetitionInstructionEnum.DaCapo:
  223. instruction = VexFlowRepetitionType.DC;
  224. break;
  225. case RepetitionInstructionEnum.DalSegno:
  226. instruction = VexFlowRepetitionType.DS;
  227. break;
  228. case RepetitionInstructionEnum.Fine:
  229. instruction = VexFlowRepetitionType.FINE;
  230. break;
  231. case RepetitionInstructionEnum.ToCoda:
  232. //instruction = "To Coda";
  233. break;
  234. case RepetitionInstructionEnum.DaCapoAlFine:
  235. instruction = VexFlowRepetitionType.DC_AL_FINE;
  236. break;
  237. case RepetitionInstructionEnum.DaCapoAlCoda:
  238. instruction = VexFlowRepetitionType.DC_AL_CODA;
  239. break;
  240. case RepetitionInstructionEnum.DalSegnoAlFine:
  241. instruction = VexFlowRepetitionType.DS_AL_FINE;
  242. break;
  243. case RepetitionInstructionEnum.DalSegnoAlCoda:
  244. instruction = VexFlowRepetitionType.DS_AL_CODA;
  245. break;
  246. default:
  247. break;
  248. }
  249. if (instruction !== undefined) {
  250. this.stave.addModifier(new Vex.Flow.Repetition(instruction, 0, 0), position);
  251. return;
  252. }
  253. this.addVolta(repetitionInstruction);
  254. }
  255. private addVolta(repetitionInstruction: RepetitionInstruction): void {
  256. let voltaType: number = Vex.Flow.Volta.type.BEGIN;
  257. if (repetitionInstruction.type === RepetitionInstructionEnum.Ending) {
  258. switch (repetitionInstruction.alignment) {
  259. case AlignmentType.Begin:
  260. if (this.parentSourceMeasure.endsRepetitionEnding()) {
  261. voltaType = Vex.Flow.Volta.type.BEGIN_END;
  262. } else {
  263. voltaType = Vex.Flow.Volta.type.BEGIN;
  264. }
  265. break;
  266. case AlignmentType.End:
  267. if (this.parentSourceMeasure.beginsRepetitionEnding()) {
  268. //voltaType = Vex.Flow.Volta.type.BEGIN_END;
  269. // don't add BEGIN_END volta a second time:
  270. return;
  271. } else {
  272. voltaType = Vex.Flow.Volta.type.END;
  273. }
  274. break;
  275. default:
  276. break;
  277. }
  278. this.stave.setVoltaType(voltaType, repetitionInstruction.endingIndices[0], 0);
  279. }
  280. }
  281. /**
  282. * Sets the overall x-width of the measure.
  283. * @param width
  284. */
  285. public setWidth(width: number): void {
  286. super.setWidth(width);
  287. // Set the width of the Vex.Flow.Stave
  288. this.stave.setWidth(width * unitInPixels);
  289. // Force the width of the Begin Instructions
  290. //this.stave.setNoteStartX(this.beginInstructionsWidth * UnitInPixels);
  291. }
  292. /**
  293. * This method is called after the StaffEntriesScaleFactor has been set.
  294. * Here the final x-positions of the staff entries have to be set.
  295. * (multiply the minimal positions with the scaling factor, considering the BeginInstructionsWidth)
  296. */
  297. public layoutSymbols(): void {
  298. // vexflow does the x-layout
  299. }
  300. /**
  301. * Draw this measure on a VexFlow CanvasContext
  302. * @param ctx
  303. */
  304. public draw(ctx: Vex.Flow.RenderContext): void {
  305. // Draw stave lines
  306. this.stave.setContext(ctx).draw();
  307. // Draw all voices
  308. for (const voiceID in this.vfVoices) {
  309. if (this.vfVoices.hasOwnProperty(voiceID)) {
  310. this.vfVoices[voiceID].draw(ctx, this.stave);
  311. // this.vfVoices[voiceID].tickables.forEach(t => t.getBoundingBox().draw(ctx));
  312. // this.vfVoices[voiceID].tickables.forEach(t => t.getBoundingBox().draw(ctx));
  313. }
  314. }
  315. // Draw beams
  316. for (const voiceID in this.vfbeams) {
  317. if (this.vfbeams.hasOwnProperty(voiceID)) {
  318. for (const beam of this.vfbeams[voiceID]) {
  319. beam.setContext(ctx).draw();
  320. }
  321. }
  322. }
  323. // Draw tuplets
  324. for (const voiceID in this.vftuplets) {
  325. if (this.vftuplets.hasOwnProperty(voiceID)) {
  326. for (const tuplet of this.vftuplets[voiceID]) {
  327. tuplet.setContext(ctx).draw();
  328. }
  329. }
  330. }
  331. // Draw ties
  332. for (const tie of this.vfTies) {
  333. tie.setContext(ctx).draw();
  334. }
  335. // Draw vertical lines
  336. for (const connector of this.connectors) {
  337. connector.setContext(ctx).draw();
  338. }
  339. }
  340. // this currently formats multiple measures, see VexFlowMusicSheetCalculator.formatMeasures()
  341. public format(): void {
  342. // If this is the first stave in the vertical measure, call the format
  343. // method to set the width of all the voices
  344. if (this.formatVoices) {
  345. // set the width of the voices to the current measure width:
  346. // (The width of the voices does not include the instructions (StaveModifiers))
  347. this.formatVoices((this.PositionAndShape.Size.width - this.beginInstructionsWidth - this.endInstructionsWidth) * unitInPixels);
  348. }
  349. }
  350. /**
  351. * Returns all the voices that are present in this measure
  352. */
  353. public getVoicesWithinMeasure(): Voice[] {
  354. const voices: Voice[] = [];
  355. for (const gse of this.staffEntries) {
  356. for (const gve of gse.graphicalVoiceEntries) {
  357. if (voices.indexOf(gve.parentVoiceEntry.ParentVoice) === -1) {
  358. voices.push(gve.parentVoiceEntry.ParentVoice);
  359. }
  360. }
  361. }
  362. return voices;
  363. }
  364. /**
  365. * Returns all the graphicalVoiceEntries of a given Voice.
  366. * @param voice the voice for which the graphicalVoiceEntries shall be returned.
  367. */
  368. public getGraphicalVoiceEntriesPerVoice(voice: Voice): GraphicalVoiceEntry[] {
  369. const voiceEntries: GraphicalVoiceEntry[] = [];
  370. for (const gse of this.staffEntries) {
  371. for (const gve of gse.graphicalVoiceEntries) {
  372. if (gve.parentVoiceEntry.ParentVoice === voice) {
  373. voiceEntries.push(gve);
  374. }
  375. }
  376. }
  377. return voiceEntries;
  378. }
  379. /**
  380. * Finds the gaps between the existing notes within a measure.
  381. * Problem here is, that the graphicalVoiceEntry does not exist yet and
  382. * that Tied notes are not present in the normal voiceEntries.
  383. * To handle this, calculation with absolute timestamps is needed.
  384. * And the graphical notes have to be analysed directly (and not the voiceEntries, as it actually should be -> needs refactoring)
  385. * @param voice the voice for which the ghost notes shall be searched.
  386. */
  387. private getRestFilledVexFlowStaveNotesPerVoice(voice: Voice): GraphicalVoiceEntry[] {
  388. let latestVoiceTimestamp: Fraction = undefined;
  389. const gvEntries: GraphicalVoiceEntry[] = this.getGraphicalVoiceEntriesPerVoice(voice);
  390. for (let idx: number = 0, len: number = gvEntries.length; idx < len; ++idx) {
  391. const gve: GraphicalVoiceEntry = gvEntries[idx];
  392. const gNotesStartTimestamp: Fraction = gve.notes[0].sourceNote.getAbsoluteTimestamp();
  393. // find the voiceEntry end timestamp:
  394. let gNotesEndTimestamp: Fraction = new Fraction();
  395. for (const graphicalNote of gve.notes) {
  396. const noteEnd: Fraction = Fraction.plus(graphicalNote.sourceNote.getAbsoluteTimestamp(), graphicalNote.sourceNote.Length);
  397. if (gNotesEndTimestamp < noteEnd) {
  398. gNotesEndTimestamp = noteEnd;
  399. }
  400. }
  401. // check if this voice has just been found the first time:
  402. if (latestVoiceTimestamp === undefined) {
  403. // if this voice is new, check for a gap from measure start to the start of the current voice entry:
  404. const gapFromMeasureStart: Fraction = Fraction.minus(gNotesStartTimestamp, this.parentSourceMeasure.AbsoluteTimestamp);
  405. if (gapFromMeasureStart.RealValue > 0) {
  406. log.debug("Ghost Found at start");
  407. const vfghost: Vex.Flow.GhostNote = VexFlowConverter.GhostNote(gapFromMeasureStart);
  408. const ghostGve: VexFlowVoiceEntry = new VexFlowVoiceEntry(undefined, undefined);
  409. ghostGve.vfStaveNote = vfghost;
  410. gvEntries.splice(0, 0, ghostGve);
  411. idx++;
  412. }
  413. } else {
  414. // get the length of the empty space between notes:
  415. const inBetweenLength: Fraction = Fraction.minus(gNotesStartTimestamp, latestVoiceTimestamp);
  416. if (inBetweenLength.RealValue > 0) {
  417. log.debug("Ghost Found in between");
  418. const vfghost: Vex.Flow.GhostNote = VexFlowConverter.GhostNote(inBetweenLength);
  419. const ghostGve: VexFlowVoiceEntry = new VexFlowVoiceEntry(undefined, undefined);
  420. ghostGve.vfStaveNote = vfghost;
  421. // add element before current element:
  422. gvEntries.splice(idx, 0, ghostGve);
  423. // and increase index, as we added an element:
  424. idx++;
  425. }
  426. }
  427. // finally set the latest timestamp of this voice to the end timestamp of the longest note in the current voiceEntry:
  428. latestVoiceTimestamp = gNotesEndTimestamp;
  429. }
  430. const measureEndTimestamp: Fraction = Fraction.plus(this.parentSourceMeasure.AbsoluteTimestamp, this.parentSourceMeasure.Duration);
  431. const restLength: Fraction = Fraction.minus(measureEndTimestamp, latestVoiceTimestamp);
  432. if (restLength.RealValue > 0) {
  433. // fill the gap with a rest ghost note
  434. // starting from lastFraction
  435. // with length restLength:
  436. log.debug("Ghost Found at end");
  437. const vfghost: Vex.Flow.GhostNote = VexFlowConverter.GhostNote(restLength);
  438. const ghostGve: VexFlowVoiceEntry = new VexFlowVoiceEntry(undefined, undefined);
  439. ghostGve.vfStaveNote = vfghost;
  440. gvEntries.push(ghostGve);
  441. }
  442. return gvEntries;
  443. }
  444. /**
  445. * Add a note to a beam
  446. * @param graphicalNote
  447. * @param beam
  448. */
  449. public handleBeam(graphicalNote: GraphicalNote, beam: Beam): void {
  450. const voiceID: number = graphicalNote.sourceNote.ParentVoiceEntry.ParentVoice.VoiceId;
  451. let beams: [Beam, VexFlowVoiceEntry[]][] = this.beams[voiceID];
  452. if (beams === undefined) {
  453. beams = this.beams[voiceID] = [];
  454. }
  455. let data: [Beam, VexFlowVoiceEntry[]];
  456. for (const mybeam of beams) {
  457. if (mybeam[0] === beam) {
  458. data = mybeam;
  459. }
  460. }
  461. if (data === undefined) {
  462. data = [beam, []];
  463. beams.push(data);
  464. }
  465. const parent: VexFlowVoiceEntry = graphicalNote.parentVoiceEntry as VexFlowVoiceEntry;
  466. if (data[1].indexOf(parent) < 0) {
  467. data[1].push(parent);
  468. }
  469. }
  470. public handleTuplet(graphicalNote: GraphicalNote, tuplet: Tuplet): void {
  471. const voiceID: number = graphicalNote.sourceNote.ParentVoiceEntry.ParentVoice.VoiceId;
  472. tuplet = graphicalNote.sourceNote.NoteTuplet;
  473. let tuplets: [Tuplet, VexFlowVoiceEntry[]][] = this.tuplets[voiceID];
  474. if (tuplets === undefined) {
  475. tuplets = this.tuplets[voiceID] = [];
  476. }
  477. let currentTupletBuilder: [Tuplet, VexFlowVoiceEntry[]];
  478. for (const t of tuplets) {
  479. if (t[0] === tuplet) {
  480. currentTupletBuilder = t;
  481. }
  482. }
  483. if (currentTupletBuilder === undefined) {
  484. currentTupletBuilder = [tuplet, []];
  485. tuplets.push(currentTupletBuilder);
  486. }
  487. const parent: VexFlowVoiceEntry = graphicalNote.parentVoiceEntry as VexFlowVoiceEntry;
  488. if (currentTupletBuilder[1].indexOf(parent) < 0) {
  489. currentTupletBuilder[1].push(parent);
  490. }
  491. }
  492. /**
  493. * Complete the creation of VexFlow Beams in this measure
  494. */
  495. public finalizeBeams(): void {
  496. // The following line resets the created Vex.Flow Beams and
  497. // created them brand new. Is this needed? And more importantly,
  498. // should the old beams be removed manually by the notes?
  499. this.vfbeams = {};
  500. for (const voiceID in this.beams) {
  501. if (this.beams.hasOwnProperty(voiceID)) {
  502. let vfbeams: Vex.Flow.Beam[] = this.vfbeams[voiceID];
  503. if (vfbeams === undefined) {
  504. vfbeams = this.vfbeams[voiceID] = [];
  505. }
  506. for (const beam of this.beams[voiceID]) {
  507. const notes: Vex.Flow.StaveNote[] = [];
  508. const psBeam: Beam = beam[0];
  509. const voiceEntries: VexFlowVoiceEntry[] = beam[1];
  510. let autoStemBeam: boolean = true;
  511. for (const gve of voiceEntries) {
  512. if (gve.parentVoiceEntry.ParentVoice === psBeam.Notes[0].ParentVoiceEntry.ParentVoice) {
  513. autoStemBeam = gve.parentVoiceEntry.StemDirection === StemDirectionType.Undefined;
  514. }
  515. }
  516. for (const entry of voiceEntries) {
  517. const note: Vex.Flow.StaveNote = ((<VexFlowVoiceEntry>entry).vfStaveNote as StaveNote);
  518. if (note !== undefined) {
  519. notes.push(note);
  520. }
  521. }
  522. if (notes.length > 1) {
  523. const vfBeam: Vex.Flow.Beam = new Vex.Flow.Beam(notes, autoStemBeam);
  524. vfbeams.push(vfBeam);
  525. // just a test for coloring the notes:
  526. // for (let note of notes) {
  527. // (<Vex.Flow.StaveNote> note).setStyle({fillStyle: "green", strokeStyle: "green"});
  528. // }
  529. } else {
  530. log.debug("Warning! Beam with no notes!");
  531. }
  532. }
  533. }
  534. }
  535. }
  536. /**
  537. * Complete the creation of VexFlow Tuplets in this measure
  538. */
  539. public finalizeTuplets(): void {
  540. // The following line resets the created Vex.Flow Tuplets and
  541. // created them brand new. Is this needed? And more importantly,
  542. // should the old tuplets be removed manually from the notes?
  543. this.vftuplets = {};
  544. for (const voiceID in this.tuplets) {
  545. if (this.tuplets.hasOwnProperty(voiceID)) {
  546. let vftuplets: Vex.Flow.Tuplet[] = this.vftuplets[voiceID];
  547. if (vftuplets === undefined) {
  548. vftuplets = this.vftuplets[voiceID] = [];
  549. }
  550. for (const tupletBuilder of this.tuplets[voiceID]) {
  551. const tupletStaveNotes: Vex.Flow.StaveNote[] = [];
  552. const tupletVoiceEntries: VexFlowVoiceEntry[] = tupletBuilder[1];
  553. for (const tupletVoiceEntry of tupletVoiceEntries) {
  554. tupletStaveNotes.push(((tupletVoiceEntry).vfStaveNote as StaveNote));
  555. }
  556. if (tupletStaveNotes.length > 1) {
  557. const notesOccupied: number = 2;
  558. vftuplets.push(new Vex.Flow.Tuplet( tupletStaveNotes,
  559. {
  560. notes_occupied: notesOccupied,
  561. num_notes: tupletStaveNotes.length //, location: -1, ratioed: true
  562. }));
  563. } else {
  564. log.debug("Warning! Tuplet with no notes! Trying to ignore, but this is a serious problem.");
  565. }
  566. }
  567. }
  568. }
  569. }
  570. public layoutStaffEntry(graphicalStaffEntry: GraphicalStaffEntry): void {
  571. return;
  572. }
  573. public graphicalMeasureCreatedCalculations(): void {
  574. for (const graphicalStaffEntry of this.staffEntries as VexFlowStaffEntry[]) {
  575. // create vex flow Stave Notes:
  576. let graceSlur: boolean = false;
  577. let graceGVoiceEntriesBefore: GraphicalVoiceEntry[] = [];
  578. for (const gve of graphicalStaffEntry.graphicalVoiceEntries) {
  579. if (gve.parentVoiceEntry.IsGrace) {
  580. graceGVoiceEntriesBefore.push(gve);
  581. if (!graceSlur) {
  582. graceSlur = gve.parentVoiceEntry.GraceSlur;
  583. }
  584. continue;
  585. }
  586. (gve as VexFlowVoiceEntry).vfStaveNote = VexFlowConverter.StaveNote(gve);
  587. if (graceGVoiceEntriesBefore.length > 0) {
  588. const graceNotes: Vex.Flow.GraceNote[] = [];
  589. for (let i: number = 0; i < graceGVoiceEntriesBefore.length; i++) {
  590. graceNotes.push(VexFlowConverter.StaveNote(graceGVoiceEntriesBefore[i]));
  591. }
  592. const graceNoteGroup: Vex.Flow.GraceNoteGroup = new Vex.Flow.GraceNoteGroup(graceNotes, graceSlur);
  593. (gve as VexFlowVoiceEntry).vfStaveNote.addModifier(0, graceNoteGroup.beamNotes());
  594. graceGVoiceEntriesBefore = [];
  595. }
  596. }
  597. }
  598. this.finalizeBeams();
  599. this.finalizeTuplets();
  600. const voices: Voice[] = this.getVoicesWithinMeasure();
  601. for (const voice of voices) {
  602. if (voice === undefined) {
  603. continue;
  604. }
  605. const isMainVoice: boolean = !(voice instanceof LinkedVoice);
  606. // add a vexFlow voice for this voice:
  607. this.vfVoices[voice.VoiceId] = new Vex.Flow.Voice({
  608. beat_value: this.parentSourceMeasure.Duration.Denominator,
  609. num_beats: this.parentSourceMeasure.Duration.Numerator,
  610. resolution: Vex.Flow.RESOLUTION,
  611. }).setMode(Vex.Flow.Voice.Mode.SOFT);
  612. const restFilledEntries: GraphicalVoiceEntry[] = this.getRestFilledVexFlowStaveNotesPerVoice(voice);
  613. // create vex flow voices and add tickables to it:
  614. for (const voiceEntry of restFilledEntries) {
  615. if (voiceEntry.parentVoiceEntry) {
  616. if (voiceEntry.parentVoiceEntry.IsGrace) {
  617. continue;
  618. }
  619. }
  620. const vexFlowVoiceEntry: VexFlowVoiceEntry = voiceEntry as VexFlowVoiceEntry;
  621. // check for in-measure clefs:
  622. // only add clefs in main voice (to not add them twice)
  623. if (isMainVoice) {
  624. const vfse: VexFlowStaffEntry = vexFlowVoiceEntry.parentStaffEntry as VexFlowStaffEntry;
  625. if (vfse && vfse.vfClefBefore !== undefined) {
  626. // add clef as NoteSubGroup so that we get modifier layouting
  627. const clefModifier: NoteSubGroup = new NoteSubGroup( [vfse.vfClefBefore] );
  628. vexFlowVoiceEntry.vfStaveNote.addModifier(0, clefModifier);
  629. }
  630. }
  631. this.vfVoices[voice.VoiceId].addTickable(vexFlowVoiceEntry.vfStaveNote);
  632. }
  633. }
  634. this.createArticulations();
  635. this.createOrnaments();
  636. }
  637. /**
  638. * Create the articulations for all notes of the current staff entry
  639. */
  640. private createArticulations(): void {
  641. for (let idx: number = 0, len: number = this.staffEntries.length; idx < len; ++idx) {
  642. const graphicalStaffEntry: VexFlowStaffEntry = (this.staffEntries[idx] as VexFlowStaffEntry);
  643. // create vex flow articulation:
  644. const graphicalVoiceEntries: GraphicalVoiceEntry[] = graphicalStaffEntry.graphicalVoiceEntries;
  645. for (const gve of graphicalVoiceEntries) {
  646. if (gve.parentVoiceEntry.IsGrace) {
  647. continue;
  648. }
  649. const vfStaveNote: StemmableNote = (gve as VexFlowVoiceEntry).vfStaveNote;
  650. VexFlowConverter.generateArticulations(vfStaveNote, gve.notes[0].sourceNote.ParentVoiceEntry.Articulations);
  651. }
  652. }
  653. }
  654. /**
  655. * Create the ornaments for all notes of the current staff entry
  656. */
  657. private createOrnaments(): void {
  658. for (let idx: number = 0, len: number = this.staffEntries.length; idx < len; ++idx) {
  659. const graphicalStaffEntry: VexFlowStaffEntry = (this.staffEntries[idx] as VexFlowStaffEntry);
  660. const gvoices: { [voiceID: number]: GraphicalVoiceEntry; } = graphicalStaffEntry.graphicalVoiceEntries;
  661. for (const voiceID in gvoices) {
  662. if (gvoices.hasOwnProperty(voiceID)) {
  663. const vfStaveNote: StemmableNote = (gvoices[voiceID] as VexFlowVoiceEntry).vfStaveNote;
  664. if (gvoices[voiceID].notes[0].sourceNote.ParentVoiceEntry.OrnamentContainer !== undefined) {
  665. VexFlowConverter.generateOrnaments(vfStaveNote, gvoices[voiceID].notes[0].sourceNote.ParentVoiceEntry.OrnamentContainer);
  666. }
  667. }
  668. }
  669. }
  670. }
  671. /**
  672. * Creates a line from 'top' to this measure, of type 'lineType'
  673. * @param top
  674. * @param lineType
  675. */
  676. public lineTo(top: VexFlowMeasure, lineType: any): void {
  677. const connector: StaveConnector = new Vex.Flow.StaveConnector(top.getVFStave(), this.stave);
  678. connector.setType(lineType);
  679. this.connectors.push(connector);
  680. }
  681. /**
  682. * Return the VexFlow Stave corresponding to this graphicalMeasure
  683. * @returns {Vex.Flow.Stave}
  684. */
  685. public getVFStave(): Vex.Flow.Stave {
  686. return this.stave;
  687. }
  688. /**
  689. * After re-running the formatting on the VexFlow Stave, update the
  690. * space needed by Instructions (in VexFlow: StaveModifiers)
  691. */
  692. private updateInstructionWidth(): void {
  693. let vfBeginInstructionsWidth: number = 0;
  694. let vfEndInstructionsWidth: number = 0;
  695. const modifiers: Vex.Flow.StaveModifier[] = this.stave.getModifiers();
  696. for (const mod of modifiers) {
  697. if (mod.getPosition() === StavePositionEnum.BEGIN) { //Vex.Flow.StaveModifier.Position.BEGIN) {
  698. vfBeginInstructionsWidth += mod.getWidth() + mod.getPadding(undefined);
  699. } else if (mod.getPosition() === StavePositionEnum.END) { //Vex.Flow.StaveModifier.Position.END) {
  700. vfEndInstructionsWidth += mod.getWidth() + mod.getPadding(undefined);
  701. }
  702. }
  703. this.beginInstructionsWidth = vfBeginInstructionsWidth / unitInPixels;
  704. this.endInstructionsWidth = vfEndInstructionsWidth / unitInPixels;
  705. }
  706. }
  707. // Gives the position of the Stave - replaces the function get Position() in the description of class StaveModifier in vexflow.d.ts
  708. // The latter gave an error because function cannot be defined in the class descriptions in vexflow.d.ts
  709. export enum StavePositionEnum {
  710. LEFT = 1,
  711. RIGHT = 2,
  712. ABOVE = 3,
  713. BELOW = 4,
  714. BEGIN = 5,
  715. END = 6
  716. }