VexFlowMeasure.ts 65 KB

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