OpenSheetMusicDisplay.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. import { IXmlElement } from "./../Common/FileIO/Xml";
  2. import { VexFlowMusicSheetCalculator } from "./../MusicalScore/Graphical/VexFlow/VexFlowMusicSheetCalculator";
  3. import { VexFlowBackend } from "./../MusicalScore/Graphical/VexFlow/VexFlowBackend";
  4. import { MusicSheetReader } from "./../MusicalScore/ScoreIO/MusicSheetReader";
  5. import { GraphicalMusicSheet } from "./../MusicalScore/Graphical/GraphicalMusicSheet";
  6. import { MusicSheetCalculator } from "./../MusicalScore/Graphical/MusicSheetCalculator";
  7. import { VexFlowMusicSheetDrawer } from "./../MusicalScore/Graphical/VexFlow/VexFlowMusicSheetDrawer";
  8. import { SvgVexFlowBackend } from "./../MusicalScore/Graphical/VexFlow/SvgVexFlowBackend";
  9. import { CanvasVexFlowBackend } from "./../MusicalScore/Graphical/VexFlow/CanvasVexFlowBackend";
  10. import { MusicSheet } from "./../MusicalScore/MusicSheet";
  11. import { Cursor } from "./Cursor";
  12. import { MXLHelper } from "../Common/FileIO/Mxl";
  13. import { AJAX } from "./AJAX";
  14. import log from "loglevel";
  15. import { DrawingParametersEnum, DrawingParameters, ColoringModes } from "../MusicalScore/Graphical/DrawingParameters";
  16. import { IOSMDOptions, OSMDOptions, AutoBeamOptions, BackendType } from "./OSMDOptions";
  17. import { EngravingRules, PageFormat } from "../MusicalScore/Graphical/EngravingRules";
  18. import { AbstractExpression } from "../MusicalScore/VoiceData/Expressions/AbstractExpression";
  19. import { Dictionary } from "typescript-collections";
  20. import { NoteEnum } from "..";
  21. import { AutoColorSet, GraphicalMusicPage } from "../MusicalScore";
  22. import jspdf = require("jspdf-yworks/dist/jspdf.min");
  23. import svg2pdf = require("svg2pdf.js/dist/svg2pdf.min");
  24. import { MusicPartManagerIterator } from "../MusicalScore/MusicParts";
  25. import { ITransposeCalculator } from "../MusicalScore/Interfaces";
  26. /**
  27. * The main class and control point of OpenSheetMusicDisplay.<br>
  28. * It can display MusicXML sheet music files in an HTML element container.<br>
  29. * After the constructor, use load() and render() to load and render a MusicXML file.
  30. */
  31. export class OpenSheetMusicDisplay {
  32. private version: string = "0.8.0-dev"; // getter: this.Version
  33. // at release, bump version and change to -release, afterwards to -dev again
  34. /**
  35. * Creates and attaches an OpenSheetMusicDisplay object to an HTML element container.<br>
  36. * After the constructor, use load() and render() to load and render a MusicXML file.
  37. * @param container The container element OSMD will be rendered into.<br>
  38. * Either a string specifying the ID of an HTML container element,<br>
  39. * or a reference to the HTML element itself (e.g. div)
  40. * @param options An object for rendering options like the backend (svg/canvas) or autoResize.<br>
  41. * For defaults see the OSMDOptionsStandard method in the [[OSMDOptions]] class.
  42. */
  43. constructor(container: string | HTMLElement,
  44. options: IOSMDOptions = OSMDOptions.OSMDOptionsStandard()) {
  45. // Store container element
  46. if (typeof container === "string") {
  47. // ID passed
  48. this.container = document.getElementById(<string>container);
  49. } else if (container && "appendChild" in <any>container) {
  50. // Element passed
  51. this.container = <HTMLElement>container;
  52. }
  53. if (!this.container) {
  54. throw new Error("Please pass a valid div container to OpenSheetMusicDisplay");
  55. }
  56. if (options.autoResize === undefined) {
  57. options.autoResize = true;
  58. }
  59. this.backendType = BackendType.SVG; // default, can be changed by options
  60. this.setOptions(options);
  61. }
  62. public cursor: Cursor;
  63. public zoom: number = 1.0;
  64. private zoomUpdated: boolean = false;
  65. private container: HTMLElement;
  66. private backendType: BackendType;
  67. private needBackendUpdate: boolean;
  68. private sheet: MusicSheet;
  69. private drawer: VexFlowMusicSheetDrawer;
  70. private drawBoundingBox: string;
  71. private drawSkyLine: boolean;
  72. private drawBottomLine: boolean;
  73. private graphic: GraphicalMusicSheet;
  74. private drawingParameters: DrawingParameters;
  75. private rules: EngravingRules;
  76. private autoResizeEnabled: boolean;
  77. private resizeHandlerAttached: boolean;
  78. private followCursor: boolean;
  79. /**
  80. * Load a MusicXML file
  81. * @param content is either the url of a file, or the root node of a MusicXML document, or the string content of a .xml/.mxl file
  82. */
  83. public load(content: string | Document): Promise<{}> {
  84. // Warning! This function is asynchronous! No error handling is done here.
  85. this.reset();
  86. //console.log("typeof content: " + typeof content);
  87. if (typeof content === "string") {
  88. const str: string = <string>content;
  89. const self: OpenSheetMusicDisplay = this;
  90. // console.log("substring: " + str.substr(0, 5));
  91. if (str.substr(0, 4) === "\x50\x4b\x03\x04") {
  92. log.debug("[OSMD] This is a zip file, unpack it first: " + str);
  93. // This is a zip file, unpack it first
  94. return MXLHelper.MXLtoXMLstring(str).then(
  95. (x: string) => {
  96. return self.load(x);
  97. },
  98. (err: any) => {
  99. log.debug(err);
  100. throw new Error("OpenSheetMusicDisplay: Invalid MXL file");
  101. }
  102. );
  103. }
  104. // Javascript loads strings as utf-16, which is wonderful BS if you want to parse UTF-8 :S
  105. if (str.substr(0, 3) === "\uf7ef\uf7bb\uf7bf") {
  106. log.debug("[OSMD] UTF with BOM detected, truncate first three bytes and pass along: " + str);
  107. // UTF with BOM detected, truncate first three bytes and pass along
  108. return self.load(str.substr(3));
  109. }
  110. if (str.substr(0, 6).includes("<?xml")) { // first character is sometimes null, making first five characters '<?xm'.
  111. log.debug("[OSMD] Finally parsing XML content, length: " + str.length);
  112. // Parse the string representing an xml file
  113. const parser: DOMParser = new DOMParser();
  114. content = parser.parseFromString(str, "application/xml");
  115. } else if (str.length < 2083) { // TODO do proper URL format check
  116. log.debug("[OSMD] Retrieve the file at the given URL: " + str);
  117. // Assume now "str" is a URL
  118. // Retrieve the file at the given URL
  119. return AJAX.ajax(str).then(
  120. (s: string) => { return self.load(s); },
  121. (exc: Error) => { throw exc; }
  122. );
  123. } else {
  124. console.error("[OSMD] osmd.load(string): Could not process string. Missing else branch?");
  125. }
  126. }
  127. if (!content || !(<any>content).nodeName) {
  128. return Promise.reject(new Error("OpenSheetMusicDisplay: The document which was provided is invalid"));
  129. }
  130. const xmlDocument: Document = (<Document>content);
  131. const xmlDocumentNodes: NodeList = xmlDocument.childNodes;
  132. log.debug("[OSMD] load(), Document url: " + xmlDocument.URL);
  133. let scorePartwiseElement: Element;
  134. for (let i: number = 0, length: number = xmlDocumentNodes.length; i < length; i += 1) {
  135. const node: Node = xmlDocumentNodes[i];
  136. if (node.nodeType === Node.ELEMENT_NODE && node.nodeName.toLowerCase() === "score-partwise") {
  137. scorePartwiseElement = <Element>node;
  138. break;
  139. }
  140. }
  141. if (!scorePartwiseElement) {
  142. console.error("Could not parse MusicXML, no valid partwise element found");
  143. return Promise.reject(new Error("OpenSheetMusicDisplay: Document is not a valid 'partwise' MusicXML"));
  144. }
  145. const score: IXmlElement = new IXmlElement(scorePartwiseElement);
  146. const reader: MusicSheetReader = new MusicSheetReader(undefined, this.rules);
  147. this.sheet = reader.createMusicSheet(score, "Untitled Score");
  148. if (this.sheet === undefined) {
  149. // error loading sheet, probably already logged, do nothing
  150. return Promise.reject(new Error("given music sheet was incomplete or could not be loaded."));
  151. }
  152. log.info(`[OSMD] Loaded sheet ${this.sheet.TitleString} successfully.`);
  153. this.needBackendUpdate = true;
  154. this.updateGraphic();
  155. return Promise.resolve({});
  156. }
  157. /**
  158. * (Re-)creates the graphic sheet from the music sheet
  159. */
  160. public updateGraphic(): void {
  161. const calc: MusicSheetCalculator = new VexFlowMusicSheetCalculator(this.rules);
  162. this.graphic = new GraphicalMusicSheet(this.sheet, calc);
  163. if (this.drawingParameters.drawCursors && this.cursor) {
  164. this.cursor.init(this.sheet.MusicPartManager, this.graphic);
  165. }
  166. }
  167. /**
  168. * Render the music sheet in the container
  169. */
  170. public render(): void {
  171. if (!this.graphic) {
  172. throw new Error("OpenSheetMusicDisplay: Before rendering a music sheet, please load a MusicXML file");
  173. }
  174. if (this.drawer) {
  175. this.drawer.clear(); // clear canvas before setting width
  176. }
  177. // musicSheetCalculator.clearSystemsAndMeasures() // maybe? don't have reference though
  178. // musicSheetCalculator.clearRecreatedObjects();
  179. // Set page width
  180. let width: number = this.container.offsetWidth;
  181. if (this.rules.RenderSingleHorizontalStaffline) {
  182. width = 32767; // set safe maximum (browser limit), will be reduced later
  183. // reduced later in MusicSheetCalculator.calculatePageLabels (sets sheet.pageWidth to page.PositionAndShape.Size.width before labels)
  184. // rough calculation:
  185. // width = 600 * this.sheet.SourceMeasures.length;
  186. }
  187. // log.debug("[OSMD] render width: " + width);
  188. this.sheet.pageWidth = width / this.zoom / 10.0;
  189. if (this.rules.PageFormat && !this.rules.PageFormat.IsUndefined) {
  190. this.rules.PageHeight = this.sheet.pageWidth / this.rules.PageFormat.aspectRatio;
  191. log.debug("[OSMD] PageHeight: " + this.rules.PageHeight);
  192. } else {
  193. log.debug("[OSMD] endless/undefined pageformat, id: " + this.rules.PageFormat.idString);
  194. this.rules.PageHeight = 100001; // infinite page height // TODO maybe Number.MAX_VALUE or Math.pow(10, 20)?
  195. }
  196. // Before introducing the following optimization (maybe irrelevant), tests
  197. // have to be modified to ensure that width is > 0 when executed
  198. //if (isNaN(width) || width === 0) {
  199. // return;
  200. //}
  201. // Calculate again
  202. this.graphic.reCalculate();
  203. if (this.drawingParameters.drawCursors) {
  204. this.graphic.Cursors.length = 0;
  205. }
  206. // needBackendUpdate is well intentioned, but we need to cover all cases.
  207. // backends also need an update when this.zoom was set from outside, which unfortunately doesn't have a setter method to set this in.
  208. // so just for compatibility, we need to assume users set osmd.zoom, so we'd need to check whether it was changed compared to last time.
  209. if (true || this.needBackendUpdate) {
  210. this.createOrRefreshRenderBackend();
  211. this.needBackendUpdate = false;
  212. }
  213. this.drawer.setZoom(this.zoom);
  214. // Finally, draw
  215. this.drawer.drawSheet(this.graphic);
  216. this.enableOrDisableCursor(this.drawingParameters.drawCursors);
  217. if (this.drawingParameters.drawCursors && this.cursor) {
  218. // Update the cursor position
  219. this.cursor.update();
  220. }
  221. this.zoomUpdated = false;
  222. //console.log("[OSMD] render finished");
  223. }
  224. private createOrRefreshRenderBackend(): void {
  225. // console.log("[OSMD] createOrRefreshRenderBackend()");
  226. // Remove old backends
  227. if (this.drawer && this.drawer.Backends) {
  228. // removing single children to remove all is error-prone, because sometimes a random SVG-child remains.
  229. // for (const backend of this.drawer.Backends) {
  230. // backend.removeFromContainer(this.container);
  231. // }
  232. if (this.drawer.Backends[0]) {
  233. this.drawer.Backends[0].removeAllChildrenFromContainer(this.container);
  234. }
  235. this.drawer.Backends.clear();
  236. }
  237. // Create the drawer
  238. this.drawingParameters.Rules = this.rules;
  239. this.drawer = new VexFlowMusicSheetDrawer(this.drawingParameters); // note that here the drawer.drawableBoundingBoxElement is lost. now saved in OSMD.
  240. this.drawer.drawableBoundingBoxElement = this.DrawBoundingBox;
  241. this.drawer.bottomLineVisible = this.drawBottomLine;
  242. this.drawer.skyLineVisible = this.drawSkyLine;
  243. // Set page width
  244. let width: number = this.container.offsetWidth;
  245. if (this.rules.RenderSingleHorizontalStaffline) {
  246. width = this.graphic.MusicPages[0].PositionAndShape.Size.width * 10 * this.zoom;
  247. // this.container.style.width = width + "px";
  248. // console.log("width: " + width)
  249. }
  250. // TODO width may need to be coordinated with render() where width is also used
  251. let height: number;
  252. const canvasDimensionsLimit: number = 32767; // browser limitation. Chrome/Firefox (16 bit, 32768 causes an error).
  253. // Could be calculated by canvas-size module.
  254. // see #678 on Github and here: https://stackoverflow.com/a/11585939/10295942
  255. // TODO check if resize is necessary. set needResize or something when size was changed
  256. for (const page of this.graphic.MusicPages) {
  257. const backend: VexFlowBackend = this.createBackend(this.backendType, page);
  258. const sizeWarningPartTwo: string = " exceeds CanvasBackend limit of 32767. Cutting off score.";
  259. if (backend.getOSMDBackendType() === BackendType.Canvas && width > canvasDimensionsLimit) {
  260. console.log("[OSMD] Warning: width of " + width + sizeWarningPartTwo);
  261. width = canvasDimensionsLimit;
  262. }
  263. if (this.rules.PageFormat && !this.rules.PageFormat.IsUndefined) {
  264. height = width / this.rules.PageFormat.aspectRatio;
  265. // console.log("pageformat given. height: " + page.PositionAndShape.Size.height);
  266. } else {
  267. height = (page.PositionAndShape.Size.height + 15) * this.zoom * 10.0;
  268. // console.log("pageformat not given. height: " + page.PositionAndShape.Size.height);
  269. }
  270. if (backend.getOSMDBackendType() === BackendType.Canvas && height > canvasDimensionsLimit) {
  271. console.log("[OSMD] Warning: height of " + height + sizeWarningPartTwo);
  272. height = Math.min(height, canvasDimensionsLimit); // this cuts off the the score, but doesn't break rendering.
  273. // TODO optional: reduce zoom to fit the score within the limit.
  274. }
  275. backend.resize(width, height);
  276. backend.clear(); // set bgcolor if defined (this.rules.PageBackgroundColor, see OSMDOptions)
  277. this.drawer.Backends.push(backend);
  278. }
  279. }
  280. /** States whether the render() function can be safely called. */
  281. public IsReadyToRender(): boolean {
  282. return this.graphic !== undefined;
  283. }
  284. /** Clears what OSMD has drawn on its canvas. */
  285. public clear(): void {
  286. this.drawer.clear();
  287. this.reset(); // without this, resize will draw loaded sheet again
  288. }
  289. /** Set OSMD rendering options using an IOSMDOptions object.
  290. * Can be called during runtime. Also called by constructor.
  291. * For example, setOptions({autoResize: false}) will disable autoResize even during runtime.
  292. */
  293. public setOptions(options: IOSMDOptions): void {
  294. if (!this.rules) {
  295. this.rules = new EngravingRules();
  296. }
  297. if (!this.drawingParameters) {
  298. this.drawingParameters = new DrawingParameters();
  299. this.drawingParameters.Rules = this.rules;
  300. }
  301. if (options === undefined || options === null) {
  302. log.warn("warning: osmd.setOptions() called without an options parameter, has no effect."
  303. + "\n" + "example usage: osmd.setOptions({drawCredits: false, drawPartNames: false})");
  304. return;
  305. }
  306. if (options.drawingParameters) {
  307. this.drawingParameters.DrawingParametersEnum =
  308. (<any>DrawingParametersEnum)[options.drawingParameters.toLowerCase()];
  309. // see DrawingParameters.ts: set DrawingParametersEnum, and DrawingParameters.ts:setForCompactTightMode()
  310. }
  311. const backendNotInitialized: boolean = !this.drawer || !this.drawer.Backends || this.drawer.Backends.length < 1;
  312. let needBackendUpdate: boolean = backendNotInitialized;
  313. if (options.backend !== undefined) {
  314. const backendTypeGiven: BackendType = OSMDOptions.BackendTypeFromString(options.backend);
  315. needBackendUpdate = needBackendUpdate || this.backendType !== backendTypeGiven;
  316. this.backendType = backendTypeGiven;
  317. }
  318. this.needBackendUpdate = needBackendUpdate;
  319. // TODO this is a necessary step during the OSMD constructor. Maybe move this somewhere else
  320. // individual drawing parameters options
  321. if (options.autoBeam !== undefined) { // only change an option if it was given in options, otherwise it will be undefined
  322. this.rules.AutoBeamNotes = options.autoBeam;
  323. }
  324. const autoBeamOptions: AutoBeamOptions = options.autoBeamOptions;
  325. if (autoBeamOptions) {
  326. if (autoBeamOptions.maintain_stem_directions === undefined) {
  327. autoBeamOptions.maintain_stem_directions = false;
  328. }
  329. this.rules.AutoBeamOptions = autoBeamOptions;
  330. if (autoBeamOptions.groups && autoBeamOptions.groups.length) {
  331. for (const fraction of autoBeamOptions.groups) {
  332. if (fraction.length !== 2) {
  333. throw new Error("Each fraction in autoBeamOptions.groups must be of length 2, e.g. [3,4] for beaming three fourths");
  334. }
  335. }
  336. }
  337. }
  338. if (options.percussionOneLineCutoff !== undefined) {
  339. this.rules.PercussionOneLineCutoff = options.percussionOneLineCutoff;
  340. }
  341. if (this.rules.PercussionOneLineCutoff !== 0 &&
  342. options.percussionForceVoicesOneLineCutoff !== undefined) {
  343. this.rules.PercussionForceVoicesOneLineCutoff = options.percussionForceVoicesOneLineCutoff;
  344. }
  345. if (options.alignRests !== undefined) {
  346. this.rules.AlignRests = options.alignRests;
  347. }
  348. if (options.coloringMode !== undefined) {
  349. this.setColoringMode(options);
  350. }
  351. if (options.coloringEnabled !== undefined) {
  352. this.rules.ColoringEnabled = options.coloringEnabled;
  353. }
  354. if (options.colorStemsLikeNoteheads !== undefined) {
  355. this.rules.ColorStemsLikeNoteheads = options.colorStemsLikeNoteheads;
  356. }
  357. if (options.disableCursor) {
  358. this.drawingParameters.drawCursors = false;
  359. }
  360. // alternative to if block: this.drawingsParameters.drawCursors = options.drawCursors !== false. No if, but always sets drawingParameters.
  361. // note that every option can be undefined, which doesn't mean the option should be set to false.
  362. if (options.drawHiddenNotes) {
  363. this.drawingParameters.drawHiddenNotes = true; // not yet supported
  364. }
  365. if (options.drawCredits !== undefined) {
  366. this.drawingParameters.DrawCredits = options.drawCredits; // sets DrawComposer, DrawTitle, DrawSubtitle, DrawLyricist.
  367. }
  368. if (options.drawComposer !== undefined) {
  369. this.drawingParameters.DrawComposer = options.drawComposer;
  370. }
  371. if (options.drawTitle !== undefined) {
  372. this.drawingParameters.DrawTitle = options.drawTitle;
  373. }
  374. if (options.drawSubtitle !== undefined) {
  375. this.drawingParameters.DrawSubtitle = options.drawSubtitle;
  376. }
  377. if (options.drawLyricist !== undefined) {
  378. this.drawingParameters.DrawLyricist = options.drawLyricist;
  379. }
  380. if (options.drawMetronomeMarks !== undefined) {
  381. this.rules.MetronomeMarksDrawn = options.drawMetronomeMarks;
  382. }
  383. if (options.drawPartNames !== undefined) {
  384. this.drawingParameters.DrawPartNames = options.drawPartNames; // indirectly writes to EngravingRules
  385. // by default, disable part abbreviations too, unless set explicitly.
  386. if (!options.drawPartAbbreviations) {
  387. this.rules.RenderPartAbbreviations = options.drawPartNames;
  388. }
  389. }
  390. if (options.drawPartAbbreviations !== undefined) {
  391. this.rules.RenderPartAbbreviations = options.drawPartAbbreviations;
  392. }
  393. if (options.drawFingerings === false) {
  394. this.rules.RenderFingerings = false;
  395. }
  396. if (options.drawMeasureNumbers !== undefined) {
  397. this.rules.RenderMeasureNumbers = options.drawMeasureNumbers;
  398. }
  399. if (options.drawLyrics !== undefined) {
  400. this.rules.RenderLyrics = options.drawLyrics;
  401. }
  402. if (options.drawSlurs !== undefined) {
  403. this.rules.RenderSlurs = options.drawSlurs;
  404. }
  405. if (options.measureNumberInterval !== undefined) {
  406. this.rules.MeasureNumberLabelOffset = options.measureNumberInterval;
  407. }
  408. if (options.fingeringPosition !== undefined) {
  409. this.rules.FingeringPosition = AbstractExpression.PlacementEnumFromString(options.fingeringPosition);
  410. }
  411. if (options.fingeringInsideStafflines !== undefined) {
  412. this.rules.FingeringInsideStafflines = options.fingeringInsideStafflines;
  413. }
  414. if (options.newSystemFromXML !== undefined) {
  415. this.rules.NewSystemAtXMLNewSystemAttribute = options.newSystemFromXML;
  416. }
  417. if (options.newPageFromXML !== undefined) {
  418. this.rules.NewPageAtXMLNewPageAttribute = options.newPageFromXML;
  419. }
  420. if (options.fillEmptyMeasuresWithWholeRest !== undefined) {
  421. this.rules.FillEmptyMeasuresWithWholeRest = options.fillEmptyMeasuresWithWholeRest;
  422. }
  423. if (options.followCursor !== undefined) {
  424. this.FollowCursor = options.followCursor;
  425. }
  426. if (options.setWantedStemDirectionByXml !== undefined) {
  427. this.rules.SetWantedStemDirectionByXml = options.setWantedStemDirectionByXml;
  428. }
  429. if (options.defaultColorNotehead) {
  430. this.rules.DefaultColorNotehead = options.defaultColorNotehead;
  431. }
  432. if (options.defaultColorRest) {
  433. this.rules.DefaultColorRest = options.defaultColorRest;
  434. }
  435. if (options.defaultColorStem) {
  436. this.rules.DefaultColorStem = options.defaultColorStem;
  437. }
  438. if (options.defaultColorLabel) {
  439. this.rules.DefaultColorLabel = options.defaultColorLabel;
  440. }
  441. if (options.defaultColorTitle) {
  442. this.rules.DefaultColorTitle = options.defaultColorTitle;
  443. }
  444. if (options.defaultFontFamily) {
  445. this.rules.DefaultFontFamily = options.defaultFontFamily; // default "Times New Roman", also used if font family not found
  446. }
  447. if (options.defaultFontStyle) {
  448. this.rules.DefaultFontStyle = options.defaultFontStyle; // e.g. FontStyles.Bold
  449. }
  450. if (options.drawUpToMeasureNumber) {
  451. this.rules.MaxMeasureToDrawIndex = options.drawUpToMeasureNumber - 1;
  452. }
  453. if (options.drawFromMeasureNumber) {
  454. this.rules.MinMeasureToDrawIndex = options.drawFromMeasureNumber - 1;
  455. }
  456. if (options.tupletsRatioed) {
  457. this.rules.TupletsRatioed = true;
  458. }
  459. if (options.tupletsBracketed) {
  460. this.rules.TupletsBracketed = true;
  461. }
  462. if (options.tripletsBracketed) {
  463. this.rules.TripletsBracketed = true;
  464. }
  465. if (options.autoResize) {
  466. if (!this.resizeHandlerAttached) {
  467. this.autoResize();
  468. }
  469. this.autoResizeEnabled = true;
  470. } else if (options.autoResize === false) { // not undefined
  471. this.autoResizeEnabled = false;
  472. // we could remove the window EventListener here, but not necessary.
  473. }
  474. if (options.pageFormat !== undefined) { // only change this option if it was given, see above
  475. this.setPageFormat(options.pageFormat);
  476. }
  477. if (options.pageBackgroundColor !== undefined) {
  478. this.rules.PageBackgroundColor = options.pageBackgroundColor;
  479. }
  480. if (options.renderSingleHorizontalStaffline !== undefined) {
  481. this.rules.RenderSingleHorizontalStaffline = options.renderSingleHorizontalStaffline;
  482. }
  483. }
  484. public setColoringMode(options: IOSMDOptions): void {
  485. if (options.coloringMode === ColoringModes.XML) {
  486. this.rules.ColoringMode = ColoringModes.XML;
  487. return;
  488. }
  489. const noteIndices: NoteEnum[] = [NoteEnum.C, NoteEnum.D, NoteEnum.E, NoteEnum.F, NoteEnum.G, NoteEnum.A, NoteEnum.B, -1];
  490. let colorSetString: string[];
  491. if (options.coloringMode === ColoringModes.CustomColorSet) {
  492. if (!options.coloringSetCustom || options.coloringSetCustom.length !== 8) {
  493. throw new Error("Invalid amount of colors: With coloringModes.customColorSet, " +
  494. "you have to provide a coloringSetCustom parameter with 8 strings (C to B, rest note).");
  495. }
  496. // validate strings input
  497. for (const colorString of options.coloringSetCustom) {
  498. const regExp: RegExp = /^\#[0-9a-fA-F]{6}$/;
  499. if (!regExp.test(colorString)) {
  500. throw new Error(
  501. "One of the color strings in options.coloringSetCustom was not a valid HTML Hex color:\n" + colorString);
  502. }
  503. }
  504. colorSetString = options.coloringSetCustom;
  505. } else if (options.coloringMode === ColoringModes.AutoColoring) {
  506. colorSetString = [];
  507. const keys: string[] = Object.keys(AutoColorSet);
  508. for (let i: number = 0; i < keys.length; i++) {
  509. colorSetString.push(AutoColorSet[keys[i]]);
  510. }
  511. } // for both cases:
  512. const coloringSetCurrent: Dictionary<NoteEnum | number, string> = new Dictionary<NoteEnum | number, string>();
  513. for (let i: number = 0; i < noteIndices.length; i++) {
  514. coloringSetCurrent.setValue(noteIndices[i], colorSetString[i]);
  515. }
  516. coloringSetCurrent.setValue(-1, colorSetString[7]);
  517. this.rules.ColoringSetCurrent = coloringSetCurrent;
  518. this.rules.ColoringMode = options.coloringMode;
  519. }
  520. /**
  521. * Sets the logging level for this OSMD instance. By default, this is set to `warn`.
  522. *
  523. * @param: content can be `trace`, `debug`, `info`, `warn` or `error`.
  524. */
  525. public setLogLevel(level: string): void {
  526. switch (level) {
  527. case "trace":
  528. log.setLevel(log.levels.TRACE);
  529. break;
  530. case "debug":
  531. log.setLevel(log.levels.DEBUG);
  532. break;
  533. case "info":
  534. log.setLevel(log.levels.INFO);
  535. break;
  536. case "warn":
  537. log.setLevel(log.levels.WARN);
  538. break;
  539. case "error":
  540. log.setLevel(log.levels.ERROR);
  541. break;
  542. default:
  543. log.warn(`Could not set log level to ${level}. Using warn instead.`);
  544. log.setLevel(log.levels.WARN);
  545. break;
  546. }
  547. }
  548. public getLogLevel(): number {
  549. return log.getLevel();
  550. }
  551. /**
  552. * Initialize this object to default values
  553. * FIXME: Probably unnecessary
  554. */
  555. private reset(): void {
  556. if (this.drawingParameters.drawCursors && this.cursor) {
  557. this.cursor.hide();
  558. }
  559. this.sheet = undefined;
  560. this.graphic = undefined;
  561. this.zoom = 1.0;
  562. }
  563. /**
  564. * Attach the appropriate handler to the window.onResize event
  565. */
  566. private autoResize(): void {
  567. const self: OpenSheetMusicDisplay = this;
  568. this.handleResize(
  569. () => {
  570. // empty
  571. },
  572. () => {
  573. // The following code is probably not needed
  574. // (the width should adapt itself to the max allowed)
  575. //let width: number = Math.max(
  576. // document.documentElement.clientWidth,
  577. // document.body.scrollWidth,
  578. // document.documentElement.scrollWidth,
  579. // document.body.offsetWidth,
  580. // document.documentElement.offsetWidth
  581. //);
  582. //self.container.style.width = width + "px";
  583. // recalculate beams, are otherwise not updated and can detach from stems, see #724
  584. if (this.graphic?.GetCalculator instanceof VexFlowMusicSheetCalculator) { // null and type check
  585. (this.graphic.GetCalculator as VexFlowMusicSheetCalculator).beamsNeedUpdate = true;
  586. }
  587. if (self.IsReadyToRender()) {
  588. self.render();
  589. }
  590. }
  591. );
  592. }
  593. /**
  594. * Helper function for managing window's onResize events
  595. * @param startCallback is the function called when resizing starts
  596. * @param endCallback is the function called when resizing (kind-of) ends
  597. */
  598. private handleResize(startCallback: () => void, endCallback: () => void): void {
  599. let rtime: number;
  600. let timeout: number = undefined;
  601. const delta: number = 200;
  602. const self: OpenSheetMusicDisplay = this;
  603. function resizeStart(): void {
  604. if (!self.AutoResizeEnabled) {
  605. return;
  606. }
  607. rtime = (new Date()).getTime();
  608. if (!timeout) {
  609. startCallback();
  610. rtime = (new Date()).getTime();
  611. timeout = window.setTimeout(resizeEnd, delta);
  612. }
  613. }
  614. function resizeEnd(): void {
  615. timeout = undefined;
  616. window.clearTimeout(timeout);
  617. if ((new Date()).getTime() - rtime < delta) {
  618. timeout = window.setTimeout(resizeEnd, delta);
  619. } else {
  620. endCallback();
  621. }
  622. }
  623. if ((<any>window).attachEvent) {
  624. // Support IE<9
  625. (<any>window).attachEvent("onresize", resizeStart);
  626. } else {
  627. window.addEventListener("resize", resizeStart);
  628. }
  629. this.resizeHandlerAttached = true;
  630. window.setTimeout(startCallback, 0);
  631. window.setTimeout(endCallback, 1);
  632. }
  633. /** Enable or disable (hide) the cursor.
  634. * @param enable whether to enable (true) or disable (false) the cursor
  635. */
  636. public enableOrDisableCursor(enable: boolean): void {
  637. this.drawingParameters.drawCursors = enable;
  638. if (enable) {
  639. // save previous cursor state
  640. const hidden: boolean = this.cursor?.Hidden;
  641. const previousIterator: MusicPartManagerIterator = this.cursor?.Iterator;
  642. // create new cursor
  643. if (this.drawer?.Backends?.length >= 1 && this.drawer.Backends[0].getRenderElement()) {
  644. this.cursor = new Cursor(this.drawer.Backends[0].getRenderElement(), this);
  645. }
  646. if (this.sheet && this.graphic && this.cursor) { // else init is called in load()
  647. this.cursor.init(this.sheet.MusicPartManager, this.graphic);
  648. }
  649. // restore old cursor state
  650. if (this.rules.RestoreCursorAfterRerender) {
  651. this.cursor.hidden = hidden;
  652. if (previousIterator) {
  653. this.cursor.iterator = previousIterator;
  654. }
  655. }
  656. } else { // disable cursor
  657. if (!this.cursor) {
  658. return;
  659. }
  660. this.cursor.hide();
  661. // this.cursor = undefined;
  662. // TODO cursor should be disabled, not just hidden. otherwise user can just call osmd.cursor.hide().
  663. // however, this could cause null calls (cursor.next() etc), maybe that needs some solution.
  664. }
  665. }
  666. public createBackend(type: BackendType, page: GraphicalMusicPage): VexFlowBackend {
  667. let backend: VexFlowBackend;
  668. if (type === undefined || type === BackendType.SVG) {
  669. backend = new SvgVexFlowBackend(this.rules);
  670. } else {
  671. backend = new CanvasVexFlowBackend(this.rules);
  672. }
  673. backend.graphicalMusicPage = page; // the page the backend renders on. needed to identify DOM element to extract image/SVG
  674. backend.initialize(this.container);
  675. return backend;
  676. }
  677. /** Standard page format options like A4 or Letter, in portrait and landscape. E.g. PageFormatStandards["A4_P"] or PageFormatStandards["Letter_L"]. */
  678. public static PageFormatStandards: { [type: string]: PageFormat } = {
  679. "A3_L": new PageFormat(420, 297, "A3_L"), // id strings should use underscores instead of white spaces to facilitate use as URL parameters.
  680. "A3_P": new PageFormat(297, 420, "A3_P"),
  681. "A4_L": new PageFormat(297, 210, "A4_L"),
  682. "A4_P": new PageFormat(210, 297, "A4_P"),
  683. "A5_L": new PageFormat(210, 148, "A5_L"),
  684. "A5_P": new PageFormat(148, 210, "A5_P"),
  685. "A6_L": new PageFormat(148, 105, "A6_L"),
  686. "A6_P": new PageFormat(105, 148, "A6_P"),
  687. "Endless": PageFormat.UndefinedPageFormat,
  688. "Letter_L": new PageFormat(279.4, 215.9, "Letter_L"),
  689. "Letter_P": new PageFormat(215.9, 279.4, "Letter_P")
  690. };
  691. public static StringToPageFormat(pageFormatString: string): PageFormat {
  692. let pageFormat: PageFormat = PageFormat.UndefinedPageFormat; // default: 'endless' page height, take canvas/container width
  693. // check for widthxheight parameter, e.g. "800x600"
  694. if (pageFormatString.match("^[0-9]+x[0-9]+$")) {
  695. const widthAndHeight: string[] = pageFormatString.split("x");
  696. const width: number = Number.parseInt(widthAndHeight[0], 10);
  697. const height: number = Number.parseInt(widthAndHeight[1], 10);
  698. if (width > 0 && width < 32768 && height > 0 && height < 32768) {
  699. pageFormat = new PageFormat(width, height, `customPageFormat${pageFormatString}`);
  700. }
  701. }
  702. // check for formatId from OpenSheetMusicDisplay.PageFormatStandards
  703. pageFormatString = pageFormatString.replace(" ", "_");
  704. pageFormatString = pageFormatString.replace("Landscape", "L");
  705. pageFormatString = pageFormatString.replace("Portrait", "P");
  706. //console.log("change format to: " + formatId);
  707. if (OpenSheetMusicDisplay.PageFormatStandards.hasOwnProperty(pageFormatString)) {
  708. pageFormat = OpenSheetMusicDisplay.PageFormatStandards[pageFormatString];
  709. return pageFormat;
  710. }
  711. return pageFormat;
  712. }
  713. /** Sets page format by string. Used by setOptions({pageFormat: "A4_P"}) for example. */
  714. public setPageFormat(formatId: string): void {
  715. const newPageFormat: PageFormat = OpenSheetMusicDisplay.StringToPageFormat(formatId);
  716. this.needBackendUpdate = !(newPageFormat.Equals(this.rules.PageFormat));
  717. this.rules.PageFormat = newPageFormat;
  718. }
  719. public setCustomPageFormat(width: number, height: number): void {
  720. if (width > 0 && height > 0) {
  721. const f: PageFormat = new PageFormat(width, height);
  722. this.rules.PageFormat = f;
  723. }
  724. }
  725. /**
  726. * Creates a Pdf of the currently rendered MusicXML
  727. * @param pdfName if no name is given, the composer and title of the piece will be used
  728. */
  729. public createPdf(pdfName: string = undefined): void {
  730. if (this.backendType !== BackendType.SVG) {
  731. console.log("[OSMD] osmd.createPdf(): Warning: createPDF is only supported for SVG background for now, not for Canvas." +
  732. " Please use osmd.setOptions({backendType: SVG}).");
  733. return;
  734. }
  735. if (pdfName === undefined) {
  736. pdfName = this.sheet.FullNameString + ".pdf";
  737. }
  738. const backends: VexFlowBackend[] = this.drawer.Backends;
  739. let svgElement: SVGElement = (<SvgVexFlowBackend>backends[0]).getSvgElement();
  740. let pageWidth: number = 210;
  741. let pageHeight: number = 297;
  742. const engravingRulesPageFormat: PageFormat = this.rules.PageFormat;
  743. if (engravingRulesPageFormat && !engravingRulesPageFormat.IsUndefined) {
  744. pageWidth = engravingRulesPageFormat.width;
  745. pageHeight = engravingRulesPageFormat.height;
  746. } else {
  747. pageHeight = pageWidth * svgElement.clientHeight / svgElement.clientWidth;
  748. }
  749. const orientation: string = pageHeight > pageWidth ? "p" : "l";
  750. // create a new jsPDF instance
  751. const pdf: any = new jspdf(orientation, "mm", [pageWidth, pageHeight]);
  752. const scale: number = pageWidth / svgElement.clientWidth;
  753. for (let idx: number = 0, len: number = backends.length; idx < len; ++idx) {
  754. if (idx > 0) {
  755. pdf.addPage();
  756. }
  757. svgElement = (<SvgVexFlowBackend>backends[idx]).getSvgElement();
  758. // render the svg element
  759. svg2pdf(svgElement, pdf, {
  760. scale: scale,
  761. xOffset: 0,
  762. yOffset: 0
  763. });
  764. }
  765. // simply save the created pdf
  766. pdf.save(pdfName);
  767. // note that using jspdf with svg2pdf creates unnecessary console warnings "AcroForm-Classes are not populated into global-namespace..."
  768. // this will hopefully be fixed with a new jspdf release, see https://github.com/yWorks/jsPDF/pull/32
  769. }
  770. //#region GETTER / SETTER
  771. public set DrawSkyLine(value: boolean) {
  772. this.drawSkyLine = value;
  773. if (this.drawer) {
  774. this.drawer.skyLineVisible = value;
  775. // this.render(); // note: we probably shouldn't automatically render when someone sets the setter
  776. // this can cause a lot of rendering time.
  777. }
  778. }
  779. public get DrawSkyLine(): boolean {
  780. return this.drawer.skyLineVisible;
  781. }
  782. public set DrawBottomLine(value: boolean) {
  783. this.drawBottomLine = value;
  784. if (this.drawer) {
  785. this.drawer.bottomLineVisible = value;
  786. // this.render(); // note: we probably shouldn't automatically render when someone sets the setter
  787. // this can cause a lot of rendering time.
  788. }
  789. }
  790. public get DrawBottomLine(): boolean {
  791. return this.drawer.bottomLineVisible;
  792. }
  793. public set DrawBoundingBox(value: string) {
  794. this.drawBoundingBox = value;
  795. this.drawer.drawableBoundingBoxElement = value; // drawer is sometimes created anew, losing this value, so it's saved in OSMD now.
  796. this.render(); // may create new Drawer.
  797. }
  798. public get DrawBoundingBox(): string {
  799. return this.drawBoundingBox;
  800. }
  801. public get AutoResizeEnabled(): boolean {
  802. return this.autoResizeEnabled;
  803. }
  804. public set AutoResizeEnabled(value: boolean) {
  805. this.autoResizeEnabled = value;
  806. }
  807. public set Zoom(value: number) {
  808. this.zoom = value;
  809. this.zoomUpdated = true;
  810. if (this.graphic?.GetCalculator instanceof VexFlowMusicSheetCalculator) { // null and type check
  811. (this.graphic.GetCalculator as VexFlowMusicSheetCalculator).beamsNeedUpdate = this.zoomUpdated;
  812. }
  813. }
  814. public set FollowCursor(value: boolean) {
  815. this.followCursor = value;
  816. }
  817. public get FollowCursor(): boolean {
  818. return this.followCursor;
  819. }
  820. public set TransposeCalculator(calculator: ITransposeCalculator) {
  821. MusicSheetCalculator.transposeCalculator = calculator;
  822. }
  823. public get TransposeCalculator(): ITransposeCalculator {
  824. return MusicSheetCalculator.transposeCalculator;
  825. }
  826. public get Sheet(): MusicSheet {
  827. return this.sheet;
  828. }
  829. public get Drawer(): VexFlowMusicSheetDrawer {
  830. return this.drawer;
  831. }
  832. public get GraphicSheet(): GraphicalMusicSheet {
  833. return this.graphic;
  834. }
  835. public get DrawingParameters(): DrawingParameters {
  836. return this.drawingParameters;
  837. }
  838. public get EngravingRules(): EngravingRules { // custom getter, useful for engraving parameter setting in Demo
  839. return this.rules;
  840. }
  841. /** Returns the version of OSMD this object is built from (the version you are using). */
  842. public get Version(): string {
  843. return this.version;
  844. }
  845. //#endregion
  846. }