-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPianoRoll.py
More file actions
1304 lines (1022 loc) · 52.7 KB
/
PianoRoll.py
File metadata and controls
1304 lines (1022 loc) · 52.7 KB
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 bisect
import pygame
import pygame.gfxdraw
import pygame.midi
import sys
from UIComponents import Button, Scrollbar
from Config import WHITE, BLACK, DARK_GRAY, RED, WINDOW_W, WINDOW_H, \
KEY_W, NOTES, BAR_HEIGHT, \
NOTE_NAMES, SCROLLBAR_W, TOOLBAR_H,\
TRACK_COLORS, PPQ, fonts, BAR_COLOR, TRACKS_HEIGHT
from Note import Note
from utils import is_black, clamp, get_note_name
# ---------------- PianoRoll ----------------
class PianoRoll:
def __init__(self, midi_manager):
# 1. Core Engine & State
self.current_playhead_px = 0
self.last_frame_tick = 0
self.draw_measure = True
self.draw_beats = True
self.draw_8ths = True
self.draw_32nds = False
self.label_step = 1
self.draw_16ths = True
self.midi_manager = midi_manager
self.previewing_note = None
self.dragging_playhead = False
self.clipboard = []
self.selected_notes = []
self.last_hovered_key_idx = None
# 2. Viewport & Scaling Constants
self.margin = 10
self.zoom_speed = 0.25
self.zoom_anchor_tick = 0
self.update_scale_mask()
# 3. Layout Dimensions
self.bar_height = BAR_HEIGHT
self.scaled_key_w = KEY_W
self.roll_x = self.scaled_key_w + self.margin
self.roll_y = TOOLBAR_H + self.bar_height
self.last_note_duration = PPQ
self.last_note_velocity = 64
# Calculate width/height based on window config
self.roll_w = WINDOW_W - self.roll_x - self.margin
self.roll_h = WINDOW_H - self.roll_y - self.margin - TRACKS_HEIGHT
# 4. Project Length Initialization
# Calculate the initial 8-bar chunked boundary immediately
self.midi_manager.update_project_length()
# 5. Zoom & Grid Settings
self.cell_h = 16
self.max_cell_h = 40
self.min_cell_h = self.roll_h / 128
# Set starting view: fit exactly 8 bars into the window
bars_to_fit_8 = 5 * self.midi_manager.time_signature[0]
self.cell_w = self.roll_w / max(1, bars_to_fit_8)
self.target_cell_w = self.cell_w # Prevents startup "zoom jump"
# Set Max Zoom Limit: exactly 2 bars
bars_to_fit_2 = 2 * self.midi_manager.time_signature[0]
self.max_cell_w = self.roll_w / max(1, bars_to_fit_2)
# 6. Fonts
self.notes_surface = pygame.Surface((self.roll_w, self.roll_h), pygame.SRCALPHA).convert_alpha()
self.notes_need_update = True # New flag for dirty note rendering
# 7. Scrollbars & Surfaces
h_content_px = self.ticks_to_pixel(self.midi_manager.project_end_tick)
v_content_px = 128 * self.cell_h
self.h_scroll = Scrollbar(
self.roll_x, self.roll_y + self.roll_h - SCROLLBAR_W,
self.roll_w - SCROLLBAR_W, SCROLLBAR_W,
content_size=h_content_px, viewport_size=self.roll_w, orientation='horizontal'
)
self.v_scroll = Scrollbar(
self.roll_x + self.roll_w - SCROLLBAR_W, self.roll_y,
SCROLLBAR_W, self.roll_h,
content_size=v_content_px, viewport_size=self.roll_h, orientation='vertical'
)
# 8. Visual Elements & Interaction
self.offset_x = 0
self.offset_y = max(0, (v_content_px // 2) - (self.roll_h // 2)) # Center on Middle C area
self.v_scroll.offset = self.offset_y
self.selection_rect = None
self.dragging_scroll = False
self.selection_start_pos = None
self.keys_viewport = pygame.Surface((self.scaled_key_w, self.roll_h)).convert()
self.bar_rect = pygame.Rect(self.roll_x, self.roll_y - self.bar_height, self.roll_w, self.bar_height)
self.roll_rect = pygame.Rect(self.roll_x, self.roll_y, self.roll_w, self.roll_h)
self.bar_surface = pygame.Surface((self.roll_w, self.bar_height)).convert()
# 9. Key Buttons (Piano Keys)
self.key_buttons = []
for i in range(128):
midi_val = 127 - i
name = f"{NOTE_NAMES[midi_val % 12]}{(midi_val // 12) - 1}"
base_col = (30, 30, 30) if is_black(midi_val) else WHITE
text_col = WHITE if is_black(midi_val) else BLACK
btn = Button(0, 0, self.scaled_key_w, self.cell_h, name,
color=base_col, text_color=text_col, border_radius=0, border=True,
callback=lambda n=i: self._trigger_preview(n, 100))
self.key_buttons.append(btn)
self.grid_needs_update = True
self.grid_surface = pygame.Surface((self.roll_w, self.roll_h)).convert() # Opaque for speed
# 10. Final Sync
self.sync_project_boundaries()
def ticks_to_pixel(self, ticks):
return (ticks / PPQ) * self.cell_w
def pixel_to_ticks(self, px):
# New: Multiply first, then divide to keep precision
denominator = max(1e-6, self.cell_w)
return int((px * PPQ) / denominator)
def get_snapped_ticks(self, raw_ticks):
tps = self.midi_manager.ticks_per_snap
return (raw_ticks // tps) * tps
def resize(self, width, height):
self.grid_needs_update = True
self.notes_need_update = True
# 1. CAPTURE STATE BEFORE RESIZE
# Find the tick currently at the horizontal center of the viewport
center_tick = self.pixel_to_ticks(self.offset_x + self.roll_w / 2)
# Vertical zoom ratio (how many notes were visible)
top_note_index = self.offset_y / self.cell_h if self.cell_h > 0 else 60
visible_notes_count = self.roll_h / self.cell_h
visible_beats = self.roll_w / self.cell_w if self.cell_w > 0 else 0
self.roll_x = self.scaled_key_w + self.margin
self.roll_w = width - self.roll_x - self.margin
self.roll_h = height - self.roll_y - self.margin - TRACKS_HEIGHT
# 3. APPLY VERTICAL SCALING
self.cell_h = self.roll_h / visible_notes_count
self.min_cell_h = self.roll_h / 128
self.cell_h = max(self.min_cell_h, min(self.cell_h, self.max_cell_h))
# 4. APPLY HORIZONTAL SCALING (Maintain 8-bar zoom)
self.target_cell_w = self.roll_w / visible_beats
# Update min_cell_w based on project length so you can't zoom out into nothing
self.min_cell_w = self.roll_w / max(1, self.midi_manager.total_beats)
self.target_cell_w = max(self.min_cell_w, min(self.target_cell_w, self.max_cell_w))
self.cell_w = self.target_cell_w
self.keys_viewport = pygame.Surface((self.scaled_key_w, self.roll_h)).convert()
# 5. RE-CENTER HORIZONTAL VIEW
# Calculate where the new offset should be to keep that center_tick in the middle
new_center_px = self.ticks_to_pixel(center_tick)
self.offset_x = new_center_px - (self.roll_w / 2)
# Vertical: Keep the top_note_index at the top of the viewport
# This is the "Maintain Vertical Position" fix
self.offset_y = top_note_index * self.cell_h
# 6. RE-INITIALIZE SURFACES
self.roll_rect = pygame.Rect(self.roll_x, self.roll_y, self.roll_w, self.roll_h)
self.bar_surface = pygame.Surface((self.roll_w, self.bar_height)).convert()
# 7. SYNC SCROLLBARS & CLAMP
h_content_px = self.ticks_to_pixel(self.midi_manager.project_end_tick)
v_content_px = 128 * self.cell_h
self.offset_x = max(0, min(self.offset_x, max(0, h_content_px - self.roll_w)))
self.offset_y = max(0, min(self.offset_y, max(0, v_content_px - self.roll_h)))
self.h_scroll.rect = pygame.Rect(self.roll_x, self.roll_y + self.roll_h - SCROLLBAR_W,
self.roll_w - SCROLLBAR_W, SCROLLBAR_W)
self.h_scroll.viewport_size = self.roll_w
self.h_scroll.content_size = h_content_px
self.h_scroll.offset = self.offset_x
self.v_scroll.rect = pygame.Rect(self.roll_x + self.roll_w - SCROLLBAR_W, self.roll_y, SCROLLBAR_W, self.roll_h)
self.v_scroll.viewport_size = self.roll_h
self.v_scroll.content_size = v_content_px
self.v_scroll.offset = self.offset_y
self.notes_surface = pygame.Surface((self.roll_w, self.roll_h), pygame.SRCALPHA).convert_alpha()
self.grid_surface = pygame.Surface((self.roll_w, self.roll_h)).convert() # Opaque for speed
def draw_keys(self):
self.keys_viewport.fill((30, 30, 33))
start_idx = int(self.offset_y // self.cell_h)
end_idx = int((self.offset_y + self.roll_h) // self.cell_h) + 1
for i in range(start_idx, min(128, end_idx)):
# Calculate the actual MIDI pitch for this index
midi_val = 127 - i
btn = self.key_buttons[i]
# Update position for the current frame
btn.rect.y = (i * self.cell_h) - self.offset_y
btn.rect.height = self.cell_h
# CHECK HIGHLIGHTING: Is this note active in the MIDI Manager?
is_pressed = midi_val in self.midi_manager.active_notes_set
if not is_pressed:
btn.color = (30, 30, 30) if is_black(midi_val) else (250, 250, 250)
btn.draw(self.keys_viewport)
def draw_bars(self):
"""
Renders the timeline ruler at the top of the piano roll with
dynamic label density based on zoom level.
"""
self.bar_surface.fill(BAR_COLOR)
ticks_per_bar = self.midi_manager.ticks_per_bar
first_bar = int(self.start_tick // ticks_per_bar)
last_bar = int(self.end_tick // ticks_per_bar) + 1
for b in range(first_bar, last_bar):
# Calculate pixel position relative to the scroll offset
px = self.ticks_to_pixel(b * ticks_per_bar) - self.offset_x
if b % self.label_step == 0:
text = fonts[12].render(f"{b + 1}", True, BLACK)
if px + 5 < self.roll_w:
self.bar_surface.blit(text, (px + 5, 2))
# self.draw_tempo_markers()
if 0 <= self.current_playhead_px <= self.roll_w:
points = [
(self.current_playhead_px - 8, 0),
(self.current_playhead_px + 8, 0),
(self.current_playhead_px, 10)
]
pygame.gfxdraw.filled_polygon(self.bar_surface, points, RED)
pygame.gfxdraw.aapolygon(self.bar_surface, points, RED)
# def draw_tempo_markers(self):
# # Calculate visible range
#
#
# for tick, bpm in self.midi_manager.tempo_map:
# if self.start_tick <= tick <= self.end_tick:
# # Convert tick to pixel position relative to the bar surface
# px = self.ticks_to_pixel(tick) - self.offset_x
#
# # Draw a small flag or line on the bar_surface
# pygame.draw.line(self.bar_surface, (0, 100, 255), (px, 0), (px, self.bar_height), 2)
#
# # Draw the BPM text
# bpm_text = fonts[10].render(f"= {round(bpm)}", True, (0, 50, 150))
# self.bar_surface.blit(bpm_text, (px + 4, 20))
def draw(self, screen):
self.sync_project_boundaries()
self.update_auto_scroll() # Follow playhead
self.start_tick = self.pixel_to_ticks(self.offset_x)
self.end_tick = self.pixel_to_ticks(self.offset_x + self.roll_w)
self.update_zoom() # Logic for smooth zoom
self._handle_drag_scrolling() # Move view when dragging notes
self._handle_continuous_playhead_scroll()
self.current_playhead_px = self.ticks_to_pixel(self.midi_manager.play_tick) - self.offset_x
# 1. Draw the Timeline Bar directly to screen
self.draw_roll(screen) # Pass the main screen here
self.draw_keys()
self.draw_bars()
screen.blit(self.bar_surface, (self.roll_x, self.roll_y - self.bar_height))
# 3. Draw Keys
screen.blit(self.keys_viewport, (self.roll_x - KEY_W, self.roll_y))
# 4. Draw scrollbars
self.h_scroll.draw(screen)
self.v_scroll.draw(screen)
def handle_event(self, event):
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if self.h_scroll.handle_event(event):
self.offset_x, self.offset_y = int(self.h_scroll.offset), int(self.v_scroll.offset)
self.grid_needs_update = True
self.notes_need_update = True
return
if self.v_scroll.handle_event(event):
self.offset_x, self.offset_y = int(self.h_scroll.offset), int(self.v_scroll.offset)
self.grid_needs_update = True
self.notes_need_update = True
return
if event.type == pygame.MOUSEBUTTONDOWN:
if self._handle_click(event):
return
elif event.type == pygame.MOUSEBUTTONUP:
if self._handle_mouse_up(event):
return
elif event.type == pygame.MOUSEMOTION:
if self._handle_mouse_motion(event):
return
elif event.type == pygame.MOUSEWHEEL:
self._handle_zoom_and_scroll(event)
return
elif event.type == pygame.KEYDOWN:
self._handle_shortcuts(event)
return
def _handle_shortcuts(self, event):
mods = pygame.key.get_mods()
ctrl = mods & pygame.KMOD_CTRL
shift = mods & pygame.KMOD_SHIFT
tps = self.midi_manager.ticks_per_snap
# 1. NON-MODIFIER KEYS
if not ctrl and not shift:
if event.key in (pygame.K_DELETE, pygame.K_BACKSPACE):
if self.selected_notes:
self.midi_manager.save_history()
# Filter notes out of their respective tracks
for track_idx in range(len(self.midi_manager.tracks)):
self.midi_manager.tracks[track_idx] = [
n for n in self.midi_manager.tracks[track_idx]
if n not in self.selected_notes
]
self.selected_notes.clear()
self.notes_need_update = True
self.midi_manager.update_project_length()
# 2. CTRL COMBINATIONS
elif ctrl:
# State-changing actions (Undo/Redo/Select All)
if event.key == pygame.K_z:
self.redo() if shift else self.undo()
elif event.key == pygame.K_a:
self.selected_notes.clear()
self.selected_notes.extend(self.midi_manager.tracks[self.midi_manager.active_track_index])
self.notes_need_update = True
elif event.key == pygame.K_c:
self.copy()
elif event.key == pygame.K_v:
self.paste()
self.notes_need_update = True
# Batch transformations (save history once)
elif event.key in (pygame.K_UP, pygame.K_DOWN, pygame.K_q) and self.selected_notes:
self.midi_manager.save_history()
for note in self.selected_notes:
if event.key == pygame.K_UP:
note.y = max(0, note.y - 12)
self.notes_need_update = True
elif event.key == pygame.K_DOWN:
note.y = min(127, note.y + 12)
self.notes_need_update = True
elif event.key == pygame.K_q:
note.x = max(0, ((note.x + tps // 2) // tps) * tps)
self.notes_need_update = True
# 3. SHIFT COMBINATIONS (Nudging / Semitones)
elif shift:
if event.key in (pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT) and self.selected_notes:
self.midi_manager.save_history()
for note in self.selected_notes:
if event.key == pygame.K_UP:
note.y = max(0, note.y - 1)
elif event.key == pygame.K_DOWN:
note.y = min(127, note.y + 1)
elif event.key == pygame.K_LEFT:
note.x = max(0, note.x - tps)
elif event.key == pygame.K_RIGHT:
note.x += tps
# Preview only once after the loop
if event.key in (pygame.K_UP, pygame.K_DOWN):
self._trigger_preview(self.selected_notes[0].y)
def _handle_mouse_motion(self, event):
# Always update the visual cursor first
self._update_cursor_icon(event.pos)
if self.dragging_scroll:
self._handle_scrolling(event.pos)
return
# 1. Viewport & Playhead (Global UI)
if self.dragging_playhead:
self._handle_playhead_drag(event.pos)
return
if any(n.dragging or n.resizing for n in self.midi_manager.notes):
self._handle_note_transformation(event.pos)
return
# 3. Selection Tools (Lasso)
if self.selection_start_pos:
self._handle_lasso_logic(event.pos)
return
# 4. Eraser (Right Click)
if pygame.mouse.get_pressed()[2]:
snapped_x, grid_y = self.get_grid_coords(event.pos)
self.midi_manager.remove_note_at(snapped_x, grid_y)
self.notes_need_update = True
else:
if event.pos[0] < self.roll_x:
raw_y = event.pos[1] - self.roll_y
# Calculate index based on the scroll position
current_key_idx = int((raw_y + self.offset_y) // self.cell_h)
# 2. Reset the previous button's hover state if we moved to a new index
if self.last_hovered_key_idx is not None and self.last_hovered_key_idx != current_key_idx:
if 0 <= self.last_hovered_key_idx < 128:
off_event = pygame.event.Event(pygame.MOUSEMOTION, {'pos': (-1, -1), 'buttons': (0, 0, 0)})
self.key_buttons[self.last_hovered_key_idx].handle_event(off_event)
# 3. Trigger the CURRENT button
if 0 <= current_key_idx < 128:
btn = self.key_buttons[current_key_idx]
# CRITICAL FIX: The button's internal rect.y is updated in draw_keys.
# We must pass the GLOBAL mouse position (relative to the screen/viewport)
# so btn.rect.collidepoint(event.pos) works.
global_y_for_btn = event.pos[1] - self.roll_y
btn_event = pygame.event.Event(event.type, {
'pos': (event.pos[0], global_y_for_btn),
'button': getattr(event, 'button', 1)
})
btn.handle_event(btn_event)
self.last_hovered_key_idx = current_key_idx
elif self.last_hovered_key_idx is not None:
off_event = pygame.event.Event(pygame.MOUSEMOTION, {'pos': (-1, -1), 'buttons': (0, 0, 0)})
self.key_buttons[self.last_hovered_key_idx].handle_event(off_event)
self.last_hovered_key_idx = None
def _handle_click(self, event):
# 1. Timeline / Playhead Interaction
if self.bar_rect.collidepoint(event.pos):
rel_x = event.pos[0] - self.roll_x + self.offset_x
raw_tick = self.pixel_to_ticks(rel_x)
snapped_tick = self.get_snapped_ticks(raw_tick)
if event.button == 1: # Left Click: Move Playhead
self.midi_manager.play_tick = max(0, raw_tick)
self.dragging_playhead = True
# 2. Piano Roll Interaction
if self.roll_rect.collidepoint(event.pos):
mods = pygame.key.get_mods()
ctrl_held = mods & pygame.KMOD_CTRL
raw_x_tick = self.get_raw_ticks(event.pos[0])
snapped_ticks, y_grid = self.get_grid_coords(event.pos)
# Find if a note exists at the exact mouse position
note = self.midi_manager.find_note_at(raw_x_tick, y_grid)
if event.button == 1: # Left Click
if note:
# Save history ONCE before any transformation begins
self.midi_manager.save_history()
# Selection Logic: If clicking an unselected note, make it the only selection
if note not in self.selected_notes:
self.selected_notes = [note]
# Determine if we are Resizing, Editing Velocity, or Moving
# Use a 12px handle for resizing
note_start_px = self.ticks_to_pixel(note.x) - self.offset_x
note_width_px = self.ticks_to_pixel(note.length)
mouse_rel_x_px = event.pos[0] - self.roll_x - note_start_px
mode = "move"
if mouse_rel_x_px > (note_width_px - 12):
mode = "resize"
# CRITICAL: Lock the starting state for EVERY note in the selection
for n in self.selected_notes:
n.start_drag(raw_x_tick, y_grid, mode=mode)
n.drag_start_pos = event.pos # Store pixels for velocity sensitivity
# 🔊 Preview the note being clicked
self._trigger_preview(note.y, note.velocity)
elif ctrl_held:
# Start Lasso Selection
self.selection_start_pos = event.pos
self.selected_notes.clear()
# Inside PianoRoll._handle_click
elif len(self.selected_notes) == 0:
self.midi_manager.save_history()
new_note = Note(snapped_ticks, y_grid, length=self.last_note_duration,
velocity=self.last_note_velocity)
# This automatically targets the active track via the property
self.midi_manager.add_note(new_note)
self.notes_need_update = True
new_note.start_drag(raw_x_tick, y_grid, mode="move")
self._trigger_preview(new_note.y, new_note.velocity)
else:
self.selected_notes.clear()
self.notes_need_update = True
elif event.button == 3: # Right Click: Delete
self.midi_manager.save_history()
self.midi_manager.remove_note_at(snapped_ticks, y_grid)
self.notes_need_update = True
elif event.button == 2: # Middle Click: Pan View
self.dragging_scroll = True
self.scroll_start = event.pos
self.offset_start = (self.offset_x, self.offset_y)
self._update_cursor_icon(event.pos)
def _handle_zoom_and_scroll(self, event):
mods = pygame.key.get_mods()
m_pos = pygame.mouse.get_pos()
if mods & pygame.KMOD_ALT:
# Determine velocity change (e.g., 5 units per scroll notch)
velocity_delta = 5 if event.y > 0 else -5
# If there's a selection, adjust the whole group
if self.selected_notes:
for note in self.selected_notes:
note.velocity = clamp(note.velocity + velocity_delta, 1, 127)
else:
# Otherwise, adjust the note currently under the mouse
x_tick, y_grid = self.get_grid_coords(m_pos)
hovered_note = self.midi_manager.find_note_at(x_tick, y_grid)
if hovered_note:
hovered_note.velocity = clamp(hovered_note.velocity + velocity_delta, 1, 127)
# Return early so we don't zoom/scroll while editing velocity
self.notes_need_update = True
return
# Capture the MIDI tick currently under the mouse to use as a zoom anchor
rel_x = self.offset_x + (m_pos[0] - self.roll_x)
rel_y = self.offset_y + (m_pos[1] - self.roll_y)
self.zoom_anchor_tick = self.pixel_to_ticks(rel_x)
if mods & pygame.KMOD_CTRL:
# We are only doing horizontal smooth zoom
factor = 1.1 if event.y > 0 else 0.9
if not (mods & pygame.KMOD_SHIFT):
# 1. Recalculate minimum zoom based on current window/project size
total_ticks = self.midi_manager.project_end_tick
# min_cell_w = pixels_available / total_steps_in_project
total_steps = (total_ticks / PPQ) * self.midi_manager.steps_per_beat
self.min_cell_w = self.roll_w / max(0.1, total_steps)
# 2. Apply zoom factor to target
self.target_cell_w = clamp(self.target_cell_w * factor, self.min_cell_w, self.max_cell_w)
else:
old_h = self.cell_h
# Update the limit calculation right before clamping
self.min_cell_h = self.roll_h / 128
self.cell_h = clamp(self.cell_h * factor, self.min_cell_h, self.max_cell_h)
# Re-anchor Y to keep the mouse position consistent
self.offset_y = (rel_y * (self.cell_h / old_h)) - (m_pos[1] - self.roll_y)
else:
# Standard Scroll (Y-axis)
scroll_dist = self.cell_h * 3
self.offset_y = clamp(self.offset_y - event.y * scroll_dist, 0, (128 * self.cell_h) - self.roll_h)
self.v_scroll.offset = self.offset_y
h_content_px = self.ticks_to_pixel(self.midi_manager.project_end_tick)
v_content_px = 128 * self.cell_h
self.h_scroll.rect = pygame.Rect(self.roll_x, self.roll_y + self.roll_h - SCROLLBAR_W, self.roll_w - SCROLLBAR_W,
SCROLLBAR_W)
self.h_scroll.content_size = h_content_px
self.h_scroll.viewport_size = self.roll_w
self.v_scroll.rect = pygame.Rect(self.roll_x + self.roll_w - SCROLLBAR_W, self.roll_y,
SCROLLBAR_W,
self.roll_h)
self.v_scroll.content_size = v_content_px
self.v_scroll.viewport_size = self.roll_h
self.offset_x = max(0, min(self.offset_x, h_content_px - self.roll_w))
self.offset_y = max(0, min(self.offset_y, v_content_px - self.roll_h))
# Sync Scrollbars
self.h_scroll.offset = self.offset_x
self.v_scroll.offset = self.offset_y
self.grid_needs_update = True
self.notes_need_update = True
def _handle_drag_scrolling(self):
"""Performs scrolling every frame if a note is being dragged outside the viewport."""
# Only scroll if we are actually dragging or resizing a note
if not any(n.dragging or n.resizing for n in self.midi_manager.notes):
return
pos = pygame.mouse.get_pos()
scroll_speed = 2 # Adjusted for per-frame execution
changed = False
# Horizontal Scroll
if pos[0] < self.roll_rect.left:
self.offset_x = max(0, self.offset_x - scroll_speed)
changed = True
elif pos[0] > self.roll_rect.right:
max_scroll_x = max(0, self.h_scroll.content_size - self.roll_w)
self.offset_x = min(max_scroll_x, self.offset_x + scroll_speed)
changed = True
# Vertical Scroll
if pos[1] < self.roll_rect.top:
self.offset_y = max(0, self.offset_y - scroll_speed)
changed = True
elif pos[1] > self.roll_rect.bottom:
max_scroll_y = max(0, (128 * self.cell_h) - self.roll_h)
self.offset_y = min(max_scroll_y, self.offset_y + scroll_speed)
changed = True
if changed:
self.h_scroll.offset = self.offset_x
self.v_scroll.offset = self.offset_y
# Re-apply transformation logic so notes stay glued to the mouse during scroll
self._handle_note_transformation(pos)
self.grid_needs_update = True
self.notes_need_update = True
def _handle_mouse_up(self, event):
if event.button == 2: # Middle Mouse Up
self.dragging_scroll = False
elif event.button == 1:
# Silence the note currently being previewed
if self.previewing_note is not None:
self.midi_manager.note_off(self.previewing_note)
self.previewing_note = None # Reset so it can be re-triggered later
# ----------------------
active_note = next((n for n in self.midi_manager.notes if n.dragging or n.resizing), None)
if active_note:
self.last_note_duration = active_note.length
self.last_note_velocity = active_note.velocity
self.dragging_playhead = False
self.selection_start_pos = None
self.selection_rect = None
for note in self.midi_manager.notes:
note.stop_drag()
note.editing_velocity = False # Reset velocity mode
def _handle_lasso_logic(self, pos):
# 1. Calculate the raw rectangle in screen space
x = min(self.selection_start_pos[0], pos[0])
y = min(self.selection_start_pos[1], pos[1])
w = abs(self.selection_start_pos[0] - pos[0])
h = abs(self.selection_start_pos[1] - pos[1])
self.selection_rect = pygame.Rect(x, y, w, h)
# 2. Convert the lasso rect to "Roll Space"
check_rect = self.selection_rect.move(-self.roll_x, -self.roll_y)
self.selected_notes.clear()
# FIX: Only iterate through the active track instead of all tracks
active_track_notes = self.midi_manager.tracks[self.midi_manager.active_track_index]
for note in active_track_notes:
# Calculate note position relative to the viewport
nx = self.ticks_to_pixel(note.x) - self.offset_x
ny = (note.y * self.cell_h) - self.offset_y
nw = max(2, self.ticks_to_pixel(note.length))
note_rect = pygame.Rect(nx, ny, nw, self.cell_h)
# Check collision in Viewport Space
if check_rect.colliderect(note_rect):
self.selected_notes.append(note)
# Mark notes as dirty so the selection highlight renders
self.notes_need_update = True
def _handle_note_transformation(self, pos):
"""
Handles moving, resizing, and velocity editing with group integrity.
"""
# 1. Identify the note being actively manipulated
active_note = next((n for n in self.midi_manager.notes if n.dragging or n.resizing or n.editing_velocity), None)
if not active_note:
return
# 2. Setup environment variables
raw_x = self.get_raw_ticks(pos[0])
_, grid_y = self.get_grid_coords(pos)
tps = self.midi_manager.ticks_per_snap
mods = pygame.key.get_mods()
alt_held = mods & pygame.KMOD_ALT
# Calculate mouse movement deltas since the initial click
delta_tick = raw_x - active_note.drag_start_tick
delta_grid_y = grid_y - active_note.drag_start_grid_y
# --- MODE A: VELOCITY EDITING ---
if active_note.editing_velocity:
# Vertical mouse movement adjusts velocity
# We use pos[1] directly for pixel-perfect sensitivity
v_delta = active_note.drag_start_pos[1] - pos[1]
for n in (self.selected_notes if active_note in self.selected_notes else [active_note]):
n.velocity = clamp(n.start_velocity + v_delta, 1, 127)
# --- MODE B: DRAGGING (MOVE) ---
elif active_note.dragging:
old_pitch = active_note.y # Store for preview logic
# Calculate horizontal displacement with snapping
if alt_held:
disp_x = delta_tick
else:
# Snap the new position of the anchor, then find the diff from its start
snapped_new_x = round((active_note.start_x + delta_tick) / tps) * tps
disp_x = snapped_new_x - active_note.start_x
disp_y = delta_grid_y
# Apply displacement to the group to maintain relative positions
if active_note in self.selected_notes:
# Group Boundary Validation
leftmost = min(n.start_x for n in self.selected_notes)
if leftmost + disp_x < 0: disp_x = -leftmost
min_y = min(n.start_y for n in self.selected_notes)
max_y = max(n.start_y for n in self.selected_notes)
if min_y + disp_y < 0: disp_y = -min_y
if max_y + disp_y > 127: disp_y = 127 - max_y
for n in self.selected_notes:
n.x = n.start_x + disp_x
n.y = n.start_y + disp_y
else:
# Individual drag
active_note.x = max(0, active_note.start_x + disp_x)
active_note.y = clamp(active_note.start_y + disp_y, 0, 127)
# Trigger preview only if the active note's pitch changed
if active_note.y != old_pitch:
self._trigger_preview(active_note.y, active_note.velocity)
# --- MODE C: RESIZING ---
elif active_note.resizing:
if alt_held:
disp_len = delta_tick
else:
# Snap the length change to the grid
snapped_new_end = round((active_note.start_x + active_note.start_length + delta_tick) / tps) * tps
disp_len = snapped_new_end - (active_note.start_x + active_note.start_length)
target_group = self.selected_notes if active_note in self.selected_notes else [active_note]
# Prevent notes from having 0 or negative length
min_possible_disp = min(n.start_length - (1 if alt_held else tps) for n in target_group)
actual_disp = max(-min_possible_disp, disp_len)
for n in target_group:
n.length = n.start_length + actual_disp
# 4. Final Housekeeping
self.notes_need_update = True
self.midi_manager.update_project_length()
self.sync_project_boundaries()
def _update_cursor_icon(self, pos):
new_cursor = pygame.SYSTEM_CURSOR_ARROW
# 1. Ensure we are inside the roll area
if self.roll_rect.collidepoint(pos):
# 2. Use RAW ticks for detection, not snapped grid coords
raw_x_tick = self.get_raw_ticks(pos[0])
# Calculate grid_y (this remains consistent as it's just pixel division)
grid_y = int((pos[1] + self.offset_y - self.roll_y) // self.cell_h)
# 3. Find the note using the exact tick under the mouse
note = self.midi_manager.find_note_at(raw_x_tick, grid_y)
if note:
# 4. Use the note's actual x (even if off-grid) to find the handle
note_start_px = self.ticks_to_pixel(note.x) - self.offset_x
note_width_px = self.ticks_to_pixel(note.length)
# Calculate mouse position relative to the note's actual start
mouse_rel_x_px = (pos[0] - self.roll_x) - note_start_px
# Define the resize handle (e.g., last 12 pixels of the note)
resize_handle_width = min(8, note_width_px / 2)
if mouse_rel_x_px > (note_width_px - resize_handle_width):
new_cursor = pygame.SYSTEM_CURSOR_SIZEWE # Resize icon
else:
new_cursor = pygame.SYSTEM_CURSOR_HAND # Move icon
pygame.mouse.set_cursor(new_cursor)
def _handle_playhead_drag(self, pos):
# Calculate position relative to the current scroll offset
rel_x = pos[0] - self.roll_x + self.offset_x
raw_tick = self.pixel_to_ticks(rel_x)
# NEW: Snap the calculated tick to the current grid resolution
target_tick = self.get_snapped_ticks(raw_tick)
# Update the manager's playhead
self.midi_manager.play_tick = max(0, target_tick)
def _handle_continuous_playhead_scroll(self):
"""Call this every frame in PianoRoll.draw() or update()"""
if not self.dragging_playhead:
return
pos = pygame.mouse.get_pos()
scroll_speed = 5 # Increased speed for better feel during snap
changed = False
# Scroll Right/Left logic remains the same
if pos[0] > self.roll_rect.right:
max_scroll = max(0, self.h_scroll.content_size - self.roll_w)
if self.offset_x < max_scroll:
self.offset_x = min(max_scroll, self.offset_x + scroll_speed)
changed = True
elif pos[0] < self.roll_rect.left:
if self.offset_x > 0:
self.offset_x = max(0, self.offset_x - scroll_speed)
changed = True
if changed:
self.h_scroll.offset = self.offset_x
# This now calls the updated _handle_playhead_drag with snapping
self._handle_playhead_drag(pos)
self.grid_needs_update = True
self.notes_need_update = True
def _handle_scrolling(self, pos):
# Calculate how far the mouse has moved from the initial click
dx = pos[0] - self.scroll_start[0]
dy = pos[1] - self.scroll_start[1]
# Update offsets based on the starting position minus the movement
# max(0, ...) prevents scrolling into negative space
self.offset_x = max(0, self.offset_start[0] - dx)
self.offset_y = max(0, self.offset_start[1] - dy)
h_max = max(0, self.h_scroll.content_size - self.roll_w)
v_max = max(0, (128 * self.cell_h) - self.roll_h)
self.offset_x = min(self.offset_x, h_max)
self.offset_y = min(self.offset_y, v_max)
# Sync the scrollbar UI objects (if they exist)
self.h_scroll.offset = self.offset_x
self.v_scroll.offset = self.offset_y
self.grid_needs_update = True
self.notes_need_update = True
def _trigger_preview(self, grid_y, velocity=64):
midi_note = (NOTES - 1) - grid_y
if self.previewing_note != midi_note:
if self.previewing_note is not None:
self.midi_manager.note_off(self.previewing_note)
# Use the passed velocity instead of the default
self.midi_manager.note_on(midi_note, velocity)
self.previewing_note = midi_note
def copy(self):
if self.selected_notes:
# Find the earliest note to use as a relative anchor for pasting
min_x = min(n.x for n in self.selected_notes)
self.clipboard = []
for n in self.selected_notes:
# Store properties as a dict or a new Note object
self.clipboard.append({
'rel_x': n.x - min_x,
'y': n.y,
'length': n.length
})
def paste(self):
if self.clipboard:
self.midi_manager.save_history() #
self.selected_notes.clear() #
# Anchor the paste to the current playhead or mouse position
paste_anchor = self.midi_manager.play_tick #
for data in self.clipboard:
new_note = Note(
paste_anchor + data['rel_x'],
data['y'],
data['length']
)
self.midi_manager.add_note(new_note) #
self.selected_notes.append(new_note) #
def get_grid_coords(self, pos):
"""Returns (snapped_ticks, y_index)"""
raw_x_pixels = pos[0] + self.offset_x - self.roll_x
raw_ticks = self.pixel_to_ticks(raw_x_pixels)
snapped_ticks = self.get_snapped_ticks(raw_ticks)
grid_y = (pos[1] + self.offset_y - self.roll_y) // self.cell_h
return snapped_ticks, int(grid_y)
def sync_project_boundaries(self):
# This is called every frame in draw()
# It updates the scrollbar UI based on the Manager's 'Truth'
new_content_px = self.ticks_to_pixel(self.midi_manager.project_end_tick)
if self.h_scroll.content_size != new_content_px:
self.h_scroll.content_size = new_content_px
def update_auto_scroll(self):
if self.h_scroll.dragging or self.dragging_scroll or self.dragging_playhead:
return
if not self.midi_manager.playing:
return
current_tick = self.midi_manager.play_tick
# Check if playhead jumped back (Loop detected)
if current_tick < self.last_frame_tick and self.midi_manager.playing:
self.offset_x = 0
self.h_scroll.offset = 0
self.grid_needs_update = True
self.notes_need_update = True
self.last_frame_tick = current_tick
center_x = self.roll_w // 2 - self.offset_x
if self.current_playhead_px > center_x: