VexFlowMeasure.ts 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  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, ClefEnum} from "../../VoiceData/Instructions/ClefInstruction";
  8. import {KeyInstruction} from "../../VoiceData/Instructions/KeyInstruction";
  9. import {RhythmInstruction} from "../../VoiceData/Instructions/RhythmInstruction";
  10. import {VexFlowConverter} 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 {LinkedVoice} from "../../VoiceData/LinkedVoice";
  30. import {EngravingRules} from "../EngravingRules";
  31. import {OrnamentContainer} from "../../VoiceData/OrnamentContainer";
  32. import {TechnicalInstruction} from "../../VoiceData/Instructions/TechnicalInstruction";
  33. import {PlacementEnum} from "../../VoiceData/Expressions/AbstractExpression";
  34. import {VexFlowGraphicalNote} from "./VexFlowGraphicalNote";
  35. import {AutoBeamOptions} from "../../../OpenSheetMusicDisplay/OSMDOptions";
  36. import {NoteType, Arpeggio} from "../../VoiceData";
  37. export class VexFlowMeasure extends GraphicalMeasure {
  38. constructor(staff: Staff, sourceMeasure: SourceMeasure = undefined, staffLine: StaffLine = undefined) {
  39. super(staff, sourceMeasure, staffLine);
  40. this.minimumStaffEntriesWidth = -1;
  41. this.resetLayout();
  42. }
  43. /** octaveOffset according to active clef */
  44. public octaveOffset: number = 3;
  45. /** The VexFlow Voices in the measure */
  46. public vfVoices: { [voiceID: number]: Vex.Flow.Voice; } = {};
  47. /** Call this function (if present) to x-format all the voices in the measure */
  48. public formatVoices: (width: number) => void;
  49. /** The VexFlow Ties in the measure */
  50. public vfTies: Vex.Flow.StaveTie[] = [];
  51. /** The repetition instructions given as words or symbols (coda, dal segno..) */
  52. public vfRepetitionWords: Vex.Flow.Repetition[] = [];
  53. /** The VexFlow Stave (= one measure in a staffline) */
  54. protected stave: Vex.Flow.Stave;
  55. /** VexFlow StaveConnectors (vertical lines) */
  56. protected connectors: Vex.Flow.StaveConnector[] = [];
  57. /** Intermediate object to construct beams */
  58. private beams: { [voiceID: number]: [Beam, VexFlowVoiceEntry[]][]; } = {};
  59. /** Beams created by (optional) autoBeam function. */
  60. private autoVfBeams: Vex.Flow.Beam[];
  61. /** Beams of tuplet notes created by (optional) autoBeam function. */
  62. private autoTupletVfBeams: Vex.Flow.Beam[];
  63. /** VexFlow Beams */
  64. private vfbeams: { [voiceID: number]: Vex.Flow.Beam[]; };
  65. /** Intermediate object to construct tuplets */
  66. protected tuplets: { [voiceID: number]: [Tuplet, VexFlowVoiceEntry[]][]; } = {};
  67. /** VexFlow Tuplets */
  68. protected vftuplets: { [voiceID: number]: Vex.Flow.Tuplet[]; } = {};
  69. // Sets the absolute coordinates of the VFStave on the canvas
  70. public setAbsoluteCoordinates(x: number, y: number): void {
  71. this.stave.setX(x).setY(y);
  72. }
  73. /**
  74. * Reset all the geometric values and parameters of this measure and put it in an initialized state.
  75. * This is needed to evaluate a measure a second time by system builder.
  76. */
  77. public resetLayout(): void {
  78. // Take into account some space for the begin and end lines of the stave
  79. // Will be changed when repetitions will be implemented
  80. //this.beginInstructionsWidth = 20 / UnitInPixels;
  81. //this.endInstructionsWidth = 20 / UnitInPixels;
  82. // TODO save beginning and end bar type, set these again after new stave.
  83. this.stave = new Vex.Flow.Stave(0, 0, 0, {
  84. space_above_staff_ln: 0,
  85. space_below_staff_ln: 0,
  86. });
  87. // constructor sets beginning and end bar type to standard
  88. this.stave.setBegBarType(Vex.Flow.Barline.type.NONE); // technically not correct, but we'd need to set the next measure's beginning bar type
  89. if (this.parentSourceMeasure && this.parentSourceMeasure.endingBarStyleEnum === SystemLinesEnum.None) {
  90. // fix for vexflow ignoring ending barline style after new stave, apparently
  91. this.stave.setEndBarType(Vex.Flow.Barline.type.NONE);
  92. }
  93. // the correct bar types seem to be set later
  94. //if (nextMeasureIndex >= EngravingRules.Rules.MinMeasureToDrawIndex && nextMeasureIndex <= EngravingRules.Rules.MaxMeasureToDrawIndex) {
  95. //this.stave.setBegBarType(Vex.Flow.Barline.type.NONE);
  96. this.updateInstructionWidth();
  97. }
  98. public clean(): void {
  99. this.vfTies.length = 0;
  100. this.connectors = [];
  101. // Clean up instructions
  102. this.resetLayout();
  103. }
  104. /**
  105. * returns the x-width (in units) of a given measure line {SystemLinesEnum}.
  106. * @param line
  107. * @returns the x-width in osmd units
  108. */
  109. public getLineWidth(line: SystemLinesEnum): number {
  110. switch (line) {
  111. // return 0 for the normal lines, as the line width will be considered at the updateInstructionWidth() method using the stavemodifiers.
  112. // case SystemLinesEnum.SingleThin:
  113. // return 5.0 / unitInPixels;
  114. // case SystemLinesEnum.DoubleThin:
  115. // return 5.0 / unitInPixels;
  116. // case SystemLinesEnum.ThinBold:
  117. // return 5.0 / unitInPixels;
  118. // but just add a little extra space for repetitions (cosmetics):
  119. case SystemLinesEnum.BoldThinDots:
  120. case SystemLinesEnum.DotsThinBold:
  121. return 10.0 / unitInPixels;
  122. case SystemLinesEnum.DotsBoldBoldDots:
  123. return 10.0 / unitInPixels;
  124. default:
  125. return 0;
  126. }
  127. }
  128. /**
  129. * adds the given clef to the begin of the measure.
  130. * This has to update/increase BeginInstructionsWidth.
  131. * @param clef
  132. */
  133. public addClefAtBegin(clef: ClefInstruction): void {
  134. this.octaveOffset = clef.OctaveOffset;
  135. if (clef.ClefType === ClefEnum.TAB) {
  136. this.stave.addClef("tab", undefined, undefined, undefined);
  137. } else {
  138. const vfclef: { type: string, size: string, annotation: string } = VexFlowConverter.Clef(clef, "default");
  139. this.stave.addClef(vfclef.type, vfclef.size, vfclef.annotation, Vex.Flow.StaveModifier.Position.BEGIN);
  140. }
  141. this.updateInstructionWidth();
  142. }
  143. /**
  144. * adds the given key to the begin of the measure.
  145. * This has to update/increase BeginInstructionsWidth.
  146. * @param currentKey the new valid key.
  147. * @param previousKey the old cancelled key. Needed to show which accidentals are not valid any more.
  148. * @param currentClef the valid clef. Needed to put the accidentals on the right y-positions.
  149. */
  150. public addKeyAtBegin(currentKey: KeyInstruction, previousKey: KeyInstruction, currentClef: ClefInstruction): void {
  151. this.stave.setKeySignature(
  152. VexFlowConverter.keySignature(currentKey),
  153. VexFlowConverter.keySignature(previousKey),
  154. undefined
  155. );
  156. this.updateInstructionWidth();
  157. }
  158. /**
  159. * adds the given rhythm to the begin of the measure.
  160. * This has to update/increase BeginInstructionsWidth.
  161. * @param rhythm
  162. */
  163. public addRhythmAtBegin(rhythm: RhythmInstruction): void {
  164. const timeSig: Vex.Flow.TimeSignature = VexFlowConverter.TimeSignature(rhythm);
  165. this.stave.addModifier(
  166. timeSig,
  167. Vex.Flow.StaveModifier.Position.BEGIN
  168. );
  169. this.updateInstructionWidth();
  170. }
  171. /**
  172. * adds the given clef to the end of the measure.
  173. * This has to update/increase EndInstructionsWidth.
  174. * @param clef
  175. */
  176. public addClefAtEnd(clef: ClefInstruction): void {
  177. const vfclef: { type: string, size: string, annotation: string } = VexFlowConverter.Clef(clef, "small");
  178. this.stave.setEndClef(vfclef.type, vfclef.size, vfclef.annotation);
  179. this.updateInstructionWidth();
  180. }
  181. public addMeasureLine(lineType: SystemLinesEnum, linePosition: SystemLinePosition): void {
  182. switch (linePosition) {
  183. case SystemLinePosition.MeasureBegin:
  184. switch (lineType) {
  185. case SystemLinesEnum.BoldThinDots:
  186. this.stave.setBegBarType(Vex.Flow.Barline.type.REPEAT_BEGIN);
  187. break;
  188. default:
  189. //this.stave.setBegBarType(Vex.Flow.Barline.type.NONE); // not necessary, it seems
  190. break;
  191. }
  192. break;
  193. case SystemLinePosition.MeasureEnd:
  194. switch (lineType) {
  195. case SystemLinesEnum.DotsBoldBoldDots:
  196. this.stave.setEndBarType(Vex.Flow.Barline.type.REPEAT_BOTH);
  197. break;
  198. case SystemLinesEnum.DotsThinBold:
  199. this.stave.setEndBarType(Vex.Flow.Barline.type.REPEAT_END);
  200. break;
  201. case SystemLinesEnum.DoubleThin:
  202. this.stave.setEndBarType(Vex.Flow.Barline.type.DOUBLE);
  203. break;
  204. case SystemLinesEnum.ThinBold:
  205. this.stave.setEndBarType(Vex.Flow.Barline.type.END);
  206. break;
  207. case SystemLinesEnum.None:
  208. this.stave.setEndBarType(Vex.Flow.Barline.type.NONE);
  209. break;
  210. // TODO: Add support for additional Barline types when VexFlow supports them
  211. default:
  212. break;
  213. }
  214. break;
  215. default:
  216. break;
  217. }
  218. }
  219. /**
  220. * Adds a measure number to the top left corner of the measure
  221. * This method is not used currently in favor of the calculateMeasureNumberPlacement
  222. * method in the MusicSheetCalculator.ts
  223. */
  224. public addMeasureNumber(): void {
  225. const text: string = this.MeasureNumber.toString();
  226. const position: number = StavePositionEnum.ABOVE; //Vex.Flow.StaveModifier.Position.ABOVE;
  227. const options: any = {
  228. justification: 1,
  229. shift_x: 0,
  230. shift_y: 0,
  231. };
  232. this.stave.setText(text, position, options);
  233. }
  234. public addWordRepetition(repetitionInstruction: RepetitionInstruction): void {
  235. let instruction: Vex.Flow.Repetition.type = undefined;
  236. let position: any = Vex.Flow.StaveModifier.Position.END;
  237. switch (repetitionInstruction.type) {
  238. case RepetitionInstructionEnum.Segno:
  239. // create Segno Symbol:
  240. instruction = Vex.Flow.Repetition.type.SEGNO_LEFT;
  241. position = Vex.Flow.StaveModifier.Position.BEGIN;
  242. break;
  243. case RepetitionInstructionEnum.Coda:
  244. // create Coda Symbol:
  245. instruction = Vex.Flow.Repetition.type.CODA_LEFT;
  246. position = Vex.Flow.StaveModifier.Position.BEGIN;
  247. break;
  248. case RepetitionInstructionEnum.DaCapo:
  249. instruction = Vex.Flow.Repetition.type.DC;
  250. break;
  251. case RepetitionInstructionEnum.DalSegno:
  252. instruction = Vex.Flow.Repetition.type.DS;
  253. break;
  254. case RepetitionInstructionEnum.Fine:
  255. instruction = Vex.Flow.Repetition.type.FINE;
  256. break;
  257. case RepetitionInstructionEnum.ToCoda:
  258. //instruction = "To Coda";
  259. break;
  260. case RepetitionInstructionEnum.DaCapoAlFine:
  261. instruction = Vex.Flow.Repetition.type.DC_AL_FINE;
  262. break;
  263. case RepetitionInstructionEnum.DaCapoAlCoda:
  264. instruction = Vex.Flow.Repetition.type.DC_AL_CODA;
  265. break;
  266. case RepetitionInstructionEnum.DalSegnoAlFine:
  267. instruction = Vex.Flow.Repetition.type.DS_AL_FINE;
  268. break;
  269. case RepetitionInstructionEnum.DalSegnoAlCoda:
  270. instruction = Vex.Flow.Repetition.type.DS_AL_CODA;
  271. break;
  272. default:
  273. break;
  274. }
  275. if (instruction !== undefined) {
  276. this.stave.addModifier(new Vex.Flow.Repetition(instruction, 0, 0), position);
  277. return;
  278. }
  279. this.addVolta(repetitionInstruction);
  280. }
  281. private addVolta(repetitionInstruction: RepetitionInstruction): void {
  282. let voltaType: number = Vex.Flow.Volta.type.BEGIN;
  283. if (repetitionInstruction.type === RepetitionInstructionEnum.Ending) {
  284. switch (repetitionInstruction.alignment) {
  285. case AlignmentType.Begin:
  286. if (this.parentSourceMeasure.endsRepetitionEnding()) {
  287. voltaType = Vex.Flow.Volta.type.BEGIN_END;
  288. } else {
  289. voltaType = Vex.Flow.Volta.type.BEGIN;
  290. }
  291. break;
  292. case AlignmentType.End:
  293. if (this.parentSourceMeasure.beginsRepetitionEnding()) {
  294. //voltaType = Vex.Flow.Volta.type.BEGIN_END;
  295. // don't add BEGIN_END volta a second time:
  296. return;
  297. } else {
  298. voltaType = Vex.Flow.Volta.type.END;
  299. }
  300. break;
  301. default:
  302. break;
  303. }
  304. this.stave.setVoltaType(voltaType, repetitionInstruction.endingIndices[0], 0);
  305. }
  306. }
  307. /**
  308. * Sets the overall x-width of the measure.
  309. * @param width
  310. */
  311. public setWidth(width: number): void {
  312. super.setWidth(width);
  313. // Set the width of the Vex.Flow.Stave
  314. this.stave.setWidth(width * unitInPixels);
  315. // Force the width of the Begin Instructions
  316. //this.stave.setNoteStartX(this.beginInstructionsWidth * UnitInPixels);
  317. }
  318. /**
  319. * This method is called after the StaffEntriesScaleFactor has been set.
  320. * Here the final x-positions of the staff entries have to be set.
  321. * (multiply the minimal positions with the scaling factor, considering the BeginInstructionsWidth)
  322. */
  323. public layoutSymbols(): void {
  324. // vexflow does the x-layout
  325. }
  326. /**
  327. * Draw this measure on a VexFlow CanvasContext
  328. * @param ctx
  329. */
  330. public draw(ctx: Vex.IRenderContext): void {
  331. // Draw stave lines
  332. this.stave.setContext(ctx).draw();
  333. // Draw all voices
  334. for (const voiceID in this.vfVoices) {
  335. if (this.vfVoices.hasOwnProperty(voiceID)) {
  336. ctx.save();
  337. this.vfVoices[voiceID].draw(ctx, this.stave);
  338. ctx.restore();
  339. // this.vfVoices[voiceID].tickables.forEach(t => t.getBoundingBox().draw(ctx));
  340. // this.vfVoices[voiceID].tickables.forEach(t => t.getBoundingBox().draw(ctx));
  341. }
  342. }
  343. // Draw beams
  344. for (const voiceID in this.vfbeams) {
  345. if (this.vfbeams.hasOwnProperty(voiceID)) {
  346. for (const beam of this.vfbeams[voiceID]) {
  347. beam.setContext(ctx).draw();
  348. }
  349. }
  350. }
  351. // Draw auto-generated beams from Beam.generateBeams()
  352. if (this.autoVfBeams) {
  353. for (const beam of this.autoVfBeams) {
  354. beam.setContext(ctx).draw();
  355. }
  356. }
  357. if (this.autoTupletVfBeams) {
  358. for (const beam of this.autoTupletVfBeams) {
  359. beam.setContext(ctx).draw();
  360. }
  361. }
  362. // Draw tuplets
  363. for (const voiceID in this.vftuplets) {
  364. if (this.vftuplets.hasOwnProperty(voiceID)) {
  365. for (const tuplet of this.vftuplets[voiceID]) {
  366. tuplet.setContext(ctx).draw();
  367. }
  368. }
  369. }
  370. // Draw ties
  371. for (const tie of this.vfTies) {
  372. tie.setContext(ctx).draw();
  373. }
  374. // Draw vertical lines
  375. for (const connector of this.connectors) {
  376. connector.setContext(ctx).draw();
  377. }
  378. }
  379. // this currently formats multiple measures, see VexFlowMusicSheetCalculator.formatMeasures()
  380. public format(): void {
  381. // If this is the first stave in the vertical measure, call the format
  382. // method to set the width of all the voices
  383. if (this.formatVoices) {
  384. // set the width of the voices to the current measure width:
  385. // (The width of the voices does not include the instructions (StaveModifiers))
  386. this.formatVoices((this.PositionAndShape.Size.width - this.beginInstructionsWidth - this.endInstructionsWidth) * unitInPixels);
  387. }
  388. }
  389. /**
  390. * Returns all the voices that are present in this measure
  391. */
  392. public getVoicesWithinMeasure(): Voice[] {
  393. const voices: Voice[] = [];
  394. for (const gse of this.staffEntries) {
  395. for (const gve of gse.graphicalVoiceEntries) {
  396. if (voices.indexOf(gve.parentVoiceEntry.ParentVoice) === -1) {
  397. voices.push(gve.parentVoiceEntry.ParentVoice);
  398. }
  399. }
  400. }
  401. return voices;
  402. }
  403. /**
  404. * Returns all the graphicalVoiceEntries of a given Voice.
  405. * @param voice the voice for which the graphicalVoiceEntries shall be returned.
  406. */
  407. public getGraphicalVoiceEntriesPerVoice(voice: Voice): GraphicalVoiceEntry[] {
  408. const voiceEntries: GraphicalVoiceEntry[] = [];
  409. for (const gse of this.staffEntries) {
  410. for (const gve of gse.graphicalVoiceEntries) {
  411. if (gve.parentVoiceEntry.ParentVoice === voice) {
  412. voiceEntries.push(gve);
  413. }
  414. }
  415. }
  416. return voiceEntries;
  417. }
  418. /**
  419. * Finds the gaps between the existing notes within a measure.
  420. * Problem here is, that the graphicalVoiceEntry does not exist yet and
  421. * that Tied notes are not present in the normal voiceEntries.
  422. * To handle this, calculation with absolute timestamps is needed.
  423. * And the graphical notes have to be analysed directly (and not the voiceEntries, as it actually should be -> needs refactoring)
  424. * @param voice the voice for which the ghost notes shall be searched.
  425. */
  426. protected getRestFilledVexFlowStaveNotesPerVoice(voice: Voice): GraphicalVoiceEntry[] {
  427. let latestVoiceTimestamp: Fraction = undefined;
  428. const gvEntries: GraphicalVoiceEntry[] = this.getGraphicalVoiceEntriesPerVoice(voice);
  429. for (let idx: number = 0, len: number = gvEntries.length; idx < len; ++idx) {
  430. const gve: GraphicalVoiceEntry = gvEntries[idx];
  431. const gNotesStartTimestamp: Fraction = gve.notes[0].sourceNote.getAbsoluteTimestamp();
  432. // find the voiceEntry end timestamp:
  433. let gNotesEndTimestamp: Fraction = new Fraction();
  434. for (const graphicalNote of gve.notes) {
  435. const noteEnd: Fraction = Fraction.plus(graphicalNote.sourceNote.getAbsoluteTimestamp(), graphicalNote.sourceNote.Length);
  436. if (gNotesEndTimestamp.lt(noteEnd)) {
  437. gNotesEndTimestamp = noteEnd;
  438. }
  439. }
  440. // check if this voice has just been found the first time:
  441. if (latestVoiceTimestamp === undefined) {
  442. // if this voice is new, check for a gap from measure start to the start of the current voice entry:
  443. const gapFromMeasureStart: Fraction = Fraction.minus(gNotesStartTimestamp, this.parentSourceMeasure.AbsoluteTimestamp);
  444. if (gapFromMeasureStart.RealValue > 0) {
  445. log.trace(`Ghost Found at start (measure ${this.MeasureNumber})`); // happens too often for valid measures to be logged to debug
  446. const vfghost: Vex.Flow.GhostNote = VexFlowConverter.GhostNote(gapFromMeasureStart);
  447. const ghostGve: VexFlowVoiceEntry = new VexFlowVoiceEntry(undefined, undefined);
  448. ghostGve.vfStaveNote = vfghost;
  449. gvEntries.splice(0, 0, ghostGve);
  450. idx++;
  451. }
  452. } else {
  453. // get the length of the empty space between notes:
  454. const inBetweenLength: Fraction = Fraction.minus(gNotesStartTimestamp, latestVoiceTimestamp);
  455. if (inBetweenLength.RealValue > 0) {
  456. log.trace(`Ghost Found in between (measure ${this.MeasureNumber})`); // happens too often for valid measures to be logged to debug
  457. const vfghost: Vex.Flow.GhostNote = VexFlowConverter.GhostNote(inBetweenLength);
  458. const ghostGve: VexFlowVoiceEntry = new VexFlowVoiceEntry(undefined, undefined);
  459. ghostGve.vfStaveNote = vfghost;
  460. // add element before current element:
  461. gvEntries.splice(idx, 0, ghostGve);
  462. // and increase index, as we added an element:
  463. idx++;
  464. }
  465. }
  466. // finally set the latest timestamp of this voice to the end timestamp of the longest note in the current voiceEntry:
  467. latestVoiceTimestamp = gNotesEndTimestamp;
  468. }
  469. const measureEndTimestamp: Fraction = Fraction.plus(this.parentSourceMeasure.AbsoluteTimestamp, this.parentSourceMeasure.Duration);
  470. const restLength: Fraction = Fraction.minus(measureEndTimestamp, latestVoiceTimestamp);
  471. if (restLength.RealValue > 0) {
  472. // fill the gap with a rest ghost note
  473. // starting from lastFraction
  474. // with length restLength:
  475. log.trace(`Ghost Found at end (measure ${this.MeasureNumber})`); // happens too often for valid measures to be logged to debug
  476. const vfghost: Vex.Flow.GhostNote = VexFlowConverter.GhostNote(restLength);
  477. const ghostGve: VexFlowVoiceEntry = new VexFlowVoiceEntry(undefined, undefined);
  478. ghostGve.vfStaveNote = vfghost;
  479. gvEntries.push(ghostGve);
  480. }
  481. return gvEntries;
  482. }
  483. /**
  484. * Add a note to a beam
  485. * @param graphicalNote
  486. * @param beam
  487. */
  488. public handleBeam(graphicalNote: GraphicalNote, beam: Beam): void {
  489. const voiceID: number = graphicalNote.sourceNote.ParentVoiceEntry.ParentVoice.VoiceId;
  490. let beams: [Beam, VexFlowVoiceEntry[]][] = this.beams[voiceID];
  491. if (beams === undefined) {
  492. beams = this.beams[voiceID] = [];
  493. }
  494. let data: [Beam, VexFlowVoiceEntry[]];
  495. for (const mybeam of beams) {
  496. if (mybeam[0] === beam) {
  497. data = mybeam;
  498. }
  499. }
  500. if (data === undefined) {
  501. data = [beam, []];
  502. beams.push(data);
  503. }
  504. const parent: VexFlowVoiceEntry = graphicalNote.parentVoiceEntry as VexFlowVoiceEntry;
  505. if (data[1].indexOf(parent) < 0) {
  506. data[1].push(parent);
  507. }
  508. }
  509. public handleTuplet(graphicalNote: GraphicalNote, tuplet: Tuplet): void {
  510. const voiceID: number = graphicalNote.sourceNote.ParentVoiceEntry.ParentVoice.VoiceId;
  511. tuplet = graphicalNote.sourceNote.NoteTuplet;
  512. let tuplets: [Tuplet, VexFlowVoiceEntry[]][] = this.tuplets[voiceID];
  513. if (tuplets === undefined) {
  514. tuplets = this.tuplets[voiceID] = [];
  515. }
  516. let currentTupletBuilder: [Tuplet, VexFlowVoiceEntry[]];
  517. for (const t of tuplets) {
  518. if (t[0] === tuplet) {
  519. currentTupletBuilder = t;
  520. }
  521. }
  522. if (currentTupletBuilder === undefined) {
  523. currentTupletBuilder = [tuplet, []];
  524. tuplets.push(currentTupletBuilder);
  525. }
  526. const parent: VexFlowVoiceEntry = graphicalNote.parentVoiceEntry as VexFlowVoiceEntry;
  527. if (currentTupletBuilder[1].indexOf(parent) < 0) {
  528. currentTupletBuilder[1].push(parent);
  529. }
  530. }
  531. /**
  532. * Complete the creation of VexFlow Beams in this measure
  533. */
  534. public finalizeBeams(): void {
  535. // The following line resets the created Vex.Flow Beams and
  536. // created them brand new. Is this needed? And more importantly,
  537. // should the old beams be removed manually by the notes?
  538. this.vfbeams = {};
  539. const beamedNotes: StaveNote[] = []; // already beamed notes, will be ignored by this.autoBeamNotes()
  540. for (const voiceID in this.beams) {
  541. if (this.beams.hasOwnProperty(voiceID)) {
  542. let vfbeams: Vex.Flow.Beam[] = this.vfbeams[voiceID];
  543. if (vfbeams === undefined) {
  544. vfbeams = this.vfbeams[voiceID] = [];
  545. }
  546. for (const beam of this.beams[voiceID]) {
  547. let beamHasQuarterNoteOrLonger: boolean = false;
  548. for (const note of beam[0].Notes) {
  549. if (note.Length.RealValue >= new Fraction(1, 4).RealValue
  550. // check whether the note has a TypeLength that's also not suitable for a beam (bigger than an eigth)
  551. && (note.TypeLength === undefined || note.TypeLength.RealValue > 0.125)) {
  552. beamHasQuarterNoteOrLonger = true;
  553. break;
  554. }
  555. }
  556. if (beamHasQuarterNoteOrLonger) {
  557. log.debug("Beam between note >= quarter, likely tremolo, currently unsupported. continuing.");
  558. continue;
  559. }
  560. const notes: Vex.Flow.StaveNote[] = [];
  561. const psBeam: Beam = beam[0];
  562. const voiceEntries: VexFlowVoiceEntry[] = beam[1];
  563. let autoStemBeam: boolean = true;
  564. for (const gve of voiceEntries) {
  565. if (gve.parentVoiceEntry.ParentVoice === psBeam.Notes[0].ParentVoiceEntry.ParentVoice) {
  566. autoStemBeam = gve.parentVoiceEntry.WantedStemDirection === StemDirectionType.Undefined;
  567. }
  568. }
  569. let isGraceBeam: boolean = false;
  570. let beamColor: string;
  571. const stemColors: string[] = [];
  572. for (const entry of voiceEntries) {
  573. const note: Vex.Flow.StaveNote = ((<VexFlowVoiceEntry>entry).vfStaveNote as StaveNote);
  574. if (note !== undefined) {
  575. notes.push(note);
  576. beamedNotes.push(note);
  577. }
  578. if (entry.parentVoiceEntry.IsGrace) {
  579. isGraceBeam = true;
  580. }
  581. if (entry.parentVoiceEntry.StemColor && EngravingRules.Rules.ColoringEnabled) {
  582. stemColors.push(entry.parentVoiceEntry.StemColor);
  583. }
  584. }
  585. if (notes.length > 1) {
  586. const vfBeam: Vex.Flow.Beam = new Vex.Flow.Beam(notes, autoStemBeam);
  587. if (isGraceBeam) {
  588. // smaller beam, as in Vexflow.GraceNoteGroup.beamNotes()
  589. (<any>vfBeam).render_options.beam_width = 3;
  590. (<any>vfBeam).render_options.partial_beam_length = 4;
  591. }
  592. if (stemColors.length >= 2 && EngravingRules.Rules.ColorBeams) {
  593. beamColor = stemColors[0];
  594. for (const stemColor of stemColors) {
  595. if (stemColor !== beamColor) {
  596. beamColor = undefined;
  597. break;
  598. }
  599. }
  600. vfBeam.setStyle({ fillStyle: beamColor, strokeStyle: beamColor });
  601. }
  602. vfbeams.push(vfBeam);
  603. } else {
  604. log.debug("Warning! Beam with no notes!");
  605. }
  606. }
  607. }
  608. }
  609. if (EngravingRules.Rules.AutoBeamNotes) {
  610. this.autoBeamNotes(beamedNotes); // try to autobeam notes except those that are already beamed (beamedNotes).
  611. }
  612. }
  613. /** Automatically creates beams for notes except beamedNotes, using Vexflow's Beam.generateBeams().
  614. * Takes options from EngravingRules.Rules.AutoBeamOptions.
  615. * @param beamedNotes notes that will not be autobeamed (usually because they are already beamed)
  616. */
  617. private autoBeamNotes(beamedNotes: StemmableNote[]): void {
  618. let notesToAutoBeam: StemmableNote[] = [];
  619. let consecutiveBeamableNotes: StemmableNote[] = [];
  620. let currentTuplet: Tuplet;
  621. let tupletNotesToAutoBeam: StaveNote[] = [];
  622. this.autoTupletVfBeams = [];
  623. const separateAutoBeams: StemmableNote[][] = []; // a set of separate beams, each having a set of notes (StemmableNote[]).
  624. this.autoVfBeams = []; // final Vex.Flow.Beams will be pushed/collected into this
  625. let timeSignature: Fraction = this.parentSourceMeasure.ActiveTimeSignature;
  626. if (timeSignature === undefined) { // this doesn't happen in OSMD, but maybe in a SourceGenerator
  627. timeSignature = this.parentSourceMeasure.Duration; // suboptimal, can be 1/1 in a 4/4 time signature
  628. }
  629. /*if (this.parentSourceMeasure.FirstInstructionsStaffEntries[0]) {
  630. for (const instruction of this.parentSourceMeasure.FirstInstructionsStaffEntries[0].Instructions) {
  631. if (instruction instanceof RhythmInstruction) { // there is not always a RhythmInstruction, but this could be useful some time.
  632. timeSignature = (instruction as RhythmInstruction).Rhythm;
  633. }
  634. }
  635. }*/
  636. for (const staffEntry of this.staffEntries) {
  637. for (const gve of staffEntry.graphicalVoiceEntries) {
  638. const vfStaveNote: StaveNote = <StaveNote> (gve as VexFlowVoiceEntry).vfStaveNote;
  639. const gNote: GraphicalNote = gve.notes[0]; // TODO check for all notes within the graphical voice entry
  640. const isOnBeat: boolean = staffEntry.relInMeasureTimestamp.isOnBeat(timeSignature);
  641. const haveTwoOrMoreNotesToBeamAlready: boolean = consecutiveBeamableNotes.length >= 2;
  642. //const noteIsQuarterOrLonger: boolean = gNote.sourceNote.Length.CompareTo(new Fraction(1, 4)) >= 0; // trusting Fraction class, no float check
  643. const noteIsQuarterOrLonger: boolean = gNote.sourceNote.Length.RealValue - new Fraction(1, 4).RealValue > (-Fraction.FloatInaccuracyTolerance);
  644. const unbeamableNote: boolean =
  645. gve.parentVoiceEntry.IsGrace || // don't beam grace notes
  646. noteIsQuarterOrLonger || // don't beam quarter or longer notes
  647. beamedNotes.contains(vfStaveNote);
  648. if (unbeamableNote || isOnBeat) { // end beam
  649. if (haveTwoOrMoreNotesToBeamAlready) {
  650. // if we already have at least 2 notes to beam, beam them. don't beam notes surrounded by quarter notes etc.
  651. for (const note of consecutiveBeamableNotes) {
  652. notesToAutoBeam.push(note); // "flush" already beamed notes
  653. }
  654. separateAutoBeams.push(notesToAutoBeam.slice()); // copy array, otherwise this beam gets the next notes of next beam later
  655. notesToAutoBeam = []; // reset notesToAutoBeam, otherwise the next beam includes the previous beam's notes too
  656. }
  657. consecutiveBeamableNotes = []; // reset notes to beam
  658. if (unbeamableNote) {
  659. continue;
  660. }
  661. // else, note will be pushed to consecutiveBeamableNotes after tuplet check, also for note on new beat
  662. }
  663. // create beams for tuplets separately
  664. const noteTuplet: Tuplet = gve.notes[0].sourceNote.NoteTuplet;
  665. if (noteTuplet) {
  666. // check if there are quarter notes or longer in the tuplet, then don't beam.
  667. // (TODO: check for consecutiveBeamableNotes inside tuplets like for non-tuplet notes above
  668. // e.g quarter eigth eighth -> beam the two eigth notes)
  669. let tupletContainsUnbeamableNote: boolean = false;
  670. for (const notes of noteTuplet.Notes) {
  671. for (const note of notes) {
  672. //const stavenote: StemmableNote = (gve as VexFlowVoiceEntry).vfStaveNote;
  673. //console.log("note " + note.ToString() + ", stavenote type: " + stavenote.getNoteType());
  674. if (note.NoteTypeXml >= NoteType.QUARTER || // quarter note or longer: don't beam
  675. // TODO: don't take Note (head) type from XML, but from current model,
  676. // so that rendering can react dynamically to changes compared to the XML.
  677. // however, taking the note length as fraction is tricky because of tuplets.
  678. // a quarter in a triplet has length < quarter, but quarter note head, which Vexflow can't beam.
  679. note.ParentVoiceEntry.IsGrace ||
  680. note.isRest() && !EngravingRules.Rules.AutoBeamOptions.beam_rests) {
  681. tupletContainsUnbeamableNote = true;
  682. break;
  683. }
  684. }
  685. if (tupletContainsUnbeamableNote) {
  686. break;
  687. }
  688. }
  689. if (currentTuplet === undefined) {
  690. currentTuplet = noteTuplet;
  691. } else {
  692. if (currentTuplet !== noteTuplet) { // new tuplet, finish old one
  693. if (tupletNotesToAutoBeam.length > 1) {
  694. this.autoTupletVfBeams.push(new Vex.Flow.Beam(tupletNotesToAutoBeam, true));
  695. }
  696. tupletNotesToAutoBeam = [];
  697. currentTuplet = noteTuplet;
  698. }
  699. }
  700. if (!tupletContainsUnbeamableNote) {
  701. tupletNotesToAutoBeam.push(vfStaveNote);
  702. }
  703. continue;
  704. } else {
  705. currentTuplet = undefined;
  706. }
  707. consecutiveBeamableNotes.push(vfStaveNote); // also happens on new beat
  708. }
  709. }
  710. if (tupletNotesToAutoBeam.length >= 2) {
  711. this.autoTupletVfBeams.push(new Vex.Flow.Beam(tupletNotesToAutoBeam, true));
  712. }
  713. if (consecutiveBeamableNotes.length >= 2) {
  714. for (const note of consecutiveBeamableNotes) {
  715. notesToAutoBeam.push(note);
  716. }
  717. separateAutoBeams.push(notesToAutoBeam);
  718. }
  719. // create options for generateBeams
  720. const autoBeamOptions: AutoBeamOptions = EngravingRules.Rules.AutoBeamOptions;
  721. const generateBeamOptions: any = {
  722. beam_middle_only: autoBeamOptions.beam_middle_rests_only,
  723. beam_rests: autoBeamOptions.beam_rests,
  724. maintain_stem_directions: autoBeamOptions.maintain_stem_directions,
  725. };
  726. if (autoBeamOptions.groups && autoBeamOptions.groups.length) {
  727. const groups: Vex.Flow.Fraction[] = [];
  728. for (const fraction of autoBeamOptions.groups) {
  729. groups.push(new Vex.Flow.Fraction(fraction[0], fraction[1]));
  730. }
  731. generateBeamOptions.groups = groups;
  732. }
  733. for (const notesForSeparateAutoBeam of separateAutoBeams) {
  734. const newBeams: Vex.Flow.Beam[] = Vex.Flow.Beam.generateBeams(notesForSeparateAutoBeam, generateBeamOptions);
  735. for (const beam of newBeams) {
  736. this.autoVfBeams.push(beam);
  737. }
  738. }
  739. }
  740. /**
  741. * Complete the creation of VexFlow Tuplets in this measure
  742. */
  743. public finalizeTuplets(): void {
  744. // The following line resets the created Vex.Flow Tuplets and
  745. // created them brand new. Is this needed? And more importantly,
  746. // should the old tuplets be removed manually from the notes?
  747. this.vftuplets = {};
  748. for (const voiceID in this.tuplets) {
  749. if (this.tuplets.hasOwnProperty(voiceID)) {
  750. let vftuplets: Vex.Flow.Tuplet[] = this.vftuplets[voiceID];
  751. if (vftuplets === undefined) {
  752. vftuplets = this.vftuplets[voiceID] = [];
  753. }
  754. for (const tupletBuilder of this.tuplets[voiceID]) {
  755. const tupletStaveNotes: Vex.Flow.StaveNote[] = [];
  756. const tupletVoiceEntries: VexFlowVoiceEntry[] = tupletBuilder[1];
  757. for (const tupletVoiceEntry of tupletVoiceEntries) {
  758. tupletStaveNotes.push(((tupletVoiceEntry).vfStaveNote as StaveNote));
  759. }
  760. if (tupletStaveNotes.length > 1) {
  761. const tuplet: Tuplet = tupletBuilder[0];
  762. const notesOccupied: number = tuplet.Notes[0][0].NormalNotes;
  763. const bracketed: boolean = tuplet.Bracket ||
  764. (tuplet.TupletLabelNumber === 3 && EngravingRules.Rules.TripletsBracketed) ||
  765. (tuplet.TupletLabelNumber !== 3 && EngravingRules.Rules.TupletsBracketed);
  766. vftuplets.push(new Vex.Flow.Tuplet( tupletStaveNotes,
  767. {
  768. bracketed: bracketed,
  769. notes_occupied: notesOccupied,
  770. num_notes: tuplet.TupletLabelNumber, //, location: -1, ratioed: true
  771. ratioed: EngravingRules.Rules.TupletsRatioed,
  772. }));
  773. } else {
  774. log.debug("Warning! Tuplet with no notes! Trying to ignore, but this is a serious problem.");
  775. }
  776. }
  777. }
  778. }
  779. }
  780. public layoutStaffEntry(graphicalStaffEntry: GraphicalStaffEntry): void {
  781. return;
  782. }
  783. public graphicalMeasureCreatedCalculations(): void {
  784. let graceSlur: boolean;
  785. let graceGVoiceEntriesBefore: GraphicalVoiceEntry[] = [];
  786. for (const graphicalStaffEntry of this.staffEntries as VexFlowStaffEntry[]) {
  787. graceSlur = false;
  788. graceGVoiceEntriesBefore = [];
  789. // create vex flow Stave Notes:
  790. for (const gve of graphicalStaffEntry.graphicalVoiceEntries) {
  791. if (gve.parentVoiceEntry.IsGrace) {
  792. // save grace notes for the next non-grace note
  793. graceGVoiceEntriesBefore.push(gve);
  794. if (!graceSlur) {
  795. graceSlur = gve.parentVoiceEntry.GraceSlur;
  796. }
  797. continue;
  798. }
  799. if (gve.notes[0].sourceNote.PrintObject) {
  800. (gve as VexFlowVoiceEntry).vfStaveNote = VexFlowConverter.StaveNote(gve);
  801. } else {
  802. // note can now also be added as StaveNote instead of GhostNote, because we set it to transparent
  803. (gve as VexFlowVoiceEntry).vfStaveNote = VexFlowConverter.StaveNote(gve);
  804. // previous method: add as GhostNote instead of StaveNote. Can cause formatting issues if critical notes are missing in the measure
  805. // don't render note. add ghost note, otherwise Vexflow can have issues with layouting when voices not complete.
  806. //(gve as VexFlowVoiceEntry).vfStaveNote = VexFlowConverter.GhostNote(gve.notes[0].sourceNote.Length);
  807. //graceGVoiceEntriesBefore = []; // if note is not rendered, its grace notes shouldn't be rendered, might need to be removed
  808. //continue;
  809. }
  810. if (graceGVoiceEntriesBefore.length > 0) {
  811. // add grace notes that came before this main note to a GraceNoteGroup in Vexflow, attached to the main note
  812. const graceNotes: Vex.Flow.GraceNote[] = [];
  813. for (let i: number = 0; i < graceGVoiceEntriesBefore.length; i++) {
  814. const gveGrace: VexFlowVoiceEntry = <VexFlowVoiceEntry>graceGVoiceEntriesBefore[i];
  815. //if (gveGrace.notes[0].sourceNote.PrintObject) {
  816. // grace notes should generally be rendered independently of main note instead of skipped if main note is invisible
  817. // could be an option to make grace notes transparent if main note is transparent. set grace notes' PrintObject to false then.
  818. const vfStaveNote: StaveNote = VexFlowConverter.StaveNote(gveGrace);
  819. gveGrace.vfStaveNote = vfStaveNote;
  820. graceNotes.push(vfStaveNote);
  821. }
  822. const graceNoteGroup: Vex.Flow.GraceNoteGroup = new Vex.Flow.GraceNoteGroup(graceNotes, graceSlur);
  823. ((gve as VexFlowVoiceEntry).vfStaveNote as StaveNote).addModifier(0, graceNoteGroup);
  824. graceGVoiceEntriesBefore = [];
  825. }
  826. }
  827. }
  828. // remaining grace notes at end of measure, turned into stand-alone grace notes:
  829. if (graceGVoiceEntriesBefore.length > 0) {
  830. for (const graceGve of graceGVoiceEntriesBefore) {
  831. (graceGve as VexFlowVoiceEntry).vfStaveNote = VexFlowConverter.StaveNote(graceGve);
  832. graceGve.parentVoiceEntry.GraceAfterMainNote = true;
  833. }
  834. }
  835. this.finalizeBeams();
  836. this.finalizeTuplets();
  837. const voices: Voice[] = this.getVoicesWithinMeasure();
  838. for (const voice of voices) {
  839. if (voice === undefined) {
  840. continue;
  841. }
  842. const isMainVoice: boolean = !(voice instanceof LinkedVoice);
  843. // add a vexFlow voice for this voice:
  844. this.vfVoices[voice.VoiceId] = new Vex.Flow.Voice({
  845. beat_value: this.parentSourceMeasure.Duration.Denominator,
  846. num_beats: this.parentSourceMeasure.Duration.Numerator,
  847. resolution: Vex.Flow.RESOLUTION,
  848. }).setMode(Vex.Flow.Voice.Mode.SOFT);
  849. const restFilledEntries: GraphicalVoiceEntry[] = this.getRestFilledVexFlowStaveNotesPerVoice(voice);
  850. // create vex flow voices and add tickables to it:
  851. for (const voiceEntry of restFilledEntries) {
  852. if (voiceEntry.parentVoiceEntry) {
  853. if (voiceEntry.parentVoiceEntry.IsGrace && !voiceEntry.parentVoiceEntry.GraceAfterMainNote) {
  854. continue;
  855. }
  856. }
  857. const vexFlowVoiceEntry: VexFlowVoiceEntry = voiceEntry as VexFlowVoiceEntry;
  858. if (voiceEntry.notes.length === 0 || !voiceEntry.notes[0] || !voiceEntry.notes[0].sourceNote.PrintObject) {
  859. // GhostNote, don't add modifiers like in-measure clefs
  860. this.vfVoices[voice.VoiceId].addTickable(vexFlowVoiceEntry.vfStaveNote);
  861. continue;
  862. }
  863. // check for in-measure clefs:
  864. // only add clefs in main voice (to not add them twice)
  865. if (isMainVoice) {
  866. const vfse: VexFlowStaffEntry = vexFlowVoiceEntry.parentStaffEntry as VexFlowStaffEntry;
  867. if (vfse && vfse.vfClefBefore !== undefined) {
  868. // add clef as NoteSubGroup so that we get modifier layouting
  869. const clefModifier: NoteSubGroup = new NoteSubGroup( [vfse.vfClefBefore] );
  870. // The cast is necesary because...vexflow -> see types
  871. if (vexFlowVoiceEntry.vfStaveNote.getCategory && vexFlowVoiceEntry.vfStaveNote.getCategory() === "stavenotes") {
  872. // GhostNotes and other StemmableNotes don't have this function
  873. (vexFlowVoiceEntry.vfStaveNote as Vex.Flow.StaveNote).addModifier(0, clefModifier);
  874. }
  875. }
  876. }
  877. // add fingering
  878. if (voiceEntry.parentVoiceEntry && EngravingRules.Rules.RenderFingerings) {
  879. this.createFingerings(voiceEntry);
  880. }
  881. // add Arpeggio
  882. if (voiceEntry.parentVoiceEntry && voiceEntry.parentVoiceEntry.Arpeggio !== undefined) {
  883. const arpeggio: Arpeggio = voiceEntry.parentVoiceEntry.Arpeggio;
  884. // TODO right now our arpeggio object has all arpeggio notes from arpeggios across all voices.
  885. // see VoiceGenerator. Doesn't matter for Vexflow for now though
  886. if (voiceEntry.notes && voiceEntry.notes.length > 1) {
  887. const type: Vex.Flow.Stroke.Type = VexFlowConverter.StrokeTypeFromArpeggioType(arpeggio.type);
  888. const stroke: Vex.Flow.Stroke = new Vex.Flow.Stroke(type, {
  889. all_voices: EngravingRules.Rules.ArpeggiosGoAcrossVoices
  890. // default: false. This causes arpeggios to always go across all voices, which is often unwanted.
  891. // also, this can cause infinite height of stroke, see #546
  892. });
  893. //if (arpeggio.notes.length === vexFlowVoiceEntry.notes.length) { // different workaround for endless y bug
  894. if (EngravingRules.Rules.RenderArpeggios) {
  895. vexFlowVoiceEntry.vfStaveNote.addStroke(0, stroke);
  896. }
  897. } else {
  898. log.debug(`[OSMD] arpeggio in measure ${this.MeasureNumber} could not be drawn.
  899. voice entry had less than two notes, arpeggio is likely between voice entries, not currently supported in Vexflow.`);
  900. // TODO: create new arpeggio with all the arpeggio's notes (arpeggio.notes), perhaps with GhostNotes in a new vfStaveNote. not easy.
  901. }
  902. }
  903. this.vfVoices[voice.VoiceId].addTickable(vexFlowVoiceEntry.vfStaveNote);
  904. }
  905. }
  906. this.createArticulations();
  907. this.createOrnaments();
  908. this.setStemDirectionFromVexFlow();
  909. }
  910. /**
  911. * Copy the stem directions chosen by VexFlow to the StemDirection variable of the graphical notes
  912. */
  913. private setStemDirectionFromVexFlow(): void {
  914. //if StemDirection was not set then read out what VexFlow has chosen
  915. for ( const vfStaffEntry of this.staffEntries ) {
  916. for ( const gVoiceEntry of vfStaffEntry.graphicalVoiceEntries) {
  917. for ( const gnote of gVoiceEntry.notes) {
  918. const vfnote: [StaveNote, number] = (gnote as VexFlowGraphicalNote).vfnote;
  919. if (vfnote === undefined || vfnote[0] === undefined) {
  920. continue;
  921. }
  922. const vfStemDir: number = vfnote[0].getStemDirection();
  923. switch (vfStemDir) {
  924. case (Vex.Flow.Stem.UP):
  925. gVoiceEntry.parentVoiceEntry.StemDirection = StemDirectionType.Up;
  926. break;
  927. case (Vex.Flow.Stem.DOWN):
  928. gVoiceEntry.parentVoiceEntry.StemDirection = StemDirectionType.Down;
  929. break;
  930. default:
  931. }
  932. }
  933. }
  934. }
  935. }
  936. /**
  937. * Create the articulations for all notes of the current staff entry
  938. */
  939. protected createArticulations(): void {
  940. for (let idx: number = 0, len: number = this.staffEntries.length; idx < len; ++idx) {
  941. const graphicalStaffEntry: VexFlowStaffEntry = (this.staffEntries[idx] as VexFlowStaffEntry);
  942. // create vex flow articulation:
  943. const graphicalVoiceEntries: GraphicalVoiceEntry[] = graphicalStaffEntry.graphicalVoiceEntries;
  944. for (const gve of graphicalVoiceEntries) {
  945. const vfStaveNote: StemmableNote = (gve as VexFlowVoiceEntry).vfStaveNote;
  946. VexFlowConverter.generateArticulations(vfStaveNote, gve.notes[0].sourceNote.ParentVoiceEntry.Articulations);
  947. }
  948. }
  949. }
  950. /**
  951. * Create the ornaments for all notes of the current staff entry
  952. */
  953. protected createOrnaments(): void {
  954. for (let idx: number = 0, len: number = this.staffEntries.length; idx < len; ++idx) {
  955. const graphicalStaffEntry: VexFlowStaffEntry = (this.staffEntries[idx] as VexFlowStaffEntry);
  956. const gvoices: { [voiceID: number]: GraphicalVoiceEntry; } = graphicalStaffEntry.graphicalVoiceEntries;
  957. for (const voiceID in gvoices) {
  958. if (gvoices.hasOwnProperty(voiceID)) {
  959. const vfStaveNote: StemmableNote = (gvoices[voiceID] as VexFlowVoiceEntry).vfStaveNote;
  960. const ornamentContainer: OrnamentContainer = gvoices[voiceID].notes[0].sourceNote.ParentVoiceEntry.OrnamentContainer;
  961. if (ornamentContainer !== undefined) {
  962. VexFlowConverter.generateOrnaments(vfStaveNote, ornamentContainer);
  963. }
  964. }
  965. }
  966. }
  967. }
  968. protected createFingerings(voiceEntry: GraphicalVoiceEntry): void {
  969. const vexFlowVoiceEntry: VexFlowVoiceEntry = voiceEntry as VexFlowVoiceEntry;
  970. const technicalInstructions: TechnicalInstruction[] = voiceEntry.parentVoiceEntry.TechnicalInstructions;
  971. const fingeringsCount: number = technicalInstructions.length;
  972. for (let i: number = 0; i < technicalInstructions.length; i++) {
  973. const technicalInstruction: TechnicalInstruction = technicalInstructions[i];
  974. let fingeringPosition: PlacementEnum = EngravingRules.Rules.FingeringPosition;
  975. if (technicalInstruction.placement !== PlacementEnum.NotYetDefined) {
  976. fingeringPosition = technicalInstruction.placement;
  977. }
  978. let modifierPosition: any; // Vex.Flow.Stavemodifier.Position
  979. switch (fingeringPosition) {
  980. default:
  981. case PlacementEnum.Left:
  982. modifierPosition = Vex.Flow.StaveModifier.Position.LEFT;
  983. break;
  984. case PlacementEnum.Right:
  985. modifierPosition = Vex.Flow.StaveModifier.Position.RIGHT;
  986. break;
  987. case PlacementEnum.Above:
  988. modifierPosition = Vex.Flow.StaveModifier.Position.ABOVE;
  989. break;
  990. case PlacementEnum.Below:
  991. modifierPosition = Vex.Flow.StaveModifier.Position.BELOW;
  992. break;
  993. case PlacementEnum.NotYetDefined: // automatic fingering placement, could be more complex/customizable
  994. const sourceStaff: Staff = voiceEntry.parentStaffEntry.sourceStaffEntry.ParentStaff;
  995. if (voiceEntry.notes.length > 1 || voiceEntry.parentStaffEntry.graphicalVoiceEntries.length > 1) {
  996. modifierPosition = Vex.Flow.StaveModifier.Position.LEFT;
  997. } else if (sourceStaff.idInMusicSheet === 0) {
  998. modifierPosition = Vex.Flow.StaveModifier.Position.ABOVE;
  999. fingeringPosition = PlacementEnum.Above;
  1000. } else {
  1001. modifierPosition = Vex.Flow.StaveModifier.Position.BELOW;
  1002. fingeringPosition = PlacementEnum.Below;
  1003. }
  1004. }
  1005. const fretFinger: Vex.Flow.FretHandFinger = new Vex.Flow.FretHandFinger(technicalInstruction.value);
  1006. fretFinger.setPosition(modifierPosition);
  1007. if (fingeringPosition === PlacementEnum.Above || fingeringPosition === PlacementEnum.Below) {
  1008. const offsetYSign: number = fingeringPosition === PlacementEnum.Above ? -1 : 1; // minus y is up
  1009. const ordering: number = fingeringPosition === PlacementEnum.Above ? i :
  1010. technicalInstructions.length - 1 - i; // reverse order for fingerings below staff
  1011. if (EngravingRules.Rules.FingeringInsideStafflines && fingeringsCount > 1) { // y-shift for single fingering is ok
  1012. // experimental, bounding boxes wrong for fretFinger above/below, better would be creating Labels
  1013. // set y-shift. vexflow fretfinger simply places directly above/below note
  1014. const perFingeringShift: number = fretFinger.getWidth() / 2;
  1015. const shiftCount: number = fingeringsCount * 2.5;
  1016. (<any>fretFinger).setOffsetY(offsetYSign * (ordering + shiftCount) * perFingeringShift);
  1017. } else if (!EngravingRules.Rules.FingeringInsideStafflines) { // use StringNumber for placement above/below stafflines
  1018. const stringNumber: Vex.Flow.StringNumber = new Vex.Flow.StringNumber(technicalInstruction.value);
  1019. (<any>stringNumber).radius = 0; // hack to remove the circle around the number
  1020. stringNumber.setPosition(modifierPosition);
  1021. stringNumber.setOffsetY(offsetYSign * ordering * stringNumber.getWidth() * 2 / 3);
  1022. // Vexflow made a mess with the addModifier signature that changes through each class so we just cast to any :(
  1023. vexFlowVoiceEntry.vfStaveNote.addModifier((i as any), (stringNumber as any));
  1024. continue;
  1025. }
  1026. }
  1027. // Vexflow made a mess with the addModifier signature that changes through each class so we just cast to any :(
  1028. vexFlowVoiceEntry.vfStaveNote.addModifier((i as any), (fretFinger as any));
  1029. }
  1030. }
  1031. /**
  1032. * Creates a line from 'top' to this measure, of type 'lineType'
  1033. * @param top
  1034. * @param lineType
  1035. */
  1036. public lineTo(top: VexFlowMeasure, lineType: any): void {
  1037. const connector: StaveConnector = new Vex.Flow.StaveConnector(top.getVFStave(), this.stave);
  1038. connector.setType(lineType);
  1039. this.connectors.push(connector);
  1040. }
  1041. /**
  1042. * Return the VexFlow Stave corresponding to this graphicalMeasure
  1043. * @returns {Vex.Flow.Stave}
  1044. */
  1045. public getVFStave(): Vex.Flow.Stave {
  1046. return this.stave;
  1047. }
  1048. /**
  1049. * After re-running the formatting on the VexFlow Stave, update the
  1050. * space needed by Instructions (in VexFlow: StaveModifiers)
  1051. */
  1052. protected updateInstructionWidth(): void {
  1053. let vfBeginInstructionsWidth: number = 0;
  1054. let vfEndInstructionsWidth: number = 0;
  1055. const modifiers: Vex.Flow.StaveModifier[] = this.stave.getModifiers();
  1056. for (const mod of modifiers) {
  1057. if (mod.getPosition() === StavePositionEnum.BEGIN) { //Vex.Flow.StaveModifier.Position.BEGIN) {
  1058. vfBeginInstructionsWidth += mod.getWidth() + mod.getPadding(undefined);
  1059. } else if (mod.getPosition() === StavePositionEnum.END) { //Vex.Flow.StaveModifier.Position.END) {
  1060. vfEndInstructionsWidth += mod.getWidth() + mod.getPadding(undefined);
  1061. }
  1062. }
  1063. this.beginInstructionsWidth = vfBeginInstructionsWidth / unitInPixels;
  1064. this.endInstructionsWidth = vfEndInstructionsWidth / unitInPixels;
  1065. }
  1066. }
  1067. // Gives the position of the Stave - replaces the function get Position() in the description of class StaveModifier in vexflow.d.ts
  1068. // The latter gave an error because function cannot be defined in the class descriptions in vexflow.d.ts
  1069. export enum StavePositionEnum {
  1070. LEFT = 1,
  1071. RIGHT = 2,
  1072. ABOVE = 3,
  1073. BELOW = 4,
  1074. BEGIN = 5,
  1075. END = 6
  1076. }