Update copyright headers
[qt:qt.git] / demos / spectrum / app / mainwidget.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2015 The Qt Company Ltd.
4 ** Contact: http://www.qt.io/licensing/
5 **
6 ** This file is part of the examples of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** You may use this file under the terms of the BSD license as follows:
10 **
11 ** "Redistribution and use in source and binary forms, with or without
12 ** modification, are permitted provided that the following conditions are
13 ** met:
14 **   * Redistributions of source code must retain the above copyright
15 **     notice, this list of conditions and the following disclaimer.
16 **   * Redistributions in binary form must reproduce the above copyright
17 **     notice, this list of conditions and the following disclaimer in
18 **     the documentation and/or other materials provided with the
19 **     distribution.
20 **   * Neither the name of The Qt Company Ltd nor the names of its
21 **     contributors may be used to endorse or promote products derived
22 **     from this software without specific prior written permission.
23 **
24 **
25 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
36 **
37 ** $QT_END_LICENSE$
38 **
39 ****************************************************************************/
40
41 #include "engine.h"
42 #include "levelmeter.h"
43 #include "mainwidget.h"
44 #include "waveform.h"
45 #include "progressbar.h"
46 #include "settingsdialog.h"
47 #include "spectrograph.h"
48 #include "tonegeneratordialog.h"
49 #include "utils.h"
50
51 #include <QLabel>
52 #include <QPushButton>
53 #include <QHBoxLayout>
54 #include <QVBoxLayout>
55 #include <QStyle>
56 #include <QMenu>
57 #include <QFileDialog>
58 #include <QTimerEvent>
59 #include <QMessageBox>
60
61 const int NullTimerId = -1;
62
63 MainWidget::MainWidget(QWidget *parent)
64     :   QWidget(parent)
65     ,   m_mode(NoMode)
66     ,   m_engine(new Engine(this))
67 #ifndef DISABLE_WAVEFORM
68     ,   m_waveform(new Waveform(this))
69 #endif
70     ,   m_progressBar(new ProgressBar(this))
71     ,   m_spectrograph(new Spectrograph(this))
72     ,   m_levelMeter(new LevelMeter(this))
73     ,   m_modeButton(new QPushButton(this))
74     ,   m_recordButton(new QPushButton(this))
75     ,   m_pauseButton(new QPushButton(this))
76     ,   m_playButton(new QPushButton(this))
77     ,   m_settingsButton(new QPushButton(this))
78     ,   m_infoMessage(new QLabel(tr("Select a mode to begin"), this))
79     ,   m_infoMessageTimerId(NullTimerId)
80     ,   m_settingsDialog(new SettingsDialog(
81             m_engine->availableAudioInputDevices(),
82             m_engine->availableAudioOutputDevices(),
83             this))
84     ,   m_toneGeneratorDialog(new ToneGeneratorDialog(this))
85     ,   m_modeMenu(new QMenu(this))
86     ,   m_loadFileAction(0)
87     ,   m_generateToneAction(0)
88     ,   m_recordAction(0)
89 {
90     m_spectrograph->setParams(SpectrumNumBands, SpectrumLowFreq, SpectrumHighFreq);
91
92     createUi();
93     connectUi();
94 }
95
96 MainWidget::~MainWidget()
97 {
98
99 }
100
101
102 //-----------------------------------------------------------------------------
103 // Public slots
104 //-----------------------------------------------------------------------------
105
106 void MainWidget::stateChanged(QAudio::Mode mode, QAudio::State state)
107 {
108     Q_UNUSED(mode);
109
110     updateButtonStates();
111
112     if (QAudio::ActiveState != state && QAudio::SuspendedState != state) {
113         m_levelMeter->reset();
114         m_spectrograph->reset();
115     }
116 }
117
118 void MainWidget::formatChanged(const QAudioFormat &format)
119 {
120    infoMessage(formatToString(format), NullMessageTimeout);
121
122 #ifndef DISABLE_WAVEFORM
123     if (QAudioFormat() != format) {
124         m_waveform->initialize(format, WaveformTileLength,
125                                WaveformWindowDuration);
126     }
127 #endif
128 }
129
130 void MainWidget::spectrumChanged(qint64 position, qint64 length,
131                                  const FrequencySpectrum &spectrum)
132 {
133     m_progressBar->windowChanged(position, length);
134     m_spectrograph->spectrumChanged(spectrum);
135 }
136
137 void MainWidget::infoMessage(const QString &message, int timeoutMs)
138 {
139     m_infoMessage->setText(message);
140
141     if (NullTimerId != m_infoMessageTimerId) {
142         killTimer(m_infoMessageTimerId);
143         m_infoMessageTimerId = NullTimerId;
144     }
145
146     if (NullMessageTimeout != timeoutMs)
147         m_infoMessageTimerId = startTimer(timeoutMs);
148 }
149
150 void MainWidget::errorMessage(const QString &heading, const QString &detail)
151 {
152 #ifdef Q_OS_SYMBIAN
153     const QString message = heading + "\n" + detail;
154     QMessageBox::warning(this, "", message, QMessageBox::Close);
155 #else
156     QMessageBox::warning(this, heading, detail, QMessageBox::Close);
157 #endif
158 }
159
160 void MainWidget::timerEvent(QTimerEvent *event)
161 {
162     Q_ASSERT(event->timerId() == m_infoMessageTimerId);
163     Q_UNUSED(event) // suppress warnings in release builds
164     killTimer(m_infoMessageTimerId);
165     m_infoMessageTimerId = NullTimerId;
166     m_infoMessage->setText("");
167 }
168
169 void MainWidget::audioPositionChanged(qint64 position)
170 {
171 #ifndef DISABLE_WAVEFORM
172     m_waveform->audioPositionChanged(position);
173 #else
174     Q_UNUSED(position)
175 #endif
176 }
177
178 void MainWidget::bufferLengthChanged(qint64 length)
179 {
180     m_progressBar->bufferLengthChanged(length);
181 }
182
183
184 //-----------------------------------------------------------------------------
185 // Private slots
186 //-----------------------------------------------------------------------------
187
188 void MainWidget::showFileDialog()
189 {
190     const QString dir;
191     const QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Open WAV file"), dir, "*.wav");
192     if (fileNames.count()) {
193         reset();
194         setMode(LoadFileMode);
195         m_engine->loadFile(fileNames.front());
196         updateButtonStates();
197     } else {
198         updateModeMenu();
199     }
200 }
201
202 void MainWidget::showSettingsDialog()
203 {
204     m_settingsDialog->exec();
205     if (m_settingsDialog->result() == QDialog::Accepted) {
206         m_engine->setAudioInputDevice(m_settingsDialog->inputDevice());
207         m_engine->setAudioOutputDevice(m_settingsDialog->outputDevice());
208         m_engine->setWindowFunction(m_settingsDialog->windowFunction());
209     }
210 }
211
212 void MainWidget::showToneGeneratorDialog()
213 {
214     m_toneGeneratorDialog->exec();
215     if (m_toneGeneratorDialog->result() == QDialog::Accepted) {
216         reset();
217         setMode(GenerateToneMode);
218         const qreal amplitude = m_toneGeneratorDialog->amplitude();
219         if (m_toneGeneratorDialog->isFrequencySweepEnabled()) {
220             m_engine->generateSweptTone(amplitude);
221         } else {
222             const qreal frequency = m_toneGeneratorDialog->frequency();
223             const Tone tone(frequency, amplitude);
224             m_engine->generateTone(tone);
225             updateButtonStates();
226         }
227     } else {
228         updateModeMenu();
229     }
230 }
231
232 void MainWidget::initializeRecord()
233 {
234     reset();
235     setMode(RecordMode);
236     if (m_engine->initializeRecord())
237         updateButtonStates();
238 }
239
240
241 //-----------------------------------------------------------------------------
242 // Private functions
243 //-----------------------------------------------------------------------------
244
245 void MainWidget::createUi()
246 {
247     createMenus();
248
249     setWindowTitle(tr("Spectrum Analyser"));
250
251     QVBoxLayout *windowLayout = new QVBoxLayout(this);
252
253     m_infoMessage->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
254     m_infoMessage->setAlignment(Qt::AlignHCenter);
255     windowLayout->addWidget(m_infoMessage);
256
257 #ifdef SUPERIMPOSE_PROGRESS_ON_WAVEFORM
258     QScopedPointer<QHBoxLayout> waveformLayout(new QHBoxLayout);
259     waveformLayout->addWidget(m_progressBar);
260     m_progressBar->setMinimumHeight(m_waveform->minimumHeight());
261     waveformLayout->setMargin(0);
262     m_waveform->setLayout(waveformLayout.data());
263     waveformLayout.take();
264     windowLayout->addWidget(m_waveform);
265 #else
266 #ifndef DISABLE_WAVEFORM
267     windowLayout->addWidget(m_waveform);
268 #endif // DISABLE_WAVEFORM
269     windowLayout->addWidget(m_progressBar);
270 #endif // SUPERIMPOSE_PROGRESS_ON_WAVEFORM
271
272     // Spectrograph and level meter
273
274     QScopedPointer<QHBoxLayout> analysisLayout(new QHBoxLayout);
275     analysisLayout->addWidget(m_spectrograph);
276     analysisLayout->addWidget(m_levelMeter);
277     windowLayout->addLayout(analysisLayout.data());
278     analysisLayout.take();
279
280     // Button panel
281
282     const QSize buttonSize(30, 30);
283
284     m_modeButton->setText(tr("Mode"));
285
286     m_recordIcon = QIcon(":/images/record.png");
287     m_recordButton->setIcon(m_recordIcon);
288     m_recordButton->setEnabled(false);
289     m_recordButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
290     m_recordButton->setMinimumSize(buttonSize);
291
292     m_pauseIcon = style()->standardIcon(QStyle::SP_MediaPause);
293     m_pauseButton->setIcon(m_pauseIcon);
294     m_pauseButton->setEnabled(false);
295     m_pauseButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
296     m_pauseButton->setMinimumSize(buttonSize);
297
298     m_playIcon = style()->standardIcon(QStyle::SP_MediaPlay);
299     m_playButton->setIcon(m_playIcon);
300     m_playButton->setEnabled(false);
301     m_playButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
302     m_playButton->setMinimumSize(buttonSize);
303
304     m_settingsIcon = QIcon(":/images/settings.png");
305     m_settingsButton->setIcon(m_settingsIcon);
306     m_settingsButton->setEnabled(true);
307     m_settingsButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
308     m_settingsButton->setMinimumSize(buttonSize);
309
310     QScopedPointer<QHBoxLayout> buttonPanelLayout(new QHBoxLayout);
311     buttonPanelLayout->addStretch();
312     buttonPanelLayout->addWidget(m_modeButton);
313     buttonPanelLayout->addWidget(m_recordButton);
314     buttonPanelLayout->addWidget(m_pauseButton);
315     buttonPanelLayout->addWidget(m_playButton);
316     buttonPanelLayout->addWidget(m_settingsButton);
317
318     QWidget *buttonPanel = new QWidget(this);
319     buttonPanel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
320     buttonPanel->setLayout(buttonPanelLayout.data());
321     buttonPanelLayout.take(); // ownership transferred to buttonPanel
322
323     QScopedPointer<QHBoxLayout> bottomPaneLayout(new QHBoxLayout);
324     bottomPaneLayout->addWidget(buttonPanel);
325     windowLayout->addLayout(bottomPaneLayout.data());
326     bottomPaneLayout.take(); // ownership transferred to windowLayout
327
328     // Apply layout
329
330     setLayout(windowLayout);
331 }
332
333 void MainWidget::connectUi()
334 {
335     CHECKED_CONNECT(m_recordButton, SIGNAL(clicked()),
336             m_engine, SLOT(startRecording()));
337
338     CHECKED_CONNECT(m_pauseButton, SIGNAL(clicked()),
339             m_engine, SLOT(suspend()));
340
341     CHECKED_CONNECT(m_playButton, SIGNAL(clicked()),
342             m_engine, SLOT(startPlayback()));
343
344     CHECKED_CONNECT(m_settingsButton, SIGNAL(clicked()),
345             this, SLOT(showSettingsDialog()));
346
347     CHECKED_CONNECT(m_engine, SIGNAL(stateChanged(QAudio::Mode,QAudio::State)),
348             this, SLOT(stateChanged(QAudio::Mode,QAudio::State)));
349
350     CHECKED_CONNECT(m_engine, SIGNAL(formatChanged(const QAudioFormat &)),
351             this, SLOT(formatChanged(const QAudioFormat &)));
352
353     m_progressBar->bufferLengthChanged(m_engine->bufferLength());
354
355     CHECKED_CONNECT(m_engine, SIGNAL(bufferLengthChanged(qint64)),
356             this, SLOT(bufferLengthChanged(qint64)));
357
358     CHECKED_CONNECT(m_engine, SIGNAL(dataLengthChanged(qint64)),
359             this, SLOT(updateButtonStates()));
360
361     CHECKED_CONNECT(m_engine, SIGNAL(recordPositionChanged(qint64)),
362             m_progressBar, SLOT(recordPositionChanged(qint64)));
363
364     CHECKED_CONNECT(m_engine, SIGNAL(playPositionChanged(qint64)),
365             m_progressBar, SLOT(playPositionChanged(qint64)));
366
367     CHECKED_CONNECT(m_engine, SIGNAL(recordPositionChanged(qint64)),
368             this, SLOT(audioPositionChanged(qint64)));
369
370     CHECKED_CONNECT(m_engine, SIGNAL(playPositionChanged(qint64)),
371             this, SLOT(audioPositionChanged(qint64)));
372
373     CHECKED_CONNECT(m_engine, SIGNAL(levelChanged(qreal, qreal, int)),
374             m_levelMeter, SLOT(levelChanged(qreal, qreal, int)));
375
376     CHECKED_CONNECT(m_engine, SIGNAL(spectrumChanged(qint64, qint64, const FrequencySpectrum &)),
377             this, SLOT(spectrumChanged(qint64, qint64, const FrequencySpectrum &)));
378
379     CHECKED_CONNECT(m_engine, SIGNAL(infoMessage(QString, int)),
380             this, SLOT(infoMessage(QString, int)));
381
382     CHECKED_CONNECT(m_engine, SIGNAL(errorMessage(QString, QString)),
383             this, SLOT(errorMessage(QString, QString)));
384
385     CHECKED_CONNECT(m_spectrograph, SIGNAL(infoMessage(QString, int)),
386             this, SLOT(infoMessage(QString, int)));
387
388 #ifndef DISABLE_WAVEFORM
389     CHECKED_CONNECT(m_engine, SIGNAL(bufferChanged(qint64, qint64, const QByteArray &)),
390             m_waveform, SLOT(bufferChanged(qint64, qint64, const QByteArray &)));
391 #endif
392 }
393
394 void MainWidget::createMenus()
395 {
396     m_modeButton->setMenu(m_modeMenu);
397
398     m_generateToneAction = m_modeMenu->addAction(tr("Play generated tone"));
399     m_recordAction = m_modeMenu->addAction(tr("Record and play back"));
400     m_loadFileAction = m_modeMenu->addAction(tr("Play file"));
401
402     m_loadFileAction->setCheckable(true);
403     m_generateToneAction->setCheckable(true);
404     m_recordAction->setCheckable(true);
405
406     connect(m_loadFileAction, SIGNAL(triggered(bool)), this, SLOT(showFileDialog()));
407     connect(m_generateToneAction, SIGNAL(triggered(bool)), this, SLOT(showToneGeneratorDialog()));
408     connect(m_recordAction, SIGNAL(triggered(bool)), this, SLOT(initializeRecord()));
409 }
410
411 void MainWidget::updateButtonStates()
412 {
413     const bool recordEnabled = ((QAudio::AudioOutput == m_engine->mode() ||
414                                 (QAudio::ActiveState != m_engine->state() &&
415                                  QAudio::IdleState != m_engine->state())) &&
416                                 RecordMode == m_mode);
417     m_recordButton->setEnabled(recordEnabled);
418
419     const bool pauseEnabled = (QAudio::ActiveState == m_engine->state() ||
420                                QAudio::IdleState == m_engine->state());
421     m_pauseButton->setEnabled(pauseEnabled);
422
423     const bool playEnabled = (/*m_engine->dataLength() &&*/
424                               (QAudio::AudioOutput != m_engine->mode() ||
425                                (QAudio::ActiveState != m_engine->state() &&
426                                 QAudio::IdleState != m_engine->state())));
427     m_playButton->setEnabled(playEnabled);
428 }
429
430 void MainWidget::reset()
431 {
432 #ifndef DISABLE_WAVEFORM
433     m_waveform->reset();
434 #endif
435     m_engine->reset();
436     m_levelMeter->reset();
437     m_spectrograph->reset();
438     m_progressBar->reset();
439 }
440
441 void MainWidget::setMode(Mode mode)
442 {
443     m_mode = mode;
444     updateModeMenu();
445 }
446
447 void MainWidget::updateModeMenu()
448 {
449     m_loadFileAction->setChecked(LoadFileMode == m_mode);
450     m_generateToneAction->setChecked(GenerateToneMode == m_mode);
451     m_recordAction->setChecked(RecordMode == m_mode);
452 }
453