Cursor.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. import {MusicPartManagerIterator} from "../MusicalScore/MusicParts/MusicPartManagerIterator";
  2. import {MusicPartManager} from "../MusicalScore/MusicParts/MusicPartManager";
  3. import {VoiceEntry} from "../MusicalScore/VoiceData/VoiceEntry";
  4. import {VexFlowStaffEntry} from "../MusicalScore/Graphical/VexFlow/VexFlowStaffEntry";
  5. import {MusicSystem} from "../MusicalScore/Graphical/MusicSystem";
  6. import {OpenSheetMusicDisplay} from "./OpenSheetMusicDisplay";
  7. import {GraphicalMusicSheet} from "../MusicalScore/Graphical/GraphicalMusicSheet";
  8. import {Instrument} from "../MusicalScore/Instrument";
  9. import {Note} from "../MusicalScore/VoiceData/Note";
  10. import {Fraction} from "../Common/DataObjects/Fraction";
  11. import { EngravingRules } from "../MusicalScore/Graphical/EngravingRules";
  12. import { SourceMeasure } from "../MusicalScore/VoiceData/SourceMeasure";
  13. import { StaffLine } from "../MusicalScore/Graphical/StaffLine";
  14. /**
  15. * A cursor which can iterate through the music sheet.
  16. */
  17. export class Cursor {
  18. constructor(container: HTMLElement, openSheetMusicDisplay: OpenSheetMusicDisplay) {
  19. this.container = container;
  20. this.openSheetMusicDisplay = openSheetMusicDisplay;
  21. this.rules = this.openSheetMusicDisplay.EngravingRules;
  22. // set cursor id
  23. // TODO add this for the OSMD object as well and refactor this into a util method?
  24. let id: number = 0;
  25. this.cursorElementId = "cursorImg-0";
  26. // find unique cursor id in document
  27. while (document.getElementById(this.cursorElementId)) {
  28. id++;
  29. this.cursorElementId = `cursorImg-${id}`;
  30. }
  31. const curs: HTMLElement = document.createElement("img");
  32. curs.id = this.cursorElementId;
  33. curs.style.position = "absolute";
  34. curs.style.zIndex = "-1";
  35. this.cursorElement = <HTMLImageElement>curs;
  36. this.container.appendChild(curs);
  37. }
  38. private container: HTMLElement;
  39. public cursorElement: HTMLImageElement;
  40. /** a unique id of the cursor's HTMLElement in the document.
  41. * Should be constant between re-renders and backend changes,
  42. * but different between different OSMD objects on the same page.
  43. */
  44. public cursorElementId: string;
  45. private openSheetMusicDisplay: OpenSheetMusicDisplay;
  46. private rules: EngravingRules;
  47. private manager: MusicPartManager;
  48. public iterator: MusicPartManagerIterator;
  49. private graphic: GraphicalMusicSheet;
  50. public hidden: boolean = true;
  51. public currentPageNumber: number = 1;
  52. /** Initialize the cursor. Necessary before using functions like show() and next(). */
  53. public init(manager: MusicPartManager, graphic: GraphicalMusicSheet): void {
  54. this.manager = manager;
  55. this.graphic = graphic;
  56. this.reset();
  57. this.hidden = true;
  58. this.hide();
  59. }
  60. /**
  61. * Make the cursor visible
  62. */
  63. public show(): void {
  64. this.hidden = false;
  65. this.resetIterator(); // TODO maybe not here? though setting measure range to draw, rerendering, then handling cursor show is difficult
  66. this.update();
  67. }
  68. public resetIterator(): void {
  69. if (!this.openSheetMusicDisplay.Sheet || !this.openSheetMusicDisplay.Sheet.SourceMeasures) { // just a safety measure
  70. console.log("OSMD.Cursor.resetIterator(): sheet or measures were null/undefined.");
  71. return;
  72. }
  73. // set selection start, so that when there's MinMeasureToDraw set, the cursor starts there right away instead of at measure 1
  74. const lastSheetMeasureIndex: number = this.openSheetMusicDisplay.Sheet.SourceMeasures.length - 1; // last measure in data model
  75. let startMeasureIndex: number = this.rules.MinMeasureToDrawIndex;
  76. startMeasureIndex = Math.min(startMeasureIndex, lastSheetMeasureIndex);
  77. let endMeasureIndex: number = this.rules.MaxMeasureToDrawIndex;
  78. endMeasureIndex = Math.min(endMeasureIndex, lastSheetMeasureIndex);
  79. if (this.openSheetMusicDisplay.Sheet && this.openSheetMusicDisplay.Sheet.SourceMeasures.length > startMeasureIndex) {
  80. this.openSheetMusicDisplay.Sheet.SelectionStart = this.openSheetMusicDisplay.Sheet.SourceMeasures[startMeasureIndex].AbsoluteTimestamp;
  81. }
  82. if (this.openSheetMusicDisplay.Sheet && this.openSheetMusicDisplay.Sheet.SourceMeasures.length > endMeasureIndex) {
  83. const lastMeasure: SourceMeasure = this.openSheetMusicDisplay.Sheet.SourceMeasures[endMeasureIndex];
  84. this.openSheetMusicDisplay.Sheet.SelectionEnd = Fraction.plus(lastMeasure.AbsoluteTimestamp, lastMeasure.Duration);
  85. }
  86. this.iterator = this.manager.getIterator();
  87. }
  88. private getStaffEntryFromVoiceEntry(voiceEntry: VoiceEntry): VexFlowStaffEntry {
  89. const measureIndex: number = voiceEntry.ParentSourceStaffEntry.VerticalContainerParent.ParentMeasure.measureListIndex;
  90. const staffIndex: number = voiceEntry.ParentSourceStaffEntry.ParentStaff.idInMusicSheet;
  91. return <VexFlowStaffEntry>this.graphic.findGraphicalStaffEntryFromMeasureList(staffIndex, measureIndex, voiceEntry.ParentSourceStaffEntry);
  92. }
  93. public update(): void {
  94. if (this.hidden || this.hidden === undefined || this.hidden === null) {
  95. return;
  96. }
  97. this.updateCurrentPage(); // attach cursor to new page DOM if necessary
  98. // this.graphic?.Cursors?.length = 0;
  99. const iterator: MusicPartManagerIterator = this.iterator;
  100. // TODO when measure draw range (drawUpToMeasureNumber) was changed, next/update can fail to move cursor. but of course it can be reset before.
  101. const voiceEntries: VoiceEntry[] = iterator.CurrentVisibleVoiceEntries();
  102. if (iterator.EndReached || !iterator.CurrentVoiceEntries || voiceEntries.length === 0) {
  103. return;
  104. }
  105. let x: number = 0, y: number = 0, height: number = 0;
  106. // get all staff entries inside the current voice entry
  107. const gseArr: VexFlowStaffEntry[] = voiceEntries.map(ve => this.getStaffEntryFromVoiceEntry(ve));
  108. // sort them by x position and take the leftmost entry
  109. const gse: VexFlowStaffEntry =
  110. gseArr.sort((a, b) => a?.PositionAndShape?.AbsolutePosition?.x <= b?.PositionAndShape?.AbsolutePosition?.x ? -1 : 1 )[0];
  111. x = gse.PositionAndShape.AbsolutePosition.x;
  112. const musicSystem: MusicSystem = gse.parentMeasure.ParentMusicSystem;
  113. if (!musicSystem) {
  114. return;
  115. }
  116. y = musicSystem.PositionAndShape.AbsolutePosition.y + musicSystem.StaffLines[0].PositionAndShape.RelativePosition.y;
  117. const bottomStaffline: StaffLine = musicSystem.StaffLines[musicSystem.StaffLines.length - 1];
  118. const endY: number = musicSystem.PositionAndShape.AbsolutePosition.y +
  119. bottomStaffline.PositionAndShape.RelativePosition.y + bottomStaffline.StaffHeight;
  120. height = endY - y;
  121. // The following code is not necessary (for now, but it could come useful later):
  122. // it highlights the notes under the cursor.
  123. //let vfNotes: { [voiceID: number]: Vex.Flow.StaveNote; } = gse.vfNotes;
  124. //for (let voiceId in vfNotes) {
  125. // if (vfNotes.hasOwnProperty(voiceId)) {
  126. // vfNotes[voiceId].setStyle({
  127. // fillStyle: "red",
  128. // strokeStyle: "red",
  129. // });
  130. // }
  131. //}
  132. // Update the graphical cursor
  133. // The following is the legacy cursor rendered on the canvas:
  134. // // let cursor: GraphicalLine = new GraphicalLine(new PointF2D(x, y), new PointF2D(x, y + height), 3, OutlineAndFillStyleEnum.PlaybackCursor);
  135. // This the current HTML Cursor:
  136. const cursorElement: HTMLImageElement = this.cursorElement;
  137. cursorElement.style.top = (y * 10.0 * this.openSheetMusicDisplay.zoom) + "px";
  138. cursorElement.style.left = ((x - 1.5) * 10.0 * this.openSheetMusicDisplay.zoom) + "px";
  139. cursorElement.height = (height * 10.0 * this.openSheetMusicDisplay.zoom);
  140. const newWidth: number = 3 * 10.0 * this.openSheetMusicDisplay.zoom;
  141. if (newWidth !== cursorElement.width) {
  142. cursorElement.width = newWidth;
  143. this.updateStyle(newWidth);
  144. }
  145. if (this.openSheetMusicDisplay.FollowCursor) {
  146. const diff: number = this.cursorElement.getBoundingClientRect().top;
  147. this.cursorElement.scrollIntoView({behavior: diff < 1000 ? "smooth" : "auto", block: "center"});
  148. }
  149. // Show cursor
  150. // // Old cursor: this.graphic.Cursors.push(cursor);
  151. this.cursorElement.style.display = "";
  152. }
  153. /**
  154. * Hide the cursor
  155. */
  156. public hide(): void {
  157. // Hide the actual cursor element
  158. this.cursorElement.style.display = "none";
  159. //this.graphic.Cursors.length = 0;
  160. // Forcing the sheet to re-render is not necessary anymore
  161. //if (!this.hidden) {
  162. // this.openSheetMusicDisplay.render();
  163. //}
  164. this.hidden = true;
  165. }
  166. /**
  167. * Go to next entry
  168. */
  169. public next(): void {
  170. this.iterator.moveToNext();
  171. this.update();
  172. }
  173. /**
  174. * reset cursor to start
  175. */
  176. public reset(): void {
  177. this.resetIterator();
  178. //this.iterator.moveToNext();
  179. this.update();
  180. }
  181. private updateStyle(width: number, color: string = "#33e02f"): void {
  182. // Create a dummy canvas to generate the gradient for the cursor
  183. // FIXME This approach needs to be improved
  184. const c: HTMLCanvasElement = document.createElement("canvas");
  185. c.width = this.cursorElement.width;
  186. c.height = 1;
  187. const ctx: CanvasRenderingContext2D = c.getContext("2d");
  188. ctx.globalAlpha = 0.5;
  189. // Generate the gradient
  190. const gradient: CanvasGradient = ctx.createLinearGradient(0, 0, this.cursorElement.width, 0);
  191. gradient.addColorStop(0, "white"); // it was: "transparent"
  192. gradient.addColorStop(0.2, color);
  193. gradient.addColorStop(0.8, color);
  194. gradient.addColorStop(1, "white"); // it was: "transparent"
  195. ctx.fillStyle = gradient;
  196. ctx.fillRect(0, 0, width, 1);
  197. // Set the actual image
  198. this.cursorElement.src = c.toDataURL("image/png");
  199. }
  200. public get Iterator(): MusicPartManagerIterator {
  201. return this.iterator;
  202. }
  203. public get Hidden(): boolean {
  204. return this.hidden;
  205. }
  206. /** returns voices under the current Cursor position. Without instrument argument, all voices are returned. */
  207. public VoicesUnderCursor(instrument?: Instrument): VoiceEntry[] {
  208. return this.iterator.CurrentVisibleVoiceEntries(instrument);
  209. }
  210. public NotesUnderCursor(instrument?: Instrument): Note[] {
  211. const voiceEntries: VoiceEntry[] = this.VoicesUnderCursor(instrument);
  212. const notes: Note[] = [];
  213. voiceEntries.forEach(voiceEntry => {
  214. notes.push.apply(notes, voiceEntry.Notes);
  215. });
  216. return notes;
  217. }
  218. /** Check if there was a change in current page, and attach cursor element to the corresponding HTMLElement (div).
  219. * This is only necessary if using PageFormat (multiple pages).
  220. */
  221. public updateCurrentPage(): number {
  222. const timestamp: Fraction = this.iterator.currentTimeStamp;
  223. for (const page of this.graphic.MusicPages) {
  224. const lastSystemTimestamp: Fraction = page.MusicSystems.last().GetSystemsLastTimeStamp();
  225. if (lastSystemTimestamp.gt(timestamp)) {
  226. // gt: the last timestamp of the last system is equal to the first of the next page,
  227. // so we do need to use gt, not gte here.
  228. const newPageNumber: number = page.PageNumber;
  229. if (newPageNumber !== this.currentPageNumber) {
  230. this.container.removeChild(this.cursorElement);
  231. this.container = document.getElementById("osmdCanvasPage" + newPageNumber);
  232. this.container.appendChild(this.cursorElement);
  233. // TODO maybe store this.pageCurrentlyAttachedTo, though right now it isn't necessary
  234. // alternative to remove/append:
  235. // this.openSheetMusicDisplay.enableOrDisableCursor(true);
  236. }
  237. return this.currentPageNumber = newPageNumber;
  238. }
  239. }
  240. return 1;
  241. }
  242. }