-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathGeneratorPresetEditor.h
More file actions
873 lines (776 loc) · 35.9 KB
/
GeneratorPresetEditor.h
File metadata and controls
873 lines (776 loc) · 35.9 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
// Super Timecode Converter
// Copyright (c) 2026 Fiverecords -- MIT License
// https://github.com/fiverecords/SuperTimecodeConverter
#pragma once
#include <JuceHeader.h>
#include "AppSettings.h"
#include "GeneratorCuePointEditor.h"
//==============================================================================
// GeneratorPresetEditor -- Table editor for named timecode generator presets.
//
// Each preset has a Name, Start TC, and Stop TC. The editor mirrors the
// TrackMapEditor UX: table + form at the bottom for add/edit.
// Calls onChange() whenever the preset map is modified.
//==============================================================================
class GeneratorPresetEditor : public juce::Component,
public juce::TableListBoxModel
{
public:
GeneratorPresetEditor(GeneratorPresetMap& map)
: presetMap(map)
{
setSize(560, 440);
rebuildRows();
// --- Table ---
addAndMakeVisible(table);
table.setModel(this);
table.setColour(juce::ListBox::backgroundColourId, bgDarker);
table.setColour(juce::ListBox::outlineColourId, borderCol);
table.setOutlineThickness(1);
table.setRowHeight(24);
table.setHeaderHeight(22);
table.getHeader().setStretchToFitActive(true);
auto& hdr = table.getHeader();
hdr.addColumn("Name", ColName, 140, 80, 300, juce::TableHeaderComponent::notSortable);
hdr.addColumn("Start TC", ColStart, 100, 80, 180, juce::TableHeaderComponent::notSortable);
hdr.addColumn("Stop TC", ColStop, 100, 80, 180, juce::TableHeaderComponent::notSortable);
hdr.addColumn("Audio", ColAudio, 180, 0, 600, juce::TableHeaderComponent::notSortable);
// --- Buttons ---
auto addBtn = [this](juce::TextButton& btn, const juce::String& text)
{
addAndMakeVisible(btn);
btn.setButtonText(text);
btn.setColour(juce::TextButton::buttonColourId, bgPanel);
btn.setColour(juce::TextButton::textColourOffId, textBright);
};
addBtn(btnAdd, "Add");
addBtn(btnSave, "Save");
addBtn(btnDelete, "Delete");
addBtn(btnCues, "Cues...");
addBtn(btnClearAll, "Clear All");
addBtn(btnImport, "Import");
addBtn(btnExport, "Export");
addBtn(btnOscHelp, "OSC ?");
btnAdd.setTooltip("Create a new preset from the form fields. "
"If a preset with the same name already exists, "
"the new one is auto-numbered (e.g. \"My preset (2)\").");
btnSave.setTooltip("Update the selected preset with the current form fields. "
"You can rename it by editing the Name field. "
"Disabled until a preset is selected -- use Add to create a new one.");
btnDelete.setTooltip("Delete the selected preset. Disabled until a preset is selected.");
btnCues.setTooltip("Edit cue points for the selected preset. "
"Cue points fire MIDI / OSC / Art-Net triggers when the generated TC "
"reaches their position. Disabled until a preset is selected.");
btnSave.setColour(juce::TextButton::buttonColourId, juce::Colour(0xFF22AA44).withAlpha(0.3f));
btnSave.setColour(juce::TextButton::textColourOffId, juce::Colour(0xFF22DD55));
btnCues.setColour(juce::TextButton::buttonColourId, juce::Colour(0xFFAA8800).withAlpha(0.3f));
btnCues.setColour(juce::TextButton::textColourOffId, juce::Colour(0xFFFFCC44));
btnImport.setColour(juce::TextButton::buttonColourId, juce::Colour(0xFF2244AA).withAlpha(0.3f));
btnImport.setColour(juce::TextButton::textColourOffId, juce::Colour(0xFF4488FF));
btnExport.setColour(juce::TextButton::buttonColourId, juce::Colour(0xFF2244AA).withAlpha(0.3f));
btnExport.setColour(juce::TextButton::textColourOffId, juce::Colour(0xFF4488FF));
btnOscHelp.setColour(juce::TextButton::buttonColourId, juce::Colour(0xFF555555));
btnOscHelp.setColour(juce::TextButton::textColourOffId, juce::Colour(0xFFFFCC44));
btnAdd.onClick = [this] { addNewPreset(); };
btnSave.onClick = [this] { saveSelectedPreset(); };
btnDelete.onClick = [this] { deleteSelected(); };
btnCues.onClick = [this] { openCueEditor(); };
btnClearAll.onClick = [this] { clearAll(); };
btnImport.onClick = [this] { importPresets(); };
btnExport.onClick = [this] { exportPresets(); };
btnOscHelp.onClick = [this] { showOscReference(); };
// --- Form fields ---
auto addField = [this](juce::Label& lbl, juce::TextEditor& ed,
const juce::String& labelText, const juce::String& defaultText)
{
addAndMakeVisible(lbl);
lbl.setText(labelText, juce::dontSendNotification);
lbl.setFont(juce::Font(juce::FontOptions(9.0f)));
lbl.setColour(juce::Label::textColourId, textMid);
lbl.setJustificationType(juce::Justification::centredRight);
addAndMakeVisible(ed);
ed.setFont(juce::Font(juce::FontOptions(11.0f)));
ed.setColour(juce::TextEditor::backgroundColourId, juce::Colour(0xFF222222));
ed.setColour(juce::TextEditor::textColourId, juce::Colours::white);
ed.setText(defaultText, false);
};
addField(lblName, edName, "Name:", "");
addField(lblStartTC, edStartTC, "Start TC:", "00:00:00:00");
addField(lblStopTC, edStopTC, "Stop TC:", "00:00:00:00");
addField(lblAudio, edAudio, "Audio:", "");
edAudio.setReadOnly(true);
edAudio.setColour(juce::TextEditor::textColourId, juce::Colour(0xFFCCCCCC));
addAndMakeVisible(btnBrowseAudio);
btnBrowseAudio.setButtonText("...");
btnBrowseAudio.setColour(juce::TextButton::buttonColourId, bgPanel);
btnBrowseAudio.setColour(juce::TextButton::textColourOffId, textBright);
btnBrowseAudio.onClick = [this] { browseForAudio(); };
addAndMakeVisible(btnClearAudio);
btnClearAudio.setButtonText("X");
btnClearAudio.setColour(juce::TextButton::buttonColourId, bgPanel);
btnClearAudio.setColour(juce::TextButton::textColourOffId, juce::Colour(0xFFFF6666));
btnClearAudio.onClick = [this] { clearAudioField(); };
addAndMakeVisible(btnLoopAudio);
btnLoopAudio.setButtonText("Loop audio file when it ends");
btnLoopAudio.setColour(juce::ToggleButton::textColourId, textBright);
// Enter on any form field commits the form. If a preset is
// selected, Enter saves it (matches the natural reading of "I'm
// editing this preset, finish editing"); otherwise Enter creates
// a new preset (matches "I just typed a name, add it"). This
// avoids the surprise where Enter silently does nothing when there
// is no selection.
auto commitForm = [this]
{
if (table.getSelectedRow() >= 0
&& table.getSelectedRow() < (int)rows.size())
saveSelectedPreset();
else
addNewPreset();
};
edName.onReturnKey = commitForm;
edStartTC.onReturnKey = commitForm;
edStopTC.onReturnKey = commitForm;
updateStopTCEnabledState();
updateButtonStates();
}
~GeneratorPresetEditor() override = default;
std::function<void()> onChange;
/// Set the engine's current fps so the cue editor can convert cue TC
/// to ms (and back) consistently. Called by MainComponent whenever
/// the editor is opened or the engine's fps changes.
void setCurrentFpsForCueEditor(double fpsValue)
{
if (fpsValue > 0.0) currentFpsForCueEditor = fpsValue;
}
/// Install a playhead getter that the cue editor (when opened) will
/// poll at ~30Hz to drive the live playback cursor in the waveform
/// strip. Returns ms-from-audio-start (i.e. corrected for the
/// preset's startTC) or a negative value when nothing is playing.
/// Pass empty std::function to disable.
void setPlayheadGetter(std::function<int64_t()> getter)
{
playheadGetter = std::move(getter);
// If a cue editor is already open, push the new getter to it
// immediately so toggling playback feedback doesn't require
// closing and reopening the cue window.
if (cueWindow != nullptr)
if (auto* ed = cueWindow->getEditor())
ed->setPlayheadGetter(playheadGetter);
}
//--------------------------------------------------------------------------
// TableListBoxModel
//--------------------------------------------------------------------------
int getNumRows() override { return (int)rows.size(); }
void paintRowBackground(juce::Graphics& g, int rowNumber, int, int,
bool rowIsSelected) override
{
g.fillAll(rowIsSelected ? accentCyan.withAlpha(0.15f)
: (rowNumber % 2 == 0 ? bgDarker : bgDarker.brighter(0.03f)));
}
void paintCell(juce::Graphics& g, int rowNumber, int columnId,
int width, int height, bool /*rowIsSelected*/) override
{
if (rowNumber < 0 || rowNumber >= (int)rows.size()) return;
auto& p = rows[(size_t)rowNumber];
// When the preset carries an audio file, the Stop TC field is
// ignored at runtime in favour of the file's actual length. Render
// it muted in the list so the user sees that the stored value is
// not the one being applied.
const bool stopOverriddenByAudio = (columnId == ColStop) && p.audioFilePath.isNotEmpty();
g.setColour(stopOverriddenByAudio ? textMid : textBright);
g.setFont(juce::Font(juce::FontOptions(11.0f)));
juce::String text;
switch (columnId)
{
case ColName: text = p.name; break;
case ColStart: text = p.startTC; break;
case ColStop:
text = stopOverriddenByAudio ? juce::String("(audio length)") : p.stopTC;
break;
case ColAudio:
if (p.audioFilePath.isNotEmpty())
{
text = juce::File(p.audioFilePath).getFileName();
if (p.audioLoop) text += " (loop)";
}
break;
}
g.drawText(text, 4, 0, width - 8, height, juce::Justification::centredLeft, true);
}
void selectedRowsChanged(int lastRowSelected) override
{
if (lastRowSelected >= 0 && lastRowSelected < (int)rows.size())
{
auto& p = rows[(size_t)lastRowSelected];
edName.setText(p.name, false);
edStartTC.setText(p.startTC, false);
edStopTC.setText(p.stopTC, false);
edAudio.setText(p.audioFilePath, false);
btnLoopAudio.setToggleState(p.audioLoop, juce::dontSendNotification);
updateStopTCEnabledState();
}
// If the cue editor window is open on a different preset, close it
// to avoid showing cues that don't belong to the current selection.
// Re-opening Cues from the toolbar will bind it to the new selection.
closeCueEditorWindow();
updateButtonStates();
}
/// SAVE / DELETE are only meaningful when a preset is selected -- without
/// a selection there's nothing to update or delete. Disabling them in
/// that state makes the difference between ADD ("create new from form")
/// and SAVE ("update the selected one") obvious without having to read
/// any documentation.
void updateButtonStates()
{
const bool hasSelection = table.getSelectedRow() >= 0
&& table.getSelectedRow() < (int)rows.size();
btnSave.setEnabled(hasSelection);
btnDelete.setEnabled(hasSelection);
btnCues.setEnabled(hasSelection);
}
/// When an audio file is set, the audio's actual length is what the
/// runtime uses -- the preset's Stop TC stored value is ignored. Make
/// that visually obvious in the form by disabling the field and
/// dimming its text, and surface a tooltip explaining why.
void updateStopTCEnabledState()
{
const bool hasAudio = edAudio.getText().trim().isNotEmpty();
edStopTC.setEnabled(! hasAudio);
edStopTC.setReadOnly(hasAudio);
// setColour() only changes the colour for *new* text; the characters
// already in the editor keep whatever colour they were drawn with.
// applyColourToAllText repaints existing characters too, so when the
// audio is cleared the previously-dimmed Stop TC text returns to the
// bright colour immediately instead of staying greyed-out until the
// user retypes it.
const auto col = hasAudio ? textMid : textBright;
edStopTC.setColour(juce::TextEditor::textColourId, col);
edStopTC.applyColourToAllText(col, true);
edStopTC.setTooltip(hasAudio
? "Stop TC is determined by the loaded audio file's length when one is set. "
"Clear the audio field to edit Stop TC manually."
: juce::String());
}
void cellDoubleClicked(int rowNumber, int, const juce::MouseEvent&) override
{
// Double-click = populate form for editing
selectedRowsChanged(rowNumber);
}
//--------------------------------------------------------------------------
// Layout
//--------------------------------------------------------------------------
void resized() override
{
auto area = getLocalBounds().reduced(8);
// Bottom form: 5 rows of label+editor + loop row + 2 button rows
auto formArea = area.removeFromBottom(210);
area.removeFromBottom(6);
// File operations row (Import / Export / OSC Help)
auto fileRow = formArea.removeFromBottom(26);
int fileBtnW = 80, gap = 4;
btnImport.setBounds(fileRow.removeFromLeft(fileBtnW)); fileRow.removeFromLeft(gap);
btnExport.setBounds(fileRow.removeFromLeft(fileBtnW)); fileRow.removeFromLeft(gap);
btnOscHelp.setBounds(fileRow.removeFromRight(50));
formArea.removeFromBottom(4);
// Edit button row
auto btnRow = formArea.removeFromBottom(26);
int btnW = 65;
btnAdd .setBounds(btnRow.removeFromLeft(btnW)); btnRow.removeFromLeft(gap);
btnSave .setBounds(btnRow.removeFromLeft(btnW)); btnRow.removeFromLeft(gap);
btnDelete .setBounds(btnRow.removeFromLeft(btnW)); btnRow.removeFromLeft(gap);
btnCues .setBounds(btnRow.removeFromLeft(btnW)); btnRow.removeFromLeft(gap);
btnClearAll.setBounds(btnRow.removeFromLeft(btnW));
formArea.removeFromBottom(6);
// Form fields
auto layField = [](juce::Label& lbl, juce::TextEditor& ed, juce::Rectangle<int>& fa)
{
auto row = fa.removeFromTop(22);
lbl.setBounds(row.removeFromLeft(60));
row.removeFromLeft(4);
ed.setBounds(row);
fa.removeFromTop(3);
};
layField(lblName, edName, formArea);
layField(lblStartTC, edStartTC, formArea);
layField(lblStopTC, edStopTC, formArea);
// Audio row: label + editor + Browse + Clear inline
{
auto row = formArea.removeFromTop(22);
lblAudio.setBounds(row.removeFromLeft(60));
row.removeFromLeft(4);
btnClearAudio .setBounds(row.removeFromRight(24));
row.removeFromRight(2);
btnBrowseAudio.setBounds(row.removeFromRight(30));
row.removeFromRight(4);
edAudio.setBounds(row);
formArea.removeFromTop(3);
}
// Loop checkbox row (offset from labels for alignment)
{
auto row = formArea.removeFromTop(22);
row.removeFromLeft(64);
btnLoopAudio.setBounds(row);
}
// Table fills the rest
table.setBounds(area);
}
private:
enum { ColName = 1, ColStart, ColStop, ColAudio };
GeneratorPresetMap& presetMap;
juce::TableListBox table { "Presets", this };
std::vector<GeneratorPreset> rows;
// Buttons
juce::TextButton btnAdd, btnSave, btnDelete, btnCues, btnClearAll;
juce::TextButton btnImport, btnExport, btnOscHelp;
juce::TextButton btnBrowseAudio, btnClearAudio;
juce::ToggleButton btnLoopAudio;
// Form
juce::Label lblName, lblStartTC, lblStopTC, lblAudio;
juce::TextEditor edName, edStartTC, edStopTC, edAudio;
// File chooser (must persist during async operation)
std::unique_ptr<juce::FileChooser> fileChooser;
// Cue editor window (lazy-created on first Cues click; reused after)
std::unique_ptr<GeneratorCuePointEditorWindow> cueWindow;
// Frame rate in fps used by the cue editor when projecting cue TC
// onto the audio waveform strip. Pushed by MainComponent (the only
// thing that knows the engine's current fps) before opening the
// window via setCurrentFpsForCueEditor. Default 30 if never set.
double currentFpsForCueEditor = 30.0;
// Playhead getter forwarded to the cue editor when opened. Set by
// MainComponent so the waveform strip can show a live red cursor
// whenever the engine is playing the preset that's being edited.
std::function<int64_t()> playheadGetter;
// Colors
juce::Colour bgDarker { 0xFF1A1A1A };
juce::Colour bgPanel { 0xFF333333 };
juce::Colour borderCol { 0xFF444444 };
juce::Colour textBright { 0xFFDDDDDD };
juce::Colour textMid { 0xFF999999 };
juce::Colour accentCyan { 0xFF00AAFF };
void rebuildRows()
{
rows = presetMap.getAllSorted();
}
void notifyChange()
{
presetMap.save();
rebuildRows();
table.updateContent();
table.repaint();
updateButtonStates();
if (onChange) onChange();
}
/// Normalize a timecode string (HH:MM:SS:FF) by carrying overflow.
static juce::String normalizeTC(const juce::String& tc)
{
auto parts = juce::StringArray::fromTokens(tc, ":.", "");
int h = 0, m = 0, s = 0, f = 0;
if (parts.size() >= 1) h = parts[0].getIntValue();
if (parts.size() >= 2) m = parts[1].getIntValue();
if (parts.size() >= 3) s = parts[2].getIntValue();
if (parts.size() >= 4) f = parts[3].getIntValue();
if (f < 0) f = 0;
if (s < 0) s = 0;
if (m < 0) m = 0;
if (h < 0) h = 0;
// Carry overflow
s += f / 30; f %= 30; // assume max 30fps for frame carry
m += s / 60; s %= 60;
h += m / 60; m %= 60;
h %= 24;
return juce::String(h).paddedLeft('0', 2) + ":"
+ juce::String(m).paddedLeft('0', 2) + ":"
+ juce::String(s).paddedLeft('0', 2) + ":"
+ juce::String(f).paddedLeft('0', 2);
}
/// Build a GeneratorPreset from the current form fields.
/// Normalises Start TC / Stop TC and writes the normalised values back
/// to the editors so what the user sees matches what gets saved.
GeneratorPreset readFormToPreset(const juce::String& name)
{
GeneratorPreset p;
p.name = name;
p.startTC = edStartTC.getText().trim();
p.stopTC = edStopTC.getText().trim();
p.audioFilePath = edAudio.getText().trim();
p.audioLoop = btnLoopAudio.getToggleState();
if (p.startTC.isEmpty()) p.startTC = "00:00:00:00";
if (p.stopTC.isEmpty()) p.stopTC = "00:00:00:00";
p.startTC = normalizeTC(p.startTC);
p.stopTC = normalizeTC(p.stopTC);
edStartTC.setText(p.startTC, false);
edStopTC.setText(p.stopTC, false);
return p;
}
/// Return `name` unchanged if no preset exists with that name; otherwise
/// append " (2)", " (3)", ... until a free name is found. Comparison
/// is case-insensitive to match the underlying map's key handling.
/// In the absurd edge case where 999 numbered duplicates already exist,
/// fall back to a timestamp suffix rather than returning a name that
/// would silently overwrite an existing preset.
juce::String makeUniqueName(const juce::String& name) const
{
if (presetMap.find(name) == nullptr)
return name;
for (int i = 2; i < 1000; ++i)
{
auto candidate = name + " (" + juce::String(i) + ")";
if (presetMap.find(candidate) == nullptr)
return candidate;
}
// Pathological -- thousands of duplicates already exist. Use a
// timestamp so we still return a unique name; if even *that* exists
// we just return it anyway, which is the best we can do without
// throwing.
return name + " (" + juce::String(juce::Time::currentTimeMillis()) + ")";
}
/// ADD always creates a new preset. If the typed name is already in
/// use, the new preset is auto-renamed "Name (2)", "Name (3)", etc.
/// The form is repopulated so the user sees the actual name used.
void addNewPreset()
{
auto name = edName.getText().trim();
if (name.isEmpty())
{
edName.grabKeyboardFocus();
return;
}
auto uniqueName = makeUniqueName(name);
auto p = readFormToPreset(uniqueName);
// Reflect the actual stored name in the field whenever it differs
// from what was typed -- either because we auto-numbered to avoid
// a collision, or because the input had surrounding whitespace
// that got trimmed.
if (uniqueName != edName.getText())
edName.setText(uniqueName, juce::dontSendNotification);
// Close any open cue window: addOrUpdate on an unordered_map can
// trigger a rehash that invalidates pointers to existing values,
// which is what the cue window is holding internally.
closeCueEditorWindow();
presetMap.addOrUpdate(p);
notifyChange();
// Select the newly added row so SAVE / DELETE target it.
for (int i = 0; i < (int)rows.size(); ++i)
{
if (rows[(size_t)i].name.equalsIgnoreCase(uniqueName))
{
table.selectRow(i);
break;
}
}
}
/// SAVE updates the currently-selected preset in place. The name field
/// can be edited to rename the preset, but only if the new name is not
/// already used by a *different* preset -- in that case we refuse and
/// tell the user, so SAVE never silently overwrites someone else's
/// preset. When no row is selected, SAVE is a no-op (the button is
/// disabled in that state, but we double-check defensively).
void saveSelectedPreset()
{
auto name = edName.getText().trim();
if (name.isEmpty())
{
edName.grabKeyboardFocus();
return;
}
int sel = table.getSelectedRow();
if (sel < 0 || sel >= (int)rows.size())
return; // nothing selected; UI should already prevent this
// Snapshot the existing name *by value* before any mutation -- the
// rows[] vector is rebuilt by notifyChange(), so a reference into
// it would dangle the moment we touch the map.
const juce::String oldName = rows[(size_t)sel].name;
const bool nameChanged = ! oldName.equalsIgnoreCase(name);
// If the user typed a name that belongs to a *different* preset,
// refuse the rename rather than silently clobber it. We're already
// inside the nameChanged branch, where the canonical keys (lower-
// cased + trimmed) of old and new differ -- so any non-null find()
// is necessarily a different preset. A case-only rename
// ("Foo" -> "FOO") sets nameChanged to false via equalsIgnoreCase
// and skips this branch entirely, hitting addOrUpdate with the same
// key and updating the entry's display name in place.
if (nameChanged && presetMap.find(name) != nullptr)
{
juce::AlertWindow::showMessageBoxAsync(
juce::MessageBoxIconType::WarningIcon,
"Name in use",
"A preset called \"" + name + "\" already exists. "
"Choose a different name, or select that preset and Save to overwrite it.",
"OK");
edName.grabKeyboardFocus();
return;
}
if (nameChanged)
presetMap.remove(oldName);
auto p = readFormToPreset(name);
// Mirror the trimmed name back if the user's input had surrounding
// whitespace (matches what addNewPreset does).
if (name != edName.getText())
edName.setText(name, juce::dontSendNotification);
// Close any cue window for safety: even if the user is editing the
// same preset, the rename / overwrite flow goes through remove +
// addOrUpdate which can rehash and invalidate the cue window's
// pointer. Re-opening Cues from the table picks up the new entry.
closeCueEditorWindow();
presetMap.addOrUpdate(p);
notifyChange();
// Re-select the (possibly renamed) preset so subsequent SAVE keeps
// working without needing to click the row again.
for (int i = 0; i < (int)rows.size(); ++i)
{
if (rows[(size_t)i].name.equalsIgnoreCase(name))
{
table.selectRow(i);
break;
}
}
}
void deleteSelected()
{
int sel = table.getSelectedRow();
if (sel < 0 || sel >= (int)rows.size()) return;
// Close cue editor: it may be holding a reference into the very
// entry we're about to remove from the map.
closeCueEditorWindow();
presetMap.remove(rows[(size_t)sel].name);
notifyChange();
// Clear form
edName.clear();
edStartTC.setText("00:00:00:00", false);
edStopTC.setText("00:00:00:00", false);
edAudio.clear();
btnLoopAudio.setToggleState(false, juce::dontSendNotification);
updateButtonStates();
}
/// Close any open cue editor window. Called before any operation
/// that mutates the preset map (delete, rename, clearAll, import) to
/// avoid leaving the cue window with a dangling reference into a
/// preset entry that may be moved or destroyed by std::map ops.
void closeCueEditorWindow()
{
if (cueWindow != nullptr)
{
cueWindow->setVisible(false);
cueWindow.reset();
}
}
/// Open the cue-point editor for the selected preset.
/// The window is constructed against a *pointer* into the live
/// GeneratorPresetMap (not against rows[], which is a sorted snapshot
/// that gets rebuilt on every notifyChange). That way edits made in
/// the cue window are persisted on the actual preset object.
void openCueEditor()
{
int sel = table.getSelectedRow();
if (sel < 0 || sel >= (int)rows.size()) return;
const auto presetName = rows[(size_t)sel].name;
auto* livePreset = presetMap.find(presetName);
if (livePreset == nullptr) return; // shouldn't happen, defensive
// Close any previous window first (it may be holding a reference
// into a different preset, or even a stale one if the user just
// renamed something).
closeCueEditorWindow();
cueWindow = std::make_unique<GeneratorCuePointEditorWindow>(
*livePreset, currentFpsForCueEditor);
if (auto* ed = cueWindow->getEditor())
{
ed->onChange = [this]
{
// Persist + refresh the preset table. rebuildRows only
// *reads* the map (copies entries into the rows snapshot),
// it doesn't mutate the underlying unordered_map, so the
// cue window's pointer into the map remains valid.
presetMap.save();
rebuildRows();
table.updateContent();
table.repaint();
if (onChange) onChange();
};
// If the host installed a playhead getter (MainComponent did,
// bound to its engine), forward the same getter to the cue
// editor so it can drive the live playback cursor in the
// waveform strip. When no getter is set the cue editor just
// doesn't show a playhead -- everything else still works.
if (playheadGetter)
ed->setPlayheadGetter(playheadGetter);
}
cueWindow->setVisible(true);
cueWindow->toFront(true);
}
void clearAll()
{
if (rows.empty()) return;
auto options = juce::MessageBoxOptions()
.withIconType(juce::MessageBoxIconType::WarningIcon)
.withTitle("Clear All Presets")
.withMessage("Remove all generator presets? This cannot be undone.")
.withButton("Clear All")
.withButton("Cancel");
confirmBox = juce::AlertWindow::showScopedAsync(options,
[this](int result)
{
if (result == 1)
{
closeCueEditorWindow();
presetMap.clear();
notifyChange();
edName.clear();
edStartTC.setText("00:00:00:00", false);
edStopTC.setText("00:00:00:00", false);
edAudio.clear();
btnLoopAudio.setToggleState(false, juce::dontSendNotification);
}
});
}
juce::ScopedMessageBox confirmBox;
void browseForAudio()
{
// Build a wildcard list of supported audio extensions. We do not
// construct an AudioFormatManager here just to query extensions; the
// file chooser will accept anything matching this pattern and the
// engine will validate when loading.
juce::String wildcards = "*.wav;*.aif;*.aiff;*.flac;*.ogg";
#if JUCE_USE_MP3AUDIOFORMAT
wildcards += ";*.mp3";
#endif
// Pick a sensible starting directory: the existing file's folder if
// it still exists, otherwise the user's Music folder. Defends
// against imported presets pointing to paths that no longer exist.
juce::File initial;
auto path = edAudio.getText().trim();
if (path.isNotEmpty())
{
juce::File f(path);
if (f.existsAsFile() || f.getParentDirectory().exists())
initial = f.getParentDirectory();
}
if (initial == juce::File())
initial = juce::File::getSpecialLocation(juce::File::userMusicDirectory);
fileChooser = std::make_unique<juce::FileChooser>(
"Select audio file for preset",
initial,
wildcards);
fileChooser->launchAsync(
juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
[this](const juce::FileChooser& fc)
{
auto file = fc.getResult();
if (file == juce::File() || ! file.existsAsFile()) return;
edAudio.setText(file.getFullPathName(), false);
updateStopTCEnabledState();
});
}
void clearAudioField()
{
edAudio.clear();
btnLoopAudio.setToggleState(false, juce::dontSendNotification);
updateStopTCEnabledState();
}
void exportPresets()
{
if (rows.empty()) return;
fileChooser = std::make_unique<juce::FileChooser>(
"Export Generator Presets",
juce::File::getSpecialLocation(juce::File::userDesktopDirectory)
.getChildFile("generator_presets.json"),
"*.json");
fileChooser->launchAsync(
juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::canSelectFiles,
[this](const juce::FileChooser& fc)
{
auto file = fc.getResult();
if (file == juce::File()) return;
auto* root = new juce::DynamicObject();
root->setProperty("version", 1);
juce::Array<juce::var> arr;
for (auto& p : rows)
arr.add(p.toVar());
root->setProperty("presets", arr);
file.replaceWithText(juce::JSON::toString(juce::var(root)));
});
}
void importPresets()
{
fileChooser = std::make_unique<juce::FileChooser>(
"Import Generator Presets",
juce::File::getSpecialLocation(juce::File::userDesktopDirectory),
"*.json");
fileChooser->launchAsync(
juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
[this](const juce::FileChooser& fc)
{
auto file = fc.getResult();
if (file == juce::File() || !file.existsAsFile()) return;
auto parsed = juce::JSON::parse(file.loadFileAsString());
auto* obj = parsed.getDynamicObject();
if (!obj || !obj->hasProperty("presets"))
{
juce::AlertWindow::showMessageBoxAsync(
juce::MessageBoxIconType::WarningIcon,
"Import Failed",
"This file is not a valid generator presets file.");
return;
}
auto* arr = obj->getProperty("presets").getArray();
if (!arr) return;
// Close any cue window: the bulk addOrUpdate calls below
// can rehash the underlying unordered_map and invalidate
// pointers held by the cue window.
closeCueEditorWindow();
int imported = 0;
for (auto& item : *arr)
{
GeneratorPreset p;
p.fromVar(item);
if (p.hasValidKey())
{
presetMap.addOrUpdate(p);
++imported;
}
}
if (imported > 0)
notifyChange();
});
}
void showOscReference()
{
juce::String help;
help << "OSC COMMAND REFERENCE\n";
help << "==============================================\n\n";
help << "Default port: 9800 (configurable in Generator panel)\n\n";
help << "ENGINE TARGETING (N = engine number, required)\n\n";
help << "TRANSPORT\n";
help << " /stc/N/gen/play\n";
help << " /stc/N/gen/pause\n";
help << " /stc/N/gen/stop\n\n";
help << "MODE\n";
help << " /stc/N/gen/clock (int) 0=transport, 1=clock\n\n";
help << "TIMECODE\n";
help << " /stc/N/gen/start (string) \"HH:MM:SS:FF\"\n";
help << " /stc/N/gen/stoptime (string) \"HH:MM:SS:FF\"\n\n";
help << "PRESETS\n";
help << " /stc/N/gen/preset (string) preset name (loads + plays)\n\n";
help << "N = 1 to 8 (engine number)\n\n";
help << "EXAMPLES\n\n";
help << "QLab (Network Cue, type OSC):\n";
help << " Destination: <STC IP>:9800\n";
help << " /stc/1/gen/play\n";
help << " /stc/1/gen/stop\n";
help << " /stc/1/gen/start 01:30:00:00\n";
help << " /stc/1/gen/stoptime 02:00:00:00\n";
help << " /stc/1/gen/preset MyPreset\n\n";
help << "Resolume / Companion / TouchOSC:\n";
help << " Host: <STC IP>, Port: 9800\n";
help << " Same address patterns as above\n\n";
help << "TIMECODE FORMAT\n";
help << " String argument: \"HH:MM:SS:FF\"\n";
help << " 00:00:00:00 = midnight\n";
help << " 01:30:00:00 = 1 hour 30 minutes\n";
help << " 00:05:30:15 = 5 min, 30 sec, frame 15";
juce::AlertWindow::showMessageBoxAsync(
juce::MessageBoxIconType::InfoIcon,
"OSC Command Reference",
help);
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(GeneratorPresetEditor)
};