-
Notifications
You must be signed in to change notification settings - Fork 311
/
Copy pathScoreSequencer.vue
1715 lines (1586 loc) · 50.8 KB
/
ScoreSequencer.vue
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
<template>
<div class="score-sequencer">
<!-- 左上の角 -->
<div class="sequencer-corner"></div>
<!-- ルーラー -->
<SequencerRuler
class="sequencer-ruler"
:offset="scrollX"
:num-of-measures="numOfMeasures"
/>
<!-- 鍵盤 -->
<SequencerKeys
class="sequencer-keys"
:offset="scrollY"
:black-key-width="28"
/>
<!-- シーケンサ -->
<div
ref="sequencerBody"
class="sequencer-body"
:class="{
'rect-selecting': editTarget === 'NOTE' && shiftKey,
'cursor-draw': editTarget === 'PITCH' && !ctrlKey,
}"
aria-label="シーケンサ"
@mousedown="onMouseDown"
@mousemove="onMouseMove"
@mouseup="onMouseUp"
@dblclick="onDoubleClick"
@mouseenter="onMouseEnter"
@mouseleave="onMouseLeave"
@wheel="onWheel"
@scroll="onScroll"
@contextmenu.prevent
>
<!-- キャラクター全身 -->
<CharacterPortrait />
<!-- グリッド -->
<!-- NOTE: 現状オクターブごとの罫線なし -->
<svg
xmlns="http://www.w3.org/2000/svg"
:width="gridWidth"
:height="gridHeight"
class="sequencer-grid"
>
<defs>
<pattern
id="sequencer-grid-octave-cells"
patternUnits="userSpaceOnUse"
:width="gridCellWidth"
:height="gridCellHeight * 12"
>
<rect
v-for="(keyInfo, index) in keyInfos"
:key="index"
x="0"
:y="gridCellHeight * index"
:width="gridCellWidth"
:height="gridCellHeight"
:class="`sequencer-grid-cell sequencer-grid-cell-${keyInfo.color}`"
/>
<template v-for="(keyInfo, index) in keyInfos" :key="index">
<line
v-if="keyInfo.pitch === 'C'"
x1="0"
:x2="gridCellWidth"
:y1="gridCellHeight * (index + 1)"
:y2="gridCellHeight * (index + 1)"
stroke-width="1"
class="sequencer-grid-octave-line"
/>
</template>
</pattern>
<pattern
id="sequencer-grid-measure"
patternUnits="userSpaceOnUse"
:width="beatWidth * beatsPerMeasure"
:height="gridHeight"
>
<line
v-for="n in beatsPerMeasure"
:key="n"
:x1="beatWidth * (n - 1)"
:x2="beatWidth * (n - 1)"
y1="0"
y2="100%"
stroke-width="1"
:class="`sequencer-grid-${n === 1 ? 'measure' : 'beat'}-line`"
/>
</pattern>
</defs>
<rect
x="0"
y="0"
width="100%"
height="100%"
fill="url(#sequencer-grid-octave-cells)"
/>
<rect
x="0"
y="0"
width="100%"
height="100%"
fill="url(#sequencer-grid-measure)"
/>
</svg>
<div
v-if="editTarget === 'NOTE' && showGuideLine"
class="sequencer-guideline"
:style="{
height: `${gridHeight}px`,
transform: `translateX(${guideLineX}px)`,
}"
></div>
<!-- TODO: 1つのv-forで全てのノートを描画できるようにする -->
<!-- undefinedだと警告が出るのでnullを渡す -->
<SequencerNote
v-for="note in unselectedNotes"
:key="note.id"
:note="note"
:preview-lyric="previewLyrics.get(note.id) || null"
:is-selected="false"
@bar-mousedown="onNoteBarMouseDown($event, note)"
@left-edge-mousedown="onNoteLeftEdgeMouseDown($event, note)"
@right-edge-mousedown="onNoteRightEdgeMouseDown($event, note)"
@lyric-mouse-down="onNoteLyricMouseDown($event, note)"
@lyric-input="onNoteLyricInput($event, note)"
@lyric-blur="onNoteLyricBlur()"
/>
<SequencerNote
v-for="note in editTarget === 'NOTE' && nowPreviewing
? previewNotes
: selectedNotes"
:key="note.id"
:note="note"
:preview-lyric="previewLyrics.get(note.id) || null"
:is-selected="true"
@bar-mousedown="onNoteBarMouseDown($event, note)"
@left-edge-mousedown="onNoteLeftEdgeMouseDown($event, note)"
@right-edge-mousedown="onNoteRightEdgeMouseDown($event, note)"
@lyric-mouse-down="onNoteLyricMouseDown($event, note)"
@lyric-input="onNoteLyricInput($event, note)"
@lyric-blur="onNoteLyricBlur()"
/>
</div>
<SequencerPitch
v-if="editTarget === 'PITCH'"
class="sequencer-pitch"
:style="{
marginRight: `${scrollBarWidth}px`,
marginBottom: `${scrollBarWidth}px`,
}"
:offset-x="scrollX"
:offset-y="scrollY"
:preview-pitch-edit="previewPitchEdit"
/>
<div
class="sequencer-overlay"
:style="{
marginRight: `${scrollBarWidth}px`,
marginBottom: `${scrollBarWidth}px`,
}"
>
<div
ref="rectSelectHitbox"
class="rect-select-preview"
:style="{
display: isRectSelecting ? 'block' : 'none',
left: `${Math.min(rectSelectStartX, cursorX)}px`,
top: `${Math.min(rectSelectStartY, cursorY)}px`,
width: `${Math.abs(cursorX - rectSelectStartX)}px`,
height: `${Math.abs(cursorY - rectSelectStartY)}px`,
}"
/>
<SequencerPhraseIndicator
v-for="phraseInfo in phraseInfos"
:key="phraseInfo.key"
:phrase-key="phraseInfo.key"
class="sequencer-phrase-indicator"
:style="{
width: `${phraseInfo.width}px`,
transform: `translateX(${phraseInfo.x - scrollX}px)`,
}"
/>
<div
class="sequencer-playhead"
data-testid="sequencer-playhead"
:style="{
transform: `translateX(${playheadX - scrollX}px)`,
}"
></div>
</div>
<input
type="range"
:min="ZOOM_X_MIN"
:max="ZOOM_X_MAX"
:step="ZOOM_X_STEP"
:value="zoomX"
:style="{
position: 'fixed',
zIndex: 100,
bottom: '20px',
right: '36px',
width: '80px',
}"
@input="setZoomX"
/>
<input
type="range"
:min="ZOOM_Y_MIN"
:max="ZOOM_Y_MAX"
:step="ZOOM_Y_STEP"
:value="zoomY"
:style="{
position: 'fixed',
zIndex: 100,
bottom: '68px',
right: '-12px',
transform: 'rotate(-90deg)',
width: '80px',
}"
@input="setZoomY"
/>
<ContextMenu
v-if="editTarget === 'NOTE'"
ref="contextMenu"
:menudata="contextMenuData"
/>
</div>
</template>
<script setup lang="ts">
import {
computed,
ref,
nextTick,
onMounted,
onActivated,
onDeactivated,
} from "vue";
import { v4 as uuidv4 } from "uuid";
import ContextMenu, {
ContextMenuItemData,
} from "@/components/Menu/ContextMenu.vue";
import { isMac } from "@/type/preload";
import { useStore } from "@/store";
import { Note, SequencerEditTarget } from "@/store/type";
import {
getEndTicksOfPhrase,
getMeasureDuration,
getNoteDuration,
getNumOfMeasures,
getStartTicksOfPhrase,
noteNumberToFrequency,
tickToSecond,
} from "@/sing/domain";
import {
getKeyBaseHeight,
tickToBaseX,
baseXToTick,
noteNumberToBaseY,
baseYToNoteNumber,
keyInfos,
getDoremiFromNoteNumber,
ZOOM_X_MIN,
ZOOM_X_MAX,
ZOOM_X_STEP,
ZOOM_Y_MIN,
ZOOM_Y_MAX,
ZOOM_Y_STEP,
PREVIEW_SOUND_DURATION,
DoubleClickDetector,
NoteAreaInfo,
GridAreaInfo,
getButton,
} from "@/sing/viewHelper";
import SequencerRuler from "@/components/Sing/SequencerRuler.vue";
import SequencerKeys from "@/components/Sing/SequencerKeys.vue";
import SequencerNote from "@/components/Sing/SequencerNote.vue";
import SequencerPhraseIndicator from "@/components/Sing/SequencerPhraseIndicator.vue";
import CharacterPortrait from "@/components/Sing/CharacterPortrait.vue";
import SequencerPitch from "@/components/Sing/SequencerPitch.vue";
import { isOnCommandOrCtrlKeyDown } from "@/store/utility";
import { createLogger } from "@/domain/frontend/log";
import { useHotkeyManager } from "@/plugins/hotkeyPlugin";
import {
useCommandOrControlKey,
useShiftKey,
} from "@/composables/useModifierKey";
import { applyGaussianFilter, linearInterpolation } from "@/sing/utility";
import { useLyricInput } from "@/composables/useLyricInput";
import { ExhaustiveError } from "@/type/utility";
type PreviewMode =
| "ADD"
| "MOVE"
| "RESIZE_RIGHT"
| "RESIZE_LEFT"
| "DRAW_PITCH"
| "ERASE_PITCH";
// 直接イベントが来ているかどうか
const isSelfEventTarget = (event: UIEvent) => {
return event.target === event.currentTarget;
};
const store = useStore();
const { warn } = createLogger("ScoreSequencer");
const state = store.state;
// 分解能(Ticks Per Quarter Note)
const tpqn = computed(() => state.tpqn);
// テンポ
const tempos = computed(() => state.tempos);
// 拍子
const timeSignatures = computed(() => state.timeSignatures);
// ノート
const notes = computed(() => store.getters.SELECTED_TRACK.notes);
const isNoteSelected = computed(() => {
return state.selectedNoteIds.size > 0;
});
const unselectedNotes = computed(() => {
const selectedNoteIds = state.selectedNoteIds;
return notes.value.filter((value) => !selectedNoteIds.has(value.id));
});
const selectedNotes = computed(() => {
const selectedNoteIds = state.selectedNoteIds;
return notes.value.filter((value) => selectedNoteIds.has(value.id));
});
// 矩形選択
const shiftKey = useShiftKey();
const isRectSelecting = ref(false);
const rectSelectStartX = ref(0);
const rectSelectStartY = ref(0);
const rectSelectHitbox = ref<HTMLElement | undefined>(undefined);
// ズーム状態
const zoomX = computed(() => state.sequencerZoomX);
const zoomY = computed(() => state.sequencerZoomY);
// スナップ
const snapTicks = computed(() => {
return getNoteDuration(state.sequencerSnapType, tpqn.value);
});
// シーケンサグリッド
const gridCellTicks = snapTicks; // ひとまずスナップ幅=グリッドセル幅
const gridCellWidth = computed(() => {
return tickToBaseX(gridCellTicks.value, tpqn.value) * zoomX.value;
});
const gridCellBaseHeight = getKeyBaseHeight();
const gridCellHeight = computed(() => {
return gridCellBaseHeight * zoomY.value;
});
const numOfMeasures = computed(() => {
// NOTE: 最低長: 仮32小節...スコア長(曲長さ)が決まっていないため、無限スクロール化する or 最後尾に足した場合は伸びるようにするなど?
const minNumOfMeasures = 32;
// NOTE: いったん最後尾に足した場合は伸びるようにする
return Math.max(
minNumOfMeasures,
getNumOfMeasures(
notes.value,
tempos.value,
timeSignatures.value,
tpqn.value,
) + 1,
);
});
const beatsPerMeasure = computed(() => {
return timeSignatures.value[0].beats;
});
const beatWidth = computed(() => {
const beatType = timeSignatures.value[0].beatType;
const wholeNoteDuration = tpqn.value * 4;
const beatTicks = wholeNoteDuration / beatType;
return tickToBaseX(beatTicks, tpqn.value) * zoomX.value;
});
const gridWidth = computed(() => {
// TODO: 複数拍子に対応する
const beats = timeSignatures.value[0].beats;
const beatType = timeSignatures.value[0].beatType;
const measureDuration = getMeasureDuration(beats, beatType, tpqn.value);
const numOfGridColumns =
Math.round(measureDuration / gridCellTicks.value) * numOfMeasures.value;
return gridCellWidth.value * numOfGridColumns;
});
const gridHeight = computed(() => {
return gridCellHeight.value * keyInfos.length;
});
// スクロール位置
const scrollX = ref(0);
const scrollY = ref(0);
// 再生ヘッドの位置
const playheadTicks = ref(0);
const playheadX = computed(() => {
const baseX = tickToBaseX(playheadTicks.value, tpqn.value);
return Math.floor(baseX * zoomX.value);
});
// フレーズ
const phraseInfos = computed(() => {
return [...state.phrases.entries()].map(([key, phrase]) => {
const startTicks = getStartTicksOfPhrase(phrase);
const endTicks = getEndTicksOfPhrase(phrase);
const startBaseX = tickToBaseX(startTicks, tpqn.value);
const endBaseX = tickToBaseX(endTicks, tpqn.value);
const startX = startBaseX * zoomX.value;
const endX = endBaseX * zoomX.value;
return { key, x: startX, width: endX - startX };
});
});
const ctrlKey = useCommandOrControlKey();
const editTarget = computed(() => state.sequencerEditTarget);
const editFrameRate = computed(() => state.editFrameRate);
const scrollBarWidth = ref(12);
const sequencerBody = ref<HTMLElement | null>(null);
// マウスカーソル位置
const cursorX = ref(0);
const cursorY = ref(0);
// 歌詞入力
const { previewLyrics, commitPreviewLyrics, splitAndUpdatePreview } =
useLyricInput();
const onNoteLyricInput = (text: string, note: Note) => {
splitAndUpdatePreview(text, note);
};
const onNoteLyricBlur = () => {
commitPreviewLyrics();
};
// プレビュー
// FIXME: 関連する値を1つのobjectにまとめる
const nowPreviewing = ref(false);
let previewMode: PreviewMode = "ADD";
let previewRequestId = 0;
let previewStartEditTarget: SequencerEditTarget = "NOTE";
let executePreviewProcess = false;
// ノート編集のプレビュー
const previewNotes = ref<Note[]>([]);
const copiedNotesForPreview = new Map<string, Note>();
let dragStartTicks = 0;
let dragStartNoteNumber = 0;
let dragStartGuideLineTicks = 0;
let draggingNoteId = ""; // FIXME: 無効状態はstring以外の型にする
let edited = false; // プレビュー終了時にstore.stateの更新を行うかどうかを表す変数
// ピッチ編集のプレビュー
const previewPitchEdit = ref<
| { type: "draw"; data: number[]; startFrame: number }
| { type: "erase"; startFrame: number; frameLength: number }
| undefined
>(undefined);
const prevCursorPos = { frame: 0, frequency: 0 }; // 前のカーソル位置
// ダブルクリック
let mouseDownAreaInfo: NoteAreaInfo | GridAreaInfo | undefined;
const doubleClickDetector = new DoubleClickDetector<
NoteAreaInfo | GridAreaInfo
>();
let ignoreDoubleClick = false;
// 入力を補助する線
const showGuideLine = ref(true);
const guideLineX = ref(0);
const previewAdd = () => {
const cursorBaseX = (scrollX.value + cursorX.value) / zoomX.value;
const cursorTicks = baseXToTick(cursorBaseX, tpqn.value);
const draggingNote = copiedNotesForPreview.get(draggingNoteId);
if (!draggingNote) {
throw new Error("draggingNote is undefined.");
}
const dragTicks = cursorTicks - dragStartTicks;
const noteDuration =
Math.round(dragTicks / snapTicks.value) * snapTicks.value;
const noteEndPos = draggingNote.position + noteDuration;
const editedNotes = new Map<string, Note>();
for (const note of previewNotes.value) {
const copiedNote = copiedNotesForPreview.get(note.id);
if (!copiedNote) {
throw new Error("copiedNote is undefined.");
}
const duration = Math.max(snapTicks.value, noteDuration);
if (note.duration !== duration) {
editedNotes.set(note.id, { ...note, duration });
}
}
if (editedNotes.size !== 0) {
previewNotes.value = previewNotes.value.map((value) => {
return editedNotes.get(value.id) ?? value;
});
}
const guideLineBaseX = tickToBaseX(noteEndPos, tpqn.value);
guideLineX.value = guideLineBaseX * zoomX.value;
};
const previewMove = () => {
const cursorBaseX = (scrollX.value + cursorX.value) / zoomX.value;
const cursorBaseY = (scrollY.value + cursorY.value) / zoomY.value;
const cursorTicks = baseXToTick(cursorBaseX, tpqn.value);
const cursorNoteNumber = baseYToNoteNumber(cursorBaseY);
const draggingNote = copiedNotesForPreview.get(draggingNoteId);
if (!draggingNote) {
throw new Error("draggingNote is undefined.");
}
const dragTicks = cursorTicks - dragStartTicks;
const notePos = draggingNote.position;
const newNotePos =
Math.round((notePos + dragTicks) / snapTicks.value) * snapTicks.value;
const movingTicks = newNotePos - notePos;
const movingSemitones = cursorNoteNumber - dragStartNoteNumber;
const editedNotes = new Map<string, Note>();
for (const note of previewNotes.value) {
const copiedNote = copiedNotesForPreview.get(note.id);
if (!copiedNote) {
throw new Error("copiedNote is undefined.");
}
const position = copiedNote.position + movingTicks;
const noteNumber = copiedNote.noteNumber + movingSemitones;
if (note.position !== position || note.noteNumber !== noteNumber) {
editedNotes.set(note.id, { ...note, noteNumber, position });
}
}
for (const note of editedNotes.values()) {
if (note.position < 0) {
// 左端より前はドラッグしない
return;
}
}
if (editedNotes.size !== 0) {
previewNotes.value = previewNotes.value.map((value) => {
return editedNotes.get(value.id) ?? value;
});
edited = true;
}
const guideLineBaseX = tickToBaseX(
dragStartGuideLineTicks + movingTicks,
tpqn.value,
);
guideLineX.value = guideLineBaseX * zoomX.value;
};
const previewResizeRight = () => {
const cursorBaseX = (scrollX.value + cursorX.value) / zoomX.value;
const cursorTicks = baseXToTick(cursorBaseX, tpqn.value);
const draggingNote = copiedNotesForPreview.get(draggingNoteId);
if (!draggingNote) {
throw new Error("draggingNote is undefined.");
}
const dragTicks = cursorTicks - dragStartTicks;
const noteEndPos = draggingNote.position + draggingNote.duration;
const newNoteEndPos =
Math.round((noteEndPos + dragTicks) / snapTicks.value) * snapTicks.value;
const movingTicks = newNoteEndPos - noteEndPos;
const editedNotes = new Map<string, Note>();
for (const note of previewNotes.value) {
const copiedNote = copiedNotesForPreview.get(note.id);
if (!copiedNote) {
throw new Error("copiedNote is undefined.");
}
const notePos = copiedNote.position;
const noteEndPos = copiedNote.position + copiedNote.duration;
const duration = Math.max(
snapTicks.value,
noteEndPos + movingTicks - notePos,
);
if (note.duration !== duration) {
editedNotes.set(note.id, { ...note, duration });
}
}
if (editedNotes.size !== 0) {
previewNotes.value = previewNotes.value.map((value) => {
return editedNotes.get(value.id) ?? value;
});
edited = true;
}
const guideLineBaseX = tickToBaseX(newNoteEndPos, tpqn.value);
guideLineX.value = guideLineBaseX * zoomX.value;
};
const previewResizeLeft = () => {
const cursorBaseX = (scrollX.value + cursorX.value) / zoomX.value;
const cursorTicks = baseXToTick(cursorBaseX, tpqn.value);
const draggingNote = copiedNotesForPreview.get(draggingNoteId);
if (!draggingNote) {
throw new Error("draggingNote is undefined.");
}
const dragTicks = cursorTicks - dragStartTicks;
const notePos = draggingNote.position;
const newNotePos =
Math.round((notePos + dragTicks) / snapTicks.value) * snapTicks.value;
const movingTicks = newNotePos - notePos;
const editedNotes = new Map<string, Note>();
for (const note of previewNotes.value) {
const copiedNote = copiedNotesForPreview.get(note.id);
if (!copiedNote) {
throw new Error("copiedNote is undefined.");
}
const notePos = copiedNote.position;
const noteEndPos = copiedNote.position + copiedNote.duration;
const position = Math.min(
noteEndPos - snapTicks.value,
notePos + movingTicks,
);
const duration = noteEndPos - position;
if (note.position !== position && note.duration !== duration) {
editedNotes.set(note.id, { ...note, position, duration });
}
}
for (const note of editedNotes.values()) {
if (note.position < 0) {
// 左端より前はドラッグしない
return;
}
}
if (editedNotes.size !== 0) {
previewNotes.value = previewNotes.value.map((value) => {
return editedNotes.get(value.id) ?? value;
});
edited = true;
}
const guideLineBaseX = tickToBaseX(newNotePos, tpqn.value);
guideLineX.value = guideLineBaseX * zoomX.value;
};
// ピッチを描く処理を行う
const previewDrawPitch = () => {
if (previewPitchEdit.value == undefined) {
throw new Error("previewPitchEdit.value is undefined.");
}
if (previewPitchEdit.value.type !== "draw") {
throw new Error("previewPitchEdit.value.type is not draw.");
}
const frameRate = editFrameRate.value;
const cursorBaseX = (scrollX.value + cursorX.value) / zoomX.value;
const cursorBaseY = (scrollY.value + cursorY.value) / zoomY.value;
const cursorTicks = baseXToTick(cursorBaseX, tpqn.value);
const cursorSeconds = tickToSecond(cursorTicks, tempos.value, tpqn.value);
const cursorFrame = Math.round(cursorSeconds * frameRate);
const cursorNoteNumber = baseYToNoteNumber(cursorBaseY, false);
const cursorFrequency = noteNumberToFrequency(cursorNoteNumber);
if (cursorFrame < 0) {
return;
}
const tempPitchEdit = {
...previewPitchEdit.value,
data: [...previewPitchEdit.value.data],
};
if (cursorFrame < tempPitchEdit.startFrame) {
const numOfFramesToUnshift = tempPitchEdit.startFrame - cursorFrame;
tempPitchEdit.data = new Array(numOfFramesToUnshift)
.fill(0)
.concat(tempPitchEdit.data);
tempPitchEdit.startFrame = cursorFrame;
}
const lastFrame = tempPitchEdit.startFrame + tempPitchEdit.data.length - 1;
if (cursorFrame > lastFrame) {
const numOfFramesToPush = cursorFrame - lastFrame;
tempPitchEdit.data = tempPitchEdit.data.concat(
new Array(numOfFramesToPush).fill(0),
);
}
if (cursorFrame === prevCursorPos.frame) {
const i = cursorFrame - tempPitchEdit.startFrame;
tempPitchEdit.data[i] = cursorFrequency;
} else if (cursorFrame < prevCursorPos.frame) {
for (let i = cursorFrame; i <= prevCursorPos.frame; i++) {
tempPitchEdit.data[i - tempPitchEdit.startFrame] = Math.exp(
linearInterpolation(
cursorFrame,
Math.log(cursorFrequency),
prevCursorPos.frame,
Math.log(prevCursorPos.frequency),
i,
),
);
}
} else {
for (let i = prevCursorPos.frame; i <= cursorFrame; i++) {
tempPitchEdit.data[i - tempPitchEdit.startFrame] = Math.exp(
linearInterpolation(
prevCursorPos.frame,
Math.log(prevCursorPos.frequency),
cursorFrame,
Math.log(cursorFrequency),
i,
),
);
}
}
previewPitchEdit.value = tempPitchEdit;
prevCursorPos.frame = cursorFrame;
prevCursorPos.frequency = cursorFrequency;
};
// ドラッグした範囲のピッチ編集データを消去する処理を行う
const previewErasePitch = () => {
if (previewPitchEdit.value == undefined) {
throw new Error("previewPitchEdit.value is undefined.");
}
if (previewPitchEdit.value.type !== "erase") {
throw new Error("previewPitchEdit.value.type is not erase.");
}
const frameRate = editFrameRate.value;
const cursorBaseX = (scrollX.value + cursorX.value) / zoomX.value;
const cursorTicks = baseXToTick(cursorBaseX, tpqn.value);
const cursorSeconds = tickToSecond(cursorTicks, tempos.value, tpqn.value);
const cursorFrame = Math.round(cursorSeconds * frameRate);
if (cursorFrame < 0) {
return;
}
const tempPitchEdit = { ...previewPitchEdit.value };
if (tempPitchEdit.startFrame > cursorFrame) {
tempPitchEdit.frameLength += tempPitchEdit.startFrame - cursorFrame;
tempPitchEdit.startFrame = cursorFrame;
}
const lastFrame = tempPitchEdit.startFrame + tempPitchEdit.frameLength - 1;
if (lastFrame < cursorFrame) {
tempPitchEdit.frameLength += cursorFrame - lastFrame;
}
previewPitchEdit.value = tempPitchEdit;
prevCursorPos.frame = cursorFrame;
};
const preview = () => {
if (executePreviewProcess) {
if (previewMode === "ADD") {
previewAdd();
}
if (previewMode === "MOVE") {
previewMove();
}
if (previewMode === "RESIZE_RIGHT") {
previewResizeRight();
}
if (previewMode === "RESIZE_LEFT") {
previewResizeLeft();
}
if (previewMode === "DRAW_PITCH") {
previewDrawPitch();
}
if (previewMode === "ERASE_PITCH") {
previewErasePitch();
}
executePreviewProcess = false;
}
previewRequestId = requestAnimationFrame(preview);
};
const getXInBorderBox = (clientX: number, element: HTMLElement) => {
return clientX - element.getBoundingClientRect().left;
};
const getYInBorderBox = (clientY: number, element: HTMLElement) => {
return clientY - element.getBoundingClientRect().top;
};
const selectOnlyThis = (note: Note) => {
store.dispatch("DESELECT_ALL_NOTES");
store.dispatch("SELECT_NOTES", { noteIds: [note.id] });
store.dispatch("PLAY_PREVIEW_SOUND", {
noteNumber: note.noteNumber,
duration: PREVIEW_SOUND_DURATION,
});
};
const startPreview = (event: MouseEvent, mode: PreviewMode, note?: Note) => {
if (nowPreviewing.value) {
warn("startPreview was called during preview.");
return;
}
const sequencerBodyElement = sequencerBody.value;
if (!sequencerBodyElement) {
throw new Error("sequencerBodyElement is null.");
}
cursorX.value = getXInBorderBox(event.clientX, sequencerBodyElement);
cursorY.value = getYInBorderBox(event.clientY, sequencerBodyElement);
if (cursorX.value >= sequencerBodyElement.clientWidth) {
return;
}
if (cursorY.value >= sequencerBodyElement.clientHeight) {
return;
}
const cursorBaseX = (scrollX.value + cursorX.value) / zoomX.value;
const cursorBaseY = (scrollY.value + cursorY.value) / zoomY.value;
if (editTarget.value === "NOTE") {
// 編集ターゲットがノートのときの処理
const cursorTicks = baseXToTick(cursorBaseX, tpqn.value);
const cursorNoteNumber = baseYToNoteNumber(cursorBaseY, true);
// NOTE: 入力を補助する線の判定の境目はスナップ幅の3/4の位置
const guideLineTicks =
Math.round(cursorTicks / snapTicks.value - 0.25) * snapTicks.value;
const copiedNotes: Note[] = [];
if (mode === "ADD") {
if (cursorNoteNumber < 0) {
return;
}
note = {
id: uuidv4(),
position: guideLineTicks,
duration: snapTicks.value,
noteNumber: cursorNoteNumber,
lyric: getDoremiFromNoteNumber(cursorNoteNumber),
};
store.dispatch("DESELECT_ALL_NOTES");
copiedNotes.push(note);
} else {
if (!note) {
throw new Error("note is undefined.");
}
if (event.shiftKey) {
let minIndex = notes.value.length - 1;
let maxIndex = 0;
for (let i = 0; i < notes.value.length; i++) {
const noteId = notes.value[i].id;
if (state.selectedNoteIds.has(noteId) || noteId === note.id) {
minIndex = Math.min(minIndex, i);
maxIndex = Math.max(maxIndex, i);
}
}
const noteIdsToSelect: string[] = [];
for (let i = minIndex; i <= maxIndex; i++) {
const noteId = notes.value[i].id;
if (!state.selectedNoteIds.has(noteId)) {
noteIdsToSelect.push(noteId);
}
}
store.dispatch("SELECT_NOTES", { noteIds: noteIdsToSelect });
} else if (isOnCommandOrCtrlKeyDown(event)) {
store.dispatch("SELECT_NOTES", { noteIds: [note.id] });
} else if (!state.selectedNoteIds.has(note.id)) {
selectOnlyThis(note);
}
for (const note of selectedNotes.value) {
copiedNotes.push({ ...note });
}
}
dragStartTicks = cursorTicks;
dragStartNoteNumber = cursorNoteNumber;
dragStartGuideLineTicks = guideLineTicks;
draggingNoteId = note.id;
edited = mode === "ADD";
copiedNotesForPreview.clear();
for (const copiedNote of copiedNotes) {
copiedNotesForPreview.set(copiedNote.id, copiedNote);
}
previewNotes.value = copiedNotes;
} else if (editTarget.value === "PITCH") {
// 編集ターゲットがピッチのときの処理
const frameRate = editFrameRate.value;
const cursorTicks = baseXToTick(cursorBaseX, tpqn.value);
const cursorSeconds = tickToSecond(cursorTicks, tempos.value, tpqn.value);
const cursorFrame = Math.round(cursorSeconds * frameRate);
const cursorNoteNumber = baseYToNoteNumber(cursorBaseY, false);
const cursorFrequency = noteNumberToFrequency(cursorNoteNumber);
if (mode === "DRAW_PITCH") {
previewPitchEdit.value = {
type: "draw",
data: [cursorFrequency],
startFrame: cursorFrame,
};
} else if (mode === "ERASE_PITCH") {
previewPitchEdit.value = {
type: "erase",
startFrame: cursorFrame,
frameLength: 1,
};
} else {
throw new Error("Unknown preview mode.");
}
prevCursorPos.frame = cursorFrame;
prevCursorPos.frequency = cursorFrequency;
} else {
throw new ExhaustiveError(editTarget.value);
}
previewMode = mode;
previewStartEditTarget = editTarget.value;
executePreviewProcess = true;
nowPreviewing.value = true;
previewRequestId = requestAnimationFrame(preview);
};
const endPreview = () => {
cancelAnimationFrame(previewRequestId);
if (previewStartEditTarget === "NOTE") {
// 編集ターゲットがノートのときにプレビューを開始した場合の処理
if (edited) {
if (previewMode === "ADD") {
store.dispatch("COMMAND_ADD_NOTES", { notes: previewNotes.value });
store.dispatch("SELECT_NOTES", {
noteIds: previewNotes.value.map((value) => value.id),
});
} else {
store.dispatch("COMMAND_UPDATE_NOTES", { notes: previewNotes.value });
}
if (previewNotes.value.length === 1) {
store.dispatch("PLAY_PREVIEW_SOUND", {
noteNumber: previewNotes.value[0].noteNumber,
duration: PREVIEW_SOUND_DURATION,
});
}
}
} else if (previewStartEditTarget === "PITCH") {
// 編集ターゲットがピッチのときにプレビューを開始した場合の処理
if (previewPitchEdit.value == undefined) {
throw new Error("previewPitchEdit.value is undefined.");
}
const previewPitchEditType = previewPitchEdit.value.type;
if (previewPitchEditType === "draw") {
// カーソルを動かさずにマウスのボタンを離したときに1フレームのみの変更になり、
// 1フレームの変更はピッチ編集ラインとして表示されないので、無視する
if (previewPitchEdit.value.data.length >= 2) {
// 平滑化を行う
let data = previewPitchEdit.value.data;
data = data.map((value) => Math.log(value));
applyGaussianFilter(data, 0.7);
data = data.map((value) => Math.exp(value));
store.dispatch("COMMAND_SET_PITCH_EDIT_DATA", {
data,
startFrame: previewPitchEdit.value.startFrame,
});
}
} else if (previewPitchEditType === "erase") {
store.dispatch("COMMAND_ERASE_PITCH_EDIT_DATA", {
startFrame: previewPitchEdit.value.startFrame,
frameLength: previewPitchEdit.value.frameLength,
});
} else {
throw new ExhaustiveError(previewPitchEditType);
}
previewPitchEdit.value = undefined;
} else {
throw new ExhaustiveError(previewStartEditTarget);
}
nowPreviewing.value = false;
};
const onNoteBarMouseDown = (event: MouseEvent, note: Note) => {
if (editTarget.value !== "NOTE" || !isSelfEventTarget(event)) {
return;
}
const mouseButton = getButton(event);
// ダブルクリック用の処理を行う
if (mouseButton === "LEFT_BUTTON") {
mouseDownAreaInfo = new NoteAreaInfo(note.id);
}
if (mouseButton === "LEFT_BUTTON") {
startPreview(event, "MOVE", note);
} else if (!state.selectedNoteIds.has(note.id)) {
selectOnlyThis(note);
}
};
const onNoteLeftEdgeMouseDown = (event: MouseEvent, note: Note) => {
if (editTarget.value !== "NOTE" || !isSelfEventTarget(event)) {
return;
}
const mouseButton = getButton(event);
// ダブルクリック用の処理を行う
if (mouseButton === "LEFT_BUTTON") {
mouseDownAreaInfo = new NoteAreaInfo(note.id);
}
if (mouseButton === "LEFT_BUTTON") {
startPreview(event, "RESIZE_LEFT", note);
} else if (!state.selectedNoteIds.has(note.id)) {
selectOnlyThis(note);
}
};