OSMD.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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 {Promise} from "es6-promise";
  14. import {AJAX} from "./AJAX";
  15. import * as log from "loglevel";
  16. export class OSMD {
  17. /**
  18. * The easy way of displaying a MusicXML sheet music file
  19. * @param container is either the ID, or the actual "div" element which will host the music sheet
  20. * @autoResize automatically resize the sheet to full page width on window resize
  21. */
  22. constructor(container: string|HTMLElement, autoResize: boolean = false, backend: string = "svg") {
  23. // Store container element
  24. if (typeof container === "string") {
  25. // ID passed
  26. this.container = document.getElementById(<string>container);
  27. } else if (container && "appendChild" in <any>container) {
  28. // Element passed
  29. this.container = <HTMLElement>container;
  30. }
  31. if (!this.container) {
  32. throw new Error("Please pass a valid div container to OSMD");
  33. }
  34. if (backend === "svg") {
  35. this.backend = new SvgVexFlowBackend();
  36. } else {
  37. this.backend = new CanvasVexFlowBackend();
  38. }
  39. this.backend.initialize(this.container);
  40. this.canvas = this.backend.getCanvas();
  41. const inner: HTMLElement = this.backend.getInnerElement();
  42. // Create the drawer
  43. this.drawer = new VexFlowMusicSheetDrawer(this.canvas, this.backend, false);
  44. // Create the cursor
  45. this.cursor = new Cursor(inner, this);
  46. if (autoResize) {
  47. this.autoResize();
  48. }
  49. }
  50. public cursor: Cursor;
  51. public zoom: number = 1.0;
  52. private container: HTMLElement;
  53. private canvas: HTMLElement;
  54. private backend: VexFlowBackend;
  55. private sheet: MusicSheet;
  56. private drawer: VexFlowMusicSheetDrawer;
  57. private graphic: GraphicalMusicSheet;
  58. /**
  59. * Load a MusicXML file
  60. * @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
  61. */
  62. public load(content: string|Document): Promise<{}> {
  63. // Warning! This function is asynchronous! No error handling is done here.
  64. this.reset();
  65. if (typeof content === "string") {
  66. const str: string = <string>content;
  67. const self: OSMD = this;
  68. if (str.substr(0, 4) === "\x50\x4b\x03\x04") {
  69. // This is a zip file, unpack it first
  70. return MXLHelper.MXLtoXMLstring(str).then(
  71. (x: string) => {
  72. return self.load(x);
  73. },
  74. (err: any) => {
  75. log.debug(err);
  76. throw new Error("OSMD: Invalid MXL file");
  77. }
  78. );
  79. }
  80. if (str.substr(0, 5) === "<?xml") {
  81. // Parse the string representing an xml file
  82. const parser: DOMParser = new DOMParser();
  83. content = parser.parseFromString(str, "text/xml");
  84. } else if (str.length < 2083) {
  85. // Assume now "str" is a URL
  86. // Retrieve the file at the given URL
  87. return AJAX.ajax(str).then(
  88. (s: string) => { return self.load(s); },
  89. (exc: Error) => { throw exc; }
  90. );
  91. }
  92. }
  93. if (!content || !(<any>content).nodeName) {
  94. return Promise.reject(new Error("OSMD: The document which was provided is invalid"));
  95. }
  96. const children: NodeList = (<Document>content).childNodes;
  97. let elem: Element;
  98. for (let i: number = 0, length: number = children.length; i < length; i += 1) {
  99. const node: Node = children[i];
  100. if (node.nodeType === Node.ELEMENT_NODE && node.nodeName.toLowerCase() === "score-partwise") {
  101. elem = <Element>node;
  102. break;
  103. }
  104. }
  105. if (!elem) {
  106. return Promise.reject(new Error("OSMD: Document is not a valid 'partwise' MusicXML"));
  107. }
  108. const score: IXmlElement = new IXmlElement(elem);
  109. const calc: MusicSheetCalculator = new VexFlowMusicSheetCalculator();
  110. const reader: MusicSheetReader = new MusicSheetReader();
  111. this.sheet = reader.createMusicSheet(score, "Unknown path");
  112. this.graphic = new GraphicalMusicSheet(this.sheet, calc);
  113. this.cursor.init(this.sheet.MusicPartManager, this.graphic);
  114. log.info(`Loaded sheet ${this.sheet.TitleString} successfully.`);
  115. return Promise.resolve({});
  116. }
  117. /**
  118. * Render the music sheet in the container
  119. */
  120. public render(): void {
  121. if (!this.graphic) {
  122. throw new Error("OSMD: Before rendering a music sheet, please load a MusicXML file");
  123. }
  124. const width: number = this.container.offsetWidth;
  125. // Before introducing the following optimization (maybe irrelevant), tests
  126. // have to be modified to ensure that width is > 0 when executed
  127. //if (isNaN(width) || width === 0) {
  128. // return;
  129. //}
  130. // Set page width
  131. this.sheet.pageWidth = width / this.zoom / 10.0;
  132. // Calculate again
  133. this.graphic.reCalculate();
  134. this.graphic.Cursors.length = 0;
  135. /*this.graphic.Cursors.push(this.graphic.calculateCursorLineAtTimestamp(new Fraction(0, 4), OutlineAndFillStyleEnum.PlaybackCursor));
  136. this.graphic.Cursors.push(this.graphic.calculateCursorLineAtTimestamp(new Fraction(1, 4), OutlineAndFillStyleEnum.PlaybackCursor));
  137. this.graphic.Cursors.push(this.graphic.calculateCursorLineAtTimestamp(new Fraction(2, 4), OutlineAndFillStyleEnum.PlaybackCursor));
  138. this.graphic.Cursors.push(this.graphic.calculateCursorLineAtTimestamp(new Fraction(3, 4), OutlineAndFillStyleEnum.PlaybackCursor));
  139. this.graphic.Cursors.push(this.graphic.calculateCursorLineAtTimestamp(new Fraction(4, 4), OutlineAndFillStyleEnum.PlaybackCursor));
  140. this.graphic.Cursors.push(this.graphic.calculateCursorLineAtTimestamp(new Fraction(5, 4), OutlineAndFillStyleEnum.PlaybackCursor));
  141. this.graphic.Cursors.push(this.graphic.calculateCursorLineAtTimestamp(new Fraction(6, 4), OutlineAndFillStyleEnum.PlaybackCursor));
  142. this.graphic.Cursors.push(this.graphic.calculateCursorLineAtTimestamp(new Fraction(7, 4), OutlineAndFillStyleEnum.PlaybackCursor));*/
  143. // Update Sheet Page
  144. const height: number = this.graphic.MusicPages[0].PositionAndShape.BorderBottom * 10.0 * this.zoom;
  145. this.drawer.clear();
  146. this.drawer.resize(width, height);
  147. this.drawer.scale(this.zoom);
  148. // Finally, draw
  149. this.drawer.drawSheet(this.graphic);
  150. // Update the cursor position
  151. this.cursor.update();
  152. }
  153. /**
  154. * Sets the logging level for this OSMD instance. By default, this is set to `warn`.
  155. *
  156. * @param: content can be `trace`, `debug`, `info`, `warn` or `error`.
  157. */
  158. public setLogLevel(level: string): void {
  159. switch (level) {
  160. case "trace":
  161. log.setLevel(log.levels.WARN);
  162. break;
  163. case "debug":
  164. log.setLevel(log.levels.DEBUG);
  165. break;
  166. case "info":
  167. log.setLevel(log.levels.INFO);
  168. break;
  169. case "warn":
  170. log.setLevel(log.levels.WARN);
  171. break;
  172. case "error":
  173. log.setLevel(log.levels.ERROR);
  174. break;
  175. default:
  176. log.warn(`Could not set log level to ${level}. Using warn instead.`);
  177. log.setLevel(log.levels.WARN);
  178. break;
  179. }
  180. }
  181. /**
  182. * Initialize this object to default values
  183. * FIXME: Probably unnecessary
  184. */
  185. private reset(): void {
  186. this.cursor.hide();
  187. this.sheet = undefined;
  188. this.graphic = undefined;
  189. this.zoom = 1.0;
  190. // this.canvas.width = 0;
  191. // this.canvas.height = 0;
  192. }
  193. /**
  194. * Attach the appropriate handler to the window.onResize event
  195. */
  196. private autoResize(): void {
  197. const self: OSMD = this;
  198. this.handleResize(
  199. () => {
  200. // empty
  201. },
  202. () => {
  203. // The following code is probably not needed
  204. // (the width should adapt itself to the max allowed)
  205. //let width: number = Math.max(
  206. // document.documentElement.clientWidth,
  207. // document.body.scrollWidth,
  208. // document.documentElement.scrollWidth,
  209. // document.body.offsetWidth,
  210. // document.documentElement.offsetWidth
  211. //);
  212. //self.container.style.width = width + "px";
  213. self.render();
  214. }
  215. );
  216. }
  217. /**
  218. * Helper function for managing window's onResize events
  219. * @param startCallback is the function called when resizing starts
  220. * @param endCallback is the function called when resizing (kind-of) ends
  221. */
  222. private handleResize(startCallback: () => void, endCallback: () => void): void {
  223. let rtime: number;
  224. let timeout: number = undefined;
  225. const delta: number = 200;
  226. function resizeEnd(): void {
  227. timeout = undefined;
  228. window.clearTimeout(timeout);
  229. if ((new Date()).getTime() - rtime < delta) {
  230. timeout = window.setTimeout(resizeEnd, delta);
  231. } else {
  232. endCallback();
  233. }
  234. }
  235. function resizeStart(): void {
  236. rtime = (new Date()).getTime();
  237. if (!timeout) {
  238. startCallback();
  239. rtime = (new Date()).getTime();
  240. timeout = window.setTimeout(resizeEnd, delta);
  241. }
  242. }
  243. if ((<any>window).attachEvent) {
  244. // Support IE<9
  245. (<any>window).attachEvent("onresize", resizeStart);
  246. } else {
  247. window.addEventListener("resize", resizeStart);
  248. }
  249. window.setTimeout(startCallback, 0);
  250. window.setTimeout(endCallback, 1);
  251. }
  252. }