VexFlowMeasure.ts 70 KB

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