Debian Codegraph @

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

raw
1 /**********************************************************************
2
3 Audacity: A Digital Audio Editor
4
5 WaveformView.cpp
6
7 Paul Licameli split from WaveChannelView.cpp
8
9 **********************************************************************/
10
11
12 #include "WaveformView.h"
13
14 #include "WaveformAppearance.h"
15 #include "ClipParameters.h"
16 #include "WaveChannelView.h"
17 #include "WaveChannelViewConstants.h"
18 #include "WaveformVRulerControls.h"
19
20 #include "SampleHandle.h"
21 #include "../../../ui/EnvelopeHandle.h"
22 #include "../../../ui/TimeShiftHandle.h"
23 #include "AColor.h"
24 #include "Envelope.h"
25 #include "../../../../EnvelopeEditor.h"
26 #include "PendingTracks.h"
27 #include "../../../../ProjectSettings.h"
28 #include "SelectedRegion.h"
29 #include "SyncLock.h"
30 #include "../../../../TrackArt.h"
31 #include "../../../../TrackArtist.h"
32 #include "../../../../TrackPanelDrawingContext.h"
33 #include "../../../../TrackPanelMouseEvent.h"
34 #include "ViewInfo.h"
35 #include "WaveChannelUtilities.h"
36 #include "WaveClip.h"
37 #include "WaveTrack.h"
38 #include "WaveTrackUtilities.h"
39 #include "../../../../WaveTrackLocation.h"
40 #include "prefs/WaveformScale.h"
41 #include "WaveformSettings.h"
42
43 #include "FrameStatistics.h"
44
45 #include <wx/graphics.h>
46 #include <wx/dc.h>
47 #include <wx/gdicmn.h>
48
49 #include <wx/dcmemory.h>
50 #include "waveform/WaveBitmapCache.h"
51 #include "waveform/WaveDataCache.h"
52 #include "waveform/WavePaintParameters.h"
53
54 #include <atomic>
55
56 #include "prefs/GUIPrefs.h"
57
58
59 static WaveChannelSubView::Type sType{
60 WaveChannelViewConstants::Waveform,
61 { wxT("Waveform"), XXO("Wa&veform") }
62 };
63
64 static WaveChannelSubViewType::RegisteredType reg{ sType };
65
66 WaveformView::~WaveformView() = default;
67
68 std::vector<UIHandlePtr> WaveformView::DetailedHitTest(
69 const TrackPanelMouseState &st,
70 const AudacityProject *pProject, int currentTool, bool bMultiTool )
71 {
72 auto &view = *this;
73 const auto pChannel = view.FindChannel<WaveChannel>();
74
75 auto pair = WaveChannelSubView::DoDetailedHitTest(
76 st, pProject, currentTool, bMultiTool, pChannel);
77 auto &results = pair.second;
78
79 if (!pair.first) {
80 UIHandlePtr result;
81
82 if (bMultiTool) {
83 // Conditional hit tests
84 // If Tools toolbar were eliminated, we would keep these
85 // The priority of these, in case more than one might apply at one
86 // point, seems arbitrary
87 if (nullptr != (result = EnvelopeHandle::WaveChannelHitTest(
88 view.mEnvelopeHandle, st.state, st.rect,
89 pProject, pChannel)))
90 results.push_back(result);
91 if (nullptr != (result = TimeShiftHandle::HitTest(
92 view.mTimeShiftHandle, st.state, st.rect,
93 pChannel->GetTrack().SharedPointer())))
94 // This is the hit test on the "grips" drawn left and
95 // right in Multi only
96 results.push_back(result);
97 if (nullptr != (result = SampleHandle::HitTest(
98 view.mSampleHandle, st.state, st.rect,
99 pProject, pChannel)))
100 results.push_back(result);
101 }
102 else {
103 switch ( currentTool ) {
104 // Unconditional hits appropriate to the tool
105 // If tools toolbar were eliminated, we would eliminate these
106 case ToolCodes::envelopeTool: {
107 auto &viewInfo = ViewInfo::Get(*pProject);
108 auto time =
109 viewInfo.PositionToTime(st.state.m_x, st.rect.GetX());
110 const auto envelope =
111 WaveChannelUtilities::GetEnvelopeAtTime(*pChannel, time);
112 result = EnvelopeHandle::HitAnywhere(
113 view.mEnvelopeHandle, envelope,
114 std::dynamic_pointer_cast<const Channel>(pChannel),
115 false);
116 break;
117 }
118 case ToolCodes::drawTool:
119 result = SampleHandle::HitAnywhere(
120 view.mSampleHandle, st.state, pChannel);
121 break;
122 default:
123 result = {};
124 break;
125 }
126 if (result)
127 results.push_back(result);
128 }
129 }
130
131 return std::move( results );
132 }
133
134 void WaveformView::DoSetMinimized( bool minimized )
135 {
136 auto wt = FindWaveChannel();
137
138 bool bHalfWave;
139 gPrefs->Read(wxT("/GUI/CollapseToHalfWave"), &bHalfWave, false);
140 if (wt && bHalfWave) {
141 auto &cache = WaveformScale::Get(*wt);
142 if (minimized)
143 // Zoom to show fractionally more than the top half of the wave.
144 cache.SetDisplayBounds( -0.01f, 1.0f );
145 else
146 // Zoom out full
147 cache.SetDisplayBounds( -1.0f, 1.0f );
148 }
149
150 ChannelView::DoSetMinimized(minimized);
151 }
152
153 auto WaveformView::SubViewType() const -> const Type &
154 {
155 return sType;
156 }
157
158 std::shared_ptr<ChannelVRulerControls> WaveformView::DoGetVRulerControls()
159 {
160 return std::make_shared<WaveformVRulerControls>(shared_from_this());
161 }
162
163 namespace
164 {
165
166
167 graphics::Color ColorFromWXPen(const wxPen& pen)
168 {
169 const auto c = pen.GetColour();
170 return graphics::Color(c.Red(), c.Green(), c.Blue());
171 }
172
173 graphics::Color ColorFromWXBrush(const wxBrush& brush)
174 {
175 const auto c = brush.GetColour();
176 return graphics::Color(c.Red(), c.Green(), c.Blue());
177 }
178
179
180 struct WaveBitmapCacheElementWX final : public WaveBitmapCacheElement
181 {
182 uint8_t* Allocate(size_t width, size_t height) override
183 {
184 mImage = wxImage(width, height, false);
185 mBitmap = wxBitmap();
186 return mImage.GetData();
187 }
188
189 wxBitmap& GetBitmap()
190 {
191 if(!mBitmap.IsOk() && mImage.IsOk())
192 mBitmap = wxBitmap(mImage);
193 return mBitmap;
194 }
195
196 size_t Width() const override
197 {
198 return mImage.GetWidth();
199 }
200
201 size_t Height() const override
202 {
203 return mImage.GetHeight();
204 }
205
206 private:
207 wxBitmap mBitmap;
208 wxImage mImage;
209 };
210
211
212 class WaveformPainter final
213 : public WaveClipListener
214 {
215 public:
216
217 static WaveformPainter& Get(const WaveClip& clip);
218
219 WaveformPainter()
220 {
221 }
222
223 WaveformPainter& EnsureClip (const WaveClip& clip)
224 {
225 const auto changed = mChanged.exchange(false);
226 if (&clip != mWaveClip || changed)
227 mChannelCaches.clear();
228
229 const auto nChannels = clip.NChannels();
230
231 if (mChannelCaches.size() == nChannels)
232 return *this;
233
234 mWaveClip = &clip;
235
236 mChannelCaches.reserve(nChannels);
237
238 for (auto channelIndex = 0; channelIndex < nChannels; ++channelIndex)
239 {
240 auto dataCache = std::make_shared<WaveDataCache>(clip, channelIndex);
241
242 auto bitmapCache = std::make_unique<WaveBitmapCache>(
243 clip, dataCache,
244 [] { return std::make_unique<WaveBitmapCacheElementWX>(); });
245
246 mChannelCaches.push_back(
247 { std::move(dataCache), std::move(bitmapCache) });
248 }
249
250 return *this;
251 }
252
253 void SetSelection(const ZoomInfo& zoomInfo, float t0, float t1, bool selected)
254 {
255 for (auto& channelCache : mChannelCaches)
256 channelCache.BitmapCache->SetSelection(zoomInfo, t0, t1, selected);
257 }
258
259 void Draw(
260 int channelIndex, wxDC& dc, const WavePaintParameters& params,
261 const ZoomInfo& zoomInfo, const wxRect& targetRect, int leftOffset,
262 double from, double to)
263 {
264 auto& channelCache = mChannelCaches[channelIndex];
265
266 channelCache.BitmapCache->SetPaintParameters(params);
267
268 auto range = channelCache.BitmapCache->PerformLookup(zoomInfo, from, to);
269
270 auto left = targetRect.x + leftOffset;
271 auto height = targetRect.height;
272
273 const auto top = targetRect.y;
274
275 wxMemoryDC memdc;
276 for (auto it = range.begin(); it != range.end(); ++it)
277 {
278 const auto elementLeftOffset = it.GetLeftOffset();
279 const auto elementRightOffset = it.GetRightOffset();
280
281 const auto width = WaveBitmapCache::CacheElementWidth -
282 elementLeftOffset - elementRightOffset;
283
284 auto& bitmap = static_cast<WaveBitmapCacheElementWX&>(*it).GetBitmap();
285 memdc.SelectObject(bitmap);
286 dc.Blit(
287 wxPoint(left, targetRect.y), wxSize(width, it->Height()), &memdc,
288 wxPoint(elementLeftOffset, 0));
289
290 left += width;
291 }
292 }
293
294 void SwapChannels() override
295 {
296 //Wave data cache captures channel index which becomes
297 //part of it's state, request cache rebuild...
298 mChanged.store(true);
299 }
300
301 void MarkChanged() noexcept override
302 {
303 //Triggered when any part of the waveform has changed
304 //TODO: invalidate parts of the cache that intersect changes
305 mChanged.store(true);
306 }
307
308 void Invalidate() override
309 {
310 for (auto& channelCache : mChannelCaches)
311 {
312 channelCache.DataCache->Invalidate();
313 channelCache.BitmapCache->Invalidate();
314 }
315 }
316
317 std::unique_ptr<WaveClipListener> Clone() const override
318 {
319 return std::make_unique<WaveformPainter>();
320 }
321
322 private:
323 const WaveClip* mWaveClip {};
324
325 struct ChannelCaches final
326 {
327 std::shared_ptr<WaveDataCache> DataCache;
328 std::unique_ptr<WaveBitmapCache> BitmapCache;
329 };
330
331 std::vector<ChannelCaches> mChannelCaches;
332 std::atomic<bool> mChanged = false;
333 };
334
335 void DrawWaveform(
336 TrackPanelDrawingContext& context, const WaveTrack& track, const WaveChannelInterval& channelInterval,
337 int leftOffset, double t0, double t1,
338 const wxRect & rect, float zoomMin, float zoomMax, bool dB, float dBRange,
339 bool muted)
340 {
341 auto& clip = channelInterval.GetClip();
342 const auto channelIndex = channelInterval.GetChannelIndex();
343
344 const auto artist = TrackArtist::Get(context);
345 const ZoomInfo zoomInfo(0.0, artist->pZoomInfo->GetZoom());
346
347 auto& clipPainter = WaveformPainter::Get(clip);
348
349 const auto trimLeft = clip.GetTrimLeft();
350 const auto sequenceStartTime = clip.GetSequenceStartTime();
351
352 WavePaintParameters paintParameters;
353
354 paintParameters
355 .SetDisplayParameters(
356 rect.GetHeight(), zoomMin, zoomMax, ShowClippingPref().Read())
357 .SetDBParameters(dBRange, dB)
358 .SetBlankColor(ColorFromWXBrush(artist->blankBrush))
359 .SetZeroLineColor(graphics::Colors::Black)
360 .SetShowRMS(ShowRMSPref().Read())
361 .SetSampleColors(
362 ColorFromWXPen(muted ? artist->muteSamplePen : artist->samplePen),
363 ColorFromWXPen(muted ? artist->muteSamplePen : artist->samplePen))
364 .SetRMSColors(
365 ColorFromWXPen(muted ? artist->muteRmsPen : artist->rmsPen),
366 ColorFromWXPen(muted ? artist->muteRmsPen : artist->rmsPen))
367 .SetBackgroundColors(
368 ColorFromWXBrush(artist->unselectedBrush),
369 ColorFromWXBrush(artist->selectedBrush))
370 .SetClippingColors(
371 ColorFromWXPen(muted ? artist->muteClippedPen : artist->clippedPen),
372 ColorFromWXPen(muted ? artist->muteClippedPen : artist->clippedPen))
373 .SetEnvelopeColors(
374 ColorFromWXBrush(artist->envelopeBackgroundBrush),
375 ColorFromWXBrush(artist->envelopeBackgroundBrush)
376 )
377 .SetDrawEnvelope(artist->drawEnvelope)
378 .SetEnvelope(clip.GetEnvelope());
379
380 clipPainter.SetSelection(
381 zoomInfo, artist->pSelectedRegion->t0() - sequenceStartTime,
382 artist->pSelectedRegion->t1() - sequenceStartTime,
383 SyncLock::IsSelectedOrSyncLockSelected(track));
384
385 clipPainter.Draw(
386 channelIndex, context.dc, paintParameters, zoomInfo, rect, leftOffset,
387 t0 + trimLeft, t1 + trimLeft);
388 }
389
390
391
392 void DrawWaveformBackground(TrackPanelDrawingContext &context,
393 int leftOffset, const wxRect &rect,
394 const double env[],
395 float zoomMin, float zoomMax,
396 int zeroLevelYCoordinate,
397 bool dB, float dBRange,
398 double t0, double t1,
399 bool bIsSyncLockSelected,
400 bool highlightEnvelope)
401 {
402 auto &dc = context.dc;
403 const auto artist = TrackArtist::Get( context );
404 const auto &zoomInfo = *artist->pZoomInfo;
405
406 // Visually (one vertical slice of the waveform background, on its side;
407 // the "*" is the actual waveform background we're drawing
408 //
409 //1.0 0.0 -1.0
410 // |--------------------------------|--------------------------------|
411 // *************** ***************
412 // | | | |
413 // maxtop maxbot mintop minbot
414
415 int h = rect.height;
416 int halfHeight = wxMax(h / 2, 1);
417 int maxtop, lmaxtop = 0;
418 int mintop, lmintop = 0;
419 int maxbot, lmaxbot = 0;
420 int minbot, lminbot = 0;
421 bool sel, lsel = false;
422 int xx, lx = 0;
423 int l, w;
424
425 const auto &blankBrush = artist->blankBrush;
426 const auto &selectedBrush = artist->selectedBrush;
427 const auto &unselectedBrush = artist->unselectedBrush;
428 const auto &envelopeBackgroundBrush = artist->envelopeBackgroundBrush;
429
430 dc.SetPen(*wxTRANSPARENT_PEN);
431 dc.SetBrush(envelopeBackgroundBrush);
432 dc.DrawRectangle(rect);
433
434 // Bug 2389 - always draw at least one pixel of selection.
435 int selectedX = zoomInfo.TimeToPosition(t0, -leftOffset);
436
437 double time = zoomInfo.PositionToTime(0, -leftOffset), nextTime;
438 for (xx = 0; xx < rect.width; ++xx, time = nextTime) {
439 nextTime = zoomInfo.PositionToTime(xx + 1, -leftOffset);
440 // First we compute the truncated shape of the waveform background.
441 // If drawEnvelope is true, then we compute the lower border of the
442 // envelope.
443
444 maxtop = GetWaveYPos(env[xx], zoomMin, zoomMax,
445 h, dB, true, dBRange, true);
446 maxbot = GetWaveYPos(env[xx], zoomMin, zoomMax,
447 h, dB, false, dBRange, true);
448
449 mintop = GetWaveYPos(-env[xx], zoomMin, zoomMax,
450 h, dB, false, dBRange, true);
451 minbot = GetWaveYPos(-env[xx], zoomMin, zoomMax,
452 h, dB, true, dBRange, true);
453
454 // Make sure it's odd so that a that max and min mirror each other
455 mintop +=1;
456 minbot +=1;
457
458 const auto drawEnvelope = artist->drawEnvelope;
459 if (!drawEnvelope || maxbot > mintop) {
460 maxbot = halfHeight;
461 mintop = halfHeight;
462 }
463
464 sel = (t0 <= time && nextTime < t1);
465 sel = sel || (xx == selectedX);
466 // We don't draw selection color for sync-lock selected tracks.
467 sel = sel && !bIsSyncLockSelected;
468
469 if (lmaxtop == maxtop &&
470 lmintop == mintop &&
471 lmaxbot == maxbot &&
472 lminbot == minbot &&
473 lsel == sel) {
474 continue;
475 }
476
477 dc.SetBrush(lsel ? selectedBrush : unselectedBrush);
478
479 l = rect.x + lx;
480 w = xx - lx;
481 if (lmaxbot < lmintop - 1) {
482 dc.DrawRectangle(l, rect.y + lmaxtop, w, lmaxbot - lmaxtop);
483 dc.DrawRectangle(l, rect.y + lmintop, w, lminbot - lmintop);
484 }
485 else {
486 dc.DrawRectangle(l, rect.y + lmaxtop, w, lminbot - lmaxtop);
487 }
488
489 if (highlightEnvelope && lmaxbot < lmintop - 1) {
490 dc.SetBrush( AColor::uglyBrush );
491 dc.DrawRectangle(l, rect.y + lmaxbot, w, lmintop - lmaxbot);
492 }
493
494 lmaxtop = maxtop;
495 lmintop = mintop;
496 lmaxbot = maxbot;
497 lminbot = minbot;
498 lsel = sel;
499 lx = xx;
500 }
501
502 dc.SetBrush(lsel ? selectedBrush : unselectedBrush);
503 l = rect.x + lx;
504 w = xx - lx;
505 if (lmaxbot < lmintop - 1) {
506 dc.DrawRectangle(l, rect.y + lmaxtop, w, lmaxbot - lmaxtop);
507 dc.DrawRectangle(l, rect.y + lmintop, w, lminbot - lmintop);
508 }
509 else {
510 dc.DrawRectangle(l, rect.y + lmaxtop, w, lminbot - lmaxtop);
511 }
512 if (highlightEnvelope && lmaxbot < lmintop - 1) {
513 dc.SetBrush( AColor::uglyBrush );
514 dc.DrawRectangle(l, rect.y + lmaxbot, w, lmintop - lmaxbot);
515 }
516
517 // If sync-lock selected, draw in linked graphics.
518 if (bIsSyncLockSelected && t0 < t1) {
519 const int begin = std::max(0, std::min(rect.width, (int)(zoomInfo.TimeToPosition(t0, -leftOffset))));
520 const int end = std::max(0, std::min(rect.width, (int)(zoomInfo.TimeToPosition(t1, -leftOffset))));
521 TrackArt::DrawSyncLockTiles( context,
522 { rect.x + begin, rect.y, end - 1 - begin, rect.height } );
523 }
524
525 //OK, the display bounds are between min and max, which
526 //is spread across rect.height. Draw the line at the proper place.
527 if (zeroLevelYCoordinate >= rect.GetTop() &&
528 zeroLevelYCoordinate <= rect.GetBottom()) {
529 dc.SetPen(*wxBLACK_PEN);
530 AColor::Line(dc, rect.x, zeroLevelYCoordinate,
531 rect.x + rect.width - 1, zeroLevelYCoordinate);
532 }
533 }
534
535 struct WavePortion {
536 wxRect rect;
537 double averageZoom;
538 bool inFisheye;
539 WavePortion(int x, int y, int w, int h, double zoom, bool i)
540 : rect(x, y, w, h), averageZoom(zoom), inFisheye(i)
541 {}
542 };
543
544 void FindWavePortions
545 (std::vector<WavePortion> &portions, const wxRect &rect, const ZoomInfo &zoomInfo,
546 const ClipParameters &params)
547 {
548 // If there is no fisheye, then only one rectangle has nonzero width.
549 // If there is a fisheye, make rectangles for before and after
550 // (except when they are squeezed to zero width), and at least one for inside
551 // the fisheye.
552
553 const auto intervals = zoomInfo.FindIntervals(rect.width, rect.x);
554 ZoomInfo::Intervals::const_iterator it = intervals.begin(), end = intervals.end(), prev;
555 wxASSERT(it != end && it->position == rect.x);
556 const int rightmost = rect.x + rect.width;
557 for (int left = rect.x; left < rightmost;) {
558 while (it != end && it->position <= left)
559 prev = it++;
560 if (it == end)
561 break;
562 const int right = std::max(left, (int)(it->position));
563 const int width = right - left;
564 if (width > 0)
565 portions.push_back(
566 WavePortion(left, rect.y, width, rect.height,
567 prev->averageZoom, prev->inFisheye)
568 );
569 left = right;
570 }
571 }
572
573 void DrawIndividualSamples(TrackPanelDrawingContext &context,
574 int leftOffset, const wxRect &rect,
575 float zoomMin, float zoomMax,
576 bool dB, float dBRange,
577 const WaveChannelInterval &clip,
578 bool showPoints, bool muted,
579 bool highlight)
580 {
581 const Envelope &envelope = clip.GetEnvelope();
582 auto &dc = context.dc;
583 const auto artist = TrackArtist::Get(context);
584 const auto &zoomInfo = *artist->pZoomInfo;
585
586 const double toffset = clip.GetPlayStartTime();
587 const double rate = clip.GetRate() / clip.GetStretchRatio();
588 const double t0 = std::max(0.0, zoomInfo.PositionToTime(0, -leftOffset) - toffset);
589 const auto s0 = sampleCount(floor(t0 * rate));
590 const auto snSamples = clip.GetVisibleSampleCount();
591 if (s0 > snSamples)
592 return;
593
594 const double t1 = zoomInfo.PositionToTime(rect.width - 1, -leftOffset) - toffset;
595 const auto s1 = sampleCount(ceil(t1 * rate));
596
597 // Assume size_t will not overflow, else we wouldn't be here drawing the
598 // few individual samples
599 auto slen = std::min(snSamples - s0, s1 - s0 + 1).as_size_t();
600
601 if (slen <= 0)
602 return;
603
604 Floats buffer{ size_t(slen) };
605 clip.GetSamples((samplePtr)buffer.get(), floatSample, s0, slen,
606 // Suppress exceptions in this drawing operation:
607 false);
608
609 ArrayOf<int> xpos{ size_t(slen) };
610 ArrayOf<int> ypos{ size_t(slen) };
611 ArrayOf<int> clipped;
612 int clipcnt = 0;
613
614 const auto bShowClipping = ShowClippingPref().Read();
615 if (bShowClipping)
616 clipped.reinit( size_t(slen) );
617
618 const auto &muteSamplePen = artist->muteSamplePen;
619 const auto &samplePen = artist->samplePen;
620 auto &pen = highlight ? AColor::uglyPen : muted ? muteSamplePen : samplePen;
621 dc.SetPen( pen );
622
623 for (decltype(slen) s = 0; s < slen; s++) {
624 const double time = toffset + (s + s0).as_double() / rate;
625 const int xx = // An offset into the rectangle rect
626 std::max(-10000, std::min(10000,
627 (int)(zoomInfo.TimeToPosition(time, -leftOffset))));
628 xpos[s] = xx;
629
630 // Calculate sample as it would be rendered, so quantize time
631 double value = envelope.GetValue(time, 1.0 / clip.GetRate());
632 const double tt = buffer[s] * value;
633
634 if (clipped && bShowClipping && ((tt <= -MAX_AUDIO) || (tt >= MAX_AUDIO)))
635 clipped[clipcnt++] = xx;
636 ypos[s] =
637 std::max(-1,
638 std::min(rect.height,
639 GetWaveYPos(tt, zoomMin, zoomMax,
640 rect.height, dB, true, dBRange, false)));
641 }
642
643
644 if (showPoints) {
645 // Draw points where spacing is enough
646 const auto bigPoints = artist->bigPoints;
647 const int tickSize = bigPoints ? 4 : 3;// Bigger ellipses when draggable.
648 wxRect pr;
649 pr.width = tickSize;
650 pr.height = tickSize;
651 //different colour when draggable.
652 const auto &dragsampleBrush = artist->dragsampleBrush;
653 const auto &sampleBrush = artist->sampleBrush;
654 auto &brush = highlight
655 ? AColor::uglyBrush
656 : bigPoints ? dragsampleBrush : sampleBrush;
657 dc.SetBrush( brush );
658 for (decltype(slen) s = 0; s < slen; s++) {
659 if (ypos[s] >= 0 && ypos[s] < rect.height) {
660 pr.x = rect.x + xpos[s] - tickSize/2;
661 pr.y = rect.y + ypos[s] - tickSize/2;
662 dc.DrawEllipse(pr);
663 }
664 }
665 }
666
667 const auto sampleDisplay = artist->mSampleDisplay;
668 if (showPoints &&
669 (sampleDisplay == (int) WaveChannelViewConstants::StemPlot)
670 ){
671 // Draw vertical lines
672 int yZero = GetWaveYPos(0.0, zoomMin, zoomMax, rect.height, dB, true, dBRange, false);
673 yZero = rect.y + std::max(-1, std::min(rect.height, yZero));
674 for (decltype(slen) s = 0; s < slen; s++) {
675 AColor::Line(dc,
676 rect.x + xpos[s], rect.y + ypos[s],
677 rect.x + xpos[s], yZero);
678 }
679 }
680 else {
681 // Connect samples with straight lines
682 for (decltype(slen) s = 0; s < slen - 1; s++) {
683 AColor::Line(dc,
684 rect.x + xpos[s], rect.y + ypos[s],
685 rect.x + xpos[s + 1], rect.y + ypos[s + 1]);
686 }
687 }
688
689 // Draw clipping
690 if (clipcnt) {
691 const auto &muteClippedPen = artist->muteClippedPen;
692 const auto &clippedPen = artist->clippedPen;
693 dc.SetPen(muted ? muteClippedPen : clippedPen);
694 while (--clipcnt >= 0) {
695 auto s = clipped[clipcnt];
696 AColor::Line(dc, rect.x + s, rect.y, rect.x + s, rect.y + rect.height);
697 }
698 }
699 }
700
701 void DrawEnvLine(
702 TrackPanelDrawingContext &context,
703 const wxRect &rect, int x0, int y0, int cy, bool top )
704 {
705 auto &dc = context.dc;
706
707 int xx = rect.x + x0;
708 int yy = rect.y + cy;
709
710 if (y0 < 0) {
711 if (x0 % 4 != 3) {
712 AColor::Line(dc, xx, yy, xx, yy + 3);
713 }
714 }
715 else if (y0 > rect.height) {
716 if (x0 % 4 != 3) {
717 AColor::Line(dc, xx, yy - 3, xx, yy);
718 }
719 }
720 else {
721 if (top) {
722 AColor::Line(dc, xx, yy, xx, yy + 3);
723 }
724 else {
725 AColor::Line(dc, xx, yy - 3, xx, yy);
726 }
727 }
728 }
729
730 void DrawEnvelope(TrackPanelDrawingContext &context,
731 const wxRect &rect, const double env[],
732 float zoomMin, float zoomMax,
733 bool dB, float dBRange, bool highlight)
734 {
735 auto &dc = context.dc;
736
737 int h = rect.height;
738
739 auto &pen = highlight ? AColor::uglyPen : AColor::envelopePen;
740 dc.SetPen( pen );
741
742 for (int x0 = 0; x0 < rect.width; ++x0) {
743 int cenvTop = GetWaveYPos(env[x0], zoomMin, zoomMax,
744 h, dB, true, dBRange, true);
745
746 int cenvBot = GetWaveYPos(-env[x0], zoomMin, zoomMax,
747 h, dB, true, dBRange, true);
748
749 int envTop = GetWaveYPos(env[x0], zoomMin, zoomMax,
750 h, dB, true, dBRange, false);
751
752 int envBot = GetWaveYPos(-env[x0], zoomMin, zoomMax,
753 h, dB, true, dBRange, false);
754
755 // Make the collision at zero actually look solid
756 if (cenvBot - cenvTop < 9) {
757 int value = (int)((zoomMax / (zoomMax - zoomMin)) * h);
758 cenvTop = value - 4;
759 cenvBot = value + 4;
760 }
761
762 DrawEnvLine( context, rect, x0, envTop, cenvTop, true );
763 DrawEnvLine( context, rect, x0, envBot, cenvBot, false );
764 }
765 }
766
767 // Headers needed only for experimental drawing below
768 //#include "tracks/playabletrack/wavetrack/ui/SampleHandle.h"
769 //#include "tracks/ui/EnvelopeHandle.h"
770 void DrawClipWaveform(TrackPanelDrawingContext &context,
771 const WaveChannel &channel, const WaveChannelInterval &clip,
772 const wxRect &rect, bool dB, bool muted, bool selected)
773 {
774 const Envelope &envelope = clip.GetEnvelope();
775 auto &dc = context.dc;
776 const auto artist = TrackArtist::Get(context);
777 const auto &selectedRegion = *artist->pSelectedRegion;
778 const auto &zoomInfo = *artist->pZoomInfo;
779
780 auto sw = FrameStatistics::CreateStopwatch(FrameStatistics::SectionID::WaveformView);
781
782 bool highlightEnvelope = false;
783 #ifdef EXPERIMENTAL_TRACK_PANEL_HIGHLIGHTING
784 auto target = dynamic_cast<EnvelopeHandle*>(context.target.get());
785 highlightEnvelope = target && target->GetEnvelope() == &envelope;
786 #endif
787
788 //If clip is "too small" draw a placeholder instead of
789 //attempting to fit the contents into a few pixels
790 if (!WaveChannelView::ClipDetailsVisible(clip, zoomInfo, rect))
791 {
792 auto clipRect = ClipParameters::GetClipRect(clip, zoomInfo, rect);
793 TrackArt::DrawClipFolded(dc, clipRect);
794 return;
795 }
796
797 const ClipParameters params { clip, rect, zoomInfo };
798 const wxRect &hiddenMid = params.hiddenMid;
799 // The "hiddenMid" rect contains the part of the display actually
800 // containing the waveform, as it appears without the fisheye. If it's empty, we're done.
801 if (hiddenMid.width <= 0) {
802 return;
803 }
804
805 const double &t0 = params.t0;
806 const double &t1 = params.t1;
807 const double playStartTime = clip.GetPlayStartTime();
808 const double &trackRectT0 = params.trackRectT0;
809 const double &averagePixelsPerSecond = params.averagePixelsPerSecond;
810 const double sampleRate = clip.GetRate();
811 const double stretchRatio = clip.GetStretchRatio();
812 double leftOffset = params.leftOffset;
813 const wxRect &mid = params.mid;
814
815 auto &settings = WaveformSettings::Get(channel);
816 const float dBRange = settings.dBRange;
817
818 dc.SetPen(*wxTRANSPARENT_PEN);
819 int iColorIndex = WaveColorAttachment::Get(clip).GetColorIndex();
820 artist->SetColours( iColorIndex );
821
822 // The bounds (controlled by vertical zooming; -1.0...1.0
823 // by default)
824 float zoomMin, zoomMax;
825 auto &cache = WaveformScale::Get(channel);
826 cache.GetDisplayBounds(zoomMin, zoomMax);
827
828 std::vector<double> vEnv(mid.width);
829 double *const env = &vEnv[0];
830 CommonChannelView::GetEnvelopeValues(envelope, playStartTime,
831
832 // PRL: change back to make envelope evaluate only at sample times
833 // and then interpolate the display
834 0, // 1.0 / sampleRate,
835
836 env, mid.width, leftOffset, zoomInfo);
837
838 // Draw the background of the track, outlining the shape of
839 // the envelope and using a colored pen for the selected
840 // part of the waveform
841 {
842 double tt0, tt1;
843 const auto &track = channel.GetTrack();
844 if (SyncLock::IsSelectedOrSyncLockSelected(track)) {
845 tt0 = track.SnapToSample(selectedRegion.t0());
846 tt1 = track.SnapToSample(selectedRegion.t1());
847 }
848 else
849 tt0 = tt1 = 0.0;
850 DrawWaveformBackground(context, leftOffset, mid,
851 env,
852 zoomMin, zoomMax,
853 cache.ZeroLevelYCoordinate(mid),
854 dB, dBRange,
855 tt0, tt1,
856 !track.GetSelected(), highlightEnvelope);
857 }
858
859 // Require at least 1/2 pixel per sample for drawing individual samples.
860 const double threshold1 = 0.5 * sampleRate / stretchRatio;
861 // Require at least 3 pixels per sample for drawing the draggable points.
862 const double threshold2 = 3 * sampleRate / stretchRatio;
863
864 bool highlight = false;
865 #ifdef EXPERIMENTAL_TRACK_PANEL_HIGHLIGHTING
866 auto target = dynamic_cast<SampleHandle*>(context.target.get());
867 highlight = target && target->FindChannel().get() == &track;
868 #endif
869
870 const bool showIndividualSamples = zoomInfo.GetZoom() > threshold1;
871 const bool showPoints = zoomInfo.GetZoom() > threshold2;
872
873 if(!showIndividualSamples)
874 {
875 DrawWaveform(
876 context, channel.GetTrack(), clip, leftOffset, t0, t1,
877 rect, zoomMin, zoomMax, dB, dBRange, muted);
878 }
879 else
880 {
881 std::vector<WavePortion> portions;
882 FindWavePortions(portions, rect, zoomInfo, params);
883 auto offset = leftOffset;
884 for(const auto& portion : portions)
885 {
886 assert(!portion.inFisheye && portion.averageZoom > threshold1);
887 if(portion.inFisheye || portion.averageZoom <= threshold1)
888 continue;
889
890 wxRect rectPortion = portion.rect;
891 rectPortion.Intersect(mid);
892 DrawIndividualSamples(
893 context, offset, rectPortion, zoomMin, zoomMax, dB, dBRange, clip,
894 showPoints, muted, highlight);
895 offset += rectPortion.width;
896 }
897
898 }
899
900 const auto drawEnvelope = artist->drawEnvelope;
901 if (drawEnvelope) {
902 DrawEnvelope(
903 context, mid, env, zoomMin, zoomMax, dB, dBRange, highlightEnvelope);
904 EnvelopeEditor::DrawPoints(envelope,
905 context, mid, dB, dBRange, zoomMin, zoomMax, true, rect.x - mid.x);
906 }
907
908 // Draw arrows on the left side if the track extends to the left of the
909 // beginning of time. :)
910 if (trackRectT0 == 0.0 && playStartTime < 0.0)
911 {
912 TrackArt::DrawNegativeOffsetTrackArrows( context, rect );
913 }
914 {
915 auto clipRect = ClipParameters::GetClipRect(clip, zoomInfo, rect);
916 TrackArt::DrawClipEdges(dc, clipRect, selected);
917 }
918 }
919
920 void DrawTimeSlider( TrackPanelDrawingContext &context,
921 const wxRect & rect,
922 bool rightwards, bool highlight )
923 {
924 auto &dc = context.dc;
925
926 const int border = 3; // 3 pixels all round.
927 const int width = 6; // width of the drag box.
928 const int taper = 6; // how much the box tapers by.
929 const int barSpacing = 4; // how far apart the bars are.
930 const int barWidth = 3;
931 const int xFlat = 3;
932
933 //Enough space to draw in?
934 if (rect.height <= ((taper+border + barSpacing) * 2)) {
935 return;
936 }
937 if (rect.width <= (width * 2 + border * 3)) {
938 return;
939 }
940
941 // The draggable box is tapered towards the direction you drag it.
942 int leftTaper = rightwards ? 0 : 6;
943 int rightTaper = rightwards ? 6 : 0;
944
945 int xLeft = rightwards ? (rect.x + border - 2)
946 : (rect.x + rect.width + 1 - (border + width));
947 int yTop = rect.y + border;
948 int yBot = rect.y + rect.height - border - 1;
949
950 AColor::Light(&dc, false, highlight);
951 AColor::Line(dc, xLeft, yBot - leftTaper, xLeft, yTop + leftTaper);
952 AColor::Line(dc, xLeft, yTop + leftTaper, xLeft + xFlat, yTop);
953 AColor::Line(dc, xLeft + xFlat, yTop, xLeft + width, yTop + rightTaper);
954
955 AColor::Dark(&dc, false, highlight);
956 AColor::Line(dc, xLeft + width, yTop + rightTaper, xLeft + width, yBot - rightTaper);
957 AColor::Line(dc, xLeft + width, yBot - rightTaper, xLeft + width-xFlat, yBot);
958 AColor::Line(dc, xLeft + width - xFlat, yBot, xLeft, yBot - leftTaper);
959
960 int firstBar = yTop + taper + taper / 2;
961 int nBars = (yBot - yTop - taper * 3) / barSpacing + 1;
962 xLeft += (width - barWidth + 1) / 2;
963 int yy;
964 int i;
965
966 AColor::Light(&dc, false, highlight);
967 for (i = 0;i < nBars; i++) {
968 yy = firstBar + barSpacing * i;
969 AColor::Line(dc, xLeft, yy, xLeft + barWidth, yy);
970 }
971 AColor::Dark(&dc, false, highlight);
972 for(i = 0;i < nBars; i++){
973 yy = firstBar + barSpacing * i + 1;
974 AColor::Line(dc, xLeft, yy, xLeft + barWidth, yy);
975 }
976 }
977
978 }
979
980 // Header needed only for experimental drawing below
981 //#include "tracks/ui/TimeShiftHandle.h"
982 void WaveformView::DoDraw(TrackPanelDrawingContext &context,
983 const WaveChannel &channel,
984 const WaveTrack::Interval* selectedClip,
985 const wxRect& rect,
986 bool muted)
987 {
988 auto &dc = context.dc;
989 const auto artist = TrackArtist::Get( context );
990
991 bool highlight = false;
992 bool gripHit = false;
993 #ifdef EXPERIMENTAL_TRACK_PANEL_HIGHLIGHTING
994 auto target = dynamic_cast<TimeShiftHandle*>(context.target.get());
995 gripHit = target && target->IsGripHit();
996 highlight = target && target->FindTrack().get() ==
997 &static_cast<const Track &>(channel.GetChannelGroup());
998 #endif
999
1000 const bool dB = !WaveformSettings::Get(channel).isLinear();
1001
1002 const auto &blankSelectedBrush = artist->blankSelectedBrush;
1003 const auto &blankBrush = artist->blankBrush;
1004 TrackArt::DrawBackgroundWithSelection(
1005 context, rect, channel, blankSelectedBrush, blankBrush );
1006
1007 for (const auto &pInterval : channel.Intervals()) {
1008 bool selected = selectedClip &&
1009 selectedClip == &pInterval->GetClip();
1010 DrawClipWaveform(context, channel, *pInterval, rect, dB, muted, selected);
1011 }
1012 DrawBoldBoundaries(context, channel, rect);
1013
1014 const auto drawSliders = artist->drawSliders;
1015 if (drawSliders) {
1016 DrawTimeSlider( context, rect, true, highlight && gripHit ); // directed right
1017 DrawTimeSlider( context, rect, false, highlight && gripHit ); // directed left
1018 }
1019 }
1020
1021 void WaveformView::Draw(
1022 TrackPanelDrawingContext &context, const wxRect &rect, unsigned iPass )
1023 {
1024 if ( iPass == TrackArtist::PassTracks ) {
1025 const auto artist = TrackArtist::Get(context);
1026 const auto &pendingTracks = *artist->pPendingTracks;
1027 auto &dc = context.dc;
1028
1029 const auto pChannel = FindChannel();
1030 if (!pChannel)
1031 return;
1032 const auto &wc = static_cast<const WaveChannel&>(
1033 pendingTracks.SubstitutePendingChangedChannel(*pChannel));
1034
1035 const auto hasSolo = artist->hasSolo;
1036 bool muted = (hasSolo || wc.GetTrack().GetMute()) &&
1037 !wc.GetTrack().GetSolo();
1038
1039 #if defined(__WXMAC__)
1040 wxAntialiasMode aamode = dc.GetGraphicsContext()->GetAntialiasMode();
1041 dc.GetGraphicsContext()->SetAntialiasMode(wxANTIALIAS_NONE);
1042 #endif
1043
1044 auto waveChannelView = GetWaveChannelView().lock();
1045 wxASSERT(waveChannelView.use_count());
1046
1047 auto selectedClip = waveChannelView->GetSelectedClip();
1048 DoDraw(context, wc, selectedClip.get(), rect, muted);
1049
1050 #if defined(__WXMAC__)
1051 dc.GetGraphicsContext()->SetAntialiasMode(aamode);
1052 #endif
1053 }
1054 WaveChannelSubView::Draw(context, rect, iPass);
1055 }
1056
1057 static const WaveChannelSubViews::RegisteredFactory key{
1058 [](WaveChannelView &view) {
1059 return std::make_shared<WaveformView>( view );
1060 }
1061 };
1062
1063 // The following attaches the wave color sub-menu to the wave track popup
1064 // menu. It is appropriate only to waveform view and so is kept in this
1065 // source file with the rest of the waveform view implementation.
1066
1067 #include <mutex> // for std::call_once
1068 #include "WaveTrackControls.h"
1069 #include "../../../../widgets/PopupMenuTable.h"
1070 #include "ProjectAudioIO.h"
1071 #include "ProjectHistory.h"
1072 #include "../../../../RefreshCode.h"
1073
1074 //=============================================================================
1075 // Table class for a sub-menu
1076 struct WaveColorMenuTable : PopupMenuTable
1077 {
1078 WaveColorMenuTable() : PopupMenuTable{ "WaveColor", XO("&Wave Color") } {}
1079 DECLARE_POPUP_MENU(WaveColorMenuTable);
1080
1081 static WaveColorMenuTable &Instance();
1082
1083 void InitUserData(void *pUserData) override;
1084
1085 PlayableTrackControls::InitMenuData *mpData{};
1086
1087 int IdOfWaveColor(int WaveColor);
1088 void OnWaveColorChange(wxCommandEvent & event);
1089
1090 int OnInstrument1ID, OnInstrument2ID, OnInstrument3ID, OnInstrument4ID;
1091 };
1092
1093 WaveColorMenuTable &WaveColorMenuTable::Instance()
1094 {
1095 static WaveColorMenuTable instance;
1096 return instance;
1097 }
1098
1099 void WaveColorMenuTable::InitUserData(void *pUserData)
1100 {
1101 mpData = static_cast<PlayableTrackControls::InitMenuData*>(pUserData);
1102 }
1103
1104 namespace {
1105 using ValueFinder = std::function< int( WaveTrack& ) >;
1106
1107 const TranslatableString GetWaveColorStr(int colorIndex)
1108 {
1109 return XXO("Instrument %i").Format( colorIndex+1 );
1110 }
1111 }
1112
1113 BEGIN_POPUP_MENU(WaveColorMenuTable)
1114 static const auto fn = []( PopupMenuHandler &handler, wxMenu &menu, int id ){
1115 auto &me = static_cast<WaveColorMenuTable&>( handler );
1116 auto pData = me.mpData;
1117 const auto &track = static_cast<WaveTrack&>(pData->track);
1118 auto &project = pData->project;
1119 bool unsafe = ProjectAudioIO::Get( project ).IsAudioActive();
1120
1121 menu.Check(id, id == me.IdOfWaveColor(
1122 WaveformAppearance::Get(track).GetColorIndex()));
1123 menu.Enable( id, !unsafe );
1124 };
1125
1126 static std::once_flag flag;
1127 std::call_once( flag, [this]{
1128 auto &hostTable = GetWaveTrackMenuTable();
1129 OnInstrument1ID = hostTable.ReserveId();
1130 OnInstrument2ID = hostTable.ReserveId();
1131 OnInstrument3ID = hostTable.ReserveId();
1132 OnInstrument4ID = hostTable.ReserveId();
1133 } );
1134
1135 AppendRadioItem( "Instrument1", OnInstrument1ID,
1136 GetWaveColorStr(0), POPUP_MENU_FN( OnWaveColorChange ), fn );
1137 AppendRadioItem( "Instrument2", OnInstrument2ID,
1138 GetWaveColorStr(1), POPUP_MENU_FN( OnWaveColorChange ), fn );
1139 AppendRadioItem( "Instrument3", OnInstrument3ID,
1140 GetWaveColorStr(2), POPUP_MENU_FN( OnWaveColorChange ), fn );
1141 AppendRadioItem( "Instrument4", OnInstrument4ID,
1142 GetWaveColorStr(3), POPUP_MENU_FN( OnWaveColorChange ), fn );
1143
1144 END_POPUP_MENU()
1145
1146 /// Converts a WaveColor enumeration to a wxWidgets menu item Id.
1147 int WaveColorMenuTable::IdOfWaveColor(int WaveColor)
1148 { return OnInstrument1ID + WaveColor;}
1149
1150 /// Handles the selection from the WaveColor submenu of the
1151 /// track menu.
1152 void WaveColorMenuTable::OnWaveColorChange(wxCommandEvent & event)
1153 {
1154 int id = event.GetId();
1155 wxASSERT(id >= OnInstrument1ID && id <= OnInstrument4ID);
1156 auto &track = static_cast<WaveTrack&>(mpData->track);
1157
1158 int newWaveColor = id - OnInstrument1ID;
1159
1160 AudacityProject *const project = &mpData->project;
1161
1162 WaveformAppearance::Get(track).SetColorIndex(newWaveColor);
1163
1164 ProjectHistory::Get( *project )
1165 .PushState(XO("Changed '%s' to %s")
1166 .Format(track.GetName(), GetWaveColorStr(newWaveColor)),
1167 XO("WaveColor Change"));
1168
1169 using namespace RefreshCode;
1170 mpData->result = RefreshAll | FixScrollbars;
1171 }
1172
1173 namespace {
1174 PopupMenuTable::AttachedItem sAttachment{
1175 GetWaveTrackMenuTable(),
1176 { "SubViews/Extra" },
1177 std::make_unique<PopupMenuSection>( "WaveColor",
1178 // Conditionally add sub-menu for wave color, if showing waveform
1179 PopupMenuTable::Adapt<WaveTrackPopupMenuTable>(
1180 [](WaveTrackPopupMenuTable &table) {
1181 const auto pTrack = &table.FindWaveTrack();
1182 const auto &view = WaveChannelView::GetFirst(*pTrack);
1183 const auto displays = view.GetDisplays();
1184 bool hasWaveform = (displays.end() != std::find(
1185 displays.begin(), displays.end(),
1186 WaveChannelSubView::Type{
1187 WaveChannelViewConstants::Waveform, {} }
1188 ) );
1189 return hasWaveform
1190 ? Registry::Indirect(WaveColorMenuTable::Instance()
1191 .Get(table.mpData))
1192 : nullptr;
1193 } ) )
1194 };
1195
1196 }
1197
1198 static WaveClip::Attachments::RegisteredFactory sKeyW{ [](WaveClip&) {
1199 return std::make_unique<WaveformPainter>();
1200 } };
1201
1202 WaveformPainter &WaveformPainter::Get( const WaveClip &clip )
1203 {
1204 return const_cast< WaveClip& >( clip ) // Consider it mutable data
1205 .Attachments::Get<WaveformPainter>(sKeyW).EnsureClip(clip);
1206 }