OpenSheetMusicDisplay.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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 OpenSheetMusicDisplay {
  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 OpenSheetMusicDisplay");
  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: OpenSheetMusicDisplay = 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("OpenSheetMusicDisplay: Invalid MXL file");
  77. }
  78. );
  79. }
  80. // Javascript loads strings as utf-16, which is wonderful BS if you want to parse UTF-8 :S
  81. if (str.substr(0, 3) === "\uf7ef\uf7bb\uf7bf") {
  82. // UTF with BOM detected, truncate first three bytes and pass along
  83. return self.load(str.substr(3));
  84. }
  85. if (str.substr(0, 5) === "<?xml") {
  86. // Parse the string representing an xml file
  87. const parser: DOMParser = new DOMParser();
  88. content = parser.parseFromString(str, "application/xml");
  89. } else if (str.length < 2083) {
  90. // Assume now "str" is a URL
  91. // Retrieve the file at the given URL
  92. return AJAX.ajax(str).then(
  93. (s: string) => { return self.load(s); },
  94. (exc: Error) => { throw exc; }
  95. );
  96. }
  97. }
  98. if (!content || !(<any>content).nodeName) {
  99. return Promise.reject(new Error("OpenSheetMusicDisplay: The document which was provided is invalid"));
  100. }
  101. const children: NodeList = (<Document>content).childNodes;
  102. let elem: Element;
  103. for (let i: number = 0, length: number = children.length; i < length; i += 1) {
  104. const node: Node = children[i];
  105. if (node.nodeType === Node.ELEMENT_NODE && node.nodeName.toLowerCase() === "score-partwise") {
  106. elem = <Element>node;
  107. break;
  108. }
  109. }
  110. if (!elem) {
  111. return Promise.reject(new Error("OpenSheetMusicDisplay: Document is not a valid 'partwise' MusicXML"));
  112. }
  113. const score: IXmlElement = new IXmlElement(elem);
  114. const calc: MusicSheetCalculator = new VexFlowMusicSheetCalculator();
  115. const reader: MusicSheetReader = new MusicSheetReader();
  116. this.sheet = reader.createMusicSheet(score, "Unknown path");
  117. this.graphic = new GraphicalMusicSheet(this.sheet, calc);
  118. this.cursor.init(this.sheet.MusicPartManager, this.graphic);
  119. log.info(`Loaded sheet ${this.sheet.TitleString} successfully.`);
  120. return Promise.resolve({});
  121. }
  122. /**
  123. * Render the music sheet in the container
  124. */
  125. public render(): void {
  126. if (!this.graphic) {
  127. throw new Error("OpenSheetMusicDisplay: Before rendering a music sheet, please load a MusicXML file");
  128. }
  129. const width: number = this.container.offsetWidth;
  130. // Before introducing the following optimization (maybe irrelevant), tests
  131. // have to be modified to ensure that width is > 0 when executed
  132. //if (isNaN(width) || width === 0) {
  133. // return;
  134. //}
  135. // Set page width
  136. this.sheet.pageWidth = width / this.zoom / 10.0;
  137. // Calculate again
  138. this.graphic.reCalculate();
  139. this.graphic.Cursors.length = 0;
  140. /*this.graphic.Cursors.push(this.graphic.calculateCursorLineAtTimestamp(new Fraction(0, 4), OutlineAndFillStyleEnum.PlaybackCursor));
  141. this.graphic.Cursors.push(this.graphic.calculateCursorLineAtTimestamp(new Fraction(1, 4), OutlineAndFillStyleEnum.PlaybackCursor));
  142. this.graphic.Cursors.push(this.graphic.calculateCursorLineAtTimestamp(new Fraction(2, 4), OutlineAndFillStyleEnum.PlaybackCursor));
  143. this.graphic.Cursors.push(this.graphic.calculateCursorLineAtTimestamp(new Fraction(3, 4), OutlineAndFillStyleEnum.PlaybackCursor));
  144. this.graphic.Cursors.push(this.graphic.calculateCursorLineAtTimestamp(new Fraction(4, 4), OutlineAndFillStyleEnum.PlaybackCursor));
  145. this.graphic.Cursors.push(this.graphic.calculateCursorLineAtTimestamp(new Fraction(5, 4), OutlineAndFillStyleEnum.PlaybackCursor));
  146. this.graphic.Cursors.push(this.graphic.calculateCursorLineAtTimestamp(new Fraction(6, 4), OutlineAndFillStyleEnum.PlaybackCursor));
  147. this.graphic.Cursors.push(this.graphic.calculateCursorLineAtTimestamp(new Fraction(7, 4), OutlineAndFillStyleEnum.PlaybackCursor));*/
  148. // Update Sheet Page
  149. const height: number = this.graphic.MusicPages[0].PositionAndShape.BorderBottom * 10.0 * this.zoom;
  150. this.drawer.clear();
  151. this.drawer.resize(width, height);
  152. this.drawer.scale(this.zoom);
  153. // Finally, draw
  154. this.drawer.drawSheet(this.graphic);
  155. // Update the cursor position
  156. this.cursor.update();
  157. }
  158. /**
  159. * Sets the logging level for this OSMD instance. By default, this is set to `warn`.
  160. *
  161. * @param: content can be `trace`, `debug`, `info`, `warn` or `error`.
  162. */
  163. public setLogLevel(level: string): void {
  164. switch (level) {
  165. case "trace":
  166. log.setLevel(log.levels.WARN);
  167. break;
  168. case "debug":
  169. log.setLevel(log.levels.DEBUG);
  170. break;
  171. case "info":
  172. log.setLevel(log.levels.INFO);
  173. break;
  174. case "warn":
  175. log.setLevel(log.levels.WARN);
  176. break;
  177. case "error":
  178. log.setLevel(log.levels.ERROR);
  179. break;
  180. default:
  181. log.warn(`Could not set log level to ${level}. Using warn instead.`);
  182. log.setLevel(log.levels.WARN);
  183. break;
  184. }
  185. }
  186. /**
  187. * Initialize this object to default values
  188. * FIXME: Probably unnecessary
  189. */
  190. private reset(): void {
  191. this.cursor.hide();
  192. this.sheet = undefined;
  193. this.graphic = undefined;
  194. this.zoom = 1.0;
  195. // this.canvas.width = 0;
  196. // this.canvas.height = 0;
  197. }
  198. /**
  199. * Attach the appropriate handler to the window.onResize event
  200. */
  201. private autoResize(): void {
  202. const self: OpenSheetMusicDisplay = this;
  203. this.handleResize(
  204. () => {
  205. // empty
  206. },
  207. () => {
  208. // The following code is probably not needed
  209. // (the width should adapt itself to the max allowed)
  210. //let width: number = Math.max(
  211. // document.documentElement.clientWidth,
  212. // document.body.scrollWidth,
  213. // document.documentElement.scrollWidth,
  214. // document.body.offsetWidth,
  215. // document.documentElement.offsetWidth
  216. //);
  217. //self.container.style.width = width + "px";
  218. self.render();
  219. }
  220. );
  221. }
  222. /**
  223. * Helper function for managing window's onResize events
  224. * @param startCallback is the function called when resizing starts
  225. * @param endCallback is the function called when resizing (kind-of) ends
  226. */
  227. private handleResize(startCallback: () => void, endCallback: () => void): void {
  228. let rtime: number;
  229. let timeout: number = undefined;
  230. const delta: number = 200;
  231. function resizeEnd(): void {
  232. timeout = undefined;
  233. window.clearTimeout(timeout);
  234. if ((new Date()).getTime() - rtime < delta) {
  235. timeout = window.setTimeout(resizeEnd, delta);
  236. } else {
  237. endCallback();
  238. }
  239. }
  240. function resizeStart(): void {
  241. rtime = (new Date()).getTime();
  242. if (!timeout) {
  243. startCallback();
  244. rtime = (new Date()).getTime();
  245. timeout = window.setTimeout(resizeEnd, delta);
  246. }
  247. }
  248. if ((<any>window).attachEvent) {
  249. // Support IE<9
  250. (<any>window).attachEvent("onresize", resizeStart);
  251. } else {
  252. window.addEventListener("resize", resizeStart);
  253. }
  254. window.setTimeout(startCallback, 0);
  255. window.setTimeout(endCallback, 1);
  256. }
  257. }