OpenSheetMusicDisplay.ts 52 KB

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