VexFlowMeasure.ts 68 KB

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