Cursor.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. import { VexFlowMeasure } from "../MusicalScore/Graphical/VexFlow/VexFlowMeasure";
  16. import { CursorOptions } from "./OSMDOptions";
  17. import { BoundingBox } from "../MusicalScore/Graphical/BoundingBox";
  18. import { GraphicalNote } from "../MusicalScore/Graphical/GraphicalNote";
  19. import { GraphicalStaffEntry } from "../MusicalScore/Graphical/GraphicalStaffEntry";
  20. import { IPlaybackListener } from "../Common/Interfaces/IPlaybackListener";
  21. import { CursorPosChangedData } from "../Common/DataObjects/CursorPosChangedData";
  22. import { PointF2D } from "../Common/DataObjects";
  23. /**
  24. * A cursor which can iterate through the music sheet.
  25. */
  26. export class Cursor implements IPlaybackListener {
  27. constructor(container: HTMLElement, openSheetMusicDisplay: OpenSheetMusicDisplay, cursorOptions: CursorOptions) {
  28. this.container = container;
  29. this.openSheetMusicDisplay = openSheetMusicDisplay;
  30. this.rules = this.openSheetMusicDisplay.EngravingRules;
  31. this.cursorOptions = cursorOptions;
  32. // set cursor id
  33. // TODO add this for the OSMD object as well and refactor this into a util method?
  34. let id: number = 0;
  35. this.cursorElementId = "cursorImg-0";
  36. // find unique cursor id in document
  37. while (document.getElementById(this.cursorElementId)) {
  38. id++;
  39. this.cursorElementId = `cursorImg-${id}`;
  40. }
  41. const curs: HTMLElement = document.createElement("img");
  42. curs.id = this.cursorElementId;
  43. curs.style.position = "absolute";
  44. if (this.cursorOptions.follow === true) {
  45. this.wantedZIndex = "-1";
  46. curs.style.zIndex = this.wantedZIndex;
  47. } else {
  48. this.wantedZIndex = "-2";
  49. curs.style.zIndex = this.wantedZIndex;
  50. }
  51. this.cursorElement = <HTMLImageElement>curs;
  52. this.container.appendChild(curs);
  53. }
  54. public cursorPositionChanged(timestamp: Fraction, data: CursorPosChangedData): void {
  55. // update iterator so cursor.NotesUnderCursor() etc works
  56. while (this.iterator.CurrentEnrolledTimestamp.lt(timestamp) && !this.iterator.EndReached) {
  57. // if iterator.EndReached, this would loop endlessly, because then moveToNext() just returns, without changes
  58. this.iterator.moveToNext();
  59. }
  60. if (this.iterator.CurrentEnrolledTimestamp.gt(timestamp)) {
  61. this.iterator = new MusicPartManagerIterator(this.manager.MusicSheet, timestamp);
  62. }
  63. this.updateWithTimestamp(data.PredictedPosition);
  64. }
  65. public pauseOccurred(o: object): void {
  66. // throw new Error("Method not implemented.");
  67. }
  68. public selectionEndReached(o: object): void {
  69. // throw new Error("Method not implemented.");
  70. }
  71. public resetOccurred(o: object): void {
  72. this.reset();
  73. }
  74. public notesPlaybackEventOccurred(o: object): void {
  75. // throw new Error("Method not implemented.");
  76. }
  77. public adjustToBackgroundColor(): void {
  78. let zIndex: string;
  79. if (!this.rules.PageBackgroundColor) {
  80. zIndex = this.wantedZIndex;
  81. } else {
  82. zIndex = "1";
  83. }
  84. this.cursorElement.style.zIndex = zIndex;
  85. }
  86. private container: HTMLElement;
  87. public cursorElement: HTMLImageElement;
  88. /** a unique id of the cursor's HTMLElement in the document.
  89. * Should be constant between re-renders and backend changes,
  90. * but different between different OSMD objects on the same page.
  91. */
  92. public cursorElementId: string;
  93. /** The desired zIndex (layer) of the cursor when no background color is set.
  94. * When a background color is set, using a negative zIndex would make the cursor invisible.
  95. */
  96. public wantedZIndex: string;
  97. private openSheetMusicDisplay: OpenSheetMusicDisplay;
  98. private rules: EngravingRules;
  99. private manager: MusicPartManager;
  100. public iterator: MusicPartManagerIterator;
  101. private graphic: GraphicalMusicSheet;
  102. public hidden: boolean = false;
  103. public currentPageNumber: number = 1;
  104. private cursorOptions: CursorOptions;
  105. private skipInvisibleNotes: boolean = true;
  106. /** Initialize the cursor. Necessary before using functions like show() and next(). */
  107. public init(manager: MusicPartManager, graphic: GraphicalMusicSheet): void {
  108. this.manager = manager;
  109. this.graphic = graphic;
  110. this.reset();
  111. this.hidden = false;
  112. }
  113. /**
  114. * Make the cursor visible
  115. */
  116. public show(): void {
  117. this.hidden = false;
  118. //this.resetIterator(); // TODO maybe not here? though setting measure range to draw, rerendering, then handling cursor show is difficult
  119. this.update();
  120. this.adjustToBackgroundColor();
  121. }
  122. public resetIterator(): void {
  123. if (!this.openSheetMusicDisplay.Sheet || !this.openSheetMusicDisplay.Sheet.SourceMeasures) { // just a safety measure
  124. console.log("OSMD.Cursor.resetIterator(): sheet or measures were null/undefined.");
  125. return;
  126. }
  127. // set selection start, so that when there's MinMeasureToDraw set, the cursor starts there right away instead of at measure 1
  128. const lastSheetMeasureIndex: number = this.openSheetMusicDisplay.Sheet.SourceMeasures.length - 1; // last measure in data model
  129. let startMeasureIndex: number = this.rules.MinMeasureToDrawIndex;
  130. startMeasureIndex = Math.min(startMeasureIndex, lastSheetMeasureIndex);
  131. let endMeasureIndex: number = this.rules.MaxMeasureToDrawIndex;
  132. endMeasureIndex = Math.min(endMeasureIndex, lastSheetMeasureIndex);
  133. const updateSelectionStart: boolean = this.openSheetMusicDisplay.Sheet && (
  134. !this.openSheetMusicDisplay.Sheet.SelectionStart ||
  135. this.openSheetMusicDisplay.Sheet.SelectionStart.WholeValue < startMeasureIndex) &&
  136. this.openSheetMusicDisplay.Sheet.SourceMeasures.length > startMeasureIndex;
  137. if (updateSelectionStart) {
  138. this.openSheetMusicDisplay.Sheet.SelectionStart = this.openSheetMusicDisplay.Sheet.SourceMeasures[startMeasureIndex].AbsoluteTimestamp;
  139. }
  140. if (this.openSheetMusicDisplay.Sheet && this.openSheetMusicDisplay.Sheet.SourceMeasures.length > endMeasureIndex) {
  141. const lastMeasure: SourceMeasure = this.openSheetMusicDisplay.Sheet.SourceMeasures[endMeasureIndex];
  142. this.openSheetMusicDisplay.Sheet.SelectionEnd = Fraction.plus(lastMeasure.AbsoluteTimestamp, lastMeasure.Duration);
  143. }
  144. this.iterator = this.manager.getIterator();
  145. // remember SkipInvisibleNotes setting, which otherwise gets reset to default value
  146. this.iterator.SkipInvisibleNotes = this.skipInvisibleNotes;
  147. }
  148. private getStaffEntryFromVoiceEntry(voiceEntry: VoiceEntry): VexFlowStaffEntry {
  149. const measureIndex: number = voiceEntry.ParentSourceStaffEntry.VerticalContainerParent.ParentMeasure.measureListIndex;
  150. const staffIndex: number = voiceEntry.ParentSourceStaffEntry.ParentStaff.idInMusicSheet;
  151. return <VexFlowStaffEntry>this.graphic.findGraphicalStaffEntryFromMeasureList(staffIndex, measureIndex, voiceEntry.ParentSourceStaffEntry);
  152. }
  153. public updateWithTimestamp(timestamp: Fraction): void {
  154. const sheetTimestamp: Fraction = this.manager.absoluteEnrolledToSheetTimestamp(timestamp);
  155. const values: [number, MusicSystem, GraphicalStaffEntry] = this.graphic.calculateXPositionFromTimestamp(sheetTimestamp);
  156. const x: number = values[0];
  157. const currentSystem: MusicSystem = values[1];
  158. this.updateCurrentPageFromSystem(currentSystem);
  159. const previousStaffEntry: GraphicalStaffEntry = values[2];
  160. if (!previousStaffEntry) {
  161. return; // TODO maybe fix calculateXPositionFromTimestamp() instead
  162. }
  163. // for samples starting with a precount measure (e.g. Mozart - An Chloe), the measure number can be 0,
  164. // so without max(n, 1), [topMeasureNumber - 1] would be [-1], causing an error
  165. const topMeasureNumber: number = Math.max(previousStaffEntry.parentMeasure.MeasureNumber, 1);
  166. // we have to find the top measure, otherwise the cursor with type 3 "jumps around" between vertical measures
  167. let topMeasure: GraphicalMeasure;
  168. for (const measure of this.graphic.MeasureList[topMeasureNumber - 1]) {
  169. if (measure) {
  170. topMeasure = measure;
  171. break;
  172. }
  173. }
  174. const points: [PointF2D, PointF2D] = this.graphic.calculateCursorPoints(x, currentSystem);
  175. const y: number = points[0].y;
  176. const height: number = points[1].y - y;
  177. this.updateWidthAndStyle(topMeasure.PositionAndShape, x, y, height);
  178. if (this.openSheetMusicDisplay.FollowCursor) {
  179. const diff: number = this.cursorElement.getBoundingClientRect().top;
  180. this.cursorElement.scrollIntoView({behavior: diff < 1000 ? "smooth" : "auto", block: "center"});
  181. }
  182. // Show cursor
  183. // // Old cursor: this.graphic.Cursors.push(cursor);
  184. this.cursorElement.style.display = "";
  185. }
  186. public update(): void {
  187. if (this.hidden || this.hidden === undefined || this.hidden === null) {
  188. return;
  189. }
  190. this.updateCurrentPage(); // attach cursor to new page DOM if necessary
  191. // this.graphic?.Cursors?.length = 0;
  192. const iterator: MusicPartManagerIterator = this.Iterator;
  193. // TODO when measure draw range (drawUpToMeasureNumber) was changed, next/update can fail to move cursor. but of course it can be reset before.
  194. let voiceEntries: VoiceEntry[] = iterator.CurrentVisibleVoiceEntries();
  195. let currentMeasureIndex: number = iterator.CurrentMeasureIndex;
  196. let x: number = 0, y: number = 0, height: number = 0;
  197. let musicSystem: MusicSystem;
  198. if (voiceEntries.length === 0 && !iterator.FrontReached && !iterator.EndReached) {
  199. // e.g. when the note at the current position is in an instrument that's now invisible, and there's no other note at this position, vertically
  200. iterator.moveToPrevious();
  201. voiceEntries = iterator.CurrentVisibleVoiceEntries();
  202. iterator.moveToNext();
  203. // after this, the else condition below should trigger, positioning the cursor at the left-most note. See #1312
  204. }
  205. if (iterator.FrontReached && voiceEntries.length === 0) {
  206. // show beginning of first measure (of stafflines, to create a visual difference to the first note position)
  207. // this position is technically before the sheet/first note - e.g. cursor.Iterator.CurrentTimestamp.RealValue = -1
  208. iterator.moveToNext();
  209. voiceEntries = iterator.CurrentVisibleVoiceEntries();
  210. const firstVisibleMeasure: GraphicalMeasure = this.findVisibleGraphicalMeasure(iterator.CurrentMeasureIndex);
  211. x = firstVisibleMeasure.PositionAndShape.AbsolutePosition.x;
  212. musicSystem = firstVisibleMeasure.ParentMusicSystem;
  213. iterator.moveToPrevious();
  214. } else if (iterator.EndReached || !iterator.CurrentVoiceEntries || voiceEntries.length === 0) {
  215. // show end of last measure (of stafflines, to create a visual difference to the first note position)
  216. // this position is technically after the sheet/last note - e.g. cursor.Iterator.CurrentTimestamp.RealValue = 99999
  217. iterator.moveToPrevious();
  218. voiceEntries = iterator.CurrentVisibleVoiceEntries();
  219. currentMeasureIndex = iterator.CurrentMeasureIndex;
  220. const lastVisibleMeasure: GraphicalMeasure = this.findVisibleGraphicalMeasure(iterator.CurrentMeasureIndex);
  221. x = lastVisibleMeasure.PositionAndShape.AbsolutePosition.x + lastVisibleMeasure.PositionAndShape.Size.width;
  222. musicSystem = lastVisibleMeasure.ParentMusicSystem;
  223. iterator.moveToNext();
  224. } else if (iterator.CurrentMeasure.isReducedToMultiRest) {
  225. // multiple measure rests aren't used when one
  226. const multiRestGMeasure: GraphicalMeasure = this.findVisibleGraphicalMeasure(iterator.CurrentMeasureIndex);
  227. const totalRestMeasures: number = multiRestGMeasure.parentSourceMeasure.multipleRestMeasures;
  228. const currentRestMeasureNumber: number = iterator.CurrentMeasure.multipleRestMeasureNumber;
  229. const progressRatio: number = currentRestMeasureNumber / (totalRestMeasures + 1);
  230. const effectiveWidth: number = multiRestGMeasure.PositionAndShape.Size.width - (multiRestGMeasure as VexFlowMeasure).beginInstructionsWidth;
  231. x = multiRestGMeasure.PositionAndShape.AbsolutePosition.x + (multiRestGMeasure as VexFlowMeasure).beginInstructionsWidth + progressRatio * effectiveWidth;
  232. musicSystem = multiRestGMeasure.ParentMusicSystem;
  233. } else {
  234. // get all staff entries inside the current voice entry
  235. const gseArr: VexFlowStaffEntry[] = voiceEntries.map(ve => this.getStaffEntryFromVoiceEntry(ve));
  236. // sort them by x position and take the leftmost entry
  237. const gse: VexFlowStaffEntry =
  238. gseArr.sort((a, b) => a?.PositionAndShape?.AbsolutePosition?.x <= b?.PositionAndShape?.AbsolutePosition?.x ? -1 : 1 )[0];
  239. if (gse) {
  240. x = gse.PositionAndShape.AbsolutePosition.x;
  241. musicSystem = gse.parentMeasure.ParentMusicSystem;
  242. }
  243. // debug: change color of notes under cursor (needs re-render)
  244. // for (const gve of gse.graphicalVoiceEntries) {
  245. // for (const note of gve.notes) {
  246. // note.sourceNote.NoteheadColor = "#0000FF";
  247. // }
  248. // }
  249. }
  250. if (!musicSystem) {
  251. return;
  252. }
  253. // y is common for both multirest and non-multirest, given the MusicSystem
  254. // note: StaffLines[0] is guaranteed to exist in this.findVisibleGraphicalMeasure
  255. y = musicSystem.PositionAndShape.AbsolutePosition.y + musicSystem.StaffLines[0].PositionAndShape.RelativePosition.y;
  256. let endY: number = musicSystem.PositionAndShape.AbsolutePosition.y;
  257. const bottomStaffline: StaffLine = musicSystem.StaffLines[musicSystem.StaffLines.length - 1];
  258. if (bottomStaffline) { // can be undefined if drawFromMeasureNumber changed after cursor was shown (extended issue 68)
  259. endY += bottomStaffline.PositionAndShape.RelativePosition.y + bottomStaffline.StaffHeight;
  260. }
  261. height = endY - y;
  262. // Update the graphical cursor
  263. const measurePositionAndShape: BoundingBox = this.graphic.findGraphicalMeasure(currentMeasureIndex, 0).PositionAndShape;
  264. this.updateWidthAndStyle(measurePositionAndShape, x, y, height);
  265. if (this.openSheetMusicDisplay.FollowCursor && this.cursorOptions.follow) {
  266. if (!this.openSheetMusicDisplay.EngravingRules.RenderSingleHorizontalStaffline) {
  267. const diff: number = this.cursorElement.getBoundingClientRect().top;
  268. this.cursorElement.scrollIntoView({behavior: diff < 1000 ? "smooth" : "auto", block: "center"});
  269. } else {
  270. this.cursorElement.scrollIntoView({behavior: "smooth", inline: "center"});
  271. }
  272. }
  273. // Show cursor
  274. // // Old cursor: this.graphic.Cursors.push(cursor);
  275. this.cursorElement.style.display = "";
  276. }
  277. private findVisibleGraphicalMeasure(measureIndex: number): GraphicalMeasure {
  278. for (let i: number = 0; i < this.graphic.NumberOfStaves; i++) {
  279. const measure: GraphicalMeasure = this.graphic.findGraphicalMeasure(this.iterator.CurrentMeasureIndex, i);
  280. if (measure?.ParentStaff.ParentInstrument.Visible) {
  281. return measure;
  282. }
  283. }
  284. }
  285. public updateWidthAndStyle(measurePositionAndShape: BoundingBox, x: number, y: number, height: number): void {
  286. const cursorElement: HTMLImageElement = this.cursorElement;
  287. let newWidth: number = 0;
  288. let heightCalc: number = height;
  289. switch (this.cursorOptions.type) {
  290. case 1:
  291. cursorElement.style.top = (y * 10.0 * this.openSheetMusicDisplay.zoom) + "px";
  292. cursorElement.style.left = ((x - 1.5) * 10.0 * this.openSheetMusicDisplay.zoom) + "px";
  293. heightCalc = (height * 10.0 * this.openSheetMusicDisplay.zoom);
  294. cursorElement.height = heightCalc;
  295. cursorElement.style.height = heightCalc + "px";
  296. newWidth = 5 * this.openSheetMusicDisplay.zoom;
  297. break;
  298. case 2:
  299. cursorElement.style.top = ((y-2.5) * 10.0 * this.openSheetMusicDisplay.zoom) + "px";
  300. cursorElement.style.left = (x * 10.0 * this.openSheetMusicDisplay.zoom) + "px";
  301. heightCalc = (1.5 * 10.0 * this.openSheetMusicDisplay.zoom);
  302. cursorElement.height = heightCalc;
  303. cursorElement.style.height = heightCalc + "px";
  304. newWidth = 5 * this.openSheetMusicDisplay.zoom;
  305. break;
  306. case 3:
  307. cursorElement.style.top = measurePositionAndShape.AbsolutePosition.y * 10.0 * this.openSheetMusicDisplay.zoom +"px";
  308. cursorElement.style.left = measurePositionAndShape.AbsolutePosition.x * 10.0 * this.openSheetMusicDisplay.zoom +"px";
  309. heightCalc = (height * 10.0 * this.openSheetMusicDisplay.zoom);
  310. cursorElement.height = heightCalc;
  311. cursorElement.style.height = heightCalc + "px";
  312. newWidth = measurePositionAndShape.Size.width * 10 * this.openSheetMusicDisplay.zoom;
  313. break;
  314. case 4:
  315. cursorElement.style.top = measurePositionAndShape.AbsolutePosition.y * 10.0 * this.openSheetMusicDisplay.zoom +"px";
  316. cursorElement.style.left = measurePositionAndShape.AbsolutePosition.x * 10.0 * this.openSheetMusicDisplay.zoom +"px";
  317. heightCalc = (height * 10.0 * this.openSheetMusicDisplay.zoom);
  318. cursorElement.height = heightCalc;
  319. cursorElement.style.height = heightCalc + "px";
  320. newWidth = (x-measurePositionAndShape.AbsolutePosition.x) * 10 * this.openSheetMusicDisplay.zoom;
  321. break;
  322. default:
  323. cursorElement.style.top = (y * 10.0 * this.openSheetMusicDisplay.zoom) + "px";
  324. cursorElement.style.left = ((x - 1.5) * 10.0 * this.openSheetMusicDisplay.zoom) + "px";
  325. heightCalc = (height * 10.0 * this.openSheetMusicDisplay.zoom);
  326. cursorElement.height = heightCalc;
  327. cursorElement.style.height = heightCalc + "px";
  328. newWidth = 3 * 10.0 * this.openSheetMusicDisplay.zoom;
  329. break;
  330. }
  331. if (newWidth !== cursorElement.width) {
  332. cursorElement.width = newWidth;
  333. this.updateStyle(newWidth, this.cursorOptions);
  334. }
  335. }
  336. /**
  337. * Hide the cursor
  338. */
  339. public hide(): void {
  340. // Hide the actual cursor element
  341. this.cursorElement.style.display = "none";
  342. //this.graphic.Cursors.length = 0;
  343. // Forcing the sheet to re-render is not necessary anymore
  344. //if (!this.hidden) {
  345. // this.openSheetMusicDisplay.render();
  346. //}
  347. this.hidden = true;
  348. }
  349. /**
  350. * Go to previous entry
  351. */
  352. public previous(): void {
  353. this.iterator.moveToPreviousVisibleVoiceEntry(false);
  354. this.update();
  355. }
  356. /**
  357. * Go to next entry
  358. */
  359. public next(): void {
  360. this.Iterator.moveToNextVisibleVoiceEntry(false); // moveToNext() would not skip notes in hidden (visible = false) parts
  361. this.update();
  362. }
  363. /**
  364. * reset cursor to start
  365. */
  366. public reset(): void {
  367. this.resetIterator();
  368. //this.iterator.moveToNext();
  369. const iterTmp: MusicPartManagerIterator = this.manager.getIterator(this.graphic.ParentMusicSheet.SelectionStart);
  370. this.updateWithTimestamp(iterTmp.CurrentEnrolledTimestamp);
  371. }
  372. private updateStyle(width: number, cursorOptions: CursorOptions = undefined): void {
  373. if (cursorOptions !== undefined) {
  374. this.cursorOptions = cursorOptions;
  375. }
  376. // Create a dummy canvas to generate the gradient for the cursor
  377. // FIXME This approach needs to be improved
  378. const c: HTMLCanvasElement = document.createElement("canvas");
  379. c.width = this.cursorElement.width;
  380. c.height = 1;
  381. const ctx: CanvasRenderingContext2D = c.getContext("2d");
  382. ctx.globalAlpha = this.cursorOptions.alpha;
  383. // Generate the gradient
  384. const gradient: CanvasGradient = ctx.createLinearGradient(0, 0, this.cursorElement.width, 0);
  385. switch (this.cursorOptions.type) {
  386. case 1:
  387. case 2:
  388. case 3:
  389. case 4:
  390. gradient.addColorStop(1, this.cursorOptions.color);
  391. break;
  392. default:
  393. gradient.addColorStop(0, "white"); // it was: "transparent"
  394. gradient.addColorStop(0.2, this.cursorOptions.color);
  395. gradient.addColorStop(0.8, this.cursorOptions.color);
  396. gradient.addColorStop(1, "white"); // it was: "transparent"
  397. break;
  398. }
  399. ctx.fillStyle = gradient;
  400. ctx.fillRect(0, 0, width, 1);
  401. // Set the actual image
  402. this.cursorElement.src = c.toDataURL("image/png");
  403. }
  404. public get Iterator(): MusicPartManagerIterator {
  405. // if (this.openSheetMusicDisplay.PlaybackManager) {
  406. // return this.openSheetMusicDisplay.PlaybackManager.CursorIterator;
  407. // }
  408. // PlaybackManager.CursorIterator is often not at the visible cursor position.
  409. return this.iterator;
  410. }
  411. public get Hidden(): boolean {
  412. return this.hidden;
  413. }
  414. /** returns voices under the current Cursor position. Without instrument argument, all voices are returned. */
  415. public VoicesUnderCursor(instrument?: Instrument): VoiceEntry[] {
  416. return this.Iterator.CurrentVisibleVoiceEntries(instrument);
  417. }
  418. public NotesUnderCursor(instrument?: Instrument): Note[] {
  419. const voiceEntries: VoiceEntry[] = this.VoicesUnderCursor(instrument);
  420. const notes: Note[] = [];
  421. voiceEntries.forEach(voiceEntry => {
  422. notes.push.apply(notes, voiceEntry.Notes);
  423. });
  424. return notes;
  425. }
  426. public GNotesUnderCursor(instrument?: Instrument): GraphicalNote[] {
  427. const voiceEntries: VoiceEntry[] = this.VoicesUnderCursor(instrument);
  428. const notes: GraphicalNote[] = [];
  429. voiceEntries.forEach(voiceEntry => {
  430. notes.push(...voiceEntry.Notes.map(note => this.rules.GNote(note)));
  431. });
  432. return notes;
  433. }
  434. /** Check if there was a change in current page, and attach cursor element to the corresponding HTMLElement (div).
  435. * This is only necessary if using PageFormat (multiple pages).
  436. */
  437. public updateCurrentPage(): number {
  438. let timestamp: Fraction = this.iterator.currentTimeStamp;
  439. if (timestamp.RealValue < 0) {
  440. timestamp = new Fraction(0, 0);
  441. }
  442. for (const page of this.graphic.MusicPages) {
  443. const lastSystemTimestamp: Fraction = page.MusicSystems.last().GetSystemsLastTimeStamp();
  444. if (lastSystemTimestamp.gt(timestamp)) {
  445. // gt: the last timestamp of the last system is equal to the first of the next page,
  446. // so we do need to use gt, not gte here.
  447. const newPageNumber: number = page.PageNumber;
  448. if (newPageNumber !== this.currentPageNumber) {
  449. this.container.removeChild(this.cursorElement);
  450. this.container = document.getElementById("osmdCanvasPage" + newPageNumber);
  451. this.container.appendChild(this.cursorElement);
  452. // TODO maybe store this.pageCurrentlyAttachedTo, though right now it isn't necessary
  453. // alternative to remove/append:
  454. // this.openSheetMusicDisplay.enableOrDisableCursor(true);
  455. }
  456. return this.currentPageNumber = newPageNumber;
  457. }
  458. }
  459. return 1;
  460. }
  461. public get SkipInvisibleNotes(): boolean {
  462. return this.skipInvisibleNotes;
  463. }
  464. public set SkipInvisibleNotes(value: boolean) {
  465. this.skipInvisibleNotes = value;
  466. this.iterator.SkipInvisibleNotes = value;
  467. }
  468. public get CursorOptions(): CursorOptions {
  469. return this.cursorOptions;
  470. }
  471. public set CursorOptions(value: CursorOptions) {
  472. this.cursorOptions = value;
  473. }
  474. public updateCurrentPageFromSystem(system: MusicSystem): number {
  475. if (system?.Parent) {
  476. const newPageNumber: number = system.Parent.PageNumber;
  477. if (newPageNumber !== this.currentPageNumber) {
  478. this.container.removeChild(this.cursorElement);
  479. this.container = document.getElementById("osmdCanvasPage" + newPageNumber);
  480. this.container.appendChild(this.cursorElement);
  481. // TODO maybe store this.pageCurrentlyAttachedTo, though right now it isn't necessary
  482. // alternative to remove/append:
  483. // this.openSheetMusicDisplay.enableOrDisableCursor(true);
  484. }
  485. return this.currentPageNumber = newPageNumber;
  486. }
  487. return 1;
  488. }
  489. public Dispose(): void {
  490. this.rules = undefined;
  491. this.openSheetMusicDisplay = undefined;
  492. this.cursorOptions = undefined;
  493. }
  494. }