-
Notifications
You must be signed in to change notification settings - Fork 202
/
AlphaTabApiBase.ts
1157 lines (1066 loc) · 45.4 KB
/
AlphaTabApiBase.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { AlphaSynthMidiFileHandler } from '@src/midi/AlphaSynthMidiFileHandler';
import { MidiFileGenerator } from '@src/midi/MidiFileGenerator';
import { MidiFile } from '@src/midi/MidiFile';
import { MidiTickLookup, MidiTickLookupFindBeatResult } from '@src/midi/MidiTickLookup';
import { IAlphaSynth } from '@src/synth/IAlphaSynth';
import { PlaybackRange } from '@src/synth/PlaybackRange';
import { PlayerState } from '@src/synth/PlayerState';
import { PlayerStateChangedEventArgs } from '@src/synth/PlayerStateChangedEventArgs';
import { PositionChangedEventArgs } from '@src/synth/PositionChangedEventArgs';
import { Environment } from '@src/Environment';
import { EventEmitter, IEventEmitter, IEventEmitterOfT, EventEmitterOfT } from '@src/EventEmitter';
import { AlphaTexImporter } from '@src/importer/AlphaTexImporter';
import { ByteBuffer } from '@src/io/ByteBuffer';
import { Beat } from '@src/model/Beat';
import { Score } from '@src/model/Score';
import { Track } from '@src/model/Track';
import { IContainer } from '@src/platform/IContainer';
import { IMouseEventArgs } from '@src/platform/IMouseEventArgs';
import { IUiFacade } from '@src/platform/IUiFacade';
import { ScrollMode } from '@src/PlayerSettings';
import { BeatContainerGlyph } from '@src/rendering/glyphs/BeatContainerGlyph';
import { IScoreRenderer } from '@src/rendering/IScoreRenderer';
import { RenderFinishedEventArgs } from '@src/rendering/RenderFinishedEventArgs';
import { ScoreRenderer } from '@src/rendering/ScoreRenderer';
import { BeatBounds } from '@src/rendering/utils/BeatBounds';
import { Bounds } from '@src/rendering/utils/Bounds';
import { BoundsLookup } from '@src/rendering/utils/BoundsLookup';
import { MasterBarBounds } from '@src/rendering/utils/MasterBarBounds';
import { StaveGroupBounds } from '@src/rendering/utils/StaveGroupBounds';
import { ResizeEventArgs } from '@src/ResizeEventArgs';
import { Settings } from '@src/Settings';
import { Logger } from '@src/Logger';
import { ModelUtils } from '@src/model/ModelUtils';
import { AlphaTabError, AlphaTabErrorType } from '@src/AlphaTabError';
class SelectionInfo {
public beat: Beat;
public bounds: BeatBounds | null = null;
public constructor(beat: Beat) {
this.beat = beat;
}
}
/**
* This class represents the public API of alphaTab and provides all logic to display
* a music sheet in any UI using the given {@link IUiFacade}
* @param <TSettings> The UI object holding the settings.
* @csharp_public
*/
export class AlphaTabApiBase<TSettings> {
private _startTime: number = 0;
private _trackIndexes: number[] | null = null;
/**
* Gets the UI facade to use for interacting with the user interface.
*/
public readonly uiFacade: IUiFacade<TSettings>;
/**
* Gets the UI container that holds the whole alphaTab control.
*/
public readonly container: IContainer;
/**
* Gets the score renderer used for rendering the music sheet. This is the low-level API responsible for the actual rendering chain.
*/
public readonly renderer: IScoreRenderer;
/**
* Gets the score holding all information about the song being rendered.
*/
public score: Score | null = null;
/**
* Gets the settings that are used for rendering the music notation.
*/
public settings!: Settings;
/**
* Gets a list of the tracks that are currently rendered;
*/
public tracks: Track[] = [];
/**
* Gets the UI container that will hold all rendered results.
*/
public readonly canvasElement: IContainer;
/**
* Initializes a new instance of the {@link AlphaTabApiBase} class.
* @param uiFacade The UI facade to use for interacting with the user interface.
* @param settings The UI settings object to use for loading the settings.
*/
public constructor(uiFacade: IUiFacade<TSettings>, settings: TSettings) {
this.uiFacade = uiFacade;
this.container = uiFacade.rootContainer;
uiFacade.initialize(this, settings);
Logger.logLevel = this.settings.core.logLevel;
this.canvasElement = uiFacade.createCanvasElement();
this.container.appendChild(this.canvasElement);
this.container.resize.on(
Environment.throttle(() => {
if (this.container.width !== this.renderer.width) {
this.triggerResize();
}
}, uiFacade.resizeThrottle)
);
if (
this.settings.core.useWorkers &&
this.uiFacade.areWorkersSupported &&
Environment.getRenderEngineFactory(this.settings).supportsWorkers
) {
this.renderer = this.uiFacade.createWorkerRenderer();
} else {
this.renderer = new ScoreRenderer(this.settings);
}
let initialResizeEventInfo: ResizeEventArgs = new ResizeEventArgs();
initialResizeEventInfo.oldWidth = this.renderer.width;
initialResizeEventInfo.newWidth = this.container.width | 0;
initialResizeEventInfo.settings = this.settings;
this.onResize(initialResizeEventInfo);
this.renderer.preRender.on(this.onRenderStarted.bind(this));
this.renderer.renderFinished.on(renderingResult => {
this.onRenderFinished(renderingResult);
});
this.renderer.postRenderFinished.on(() => {
let duration: number = Date.now() - this._startTime;
Logger.debug('rendering', 'Rendering completed in ' + duration + 'ms');
this.onPostRenderFinished();
});
this.renderer.preRender.on(_ => {
this._startTime = Date.now();
});
this.renderer.partialRenderFinished.on(this.appendRenderResult.bind(this));
this.renderer.renderFinished.on(r => {
this.appendRenderResult(r);
this.appendRenderResult(null); // marks last element
});
this.renderer.error.on(this.onError.bind(this));
if (this.settings.player.enablePlayer) {
this.setupPlayer();
}
this.setupClickHandling();
// delay rendering to allow ui to hook up with events first.
this.uiFacade.beginInvoke(() => {
this.uiFacade.initialRender();
});
}
/**
* Destroys the alphaTab control and restores the initial state of the UI.
*/
public destroy(): void {
if (this.player) {
this.player.destroy();
}
this.uiFacade.destroy();
this.renderer.destroy();
}
/**
* Applies any changes that were done to the settings object and informs the {@link renderer} about any new values to consider.
*/
public updateSettings(): void {
this.renderer.updateSettings(this.settings);
// enable/disable player if needed
if (this.settings.player.enablePlayer) {
this.setupPlayer();
} else {
this.destroyPlayer();
}
}
/**
* Attempts a load of the score represented by the given data object.
* @param scoreData The data container supported by {@link IUiFacade}
* @param trackIndexes The indexes of the tracks from the song that should be rendered. If not provided, the first track of the
* song will be shown.
* @returns true if the data object is supported and a load was initiated, otherwise false
*/
public load(scoreData: unknown, trackIndexes?: number[]): boolean {
try {
return this.uiFacade.load(
scoreData,
score => {
this.renderScore(score, trackIndexes);
},
error => {
this.onError(error);
}
);
} catch (e) {
this.onError(e);
return false;
}
}
/**
* Initiates a rendering of the given score.
* @param score The score containing the tracks to be rendered.
* @param trackIndexes The indexes of the tracks from the song that should be rendered. If not provided, the first track of the
* song will be shown.
*/
public renderScore(score: Score, trackIndexes?: number[]): void {
let tracks: Track[] = [];
if (!trackIndexes) {
if (score.tracks.length > 0) {
tracks.push(score.tracks[0]);
}
} else {
if (trackIndexes.length === 0) {
if (score.tracks.length > 0) {
tracks.push(score.tracks[0]);
}
} else if (trackIndexes.length === 1 && trackIndexes[0] === -1) {
for (let track of score.tracks) {
tracks.push(track);
}
} else {
for (let index of trackIndexes) {
if (index >= 0 && index <= score.tracks.length) {
tracks.push(score.tracks[index]);
}
}
}
}
this.internalRenderTracks(score, tracks);
}
/**
* Renders the given list of tracks.
* @param tracks The tracks to render. They must all belong to the same score.
*/
public renderTracks(tracks: Track[]): void {
if (tracks.length > 0) {
let score: Score = tracks[0].score;
for (let track of tracks) {
if (track.score !== score) {
this.onError(new AlphaTabError(AlphaTabErrorType.General, 'All rendered tracks must belong to the same score.'));
return;
}
}
this.internalRenderTracks(score, tracks);
}
}
private internalRenderTracks(score: Score, tracks: Track[]): void {
if (score !== this.score) {
ModelUtils.applyPitchOffsets(this.settings, score);
this.score = score;
this.tracks = tracks;
this._trackIndexes = [];
for (let track of tracks) {
this._trackIndexes.push(track.index);
}
this.onScoreLoaded(score);
this.loadMidiForScore();
this.render();
} else {
this.tracks = tracks;
this._trackIndexes = [];
for (let track of tracks) {
this._trackIndexes.push(track.index);
}
this.render();
}
}
private triggerResize(): void {
if (!this.container.isVisible) {
Logger.warning(
'Rendering',
'AlphaTab container was invisible while autosizing, waiting for element to become visible',
null
);
this.uiFacade.rootContainerBecameVisible.on(() => {
Logger.debug('Rendering', 'AlphaTab container became visible, doing autosizing', null);
this.triggerResize();
});
} else {
let resizeEventInfo: ResizeEventArgs = new ResizeEventArgs();
resizeEventInfo.oldWidth = this.renderer.width;
resizeEventInfo.newWidth = this.container.width;
resizeEventInfo.settings = this.settings;
this.onResize(resizeEventInfo);
this.renderer.updateSettings(this.settings);
this.renderer.width = this.container.width;
this.renderer.resizeRender();
}
}
private appendRenderResult(result: RenderFinishedEventArgs | null): void {
if (result) {
this.canvasElement.width = result.totalWidth;
this.canvasElement.height = result.totalHeight;
if (this._cursorWrapper) {
this._cursorWrapper.width = result.totalWidth;
this._cursorWrapper.height = result.totalHeight;
}
}
if (!result || result.renderResult) {
this.uiFacade.beginAppendRenderResults(result);
}
}
/**
* Tells alphaTab to render the given alphaTex.
* @param tex The alphaTex code to render.
* @param tracks If set, the given tracks will be rendered, otherwise the first track only will be rendered.
*/
public tex(tex: string, tracks?: number[]): void {
try {
let parser: AlphaTexImporter = new AlphaTexImporter();
let data: ByteBuffer = ByteBuffer.fromString(tex);
parser.init(data, this.settings);
let score: Score = parser.readScore();
this.renderScore(score, tracks);
} catch (e) {
this.onError(e);
}
}
/**
* Attempts a load of the score represented by the given data object.
* @param data The data object to decode
* @returns true if the data object is supported and a load was initiated, otherwise false
*/
public loadSoundFont(data: unknown): boolean {
if (!this.player) {
return false;
}
return this.uiFacade.loadSoundFont(data);
}
/**
* Initiates a re-rendering of the current setup. If rendering is not yet possible, it will be deferred until the UI changes to be ready for rendering.
*/
public render(): void {
if (!this.renderer) {
return;
}
if (this.uiFacade.canRender) {
// when font is finally loaded, start rendering
this.renderer.width = this.container.width;
this.renderer.renderScore(this.score!, this._trackIndexes as any);
} else {
this.uiFacade.canRenderChanged.on(() => this.render());
}
}
private _tickCache: MidiTickLookup | null = null;
/**
* Gets the alphaSynth player used for playback. This is the low-level API to the Midi synthesizer used for playback.
*/
public player: IAlphaSynth | null = null;
public get isReadyForPlayback(): boolean {
if (!this.player) {
return false;
}
return this.player.isReadyForPlayback;
}
public get playerState(): PlayerState {
if (!this.player) {
return PlayerState.Paused;
}
return this.player.state;
}
public get masterVolume(): number {
if (!this.player) {
return 0;
}
return this.player.masterVolume;
}
public set masterVolume(value: number) {
if (this.player) {
this.player.masterVolume = value;
}
}
public get metronomeVolume(): number {
if (!this.player) {
return 0;
}
return this.player.metronomeVolume;
}
public set metronomeVolume(value: number) {
if (this.player) {
this.player.metronomeVolume = value;
}
}
public get tickPosition(): number {
if (!this.player) {
return 0;
}
return this.player.tickPosition;
}
public set tickPosition(value: number) {
if (this.player) {
this.player.tickPosition = value;
}
}
public get timePosition(): number {
if (!this.player) {
return 0;
}
return this.player.timePosition;
}
public set timePosition(value: number) {
if (this.player) {
this.player.timePosition = value;
}
}
public get playbackRange(): PlaybackRange | null {
if (!this.player) {
return null;
}
return this.player.playbackRange;
}
public set playbackRange(value: PlaybackRange | null) {
if (this.player) {
this.player.playbackRange = value;
}
}
public get playbackSpeed(): number {
if (!this.player) {
return 0;
}
return this.player.playbackSpeed;
}
public set playbackSpeed(value: number) {
if (this.player) {
this.player.playbackSpeed = value;
}
}
public get isLooping(): boolean {
if (!this.player) {
return false;
}
return this.player.isLooping;
}
public set isLooping(value: boolean) {
if (this.player) {
this.player.isLooping = value;
}
}
private destroyPlayer(): void {
if (!this.player) {
return;
}
this.player.destroy();
this.player = null;
this.destroyCursors();
}
private setupPlayer(): void {
if (this.player) {
return;
}
this.player = this.uiFacade.createWorkerPlayer();
if (!this.player) {
return;
}
this.player.ready.on(() => {
this.loadMidiForScore();
});
this.player.readyForPlayback.on(() => {
this.onPlayerReady();
if (this.tracks) {
for (let track of this.tracks) {
let volume: number = track.playbackInfo.volume / 16;
this.player!.setChannelVolume(track.playbackInfo.primaryChannel, volume);
this.player!.setChannelVolume(track.playbackInfo.secondaryChannel, volume);
}
}
});
this.player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this));
this.player.soundFontLoadFailed.on(e => {
this.onError(e);
});
this.player.midiLoaded.on(this.onMidiLoaded.bind(this));
this.player.midiLoadFailed.on(e => {
this.onError(e);
});
this.player.stateChanged.on(this.onPlayerStateChanged.bind(this));
this.player.positionChanged.on(this.onPlayerPositionChanged.bind(this));
this.player.finished.on(this.onPlayerFinished.bind(this));
if (this.settings.player.enableCursor) {
this.setupCursors();
} else {
this.destroyCursors();
}
}
private loadMidiForScore(): void {
if (!this.player || !this.score || !this.player.isReady) {
return;
}
Logger.debug('AlphaTab', 'Generating Midi');
let midiFile: MidiFile = new MidiFile();
let handler: AlphaSynthMidiFileHandler = new AlphaSynthMidiFileHandler(midiFile);
let generator: MidiFileGenerator = new MidiFileGenerator(this.score, this.settings, handler);
generator.generate();
this._tickCache = generator.tickLookup;
this.player.loadMidiFile(midiFile);
}
/**
* Changes the volume of the given tracks.
* @param tracks The tracks for which the volume should be changed.
* @param volume The volume to set for all tracks in percent (0-1)
*/
public changeTrackVolume(tracks: Track[], volume: number): void {
if (!this.player) {
return;
}
for (let track of tracks) {
this.player.setChannelVolume(track.playbackInfo.primaryChannel, volume);
this.player.setChannelVolume(track.playbackInfo.secondaryChannel, volume);
}
}
/**
* Changes the given tracks to be played solo or not.
* If one or more tracks are set to solo, only those tracks are hearable.
* @param tracks The list of tracks to play solo or not.
* @param solo If set to true, the tracks will be added to the solo list. If false, they are removed.
*/
public changeTrackSolo(tracks: Track[], solo: boolean): void {
if (!this.player) {
return;
}
for (let track of tracks) {
this.player.setChannelSolo(track.playbackInfo.primaryChannel, solo);
this.player.setChannelSolo(track.playbackInfo.secondaryChannel, solo);
}
}
/**
* Changes the given tracks to be muted or not.
* @param tracks The list of track to mute or unmute.
* @param mute If set to true, the tracks will be muted. If false they are unmuted.
*/
public changeTrackMute(tracks: Track[], mute: boolean): void {
if (!this.player) {
return;
}
for (let track of tracks) {
this.player.setChannelMute(track.playbackInfo.primaryChannel, mute);
this.player.setChannelMute(track.playbackInfo.secondaryChannel, mute);
}
}
/**
* Starts the playback of the current song.
* @returns true if the playback was started, otherwise false. Reasons for not starting can be that the player is not ready or already playing.
*/
public play(): boolean {
if (!this.player) {
return false;
}
return this.player.play();
}
/**
* Pauses the playback of the current song.
*/
public pause(): void {
if (!this.player) {
return;
}
this.player.pause();
}
/**
* Toggles between play/pause depending on the current player state.
*/
public playPause(): void {
if (!this.player) {
return;
}
this.player.playPause();
}
/**
* Stops the playback of the current song, and moves the playback position back to the start.
*/
public stop(): void {
if (!this.player) {
return;
}
this.player.stop();
}
private _cursorWrapper: IContainer | null = null;
private _barCursor: IContainer | null = null;
private _beatCursor: IContainer | null = null;
private _selectionWrapper: IContainer | null = null;
private _previousTick: number = 0;
private _playerState: PlayerState = PlayerState.Paused;
private _currentBeat: Beat | null = null;
private _previousStateForCursor: PlayerState = PlayerState.Paused;
private _previousCursorCache: BoundsLookup | null = null;
private _lastScroll: number = 0;
private destroyCursors(): void {
if (!this._cursorWrapper) {
return;
}
this.uiFacade.destroyCursors();
this._cursorWrapper = null;
this._barCursor = null;
this._beatCursor = null;
this._selectionWrapper = null;
this._previousTick = 0;
this._playerState = PlayerState.Paused;
}
private setupCursors(): void {
//
// Create cursors
let cursors = this.uiFacade.createCursors();
if (!cursors) {
return;
}
// store options and created elements for fast access
this._cursorWrapper = cursors.cursorWrapper;
this._barCursor = cursors.barCursor;
this._beatCursor = cursors.beatCursor;
this._selectionWrapper = cursors.selectionWrapper;
//
// Hook into events
this._previousTick = 0;
this._playerState = PlayerState.Paused;
// we need to update our position caches if we render a tablature
this.renderer.postRenderFinished.on(() => {
this.cursorUpdateTick(this._previousTick, false);
});
if (this.player) {
this.player.positionChanged.on(e => {
this._previousTick = e.currentTick;
this.uiFacade.beginInvoke(() => {
this.cursorUpdateTick(e.currentTick, false);
});
});
this.player.stateChanged.on(e => {
this._playerState = e.state;
if (!e.stopped && e.state === PlayerState.Paused) {
let currentBeat: Beat | null = this._currentBeat;
let tickCache: MidiTickLookup | null = this._tickCache;
if (currentBeat && tickCache) {
this.player!.tickPosition =
tickCache.getMasterBarStart(currentBeat.voice.bar.masterBar) + currentBeat.playbackStart;
}
}
});
}
}
/**
* updates the cursors to highlight the beat at the specified tick position
* @param tick
* @param stop
*/
private cursorUpdateTick(tick: number, stop: boolean = false): void {
this.uiFacade.beginInvoke(() => {
let cache: MidiTickLookup | null = this._tickCache;
if (cache) {
let tracks: Track[] = this.tracks;
if (tracks.length > 0) {
let beat: MidiTickLookupFindBeatResult | null = cache.findBeat(tracks, tick);
if (beat) {
this.cursorUpdateBeat(
beat.currentBeat,
beat.nextBeat,
beat.duration,
stop,
beat.beatsToHighlight
);
}
}
}
});
}
/**
* updates the cursors to highlight the specified beat
*/
private cursorUpdateBeat(
beat: Beat,
nextBeat: Beat | null,
duration: number,
stop: boolean,
beatsToHighlight: Beat[] | null = null
): void {
if (!beat) {
return;
}
let cache: BoundsLookup | null = this.renderer.boundsLookup;
if (!cache) {
return;
}
let previousBeat: Beat | null = this._currentBeat;
let previousCache: BoundsLookup | null = this._previousCursorCache;
let previousState: PlayerState | null = this._previousStateForCursor;
this._currentBeat = beat;
this._previousCursorCache = cache;
this._previousStateForCursor = this._playerState;
if (beat === previousBeat && cache === previousCache && previousState === this._playerState) {
return;
}
let barCursor: IContainer | null = this._barCursor;
let beatCursor: IContainer | null = this._beatCursor;
let beatBoundings: BeatBounds | null = cache.findBeat(beat);
if (!beatBoundings) {
return;
}
let barBoundings: MasterBarBounds = beatBoundings.barBounds.masterBarBounds;
let barBounds: Bounds = barBoundings.visualBounds;
if (barCursor) {
barCursor.top = barBounds.y;
barCursor.left = barBounds.x;
barCursor.width = barBounds.w;
barCursor.height = barBounds.h;
}
if (beatCursor) {
// move beat to start position immediately
beatCursor.stopAnimation();
beatCursor.top = barBounds.y;
beatCursor.left = beatBoundings.visualBounds.x;
beatCursor.height = barBounds.h;
}
// if playing, animate the cursor to the next beat
this.uiFacade.removeHighlights();
if (this._playerState === PlayerState.Playing || stop) {
duration /= this.playbackSpeed;
if (!stop) {
if (beatsToHighlight) {
for (let highlight of beatsToHighlight) {
let className: string = BeatContainerGlyph.getGroupId(highlight);
this.uiFacade.highlightElements(className);
}
}
let nextBeatX: number = barBoundings.visualBounds.x + barBoundings.visualBounds.w;
// get position of next beat on same stavegroup
if (nextBeat) {
// if we are moving within the same bar or to the next bar
// transition to the next beat, otherwise transition to the end of the bar.
if (
nextBeat.voice.bar.index === beat.voice.bar.index ||
nextBeat.voice.bar.index === beat.voice.bar.index + 1
) {
let nextBeatBoundings: BeatBounds | null = cache.findBeat(nextBeat);
if (
nextBeatBoundings &&
nextBeatBoundings.barBounds.masterBarBounds.staveGroupBounds ===
barBoundings.staveGroupBounds
) {
nextBeatX = nextBeatBoundings.visualBounds.x;
}
}
}
if (beatCursor) {
this.uiFacade.beginInvoke(() => {
// Logger.Info("Player",
// "Transition from " + beatBoundings.VisualBounds.X + " to " + nextBeatX + " in " + duration +
// "(" + Player.PlaybackRange + ")");
beatCursor!.transitionToX(duration, nextBeatX);
});
}
}
if (!this._beatMouseDown && this.settings.player.scrollMode !== ScrollMode.Off) {
let scrollElement: IContainer = this.uiFacade.getScrollContainer();
let isVertical: boolean = Environment.getLayoutEngineFactory(this.settings).vertical;
let mode: ScrollMode = this.settings.player.scrollMode;
let elementOffset: Bounds = this.uiFacade.getOffset(scrollElement, this.container);
if (isVertical) {
switch (mode) {
case ScrollMode.Continuous:
let y: number =
elementOffset.y + barBoundings.realBounds.y + this.settings.player.scrollOffsetY;
if (y !== this._lastScroll) {
this._lastScroll = y;
this.uiFacade.scrollToY(scrollElement, y, this.settings.player.scrollSpeed);
}
break;
case ScrollMode.OffScreen:
let elementBottom: number =
scrollElement.scrollTop + this.uiFacade.getOffset(null, scrollElement).h;
if (
barBoundings.visualBounds.y + barBoundings.visualBounds.h >= elementBottom ||
barBoundings.visualBounds.y < scrollElement.scrollTop
) {
let scrollTop: number = barBoundings.realBounds.y + this.settings.player.scrollOffsetY;
this._lastScroll = barBoundings.visualBounds.x;
this.uiFacade.scrollToY(scrollElement, scrollTop, this.settings.player.scrollSpeed);
}
break;
}
} else {
switch (mode) {
case ScrollMode.Continuous:
let x: number = barBoundings.visualBounds.x;
if (x !== this._lastScroll) {
let scrollLeft: number = barBoundings.realBounds.x + this.settings.player.scrollOffsetX;
this._lastScroll = barBoundings.visualBounds.x;
this.uiFacade.scrollToX(scrollElement, scrollLeft, this.settings.player.scrollSpeed);
}
break;
case ScrollMode.OffScreen:
let elementRight: number =
scrollElement.scrollLeft + this.uiFacade.getOffset(null, scrollElement).w;
if (
barBoundings.visualBounds.x + barBoundings.visualBounds.w >= elementRight ||
barBoundings.visualBounds.x < scrollElement.scrollLeft
) {
let scrollLeft: number = barBoundings.realBounds.x + this.settings.player.scrollOffsetX;
this._lastScroll = barBoundings.visualBounds.x;
this.uiFacade.scrollToX(scrollElement, scrollLeft, this.settings.player.scrollSpeed);
}
break;
}
}
}
// trigger an event for others to indicate which beat/bar is played
this.onPlayedBeatChanged(beat);
}
}
public playedBeatChanged: IEventEmitterOfT<Beat> = new EventEmitterOfT<Beat>();
private onPlayedBeatChanged(beat: Beat): void {
(this.playedBeatChanged as EventEmitterOfT<Beat>).trigger(beat);
this.uiFacade.triggerEvent(this.container, 'playedBeatChanged', beat);
}
private _beatMouseDown: boolean = false;
private _selectionStart: SelectionInfo | null = null;
private _selectionEnd: SelectionInfo | null = null;
public beatMouseDown: IEventEmitterOfT<Beat> = new EventEmitterOfT<Beat>();
public beatMouseMove: IEventEmitterOfT<Beat> = new EventEmitterOfT<Beat>();
public beatMouseUp: IEventEmitterOfT<Beat | null> = new EventEmitterOfT<Beat | null>();
private onBeatMouseDown(originalEvent: IMouseEventArgs, beat: Beat): void {
if (
this.settings.player.enablePlayer &&
this.settings.player.enableCursor &&
this.settings.player.enableUserInteraction
) {
this._selectionStart = new SelectionInfo(beat);
this._selectionEnd = null;
}
this._beatMouseDown = true;
(this.beatMouseDown as EventEmitterOfT<Beat>).trigger(beat);
this.uiFacade.triggerEvent(this.container, 'beatMouseDown', beat, originalEvent);
}
private onBeatMouseMove(originalEvent: IMouseEventArgs, beat: Beat): void {
if (this.settings.player.enableUserInteraction) {
if (!this._selectionEnd || this._selectionEnd.beat !== beat) {
this._selectionEnd = new SelectionInfo(beat);
this.cursorSelectRange(this._selectionStart, this._selectionEnd);
}
}
(this.beatMouseMove as EventEmitterOfT<Beat>).trigger(beat);
this.uiFacade.triggerEvent(this.container, 'beatMouseMove', beat, originalEvent);
}
private onBeatMouseUp(originalEvent: IMouseEventArgs, beat: Beat | null): void {
if (this.settings.player.enableUserInteraction) {
// for the selection ensure start < end
if (this._selectionEnd) {
let startTick: number = this._selectionStart!.beat.absoluteDisplayStart;
let endTick: number = this._selectionStart!.beat.absoluteDisplayStart;
if (endTick < startTick) {
let t: SelectionInfo = this._selectionStart!;
this._selectionStart = this._selectionEnd;
this._selectionEnd = t;
}
}
if (this._selectionStart && this._tickCache) {
// get the start and stop ticks (which consider properly repeats)
let tickCache: MidiTickLookup = this._tickCache;
let realMasterBarStart: number = tickCache.getMasterBarStart(
this._selectionStart.beat.voice.bar.masterBar
);
// move to selection start
this._currentBeat = null; // reset current beat so it is updating the cursor
if(this._playerState === PlayerState.Paused) {
this.cursorUpdateBeat(this._selectionStart.beat, null, 0, false, [this._selectionStart.beat]);
}
this.tickPosition = realMasterBarStart + this._selectionStart.beat.playbackStart;
// set playback range
if (this._selectionEnd && this._selectionStart.beat !== this._selectionEnd.beat) {
let realMasterBarEnd: number = tickCache.getMasterBarStart(
this._selectionEnd.beat.voice.bar.masterBar
);
let range = new PlaybackRange();
range.startTick = realMasterBarStart + this._selectionStart.beat.playbackStart;
range.endTick =
realMasterBarEnd +
this._selectionEnd.beat.playbackStart +
this._selectionEnd.beat.playbackDuration -
50;
this.playbackRange = range;
} else {
this._selectionStart = null;
this.playbackRange = null;
this.cursorSelectRange(this._selectionStart, this._selectionEnd);
}
}
}
(this.beatMouseUp as EventEmitterOfT<Beat | null>).trigger(beat);
this.uiFacade.triggerEvent(this.container, 'beatMouseUp', beat, originalEvent);
this._beatMouseDown = false;
}
private setupClickHandling(): void {
this.canvasElement.mouseDown.on(e => {
if (!e.isLeftMouseButton) {
return;
}
if (this.settings.player.enableUserInteraction) {
e.preventDefault();
}
let relX: number = e.getX(this.canvasElement);
let relY: number = e.getY(this.canvasElement);
let beat: Beat | null = this.renderer.boundsLookup?.getBeatAtPos(relX, relY) ?? null;
if (beat) {
this.onBeatMouseDown(e, beat);
}
});
this.canvasElement.mouseMove.on(e => {
if (!this._beatMouseDown) {
return;
}
let relX: number = e.getX(this.canvasElement);
let relY: number = e.getY(this.canvasElement);
let beat: Beat | null = this.renderer.boundsLookup?.getBeatAtPos(relX, relY) ?? null;
if (beat) {
this.onBeatMouseMove(e, beat);
}
});
this.canvasElement.mouseUp.on(e => {
if (!this._beatMouseDown) {
return;
}
if (this.settings.player.enableUserInteraction) {
e.preventDefault();
}
let relX: number = e.getX(this.canvasElement);
let relY: number = e.getY(this.canvasElement);
let beat: Beat | null = this.renderer.boundsLookup?.getBeatAtPos(relX, relY) ?? null;
this.onBeatMouseUp(e, beat);
});
this.renderer.postRenderFinished.on(() => {
if (
!this._selectionStart ||
!this.settings.player.enablePlayer ||
!this.settings.player.enableCursor ||
!this.settings.player.enableUserInteraction
) {
return;
}
this.cursorSelectRange(this._selectionStart, this._selectionEnd);
});
}
private cursorSelectRange(startBeat: SelectionInfo | null, endBeat: SelectionInfo | null): void {