OpenSheetMusicDisplay.ts 48 KB

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