OpenSheetMusicDisplay.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. import {DrawingParametersEnum, DrawingParameters} from "../MusicalScore/Graphical/DrawingParameters";
  17. import {IOSMDOptions, OSMDOptions, AutoBeamOptions} from "./OSMDOptions";
  18. import {EngravingRules} from "../MusicalScore/Graphical/EngravingRules";
  19. import {AbstractExpression} from "../MusicalScore/VoiceData/Expressions/AbstractExpression";
  20. /**
  21. * The main class and control point of OpenSheetMusicDisplay.<br>
  22. * It can display MusicXML sheet music files in an HTML element container.<br>
  23. * After the constructor, use load() and render() to load and render a MusicXML file.
  24. */
  25. export class OpenSheetMusicDisplay {
  26. private version: string = "0.6.7-release"; // getter: this.Version
  27. /**
  28. * Creates and attaches an OpenSheetMusicDisplay object to an HTML element container.<br>
  29. * After the constructor, use load() and render() to load and render a MusicXML file.
  30. * @param container The container element OSMD will be rendered into.<br>
  31. * Either a string specifying the ID of an HTML container element,<br>
  32. * or a reference to the HTML element itself (e.g. div)
  33. * @param options An object for rendering options like the backend (svg/canvas) or autoResize.<br>
  34. * For defaults see the OSMDOptionsStandard method in the [[OSMDOptions]] class.
  35. */
  36. constructor(container: string|HTMLElement,
  37. options: IOSMDOptions = OSMDOptions.OSMDOptionsStandard()) {
  38. // Store container element
  39. if (typeof container === "string") {
  40. // ID passed
  41. this.container = document.getElementById(<string>container);
  42. } else if (container && "appendChild" in <any>container) {
  43. // Element passed
  44. this.container = <HTMLElement>container;
  45. }
  46. if (!this.container) {
  47. throw new Error("Please pass a valid div container to OpenSheetMusicDisplay");
  48. }
  49. if (options.autoResize === undefined) {
  50. options.autoResize = true;
  51. }
  52. this.setOptions(options);
  53. }
  54. public cursor: Cursor;
  55. public zoom: number = 1.0;
  56. private container: HTMLElement;
  57. private canvas: HTMLElement;
  58. private backend: VexFlowBackend;
  59. private innerElement: HTMLElement;
  60. private sheet: MusicSheet;
  61. private drawer: VexFlowMusicSheetDrawer;
  62. private graphic: GraphicalMusicSheet;
  63. private drawingParameters: DrawingParameters;
  64. private autoResizeEnabled: boolean;
  65. private resizeHandlerAttached: boolean;
  66. /**
  67. * Load a MusicXML file
  68. * @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
  69. */
  70. public load(content: string|Document): Promise<{}> {
  71. // Warning! This function is asynchronous! No error handling is done here.
  72. this.reset();
  73. if (typeof content === "string") {
  74. const str: string = <string>content;
  75. const self: OpenSheetMusicDisplay = this;
  76. if (str.substr(0, 4) === "\x50\x4b\x03\x04") {
  77. // This is a zip file, unpack it first
  78. return MXLHelper.MXLtoXMLstring(str).then(
  79. (x: string) => {
  80. return self.load(x);
  81. },
  82. (err: any) => {
  83. log.debug(err);
  84. throw new Error("OpenSheetMusicDisplay: Invalid MXL file");
  85. }
  86. );
  87. }
  88. // Javascript loads strings as utf-16, which is wonderful BS if you want to parse UTF-8 :S
  89. if (str.substr(0, 3) === "\uf7ef\uf7bb\uf7bf") {
  90. // UTF with BOM detected, truncate first three bytes and pass along
  91. return self.load(str.substr(3));
  92. }
  93. if (str.substr(0, 5) === "<?xml") {
  94. // Parse the string representing an xml file
  95. const parser: DOMParser = new DOMParser();
  96. content = parser.parseFromString(str, "application/xml");
  97. } else if (str.length < 2083) {
  98. // Assume now "str" is a URL
  99. // Retrieve the file at the given URL
  100. return AJAX.ajax(str).then(
  101. (s: string) => { return self.load(s); },
  102. (exc: Error) => { throw exc; }
  103. );
  104. }
  105. }
  106. if (!content || !(<any>content).nodeName) {
  107. return Promise.reject(new Error("OpenSheetMusicDisplay: The document which was provided is invalid"));
  108. }
  109. const children: NodeList = (<Document>content).childNodes;
  110. let elem: Element;
  111. for (let i: number = 0, length: number = children.length; i < length; i += 1) {
  112. const node: Node = children[i];
  113. if (node.nodeType === Node.ELEMENT_NODE && node.nodeName.toLowerCase() === "score-partwise") {
  114. elem = <Element>node;
  115. break;
  116. }
  117. }
  118. if (!elem) {
  119. return Promise.reject(new Error("OpenSheetMusicDisplay: Document is not a valid 'partwise' MusicXML"));
  120. }
  121. const score: IXmlElement = new IXmlElement(elem);
  122. const calc: MusicSheetCalculator = new VexFlowMusicSheetCalculator();
  123. const reader: MusicSheetReader = new MusicSheetReader();
  124. this.sheet = reader.createMusicSheet(score, "Untitled Score");
  125. if (this.sheet === undefined) {
  126. // error loading sheet, probably already logged, do nothing
  127. return Promise.reject(new Error("given music sheet was incomplete or could not be loaded."));
  128. }
  129. this.graphic = new GraphicalMusicSheet(this.sheet, calc);
  130. if (this.drawingParameters.drawCursors && this.cursor) {
  131. this.cursor.init(this.sheet.MusicPartManager, this.graphic);
  132. }
  133. log.info(`Loaded sheet ${this.sheet.TitleString} successfully.`);
  134. return Promise.resolve({});
  135. }
  136. /**
  137. * Render the music sheet in the container
  138. */
  139. public render(): void {
  140. if (!this.graphic) {
  141. throw new Error("OpenSheetMusicDisplay: Before rendering a music sheet, please load a MusicXML file");
  142. }
  143. this.drawer.clear(); // clear canvas before setting width
  144. // Set page width
  145. const width: number = this.container.offsetWidth;
  146. this.sheet.pageWidth = width / this.zoom / 10.0;
  147. // Before introducing the following optimization (maybe irrelevant), tests
  148. // have to be modified to ensure that width is > 0 when executed
  149. //if (isNaN(width) || width === 0) {
  150. // return;
  151. //}
  152. // Calculate again
  153. this.graphic.reCalculate();
  154. const height: number = this.graphic.MusicPages[0].PositionAndShape.BorderBottom * 10.0 * this.zoom;
  155. if (this.drawingParameters.drawCursors) {
  156. this.graphic.Cursors.length = 0;
  157. }
  158. // Update Sheet Page
  159. this.drawer.resize(width, height);
  160. this.drawer.scale(this.zoom);
  161. // Finally, draw
  162. this.drawer.drawSheet(this.graphic);
  163. if (this.drawingParameters.drawCursors && this.cursor) {
  164. // Update the cursor position
  165. this.cursor.update();
  166. }
  167. }
  168. /** States whether the render() function can be safely called. */
  169. public IsReadyToRender(): boolean {
  170. return this.graphic !== undefined;
  171. }
  172. /** Clears what OSMD has drawn on its canvas. */
  173. public clear(): void {
  174. this.drawer.clear();
  175. this.reset(); // without this, resize will draw loaded sheet again
  176. }
  177. /** Set OSMD rendering options using an IOSMDOptions object.
  178. * Can be called during runtime. Also called by constructor.
  179. * For example, setOptions({autoResize: false}) will disable autoResize even during runtime.
  180. */
  181. public setOptions(options: IOSMDOptions): void {
  182. this.drawingParameters = new DrawingParameters();
  183. if (options.drawingParameters) {
  184. this.drawingParameters.DrawingParametersEnum =
  185. (<any>DrawingParametersEnum)[options.drawingParameters.toLowerCase()];
  186. }
  187. const updateExistingBackend: boolean = this.backend !== undefined;
  188. if (options.backend !== undefined || this.backend === undefined) {
  189. if (updateExistingBackend) {
  190. // TODO doesn't work yet, still need to create a new OSMD object
  191. this.drawer.clear();
  192. // musicSheetCalculator.clearSystemsAndMeasures() // maybe? don't have reference though
  193. // musicSheetCalculator.clearRecreatedObjects();
  194. }
  195. if (options.backend === undefined || options.backend.toLowerCase() === "svg") {
  196. this.backend = new SvgVexFlowBackend();
  197. } else {
  198. this.backend = new CanvasVexFlowBackend();
  199. }
  200. this.backend.initialize(this.container);
  201. this.canvas = this.backend.getCanvas();
  202. this.innerElement = this.backend.getInnerElement();
  203. this.enableOrDisableCursor(this.drawingParameters.drawCursors);
  204. // Create the drawer
  205. this.drawer = new VexFlowMusicSheetDrawer(this.canvas, this.backend, this.drawingParameters);
  206. }
  207. // individual drawing parameters options
  208. if (options.autoBeam !== undefined) {
  209. EngravingRules.Rules.AutoBeamNotes = options.autoBeam;
  210. }
  211. const autoBeamOptions: AutoBeamOptions = options.autoBeamOptions;
  212. if (autoBeamOptions) {
  213. if (autoBeamOptions.maintain_stem_directions === undefined) {
  214. autoBeamOptions.maintain_stem_directions = false;
  215. }
  216. EngravingRules.Rules.AutoBeamOptions = autoBeamOptions;
  217. if (autoBeamOptions.groups && autoBeamOptions.groups.length) {
  218. for (const fraction of autoBeamOptions.groups) {
  219. if (fraction.length !== 2) {
  220. throw new Error("Each fraction in autoBeamOptions.groups must be of length 2, e.g. [3,4] for beaming three fourths");
  221. }
  222. }
  223. }
  224. }
  225. if (options.coloringEnabled !== undefined) {
  226. EngravingRules.Rules.ColoringEnabled = options.coloringEnabled;
  227. }
  228. if (options.disableCursor) {
  229. this.drawingParameters.drawCursors = false;
  230. this.enableOrDisableCursor(this.drawingParameters.drawCursors);
  231. }
  232. // alternative to if block: this.drawingsParameters.drawCursors = options.drawCursors !== false. No if, but always sets drawingParameters.
  233. // note that every option can be undefined, which doesn't mean the option should be set to false.
  234. if (options.drawHiddenNotes) {
  235. this.drawingParameters.drawHiddenNotes = true;
  236. }
  237. if (options.drawTitle !== undefined) {
  238. this.drawingParameters.DrawTitle = options.drawTitle;
  239. // TODO these settings are duplicate in drawingParameters and EngravingRules. Maybe we only need them in EngravingRules.
  240. // this sets the parameter in DrawingParameters, which in turn sets the parameter in EngravingRules.
  241. // see settings below that don't call drawingParameters for the immediate approach
  242. }
  243. if (options.drawSubtitle !== undefined) {
  244. this.drawingParameters.DrawSubtitle = options.drawSubtitle;
  245. }
  246. if (options.drawLyricist !== undefined) {
  247. this.drawingParameters.DrawLyricist = options.drawLyricist;
  248. }
  249. if (options.drawCredits !== undefined) {
  250. this.drawingParameters.drawCredits = options.drawCredits;
  251. }
  252. if (options.drawPartNames !== undefined) {
  253. this.drawingParameters.DrawPartNames = options.drawPartNames;
  254. }
  255. if (options.drawFingerings === false) {
  256. EngravingRules.Rules.RenderFingerings = false;
  257. }
  258. if (options.fingeringPosition !== undefined) {
  259. EngravingRules.Rules.FingeringPosition = AbstractExpression.PlacementEnumFromString(options.fingeringPosition);
  260. }
  261. if (options.fingeringInsideStafflines !== undefined) {
  262. EngravingRules.Rules.FingeringInsideStafflines = options.fingeringInsideStafflines;
  263. }
  264. if (options.setWantedStemDirectionByXml !== undefined) {
  265. EngravingRules.Rules.SetWantedStemDirectionByXml = options.setWantedStemDirectionByXml;
  266. }
  267. if (options.defaultColorNotehead) {
  268. EngravingRules.Rules.DefaultColorNotehead = options.defaultColorNotehead;
  269. }
  270. if (options.defaultColorRest) {
  271. EngravingRules.Rules.DefaultColorRest = options.defaultColorRest;
  272. }
  273. if (options.defaultColorStem) {
  274. EngravingRules.Rules.DefaultColorStem = options.defaultColorStem;
  275. }
  276. if (options.defaultColorLabel) {
  277. EngravingRules.Rules.DefaultColorLabel = options.defaultColorLabel;
  278. }
  279. if (options.defaultColorTitle) {
  280. EngravingRules.Rules.DefaultColorTitle = options.defaultColorTitle;
  281. }
  282. if (options.drawUpToMeasureNumber) {
  283. EngravingRules.Rules.MaxMeasureToDrawIndex = options.drawUpToMeasureNumber;
  284. }
  285. if (options.tupletsRatioed) {
  286. EngravingRules.Rules.TupletsRatioed = true;
  287. }
  288. if (options.tupletsBracketed) {
  289. EngravingRules.Rules.TupletsBracketed = true;
  290. }
  291. if (options.tripletsBracketed) {
  292. EngravingRules.Rules.TripletsBracketed = true;
  293. }
  294. if (options.autoResize) {
  295. if (!this.resizeHandlerAttached) {
  296. this.autoResize();
  297. }
  298. this.autoResizeEnabled = true;
  299. } else if (options.autoResize === false) { // not undefined
  300. this.autoResizeEnabled = false;
  301. // we could remove the window EventListener here, but not necessary.
  302. }
  303. }
  304. /**
  305. * Sets the logging level for this OSMD instance. By default, this is set to `warn`.
  306. *
  307. * @param: content can be `trace`, `debug`, `info`, `warn` or `error`.
  308. */
  309. public setLogLevel(level: string): void {
  310. switch (level) {
  311. case "trace":
  312. log.setLevel(log.levels.TRACE);
  313. break;
  314. case "debug":
  315. log.setLevel(log.levels.DEBUG);
  316. break;
  317. case "info":
  318. log.setLevel(log.levels.INFO);
  319. break;
  320. case "warn":
  321. log.setLevel(log.levels.WARN);
  322. break;
  323. case "error":
  324. log.setLevel(log.levels.ERROR);
  325. break;
  326. default:
  327. log.warn(`Could not set log level to ${level}. Using warn instead.`);
  328. log.setLevel(log.levels.WARN);
  329. break;
  330. }
  331. }
  332. /**
  333. * Initialize this object to default values
  334. * FIXME: Probably unnecessary
  335. */
  336. private reset(): void {
  337. if (this.drawingParameters.drawCursors && this.cursor) {
  338. this.cursor.hide();
  339. }
  340. this.sheet = undefined;
  341. this.graphic = undefined;
  342. this.zoom = 1.0;
  343. }
  344. /**
  345. * Attach the appropriate handler to the window.onResize event
  346. */
  347. private autoResize(): void {
  348. const self: OpenSheetMusicDisplay = this;
  349. this.handleResize(
  350. () => {
  351. // empty
  352. },
  353. () => {
  354. // The following code is probably not needed
  355. // (the width should adapt itself to the max allowed)
  356. //let width: number = Math.max(
  357. // document.documentElement.clientWidth,
  358. // document.body.scrollWidth,
  359. // document.documentElement.scrollWidth,
  360. // document.body.offsetWidth,
  361. // document.documentElement.offsetWidth
  362. //);
  363. //self.container.style.width = width + "px";
  364. if (self.IsReadyToRender()) {
  365. self.render();
  366. }
  367. }
  368. );
  369. }
  370. /**
  371. * Helper function for managing window's onResize events
  372. * @param startCallback is the function called when resizing starts
  373. * @param endCallback is the function called when resizing (kind-of) ends
  374. */
  375. private handleResize(startCallback: () => void, endCallback: () => void): void {
  376. let rtime: number;
  377. let timeout: number = undefined;
  378. const delta: number = 200;
  379. const self: OpenSheetMusicDisplay = this;
  380. function resizeStart(): void {
  381. if (!self.AutoResizeEnabled) {
  382. return;
  383. }
  384. rtime = (new Date()).getTime();
  385. if (!timeout) {
  386. startCallback();
  387. rtime = (new Date()).getTime();
  388. timeout = window.setTimeout(resizeEnd, delta);
  389. }
  390. }
  391. function resizeEnd(): void {
  392. timeout = undefined;
  393. window.clearTimeout(timeout);
  394. if ((new Date()).getTime() - rtime < delta) {
  395. timeout = window.setTimeout(resizeEnd, delta);
  396. } else {
  397. endCallback();
  398. }
  399. }
  400. if ((<any>window).attachEvent) {
  401. // Support IE<9
  402. (<any>window).attachEvent("onresize", resizeStart);
  403. } else {
  404. window.addEventListener("resize", resizeStart);
  405. }
  406. this.resizeHandlerAttached = true;
  407. window.setTimeout(startCallback, 0);
  408. window.setTimeout(endCallback, 1);
  409. }
  410. /** Enable or disable (hide) the cursor.
  411. * @param enable whether to enable (true) or disable (false) the cursor
  412. */
  413. public enableOrDisableCursor(enable: boolean): void {
  414. this.drawingParameters.drawCursors = enable;
  415. if (enable) {
  416. if (!this.cursor) {
  417. this.cursor = new Cursor(this.innerElement, this);
  418. if (this.sheet && this.graphic) { // else init is called in load()
  419. this.cursor.init(this.sheet.MusicPartManager, this.graphic);
  420. }
  421. }
  422. } else { // disable cursor
  423. if (!this.cursor) {
  424. return;
  425. }
  426. this.cursor.hide();
  427. // this.cursor = undefined;
  428. // TODO cursor should be disabled, not just hidden. otherwise user can just call osmd.cursor.hide().
  429. // however, this could cause null calls (cursor.next() etc), maybe that needs some solution.
  430. }
  431. }
  432. //#region GETTER / SETTER
  433. public set DrawSkyLine(value: boolean) {
  434. if (this.drawer) {
  435. this.drawer.skyLineVisible = value;
  436. this.render();
  437. }
  438. }
  439. public get DrawSkyLine(): boolean {
  440. return this.drawer.skyLineVisible;
  441. }
  442. public set DrawBottomLine(value: boolean) {
  443. if (this.drawer) {
  444. this.drawer.bottomLineVisible = value;
  445. this.render();
  446. }
  447. }
  448. public get DrawBottomLine(): boolean {
  449. return this.drawer.bottomLineVisible;
  450. }
  451. public set DrawBoundingBox(value: string) {
  452. this.drawer.drawableBoundingBoxElement = value;
  453. this.render();
  454. }
  455. public get DrawBoundingBox(): string {
  456. return this.drawer.drawableBoundingBoxElement;
  457. }
  458. public get AutoResizeEnabled(): boolean {
  459. return this.autoResizeEnabled;
  460. }
  461. public set AutoResizeEnabled(value: boolean) {
  462. this.autoResizeEnabled = value;
  463. }
  464. public get Sheet(): MusicSheet {
  465. return this.sheet;
  466. }
  467. public get Drawer(): VexFlowMusicSheetDrawer {
  468. return this.drawer;
  469. }
  470. public get GraphicSheet(): GraphicalMusicSheet {
  471. return this.graphic;
  472. }
  473. public get DrawingParameters(): DrawingParameters {
  474. return this.drawingParameters;
  475. }
  476. public get Version(): string {
  477. return this.version;
  478. }
  479. //#endregion
  480. }