b23612524fe2df3bce71417f91d11a4ac9e5038d
[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, public FreqOffsetAndPrecisionClass
164 {
165 public:
166   WaterfallZoomer(QwtPlotCanvas* canvas, const unsigned int freqPrecision)
167     : QwtPlotZoomer(canvas), TimeScaleData(), 
168       FreqOffsetAndPrecisionClass(freqPrecision)
169   {
170     setTrackerMode(QwtPicker::AlwaysOn);
171   }
172
173   virtual ~WaterfallZoomer()
174   {
175   }
176   
177   virtual void updateTrackerText()
178   {
179     updateDisplay();
180   }
181
182   void SetUnitType(const std::string &type)
183   {
184     _unitType = type;
185   }
186
187 protected:
188   virtual QwtText trackerText( const QwtDoublePoint& p ) const 
189   {
190     QString yLabel("");
191
192     timespec lineTime = timespec_add(GetZeroTime(), (-p.y()) * GetSecondsPerLine());
193     struct tm timeTm;
194     gmtime_r(&lineTime.tv_sec, &timeTm);
195     yLabel = (QString("").sprintf("%04d/%02d/%02d %02d:%02d:%02d.%03ld",
196                                   timeTm.tm_year+1900, timeTm.tm_mon+1,
197                                   timeTm.tm_mday, timeTm.tm_hour, timeTm.tm_min,
198                                   timeTm.tm_sec, lineTime.tv_nsec/1000000));
199
200     QwtText t(QString("%1 %2, %3").arg(p.x(), 0, 'f',
201                                        GetFrequencyPrecision()).arg(_unitType.c_str()).arg(yLabel));
202
203     return t;
204   }
205
206 private:
207   std::string _unitType;
208 };
209
210
211 const int WaterfallDisplayPlot::INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR;
212 const int WaterfallDisplayPlot::INTENSITY_COLOR_MAP_TYPE_WHITE_HOT;
213 const int WaterfallDisplayPlot::INTENSITY_COLOR_MAP_TYPE_BLACK_HOT;
214 const int WaterfallDisplayPlot::INTENSITY_COLOR_MAP_TYPE_INCANDESCENT;
215 const int WaterfallDisplayPlot::INTENSITY_COLOR_MAP_TYPE_USER_DEFINED;
216
217 WaterfallDisplayPlot::WaterfallDisplayPlot(QWidget* parent)
218   : QwtPlot(parent)
219 {
220   _zoomer = NULL;
221   _startFrequency = 0;
222   _stopFrequency = 4000;
223   
224   resize(parent->width(), parent->height());
225   _numPoints = 1024;
226
227   _displayIntervalTime = (1.0/5.0); // 1/5 of a second between updates
228
229   _waterfallData = new WaterfallData(_startFrequency, _stopFrequency, _numPoints, 200);
230
231   QPalette palette;
232   palette.setColor(canvas()->backgroundRole(), QColor("white"));
233   canvas()->setPalette(palette);   
234
235   setAxisTitle(QwtPlot::xBottom, "Frequency (Hz)");
236   setAxisScaleDraw(QwtPlot::xBottom, new WaterfallFreqDisplayScaleDraw(0));
237
238   setAxisTitle(QwtPlot::yLeft, "Time");
239   setAxisScaleDraw(QwtPlot::yLeft, new QwtTimeScaleDraw());
240
241   timespec_reset(&_lastReplot);
242
243   d_spectrogram = new PlotWaterfall(_waterfallData, "Waterfall Display");
244
245   _intensityColorMapType = INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR;
246
247   QwtLinearColorMap colorMap(Qt::darkCyan, Qt::white);
248   colorMap.addColorStop(0.25, Qt::cyan);
249   colorMap.addColorStop(0.5, Qt::yellow);
250   colorMap.addColorStop(0.75, Qt::red);
251
252   d_spectrogram->setColorMap(colorMap);
253   
254   d_spectrogram->attach(this);
255   
256   // LeftButton for the zooming
257   // MidButton for the panning
258   // RightButton: zoom out by 1
259   // Ctrl+RighButton: zoom out to full size
260   
261   _zoomer = new WaterfallZoomer(canvas(), 0);
262 #if QT_VERSION < 0x040000
263   _zoomer->setMousePattern(QwtEventPattern::MouseSelect2,
264                            Qt::RightButton, Qt::ControlModifier);
265 #else
266   _zoomer->setMousePattern(QwtEventPattern::MouseSelect2,
267                            Qt::RightButton, Qt::ControlModifier);
268 #endif
269   _zoomer->setMousePattern(QwtEventPattern::MouseSelect3,
270                            Qt::RightButton);
271   
272   _panner = new QwtPlotPanner(canvas());
273   _panner->setAxisEnabled(QwtPlot::yRight, false);
274   _panner->setMouseButton(Qt::MidButton);
275   
276   // Avoid jumping when labels with more/less digits
277   // appear/disappear when scrolling vertically
278   
279   const QFontMetrics fm(axisWidget(QwtPlot::yLeft)->font());
280   QwtScaleDraw *sd = axisScaleDraw(QwtPlot::yLeft);
281   sd->setMinimumExtent( fm.width("100.00") );
282   
283   const QColor c(Qt::white);
284   _zoomer->setRubberBandPen(c);
285   _zoomer->setTrackerPen(c);
286
287   _UpdateIntensityRangeDisplay();
288 }
289
290 WaterfallDisplayPlot::~WaterfallDisplayPlot()
291 {
292   delete _waterfallData;
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     _waterfallData->addFFTData(dataPoints, numDataPoints, droppedFrames);
395     _waterfallData->IncrementNumLinesToUpdate();
396
397     QwtTimeScaleDraw* timeScale = (QwtTimeScaleDraw*)axisScaleDraw(QwtPlot::yLeft);
398     timeScale->SetSecondsPerLine(timePerFFT);
399     timeScale->SetZeroTime(timestamp);
400
401     ((WaterfallZoomer*)_zoomer)->SetSecondsPerLine(timePerFFT);
402     ((WaterfallZoomer*)_zoomer)->SetZeroTime(timestamp);
403   }
404
405   // Allow at least a 50% duty cycle
406   if(diff_timespec(get_highres_clock(), _lastReplot) > _displayIntervalTime){
407
408     d_spectrogram->invalidateCache();
409     d_spectrogram->itemChanged();
410
411     // Only update when window is visible
412     if(isVisible()){
413       replot();
414     }
415
416     _lastReplot = get_highres_clock();
417   }
418 }
419
420 void
421 WaterfallDisplayPlot::SetIntensityRange(const double minIntensity, 
422                                              const double maxIntensity)
423 {
424   _waterfallData->setRange(QwtDoubleInterval(minIntensity, maxIntensity));
425
426   emit UpdatedLowerIntensityLevel(minIntensity);
427   emit UpdatedUpperIntensityLevel(maxIntensity);
428
429   _UpdateIntensityRangeDisplay();
430 }
431
432 void
433 WaterfallDisplayPlot::replot()
434 {
435   const timespec startTime = get_highres_clock();
436
437   QwtTimeScaleDraw* timeScale = (QwtTimeScaleDraw*)axisScaleDraw(QwtPlot::yLeft);
438   timeScale->initiateUpdate();
439
440   WaterfallFreqDisplayScaleDraw* freqScale = (WaterfallFreqDisplayScaleDraw*)axisScaleDraw(QwtPlot::xBottom);
441   freqScale->initiateUpdate();
442
443   // Update the time axis display
444   if(axisWidget(QwtPlot::yLeft) != NULL){
445     axisWidget(QwtPlot::yLeft)->update();
446   }
447
448   // Update the Frequency Offset Display
449   if(axisWidget(QwtPlot::xBottom) != NULL){
450     axisWidget(QwtPlot::xBottom)->update();
451   }
452
453   if(_zoomer != NULL){
454     ((WaterfallZoomer*)_zoomer)->updateTrackerText();
455   }
456
457   QwtPlot::replot();
458
459   double differenceTime = (diff_timespec(get_highres_clock(), startTime));
460   
461   // Require at least a 5% duty cycle
462   differenceTime *= 19.0;
463   if(differenceTime > (1.0/5.0)){
464     _displayIntervalTime = differenceTime;
465   }
466 }
467
468 void
469 WaterfallDisplayPlot::resizeSlot( QSize *s )
470 {
471   resize(s->width(), s->height());
472 }
473
474 int
475 WaterfallDisplayPlot::GetIntensityColorMapType() const
476 {
477   return _intensityColorMapType;
478 }
479
480 void
481 WaterfallDisplayPlot::SetIntensityColorMapType(const int newType, 
482                                                const QColor lowColor, 
483                                                const QColor highColor)
484 {
485   if((_intensityColorMapType != newType) || 
486      ((newType == INTENSITY_COLOR_MAP_TYPE_USER_DEFINED) &&
487       (lowColor.isValid() && highColor.isValid()))){
488     switch(newType){
489     case INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR:{
490       _intensityColorMapType = newType;
491       QwtLinearColorMap colorMap(Qt::darkCyan, Qt::white);
492       colorMap.addColorStop(0.25, Qt::cyan);
493       colorMap.addColorStop(0.5, Qt::yellow);
494       colorMap.addColorStop(0.75, Qt::red);
495       d_spectrogram->setColorMap(colorMap);
496       break;
497     }
498     case INTENSITY_COLOR_MAP_TYPE_WHITE_HOT:{
499       _intensityColorMapType = newType;
500       QwtLinearColorMap colorMap(Qt::black, Qt::white);
501       d_spectrogram->setColorMap(colorMap);
502       break;
503     }
504     case INTENSITY_COLOR_MAP_TYPE_BLACK_HOT:{
505       _intensityColorMapType = newType;
506       QwtLinearColorMap colorMap(Qt::white, Qt::black);
507       d_spectrogram->setColorMap(colorMap);
508       break;
509     }
510     case INTENSITY_COLOR_MAP_TYPE_INCANDESCENT:{
511       _intensityColorMapType = newType;
512       QwtLinearColorMap colorMap(Qt::black, Qt::white);
513       colorMap.addColorStop(0.5, Qt::darkRed);
514       d_spectrogram->setColorMap(colorMap);
515       break;
516     }
517     case INTENSITY_COLOR_MAP_TYPE_USER_DEFINED:{
518       _userDefinedLowIntensityColor = lowColor;
519       _userDefinedHighIntensityColor = highColor;
520       _intensityColorMapType = newType;
521       QwtLinearColorMap colorMap(_userDefinedLowIntensityColor, _userDefinedHighIntensityColor);
522       d_spectrogram->setColorMap(colorMap);
523       break;
524     }
525     default: break;
526     }
527     
528     _UpdateIntensityRangeDisplay();
529   }
530 }
531
532 const QColor
533 WaterfallDisplayPlot::GetUserDefinedLowIntensityColor() const
534 {
535   return _userDefinedLowIntensityColor;
536 }
537
538 const QColor
539 WaterfallDisplayPlot::GetUserDefinedHighIntensityColor() const
540 {
541   return _userDefinedHighIntensityColor;
542 }
543
544 void
545 WaterfallDisplayPlot::_UpdateIntensityRangeDisplay()
546 {
547   QwtScaleWidget *rightAxis = axisWidget(QwtPlot::yRight);
548   rightAxis->setTitle("Intensity (dB)");
549   rightAxis->setColorBarEnabled(true);
550   rightAxis->setColorMap(d_spectrogram->data()->range(),
551                          d_spectrogram->colorMap());
552
553   setAxisScale(QwtPlot::yRight, 
554                d_spectrogram->data()->range().minValue(),
555                d_spectrogram->data()->range().maxValue() );
556   enableAxis(QwtPlot::yRight);
557   
558   plotLayout()->setAlignCanvasToScales(true);
559
560   // Tell the display to redraw everything
561   d_spectrogram->invalidateCache();
562   d_spectrogram->itemChanged();
563
564   // Draw again
565   replot();
566
567   // Update the last replot timer
568   _lastReplot = get_highres_clock();
569 }
570
571 #endif /* WATERFALL_DISPLAY_PLOT_C */