Debian Codegraph @

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

raw
1 /**********************************************************************
2
3 Audacity: A Digital Audio Editor
4
5 WaveChannelView.cpp
6
7 Paul Licameli split from TrackPanel.cpp
8
9 **********************************************************************/
10
11 #include "WaveChannelView.h"
12
13 #include <unordered_set>
14
15 #include "CutlineHandle.h"
16
17 #include <numeric>
18 #include <wx/dc.h>
19 #include <wx/graphics.h>
20
21 #include "AColor.h"
22 #include "WaveTrack.h"
23
24 #include "../../../../../images/Cursors.h"
25 #include "AllThemeResources.h"
26
27 #include "../../../../HitTestResult.h"
28 #include "../../../../RefreshCode.h"
29 #include "../../../../TrackArtist.h"
30 #include "../../../../TrackPanel.h"
31 #include "../../../../TrackPanelDrawingContext.h"
32 #include "../../../../TrackPanelMouseEvent.h"
33 #include "../../../../TrackPanelResizeHandle.h"
34 #include "../../../../prefs/TracksPrefs.h"
35 #include "CommandContext.h"
36 #include "PitchAndSpeedDialog.h"
37 #include "ProjectHistory.h"
38 #include "SyncLock.h"
39 #include "TrackFocus.h"
40 #include "ViewInfo.h"
41
42 #include "../../../ui/TimeShiftHandle.h"
43 #include "../../../ui/ButtonHandle.h"
44 #include "../../../ui/CommonTrackInfo.h"
45
46 #include "ClipParameters.h"
47 #include "WaveChannelUtilities.h"
48 #include "WaveTrackAffordanceControls.h"
49 #include "WaveTrackAffordanceHandle.h"
50 #include "WaveClipAdjustBorderHandle.h"
51 #include "WaveClipUIUtilities.h"
52
53 constexpr int kClipDetailedViewMinimumWidth{ 3 };
54
55 using WaveChannelSubViewPtrs = std::vector<std::shared_ptr<WaveChannelSubView>>;
56
57 namespace {
58 struct PlacementArray : ClientData::Cloneable<> {
59 static PlacementArray &Get(Track &track);
60 static const PlacementArray &Get(const Track &track);
61 ~PlacementArray() = default;
62 std::unique_ptr<Cloneable<>> Clone() const {
63 return std::make_unique<PlacementArray>(*this); }
64 WaveChannelSubViewPlacements mPlacements;
65 bool mMultiView{ false };
66 };
67
68 static const ChannelGroup::Attachments::RegisteredFactory
69 key { [](auto &) { return std::make_unique<PlacementArray>(); } };
70
71 // Access for per-track effect list
72 PlacementArray &PlacementArray::Get(Track &track)
73 {
74 return track.Attachments::Get<PlacementArray>(key);
75 }
76
77 const PlacementArray &PlacementArray::Get(const Track &track)
78 {
79 return Get(const_cast<Track &>(track));
80 }
81 }
82
83 WaveChannelSubViewPlacements &WaveChannelView::DoGetPlacements()
84 {
85 auto &waveChannel = *FindWaveChannel();
86 return PlacementArray::Get(waveChannel.GetTrack()).mPlacements;
87 }
88
89 const WaveChannelSubViewPlacements &WaveChannelView::DoGetPlacements() const
90 {
91 return const_cast<WaveChannelView&>(*this).DoGetPlacements();
92 }
93
94 bool &WaveChannelView::DoGetMultiView()
95 {
96 auto &waveTrack = FindWaveChannel()->GetTrack();
97 return PlacementArray::Get(waveTrack).mMultiView;
98 }
99
100 bool WaveChannelView::DoGetMultiView() const
101 {
102 return const_cast<WaveChannelView&>(*this).DoGetMultiView();
103 }
104
105 // Structure that collects and modifies information on sub-view positions
106 // Written with great generality, allowing any number of sub-views
107 struct SubViewAdjuster
108 {
109 enum { HotZoneSize = 5 }; // so many pixels at top and bottom of each subview
110
111 SubViewAdjuster(WaveChannelView &view)
112 : mwView{
113 std::static_pointer_cast<WaveChannelView>(view.shared_from_this()) }
114 {
115 mSubViews = view.GetAllSubViews();
116 mOrigPlacements = mNewPlacements = view.SavePlacements();
117 FindPermutation();
118 }
119
120 void FindPermutation()
121 {
122 // Find a certain sort of the sub-views
123 auto size = mOrigPlacements.size();
124 wxASSERT( mSubViews.size() == size );
125 mPermutation.resize( size );
126 const auto begin = mPermutation.begin(), end = mPermutation.end();
127 std::iota( begin, end, 0 );
128 static auto invisible = [](const WaveChannelSubViewPlacement &placement) {
129 return placement.index < 0 || placement.fraction <= 0;
130 };
131 const auto comp = [this]( size_t ii, size_t jj ){
132 auto &pi = mOrigPlacements[ii];
133 bool iInvisible = invisible( pi );
134
135 auto &pj = mOrigPlacements[jj];
136 bool jInvisible = invisible( pj );
137
138 // Sort the invisibles to the front, rest by index
139 if ( iInvisible != jInvisible )
140 return iInvisible;
141 else if ( !iInvisible )
142 return pi.index < pj.index;
143 else
144 // Minor sort among the invisible views by their type
145 return mSubViews[ii]->SubViewType() < mSubViews[jj]->SubViewType();
146 };
147 std::sort( begin, end, comp );
148 // Find the start of visible sub-views
149 auto first = std::find_if( begin, end, [this](size_t ii){
150 return !invisible( mOrigPlacements[ii] );
151 } );
152 mFirstSubView = first - begin;
153 }
154
155 size_t NVisible() const
156 { return mPermutation.size() - mFirstSubView; }
157
158 bool ModifyPermutation( bool top )
159 {
160 bool rotated = false;
161 const auto pBegin = mPermutation.begin(), pEnd = mPermutation.end();
162 auto pFirst = pBegin + mFirstSubView;
163 if ( mFirstSubView > 0 ) {
164 // In case of dragging the top edge of the topmost view, or the
165 // bottom edge of the bottommost, decide which of the invisible
166 // views can become visible, and reassign the sequence.
167 // For definiteness, that choice depends on the subview type numbers;
168 // see the sorting criteria above.
169 --mFirstSubView;
170 --pFirst;
171 if ( top ) {
172 // If you drag down the top, the greatest-numbered invisible
173 // subview type will appear there.
174 mNewPlacements[ *pFirst ].fraction = 0;
175 }
176 else {
177 // If you drag up the bottom, let the least-numbered invisible
178 // subview type appear there.
179 mNewPlacements[ *pBegin ].fraction = 0;
180 std::rotate( pBegin, pBegin + 1, pEnd );
181 rotated = true;
182 }
183 }
184 // Reassign index numbers to all sub-views and 0 fraction to invisibles
185 for ( auto pIter = pBegin; pIter != pFirst; ++pIter ) {
186 auto &placement = mNewPlacements[ *pIter ];
187 placement.index = -1;
188 placement.fraction = 0;
189 }
190 size_t index = 0;
191 for ( auto pIter = pFirst; pIter != pEnd; ++pIter )
192 mNewPlacements[ *pIter ].index = index++;
193 return rotated;
194 }
195
196 size_t FindIndex(WaveChannelSubView &subView) const
197 {
198 const auto begin = mPermutation.begin(), end = mPermutation.end();
199 auto iter = std::find_if( begin, end, [&](size_t ii){
200 return mSubViews[ ii ].get() == &subView;
201 } );
202 return iter - begin;
203 }
204
205 std::pair< size_t, bool >
206 HitTest(WaveChannelSubView &subView,
207 wxCoord yy, wxCoord top, wxCoord height)
208 {
209 const auto index = FindIndex( subView );
210 auto size = mPermutation.size();
211 if ( index < (int)size ) {
212 yy -= top;
213 if ( yy >= 0 && yy < HotZoneSize && index > 0 )
214 return { index, true }; // top hit
215 if ( yy < height && yy >= height - HotZoneSize &&
216 // Have not yet called ModifyPermutation; dragging bottom of
217 // bottommost view allowed only if at least one view is invisible
218 ( index < (int)size - 1 || mFirstSubView > 0 ) )
219 return { index, false }; // bottom hit
220 }
221 return { size, false }; // not hit
222 }
223
224 std::vector<wxCoord> ComputeHeights( wxCoord totalHeight )
225 {
226 // Compute integer-valued heights
227 float total = 0;
228 for (const auto index : mPermutation ) {
229 const auto &placement = mOrigPlacements[ index ];
230 total += std::max( 0.f, placement.fraction );
231 }
232 float partial = 0;
233 wxCoord lastCoord = 0;
234 std::vector<wxCoord> result;
235 for (const auto index : mPermutation ) {
236 const auto &placement = mOrigPlacements[ index ];
237 auto fraction = std::max( 0.f, placement.fraction );
238 wxCoord coord = ( (partial + fraction ) / total ) * totalHeight;
239 auto height = coord - lastCoord;
240 result.emplace_back( height );
241 mNewPlacements[ index ].fraction = height;
242 lastCoord = coord;
243 partial += fraction;
244 }
245 return result;
246 }
247
248 void UpdateViews( bool rollback )
249 {
250 auto pView = mwView.lock();
251 if ( pView ) {
252 WaveChannelView::Get(*pView->FindWaveChannel()).RestorePlacements(
253 rollback ? mOrigPlacements : mNewPlacements);
254 }
255 }
256
257 std::weak_ptr<WaveChannelView> mwView;
258 WaveChannelSubViewPtrs mSubViews;
259 WaveChannelSubViewPlacements mOrigPlacements, mNewPlacements;
260 // Array mapping ordinal into the placement and subview arrays
261 std::vector< size_t > mPermutation;
262 // index into mPermutation
263 size_t mFirstSubView{};
264 };
265
266 class SubViewAdjustHandle : public UIHandle
267 {
268 public:
269 enum { MinHeight = SubViewAdjuster::HotZoneSize };
270
271 static UIHandlePtr HitTest(std::weak_ptr<SubViewAdjustHandle> &holder,
272 WaveChannelView &view,
273 WaveChannelSubView &subView,
274 const TrackPanelMouseState &state)
275 {
276 if ( !view.GetMultiView() )
277 return {};
278
279 SubViewAdjuster adjuster{ view };
280 auto hit = adjuster.HitTest( subView,
281 state.state.GetY(), state.rect.GetTop(), state.rect.GetHeight() );
282 auto index = hit.first;
283
284 if ( index < adjuster.mPermutation.size() ) {
285 auto result = std::make_shared< SubViewAdjustHandle >(
286 std::move( adjuster ), index, view.GetLastHeight(), hit.second
287 );
288 result = AssignUIHandlePtr( holder, result );
289 return result;
290 }
291 else
292 return {};
293 }
294
295 SubViewAdjustHandle(
296 SubViewAdjuster &&adjuster, size_t subViewIndex,
297 wxCoord viewHeight, bool top )
298 : mAdjuster{ std::move( adjuster ) }
299 , mMySubView{ subViewIndex }
300 , mViewHeight{ viewHeight }
301 , mTop{ top }
302 {
303 if ( mAdjuster.ModifyPermutation( top ) )
304 --mMySubView;
305 }
306
307 std::shared_ptr<const Track> FindTrack() const override
308 {
309 auto pView = mAdjuster.mwView.lock();
310 if (pView)
311 return TrackFromChannel(pView->FindChannel());
312 return nullptr;
313 }
314
315 Result Click(
316 const TrackPanelMouseEvent &event, AudacityProject *pProject ) override
317 {
318 using namespace RefreshCode;
319 const auto &permutation = mAdjuster.mPermutation;
320 const auto size = permutation.size();
321 if ( mMySubView >= size )
322 return Cancelled;
323
324 if (event.event.LeftDClick()) {
325 for ( auto &placement : mAdjuster.mNewPlacements ) {
326 if ( placement.index >= 0 )
327 placement.fraction = 1.0f;
328 else
329 placement.fraction = 0.0f;
330 }
331 mAdjuster.UpdateViews( false );
332 ProjectHistory::Get( *pProject ).ModifyState( false );
333
334 // Do not start a drag
335 return Cancelled | RefreshAll;
336 }
337
338 const auto &rect = event.rect;
339 const auto height = rect.GetHeight();
340 mOrigHeight = height;
341
342 mOrigHeights = mAdjuster.ComputeHeights( mViewHeight );
343
344 // Find the total height of the sub-views that may resize
345 mTotalHeight = 0;
346 auto index = ( mTop ? mAdjuster.mFirstSubView : mMySubView );
347 const auto end = ( mTop ? mMySubView + 1 : permutation.size() );
348 for (; index != end; ++index)
349 mTotalHeight += mOrigHeights[ index ];
350
351 wxASSERT( height == mOrigHeights[ mMySubView ] );
352
353 // Compute the maximum and minimum Y coordinates for drag effect
354 if ( mTop ) {
355 mOrigY = rect.GetTop();
356 mYMax = rect.GetBottom();
357 mYMin = mYMax - mTotalHeight + 1;
358 }
359 else {
360 mOrigY = rect.GetBottom();
361 mYMin = rect.GetTop();
362 mYMax = mYMin + mTotalHeight - 1;
363 }
364
365 return RefreshNone;
366 }
367
368 Result Drag( const TrackPanelMouseEvent &event, AudacityProject * ) override
369 {
370 using namespace RefreshCode;
371 auto pView = mAdjuster.mwView.lock();
372 if ( !pView )
373 return Cancelled;
374
375 // Find new height for the dragged sub-view
376 auto newY = std::max( mYMin, std::min( mYMax, event.event.GetY() ) );
377 const auto delta = newY - mOrigY;
378 wxCoord newHeight = mTop
379 ? mOrigHeight - delta
380 : mOrigHeight + delta
381 ;
382 wxASSERT( newHeight >= 0 && newHeight <= mTotalHeight );
383 if ( newHeight < MinHeight )
384 // Snap the dragged sub-view to nothing
385 newHeight = 0;
386
387 // Reassign height for the dragged sub-view
388 auto &myPlacement =
389 mAdjuster.mNewPlacements[ mAdjuster.mPermutation[ mMySubView ] ];
390 myPlacement.fraction = newHeight;
391
392 // Grow or shrink other sub-views
393 auto excess = newHeight - mOrigHeight; // maybe negative
394 const auto adjustHeight = [&](size_t ii) {
395 if (excess == 0)
396 return true;
397
398 const auto oldFraction = mOrigHeights[ ii ];
399
400 auto index = mAdjuster.mPermutation[ ii ];
401 auto &placement = mAdjuster.mNewPlacements[ index ];
402 auto &fraction = placement.fraction;
403
404 if (excess > oldFraction) {
405 excess -= oldFraction, fraction = 0;
406 return false;
407 }
408 else {
409 auto newFraction = oldFraction - excess;
410 if ( newFraction < MinHeight ) {
411 // This snaps very short sub-views to nothing
412 myPlacement.fraction += newFraction;
413 fraction = 0;
414 }
415 else
416 fraction = newFraction;
417 return true;
418 }
419 };
420 if ( mTop ) {
421 for ( size_t ii = mMySubView; ii > 0; ) {
422 --ii;
423 if ( adjustHeight( ii ) )
424 break;
425 }
426 }
427 else {
428 for ( size_t ii = mMySubView + 1, size = mAdjuster.mPermutation.size();
429 ii < size; ++ii
430 ) {
431 if ( adjustHeight( ii ) )
432 break;
433 }
434 }
435
436 // Save adjustment to the track and request a redraw
437 mAdjuster.UpdateViews( false );
438 return RefreshAll;
439 }
440
441 HitTestPreview Preview(
442 const TrackPanelMouseState &state, AudacityProject * ) override
443 {
444 static auto resizeCursor =
445 ::MakeCursor(wxCURSOR_ARROW, SubViewsCursorXpm, 16, 16);
446 return {
447 XO(
448 "Click and drag to adjust sizes of sub-views, double-click to split evenly"),
449 &*resizeCursor
450 };
451 }
452
453 Result Release(
454 const TrackPanelMouseEvent &event, AudacityProject *pProject,
455 wxWindow *pParent) override
456 {
457 ProjectHistory::Get( *pProject ).ModifyState( false );
458 return RefreshCode::RefreshNone;
459 }
460
461 Result Cancel( AudacityProject * ) override
462 {
463 mAdjuster.UpdateViews( true );
464 return RefreshCode::RefreshAll;
465 }
466
467 private:
468
469 SubViewAdjuster mAdjuster;
470 std::vector<wxCoord> mOrigHeights;
471
472 // An index into mAdjuster.mPermutation
473 size_t mMySubView{};
474
475 wxCoord mYMin{}, mYMax{};
476 wxCoord mViewHeight{}; // Total height of all sub-views
477 wxCoord mTotalHeight{}; // Total height of adjusting sub-views only
478 wxCoord mOrigHeight{};
479 wxCoord mOrigY{};
480
481 // Whether we drag the top or the bottom of the sub-view
482 bool mTop{};
483 };
484
485 class SubViewRearrangeHandle : public UIHandle
486 {
487 public:
488 // Make it somewhat wider than the close button
489 enum { HotZoneWidth = 3 * kTrackInfoBtnSize / 2 };
490
491 static UIHandlePtr HitTest(std::weak_ptr<SubViewRearrangeHandle> &holder,
492 WaveChannelView &view, WaveChannelSubView &subView,
493 const TrackPanelMouseState &state)
494 {
495 if ( !view.GetMultiView() )
496 return {};
497
498 SubViewAdjuster adjuster{ view };
499 if ( adjuster.NVisible() < 2 )
500 return {};
501
502 auto relX = state.state.GetX() - state.rect.GetLeft();
503 if ( relX >= HotZoneWidth )
504 return {};
505
506 auto index = adjuster.FindIndex( subView );
507
508 // Hit on the rearrange cursor only in the top and bottom thirds of
509 // sub-view height, leaving the rest free to hit the selection cursor
510 // first.
511 // And also exclude the top third of the topmost sub-view and bottom
512 // third of bottommost.
513 auto relY = state.state.GetY() - state.rect.GetTop();
514 auto height = state.rect.GetHeight();
515 bool hit =
516 ( ( 3 * relY < height ) && index > 0 ) // top hit
517 ||
518 ( ( 3 * relY > 2 * height ) &&
519 index < adjuster.mPermutation.size() - 1 ) // bottom
520 ;
521 if ( ! hit )
522 return {};
523
524 auto result = std::make_shared< SubViewRearrangeHandle >(
525 std::move( adjuster ),
526 index, view.GetLastHeight()
527 );
528 result = AssignUIHandlePtr( holder, result );
529 return result;
530 }
531
532 SubViewRearrangeHandle(
533 SubViewAdjuster &&adjuster, size_t subViewIndex,
534 wxCoord viewHeight )
535 : mAdjuster{ std::move( adjuster ) }
536 , mMySubView{ subViewIndex }
537 , mViewHeight{ viewHeight }
538 {
539 }
540
541 std::shared_ptr<const Track> FindTrack() const override
542 {
543 auto pView = mAdjuster.mwView.lock();
544 if (pView)
545 return TrackFromChannel(pView->FindChannel());
546 return nullptr;
547 }
548
549 Result Click(
550 const TrackPanelMouseEvent &event, AudacityProject *pProject ) override
551 {
552 using namespace RefreshCode;
553 const auto &permutation = mAdjuster.mPermutation;
554 const auto size = permutation.size();
555 if ( mMySubView >= size )
556 return Cancelled;
557
558 mHeights = mAdjuster.ComputeHeights( mViewHeight );
559
560 // Find y coordinate of first sub-view
561 wxCoord heightAbove = 0;
562 for (auto index = mAdjuster.mFirstSubView;
563 index != mMySubView; ++index)
564 heightAbove += mHeights[ index ];
565 mTopY = event.rect.GetTop() - heightAbove;
566
567 return RefreshNone;
568 }
569
570 bool Clicked() const { return !mHeights.empty(); }
571
572 enum DragChoice_t{ Upward, Downward, Neutral };
573
574 DragChoice_t DragChoice( const TrackPanelMouseEvent &event ) const
575 {
576 // Disregard x coordinate -- so the mouse need not be in any sub-view,
577 // just in the correct range of y coordinates
578 auto yy = event.event.GetY();
579 auto coord = mTopY;
580 size_t ii = mAdjuster.mFirstSubView;
581 if ( yy < mTopY )
582 return ( mMySubView == ii ) ? Neutral : Upward;
583
584 for ( auto nn = mHeights.size(); ii < nn; ++ii ) {
585 const auto height = mHeights[ ii ];
586 coord += height;
587 if ( yy < coord )
588 break;
589 }
590
591 if ( ii < mMySubView ) {
592 if ( yy < coord - mHeights[ ii ] + mHeights[ mMySubView ] )
593 return Upward;
594 }
595
596 if ( ii > mMySubView ) {
597 if( mMySubView < mHeights.size() - 1 &&
598 yy >= coord - mHeights[ mMySubView ] )
599 return Downward;
600 }
601
602 return Neutral;
603 }
604
605 Result Drag( const TrackPanelMouseEvent &event, AudacityProject * ) override
606 {
607 using namespace RefreshCode;
608 auto pView = mAdjuster.mwView.lock();
609 if ( !pView )
610 return Cancelled;
611
612 switch( DragChoice( event ) ) {
613 case Upward:
614 {
615 std::swap( mHeights[ mMySubView ], mHeights[ mMySubView - 1 ] );
616 std::swap(
617 mAdjuster.mNewPlacements[ mMySubView ].index,
618 mAdjuster.mNewPlacements[ mMySubView - 1 ].index
619 );
620 --mMySubView;
621 break;
622 }
623 case Downward:
624 {
625 std::swap( mHeights[ mMySubView ], mHeights[ mMySubView + 1 ] );
626 std::swap(
627 mAdjuster.mNewPlacements[ mMySubView ].index,
628 mAdjuster.mNewPlacements[ mMySubView + 1 ].index
629 );
630 ++mMySubView;
631 break;
632 }
633 default:
634 return RefreshNone;
635 }
636
637 // Save adjustment to the track and request a redraw
638 mAdjuster.UpdateViews( false );
639 return RefreshAll;
640 }
641
642 HitTestPreview Preview(
643 const TrackPanelMouseState &state, AudacityProject * ) override
644 {
645 static auto hoverCursor =
646 ::MakeCursor(wxCURSOR_HAND, RearrangeCursorXpm, 16, 16);
647 static auto clickedCursor =
648 ::MakeCursor(wxCURSOR_HAND, RearrangingCursorXpm, 16, 16);
649 return {
650 XO("Click and drag to rearrange sub-views"),
651 Clicked() ? &*clickedCursor : &*hoverCursor,
652 XO("Rearrange sub-views")
653 };
654 }
655
656 Result Release(
657 const TrackPanelMouseEvent &event, AudacityProject *pProject,
658 wxWindow *pParent) override
659 {
660 ProjectHistory::Get( *pProject ).ModifyState( false );
661 return RefreshCode::RefreshNone;
662 }
663
664 Result Cancel( AudacityProject * ) override
665 {
666 mAdjuster.UpdateViews( true );
667 return RefreshCode::RefreshAll;
668 }
669
670 private:
671
672 SubViewAdjuster mAdjuster;
673 std::vector<wxCoord> mHeights;
674 wxCoord mTopY;
675
676 // An index into mAdjuster.mPermutation
677 size_t mMySubView{};
678
679 wxCoord mViewHeight{}; // Total height of all sub-views
680 };
681
682 class SubViewCloseHandle : public ButtonHandle
683 {
684 static wxRect GetButtonRect( const wxRect &rect )
685 {
686 return {
687 rect.GetLeft(),
688 rect.GetTop(),
689 kTrackInfoBtnSize,
690 kTrackInfoBtnSize
691 };
692 }
693
694 public:
695 static UIHandlePtr HitTest(std::weak_ptr<SubViewCloseHandle> &holder,
696 WaveChannelView &view, WaveChannelSubView &subView,
697 const TrackPanelMouseState &state)
698 {
699 SubViewAdjuster adjuster{ view };
700 if ( adjuster.NVisible() < 2 )
701 return {};
702
703 const auto rect = GetButtonRect( state.rect );
704 if ( !rect.Contains( state.state.GetPosition() ) )
705 return {};
706 auto index = adjuster.FindIndex( subView );
707 auto result = std::make_shared<SubViewCloseHandle>(
708 std::move(adjuster), index, view.FindChannel(), rect);
709 result = AssignUIHandlePtr( holder, result );
710 return result;
711 }
712
713 SubViewCloseHandle(
714 SubViewAdjuster &&adjuster, size_t index,
715 const std::shared_ptr<Channel> &pChannel, const wxRect &rect )
716 : ButtonHandle{ static_cast<Track&>(pChannel->GetChannelGroup())
717 .SharedPointer(),
718 rect }
719 , mpChannel{ pChannel }
720 , mAdjuster{ std::move( adjuster ) }
721 , mMySubView{ index }
722 {
723 }
724
725 Result CommitChanges(
726 const wxMouseEvent &event, AudacityProject *pProject, wxWindow *pParent)
727 override
728 {
729 ProjectHistory::Get( *pProject ).ModifyState( false );
730 auto &myPlacement =
731 mAdjuster.mNewPlacements[ mAdjuster.mPermutation[ mMySubView ] ];
732 myPlacement.fraction = 0;
733 mAdjuster.UpdateViews( false );
734 return RefreshCode::RefreshAll;
735 }
736
737 TranslatableString Tip(
738 const wxMouseState &state, AudacityProject &project) const override
739 {
740 return XO("Close sub-view");
741 }
742
743 // TrackPanelDrawable implementation
744 void Draw(
745 TrackPanelDrawingContext &context, const wxRect &rect, unsigned iPass )
746 override
747 {
748 if (iPass == TrackArtist::PassMargins) { // after PassTracks
749 CommonTrackInfo::DrawCloseButton(
750 context, GetButtonRect(rect), mpChannel.lock().get(), this);
751 }
752 }
753
754 private:
755 std::weak_ptr<Channel> mpChannel;
756 SubViewAdjuster mAdjuster;
757 size_t mMySubView{};
758 };
759
760 std::pair<
761 bool, // if true, hit-testing is finished
762 std::vector<UIHandlePtr>
763 > WaveChannelSubView::DoDetailedHitTest(
764 const TrackPanelMouseState &state,
765 const AudacityProject *pProject, int currentTool, bool bMultiTool,
766 const std::shared_ptr<WaveChannel> &wc)
767 {
768 const auto waveTrack = wc->GetTrack().SharedPointer<WaveTrack>();
769 auto results = WaveChannelView::DoDetailedHitTest(
770 state, pProject, currentTool, bMultiTool, wc, *this);
771 if (results.first)
772 return results;
773
774 auto pWaveChannelView = mwWaveChannelView.lock();
775 if ( pWaveChannelView && !state.state.HasModifiers() ) {
776 if ( auto pHandle = SubViewCloseHandle::HitTest(
777 mCloseHandle,
778 *pWaveChannelView, *this, state ) )
779 results.second.push_back( pHandle );
780
781 auto &&channels = waveTrack->Channels();
782 if(channels.size() > 1) {
783 // Only one cell is tested and we need to know
784 // which one and it's relative location to the border.
785 auto subviews = pWaveChannelView->GetSubViews();
786 auto currentSubview = std::find_if(subviews.begin(), subviews.end(),
787 [self = shared_from_this()](const auto& p){
788 return self == p.second;
789 });
790 if (currentSubview != subviews.end())
791 {
792 auto currentSubviewIndex = std::distance(subviews.begin(), currentSubview);
793
794 const auto py = state.state.GetY();
795 const auto topBorderHit = std::abs(py - state.rect.GetTop())
796 <= WaveChannelView::kChannelSeparatorThickness / 2;
797 const auto bottomBorderHit = std::abs(py - state.rect.GetBottom())
798 <= WaveChannelView::kChannelSeparatorThickness / 2;
799
800 auto it = channels.find(wc);
801 auto currentChannelIndex = std::distance(channels.begin(), it);
802
803 if (//for not-last-view check the bottom border hit
804 ((currentChannelIndex != channels.size() - 1)
805 && (currentSubviewIndex == static_cast<int>(subviews.size()) - 1)
806 && bottomBorderHit)
807 ||
808 //or for not-first-view check the top border hit
809 ((currentChannelIndex != 0) && currentSubviewIndex == 0 && topBorderHit))
810 {
811 //depending on which border hit test succeeded on we
812 //need to choose a proper target for resizing
813 if (!bottomBorderHit)
814 --it;
815 auto result = std::make_shared<TrackPanelResizeHandle>(*it, py);
816 result = AssignUIHandlePtr(mResizeHandle, result);
817 results.second.push_back(result);
818 }
819 }
820 }
821
822 if ( auto pHandle = SubViewAdjustHandle::HitTest(
823 mAdjustHandle,
824 *pWaveChannelView, *this, state ) )
825 results.second.push_back( pHandle );
826 if ( auto pHandle = SubViewRearrangeHandle::HitTest(
827 mRearrangeHandle,
828 *pWaveChannelView, *this, state ) )
829 results.second.push_back( pHandle );
830 }
831 if( pWaveChannelView )
832 {
833 if (auto pHandle = WaveClipAdjustBorderHandle::HitTest(
834 mClipBorderAdjustHandle,
835 *pWaveChannelView, pProject, state))
836 results.second.push_back(pHandle);
837 }
838 if (auto result = CutlineHandle::HitTest(
839 mCutlineHandle, state.state, state.rect, pProject, waveTrack))
840 // This overriding test applies in all tools
841 results.second.push_back(result);
842
843 return results;
844 }
845
846
847 void WaveChannelSubView::DrawBoldBoundaries(
848 TrackPanelDrawingContext &context, const WaveChannel &channel,
849 const wxRect &rect)
850 {
851 auto &dc = context.dc;
852 const auto artist = TrackArtist::Get( context );
853
854 const auto &zoomInfo = *artist->pZoomInfo;
855
856 #ifdef EXPERIMENTAL_TRACK_PANEL_HIGHLIGHTING
857 auto target2 = dynamic_cast<CutlineHandle*>(context.target.get());
858 #endif
859 // x coordinates for bold lines will be the same across channels
860 for (const auto loc : FindWaveTrackLocations(channel.GetTrack())) {
861 bool highlightLoc = false;
862 #ifdef EXPERIMENTAL_TRACK_PANEL_HIGHLIGHTING
863 highlightLoc =
864 target2 && target2->GetTrack().get() == &channel &&
865 target2->GetLocation() == loc;
866 #endif
867 const int xx = zoomInfo.TimeToPosition(loc.pos);
868 if (xx >= 0 && xx < rect.width) {
869 dc.SetPen( highlightLoc ? AColor::uglyPen : *wxGREY_PEN );
870 AColor::Line(dc, (int) (rect.x + xx - 1), rect.y, (int) (rect.x + xx - 1), rect.y + rect.height);
871 dc.SetPen( highlightLoc ? AColor::uglyPen : *wxRED_PEN );
872 AColor::Line(dc, (int) (rect.x + xx), rect.y, (int) (rect.x + xx), rect.y + rect.height);
873 dc.SetPen( highlightLoc ? AColor::uglyPen : *wxGREY_PEN );
874 AColor::Line(dc, (int) (rect.x + xx + 1), rect.y, (int) (rect.x + xx + 1), rect.y + rect.height);
875 }
876 }
877 }
878
879 std::weak_ptr<WaveChannelView> WaveChannelSubView::GetWaveChannelView() const
880 {
881 return mwWaveChannelView;
882 }
883
884 auto WaveChannelSubView::GetMenuItems(
885 const wxRect &rect, const wxPoint *pPosition, AudacityProject *pProject)
886 -> std::vector<MenuItem>
887 {
888 auto pChannel = FindWaveChannel();
889 if (pChannel != nullptr && pPosition != nullptr)
890 {
891 auto &track = pChannel->GetTrack();
892 const auto &viewInfo = ViewInfo::Get(*pProject);
893 const auto t = viewInfo.PositionToTime(pPosition->x, rect.x);
894 if (
895 (track.IsSelected() && t > viewInfo.selectedRegion.t0() &&
896 t < viewInfo.selectedRegion.t1() &&
897 !track
898 .GetSortedClipsIntersecting(
899 viewInfo.selectedRegion.t0(), viewInfo.selectedRegion.t1())
900 .empty()) ||
901 WaveChannelUtilities::GetClipAtTime(**track.Channels().begin(), t))
902 {
903 return WaveClipUIUtilities::GetWaveClipMenuItems();
904 }
905 }
906 return {
907 { L"Paste", XO("Paste") },
908 {},
909 { L"TrackMute", XO("Mute/Unmute Track") },
910 };
911 }
912
913 WaveChannelView &WaveChannelView::Get(WaveChannel &channel)
914 {
915 return static_cast<WaveChannelView&>(ChannelView::Get(channel));
916 }
917
918 const WaveChannelView &WaveChannelView::Get(const WaveChannel &channel)
919 {
920 return Get(const_cast<WaveChannel&>(channel));
921 }
922
923 WaveChannelView *WaveChannelView::Find(WaveChannel *pChannel)
924 {
925 return static_cast<WaveChannelView*>(ChannelView::Find(pChannel));
926 }
927
928 const WaveChannelView *WaveChannelView::Find(const WaveChannel *pChannel)
929 {
930 return Find(const_cast<WaveChannel*>(pChannel));
931 }
932
933 WaveChannelView &WaveChannelView::GetFirst(WaveTrack &wt)
934 {
935 assert(wt.Channels().size() > 0);
936 return Get(**wt.Channels().begin());
937 }
938
939 const WaveChannelView &WaveChannelView::GetFirst(const WaveTrack &wt)
940 {
941 return GetFirst(const_cast<WaveTrack&>(wt));
942 }
943
944 WaveChannelView *WaveChannelView::FindFirst(WaveTrack *pWt)
945 {
946 return pWt ? &GetFirst(*pWt): nullptr;
947 }
948
949 const WaveChannelView *WaveChannelView::FindFirst(const WaveTrack *pWt)
950 {
951 return pWt ? &GetFirst(*pWt): nullptr;
952 }
953
954 WaveChannelSubView::WaveChannelSubView(WaveChannelView &waveChannelView)
955 : CommonChannelView{ waveChannelView.FindChannel() }
956 {
957 mwWaveChannelView = std::static_pointer_cast<WaveChannelView>(
958 waveChannelView.shared_from_this() );
959 }
960
961 std::shared_ptr<WaveChannel> WaveChannelSubView::FindWaveChannel()
962 {
963 return FindChannel<WaveChannel>();
964 }
965
966 void WaveChannelSubView::CopyToSubView(WaveChannelSubView *destSubView) const {
967
968 }
969
970 WaveChannelView::~WaveChannelView()
971 {
972 }
973
974 std::shared_ptr<WaveChannel> WaveChannelView::FindWaveChannel()
975 {
976 return FindChannel<WaveChannel>();
977 }
978
979 void WaveChannelView::CopyTo(Track &track, size_t iChannel) const
980 {
981 ChannelView::CopyTo(track, iChannel);
982 auto &other = ChannelView::Get(*track.GetChannel(0));
983 if (const auto pOther = dynamic_cast<WaveChannelView*>(&other)) {
984 // only these fields are important to preserve in undo/redo history
985 pOther->RestorePlacements( SavePlacements() );
986 pOther->DoGetMultiView() = DoGetMultiView();
987
988 auto srcSubViewsPtrs =
989 const_cast<WaveChannelView*>(this)->GetAllSubViews();
990 auto destSubViewsPtrs =
991 const_cast<WaveChannelView*>(pOther)->GetAllSubViews();
992 wxASSERT(srcSubViewsPtrs.size() == destSubViewsPtrs.size());
993
994 for(auto i = 0; i != srcSubViewsPtrs.size(); i++){
995 srcSubViewsPtrs[i]->CopyToSubView(destSubViewsPtrs[i].get());
996 }
997 }
998 }
999
1000 std::vector<UIHandlePtr> WaveChannelView::DetailedHitTest(
1001 const TrackPanelMouseState &st,
1002 const AudacityProject *pProject, int currentTool, bool bMultiTool)
1003 {
1004 // should not come here any more, delegation to sub-view instead
1005 wxASSERT( false );
1006 return {};
1007 }
1008
1009 std::pair< bool, std::vector<UIHandlePtr> >
1010 WaveChannelView::DoDetailedHitTest(
1011 const TrackPanelMouseState &st,
1012 const AudacityProject *pProject, int currentTool, bool bMultiTool,
1013 const std::shared_ptr<WaveChannel> &pChannel,
1014 CommonChannelView &view)
1015 {
1016 // common hit-testing for different sub-view types, to help implement their
1017 // DetailedHitTest()
1018
1019 // This is the only override of Track::DetailedHitTest that still
1020 // depends on the state of the Tools toolbar.
1021 // If that toolbar were eliminated, this could simplify to a sequence of
1022 // hit test routines describable by a table.
1023
1024 std::vector<UIHandlePtr> results;
1025
1026 const auto& viewInfo = ViewInfo::Get(*pProject);
1027 const auto pTrack = pChannel->GetTrack().SharedPointer<WaveTrack>();
1028
1029 for (const auto &clip : pChannel->Intervals())
1030 {
1031 if (!WaveChannelView::ClipDetailsVisible(*clip, viewInfo, st.rect)
1032 && HitTest(*clip, viewInfo, st.rect, st.state.GetPosition()))
1033 {
1034 auto &waveChannelView = WaveChannelView::Get(*pChannel);
1035 results.push_back(
1036 AssignUIHandlePtr(
1037 waveChannelView.mAffordanceHandle,
1038 std::make_shared<WaveTrackAffordanceHandle>(pTrack, clip)
1039 )
1040 );
1041 }
1042 }
1043
1044 if (bMultiTool && st.state.CmdDown()) {
1045 // Ctrl modifier key in multi-tool overrides everything else
1046 // (But this does not do the time shift constrained to the vertical only,
1047 // which is what happens when you hold Ctrl in the Time Shift tool mode)
1048 auto result = TimeShiftHandle::HitAnywhere(view.mTimeShiftHandle,
1049 pTrack, false);
1050 if (result)
1051 results.push_back(result);
1052 return { true, results };
1053 }
1054
1055 return { false, results };
1056 }
1057
1058 auto WaveChannelView::GetDisplays() const
1059 -> std::vector<WaveChannelSubView::Type>
1060 {
1061 BuildSubViews();
1062
1063 // Collect the display types of visible views and sort them by position
1064 using Pair = std::pair<int, WaveChannelSubView::Type>;
1065 std::vector< Pair > pairs;
1066 size_t ii = 0;
1067 const auto &placements = DoGetPlacements();
1068 WaveChannelSubViews::ForEach([&](const WaveChannelSubView &subView) {
1069 auto &placement = placements[ii];
1070 if (placement.fraction > 0)
1071 pairs.emplace_back(placement.index, subView.SubViewType());
1072 ++ii;
1073 } );
1074 std::sort( pairs.begin(), pairs.end() );
1075 std::vector<WaveChannelSubView::Type> results;
1076 for (const auto &pair : pairs)
1077 results.push_back(pair.second);
1078 return results;
1079 }
1080
1081 void WaveChannelView::SetDisplay(Display display, bool exclusive)
1082 {
1083 BuildSubViews();
1084 DoSetDisplay( display, exclusive );
1085 }
1086
1087 bool WaveChannelView::ToggleSubView(Display display)
1088 {
1089 size_t ii = 0;
1090 size_t found = 0;
1091 if (WaveChannelSubViews::FindIf([&](const WaveChannelSubView &subView) {
1092 if (subView.SubViewType().id == display) {
1093 found = ii;
1094 return true;
1095 }
1096 ++ii;
1097 return false;
1098 })) {
1099 auto &placements = DoGetPlacements();
1100 auto &foundPlacement = placements[found];
1101 if ( foundPlacement.fraction > 0.0 ) {
1102 // Toggle off
1103
1104 if (GetDisplays().size() < 2)
1105 // refuse to do it
1106 return false;
1107
1108 auto index = foundPlacement.index;
1109 foundPlacement = { -1, 0.0 };
1110 if (index >= 0) {
1111 for ( auto &placement : placements ) {
1112 if ( placement.index > index )
1113 --placement.index;
1114 }
1115 }
1116
1117 return true;
1118 }
1119 else {
1120 // Toggle on
1121 float total = 0;
1122 int greatest = -1;
1123 unsigned nn = 0;
1124 for ( const auto &placement : placements ) {
1125 if ( placement.fraction > 0.0 && placement.index >= 0 ) {
1126 total += placement.fraction;
1127 greatest = std::max( greatest, placement.index );
1128 ++nn;
1129 }
1130 }
1131 // Turn on the sub-view, putting it lowest, and with average of the
1132 // heights of the other sub-views
1133 foundPlacement = { greatest + 1, total / nn };
1134
1135 return true;
1136 }
1137 }
1138 else
1139 // unknown sub-view
1140 return false;
1141 }
1142
1143 // If exclusive, make the chosen view take up all the height. Else,
1144 // partition equally, putting the specified view on top.
1145 // Be sure the sequence in which the other views appear is determinate.
1146 void WaveChannelView::DoSetDisplay(Display display, bool exclusive)
1147 {
1148 // Some generality here anticipating more than two views.
1149 // The order of sub-views in the array is not specified, so make it definite
1150 // by sorting by the view type constants.
1151 size_t ii = 0;
1152 std::vector<std::pair<WaveChannelViewConstants::Display, size_t>> pairs;
1153 WaveChannelSubViews::ForEach([&pairs, &ii](WaveChannelSubView &subView){
1154 pairs.push_back({ subView.SubViewType().id, ii++ });
1155 });
1156 std::sort( pairs.begin(), pairs.end() );
1157
1158 int jj = 1;
1159 auto &placements = DoGetPlacements();
1160 for ( const auto &pair : pairs ) {
1161 auto &placement = placements[ pair.second ];
1162 if (pair.first == display) {
1163 // 0 for first view
1164 placement = { 0, 1.0 };
1165 }
1166 else if( exclusive )
1167 // -1 for not displayed
1168 placement = { -1, 0.0 };
1169 else
1170 // positions other than the first.
1171 // (Note that the fractions in the placement don't need to be
1172 // denominated to 1. Just make them all equal to get an equal
1173 // partitioning of the sub-views.)
1174 placement = { jj++, 1.0 };
1175 }
1176 }
1177
1178 namespace {
1179 template<typename Iter>
1180 Iter SelectedClip(const ViewInfo& viewInfo, Iter begin, Iter end)
1181 {
1182 //! Decide whether a clip is selected from its start and end times (only)
1183 const auto isClipSelected =
1184 [&viewInfo](const std::shared_ptr<WaveChannelInterval> &pClip) {
1185 return pClip->GetPlayStartTime() == viewInfo.selectedRegion.t0() &&
1186 pClip->GetPlayEndTime() == viewInfo.selectedRegion.t1();
1187 };
1188 return std::find_if(begin, end, isClipSelected);
1189 }
1190
1191 template<typename Iter, typename Comp>
1192 std::shared_ptr<WaveChannelInterval>
1193 NextClipLooped(ViewInfo& viewInfo, Iter begin, Iter end, Comp comp)
1194 {
1195 auto it = SelectedClip(viewInfo, begin, end);
1196 if (it == end)
1197 it = std::find_if(begin, end, comp);
1198 else
1199 it = std::next(it);
1200
1201 if (it == end)
1202 return *begin;
1203 return *it;
1204 }
1205 }
1206
1207 bool WaveChannelView::SelectNextClip(
1208 ViewInfo& viewInfo, AudacityProject* project, bool forward)
1209 {
1210 //Iterates through clips in a looped manner
1211 const auto pChannel = FindWaveChannel();
1212 if (!pChannel)
1213 return false;
1214 auto clips = WaveChannelUtilities::SortedClipArray(*pChannel);
1215 if (clips.empty())
1216 return false;
1217
1218 std::shared_ptr<WaveChannelInterval> clip{};
1219 if (forward)
1220 {
1221 clip = NextClipLooped(viewInfo, clips.begin(), clips.end(),
1222 [&](const auto &other) {
1223 return other->GetPlayStartTime() >= viewInfo.selectedRegion.t1();
1224 });
1225 }
1226 else
1227 {
1228 clip = NextClipLooped(viewInfo, clips.rbegin(), clips.rend(),
1229 [&](const auto &other) {
1230 return other->GetPlayStartTime() <= viewInfo.selectedRegion.t0();
1231 });
1232 }
1233
1234 viewInfo.selectedRegion.setTimes(clip->GetPlayStartTime(), clip->GetPlayEndTime());
1235 ProjectHistory::Get(*project).ModifyState(false);
1236
1237 // create and send message to screen reader
1238 auto it = std::find(clips.begin(), clips.end(), clip);
1239 auto index = std::distance(clips.begin(), it);
1240
1241 auto &waveTrack = pChannel->GetTrack();
1242 auto wideClipIt = waveTrack.Intervals().first;
1243 std::advance(wideClipIt, waveTrack.GetClipIndex(clip->GetClip()));
1244 PitchAndSpeedDialog::Get(*project)
1245 .Retarget(waveTrack.SharedPointer<WaveTrack>(), *wideClipIt);
1246
1247 auto message = XP(
1248 /* i18n-hint:
1249 string is the name of a clip
1250 first number is the position of that clip in a sequence of clips,
1251 second number counts the clips */
1252 "%s, %d of %d clip",
1253 "%s, %d of %d clips",
1254 2
1255 )(
1256 clip->GetClip().GetName(),
1257 static_cast<int>(index + 1),
1258 static_cast<int>(clips.size())
1259 );
1260
1261 TrackFocus::Get(*project).MessageForScreenReader(message);
1262 return true;
1263 }
1264
1265 auto WaveChannelView::GetSubViews(const wxRect &rect) -> Refinement
1266 {
1267 return GetSubViews(&rect);
1268 }
1269
1270 auto WaveChannelView::GetSubViews(const wxRect* rect) -> Refinement
1271 {
1272 BuildSubViews();
1273
1274 // Collect the visible views in the right sequence
1275 struct Item {
1276 int index; float fraction; std::shared_ptr<ChannelView> pView;
1277 };
1278 std::vector< Item > items;
1279 size_t ii = 0;
1280 float total = 0;
1281 const auto &placements = DoGetPlacements();
1282 WaveChannelSubViews::ForEach([&](WaveChannelSubView& subView) {
1283 auto& placement = placements[ii];
1284 auto index = placement.index;
1285 auto fraction = placement.fraction;
1286 if (index >= 0 && fraction > 0.0)
1287 total += fraction,
1288 items.push_back({ index, fraction, subView.shared_from_this() });
1289 ++ii;
1290 });
1291 std::sort(items.begin(), items.end(), [](const Item& a, const Item& b) {
1292 return a.index < b.index;
1293 });
1294
1295 // Remove views we don't need
1296 auto begin = items.begin(), end = items.end(),
1297 newEnd = std::remove_if(begin, end,
1298 [](const Item& item) { return !item.pView; });
1299 items.erase(newEnd, end);
1300
1301 Refinement results;
1302
1303 if (rect != nullptr)
1304 {
1305 // Assign coordinates, redenominating to the total height,
1306 // storing integer values
1307 results.reserve(items.size());
1308 const auto top = rect->GetTop();
1309 const auto height = rect->GetHeight();
1310 float partial = 0;
1311 wxCoord lastCoord = 0;
1312 for (const auto& item : items) {
1313 wxCoord newCoord = top + (partial / total) * height;
1314 results.emplace_back(newCoord, item.pView);
1315 partial += item.fraction;
1316 }
1317
1318 // Cache for the use of sub-view dragging
1319 mLastHeight = height;
1320 }
1321 else
1322 {
1323 std::transform(items.begin(), items.end(), std::back_inserter(results), [](const auto& item) {
1324 return std::make_pair(0, item.pView);
1325 });
1326 }
1327
1328 return results;
1329 }
1330
1331 /*
1332 Note that the WaveChannelView isn't in the TrackPanel subdivision, but it is
1333 set sometimes as the focused cell, and therefore the following functions can
1334 be visited. To visit their overrides in the sub-views and affordances,
1335 which are never focused, we must forward to them. To do that properly, if
1336 any cell declines to handle the event by setting it as skipped, it must be
1337 set again to not-skipped before attempting the next call-through.
1338 */
1339 unsigned WaveChannelView::CaptureKey(
1340 wxKeyEvent& event, ViewInfo& viewInfo, wxWindow* pParent,
1341 AudacityProject* project)
1342 {
1343 unsigned result{ RefreshCode::RefreshNone };
1344 const auto pChannel = FindWaveChannel();
1345 if (!pChannel)
1346 return result;
1347 auto &track = pChannel->GetTrack();
1348 for (auto pChannel : track.Channels()) {
1349 event.Skip(false);
1350 auto &waveChannelView = WaveChannelView::Get(*pChannel);
1351 // Give sub-views first chance to handle the event
1352 for (auto &subView : waveChannelView.GetSubViews()) {
1353 // Event defaults in skipped state which must be turned off explicitly
1354 wxASSERT(!event.GetSkipped());
1355 result |= subView.second->CaptureKey(event, viewInfo, pParent, project);
1356 if (!event.GetSkipped()) {
1357 // sub view wants it
1358 mKeyEventDelegate = subView.second;
1359 return result;
1360 }
1361 else
1362 event.Skip(false);
1363 }
1364
1365 if (auto affordance = waveChannelView.GetAffordanceControls()) {
1366 result |= affordance->CaptureKey(event, viewInfo, pParent, project);
1367 if (!event.GetSkipped()) {
1368 mKeyEventDelegate = affordance;
1369 return result;
1370 }
1371 }
1372
1373 event.Skip(false);
1374 }
1375 switch (event.GetKeyCode())
1376 {
1377 case WXK_TAB:
1378 break;
1379 default:
1380 result |= CommonChannelView::CaptureKey(
1381 event, viewInfo, pParent, project);
1382 break;
1383 };
1384 if (!event.GetSkipped()) {
1385 mKeyEventDelegate = shared_from_this();
1386 }
1387
1388 return result;
1389 }
1390
1391 unsigned WaveChannelView::KeyDown(
1392 wxKeyEvent& event, ViewInfo& viewInfo, wxWindow* pParent,
1393 AudacityProject* project)
1394 {
1395 unsigned result{ RefreshCode::RefreshNone };
1396 if (auto delegate = mKeyEventDelegate.lock()) {
1397 if (auto pWaveChannelView =
1398 dynamic_cast<WaveChannelView*>(delegate.get()))
1399 {
1400 if (event.GetKeyCode() == WXK_TAB)
1401 {
1402 SelectNextClip(viewInfo, project, event.GetModifiers() != wxMOD_SHIFT);
1403 result |= RefreshCode::RefreshCell;
1404 }
1405 else
1406 result |= pWaveChannelView->CommonChannelView::KeyDown(
1407 event, viewInfo, pParent, project);
1408 }
1409 else
1410 result |= delegate->KeyDown(event, viewInfo, pParent, project);
1411 }
1412 else
1413 event.Skip();
1414
1415 return result;
1416 }
1417
1418 unsigned WaveChannelView::Char(
1419 wxKeyEvent& event, ViewInfo& viewInfo, wxWindow* pParent,
1420 AudacityProject* project)
1421 {
1422 unsigned result{ RefreshCode::RefreshNone };
1423 if (auto delegate = mKeyEventDelegate.lock()) {
1424 if (auto pWaveChannelView =
1425 dynamic_cast<WaveChannelView*>(delegate.get()))
1426 result |= pWaveChannelView->CommonChannelView::Char(
1427 event, viewInfo, pParent, project);
1428 else
1429 result |= delegate->Char(event, viewInfo, pParent, project);
1430 }
1431 else
1432 event.Skip();
1433
1434 return result;
1435 }
1436
1437 unsigned WaveChannelView::LoseFocus(AudacityProject *project)
1438 {
1439 unsigned result = RefreshCode::RefreshNone;
1440 if (auto delegate = mKeyEventDelegate.lock()) {
1441 if (auto pWaveChannelView =
1442 dynamic_cast<WaveChannelView*>(delegate.get()))
1443 result = pWaveChannelView->CommonChannelView::LoseFocus(project);
1444 else
1445 result = delegate->LoseFocus(project);
1446 mKeyEventDelegate.reset();
1447 }
1448 return result;
1449 }
1450
1451 namespace {
1452 using PMF = bool (WaveTrackAffordanceControls::*)(AudacityProject &);
1453 bool AnyAffordance(AudacityProject& project, WaveChannelView &view, PMF pmf)
1454 {
1455 const auto pWaveChannel = view.FindWaveChannel();
1456 const auto pTrack = &pWaveChannel->GetTrack();
1457 auto& channelView = ChannelView::Get(**pTrack->Channels().begin());
1458 if (const auto affordance =
1459 std::dynamic_pointer_cast<WaveTrackAffordanceControls>(
1460 channelView.GetAffordanceControls()).get()
1461 ; affordance && (affordance->*pmf)(project)
1462 )
1463 return true;
1464 return false;
1465 }
1466 }
1467
1468 bool WaveChannelView::CutSelectedText(AudacityProject& project)
1469 {
1470 return
1471 AnyAffordance(project, *this, &WaveTrackAffordanceControls::OnTextCut);
1472 }
1473
1474 bool WaveChannelView::CopySelectedText(AudacityProject& project)
1475 {
1476 return
1477 AnyAffordance(project, *this, &WaveTrackAffordanceControls::OnTextCopy);
1478 }
1479
1480 bool WaveChannelView::ClipDetailsVisible(const ClipTimes& clip,
1481 const ZoomInfo& zoomInfo, const wxRect& viewRect)
1482 {
1483 //Do not fold clips to line at sample zoom level, as
1484 //it may become impossible to 'unfold' it when clip is trimmed
1485 //to a single sample
1486 bool showSamples{ false };
1487 auto clipRect = ClipParameters::GetClipRect(clip, zoomInfo, viewRect, &showSamples);
1488 return showSamples || clipRect.width >= kClipDetailedViewMinimumWidth;
1489 }
1490
1491 wxRect WaveChannelView::ClipHitTestArea(const ClipTimes& clip,
1492 const ZoomInfo& zoomInfo, const wxRect& viewRect)
1493 {
1494 bool showSamples{ false };
1495 auto clipRect = ClipParameters::GetClipRect(clip, zoomInfo, viewRect, &showSamples);
1496 if (showSamples || clipRect.width >= kClipDetailedViewMinimumWidth)
1497 return clipRect;
1498
1499 return clipRect.Inflate(2, 0);
1500 }
1501
1502 bool WaveChannelView::HitTest(const ClipTimes& clip,
1503 const ZoomInfo& viewInfo, const wxRect& viewRect, const wxPoint& pos)
1504 {
1505 return ClipHitTestArea(clip, viewInfo, viewRect).Contains(pos);
1506 }
1507
1508 bool WaveChannelView::PasteText(AudacityProject& project)
1509 {
1510 return
1511 AnyAffordance(project, *this, &WaveTrackAffordanceControls::OnTextPaste);
1512 }
1513
1514 bool WaveChannelView::SelectAllText(AudacityProject& project)
1515 {
1516 return
1517 AnyAffordance(project, *this, &WaveTrackAffordanceControls::OnTextSelect);
1518 }
1519
1520 std::vector<std::shared_ptr<WaveChannelSubView>>
1521 WaveChannelView::GetAllSubViews()
1522 {
1523 BuildSubViews();
1524
1525 std::vector<std::shared_ptr<WaveChannelSubView>> results;
1526 WaveChannelSubViews::ForEach([&](WaveChannelSubView &subView) {
1527 results.push_back(std::static_pointer_cast<WaveChannelSubView>(
1528 subView.shared_from_this()));
1529 });
1530 return results;
1531 }
1532
1533 std::shared_ptr<CommonTrackCell> WaveChannelView::GetAffordanceControls()
1534 {
1535 auto pChannel = FindWaveChannel();
1536 if (pChannel) {
1537 auto &track = pChannel->GetTrack();
1538 if (pChannel == *track.Channels().begin()) {
1539 return DoGetAffordance(track);
1540 }
1541 }
1542 return {};
1543 }
1544
1545 void WaveChannelView::DoSetMinimized(bool minimized)
1546 {
1547 BuildSubViews();
1548
1549 // May come here. Invoke also on sub-views.
1550 ChannelView::DoSetMinimized(minimized);
1551 WaveChannelSubViews::ForEach([minimized](WaveChannelSubView &subView) {
1552 subView.DoSetMinimized(minimized);
1553 });
1554 }
1555
1556 std::shared_ptr<CommonTrackCell>
1557 WaveChannelView::DoGetAffordance(Track& track)
1558 {
1559 if (mpAffordanceCellControl == nullptr)
1560 mpAffordanceCellControl =
1561 std::make_shared<WaveTrackAffordanceControls>(track.SharedPointer());
1562 return mpAffordanceCellControl;
1563 }
1564
1565 using DoGetWaveChannelView = DoGetView::Override<WaveTrack>;
1566 DEFINE_ATTACHED_VIRTUAL_OVERRIDE(DoGetWaveChannelView) {
1567 return [](WaveTrack &track, size_t iChannel) {
1568 auto channels = track.Channels();
1569 assert(iChannel < channels.size());
1570 auto &iter = channels.first;
1571 std::advance(iter, iChannel);
1572 return std::make_shared<WaveChannelView>(*iter);
1573 };
1574 }
1575
1576 std::shared_ptr<ChannelVRulerControls> WaveChannelView::DoGetVRulerControls()
1577 {
1578 return {};
1579 }
1580
1581 void WaveChannelView::Reparent(
1582 const std::shared_ptr<Track> &parent, size_t iChannel)
1583 {
1584 // BuildSubViews(); // not really needed
1585 CommonChannelView::Reparent(parent, iChannel);
1586 WaveChannelSubViews::ForEach([&parent, iChannel](WaveChannelSubView &subView)
1587 {
1588 subView.Reparent(parent, iChannel);
1589 });
1590 if (mpAffordanceCellControl)
1591 mpAffordanceCellControl->Reparent(parent);
1592 }
1593
1594 WaveTrack::IntervalHolder WaveChannelView::GetSelectedClip()
1595 {
1596 const auto pChannel = FindWaveChannel();
1597 if (!pChannel)
1598 return {};
1599 auto &track = pChannel->GetTrack();
1600 auto &topmostView = Get(**track.Channels().begin());
1601 if (auto affordance = std::dynamic_pointer_cast<WaveTrackAffordanceControls>(
1602 topmostView.GetAffordanceControls()))
1603 {
1604 return *affordance->GetSelectedInterval();
1605 }
1606 return {};
1607 }
1608
1609 void WaveChannelView::BuildSubViews() const
1610 {
1611 if (WaveChannelSubViews::size() == 0) {
1612 // On-demand steps that can't happen in the constructor
1613 auto pThis = const_cast<WaveChannelView*>(this);
1614 pThis->BuildAll();
1615 bool minimized = GetMinimized();
1616 pThis->WaveChannelSubViews::ForEach([&](WaveChannelSubView &subView){
1617 subView.DoSetMinimized(minimized);
1618 });
1619
1620 auto &placements = pThis->DoGetPlacements();
1621 if (placements.empty()) {
1622 placements.resize(WaveChannelSubViews::size());
1623
1624 auto display = TracksPrefs::ViewModeChoice();
1625 bool multi = (display == WaveChannelViewConstants::MultiView);
1626 if (multi) {
1627 pThis->SetMultiView( true );
1628 display = WaveChannelSubViewType::Default();
1629 }
1630
1631 pThis->DoSetDisplay( display, !multi );
1632 }
1633 }
1634 }
1635
1636 void WaveChannelView::Draw(
1637 TrackPanelDrawingContext &context,
1638 const wxRect &rect, unsigned iPass)
1639 {
1640 // Should not come here, drawing is now delegated to sub-views
1641 wxASSERT( false );
1642
1643 CommonChannelView::Draw(context, rect, iPass);
1644 }
1645
1646 using GetWaveTrackSyncLockPolicy =
1647 GetSyncLockPolicy::Override< const WaveTrack >;
1648 DEFINE_ATTACHED_VIRTUAL_OVERRIDE(GetWaveTrackSyncLockPolicy) {
1649 return [](auto &) { return SyncLockPolicy::Grouped; };
1650 }