VexFlowMeasure.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. import Vex = require("vexflow");
  2. import {StaffMeasure} from "../StaffMeasure";
  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} from "../../VoiceData/Instructions/ClefInstruction";
  8. import {KeyInstruction} from "../../VoiceData/Instructions/KeyInstruction";
  9. import {RhythmInstruction} from "../../VoiceData/Instructions/RhythmInstruction";
  10. import {VexFlowConverter, VexFlowRepetitionType, VexFlowBarlineType} 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 {Logging} from "../../../Common/Logging";
  18. import {unitInPixels} from "./VexFlowMusicSheetDrawer";
  19. import {Tuplet} from "../../VoiceData/Tuplet";
  20. import { RepetitionInstructionEnum } from "../../VoiceData/Instructions/RepetitionInstruction";
  21. import { SystemLinePosition } from "../SystemLinePosition";
  22. export class VexFlowMeasure extends StaffMeasure {
  23. constructor(staff: Staff, staffLine: StaffLine = undefined, sourceMeasure: SourceMeasure = undefined) {
  24. super(staff, sourceMeasure, staffLine);
  25. this.minimumStaffEntriesWidth = -1;
  26. this.resetLayout();
  27. }
  28. // octaveOffset according to active clef
  29. public octaveOffset: number = 3;
  30. // The VexFlow Voices in the measure
  31. public vfVoices: { [voiceID: number]: Vex.Flow.Voice; } = {};
  32. // Call this function (if present) to x-format all the voices in the measure
  33. public formatVoices: (width: number) => void;
  34. // The VexFlow Ties in the measure
  35. public vfTies: Vex.Flow.StaveTie[] = [];
  36. // The repetition instructions given as words or symbols (coda, dal segno..)
  37. public vfRepetitionWords: Vex.Flow.Repetition[] = [];
  38. // The VexFlow Stave (= one measure in a staffline)
  39. private stave: Vex.Flow.Stave;
  40. // VexFlow StaveConnectors (vertical lines)
  41. private connectors: Vex.Flow.StaveConnector[] = [];
  42. // Intermediate object to construct beams
  43. private beams: { [voiceID: number]: [Beam, VexFlowStaffEntry[]][]; } = {};
  44. // VexFlow Beams
  45. private vfbeams: { [voiceID: number]: Vex.Flow.Beam[]; };
  46. // Intermediate object to construct tuplets
  47. private tuplets: { [voiceID: number]: [Tuplet, VexFlowStaffEntry[]][]; } = {};
  48. // VexFlow Tuplets
  49. private vftuplets: { [voiceID: number]: Vex.Flow.Tuplet[]; } = {};
  50. // Sets the absolute coordinates of the VFStave on the canvas
  51. public setAbsoluteCoordinates(x: number, y: number): void {
  52. this.stave.setX(x).setY(y);
  53. }
  54. /**
  55. * Reset all the geometric values and parameters of this measure and put it in an initialized state.
  56. * This is needed to evaluate a measure a second time by system builder.
  57. */
  58. public resetLayout(): void {
  59. // Take into account some space for the begin and end lines of the stave
  60. // Will be changed when repetitions will be implemented
  61. //this.beginInstructionsWidth = 20 / UnitInPixels;
  62. //this.endInstructionsWidth = 20 / UnitInPixels;
  63. this.stave = new Vex.Flow.Stave(0, 0, 0, {
  64. space_above_staff_ln: 0,
  65. space_below_staff_ln: 0,
  66. });
  67. this.updateInstructionWidth();
  68. }
  69. public clean(): void {
  70. this.vfTies.length = 0;
  71. this.connectors = [];
  72. // Clean up instructions
  73. this.resetLayout();
  74. }
  75. /**
  76. * returns the x-width (in units) of a given measure line {SystemLinesEnum}.
  77. * @param line
  78. * @returns the x-width in osmd units
  79. */
  80. public getLineWidth(line: SystemLinesEnum): number {
  81. switch (line) {
  82. // return 0 for the normal lines, as the line width will be considered at the updateInstructionWidth() method using the stavemodifiers.
  83. // case SystemLinesEnum.SingleThin:
  84. // return 5.0 / unitInPixels;
  85. // case SystemLinesEnum.DoubleThin:
  86. // return 5.0 / unitInPixels;
  87. // case SystemLinesEnum.ThinBold:
  88. // return 5.0 / unitInPixels;
  89. // but just add a little extra space for repetitions (cosmetics):
  90. case SystemLinesEnum.BoldThinDots:
  91. case SystemLinesEnum.DotsThinBold:
  92. return 10.0 / unitInPixels;
  93. case SystemLinesEnum.DotsBoldBoldDots:
  94. return 10.0 / unitInPixels;
  95. default:
  96. return 0;
  97. }
  98. }
  99. /**
  100. * adds the given clef to the begin of the measure.
  101. * This has to update/increase BeginInstructionsWidth.
  102. * @param clef
  103. */
  104. public addClefAtBegin(clef: ClefInstruction): void {
  105. this.octaveOffset = clef.OctaveOffset;
  106. const vfclef: { type: string, size: string, annotation: string } = VexFlowConverter.Clef(clef, "default");
  107. this.stave.addClef(vfclef.type, vfclef.size, vfclef.annotation, Vex.Flow.Modifier.Position.BEGIN);
  108. this.updateInstructionWidth();
  109. }
  110. /**
  111. * adds the given key to the begin of the measure.
  112. * This has to update/increase BeginInstructionsWidth.
  113. * @param currentKey the new valid key.
  114. * @param previousKey the old cancelled key. Needed to show which accidentals are not valid any more.
  115. * @param currentClef the valid clef. Needed to put the accidentals on the right y-positions.
  116. */
  117. public addKeyAtBegin(currentKey: KeyInstruction, previousKey: KeyInstruction, currentClef: ClefInstruction): void {
  118. this.stave.setKeySignature(
  119. VexFlowConverter.keySignature(currentKey),
  120. VexFlowConverter.keySignature(previousKey),
  121. undefined
  122. );
  123. this.updateInstructionWidth();
  124. }
  125. /**
  126. * adds the given rhythm to the begin of the measure.
  127. * This has to update/increase BeginInstructionsWidth.
  128. * @param rhythm
  129. */
  130. public addRhythmAtBegin(rhythm: RhythmInstruction): void {
  131. const timeSig: Vex.Flow.TimeSignature = VexFlowConverter.TimeSignature(rhythm);
  132. this.stave.addModifier(
  133. timeSig,
  134. Vex.Flow.Modifier.Position.BEGIN
  135. );
  136. this.updateInstructionWidth();
  137. }
  138. /**
  139. * adds the given clef to the end of the measure.
  140. * This has to update/increase EndInstructionsWidth.
  141. * @param clef
  142. */
  143. public addClefAtEnd(clef: ClefInstruction): void {
  144. const vfclef: { type: string, size: string, annotation: string } = VexFlowConverter.Clef(clef, "small");
  145. this.stave.setEndClef(vfclef.type, vfclef.size, vfclef.annotation);
  146. this.updateInstructionWidth();
  147. }
  148. public addMeasureLine(lineType: SystemLinesEnum, linePosition: SystemLinePosition): void {
  149. switch (linePosition) {
  150. case SystemLinePosition.MeasureBegin:
  151. switch (lineType) {
  152. case SystemLinesEnum.BoldThinDots:
  153. this.stave.setBegBarType(VexFlowBarlineType.REPEAT_BEGIN);
  154. break;
  155. default:
  156. break;
  157. }
  158. break;
  159. case SystemLinePosition.MeasureEnd:
  160. switch (lineType) {
  161. case SystemLinesEnum.DotsBoldBoldDots:
  162. this.stave.setEndBarType(VexFlowBarlineType.REPEAT_BOTH);
  163. break;
  164. case SystemLinesEnum.DotsThinBold:
  165. this.stave.setEndBarType(VexFlowBarlineType.REPEAT_END);
  166. break;
  167. case SystemLinesEnum.DoubleThin:
  168. this.stave.setEndBarType(VexFlowBarlineType.DOUBLE);
  169. break;
  170. case SystemLinesEnum.ThinBold:
  171. this.stave.setEndBarType(VexFlowBarlineType.END);
  172. break;
  173. default:
  174. break;
  175. }
  176. break;
  177. default:
  178. break;
  179. }
  180. }
  181. public addWordRepetition(repetitionInstruction: RepetitionInstructionEnum): void {
  182. let instruction: VexFlowRepetitionType = undefined;
  183. let position: any = Vex.Flow.Modifier.Position.END;
  184. switch (repetitionInstruction) {
  185. case RepetitionInstructionEnum.Segno:
  186. // create Segno Symbol:
  187. instruction = VexFlowRepetitionType.SEGNO_LEFT;
  188. position = Vex.Flow.Modifier.Position.BEGIN;
  189. break;
  190. case RepetitionInstructionEnum.Coda:
  191. // create Coda Symbol:
  192. instruction = VexFlowRepetitionType.CODA_LEFT;
  193. position = Vex.Flow.Modifier.Position.BEGIN;
  194. break;
  195. case RepetitionInstructionEnum.DaCapo:
  196. instruction = VexFlowRepetitionType.DC;
  197. break;
  198. case RepetitionInstructionEnum.DalSegno:
  199. instruction = VexFlowRepetitionType.DS;
  200. break;
  201. case RepetitionInstructionEnum.Fine:
  202. instruction = VexFlowRepetitionType.FINE;
  203. break;
  204. case RepetitionInstructionEnum.ToCoda:
  205. //instruction = "To Coda";
  206. break;
  207. case RepetitionInstructionEnum.DaCapoAlFine:
  208. instruction = VexFlowRepetitionType.DC_AL_FINE;
  209. break;
  210. case RepetitionInstructionEnum.DaCapoAlCoda:
  211. instruction = VexFlowRepetitionType.DC_AL_CODA;
  212. break;
  213. case RepetitionInstructionEnum.DalSegnoAlFine:
  214. instruction = VexFlowRepetitionType.DS_AL_FINE;
  215. break;
  216. case RepetitionInstructionEnum.DalSegnoAlCoda:
  217. instruction = VexFlowRepetitionType.DS_AL_CODA;
  218. break;
  219. default:
  220. break;
  221. }
  222. if (instruction !== undefined) {
  223. this.stave.addModifier(new Vex.Flow.Repetition(instruction, 0, 0), position);
  224. }
  225. }
  226. /**
  227. * Sets the overall x-width of the measure.
  228. * @param width
  229. */
  230. public setWidth(width: number): void {
  231. super.setWidth(width);
  232. // Set the width of the Vex.Flow.Stave
  233. this.stave.setWidth(width * unitInPixels);
  234. // Force the width of the Begin Instructions
  235. //this.stave.setNoteStartX(this.beginInstructionsWidth * UnitInPixels);
  236. }
  237. /**
  238. * This method is called after the StaffEntriesScaleFactor has been set.
  239. * Here the final x-positions of the staff entries have to be set.
  240. * (multiply the minimal positions with the scaling factor, considering the BeginInstructionsWidth)
  241. */
  242. public layoutSymbols(): void {
  243. //this.stave.format();
  244. }
  245. //public addGraphicalStaffEntry(entry: VexFlowStaffEntry): void {
  246. // super.addGraphicalStaffEntry(entry);
  247. //}
  248. //
  249. //public addGraphicalStaffEntryAtTimestamp(entry: VexFlowStaffEntry): void {
  250. // super.addGraphicalStaffEntryAtTimestamp(entry);
  251. // // TODO
  252. //}
  253. /**
  254. * Draw this measure on a VexFlow CanvasContext
  255. * @param ctx
  256. */
  257. public draw(ctx: Vex.Flow.RenderContext): void {
  258. // Draw stave lines
  259. this.stave.setContext(ctx).draw();
  260. // Draw all voices
  261. for (const voiceID in this.vfVoices) {
  262. if (this.vfVoices.hasOwnProperty(voiceID)) {
  263. this.vfVoices[voiceID].draw(ctx, this.stave);
  264. }
  265. }
  266. // Draw beams
  267. for (const voiceID in this.vfbeams) {
  268. if (this.vfbeams.hasOwnProperty(voiceID)) {
  269. for (const beam of this.vfbeams[voiceID]) {
  270. beam.setContext(ctx).draw();
  271. }
  272. }
  273. }
  274. // Draw tuplets
  275. for (const voiceID in this.vftuplets) {
  276. if (this.vftuplets.hasOwnProperty(voiceID)) {
  277. for (const tuplet of this.vftuplets[voiceID]) {
  278. tuplet.setContext(ctx).draw();
  279. }
  280. }
  281. }
  282. // Draw ties
  283. for (const tie of this.vfTies) {
  284. tie.setContext(ctx).draw();
  285. }
  286. // Draw vertical lines
  287. for (const connector of this.connectors) {
  288. connector.setContext(ctx).draw();
  289. }
  290. }
  291. public format(): void {
  292. // If this is the first stave in the vertical measure, call the format
  293. // method to set the width of all the voices
  294. if (this.formatVoices) {
  295. // The width of the voices does not include the instructions (StaveModifiers)
  296. this.formatVoices((this.PositionAndShape.BorderRight - this.beginInstructionsWidth - this.endInstructionsWidth) * unitInPixels);
  297. }
  298. // Force the width of the Begin Instructions
  299. this.stave.setNoteStartX(this.stave.getX() + unitInPixels * this.beginInstructionsWidth);
  300. }
  301. /**
  302. * Add a note to a beam
  303. * @param graphicalNote
  304. * @param beam
  305. */
  306. public handleBeam(graphicalNote: GraphicalNote, beam: Beam): void {
  307. const voiceID: number = graphicalNote.sourceNote.ParentVoiceEntry.ParentVoice.VoiceId;
  308. let beams: [Beam, VexFlowStaffEntry[]][] = this.beams[voiceID];
  309. if (beams === undefined) {
  310. beams = this.beams[voiceID] = [];
  311. }
  312. let data: [Beam, VexFlowStaffEntry[]];
  313. for (const mybeam of beams) {
  314. if (mybeam[0] === beam) {
  315. data = mybeam;
  316. }
  317. }
  318. if (data === undefined) {
  319. data = [beam, []];
  320. beams.push(data);
  321. }
  322. const parent: VexFlowStaffEntry = graphicalNote.parentStaffEntry as VexFlowStaffEntry;
  323. if (data[1].indexOf(parent) < 0) {
  324. data[1].push(parent);
  325. }
  326. }
  327. public handleTuplet(graphicalNote: GraphicalNote, tuplet: Tuplet): void {
  328. const voiceID: number = graphicalNote.sourceNote.ParentVoiceEntry.ParentVoice.VoiceId;
  329. tuplet = graphicalNote.sourceNote.NoteTuplet;
  330. let tuplets: [Tuplet, VexFlowStaffEntry[]][] = this.tuplets[voiceID];
  331. if (tuplets === undefined) {
  332. tuplets = this.tuplets[voiceID] = [];
  333. }
  334. let currentTupletBuilder: [Tuplet, VexFlowStaffEntry[]];
  335. for (const t of tuplets) {
  336. if (t[0] === tuplet) {
  337. currentTupletBuilder = t;
  338. }
  339. }
  340. if (currentTupletBuilder === undefined) {
  341. currentTupletBuilder = [tuplet, []];
  342. tuplets.push(currentTupletBuilder);
  343. }
  344. const parent: VexFlowStaffEntry = graphicalNote.parentStaffEntry as VexFlowStaffEntry;
  345. if (currentTupletBuilder[1].indexOf(parent) < 0) {
  346. currentTupletBuilder[1].push(parent);
  347. }
  348. }
  349. /**
  350. * Complete the creation of VexFlow Beams in this measure
  351. */
  352. public finalizeBeams(): void {
  353. // The following line resets the created Vex.Flow Beams and
  354. // created them brand new. Is this needed? And more importantly,
  355. // should the old beams be removed manually by the notes?
  356. this.vfbeams = {};
  357. for (const voiceID in this.beams) {
  358. if (this.beams.hasOwnProperty(voiceID)) {
  359. let vfbeams: Vex.Flow.Beam[] = this.vfbeams[voiceID];
  360. if (vfbeams === undefined) {
  361. vfbeams = this.vfbeams[voiceID] = [];
  362. }
  363. for (const beam of this.beams[voiceID]) {
  364. const notes: Vex.Flow.StaveNote[] = [];
  365. const staffEntries: VexFlowStaffEntry[] = beam[1];
  366. const autoStemBeam: boolean = staffEntries[0].graphicalNotes[voiceID][0].sourceNote.ParentVoiceEntry.stemDirection === undefined;
  367. for (const entry of staffEntries) {
  368. const note: Vex.Flow.StaveNote = (<VexFlowStaffEntry>entry).vfNotes[voiceID];
  369. if (note !== undefined) {
  370. notes.push(note);
  371. }
  372. }
  373. if (notes.length > 1) {
  374. const vfBeam: Vex.Flow.Beam = new Vex.Flow.Beam(notes, autoStemBeam);
  375. vfbeams.push(vfBeam);
  376. // just a test for coloring the notes:
  377. // for (let note of notes) {
  378. // (<Vex.Flow.StaveNote> note).setStyle({fillStyle: "green", strokeStyle: "green"});
  379. // }
  380. } else {
  381. Logging.log("Warning! Beam with no notes!");
  382. }
  383. }
  384. }
  385. }
  386. }
  387. /**
  388. * Complete the creation of VexFlow Tuplets in this measure
  389. */
  390. public finalizeTuplets(): void {
  391. // The following line resets the created Vex.Flow Tuplets and
  392. // created them brand new. Is this needed? And more importantly,
  393. // should the old tuplets be removed manually from the notes?
  394. this.vftuplets = {};
  395. for (const voiceID in this.tuplets) {
  396. if (this.tuplets.hasOwnProperty(voiceID)) {
  397. let vftuplets: Vex.Flow.Tuplet[] = this.vftuplets[voiceID];
  398. if (vftuplets === undefined) {
  399. vftuplets = this.vftuplets[voiceID] = [];
  400. }
  401. for (const tupletBuilder of this.tuplets[voiceID]) {
  402. const tupletStaveNotes: Vex.Flow.StaveNote[] = [];
  403. const tupletStaffEntries: VexFlowStaffEntry[] = tupletBuilder[1];
  404. for (const tupletStaffEntry of tupletStaffEntries) {
  405. tupletStaveNotes.push((tupletStaffEntry).vfNotes[voiceID]);
  406. }
  407. if (tupletStaveNotes.length > 1) {
  408. const notesOccupied: number = 2;
  409. vftuplets.push(new Vex.Flow.Tuplet( tupletStaveNotes,
  410. {
  411. notes_occupied: notesOccupied,
  412. num_notes: tupletStaveNotes.length //, location: -1, ratioed: true
  413. }));
  414. } else {
  415. Logging.log("Warning! Tuplet with no notes! Trying to ignore, but this is a serious problem.");
  416. }
  417. }
  418. }
  419. }
  420. }
  421. public layoutStaffEntry(graphicalStaffEntry: GraphicalStaffEntry): void {
  422. return;
  423. }
  424. public staffMeasureCreatedCalculations(): void {
  425. for (let idx: number = 0, len: number = this.staffEntries.length; idx < len; ++idx) {
  426. const graphicalStaffEntry: VexFlowStaffEntry = (this.staffEntries[idx] as VexFlowStaffEntry);
  427. // create vex flow Notes:
  428. const gnotes: { [voiceID: number]: GraphicalNote[]; } = graphicalStaffEntry.graphicalNotes;
  429. for (const voiceID in gnotes) {
  430. if (gnotes.hasOwnProperty(voiceID)) {
  431. const vfnote: StaveNote = VexFlowConverter.StaveNote(gnotes[voiceID]);
  432. (graphicalStaffEntry as VexFlowStaffEntry).vfNotes[voiceID] = vfnote;
  433. }
  434. }
  435. }
  436. this.finalizeBeams();
  437. this.finalizeTuplets();
  438. for (let idx: number = 0, len: number = this.staffEntries.length; idx < len; ++idx) {
  439. const graphicalStaffEntry: VexFlowStaffEntry = (this.staffEntries[idx] as VexFlowStaffEntry);
  440. const gnotes: { [voiceID: number]: GraphicalNote[]; } = graphicalStaffEntry.graphicalNotes;
  441. // create vex flow voices and add tickables to it:
  442. const vfVoices: { [voiceID: number]: Vex.Flow.Voice; } = this.vfVoices;
  443. for (const voiceID in gnotes) {
  444. if (gnotes.hasOwnProperty(voiceID)) {
  445. if (!(voiceID in vfVoices)) {
  446. vfVoices[voiceID] = new Vex.Flow.Voice({
  447. beat_value: this.parentSourceMeasure.Duration.Denominator,
  448. num_beats: this.parentSourceMeasure.Duration.Numerator,
  449. resolution: Vex.Flow.RESOLUTION,
  450. }).setMode(Vex.Flow.Voice.Mode.SOFT);
  451. }
  452. vfVoices[voiceID].addTickable(graphicalStaffEntry.vfNotes[voiceID]);
  453. }
  454. }
  455. }
  456. }
  457. /**
  458. * Creates a line from 'top' to this measure, of type 'lineType'
  459. * @param top
  460. * @param lineType
  461. */
  462. public lineTo(top: VexFlowMeasure, lineType: any): void {
  463. const connector: StaveConnector = new Vex.Flow.StaveConnector(top.getVFStave(), this.stave);
  464. connector.setType(lineType);
  465. this.connectors.push(connector);
  466. }
  467. /**
  468. * Return the VexFlow Stave corresponding to this StaffMeasure
  469. * @returns {Vex.Flow.Stave}
  470. */
  471. public getVFStave(): Vex.Flow.Stave {
  472. return this.stave;
  473. }
  474. /**
  475. * After re-running the formatting on the VexFlow Stave, update the
  476. * space needed by Instructions (in VexFlow: StaveModifiers)
  477. */
  478. private updateInstructionWidth(): void {
  479. let beginInstructionsWidth: number = 0;
  480. let endInstructionsWidth: number = 0;
  481. const modifiers: Vex.Flow.StaveModifier[] = this.stave.getModifiers();
  482. for (const mod of modifiers) {
  483. if (mod.getPosition() === Vex.Flow.StaveModifier.Position.BEGIN) {
  484. beginInstructionsWidth += mod.getWidth() + mod.getPadding(undefined);
  485. } else if (mod.getPosition() === Vex.Flow.StaveModifier.Position.END) {
  486. endInstructionsWidth += mod.getWidth() + mod.getPadding(undefined);
  487. }
  488. }
  489. this.beginInstructionsWidth = beginInstructionsWidth / unitInPixels;
  490. this.endInstructionsWidth = endInstructionsWidth / unitInPixels;
  491. //this.beginInstructionsWidth = (this.stave.getNoteStartX() - this.stave.getX()) / unitInPixels;
  492. //this.endInstructionsWidth = (this.stave.getX() + this.stave.getWidth() - this.stave.getNoteEndX()) / unitInPixels;
  493. }
  494. }