1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*-  vi:set ts=8 sts=4 sw=4: */
2 
3 /*
4     Sonic Visualiser
5     An audio file viewer and annotation editor.
6     Centre for Digital Music, Queen Mary, University of London.
7     This file copyright 2006 Chris Cannam.
8 
9     This program is free software; you can redistribute it and/or
10     modify it under the terms of the GNU General Public License as
11     published by the Free Software Foundation; either version 2 of the
12     License, or (at your option) any later version.  See the file
13     COPYING included with this distribution for more information.
14 */
15 
16 #include "View.h"
17 #include "layer/Layer.h"
18 #include "data/model/Model.h"
19 #include "base/ZoomConstraint.h"
20 #include "base/Profiler.h"
21 #include "base/Pitch.h"
22 #include "base/Preferences.h"
23 #include "base/HitCount.h"
24 #include "ViewProxy.h"
25 
26 #include "layer/TimeRulerLayer.h"
27 #include "layer/SingleColourLayer.h"
28 #include "layer/PaintAssistant.h"
29 
30 #include "data/model/RelativelyFineZoomConstraint.h"
31 #include "data/model/RangeSummarisableTimeValueModel.h"
32 
33 #include "widgets/IconLoader.h"
34 
35 #include <QPainter>
36 #include <QPaintEvent>
37 #include <QRect>
38 #include <QApplication>
39 #include <QProgressDialog>
40 #include <QTextStream>
41 #include <QFont>
42 #include <QMessageBox>
43 #include <QPushButton>
44 #include <QSettings>
45 #include <QSvgGenerator>
46 
47 #include <iostream>
48 #include <cassert>
49 #include <cmath>
50 
51 //#define DEBUG_VIEW 1
52 //#define DEBUG_VIEW_WIDGET_PAINT 1
53 //#define DEBUG_PROGRESS_STUFF 1
54 //#define DEBUG_VIEW_SCALE_CHOICE 1
55 
View(QWidget * w,bool showProgress)56 View::View(QWidget *w, bool showProgress) :
57     QFrame(w),
58     m_id(getNextId()),
59     m_centreFrame(0),
60     m_zoomLevel(ZoomLevel::FramesPerPixel, 1024),
61     m_followPan(true),
62     m_followZoom(true),
63     m_followPlay(PlaybackScrollPageWithCentre),
64     m_followPlayIsDetached(false),
65     m_playPointerFrame(0),
66     m_showProgress(showProgress),
67     m_cache(nullptr),
68     m_buffer(nullptr),
69     m_cacheValid(false),
70     m_cacheCentreFrame(0),
71     m_cacheZoomLevel(ZoomLevel::FramesPerPixel, 1024),
72     m_selectionCached(false),
73     m_deleting(false),
74     m_haveSelectedLayer(false),
75     m_useAligningProxy(false),
76     m_alignmentProgressBar({ {}, nullptr }),
77     m_manager(nullptr),
78     m_propertyContainer(new ViewPropertyContainer(this))
79 {
80 //    SVCERR << "View::View[" << getId() << "]" << endl;
81 }
82 
~View()83 View::~View()
84 {
85 //    SVCERR << "View::~View[" << getId() << "]" << endl;
86 
87     m_deleting = true;
88     delete m_propertyContainer;
89     delete m_cache;
90     delete m_buffer;
91 }
92 
93 PropertyContainer::PropertyList
getProperties() const94 View::getProperties() const
95 {
96     PropertyContainer::PropertyList list;
97     list.push_back("Global Scroll");
98     list.push_back("Global Zoom");
99     list.push_back("Follow Playback");
100     return list;
101 }
102 
103 QString
getPropertyLabel(const PropertyName & pn) const104 View::getPropertyLabel(const PropertyName &pn) const
105 {
106     if (pn == "Global Scroll") return tr("Global Scroll");
107     if (pn == "Global Zoom") return tr("Global Zoom");
108     if (pn == "Follow Playback") return tr("Follow Playback");
109     return "";
110 }
111 
112 PropertyContainer::PropertyType
getPropertyType(const PropertyContainer::PropertyName & name) const113 View::getPropertyType(const PropertyContainer::PropertyName &name) const
114 {
115     if (name == "Global Scroll") return PropertyContainer::ToggleProperty;
116     if (name == "Global Zoom") return PropertyContainer::ToggleProperty;
117     if (name == "Follow Playback") return PropertyContainer::ValueProperty;
118     return PropertyContainer::InvalidProperty;
119 }
120 
121 int
getPropertyRangeAndValue(const PropertyContainer::PropertyName & name,int * min,int * max,int * deflt) const122 View::getPropertyRangeAndValue(const PropertyContainer::PropertyName &name,
123                                int *min, int *max, int *deflt) const
124 {
125     if (deflt) *deflt = 1;
126     if (name == "Global Scroll") return m_followPan;
127     if (name == "Global Zoom") return m_followZoom;
128     if (name == "Follow Playback") {
129         if (min) *min = 0;
130         if (max) *max = 2;
131         if (deflt) *deflt = int(PlaybackScrollPageWithCentre);
132         switch (m_followPlay) {
133         case PlaybackScrollContinuous: return 0;
134         case PlaybackScrollPageWithCentre: case PlaybackScrollPage: return 1;
135         case PlaybackIgnore: return 2;
136         }
137     }
138     if (min) *min = 0;
139     if (max) *max = 0;
140     if (deflt) *deflt = 0;
141     return 0;
142 }
143 
144 QString
getPropertyValueLabel(const PropertyContainer::PropertyName & name,int value) const145 View::getPropertyValueLabel(const PropertyContainer::PropertyName &name,
146                             int value) const
147 {
148     if (name == "Follow Playback") {
149         switch (value) {
150         default:
151         case 0: return tr("Scroll");
152         case 1: return tr("Page");
153         case 2: return tr("Off");
154         }
155     }
156     return tr("<unknown>");
157 }
158 
159 void
setProperty(const PropertyContainer::PropertyName & name,int value)160 View::setProperty(const PropertyContainer::PropertyName &name, int value)
161 {
162     if (name == "Global Scroll") {
163         setFollowGlobalPan(value != 0);
164     } else if (name == "Global Zoom") {
165         setFollowGlobalZoom(value != 0);
166     } else if (name == "Follow Playback") {
167         switch (value) {
168         default:
169         case 0: setPlaybackFollow(PlaybackScrollContinuous); break;
170         case 1: setPlaybackFollow(PlaybackScrollPageWithCentre); break;
171         case 2: setPlaybackFollow(PlaybackIgnore); break;
172         }
173     }
174 }
175 
176 int
getPropertyContainerCount() const177 View::getPropertyContainerCount() const
178 {
179     return int(m_fixedOrderLayers.size()) + 1; // the 1 is for me
180 }
181 
182 const PropertyContainer *
getPropertyContainer(int i) const183 View::getPropertyContainer(int i) const
184 {
185     return (const PropertyContainer *)(((View *)this)->
186                                        getPropertyContainer(i));
187 }
188 
189 PropertyContainer *
getPropertyContainer(int i)190 View::getPropertyContainer(int i)
191 {
192     if (i == 0) return m_propertyContainer;
193     return m_fixedOrderLayers[i-1];
194 }
195 
196 bool
getVisibleExtentsForUnit(QString unit,double & min,double & max,bool & log) const197 View::getVisibleExtentsForUnit(QString unit,
198                                double &min, double &max,
199                                bool &log) const
200 {
201 #ifdef DEBUG_VIEW_SCALE_CHOICE
202     SVCERR << "View[" << getId() << "]::getVisibleExtentsForUnit("
203            << unit << ")" << endl;
204 #endif
205 
206     Layer *layer = getScaleProvidingLayerForUnit(unit);
207 
208     QString layerUnit;
209     double layerMin, layerMax;
210 
211     if (!layer) {
212 #ifdef DEBUG_VIEW_SCALE_CHOICE
213         SVCERR << "View[" << getId() << "]::getVisibleExtentsForUnit("
214                << unit << "): No scale-providing layer for this unit, "
215                << "taking union of extents of layers with this unit" << endl;
216 #endif
217         bool haveAny = false;
218         bool layerLog;
219         for (auto i = m_layerStack.rbegin(); i != m_layerStack.rend(); ++i) {
220             Layer *layer = *i;
221             if (layer->getValueExtents(layerMin, layerMax,
222                                        layerLog, layerUnit)) {
223                 if (unit.toLower() != layerUnit.toLower()) {
224                     continue;
225                 }
226                 if (!haveAny || layerMin < min) {
227                     min = layerMin;
228                 }
229                 if (!haveAny || layerMax > max) {
230                     max = layerMax;
231                 }
232                 if (!haveAny || layerLog) {
233                     log = layerLog;
234                 }
235                 haveAny = true;
236             }
237         }
238         return haveAny;
239     }
240 
241     return (layer->getValueExtents(layerMin, layerMax, log, layerUnit) &&
242             layer->getDisplayExtents(min, max));
243 }
244 
245 Layer *
getScaleProvidingLayerForUnit(QString unit) const246 View::getScaleProvidingLayerForUnit(QString unit) const
247 {
248     // Return the layer which is used to provide the min/max/log for
249     // any auto-align layer of a given unit. This is also the layer
250     // that will draw the scale, if possible.
251     //
252     // The returned layer is
253     //
254     // - the topmost visible layer having that unit that is not also
255     // auto-aligning; or if there is no such layer,
256     //
257     // - the topmost layer of any visibility having that unit that is
258     // not also auto-aligning (because a dormant layer can still draw
259     // a scale, and it makes sense for layers aligned to it not to
260     // jump about when its visibility is toggled); or if there is no
261     // such layer,
262     //
263     // - none
264 
265     Layer *dormantOption = nullptr;
266 
267     for (auto i = m_layerStack.rbegin(); i != m_layerStack.rend(); ++i) {
268 
269         Layer *layer = *i;
270 
271 #ifdef DEBUG_VIEW_SCALE_CHOICE
272         SVCERR << "View[" << getId() << "]::getScaleProvidingLayerForUnit("
273                << unit << "): Looking at layer " << layer
274                << " (" << layer->getLayerPresentationName() << ")" << endl;
275 #endif
276 
277         QString layerUnit;
278         double layerMin = 0.0, layerMax = 0.0;
279         bool layerLog = false;
280 
281         if (!layer->getValueExtents(layerMin, layerMax, layerLog, layerUnit)) {
282 #ifdef DEBUG_VIEW_SCALE_CHOICE
283             SVCERR << "... it has no value extents" << endl;
284 #endif
285             continue;
286         }
287 
288         if (layerUnit.toLower() != unit.toLower()) {
289 #ifdef DEBUG_VIEW_SCALE_CHOICE
290             SVCERR << "... it has the wrong unit (" << layerUnit << ")" << endl;
291 #endif
292             continue;
293         }
294 
295         double displayMin = 0.0, displayMax = 0.0;
296         if (!layer->getDisplayExtents(displayMin, displayMax)) {
297 #ifdef DEBUG_VIEW_SCALE_CHOICE
298             SVCERR << "... it has no display extents (is auto-aligning or not alignable)" << endl;
299 #endif
300             continue;
301         }
302 
303         if (layer->isLayerDormant(this)) {
304 #ifdef DEBUG_VIEW_SCALE_CHOICE
305             SVCERR << "... it's dormant" << endl;
306 #endif
307             if (!dormantOption) {
308                 dormantOption = layer;
309             }
310             continue;
311         }
312 
313 #ifdef DEBUG_VIEW_SCALE_CHOICE
314         SVCERR << "... it's good" << endl;
315 #endif
316         return layer;
317     }
318 
319     return dormantOption;
320 }
321 
322 bool
getVisibleExtentsForAnyUnit(double & min,double & max,bool & log,QString & unit) const323 View::getVisibleExtentsForAnyUnit(double &min, double &max,
324                                   bool &log, QString &unit) const
325 {
326     bool have = false;
327 
328     // Iterate in reverse order, so as to return display extents of
329     // topmost layer that fits the bill
330 
331     for (auto i = m_layerStack.rbegin(); i != m_layerStack.rend(); ++i) {
332 
333         Layer *layer = *i;
334 
335         if (layer->isLayerDormant(this)) {
336             continue;
337         }
338 
339         QString layerUnit;
340         double layerMin = 0.0, layerMax = 0.0;
341         bool layerLog = false;
342 
343         if (!layer->getValueExtents(layerMin, layerMax, layerLog, layerUnit)) {
344             continue;
345         }
346         if (layerUnit == "") {
347             continue;
348         }
349 
350         double displayMin = 0.0, displayMax = 0.0;
351 
352         if (layer->getDisplayExtents(displayMin, displayMax)) {
353 
354             min = displayMin;
355             max = displayMax;
356             log = layerLog;
357             unit = layerUnit;
358             have = true;
359             break;
360         }
361     }
362 
363     return have;
364 }
365 
366 int
getTextLabelYCoord(const Layer * layer,QPainter & paint) const367 View::getTextLabelYCoord(const Layer *layer, QPainter &paint) const
368 {
369     std::map<int, Layer *> sortedLayers;
370 
371     for (LayerList::const_iterator i = m_layerStack.begin();
372          i != m_layerStack.end(); ++i) {
373         if ((*i)->needsTextLabelHeight()) {
374             sortedLayers[(*i)->getExportId()] = *i;
375         }
376     }
377 
378     int y = scalePixelSize(15) + paint.fontMetrics().ascent();
379 
380     for (std::map<int, Layer *>::const_iterator i = sortedLayers.begin();
381          i != sortedLayers.end(); ++i) {
382         if (i->second == layer) break;
383         y += paint.fontMetrics().height();
384     }
385 
386     return y;
387 }
388 
389 void
propertyContainerSelected(View * client,PropertyContainer * pc)390 View::propertyContainerSelected(View *client, PropertyContainer *pc)
391 {
392     if (client != this) return;
393 
394     if (pc == m_propertyContainer) {
395         if (m_haveSelectedLayer) {
396             m_haveSelectedLayer = false;
397             update();
398         }
399         return;
400     }
401 
402     m_cacheValid = false;
403 
404     Layer *selectedLayer = nullptr;
405 
406     for (LayerList::iterator i = m_layerStack.begin(); i != m_layerStack.end(); ++i) {
407         if (*i == pc) {
408             selectedLayer = *i;
409             m_layerStack.erase(i);
410             break;
411         }
412     }
413 
414     if (selectedLayer) {
415         m_haveSelectedLayer = true;
416         m_layerStack.push_back(selectedLayer);
417         update();
418     } else {
419         m_haveSelectedLayer = false;
420     }
421 
422     emit propertyContainerSelected(pc);
423 }
424 
425 void
toolModeChanged()426 View::toolModeChanged()
427 {
428 //    SVDEBUG << "View::toolModeChanged(" << m_manager->getToolMode() << ")" << endl;
429 }
430 
431 void
overlayModeChanged()432 View::overlayModeChanged()
433 {
434     m_cacheValid = false;
435     update();
436 }
437 
438 void
zoomWheelsEnabledChanged()439 View::zoomWheelsEnabledChanged()
440 {
441     // subclass might override this
442 }
443 
444 sv_frame_t
getStartFrame() const445 View::getStartFrame() const
446 {
447     return getFrameForX(0);
448 }
449 
450 sv_frame_t
getEndFrame() const451 View::getEndFrame() const
452 {
453     return getFrameForX(width()) - 1;
454 }
455 
456 void
setStartFrame(sv_frame_t f)457 View::setStartFrame(sv_frame_t f)
458 {
459     setCentreFrame(f + sv_frame_t(round
460                                   (m_zoomLevel.pixelsToFrames(width() / 2))));
461 }
462 
463 bool
setCentreFrame(sv_frame_t f,bool e)464 View::setCentreFrame(sv_frame_t f, bool e)
465 {
466     bool changeVisible = false;
467 
468 #ifdef DEBUG_VIEW
469     SVCERR << "View[" << getId() << "]::setCentreFrame: from " << m_centreFrame
470            << " to " << f << endl;
471 #endif
472 
473     if (m_centreFrame != f) {
474 
475         sv_frame_t formerCentre = m_centreFrame;
476         m_centreFrame = f;
477 
478         if (m_zoomLevel.zone == ZoomLevel::PixelsPerFrame) {
479 
480 #ifdef DEBUG_VIEW
481             SVCERR << "View[" << getId() << "]::setCentreFrame: in PixelsPerFrame zone, so change must be visible" << endl;
482 #endif
483             update();
484             changeVisible = true;
485 
486         } else {
487 
488             int formerPixel = int(formerCentre / m_zoomLevel.level);
489             int newPixel = int(m_centreFrame / m_zoomLevel.level);
490 
491             if (newPixel != formerPixel) {
492 
493 #ifdef DEBUG_VIEW
494                 SVCERR << "View[" << getId() << "]::setCentreFrame: newPixel " << newPixel << ", formerPixel " << formerPixel << endl;
495 #endif
496                 // ensure the centre frame is a multiple of the zoom level
497                 m_centreFrame = sv_frame_t(newPixel) * m_zoomLevel.level;
498 
499 #ifdef DEBUG_VIEW
500                 SVCERR << "View[" << getId()
501                        << "]::setCentreFrame: centre frame rounded to "
502                        << m_centreFrame << " (zoom level is "
503                        << m_zoomLevel.level << ")" << endl;
504 #endif
505 
506                 update();
507                 changeVisible = true;
508             }
509         }
510 
511         if (e) {
512             sv_frame_t rf = alignToReference(m_centreFrame);
513 #ifdef DEBUG_VIEW
514             SVCERR << "View[" << getId() << "]::setCentreFrame(" << f
515                  << "): m_centreFrame = " << m_centreFrame
516                  << ", emitting centreFrameChanged with aligned frame "
517                  << rf << endl;
518 #endif
519             emit centreFrameChanged(rf, m_followPan, m_followPlay);
520         }
521     }
522 
523     return changeVisible;
524 }
525 
526 int
getXForFrame(sv_frame_t frame) const527 View::getXForFrame(sv_frame_t frame) const
528 {
529     // In FramesPerPixel mode, the pixel should be the one "covering"
530     // the given frame, i.e. to the "left" of it - not necessarily the
531     // nearest boundary.
532 
533     sv_frame_t level = m_zoomLevel.level;
534     sv_frame_t fdiff = frame - m_centreFrame;
535     int result = 0;
536 
537     bool inRange = false;
538     if (m_zoomLevel.zone == ZoomLevel::FramesPerPixel) {
539         inRange = ((fdiff / level) < sv_frame_t(INT_MAX) &&
540                    (fdiff / level) > sv_frame_t(INT_MIN));
541     } else {
542         inRange = (fdiff < sv_frame_t(INT_MAX) / level &&
543                    fdiff > sv_frame_t(INT_MIN) / level);
544     }
545 
546     if (inRange) {
547 
548         sv_frame_t adjusted;
549 
550         if (m_zoomLevel.zone == ZoomLevel::FramesPerPixel) {
551             sv_frame_t roundedCentreFrame = (m_centreFrame / level) * level;
552             fdiff = frame - roundedCentreFrame;
553             adjusted = fdiff / level;
554             if ((fdiff < 0) && ((fdiff % level) != 0)) {
555                 --adjusted; // round to the left
556             }
557         } else {
558             adjusted = fdiff * level;
559         }
560 
561         adjusted = adjusted + (width()/2);
562 
563         if (adjusted > INT_MAX || adjusted < INT_MIN) {
564             inRange = false;
565         } else {
566             result = int(adjusted);
567         }
568     }
569 
570     if (!inRange) {
571         SVCERR << "ERROR: Frame " << frame
572                << " is out of range in View::getXForFrame" << endl;
573         SVCERR << "ERROR: (centre frame = " << getCentreFrame() << ", fdiff = "
574                << fdiff << ", zoom level = " << m_zoomLevel << ")" << endl;
575         SVCERR << "ERROR: This is a logic error: getXForFrame should not be "
576                << "called for locations unadjacent to the current view"
577                << endl;
578         return 0;
579     }
580 
581 #ifdef DEBUG_VIEW
582     if (m_zoomLevel.zone == ZoomLevel::PixelsPerFrame) {
583         sv_frame_t reversed = getFrameForX(result);
584         if (reversed != frame) {
585             SVCERR << "View[" << getId() << "]::getXForFrame: WARNING: Converted frame " << frame << " to x " << result << " in PixelsPerFrame zone, but the reverse conversion gives frame " << reversed << " (error = " << reversed - frame << ")" << endl;
586             SVCERR << "(centre frame = " << getCentreFrame() << ", fdiff = "
587                    << fdiff << ", level = " << level << ", centre % level = "
588                    << (getCentreFrame() % level) << ", fdiff % level = "
589                    << (fdiff % level) << ", frame % level = "
590                    << (frame % level) << ", reversed % level = "
591                    << (reversed % level) << ")" << endl;
592         }
593     }
594 #endif
595 
596     return result;
597 }
598 
599 sv_frame_t
getFrameForX(int x) const600 View::getFrameForX(int x) const
601 {
602     // Note, this must always return a value that is on a zoom-level
603     // boundary - regardless of whether the nominal centre frame is on
604     // such a boundary or not. (It is legitimate for the centre frame
605     // not to be on a zoom-level boundary, because the centre frame
606     // may be shared with other views having different zoom levels.)
607 
608     // In FramesPerPixel mode, the frame returned for a given x should
609     // be the first for which getXForFrame(frame) == x; a corollary is
610     // that if the centre frame is not on a zoom-level boundary, then
611     // getFrameForX(x) should not return the centre frame for any x.
612 
613     // In PixelsPerFrame mode, the frame returned should be the one
614     // immediately left of the given pixel, not necessarily the
615     // nearest.
616 
617     int diff = x - (width()/2);
618     sv_frame_t level = m_zoomLevel.level;
619     sv_frame_t fdiff, result;
620 
621     if (m_zoomLevel.zone == ZoomLevel::FramesPerPixel) {
622         sv_frame_t roundedCentreFrame = (m_centreFrame / level) * level;
623         fdiff = diff * level;
624         result = fdiff + roundedCentreFrame;
625     } else {
626         fdiff = diff / level;
627         if ((diff < 0) && ((diff % level) != 0)) {
628             --fdiff; // round to the left
629         }
630         result = fdiff + m_centreFrame;
631     }
632 
633 #ifdef DEBUG_VIEW_WIDGET_PAINT
634 /*
635     if (x == 0) {
636         SVCERR << "getFrameForX(" << x << "): diff = " << diff << ", fdiff = "
637                << fdiff << ", m_centreFrame = " << m_centreFrame
638                << ", level = " << m_zoomLevel.level
639                << ", diff % level = " << (diff % m_zoomLevel.level)
640                << ", nominal " << fdiff + m_centreFrame
641                << ", will return " << result
642                << endl;
643     }
644 */
645 #endif
646 
647 #ifdef DEBUG_VIEW
648     if (m_zoomLevel.zone == ZoomLevel::FramesPerPixel) {
649         int reversed = getXForFrame(result);
650         if (reversed != x) {
651             SVCERR << "View[" << getId() << "]::getFrameForX: WARNING: Converted pixel " << x << " to frame " << result << " in FramesPerPixel zone, but the reverse conversion gives pixel " << reversed << " (error = " << reversed - x << ")" << endl;
652             SVCERR << "(centre frame = " << getCentreFrame()
653                    << ", width/2 = " << width()/2 << ", diff = " << diff
654                    << ", fdiff = " << fdiff << ", level = " << level
655                    << ", centre % level = " << (getCentreFrame() % level)
656                    << ", fdiff % level = " << (fdiff % level)
657                    << ", frame % level = " << (result % level) << ")" << endl;
658         }
659     }
660 #endif
661 
662     return result;
663 }
664 
665 double
getYForFrequency(double frequency,double minf,double maxf,bool logarithmic) const666 View::getYForFrequency(double frequency,
667                        double minf,
668                        double maxf,
669                        bool logarithmic) const
670 {
671     Profiler profiler("View::getYForFrequency");
672 
673     int h = height();
674 
675     if (logarithmic) {
676 
677         static double lastminf = 0.0, lastmaxf = 0.0;
678         static double logminf = 0.0, logmaxf = 0.0;
679 
680         if (lastminf != minf) {
681             lastminf = (minf == 0.0 ? 1.0 : minf);
682             logminf = log10(minf);
683         }
684         if (lastmaxf != maxf) {
685             lastmaxf = (maxf < lastminf ? lastminf : maxf);
686             logmaxf = log10(maxf);
687         }
688 
689         if (logminf == logmaxf) return 0;
690         return h - (h * (log10(frequency) - logminf)) / (logmaxf - logminf);
691 
692     } else {
693 
694         if (minf == maxf) return 0;
695         return h - (h * (frequency - minf)) / (maxf - minf);
696     }
697 }
698 
699 double
getFrequencyForY(double y,double minf,double maxf,bool logarithmic) const700 View::getFrequencyForY(double y,
701                        double minf,
702                        double maxf,
703                        bool logarithmic) const
704 {
705     double h = height();
706 
707     if (logarithmic) {
708 
709         static double lastminf = 0.0, lastmaxf = 0.0;
710         static double logminf = 0.0, logmaxf = 0.0;
711 
712         if (lastminf != minf) {
713             lastminf = (minf == 0.0 ? 1.0 : minf);
714             logminf = log10(minf);
715         }
716         if (lastmaxf != maxf) {
717             lastmaxf = (maxf < lastminf ? lastminf : maxf);
718             logmaxf = log10(maxf);
719         }
720 
721         if (logminf == logmaxf) return 0;
722         return pow(10.0, logminf + ((logmaxf - logminf) * (h - y)) / h);
723 
724     } else {
725 
726         if (minf == maxf) return 0;
727         return minf + ((h - y) * (maxf - minf)) / h;
728     }
729 }
730 
731 ZoomLevel
getZoomLevel() const732 View::getZoomLevel() const
733 {
734 #ifdef DEBUG_VIEW_WIDGET_PAINT
735 //        cout << "zoom level: " << m_zoomLevel << endl;
736 #endif
737     return m_zoomLevel;
738 }
739 
740 int
effectiveDevicePixelRatio() const741 View::effectiveDevicePixelRatio() const
742 {
743 #ifdef Q_OS_MAC
744     int dpratio = devicePixelRatio();
745     if (dpratio > 1) {
746         QSettings settings;
747         settings.beginGroup("Preferences");
748         if (!settings.value("scaledHiDpi", true).toBool()) {
749             dpratio = 1;
750         }
751         settings.endGroup();
752     }
753     return dpratio;
754 #else
755     return 1;
756 #endif
757 }
758 
759 void
setZoomLevel(ZoomLevel z)760 View::setZoomLevel(ZoomLevel z)
761 {
762 //!!!    int dpratio = effectiveDevicePixelRatio();
763 //    if (z < dpratio) return;
764 //    if (z < 1) z = 1;
765     if (m_zoomLevel == z) {
766         return;
767     }
768     m_zoomLevel = z;
769     emit zoomLevelChanged(z, m_followZoom);
770     update();
771 }
772 
773 bool
hasLightBackground() const774 View::hasLightBackground() const
775 {
776     bool darkPalette = false;
777     if (m_manager) darkPalette = m_manager->getGlobalDarkBackground();
778 
779     Layer::ColourSignificance maxSignificance = Layer::ColourAbsent;
780     bool mostSignificantHasDarkBackground = false;
781 
782     for (LayerList::const_iterator i = m_layerStack.begin();
783          i != m_layerStack.end(); ++i) {
784 
785         Layer::ColourSignificance s = (*i)->getLayerColourSignificance();
786         bool light = (*i)->hasLightBackground();
787 
788         if (int(s) > int(maxSignificance)) {
789             maxSignificance = s;
790             mostSignificantHasDarkBackground = !light;
791         } else if (s == maxSignificance && !light) {
792             mostSignificantHasDarkBackground = true;
793         }
794     }
795 
796     if (int(maxSignificance) >= int(Layer::ColourDistinguishes)) {
797         return !mostSignificantHasDarkBackground;
798     } else {
799         return !darkPalette;
800     }
801 }
802 
803 QColor
getBackground() const804 View::getBackground() const
805 {
806     bool light = hasLightBackground();
807 
808     QColor widgetbg = palette().window().color();
809     bool widgetLight =
810         (widgetbg.red() + widgetbg.green() + widgetbg.blue()) > 384;
811 
812     if (widgetLight == light) {
813         if (widgetLight) {
814             return widgetbg.lighter();
815         } else {
816             return widgetbg.darker();
817         }
818     }
819     else if (light) return Qt::white;
820     else return Qt::black;
821 }
822 
823 QColor
getForeground() const824 View::getForeground() const
825 {
826     bool light = hasLightBackground();
827 
828     QColor widgetfg = palette().text().color();
829     bool widgetLight =
830         (widgetfg.red() + widgetfg.green() + widgetfg.blue()) > 384;
831 
832     if (widgetLight != light) return widgetfg;
833     else if (light) return Qt::black;
834     else return Qt::white;
835 }
836 
837 void
addLayer(Layer * layer)838 View::addLayer(Layer *layer)
839 {
840     m_cacheValid = false;
841 
842     SingleColourLayer *scl = dynamic_cast<SingleColourLayer *>(layer);
843     if (scl) scl->setDefaultColourFor(this);
844 
845     m_fixedOrderLayers.push_back(layer);
846     m_layerStack.push_back(layer);
847 
848     QProgressBar *pb = new QProgressBar(this);
849     pb->setMinimum(0);
850     pb->setMaximum(0);
851     pb->setFixedWidth(80);
852     pb->setTextVisible(false);
853 
854     QPushButton *cancel = new QPushButton(this);
855     cancel->setIcon(IconLoader().load("cancel"));
856     cancel->setFlat(true);
857     int scaled20 = scalePixelSize(20);
858     cancel->setFixedSize(QSize(scaled20, scaled20));
859     connect(cancel, SIGNAL(clicked()), this, SLOT(cancelClicked()));
860 
861     ProgressBarRec pbr;
862     pbr.cancel = cancel;
863     pbr.bar = pb;
864     pbr.lastStallCheckValue = 0;
865     pbr.stallCheckTimer = new QTimer();
866     connect(pbr.stallCheckTimer, SIGNAL(timeout()), this,
867             SLOT(progressCheckStalledTimerElapsed()));
868 
869     m_progressBars[layer] = pbr;
870 
871     QFont f(pb->font());
872     int fs = Preferences::getInstance()->getViewFontSize();
873     f.setPointSize(std::min(fs, int(ceil(fs * 0.85))));
874 
875     cancel->hide();
876 
877     pb->setFont(f);
878     pb->hide();
879 
880     connect(layer, SIGNAL(layerParametersChanged()),
881             this,    SLOT(layerParametersChanged()));
882     connect(layer, SIGNAL(layerParameterRangesChanged()),
883             this,    SLOT(layerParameterRangesChanged()));
884     connect(layer, SIGNAL(layerMeasurementRectsChanged()),
885             this,    SLOT(layerMeasurementRectsChanged()));
886     connect(layer, SIGNAL(layerNameChanged()),
887             this,    SLOT(layerNameChanged()));
888     connect(layer, SIGNAL(modelChanged(ModelId)),
889             this,    SLOT(modelChanged(ModelId)));
890     connect(layer, SIGNAL(modelCompletionChanged(ModelId)),
891             this,    SLOT(modelCompletionChanged(ModelId)));
892     connect(layer, SIGNAL(modelAlignmentCompletionChanged(ModelId)),
893             this,    SLOT(modelAlignmentCompletionChanged(ModelId)));
894     connect(layer, SIGNAL(modelChangedWithin(ModelId, sv_frame_t, sv_frame_t)),
895             this,    SLOT(modelChangedWithin(ModelId, sv_frame_t, sv_frame_t)));
896     connect(layer, SIGNAL(modelReplaced()),
897             this,    SLOT(modelReplaced()));
898 
899     update();
900 
901     emit propertyContainerAdded(layer);
902 }
903 
904 void
removeLayer(Layer * layer)905 View::removeLayer(Layer *layer)
906 {
907     if (m_deleting) {
908         return;
909     }
910 
911     m_cacheValid = false;
912 
913     for (LayerList::iterator i = m_fixedOrderLayers.begin();
914          i != m_fixedOrderLayers.end();
915          ++i) {
916         if (*i == layer) {
917             m_fixedOrderLayers.erase(i);
918             break;
919         }
920     }
921 
922     for (LayerList::iterator i = m_layerStack.begin();
923          i != m_layerStack.end();
924          ++i) {
925         if (*i == layer) {
926             m_layerStack.erase(i);
927             if (m_progressBars.find(layer) != m_progressBars.end()) {
928                 delete m_progressBars[layer].bar;
929                 delete m_progressBars[layer].cancel;
930                 delete m_progressBars[layer].stallCheckTimer;
931                 m_progressBars.erase(layer);
932             }
933             break;
934         }
935     }
936 
937     disconnect(layer, SIGNAL(layerParametersChanged()),
938                this,    SLOT(layerParametersChanged()));
939     disconnect(layer, SIGNAL(layerParameterRangesChanged()),
940                this,    SLOT(layerParameterRangesChanged()));
941     disconnect(layer, SIGNAL(layerNameChanged()),
942                this,    SLOT(layerNameChanged()));
943     disconnect(layer, SIGNAL(modelChanged(ModelId)),
944                this,    SLOT(modelChanged(ModelId)));
945     disconnect(layer, SIGNAL(modelCompletionChanged(ModelId)),
946                this,    SLOT(modelCompletionChanged(ModelId)));
947     disconnect(layer, SIGNAL(modelAlignmentCompletionChanged(ModelId)),
948                this,    SLOT(modelAlignmentCompletionChanged(ModelId)));
949     disconnect(layer, SIGNAL(modelChangedWithin(ModelId, sv_frame_t, sv_frame_t)),
950                this,    SLOT(modelChangedWithin(ModelId, sv_frame_t, sv_frame_t)));
951     disconnect(layer, SIGNAL(modelReplaced()),
952                this,    SLOT(modelReplaced()));
953 
954     update();
955 
956     emit propertyContainerRemoved(layer);
957 }
958 
959 Layer *
getInteractionLayer()960 View::getInteractionLayer()
961 {
962     Layer *sl = getSelectedLayer();
963     if (sl && !(sl->isLayerDormant(this))) {
964         return sl;
965     }
966     if (!m_layerStack.empty()) {
967         int n = getLayerCount();
968         while (n > 0) {
969             --n;
970             Layer *layer = getLayer(n);
971             if (!(layer->isLayerDormant(this))) {
972                 return layer;
973             }
974         }
975     }
976     return nullptr;
977 }
978 
979 const Layer *
getInteractionLayer() const980 View::getInteractionLayer() const
981 {
982     return const_cast<const Layer *>(const_cast<View *>(this)->getInteractionLayer());
983 }
984 
985 Layer *
getSelectedLayer()986 View::getSelectedLayer()
987 {
988     if (m_haveSelectedLayer && !m_layerStack.empty()) {
989         return getLayer(getLayerCount() - 1);
990     } else {
991         return nullptr;
992     }
993 }
994 
995 const Layer *
getSelectedLayer() const996 View::getSelectedLayer() const
997 {
998     return const_cast<const Layer *>(const_cast<View *>(this)->getSelectedLayer());
999 }
1000 
1001 void
setViewManager(ViewManager * manager)1002 View::setViewManager(ViewManager *manager)
1003 {
1004     if (m_manager) {
1005         m_manager->disconnect(this, SLOT(globalCentreFrameChanged(sv_frame_t)));
1006         m_manager->disconnect(this, SLOT(viewCentreFrameChanged(View *, sv_frame_t)));
1007         m_manager->disconnect(this, SLOT(viewManagerPlaybackFrameChanged(sv_frame_t)));
1008         m_manager->disconnect(this, SLOT(viewZoomLevelChanged(View *, ZoomLevel, bool)));
1009         m_manager->disconnect(this, SLOT(toolModeChanged()));
1010         m_manager->disconnect(this, SLOT(selectionChanged()));
1011         m_manager->disconnect(this, SLOT(overlayModeChanged()));
1012         m_manager->disconnect(this, SLOT(zoomWheelsEnabledChanged()));
1013         disconnect(m_manager, SLOT(viewCentreFrameChanged(sv_frame_t, bool, PlaybackFollowMode)));
1014         disconnect(m_manager, SLOT(zoomLevelChanged(ZoomLevel, bool)));
1015     }
1016 
1017     m_manager = manager;
1018 
1019     connect(m_manager, SIGNAL(globalCentreFrameChanged(sv_frame_t)),
1020             this, SLOT(globalCentreFrameChanged(sv_frame_t)));
1021     connect(m_manager, SIGNAL(viewCentreFrameChanged(View *, sv_frame_t)),
1022             this, SLOT(viewCentreFrameChanged(View *, sv_frame_t)));
1023     connect(m_manager, SIGNAL(playbackFrameChanged(sv_frame_t)),
1024             this, SLOT(viewManagerPlaybackFrameChanged(sv_frame_t)));
1025 
1026     connect(m_manager, SIGNAL(viewZoomLevelChanged(View *, ZoomLevel, bool)),
1027             this, SLOT(viewZoomLevelChanged(View *, ZoomLevel, bool)));
1028 
1029     connect(m_manager, SIGNAL(toolModeChanged()),
1030             this, SLOT(toolModeChanged()));
1031     connect(m_manager, SIGNAL(selectionChanged()),
1032             this, SLOT(selectionChanged()));
1033     connect(m_manager, SIGNAL(inProgressSelectionChanged()),
1034             this, SLOT(selectionChanged()));
1035     connect(m_manager, SIGNAL(overlayModeChanged()),
1036             this, SLOT(overlayModeChanged()));
1037     connect(m_manager, SIGNAL(showCentreLineChanged()),
1038             this, SLOT(overlayModeChanged()));
1039     connect(m_manager, SIGNAL(zoomWheelsEnabledChanged()),
1040             this, SLOT(zoomWheelsEnabledChanged()));
1041 
1042     connect(this, SIGNAL(centreFrameChanged(sv_frame_t, bool,
1043                                             PlaybackFollowMode)),
1044             m_manager, SLOT(viewCentreFrameChanged(sv_frame_t, bool,
1045                                                    PlaybackFollowMode)));
1046 
1047     connect(this, SIGNAL(zoomLevelChanged(ZoomLevel, bool)),
1048             m_manager, SLOT(viewZoomLevelChanged(ZoomLevel, bool)));
1049 
1050     switch (m_followPlay) {
1051 
1052     case PlaybackScrollPage:
1053     case PlaybackScrollPageWithCentre:
1054         setCentreFrame(m_manager->getGlobalCentreFrame(), false);
1055         break;
1056 
1057     case PlaybackScrollContinuous:
1058         setCentreFrame(m_manager->getPlaybackFrame(), false);
1059         break;
1060 
1061     case PlaybackIgnore:
1062         if (m_followPan) {
1063             setCentreFrame(m_manager->getGlobalCentreFrame(), false);
1064         }
1065         break;
1066     }
1067 
1068     if (m_followZoom) setZoomLevel(m_manager->getGlobalZoom());
1069 
1070     movePlayPointer(getAlignedPlaybackFrame());
1071 
1072     toolModeChanged();
1073 }
1074 
1075 void
setViewManager(ViewManager * vm,sv_frame_t initialCentreFrame)1076 View::setViewManager(ViewManager *vm, sv_frame_t initialCentreFrame)
1077 {
1078     setViewManager(vm);
1079     setCentreFrame(initialCentreFrame, false);
1080 }
1081 
1082 void
setFollowGlobalPan(bool f)1083 View::setFollowGlobalPan(bool f)
1084 {
1085     m_followPan = f;
1086     emit propertyContainerPropertyChanged(m_propertyContainer);
1087 }
1088 
1089 void
setFollowGlobalZoom(bool f)1090 View::setFollowGlobalZoom(bool f)
1091 {
1092     m_followZoom = f;
1093     emit propertyContainerPropertyChanged(m_propertyContainer);
1094 }
1095 
1096 void
setPlaybackFollow(PlaybackFollowMode m)1097 View::setPlaybackFollow(PlaybackFollowMode m)
1098 {
1099     m_followPlay = m;
1100     emit propertyContainerPropertyChanged(m_propertyContainer);
1101 }
1102 
1103 void
modelChanged(ModelId modelId)1104 View::modelChanged(ModelId modelId)
1105 {
1106 #if defined(DEBUG_VIEW_WIDGET_PAINT) || defined(DEBUG_PROGRESS_STUFF)
1107     SVCERR << "View[" << getId() << "]::modelChanged(" << modelId << ")" << endl;
1108 #endif
1109 
1110     // If the model that has changed is not used by any of the cached
1111     // layers, we won't need to recreate the cache
1112 
1113     bool recreate = false;
1114 
1115     bool discard;
1116     LayerList scrollables = getScrollableBackLayers(false, discard);
1117     for (LayerList::const_iterator i = scrollables.begin();
1118          i != scrollables.end(); ++i) {
1119         if ((*i)->getModel() == modelId) {
1120             recreate = true;
1121             break;
1122         }
1123     }
1124 
1125     if (recreate) {
1126         m_cacheValid = false;
1127     }
1128 
1129     emit layerModelChanged();
1130 
1131     checkProgress(modelId);
1132 
1133     update();
1134 }
1135 
1136 void
modelChangedWithin(ModelId modelId,sv_frame_t startFrame,sv_frame_t endFrame)1137 View::modelChangedWithin(ModelId modelId,
1138                          sv_frame_t startFrame, sv_frame_t endFrame)
1139 {
1140     sv_frame_t myStartFrame = getStartFrame();
1141     sv_frame_t myEndFrame = getEndFrame();
1142 
1143 #ifdef DEBUG_VIEW_WIDGET_PAINT
1144     SVCERR << "View[" << getId() << "]::modelChangedWithin(" << startFrame << "," << endFrame << ") [me " << myStartFrame << "," << myEndFrame << "]" << endl;
1145 #endif
1146 
1147     if (myStartFrame > 0 && endFrame < myStartFrame) {
1148         checkProgress(modelId);
1149         return;
1150     }
1151     if (startFrame > myEndFrame) {
1152         checkProgress(modelId);
1153         return;
1154     }
1155 
1156     // If the model that has changed is not used by any of the cached
1157     // layers, we won't need to recreate the cache
1158 
1159     bool recreate = false;
1160 
1161     bool discard;
1162     LayerList scrollables = getScrollableBackLayers(false, discard);
1163     for (LayerList::const_iterator i = scrollables.begin();
1164          i != scrollables.end(); ++i) {
1165         if ((*i)->getModel() == modelId) {
1166             recreate = true;
1167             break;
1168         }
1169     }
1170 
1171     if (recreate) {
1172         m_cacheValid = false;
1173     }
1174 
1175     if (startFrame < myStartFrame) startFrame = myStartFrame;
1176     if (endFrame > myEndFrame) endFrame = myEndFrame;
1177 
1178     checkProgress(modelId);
1179 
1180     update();
1181 }
1182 
1183 void
modelCompletionChanged(ModelId modelId)1184 View::modelCompletionChanged(ModelId modelId)
1185 {
1186 #ifdef DEBUG_PROGRESS_STUFF
1187     SVCERR << "View[" << getId() << "]::modelCompletionChanged(" << modelId << ")" << endl;
1188 #endif
1189     checkProgress(modelId);
1190 }
1191 
1192 void
modelAlignmentCompletionChanged(ModelId modelId)1193 View::modelAlignmentCompletionChanged(ModelId modelId)
1194 {
1195 #ifdef DEBUG_PROGRESS_STUFF
1196     SVCERR << "View[" << getId() << "]::modelAlignmentCompletionChanged(" << modelId << ")" << endl;
1197 #endif
1198     checkAlignmentProgress(modelId);
1199 }
1200 
1201 void
modelReplaced()1202 View::modelReplaced()
1203 {
1204 #ifdef DEBUG_VIEW_WIDGET_PAINT
1205     SVCERR << "View[" << getId() << "]::modelReplaced()" << endl;
1206 #endif
1207     m_cacheValid = false;
1208     update();
1209 }
1210 
1211 void
layerParametersChanged()1212 View::layerParametersChanged()
1213 {
1214     Layer *layer = dynamic_cast<Layer *>(sender());
1215 
1216 #ifdef DEBUG_VIEW_WIDGET_PAINT
1217     SVDEBUG << "View::layerParametersChanged()" << endl;
1218 #endif
1219 
1220     m_cacheValid = false;
1221     update();
1222 
1223     if (layer) {
1224         emit propertyContainerPropertyChanged(layer);
1225     }
1226 }
1227 
1228 void
layerParameterRangesChanged()1229 View::layerParameterRangesChanged()
1230 {
1231     Layer *layer = dynamic_cast<Layer *>(sender());
1232     if (layer) emit propertyContainerPropertyRangeChanged(layer);
1233 }
1234 
1235 void
layerMeasurementRectsChanged()1236 View::layerMeasurementRectsChanged()
1237 {
1238     Layer *layer = dynamic_cast<Layer *>(sender());
1239     if (layer) update();
1240 }
1241 
1242 void
layerNameChanged()1243 View::layerNameChanged()
1244 {
1245     Layer *layer = dynamic_cast<Layer *>(sender());
1246     if (layer) emit propertyContainerNameChanged(layer);
1247 }
1248 
1249 void
globalCentreFrameChanged(sv_frame_t rf)1250 View::globalCentreFrameChanged(sv_frame_t rf)
1251 {
1252     if (m_followPan) {
1253         sv_frame_t f = alignFromReference(rf);
1254 #ifdef DEBUG_VIEW
1255         SVCERR << "View[" << getId() << "]::globalCentreFrameChanged(" << rf
1256                   << "): setting centre frame to " << f << endl;
1257 #endif
1258         setCentreFrame(f, false);
1259     }
1260 }
1261 
1262 void
viewCentreFrameChanged(View *,sv_frame_t)1263 View::viewCentreFrameChanged(View *, sv_frame_t )
1264 {
1265     // We do nothing with this, but a subclass might
1266 }
1267 
1268 void
viewManagerPlaybackFrameChanged(sv_frame_t f)1269 View::viewManagerPlaybackFrameChanged(sv_frame_t f)
1270 {
1271     if (m_manager) {
1272         if (sender() != m_manager) return;
1273     }
1274 
1275 #ifdef DEBUG_VIEW
1276     SVCERR << "View[" << getId() << "]::viewManagerPlaybackFrameChanged(" << f << ")" << endl;
1277 #endif
1278 
1279     f = getAlignedPlaybackFrame();
1280 
1281 #ifdef DEBUG_VIEW
1282     SVCERR << " -> aligned frame = " << f << endl;
1283 #endif
1284 
1285     movePlayPointer(f);
1286 }
1287 
1288 void
movePlayPointer(sv_frame_t newFrame)1289 View::movePlayPointer(sv_frame_t newFrame)
1290 {
1291 #ifdef DEBUG_VIEW
1292     SVCERR << "View[" << getId() << "]::movePlayPointer(" << newFrame << ")" << endl;
1293 #endif
1294 
1295     if (m_playPointerFrame == newFrame) return;
1296     bool visibleChange =
1297         (getXForFrame(m_playPointerFrame) != getXForFrame(newFrame));
1298 
1299 #ifdef DEBUG_VIEW_WIDGET_PAINT
1300     SVCERR << "View[" << getId() << "]::movePlayPointer: moving from "
1301            << m_playPointerFrame << " to " << newFrame << ", visible = "
1302            << visibleChange << endl;
1303 #endif
1304 
1305     sv_frame_t oldPlayPointerFrame = m_playPointerFrame;
1306     m_playPointerFrame = newFrame;
1307     if (!visibleChange) return;
1308 
1309     bool somethingGoingOn =
1310         ((QApplication::mouseButtons() != Qt::NoButton) ||
1311          (QApplication::keyboardModifiers() & Qt::AltModifier));
1312 
1313     bool pointerInVisibleArea =
1314         long(m_playPointerFrame) >= getStartFrame() &&
1315         (m_playPointerFrame < getEndFrame() ||
1316          // include old pointer location so we know to refresh when moving out
1317          oldPlayPointerFrame < getEndFrame());
1318 
1319     switch (m_followPlay) {
1320 
1321     case PlaybackScrollContinuous:
1322         if (!somethingGoingOn) {
1323             setCentreFrame(m_playPointerFrame, false);
1324         }
1325         break;
1326 
1327     case PlaybackScrollPage:
1328     case PlaybackScrollPageWithCentre:
1329 
1330         if (!pointerInVisibleArea && somethingGoingOn) {
1331 
1332             m_followPlayIsDetached = true;
1333 
1334         } else if (!pointerInVisibleArea && m_followPlayIsDetached) {
1335 
1336             // do nothing; we aren't tracking until the pointer comes back in
1337 
1338         } else {
1339 
1340             int xold = getXForFrame(oldPlayPointerFrame);
1341             update(xold - 4, 0, 9, height());
1342 
1343             sv_frame_t w = getEndFrame() - getStartFrame();
1344             w -= w/5;
1345             sv_frame_t sf = m_playPointerFrame;
1346             if (w > 0) {
1347                 sf = (sf / w) * w - w/8;
1348             }
1349 
1350             if (m_manager &&
1351                 m_manager->isPlaying() &&
1352                 m_manager->getPlaySelectionMode()) {
1353                 MultiSelection::SelectionList selections = m_manager->getSelections();
1354                 if (!selections.empty()) {
1355                     sv_frame_t selectionStart = selections.begin()->getStartFrame();
1356                     if (sf < selectionStart - w / 10) {
1357                         sf = selectionStart - w / 10;
1358                     }
1359                 }
1360             }
1361 
1362 #ifdef DEBUG_VIEW_WIDGET_PAINT
1363             SVCERR << "PlaybackScrollPage: f = " << m_playPointerFrame << ", sf = " << sf << ", start frame "
1364                  << getStartFrame() << endl;
1365 #endif
1366 
1367             // We don't consider scrolling unless the pointer is outside
1368             // the central visible range already
1369 
1370             int xnew = getXForFrame(m_playPointerFrame);
1371 
1372 #ifdef DEBUG_VIEW_WIDGET_PAINT
1373             SVCERR << "xnew = " << xnew << ", width = " << width() << endl;
1374 #endif
1375 
1376             bool shouldScroll = (xnew > (width() * 7) / 8);
1377 
1378             if (!m_followPlayIsDetached && (xnew < width() / 8)) {
1379                 shouldScroll = true;
1380             }
1381 
1382             if (xnew > width() / 8) {
1383                 m_followPlayIsDetached = false;
1384             } else if (somethingGoingOn) {
1385                 m_followPlayIsDetached = true;
1386             }
1387 
1388             if (!somethingGoingOn && shouldScroll) {
1389                 sv_frame_t offset = getFrameForX(width()/2) - getStartFrame();
1390                 sv_frame_t newCentre = sf + offset;
1391                 bool changed = setCentreFrame(newCentre, false);
1392                 if (changed) {
1393                     xold = getXForFrame(oldPlayPointerFrame);
1394                     update(xold - 4, 0, 9, height());
1395                 }
1396             }
1397 
1398             update(xnew - 4, 0, 9, height());
1399         }
1400         break;
1401 
1402     case PlaybackIgnore:
1403         if (m_playPointerFrame >= getStartFrame() &&
1404             m_playPointerFrame < getEndFrame()) {
1405             update();
1406         }
1407         break;
1408     }
1409 }
1410 
1411 void
viewZoomLevelChanged(View * p,ZoomLevel z,bool locked)1412 View::viewZoomLevelChanged(View *p, ZoomLevel z, bool locked)
1413 {
1414 #ifdef DEBUG_VIEW_WIDGET_PAINT
1415     SVCERR  << "View[" << getId() << "]: viewZoomLevelChanged(" << p << ", " << z << ", " << locked << ")" << endl;
1416 #endif
1417     if (m_followZoom && p != this && locked) {
1418         setZoomLevel(z);
1419     }
1420 }
1421 
1422 void
selectionChanged()1423 View::selectionChanged()
1424 {
1425     if (m_selectionCached) {
1426         m_cacheValid = false;
1427         m_selectionCached = false;
1428     }
1429     update();
1430 }
1431 
1432 sv_frame_t
getFirstVisibleFrame() const1433 View::getFirstVisibleFrame() const
1434 {
1435     sv_frame_t f0 = getStartFrame();
1436     sv_frame_t f = getModelsStartFrame();
1437     if (f0 < 0 || f0 < f) return f;
1438     return f0;
1439 }
1440 
1441 sv_frame_t
getLastVisibleFrame() const1442 View::getLastVisibleFrame() const
1443 {
1444     sv_frame_t f0 = getEndFrame();
1445     sv_frame_t f = getModelsEndFrame();
1446     if (f0 > f) return f;
1447     return f0;
1448 }
1449 
1450 sv_frame_t
getModelsStartFrame() const1451 View::getModelsStartFrame() const
1452 {
1453     bool first = true;
1454     sv_frame_t startFrame = 0;
1455 
1456     for (Layer *layer: m_layerStack) {
1457 
1458         auto model = ModelById::get(layer->getModel());
1459 
1460         if (model && model->isOK()) {
1461 
1462             sv_frame_t thisStartFrame = model->getStartFrame();
1463 
1464             if (first || thisStartFrame < startFrame) {
1465                 startFrame = thisStartFrame;
1466             }
1467             first = false;
1468         }
1469     }
1470 
1471     return startFrame;
1472 }
1473 
1474 sv_frame_t
getModelsEndFrame() const1475 View::getModelsEndFrame() const
1476 {
1477     bool first = true;
1478     sv_frame_t endFrame = 0;
1479 
1480     for (Layer *layer: m_layerStack) {
1481 
1482         auto model = ModelById::get(layer->getModel());
1483 
1484         if (model && model->isOK()) {
1485 
1486             sv_frame_t thisEndFrame = model->getEndFrame();
1487 
1488             if (first || thisEndFrame > endFrame) {
1489                 endFrame = thisEndFrame;
1490             }
1491             first = false;
1492         }
1493     }
1494 
1495     if (first) return getModelsStartFrame();
1496     return endFrame;
1497 }
1498 
1499 sv_samplerate_t
getModelsSampleRate() const1500 View::getModelsSampleRate() const
1501 {
1502     //!!! Just go for the first, for now.  If we were supporting
1503     // multiple samplerates, we'd probably want to do frame/time
1504     // conversion in the model
1505 
1506     //!!! nah, this wants to always return the sr of the main model!
1507 
1508     for (Layer *layer: m_layerStack) {
1509 
1510         auto model = ModelById::get(layer->getModel());
1511 
1512         if (model && model->isOK()) {
1513             return model->getSampleRate();
1514         }
1515     }
1516 
1517     return 0;
1518 }
1519 
1520 View::ModelSet
getModels()1521 View::getModels()
1522 {
1523     ModelSet models;
1524 
1525     for (int i = 0; i < getLayerCount(); ++i) {
1526 
1527         Layer *layer = getLayer(i);
1528 
1529         if (dynamic_cast<TimeRulerLayer *>(layer)) {
1530             continue;
1531         }
1532 
1533         if (layer && !layer->getModel().isNone()) {
1534             models.insert(layer->getModel());
1535         }
1536     }
1537 
1538     return models;
1539 }
1540 
1541 ModelId
getAligningModel() const1542 View::getAligningModel() const
1543 {
1544     ModelId aligning, reference;
1545     getAligningAndReferenceModels(aligning, reference);
1546     return aligning;
1547 }
1548 
1549 void
getAligningAndReferenceModels(ModelId & aligning,ModelId & reference) const1550 View::getAligningAndReferenceModels(ModelId &aligning,
1551                                     ModelId &reference) const
1552 {
1553     if (!m_manager ||
1554         !m_manager->getAlignMode() ||
1555         m_manager->getPlaybackModel().isNone()) {
1556         return;
1557     }
1558 
1559     ModelId anyModel;
1560 
1561     for (auto layer: m_layerStack) {
1562 
1563         if (!layer) continue;
1564         if (dynamic_cast<TimeRulerLayer *>(layer)) continue;
1565 
1566         ModelId thisId = layer->getModel();
1567         auto model = ModelById::get(thisId);
1568         if (!model) continue;
1569 
1570         anyModel = thisId;
1571 
1572         if (!model->getAlignmentReference().isNone()) {
1573 
1574             if (layer->isLayerOpaque() ||
1575                 std::dynamic_pointer_cast
1576                 <RangeSummarisableTimeValueModel>(model)) {
1577 
1578                 aligning = thisId;
1579                 reference = model->getAlignmentReference();
1580                 return;
1581 
1582             } else if (aligning.isNone()) {
1583 
1584                 aligning = thisId;
1585                 reference = model->getAlignmentReference();
1586             }
1587         }
1588     }
1589 
1590     if (aligning.isNone()) {
1591         aligning = anyModel;
1592         reference = {};
1593     }
1594 }
1595 
1596 sv_frame_t
alignFromReference(sv_frame_t f) const1597 View::alignFromReference(sv_frame_t f) const
1598 {
1599     if (!m_manager || !m_manager->getAlignMode()) return f;
1600     auto aligningModel = ModelById::get(getAligningModel());
1601     if (!aligningModel) return f;
1602     return aligningModel->alignFromReference(f);
1603 }
1604 
1605 sv_frame_t
alignToReference(sv_frame_t f) const1606 View::alignToReference(sv_frame_t f) const
1607 {
1608     if (!m_manager->getAlignMode()) return f;
1609     auto aligningModel = ModelById::get(getAligningModel());
1610     if (!aligningModel) return f;
1611     return aligningModel->alignToReference(f);
1612 }
1613 
1614 sv_frame_t
getAlignedPlaybackFrame() const1615 View::getAlignedPlaybackFrame() const
1616 {
1617     if (!m_manager) return 0;
1618     sv_frame_t pf = m_manager->getPlaybackFrame();
1619     if (!m_manager->getAlignMode()) return pf;
1620 
1621     auto aligningModel = ModelById::get(getAligningModel());
1622     if (!aligningModel) return pf;
1623 
1624     sv_frame_t af = aligningModel->alignFromReference(pf);
1625 
1626     return af;
1627 }
1628 
1629 bool
areLayersScrollable() const1630 View::areLayersScrollable() const
1631 {
1632     // True iff all views are scrollable
1633     for (LayerList::const_iterator i = m_layerStack.begin(); i != m_layerStack.end(); ++i) {
1634         if (!(*i)->isLayerScrollable(this)) return false;
1635     }
1636     return true;
1637 }
1638 
1639 View::LayerList
getScrollableBackLayers(bool testChanged,bool & changed) const1640 View::getScrollableBackLayers(bool testChanged, bool &changed) const
1641 {
1642     changed = false;
1643 
1644     // We want a list of all the scrollable layers that are behind the
1645     // backmost non-scrollable layer.
1646 
1647     LayerList scrollables;
1648     bool metUnscrollable = false;
1649 
1650     for (LayerList::const_iterator i = m_layerStack.begin(); i != m_layerStack.end(); ++i) {
1651 //        SVDEBUG << "View::getScrollableBackLayers: calling isLayerDormant on layer " << *i << endl;
1652 //        SVCERR << "(name is " << (*i)->objectName() << ")"
1653 //                  << endl;
1654 //        SVDEBUG << "View::getScrollableBackLayers: I am " << getId() << endl;
1655         if ((*i)->isLayerDormant(this)) continue;
1656         if ((*i)->isLayerOpaque()) {
1657             // You can't see anything behind an opaque layer!
1658             scrollables.clear();
1659             if (metUnscrollable) break;
1660         }
1661         if (!metUnscrollable && (*i)->isLayerScrollable(this)) {
1662             scrollables.push_back(*i);
1663         } else {
1664             metUnscrollable = true;
1665         }
1666     }
1667 
1668     if (testChanged && scrollables != m_lastScrollableBackLayers) {
1669         m_lastScrollableBackLayers = scrollables;
1670         changed = true;
1671     }
1672     return scrollables;
1673 }
1674 
1675 View::LayerList
getNonScrollableFrontLayers(bool testChanged,bool & changed) const1676 View::getNonScrollableFrontLayers(bool testChanged, bool &changed) const
1677 {
1678     changed = false;
1679     LayerList nonScrollables;
1680 
1681     // Everything in front of the first non-scrollable from the back
1682     // should also be considered non-scrollable
1683 
1684     bool started = false;
1685 
1686     for (LayerList::const_iterator i = m_layerStack.begin(); i != m_layerStack.end(); ++i) {
1687         if ((*i)->isLayerDormant(this)) continue;
1688         if (!started && (*i)->isLayerScrollable(this)) {
1689             continue;
1690         }
1691         started = true;
1692         if ((*i)->isLayerOpaque()) {
1693             // You can't see anything behind an opaque layer!
1694             nonScrollables.clear();
1695         }
1696         nonScrollables.push_back(*i);
1697     }
1698 
1699     if (testChanged && nonScrollables != m_lastNonScrollableBackLayers) {
1700         m_lastNonScrollableBackLayers = nonScrollables;
1701         changed = true;
1702     }
1703 
1704     return nonScrollables;
1705 }
1706 
1707 ZoomLevel
getZoomConstraintLevel(ZoomLevel zoomLevel,ZoomConstraint::RoundingDirection dir) const1708 View::getZoomConstraintLevel(ZoomLevel zoomLevel,
1709                              ZoomConstraint::RoundingDirection dir)
1710     const
1711 {
1712     using namespace std::rel_ops;
1713 
1714     ZoomLevel candidate =
1715         RelativelyFineZoomConstraint().getNearestZoomLevel(zoomLevel, dir);
1716 
1717     for (auto i : m_layerStack) {
1718 
1719         if (i->supportsOtherZoomLevels() || !(i->getZoomConstraint())) {
1720             continue;
1721         }
1722 
1723         ZoomLevel thisLevel =
1724             i->getZoomConstraint()->getNearestZoomLevel(zoomLevel, dir);
1725 
1726         // Go for the block size that's furthest from the one
1727         // passed in.  Most of the time, that's what we want.
1728         if ((thisLevel > zoomLevel && thisLevel > candidate) ||
1729             (thisLevel < zoomLevel && thisLevel < candidate)) {
1730             candidate = thisLevel;
1731         }
1732     }
1733 
1734     return candidate;
1735 }
1736 
1737 int
countZoomLevels() const1738 View::countZoomLevels() const
1739 {
1740     int n = 0;
1741     ZoomLevel min = ZoomConstraint().getMinZoomLevel();
1742     ZoomLevel max = ZoomConstraint().getMaxZoomLevel();
1743     ZoomLevel level = min;
1744     while (true) {
1745         ++n;
1746         if (level == max) {
1747             break;
1748         }
1749         level = getZoomConstraintLevel
1750             (level.incremented(), ZoomConstraint::RoundUp);
1751     }
1752 //    SVCERR << "View::countZoomLevels: " << n << endl;
1753     return n;
1754 }
1755 
1756 ZoomLevel
getZoomLevelByIndex(int ix) const1757 View::getZoomLevelByIndex(int ix) const
1758 {
1759     int n = 0;
1760     ZoomLevel min = ZoomConstraint().getMinZoomLevel();
1761     ZoomLevel max = ZoomConstraint().getMaxZoomLevel();
1762     ZoomLevel level = min;
1763     while (true) {
1764         if (n == ix) {
1765 //            SVCERR << "View::getZoomLevelByIndex: " << ix << " -> " << level
1766 //                 << endl;
1767             return level;
1768         }
1769         ++n;
1770         if (level == max) {
1771             break;
1772         }
1773         level = getZoomConstraintLevel
1774             (level.incremented(), ZoomConstraint::RoundUp);
1775     }
1776 //    SVCERR << "View::getZoomLevelByIndex: " << ix << " -> " << max << " (max)"
1777 //         << endl;
1778     return max;
1779 }
1780 
1781 int
getZoomLevelIndex(ZoomLevel z) const1782 View::getZoomLevelIndex(ZoomLevel z) const
1783 {
1784     int n = 0;
1785     ZoomLevel min = ZoomConstraint().getMinZoomLevel();
1786     ZoomLevel max = ZoomConstraint().getMaxZoomLevel();
1787     ZoomLevel level = min;
1788     while (true) {
1789         if (z == level) {
1790 //            SVCERR << "View::getZoomLevelIndex: " << z << " -> " << n
1791 //                 << endl;
1792             return n;
1793         }
1794         ++n;
1795         if (level == max) {
1796             break;
1797         }
1798         level = getZoomConstraintLevel
1799             (level.incremented(), ZoomConstraint::RoundUp);
1800     }
1801 //    SVCERR << "View::getZoomLevelIndex: " << z << " -> " << n << " (max)"
1802 //         << endl;
1803     return n;
1804 }
1805 
1806 double
scaleSize(double size) const1807 View::scaleSize(double size) const
1808 {
1809     static double ratio = 0.0;
1810 
1811     if (ratio == 0.0) {
1812         double baseEm;
1813 #ifdef Q_OS_MAC
1814         baseEm = 17.0;
1815 #else
1816         baseEm = 15.0;
1817 #endif
1818         double em = QFontMetrics(QFont()).height();
1819         ratio = em / baseEm;
1820 
1821         SVDEBUG << "View::scaleSize: ratio is " << ratio
1822                 << " (em = " << em << ")" << endl;
1823 
1824         if (ratio < 1.0) {
1825             SVDEBUG << "View::scaleSize: rounding ratio up to 1.0" << endl;
1826             ratio = 1.0;
1827         }
1828     }
1829 
1830     return size * ratio;
1831 }
1832 
1833 int
scalePixelSize(int size) const1834 View::scalePixelSize(int size) const
1835 {
1836     double d = scaleSize(size);
1837     int i = int(d + 0.5);
1838     if (size != 0 && i == 0) i = 1;
1839     return i;
1840 }
1841 
1842 double
scalePenWidth(double width) const1843 View::scalePenWidth(double width) const
1844 {
1845     if (width <= 0) { // zero-width pen, produce a scaled one-pixel pen
1846         width = 1;
1847     }
1848     double ratio = scaleSize(1.0);
1849     return width * sqrt(ratio);
1850 }
1851 
1852 QPen
scalePen(QPen pen) const1853 View::scalePen(QPen pen) const
1854 {
1855     return QPen(pen.color(), scalePenWidth(pen.width()));
1856 }
1857 
1858 bool
areLayerColoursSignificant() const1859 View::areLayerColoursSignificant() const
1860 {
1861     for (LayerList::const_iterator i = m_layerStack.begin(); i != m_layerStack.end(); ++i) {
1862         if ((*i)->getLayerColourSignificance() ==
1863             Layer::ColourHasMeaningfulValue) return true;
1864         if ((*i)->isLayerOpaque()) break;
1865     }
1866     return false;
1867 }
1868 
1869 bool
hasTopLayerTimeXAxis() const1870 View::hasTopLayerTimeXAxis() const
1871 {
1872     LayerList::const_iterator i = m_layerStack.end();
1873     if (i == m_layerStack.begin()) return false;
1874     --i;
1875     return (*i)->hasTimeXAxis();
1876 }
1877 
1878 void
zoom(bool in)1879 View::zoom(bool in)
1880 {
1881     ZoomLevel newZoomLevel = m_zoomLevel;
1882 
1883     if (in) {
1884         newZoomLevel = getZoomConstraintLevel(m_zoomLevel.decremented(),
1885                                               ZoomConstraint::RoundDown);
1886     } else {
1887         newZoomLevel = getZoomConstraintLevel(m_zoomLevel.incremented(),
1888                                               ZoomConstraint::RoundUp);
1889     }
1890 
1891     using namespace std::rel_ops;
1892 
1893     if (newZoomLevel != m_zoomLevel) {
1894         setZoomLevel(newZoomLevel);
1895     }
1896 }
1897 
1898 void
scroll(bool right,bool lots,bool e)1899 View::scroll(bool right, bool lots, bool e)
1900 {
1901     sv_frame_t delta;
1902     if (lots) {
1903         delta = (getEndFrame() - getStartFrame()) / 2;
1904     } else {
1905         delta = (getEndFrame() - getStartFrame()) / 20;
1906     }
1907     if (right) delta = -delta;
1908 
1909 #ifdef DEBUG_VIEW
1910     SVCERR << "View::scroll(" << right << ", " << lots << ", " << e << "): "
1911            << "delta = " << delta << ", m_centreFrame = " << m_centreFrame
1912            << endl;
1913 #endif
1914 
1915     if (m_centreFrame < delta) {
1916         setCentreFrame(0, e);
1917     } else if (m_centreFrame - delta >= getModelsEndFrame()) {
1918         setCentreFrame(getModelsEndFrame(), e);
1919     } else {
1920         setCentreFrame(m_centreFrame - delta, e);
1921     }
1922 }
1923 
1924 void
cancelClicked()1925 View::cancelClicked()
1926 {
1927     QPushButton *cancel = qobject_cast<QPushButton *>(sender());
1928     if (!cancel) return;
1929 
1930     Layer *layer = nullptr;
1931 
1932     for (ProgressMap::iterator i = m_progressBars.begin();
1933          i != m_progressBars.end(); ++i) {
1934         if (i->second.cancel == cancel) {
1935             layer = i->first;
1936             break;
1937         }
1938     }
1939 
1940     if (layer) {
1941         emit cancelButtonPressed(layer);
1942     }
1943 }
1944 
1945 void
checkProgress(ModelId modelId)1946 View::checkProgress(ModelId modelId)
1947 {
1948     if (!m_showProgress) {
1949 #ifdef DEBUG_PROGRESS_STUFF
1950         SVCERR << "View[" << getId() << "]::checkProgress(" << modelId << "): "
1951                << "m_showProgress is off" << endl;
1952 #endif
1953         return;
1954     }
1955 
1956 #ifdef DEBUG_PROGRESS_STUFF
1957     SVCERR << "View[" << getId() << "]::checkProgress(" << modelId << ")" << endl;
1958 #endif
1959 
1960     QSettings settings;
1961     settings.beginGroup("View");
1962     bool showCancelButton = settings.value("showcancelbuttons", true).toBool();
1963     settings.endGroup();
1964 
1965     int ph = height();
1966     bool found = false;
1967 
1968     if (m_alignmentProgressBar.bar) {
1969         ph -= m_alignmentProgressBar.bar->height();
1970     }
1971 
1972     for (ProgressMap::iterator i = m_progressBars.begin();
1973          i != m_progressBars.end(); ++i) {
1974 
1975         QProgressBar *pb = i->second.bar;
1976         QPushButton *cancel = i->second.cancel;
1977 
1978         if (i->first && i->first->getModel() == modelId) {
1979 
1980             found = true;
1981 
1982             // The timer is used to test for stalls.  If the progress
1983             // bar does not get updated for some length of time, the
1984             // timer prompts it to go back into "indeterminate" mode
1985             QTimer *timer = i->second.stallCheckTimer;
1986 
1987             int completion = i->first->getCompletion(this);
1988             QString error = i->first->getError(this);
1989 
1990 #ifdef DEBUG_PROGRESS_STUFF
1991             SVCERR << "View[" << getId() << "]::checkProgress(" << modelId << "): "
1992                    << "found progress bar " << pb << " for layer at height " << ph
1993                    << ": completion = " << completion << endl;
1994 #endif
1995 
1996             if (error != "" && error != m_lastError) {
1997                 QMessageBox::critical(this, tr("Layer rendering error"), error);
1998                 m_lastError = error;
1999             }
2000 
2001             if (completion > 0) {
2002                 pb->setMaximum(100); // was 0, for indeterminate start
2003             }
2004 
2005             if (completion < 100 &&
2006                 ModelById::isa<RangeSummarisableTimeValueModel>(modelId)) {
2007                 update(); // ensure duration &c gets updated
2008             }
2009 
2010             if (completion >= 100) {
2011 
2012                 pb->hide();
2013                 cancel->hide();
2014                 timer->stop();
2015 
2016             } else if (i->first->isLayerDormant(this)) {
2017 
2018                 // A dormant (invisible) layer can still be busy
2019                 // generating, but we don't usually want to indicate
2020                 // it because it probably means it's a duplicate of a
2021                 // visible layer
2022 #ifdef DEBUG_PROGRESS_STUFF
2023                 SVCERR << "View[" << getId() << "]::checkProgress("
2024                        << modelId << "): layer is dormant" << endl;
2025 #endif
2026                 pb->hide();
2027                 cancel->hide();
2028                 timer->stop();
2029 
2030             } else {
2031 
2032                 if (!pb->isVisible()) {
2033                     i->second.lastStallCheckValue = 0;
2034                     timer->setInterval(2000);
2035                     timer->start();
2036                 }
2037 
2038                 if (showCancelButton) {
2039 
2040                     int scaled20 = scalePixelSize(20);
2041 
2042                     cancel->move(0, ph - pb->height()/2 - scaled20/2);
2043                     cancel->show();
2044 
2045                     pb->setValue(completion);
2046                     pb->move(scaled20, ph - pb->height());
2047 
2048                 } else {
2049 
2050                     cancel->hide();
2051 
2052                     pb->setValue(completion);
2053                     pb->move(0, ph - pb->height());
2054                 }
2055 
2056                 pb->show();
2057                 pb->update();
2058 
2059                 if (pb->isVisible()) {
2060                     ph -= pb->height();
2061                 }
2062             }
2063         } else {
2064             if (pb->isVisible()) {
2065                 ph -= pb->height();
2066             }
2067         }
2068     }
2069 
2070     if (!found) {
2071 #ifdef DEBUG_PROGRESS_STUFF
2072         SVCERR << "View[" << getId() << "]::checkProgress(" << modelId << "): "
2073                << "failed to find layer for model in progress map"
2074                << endl;
2075 #endif
2076     }
2077 }
2078 
2079 void
checkAlignmentProgress(ModelId modelId)2080 View::checkAlignmentProgress(ModelId modelId)
2081 {
2082     if (!m_showProgress) {
2083 #ifdef DEBUG_PROGRESS_STUFF
2084         SVCERR << "View[" << getId() << "]::checkAlignmentProgress(" << modelId << "): "
2085                << "m_showProgress is off" << endl;
2086 #endif
2087         return;
2088     }
2089 
2090 #ifdef DEBUG_PROGRESS_STUFF
2091     SVCERR << "View[" << getId() << "]::checkAlignmentProgress(" << modelId << ")" << endl;
2092 #endif
2093 
2094     if (!m_alignmentProgressBar.alignedModel.isNone() &&
2095         modelId != m_alignmentProgressBar.alignedModel) {
2096 #ifdef DEBUG_PROGRESS_STUFF
2097         SVCERR << "View[" << getId() << "]::checkAlignmentProgress(" << modelId << "): Different model (we're currently showing alignment progress for " << modelId << ", ignoring" << endl;
2098 #endif
2099         return;
2100     }
2101 
2102     auto model = ModelById::get(modelId);
2103     if (!model) {
2104 #ifdef DEBUG_PROGRESS_STUFF
2105         SVCERR << "View[" << getId() << "]::checkAlignmentProgress(" << modelId << "): Model gone" << endl;
2106 #endif
2107         m_alignmentProgressBar.alignedModel = {};
2108         delete m_alignmentProgressBar.bar;
2109         m_alignmentProgressBar.bar = nullptr;
2110         return;
2111     }
2112 
2113     int completion = model->getAlignmentCompletion();
2114 
2115 #ifdef DEBUG_PROGRESS_STUFF
2116     SVCERR << "View[" << getId() << "]::checkAlignmentProgress(" << modelId << "): Completion is " << completion << endl;
2117 #endif
2118 
2119     int ph = height();
2120 
2121     if (completion >= 100) {
2122         m_alignmentProgressBar.alignedModel = {};
2123         delete m_alignmentProgressBar.bar;
2124         m_alignmentProgressBar.bar = nullptr;
2125         return;
2126     }
2127 
2128     QProgressBar *pb = m_alignmentProgressBar.bar;
2129     if (!pb) {
2130         pb = new QProgressBar(this);
2131         pb->setMinimum(0);
2132         pb->setMaximum(100);
2133         pb->setFixedWidth(80);
2134         pb->setTextVisible(false);
2135         m_alignmentProgressBar.alignedModel = modelId;
2136         m_alignmentProgressBar.bar = pb;
2137     }
2138 
2139     pb->setValue(completion);
2140     pb->move(0, ph - pb->height());
2141     pb->show();
2142     pb->update();
2143 }
2144 
2145 void
progressCheckStalledTimerElapsed()2146 View::progressCheckStalledTimerElapsed()
2147 {
2148     QObject *s = sender();
2149     QTimer *t = qobject_cast<QTimer *>(s);
2150     if (!t) return;
2151 
2152     for (ProgressMap::iterator i =  m_progressBars.begin();
2153          i != m_progressBars.end(); ++i) {
2154 
2155         if (i->second.stallCheckTimer == t) {
2156 
2157             int value = i->second.bar->value();
2158 
2159 #ifdef DEBUG_PROGRESS_STUFF
2160             SVCERR << "View[" << getId() << "]::progressCheckStalledTimerElapsed for layer " << i->first << ": value is " << value << endl;
2161 #endif
2162 
2163             if (value > 0 && value == i->second.lastStallCheckValue) {
2164                 i->second.bar->setMaximum(0); // indeterminate
2165             }
2166             i->second.lastStallCheckValue = value;
2167             return;
2168         }
2169     }
2170 }
2171 
2172 int
getProgressBarWidth() const2173 View::getProgressBarWidth() const
2174 {
2175     if (m_alignmentProgressBar.bar) {
2176         return m_alignmentProgressBar.bar->width();
2177     }
2178 
2179     for (ProgressMap::const_iterator i = m_progressBars.begin();
2180          i != m_progressBars.end(); ++i) {
2181         if (i->second.bar && i->second.bar->isVisible()) {
2182             return i->second.bar->width();
2183         }
2184     }
2185 
2186     return 0;
2187 }
2188 
2189 void
setPaintFont(QPainter & paint)2190 View::setPaintFont(QPainter &paint)
2191 {
2192     int scaleFactor = 1;
2193     int dpratio = effectiveDevicePixelRatio();
2194     if (dpratio > 1) {
2195         QPaintDevice *dev = paint.device();
2196         if (dynamic_cast<QPixmap *>(dev) || dynamic_cast<QImage *>(dev)) {
2197             scaleFactor = dpratio;
2198         }
2199     }
2200 
2201     QFont font(paint.font());
2202     font.setPointSize(Preferences::getInstance()->getViewFontSize()
2203                       * scaleFactor);
2204     paint.setFont(font);
2205 }
2206 
2207 QRect
getPaintRect() const2208 View::getPaintRect() const
2209 {
2210     return rect();
2211 }
2212 
2213 void
paintEvent(QPaintEvent * e)2214 View::paintEvent(QPaintEvent *e)
2215 {
2216 //    Profiler prof("View::paintEvent", false);
2217 
2218 #ifdef DEBUG_VIEW_WIDGET_PAINT
2219     {
2220         sv_frame_t startFrame = getStartFrame();
2221         SVCERR << "View[" << getId() << "]::paintEvent: centre frame is " << m_centreFrame << " (start frame " << startFrame << ", height " << height() << ")" << endl;
2222     }
2223 #endif
2224 
2225     if (m_layerStack.empty()) {
2226         QFrame::paintEvent(e);
2227         return;
2228     }
2229 
2230     // ensure our constraints are met
2231     m_zoomLevel = getZoomConstraintLevel
2232         (m_zoomLevel, ZoomConstraint::RoundNearest);
2233 
2234     // We have a cache, which retains the state of scrollable (back)
2235     // layers from one paint to the next, and a buffer, which we paint
2236     // onto before copying directly to the widget. Both are at scaled
2237     // resolution (e.g. 2x on a pixel-doubled display), whereas the
2238     // paint event always comes in at formal (1x) resolution.
2239 
2240     // If we touch the cache, we always leave it in a valid state
2241     // across its whole extent. When another method invalidates the
2242     // cache, it does so by setting m_cacheValid false, so if that
2243     // flag is true on entry, then the cache is valid across its whole
2244     // extent - although it may be valid for a different centre frame,
2245     // zoom level, or view size from those now in effect.
2246 
2247     // Our process goes:
2248     //
2249     // 1. Check whether we have any scrollable (cacheable) layers.  If
2250     //    we don't, then invalidate and ignore the cache and go to
2251     //    step 5.  Otherwise:
2252     //
2253     // 2. Check the cache, scroll as necessary, identify any area that
2254     //    needs to be refreshed (this might be the whole cache).
2255     //
2256     // 3. Paint to cache the area that needs to be refreshed, from the
2257     //    stack of scrollable layers.
2258     //
2259     // 4. Paint to buffer from cache: if there are no non-cached areas
2260     //    or selections and the cache has not scrolled, then paint the
2261     //    union of the area of cache that has changed and the area
2262     //    that the paint event reported as exposed; otherwise paint
2263     //    the whole.
2264     //
2265     // 5. Paint the exposed area to the buffer from the cache plus all
2266     //    the layers that haven't been cached, plus selections etc.
2267     //
2268     // 6. Paint the exposed rect from the buffer.
2269     //
2270     // Note that all rects except the target for the final step are at
2271     // cache (scaled, 2x as applicable) resolution.
2272 
2273     int dpratio = effectiveDevicePixelRatio();
2274 
2275     QRect requestedPaintArea(scaledRect(rect(), dpratio));
2276     if (e) {
2277         // cut down to only the area actually exposed
2278         requestedPaintArea &= scaledRect(e->rect(), dpratio);
2279     }
2280 
2281     // If not all layers are scrollable, but some of the back layers
2282     // are, we should store only those in the cache.
2283 
2284     bool layersChanged = false;
2285     LayerList scrollables = getScrollableBackLayers(true, layersChanged);
2286     LayerList nonScrollables = getNonScrollableFrontLayers(true, layersChanged);
2287 
2288 #ifdef DEBUG_VIEW_WIDGET_PAINT
2289     SVCERR << "View[" << getId() << "]::paintEvent: have " << scrollables.size()
2290               << " scrollable back layers and " << nonScrollables.size()
2291               << " non-scrollable front layers" << endl;
2292 #endif
2293 
2294     if (layersChanged || scrollables.empty()) {
2295         m_cacheValid = false;
2296     }
2297 
2298     QRect wholeArea(scaledRect(rect(), dpratio));
2299     QSize wholeSize(scaledSize(size(), dpratio));
2300 
2301     if (!m_buffer || wholeSize != m_buffer->size()) {
2302         delete m_buffer;
2303         m_buffer = new QPixmap(wholeSize);
2304     }
2305 
2306     bool shouldUseCache = false;
2307     bool shouldRepaintCache = false;
2308     QRect cacheAreaToRepaint;
2309 
2310     static HitCount count("View cache");
2311 
2312     if (!scrollables.empty()) {
2313 
2314         shouldUseCache = true;
2315         shouldRepaintCache = true;
2316         cacheAreaToRepaint = wholeArea;
2317 
2318 #ifdef DEBUG_VIEW_WIDGET_PAINT
2319         SVCERR << "View[" << getId() << "]: cache " << m_cache << ", cache zoom "
2320                   << m_cacheZoomLevel << ", zoom " << m_zoomLevel << endl;
2321 #endif
2322 
2323         using namespace std::rel_ops;
2324 
2325         if (!m_cacheValid ||
2326             !m_cache ||
2327             m_cacheZoomLevel != m_zoomLevel ||
2328             m_cache->size() != wholeSize) {
2329 
2330             // cache is not valid at all
2331 
2332             if (requestedPaintArea.width() < wholeSize.width() / 10) {
2333 
2334                 m_cacheValid = false;
2335                 shouldUseCache = false;
2336                 shouldRepaintCache = false;
2337 
2338 #ifdef DEBUG_VIEW_WIDGET_PAINT
2339                 SVCERR << "View[" << getId() << "]::paintEvent: cache is invalid but only small area requested, will repaint directly instead" << endl;
2340 #endif
2341             } else {
2342 
2343                 if (!m_cache ||
2344                     m_cache->size() != wholeSize) {
2345                     delete m_cache;
2346                     m_cache = new QPixmap(wholeSize);
2347                 }
2348 
2349 #ifdef DEBUG_VIEW_WIDGET_PAINT
2350                 SVCERR << "View[" << getId() << "]::paintEvent: cache is invalid, will repaint whole" << endl;
2351 #endif
2352             }
2353 
2354             count.miss();
2355 
2356         } else if (m_cacheCentreFrame != m_centreFrame) {
2357 
2358 #ifdef DEBUG_VIEW_WIDGET_PAINT
2359             SVCERR << "View[" << getId() << "]::paintEvent: cache centre frame is " << m_cacheCentreFrame << endl;
2360 #endif
2361 
2362             int dx = dpratio * (getXForFrame(m_cacheCentreFrame) -
2363                                 getXForFrame(m_centreFrame));
2364 
2365             if (dx > -m_cache->width() && dx < m_cache->width()) {
2366 
2367                 m_cache->scroll(dx, 0, m_cache->rect(), nullptr);
2368 
2369                 if (dx < 0) {
2370                     cacheAreaToRepaint =
2371                         QRect(m_cache->width() + dx, 0, -dx, m_cache->height());
2372                 } else {
2373                     cacheAreaToRepaint =
2374                         QRect(0, 0, dx, m_cache->height());
2375                 }
2376 
2377                 count.partial();
2378 
2379 #ifdef DEBUG_VIEW_WIDGET_PAINT
2380                 SVCERR << "View[" << getId() << "]::paintEvent: scrolled cache by " << dx << endl;
2381 #endif
2382             } else {
2383                 count.miss();
2384 #ifdef DEBUG_VIEW_WIDGET_PAINT
2385                 SVCERR << "View[" << getId() << "]::paintEvent: scrolling too far" << endl;
2386 #endif
2387             }
2388 
2389         } else {
2390 #ifdef DEBUG_VIEW_WIDGET_PAINT
2391             SVCERR << "View[" << getId() << "]::paintEvent: cache is good" << endl;
2392 #endif
2393             count.hit();
2394             shouldRepaintCache = false;
2395         }
2396     }
2397 
2398 #ifdef DEBUG_VIEW_WIDGET_PAINT
2399     SVCERR << "View[" << getId() << "]::paintEvent: m_cacheValid = " << m_cacheValid << ", shouldUseCache = " << shouldUseCache << ", shouldRepaintCache = " << shouldRepaintCache << ", cacheAreaToRepaint = " << cacheAreaToRepaint.x() << "," << cacheAreaToRepaint.y() << " " << cacheAreaToRepaint.width() << "x" << cacheAreaToRepaint.height() << endl;
2400 #endif
2401 
2402     if (shouldRepaintCache && !shouldUseCache) {
2403         // If we are repainting the cache, then we paint the
2404         // scrollables only to the cache, not to the buffer. So if
2405         // shouldUseCache is also false, then the scrollables can't
2406         // appear because they will only be on the cache
2407         throw std::logic_error("ERROR: shouldRepaintCache is true, but shouldUseCache is false: this can't lead to the correct result");
2408     }
2409 
2410     // Create the ViewProxy for geometry provision, using the
2411     // device-pixel ratio for pixel-doubled hi-dpi rendering as
2412     // appropriate.
2413 
2414     ViewProxy proxy(this, dpratio);
2415 
2416     // Some layers may need an aligning proxy. If a layer's model has
2417     // a source model that is the reference model for the aligning
2418     // model, and the layer is tagged as to be aligned, then we might
2419     // use an aligning proxy. Note this is actually made use of only
2420     // if m_useAligningProxy is true further down.
2421 
2422     ModelId alignmentModelId;
2423     ModelId alignmentReferenceId;
2424     auto aligningModel = ModelById::get(getAligningModel());
2425     if (aligningModel) {
2426         alignmentModelId = aligningModel->getAlignment();
2427         alignmentReferenceId = aligningModel->getAlignmentReference();
2428 #ifdef DEBUG_VIEW_WIDGET_PAINT
2429         SVCERR << "alignmentModelId = " << alignmentModelId << " (reference = " << alignmentReferenceId << ")" << endl;
2430 #endif
2431     } else {
2432 #ifdef DEBUG_VIEW_WIDGET_PAINT
2433         SVCERR << "no aligningModel" << endl;
2434 #endif
2435     }
2436     ViewProxy aligningProxy(this, dpratio, alignmentModelId);
2437 
2438     // Scrollable (cacheable) items first. If we are repainting the
2439     // cache, then we paint these to the cache; otherwise straight to
2440     // the buffer.
2441     QRect areaToPaint;
2442     QPainter paint;
2443 
2444     if (shouldRepaintCache) {
2445         paint.begin(m_cache);
2446         areaToPaint = cacheAreaToRepaint;
2447     } else {
2448         paint.begin(m_buffer);
2449         areaToPaint = requestedPaintArea;
2450     }
2451 
2452     setPaintFont(paint);
2453     paint.setClipRect(areaToPaint);
2454 
2455     paint.setPen(getBackground());
2456     paint.setBrush(getBackground());
2457     paint.drawRect(areaToPaint);
2458 
2459     paint.setPen(getForeground());
2460     paint.setBrush(Qt::NoBrush);
2461 
2462     for (LayerList::iterator i = scrollables.begin();
2463          i != scrollables.end(); ++i) {
2464 
2465         paint.setRenderHint(QPainter::Antialiasing, false);
2466         paint.save();
2467 
2468         Layer *layer = *i;
2469 
2470         bool useAligningProxy = false;
2471         if (m_useAligningProxy) {
2472             if (layer->getModel() == alignmentReferenceId ||
2473                 layer->getSourceModel() == alignmentReferenceId) {
2474                 useAligningProxy = true;
2475             }
2476         }
2477 
2478 #ifdef DEBUG_VIEW_WIDGET_PAINT
2479         SVCERR << "Painting scrollable layer " << layer << " (model " << layer->getModel() << ", source model " << layer->getSourceModel() << ") with shouldRepaintCache = " << shouldRepaintCache << ", useAligningProxy = " << useAligningProxy << ", dpratio = " << dpratio << ", areaToPaint = " << areaToPaint.x() << "," << areaToPaint.y() << " " << areaToPaint.width() << "x" << areaToPaint.height() << endl;
2480 #endif
2481 
2482         layer->paint(useAligningProxy ? &aligningProxy : &proxy,
2483                      paint, areaToPaint);
2484 
2485         paint.restore();
2486     }
2487 
2488     paint.end();
2489 
2490     if (shouldRepaintCache) {
2491         // and now we have
2492         m_cacheValid = true;
2493         m_cacheCentreFrame = m_centreFrame;
2494         m_cacheZoomLevel = m_zoomLevel;
2495     }
2496 
2497     if (shouldUseCache) {
2498         paint.begin(m_buffer);
2499         paint.drawPixmap(requestedPaintArea, *m_cache, requestedPaintArea);
2500         paint.end();
2501     }
2502 
2503     // Now non-cacheable items.
2504 
2505     paint.begin(m_buffer);
2506     paint.setClipRect(requestedPaintArea);
2507     setPaintFont(paint);
2508     if (scrollables.empty()) {
2509         paint.setPen(getBackground());
2510         paint.setBrush(getBackground());
2511         paint.drawRect(requestedPaintArea);
2512     }
2513 
2514     paint.setPen(getForeground());
2515     paint.setBrush(Qt::NoBrush);
2516 
2517     for (LayerList::iterator i = nonScrollables.begin();
2518          i != nonScrollables.end(); ++i) {
2519 
2520         Layer *layer = *i;
2521 
2522         bool useAligningProxy = false;
2523         if (m_useAligningProxy) {
2524             if (layer->getModel() == alignmentReferenceId ||
2525                 layer->getSourceModel() == alignmentReferenceId) {
2526                 useAligningProxy = true;
2527             }
2528         }
2529 
2530 #ifdef DEBUG_VIEW_WIDGET_PAINT
2531         SVCERR << "Painting non-scrollable layer " << layer << " (model " << layer->getModel() << ", source model " << layer->getSourceModel() << ") with shouldRepaintCache = " << shouldRepaintCache << ", useAligningProxy = " << useAligningProxy << ", dpratio = " << dpratio << ", requestedPaintArea = " << requestedPaintArea.x() << "," << requestedPaintArea.y() << " " << requestedPaintArea.width() << "x" << requestedPaintArea.height() << endl;
2532 #endif
2533 
2534         layer->paint(useAligningProxy ? &aligningProxy : &proxy,
2535                      paint, requestedPaintArea);
2536     }
2537 
2538     paint.end();
2539 
2540     // Now paint to widget from buffer: target rects from here on,
2541     // unlike all the preceding, are at formal (1x) resolution
2542 
2543     paint.begin(this);
2544     setPaintFont(paint);
2545     if (e) paint.setClipRect(e->rect());
2546 
2547     QRect finalPaintRect = e ? e->rect() : rect();
2548     paint.drawPixmap(finalPaintRect, *m_buffer,
2549                      scaledRect(finalPaintRect, dpratio));
2550 
2551     drawSelections(paint);
2552     drawPlayPointer(paint);
2553 
2554     paint.end();
2555 
2556     QFrame::paintEvent(e);
2557 }
2558 
2559 void
drawSelections(QPainter & paint)2560 View::drawSelections(QPainter &paint)
2561 {
2562     if (!hasTopLayerTimeXAxis()) return;
2563 
2564     MultiSelection::SelectionList selections;
2565 
2566     if (m_manager) {
2567         selections = m_manager->getSelections();
2568         if (m_manager->haveInProgressSelection()) {
2569             bool exclusive;
2570             Selection inProgressSelection =
2571                 m_manager->getInProgressSelection(exclusive);
2572             if (exclusive) selections.clear();
2573             selections.insert(inProgressSelection);
2574         }
2575     }
2576 
2577     paint.save();
2578 
2579     bool translucent = !areLayerColoursSignificant();
2580 
2581     if (translucent) {
2582         paint.setBrush(QColor(150, 150, 255, 80));
2583     } else {
2584         paint.setBrush(Qt::NoBrush);
2585     }
2586 
2587     sv_samplerate_t sampleRate = getModelsSampleRate();
2588 
2589     QPoint localPos;
2590     sv_frame_t illuminateFrame = -1;
2591     bool closeToLeft, closeToRight;
2592 
2593     if (shouldIlluminateLocalSelection(localPos, closeToLeft, closeToRight)) {
2594         illuminateFrame = getFrameForX(localPos.x());
2595     }
2596 
2597     const QFontMetrics &metrics = paint.fontMetrics();
2598 
2599     for (MultiSelection::SelectionList::iterator i = selections.begin();
2600          i != selections.end(); ++i) {
2601 
2602         int p0 = getXForFrame(alignFromReference(i->getStartFrame()));
2603         int p1 = getXForFrame(alignFromReference(i->getEndFrame()));
2604 
2605         if (p1 < 0 || p0 > width()) continue;
2606 
2607 #ifdef DEBUG_VIEW_WIDGET_PAINT
2608         SVDEBUG << "View::drawSelections: " << p0 << ",-1 [" << (p1-p0) << "x" << (height()+1) << "]" << endl;
2609 #endif
2610 
2611         bool illuminateThis =
2612             (illuminateFrame >= 0 && i->contains(illuminateFrame));
2613 
2614         double h = height();
2615         double penWidth = scalePenWidth(1.0);
2616         double half = penWidth/2.0;
2617 
2618         paint.setPen(QPen(QColor(150, 150, 255), penWidth));
2619 
2620         if (translucent && shouldLabelSelections()) {
2621             paint.drawRect(QRectF(p0, -penWidth, p1 - p0, h + 2*penWidth));
2622         } else {
2623             // Make the top & bottom lines of the box visible if we
2624             // are lacking some of the other visual cues.  There's no
2625             // particular logic to this, it's just a question of what
2626             // I happen to think looks nice.
2627             paint.drawRect(QRectF(p0, half, p1 - p0, h - penWidth));
2628         }
2629 
2630         if (illuminateThis) {
2631             paint.save();
2632             penWidth = scalePenWidth(2.0);
2633             half = penWidth/2.0;
2634             paint.setPen(QPen(getForeground(), penWidth));
2635             if (closeToLeft) {
2636                 paint.drawLine(QLineF(p0, half, p1, half));
2637                 paint.drawLine(QLineF(p0, half, p0, h - half));
2638                 paint.drawLine(QLineF(p0, h - half, p1, h - half));
2639             } else if (closeToRight) {
2640                 paint.drawLine(QLineF(p0, half, p1, half));
2641                 paint.drawLine(QLineF(p1, half, p1, h - half));
2642                 paint.drawLine(QLineF(p0, h - half, p1, h - half));
2643             } else {
2644                 paint.setBrush(Qt::NoBrush);
2645                 paint.drawRect(QRectF(p0, half, p1 - p0, h - penWidth));
2646             }
2647             paint.restore();
2648         }
2649 
2650         if (sampleRate && shouldLabelSelections() && m_manager &&
2651             m_manager->shouldShowSelectionExtents()) {
2652 
2653             QString startText = QString("%1 / %2")
2654                 .arg(QString::fromStdString
2655                      (RealTime::frame2RealTime
2656                       (i->getStartFrame(), sampleRate).toText(true)))
2657                 .arg(i->getStartFrame());
2658 
2659             QString endText = QString(" %1 / %2")
2660                 .arg(QString::fromStdString
2661                      (RealTime::frame2RealTime
2662                       (i->getEndFrame(), sampleRate).toText(true)))
2663                 .arg(i->getEndFrame());
2664 
2665             QString durationText = QString("(%1 / %2) ")
2666                 .arg(QString::fromStdString
2667                      (RealTime::frame2RealTime
2668                       (i->getEndFrame() - i->getStartFrame(), sampleRate)
2669                       .toText(true)))
2670                 .arg(i->getEndFrame() - i->getStartFrame());
2671 
2672     // Qt 5.13 deprecates QFontMetrics::width(), but its suggested
2673     // replacement (horizontalAdvance) was only added in Qt 5.11
2674     // which is too new for us
2675 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
2676 
2677             int sw = metrics.width(startText),
2678                 ew = metrics.width(endText),
2679                 dw = metrics.width(durationText);
2680 
2681             int sy = metrics.ascent() + metrics.height() + 4;
2682             int ey = sy;
2683             int dy = sy + metrics.height();
2684 
2685             int sx = p0 + 2;
2686             int ex = sx;
2687             int dx = sx;
2688 
2689             bool durationBothEnds = true;
2690 
2691             if (sw + ew > (p1 - p0)) {
2692                 ey += metrics.height();
2693                 dy += metrics.height();
2694                 durationBothEnds = false;
2695             }
2696 
2697             if (ew < (p1 - p0)) {
2698                 ex = p1 - 2 - ew;
2699             }
2700 
2701             if (dw < (p1 - p0)) {
2702                 dx = p1 - 2 - dw;
2703             }
2704 
2705             PaintAssistant::drawVisibleText(this, paint, sx, sy, startText,
2706                                             PaintAssistant::OutlinedText);
2707             PaintAssistant::drawVisibleText(this, paint, ex, ey, endText,
2708                                             PaintAssistant::OutlinedText);
2709             PaintAssistant::drawVisibleText(this, paint, dx, dy, durationText,
2710                                             PaintAssistant::OutlinedText);
2711             if (durationBothEnds) {
2712                 PaintAssistant::drawVisibleText(this, paint, sx, dy, durationText,
2713                                                 PaintAssistant::OutlinedText);
2714             }
2715         }
2716     }
2717 
2718     paint.restore();
2719 }
2720 
2721 void
drawPlayPointer(QPainter & paint)2722 View::drawPlayPointer(QPainter &paint)
2723 {
2724     bool showPlayPointer = true;
2725 
2726     if (m_followPlay == PlaybackScrollContinuous) {
2727         showPlayPointer = false;
2728     } else if (m_playPointerFrame <= getStartFrame() ||
2729                m_playPointerFrame >= getEndFrame()) {
2730         showPlayPointer = false;
2731     } else if (m_manager && !m_manager->isPlaying()) {
2732         if (m_playPointerFrame == getCentreFrame() &&
2733             m_manager->shouldShowCentreLine() &&
2734             m_followPlay != PlaybackIgnore) {
2735             // Don't show the play pointer when it is redundant with
2736             // the centre line
2737             showPlayPointer = false;
2738         }
2739     }
2740 
2741     if (showPlayPointer) {
2742 
2743         int playx = getXForFrame(m_playPointerFrame);
2744 
2745         paint.setPen(getForeground());
2746         paint.drawLine(playx - 1, 0, playx - 1, height() - 1);
2747         paint.drawLine(playx + 1, 0, playx + 1, height() - 1);
2748         paint.drawPoint(playx, 0);
2749         paint.drawPoint(playx, height() - 1);
2750         paint.setPen(getBackground());
2751         paint.drawLine(playx, 1, playx, height() - 2);
2752     }
2753 }
2754 
2755 void
drawMeasurementRect(QPainter & paint,const Layer * topLayer,QRect r,bool focus) const2756 View::drawMeasurementRect(QPainter &paint, const Layer *topLayer, QRect r,
2757                           bool focus) const
2758 {
2759 //    SVDEBUG << "View::drawMeasurementRect(" << r.x() << "," << r.y() << " "
2760 //              << r.width() << "x" << r.height() << ")" << endl;
2761 
2762     if (r.x() + r.width() < 0 || r.x() >= width()) return;
2763 
2764     if (r.width() != 0 || r.height() != 0) {
2765         paint.save();
2766         if (focus) {
2767             paint.setPen(Qt::NoPen);
2768             QColor brushColour(Qt::black);
2769             brushColour.setAlpha(hasLightBackground() ? 15 : 40);
2770             paint.setBrush(brushColour);
2771             if (r.x() > 0) {
2772                 paint.drawRect(0, 0, r.x(), height());
2773             }
2774             if (r.x() + r.width() < width()) {
2775                 paint.drawRect(r.x() + r.width(), 0, width()-r.x()-r.width(), height());
2776             }
2777             if (r.y() > 0) {
2778                 paint.drawRect(r.x(), 0, r.width(), r.y());
2779             }
2780             if (r.y() + r.height() < height()) {
2781                 paint.drawRect(r.x(), r.y() + r.height(), r.width(), height()-r.y()-r.height());
2782             }
2783             paint.setBrush(Qt::NoBrush);
2784         }
2785         paint.setPen(Qt::green);
2786         paint.drawRect(r);
2787         paint.restore();
2788     } else {
2789         paint.save();
2790         paint.setPen(Qt::green);
2791         paint.drawPoint(r.x(), r.y());
2792         paint.restore();
2793     }
2794 
2795     if (!focus) return;
2796 
2797     paint.save();
2798     QFont fn = paint.font();
2799     if (fn.pointSize() > 8) {
2800         fn.setPointSize(fn.pointSize() - 1);
2801         paint.setFont(fn);
2802     }
2803 
2804     int fontHeight = paint.fontMetrics().height();
2805     int fontAscent = paint.fontMetrics().ascent();
2806 
2807     double v0, v1;
2808     QString u0, u1;
2809     bool b0 = false, b1 = false;
2810 
2811     QString axs, ays, bxs, bys, dxs, dys;
2812 
2813     int axx, axy, bxx, bxy, dxx, dxy;
2814     int aw = 0, bw = 0, dw = 0;
2815 
2816     int labelCount = 0;
2817 
2818     // top-left point, x-coord
2819 
2820     if ((b0 = topLayer->getXScaleValue(this, r.x(), v0, u0))) {
2821         axs = QString("%1 %2").arg(v0).arg(u0);
2822         if (u0 == "Hz" && Pitch::isFrequencyInMidiRange(v0)) {
2823             axs = QString("%1 (%2)").arg(axs)
2824                 .arg(Pitch::getPitchLabelForFrequency(v0));
2825         }
2826         aw = paint.fontMetrics().width(axs);
2827         ++labelCount;
2828     }
2829 
2830     // bottom-right point, x-coord
2831 
2832     if (r.width() > 0) {
2833         if ((b1 = topLayer->getXScaleValue(this, r.x() + r.width(), v1, u1))) {
2834             bxs = QString("%1 %2").arg(v1).arg(u1);
2835             if (u1 == "Hz" && Pitch::isFrequencyInMidiRange(v1)) {
2836                 bxs = QString("%1 (%2)").arg(bxs)
2837                     .arg(Pitch::getPitchLabelForFrequency(v1));
2838             }
2839             bw = paint.fontMetrics().width(bxs);
2840         }
2841     }
2842 
2843     // dimension, width
2844 
2845     if (b0 && b1 && v1 != v0 && u0 == u1) {
2846         dxs = QString("[%1 %2]").arg(fabs(v1 - v0)).arg(u1);
2847         dw = paint.fontMetrics().width(dxs);
2848     }
2849 
2850     b0 = false;
2851     b1 = false;
2852 
2853     // top-left point, y-coord
2854 
2855     if ((b0 = topLayer->getYScaleValue(this, r.y(), v0, u0))) {
2856         ays = QString("%1 %2").arg(v0).arg(u0);
2857         if (u0 == "Hz" && Pitch::isFrequencyInMidiRange(v0)) {
2858             ays = QString("%1 (%2)").arg(ays)
2859                 .arg(Pitch::getPitchLabelForFrequency(v0));
2860         }
2861         aw = std::max(aw, paint.fontMetrics().width(ays));
2862         ++labelCount;
2863     }
2864 
2865     // bottom-right point, y-coord
2866 
2867     if (r.height() > 0) {
2868         if ((b1 = topLayer->getYScaleValue(this, r.y() + r.height(), v1, u1))) {
2869             bys = QString("%1 %2").arg(v1).arg(u1);
2870             if (u1 == "Hz" && Pitch::isFrequencyInMidiRange(v1)) {
2871                 bys = QString("%1 (%2)").arg(bys)
2872                     .arg(Pitch::getPitchLabelForFrequency(v1));
2873             }
2874             bw = std::max(bw, paint.fontMetrics().width(bys));
2875         }
2876     }
2877 
2878     bool bd = false;
2879     double dy = 0.f;
2880     QString du;
2881 
2882     // dimension, height
2883 
2884     if ((bd = topLayer->getYScaleDifference(this, r.y(), r.y() + r.height(),
2885                                             dy, du)) &&
2886         dy != 0) {
2887         if (du != "") {
2888             if (du == "Hz") {
2889                 int semis;
2890                 double cents;
2891                 semis = Pitch::getPitchForFrequencyDifference(v0, v1, &cents);
2892                 dys = QString("[%1 %2 (%3)]")
2893                     .arg(dy).arg(du)
2894                     .arg(Pitch::getLabelForPitchRange(semis, cents));
2895             } else {
2896                 dys = QString("[%1 %2]").arg(dy).arg(du);
2897             }
2898         } else {
2899             dys = QString("[%1]").arg(dy);
2900         }
2901         dw = std::max(dw, paint.fontMetrics().width(dys));
2902     }
2903 
2904     int mw = r.width();
2905     int mh = r.height();
2906 
2907     bool edgeLabelsInside = false;
2908     bool sizeLabelsInside = false;
2909 
2910     if (mw < std::max(aw, std::max(bw, dw)) + 4) {
2911         // defaults stand
2912     } else if (mw < aw + bw + 4) {
2913         if (mh > fontHeight * labelCount * 3 + 4) {
2914             edgeLabelsInside = true;
2915             sizeLabelsInside = true;
2916         } else if (mh > fontHeight * labelCount * 2 + 4) {
2917             edgeLabelsInside = true;
2918         }
2919     } else if (mw < aw + bw + dw + 4) {
2920         if (mh > fontHeight * labelCount * 3 + 4) {
2921             edgeLabelsInside = true;
2922             sizeLabelsInside = true;
2923         } else if (mh > fontHeight * labelCount + 4) {
2924             edgeLabelsInside = true;
2925         }
2926     } else {
2927         if (mh > fontHeight * labelCount + 4) {
2928             edgeLabelsInside = true;
2929             sizeLabelsInside = true;
2930         }
2931     }
2932 
2933     if (edgeLabelsInside) {
2934 
2935         axx = r.x() + 2;
2936         axy = r.y() + fontAscent + 2;
2937 
2938         bxx = r.x() + r.width() - bw - 2;
2939         bxy = r.y() + r.height() - (labelCount-1) * fontHeight - 2;
2940 
2941     } else {
2942 
2943         axx = r.x() - aw - 2;
2944         axy = r.y() + fontAscent;
2945 
2946         bxx = r.x() + r.width() + 2;
2947         bxy = r.y() + r.height() - (labelCount-1) * fontHeight;
2948     }
2949 
2950     dxx = r.width()/2 + r.x() - dw/2;
2951 
2952     if (sizeLabelsInside) {
2953 
2954         dxy = r.height()/2 + r.y() - (labelCount * fontHeight)/2 + fontAscent;
2955 
2956     } else {
2957 
2958         dxy = r.y() + r.height() + fontAscent + 2;
2959     }
2960 
2961     if (axs != "") {
2962         PaintAssistant::drawVisibleText(this, paint, axx, axy, axs, PaintAssistant::OutlinedText);
2963         axy += fontHeight;
2964     }
2965 
2966     if (ays != "") {
2967         PaintAssistant::drawVisibleText(this, paint, axx, axy, ays, PaintAssistant::OutlinedText);
2968         axy += fontHeight;
2969     }
2970 
2971     if (bxs != "") {
2972         PaintAssistant::drawVisibleText(this, paint, bxx, bxy, bxs, PaintAssistant::OutlinedText);
2973         bxy += fontHeight;
2974     }
2975 
2976     if (bys != "") {
2977         PaintAssistant::drawVisibleText(this, paint, bxx, bxy, bys, PaintAssistant::OutlinedText);
2978         bxy += fontHeight;
2979     }
2980 
2981     if (dxs != "") {
2982         PaintAssistant::drawVisibleText(this, paint, dxx, dxy, dxs, PaintAssistant::OutlinedText);
2983         dxy += fontHeight;
2984     }
2985 
2986     if (dys != "") {
2987         PaintAssistant::drawVisibleText(this, paint, dxx, dxy, dys, PaintAssistant::OutlinedText);
2988         dxy += fontHeight;
2989     }
2990 
2991     paint.restore();
2992 }
2993 
2994 bool
render(QPainter & paint,int xorigin,sv_frame_t f0,sv_frame_t f1)2995 View::render(QPainter &paint, int xorigin, sv_frame_t f0, sv_frame_t f1)
2996 {
2997     int x0 = int(round(m_zoomLevel.framesToPixels(double(f0))));
2998     int x1 = int(round(m_zoomLevel.framesToPixels(double(f1))));
2999 
3000     int w = x1 - x0;
3001 
3002     sv_frame_t origCentreFrame = m_centreFrame;
3003 
3004     bool someLayersIncomplete = false;
3005 
3006     for (LayerList::iterator i = m_layerStack.begin();
3007          i != m_layerStack.end(); ++i) {
3008 
3009         int c = (*i)->getCompletion(this);
3010         if (c < 100) {
3011             someLayersIncomplete = true;
3012             break;
3013         }
3014     }
3015 
3016     if (someLayersIncomplete) {
3017 
3018         QProgressDialog progress(tr("Waiting for layers to be ready..."),
3019                                  tr("Cancel"), 0, 100, this);
3020 
3021         int layerCompletion = 0;
3022 
3023         while (layerCompletion < 100) {
3024 
3025             for (LayerList::iterator i = m_layerStack.begin();
3026                  i != m_layerStack.end(); ++i) {
3027 
3028                 int c = (*i)->getCompletion(this);
3029                 if (i == m_layerStack.begin() || c < layerCompletion) {
3030                     layerCompletion = c;
3031                 }
3032             }
3033 
3034             if (layerCompletion >= 100) break;
3035 
3036             progress.setValue(layerCompletion);
3037             qApp->processEvents();
3038             if (progress.wasCanceled()) {
3039                 update();
3040                 return false;
3041             }
3042 
3043             usleep(50000);
3044         }
3045     }
3046 
3047     QProgressDialog progress(tr("Rendering image..."),
3048                              tr("Cancel"), 0, w / width(), this);
3049 
3050     for (int x = 0; x < w; x += width()) {
3051 
3052         progress.setValue(x / width());
3053         qApp->processEvents();
3054         if (progress.wasCanceled()) {
3055             m_centreFrame = origCentreFrame;
3056             update();
3057             return false;
3058         }
3059 
3060         m_centreFrame = f0 + sv_frame_t(round(m_zoomLevel.pixelsToFrames
3061                                               (x + width()/2)));
3062 
3063         QRect chunk(0, 0, width(), height());
3064 
3065         paint.setPen(getBackground());
3066         paint.setBrush(getBackground());
3067 
3068         paint.drawRect(QRect(xorigin + x, 0, width(), height()));
3069 
3070         paint.setPen(getForeground());
3071         paint.setBrush(Qt::NoBrush);
3072 
3073         for (LayerList::iterator i = m_layerStack.begin();
3074              i != m_layerStack.end(); ++i) {
3075             if (!((*i)->isLayerDormant(this))){
3076 
3077                 paint.setRenderHint(QPainter::Antialiasing, false);
3078 
3079                 paint.save();
3080                 paint.translate(xorigin + x, 0);
3081 
3082                 SVCERR << "Centre frame now: " << m_centreFrame << " drawing to " << chunk.x() + x + xorigin << ", " << chunk.width() << endl;
3083 
3084                 (*i)->setSynchronousPainting(true);
3085 
3086                 (*i)->paint(this, paint, chunk);
3087 
3088                 (*i)->setSynchronousPainting(false);
3089 
3090                 paint.restore();
3091             }
3092         }
3093     }
3094 
3095     m_centreFrame = origCentreFrame;
3096     update();
3097     return true;
3098 }
3099 
3100 QImage *
renderToNewImage()3101 View::renderToNewImage()
3102 {
3103     sv_frame_t f0 = getModelsStartFrame();
3104     sv_frame_t f1 = getModelsEndFrame();
3105 
3106     return renderPartToNewImage(f0, f1);
3107 }
3108 
3109 QImage *
renderPartToNewImage(sv_frame_t f0,sv_frame_t f1)3110 View::renderPartToNewImage(sv_frame_t f0, sv_frame_t f1)
3111 {
3112     int x0 = int(round(getZoomLevel().framesToPixels(double(f0))));
3113     int x1 = int(round(getZoomLevel().framesToPixels(double(f1))));
3114 
3115     QImage *image = new QImage(x1 - x0, height(), QImage::Format_RGB32);
3116 
3117     QPainter *paint = new QPainter(image);
3118     if (!render(*paint, 0, f0, f1)) {
3119         delete paint;
3120         delete image;
3121         return nullptr;
3122     } else {
3123         delete paint;
3124         return image;
3125     }
3126 }
3127 
3128 QSize
getRenderedImageSize()3129 View::getRenderedImageSize()
3130 {
3131     sv_frame_t f0 = getModelsStartFrame();
3132     sv_frame_t f1 = getModelsEndFrame();
3133 
3134     return getRenderedPartImageSize(f0, f1);
3135 }
3136 
3137 QSize
getRenderedPartImageSize(sv_frame_t f0,sv_frame_t f1)3138 View::getRenderedPartImageSize(sv_frame_t f0, sv_frame_t f1)
3139 {
3140     int x0 = int(round(getZoomLevel().framesToPixels(double(f0))));
3141     int x1 = int(round(getZoomLevel().framesToPixels(double(f1))));
3142 
3143     return QSize(x1 - x0, height());
3144 }
3145 
3146 bool
renderToSvgFile(QString filename)3147 View::renderToSvgFile(QString filename)
3148 {
3149     sv_frame_t f0 = getModelsStartFrame();
3150     sv_frame_t f1 = getModelsEndFrame();
3151 
3152     return renderPartToSvgFile(filename, f0, f1);
3153 }
3154 
3155 bool
renderPartToSvgFile(QString filename,sv_frame_t f0,sv_frame_t f1)3156 View::renderPartToSvgFile(QString filename, sv_frame_t f0, sv_frame_t f1)
3157 {
3158     int x0 = int(round(getZoomLevel().framesToPixels(double(f0))));
3159     int x1 = int(round(getZoomLevel().framesToPixels(double(f1))));
3160 
3161     QSvgGenerator generator;
3162     generator.setFileName(filename);
3163     generator.setSize(QSize(x1 - x0, height()));
3164     generator.setViewBox(QRect(0, 0, x1 - x0, height()));
3165     generator.setTitle(tr("Exported image from %1")
3166                        .arg(QApplication::applicationName()));
3167 
3168     QPainter paint;
3169     paint.begin(&generator);
3170     bool result = render(paint, 0, f0, f1);
3171     paint.end();
3172     return result;
3173 }
3174 
3175 void
toXml(QTextStream & stream,QString indent,QString extraAttributes) const3176 View::toXml(QTextStream &stream,
3177             QString indent, QString extraAttributes) const
3178 {
3179     stream << indent;
3180 
3181     int classicZoomValue, deepZoomValue;
3182 
3183     if (m_zoomLevel.zone == ZoomLevel::FramesPerPixel) {
3184         classicZoomValue = m_zoomLevel.level;
3185         deepZoomValue = 1;
3186     } else {
3187         classicZoomValue = 1;
3188         deepZoomValue = m_zoomLevel.level;
3189     }
3190 
3191     stream << QString("<view "
3192                       "centre=\"%1\" "
3193                       "zoom=\"%2\" "
3194                       "deepZoom=\"%3\" "
3195                       "followPan=\"%4\" "
3196                       "followZoom=\"%5\" "
3197                       "tracking=\"%6\" "
3198                       " %7>\n")
3199         .arg(m_centreFrame)
3200         .arg(classicZoomValue)
3201         .arg(deepZoomValue)
3202         .arg(m_followPan)
3203         .arg(m_followZoom)
3204         .arg(m_followPlay == PlaybackScrollContinuous ? "scroll" :
3205              m_followPlay == PlaybackScrollPageWithCentre ? "page" :
3206              m_followPlay == PlaybackScrollPage ? "daw" :
3207              "ignore")
3208         .arg(extraAttributes);
3209 
3210     for (int i = 0; i < (int)m_fixedOrderLayers.size(); ++i) {
3211         bool visible = !m_fixedOrderLayers[i]->isLayerDormant(this);
3212         m_fixedOrderLayers[i]->toBriefXml(stream, indent + "  ",
3213                                           QString("visible=\"%1\"")
3214                                           .arg(visible ? "true" : "false"));
3215     }
3216 
3217     stream << indent + "</view>\n";
3218 }
3219 
ViewPropertyContainer(View * v)3220 ViewPropertyContainer::ViewPropertyContainer(View *v) :
3221     m_v(v)
3222 {
3223 //    SVCERR << "ViewPropertyContainer: " << getId() << " is owned by View " << v << endl;
3224     connect(m_v, SIGNAL(propertyChanged(PropertyContainer::PropertyName)),
3225             this, SIGNAL(propertyChanged(PropertyContainer::PropertyName)));
3226 }
3227 
~ViewPropertyContainer()3228 ViewPropertyContainer::~ViewPropertyContainer()
3229 {
3230 }
3231