OpenSheetMusicDisplay.ts 46 KB

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