Cursor.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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.currentPageNumber = 1;
  67. this.update();
  68. }
  69. public resetIterator(): void {
  70. if (!this.openSheetMusicDisplay.Sheet || !this.openSheetMusicDisplay.Sheet.SourceMeasures) { // just a safety measure
  71. console.log("OSMD.Cursor.resetIterator(): sheet or measures were null/undefined.");
  72. return;
  73. }
  74. // set selection start, so that when there's MinMeasureToDraw set, the cursor starts there right away instead of at measure 1
  75. const lastSheetMeasureIndex: number = this.openSheetMusicDisplay.Sheet.SourceMeasures.length - 1; // last measure in data model
  76. let startMeasureIndex: number = this.rules.MinMeasureToDrawIndex;
  77. startMeasureIndex = Math.min(startMeasureIndex, lastSheetMeasureIndex);
  78. let endMeasureIndex: number = this.rules.MaxMeasureToDrawIndex;
  79. endMeasureIndex = Math.min(endMeasureIndex, lastSheetMeasureIndex);
  80. if (this.openSheetMusicDisplay.Sheet && this.openSheetMusicDisplay.Sheet.SourceMeasures.length > startMeasureIndex) {
  81. this.openSheetMusicDisplay.Sheet.SelectionStart = this.openSheetMusicDisplay.Sheet.SourceMeasures[startMeasureIndex].AbsoluteTimestamp;
  82. }
  83. if (this.openSheetMusicDisplay.Sheet && this.openSheetMusicDisplay.Sheet.SourceMeasures.length > endMeasureIndex) {
  84. const lastMeasure: SourceMeasure = this.openSheetMusicDisplay.Sheet.SourceMeasures[endMeasureIndex];
  85. this.openSheetMusicDisplay.Sheet.SelectionEnd = Fraction.plus(lastMeasure.AbsoluteTimestamp, lastMeasure.Duration);
  86. }
  87. this.iterator = this.manager.getIterator();
  88. }
  89. private getStaffEntryFromVoiceEntry(voiceEntry: VoiceEntry): VexFlowStaffEntry {
  90. const measureIndex: number = voiceEntry.ParentSourceStaffEntry.VerticalContainerParent.ParentMeasure.measureListIndex;
  91. const staffIndex: number = voiceEntry.ParentSourceStaffEntry.ParentStaff.idInMusicSheet;
  92. return <VexFlowStaffEntry>this.graphic.findGraphicalStaffEntryFromMeasureList(staffIndex, measureIndex, voiceEntry.ParentSourceStaffEntry);
  93. }
  94. public update(): void {
  95. if (this.hidden || this.hidden === undefined || this.hidden === null) {
  96. return;
  97. }
  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.updateCurrentPage();
  172. this.update();
  173. }
  174. /**
  175. * reset cursor to start
  176. */
  177. public reset(): void {
  178. this.resetIterator();
  179. this.updateCurrentPage();
  180. //this.iterator.moveToNext();
  181. this.update();
  182. }
  183. private updateStyle(width: number, color: string = "#33e02f"): void {
  184. // Create a dummy canvas to generate the gradient for the cursor
  185. // FIXME This approach needs to be improved
  186. const c: HTMLCanvasElement = document.createElement("canvas");
  187. c.width = this.cursorElement.width;
  188. c.height = 1;
  189. const ctx: CanvasRenderingContext2D = c.getContext("2d");
  190. ctx.globalAlpha = 0.5;
  191. // Generate the gradient
  192. const gradient: CanvasGradient = ctx.createLinearGradient(0, 0, this.cursorElement.width, 0);
  193. gradient.addColorStop(0, "white"); // it was: "transparent"
  194. gradient.addColorStop(0.2, color);
  195. gradient.addColorStop(0.8, color);
  196. gradient.addColorStop(1, "white"); // it was: "transparent"
  197. ctx.fillStyle = gradient;
  198. ctx.fillRect(0, 0, width, 1);
  199. // Set the actual image
  200. this.cursorElement.src = c.toDataURL("image/png");
  201. }
  202. public get Iterator(): MusicPartManagerIterator {
  203. return this.iterator;
  204. }
  205. public get Hidden(): boolean {
  206. return this.hidden;
  207. }
  208. /** returns voices under the current Cursor position. Without instrument argument, all voices are returned. */
  209. public VoicesUnderCursor(instrument?: Instrument): VoiceEntry[] {
  210. return this.iterator.CurrentVisibleVoiceEntries(instrument);
  211. }
  212. public NotesUnderCursor(instrument?: Instrument): Note[] {
  213. const voiceEntries: VoiceEntry[] = this.VoicesUnderCursor(instrument);
  214. const notes: Note[] = [];
  215. voiceEntries.forEach(voiceEntry => {
  216. notes.push.apply(notes, voiceEntry.Notes);
  217. });
  218. return notes;
  219. }
  220. public updateCurrentPage(): number {
  221. const timestamp: Fraction = this.iterator.currentTimeStamp;
  222. for (const page of this.graphic.MusicPages) {
  223. const lastSystemTimestamp: Fraction = page.MusicSystems.last().GetSystemsLastTimeStamp();
  224. if (lastSystemTimestamp.gt(timestamp)) {
  225. // gt: the last timestamp of the last system is equal to the first of the next page,
  226. // so we do need to use gt, not gte here.
  227. const newPageNumber: number = page.PageNumber;
  228. if (newPageNumber !== this.currentPageNumber) {
  229. this.container.removeChild(this.cursorElement);
  230. this.container = document.getElementById("osmdCanvasPage" + newPageNumber);
  231. this.container.appendChild(this.cursorElement);
  232. // alternatively:
  233. // this.openSheetMusicDisplay.enableOrDisableCursor(true);
  234. }
  235. return this.currentPageNumber = newPageNumber;
  236. }
  237. }
  238. return 1;
  239. }
  240. }