VexFlowMeasure.ts 84 KB

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