VexFlowConverter.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. import Vex = require("vexflow");
  2. import {ClefEnum} from "../../VoiceData/Instructions/ClefInstruction";
  3. import {ClefInstruction} from "../../VoiceData/Instructions/ClefInstruction";
  4. import {Pitch} from "../../../Common/DataObjects/Pitch";
  5. import {Fraction} from "../../../Common/DataObjects/Fraction";
  6. import {RhythmInstruction} from "../../VoiceData/Instructions/RhythmInstruction";
  7. import {RhythmSymbolEnum} from "../../VoiceData/Instructions/RhythmInstruction";
  8. import {KeyInstruction} from "../../VoiceData/Instructions/KeyInstruction";
  9. import {KeyEnum} from "../../VoiceData/Instructions/KeyInstruction";
  10. import {AccidentalEnum} from "../../../Common/DataObjects/Pitch";
  11. import {NoteEnum} from "../../../Common/DataObjects/Pitch";
  12. import {VexFlowGraphicalNote} from "./VexFlowGraphicalNote";
  13. import {GraphicalNote} from "../GraphicalNote";
  14. import {SystemLinesEnum} from "../SystemLinesEnum";
  15. import {FontStyles} from "../../../Common/Enums/FontStyles";
  16. import {Fonts} from "../../../Common/Enums/Fonts";
  17. import {OutlineAndFillStyleEnum, OUTLINE_AND_FILL_STYLE_DICT} from "../DrawingEnums";
  18. import * as log from "loglevel";
  19. import { ArticulationEnum, StemDirectionType } from "../../VoiceData/VoiceEntry";
  20. import { SystemLinePosition } from "../SystemLinePosition";
  21. import { GraphicalVoiceEntry } from "../GraphicalVoiceEntry";
  22. import { OrnamentEnum, OrnamentContainer } from "../../VoiceData/OrnamentContainer";
  23. import { Notehead, NoteHeadShape } from "../../VoiceData/Notehead";
  24. import { unitInPixels } from "./VexFlowMusicSheetDrawer";
  25. import { EngravingRules } from "../EngravingRules";
  26. import { Note } from "../..";
  27. import StaveNote = Vex.Flow.StaveNote;
  28. import { ArpeggioType } from "../../VoiceData";
  29. import { TabNote } from "../../VoiceData/TabNote";
  30. /**
  31. * Helper class, which contains static methods which actually convert
  32. * from OSMD objects to VexFlow objects.
  33. */
  34. export class VexFlowConverter {
  35. /**
  36. * Mapping from numbers of alterations on the key signature to major keys
  37. * @type {[alterationsNo: number]: string; }
  38. */
  39. private static majorMap: {[_: number]: string; } = {
  40. "-1": "F", "-2": "Bb", "-3": "Eb", "-4": "Ab", "-5": "Db", "-6": "Gb", "-7": "Cb", "-8": "Fb",
  41. "0": "C", "1": "G", "2": "D", "3": "A", "4": "E", "5": "B", "6": "F#", "7": "C#", "8": "G#"
  42. };
  43. /**
  44. * Mapping from numbers of alterations on the key signature to minor keys
  45. * @type {[alterationsNo: number]: string; }
  46. */
  47. private static minorMap: {[_: number]: string; } = {
  48. "-1": "D", "-2": "G", "-3": "C", "-4": "F", "-5": "Bb", "-6": "Eb", "-7": "Ab", "-8": "Db",
  49. "0": "A", "1": "E", "2": "B", "3": "F#", "4": "C#", "5": "G#", "6": "D#", "7": "A#", "8": "E#"
  50. };
  51. /**
  52. * Convert a fraction to a string which represents a duration in VexFlow
  53. * @param fraction a fraction representing the duration of a note
  54. * @returns {string}
  55. */
  56. public static duration(fraction: Fraction, isTuplet: boolean): string {
  57. const dur: number = fraction.RealValue;
  58. if (dur >= 1) {
  59. return "w";
  60. } else if (dur < 1 && dur >= 0.5) {
  61. // change to the next higher straight note to get the correct note display type
  62. if (isTuplet) {
  63. return "w";
  64. }
  65. return "h";
  66. } else if (dur < 0.5 && dur >= 0.25) {
  67. // change to the next higher straight note to get the correct note display type
  68. if (isTuplet && dur > 0.25) {
  69. return "h";
  70. }
  71. return "q";
  72. } else if (dur < 0.25 && dur >= 0.125) {
  73. // change to the next higher straight note to get the correct note display type
  74. if (isTuplet && dur > 0.125) {
  75. return "q";
  76. }
  77. return "8";
  78. } else if (dur < 0.125 && dur >= 0.0625) {
  79. // change to the next higher straight note to get the correct note display type
  80. if (isTuplet && dur > 0.0625) {
  81. return "8";
  82. }
  83. return "16";
  84. } else if (dur < 0.0625 && dur >= 0.03125) {
  85. // change to the next higher straight note to get the correct note display type
  86. if (isTuplet && dur > 0.03125) {
  87. return "16";
  88. }
  89. return "32";
  90. } else if (dur < 0.03125 && dur >= 0.015625) {
  91. // change to the next higher straight note to get the correct note display type
  92. if (isTuplet && dur > 0.015625) {
  93. return "32";
  94. }
  95. return "64";
  96. }
  97. if (isTuplet) {
  98. return "64";
  99. }
  100. return "128";
  101. }
  102. /**
  103. * Takes a Pitch and returns a string representing a VexFlow pitch,
  104. * which has the form "b/4", plus its alteration (accidental)
  105. * @param pitch
  106. * @returns {string[]}
  107. */
  108. public static pitch(note: VexFlowGraphicalNote, pitch: Pitch): [string, string, ClefInstruction] {
  109. const fund: string = NoteEnum[pitch.FundamentalNote].toLowerCase();
  110. const acc: string = Pitch.accidentalVexflow(pitch.Accidental);
  111. // The octave seems to need a shift of three FIXME?
  112. const octave: number = pitch.Octave - note.Clef().OctaveOffset + 3;
  113. const notehead: Notehead = note.sourceNote.Notehead;
  114. let noteheadCode: string = "";
  115. if (notehead !== undefined) {
  116. noteheadCode = this.NoteHeadCode(notehead);
  117. }
  118. return [fund + "n/" + octave + noteheadCode, acc, note.Clef()];
  119. }
  120. /** returns the Vexflow code for a note head. Some are still unsupported, see Vexflow/tables.js */
  121. public static NoteHeadCode(notehead: Notehead): string {
  122. const codeStart: string = "/";
  123. const codeFilled: string = notehead.Filled ? "2" : "1"; // filled/unfilled notehead code in most vexflow glyphs
  124. switch (notehead.Shape) {
  125. case NoteHeadShape.NORMAL:
  126. return "";
  127. case NoteHeadShape.DIAMOND:
  128. return codeStart + "D" + codeFilled;
  129. case NoteHeadShape.TRIANGLE:
  130. return codeStart + "T" + codeFilled;
  131. case NoteHeadShape.X:
  132. return codeStart + "X" + codeFilled;
  133. case NoteHeadShape.CIRCLEX:
  134. return codeStart + "X3";
  135. case NoteHeadShape.RECTANGLE:
  136. return codeStart + "R" + codeFilled;
  137. case NoteHeadShape.SQUARE:
  138. return codeStart + "S" + codeFilled;
  139. case NoteHeadShape.SLASH:
  140. return ""; // slash is specified at end of duration string in Vexflow
  141. default:
  142. return "";
  143. }
  144. }
  145. public static GhostNote(frac: Fraction): Vex.Flow.GhostNote {
  146. return new Vex.Flow.GhostNote({
  147. duration: VexFlowConverter.duration(frac, false),
  148. });
  149. }
  150. /**
  151. * Convert a GraphicalVoiceEntry to a VexFlow StaveNote
  152. * @param gve the GraphicalVoiceEntry which can hold a note or a chord on the staff belonging to one voice
  153. * @returns {Vex.Flow.StaveNote}
  154. */
  155. public static StaveNote(gve: GraphicalVoiceEntry): Vex.Flow.StaveNote {
  156. // sort notes
  157. /* seems unnecessary for now
  158. if (gve.octaveShiftValue !== undefined && gve.octaveShiftValue !== OctaveEnum.NONE) {
  159. gve.sort(); // gves with accidentals in octave shift brackets can be unsorted
  160. } */
  161. // VexFlow needs the notes ordered vertically in the other direction:
  162. const notes: GraphicalNote[] = gve.notes.reverse();
  163. const baseNote: GraphicalNote = notes[0];
  164. let keys: string[] = [];
  165. const accidentals: string[] = [];
  166. const frac: Fraction = baseNote.graphicalNoteLength;
  167. const isTuplet: boolean = baseNote.sourceNote.NoteTuplet !== undefined;
  168. let duration: string = VexFlowConverter.duration(frac, isTuplet);
  169. if (baseNote.sourceNote.TypeLength !== undefined && baseNote.sourceNote.TypeLength !== frac) {
  170. duration = VexFlowConverter.duration(baseNote.sourceNote.TypeLength, isTuplet);
  171. }
  172. let vfClefType: string = undefined;
  173. let numDots: number = baseNote.numberOfDots;
  174. let alignCenter: boolean = false;
  175. let xShift: number = 0;
  176. let slashNoteHead: boolean = false;
  177. let isRest: boolean = false;
  178. for (const note of notes) {
  179. if (numDots < note.numberOfDots) {
  180. numDots = note.numberOfDots;
  181. }
  182. // if it is a rest:
  183. if (note.sourceNote.isRest()) {
  184. isRest = true;
  185. keys = ["b/4"];
  186. // TODO do collision checking, place rest e.g. either below staff (A3, for stem direction below voice) or above (C5)
  187. // if it is a full measure rest:
  188. if (note.parentVoiceEntry.parentStaffEntry.parentMeasure.parentSourceMeasure.Duration.RealValue <= frac.RealValue) {
  189. keys = ["d/5"];
  190. duration = "w";
  191. numDots = 0;
  192. // If it's a whole rest we want it smack in the middle. Apparently there is still an issue in vexflow:
  193. // https://github.com/0xfe/vexflow/issues/579 The author reports that he needs to add some negative x shift
  194. // if the measure has no modifiers.
  195. alignCenter = true;
  196. xShift = EngravingRules.Rules.WholeRestXShiftVexflow * unitInPixels; // TODO find way to make dependent on the modifiers
  197. // affects VexFlowStaffEntry.calculateXPosition()
  198. }
  199. break;
  200. }
  201. if (note.sourceNote.Notehead) {
  202. if (note.sourceNote.Notehead.Shape === NoteHeadShape.SLASH) {
  203. slashNoteHead = true;
  204. // if we have slash heads and other heads in the voice entry, this will create the same head for all.
  205. // same problem with numDots. The slash case should be extremely rare though.
  206. }
  207. }
  208. const pitch: [string, string, ClefInstruction] = (note as VexFlowGraphicalNote).vfpitch;
  209. keys.push(pitch[0]);
  210. accidentals.push(pitch[1]);
  211. if (!vfClefType) {
  212. const vfClef: {type: string, annotation: string} = VexFlowConverter.Clef(pitch[2]);
  213. vfClefType = vfClef.type;
  214. }
  215. }
  216. for (let i: number = 0, len: number = numDots; i < len; ++i) {
  217. duration += "d";
  218. }
  219. if (slashNoteHead) {
  220. duration += "s"; // we have to specify a slash note head like this in Vexflow
  221. }
  222. if (isRest) {
  223. // "r" has to be put after the "d"s for rest notes.
  224. duration += "r";
  225. }
  226. let vfnote: Vex.Flow.StaveNote;
  227. const vfnoteStruct: any = {
  228. align_center: alignCenter,
  229. auto_stem: true,
  230. clef: vfClefType,
  231. duration: duration,
  232. keys: keys,
  233. slash: gve.parentVoiceEntry.GraceNoteSlash,
  234. };
  235. const firstNote: Note = gve.notes[0].sourceNote;
  236. if (firstNote.IsCueNote) {
  237. vfnoteStruct.glyph_font_scale = Vex.Flow.DEFAULT_NOTATION_FONT_SCALE * Vex.Flow.GraceNote.SCALE;
  238. vfnoteStruct.stroke_px = Vex.Flow.GraceNote.LEDGER_LINE_OFFSET;
  239. }
  240. if (gve.parentVoiceEntry.IsGrace || gve.notes[0].sourceNote.IsCueNote) {
  241. vfnote = new Vex.Flow.GraceNote(vfnoteStruct);
  242. } else {
  243. vfnote = new Vex.Flow.StaveNote(vfnoteStruct);
  244. }
  245. if (EngravingRules.Rules.ColoringEnabled) {
  246. const defaultColorStem: string = EngravingRules.Rules.DefaultColorStem;
  247. let stemColor: string = gve.parentVoiceEntry.StemColor;
  248. if (!stemColor && defaultColorStem) {
  249. stemColor = defaultColorStem;
  250. }
  251. const stemStyle: Object = { fillStyle: stemColor, strokeStyle: stemColor };
  252. if (stemColor) {
  253. gve.parentVoiceEntry.StemColor = stemColor;
  254. vfnote.setStemStyle(stemStyle);
  255. if (vfnote.flag && EngravingRules.Rules.ColorFlags) {
  256. vfnote.setFlagStyle(stemStyle);
  257. }
  258. }
  259. }
  260. vfnote.x_shift = xShift;
  261. if (gve.parentVoiceEntry.IsGrace && gve.notes[0].sourceNote.NoteBeam) {
  262. // Vexflow seems to have issues with wanted stem direction for beamed grace notes,
  263. // when the stem is connected to a beamed main note (e.g. Haydn Concertante bar 57)
  264. gve.parentVoiceEntry.WantedStemDirection = gve.notes[0].sourceNote.NoteBeam.Notes[0].ParentVoiceEntry.WantedStemDirection;
  265. }
  266. if (gve.parentVoiceEntry !== undefined) {
  267. const wantedStemDirection: StemDirectionType = gve.parentVoiceEntry.WantedStemDirection;
  268. switch (wantedStemDirection) {
  269. case(StemDirectionType.Up):
  270. vfnote.setStemDirection(Vex.Flow.Stem.UP);
  271. break;
  272. case (StemDirectionType.Down):
  273. vfnote.setStemDirection(Vex.Flow.Stem.DOWN);
  274. break;
  275. default:
  276. }
  277. }
  278. // add accidentals
  279. for (let i: number = 0, len: number = notes.length; i < len; i += 1) {
  280. (notes[i] as VexFlowGraphicalNote).setIndex(vfnote, i);
  281. if (accidentals[i]) {
  282. if (accidentals[i] === "++") { // triple sharp
  283. vfnote.addAccidental(i, new Vex.Flow.Accidental("##"));
  284. vfnote.addAccidental(i, new Vex.Flow.Accidental("#"));
  285. continue;
  286. } else if (accidentals[i] === "bbs") { // triple flat
  287. vfnote.addAccidental(i, new Vex.Flow.Accidental("bb"));
  288. vfnote.addAccidental(i, new Vex.Flow.Accidental("b"));
  289. continue;
  290. }
  291. vfnote.addAccidental(i, new Vex.Flow.Accidental(accidentals[i])); // normal accidental
  292. }
  293. // add Tremolo strokes (only single note tremolos for now, Vexflow doesn't have beams for two-note tremolos yet)
  294. const tremoloStrokes: number = notes[i].sourceNote.TremoloStrokes;
  295. if (tremoloStrokes > 0) {
  296. vfnote.addModifier(i, new Vex.Flow.Tremolo(tremoloStrokes));
  297. }
  298. }
  299. // half note tremolo: set notehead to half note (Vexflow otherwise takes the notehead from duration) (Hack)
  300. if (firstNote.Length.RealValue === 0.25 && firstNote.Notehead && firstNote.Notehead.Filled === false) {
  301. const keyProps: Object[] = vfnote.getKeyProps();
  302. for (let i: number = 0; i < keyProps.length; i++) {
  303. (<any>keyProps[i]).code = "v81";
  304. }
  305. }
  306. for (let i: number = 0, len: number = numDots; i < len; ++i) {
  307. vfnote.addDotToAll();
  308. }
  309. return vfnote;
  310. }
  311. public static generateArticulations(vfnote: Vex.Flow.StemmableNote, articulations: ArticulationEnum[]): void {
  312. if (vfnote === undefined || vfnote.getAttribute("type") === "GhostNote") {
  313. return;
  314. }
  315. // Articulations:
  316. let vfArtPosition: number = Vex.Flow.Modifier.Position.ABOVE;
  317. if (vfnote.getStemDirection() === Vex.Flow.Stem.UP) {
  318. vfArtPosition = Vex.Flow.Modifier.Position.BELOW;
  319. }
  320. for (const articulation of articulations) {
  321. // tslint:disable-next-line:switch-default
  322. let vfArt: Vex.Flow.Articulation = undefined;
  323. switch (articulation) {
  324. case ArticulationEnum.accent: {
  325. vfArt = new Vex.Flow.Articulation("a>");
  326. break;
  327. }
  328. case ArticulationEnum.downbow: {
  329. vfArt = new Vex.Flow.Articulation("am");
  330. break;
  331. }
  332. case ArticulationEnum.fermata: {
  333. vfArt = new Vex.Flow.Articulation("a@a");
  334. vfArtPosition = Vex.Flow.Modifier.Position.ABOVE;
  335. break;
  336. }
  337. case ArticulationEnum.invertedfermata: {
  338. vfArt = new Vex.Flow.Articulation("a@u");
  339. vfArtPosition = Vex.Flow.Modifier.Position.BELOW;
  340. break;
  341. }
  342. case ArticulationEnum.lefthandpizzicato: {
  343. vfArt = new Vex.Flow.Articulation("a+");
  344. break;
  345. }
  346. case ArticulationEnum.snappizzicato: {
  347. vfArt = new Vex.Flow.Articulation("ao");
  348. break;
  349. }
  350. case ArticulationEnum.staccatissimo: {
  351. vfArt = new Vex.Flow.Articulation("av");
  352. break;
  353. }
  354. case ArticulationEnum.staccato: {
  355. vfArt = new Vex.Flow.Articulation("a.");
  356. break;
  357. }
  358. case ArticulationEnum.tenuto: {
  359. vfArt = new Vex.Flow.Articulation("a-");
  360. break;
  361. }
  362. case ArticulationEnum.upbow: {
  363. vfArt = new Vex.Flow.Articulation("a|");
  364. break;
  365. }
  366. case ArticulationEnum.strongaccent: {
  367. vfArt = new Vex.Flow.Articulation("a^");
  368. break;
  369. }
  370. default: {
  371. break;
  372. }
  373. }
  374. if (vfArt !== undefined) {
  375. vfArt.setPosition(vfArtPosition);
  376. (vfnote as StaveNote).addModifier(0, vfArt);
  377. }
  378. }
  379. }
  380. public static generateOrnaments(vfnote: Vex.Flow.StemmableNote, oContainer: OrnamentContainer): void {
  381. let vfPosition: number = Vex.Flow.Modifier.Position.ABOVE;
  382. if (vfnote.getStemDirection() === Vex.Flow.Stem.UP) {
  383. vfPosition = Vex.Flow.Modifier.Position.BELOW;
  384. }
  385. let vfOrna: Vex.Flow.Ornament = undefined;
  386. switch (oContainer.GetOrnament) {
  387. case OrnamentEnum.DelayedInvertedTurn: {
  388. vfOrna = new Vex.Flow.Ornament("turn_inverted");
  389. vfOrna.setDelayed(true);
  390. break;
  391. }
  392. case OrnamentEnum.DelayedTurn: {
  393. vfOrna = new Vex.Flow.Ornament("turn");
  394. vfOrna.setDelayed(true);
  395. break;
  396. }
  397. case OrnamentEnum.InvertedMordent: {
  398. vfOrna = new Vex.Flow.Ornament("mordent_inverted");
  399. vfOrna.setDelayed(false);
  400. break;
  401. }
  402. case OrnamentEnum.InvertedTurn: {
  403. vfOrna = new Vex.Flow.Ornament("turn_inverted");
  404. vfOrna.setDelayed(false);
  405. break;
  406. }
  407. case OrnamentEnum.Mordent: {
  408. vfOrna = new Vex.Flow.Ornament("mordent");
  409. vfOrna.setDelayed(false);
  410. break;
  411. }
  412. case OrnamentEnum.Trill: {
  413. vfOrna = new Vex.Flow.Ornament("tr");
  414. vfOrna.setDelayed(false);
  415. break;
  416. }
  417. case OrnamentEnum.Turn: {
  418. vfOrna = new Vex.Flow.Ornament("turn");
  419. vfOrna.setDelayed(false);
  420. break;
  421. }
  422. default: {
  423. log.warn("unhandled OrnamentEnum type: " + oContainer.GetOrnament);
  424. return;
  425. }
  426. }
  427. if (vfOrna !== undefined) {
  428. if (oContainer.AccidentalBelow !== AccidentalEnum.NONE) {
  429. vfOrna.setLowerAccidental(Pitch.accidentalVexflow(oContainer.AccidentalBelow));
  430. }
  431. if (oContainer.AccidentalAbove !== AccidentalEnum.NONE) {
  432. vfOrna.setUpperAccidental(Pitch.accidentalVexflow(oContainer.AccidentalAbove));
  433. }
  434. vfOrna.setPosition(vfPosition);
  435. (vfnote as StaveNote).addModifier(0, vfOrna);
  436. }
  437. }
  438. public static StrokeTypeFromArpeggioType(arpeggioType: ArpeggioType): Vex.Flow.Stroke.Type {
  439. switch (arpeggioType) {
  440. case ArpeggioType.ARPEGGIO_DIRECTIONLESS:
  441. return Vex.Flow.Stroke.Type.ARPEGGIO_DIRECTIONLESS;
  442. case ArpeggioType.BRUSH_DOWN:
  443. return Vex.Flow.Stroke.Type.BRUSH_UP; // TODO somehow up and down are mixed up in Vexflow right now
  444. case ArpeggioType.BRUSH_UP:
  445. return Vex.Flow.Stroke.Type.BRUSH_DOWN; // TODO somehow up and down are mixed up in Vexflow right now
  446. case ArpeggioType.RASQUEDO_DOWN:
  447. return Vex.Flow.Stroke.Type.RASQUEDO_UP;
  448. case ArpeggioType.RASQUEDO_UP:
  449. return Vex.Flow.Stroke.Type.RASQUEDO_DOWN;
  450. case ArpeggioType.ROLL_DOWN:
  451. return Vex.Flow.Stroke.Type.ROLL_UP; // TODO somehow up and down are mixed up in Vexflow right now
  452. case ArpeggioType.ROLL_UP:
  453. return Vex.Flow.Stroke.Type.ROLL_DOWN; // TODO somehow up and down are mixed up in Vexflow right now
  454. default:
  455. return Vex.Flow.Stroke.Type.ARPEGGIO_DIRECTIONLESS;
  456. }
  457. }
  458. /**
  459. * Convert a set of GraphicalNotes to a VexFlow StaveNote
  460. * @param notes form a chord on the staff
  461. * @returns {Vex.Flow.StaveNote}
  462. */
  463. public static CreateTabNote(gve: GraphicalVoiceEntry): Vex.Flow.TabNote {
  464. const tabPositions: {str: number, fret: number}[] = [];
  465. const frac: Fraction = gve.notes[0].graphicalNoteLength;
  466. const isTuplet: boolean = gve.notes[0].sourceNote.NoteTuplet !== undefined;
  467. let duration: string = VexFlowConverter.duration(frac, isTuplet);
  468. let numDots: number = 0;
  469. for (const note of gve.notes) {
  470. const tabNote: TabNote = note.sourceNote as TabNote;
  471. const tabPosition: {str: number, fret: number} = {str: tabNote.StringNumber, fret: tabNote.FretNumber};
  472. tabPositions.push(tabPosition);
  473. if (numDots < note.numberOfDots) {
  474. numDots = note.numberOfDots;
  475. }
  476. }
  477. for (let i: number = 0, len: number = numDots; i < len; ++i) {
  478. duration += "d";
  479. }
  480. const vfnote: Vex.Flow.TabNote = new Vex.Flow.TabNote({
  481. duration: duration,
  482. positions: tabPositions,
  483. });
  484. return vfnote;
  485. }
  486. /**
  487. * Convert a ClefInstruction to a string represention of a clef type in VexFlow.
  488. *
  489. * @param clef The OSMD object to be converted representing the clef
  490. * @param size The VexFlow size to be used. Can be `default` or `small`. As soon as
  491. * #118 is done, this parameter will be dispensable.
  492. * @returns A string representation of a VexFlow clef
  493. * @see https://github.com/0xfe/vexflow/blob/master/src/clef.js
  494. * @see https://github.com/0xfe/vexflow/blob/master/tests/clef_tests.js
  495. */
  496. public static Clef(clef: ClefInstruction, size: string = "default"): { type: string, size: string, annotation: string } {
  497. let type: string;
  498. let annotation: string;
  499. // Make sure size is either "default" or "small"
  500. if (size !== "default" && size !== "small") {
  501. log.warn(`Invalid VexFlow clef size "${size}" specified. Using "default".`);
  502. size = "default";
  503. }
  504. /*
  505. * For all of the following conversions, OSMD uses line numbers 1-5 starting from
  506. * the bottom, while VexFlow uses 0-4 starting from the top.
  507. */
  508. switch (clef.ClefType) {
  509. // G Clef
  510. case ClefEnum.G:
  511. switch (clef.Line) {
  512. case 1:
  513. type = "french"; // VexFlow line 4
  514. break;
  515. case 2:
  516. type = "treble"; // VexFlow line 3
  517. break;
  518. default:
  519. type = "treble";
  520. log.error(`Clef ${ClefEnum[clef.ClefType]} on line ${clef.Line} not supported by VexFlow. Using default value "${type}".`);
  521. }
  522. break;
  523. // F Clef
  524. case ClefEnum.F:
  525. switch (clef.Line) {
  526. case 4:
  527. type = "bass"; // VexFlow line 1
  528. break;
  529. case 3:
  530. type = "baritone-f"; // VexFlow line 2
  531. break;
  532. case 5:
  533. type = "subbass"; // VexFlow line 0
  534. break;
  535. default:
  536. type = "bass";
  537. log.error(`Clef ${ClefEnum[clef.ClefType]} on line ${clef.Line} not supported by VexFlow. Using default value "${type}".`);
  538. }
  539. break;
  540. // C Clef
  541. case ClefEnum.C:
  542. switch (clef.Line) {
  543. case 3:
  544. type = "alto"; // VexFlow line 2
  545. break;
  546. case 4:
  547. type = "tenor"; // VexFlow line 1
  548. break;
  549. case 1:
  550. type = "soprano"; // VexFlow line 4
  551. break;
  552. case 2:
  553. type = "mezzo-soprano"; // VexFlow line 3
  554. break;
  555. default:
  556. type = "alto";
  557. log.error(`Clef ${ClefEnum[clef.ClefType]} on line ${clef.Line} not supported by VexFlow. Using default value "${type}".`);
  558. }
  559. break;
  560. // Percussion Clef
  561. case ClefEnum.percussion:
  562. type = "percussion";
  563. break;
  564. // TAB Clef
  565. case ClefEnum.TAB:
  566. // only used currently for creating the notes in the normal stave: There we need a normal treble clef
  567. type = "treble";
  568. break;
  569. default:
  570. }
  571. // annotations in vexflow don't allow bass and 8va. No matter the offset :(
  572. if (clef.OctaveOffset === 1 && type !== "bass" ) {
  573. annotation = "8va";
  574. } else if (clef.OctaveOffset === -1) {
  575. annotation = "8vb";
  576. }
  577. return { type, size, annotation };
  578. }
  579. /**
  580. * Convert a RhythmInstruction to a VexFlow TimeSignature object
  581. * @param rhythm
  582. * @returns {Vex.Flow.TimeSignature}
  583. * @constructor
  584. */
  585. public static TimeSignature(rhythm: RhythmInstruction): Vex.Flow.TimeSignature {
  586. let timeSpec: string;
  587. switch (rhythm.SymbolEnum) {
  588. case RhythmSymbolEnum.NONE:
  589. timeSpec = rhythm.Rhythm.Numerator + "/" + rhythm.Rhythm.Denominator;
  590. break;
  591. case RhythmSymbolEnum.COMMON:
  592. timeSpec = "C";
  593. break;
  594. case RhythmSymbolEnum.CUT:
  595. timeSpec = "C|";
  596. break;
  597. default:
  598. }
  599. return new Vex.Flow.TimeSignature(timeSpec);
  600. }
  601. /**
  602. * Convert a KeyInstruction to a string representing in VexFlow a key
  603. * @param key
  604. * @returns {string}
  605. */
  606. public static keySignature(key: KeyInstruction): string {
  607. if (key === undefined) {
  608. return undefined;
  609. }
  610. let ret: string;
  611. switch (key.Mode) {
  612. case KeyEnum.minor:
  613. ret = VexFlowConverter.minorMap[key.Key] + "m";
  614. break;
  615. case KeyEnum.major:
  616. ret = VexFlowConverter.majorMap[key.Key];
  617. break;
  618. // some XMLs don't have the mode set despite having a key signature.
  619. case KeyEnum.none:
  620. ret = VexFlowConverter.majorMap[key.Key];
  621. break;
  622. default:
  623. ret = "C";
  624. }
  625. return ret;
  626. }
  627. /**
  628. * Converts a lineType to a VexFlow StaveConnector type
  629. * @param lineType
  630. * @returns {any}
  631. */
  632. public static line(lineType: SystemLinesEnum, linePosition: SystemLinePosition): any {
  633. switch (lineType) {
  634. case SystemLinesEnum.SingleThin:
  635. if (linePosition === SystemLinePosition.MeasureBegin) {
  636. return Vex.Flow.StaveConnector.type.SINGLE;
  637. }
  638. return Vex.Flow.StaveConnector.type.SINGLE_RIGHT;
  639. case SystemLinesEnum.DoubleThin:
  640. return Vex.Flow.StaveConnector.type.DOUBLE;
  641. case SystemLinesEnum.ThinBold:
  642. return Vex.Flow.StaveConnector.type.BOLD_DOUBLE_RIGHT;
  643. case SystemLinesEnum.BoldThinDots:
  644. return Vex.Flow.StaveConnector.type.BOLD_DOUBLE_LEFT;
  645. case SystemLinesEnum.DotsThinBold:
  646. return Vex.Flow.StaveConnector.type.BOLD_DOUBLE_RIGHT;
  647. case SystemLinesEnum.DotsBoldBoldDots:
  648. return Vex.Flow.StaveConnector.type.BOLD_DOUBLE_RIGHT;
  649. case SystemLinesEnum.None:
  650. return Vex.Flow.StaveConnector.type.NONE;
  651. default:
  652. }
  653. }
  654. /**
  655. * Construct a string which can be used in a CSS font property
  656. * @param fontSize
  657. * @param fontStyle
  658. * @param font
  659. * @returns {string}
  660. */
  661. public static font(fontSize: number, fontStyle: FontStyles = FontStyles.Regular, font: Fonts = Fonts.TimesNewRoman): string {
  662. let style: string = "normal";
  663. let weight: string = "normal";
  664. const family: string = "'" + EngravingRules.Rules.DefaultFontFamily + "'"; // default "'Times New Roman'"
  665. switch (fontStyle) {
  666. case FontStyles.Bold:
  667. weight = "bold";
  668. break;
  669. case FontStyles.Italic:
  670. style = "italic";
  671. break;
  672. case FontStyles.BoldItalic:
  673. style = "italic";
  674. weight = "bold";
  675. break;
  676. case FontStyles.Underlined:
  677. // TODO
  678. break;
  679. default:
  680. break;
  681. }
  682. switch (font) { // currently not used
  683. case Fonts.Kokila:
  684. // TODO Not Supported
  685. break;
  686. default:
  687. }
  688. return style + " " + weight + " " + Math.floor(fontSize) + "px " + family;
  689. }
  690. /**
  691. * Converts the style into a string that VexFlow RenderContext can understand
  692. * as the weight of the font
  693. */
  694. public static fontStyle(style: FontStyles): string {
  695. switch (style) {
  696. case FontStyles.Bold:
  697. return "bold";
  698. case FontStyles.Italic:
  699. return "italic";
  700. case FontStyles.BoldItalic:
  701. return "italic bold";
  702. default:
  703. return "normal";
  704. }
  705. }
  706. /**
  707. * Convert OutlineAndFillStyle to CSS properties
  708. * @param styleId
  709. * @returns {string}
  710. */
  711. public static style(styleId: OutlineAndFillStyleEnum): string {
  712. const ret: string = OUTLINE_AND_FILL_STYLE_DICT.getValue(styleId);
  713. return ret;
  714. }
  715. }