Fixes segfault on close. Using the right objective (d_main_gui) instead of d_object...
[debian/gnuradio] / gr-qtgui / src / lib / WaterfallDisplayPlot.cc
1 #ifndef WATERFALL_DISPLAY_PLOT_C
2 #define WATERFALL_DISPLAY_PLOT_C
3
4 #include <WaterfallDisplayPlot.h>
5
6 #include <qwt_color_map.h>
7 #include <qwt_scale_widget.h>
8 #include <qwt_scale_draw.h>
9 #include <qwt_plot_zoomer.h>
10 #include <qwt_plot_panner.h>
11 #include <qwt_plot_layout.h>
12
13 #include <qapplication.h>
14
15 class FreqOffsetAndPrecisionClass
16 {
17 public:
18   FreqOffsetAndPrecisionClass(const int freqPrecision)
19   {
20     _frequencyPrecision = freqPrecision;
21     _centerFrequency = 0;
22   }
23
24   virtual ~FreqOffsetAndPrecisionClass()
25   {
26   }
27
28   virtual unsigned int GetFrequencyPrecision() const
29   {
30     return _frequencyPrecision;
31   }
32
33   virtual void SetFrequencyPrecision(const unsigned int newPrecision)
34   {
35     _frequencyPrecision = newPrecision;
36   }
37
38   virtual double GetCenterFrequency() const
39   {
40     return _centerFrequency;
41   }
42
43   virtual void SetCenterFrequency(const double newFreq)
44   {
45     _centerFrequency = newFreq;
46   }
47
48 protected:
49   unsigned int _frequencyPrecision;
50   double _centerFrequency;
51
52 private:
53
54 };
55
56 class WaterfallFreqDisplayScaleDraw: public QwtScaleDraw, public FreqOffsetAndPrecisionClass{
57 public:
58   WaterfallFreqDisplayScaleDraw(const unsigned int precision)
59     : QwtScaleDraw(), FreqOffsetAndPrecisionClass(precision)
60   {
61   }
62
63   virtual ~WaterfallFreqDisplayScaleDraw()
64   {
65   }
66
67   QwtText label(double value) const
68   {
69     return QString("%1").arg(value, 0, 'f', GetFrequencyPrecision());
70   }
71
72   virtual void initiateUpdate()
73   {
74     invalidateCache();
75   }
76
77 protected:
78
79 private:
80
81 };
82
83 class TimeScaleData
84 {
85 public:
86   TimeScaleData()
87   {
88     timespec_reset(&_zeroTime);
89     _secondsPerLine = 1.0;
90   }
91   
92   virtual ~TimeScaleData()
93   {    
94   }
95
96   virtual timespec GetZeroTime() const
97   {
98     return _zeroTime;
99   }
100   
101   virtual void SetZeroTime(const timespec newTime)
102   {
103     _zeroTime = newTime;
104   }
105
106   virtual void SetSecondsPerLine(const double newTime)
107   {
108     _secondsPerLine = newTime;
109   }
110
111   virtual double GetSecondsPerLine() const
112   {
113     return _secondsPerLine;
114   }
115
116   
117 protected:
118   timespec _zeroTime;
119   double _secondsPerLine;
120   
121 private:
122   
123 };
124
125 class QwtTimeScaleDraw: public QwtScaleDraw, public TimeScaleData
126 {
127 public:
128   QwtTimeScaleDraw():QwtScaleDraw(),TimeScaleData()
129   {    
130   }
131
132   virtual ~QwtTimeScaleDraw()
133   {    
134   }
135
136   virtual QwtText label(double value) const
137   {
138     QwtText returnLabel("");
139
140     timespec lineTime = timespec_add(GetZeroTime(), (-value) * GetSecondsPerLine());
141     struct tm timeTm;
142     gmtime_r(&lineTime.tv_sec, &timeTm);
143     returnLabel = (QString("").sprintf("%04d/%02d/%02d\n%02d:%02d:%02d.%03ld",
144                                        timeTm.tm_year+1900, timeTm.tm_mon+1,
145                                        timeTm.tm_mday, timeTm.tm_hour, timeTm.tm_min,
146                                        timeTm.tm_sec, lineTime.tv_nsec/1000000));
147     return returnLabel;
148   }
149
150   virtual void initiateUpdate()
151   {
152     // Do this in one call rather than when zeroTime and secondsPerLine
153     // updates is to prevent the display from being updated too often...
154     invalidateCache();
155   }
156   
157 protected:
158
159 private:
160
161 };
162
163 class WaterfallZoomer: public QwtPlotZoomer, public TimeScaleData, 
164                        public FreqOffsetAndPrecisionClass
165 {
166 public:
167   WaterfallZoomer(QwtPlotCanvas* canvas, const unsigned int freqPrecision)
168     : QwtPlotZoomer(canvas), TimeScaleData(), 
169       FreqOffsetAndPrecisionClass(freqPrecision)
170   {
171     setTrackerMode(QwtPicker::AlwaysOn);
172   }
173
174   virtual ~WaterfallZoomer()
175   {
176   }
177   
178   virtual void updateTrackerText()
179   {
180     updateDisplay();
181   }
182
183   void SetUnitType(const std::string &type)
184   {
185     _unitType = type;
186   }
187
188 protected:
189   virtual QwtText trackerText( const QwtDoublePoint& p ) const 
190   {
191     QString yLabel("");
192
193     timespec lineTime = timespec_add(GetZeroTime(), (-p.y()) * GetSecondsPerLine());
194     struct tm timeTm;
195     gmtime_r(&lineTime.tv_sec, &timeTm);
196     yLabel = (QString("").sprintf("%04d/%02d/%02d %02d:%02d:%02d.%03ld",
197                                   timeTm.tm_year+1900, timeTm.tm_mon+1,
198                                   timeTm.tm_mday, timeTm.tm_hour, timeTm.tm_min,
199                                   timeTm.tm_sec, lineTime.tv_nsec/1000000));
200
201     QwtText t(QString("%1 %2, %3").
202               arg(p.x(), 0, 'f', GetFrequencyPrecision()).
203               arg(_unitType.c_str()).arg(yLabel));
204     return t;
205   }
206
207 private:
208   std::string _unitType;
209 };
210
211
212 const int WaterfallDisplayPlot::INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR;
213 const int WaterfallDisplayPlot::INTENSITY_COLOR_MAP_TYPE_WHITE_HOT;
214 const int WaterfallDisplayPlot::INTENSITY_COLOR_MAP_TYPE_BLACK_HOT;
215 const int WaterfallDisplayPlot::INTENSITY_COLOR_MAP_TYPE_INCANDESCENT;
216 const int WaterfallDisplayPlot::INTENSITY_COLOR_MAP_TYPE_USER_DEFINED;
217
218 WaterfallDisplayPlot::WaterfallDisplayPlot(QWidget* parent)
219   : QwtPlot(parent)
220 {
221   _zoomer = NULL;
222   _startFrequency = 0;
223   _stopFrequency = 4000;
224   
225   resize(parent->width(), parent->height());
226   _numPoints = 1024;
227
228   _waterfallData = new WaterfallData(_startFrequency, _stopFrequency, _numPoints, 200);
229
230   QPalette palette;
231   palette.setColor(canvas()->backgroundRole(), QColor("white"));
232   canvas()->setPalette(palette);   
233
234   setAxisTitle(QwtPlot::xBottom, "Frequency (Hz)");
235   setAxisScaleDraw(QwtPlot::xBottom, new WaterfallFreqDisplayScaleDraw(0));
236
237   setAxisTitle(QwtPlot::yLeft, "Time");
238   setAxisScaleDraw(QwtPlot::yLeft, new QwtTimeScaleDraw());
239
240   timespec_reset(&_lastReplot);
241
242   d_spectrogram = new PlotWaterfall(_waterfallData, "Waterfall Display");
243
244   _intensityColorMapType = INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR;
245
246   QwtLinearColorMap colorMap(Qt::darkCyan, Qt::white);
247   colorMap.addColorStop(0.25, Qt::cyan);
248   colorMap.addColorStop(0.5, Qt::yellow);
249   colorMap.addColorStop(0.75, Qt::red);
250
251   d_spectrogram->setColorMap(colorMap);
252   
253   d_spectrogram->attach(this);
254   
255   // LeftButton for the zooming
256   // MidButton for the panning
257   // RightButton: zoom out by 1
258   // Ctrl+RighButton: zoom out to full size
259   
260   _zoomer = new WaterfallZoomer(canvas(), 0);
261 #if QT_VERSION < 0x040000
262   _zoomer->setMousePattern(QwtEventPattern::MouseSelect2,
263                            Qt::RightButton, Qt::ControlModifier);
264 #else
265   _zoomer->setMousePattern(QwtEventPattern::MouseSelect2,
266                            Qt::RightButton, Qt::ControlModifier);
267 #endif
268   _zoomer->setMousePattern(QwtEventPattern::MouseSelect3,
269                            Qt::RightButton);
270   
271   _panner = new QwtPlotPanner(canvas());
272   _panner->setAxisEnabled(QwtPlot::yRight, false);
273   _panner->setMouseButton(Qt::MidButton);
274   
275   // Avoid jumping when labels with more/less digits
276   // appear/disappear when scrolling vertically
277   
278   const QFontMetrics fm(axisWidget(QwtPlot::yLeft)->font());
279   QwtScaleDraw *sd = axisScaleDraw(QwtPlot::yLeft);
280   sd->setMinimumExtent( fm.width("100.00") );
281   
282   const QColor c(Qt::white);
283   _zoomer->setRubberBandPen(c);
284   _zoomer->setTrackerPen(c);
285
286   _UpdateIntensityRangeDisplay();
287 }
288
289 WaterfallDisplayPlot::~WaterfallDisplayPlot()
290 {
291   delete _waterfallData;
292   delete d_spectrogram;
293 }
294
295 void 
296 WaterfallDisplayPlot::Reset()
297 {
298   _waterfallData->ResizeData(_startFrequency, _stopFrequency, _numPoints);
299   _waterfallData->Reset();
300
301   // Load up the new base zoom settings
302   QwtDoubleRect newSize = _zoomer->zoomBase();
303   newSize.setLeft(_startFrequency);
304   newSize.setWidth(_stopFrequency-_startFrequency);
305   _zoomer->zoom(newSize);
306   _zoomer->setZoomBase(newSize);
307   _zoomer->zoom(0);
308 }
309
310 void
311 WaterfallDisplayPlot::SetFrequencyRange(const double constStartFreq,
312                                         const double constStopFreq,
313                                         const double constCenterFreq,
314                                         const bool useCenterFrequencyFlag,
315                                         const double units, const std::string &strunits)
316 {
317   double startFreq = constStartFreq / units;
318   double stopFreq = constStopFreq / units;
319   double centerFreq = constCenterFreq / units;
320
321   _useCenterFrequencyFlag = useCenterFrequencyFlag;
322
323   if(_useCenterFrequencyFlag){
324     startFreq = (startFreq + centerFreq);
325     stopFreq = (stopFreq + centerFreq);
326   }
327
328   bool reset = false;
329   if((startFreq != _startFrequency) || (stopFreq != _stopFrequency))
330     reset = true;
331
332   if(stopFreq > startFreq) {
333     _startFrequency = startFreq;
334     _stopFrequency = stopFreq;
335
336  
337     if((axisScaleDraw(QwtPlot::xBottom) != NULL) && (_zoomer != NULL)){
338       double display_units = ceil(log10(units)/2.0);
339       setAxisScale(QwtPlot::xBottom, _startFrequency, _stopFrequency);
340       setAxisScaleDraw(QwtPlot::xBottom, new WaterfallFreqDisplayScaleDraw(display_units));
341
342       if(reset) {
343         Reset();
344       }
345
346       ((WaterfallZoomer*)_zoomer)->SetFrequencyPrecision(display_units);
347       ((WaterfallZoomer*)_zoomer)->SetUnitType(strunits);
348
349       // Load up the new base zoom settings
350       _zoomer->setZoomBase();
351       
352       // Zooms back to the base and clears any other zoom levels
353       _zoomer->zoom(0);
354     }
355   }
356 }
357
358
359 double
360 WaterfallDisplayPlot::GetStartFrequency() const
361 {
362   return _startFrequency;
363 }
364
365 double
366 WaterfallDisplayPlot::GetStopFrequency() const
367 {
368   return _stopFrequency;
369 }
370
371 void
372 WaterfallDisplayPlot::PlotNewData(const double* dataPoints, 
373                                   const int64_t numDataPoints,
374                                   const double timePerFFT,
375                                   const timespec timestamp,
376                                   const int droppedFrames)
377 {
378   if(numDataPoints > 0){
379     if(numDataPoints != _numPoints){
380       _numPoints = numDataPoints;
381       
382       Reset();
383       
384       d_spectrogram->invalidateCache();
385       d_spectrogram->itemChanged();
386       
387       if(isVisible()){
388         replot();
389       }
390       
391       _lastReplot = get_highres_clock();
392     }
393
394     if(diff_timespec(get_highres_clock(), _lastReplot) > timePerFFT) {
395       //FIXME: We may want to average the data between these updates to smooth display
396       _waterfallData->addFFTData(dataPoints, numDataPoints, droppedFrames);
397       _waterfallData->IncrementNumLinesToUpdate();
398       
399       QwtTimeScaleDraw* timeScale = (QwtTimeScaleDraw*)axisScaleDraw(QwtPlot::yLeft);
400       timeScale->SetSecondsPerLine(timePerFFT);
401       timeScale->SetZeroTime(timestamp);
402       
403       ((WaterfallZoomer*)_zoomer)->SetSecondsPerLine(timePerFFT);
404       ((WaterfallZoomer*)_zoomer)->SetZeroTime(timestamp);
405       
406       d_spectrogram->invalidateCache();
407       d_spectrogram->itemChanged();
408       
409       replot();
410
411       _lastReplot = get_highres_clock();
412     }
413   }
414 }
415
416 void
417 WaterfallDisplayPlot::SetIntensityRange(const double minIntensity, 
418                                              const double maxIntensity)
419 {
420   _waterfallData->setRange(QwtDoubleInterval(minIntensity, maxIntensity));
421
422   emit UpdatedLowerIntensityLevel(minIntensity);
423   emit UpdatedUpperIntensityLevel(maxIntensity);
424
425   _UpdateIntensityRangeDisplay();
426 }
427
428 void
429 WaterfallDisplayPlot::replot()
430 {
431   QwtTimeScaleDraw* timeScale = (QwtTimeScaleDraw*)axisScaleDraw(QwtPlot::yLeft);
432   timeScale->initiateUpdate();
433
434   WaterfallFreqDisplayScaleDraw* freqScale = (WaterfallFreqDisplayScaleDraw*)axisScaleDraw(QwtPlot::xBottom);
435   freqScale->initiateUpdate();
436
437   // Update the time axis display
438   if(axisWidget(QwtPlot::yLeft) != NULL){
439     axisWidget(QwtPlot::yLeft)->update();
440   }
441
442   // Update the Frequency Offset Display
443   if(axisWidget(QwtPlot::xBottom) != NULL){
444     axisWidget(QwtPlot::xBottom)->update();
445   }
446
447   if(_zoomer != NULL){
448     ((WaterfallZoomer*)_zoomer)->updateTrackerText();
449   }
450
451   QwtPlot::replot();
452 }
453
454 void
455 WaterfallDisplayPlot::resizeSlot( QSize *s )
456 {
457   resize(s->width(), s->height());
458 }
459
460 int
461 WaterfallDisplayPlot::GetIntensityColorMapType() const
462 {
463   return _intensityColorMapType;
464 }
465
466 void
467 WaterfallDisplayPlot::SetIntensityColorMapType(const int newType, 
468                                                const QColor lowColor, 
469                                                const QColor highColor)
470 {
471   if((_intensityColorMapType != newType) || 
472      ((newType == INTENSITY_COLOR_MAP_TYPE_USER_DEFINED) &&
473       (lowColor.isValid() && highColor.isValid()))){
474     switch(newType){
475     case INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR:{
476       _intensityColorMapType = newType;
477       QwtLinearColorMap colorMap(Qt::darkCyan, Qt::white);
478       colorMap.addColorStop(0.25, Qt::cyan);
479       colorMap.addColorStop(0.5, Qt::yellow);
480       colorMap.addColorStop(0.75, Qt::red);
481       d_spectrogram->setColorMap(colorMap);
482       break;
483     }
484     case INTENSITY_COLOR_MAP_TYPE_WHITE_HOT:{
485       _intensityColorMapType = newType;
486       QwtLinearColorMap colorMap(Qt::black, Qt::white);
487       d_spectrogram->setColorMap(colorMap);
488       break;
489     }
490     case INTENSITY_COLOR_MAP_TYPE_BLACK_HOT:{
491       _intensityColorMapType = newType;
492       QwtLinearColorMap colorMap(Qt::white, Qt::black);
493       d_spectrogram->setColorMap(colorMap);
494       break;
495     }
496     case INTENSITY_COLOR_MAP_TYPE_INCANDESCENT:{
497       _intensityColorMapType = newType;
498       QwtLinearColorMap colorMap(Qt::black, Qt::white);
499       colorMap.addColorStop(0.5, Qt::darkRed);
500       d_spectrogram->setColorMap(colorMap);
501       break;
502     }
503     case INTENSITY_COLOR_MAP_TYPE_USER_DEFINED:{
504       _userDefinedLowIntensityColor = lowColor;
505       _userDefinedHighIntensityColor = highColor;
506       _intensityColorMapType = newType;
507       QwtLinearColorMap colorMap(_userDefinedLowIntensityColor, _userDefinedHighIntensityColor);
508       d_spectrogram->setColorMap(colorMap);
509       break;
510     }
511     default: break;
512     }
513     
514     _UpdateIntensityRangeDisplay();
515   }
516 }
517
518 const QColor
519 WaterfallDisplayPlot::GetUserDefinedLowIntensityColor() const
520 {
521   return _userDefinedLowIntensityColor;
522 }
523
524 const QColor
525 WaterfallDisplayPlot::GetUserDefinedHighIntensityColor() const
526 {
527   return _userDefinedHighIntensityColor;
528 }
529
530 void
531 WaterfallDisplayPlot::_UpdateIntensityRangeDisplay()
532 {
533   QwtScaleWidget *rightAxis = axisWidget(QwtPlot::yRight);
534   rightAxis->setTitle("Intensity (dB)");
535   rightAxis->setColorBarEnabled(true);
536   rightAxis->setColorMap(d_spectrogram->data()->range(),
537                          d_spectrogram->colorMap());
538
539   setAxisScale(QwtPlot::yRight, 
540                d_spectrogram->data()->range().minValue(),
541                d_spectrogram->data()->range().maxValue() );
542   enableAxis(QwtPlot::yRight);
543   
544   plotLayout()->setAlignCanvasToScales(true);
545
546   // Tell the display to redraw everything
547   d_spectrogram->invalidateCache();
548   d_spectrogram->itemChanged();
549
550   // Draw again
551   replot();
552
553   // Update the last replot timer
554   _lastReplot = get_highres_clock();
555 }
556
557 #endif /* WATERFALL_DISPLAY_PLOT_C */