Debian Codegraph @

src/tracks/playabletrack/wavetrack/ui/WaveTrackControls.cpp

raw
1 /**********************************************************************
2
3 Audacity: A Digital Audio Editor
4
5 WaveTrackControls.cpp
6
7 Paul Licameli split from TrackPanel.cpp
8
9 **********************************************************************/
10
11
12 #include "WaveTrackControls.h"
13
14 #include "../../ui/PlayableTrackButtonHandles.h"
15 #include "WaveTrackSliderHandles.h"
16
17 #include "WaveChannelView.h"
18 #include "WaveChannelViewConstants.h"
19 #include "AudioIOBase.h"
20 #include "../../../../CellularPanel.h"
21 #include "Project.h"
22 #include "ProjectAudioIO.h"
23 #include "ProjectHistory.h"
24 #include "../../../../ProjectWindows.h"
25 #include "../../../../RefreshCode.h"
26 #include "ShuttleGui.h"
27 #include "SyncLock.h"
28 #include "Theme.h"
29 #include "../../../../TrackArtist.h"
30 #include "../../../../TrackPanel.h"
31 #include "TrackFocus.h"
32 #include "../../../../TrackPanelMouseEvent.h"
33 #include "WaveClip.h"
34 #include "WaveTrack.h"
35 #include "WaveTrackUtilities.h"
36 #include "RealtimeEffectManager.h"
37 #include "../../../../prefs/PrefsDialog.h"
38 #include "../../../../prefs/ThemePrefs.h"
39 #include "AudacityMessageBox.h"
40 #include "ProgressDialog.h"
41 #include "UserException.h"
42 #include "Identifier.h"
43
44 #include <wx/app.h>
45 #include <wx/combobox.h>
46 #include <wx/frame.h>
47 #include <wx/sizer.h>
48
49 #include "MixAndRender.h"
50
51 WaveTrackControls::~WaveTrackControls() = default;
52
53 std::vector<UIHandlePtr> WaveTrackControls::HitTest
54 (const TrackPanelMouseState & st,
55 const AudacityProject *pProject)
56 {
57 // Hits are mutually exclusive, results single
58 const wxMouseState &state = st.state;
59 const wxRect &rect = st.rect;
60 if (state.ButtonIsDown(wxMOUSE_BTN_LEFT)) {
61 auto track = FindTrack();
62 std::vector<UIHandlePtr> results;
63 auto result = [&]{
64 UIHandlePtr result;
65 if (NULL != (result = MuteButtonHandle::HitTest(
66 mMuteHandle, state, rect, pProject, track)))
67 return result;
68
69 if (NULL != (result = SoloButtonHandle::HitTest(
70 mSoloHandle, state, rect, pProject, track)))
71 return result;
72
73 if (NULL != (result = EffectsButtonHandle::HitTest(
74 mEffectsHandle, state, rect, pProject, track)))
75 return result;
76
77 if (NULL != (result = VolumeSliderHandle::HitTest(
78 mVolumeHandle, state, rect, track)))
79 return result;
80
81 if (NULL != (result = PanSliderHandle::HitTest(
82 mPanHandle, state, rect, track)))
83 return result;
84
85 return result;
86 }();
87 if (result) {
88 results.push_back(result);
89 return results;
90 }
91 }
92
93 return PlayableTrackControls::HitTest(st, pProject);
94 }
95
96 WaveTrack &WaveTrackPopupMenuTable::FindWaveTrack() const
97 {
98 return static_cast<WaveTrack&>(mpData->track);
99 };
100
101 enum {
102 reserveDisplays = 100,
103
104 OnRate8ID = 30000, // <---
105 OnRate11ID, // |
106 OnRate16ID, // |
107 OnRate22ID, // |
108 OnRate44ID, // |
109 OnRate48ID, // | Leave these in order
110 OnRate88ID, // |
111 OnRate96ID, // |
112 OnRate176ID, // |
113 OnRate192ID, // |
114 OnRate352ID, // |
115 OnRate384ID, // |
116 OnRateOtherID, // |
117 // |
118 On16BitID, // |
119 On24BitID, // |
120 OnFloatID, // <---
121
122 OnMultiViewID,
123
124 OnSetDisplayId, lastDisplayId = (OnSetDisplayId + reserveDisplays - 1),
125
126 OnChannelLeftID,
127 OnChannelRightID,
128 OnChannelMonoID,
129
130 OnMergeStereoID,
131
132 OnSwapChannelsID,
133 OnSplitStereoID,
134 OnSplitStereoMonoID,
135
136 ChannelMenuID,
137
138 // Range of ids for registered items -- keep this last!
139 FirstAttachedItemId,
140 };
141
142
143 namespace {
144 using ValueFinder = std::function< int( WaveTrack& ) >;
145
146 // A function that makes functions that check and enable sub-menu items,
147 // parametrized by how you get the relevant value from a track's settings
148 template< typename Table >
149 PopupMenuTableEntry::InitFunction initFn( const ValueFinder &findValue )
150 {
151 return [findValue]( PopupMenuHandler &handler, wxMenu &menu, int id ){
152 auto pData = static_cast<Table&>( handler ).mpData;
153 auto &track = static_cast<WaveTrack&>(pData->track);
154 auto &project = pData->project;
155 bool unsafe = ProjectAudioIO::Get( project ).IsAudioActive();
156
157 menu.Check(id, id == findValue(track));
158 menu.Enable( id, !unsafe );
159 };
160 };
161 }
162
163
164 //=============================================================================
165 // Table class for a sub-menu
166 struct FormatMenuTable : PopupMenuTable
167 {
168 FormatMenuTable()
169 : PopupMenuTable{ "SampleFormat", XO("&Format") }
170 {}
171 DECLARE_POPUP_MENU(FormatMenuTable);
172
173 static FormatMenuTable &Instance();
174
175 void InitUserData(void *pUserData) override;
176
177 PlayableTrackControls::InitMenuData *mpData{};
178
179 static int IdOfFormat(sampleFormat format);
180
181 void OnFormatChange(wxCommandEvent & event);
182 };
183
184 FormatMenuTable &FormatMenuTable::Instance()
185 {
186 static FormatMenuTable instance;
187 return instance;
188 }
189
190 void FormatMenuTable::InitUserData(void *pUserData)
191 {
192 mpData = static_cast<PlayableTrackControls::InitMenuData*>(pUserData);
193 }
194
195
196 BEGIN_POPUP_MENU(FormatMenuTable)
197 static const auto fn = initFn< FormatMenuTable >(
198 []( WaveTrack &track ){
199 return IdOfFormat( track.GetSampleFormat() );
200 }
201 );
202
203 AppendRadioItem( "16Bit", On16BitID,
204 GetSampleFormatStr(int16Sample), POPUP_MENU_FN( OnFormatChange ), fn );
205 AppendRadioItem("24Bit", On24BitID,
206 GetSampleFormatStr( int24Sample), POPUP_MENU_FN( OnFormatChange ), fn );
207 AppendRadioItem( "Float", OnFloatID,
208 GetSampleFormatStr(floatSample), POPUP_MENU_FN( OnFormatChange ), fn );
209
210 END_POPUP_MENU()
211
212 /// Converts a format enumeration to a wxWidgets menu item Id.
213 int FormatMenuTable::IdOfFormat(sampleFormat format)
214 {
215 switch (format) {
216 case int16Sample:
217 return On16BitID;
218 case int24Sample:
219 return On24BitID;
220 case floatSample:
221 return OnFloatID;
222 default:
223 // ERROR -- should not happen
224 wxASSERT(false);
225 break;
226 }
227 return OnFloatID;// Compiler food.
228 }
229
230 /// Handles the selection from the Format submenu of the
231 /// track menu.
232 void FormatMenuTable::OnFormatChange(wxCommandEvent & event)
233 {
234 int id = event.GetId();
235 wxASSERT(id >= On16BitID && id <= OnFloatID);
236 auto &track = static_cast<WaveTrack&>(mpData->track);
237
238 sampleFormat newFormat = int16Sample;
239
240 switch (id) {
241 case On16BitID:
242 newFormat = int16Sample;
243 break;
244 case On24BitID:
245 newFormat = int24Sample;
246 break;
247 case OnFloatID:
248 newFormat = floatSample;
249 break;
250 default:
251 // ERROR -- should not happen
252 wxASSERT(false);
253 break;
254 }
255 if (newFormat == track.GetSampleFormat())
256 return; // Nothing to do.
257
258 AudacityProject *const project = &mpData->project;
259
260 ProgressDialog progress{ XO("Changing sample format"),
261 XO("Processing... 0%%"),
262 pdlgHideStopButton };
263
264 // Simply finding a denominator for the progress dialog
265 // Hidden samples are processed too, they should be counted as well
266 // (Correctly counting all samples of all channels)
267 const sampleCount totalSamples =
268 WaveTrackUtilities::GetSequenceSamplesCount(track);
269 sampleCount processedSamples{ 0 };
270
271 // Below is the lambda function that is passed along the call chain to
272 // the Sequence::ConvertToSampleFormat. This callback function is used
273 // to report the conversion progress and update the progress dialog.
274 auto progressUpdate = [&progress, &totalSamples, &processedSamples]
275 (size_t newlyProcessedCount)->void
276 {
277 processedSamples += newlyProcessedCount;
278 double d_processed = processedSamples.as_double();
279 double d_total = totalSamples.as_double();
280 int percentage{ static_cast<int>((d_processed / d_total) * 100) };
281
282 auto progressStatus = progress.Update(d_processed, d_total,
283 XO("Processing... %i%%").Format(percentage));
284
285 if (progressStatus != ProgressResult::Success)
286 throw UserException{};
287 };
288
289 track.ConvertToSampleFormat(newFormat, progressUpdate);
290
291 ProjectHistory::Get( *project )
292 /* i18n-hint: The strings name a track and a format */
293 .PushState(XO("Changed '%s' to %s")
294 .Format(track.GetName(), GetSampleFormatStr(newFormat)),
295 XO("Format Change"));
296
297 using namespace RefreshCode;
298 mpData->result = RefreshAll | FixScrollbars;
299 }
300
301
302 //=============================================================================
303 // Table class for a sub-menu
304 struct RateMenuTable : PopupMenuTable
305 {
306 RateMenuTable()
307 : PopupMenuTable{ "SampleRate", XO("Rat&e") }
308 {}
309 DECLARE_POPUP_MENU(RateMenuTable);
310
311 static RateMenuTable &Instance();
312
313 void InitUserData(void *pUserData) override;
314
315 PlayableTrackControls::InitMenuData *mpData{};
316
317 static int IdOfRate(int rate);
318 /// Sets the sample rate for a track
319 void SetRate(WaveTrack &track, double rate);
320
321 void OnRateChange(wxCommandEvent & event);
322 void OnRateOther(wxCommandEvent & event);
323 };
324
325 RateMenuTable &RateMenuTable::Instance()
326 {
327 static RateMenuTable instance;
328 return instance;
329 }
330
331 void RateMenuTable::InitUserData(void *pUserData)
332 {
333 mpData = static_cast<PlayableTrackControls::InitMenuData*>(pUserData);
334 }
335
336 // Because of Bug 1780 we can't use AppendRadioItem
337 // If we did, we'd get no message when clicking on Other...
338 // when it is already selected.
339 BEGIN_POPUP_MENU(RateMenuTable)
340 static const auto fn = initFn< RateMenuTable >(
341 []( WaveTrack &track ){
342 return IdOfRate( (int)track.GetRate() );
343 }
344 );
345
346 AppendCheckItem( "8000", OnRate8ID, XXO("8000 Hz"), POPUP_MENU_FN( OnRateChange ), fn );
347 AppendCheckItem( "11025", OnRate11ID, XXO("11025 Hz"), POPUP_MENU_FN( OnRateChange ), fn );
348 AppendCheckItem( "16000", OnRate16ID, XXO("16000 Hz"), POPUP_MENU_FN( OnRateChange ), fn );
349 AppendCheckItem( "22050", OnRate22ID, XXO("22050 Hz"), POPUP_MENU_FN( OnRateChange ), fn );
350 AppendCheckItem( "44100", OnRate44ID, XXO("44100 Hz"), POPUP_MENU_FN( OnRateChange ), fn );
351 AppendCheckItem( "48000", OnRate48ID, XXO("48000 Hz"), POPUP_MENU_FN( OnRateChange ), fn );
352 AppendCheckItem( "88200", OnRate88ID, XXO("88200 Hz"), POPUP_MENU_FN( OnRateChange ), fn );
353 AppendCheckItem( "96000", OnRate96ID, XXO("96000 Hz"), POPUP_MENU_FN( OnRateChange ), fn );
354 AppendCheckItem( "176400", OnRate176ID, XXO("176400 Hz"), POPUP_MENU_FN( OnRateChange ), fn );
355 AppendCheckItem( "192000", OnRate192ID, XXO("192000 Hz"), POPUP_MENU_FN( OnRateChange ), fn );
356 AppendCheckItem( "352800", OnRate352ID, XXO("352800 Hz"), POPUP_MENU_FN( OnRateChange ), fn );
357 AppendCheckItem( "384000", OnRate384ID, XXO("384000 Hz"), POPUP_MENU_FN( OnRateChange ), fn );
358 AppendCheckItem( "Other", OnRateOtherID, XXO("&Other..."), POPUP_MENU_FN( OnRateOther ), fn );
359
360 END_POPUP_MENU()
361
362 const int nRates = 12;
363
364 /// gRates MUST CORRESPOND DIRECTLY TO THE RATES AS LISTED IN THE MENU!!
365 /// IN THE SAME ORDER!!
366 static int gRates[nRates] = { 8000, 11025, 16000, 22050, 44100, 48000, 88200, 96000,
367 176400, 192000, 352800, 384000 };
368
369 /// Converts a sampling rate to a wxWidgets menu item id
370 int RateMenuTable::IdOfRate(int rate)
371 {
372 for (int i = 0; i<nRates; i++) {
373 if (gRates[i] == rate)
374 return i + OnRate8ID;
375 }
376 return OnRateOtherID;
377 }
378
379 void RateMenuTable::SetRate(WaveTrack &track, double rate)
380 {
381 AudacityProject *const project = &mpData->project;
382 auto end1 = track.GetEndTime();
383 track.SetRate(rate);
384 if (SyncLockState::Get(*project).IsSyncLocked()) {
385 auto end2 = track.GetEndTime();
386 for (auto pLocked : SyncLock::Group(track)) {
387 if (pLocked != &track)
388 pLocked->SyncLockAdjust(end1, end2);
389 }
390 }
391
392 // Separate conversion of "rate" enables changing the decimals without affecting i18n
393 wxString rateString = wxString::Format(wxT("%.3f"), rate);
394 ProjectHistory::Get( *project )
395 /* i18n-hint: The string names a track */
396 .PushState(XO("Changed '%s' to %s Hz")
397 .Format(track.GetName(), rateString),
398 XO("Rate Change"));
399 }
400
401 /// This method handles the selection from the Rate
402 /// submenu of the track menu, except for "Other" (/see OnRateOther).
403 void RateMenuTable::OnRateChange(wxCommandEvent & event)
404 {
405 int id = event.GetId();
406 wxASSERT(id >= OnRate8ID && id <= OnRate384ID);
407 auto &track = static_cast<WaveTrack&>(mpData->track);
408
409 SetRate(track, gRates[id - OnRate8ID]);
410
411 using namespace RefreshCode;
412 mpData->result = RefreshAll | FixScrollbars;
413 }
414
415 void RateMenuTable::OnRateOther(wxCommandEvent &)
416 {
417 auto &track = static_cast<WaveTrack&>(mpData->track);
418
419 int newRate;
420
421 /// \todo Remove artificial constants!!
422 /// \todo Make a real dialog box out of this!!
423 while (true)
424 {
425 wxDialogWrapper dlg(mpData->pParent, wxID_ANY, XO("Set Rate"));
426 dlg.SetName();
427 ShuttleGui S(&dlg, eIsCreating);
428 wxString rate;
429 wxComboBox *cb;
430
431 rate.Printf(wxT("%ld"), lrint(track.GetRate()));
432
433 wxArrayStringEx rates{
434 wxT("8000") ,
435 wxT("11025") ,
436 wxT("16000") ,
437 wxT("22050") ,
438 wxT("44100") ,
439 wxT("48000") ,
440 wxT("88200") ,
441 wxT("96000") ,
442 wxT("176400") ,
443 wxT("192000") ,
444 wxT("352800") ,
445 wxT("384000") ,
446 };
447
448 S.StartVerticalLay(true);
449 {
450 S.SetBorder(10);
451 S.StartHorizontalLay(wxEXPAND, false);
452 {
453 cb = S.AddCombo(XXO("New sample rate (Hz):"),
454 rate,
455 rates);
456 #if defined(__WXMAC__)
457 // As of wxMac-2.8.12, setting manually is required
458 // to handle rates not in the list. See: Bug #427
459 cb->SetValue(rate);
460 #endif
461 }
462 S.EndHorizontalLay();
463 S.AddStandardButtons();
464 }
465 S.EndVerticalLay();
466
467 dlg.SetClientSize(dlg.GetSizer()->CalcMin());
468 dlg.Center();
469
470 if (dlg.ShowModal() != wxID_OK)
471 {
472 return; // user cancelled dialog
473 }
474
475 long lrate;
476 if (cb->GetValue().ToLong(&lrate) && lrate >= 1 && lrate <= 1000000)
477 {
478 newRate = (int)lrate;
479 break;
480 }
481
482 AudacityMessageBox(
483 XO("The entered value is invalid"),
484 XO("Error"),
485 wxICON_ERROR,
486 mpData->pParent);
487 }
488
489 SetRate(track, newRate);
490
491 using namespace RefreshCode;
492 mpData->result = RefreshAll | FixScrollbars;
493 }
494
495 static const auto MenuPathStart = wxT("WaveTrackMenu");
496
497 //=============================================================================
498 // Class defining common command handlers for mono and stereo tracks
499 struct WaveTrackMenuTable : WaveTrackPopupMenuTable
500 {
501 static WaveTrackMenuTable &Instance();
502
503 WaveTrackMenuTable()
504 : WaveTrackPopupMenuTable{ MenuPathStart }
505 {
506 mNextId = FirstAttachedItemId;
507 }
508
509 void InitUserData(void *pUserData) override;
510
511 DECLARE_POPUP_MENU(WaveTrackMenuTable);
512
513 void OnMultiView(wxCommandEvent & event);
514 void OnSetDisplay(wxCommandEvent & event);
515
516 void OnMergeStereo(wxCommandEvent & event);
517
518 // TODO: more-than-two-channels
519 // How should we define generalized channel manipulation operations?
520 /// @brief Splits stereo track into two mono tracks, preserving
521 /// panning if \p stereo is set
522 void SplitStereo(bool stereo);
523
524 void OnSwapChannels(wxCommandEvent & event);
525 void OnSplitStereo(wxCommandEvent & event);
526 void OnSplitStereoMono(wxCommandEvent & event);
527 };
528
529 WaveTrackMenuTable &WaveTrackMenuTable::Instance()
530 {
531 static WaveTrackMenuTable instance;
532 return instance;
533 }
534
535 void WaveTrackMenuTable::InitUserData(void *pUserData)
536 {
537 mpData = static_cast<PlayableTrackControls::InitMenuData*>(pUserData);
538 }
539
540 static std::vector<WaveChannelSubViewType> AllTypes()
541 {
542 auto result = WaveChannelSubViewType::All();
543 if (result.size() > reserveDisplays) {
544 wxASSERT( false );
545 result.resize(reserveDisplays);
546 }
547 return result;
548 }
549
550 BEGIN_POPUP_MENU(WaveTrackMenuTable)
551 // Functions usable in callbacks to check and disable items
552 static const auto isMono =
553 []( PopupMenuHandler &handler ) -> bool {
554 auto &track =
555 static_cast< WaveTrackMenuTable& >( handler ).FindWaveTrack();
556 return 1 == track.NChannels();
557 };
558
559 static const auto isUnsafe =
560 []( PopupMenuHandler &handler ) -> bool {
561 auto &project =
562 static_cast< WaveTrackMenuTable& >( handler ).mpData->project;
563 return RealtimeEffectManager::Get(project).IsActive() &&
564 ProjectAudioIO::Get( project ).IsAudioActive();
565 };
566
567
568 BeginSection( "SubViews" );
569 // Multi-view check mark item, if more than one track sub-view type is
570 // known
571 Append(Adapt<My>([](My &table) {
572 return (WaveChannelSubViews::numFactories() > 1)
573 ? std::make_unique<Entry>(
574 "MultiView", Entry::CheckItem, OnMultiViewID, XXO("&Multi-view"),
575 POPUP_MENU_FN( OnMultiView ),
576 table,
577 [](PopupMenuHandler &handler, wxMenu &menu, int id){
578 auto &table = static_cast<WaveTrackMenuTable&>(handler);
579 auto &track = table.FindWaveTrack();
580 const auto &view = WaveChannelView::GetFirst(track);
581 menu.Check(id, view.GetMultiView());
582 })
583 : nullptr;
584 }));
585
586 // Append either a checkbox or radio item for each sub-view.
587 // Radio buttons if in single-view mode, else checkboxes
588 int id = OnSetDisplayId;
589 for ( const auto &type : AllTypes() ) {
590 static const auto initFn = []( bool radio ){ return
591 [radio]( PopupMenuHandler &handler, wxMenu &menu, int id ){
592 // Find all known sub-view types
593 const auto allTypes = AllTypes();
594
595 // How to convert a type to a menu item id
596 const auto IdForType =
597 [&allTypes](const WaveChannelSubViewType &type) -> int {
598 const auto begin = allTypes.begin();
599 return OnSetDisplayId +
600 (std::find(begin, allTypes.end(), type) - begin);
601 };
602
603 auto &table = static_cast< WaveTrackMenuTable& >( handler );
604 auto &track = table.FindWaveTrack();
605
606 const auto &view = WaveChannelView::GetFirst(track);
607
608 const auto displays = view.GetDisplays();
609 const auto end = displays.end();
610 bool check = (end !=
611 std::find_if(displays.begin(), end,
612 [&](const WaveChannelSubViewType &type){
613 return id == IdForType(type); }));
614 menu.Check( id, check );
615
616 // Bug2275 residual
617 // Disable the checking-off of the only sub-view
618 if ( !radio && displays.size() == 1 && check )
619 menu.Enable( id, false );
620 };
621 };
622 Append(Adapt<My>([type, id](My &table) {
623 const auto pTrack = &table.FindWaveTrack();
624 const auto &view = WaveChannelView::GetFirst(*pTrack);
625 const auto itemType =
626 view.GetMultiView() ? Entry::CheckItem : Entry::RadioItem;
627 return std::make_unique<Entry>( type.name.Internal(), itemType,
628 id, type.name.Msgid(),
629 POPUP_MENU_FN( OnSetDisplay ), table,
630 initFn( !view.GetMultiView() ) );
631 }));
632 ++id;
633 }
634 BeginSection( "Extra" );
635 EndSection();
636 EndSection();
637
638 BeginSection( "Channels" );
639 AppendItem( "MakeStereo", OnMergeStereoID, XXO("Ma&ke Stereo Track"),
640 POPUP_MENU_FN( OnMergeStereo ),
641 []( PopupMenuHandler &handler, wxMenu &menu, int id ){
642 bool canMakeStereo = !isUnsafe( handler ) && isMono( handler );
643 if ( canMakeStereo ) {
644 AudacityProject &project =
645 static_cast< WaveTrackMenuTable& >( handler ).mpData->project;
646 auto &tracks = TrackList::Get( project );
647 auto &table = static_cast< WaveTrackMenuTable& >( handler );
648 auto &track = table.FindWaveTrack();
649 auto next = * ++ tracks.Find(&track);
650 canMakeStereo =
651 (next &&
652 next->NChannels() == 1 &&
653 track_cast<WaveTrack*>(next));
654 }
655 menu.Enable( id, canMakeStereo );
656 }
657 );
658
659 AppendItem( "Swap", OnSwapChannelsID, XXO("Swap Stereo &Channels"),
660 POPUP_MENU_FN( OnSwapChannels ),
661 []( PopupMenuHandler &handler, wxMenu &menu, int id ){
662 auto &track =
663 static_cast< WaveTrackMenuTable& >( handler ).FindWaveTrack();
664 bool isStereo =
665 2 == track.NChannels();
666 menu.Enable( id, isStereo && !isUnsafe( handler ) );
667 }
668 );
669
670 static const auto enableSplitStereo =
671 []( PopupMenuHandler &handler, wxMenu &menu, int id ){
672 menu.Enable( id, !isMono( handler ) && !isUnsafe( handler ) );
673 };
674
675 AppendItem( "Split", OnSplitStereoID, XXO("Spl&it Stereo Track"),
676 POPUP_MENU_FN( OnSplitStereo ), enableSplitStereo );
677 AppendItem( "SplitToMono", OnSplitStereoMonoID,
678 XXO("Split Stereo to Mo&no"), POPUP_MENU_FN( OnSplitStereoMono ),
679 enableSplitStereo );
680 EndSection();
681
682 BeginSection( "Format" );
683 POPUP_MENU_SUB_MENU( "Format", FormatMenuTable, mpData )
684 EndSection();
685
686 BeginSection( "Rate" );
687 POPUP_MENU_SUB_MENU( "Rate", RateMenuTable, mpData )
688 EndSection();
689 END_POPUP_MENU()
690
691
692 void WaveTrackMenuTable::OnMultiView(wxCommandEvent & event)
693 {
694 auto &track = static_cast<WaveTrack&>(mpData->track);
695 auto &view = WaveChannelView::GetFirst(track);
696 bool multi = !view.GetMultiView();
697 const auto &displays = view.GetDisplays();
698 const auto display = displays.empty()
699 ? WaveChannelViewConstants::Waveform : displays.begin()->id;
700 view.SetMultiView(multi);
701
702 // Whichever sub-view was on top stays on top
703 // If going into Multi-view, it will be 1/nth the height.
704 // If exiting multi-view, it will be full height.
705 view.SetDisplay(display, !multi);
706 }
707
708 /// Set the Display mode based on the menu choice in the Track Menu.
709 void WaveTrackMenuTable::OnSetDisplay(wxCommandEvent & event)
710 {
711 int idInt = event.GetId();
712 wxASSERT(idInt >= OnSetDisplayId &&
713 idInt <= lastDisplayId);
714 auto &track = static_cast<WaveTrack&>(mpData->track);
715
716 auto id = AllTypes()[ idInt - OnSetDisplayId ].id;
717
718 auto &view = WaveChannelView::GetFirst(track);
719 if (view.GetMultiView()) {
720 if (!WaveChannelView::GetFirst(track)
721 .ToggleSubView(WaveChannelView::Display{ id } )) {
722 // Trying to toggle off the last sub-view. It was refused.
723 // Decide what to do here. Turn off multi-view instead?
724 // PRL: I don't agree that it makes sense
725 }
726 else
727 ProjectHistory::Get(mpData->project).ModifyState(true);
728 }
729 else {
730 const auto displays = view.GetDisplays();
731 const bool wrongType =
732 !(displays.size() == 1 && displays[0].id == id);
733 if (wrongType) {
734 WaveChannelView::GetFirst(track).SetDisplay(WaveChannelView::Display{ id });
735
736 AudacityProject *const project = &mpData->project;
737 ProjectHistory::Get( *project ).ModifyState(true);
738
739 using namespace RefreshCode;
740 mpData->result = RefreshAll | UpdateVRuler;
741 }
742 }
743 }
744
745 /// Merge two tracks into one stereo track ??
746 void WaveTrackMenuTable::OnMergeStereo(wxCommandEvent &)
747 {
748 AudacityProject *const project = &mpData->project;
749 auto &tracks = TrackList::Get( *project );
750
751 const auto first = tracks.Any<WaveTrack>().find(&mpData->track);
752 const auto left = *first;
753 const auto right = *std::next(first);
754
755 const auto checkAligned = [](const WaveTrack& left, const WaveTrack& right)
756 {
757 auto eqTrims = [](double a, double b)
758 {
759 return std::abs(a - b) <=
760 std::numeric_limits<double>::epsilon() * std::max(a, b);
761 };
762 const auto eps = 0.5 / left.GetRate();
763 const auto &rightIntervals = right.Intervals();
764 for (const auto &a : left.Intervals()) {
765 auto it = std::find_if(
766 rightIntervals.begin(),
767 rightIntervals.end(),
768 [&](const auto& b)
769 {
770 //Start() and End() are always snapped to a sample grid
771 return std::abs(a->Start() - b->Start()) < eps &&
772 std::abs(a->End() - b->End()) < eps &&
773 eqTrims(a->GetTrimLeft(), b->GetTrimLeft()) &&
774 eqTrims(a->GetTrimRight(), b->GetTrimRight()) &&
775 a->HasEqualPitchAndSpeed(*b);
776 });
777 if(it == rightIntervals.end())
778 return false;
779 }
780 return true;
781 };
782
783 if(RealtimeEffectList::Get(*left).GetStatesCount() != 0 ||
784 RealtimeEffectList::Get(*right).GetStatesCount() != 0 ||
785 !checkAligned(*left, *right))
786 {
787 const auto answer = BasicUI::ShowMessageBox(
788 XO(
789 "The tracks you are attempting to merge to stereo contain clips at\n"
790 "different positions, or otherwise mismatching clips. Merging them\n"
791 "will render the tracks.\n\n"
792 "This causes any realtime effects to be applied to the waveform and\n"
793 "hidden data to be removed. Additionally, the entire track will\n"
794 "become one large clip.\n\n"
795 "Do you wish to continue?"
796 ),
797 BasicUI::MessageBoxOptions{}
798 .ButtonStyle(BasicUI::Button::YesNo)
799 .Caption(XO("Combine mono to stereo")));
800 if(answer != BasicUI::MessageBoxResult::Yes)
801 return;
802 }
803
804 const auto viewMinimized =
805 ChannelView::Get(*left->GetChannel(0)).GetMinimized() &&
806 ChannelView::Get(*right->GetChannel(0)).GetMinimized();
807 const auto averageViewHeight =
808 (WaveChannelView::GetFirst(*left).GetHeight() +
809 WaveChannelView::GetFirst(*right).GetHeight()) / 2;
810
811 float origPanLeft = left->GetPan();
812 float origPanRight = right->GetPan();
813
814 left->SetPan(-1.0f);
815 right->SetPan(1.0f);
816 auto mix = MixAndRender(
817 TrackIterRange {
818 tracks.Any<const WaveTrack>().find(left),
819 ++tracks.Any<const WaveTrack>().find(right)
820 },
821 Mixer::WarpOptions{ tracks.GetOwner() },
822 (*first)->GetName(),
823 &WaveTrackFactory::Get(*project),
824 //use highest sample rate
825 std::max(left->GetRate(), right->GetRate()),
826 //use widest sample format
827 std::max(left->GetSampleFormat(), right->GetSampleFormat()),
828 0.0, 0.0);
829
830 if (!mix)
831 {
832 left->SetPan(origPanLeft);
833 right->SetPan(origPanRight);
834 return;
835 }
836
837 tracks.Insert(*first, mix);
838 tracks.Remove(*left);
839 tracks.Remove(*right);
840
841 for(const auto& channel : mix->Channels())
842 {
843 // Set NEW track heights and minimized state
844 auto& view = ChannelView::Get(*channel);
845 view.SetMinimized(viewMinimized);
846 view.SetExpandedHeight(averageViewHeight);
847 }
848 ProjectHistory::Get( *project ).PushState(
849 /* i18n-hint: The string names a track */
850 XO("Made '%s' a stereo track").Format(mix->GetName()),
851 XO("Make Stereo"));
852
853 using namespace RefreshCode;
854 mpData->result = RefreshAll | FixScrollbars;
855 }
856
857 /// Split a stereo track (or more-than-stereo?) into two (or more) tracks...
858 void WaveTrackMenuTable::SplitStereo(bool stereo)
859 {
860 AudacityProject *const project = &mpData->project;
861
862 int totalHeight = 0;
863 int nChannels = 0;
864
865 auto &track = static_cast<WaveTrack&>(mpData->track);
866 const std::vector<WaveTrack::Holder> unlinkedTracks = track.SplitChannels();
867 if (stereo) {
868 unlinkedTracks[0]->SetPan(-1.0f);
869 unlinkedTracks[1]->SetPan(1.0f);
870 }
871
872 for (const auto track : unlinkedTracks) {
873 auto &view = ChannelView::Get(*track->GetChannel(0));
874
875 //make sure no channel is smaller than its minimum height
876 if (view.GetHeight() < view.GetMinimizedHeight())
877 view.SetExpandedHeight(view.GetMinimizedHeight());
878 totalHeight += view.GetHeight();
879 ++nChannels;
880 }
881
882 int averageHeight = totalHeight / nChannels;
883
884 for (const auto track : unlinkedTracks)
885 // Make tracks the same height
886 ChannelView::Get(*track->GetChannel(0)).SetExpandedHeight(averageHeight);
887 }
888
889 /// Swap the left and right channels of a stero track...
890 void WaveTrackMenuTable::OnSwapChannels(wxCommandEvent &)
891 {
892 AudacityProject *const project = &mpData->project;
893
894 auto &trackFocus = TrackFocus::Get( *project );
895 auto &track = static_cast<WaveTrack&>(mpData->track);
896 track.SwapChannels();
897 ProjectHistory::Get( *project ).PushState(
898 /* i18n-hint: The string names a track */
899 XO("Swapped Channels in '%s'").Format(track.GetName()),
900 XO("Swap Channels"));
901
902 mpData->result = RefreshCode::RefreshAll;
903 }
904
905 /// Split a stereo track into two tracks...
906 void WaveTrackMenuTable::OnSplitStereo(wxCommandEvent &)
907 {
908 SplitStereo(true);
909 auto &track = static_cast<WaveTrack&>(mpData->track);
910 AudacityProject *const project = &mpData->project;
911 ProjectHistory::Get( *project ).PushState(
912 /* i18n-hint: The string names a track */
913 XO("Split stereo track '%s'").Format(track.GetName()),
914 XO("Split"));
915
916 using namespace RefreshCode;
917 mpData->result = RefreshAll | FixScrollbars;
918 }
919
920 /// Split a stereo track into two mono tracks...
921 void WaveTrackMenuTable::OnSplitStereoMono(wxCommandEvent &)
922 {
923 SplitStereo(false);
924 auto &track = static_cast<WaveTrack&>(mpData->track);
925 AudacityProject *const project = &mpData->project;
926 ProjectHistory::Get( *project ).PushState(
927 /* i18n-hint: The string names a track */
928 XO("Split Stereo to Mono '%s'").Format(track.GetName()),
929 XO("Split to Mono"));
930
931 using namespace RefreshCode;
932 mpData->result = RefreshAll | FixScrollbars;
933 }
934
935 PopupMenuTable *WaveTrackControls::GetMenuExtension(Track * pTrack)
936 {
937 static Registry::OrderingPreferenceInitializer init{
938 MenuPathStart,
939 {
940 {wxT("/SubViews/Extra"), wxT("WaveColor,SpectrogramSettings")},
941 }
942 };
943
944 WaveTrackMenuTable & result = WaveTrackMenuTable::Instance();
945 return &result;
946 }
947
948 WaveTrackPopupMenuTable &GetWaveTrackMenuTable()
949 {
950 return WaveTrackMenuTable::Instance();
951 }
952
953 // drawing related
954 #include "../../../../widgets/ASlider.h"
955 #include "../../../ui/CommonTrackInfo.h"
956 #include "../../../../TrackPanelDrawingContext.h"
957 #include "ViewInfo.h"
958
959 namespace {
960
961 void SliderDrawFunction
962 ( LWSlider *(*Selector)
963 (const wxRect &sliderRect, const WaveTrack *t, bool captured, wxWindow*),
964 wxDC *dc, const wxRect &rect, const Track *pTrack,
965 wxWindow *pParent,
966 bool captured, bool highlight )
967 {
968 wxRect sliderRect = rect;
969 CommonTrackInfo::GetSliderHorizontalBounds( rect, sliderRect );
970 auto wt = static_cast<const WaveTrack*>( pTrack );
971 Selector( sliderRect, wt, captured, pParent )->OnPaint(*dc, highlight);
972 }
973
974 void PanSliderDrawFunction
975 ( TrackPanelDrawingContext &context,
976 const wxRect &rect, const Track *pTrack )
977 {
978 auto target = dynamic_cast<PanSliderHandle*>( context.target.get() );
979 auto dc = &context.dc;
980 bool hit = target && target->GetTrack().get() == pTrack;
981 bool captured = hit && target->IsDragging();
982
983 const auto artist = TrackArtist::Get( context );
984 auto pParent = FindProjectFrame( artist->parent->GetProject() );
985
986 SliderDrawFunction(
987 &WaveTrackControls::PanSlider, dc, rect, pTrack,
988 pParent, captured, hit);
989 }
990
991 void VolumeSliderDrawFunction
992 ( TrackPanelDrawingContext &context,
993 const wxRect &rect, const Track *pTrack )
994 {
995 auto target = dynamic_cast<VolumeSliderHandle*>( context.target.get() );
996 auto dc = &context.dc;
997 bool hit = target && target->GetTrack().get() == pTrack;
998 if( hit )
999 hit=hit;
1000 bool captured = hit && target->IsDragging();
1001
1002 const auto artist = TrackArtist::Get( context );
1003 auto pParent = FindProjectFrame( artist->parent->GetProject() );
1004
1005 SliderDrawFunction(
1006 &WaveTrackControls::VolumeSlider, dc, rect, pTrack,
1007 pParent, captured, hit);
1008 }
1009
1010
1011 }
1012
1013 using TCPLine = TrackInfo::TCPLine;
1014
1015 static const struct WaveTrackTCPLines
1016 : TCPLines { WaveTrackTCPLines() {
1017 (TCPLines&)*this =
1018 PlayableTrackControls::StaticWaveTCPLines();
1019 insert( end(), {
1020
1021 { TCPLine::kItemVolume, kTrackInfoSliderHeight, kTrackInfoSliderExtra,
1022 VolumeSliderDrawFunction },
1023 { TCPLine::kItemPan, kTrackInfoSliderHeight, kTrackInfoSliderExtra,
1024 PanSliderDrawFunction },
1025
1026 } );
1027 } } waveTrackTCPLines;
1028
1029 void WaveTrackControls::GetVolumeRect(const wxRect &rect_, wxRect & dest)
1030 {
1031 const auto rect = wxRect(rect_).Deflate(CommonTrackInfo::Margin);
1032 CommonTrackInfo::GetSliderHorizontalBounds( rect, dest );
1033 const auto results = CalcItemY( waveTrackTCPLines, TCPLine::kItemVolume );
1034 dest.y = rect.y + results.first;
1035 dest.height = results.second;
1036 }
1037
1038 void WaveTrackControls::GetPanRect(const wxRect &rect_, wxRect & dest)
1039 {
1040 const auto rect = wxRect(rect_).Deflate(CommonTrackInfo::Margin);
1041 CommonTrackInfo::GetSliderHorizontalBounds( rect, dest );
1042 const auto results = CalcItemY( waveTrackTCPLines, TCPLine::kItemPan );
1043 dest.y = rect.y + results.first;
1044 dest.height = results.second;
1045 }
1046
1047 unsigned WaveTrackControls::DefaultWaveTrackHeight()
1048 {
1049 return CommonTrackInfo::DefaultTrackHeight( waveTrackTCPLines );
1050 }
1051
1052 const TCPLines &WaveTrackControls::GetTCPLines() const
1053 {
1054 return waveTrackTCPLines;
1055 }
1056
1057 namespace
1058 {
1059 std::unique_ptr<LWSlider>
1060 gVolumeCaptured
1061 , gPanCaptured
1062 , gVolume
1063 , gPan;
1064 }
1065
1066 LWSlider *WaveTrackControls::VolumeSlider(
1067 CellularPanel &panel, const WaveTrack &wt )
1068 {
1069 auto &controls = TrackControls::Get( wt );
1070 const auto rect = panel.FindRect( controls ).Deflate(CommonTrackInfo::Margin);
1071 wxRect sliderRect;
1072 GetVolumeRect( rect, sliderRect );
1073 return VolumeSlider( sliderRect, &wt, false, &panel );
1074 }
1075
1076 LWSlider * WaveTrackControls::VolumeSlider
1077 (const wxRect &sliderRect, const WaveTrack *t, bool captured, wxWindow *pParent)
1078 {
1079 static std::once_flag flag;
1080 std::call_once( flag, []{ ReCreateVolumeSlider({}); });
1081 static auto subscription = theTheme.Subscribe(ReCreateVolumeSlider);
1082
1083 wxPoint pos = sliderRect.GetPosition();
1084 float volume = t ? t->GetVolume() : 1.0;
1085
1086 gVolume->Move(pos);
1087 gVolume->Set(volume);
1088 gVolumeCaptured->Move(pos);
1089 gVolumeCaptured->Set(volume);
1090
1091 auto slider = (captured ? gVolumeCaptured : gVolume).get();
1092 slider->SetParent( pParent );
1093 return slider;
1094 }
1095
1096 void WaveTrackControls::ReCreateVolumeSlider(ThemeChangeMessage message)
1097 {
1098 if (message.appearance)
1099 return;
1100
1101 const auto sliderRect = wxRect(0, 0, kTrackInfoSliderWidth, kTrackInfoSliderHeight);
1102
1103 float defPos = 1.0;
1104 /* i18n-hint: Title of the Volume slider, used to adjust the volume */
1105 gVolume = std::make_unique<LWSlider>(nullptr, XO("Volume"),
1106 wxPoint(sliderRect.x, sliderRect.y),
1107 wxSize(sliderRect.width, sliderRect.height),
1108 DB_SLIDER);
1109 gVolume->SetDefaultValue(defPos);
1110
1111 gVolumeCaptured = std::make_unique<LWSlider>(nullptr, XO("Volume"),
1112 wxPoint(sliderRect.x, sliderRect.y),
1113 wxSize(sliderRect.width, sliderRect.height),
1114 DB_SLIDER);
1115 gVolumeCaptured->SetDefaultValue(defPos);
1116 }
1117
1118 LWSlider *WaveTrackControls::PanSlider(
1119 CellularPanel &panel, const WaveTrack &wt )
1120 {
1121 auto &controls = TrackControls::Get( wt );
1122 auto rect = panel.FindRect( controls );
1123 wxRect sliderRect;
1124 GetPanRect( rect, sliderRect );
1125 return PanSlider( sliderRect, &wt, false, &panel );
1126 }
1127
1128 LWSlider * WaveTrackControls::PanSlider
1129 (const wxRect &sliderRect, const WaveTrack *t, bool captured, wxWindow *pParent)
1130 {
1131 static std::once_flag flag;
1132 std::call_once( flag, []{ ReCreatePanSlider({}); });
1133 static auto subscription = theTheme.Subscribe(ReCreatePanSlider);
1134
1135 wxPoint pos = sliderRect.GetPosition();
1136 float pan = t ? t->GetPan() : 0.0;
1137
1138 gPan->Move(pos);
1139 gPan->Set(pan);
1140 gPanCaptured->Move(pos);
1141 gPanCaptured->Set(pan);
1142
1143 auto slider = (captured ? gPanCaptured : gPan).get();
1144 slider->SetParent( pParent );
1145 return slider;
1146 }
1147
1148 void WaveTrackControls::ReCreatePanSlider(ThemeChangeMessage message)
1149 {
1150 if (message.appearance)
1151 return;
1152
1153 const auto sliderRect = wxRect(0, 0, kTrackInfoSliderWidth, kTrackInfoSliderHeight);
1154
1155 float defPos = 0.0;
1156 /* i18n-hint: Title of the Pan slider, used to move the sound left or right */
1157 gPan = std::make_unique<LWSlider>(nullptr, XO("Pan"),
1158 wxPoint(sliderRect.x, sliderRect.y),
1159 wxSize(sliderRect.width, sliderRect.height),
1160 PAN_SLIDER);
1161 gPan->SetDefaultValue(defPos);
1162
1163 gPanCaptured = std::make_unique<LWSlider>(nullptr, XO("Pan"),
1164 wxPoint(sliderRect.x, sliderRect.y),
1165 wxSize(sliderRect.width, sliderRect.height),
1166 PAN_SLIDER);
1167 gPanCaptured->SetDefaultValue(defPos);
1168 }
1169
1170 using DoGetWaveTrackControls = DoGetControls::Override< WaveTrack >;
1171 DEFINE_ATTACHED_VIRTUAL_OVERRIDE(DoGetWaveTrackControls) {
1172 return [](WaveTrack &track) {
1173 return std::make_shared<WaveTrackControls>( track.SharedPointer() );
1174 };
1175 }
1176
1177 using GetDefaultWaveTrackHeight = GetDefaultTrackHeight::Override<WaveChannel>;
1178 DEFINE_ATTACHED_VIRTUAL_OVERRIDE(GetDefaultWaveTrackHeight) {
1179 return [](WaveChannel &) {
1180 return WaveTrackControls::DefaultWaveTrackHeight();
1181 };
1182 }
1183