VexFlowMeasure.ts 79 KB

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