OpenSheetMusicDisplay.ts 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  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.5-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); // this resets strokeStyle for Canvas
  383. backend.clear(); // set bgcolor if defined (this.rules.PageBackgroundColor, see OSMDOptions)
  384. backend.getContext().setFillStyle(this.rules.DefaultColorMusic);
  385. backend.getContext().setStrokeStyle(this.rules.DefaultColorMusic); // needs to be set after resize()
  386. this.drawer.Backends.push(backend);
  387. this.graphic.drawer = this.drawer;
  388. }
  389. }
  390. // for now SVG only, see generateImages_browserless (PNG/SVG)
  391. public exportSVG(): void {
  392. for (const backend of this.drawer?.Backends) {
  393. if (backend instanceof SvgVexFlowBackend) {
  394. (backend as SvgVexFlowBackend).export();
  395. }
  396. // if we add CanvasVexFlowBackend exporting, rename function to export() or exportImages() again
  397. }
  398. }
  399. /** States whether the render() function can be safely called. */
  400. public IsReadyToRender(): boolean {
  401. return this.graphic !== undefined;
  402. }
  403. /** Clears what OSMD has drawn on its canvas. */
  404. public clear(): void {
  405. this.drawer?.clear();
  406. this.reset(); // without this, resize will draw loaded sheet again
  407. }
  408. /** Dispose listeners created by OSMD */
  409. public dispose(): void {
  410. if (this.disposeResizeListener) {
  411. this.disposeResizeListener();
  412. }
  413. if (this.InteractionManager) {
  414. this.InteractionManager.Dispose();
  415. }
  416. }
  417. /** Set OSMD rendering options using an IOSMDOptions object.
  418. * Can be called during runtime. Also called by constructor.
  419. * For example, setOptions({autoResize: false}) will disable autoResize even during runtime.
  420. */
  421. public setOptions(options: IOSMDOptions): void {
  422. if (!this.rules) {
  423. this.rules = new EngravingRules();
  424. }
  425. if (!this.drawingParameters && !options.drawingParameters) {
  426. this.drawingParameters = new DrawingParameters(DrawingParametersEnum.default, this.rules);
  427. // if "default", will be created below
  428. } else if (options.drawingParameters) {
  429. if (!this.drawingParameters) {
  430. this.drawingParameters = new DrawingParameters(DrawingParametersEnum[options.drawingParameters], this.rules);
  431. } else {
  432. this.drawingParameters.DrawingParametersEnum =
  433. (<any>DrawingParametersEnum)[options.drawingParameters.toLowerCase()];
  434. // see DrawingParameters.ts: set DrawingParametersEnum, and DrawingParameters.ts:setForCompactTightMode()
  435. }
  436. }
  437. if (options === undefined || options === null) {
  438. log.warn("warning: osmd.setOptions() called without an options parameter, has no effect."
  439. + "\n" + "example usage: osmd.setOptions({drawCredits: false, drawPartNames: false})");
  440. return;
  441. }
  442. this.OnXMLRead = function(xml): string {return xml;};
  443. if (options.onXMLRead) {
  444. this.OnXMLRead = options.onXMLRead;
  445. }
  446. const backendNotInitialized: boolean = !this.drawer || !this.drawer.Backends || this.drawer.Backends.length < 1;
  447. let needBackendUpdate: boolean = backendNotInitialized;
  448. if (options.backend !== undefined) {
  449. const backendTypeGiven: BackendType = OSMDOptions.BackendTypeFromString(options.backend);
  450. needBackendUpdate = needBackendUpdate || this.backendType !== backendTypeGiven;
  451. this.backendType = backendTypeGiven;
  452. }
  453. this.needBackendUpdate = needBackendUpdate;
  454. // TODO this is a necessary step during the OSMD constructor. Maybe move this somewhere else
  455. // individual drawing parameters options
  456. if (options.autoBeam !== undefined) { // only change an option if it was given in options, otherwise it will be undefined
  457. this.rules.AutoBeamNotes = options.autoBeam;
  458. }
  459. const autoBeamOptions: AutoBeamOptions = options.autoBeamOptions;
  460. if (autoBeamOptions) {
  461. if (autoBeamOptions.maintain_stem_directions === undefined) {
  462. autoBeamOptions.maintain_stem_directions = false;
  463. }
  464. this.rules.AutoBeamOptions = autoBeamOptions;
  465. if (autoBeamOptions.groups && autoBeamOptions.groups.length) {
  466. for (const fraction of autoBeamOptions.groups) {
  467. if (fraction.length !== 2) {
  468. throw new Error("Each fraction in autoBeamOptions.groups must be of length 2, e.g. [3,4] for beaming three fourths");
  469. }
  470. }
  471. }
  472. }
  473. if (options.percussionOneLineCutoff !== undefined) {
  474. this.rules.PercussionOneLineCutoff = options.percussionOneLineCutoff;
  475. }
  476. if (this.rules.PercussionOneLineCutoff !== 0 &&
  477. options.percussionForceVoicesOneLineCutoff !== undefined) {
  478. this.rules.PercussionForceVoicesOneLineCutoff = options.percussionForceVoicesOneLineCutoff;
  479. }
  480. if (options.alignRests !== undefined) {
  481. this.rules.AlignRests = options.alignRests;
  482. }
  483. if (options.coloringMode !== undefined) {
  484. this.setColoringMode(options);
  485. }
  486. if (options.coloringEnabled !== undefined) {
  487. this.rules.ColoringEnabled = options.coloringEnabled;
  488. }
  489. if (options.colorStemsLikeNoteheads !== undefined) {
  490. this.rules.ColorStemsLikeNoteheads = options.colorStemsLikeNoteheads;
  491. }
  492. if (options.disableCursor) {
  493. this.drawingParameters.drawCursors = false;
  494. }
  495. // alternative to if block: this.drawingsParameters.drawCursors = options.drawCursors !== false. No if, but always sets drawingParameters.
  496. // note that every option can be undefined, which doesn't mean the option should be set to false.
  497. if (options.drawHiddenNotes) {
  498. this.drawingParameters.drawHiddenNotes = true; // not yet supported
  499. }
  500. if (options.drawCredits !== undefined) {
  501. this.drawingParameters.DrawCredits = options.drawCredits; // sets DrawComposer, DrawTitle, DrawSubtitle, DrawLyricist.
  502. }
  503. if (options.drawComposer !== undefined) {
  504. this.drawingParameters.DrawComposer = options.drawComposer;
  505. }
  506. if (options.drawTitle !== undefined) {
  507. this.drawingParameters.DrawTitle = options.drawTitle;
  508. }
  509. if (options.drawSubtitle !== undefined) {
  510. this.drawingParameters.DrawSubtitle = options.drawSubtitle;
  511. }
  512. if (options.drawLyricist !== undefined) {
  513. this.drawingParameters.DrawLyricist = options.drawLyricist;
  514. }
  515. if (options.drawMetronomeMarks !== undefined) {
  516. this.rules.MetronomeMarksDrawn = options.drawMetronomeMarks;
  517. }
  518. if (options.drawPartNames !== undefined) {
  519. this.drawingParameters.DrawPartNames = options.drawPartNames; // indirectly writes to EngravingRules
  520. // by default, disable part abbreviations too, unless set explicitly.
  521. if (!options.drawPartAbbreviations) {
  522. this.rules.RenderPartAbbreviations = options.drawPartNames;
  523. }
  524. }
  525. if (options.drawPartAbbreviations !== undefined) {
  526. this.rules.RenderPartAbbreviations = options.drawPartAbbreviations;
  527. }
  528. if (options.drawFingerings === false) {
  529. this.rules.RenderFingerings = false;
  530. }
  531. if (options.drawMeasureNumbers !== undefined) {
  532. this.rules.RenderMeasureNumbers = options.drawMeasureNumbers;
  533. }
  534. if (options.drawMeasureNumbersOnlyAtSystemStart) {
  535. this.rules.RenderMeasureNumbersOnlyAtSystemStart = options.drawMeasureNumbersOnlyAtSystemStart;
  536. }
  537. if (options.drawLyrics !== undefined) {
  538. this.rules.RenderLyrics = options.drawLyrics;
  539. }
  540. if (options.drawTimeSignatures !== undefined) {
  541. this.rules.RenderTimeSignatures = options.drawTimeSignatures;
  542. }
  543. if (options.drawSlurs !== undefined) {
  544. this.rules.RenderSlurs = options.drawSlurs;
  545. }
  546. if (options.measureNumberInterval !== undefined) {
  547. this.rules.MeasureNumberLabelOffset = options.measureNumberInterval;
  548. }
  549. if (options.useXMLMeasureNumbers !== undefined) {
  550. this.rules.UseXMLMeasureNumbers = options.useXMLMeasureNumbers;
  551. }
  552. if (options.fingeringPosition !== undefined) {
  553. this.rules.FingeringPosition = AbstractExpression.PlacementEnumFromString(options.fingeringPosition);
  554. }
  555. if (options.fingeringInsideStafflines !== undefined) {
  556. this.rules.FingeringInsideStafflines = options.fingeringInsideStafflines;
  557. }
  558. if (options.newSystemFromXML !== undefined) {
  559. this.rules.NewSystemAtXMLNewSystemAttribute = options.newSystemFromXML;
  560. }
  561. if (options.newPageFromXML !== undefined) {
  562. this.rules.NewPageAtXMLNewPageAttribute = options.newPageFromXML;
  563. }
  564. if (options.fillEmptyMeasuresWithWholeRest !== undefined) {
  565. this.rules.FillEmptyMeasuresWithWholeRest = options.fillEmptyMeasuresWithWholeRest;
  566. }
  567. if (options.followCursor !== undefined) {
  568. this.FollowCursor = options.followCursor;
  569. }
  570. if (options.setWantedStemDirectionByXml !== undefined) {
  571. this.rules.SetWantedStemDirectionByXml = options.setWantedStemDirectionByXml;
  572. }
  573. if (options.darkMode) {
  574. this.rules.applyDefaultColorMusic("#FFFFFF");
  575. this.rules.PageBackgroundColor = "#000000";
  576. } else if (options.darkMode === false) { // not if undefined!
  577. this.rules.applyDefaultColorMusic("#000000");
  578. this.rules.PageBackgroundColor = undefined;
  579. }
  580. if (options.defaultColorMusic) {
  581. this.rules.applyDefaultColorMusic(options.defaultColorMusic);
  582. }
  583. if (options.defaultColorNotehead) {
  584. this.rules.DefaultColorNotehead = options.defaultColorNotehead;
  585. }
  586. if (options.defaultColorRest) {
  587. this.rules.DefaultColorRest = options.defaultColorRest;
  588. }
  589. if (options.defaultColorStem) {
  590. this.rules.DefaultColorStem = options.defaultColorStem;
  591. }
  592. if (options.defaultColorLabel) {
  593. this.rules.DefaultColorLabel = options.defaultColorLabel;
  594. }
  595. if (options.defaultColorTitle) {
  596. this.rules.DefaultColorTitle = options.defaultColorTitle;
  597. }
  598. if (options.defaultFontFamily) {
  599. this.rules.DefaultFontFamily = options.defaultFontFamily; // default "Times New Roman", also used if font family not found
  600. }
  601. if (options.defaultFontStyle) {
  602. this.rules.DefaultFontStyle = options.defaultFontStyle; // e.g. FontStyles.Bold
  603. }
  604. if (options.drawUpToMeasureNumber) {
  605. this.rules.MaxMeasureToDrawIndex = options.drawUpToMeasureNumber - 1;
  606. }
  607. if (options.drawFromMeasureNumber) {
  608. this.rules.MinMeasureToDrawIndex = options.drawFromMeasureNumber - 1;
  609. }
  610. if (options.drawUpToPageNumber) {
  611. this.rules.MaxPageToDrawNumber = options.drawUpToPageNumber;
  612. }
  613. if (options.drawUpToSystemNumber) {
  614. this.rules.MaxSystemToDrawNumber = options.drawUpToSystemNumber;
  615. }
  616. if (options.tupletsRatioed) {
  617. this.rules.TupletsRatioed = true;
  618. }
  619. if (options.tupletsBracketed) {
  620. this.rules.TupletsBracketed = true;
  621. }
  622. if (options.tripletsBracketed) {
  623. this.rules.TripletsBracketed = true;
  624. }
  625. if (options.autoResize) {
  626. if (!this.resizeHandlerAttached) {
  627. this.autoResize();
  628. }
  629. this.autoResizeEnabled = true;
  630. } else if (options.autoResize === false) { // not undefined
  631. this.autoResizeEnabled = false;
  632. // we could remove the window EventListener here, but not necessary.
  633. }
  634. if (options.pageFormat !== undefined) { // only change this option if it was given, see above
  635. this.setPageFormat(options.pageFormat);
  636. }
  637. if (options.pageBackgroundColor !== undefined) {
  638. this.rules.PageBackgroundColor = options.pageBackgroundColor;
  639. }
  640. if (options.performanceMode !== undefined) {
  641. this.rules.PerformanceMode = options.performanceMode;
  642. }
  643. if (options.renderSingleHorizontalStaffline !== undefined) {
  644. this.rules.RenderSingleHorizontalStaffline = options.renderSingleHorizontalStaffline;
  645. }
  646. if (options.spacingFactorSoftmax !== undefined) {
  647. this.rules.SoftmaxFactorVexFlow = options.spacingFactorSoftmax;
  648. }
  649. if (options.spacingBetweenTextLines !== undefined) {
  650. this.rules.SpacingBetweenTextLines = options.spacingBetweenTextLines;
  651. }
  652. if (options.stretchLastSystemLine !== undefined) {
  653. this.rules.StretchLastSystemLine = options.stretchLastSystemLine;
  654. }
  655. if (options.autoGenerateMutipleRestMeasuresFromRestMeasures !== undefined) {
  656. this.rules.AutoGenerateMutipleRestMeasuresFromRestMeasures = options.autoGenerateMutipleRestMeasuresFromRestMeasures;
  657. }
  658. if (options.cursorsOptions !== undefined) {
  659. this.cursorsOptions = options.cursorsOptions;
  660. } else {
  661. this.cursorsOptions = [{type: 0, color: this.EngravingRules.DefaultColorCursor, alpha: 0.5, follow: true}];
  662. }
  663. if (options.preferredSkyBottomLineBatchCalculatorBackend !== undefined) {
  664. this.rules.PreferredSkyBottomLineBatchCalculatorBackend = options.preferredSkyBottomLineBatchCalculatorBackend;
  665. }
  666. if (options.skyBottomLineBatchMinMeasures !== undefined) {
  667. this.rules.SkyBottomLineBatchMinMeasures = options.skyBottomLineBatchMinMeasures;
  668. }
  669. }
  670. public setColoringMode(options: IOSMDOptions): void {
  671. if (options.coloringMode === ColoringModes.XML) {
  672. this.rules.ColoringMode = ColoringModes.XML;
  673. return;
  674. }
  675. const noteIndices: NoteEnum[] = [NoteEnum.C, NoteEnum.D, NoteEnum.E, NoteEnum.F, NoteEnum.G, NoteEnum.A, NoteEnum.B, -1];
  676. let colorSetString: string[];
  677. if (options.coloringMode === ColoringModes.CustomColorSet) {
  678. if (!options.coloringSetCustom || options.coloringSetCustom.length !== 8) {
  679. throw new Error("Invalid amount of colors: With coloringModes.customColorSet, " +
  680. "you have to provide a coloringSetCustom parameter with 8 strings (C to B, rest note).");
  681. }
  682. // validate strings input
  683. for (const colorString of options.coloringSetCustom) {
  684. const regExp: RegExp = /^\#[0-9a-fA-F]{6}$/;
  685. if (!regExp.test(colorString)) {
  686. throw new Error(
  687. "One of the color strings in options.coloringSetCustom was not a valid HTML Hex color:\n" + colorString);
  688. }
  689. }
  690. colorSetString = options.coloringSetCustom;
  691. } else if (options.coloringMode === ColoringModes.AutoColoring) {
  692. colorSetString = [];
  693. const keys: string[] = Object.keys(AutoColorSet);
  694. for (let i: number = 0; i < keys.length; i++) {
  695. colorSetString.push(AutoColorSet[keys[i]]);
  696. }
  697. } // for both cases:
  698. const coloringSetCurrent: Dictionary<NoteEnum | number, string> = new Dictionary<NoteEnum | number, string>();
  699. for (let i: number = 0; i < noteIndices.length; i++) {
  700. coloringSetCurrent.setValue(noteIndices[i], colorSetString[i]);
  701. }
  702. coloringSetCurrent.setValue(-1, colorSetString[7]);
  703. this.rules.ColoringSetCurrent = coloringSetCurrent;
  704. this.rules.ColoringMode = options.coloringMode;
  705. }
  706. /**
  707. * Sets the logging level for this OSMD instance. By default, this is set to `warn`.
  708. *
  709. * @param: content can be `trace`, `debug`, `info`, `warn` or `error`.
  710. */
  711. public setLogLevel(level: string): void {
  712. switch (level) {
  713. case "trace":
  714. log.setLevel(log.levels.TRACE);
  715. break;
  716. case "debug":
  717. log.setLevel(log.levels.DEBUG);
  718. break;
  719. case "info":
  720. log.setLevel(log.levels.INFO);
  721. break;
  722. case "warn":
  723. log.setLevel(log.levels.WARN);
  724. break;
  725. case "error":
  726. log.setLevel(log.levels.ERROR);
  727. break;
  728. case "silent":
  729. log.setLevel(log.levels.SILENT);
  730. break;
  731. default:
  732. log.warn(`Could not set log level to ${level}. Using warn instead.`);
  733. log.setLevel(log.levels.WARN);
  734. break;
  735. }
  736. }
  737. public getLogLevel(): number {
  738. return log.getLevel();
  739. }
  740. /**
  741. * Initialize this object to default values
  742. * FIXME: Probably unnecessary
  743. */
  744. protected reset(): void {
  745. if (this.drawingParameters.drawCursors) {
  746. this.cursors.forEach(cursor => {
  747. cursor.hide();
  748. });
  749. }
  750. this.sheet = undefined;
  751. this.graphic = undefined;
  752. this.zoom = 1.0;
  753. }
  754. /**
  755. * Attach the appropriate handler to the window.onResize event
  756. */
  757. protected autoResize(): void {
  758. const self: OpenSheetMusicDisplay = this;
  759. this.handleResize(
  760. () => {
  761. // empty
  762. },
  763. () => {
  764. // The following code is probably not needed
  765. // (the width should adapt itself to the max allowed)
  766. //let width: number = Math.max(
  767. // document.documentElement.clientWidth,
  768. // document.body.scrollWidth,
  769. // document.documentElement.scrollWidth,
  770. // document.body.offsetWidth,
  771. // document.documentElement.offsetWidth
  772. //);
  773. //self.container.style.width = width + "px";
  774. // recalculate beams, are otherwise not updated and can detach from stems, see #724
  775. if (this.graphic?.GetCalculator instanceof VexFlowMusicSheetCalculator) { // null and type check
  776. (this.graphic.GetCalculator as VexFlowMusicSheetCalculator).beamsNeedUpdate = true;
  777. }
  778. if (self.IsReadyToRender()) {
  779. self.render();
  780. }
  781. }
  782. );
  783. }
  784. /**
  785. * Helper function for managing window's onResize events
  786. * @param startCallback is the function called when resizing starts
  787. * @param endCallback is the function called when resizing (kind-of) ends
  788. */
  789. protected handleResize(startCallback: () => void, endCallback: () => void): void {
  790. let rtime: number;
  791. let timeout: number = undefined;
  792. const delta: number = 200;
  793. const self: OpenSheetMusicDisplay = this;
  794. function resizeStart(): void {
  795. if (!self.AutoResizeEnabled) {
  796. return;
  797. }
  798. rtime = (new Date()).getTime();
  799. if (!timeout) {
  800. startCallback();
  801. rtime = (new Date()).getTime();
  802. timeout = window.setTimeout(resizeEnd, delta);
  803. }
  804. }
  805. function resizeEnd(): void {
  806. timeout = undefined;
  807. window.clearTimeout(timeout);
  808. if ((new Date()).getTime() - rtime < delta) {
  809. timeout = window.setTimeout(resizeEnd, delta);
  810. } else {
  811. endCallback();
  812. }
  813. }
  814. if ((<any>window).attachEvent) {
  815. // Support IE<9
  816. (<any>window).attachEvent("onresize", resizeStart);
  817. } else {
  818. window.addEventListener("resize", resizeStart);
  819. }
  820. this.disposeResizeListener = (): void => {
  821. if ((<any>window).detachEvent) {
  822. // Support IE<9
  823. (<any>window).detachEvent ("onresize", resizeStart);
  824. } else {
  825. window.removeEventListener("resize", resizeStart);
  826. }
  827. this.resizeHandlerAttached = false;
  828. };
  829. this.resizeHandlerAttached = true;
  830. window.setTimeout(startCallback, 0);
  831. window.setTimeout(endCallback, 1);
  832. }
  833. /** Enable or disable (hide) the cursor.
  834. * @param enable whether to enable (true) or disable (false) the cursor
  835. */
  836. public enableOrDisableCursors(enable: boolean): void {
  837. this.drawingParameters.drawCursors = enable;
  838. if (enable) {
  839. for (let i: number = 0; i < this.cursorsOptions.length; i++){
  840. // save previous cursor state
  841. const hidden: boolean = this.cursors[i]?.Hidden ?? false;
  842. const previousIterator: MusicPartManagerIterator = this.cursors[i]?.Iterator;
  843. this.cursors[i]?.hide();
  844. // check which page/backend to draw the cursor on (the pages may have changed since last cursor)
  845. let backendToDrawOn: VexFlowBackend = this.drawer?.Backends[0];
  846. if (backendToDrawOn && this.rules.RestoreCursorAfterRerender && this.cursors[i]) {
  847. const newPageNumber: number = this.cursors[i].updateCurrentPage();
  848. backendToDrawOn = this.drawer.Backends[newPageNumber - 1];
  849. }
  850. // create new cursor
  851. if (backendToDrawOn && backendToDrawOn.getRenderElement()) {
  852. if (this.cursors[i]) {
  853. this.PlaybackManager?.removeListener(this.cursors[i]);
  854. this.cursors[i].Dispose();
  855. }
  856. this.cursors[i] = new Cursor(backendToDrawOn.getRenderElement(), this, this.cursorsOptions[i]);
  857. }
  858. if (this.sheet && this.graphic && this.cursors[i]) { // else init is called in load()
  859. this.cursors[i].init(this.sheet.MusicPartManager, this.graphic);
  860. }
  861. // restore old cursor state
  862. if (this.rules.RestoreCursorAfterRerender) {
  863. if (previousIterator) {
  864. this.cursors[i].iterator = previousIterator;
  865. // this.cursors[i].update();
  866. }
  867. if (hidden) {
  868. this.cursors[i].hide();
  869. } else {
  870. this.cursors[i].show();
  871. }
  872. }
  873. }
  874. this.renderingManager.PlaybackManager?.addListener(this.cursor);
  875. } else { // disable cursor
  876. this.cursors.forEach(cursor => {
  877. cursor.hide();
  878. });
  879. // this.cursor = undefined;
  880. // TODO cursor should be disabled, not just hidden. otherwise user can just call osmd.cursor.hide().
  881. // however, this could cause null calls (cursor.next() etc), maybe that needs some solution.
  882. }
  883. }
  884. public createBackend(type: BackendType, page: GraphicalMusicPage): VexFlowBackend {
  885. let backend: VexFlowBackend;
  886. if (type === undefined || type === BackendType.SVG) {
  887. backend = new SvgVexFlowBackend(this.rules);
  888. } else {
  889. backend = new CanvasVexFlowBackend(this.rules);
  890. }
  891. backend.graphicalMusicPage = page; // the page the backend renders on. needed to identify DOM element to extract image/SVG
  892. backend.initialize(this.container, this.zoom);
  893. //backend.getContext().setFillStyle(this.rules.DefaultColorMusic);
  894. //backend.getContext().setStrokeStyle(this.rules.DefaultColorMusic);
  895. // color needs to be set after resize() for CanvasBackend
  896. return backend;
  897. }
  898. /** Standard page format options like A4 or Letter, in portrait and landscape. E.g. PageFormatStandards["A4_P"] or PageFormatStandards["Letter_L"]. */
  899. public static PageFormatStandards: { [type: string]: PageFormat } = {
  900. "A3_L": new PageFormat(420, 297, "A3_L"), // id strings should use underscores instead of white spaces to facilitate use as URL parameters.
  901. "A3_P": new PageFormat(297, 420, "A3_P"),
  902. "A4_L": new PageFormat(297, 210, "A4_L"),
  903. "A4_P": new PageFormat(210, 297, "A4_P"),
  904. "A5_L": new PageFormat(210, 148, "A5_L"),
  905. "A5_P": new PageFormat(148, 210, "A5_P"),
  906. "A6_L": new PageFormat(148, 105, "A6_L"),
  907. "A6_P": new PageFormat(105, 148, "A6_P"),
  908. "Endless": PageFormat.UndefinedPageFormat,
  909. "Letter_L": new PageFormat(279.4, 215.9, "Letter_L"),
  910. "Letter_P": new PageFormat(215.9, 279.4, "Letter_P")
  911. };
  912. public static StringToPageFormat(pageFormatString: string): PageFormat {
  913. let pageFormat: PageFormat = PageFormat.UndefinedPageFormat; // default: 'endless' page height, take canvas/container width
  914. // check for widthxheight parameter, e.g. "800x600"
  915. if (pageFormatString.match("^[0-9]+x[0-9]+$")) {
  916. const widthAndHeight: string[] = pageFormatString.split("x");
  917. const width: number = Number.parseInt(widthAndHeight[0], 10);
  918. const height: number = Number.parseInt(widthAndHeight[1], 10);
  919. if (width > 0 && width < 32768 && height > 0 && height < 32768) {
  920. pageFormat = new PageFormat(width, height, `customPageFormat${pageFormatString}`);
  921. }
  922. }
  923. // check for formatId from OpenSheetMusicDisplay.PageFormatStandards
  924. pageFormatString = pageFormatString.replace(" ", "_");
  925. pageFormatString = pageFormatString.replace("Landscape", "L");
  926. pageFormatString = pageFormatString.replace("Portrait", "P");
  927. //console.log("change format to: " + formatId);
  928. if (OpenSheetMusicDisplay.PageFormatStandards.hasOwnProperty(pageFormatString)) {
  929. pageFormat = OpenSheetMusicDisplay.PageFormatStandards[pageFormatString];
  930. return pageFormat;
  931. }
  932. return pageFormat;
  933. }
  934. /** Sets page format by string. Used by setOptions({pageFormat: "A4_P"}) for example. */
  935. public setPageFormat(formatId: string): void {
  936. const newPageFormat: PageFormat = OpenSheetMusicDisplay.StringToPageFormat(formatId);
  937. this.needBackendUpdate = !(newPageFormat.Equals(this.rules.PageFormat));
  938. this.rules.PageFormat = newPageFormat;
  939. }
  940. public setCustomPageFormat(width: number, height: number): void {
  941. if (width > 0 && height > 0) {
  942. const f: PageFormat = new PageFormat(width, height);
  943. this.rules.PageFormat = f;
  944. }
  945. }
  946. //#region GETTER / SETTER
  947. public set DrawSkyLine(value: boolean) {
  948. this.drawSkyLine = value;
  949. if (this.drawer) {
  950. this.drawer.skyLineVisible = value;
  951. // this.render(); // note: we probably shouldn't automatically render when someone sets the setter
  952. // this can cause a lot of rendering time.
  953. }
  954. }
  955. public get DrawSkyLine(): boolean {
  956. return this.drawer.skyLineVisible;
  957. }
  958. public set DrawBottomLine(value: boolean) {
  959. this.drawBottomLine = value;
  960. if (this.drawer) {
  961. this.drawer.bottomLineVisible = value;
  962. // this.render(); // note: we probably shouldn't automatically render when someone sets the setter
  963. // this can cause a lot of rendering time.
  964. }
  965. }
  966. public get DrawBottomLine(): boolean {
  967. return this.drawer.bottomLineVisible;
  968. }
  969. public set DrawBoundingBox(value: string) {
  970. this.setDrawBoundingBox(value, true);
  971. }
  972. public get DrawBoundingBox(): string {
  973. return this.drawBoundingBox;
  974. }
  975. public setDrawBoundingBox(value: string, render: boolean = false): void {
  976. this.drawBoundingBox = value;
  977. if (this.drawer) {
  978. this.drawer.drawableBoundingBoxElement = value; // drawer is sometimes created anew, losing this value, so it's saved in OSMD now.
  979. }
  980. if (render) {
  981. this.render(); // may create new Drawer.
  982. }
  983. }
  984. public get AutoResizeEnabled(): boolean {
  985. return this.autoResizeEnabled;
  986. }
  987. public set AutoResizeEnabled(value: boolean) {
  988. this.autoResizeEnabled = value;
  989. }
  990. public get Zoom(): number {
  991. return this.zoom;
  992. }
  993. public set Zoom(value: number) {
  994. this.zoom = value;
  995. this.zoomUpdated = true;
  996. if (this.graphic?.GetCalculator instanceof VexFlowMusicSheetCalculator) { // null and type check
  997. (this.graphic.GetCalculator as VexFlowMusicSheetCalculator).beamsNeedUpdate = this.zoomUpdated;
  998. }
  999. }
  1000. public set FollowCursor(value: boolean) {
  1001. this.followCursor = value;
  1002. }
  1003. public get FollowCursor(): boolean {
  1004. return this.followCursor;
  1005. }
  1006. public set TransposeCalculator(calculator: ITransposeCalculator) {
  1007. MusicSheetCalculator.transposeCalculator = calculator;
  1008. }
  1009. public get TransposeCalculator(): ITransposeCalculator {
  1010. return MusicSheetCalculator.transposeCalculator;
  1011. }
  1012. public get Sheet(): MusicSheet {
  1013. return this.sheet;
  1014. }
  1015. public get Drawer(): VexFlowMusicSheetDrawer {
  1016. return this.drawer;
  1017. }
  1018. public get GraphicSheet(): GraphicalMusicSheet {
  1019. return this.graphic;
  1020. }
  1021. public get DrawingParameters(): DrawingParameters {
  1022. return this.drawingParameters;
  1023. }
  1024. public get EngravingRules(): EngravingRules { // custom getter, useful for engraving parameter setting in Demo
  1025. return this.rules;
  1026. }
  1027. public get InteractionManager(): AbstractDisplayInteractionManager {
  1028. return this.interactionManager;
  1029. }
  1030. /** Returns the version of OSMD this object is built from (the version you are using). */
  1031. public get Version(): string {
  1032. return this.version;
  1033. }
  1034. //#endregion
  1035. }