OpenSheetMusicDisplay.ts 50 KB

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