Cursor.ts 11 KB

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