OpenSheetMusicDisplay.ts 42 KB

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