VexFlowMeasure.ts 80 KB

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