VexFlowMeasure.ts 36 KB

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