-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathToolbar.py
More file actions
387 lines (305 loc) · 14.6 KB
/
Toolbar.py
File metadata and controls
387 lines (305 loc) · 14.6 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
from Config import WINDOW_W, TEXT_MUTED, SURFACE_DARK, REC_RED, PLAY_GREEN, \
fonts, FONT, PPQ, musical_keys
import pygame
import os
from utils import open_midi_file, save_midi_file, open_sf2_file, load_icon
from UIComponents import Slider, TextInput, Button, DropdownMenu
play_icon = load_icon("images/play_arrow_24dp_828282_FILL1_wght400_GRAD0_opsz24.png")
pause_icon = load_icon("images/pause_24dp_828282_FILL1_wght400_GRAD0_opsz24.png")
record_icon = load_icon("images/fiber_manual_record_24dp_C80000.png")
stop_icon = load_icon("images/stop_24dp_828282_FILL1_wght400_GRAD0_opsz24.png")
class Toolbar:
def __init__(self, midi_manager, piano_roll, tab_bar):
self.tab_bar = tab_bar
self.rect = pygame.Rect(0, 0, WINDOW_W, 130)
self.midi_manager = midi_manager
self.piano_roll = piano_roll
# UI Constants
self.margin = 10
self.menu_h = 40
self.square_size = 40
self.current_key = "C Major" # New state for the key
# Icons
self.master_volume = Slider(0, 0, 180, 15, initial_val=0.8) # Position will be set in setup_layout
self.buttons = {}
self.menu_buttons = {}
self.active_menu_key = None
self.dropdowns = {}
self.setup_layout()
def setup_layout(self):
# 1. Define the Standard File Menus
self.menu_structure = {
"file": ["Import MIDI", "Export MIDI"],
"edit": ["Undo", "Redo"],
"view": ["Zoom In", "Zoom Out"] # Removed Grid Settings as it's now a dedicated dropdown
}
# Map string names to methods in your ProjectManager (midi_manager)
callback_map = {
"Import MIDI": self.on_import,
"Export MIDI": self.on_export,
"Undo": self.piano_roll.undo,
"Redo": self.piano_roll.redo,
"Zoom In": self.piano_roll.zoom_in, # New callback
"Zoom Out": self.piano_roll.zoom_out # New callback
}
# 2. Initialize the Top Menu Bar
menu_x = 0
for item_name, options in self.menu_structure.items():
# Define the area where the header will sit
header_rect = pygame.Rect(menu_x, 0, 70, self.menu_h)
# The DropdownMenu now creates its own internal header button
self.dropdowns[item_name] = DropdownMenu(
header_rect, item_name.capitalize(), options,callback_map,color = (20,20,20)
)
self.dropdowns[item_name].header_btn.refresh_size(fonts)
menu_x += self.dropdowns[item_name].header_btn.rect.width
# --- KEY SELECTION SECTION ---
self.key_section_x = self.margin
row_y = self.menu_h + 40
key_w = 100
key_rect = pygame.Rect(self.key_section_x, row_y, key_w, self.square_size)
key_callback_map = {k: lambda val=k: self.set_project_key(val) for k in musical_keys}
# 3. Initialize the DropdownMenu (it now creates its own header button)
self.key_select_button = DropdownMenu(
key_rect,
self.current_key, # Initial label
musical_keys,
key_callback_map, color = SURFACE_DARK, border_radius = 3, border=False
)
curr_x = self.key_section_x + key_w + (self.margin * 3)
self.playback_section_x = curr_x
self.buttons["stop"] = Button(curr_x, row_y, self.square_size, self.square_size, icon=stop_icon,
color=SURFACE_DARK, callback=self.stop_playback)
curr_x += self.square_size + 5
self.buttons["play"] = Button(curr_x, row_y, self.square_size, self.square_size, icon=play_icon,
color=SURFACE_DARK, callback=self.play)
curr_x += self.square_size + 5
self.buttons["record"] = Button(curr_x, row_y, self.square_size, self.square_size, icon=record_icon,
color=SURFACE_DARK, callback=self.toggle_record)
curr_x += self.square_size + (self.margin * 3)
# --- 2. METER ---
self.meter_section_x = curr_x
meter_text = f"{self.midi_manager.time_signature[0]}/{self.midi_manager.time_signature[1]}"
self.meter_input = TextInput(curr_x, row_y, 60, self.square_size, meter_text)
curr_x += 60 + (self.margin * 3)
# --- 3. TEMPO (Moved before Grid) ---
self.tempo_section_x = curr_x
self.tempo_input = TextInput(curr_x, row_y, 60, self.square_size, str(int(self.midi_manager.current_tempo)))
curr_x += 60 + (self.margin * 3)
# --- 4. GRID (Now after Tempo) ---
self.grid_section_x = curr_x
grid_rect = pygame.Rect(curr_x, row_y, 60, self.square_size)
grid_options = ["1/4", "1/8", "1/16", "1/32"]
grid_callback_map = {
opt: lambda val=opt: self.set_grid_snap(val) for opt in grid_options
}
self.grid_snap_button = DropdownMenu(
grid_rect, "1/16", grid_options, grid_callback_map, color = SURFACE_DARK, border_radius = 3, border=False
)
curr_x += 60 + (self.margin * 3)
self.master_vol_x = curr_x
self.master_volume.rect.x = curr_x
self.master_volume.rect.y = row_y + (self.square_size // 2) - 8
curr_x += 110 + (self.margin * 3)
def handle_event(self, event):
# 1. Process standard toolbar buttons (Play, Stop, Record, SF2)
# 2. Process ALL Dropdowns
# We iterate through them; the DropdownMenu.handle_event internally
# handles the header click and the sub-item clicks.
if self.master_volume.handle_event(event):
# Apply volume to the FluidSynth engine (channel 0-15 or global gain)
# Using synth.gain for a true "Master" volume
self.midi_manager.fs.setting('synth.gain', self.master_volume.val * 2.0)
return True
for key, dropdown in self.dropdowns.items():
if dropdown.handle_event(event):
# If a dropdown was interacted with, ensure it's the only active one
if dropdown.visible:
self.active_menu_key = key
# Close all other dropdowns
for other_key, other_dropdown in self.dropdowns.items():
if other_key != key:
other_dropdown.visible = False
else:
self.active_menu_key = None
return True
if self.key_select_button.handle_event(event):
self.piano_roll.grid_needs_update=True
return True
if self.grid_snap_button.handle_event(event):
return True
for btn in self.buttons.values():
if btn.handle_event(event):
return True
# 3. Handle closing menus when clicking outside
if event.type == pygame.MOUSEBUTTONDOWN:
clicked_any_menu = False
for dropdown in self.dropdowns.values():
# Check if click was inside the header or the visible list
if dropdown.header_btn.rect.collidepoint(event.pos) or \
(dropdown.visible and any(b.rect.collidepoint(event.pos) for b in dropdown.option_buttons)):
clicked_any_menu = True
if not clicked_any_menu:
# Close all menus if clicking empty space
for d in self.dropdowns.values():
d.visible = False
self.active_menu_key = None
# 4. Process text inputs
if self.tempo_input.handle_event(event):
try:
new_bpm = float(self.tempo_input.text)
new_bpm = max(10, min(400, new_bpm))
self.midi_manager.current_tempo = new_bpm
self.piano_roll.notes_need_update = True # Refresh visual tempo markers
except ValueError:
# Revert text if input is invalid
self.sync_tempo()
return True
if self.meter_input.handle_event(event):
if "/" in self.meter_input.text:
try:
parts = self.meter_input.text.split('/')
if len(parts) == 2:
n, d = int(parts[0]), int(parts[1])
# Validation
if n > 0 and d > 0 and (d & (d - 1) == 0):
self.midi_manager.set_time_signature(n, d)
self.piano_roll.grid_needs_update = True
self.piano_roll.notes_need_update = True
self.piano_roll.update_lod()
except ValueError:
pass
return True
return False
def draw(self, screen):
self.buttons["play"].color = PLAY_GREEN if self.midi_manager.playing else SURFACE_DARK
self.buttons["play"].icon = pause_icon if self.midi_manager.playing else play_icon
self.buttons["record"].color = REC_RED if self.midi_manager.recording else SURFACE_DARK
# Section Labels
label_font = fonts[12]
lbl_y = self.menu_h + 20
labels = [
("KEY", self.key_section_x), # Added Label
("PLAYBACK", self.playback_section_x),
("METER", self.meter_section_x),
("GRID", self.grid_section_x),
("TEMPO", self.tempo_section_x),
]
for text, x in labels:
screen.blit(label_font.render(text, True, TEXT_MUTED), (x, lbl_y))
# Draw Elements
for btn in self.menu_buttons.values(): btn.draw(screen)
for btn in self.buttons.values(): btn.draw(screen)
# self.sync_tempo()
self.tempo_input.draw(screen, FONT)
self.meter_input.draw(screen, FONT)
self.key_select_button.draw(screen)
self.grid_snap_button.draw(screen)
for dropdown in self.dropdowns.values():
dropdown.draw(screen)
if not self.meter_input.active:
# Sync the text box with the "Truth" in the manager
current_sig = f"{self.midi_manager.time_signature[0]}/{self.midi_manager.time_signature[1]}"
if self.meter_input.text != current_sig:
self.meter_input.text = current_sig
# ... (Keep existing helper methods like toggle_file_menu, get_formatted_time, etc.) ...
def toggle_file_menu(self):
self.file_menu_open = not self.file_menu_open
def on_import_and_close(self):
self.on_import()
self.file_menu_open = False
def on_export_and_close(self):
self.on_export()
self.file_menu_open = False
def get_formatted_time(self):
current_ticks = self.midi_manager.play_tick
total_seconds = (current_ticks * 60) / (self.midi_manager.current_tempo * PPQ)
minutes = int(total_seconds // 60)
seconds = int(total_seconds % 60)
millis = int((total_seconds * 100) % 100)
return f"{minutes:02}:{seconds:02}.{millis:02}"
def play(self):
self.midi_manager.playing = not self.midi_manager.playing
def toggle_record(self):
if not self.midi_manager.recording:
# Start Recording
self.midi_manager.start_recording()
else:
# Stop Recording
self.midi_manager.stop_recording()
def on_import(self):
self.midi_manager.playing = False
path = open_midi_file()
if path:
self.midi_manager.import_midi(path)
self.sync_tempo()
self.tab_bar.refresh_tabs()
self.piano_roll.notes_need_update = True
self.piano_roll.grid_needs_update = True
self.piano_roll.sync_project_boundaries()
def on_export(self):
path = save_midi_file()
if path:
self.midi_manager.export_midi(path)
def on_load_sf2(self):
default_path = os.path.join(os.getcwd(), "Soundfonts")
# Ensure the folder exists so the dialog opens there
if not os.path.exists(default_path):
os.makedirs(default_path)
# Call the file dialog starting in the 'soundfonts' directory
path = open_sf2_file(initial_dir=default_path)
if path:
if self.midi_manager.load_soundfont(path):
new_name = os.path.basename(path)
self.midi_manager.track_names[self.midi_manager.active_track_index] = new_name
def change_tempo(self, amount):
self.midi_manager.save_history()
# 1. Calculate the new value based on the current playhead's tempo
new_tempo = self.midi_manager.get_tempo_at_tick(self.midi_manager.play_tick) + amount
new_tempo = max(10, min(400, new_tempo))
# 2. Update the marker governing the current playhead position
self.midi_manager.update_active_tempo(new_tempo)
# 3. Update the UI text
self.tempo_input.text = str(int(new_tempo))
def on_toolbar_tempo_change(self, new_bpm):
# Find which marker is currently active based on the playhead
idx = self.midi_manager.get_current_tempo_marker_index()
tick, _ = self.midi_manager.tempo_map[idx]
# Update that specific marker's BPM
self.midi_manager.tempo_map[idx] = (tick, new_bpm)
def sync_tempo(self):
self.tempo_input.text = str(round(self.midi_manager.current_tempo))
def resize(self, scale):
self.rect.width = WINDOW_W * scale
self.setup_layout()
def toggle_dropdown(self, menu_name):
if self.active_menu_key == menu_name:
self.dropdowns[self.active_menu_key].visible = False
self.active_menu_key = None
else:
for d in self.dropdowns.values():
d.visible = False
self.active_menu_key = menu_name
self.dropdowns[menu_name].visible = True
def stop_playback(self):
self.midi_manager.playing = False
self.midi_manager.play_tick = 0
def set_project_key(self, new_key):
self.current_key = new_key
self.midi_manager.current_key = new_key
self.key_select_button.header_btn.text = new_key
self.key_select_button.visible = False
if hasattr(self, 'piano_roll'):
self.piano_roll.update_key_labels()
self.piano_roll.update_scale_mask()
self.active_menu_key = None
def set_grid_snap(self, snap_setting):
self.grid_snap_button.header_btn.text = snap_setting
try:
denominator = int(snap_setting.split('/')[-1])
self.midi_manager.set_grid_resolution(denominator)
except Exception as e:
print(f"Error setting grid: {e}")
self.grid_snap_button.visible = False
self.piano_roll.update_lod()
self.piano_roll.grid_needs_update = True