From f1b0ab898d5584389e7eee912d7274485c64b8e2 Mon Sep 17 00:00:00 2001 From: Martin Date: Sun, 19 Apr 2020 21:25:01 +0200 Subject: [PATCH] complete clang-format, no content change Signed-off-by: Martin --- openhantek/.clang-format | 14 +- openhantek/src/OH_BUILD.h | 2 +- openhantek/src/OH_VERSION.h | 20 +- .../configdialog/DsoConfigAnalysisPage.cpp | 74 +- .../src/configdialog/DsoConfigAnalysisPage.h | 2 +- .../src/configdialog/DsoConfigColorsPage.cpp | 175 +- .../src/configdialog/DsoConfigColorsPage.h | 2 +- .../src/configdialog/DsoConfigFilePage.cpp | 65 +- .../src/configdialog/DsoConfigFilePage.h | 2 +- .../src/configdialog/DsoConfigScopePage.cpp | 61 +- .../src/configdialog/DsoConfigScopePage.h | 2 +- openhantek/src/configdialog/configdialog.cpp | 114 +- openhantek/src/configdialog/configdialog.h | 4 +- openhantek/src/docks/HorizontalDock.cpp | 235 +-- openhantek/src/docks/HorizontalDock.h | 63 +- openhantek/src/docks/SpectrumDock.cpp | 101 +- openhantek/src/docks/SpectrumDock.h | 26 +- openhantek/src/docks/TriggerDock.cpp | 117 +- openhantek/src/docks/TriggerDock.h | 27 +- openhantek/src/docks/VoltageDock.cpp | 232 +-- openhantek/src/docks/VoltageDock.h | 55 +- openhantek/src/docks/dockwindows.cpp | 22 +- openhantek/src/docks/dockwindows.h | 2 +- openhantek/src/dsosettings.cpp | 427 +++-- openhantek/src/dsosettings.h | 6 +- openhantek/src/dsowidget.cpp | 1020 +++++----- openhantek/src/dsowidget.h | 85 +- openhantek/src/exporting/exportcsv.cpp | 101 +- openhantek/src/exporting/exportcsv.h | 12 +- openhantek/src/exporting/exporterinterface.h | 20 +- .../src/exporting/exporterprocessor.cpp | 4 +- openhantek/src/exporting/exporterprocessor.h | 14 +- openhantek/src/exporting/exporterregistry.cpp | 74 +- openhantek/src/exporting/exporterregistry.h | 16 +- openhantek/src/exporting/exportimage.cpp | 60 +- openhantek/src/exporting/exportimage.h | 12 +- openhantek/src/exporting/exportprint.cpp | 33 +- openhantek/src/exporting/exportprint.h | 12 +- openhantek/src/exporting/exportsettings.h | 6 +- .../src/exporting/legacyexportdrawer.cpp | 478 ++--- openhantek/src/exporting/legacyexportdrawer.h | 16 +- openhantek/src/glscope.cpp | 608 +++--- openhantek/src/glscope.h | 63 +- openhantek/src/glscopegraph.cpp | 95 +- openhantek/src/glscopegraph.h | 6 +- openhantek/src/hantekdso/controlsettings.cpp | 14 +- openhantek/src/hantekdso/controlsettings.h | 50 +- .../src/hantekdso/controlspecification.cpp | 6 +- .../src/hantekdso/controlspecification.h | 5 +- openhantek/src/hantekdso/dsomodel.cpp | 17 +- openhantek/src/hantekdso/dsomodel.h | 8 +- openhantek/src/hantekdso/enums.cpp | 122 +- openhantek/src/hantekdso/enums.h | 24 +- openhantek/src/hantekdso/errorcodes.h | 2 +- openhantek/src/hantekdso/hantekdsocontrol.cpp | 500 ++--- openhantek/src/hantekdso/hantekdsocontrol.h | 84 +- openhantek/src/hantekdso/modelregistry.cpp | 2 +- openhantek/src/hantekdso/modelregistry.h | 11 +- .../src/hantekdso/models/modelDDS120.cpp | 114 +- openhantek/src/hantekdso/models/modelDDS120.h | 2 +- .../src/hantekdso/models/modelDSO6022.cpp | 164 +- .../src/hantekdso/models/modelDSO6022.h | 10 +- openhantek/src/hantekdso/states.h | 2 +- .../src/hantekprotocol/controlStructs.cpp | 65 +- .../src/hantekprotocol/controlStructs.h | 16 +- openhantek/src/hantekprotocol/controlcode.h | 5 +- .../src/hantekprotocol/controlcommand.cpp | 3 +- .../src/hantekprotocol/controlcommand.h | 9 +- openhantek/src/hantekprotocol/controlvalue.h | 3 +- openhantek/src/hantekprotocol/definitions.h | 6 +- openhantek/src/iconfont/QtAwesome.cpp | 196 +- openhantek/src/iconfont/QtAwesome.h | 1633 ++++++++--------- openhantek/src/iconfont/QtAwesomeAnim.cpp | 26 +- openhantek/src/iconfont/QtAwesomeAnim.h | 19 +- openhantek/src/main.cpp | 139 +- openhantek/src/mainwindow.cpp | 446 +++-- openhantek/src/mainwindow.h | 14 +- openhantek/src/post/graphgenerator.cpp | 132 +- openhantek/src/post/graphgenerator.h | 10 +- openhantek/src/post/mathchannelgenerator.cpp | 78 +- openhantek/src/post/mathchannelgenerator.h | 12 +- openhantek/src/post/postprocessing.cpp | 38 +- openhantek/src/post/postprocessing.h | 12 +- .../src/post/postprocessingsettings.cpp | 18 +- openhantek/src/post/postprocessingsettings.h | 13 +- openhantek/src/post/ppresult.cpp | 14 +- openhantek/src/post/ppresult.h | 38 +- openhantek/src/post/processor.h | 4 +- openhantek/src/post/spectrumgenerator.cpp | 232 +-- openhantek/src/post/spectrumgenerator.h | 16 +- openhantek/src/scopesettings.h | 49 +- openhantek/src/selectdevice/devicelistentry.h | 5 +- .../src/selectdevice/deviceslistmodel.cpp | 93 +- .../src/selectdevice/deviceslistmodel.h | 21 +- .../newdevicemodelfromexisting.cpp | 84 +- .../selectdevice/newdevicemodelfromexisting.h | 21 +- .../src/selectdevice/rawdevicelistentry.h | 6 +- .../src/selectdevice/rawdeviceslistmodel.cpp | 82 +- .../src/selectdevice/rawdeviceslistmodel.h | 27 +- .../selectdevice/selectsupporteddevice.cpp | 171 +- .../src/selectdevice/selectsupporteddevice.h | 18 +- openhantek/src/usb/ezusb.cpp | 418 +++-- openhantek/src/usb/ezusb.h | 4 +- openhantek/src/usb/finddevices.cpp | 35 +- openhantek/src/usb/finddevices.h | 9 +- openhantek/src/usb/uploadFirmware.cpp | 45 +- openhantek/src/usb/uploadFirmware.h | 3 +- openhantek/src/usb/usbdevice.cpp | 166 +- openhantek/src/usb/usbdevice.h | 59 +- openhantek/src/usb/usbdevicedefinitions.h | 8 +- openhantek/src/utils/enumclass.h | 51 +- openhantek/src/utils/printutils.cpp | 231 +-- openhantek/src/utils/printutils.h | 15 +- openhantek/src/viewconstants.h | 6 +- openhantek/src/viewsettings.h | 28 +- openhantek/src/widgets/colorbox.cpp | 21 +- openhantek/src/widgets/colorbox.h | 6 +- openhantek/src/widgets/datagrid.cpp | 124 +- openhantek/src/widgets/datagrid.h | 41 +- openhantek/src/widgets/levelslider.cpp | 415 +++-- openhantek/src/widgets/levelslider.h | 54 +- openhantek/src/widgets/sispinbox.cpp | 100 +- openhantek/src/widgets/sispinbox.h | 22 +- openhantek/translations/openhantek_de.ts | 290 +-- openhantek/translations/openhantek_es.ts | 290 +-- openhantek/translations/openhantek_fr.ts | 290 +-- openhantek/translations/openhantek_it.ts | 290 +-- openhantek/translations/openhantek_pt.ts | 290 +-- readme.md | 6 +- 129 files changed, 6511 insertions(+), 6302 deletions(-) diff --git a/openhantek/.clang-format b/openhantek/.clang-format index 2e9d003d..341b8d3e 100644 --- a/openhantek/.clang-format +++ b/openhantek/.clang-format @@ -9,18 +9,18 @@ AlignEscapedNewlinesLeft: false AlignOperands: true AlignTrailingComments: true AllowAllParametersOfDeclarationOnNextLine: true -AllowShortBlocksOnASingleLine: true +AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: All -AllowShortIfStatementsOnASingleLine: true -AllowShortLoopsOnASingleLine: true +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: false BinPackArguments: true BinPackParameters: true -BraceWrapping: +BraceWrapping: AfterClass: false AfterControlStatement: false AfterEnum: false @@ -64,7 +64,7 @@ JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: true MacroBlockBegin: '' MacroBlockEnd: '' -MaxEmptyLinesToKeep: 1 +MaxEmptyLinesToKeep: 2 NamespaceIndentation: None ObjCBlockIndentWidth: 2 ObjCSpaceAfterProperty: false @@ -86,8 +86,8 @@ SpacesBeforeTrailingComments: 1 SpacesInAngles: false SpacesInContainerLiterals: true SpacesInCStyleCastParentheses: false -SpacesInParentheses: false -SpacesInSquareBrackets: false +SpacesInParentheses: true +SpacesInSquareBrackets: true Standard: Cpp11 TabWidth: 8 UseTab: Never diff --git a/openhantek/src/OH_BUILD.h b/openhantek/src/OH_BUILD.h index 6504a8f8..5739a30d 100644 --- a/openhantek/src/OH_BUILD.h +++ b/openhantek/src/OH_BUILD.h @@ -1,2 +1,2 @@ // Do not edit, will be re-created at each commit! -#define OH_BUILD "20200414 build 642" +#define OH_BUILD "20200419 build 644" diff --git a/openhantek/src/OH_VERSION.h b/openhantek/src/OH_VERSION.h index 329df5e6..56136322 100644 --- a/openhantek/src/OH_VERSION.h +++ b/openhantek/src/OH_VERSION.h @@ -4,13 +4,13 @@ #define OH_VERSION "3.0.4b" -# ifdef OH_VERSION -# undef VERSION -# define VERSION OH_VERSION -# else -# include "OH_BUILD.h" -# ifdef OH_BUILD -# undef VERSION -# define VERSION OH_BUILD -# endif -# endif +#ifdef OH_VERSION +#undef VERSION +#define VERSION OH_VERSION +#else +#include "OH_BUILD.h" +#ifdef OH_BUILD +#undef VERSION +#define VERSION OH_BUILD +#endif +#endif diff --git a/openhantek/src/configdialog/DsoConfigAnalysisPage.cpp b/openhantek/src/configdialog/DsoConfigAnalysisPage.cpp index 104f6d22..691e7269 100644 --- a/openhantek/src/configdialog/DsoConfigAnalysisPage.cpp +++ b/openhantek/src/configdialog/DsoConfigAnalysisPage.cpp @@ -2,64 +2,66 @@ #include "DsoConfigAnalysisPage.h" -DsoConfigAnalysisPage::DsoConfigAnalysisPage(DsoSettings *settings, QWidget *parent) - : QWidget(parent), settings(settings) { +DsoConfigAnalysisPage::DsoConfigAnalysisPage( DsoSettings *settings, QWidget *parent ) + : QWidget( parent ), settings( settings ) { // Initialize lists for comboboxes QStringList windowFunctionStrings; - windowFunctionStrings << tr("Rectangular") << tr("Hamming") << tr("Hann") << tr("Cosine") << tr("Lanczos") - << tr("Bartlett") << tr("Triangular") << tr("Gauss") << tr("Bartlett-Hann") << tr("Blackman") + windowFunctionStrings << tr( "Rectangular" ) << tr( "Hamming" ) << tr( "Hann" ) << tr( "Cosine" ) << tr( "Lanczos" ) + << tr( "Bartlett" ) << tr( "Triangular" ) << tr( "Gauss" ) << tr( "Bartlett-Hann" ) + << tr( "Blackman" ) //<< tr("Kaiser") - << tr("Nuttall") << tr("Blackman-Harris") << tr("Blackman-Nuttall") << tr("Flat top"); + << tr( "Nuttall" ) << tr( "Blackman-Harris" ) << tr( "Blackman-Nuttall" ) << tr( "Flat top" ); // Initialize elements - windowFunctionLabel = new QLabel(tr("Window function")); + windowFunctionLabel = new QLabel( tr( "Window function" ) ); windowFunctionComboBox = new QComboBox(); - windowFunctionComboBox->addItems(windowFunctionStrings); - windowFunctionComboBox->setCurrentIndex(int(settings->post.spectrumWindow)); + windowFunctionComboBox->addItems( windowFunctionStrings ); + windowFunctionComboBox->setCurrentIndex( int( settings->post.spectrumWindow ) ); - referenceLevelLabel = new QLabel(tr("Reference level
0 dBu = -2.2 dBV
0 dBm (@600 Ω) = -2.2 dBV
0 dBm (@50 Ω) = -13 dBV")); + referenceLevelLabel = new QLabel( tr( "Reference level
0 dBu = -2.2 dBV
0 dBm (@600 Ω) = -2.2 " + "dBV
0 dBm (@50 Ω) = -13 dBV" ) ); referenceLevelSpinBox = new QDoubleSpinBox(); - referenceLevelSpinBox->setDecimals(1); - referenceLevelSpinBox->setMinimum(-100.0); - referenceLevelSpinBox->setMaximum(100.0); - referenceLevelSpinBox->setValue(settings->post.spectrumReference); - referenceLevelUnitLabel = new QLabel(tr("dBV")); + referenceLevelSpinBox->setDecimals( 1 ); + referenceLevelSpinBox->setMinimum( -100.0 ); + referenceLevelSpinBox->setMaximum( 100.0 ); + referenceLevelSpinBox->setValue( settings->post.spectrumReference ); + referenceLevelUnitLabel = new QLabel( tr( "dBV" ) ); referenceLevelLayout = new QHBoxLayout(); - referenceLevelLayout->addWidget(referenceLevelSpinBox); - referenceLevelLayout->addWidget(referenceLevelUnitLabel); + referenceLevelLayout->addWidget( referenceLevelSpinBox ); + referenceLevelLayout->addWidget( referenceLevelUnitLabel ); - minimumMagnitudeLabel = new QLabel(tr("Minimum magnitude")); + minimumMagnitudeLabel = new QLabel( tr( "Minimum magnitude" ) ); minimumMagnitudeSpinBox = new QDoubleSpinBox(); - minimumMagnitudeSpinBox->setDecimals(1); - minimumMagnitudeSpinBox->setMinimum(-100.0); - minimumMagnitudeSpinBox->setMaximum(100.0); - minimumMagnitudeSpinBox->setValue(settings->post.spectrumLimit); - minimumMagnitudeUnitLabel = new QLabel(tr("dBV")); + minimumMagnitudeSpinBox->setDecimals( 1 ); + minimumMagnitudeSpinBox->setMinimum( -100.0 ); + minimumMagnitudeSpinBox->setMaximum( 100.0 ); + minimumMagnitudeSpinBox->setValue( settings->post.spectrumLimit ); + minimumMagnitudeUnitLabel = new QLabel( tr( "dBV" ) ); minimumMagnitudeLayout = new QHBoxLayout(); - minimumMagnitudeLayout->addWidget(minimumMagnitudeSpinBox); - minimumMagnitudeLayout->addWidget(minimumMagnitudeUnitLabel); + minimumMagnitudeLayout->addWidget( minimumMagnitudeSpinBox ); + minimumMagnitudeLayout->addWidget( minimumMagnitudeUnitLabel ); spectrumLayout = new QGridLayout(); - spectrumLayout->addWidget(windowFunctionLabel, 0, 0); - spectrumLayout->addWidget(windowFunctionComboBox, 0, 1); - spectrumLayout->addWidget(referenceLevelLabel, 1, 0); - spectrumLayout->addLayout(referenceLevelLayout, 1, 1); - spectrumLayout->addWidget(minimumMagnitudeLabel, 2, 0); - spectrumLayout->addLayout(minimumMagnitudeLayout, 2, 1); + spectrumLayout->addWidget( windowFunctionLabel, 0, 0 ); + spectrumLayout->addWidget( windowFunctionComboBox, 0, 1 ); + spectrumLayout->addWidget( referenceLevelLabel, 1, 0 ); + spectrumLayout->addLayout( referenceLevelLayout, 1, 1 ); + spectrumLayout->addWidget( minimumMagnitudeLabel, 2, 0 ); + spectrumLayout->addLayout( minimumMagnitudeLayout, 2, 1 ); - spectrumGroup = new QGroupBox(tr("Spectrum")); - spectrumGroup->setLayout(spectrumLayout); + spectrumGroup = new QGroupBox( tr( "Spectrum" ) ); + spectrumGroup->setLayout( spectrumLayout ); mainLayout = new QVBoxLayout(); - mainLayout->addWidget(spectrumGroup); - mainLayout->addStretch(1); + mainLayout->addWidget( spectrumGroup ); + mainLayout->addStretch( 1 ); - setLayout(mainLayout); + setLayout( mainLayout ); } /// \brief Saves the new settings. void DsoConfigAnalysisPage::saveSettings() { - settings->post.spectrumWindow = Dso::WindowFunction(windowFunctionComboBox->currentIndex()); + settings->post.spectrumWindow = Dso::WindowFunction( windowFunctionComboBox->currentIndex() ); settings->post.spectrumReference = referenceLevelSpinBox->value(); settings->post.spectrumLimit = minimumMagnitudeSpinBox->value(); } diff --git a/openhantek/src/configdialog/DsoConfigAnalysisPage.h b/openhantek/src/configdialog/DsoConfigAnalysisPage.h index 531ca0de..502d691c 100644 --- a/openhantek/src/configdialog/DsoConfigAnalysisPage.h +++ b/openhantek/src/configdialog/DsoConfigAnalysisPage.h @@ -21,7 +21,7 @@ class DsoConfigAnalysisPage : public QWidget { Q_OBJECT public: - DsoConfigAnalysisPage(DsoSettings *settings, QWidget *parent = nullptr); + DsoConfigAnalysisPage( DsoSettings *settings, QWidget *parent = nullptr ); public slots: void saveSettings(); diff --git a/openhantek/src/configdialog/DsoConfigColorsPage.cpp b/openhantek/src/configdialog/DsoConfigColorsPage.cpp index 85e96e7c..cc2a8259 100644 --- a/openhantek/src/configdialog/DsoConfigColorsPage.cpp +++ b/openhantek/src/configdialog/DsoConfigColorsPage.cpp @@ -2,127 +2,128 @@ #include "DsoConfigColorsPage.h" -DsoConfigColorsPage::DsoConfigColorsPage(DsoSettings *settings, QWidget *parent) : QWidget(parent), settings(settings) { +DsoConfigColorsPage::DsoConfigColorsPage( DsoSettings *settings, QWidget *parent ) + : QWidget( parent ), settings( settings ) { // Initialize elements DsoSettingsView &colorSettings = settings->view; enum { COL_LABEL = 0, COL_SCR_CHANNEL, COL_SCR_SPECTRUM, COL_PRT_CHANNEL, COL_PRT_SPECTRUM }; // Plot Area - graphLabel = new QLabel(tr("
")); // 4*80 - graphLabel->setAlignment(Qt::AlignRight); - graphLabel->setTextFormat(Qt::RichText); + graphLabel = new QLabel( tr( "
" ) ); // 4*80 + graphLabel->setAlignment( Qt::AlignRight ); + graphLabel->setTextFormat( Qt::RichText ); - screenColorsLabel = new QLabel(tr("Screen")); - screenColorsLabel->setAlignment(Qt::AlignHCenter); - printColorsLabel = new QLabel(tr("Print")); - printColorsLabel->setAlignment(Qt::AlignHCenter); + screenColorsLabel = new QLabel( tr( "Screen" ) ); + screenColorsLabel->setAlignment( Qt::AlignHCenter ); + printColorsLabel = new QLabel( tr( "Print" ) ); + printColorsLabel->setAlignment( Qt::AlignHCenter ); - axesLabel = new QLabel(tr("Axes")); - axesColorBox = new ColorBox(colorSettings.screen.axes); - printAxesColorBox = new ColorBox(colorSettings.print.axes); + axesLabel = new QLabel( tr( "Axes" ) ); + axesColorBox = new ColorBox( colorSettings.screen.axes ); + printAxesColorBox = new ColorBox( colorSettings.print.axes ); - backgroundLabel = new QLabel(tr("Background")); - backgroundColorBox = new ColorBox(colorSettings.screen.background); - printBackgroundColorBox = new ColorBox(colorSettings.print.background); + backgroundLabel = new QLabel( tr( "Background" ) ); + backgroundColorBox = new ColorBox( colorSettings.screen.background ); + printBackgroundColorBox = new ColorBox( colorSettings.print.background ); - borderLabel = new QLabel(tr("Border")); - borderColorBox = new ColorBox(colorSettings.screen.border); - printBorderColorBox = new ColorBox(colorSettings.print.border); + borderLabel = new QLabel( tr( "Border" ) ); + borderColorBox = new ColorBox( colorSettings.screen.border ); + printBorderColorBox = new ColorBox( colorSettings.print.border ); - gridLabel = new QLabel(tr("Grid")); - gridColorBox = new ColorBox(colorSettings.screen.grid); - printGridColorBox = new ColorBox(colorSettings.print.grid); + gridLabel = new QLabel( tr( "Grid" ) ); + gridColorBox = new ColorBox( colorSettings.screen.grid ); + printGridColorBox = new ColorBox( colorSettings.print.grid ); - markersLabel = new QLabel(tr("Markers")); - markersColorBox = new ColorBox(colorSettings.screen.markers); - printMarkersColorBox = new ColorBox(colorSettings.print.markers); + markersLabel = new QLabel( tr( "Markers" ) ); + markersColorBox = new ColorBox( colorSettings.screen.markers ); + printMarkersColorBox = new ColorBox( colorSettings.print.markers ); - textLabel = new QLabel(tr("Text")); - textColorBox = new ColorBox(colorSettings.screen.text); - printTextColorBox = new ColorBox(colorSettings.print.text); + textLabel = new QLabel( tr( "Text" ) ); + textColorBox = new ColorBox( colorSettings.screen.text ); + printTextColorBox = new ColorBox( colorSettings.print.text ); // Graph category - screenChannelLabel = new QLabel(tr("Channel")); - screenChannelLabel->setAlignment(Qt::AlignHCenter); - screenSpectrumLabel = new QLabel(tr("Spectrum")); - screenSpectrumLabel->setAlignment(Qt::AlignHCenter); - printChannelLabel = new QLabel(tr("Channel")); - printChannelLabel->setAlignment(Qt::AlignHCenter); - printSpectrumLabel = new QLabel(tr("Spectrum")); - printSpectrumLabel->setAlignment(Qt::AlignHCenter); - - for (ChannelID channel = 0; channel < settings->scope.voltage.size(); ++channel) { - colorLabel.push_back(new QLabel(settings->scope.voltage[channel].name)); - screenChannelColorBox.push_back(new ColorBox(colorSettings.screen.voltage[channel])); - screenSpectrumColorBox.push_back(new ColorBox(colorSettings.screen.spectrum[channel])); - printChannelColorBox.push_back(new ColorBox(colorSettings.print.voltage[channel])); - printSpectrumColorBox.push_back(new ColorBox(colorSettings.print.spectrum[channel])); + screenChannelLabel = new QLabel( tr( "Channel" ) ); + screenChannelLabel->setAlignment( Qt::AlignHCenter ); + screenSpectrumLabel = new QLabel( tr( "Spectrum" ) ); + screenSpectrumLabel->setAlignment( Qt::AlignHCenter ); + printChannelLabel = new QLabel( tr( "Channel" ) ); + printChannelLabel->setAlignment( Qt::AlignHCenter ); + printSpectrumLabel = new QLabel( tr( "Spectrum" ) ); + printSpectrumLabel->setAlignment( Qt::AlignHCenter ); + + for ( ChannelID channel = 0; channel < settings->scope.voltage.size(); ++channel ) { + colorLabel.push_back( new QLabel( settings->scope.voltage[ channel ].name ) ); + screenChannelColorBox.push_back( new ColorBox( colorSettings.screen.voltage[ channel ] ) ); + screenSpectrumColorBox.push_back( new ColorBox( colorSettings.screen.spectrum[ channel ] ) ); + printChannelColorBox.push_back( new ColorBox( colorSettings.print.voltage[ channel ] ) ); + printSpectrumColorBox.push_back( new ColorBox( colorSettings.print.spectrum[ channel ] ) ); } // Plot Area Layout colorsLayout = new QGridLayout(); - colorsLayout->setColumnStretch(COL_LABEL, 1); - colorsLayout->setColumnMinimumWidth(COL_SCR_CHANNEL, 80); - colorsLayout->setColumnMinimumWidth(COL_SCR_SPECTRUM, 80); - colorsLayout->setColumnMinimumWidth(COL_PRT_CHANNEL, 80); - colorsLayout->setColumnMinimumWidth(COL_PRT_SPECTRUM, 80); + colorsLayout->setColumnStretch( COL_LABEL, 1 ); + colorsLayout->setColumnMinimumWidth( COL_SCR_CHANNEL, 80 ); + colorsLayout->setColumnMinimumWidth( COL_SCR_SPECTRUM, 80 ); + colorsLayout->setColumnMinimumWidth( COL_PRT_CHANNEL, 80 ); + colorsLayout->setColumnMinimumWidth( COL_PRT_SPECTRUM, 80 ); int row = 0; - colorsLayout->addWidget(screenColorsLabel, row, COL_SCR_CHANNEL, 1, 2); - colorsLayout->addWidget(printColorsLabel, row, COL_PRT_CHANNEL, 1, 2); + colorsLayout->addWidget( screenColorsLabel, row, COL_SCR_CHANNEL, 1, 2 ); + colorsLayout->addWidget( printColorsLabel, row, COL_PRT_CHANNEL, 1, 2 ); ++row; - colorsLayout->addWidget(backgroundLabel, row, COL_LABEL); - colorsLayout->addWidget(backgroundColorBox, row, COL_SCR_CHANNEL, 1, 2); - colorsLayout->addWidget(printBackgroundColorBox, row, COL_PRT_CHANNEL, 1, 2); + colorsLayout->addWidget( backgroundLabel, row, COL_LABEL ); + colorsLayout->addWidget( backgroundColorBox, row, COL_SCR_CHANNEL, 1, 2 ); + colorsLayout->addWidget( printBackgroundColorBox, row, COL_PRT_CHANNEL, 1, 2 ); ++row; - colorsLayout->addWidget(gridLabel, row, COL_LABEL); - colorsLayout->addWidget(gridColorBox, row, COL_SCR_CHANNEL, 1, 2); - colorsLayout->addWidget(printGridColorBox, row, COL_PRT_CHANNEL, 1, 2); + colorsLayout->addWidget( gridLabel, row, COL_LABEL ); + colorsLayout->addWidget( gridColorBox, row, COL_SCR_CHANNEL, 1, 2 ); + colorsLayout->addWidget( printGridColorBox, row, COL_PRT_CHANNEL, 1, 2 ); ++row; - colorsLayout->addWidget(axesLabel, row, COL_LABEL); - colorsLayout->addWidget(axesColorBox, row, COL_SCR_CHANNEL, 1, 2); - colorsLayout->addWidget(printAxesColorBox, row, COL_PRT_CHANNEL, 1, 2); + colorsLayout->addWidget( axesLabel, row, COL_LABEL ); + colorsLayout->addWidget( axesColorBox, row, COL_SCR_CHANNEL, 1, 2 ); + colorsLayout->addWidget( printAxesColorBox, row, COL_PRT_CHANNEL, 1, 2 ); ++row; - colorsLayout->addWidget(borderLabel, row, COL_LABEL); - colorsLayout->addWidget(borderColorBox, row, COL_SCR_CHANNEL, 1, 2); - colorsLayout->addWidget(printBorderColorBox, row, COL_PRT_CHANNEL, 1, 2); + colorsLayout->addWidget( borderLabel, row, COL_LABEL ); + colorsLayout->addWidget( borderColorBox, row, COL_SCR_CHANNEL, 1, 2 ); + colorsLayout->addWidget( printBorderColorBox, row, COL_PRT_CHANNEL, 1, 2 ); ++row; - colorsLayout->addWidget(markersLabel, row, COL_LABEL); - colorsLayout->addWidget(markersColorBox, row, COL_SCR_CHANNEL, 1, 2); - colorsLayout->addWidget(printMarkersColorBox, row, COL_PRT_CHANNEL, 1, 2); + colorsLayout->addWidget( markersLabel, row, COL_LABEL ); + colorsLayout->addWidget( markersColorBox, row, COL_SCR_CHANNEL, 1, 2 ); + colorsLayout->addWidget( printMarkersColorBox, row, COL_PRT_CHANNEL, 1, 2 ); ++row; - colorsLayout->addWidget(textLabel, row, COL_LABEL); - colorsLayout->addWidget(textColorBox, row, COL_SCR_CHANNEL, 1, 2); - colorsLayout->addWidget(printTextColorBox, row, COL_PRT_CHANNEL, 1, 2); + colorsLayout->addWidget( textLabel, row, COL_LABEL ); + colorsLayout->addWidget( textColorBox, row, COL_SCR_CHANNEL, 1, 2 ); + colorsLayout->addWidget( printTextColorBox, row, COL_PRT_CHANNEL, 1, 2 ); ++row; // Graph - colorsLayout->addWidget(graphLabel, row, COL_LABEL, 1, COL_PRT_SPECTRUM - COL_LABEL + 1); + colorsLayout->addWidget( graphLabel, row, COL_LABEL, 1, COL_PRT_SPECTRUM - COL_LABEL + 1 ); ++row; - colorsLayout->addWidget(screenChannelLabel, row, COL_SCR_CHANNEL); - colorsLayout->addWidget(screenSpectrumLabel, row, COL_SCR_SPECTRUM); - colorsLayout->addWidget(printChannelLabel, row, COL_PRT_CHANNEL); - colorsLayout->addWidget(printSpectrumLabel, row, COL_PRT_SPECTRUM); + colorsLayout->addWidget( screenChannelLabel, row, COL_SCR_CHANNEL ); + colorsLayout->addWidget( screenSpectrumLabel, row, COL_SCR_SPECTRUM ); + colorsLayout->addWidget( printChannelLabel, row, COL_PRT_CHANNEL ); + colorsLayout->addWidget( printSpectrumLabel, row, COL_PRT_SPECTRUM ); ++row; - for (ChannelID channel = 0; channel < settings->scope.voltage.size(); ++channel, ++row) { - colorsLayout->addWidget(colorLabel[channel], row, COL_LABEL); - colorsLayout->addWidget(screenChannelColorBox[channel], row, COL_SCR_CHANNEL); - colorsLayout->addWidget(screenSpectrumColorBox[channel], row, COL_SCR_SPECTRUM); - colorsLayout->addWidget(printChannelColorBox[channel], row, COL_PRT_CHANNEL); - colorsLayout->addWidget(printSpectrumColorBox[channel], row, COL_PRT_SPECTRUM); + for ( ChannelID channel = 0; channel < settings->scope.voltage.size(); ++channel, ++row ) { + colorsLayout->addWidget( colorLabel[ channel ], row, COL_LABEL ); + colorsLayout->addWidget( screenChannelColorBox[ channel ], row, COL_SCR_CHANNEL ); + colorsLayout->addWidget( screenSpectrumColorBox[ channel ], row, COL_SCR_SPECTRUM ); + colorsLayout->addWidget( printChannelColorBox[ channel ], row, COL_PRT_CHANNEL ); + colorsLayout->addWidget( printSpectrumColorBox[ channel ], row, COL_PRT_SPECTRUM ); } - colorsGroup = new QGroupBox(tr("Screen and Print Colors")); - colorsGroup->setLayout(colorsLayout); + colorsGroup = new QGroupBox( tr( "Screen and Print Colors" ) ); + colorsGroup->setLayout( colorsLayout ); // Main layout mainLayout = new QVBoxLayout(); - mainLayout->addWidget(colorsGroup); - mainLayout->addStretch(1); + mainLayout->addWidget( colorsGroup ); + mainLayout->addStretch( 1 ); - setLayout(mainLayout); + setLayout( mainLayout ); } /// \brief Saves the new settings. @@ -146,10 +147,10 @@ void DsoConfigColorsPage::saveSettings() { colorSettings.print.text = printTextColorBox->getColor(); // Graph category - for (ChannelID channel = 0; channel < settings->scope.voltage.size(); ++channel) { - colorSettings.screen.voltage[channel] = screenChannelColorBox[channel]->getColor(); - colorSettings.screen.spectrum[channel] = screenSpectrumColorBox[channel]->getColor(); - colorSettings.print.voltage[channel] = printChannelColorBox[channel]->getColor(); - colorSettings.print.spectrum[channel] = printSpectrumColorBox[channel]->getColor(); + for ( ChannelID channel = 0; channel < settings->scope.voltage.size(); ++channel ) { + colorSettings.screen.voltage[ channel ] = screenChannelColorBox[ channel ]->getColor(); + colorSettings.screen.spectrum[ channel ] = screenSpectrumColorBox[ channel ]->getColor(); + colorSettings.print.voltage[ channel ] = printChannelColorBox[ channel ]->getColor(); + colorSettings.print.spectrum[ channel ] = printSpectrumColorBox[ channel ]->getColor(); } } diff --git a/openhantek/src/configdialog/DsoConfigColorsPage.h b/openhantek/src/configdialog/DsoConfigColorsPage.h index e6a1e42e..da5faa3b 100644 --- a/openhantek/src/configdialog/DsoConfigColorsPage.h +++ b/openhantek/src/configdialog/DsoConfigColorsPage.h @@ -23,7 +23,7 @@ class DsoConfigColorsPage : public QWidget { Q_OBJECT public: - DsoConfigColorsPage(DsoSettings *settings, QWidget *parent = nullptr); + DsoConfigColorsPage( DsoSettings *settings, QWidget *parent = nullptr ); public slots: void saveSettings(); diff --git a/openhantek/src/configdialog/DsoConfigFilePage.cpp b/openhantek/src/configdialog/DsoConfigFilePage.cpp index 986008b4..91064034 100644 --- a/openhantek/src/configdialog/DsoConfigFilePage.cpp +++ b/openhantek/src/configdialog/DsoConfigFilePage.cpp @@ -2,59 +2,60 @@ #include "DsoConfigFilePage.h" -DsoConfigFilePage::DsoConfigFilePage(DsoSettings *settings, QWidget *parent) : QWidget(parent), settings(settings) { +DsoConfigFilePage::DsoConfigFilePage( DsoSettings *settings, QWidget *parent ) + : QWidget( parent ), settings( settings ) { // Export group - screenColorCheckBox = new QCheckBox(tr("Export Images with Screen Colors")); - screenColorCheckBox->setChecked(settings->view.screenColorImages); + screenColorCheckBox = new QCheckBox( tr( "Export Images with Screen Colors" ) ); + screenColorCheckBox->setChecked( settings->view.screenColorImages ); - imageWidthLabel = new QLabel(tr("Image width")); + imageWidthLabel = new QLabel( tr( "Image width" ) ); imageWidthSpinBox = new QSpinBox(); - imageWidthSpinBox->setMinimum(100); - imageWidthSpinBox->setMaximum(9999); - imageWidthSpinBox->setValue(settings->exporting.imageSize.width()); - imageHeightLabel = new QLabel(tr("Image height")); + imageWidthSpinBox->setMinimum( 100 ); + imageWidthSpinBox->setMaximum( 9999 ); + imageWidthSpinBox->setValue( settings->exporting.imageSize.width() ); + imageHeightLabel = new QLabel( tr( "Image height" ) ); imageHeightSpinBox = new QSpinBox(); - imageHeightSpinBox->setMinimum(100); - imageHeightSpinBox->setMaximum(9999); - imageHeightSpinBox->setValue(settings->exporting.imageSize.height()); + imageHeightSpinBox->setMinimum( 100 ); + imageHeightSpinBox->setMaximum( 9999 ); + imageHeightSpinBox->setValue( settings->exporting.imageSize.height() ); exportLayout = new QGridLayout(); - exportLayout->addWidget(screenColorCheckBox, 0, 0, 1, 2); - exportLayout->addWidget(imageWidthLabel, 1, 0); - exportLayout->addWidget(imageWidthSpinBox, 1, 1); - exportLayout->addWidget(imageHeightLabel, 2, 0); - exportLayout->addWidget(imageHeightSpinBox, 2, 1); + exportLayout->addWidget( screenColorCheckBox, 0, 0, 1, 2 ); + exportLayout->addWidget( imageWidthLabel, 1, 0 ); + exportLayout->addWidget( imageWidthSpinBox, 1, 1 ); + exportLayout->addWidget( imageHeightLabel, 2, 0 ); + exportLayout->addWidget( imageHeightSpinBox, 2, 1 ); - exportGroup = new QGroupBox(tr("Export")); - exportGroup->setLayout(exportLayout); + exportGroup = new QGroupBox( tr( "Export" ) ); + exportGroup->setLayout( exportLayout ); // Configuration group - saveOnExitCheckBox = new QCheckBox(tr("Save default settings on exit")); - saveOnExitCheckBox->setChecked(settings->alwaysSave); - saveNowButton = new QPushButton(tr("Save default settings now")); + saveOnExitCheckBox = new QCheckBox( tr( "Save default settings on exit" ) ); + saveOnExitCheckBox->setChecked( settings->alwaysSave ); + saveNowButton = new QPushButton( tr( "Save default settings now" ) ); configurationLayout = new QVBoxLayout(); - configurationLayout->addWidget(saveOnExitCheckBox, 0); - configurationLayout->addWidget(saveNowButton, 1); + configurationLayout->addWidget( saveOnExitCheckBox, 0 ); + configurationLayout->addWidget( saveNowButton, 1 ); - configurationGroup = new QGroupBox(tr("Configuration")); - configurationGroup->setLayout(configurationLayout); + configurationGroup = new QGroupBox( tr( "Configuration" ) ); + configurationGroup->setLayout( configurationLayout ); // Main layout mainLayout = new QVBoxLayout(); - mainLayout->addWidget(exportGroup); - mainLayout->addWidget(configurationGroup); - mainLayout->addStretch(1); + mainLayout->addWidget( exportGroup ); + mainLayout->addWidget( configurationGroup ); + mainLayout->addStretch( 1 ); - setLayout(mainLayout); + setLayout( mainLayout ); - connect(saveNowButton, &QAbstractButton::clicked, [settings]() { settings->save(); }); + connect( saveNowButton, &QAbstractButton::clicked, [settings]() { settings->save(); } ); } /// \brief Saves the new settings. void DsoConfigFilePage::saveSettings() { settings->alwaysSave = saveOnExitCheckBox->isChecked(); settings->view.screenColorImages = screenColorCheckBox->isChecked(); - settings->exporting.imageSize.setWidth(imageWidthSpinBox->value()); - settings->exporting.imageSize.setHeight(imageHeightSpinBox->value()); + settings->exporting.imageSize.setWidth( imageWidthSpinBox->value() ); + settings->exporting.imageSize.setHeight( imageHeightSpinBox->value() ); } diff --git a/openhantek/src/configdialog/DsoConfigFilePage.h b/openhantek/src/configdialog/DsoConfigFilePage.h index eda76729..d57b0fde 100644 --- a/openhantek/src/configdialog/DsoConfigFilePage.h +++ b/openhantek/src/configdialog/DsoConfigFilePage.h @@ -22,7 +22,7 @@ class DsoConfigFilePage : public QWidget { Q_OBJECT public: - DsoConfigFilePage(DsoSettings *settings, QWidget *parent = nullptr); + DsoConfigFilePage( DsoSettings *settings, QWidget *parent = nullptr ); public slots: void saveSettings(); diff --git a/openhantek/src/configdialog/DsoConfigScopePage.cpp b/openhantek/src/configdialog/DsoConfigScopePage.cpp index 371cd524..c838d870 100644 --- a/openhantek/src/configdialog/DsoConfigScopePage.cpp +++ b/openhantek/src/configdialog/DsoConfigScopePage.cpp @@ -2,55 +2,56 @@ #include "DsoConfigScopePage.h" -DsoConfigScopePage::DsoConfigScopePage(DsoSettings *settings, QWidget *parent) : QWidget(parent), settings(settings) { +DsoConfigScopePage::DsoConfigScopePage( DsoSettings *settings, QWidget *parent ) + : QWidget( parent ), settings( settings ) { // Initialize lists for comboboxes QStringList interpolationStrings; - interpolationStrings << tr("Off") << tr("Linear"); + interpolationStrings << tr( "Off" ) << tr( "Linear" ); // Initialize elements - interpolationLabel = new QLabel(tr("Interpolation")); + interpolationLabel = new QLabel( tr( "Interpolation" ) ); interpolationComboBox = new QComboBox(); - interpolationComboBox->addItems(interpolationStrings); - interpolationComboBox->setCurrentIndex(settings->view.interpolation); - digitalPhosphorDepthLabel = new QLabel(tr("Digital phosphor depth")); + interpolationComboBox->addItems( interpolationStrings ); + interpolationComboBox->setCurrentIndex( settings->view.interpolation ); + digitalPhosphorDepthLabel = new QLabel( tr( "Digital phosphor depth" ) ); digitalPhosphorDepthSpinBox = new QSpinBox(); - digitalPhosphorDepthSpinBox->setMinimum(2); - digitalPhosphorDepthSpinBox->setMaximum(99); - digitalPhosphorDepthSpinBox->setValue(int(settings->view.digitalPhosphorDepth)); + digitalPhosphorDepthSpinBox->setMinimum( 2 ); + digitalPhosphorDepthSpinBox->setMaximum( 99 ); + digitalPhosphorDepthSpinBox->setValue( int( settings->view.digitalPhosphorDepth ) ); graphLayout = new QGridLayout(); - graphLayout->addWidget(interpolationLabel, 1, 0); - graphLayout->addWidget(interpolationComboBox, 1, 1); - graphLayout->addWidget(digitalPhosphorDepthLabel, 2, 0); - graphLayout->addWidget(digitalPhosphorDepthSpinBox, 2, 1); + graphLayout->addWidget( interpolationLabel, 1, 0 ); + graphLayout->addWidget( interpolationComboBox, 1, 1 ); + graphLayout->addWidget( digitalPhosphorDepthLabel, 2, 0 ); + graphLayout->addWidget( digitalPhosphorDepthSpinBox, 2, 1 ); - graphGroup = new QGroupBox(tr("Graph")); - graphGroup->setLayout(graphLayout); + graphGroup = new QGroupBox( tr( "Graph" ) ); + graphGroup->setLayout( graphLayout ); - cursorsLabel = new QLabel(tr("Position")); + cursorsLabel = new QLabel( tr( "Position" ) ); cursorsComboBox = new QComboBox(); - cursorsComboBox->addItem(tr("Left"), Qt::LeftToolBarArea); - cursorsComboBox->addItem(tr("Right"), Qt::RightToolBarArea); - cursorsComboBox->setCurrentIndex(settings->view.cursorGridPosition == Qt::LeftToolBarArea ? 0 : 1); + cursorsComboBox->addItem( tr( "Left" ), Qt::LeftToolBarArea ); + cursorsComboBox->addItem( tr( "Right" ), Qt::RightToolBarArea ); + cursorsComboBox->setCurrentIndex( settings->view.cursorGridPosition == Qt::LeftToolBarArea ? 0 : 1 ); cursorsLayout = new QGridLayout(); - cursorsLayout->addWidget(cursorsLabel, 0, 0); - cursorsLayout->addWidget(cursorsComboBox, 0, 1); + cursorsLayout->addWidget( cursorsLabel, 0, 0 ); + cursorsLayout->addWidget( cursorsComboBox, 0, 1 ); - cursorsGroup = new QGroupBox(tr("Cursors")); - cursorsGroup->setLayout(cursorsLayout); + cursorsGroup = new QGroupBox( tr( "Cursors" ) ); + cursorsGroup->setLayout( cursorsLayout ); mainLayout = new QVBoxLayout(); - mainLayout->addWidget(graphGroup); - mainLayout->addWidget(cursorsGroup); - mainLayout->addStretch(1); + mainLayout->addWidget( graphGroup ); + mainLayout->addWidget( cursorsGroup ); + mainLayout->addStretch( 1 ); - setLayout(mainLayout); + setLayout( mainLayout ); } /// \brief Saves the new settings. void DsoConfigScopePage::saveSettings() { - settings->view.interpolation = Dso::InterpolationMode(interpolationComboBox->currentIndex()); - settings->view.digitalPhosphorDepth = unsigned(digitalPhosphorDepthSpinBox->value()); - settings->view.cursorGridPosition = Qt::ToolBarArea(cursorsComboBox->currentData().toUInt()); + settings->view.interpolation = Dso::InterpolationMode( interpolationComboBox->currentIndex() ); + settings->view.digitalPhosphorDepth = unsigned( digitalPhosphorDepthSpinBox->value() ); + settings->view.cursorGridPosition = Qt::ToolBarArea( cursorsComboBox->currentData().toUInt() ); } diff --git a/openhantek/src/configdialog/DsoConfigScopePage.h b/openhantek/src/configdialog/DsoConfigScopePage.h index 378101db..ee6bc4c0 100644 --- a/openhantek/src/configdialog/DsoConfigScopePage.h +++ b/openhantek/src/configdialog/DsoConfigScopePage.h @@ -21,7 +21,7 @@ class DsoConfigScopePage : public QWidget { Q_OBJECT public: - DsoConfigScopePage(DsoSettings *settings, QWidget *parent = nullptr); + DsoConfigScopePage( DsoSettings *settings, QWidget *parent = nullptr ); public slots: void saveSettings(); diff --git a/openhantek/src/configdialog/configdialog.cpp b/openhantek/src/configdialog/configdialog.cpp index a5cd8a0a..2caf57b7 100644 --- a/openhantek/src/configdialog/configdialog.cpp +++ b/openhantek/src/configdialog/configdialog.cpp @@ -40,60 +40,60 @@ anyway, ignore it /// \param settings The target settings object. /// \param parent The parent widget. /// \param flags Flags for the window manager. -DsoConfigDialog::DsoConfigDialog(DsoSettings *settings, QWidget *parent, Qt::WindowFlags flags) - : QDialog(parent, flags), settings(settings) { +DsoConfigDialog::DsoConfigDialog( DsoSettings *settings, QWidget *parent, Qt::WindowFlags flags ) + : QDialog( parent, flags ), settings( settings ) { - this->setWindowTitle(tr("Settings")); + this->setWindowTitle( tr( "Settings" ) ); this->contentsWidget = new QListWidget; - this->contentsWidget->setViewMode(QListView::IconMode); - this->contentsWidget->setIconSize(QSize(CONFIG_LIST_ICONWIDTH, CONFIG_LIST_ICONHEIGHT)); - this->contentsWidget->setMovement(QListView::Static); + this->contentsWidget->setViewMode( QListView::IconMode ); + this->contentsWidget->setIconSize( QSize( CONFIG_LIST_ICONWIDTH, CONFIG_LIST_ICONHEIGHT ) ); + this->contentsWidget->setMovement( QListView::Static ); this->contentsWidget->setGridSize( - QSize(CONFIG_LIST_WIDTH - 2 * this->contentsWidget->frameWidth(), CONFIG_LIST_ITEMHEIGHT)); - this->contentsWidget->setMaximumWidth(CONFIG_LIST_WIDTH); - this->contentsWidget->setMinimumWidth(CONFIG_LIST_WIDTH); - this->contentsWidget->setMinimumHeight(CONFIG_LIST_ITEMHEIGHT * 3 + 2 * (this->contentsWidget->frameWidth())); - - this->analysisPage = new DsoConfigAnalysisPage(settings); - this->colorsPage = new DsoConfigColorsPage(settings); - this->filePage = new DsoConfigFilePage(settings); - this->scopePage = new DsoConfigScopePage(settings); + QSize( CONFIG_LIST_WIDTH - 2 * this->contentsWidget->frameWidth(), CONFIG_LIST_ITEMHEIGHT ) ); + this->contentsWidget->setMaximumWidth( CONFIG_LIST_WIDTH ); + this->contentsWidget->setMinimumWidth( CONFIG_LIST_WIDTH ); + this->contentsWidget->setMinimumHeight( CONFIG_LIST_ITEMHEIGHT * 3 + 2 * ( this->contentsWidget->frameWidth() ) ); + + this->analysisPage = new DsoConfigAnalysisPage( settings ); + this->colorsPage = new DsoConfigColorsPage( settings ); + this->filePage = new DsoConfigFilePage( settings ); + this->scopePage = new DsoConfigScopePage( settings ); this->pagesWidget = new QStackedWidget; - this->pagesWidget->addWidget(this->analysisPage); - this->pagesWidget->addWidget(this->scopePage); - this->pagesWidget->addWidget(this->colorsPage); - this->pagesWidget->addWidget(this->filePage); + this->pagesWidget->addWidget( this->analysisPage ); + this->pagesWidget->addWidget( this->scopePage ); + this->pagesWidget->addWidget( this->colorsPage ); + this->pagesWidget->addWidget( this->filePage ); - this->acceptButton = new QPushButton(tr("&Ok")); - this->acceptButton->setDefault(true); - this->applyButton = new QPushButton(tr("&Apply")); - this->rejectButton = new QPushButton(tr("&Cancel")); + this->acceptButton = new QPushButton( tr( "&Ok" ) ); + this->acceptButton->setDefault( true ); + this->applyButton = new QPushButton( tr( "&Apply" ) ); + this->rejectButton = new QPushButton( tr( "&Cancel" ) ); this->createIcons(); - this->contentsWidget->setCurrentRow(0); + this->contentsWidget->setCurrentRow( 0 ); this->horizontalLayout = new QHBoxLayout; - this->horizontalLayout->addWidget(this->contentsWidget); - this->horizontalLayout->addWidget(this->pagesWidget, 1); + this->horizontalLayout->addWidget( this->contentsWidget ); + this->horizontalLayout->addWidget( this->pagesWidget, 1 ); this->buttonsLayout = new QHBoxLayout; - this->buttonsLayout->setSpacing(8); - this->buttonsLayout->addStretch(1); - this->buttonsLayout->addWidget(this->acceptButton); - this->buttonsLayout->addWidget(this->applyButton); - this->buttonsLayout->addWidget(this->rejectButton); + this->buttonsLayout->setSpacing( 8 ); + this->buttonsLayout->addStretch( 1 ); + this->buttonsLayout->addWidget( this->acceptButton ); + this->buttonsLayout->addWidget( this->applyButton ); + this->buttonsLayout->addWidget( this->rejectButton ); this->mainLayout = new QVBoxLayout; - this->mainLayout->addLayout(this->horizontalLayout); - this->mainLayout->addStretch(1); - this->mainLayout->addSpacing(8); - this->mainLayout->addLayout(this->buttonsLayout); - this->setLayout(this->mainLayout); - - connect(this->acceptButton, &QAbstractButton::clicked, this, &DsoConfigDialog::accept); - connect(this->applyButton, &QAbstractButton::clicked, this, &DsoConfigDialog::apply); - connect(this->rejectButton, &QAbstractButton::clicked, this, &QDialog::reject); + this->mainLayout->addLayout( this->horizontalLayout ); + this->mainLayout->addStretch( 1 ); + this->mainLayout->addSpacing( 8 ); + this->mainLayout->addLayout( this->buttonsLayout ); + this->setLayout( this->mainLayout ); + + connect( this->acceptButton, &QAbstractButton::clicked, this, &DsoConfigDialog::accept ); + connect( this->applyButton, &QAbstractButton::clicked, this, &DsoConfigDialog::apply ); + connect( this->rejectButton, &QAbstractButton::clicked, this, &QDialog::reject ); } /// \brief Cleans up the dialog. @@ -101,24 +101,23 @@ DsoConfigDialog::~DsoConfigDialog() {} /// \brief Create the icons for the pages. void DsoConfigDialog::createIcons() { - QListWidgetItem *analysisButton = new QListWidgetItem(contentsWidget); - analysisButton->setIcon(QIcon(":config/analysis.png")); - analysisButton->setText(tr("Spectrum")); + QListWidgetItem *analysisButton = new QListWidgetItem( contentsWidget ); + analysisButton->setIcon( QIcon( ":config/analysis.png" ) ); + analysisButton->setText( tr( "Spectrum" ) ); - QListWidgetItem *scopeButton = new QListWidgetItem(contentsWidget); - scopeButton->setIcon(QIcon(":config/scope.png")); - scopeButton->setText(tr("Scope")); + QListWidgetItem *scopeButton = new QListWidgetItem( contentsWidget ); + scopeButton->setIcon( QIcon( ":config/scope.png" ) ); + scopeButton->setText( tr( "Scope" ) ); - QListWidgetItem *colorsButton = new QListWidgetItem(contentsWidget); - colorsButton->setIcon(QIcon(":config/colors.png")); - colorsButton->setText(tr("Colors")); + QListWidgetItem *colorsButton = new QListWidgetItem( contentsWidget ); + colorsButton->setIcon( QIcon( ":config/colors.png" ) ); + colorsButton->setText( tr( "Colors" ) ); - QListWidgetItem *fileButton = new QListWidgetItem(contentsWidget); - fileButton->setIcon(QIcon(":config/file.png")); - fileButton->setText(tr("File")); + QListWidgetItem *fileButton = new QListWidgetItem( contentsWidget ); + fileButton->setIcon( QIcon( ":config/file.png" ) ); + fileButton->setText( tr( "File" ) ); - connect(contentsWidget, &QListWidget::currentItemChanged, this, - &DsoConfigDialog::changePage); + connect( contentsWidget, &QListWidget::currentItemChanged, this, &DsoConfigDialog::changePage ); } /// \brief Saves the settings and closes the dialog. @@ -139,8 +138,9 @@ void DsoConfigDialog::apply() { /// \brief Change the config page. /// \param current The page that has been selected. /// \param previous The page that was selected before. -void DsoConfigDialog::changePage(QListWidgetItem *current, QListWidgetItem *previous) { - if (!current) current = previous; +void DsoConfigDialog::changePage( QListWidgetItem *current, QListWidgetItem *previous ) { + if ( !current ) + current = previous; - pagesWidget->setCurrentIndex(contentsWidget->row(current)); + pagesWidget->setCurrentIndex( contentsWidget->row( current ) ); } diff --git a/openhantek/src/configdialog/configdialog.h b/openhantek/src/configdialog/configdialog.h index 424234a3..ba36a7dc 100644 --- a/openhantek/src/configdialog/configdialog.h +++ b/openhantek/src/configdialog/configdialog.h @@ -22,14 +22,14 @@ class DsoConfigDialog : public QDialog { Q_OBJECT public: - DsoConfigDialog(DsoSettings *settings, QWidget *parent = nullptr, Qt::WindowFlags flags = nullptr); + DsoConfigDialog( DsoSettings *settings, QWidget *parent = nullptr, Qt::WindowFlags flags = nullptr ); ~DsoConfigDialog(); public slots: void accept(); void apply(); - void changePage(QListWidgetItem *current, QListWidgetItem *previous); + void changePage( QListWidgetItem *current, QListWidgetItem *previous ); private: void createIcons(); diff --git a/openhantek/src/docks/HorizontalDock.cpp b/openhantek/src/docks/HorizontalDock.cpp index 36ac19ea..bea37bbf 100644 --- a/openhantek/src/docks/HorizontalDock.cpp +++ b/openhantek/src/docks/HorizontalDock.cpp @@ -3,191 +3,196 @@ #include #include #include +#include +#include #include #include #include -#include -#include #include #include "HorizontalDock.h" #include "dockwindows.h" -#include "viewconstants.h" #include "scopesettings.h" #include "sispinbox.h" #include "utils/printutils.h" +#include "viewconstants.h" static int row = 0; -template struct SELECT { - template - static constexpr auto OVERLOAD_OF( R (C::*pmf)(Args...) ) -> decltype(pmf) { +template struct SELECT { + template static constexpr auto OVERLOAD_OF( R ( C::*pmf )( Args... ) ) -> decltype( pmf ) { return pmf; } }; -HorizontalDock::HorizontalDock(DsoSettingsScope *scope, const Dso::ControlSpecification *spec, QWidget *parent, Qt::WindowFlags flags) - : QDockWidget(tr("Horizontal"), parent, flags), scope(scope) { +HorizontalDock::HorizontalDock( DsoSettingsScope *scope, const Dso::ControlSpecification *spec, QWidget *parent, + Qt::WindowFlags flags ) + : QDockWidget( tr( "Horizontal" ), parent, flags ), scope( scope ) { // Initialize elements - this->samplerateLabel = new QLabel(tr("Samplerate")); - this->samplerateSiSpinBox = new SiSpinBox(UNIT_SAMPLES); - this->samplerateSiSpinBox->setMinimum(1); - this->samplerateSiSpinBox->setMaximum(1e8); - this->samplerateSiSpinBox->setUnitPostfix("/s"); + this->samplerateLabel = new QLabel( tr( "Samplerate" ) ); + this->samplerateSiSpinBox = new SiSpinBox( UNIT_SAMPLES ); + this->samplerateSiSpinBox->setMinimum( 1 ); + this->samplerateSiSpinBox->setMaximum( 1e8 ); + this->samplerateSiSpinBox->setUnitPostfix( "/s" ); timebaseSteps << 1.0 << 2.0 << 5.0 << 10.0; - this->timebaseLabel = new QLabel(tr("Timebase")); - this->timebaseSiSpinBox = new SiSpinBox(UNIT_SECONDS); - this->timebaseSiSpinBox->setSteps(timebaseSteps); - this->timebaseSiSpinBox->setMinimum(1e-9); - this->timebaseSiSpinBox->setMaximum(3.6e3); + this->timebaseLabel = new QLabel( tr( "Timebase" ) ); + this->timebaseSiSpinBox = new SiSpinBox( UNIT_SECONDS ); + this->timebaseSiSpinBox->setSteps( timebaseSteps ); + this->timebaseSiSpinBox->setMinimum( 1e-9 ); + this->timebaseSiSpinBox->setMaximum( 3.6e3 ); - this->frequencybaseLabel = new QLabel(tr("Frequencybase")); - this->frequencybaseSiSpinBox = new SiSpinBox(UNIT_HERTZ); - this->frequencybaseSiSpinBox->setMinimum(1.0); - this->frequencybaseSiSpinBox->setMaximum(100e6); + this->frequencybaseLabel = new QLabel( tr( "Frequencybase" ) ); + this->frequencybaseSiSpinBox = new SiSpinBox( UNIT_HERTZ ); + this->frequencybaseSiSpinBox->setMinimum( 1.0 ); + this->frequencybaseSiSpinBox->setMaximum( 100e6 ); - this->formatLabel = new QLabel(tr("Format")); + this->formatLabel = new QLabel( tr( "Format" ) ); this->formatComboBox = new QComboBox(); - for (Dso::GraphFormat format: Dso::GraphFormatEnum) - this->formatComboBox->addItem(Dso::graphFormatString(format)); + for ( Dso::GraphFormat format : Dso::GraphFormatEnum ) + this->formatComboBox->addItem( Dso::graphFormatString( format ) ); - this->calfreqLabel = new QLabel(tr("Calibration out")); - this->calfreqSiSpinBox = new SiSpinBox(UNIT_HERTZ); - this->calfreqSiSpinBox->setSteps(spec->calfreqSteps); - this->calfreqSiSpinBox->setMinimum(spec->calfreqSteps.first()); - this->calfreqSiSpinBox->setMaximum(spec->calfreqSteps.last()); + this->calfreqLabel = new QLabel( tr( "Calibration out" ) ); + this->calfreqSiSpinBox = new SiSpinBox( UNIT_HERTZ ); + this->calfreqSiSpinBox->setSteps( spec->calfreqSteps ); + this->calfreqSiSpinBox->setMinimum( spec->calfreqSteps.first() ); + this->calfreqSiSpinBox->setMaximum( spec->calfreqSteps.last() ); this->dockLayout = new QGridLayout(); - this->dockLayout->setColumnMinimumWidth(0, 64); - this->dockLayout->setColumnStretch(1, 1); + this->dockLayout->setColumnMinimumWidth( 0, 64 ); + this->dockLayout->setColumnStretch( 1, 1 ); this->dockLayout->setSpacing( DOCK_LAYOUT_SPACING ); - row = 0; // allows flexible shift up/down - this->dockLayout->addWidget(this->timebaseLabel, row, 0); - this->dockLayout->addWidget(this->timebaseSiSpinBox, row++, 1); - this->dockLayout->addWidget(this->samplerateLabel, row, 0); - this->dockLayout->addWidget(this->samplerateSiSpinBox, row++, 1); - this->dockLayout->addWidget(this->frequencybaseLabel, row, 0); - this->dockLayout->addWidget(this->frequencybaseSiSpinBox, row++, 1); - this->dockLayout->addWidget(this->formatLabel, row, 0); - this->dockLayout->addWidget(this->formatComboBox, row++, 1); - this->dockLayout->addWidget(this->calfreqLabel, row, 0); - this->dockLayout->addWidget(this->calfreqSiSpinBox, row++, 1); + row = 0; // allows flexible shift up/down + this->dockLayout->addWidget( this->timebaseLabel, row, 0 ); + this->dockLayout->addWidget( this->timebaseSiSpinBox, row++, 1 ); + this->dockLayout->addWidget( this->samplerateLabel, row, 0 ); + this->dockLayout->addWidget( this->samplerateSiSpinBox, row++, 1 ); + this->dockLayout->addWidget( this->frequencybaseLabel, row, 0 ); + this->dockLayout->addWidget( this->frequencybaseSiSpinBox, row++, 1 ); + this->dockLayout->addWidget( this->formatLabel, row, 0 ); + this->dockLayout->addWidget( this->formatComboBox, row++, 1 ); + this->dockLayout->addWidget( this->calfreqLabel, row, 0 ); + this->dockLayout->addWidget( this->calfreqSiSpinBox, row++, 1 ); this->dockWidget = new QWidget(); - SetupDockWidget(this, dockWidget, dockLayout); + SetupDockWidget( this, dockWidget, dockLayout ); // Load settings into GUI - this->loadSettings(scope); - + this->loadSettings( scope ); + // Connect signals and slots - connect(this->samplerateSiSpinBox, SELECT::OVERLOAD_OF(&QDoubleSpinBox::valueChanged), this, &HorizontalDock::samplerateSelected); - connect(this->timebaseSiSpinBox, SELECT::OVERLOAD_OF(&QDoubleSpinBox::valueChanged), this, &HorizontalDock::timebaseSelected); - connect(this->frequencybaseSiSpinBox, SELECT::OVERLOAD_OF(&QDoubleSpinBox::valueChanged), this, &HorizontalDock::frequencybaseSelected); - connect(this->formatComboBox, SELECT::OVERLOAD_OF(&QComboBox::currentIndexChanged), this, &HorizontalDock::formatSelected); - connect(this->calfreqSiSpinBox, SELECT::OVERLOAD_OF(&QDoubleSpinBox::valueChanged), this, &HorizontalDock::calfreqSelected); + connect( this->samplerateSiSpinBox, SELECT::OVERLOAD_OF( &QDoubleSpinBox::valueChanged ), this, + &HorizontalDock::samplerateSelected ); + connect( this->timebaseSiSpinBox, SELECT::OVERLOAD_OF( &QDoubleSpinBox::valueChanged ), this, + &HorizontalDock::timebaseSelected ); + connect( this->frequencybaseSiSpinBox, SELECT::OVERLOAD_OF( &QDoubleSpinBox::valueChanged ), this, + &HorizontalDock::frequencybaseSelected ); + connect( this->formatComboBox, SELECT::OVERLOAD_OF( &QComboBox::currentIndexChanged ), this, + &HorizontalDock::formatSelected ); + connect( this->calfreqSiSpinBox, SELECT::OVERLOAD_OF( &QDoubleSpinBox::valueChanged ), this, + &HorizontalDock::calfreqSelected ); } -void HorizontalDock::loadSettings(DsoSettingsScope *scope) { +void HorizontalDock::loadSettings( DsoSettingsScope *scope ) { // Set values - this->setSamplerate(scope->horizontal.samplerate); - this->setTimebase(scope->horizontal.timebase); - this->setFrequencybase(scope->horizontal.frequencybase); - this->setFormat(scope->horizontal.format); - this->setCalfreq(scope->horizontal.calfreq); + this->setSamplerate( scope->horizontal.samplerate ); + this->setTimebase( scope->horizontal.timebase ); + this->setFrequencybase( scope->horizontal.frequencybase ); + this->setFormat( scope->horizontal.format ); + this->setCalfreq( scope->horizontal.calfreq ); } /// \brief Don't close the dock, just hide it. /// \param event The close event that should be handled. -void HorizontalDock::closeEvent(QCloseEvent *event) { +void HorizontalDock::closeEvent( QCloseEvent *event ) { this->hide(); event->accept(); } -void HorizontalDock::setFrequencybase(double frequencybase) { - QSignalBlocker blocker(frequencybaseSiSpinBox); - frequencybaseSiSpinBox->setValue(frequencybase); +void HorizontalDock::setFrequencybase( double frequencybase ) { + QSignalBlocker blocker( frequencybaseSiSpinBox ); + frequencybaseSiSpinBox->setValue( frequencybase ); } -double HorizontalDock::setSamplerate(double samplerate) { - //printf( "HD::setSamplerate( %g )\n", samplerate ); - QSignalBlocker blocker(samplerateSiSpinBox); - samplerateSiSpinBox->setValue(samplerate); +double HorizontalDock::setSamplerate( double samplerate ) { + // printf( "HD::setSamplerate( %g )\n", samplerate ); + QSignalBlocker blocker( samplerateSiSpinBox ); + samplerateSiSpinBox->setValue( samplerate ); double maxFreqBase = samplerate / DIVS_TIME / 2; frequencybaseSiSpinBox->setMaximum( maxFreqBase ); - if (frequencybaseSiSpinBox->value() > maxFreqBase ) + if ( frequencybaseSiSpinBox->value() > maxFreqBase ) setFrequencybase( maxFreqBase ); return samplerateSiSpinBox->value(); } -double HorizontalDock::setTimebase(double timebase) { - //printf( "HD::setTimebase( %g )\n", timebase ); - QSignalBlocker blocker(timebaseSiSpinBox); +double HorizontalDock::setTimebase( double timebase ) { + // printf( "HD::setTimebase( %g )\n", timebase ); + QSignalBlocker blocker( timebaseSiSpinBox ); // timebaseSteps are repeated in each decade - double decade = pow(10, floor(log10(timebase))); + double decade = pow( 10, floor( log10( timebase ) ) ); double vNorm = timebase / decade; - for (int i = 0; i < timebaseSteps.size() - 1; ++i) { - if (timebaseSteps.at(i) <= vNorm && vNorm < timebaseSteps.at(i + 1)) { - timebaseSiSpinBox->setValue(decade * timebaseSteps.at(i)); + for ( int i = 0; i < timebaseSteps.size() - 1; ++i ) { + if ( timebaseSteps.at( i ) <= vNorm && vNorm < timebaseSteps.at( i + 1 ) ) { + timebaseSiSpinBox->setValue( decade * timebaseSteps.at( i ) ); break; } } - //printf( "return %g\n", timebaseSiSpinBox->value() ); + // printf( "return %g\n", timebaseSiSpinBox->value() ); calculateSamplerateSteps( timebase ); return timebaseSiSpinBox->value(); } -int HorizontalDock::setFormat(Dso::GraphFormat format) { - QSignalBlocker blocker(formatComboBox); - if (format >= Dso::GraphFormat::TY && format <= Dso::GraphFormat::XY) { - formatComboBox->setCurrentIndex(format); +int HorizontalDock::setFormat( Dso::GraphFormat format ) { + QSignalBlocker blocker( formatComboBox ); + if ( format >= Dso::GraphFormat::TY && format <= Dso::GraphFormat::XY ) { + formatComboBox->setCurrentIndex( format ); return format; } return -1; } -double HorizontalDock::setCalfreq(double calfreq) { - QSignalBlocker blocker(calfreqSiSpinBox); - calfreqSiSpinBox->setValue(calfreq); +double HorizontalDock::setCalfreq( double calfreq ) { + QSignalBlocker blocker( calfreqSiSpinBox ); + calfreqSiSpinBox->setValue( calfreq ); return calfreqSiSpinBox->value(); } -void HorizontalDock::setSamplerateLimits(double minimum, double maximum) { - //printf( "HD::setSamplerateLimits( %g, %g )\n", minimum, maximum ); - QSignalBlocker blocker(samplerateSiSpinBox); - if ( bool(minimum) ) - this->samplerateSiSpinBox->setMinimum(minimum); - if ( bool(maximum) ) - this->samplerateSiSpinBox->setMaximum(maximum); +void HorizontalDock::setSamplerateLimits( double minimum, double maximum ) { + // printf( "HD::setSamplerateLimits( %g, %g )\n", minimum, maximum ); + QSignalBlocker blocker( samplerateSiSpinBox ); + if ( bool( minimum ) ) + this->samplerateSiSpinBox->setMinimum( minimum ); + if ( bool( maximum ) ) + this->samplerateSiSpinBox->setMaximum( maximum ); } -void HorizontalDock::setSamplerateSteps(int mode, const QList steps) { - //printf( "HD::setSamplerateSteps( %d )\n", mode ); +void HorizontalDock::setSamplerateSteps( int mode, const QList steps ) { + // printf( "HD::setSamplerateSteps( %d )\n", mode ); samplerateSteps = steps; // Assume that method is invoked for fixed samplerate devices only - QSignalBlocker samplerateBlocker(samplerateSiSpinBox); - samplerateSiSpinBox->setMode(mode); - samplerateSiSpinBox->setSteps(steps); - samplerateSiSpinBox->setMinimum(steps.first()); - samplerateSiSpinBox->setMaximum(steps.last()); + QSignalBlocker samplerateBlocker( samplerateSiSpinBox ); + samplerateSiSpinBox->setMode( mode ); + samplerateSiSpinBox->setSteps( steps ); + samplerateSiSpinBox->setMinimum( steps.first() ); + samplerateSiSpinBox->setMaximum( steps.last() ); // Make reasonable adjustments to the timebase spinbox - QSignalBlocker timebaseBlocker(timebaseSiSpinBox); + QSignalBlocker timebaseBlocker( timebaseSiSpinBox ); timebaseSiSpinBox->setMinimum( pow( 10, floor( log10( 1.0 / steps.last() ) ) ) ); // max 1000 ms - double maxTime = pow(10, ceil(log10(1000.0 / (steps.first())))); + double maxTime = pow( 10, ceil( log10( 1000.0 / ( steps.first() ) ) ) ); timebaseSiSpinBox->setMaximum( maxTime ); calculateSamplerateSteps( timebaseSiSpinBox->value() ); } @@ -195,32 +200,32 @@ void HorizontalDock::setSamplerateSteps(int mode, const QList steps) { /// \brief Called when the frequencybase spinbox changes its value. /// \param frequencybase The frequencybase in hertz. -void HorizontalDock::frequencybaseSelected(double frequencybase) { +void HorizontalDock::frequencybaseSelected( double frequencybase ) { scope->horizontal.frequencybase = frequencybase; - emit frequencybaseChanged(frequencybase); + emit frequencybaseChanged( frequencybase ); } /// \brief Called when the samplerate spinbox changes its value. /// \param samplerate The samplerate in samples/second. -void HorizontalDock::samplerateSelected(double samplerate) { - //printf( "HD::samplerateSelected( %g )\n", samplerate ); +void HorizontalDock::samplerateSelected( double samplerate ) { + // printf( "HD::samplerateSelected( %g )\n", samplerate ); scope->horizontal.samplerate = samplerate; - emit samplerateChanged(samplerate); + emit samplerateChanged( samplerate ); } /// \brief Called when the timebase spinbox changes its value. /// \param timebase The timebase in seconds. -void HorizontalDock::timebaseSelected(double timebase) { - //printf( "HD::timebaseSelected( %g )\n", timebase ); +void HorizontalDock::timebaseSelected( double timebase ) { + // printf( "HD::timebaseSelected( %g )\n", timebase ); scope->horizontal.timebase = timebase; calculateSamplerateSteps( timebase ); - emit timebaseChanged(timebase); + emit timebaseChanged( timebase ); } -void HorizontalDock::calculateSamplerateSteps(double timebase) { +void HorizontalDock::calculateSamplerateSteps( double timebase ) { int size = samplerateSteps.size(); if ( size ) { // search appropriate min & max sample rate @@ -228,10 +233,10 @@ void HorizontalDock::calculateSamplerateSteps(double timebase) { double max = samplerateSteps[ 0 ]; for ( int id = 0; id < size; ++id ) { double sRate = samplerateSteps[ id ]; - //printf( "sRate %g, sRate*timebase %g\n", sRate, sRate * timebase ); + // printf( "sRate %g, sRate*timebase %g\n", sRate, sRate * timebase ); // min must be < maxRate // find minimal samplerate to get at least this number of samples per div - if ( id < size-1 && sRate * timebase <= 10 ) { + if ( id < size - 1 && sRate * timebase <= 10 ) { min = sRate; } // max must be > minRate @@ -241,7 +246,7 @@ void HorizontalDock::calculateSamplerateSteps(double timebase) { max = sRate; } } - //printf( "cSS limits: %g, %g\n", min, max ); + // printf( "cSS limits: %g, %g\n", min, max ); setSamplerateLimits( min, max ); } } @@ -249,16 +254,16 @@ void HorizontalDock::calculateSamplerateSteps(double timebase) { /// \brief Called when the format combo box changes its value. /// \param index The index of the combo box item. -void HorizontalDock::formatSelected(int index) { - scope->horizontal.format = Dso::GraphFormat(index); - emit formatChanged(scope->horizontal.format); +void HorizontalDock::formatSelected( int index ) { + scope->horizontal.format = Dso::GraphFormat( index ); + emit formatChanged( scope->horizontal.format ); } /// \brief Called when the calfreq spinbox changes its value. /// \param calfreq The calibration frequency in hertz. -void HorizontalDock::calfreqSelected(double calfreq) { - //printf( "calfreqSelected: %g\n", calfreq ); +void HorizontalDock::calfreqSelected( double calfreq ) { + // printf( "calfreqSelected: %g\n", calfreq ); scope->horizontal.calfreq = calfreq; - emit calfreqChanged(calfreq); + emit calfreqChanged( calfreq ); } diff --git a/openhantek/src/docks/HorizontalDock.h b/openhantek/src/docks/HorizontalDock.h index 10f9b91f..2e36cae2 100644 --- a/openhantek/src/docks/HorizontalDock.h +++ b/openhantek/src/docks/HorizontalDock.h @@ -7,8 +7,8 @@ #include -#include "hantekdso/enums.h" #include "hantekdso/controlspecification.h" +#include "hantekdso/enums.h" class QLabel; class QCheckBox; @@ -17,10 +17,10 @@ class QComboBox; class SiSpinBox; struct DsoSettingsScope; -//struct ControlSpecification; +// struct ControlSpecification; -Q_DECLARE_METATYPE(std::vector) -Q_DECLARE_METATYPE(std::vector) +Q_DECLARE_METATYPE( std::vector ) +Q_DECLARE_METATYPE( std::vector ) /// \brief Dock window for the horizontal axis. /// It contains the settings for the timebase and the display format. @@ -32,33 +32,34 @@ class HorizontalDock : public QDockWidget { /// \param settings The target settings object. /// \param parent The parent widget. /// \param flags Flags for the window manager. - HorizontalDock(DsoSettingsScope *scope, const Dso::ControlSpecification *spec, QWidget *parent, Qt::WindowFlags flags = nullptr); + HorizontalDock( DsoSettingsScope *scope, const Dso::ControlSpecification *spec, QWidget *parent, + Qt::WindowFlags flags = nullptr ); /// \brief Changes the frequencybase. /// \param frequencybase The frequencybase in hertz. - void setFrequencybase(double timebase); + void setFrequencybase( double timebase ); /// \brief Changes the samplerate. /// \param samplerate The samplerate in seconds. - double setSamplerate(double samplerate); + double setSamplerate( double samplerate ); /// \brief Changes the timebase. /// \param timebase The timebase in seconds. - double setTimebase(double timebase); + double setTimebase( double timebase ); /// \brief Changes the record length if the new value is supported. /// \param recordLength The record length in samples. - void setRecordLength(unsigned int recordLength); + void setRecordLength( unsigned int recordLength ); /// \brief Changes the format if the new value is supported. /// \param format The format for the horizontal axis. /// \return Index of format-value, -1 on error. - int setFormat(Dso::GraphFormat format); + int setFormat( Dso::GraphFormat format ); /// \brief Updates the minimum and maximum of the samplerate spin box. /// \param minimum The minimum value the spin box should accept. /// \param maximum The minimum value the spin box should accept. - void setSamplerateLimits(double minimum, double maximum); + void setSamplerateLimits( double minimum, double maximum ); /// \brief Updates the mode and steps of the samplerate spin box. /// \param mode The mode value the spin box should accept. /// \param steps The steps value the spin box should accept. - void setSamplerateSteps(int mode, QList sampleSteps); - void calculateSamplerateSteps(double timebase); + void setSamplerateSteps( int mode, QList sampleSteps ); + void calculateSamplerateSteps( double timebase ); /// \brief Changes the calibration frequency. /// \param calfreq The calibration frequency in hertz. double setCalfreq( double calfreq ); @@ -66,10 +67,10 @@ class HorizontalDock : public QDockWidget { public slots: /// \brief Loads settings into GUI /// \param scope Settings to load - void loadSettings(DsoSettingsScope *scope); + void loadSettings( DsoSettingsScope *scope ); protected: - void closeEvent(QCloseEvent *event); + void closeEvent( QCloseEvent *event ); QGridLayout *dockLayout; ///< The main layout for the dock window QWidget *dockWidget; ///< The main widget for the dock window QLabel *samplerateLabel; ///< The label for the samplerate spinbox @@ -84,25 +85,25 @@ class HorizontalDock : public QDockWidget { /// interpreted and shown SiSpinBox *calfreqSiSpinBox; ///< Selects the calibration frequency - DsoSettingsScope *scope; ///< The settings provided by the parent class - QList timebaseSteps; ///< Steps for the timebase spinbox - QList calfreqSteps; ///< Steps for the calfreq spinbox - QList samplerateSteps; ///< Possible sampe rates + DsoSettingsScope *scope; ///< The settings provided by the parent class + QList timebaseSteps; ///< Steps for the timebase spinbox + QList calfreqSteps; ///< Steps for the calfreq spinbox + QList samplerateSteps; ///< Possible sampe rates - QStringList formatStrings; ///< Strings for the formats + QStringList formatStrings; ///< Strings for the formats protected slots: - void frequencybaseSelected(double frequencybase); - void samplerateSelected(double samplerate); - void timebaseSelected(double timebase); - void formatSelected(int index); - void calfreqSelected(double calfreq); + void frequencybaseSelected( double frequencybase ); + void samplerateSelected( double samplerate ); + void timebaseSelected( double timebase ); + void formatSelected( int index ); + void calfreqSelected( double calfreq ); signals: - void frequencybaseChanged(double frequencybase); ///< The frequencybase has been changed - void samplerateChanged(double samplerate); ///< The samplerate has been changed - void timebaseChanged(double timebase); ///< The timebase has been changed - void recordLengthChanged(unsigned long recordLength); ///< The recordd length has been changed - void formatChanged(Dso::GraphFormat format); ///< The viewing format has been changed - void calfreqChanged(double calfreq); ///< The timebase has been changed + void frequencybaseChanged( double frequencybase ); ///< The frequencybase has been changed + void samplerateChanged( double samplerate ); ///< The samplerate has been changed + void timebaseChanged( double timebase ); ///< The timebase has been changed + void recordLengthChanged( unsigned long recordLength ); ///< The recordd length has been changed + void formatChanged( Dso::GraphFormat format ); ///< The viewing format has been changed + void calfreqChanged( double calfreq ); ///< The timebase has been changed }; diff --git a/openhantek/src/docks/SpectrumDock.cpp b/openhantek/src/docks/SpectrumDock.cpp index 85594d00..e84efecd 100644 --- a/openhantek/src/docks/SpectrumDock.cpp +++ b/openhantek/src/docks/SpectrumDock.cpp @@ -12,100 +12,103 @@ #include "SpectrumDock.h" #include "dockwindows.h" -#include "viewconstants.h" #include "dsosettings.h" #include "sispinbox.h" #include "utils/printutils.h" +#include "viewconstants.h" -template struct SELECT { - template - static constexpr auto OVERLOAD_OF( R (C::*pmf)(Args...) ) -> decltype(pmf) { +template struct SELECT { + template static constexpr auto OVERLOAD_OF( R ( C::*pmf )( Args... ) ) -> decltype( pmf ) { return pmf; } }; -SpectrumDock::SpectrumDock(DsoSettingsScope *scope, QWidget *parent, Qt::WindowFlags flags) - : QDockWidget(tr("Spectrum"), parent, flags), scope(scope) { +SpectrumDock::SpectrumDock( DsoSettingsScope *scope, QWidget *parent, Qt::WindowFlags flags ) + : QDockWidget( tr( "Spectrum" ), parent, flags ), scope( scope ) { // Initialize lists for comboboxes - this->magnitudeSteps = { 1e0 , 2e0 , 3e0 , 6e0 , 1e1 , 2e1 , 3e1 , 6e1 , 1e2 , 2e2 , 3e2, 6e2 }; - for (const auto& magnitude: magnitudeSteps) - this->magnitudeStrings << valueToString(magnitude, UNIT_DECIBEL, 0); + this->magnitudeSteps = {1e0, 2e0, 3e0, 6e0, 1e1, 2e1, 3e1, 6e1, 1e2, 2e2, 3e2, 6e2}; + for ( const auto &magnitude : magnitudeSteps ) + this->magnitudeStrings << valueToString( magnitude, UNIT_DECIBEL, 0 ); this->dockLayout = new QGridLayout(); - this->dockLayout->setColumnMinimumWidth(0, 64); - this->dockLayout->setColumnStretch(1, 1); + this->dockLayout->setColumnMinimumWidth( 0, 64 ); + this->dockLayout->setColumnStretch( 1, 1 ); this->dockLayout->setSpacing( DOCK_LAYOUT_SPACING ); // Initialize elements - for (ChannelID channel = 0; channel < scope->voltage.size(); ++channel) { + for ( ChannelID channel = 0; channel < scope->voltage.size(); ++channel ) { ChannelBlock b; - b.magnitudeComboBox=(new QComboBox()); - b.usedCheckBox=(new QCheckBox(scope->voltage[channel].name)); + b.magnitudeComboBox = ( new QComboBox() ); + b.usedCheckBox = ( new QCheckBox( scope->voltage[ channel ].name ) ); - channelBlocks.push_back(b); + channelBlocks.push_back( b ); - this->dockLayout->addWidget(b.usedCheckBox, int(channel), 0); - this->dockLayout->addWidget(b.magnitudeComboBox, int(channel), 1); + this->dockLayout->addWidget( b.usedCheckBox, int( channel ), 0 ); + this->dockLayout->addWidget( b.magnitudeComboBox, int( channel ), 1 ); - b.magnitudeComboBox->addItems(this->magnitudeStrings); + b.magnitudeComboBox->addItems( this->magnitudeStrings ); // Connect signals and slots - connect(b.usedCheckBox, &QCheckBox::toggled, [this,channel](bool checked) { + connect( b.usedCheckBox, &QCheckBox::toggled, [this, channel]( bool checked ) { // Send signal if it was one of the checkboxes - if (channel < this->scope->voltage.size()) { - this->scope->spectrum[channel].used = checked; - emit usedChanged(channel, checked); - } - }); - - connect(b.magnitudeComboBox, SELECT::OVERLOAD_OF(&QComboBox::currentIndexChanged), [this,channel](unsigned index) { - // Send signal if it was one of the comboboxes - if (channel < this->scope->voltage.size()) { - this->scope->spectrum[channel].magnitude = this->magnitudeSteps.at(index); - emit magnitudeChanged(channel, this->scope->spectrum[channel].magnitude); + if ( channel < this->scope->voltage.size() ) { + this->scope->spectrum[ channel ].used = checked; + emit usedChanged( channel, checked ); } - }); + } ); + + connect( b.magnitudeComboBox, SELECT::OVERLOAD_OF( &QComboBox::currentIndexChanged ), + [this, channel]( unsigned index ) { + // Send signal if it was one of the comboboxes + if ( channel < this->scope->voltage.size() ) { + this->scope->spectrum[ channel ].magnitude = this->magnitudeSteps.at( index ); + emit magnitudeChanged( channel, this->scope->spectrum[ channel ].magnitude ); + } + } ); } // Load settings into GUI - this->loadSettings(scope); + this->loadSettings( scope ); dockWidget = new QWidget(); - SetupDockWidget(this, dockWidget, dockLayout); + SetupDockWidget( this, dockWidget, dockLayout ); } -void SpectrumDock::loadSettings(DsoSettingsScope *scope) { +void SpectrumDock::loadSettings( DsoSettingsScope *scope ) { // Initialize elements - for (ChannelID channel = 0; channel < scope->voltage.size(); ++channel) { - this->setMagnitude(channel, scope->spectrum[channel].magnitude); - this->setUsed(channel, scope->spectrum[channel].used); + for ( ChannelID channel = 0; channel < scope->voltage.size(); ++channel ) { + this->setMagnitude( channel, scope->spectrum[ channel ].magnitude ); + this->setUsed( channel, scope->spectrum[ channel ].used ); } } /// \brief Don't close the dock, just hide it /// \param event The close event that should be handled. -void SpectrumDock::closeEvent(QCloseEvent *event) { +void SpectrumDock::closeEvent( QCloseEvent *event ) { this->hide(); event->accept(); } -int SpectrumDock::setMagnitude(ChannelID channel, double magnitude) { - if (channel >= scope->voltage.size()) return -1; - QSignalBlocker blocker(channelBlocks[channel].magnitudeComboBox); +int SpectrumDock::setMagnitude( ChannelID channel, double magnitude ) { + if ( channel >= scope->voltage.size() ) + return -1; + QSignalBlocker blocker( channelBlocks[ channel ].magnitudeComboBox ); - auto indexIt = std::find(magnitudeSteps.begin(),magnitudeSteps.end(),magnitude); - if (indexIt == magnitudeSteps.end()) return -1; - int index = int(std::distance(magnitudeSteps.begin(), indexIt)); - channelBlocks[channel].magnitudeComboBox->setCurrentIndex(index); + auto indexIt = std::find( magnitudeSteps.begin(), magnitudeSteps.end(), magnitude ); + if ( indexIt == magnitudeSteps.end() ) + return -1; + int index = int( std::distance( magnitudeSteps.begin(), indexIt ) ); + channelBlocks[ channel ].magnitudeComboBox->setCurrentIndex( index ); return index; } -unsigned SpectrumDock::setUsed(ChannelID channel, bool used) { - if (channel >= scope->voltage.size()) return INT_MAX; - QSignalBlocker blocker(channelBlocks[channel].usedCheckBox); +unsigned SpectrumDock::setUsed( ChannelID channel, bool used ) { + if ( channel >= scope->voltage.size() ) + return INT_MAX; + QSignalBlocker blocker( channelBlocks[ channel ].usedCheckBox ); - channelBlocks[channel].usedCheckBox->setChecked(used); + channelBlocks[ channel ].usedCheckBox->setChecked( used ); return channel; } diff --git a/openhantek/src/docks/SpectrumDock.h b/openhantek/src/docks/SpectrumDock.h index f1ff4239..7f11d331 100644 --- a/openhantek/src/docks/SpectrumDock.h +++ b/openhantek/src/docks/SpectrumDock.h @@ -24,44 +24,44 @@ class SpectrumDock : public QDockWidget { /// \param settings The target settings object. /// \param parent The parent widget. /// \param flags Flags for the window manager. - SpectrumDock(DsoSettingsScope *scope, QWidget *parent, Qt::WindowFlags flags = nullptr); + SpectrumDock( DsoSettingsScope *scope, QWidget *parent, Qt::WindowFlags flags = nullptr ); /// \brief Sets the magnitude for a channel. /// \param channel The channel, whose magnitude should be set. /// \param magnitude The magnitude in dB. /// \return Index of magnitude-value, -1 on error. - int setMagnitude(ChannelID channel, double magnitude); + int setMagnitude( ChannelID channel, double magnitude ); /// \brief Enables/disables a channel. /// \param channel The channel, that should be enabled/disabled. /// \param used True if the channel should be enabled, false otherwise. /// \return Index of channel, INT_MAX on error. - unsigned setUsed(ChannelID channel, bool used); + unsigned setUsed( ChannelID channel, bool used ); public slots: /// \brief Loads settings into GUI /// \param scope Settings to load - void loadSettings(DsoSettingsScope *scope); + void loadSettings( DsoSettingsScope *scope ); protected: - void closeEvent(QCloseEvent *event); + void closeEvent( QCloseEvent *event ); - QGridLayout *dockLayout; ///< The main layout for the dock window - QWidget *dockWidget; ///< The main widget for the dock window + QGridLayout *dockLayout; ///< The main layout for the dock window + QWidget *dockWidget; ///< The main widget for the dock window struct ChannelBlock { - QCheckBox * usedCheckBox; ///< Enable/disable a specific channel - QComboBox * magnitudeComboBox; ///< Select the vertical magnitude for the spectrums + QCheckBox *usedCheckBox; ///< Enable/disable a specific channel + QComboBox *magnitudeComboBox; ///< Select the vertical magnitude for the spectrums }; std::vector channelBlocks; - DsoSettingsScope* scope; ///< The settings provided by the parent class + DsoSettingsScope *scope; ///< The settings provided by the parent class std::vector magnitudeSteps; ///< The selectable magnitude steps in dB/div - QStringList magnitudeStrings; ///< String representations for the magnitude steps + QStringList magnitudeStrings; ///< String representations for the magnitude steps signals: - void magnitudeChanged(ChannelID channel, double magnitude); ///< A magnitude has been selected - void usedChanged(ChannelID channel, bool used); ///< A spectrum has been enabled/disabled + void magnitudeChanged( ChannelID channel, double magnitude ); ///< A magnitude has been selected + void usedChanged( ChannelID channel, bool used ); ///< A spectrum has been enabled/disabled }; diff --git a/openhantek/src/docks/TriggerDock.cpp b/openhantek/src/docks/TriggerDock.cpp index ea50bf17..636429f8 100644 --- a/openhantek/src/docks/TriggerDock.cpp +++ b/openhantek/src/docks/TriggerDock.cpp @@ -12,101 +12,104 @@ #include "TriggerDock.h" #include "dockwindows.h" -#include "viewconstants.h" -#include "hantekdso/controlspecification.h" #include "dsosettings.h" +#include "hantekdso/controlspecification.h" #include "sispinbox.h" #include "utils/printutils.h" +#include "viewconstants.h" -TriggerDock::TriggerDock(DsoSettingsScope *scope, const Dso::ControlSpecification *spec, QWidget *parent, - Qt::WindowFlags flags) - : QDockWidget(tr("Trigger"), parent, flags), scope(scope), mSpec(spec) { +TriggerDock::TriggerDock( DsoSettingsScope *scope, const Dso::ControlSpecification *spec, QWidget *parent, + Qt::WindowFlags flags ) + : QDockWidget( tr( "Trigger" ), parent, flags ), scope( scope ), mSpec( spec ) { // Initialize lists for comboboxes - for (ChannelID channel = 0; channel < mSpec->channels; ++channel) - this->sourceStandardStrings << tr("CH%1").arg(channel + 1); + for ( ChannelID channel = 0; channel < mSpec->channels; ++channel ) + this->sourceStandardStrings << tr( "CH%1" ).arg( channel + 1 ); // add "smooth" source - for (ChannelID channel = 0; channel < mSpec->channels; ++channel) - this->sourceStandardStrings << tr("CH%1 smooth").arg(channel + 1); + for ( ChannelID channel = 0; channel < mSpec->channels; ++channel ) + this->sourceStandardStrings << tr( "CH%1 smooth" ).arg( channel + 1 ); // Initialize elements - this->modeLabel = new QLabel(tr("Mode")); + this->modeLabel = new QLabel( tr( "Mode" ) ); this->modeComboBox = new QComboBox(); - for (Dso::TriggerMode mode : mSpec->triggerModes) this->modeComboBox->addItem(Dso::triggerModeString(mode)); + for ( Dso::TriggerMode mode : mSpec->triggerModes ) + this->modeComboBox->addItem( Dso::triggerModeString( mode ) ); - this->slopeLabel = new QLabel(tr("Slope")); + this->slopeLabel = new QLabel( tr( "Slope" ) ); this->slopeComboBox = new QComboBox(); - for (Dso::Slope slope : Dso::SlopeEnum) this->slopeComboBox->addItem(Dso::slopeString(slope)); + for ( Dso::Slope slope : Dso::SlopeEnum ) + this->slopeComboBox->addItem( Dso::slopeString( slope ) ); - this->sourceLabel = new QLabel(tr("Source")); + this->sourceLabel = new QLabel( tr( "Source" ) ); this->sourceComboBox = new QComboBox(); - this->sourceComboBox->addItems(this->sourceStandardStrings); + this->sourceComboBox->addItems( this->sourceStandardStrings ); this->dockLayout = new QGridLayout(); - this->dockLayout->setColumnMinimumWidth(0, 64); - this->dockLayout->setColumnStretch(1, 1); + this->dockLayout->setColumnMinimumWidth( 0, 64 ); + this->dockLayout->setColumnStretch( 1, 1 ); this->dockLayout->setSpacing( DOCK_LAYOUT_SPACING ); - this->dockLayout->addWidget(this->modeLabel, 0, 0); - this->dockLayout->addWidget(this->modeComboBox, 0, 1); - this->dockLayout->addWidget(this->sourceLabel, 1, 0); - this->dockLayout->addWidget(this->sourceComboBox, 1, 1); - this->dockLayout->addWidget(this->slopeLabel, 2, 0); - this->dockLayout->addWidget(this->slopeComboBox, 2, 1); + this->dockLayout->addWidget( this->modeLabel, 0, 0 ); + this->dockLayout->addWidget( this->modeComboBox, 0, 1 ); + this->dockLayout->addWidget( this->sourceLabel, 1, 0 ); + this->dockLayout->addWidget( this->sourceComboBox, 1, 1 ); + this->dockLayout->addWidget( this->slopeLabel, 2, 0 ); + this->dockLayout->addWidget( this->slopeComboBox, 2, 1 ); this->dockWidget = new QWidget(); - SetupDockWidget(this, dockWidget, dockLayout); + SetupDockWidget( this, dockWidget, dockLayout ); // Load settings into GUI - this->loadSettings(scope); - + this->loadSettings( scope ); + // Connect signals and slots - connect(this->modeComboBox, static_cast(&QComboBox::currentIndexChanged), - [this](int index) { - this->scope->trigger.mode = mSpec->triggerModes[unsigned(index)]; - emit modeChanged(this->scope->trigger.mode); - }); - connect(this->slopeComboBox, static_cast(&QComboBox::currentIndexChanged), - [this](int index) { - this->scope->trigger.slope = Dso::Slope(index); - emit slopeChanged(this->scope->trigger.slope); - }); - connect(this->sourceComboBox, static_cast(&QComboBox::currentIndexChanged), - [this](unsigned index) { - bool smooth = index >= mSpec->channels; - this->scope->trigger.source = index & (mSpec->channels - 1) ; - emit sourceChanged(index & (mSpec->channels - 1), smooth ); - }); + connect( this->modeComboBox, static_cast( &QComboBox::currentIndexChanged ), + [this]( int index ) { + this->scope->trigger.mode = mSpec->triggerModes[ unsigned( index ) ]; + emit modeChanged( this->scope->trigger.mode ); + } ); + connect( this->slopeComboBox, static_cast( &QComboBox::currentIndexChanged ), + [this]( int index ) { + this->scope->trigger.slope = Dso::Slope( index ); + emit slopeChanged( this->scope->trigger.slope ); + } ); + connect( this->sourceComboBox, static_cast( &QComboBox::currentIndexChanged ), + [this]( unsigned index ) { + bool smooth = index >= mSpec->channels; + this->scope->trigger.source = index & ( mSpec->channels - 1 ); + emit sourceChanged( index & ( mSpec->channels - 1 ), smooth ); + } ); } -void TriggerDock::loadSettings(DsoSettingsScope *scope) { +void TriggerDock::loadSettings( DsoSettingsScope *scope ) { // Set values - setMode(scope->trigger.mode); - setSlope(scope->trigger.slope); - setSource(int(scope->trigger.source)); + setMode( scope->trigger.mode ); + setSlope( scope->trigger.slope ); + setSource( int( scope->trigger.source ) ); } /// \brief Don't close the dock, just hide it /// \param event The close event that should be handled. -void TriggerDock::closeEvent(QCloseEvent *event) { +void TriggerDock::closeEvent( QCloseEvent *event ) { this->hide(); event->accept(); } -void TriggerDock::setMode(Dso::TriggerMode mode) { - int index = int(std::find(mSpec->triggerModes.begin(), mSpec->triggerModes.end(), mode) - mSpec->triggerModes.begin()); - QSignalBlocker blocker(modeComboBox); - modeComboBox->setCurrentIndex(index); +void TriggerDock::setMode( Dso::TriggerMode mode ) { + int index = + int( std::find( mSpec->triggerModes.begin(), mSpec->triggerModes.end(), mode ) - mSpec->triggerModes.begin() ); + QSignalBlocker blocker( modeComboBox ); + modeComboBox->setCurrentIndex( index ); } -void TriggerDock::setSlope(Dso::Slope slope) { - QSignalBlocker blocker(slopeComboBox); - slopeComboBox->setCurrentIndex(int(slope)); +void TriggerDock::setSlope( Dso::Slope slope ) { + QSignalBlocker blocker( slopeComboBox ); + slopeComboBox->setCurrentIndex( int( slope ) ); } -void TriggerDock::setSource(int id) { +void TriggerDock::setSource( int id ) { if ( id >= this->sourceStandardStrings.count() ) return; - QSignalBlocker blocker(sourceComboBox); - sourceComboBox->setCurrentIndex(id); + QSignalBlocker blocker( sourceComboBox ); + sourceComboBox->setCurrentIndex( id ); } diff --git a/openhantek/src/docks/TriggerDock.h b/openhantek/src/docks/TriggerDock.h index 91135d72..87d4ea7b 100644 --- a/openhantek/src/docks/TriggerDock.h +++ b/openhantek/src/docks/TriggerDock.h @@ -2,11 +2,11 @@ #pragma once +#include +#include #include #include #include -#include -#include #include "hantekdso/enums.h" @@ -27,27 +27,28 @@ class TriggerDock : public QDockWidget { /// \param spec /// \param parent The parent widget. /// \param flags Flags for the window manager. - TriggerDock(DsoSettingsScope *scope, const Dso::ControlSpecification* mSpec, QWidget *parent, Qt::WindowFlags flags = nullptr); + TriggerDock( DsoSettingsScope *scope, const Dso::ControlSpecification *mSpec, QWidget *parent, + Qt::WindowFlags flags = nullptr ); /// \brief Changes the trigger mode if the new mode is supported. /// \param mode The trigger mode. - void setMode(Dso::TriggerMode mode); + void setMode( Dso::TriggerMode mode ); /// \brief Changes the trigger source if the new source is supported. /// \param id The number of the channel, that should be used as trigger. - void setSource(int id); + void setSource( int id ); /// \brief Changes the trigger slope if the new slope is supported. /// \param slope The trigger slope. - void setSlope(Dso::Slope slope); + void setSlope( Dso::Slope slope ); public slots: /// \brief Loads settings into GUI /// \param scope Settings to load - void loadSettings(DsoSettingsScope *scope); + void loadSettings( DsoSettingsScope *scope ); protected: - void closeEvent(QCloseEvent *event); + void closeEvent( QCloseEvent *event ); QGridLayout *dockLayout; ///< The main layout for the dock window QWidget *dockWidget; ///< The main widget for the dock window @@ -59,12 +60,12 @@ class TriggerDock : public QDockWidget { QComboBox *slopeComboBox; ///< Select the slope that causes triggering DsoSettingsScope *scope; ///< The settings provided by the parent class - const Dso::ControlSpecification* mSpec; + const Dso::ControlSpecification *mSpec; QStringList sourceStandardStrings; ///< Strings for the standard trigger sources -signals: - void modeChanged(Dso::TriggerMode); ///< The trigger mode has been changed - void sourceChanged(unsigned int id, bool smooth); ///< The trigger source has been changed - void slopeChanged(Dso::Slope); ///< The trigger slope has been changed + signals: + void modeChanged( Dso::TriggerMode ); ///< The trigger mode has been changed + void sourceChanged( unsigned int id, bool smooth ); ///< The trigger source has been changed + void slopeChanged( Dso::Slope ); ///< The trigger slope has been changed }; diff --git a/openhantek/src/docks/VoltageDock.cpp b/openhantek/src/docks/VoltageDock.cpp index 779cb23c..2e44885e 100644 --- a/openhantek/src/docks/VoltageDock.cpp +++ b/openhantek/src/docks/VoltageDock.cpp @@ -1,193 +1,203 @@ // SPDX-License-Identifier: GPL-2.0+ #include +#include #include #include -#include #include #include "VoltageDock.h" #include "dockwindows.h" -#include "viewconstants.h" #include "dsosettings.h" #include "sispinbox.h" #include "utils/printutils.h" +#include "viewconstants.h" -template struct SELECT { - template - static constexpr auto OVERLOAD_OF( R (C::*pmf)(Args...) ) -> decltype(pmf) { +template struct SELECT { + template static constexpr auto OVERLOAD_OF( R ( C::*pmf )( Args... ) ) -> decltype( pmf ) { return pmf; } }; -VoltageDock::VoltageDock(DsoSettingsScope *scope, const Dso::ControlSpecification *spec, QWidget *parent, Qt::WindowFlags flags) - : QDockWidget(tr("Voltage"), parent, flags), scope(scope), spec(spec) { +VoltageDock::VoltageDock( DsoSettingsScope *scope, const Dso::ControlSpecification *spec, QWidget *parent, + Qt::WindowFlags flags ) + : QDockWidget( tr( "Voltage" ), parent, flags ), scope( scope ), spec( spec ) { // Initialize lists for comboboxes - for (Dso::Coupling c: spec->couplings) - couplingStrings.append(Dso::couplingString(c)); + for ( Dso::Coupling c : spec->couplings ) + couplingStrings.append( Dso::couplingString( c ) ); - for( auto e: Dso::MathModeEnum ) { - modeStrings.append(Dso::mathModeString(e)); + for ( auto e : Dso::MathModeEnum ) { + modeStrings.append( Dso::mathModeString( e ) ); } - for (double gainStep: scope->gainSteps) { - gainStrings << valueToString(gainStep, UNIT_VOLTS, 0); + for ( double gainStep : scope->gainSteps ) { + gainStrings << valueToString( gainStep, UNIT_VOLTS, 0 ); } dockLayout = new QGridLayout(); - dockLayout->setColumnMinimumWidth(0, 64); - dockLayout->setColumnStretch(1, 1); // stretch ComboBox in 2nd (middle) column - dockLayout->setColumnStretch(2, 1); // stretch ComboBox in 3rd (last) column + dockLayout->setColumnMinimumWidth( 0, 64 ); + dockLayout->setColumnStretch( 1, 1 ); // stretch ComboBox in 2nd (middle) column + dockLayout->setColumnStretch( 2, 1 ); // stretch ComboBox in 3rd (last) column dockLayout->setSpacing( DOCK_LAYOUT_SPACING ); // Initialize elements int row = 0; - for (ChannelID channel = 0; channel < scope->voltage.size(); ++channel) { + for ( ChannelID channel = 0; channel < scope->voltage.size(); ++channel ) { ChannelBlock b; - if (channel < spec->channels) - b.usedCheckBox = new QCheckBox( tr("CH&%1").arg( channel+1 ) ); // define shortcut 1 / 2 + if ( channel < spec->channels ) + b.usedCheckBox = new QCheckBox( tr( "CH&%1" ).arg( channel + 1 ) ); // define shortcut 1 / 2 else - b.usedCheckBox = new QCheckBox( tr("&MATH")); + b.usedCheckBox = new QCheckBox( tr( "&MATH" ) ); b.miscComboBox = new QComboBox(); b.gainComboBox = new QComboBox(); - b.invertCheckBox = new QCheckBox(tr("Invert")); + b.invertCheckBox = new QCheckBox( tr( "Invert" ) ); b.attnSpinBox = new QSpinBox(); - b.attnSpinBox->setMinimum(ATTENUATION_MIN); - b.attnSpinBox->setMaximum(ATTENUATION_MAX); - b.attnSpinBox->setPrefix(tr("x")); + b.attnSpinBox->setMinimum( ATTENUATION_MIN ); + b.attnSpinBox->setMaximum( ATTENUATION_MAX ); + b.attnSpinBox->setPrefix( tr( "x" ) ); - channelBlocks.push_back(std::move(b)); + channelBlocks.push_back( std::move( b ) ); - if (channel < spec->channels) - b.miscComboBox->addItems(couplingStrings); + if ( channel < spec->channels ) + b.miscComboBox->addItems( couplingStrings ); else - b.miscComboBox->addItems(modeStrings); + b.miscComboBox->addItems( modeStrings ); - b.gainComboBox->addItems(gainStrings); + b.gainComboBox->addItems( gainStrings ); dockLayout->addWidget( b.usedCheckBox, row, 0 ); - dockLayout->addWidget( b.gainComboBox, row++, 1, 1, 2); + dockLayout->addWidget( b.gainComboBox, row++, 1, 1, 2 ); dockLayout->addWidget( b.invertCheckBox, row, 0 ); - if (channel < spec->channels) { - dockLayout->addWidget( b.attnSpinBox, row, 1, 1, 1 ) ; - dockLayout->addWidget( b.miscComboBox, row++, 2, 1, 1) ; + if ( channel < spec->channels ) { + dockLayout->addWidget( b.attnSpinBox, row, 1, 1, 1 ); + dockLayout->addWidget( b.miscComboBox, row++, 2, 1, 1 ); } else { dockLayout->addWidget( b.miscComboBox, row++, 1, 1, 2 ); } // draw divider line - if (channel < spec->channels) { + if ( channel < spec->channels ) { QFrame *divider = new QFrame(); - divider->setLineWidth(1); - divider->setFrameShape(QFrame::HLine); - dockLayout->addWidget(divider, row++, 0, 1, 3); + divider->setLineWidth( 1 ); + divider->setFrameShape( QFrame::HLine ); + dockLayout->addWidget( divider, row++, 0, 1, 3 ); } - connect(b.gainComboBox, SELECT::OVERLOAD_OF(&QComboBox::currentIndexChanged), [this,channel](unsigned index) { - this->scope->voltage[channel].gainStepIndex = index; - emit gainChanged( channel, this->scope->gain(channel) ); - }); - connect(b.attnSpinBox, SELECT::OVERLOAD_OF(&QSpinBox::valueChanged), [this,channel](unsigned attnValue) { - this->scope->voltage[channel].probeAttn = attnValue; - setAttn( channel, attnValue ); - emit probeAttnChanged( channel, attnValue ); // make sure to set the probe first, since this will influence the gain - emit gainChanged(channel, this->scope->gain(channel)); - }); - connect(b.invertCheckBox, &QAbstractButton::toggled, [this,channel](bool checked) { - this->scope->voltage[channel].inverted = checked; + connect( b.gainComboBox, SELECT::OVERLOAD_OF( &QComboBox::currentIndexChanged ), + [this, channel]( unsigned index ) { + this->scope->voltage[ channel ].gainStepIndex = index; + emit gainChanged( channel, this->scope->gain( channel ) ); + } ); + connect( b.attnSpinBox, SELECT::OVERLOAD_OF( &QSpinBox::valueChanged ), + [this, channel]( unsigned attnValue ) { + this->scope->voltage[ channel ].probeAttn = attnValue; + setAttn( channel, attnValue ); + emit probeAttnChanged( + channel, attnValue ); // make sure to set the probe first, since this will influence the gain + emit gainChanged( channel, this->scope->gain( channel ) ); + } ); + connect( b.invertCheckBox, &QAbstractButton::toggled, [this, channel]( bool checked ) { + this->scope->voltage[ channel ].inverted = checked; emit invertedChanged( channel, checked ); - }); - connect(b.miscComboBox, SELECT::OVERLOAD_OF(&QComboBox::currentIndexChanged), [this,channel,spec,scope](unsigned index) { - this->scope->voltage[channel].couplingOrMathIndex = index; - if (channel < spec->channels) { - //setCoupling(channel, (unsigned)index); - emit couplingChanged(channel, scope->coupling(channel, spec)); - } else { - emit modeChanged(Dso::getMathMode(this->scope->voltage[channel])); - } - }); - connect(b.usedCheckBox, &QAbstractButton::toggled, [this,channel](bool checked) { - this->scope->voltage[channel].used = checked; - emit usedChanged(channel, checked); - }); + } ); + connect( b.miscComboBox, SELECT::OVERLOAD_OF( &QComboBox::currentIndexChanged ), + [this, channel, spec, scope]( unsigned index ) { + this->scope->voltage[ channel ].couplingOrMathIndex = index; + if ( channel < spec->channels ) { + // setCoupling(channel, (unsigned)index); + emit couplingChanged( channel, scope->coupling( channel, spec ) ); + } else { + emit modeChanged( Dso::getMathMode( this->scope->voltage[ channel ] ) ); + } + } ); + connect( b.usedCheckBox, &QAbstractButton::toggled, [this, channel]( bool checked ) { + this->scope->voltage[ channel ].used = checked; + emit usedChanged( channel, checked ); + } ); } // Load settings into GUI - this->loadSettings(scope, spec); - + this->loadSettings( scope, spec ); + dockWidget = new QWidget(); - SetupDockWidget(this, dockWidget, dockLayout); + SetupDockWidget( this, dockWidget, dockLayout ); } -void VoltageDock::loadSettings(DsoSettingsScope *scope, const Dso::ControlSpecification *spec) { - for (ChannelID channel = 0; channel < scope->voltage.size(); ++channel) { - if (channel < spec->channels) { - if ( int(scope->voltage[channel].couplingOrMathIndex) < couplingStrings.size() ) - setCoupling(channel, scope->voltage[channel].couplingOrMathIndex); - } - else { - setMode(scope->voltage[channel].couplingOrMathIndex); +void VoltageDock::loadSettings( DsoSettingsScope *scope, const Dso::ControlSpecification *spec ) { + for ( ChannelID channel = 0; channel < scope->voltage.size(); ++channel ) { + if ( channel < spec->channels ) { + if ( int( scope->voltage[ channel ].couplingOrMathIndex ) < couplingStrings.size() ) + setCoupling( channel, scope->voltage[ channel ].couplingOrMathIndex ); + } else { + setMode( scope->voltage[ channel ].couplingOrMathIndex ); } - setGain(channel, scope->voltage[channel].gainStepIndex); - setUsed(channel, scope->voltage[channel].used); - setAttn(channel, scope->voltage[channel].probeAttn); - setInverted(channel, scope->voltage[channel].inverted); + setGain( channel, scope->voltage[ channel ].gainStepIndex ); + setUsed( channel, scope->voltage[ channel ].used ); + setAttn( channel, scope->voltage[ channel ].probeAttn ); + setInverted( channel, scope->voltage[ channel ].inverted ); } } /// \brief Don't close the dock, just hide it /// \param event The close event that should be handled. -void VoltageDock::closeEvent(QCloseEvent *event) { +void VoltageDock::closeEvent( QCloseEvent *event ) { hide(); event->accept(); } -void VoltageDock::setCoupling(ChannelID channel, unsigned couplingIndex) { - if (channel >= spec->channels) return; - if (couplingIndex >= spec->couplings.size()) return; - QSignalBlocker blocker(channelBlocks[channel].miscComboBox); - channelBlocks[channel].miscComboBox->setCurrentIndex(int(couplingIndex)); +void VoltageDock::setCoupling( ChannelID channel, unsigned couplingIndex ) { + if ( channel >= spec->channels ) + return; + if ( couplingIndex >= spec->couplings.size() ) + return; + QSignalBlocker blocker( channelBlocks[ channel ].miscComboBox ); + channelBlocks[ channel ].miscComboBox->setCurrentIndex( int( couplingIndex ) ); } -void VoltageDock::setGain(ChannelID channel, unsigned gainStepIndex) { - if (channel >= scope->voltage.size()) return; - if (gainStepIndex >= scope->gainSteps.size()) return; - QSignalBlocker blocker(channelBlocks[channel].gainComboBox); - channelBlocks[channel].gainComboBox->setCurrentIndex(int(gainStepIndex)); +void VoltageDock::setGain( ChannelID channel, unsigned gainStepIndex ) { + if ( channel >= scope->voltage.size() ) + return; + if ( gainStepIndex >= scope->gainSteps.size() ) + return; + QSignalBlocker blocker( channelBlocks[ channel ].gainComboBox ); + channelBlocks[ channel ].gainComboBox->setCurrentIndex( int( gainStepIndex ) ); } -void VoltageDock::setAttn(ChannelID channel, double attnValue) { - if (channel >= scope->voltage.size()) return; - QSignalBlocker blocker(channelBlocks[channel].gainComboBox); - int index = channelBlocks[channel].gainComboBox->currentIndex(); +void VoltageDock::setAttn( ChannelID channel, double attnValue ) { + if ( channel >= scope->voltage.size() ) + return; + QSignalBlocker blocker( channelBlocks[ channel ].gainComboBox ); + int index = channelBlocks[ channel ].gainComboBox->currentIndex(); gainStrings.clear(); - for (double gainStep: scope->gainSteps) { - gainStrings << valueToString(gainStep * attnValue, UNIT_VOLTS, -1); // auto format + for ( double gainStep : scope->gainSteps ) { + gainStrings << valueToString( gainStep * attnValue, UNIT_VOLTS, -1 ); // auto format } - channelBlocks[channel].gainComboBox->clear(); - channelBlocks[channel].gainComboBox->addItems( gainStrings ); - channelBlocks[channel].gainComboBox->setCurrentIndex( index ); - scope->voltage[channel].probeAttn = attnValue; - channelBlocks[channel].attnSpinBox->setValue(int(attnValue)); + channelBlocks[ channel ].gainComboBox->clear(); + channelBlocks[ channel ].gainComboBox->addItems( gainStrings ); + channelBlocks[ channel ].gainComboBox->setCurrentIndex( index ); + scope->voltage[ channel ].probeAttn = attnValue; + channelBlocks[ channel ].attnSpinBox->setValue( int( attnValue ) ); } -void VoltageDock::setMode(unsigned mathModeIndex) { - QSignalBlocker blocker(channelBlocks[spec->channels].miscComboBox); - channelBlocks[spec->channels].miscComboBox->setCurrentIndex(int(mathModeIndex)); +void VoltageDock::setMode( unsigned mathModeIndex ) { + QSignalBlocker blocker( channelBlocks[ spec->channels ].miscComboBox ); + channelBlocks[ spec->channels ].miscComboBox->setCurrentIndex( int( mathModeIndex ) ); } -void VoltageDock::setUsed(ChannelID channel, bool used) { - if (channel >= scope->voltage.size()) return; - QSignalBlocker blocker(channelBlocks[channel].usedCheckBox); - channelBlocks[channel].usedCheckBox->setChecked(used); +void VoltageDock::setUsed( ChannelID channel, bool used ) { + if ( channel >= scope->voltage.size() ) + return; + QSignalBlocker blocker( channelBlocks[ channel ].usedCheckBox ); + channelBlocks[ channel ].usedCheckBox->setChecked( used ); } -void VoltageDock::setInverted(ChannelID channel, bool inverted) { - if (channel >= scope->voltage.size()) return; - QSignalBlocker blocker(channelBlocks[channel].invertCheckBox); - channelBlocks[channel].invertCheckBox->setChecked(inverted); +void VoltageDock::setInverted( ChannelID channel, bool inverted ) { + if ( channel >= scope->voltage.size() ) + return; + QSignalBlocker blocker( channelBlocks[ channel ].invertCheckBox ); + channelBlocks[ channel ].invertCheckBox->setChecked( inverted ); } diff --git a/openhantek/src/docks/VoltageDock.h b/openhantek/src/docks/VoltageDock.h index 04e6d0ab..db0b77b6 100644 --- a/openhantek/src/docks/VoltageDock.h +++ b/openhantek/src/docks/VoltageDock.h @@ -2,19 +2,19 @@ #pragma once -#include -#include #include #include +#include +#include #include #include -#include "scopesettings.h" #include "hantekdso/controlspecification.h" #include "post/postprocessingsettings.h" +#include "scopesettings.h" -#define ATTENUATION_MIN 1 ///< Minimum probe attenuation -#define ATTENUATION_MAX 1000 ///< Maximum probe attenuation +#define ATTENUATION_MIN 1 ///< Minimum probe attenuation +#define ATTENUATION_MAX 1000 ///< Maximum probe attenuation class SiSpinBox; @@ -29,55 +29,56 @@ class VoltageDock : public QDockWidget { /// \param settings The target settings object. /// \param parent The parent widget. /// \param flags Flags for the window manager. - VoltageDock(DsoSettingsScope *scope, const Dso::ControlSpecification* spec, QWidget *parent, Qt::WindowFlags flags = nullptr); + VoltageDock( DsoSettingsScope *scope, const Dso::ControlSpecification *spec, QWidget *parent, + Qt::WindowFlags flags = nullptr ); /// \brief Sets the coupling for a channel. /// \param channel The channel, whose coupling should be set. /// \param couplingIndex The coupling-mode index. - void setCoupling(ChannelID channel, unsigned couplingIndex); + void setCoupling( ChannelID channel, unsigned couplingIndex ); /// \brief Sets the gain for a channel. /// \param channel The channel, whose gain should be set. /// \param gain The gain in volts. - void setGain(ChannelID channel, unsigned gainStepIndex); + void setGain( ChannelID channel, unsigned gainStepIndex ); /// \brief Sets the probe attenuation for a channel. /// \param channel The channel, whose attn should be set. /// \param attn The attn value. - void setAttn(ChannelID channel, double attnValue); + void setAttn( ChannelID channel, double attnValue ); /// \brief Sets the mode for the math channel. /// \param mathModeIndex The math-mode index. - void setMode(unsigned mathModeIndex); + void setMode( unsigned mathModeIndex ); /// \brief Enables/disables a channel. /// \param channel The channel, that should be enabled/disabled. /// \param used True if the channel should be enabled, false otherwise. - void setUsed(ChannelID channel, bool used); + void setUsed( ChannelID channel, bool used ); /// \brief Set channel inverted. /// \param channel The channel, that should be inverted. /// \param used True if the channel should be inverted, false otherwise. - void setInverted(ChannelID channel, bool inverted); + void setInverted( ChannelID channel, bool inverted ); public slots: /// \brief Loads settings into GUI /// \param scope Settings to load /// \param spec Current scope specifications - void loadSettings(DsoSettingsScope *scope, const Dso::ControlSpecification *spec); + void loadSettings( DsoSettingsScope *scope, const Dso::ControlSpecification *spec ); protected: - void closeEvent(QCloseEvent *event); + void closeEvent( QCloseEvent *event ); - QGridLayout *dockLayout; ///< The main layout for the dock window - QWidget *dockWidget; ///< The main widget for the dock window + QGridLayout *dockLayout; ///< The main layout for the dock window + QWidget *dockWidget; ///< The main widget for the dock window struct ChannelBlock { - QCheckBox *usedCheckBox; ///< Enable/disable a specific channel - QComboBox *gainComboBox; ///< Select the vertical gain for the channels - QComboBox *miscComboBox; ///< Select coupling for real and mode for math channels - QCheckBox *invertCheckBox; ///< Select if the channels should be displayed inverted - QSpinBox *attnSpinBox; ///< Enter the attenuation probe value + QCheckBox *usedCheckBox; ///< Enable/disable a specific channel + QComboBox *gainComboBox; ///< Select the vertical gain for the channels + QComboBox *miscComboBox; ///< Select coupling for real and mode for math channels + QCheckBox *invertCheckBox; ///< Select if the channels should be displayed inverted + QSpinBox *attnSpinBox; ///< Enter the attenuation probe value }; std::vector channelBlocks; @@ -91,10 +92,10 @@ class VoltageDock : public QDockWidget { QStringList attnStrings; ///< String representations for the probe attn steps signals: - void couplingChanged(ChannelID channel, Dso::Coupling coupling); ///< A coupling has been selected - void gainChanged(ChannelID channel, double gain); ///< A gain has been selected - void modeChanged(Dso::MathMode mode); ///< The mode for the math channels has been changed - void usedChanged(ChannelID channel, bool used); ///< A channel has been enabled/disabled - void probeAttnChanged(ChannelID channel, double probeAttn); ///< A channel probe attenuation has been changed - void invertedChanged(ChannelID channel, bool inverted); ///< A channel "inverted" has been toggled + void couplingChanged( ChannelID channel, Dso::Coupling coupling ); ///< A coupling has been selected + void gainChanged( ChannelID channel, double gain ); ///< A gain has been selected + void modeChanged( Dso::MathMode mode ); ///< The mode for the math channels has been changed + void usedChanged( ChannelID channel, bool used ); ///< A channel has been enabled/disabled + void probeAttnChanged( ChannelID channel, double probeAttn ); ///< A channel probe attenuation has been changed + void invertedChanged( ChannelID channel, bool inverted ); ///< A channel "inverted" has been toggled }; diff --git a/openhantek/src/docks/dockwindows.cpp b/openhantek/src/docks/dockwindows.cpp index 37fff337..2f4e3ff1 100644 --- a/openhantek/src/docks/dockwindows.cpp +++ b/openhantek/src/docks/dockwindows.cpp @@ -8,17 +8,17 @@ #include -#include "post/postprocessingsettings.h" +#include "dockwindows.h" #include "hantekdso/enums.h" #include "hantekprotocol/types.h" -#include "dockwindows.h" +#include "post/postprocessingsettings.h" -void SetupDockWidget(QDockWidget *dockWindow, QWidget *dockWidget, QLayout *layout) { - dockWindow->setObjectName(dockWindow->windowTitle()); - dockWindow->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); - dockWidget->setLayout(layout); - dockWidget->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed, QSizePolicy::DefaultType)); - dockWindow->setWidget(dockWidget); +void SetupDockWidget( QDockWidget *dockWindow, QWidget *dockWidget, QLayout *layout ) { + dockWindow->setObjectName( dockWindow->windowTitle() ); + dockWindow->setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea ); + dockWidget->setLayout( layout ); + dockWidget->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Fixed, QSizePolicy::DefaultType ) ); + dockWindow->setWidget( dockWidget ); } void registerDockMetaTypes() { @@ -30,7 +30,7 @@ void registerDockMetaTypes() { qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); - qRegisterMetaType >(); - qRegisterMetaType >(); - qRegisterMetaType("ChannelID"); + qRegisterMetaType>(); + qRegisterMetaType>(); + qRegisterMetaType( "ChannelID" ); } diff --git a/openhantek/src/docks/dockwindows.h b/openhantek/src/docks/dockwindows.h index 3a479b44..15e81a43 100644 --- a/openhantek/src/docks/dockwindows.h +++ b/openhantek/src/docks/dockwindows.h @@ -6,4 +6,4 @@ #include void registerDockMetaTypes(); -void SetupDockWidget(QDockWidget *dockWindow, QWidget *dockWidget, QLayout *layout); +void SetupDockWidget( QDockWidget *dockWindow, QWidget *dockWidget, QLayout *layout ); diff --git a/openhantek/src/dsosettings.cpp b/openhantek/src/dsosettings.cpp index f3f3c186..2e111b68 100644 --- a/openhantek/src/dsosettings.cpp +++ b/openhantek/src/dsosettings.cpp @@ -11,318 +11,359 @@ /// \brief Set the number of channels. /// \param channels The new channel count, that will be applied to lists. -DsoSettings::DsoSettings(const Dso::ControlSpecification* deviceSpecification) : deviceSpecification(deviceSpecification) { +DsoSettings::DsoSettings( const Dso::ControlSpecification *deviceSpecification ) + : deviceSpecification( deviceSpecification ) { // Add new channels to the list - unsigned char trace_hue[] = { 60, 240, 0, 120 }; // yellow, blue, red, green + unsigned char trace_hue[] = {60, 240, 0, 120}; // yellow, blue, red, green unsigned index = 0; - while (scope.spectrum.size() < deviceSpecification->channels) { + while ( scope.spectrum.size() < deviceSpecification->channels ) { // Spectrum DsoSettingsScopeSpectrum newSpectrum; - newSpectrum.name = QApplication::tr("SP%1").arg(index+1); - scope.spectrum.push_back(newSpectrum); + newSpectrum.name = QApplication::tr( "SP%1" ).arg( index + 1 ); + scope.spectrum.push_back( newSpectrum ); // Voltage DsoSettingsScopeVoltage newVoltage; - newVoltage.name = QApplication::tr("CH%1").arg(index+1); - scope.voltage.push_back(newVoltage); + newVoltage.name = QApplication::tr( "CH%1" ).arg( index + 1 ); + scope.voltage.push_back( newVoltage ); view.screen.voltage.push_back( QColor::fromHsv( trace_hue[ index ], 0xff, 0xff ) ); - view.screen.spectrum.push_back(view.screen.voltage.back().lighter()); - view.print.voltage.push_back(view.screen.voltage.back().darker(120)); - view.print.spectrum.push_back(view.screen.voltage.back().darker()); + view.screen.spectrum.push_back( view.screen.voltage.back().lighter() ); + view.print.voltage.push_back( view.screen.voltage.back().darker( 120 ) ); + view.print.spectrum.push_back( view.screen.voltage.back().darker() ); if ( ++index >= sizeof trace_hue ) index = 0; } DsoSettingsScopeSpectrum newSpectrum; - newSpectrum.name = QApplication::tr("SPM"); - scope.spectrum.push_back(newSpectrum); + newSpectrum.name = QApplication::tr( "SPM" ); + scope.spectrum.push_back( newSpectrum ); DsoSettingsScopeVoltage newVoltage; newVoltage.couplingOrMathIndex = unsigned( Dso::MathMode::ADD_CH1_CH2 ); - newVoltage.name = QApplication::tr("MATH"); - scope.voltage.push_back(newVoltage); + newVoltage.name = QApplication::tr( "MATH" ); + scope.voltage.push_back( newVoltage ); - view.screen.voltage.push_back(QColor(0xff, 0x00, 0xff, 0xff)); // purple - view.screen.spectrum.push_back(view.screen.voltage.back().lighter()); - view.print.voltage.push_back(view.screen.voltage.back()); - view.print.spectrum.push_back(view.print.voltage.back().darker()); + view.screen.voltage.push_back( QColor( 0xff, 0x00, 0xff, 0xff ) ); // purple + view.screen.spectrum.push_back( view.screen.voltage.back().lighter() ); + view.print.voltage.push_back( view.screen.voltage.back() ); + view.print.spectrum.push_back( view.print.voltage.back().darker() ); load(); } -bool DsoSettings::setFilename(const QString &filename) { - std::unique_ptr local = std::unique_ptr(new QSettings(filename, QSettings::IniFormat)); - if (local->status() != QSettings::NoError) { +bool DsoSettings::setFilename( const QString &filename ) { + std::unique_ptr local = std::unique_ptr( new QSettings( filename, QSettings::IniFormat ) ); + if ( local->status() != QSettings::NoError ) { qWarning() << "Could not change the settings file to " << filename; return false; } - store.swap(local); + store.swap( local ); return true; } void DsoSettings::load() { // General options - store->beginGroup("options"); - if (store->contains("alwaysSave")) alwaysSave = store->value("alwaysSave").toBool(); + store->beginGroup( "options" ); + if ( store->contains( "alwaysSave" ) ) + alwaysSave = store->value( "alwaysSave" ).toBool(); store->endGroup(); - store->beginGroup("exporting"); - if (store->contains("imageSize")) exporting.imageSize = store->value("imageSize").toSize(); + store->beginGroup( "exporting" ); + if ( store->contains( "imageSize" ) ) + exporting.imageSize = store->value( "imageSize" ).toSize(); store->endGroup(); // Oscilloscope settings - store->beginGroup("scope"); + store->beginGroup( "scope" ); // Horizontal axis - store->beginGroup("horizontal"); - if (store->contains("format")) scope.horizontal.format = Dso::GraphFormat( store->value("format").toInt() ); - if (store->contains("frequencybase")) - scope.horizontal.frequencybase = store->value("frequencybase").toDouble(); - for (int marker = 0; marker < MARKER_COUNT; ++marker) { + store->beginGroup( "horizontal" ); + if ( store->contains( "format" ) ) + scope.horizontal.format = Dso::GraphFormat( store->value( "format" ).toInt() ); + if ( store->contains( "frequencybase" ) ) + scope.horizontal.frequencybase = store->value( "frequencybase" ).toDouble(); + for ( int marker = 0; marker < MARKER_COUNT; ++marker ) { QString name; - name = QString("marker%1").arg(marker); - if (store->contains(name)) scope.setMarker( unsigned( marker ), store->value(name).toDouble()); + name = QString( "marker%1" ).arg( marker ); + if ( store->contains( name ) ) + scope.setMarker( unsigned( marker ), store->value( name ).toDouble() ); } - if (store->contains("timebase")) scope.horizontal.timebase = store->value("timebase").toDouble(); - if (store->contains("recordLength")) scope.horizontal.recordLength = store->value("recordLength").toUInt(); - if (store->contains("samplerate")) scope.horizontal.samplerate = store->value("samplerate").toDouble(); - if (store->contains("calfreq")) scope.horizontal.calfreq = store->value("calfreq").toDouble(); + if ( store->contains( "timebase" ) ) + scope.horizontal.timebase = store->value( "timebase" ).toDouble(); + if ( store->contains( "recordLength" ) ) + scope.horizontal.recordLength = store->value( "recordLength" ).toUInt(); + if ( store->contains( "samplerate" ) ) + scope.horizontal.samplerate = store->value( "samplerate" ).toDouble(); + if ( store->contains( "calfreq" ) ) + scope.horizontal.calfreq = store->value( "calfreq" ).toDouble(); store->endGroup(); // Trigger - store->beginGroup("trigger"); - if (store->contains("mode")) scope.trigger.mode = Dso::TriggerMode( store->value("mode").toUInt() ); - if (store->contains("position")) scope.trigger.offset = store->value("position").toDouble(); - if (store->contains("slope")) scope.trigger.slope = Dso::Slope( store->value("slope").toUInt() ); - if (store->contains("source")) scope.trigger.source = store->value("source").toUInt(); + store->beginGroup( "trigger" ); + if ( store->contains( "mode" ) ) + scope.trigger.mode = Dso::TriggerMode( store->value( "mode" ).toUInt() ); + if ( store->contains( "position" ) ) + scope.trigger.offset = store->value( "position" ).toDouble(); + if ( store->contains( "slope" ) ) + scope.trigger.slope = Dso::Slope( store->value( "slope" ).toUInt() ); + if ( store->contains( "source" ) ) + scope.trigger.source = store->value( "source" ).toUInt(); store->endGroup(); // Spectrum - for (ChannelID channel = 0; channel < scope.spectrum.size(); ++channel) { - store->beginGroup(QString("spectrum%1").arg(channel)); - if (store->contains("magnitude")) - scope.spectrum[channel].magnitude = store->value("magnitude").toDouble(); - if (store->contains("offset")) scope.spectrum[channel].offset = store->value("offset").toDouble(); - if (store->contains("used")) scope.spectrum[channel].used = store->value("used").toBool(); - store->beginGroup("cursor"); - if (store->contains("shape")) scope.spectrum[channel].cursor.shape = - DsoSettingsScopeCursor::CursorShape(store->value("shape").toUInt()); - for (int marker = 0; marker < MARKER_COUNT; ++marker) { + for ( ChannelID channel = 0; channel < scope.spectrum.size(); ++channel ) { + store->beginGroup( QString( "spectrum%1" ).arg( channel ) ); + if ( store->contains( "magnitude" ) ) + scope.spectrum[ channel ].magnitude = store->value( "magnitude" ).toDouble(); + if ( store->contains( "offset" ) ) + scope.spectrum[ channel ].offset = store->value( "offset" ).toDouble(); + if ( store->contains( "used" ) ) + scope.spectrum[ channel ].used = store->value( "used" ).toBool(); + store->beginGroup( "cursor" ); + if ( store->contains( "shape" ) ) + scope.spectrum[ channel ].cursor.shape = + DsoSettingsScopeCursor::CursorShape( store->value( "shape" ).toUInt() ); + for ( int marker = 0; marker < MARKER_COUNT; ++marker ) { QString name; - name = QString("x%1").arg(marker); - if (store->contains(name)) scope.spectrum[channel].cursor.pos[marker].setX(store->value(name).toDouble()); - name = QString("y%1").arg(marker); - if (store->contains(name)) scope.spectrum[channel].cursor.pos[marker].setY(store->value(name).toDouble()); + name = QString( "x%1" ).arg( marker ); + if ( store->contains( name ) ) + scope.spectrum[ channel ].cursor.pos[ marker ].setX( store->value( name ).toDouble() ); + name = QString( "y%1" ).arg( marker ); + if ( store->contains( name ) ) + scope.spectrum[ channel ].cursor.pos[ marker ].setY( store->value( name ).toDouble() ); } store->endGroup(); store->endGroup(); } // Voltage - for (ChannelID channel = 0; channel < scope.voltage.size(); ++channel) { - store->beginGroup(QString("vertical%1").arg(channel)); - if (store->contains("gainStepIndex")) scope.voltage[channel].gainStepIndex = store->value("gainStepIndex").toUInt(); - if (store->contains("couplingOrMathIndex")) { - scope.voltage[channel].couplingOrMathIndex = - store->value("couplingOrMathIndex").toUInt(); - if (channel < deviceSpecification->channels) - if ( scope.voltage[channel].couplingOrMathIndex >= deviceSpecification->couplings.size() ) - scope.voltage[channel].couplingOrMathIndex = 0; // set to default if out of range + for ( ChannelID channel = 0; channel < scope.voltage.size(); ++channel ) { + store->beginGroup( QString( "vertical%1" ).arg( channel ) ); + if ( store->contains( "gainStepIndex" ) ) + scope.voltage[ channel ].gainStepIndex = store->value( "gainStepIndex" ).toUInt(); + if ( store->contains( "couplingOrMathIndex" ) ) { + scope.voltage[ channel ].couplingOrMathIndex = store->value( "couplingOrMathIndex" ).toUInt(); + if ( channel < deviceSpecification->channels ) + if ( scope.voltage[ channel ].couplingOrMathIndex >= deviceSpecification->couplings.size() ) + scope.voltage[ channel ].couplingOrMathIndex = 0; // set to default if out of range } - if (store->contains("inverted")) scope.voltage[channel].inverted = store->value("inverted").toBool(); - if (store->contains("offset")) scope.voltage[channel].offset = store->value("offset").toDouble(); - if (store->contains("trigger")) scope.voltage[channel].trigger = store->value("trigger").toDouble(); - if (store->contains("probeAttn")) scope.voltage[channel].probeAttn = store->value("probeAttn").toDouble(); - if (store->contains("used")) - scope.voltage[channel].used = store->value("used").toBool(); + if ( store->contains( "inverted" ) ) + scope.voltage[ channel ].inverted = store->value( "inverted" ).toBool(); + if ( store->contains( "offset" ) ) + scope.voltage[ channel ].offset = store->value( "offset" ).toDouble(); + if ( store->contains( "trigger" ) ) + scope.voltage[ channel ].trigger = store->value( "trigger" ).toDouble(); + if ( store->contains( "probeAttn" ) ) + scope.voltage[ channel ].probeAttn = store->value( "probeAttn" ).toDouble(); + if ( store->contains( "used" ) ) + scope.voltage[ channel ].used = store->value( "used" ).toBool(); else if ( 0 == channel ) // no "used" entry -> no config file: ch0 is active as default - scope.voltage[channel].used = true; - store->beginGroup("cursor"); - if (store->contains("shape")) scope.voltage[channel].cursor.shape = - DsoSettingsScopeCursor::CursorShape(store->value("shape").toUInt()); - for (int marker = 0; marker < MARKER_COUNT; ++marker) { + scope.voltage[ channel ].used = true; + store->beginGroup( "cursor" ); + if ( store->contains( "shape" ) ) + scope.voltage[ channel ].cursor.shape = + DsoSettingsScopeCursor::CursorShape( store->value( "shape" ).toUInt() ); + for ( int marker = 0; marker < MARKER_COUNT; ++marker ) { QString name; - name = QString("x%1").arg(marker); - if (store->contains(name)) scope.voltage[channel].cursor.pos[marker].setX(store->value(name).toDouble()); - name = QString("y%1").arg(marker); - if (store->contains(name)) scope.voltage[channel].cursor.pos[marker].setY(store->value(name).toDouble()); + name = QString( "x%1" ).arg( marker ); + if ( store->contains( name ) ) + scope.voltage[ channel ].cursor.pos[ marker ].setX( store->value( name ).toDouble() ); + name = QString( "y%1" ).arg( marker ); + if ( store->contains( name ) ) + scope.voltage[ channel ].cursor.pos[ marker ].setY( store->value( name ).toDouble() ); } store->endGroup(); store->endGroup(); } // Post processing - if (store->contains("spectrumLimit")) post.spectrumLimit = store->value("spectrumLimit").toDouble(); - if (store->contains("spectrumReference")) - post.spectrumReference = store->value("spectrumReference").toDouble(); - if (store->contains("spectrumWindow")) - post.spectrumWindow = Dso::WindowFunction( store->value("spectrumWindow").toInt() ); + if ( store->contains( "spectrumLimit" ) ) + post.spectrumLimit = store->value( "spectrumLimit" ).toDouble(); + if ( store->contains( "spectrumReference" ) ) + post.spectrumReference = store->value( "spectrumReference" ).toDouble(); + if ( store->contains( "spectrumWindow" ) ) + post.spectrumWindow = Dso::WindowFunction( store->value( "spectrumWindow" ).toInt() ); store->endGroup(); // View - store->beginGroup("view"); + store->beginGroup( "view" ); // Colors - store->beginGroup("color"); + store->beginGroup( "color" ); DsoSettingsColorValues *colors; - for (int mode = 0; mode < 2; ++mode) { - if (mode == 0) { + for ( int mode = 0; mode < 2; ++mode ) { + if ( mode == 0 ) { colors = &view.screen; - store->beginGroup("screen"); + store->beginGroup( "screen" ); } else { colors = &view.print; - store->beginGroup("print"); + store->beginGroup( "print" ); } - if (store->contains("axes")) colors->axes = store->value("axes").value(); - if (store->contains("background")) colors->background = store->value("background").value(); - if (store->contains("border")) colors->border = store->value("border").value(); - if (store->contains("grid")) colors->grid = store->value("grid").value(); - if (store->contains("markers")) colors->markers = store->value("markers").value(); - for (ChannelID channel = 0; channel < scope.spectrum.size(); ++channel) { - QString key = QString("spectrum%1").arg(channel); - if (store->contains(key)) colors->spectrum[channel] = store->value(key).value(); + if ( store->contains( "axes" ) ) + colors->axes = store->value( "axes" ).value(); + if ( store->contains( "background" ) ) + colors->background = store->value( "background" ).value(); + if ( store->contains( "border" ) ) + colors->border = store->value( "border" ).value(); + if ( store->contains( "grid" ) ) + colors->grid = store->value( "grid" ).value(); + if ( store->contains( "markers" ) ) + colors->markers = store->value( "markers" ).value(); + for ( ChannelID channel = 0; channel < scope.spectrum.size(); ++channel ) { + QString key = QString( "spectrum%1" ).arg( channel ); + if ( store->contains( key ) ) + colors->spectrum[ channel ] = store->value( key ).value(); } - if (store->contains("text")) colors->text = store->value("text").value(); - for (ChannelID channel = 0; channel < scope.voltage.size(); ++channel) { - QString key = QString("voltage%1").arg(channel); - if (store->contains(key)) colors->voltage[channel] = store->value(key).value(); + if ( store->contains( "text" ) ) + colors->text = store->value( "text" ).value(); + for ( ChannelID channel = 0; channel < scope.voltage.size(); ++channel ) { + QString key = QString( "voltage%1" ).arg( channel ); + if ( store->contains( key ) ) + colors->voltage[ channel ] = store->value( key ).value(); } store->endGroup(); } store->endGroup(); // Other view settings - if (store->contains("histogram") ) scope.histogram = store->value("histogram").toBool(); - if (store->contains("digitalPhosphor")) view.digitalPhosphor = store->value("digitalPhosphor").toBool(); - if (store->contains("interpolation")) - view.interpolation = Dso::InterpolationMode( store->value("interpolation").toInt() ); - if (store->contains("screenColorImages")) view.screenColorImages = store->value("screenColorImages").toBool(); - if (store->contains("zoom")) view.zoom = store->value("zoom").toBool(); - if (store->contains("cursorGridPosition")) - view.cursorGridPosition = Qt::ToolBarArea( store->value("cursorGridPosition").toUInt() ); - if (store->contains("cursorsVisible")) view.cursorsVisible = store->value("cursorsVisible").toBool(); + if ( store->contains( "histogram" ) ) + scope.histogram = store->value( "histogram" ).toBool(); + if ( store->contains( "digitalPhosphor" ) ) + view.digitalPhosphor = store->value( "digitalPhosphor" ).toBool(); + if ( store->contains( "interpolation" ) ) + view.interpolation = Dso::InterpolationMode( store->value( "interpolation" ).toInt() ); + if ( store->contains( "screenColorImages" ) ) + view.screenColorImages = store->value( "screenColorImages" ).toBool(); + if ( store->contains( "zoom" ) ) + view.zoom = store->value( "zoom" ).toBool(); + if ( store->contains( "cursorGridPosition" ) ) + view.cursorGridPosition = Qt::ToolBarArea( store->value( "cursorGridPosition" ).toUInt() ); + if ( store->contains( "cursorsVisible" ) ) + view.cursorsVisible = store->value( "cursorsVisible" ).toBool(); store->endGroup(); - store->beginGroup("window"); - mainWindowGeometry = store->value("geometry").toByteArray(); - mainWindowState = store->value("state").toByteArray(); + store->beginGroup( "window" ); + mainWindowGeometry = store->value( "geometry" ).toByteArray(); + mainWindowState = store->value( "state" ).toByteArray(); store->endGroup(); } void DsoSettings::save() { // Main window layout and other general options - store->beginGroup("options"); - store->setValue("alwaysSave", alwaysSave); + store->beginGroup( "options" ); + store->setValue( "alwaysSave", alwaysSave ); store->endGroup(); - store->beginGroup("exporting"); - store->setValue("imageSize", exporting.imageSize); + store->beginGroup( "exporting" ); + store->setValue( "imageSize", exporting.imageSize ); store->endGroup(); // Oszilloskope settings - store->beginGroup("scope"); + store->beginGroup( "scope" ); // Horizontal axis - store->beginGroup("horizontal"); - store->setValue("format", scope.horizontal.format); - store->setValue("frequencybase", scope.horizontal.frequencybase); - for (int marker = 0; marker < MARKER_COUNT; ++marker) - store->setValue(QString("marker%1").arg(marker), scope.getMarker( unsigned( marker) ) ); - store->setValue("timebase", scope.horizontal.timebase); - store->setValue("recordLength", scope.horizontal.recordLength); - store->setValue("samplerate", scope.horizontal.samplerate); - store->setValue("calfreq", scope.horizontal.calfreq); + store->beginGroup( "horizontal" ); + store->setValue( "format", scope.horizontal.format ); + store->setValue( "frequencybase", scope.horizontal.frequencybase ); + for ( int marker = 0; marker < MARKER_COUNT; ++marker ) + store->setValue( QString( "marker%1" ).arg( marker ), scope.getMarker( unsigned( marker ) ) ); + store->setValue( "timebase", scope.horizontal.timebase ); + store->setValue( "recordLength", scope.horizontal.recordLength ); + store->setValue( "samplerate", scope.horizontal.samplerate ); + store->setValue( "calfreq", scope.horizontal.calfreq ); store->endGroup(); // horizontal // Trigger - store->beginGroup("trigger"); - store->setValue("mode", unsigned( scope.trigger.mode) ); - store->setValue("position", scope.trigger.offset ); - store->setValue("slope", unsigned( scope.trigger.slope) ); - store->setValue("source", scope.trigger.source); + store->beginGroup( "trigger" ); + store->setValue( "mode", unsigned( scope.trigger.mode ) ); + store->setValue( "position", scope.trigger.offset ); + store->setValue( "slope", unsigned( scope.trigger.slope ) ); + store->setValue( "source", scope.trigger.source ); store->endGroup(); // trigger // Spectrum - for (ChannelID channel = 0; channel < scope.spectrum.size(); ++channel) { - store->beginGroup(QString("spectrum%1").arg(channel)); - store->setValue("magnitude", scope.spectrum[channel].magnitude); - store->setValue("offset", scope.spectrum[channel].offset); - store->setValue("used", scope.spectrum[channel].used); - store->beginGroup("cursor"); - store->setValue("shape", scope.spectrum[channel].cursor.shape); - for (int marker = 0; marker < MARKER_COUNT; ++marker) { + for ( ChannelID channel = 0; channel < scope.spectrum.size(); ++channel ) { + store->beginGroup( QString( "spectrum%1" ).arg( channel ) ); + store->setValue( "magnitude", scope.spectrum[ channel ].magnitude ); + store->setValue( "offset", scope.spectrum[ channel ].offset ); + store->setValue( "used", scope.spectrum[ channel ].used ); + store->beginGroup( "cursor" ); + store->setValue( "shape", scope.spectrum[ channel ].cursor.shape ); + for ( int marker = 0; marker < MARKER_COUNT; ++marker ) { QString name; - name = QString("x%1").arg(marker); - store->setValue(name, scope.spectrum[channel].cursor.pos[marker].x()); - name = QString("y%1").arg(marker); - store->setValue(name, scope.spectrum[channel].cursor.pos[marker].y()); + name = QString( "x%1" ).arg( marker ); + store->setValue( name, scope.spectrum[ channel ].cursor.pos[ marker ].x() ); + name = QString( "y%1" ).arg( marker ); + store->setValue( name, scope.spectrum[ channel ].cursor.pos[ marker ].y() ); } store->endGroup(); // cursor store->endGroup(); // spectrum%1 } // Voltage - for (ChannelID channel = 0; channel < scope.voltage.size(); ++channel) { - store->beginGroup(QString("vertical%1").arg(channel)); - store->setValue("gainStepIndex", scope.voltage[channel].gainStepIndex); - store->setValue("couplingOrMathIndex", scope.voltage[channel].couplingOrMathIndex); - store->setValue("inverted", scope.voltage[channel].inverted); - store->setValue("offset", scope.voltage[channel].offset); - store->setValue("trigger", scope.voltage[channel].trigger); - store->setValue("used", scope.voltage[channel].used); - store->setValue("probeAttn", scope.voltage[channel].probeAttn); - store->beginGroup("cursor"); - store->setValue("shape", scope.voltage[channel].cursor.shape); - for (int marker = 0; marker < MARKER_COUNT; ++marker) { + for ( ChannelID channel = 0; channel < scope.voltage.size(); ++channel ) { + store->beginGroup( QString( "vertical%1" ).arg( channel ) ); + store->setValue( "gainStepIndex", scope.voltage[ channel ].gainStepIndex ); + store->setValue( "couplingOrMathIndex", scope.voltage[ channel ].couplingOrMathIndex ); + store->setValue( "inverted", scope.voltage[ channel ].inverted ); + store->setValue( "offset", scope.voltage[ channel ].offset ); + store->setValue( "trigger", scope.voltage[ channel ].trigger ); + store->setValue( "used", scope.voltage[ channel ].used ); + store->setValue( "probeAttn", scope.voltage[ channel ].probeAttn ); + store->beginGroup( "cursor" ); + store->setValue( "shape", scope.voltage[ channel ].cursor.shape ); + for ( int marker = 0; marker < MARKER_COUNT; ++marker ) { QString name; - name = QString("x%1").arg(marker); - store->setValue(name, scope.voltage[channel].cursor.pos[marker].x()); - name = QString("y%1").arg(marker); - store->setValue(name, scope.voltage[channel].cursor.pos[marker].y()); + name = QString( "x%1" ).arg( marker ); + store->setValue( name, scope.voltage[ channel ].cursor.pos[ marker ].x() ); + name = QString( "y%1" ).arg( marker ); + store->setValue( name, scope.voltage[ channel ].cursor.pos[ marker ].y() ); } store->endGroup(); // cursor store->endGroup(); // vertical%1 } // Post processing - store->setValue("spectrumLimit", post.spectrumLimit); - store->setValue("spectrumReference", post.spectrumReference); - store->setValue("spectrumWindow", unsigned( post.spectrumWindow ) ); - store->endGroup(); //scope + store->setValue( "spectrumLimit", post.spectrumLimit ); + store->setValue( "spectrumReference", post.spectrumReference ); + store->setValue( "spectrumWindow", unsigned( post.spectrumWindow ) ); + store->endGroup(); // scope // View - store->beginGroup("view"); + store->beginGroup( "view" ); // Colors - store->beginGroup("color"); + store->beginGroup( "color" ); DsoSettingsColorValues *colors; - for (int mode = 0; mode < 2; ++mode) { - if (mode == 0) { + for ( int mode = 0; mode < 2; ++mode ) { + if ( mode == 0 ) { colors = &view.screen; - store->beginGroup("screen"); + store->beginGroup( "screen" ); } else { colors = &view.print; - store->beginGroup("print"); + store->beginGroup( "print" ); } - store->setValue("axes", colors->axes.name(QColor::HexArgb)); - store->setValue("background", colors->background.name(QColor::HexArgb)); - store->setValue("border", colors->border.name(QColor::HexArgb)); - store->setValue("grid", colors->grid.name(QColor::HexArgb)); - store->setValue("markers", colors->markers.name(QColor::HexArgb)); - for (ChannelID channel = 0; channel < scope.spectrum.size(); ++channel) - store->setValue(QString("spectrum%1").arg(channel), colors->spectrum[channel].name(QColor::HexArgb)); - store->setValue("text", colors->text.name(QColor::HexArgb)); - for (ChannelID channel = 0; channel < scope.voltage.size(); ++channel) - store->setValue(QString("voltage%1").arg(channel), colors->voltage[channel].name(QColor::HexArgb)); + store->setValue( "axes", colors->axes.name( QColor::HexArgb ) ); + store->setValue( "background", colors->background.name( QColor::HexArgb ) ); + store->setValue( "border", colors->border.name( QColor::HexArgb ) ); + store->setValue( "grid", colors->grid.name( QColor::HexArgb ) ); + store->setValue( "markers", colors->markers.name( QColor::HexArgb ) ); + for ( ChannelID channel = 0; channel < scope.spectrum.size(); ++channel ) + store->setValue( QString( "spectrum%1" ).arg( channel ), + colors->spectrum[ channel ].name( QColor::HexArgb ) ); + store->setValue( "text", colors->text.name( QColor::HexArgb ) ); + for ( ChannelID channel = 0; channel < scope.voltage.size(); ++channel ) + store->setValue( QString( "voltage%1" ).arg( channel ), + colors->voltage[ channel ].name( QColor::HexArgb ) ); store->endGroup(); // screen / print } store->endGroup(); // color // Other view settings - store->setValue("histogram", scope.histogram); - store->setValue("digitalPhosphor", view.digitalPhosphor); - store->setValue("interpolation", view.interpolation); - store->setValue("screenColorImages", view.screenColorImages); - store->setValue("zoom", view.zoom); - store->setValue("cursorGridPosition", view.cursorGridPosition); - store->setValue("cursorsVisible", view.cursorsVisible); + store->setValue( "histogram", scope.histogram ); + store->setValue( "digitalPhosphor", view.digitalPhosphor ); + store->setValue( "interpolation", view.interpolation ); + store->setValue( "screenColorImages", view.screenColorImages ); + store->setValue( "zoom", view.zoom ); + store->setValue( "cursorGridPosition", view.cursorGridPosition ); + store->setValue( "cursorsVisible", view.cursorsVisible ); store->endGroup(); // view - store->beginGroup("window"); - store->setValue("geometry", mainWindowGeometry); - store->setValue("state", mainWindowState); + store->beginGroup( "window" ); + store->setValue( "geometry", mainWindowGeometry ); + store->setValue( "state", mainWindowState ); store->endGroup(); // window } diff --git a/openhantek/src/dsosettings.h b/openhantek/src/dsosettings.h index 18ee8a9c..426aedb8 100644 --- a/openhantek/src/dsosettings.h +++ b/openhantek/src/dsosettings.h @@ -15,8 +15,8 @@ /// \brief Holds the settings of the program. class DsoSettings { public: - explicit DsoSettings(const Dso::ControlSpecification *deviceSpecification); - bool setFilename(const QString &filename); + explicit DsoSettings( const Dso::ControlSpecification *deviceSpecification ); + bool setFilename( const QString &filename ); DsoSettingsExport exporting; ///< General options of the program DsoSettingsScope scope; ///< All oscilloscope related settings @@ -34,6 +34,6 @@ class DsoSettings { void save(); private: - std::unique_ptr store = std::unique_ptr(new QSettings); + std::unique_ptr store = std::unique_ptr( new QSettings ); const Dso::ControlSpecification *deviceSpecification; }; diff --git a/openhantek/src/dsowidget.cpp b/openhantek/src/dsowidget.cpp index c2a8879a..b847be47 100644 --- a/openhantek/src/dsowidget.cpp +++ b/openhantek/src/dsowidget.cpp @@ -11,8 +11,8 @@ #include "dsowidget.h" -#include "post/postprocessingsettings.h" #include "post/graphgenerator.h" +#include "post/postprocessingsettings.h" #include "post/ppresult.h" #include "utils/printutils.h" @@ -21,409 +21,415 @@ #include "scopesettings.h" #include "viewconstants.h" #include "viewsettings.h" -#include "widgets/levelslider.h" #include "widgets/datagrid.h" +#include "widgets/levelslider.h" static int zoomScopeRow = 0; -DsoWidget::DsoWidget(DsoSettingsScope *scope, DsoSettingsView *view, const Dso::ControlSpecification *spec, - QWidget *parent, Qt::WindowFlags flags) - : QWidget(parent, flags), scope(scope), view(view), spec(spec), mainScope(GlScope::createNormal(scope, view)), - zoomScope(GlScope::createZoomed(scope, view)) { +DsoWidget::DsoWidget( DsoSettingsScope *scope, DsoSettingsView *view, const Dso::ControlSpecification *spec, + QWidget *parent, Qt::WindowFlags flags ) + : QWidget( parent, flags ), scope( scope ), view( view ), spec( spec ), + mainScope( GlScope::createNormal( scope, view ) ), zoomScope( GlScope::createZoomed( scope, view ) ) { // Palette for this widget QPalette palette; - palette.setColor(QPalette::Background, view->screen.background); - palette.setColor(QPalette::WindowText, view->screen.text); - - setupSliders(mainSliders); - setupSliders(zoomSliders); - - connect(mainScope, &GlScope::markerMoved, [this](unsigned cursorIndex, unsigned marker) { - mainSliders.markerSlider->setValue(int(marker), this->scope->getMarker(marker)); - mainScope->updateCursor(cursorIndex); - zoomScope->updateCursor(cursorIndex); - }); - connect(zoomScope, &GlScope::markerMoved, [this](unsigned cursorIndex) { - mainScope->updateCursor(cursorIndex); - zoomScope->updateCursor(cursorIndex); - }); + palette.setColor( QPalette::Background, view->screen.background ); + palette.setColor( QPalette::WindowText, view->screen.text ); + + setupSliders( mainSliders ); + setupSliders( zoomSliders ); + + connect( mainScope, &GlScope::markerMoved, [this]( unsigned cursorIndex, unsigned marker ) { + mainSliders.markerSlider->setValue( int( marker ), this->scope->getMarker( marker ) ); + mainScope->updateCursor( cursorIndex ); + zoomScope->updateCursor( cursorIndex ); + } ); + connect( zoomScope, &GlScope::markerMoved, [this]( unsigned cursorIndex ) { + mainScope->updateCursor( cursorIndex ); + zoomScope->updateCursor( cursorIndex ); + } ); // The table for the settings at screen top settingsTriggerLabel = new QLabel(); - settingsTriggerLabel->setMinimumWidth(320); - settingsTriggerLabel->setIndent(5); + settingsTriggerLabel->setMinimumWidth( 320 ); + settingsTriggerLabel->setIndent( 5 ); settingsSamplesOnScreen = new QLabel(); - settingsSamplesOnScreen->setAlignment(Qt::AlignRight); - settingsSamplesOnScreen->setPalette(palette); + settingsSamplesOnScreen->setAlignment( Qt::AlignRight ); + settingsSamplesOnScreen->setPalette( palette ); settingsSamplerateLabel = new QLabel(); - settingsSamplerateLabel->setAlignment(Qt::AlignRight); - settingsSamplerateLabel->setPalette(palette); + settingsSamplerateLabel->setAlignment( Qt::AlignRight ); + settingsSamplerateLabel->setPalette( palette ); settingsTimebaseLabel = new QLabel(); - settingsTimebaseLabel->setAlignment(Qt::AlignRight); - settingsTimebaseLabel->setPalette(palette); + settingsTimebaseLabel->setAlignment( Qt::AlignRight ); + settingsTimebaseLabel->setPalette( palette ); settingsFrequencybaseLabel = new QLabel(); - settingsFrequencybaseLabel->setAlignment(Qt::AlignRight); - settingsFrequencybaseLabel->setPalette(palette); + settingsFrequencybaseLabel->setAlignment( Qt::AlignRight ); + settingsFrequencybaseLabel->setPalette( palette ); swTriggerStatus = new QLabel(); - swTriggerStatus->setMinimumWidth(20); - swTriggerStatus->setText(tr("TR")); - swTriggerStatus->setAlignment(Qt::AlignCenter); - swTriggerStatus->setAutoFillBackground(true); - swTriggerStatus->setVisible(false); + swTriggerStatus->setMinimumWidth( 20 ); + swTriggerStatus->setText( tr( "TR" ) ); + swTriggerStatus->setAlignment( Qt::AlignCenter ); + swTriggerStatus->setAutoFillBackground( true ); + swTriggerStatus->setVisible( false ); settingsLayout = new QHBoxLayout(); - settingsLayout->addWidget(swTriggerStatus); - settingsLayout->addWidget(settingsTriggerLabel); - settingsLayout->addWidget(settingsSamplesOnScreen, 1); - settingsLayout->addWidget(settingsSamplerateLabel, 1); - settingsLayout->addWidget(settingsTimebaseLabel, 1); - settingsLayout->addWidget(settingsFrequencybaseLabel, 1); + settingsLayout->addWidget( swTriggerStatus ); + settingsLayout->addWidget( settingsTriggerLabel ); + settingsLayout->addWidget( settingsSamplesOnScreen, 1 ); + settingsLayout->addWidget( settingsSamplerateLabel, 1 ); + settingsLayout->addWidget( settingsTimebaseLabel, 1 ); + settingsLayout->addWidget( settingsFrequencybaseLabel, 1 ); // The table for the marker details markerInfoLabel = new QLabel(); - markerInfoLabel->setAlignment(Qt::AlignLeft); - markerInfoLabel->setPalette(palette); + markerInfoLabel->setAlignment( Qt::AlignLeft ); + markerInfoLabel->setPalette( palette ); markerTimeLabel = new QLabel(); - markerTimeLabel->setAlignment(Qt::AlignLeft); - markerTimeLabel->setPalette(palette); + markerTimeLabel->setAlignment( Qt::AlignLeft ); + markerTimeLabel->setPalette( palette ); markerFrequencyLabel = new QLabel(); - markerFrequencyLabel->setAlignment(Qt::AlignLeft); - markerFrequencyLabel->setPalette(palette); + markerFrequencyLabel->setAlignment( Qt::AlignLeft ); + markerFrequencyLabel->setPalette( palette ); markerTimebaseLabel = new QLabel(); - markerTimebaseLabel->setAlignment(Qt::AlignRight); - markerTimebaseLabel->setPalette(palette); + markerTimebaseLabel->setAlignment( Qt::AlignRight ); + markerTimebaseLabel->setPalette( palette ); markerFrequencybaseLabel = new QLabel(); - markerFrequencybaseLabel->setAlignment(Qt::AlignRight); - markerFrequencybaseLabel->setPalette(palette); + markerFrequencybaseLabel->setAlignment( Qt::AlignRight ); + markerFrequencybaseLabel->setPalette( palette ); markerLayout = new QHBoxLayout(); - markerLayout->addWidget(markerInfoLabel); - markerLayout->addWidget(markerTimeLabel, 1); - markerLayout->addWidget(markerFrequencyLabel, 1); - markerLayout->addWidget(markerTimebaseLabel, 1); - markerLayout->addWidget(markerFrequencybaseLabel, 1); + markerLayout->addWidget( markerInfoLabel ); + markerLayout->addWidget( markerTimeLabel, 1 ); + markerLayout->addWidget( markerFrequencyLabel, 1 ); + markerLayout->addWidget( markerTimebaseLabel, 1 ); + markerLayout->addWidget( markerFrequencybaseLabel, 1 ); // The table for the measurements at screen bottom QPalette tablePalette = palette; measurementLayout = new QGridLayout(); - int iii=0; - measurementLayout->setColumnMinimumWidth(iii++, 50); - measurementLayout->setColumnMinimumWidth(iii++, 30); - measurementLayout->setColumnStretch(iii++, 3); - measurementLayout->setColumnStretch(iii++, 3); - measurementLayout->setColumnStretch(iii++, 3); - measurementLayout->setColumnStretch(iii++, 3); - measurementLayout->setColumnStretch(iii++, 3); - measurementLayout->setColumnStretch(iii++, 3); - measurementLayout->setColumnStretch(iii++, 3); - measurementLayout->setColumnStretch(iii++, 3); - for (ChannelID channel = 0; channel < scope->voltage.size(); ++channel) { - tablePalette.setColor(QPalette::WindowText, view->screen.voltage[channel]); - measurementNameLabel.push_back(new QLabel(scope->voltage[channel].name)); - measurementNameLabel[channel]->setAlignment(Qt::AlignCenter); - measurementNameLabel[channel]->setPalette(tablePalette); - measurementNameLabel[channel]->setAutoFillBackground(true); - measurementMiscLabel.push_back(new QLabel()); - measurementMiscLabel[channel]->setAlignment(Qt::AlignLeft); - measurementMiscLabel[channel]->setPalette(tablePalette); - measurementGainLabel.push_back(new QLabel()); - measurementGainLabel[channel]->setAlignment(Qt::AlignRight); - measurementGainLabel[channel]->setPalette(tablePalette); - tablePalette.setColor(QPalette::WindowText, view->screen.spectrum[channel]); - measurementMagnitudeLabel.push_back(new QLabel()); - measurementMagnitudeLabel[channel]->setAlignment(Qt::AlignRight); - measurementMagnitudeLabel[channel]->setPalette(tablePalette); - measurementVppLabel.push_back(new QLabel()); - measurementVppLabel[channel]->setAlignment(Qt::AlignRight); - measurementVppLabel[channel]->setPalette(palette); - measurementRMSLabel.push_back(new QLabel()); - measurementRMSLabel[channel]->setAlignment(Qt::AlignRight); - measurementRMSLabel[channel]->setPalette(palette); - measurementDCLabel.push_back(new QLabel()); - measurementDCLabel[channel]->setAlignment(Qt::AlignRight); - measurementDCLabel[channel]->setPalette(palette); - measurementACLabel.push_back(new QLabel()); - measurementACLabel[channel]->setAlignment(Qt::AlignRight); - measurementACLabel[channel]->setPalette(palette); - measurementdBLabel.push_back(new QLabel()); - measurementdBLabel[channel]->setAlignment(Qt::AlignRight); - measurementdBLabel[channel]->setPalette(palette); - measurementFrequencyLabel.push_back(new QLabel()); - measurementFrequencyLabel[channel]->setAlignment(Qt::AlignRight); - measurementFrequencyLabel[channel]->setPalette(palette); - setMeasurementVisible(channel); + int iii = 0; + measurementLayout->setColumnMinimumWidth( iii++, 50 ); + measurementLayout->setColumnMinimumWidth( iii++, 30 ); + measurementLayout->setColumnStretch( iii++, 3 ); + measurementLayout->setColumnStretch( iii++, 3 ); + measurementLayout->setColumnStretch( iii++, 3 ); + measurementLayout->setColumnStretch( iii++, 3 ); + measurementLayout->setColumnStretch( iii++, 3 ); + measurementLayout->setColumnStretch( iii++, 3 ); + measurementLayout->setColumnStretch( iii++, 3 ); + measurementLayout->setColumnStretch( iii++, 3 ); + for ( ChannelID channel = 0; channel < scope->voltage.size(); ++channel ) { + tablePalette.setColor( QPalette::WindowText, view->screen.voltage[ channel ] ); + measurementNameLabel.push_back( new QLabel( scope->voltage[ channel ].name ) ); + measurementNameLabel[ channel ]->setAlignment( Qt::AlignCenter ); + measurementNameLabel[ channel ]->setPalette( tablePalette ); + measurementNameLabel[ channel ]->setAutoFillBackground( true ); + measurementMiscLabel.push_back( new QLabel() ); + measurementMiscLabel[ channel ]->setAlignment( Qt::AlignLeft ); + measurementMiscLabel[ channel ]->setPalette( tablePalette ); + measurementGainLabel.push_back( new QLabel() ); + measurementGainLabel[ channel ]->setAlignment( Qt::AlignRight ); + measurementGainLabel[ channel ]->setPalette( tablePalette ); + tablePalette.setColor( QPalette::WindowText, view->screen.spectrum[ channel ] ); + measurementMagnitudeLabel.push_back( new QLabel() ); + measurementMagnitudeLabel[ channel ]->setAlignment( Qt::AlignRight ); + measurementMagnitudeLabel[ channel ]->setPalette( tablePalette ); + measurementVppLabel.push_back( new QLabel() ); + measurementVppLabel[ channel ]->setAlignment( Qt::AlignRight ); + measurementVppLabel[ channel ]->setPalette( palette ); + measurementRMSLabel.push_back( new QLabel() ); + measurementRMSLabel[ channel ]->setAlignment( Qt::AlignRight ); + measurementRMSLabel[ channel ]->setPalette( palette ); + measurementDCLabel.push_back( new QLabel() ); + measurementDCLabel[ channel ]->setAlignment( Qt::AlignRight ); + measurementDCLabel[ channel ]->setPalette( palette ); + measurementACLabel.push_back( new QLabel() ); + measurementACLabel[ channel ]->setAlignment( Qt::AlignRight ); + measurementACLabel[ channel ]->setPalette( palette ); + measurementdBLabel.push_back( new QLabel() ); + measurementdBLabel[ channel ]->setAlignment( Qt::AlignRight ); + measurementdBLabel[ channel ]->setPalette( palette ); + measurementFrequencyLabel.push_back( new QLabel() ); + measurementFrequencyLabel[ channel ]->setAlignment( Qt::AlignRight ); + measurementFrequencyLabel[ channel ]->setPalette( palette ); + setMeasurementVisible( channel ); iii = 0; - measurementLayout->addWidget(measurementNameLabel[channel], int(channel), iii++); - measurementLayout->addWidget(measurementMiscLabel[channel], int(channel), iii++); - measurementLayout->addWidget(measurementGainLabel[channel], int(channel), iii++); - measurementLayout->addWidget(measurementMagnitudeLabel[channel], int(channel), iii++); - measurementLayout->addWidget(measurementVppLabel[channel], int(channel), iii++); - measurementLayout->addWidget(measurementRMSLabel[channel], int(channel), iii++); - measurementLayout->addWidget(measurementDCLabel[channel], int(channel), iii++); - measurementLayout->addWidget(measurementACLabel[channel], int(channel), iii++); - measurementLayout->addWidget(measurementdBLabel[channel], int(channel), iii++); - measurementLayout->addWidget(measurementFrequencyLabel[channel], int(channel), iii++); - if (channel < spec->channels) - updateVoltageCoupling(channel); + measurementLayout->addWidget( measurementNameLabel[ channel ], int( channel ), iii++ ); + measurementLayout->addWidget( measurementMiscLabel[ channel ], int( channel ), iii++ ); + measurementLayout->addWidget( measurementGainLabel[ channel ], int( channel ), iii++ ); + measurementLayout->addWidget( measurementMagnitudeLabel[ channel ], int( channel ), iii++ ); + measurementLayout->addWidget( measurementVppLabel[ channel ], int( channel ), iii++ ); + measurementLayout->addWidget( measurementRMSLabel[ channel ], int( channel ), iii++ ); + measurementLayout->addWidget( measurementDCLabel[ channel ], int( channel ), iii++ ); + measurementLayout->addWidget( measurementACLabel[ channel ], int( channel ), iii++ ); + measurementLayout->addWidget( measurementdBLabel[ channel ], int( channel ), iii++ ); + measurementLayout->addWidget( measurementFrequencyLabel[ channel ], int( channel ), iii++ ); + if ( channel < spec->channels ) + updateVoltageCoupling( channel ); else updateMathMode(); - updateVoltageDetails(channel); - updateSpectrumDetails(channel); + updateVoltageDetails( channel ); + updateSpectrumDetails( channel ); } // Cursors - cursorDataGrid = new DataGrid(this); - cursorDataGrid->setBackgroundColor(view->screen.background); - cursorDataGrid->addItem(tr("Markers"), view->screen.text); - for (ChannelID channel = 0; channel < scope->voltage.size(); ++channel) { - cursorDataGrid->addItem(scope->voltage[channel].name, view->screen.voltage[channel]); + cursorDataGrid = new DataGrid( this ); + cursorDataGrid->setBackgroundColor( view->screen.background ); + cursorDataGrid->addItem( tr( "Markers" ), view->screen.text ); + for ( ChannelID channel = 0; channel < scope->voltage.size(); ++channel ) { + cursorDataGrid->addItem( scope->voltage[ channel ].name, view->screen.voltage[ channel ] ); } - for (ChannelID channel = 0; channel < scope->spectrum.size(); ++channel) { - cursorDataGrid->addItem(scope->spectrum[channel].name, view->screen.spectrum[channel]); + for ( ChannelID channel = 0; channel < scope->spectrum.size(); ++channel ) { + cursorDataGrid->addItem( scope->spectrum[ channel ].name, view->screen.spectrum[ channel ] ); } - cursorDataGrid->selectItem(0); + cursorDataGrid->selectItem( 0 ); - connect(cursorDataGrid, &DataGrid::itemSelected, [this] (unsigned index) { - mainScope->cursorSelected(index); - zoomScope->cursorSelected(index); - }); - connect(cursorDataGrid, &DataGrid::itemUpdated, [this, scope] (unsigned index) { + connect( cursorDataGrid, &DataGrid::itemSelected, [this]( unsigned index ) { + mainScope->cursorSelected( index ); + zoomScope->cursorSelected( index ); + } ); + connect( cursorDataGrid, &DataGrid::itemUpdated, [this, scope]( unsigned index ) { unsigned channelCount = scope->countChannels(); - if (0 < index && index < channelCount + 1) { + if ( 0 < index && index < channelCount + 1 ) { ChannelID channel = index - 1; - if (scope->voltage[channel].used) { - unsigned shape = scope->voltage[channel].cursor.shape; - if (shape == DsoSettingsScopeCursor::NONE) { - scope->voltage[channel].cursor.shape = DsoSettingsScopeCursor::RECTANGULAR; + if ( scope->voltage[ channel ].used ) { + unsigned shape = scope->voltage[ channel ].cursor.shape; + if ( shape == DsoSettingsScopeCursor::NONE ) { + scope->voltage[ channel ].cursor.shape = DsoSettingsScopeCursor::RECTANGULAR; } else { - scope->voltage[channel].cursor.shape = DsoSettingsScopeCursor::NONE; + scope->voltage[ channel ].cursor.shape = DsoSettingsScopeCursor::NONE; } } - } else if (channelCount < index && index < 2 * channelCount + 1) { + } else if ( channelCount < index && index < 2 * channelCount + 1 ) { ChannelID channel = index - channelCount - 1; - if (scope->spectrum[channel].used) { - unsigned shape = scope->spectrum[channel].cursor.shape; - if (shape == DsoSettingsScopeCursor::NONE) { - scope->spectrum[channel].cursor.shape = DsoSettingsScopeCursor::RECTANGULAR; + if ( scope->spectrum[ channel ].used ) { + unsigned shape = scope->spectrum[ channel ].cursor.shape; + if ( shape == DsoSettingsScopeCursor::NONE ) { + scope->spectrum[ channel ].cursor.shape = DsoSettingsScopeCursor::RECTANGULAR; } else { - scope->spectrum[channel].cursor.shape = DsoSettingsScopeCursor::NONE; + scope->spectrum[ channel ].cursor.shape = DsoSettingsScopeCursor::NONE; } } } updateMarkerDetails(); - mainScope->updateCursor(index); - zoomScope->updateCursor(index); - }); + mainScope->updateCursor( index ); + zoomScope->updateCursor( index ); + } ); scope->horizontal.cursor.shape = DsoSettingsScopeCursor::VERTICAL; // The layout for the widgets mainLayout = new QGridLayout(); - mainLayout->setColumnStretch(3, 1); // Scopes increase their size + mainLayout->setColumnStretch( 3, 1 ); // Scopes increase their size // Bars around the scope, needed because the slider-drawing-area is outside // the scope at min/max - mainLayout->setColumnMinimumWidth(2, mainSliders.triggerOffsetSlider->preMargin()); - mainLayout->setColumnMinimumWidth(4, mainSliders.triggerOffsetSlider->postMargin()); - mainLayout->setSpacing(0); + mainLayout->setColumnMinimumWidth( 2, mainSliders.triggerOffsetSlider->preMargin() ); + mainLayout->setColumnMinimumWidth( 4, mainSliders.triggerOffsetSlider->postMargin() ); + mainLayout->setSpacing( 0 ); int row = 0; // display settings on top of scope - mainLayout->addLayout(settingsLayout, row, 1, 1, 5); + mainLayout->addLayout( settingsLayout, row, 1, 1, 5 ); ++row; // 5x5 box for mainScope & mainSliders & markerSlider - mainLayout->addWidget(mainSliders.triggerOffsetSlider, row, 2, 2, 3, Qt::AlignBottom); + mainLayout->addWidget( mainSliders.triggerOffsetSlider, row, 2, 2, 3, Qt::AlignBottom ); ++row; - mainLayout->setRowMinimumHeight(row, mainSliders.voltageOffsetSlider->preMargin()); - mainLayout->addWidget(mainSliders.voltageOffsetSlider, row, 1, 3, 2, Qt::AlignRight); - mainLayout->addWidget(mainSliders.triggerLevelSlider, row, 4, 3, 2, Qt::AlignLeft); + mainLayout->setRowMinimumHeight( row, mainSliders.voltageOffsetSlider->preMargin() ); + mainLayout->addWidget( mainSliders.voltageOffsetSlider, row, 1, 3, 2, Qt::AlignRight ); + mainLayout->addWidget( mainSliders.triggerLevelSlider, row, 4, 3, 2, Qt::AlignLeft ); ++row; - mainLayout->setRowStretch(row, 1); // the scope gets max space - mainLayout->addWidget(mainScope, row, 3); + mainLayout->setRowStretch( row, 1 ); // the scope gets max space + mainLayout->addWidget( mainScope, row, 3 ); ++row; - mainLayout->setRowMinimumHeight(row, mainSliders.voltageOffsetSlider->postMargin()); - mainLayout->addWidget(mainSliders.markerSlider, row, 2, 2, 3, Qt::AlignTop); + mainLayout->setRowMinimumHeight( row, mainSliders.voltageOffsetSlider->postMargin() ); + mainLayout->addWidget( mainSliders.markerSlider, row, 2, 2, 3, Qt::AlignTop ); row += 2; // end 5x5 box // Separators and markerLayout - mainLayout->setRowMinimumHeight(row, 4); + mainLayout->setRowMinimumHeight( row, 4 ); ++row; - mainLayout->addLayout(markerLayout, row, 1, 1, 5); + mainLayout->addLayout( markerLayout, row, 1, 1, 5 ); ++row; - mainLayout->setRowMinimumHeight(row, 4); + mainLayout->setRowMinimumHeight( row, 4 ); ++row; // 5x4 box for zoomScope & zoomSliders - mainLayout->addWidget(zoomSliders.triggerOffsetSlider, row, 2, 2, 3, Qt::AlignBottom); + mainLayout->addWidget( zoomSliders.triggerOffsetSlider, row, 2, 2, 3, Qt::AlignBottom ); ++row; - mainLayout->setRowMinimumHeight(row, zoomSliders.voltageOffsetSlider->preMargin()); - mainLayout->addWidget(zoomSliders.voltageOffsetSlider, row, 1, 3, 2, Qt::AlignRight); - mainLayout->addWidget(zoomSliders.triggerLevelSlider, row, 4, 3, 2, Qt::AlignLeft); + mainLayout->setRowMinimumHeight( row, zoomSliders.voltageOffsetSlider->preMargin() ); + mainLayout->addWidget( zoomSliders.voltageOffsetSlider, row, 1, 3, 2, Qt::AlignRight ); + mainLayout->addWidget( zoomSliders.triggerLevelSlider, row, 4, 3, 2, Qt::AlignLeft ); ++row; - mainLayout->addWidget(zoomScope, zoomScopeRow = row, 3); + mainLayout->addWidget( zoomScope, zoomScopeRow = row, 3 ); ++row; - mainLayout->setRowMinimumHeight(row, zoomSliders.voltageOffsetSlider->postMargin()); + mainLayout->setRowMinimumHeight( row, zoomSliders.voltageOffsetSlider->postMargin() ); ++row; // end 5x4 box // Separator and embedded measurementLayout - mainLayout->setRowMinimumHeight(row, 8); + mainLayout->setRowMinimumHeight( row, 8 ); ++row; - mainLayout->addLayout(measurementLayout, row, 1, 1, 5); + mainLayout->addLayout( measurementLayout, row, 1, 1, 5 ); - updateCursorGrid(view->cursorsVisible); + updateCursorGrid( view->cursorsVisible ); // The widget itself - setPalette(palette); - setBackgroundRole(QPalette::Background); - setAutoFillBackground(true); - setLayout(mainLayout); + setPalette( palette ); + setBackgroundRole( QPalette::Background ); + setAutoFillBackground( true ); + setLayout( mainLayout ); // Connect change-signals of sliders - connect(mainSliders.voltageOffsetSlider, &LevelSlider::valueChanged, this, &DsoWidget::updateOffset); - connect(zoomSliders.voltageOffsetSlider, &LevelSlider::valueChanged, this, &DsoWidget::updateOffset); + connect( mainSliders.voltageOffsetSlider, &LevelSlider::valueChanged, this, &DsoWidget::updateOffset ); + connect( zoomSliders.voltageOffsetSlider, &LevelSlider::valueChanged, this, &DsoWidget::updateOffset ); - connect(mainSliders.triggerOffsetSlider, &LevelSlider::valueChanged, [this](int index, double value) { - updateTriggerOffset (index, value, true); - }); - connect(zoomSliders.triggerOffsetSlider, &LevelSlider::valueChanged, [this](int index, double value) { - updateTriggerOffset (index, value, false); - }); + connect( mainSliders.triggerOffsetSlider, &LevelSlider::valueChanged, + [this]( int index, double value ) { updateTriggerOffset( index, value, true ); } ); + connect( zoomSliders.triggerOffsetSlider, &LevelSlider::valueChanged, + [this]( int index, double value ) { updateTriggerOffset( index, value, false ); } ); - connect(mainSliders.triggerLevelSlider, &LevelSlider::valueChanged, this, &DsoWidget::updateTriggerLevel); - connect(zoomSliders.triggerLevelSlider, &LevelSlider::valueChanged, this, &DsoWidget::updateTriggerLevel); + connect( mainSliders.triggerLevelSlider, &LevelSlider::valueChanged, this, &DsoWidget::updateTriggerLevel ); + connect( zoomSliders.triggerLevelSlider, &LevelSlider::valueChanged, this, &DsoWidget::updateTriggerLevel ); - connect(mainSliders.markerSlider, &LevelSlider::valueChanged, [this](int index, double value) { - updateMarker(unsigned(index), value); + connect( mainSliders.markerSlider, &LevelSlider::valueChanged, [this]( int index, double value ) { + updateMarker( unsigned( index ), value ); mainScope->updateCursor(); zoomScope->updateCursor(); - }); - zoomSliders.markerSlider->setEnabled(false); + } ); + zoomSliders.markerSlider->setEnabled( false ); } -void DsoWidget::updateCursorGrid(bool enabled) { - if (!enabled) { - cursorDataGrid->selectItem(0); - cursorDataGrid->setParent(nullptr); - mainScope->cursorSelected(0); - zoomScope->cursorSelected(0); +void DsoWidget::updateCursorGrid( bool enabled ) { + if ( !enabled ) { + cursorDataGrid->selectItem( 0 ); + cursorDataGrid->setParent( nullptr ); + mainScope->cursorSelected( 0 ); + zoomScope->cursorSelected( 0 ); return; } - switch (view->cursorGridPosition) { + switch ( view->cursorGridPosition ) { case Qt::LeftToolBarArea: - if (mainLayout->itemAtPosition(0, 0) == nullptr) { - cursorDataGrid->setParent(nullptr); - mainLayout->addWidget(cursorDataGrid, 0, 0, mainLayout->rowCount(), 1); + if ( mainLayout->itemAtPosition( 0, 0 ) == nullptr ) { + cursorDataGrid->setParent( nullptr ); + mainLayout->addWidget( cursorDataGrid, 0, 0, mainLayout->rowCount(), 1 ); } break; case Qt::RightToolBarArea: - if (mainLayout->itemAtPosition(0, 6) == nullptr) { - cursorDataGrid->setParent(nullptr); - mainLayout->addWidget(cursorDataGrid, 0, 6, mainLayout->rowCount(), 1); + if ( mainLayout->itemAtPosition( 0, 6 ) == nullptr ) { + cursorDataGrid->setParent( nullptr ); + mainLayout->addWidget( cursorDataGrid, 0, 6, mainLayout->rowCount(), 1 ); } break; default: - if (cursorDataGrid->parent() != nullptr) { - cursorDataGrid->setParent(nullptr); + if ( cursorDataGrid->parent() != nullptr ) { + cursorDataGrid->setParent( nullptr ); } break; } } -void DsoWidget::setupSliders(DsoWidget::Sliders &sliders) { +void DsoWidget::setupSliders( DsoWidget::Sliders &sliders ) { // The offset sliders for all possible channels - sliders.voltageOffsetSlider = new LevelSlider(Qt::RightArrow); - for (ChannelID channel = 0; channel < scope->voltage.size(); ++channel) { - sliders.voltageOffsetSlider->addSlider(scope->voltage[channel].name, int(channel)); - sliders.voltageOffsetSlider->setColor((channel), view->screen.voltage[channel]); - sliders.voltageOffsetSlider->setLimits(int(channel), -DIVS_VOLTAGE / 2, DIVS_VOLTAGE / 2); - sliders.voltageOffsetSlider->setStep(int(channel), 0.2); - sliders.voltageOffsetSlider->setValue(int(channel), scope->voltage[channel].offset); - sliders.voltageOffsetSlider->setIndexVisible(channel, scope->voltage[channel].used); + sliders.voltageOffsetSlider = new LevelSlider( Qt::RightArrow ); + for ( ChannelID channel = 0; channel < scope->voltage.size(); ++channel ) { + sliders.voltageOffsetSlider->addSlider( scope->voltage[ channel ].name, int( channel ) ); + sliders.voltageOffsetSlider->setColor( ( channel ), view->screen.voltage[ channel ] ); + sliders.voltageOffsetSlider->setLimits( int( channel ), -DIVS_VOLTAGE / 2, DIVS_VOLTAGE / 2 ); + sliders.voltageOffsetSlider->setStep( int( channel ), 0.2 ); + sliders.voltageOffsetSlider->setValue( int( channel ), scope->voltage[ channel ].offset ); + sliders.voltageOffsetSlider->setIndexVisible( channel, scope->voltage[ channel ].used ); } - for (ChannelID channel = 0; channel < scope->voltage.size(); ++channel) { - sliders.voltageOffsetSlider->addSlider(scope->spectrum[channel].name, int(scope->voltage.size() + channel)); - sliders.voltageOffsetSlider->setColor(unsigned( scope->voltage.size() ) + channel, view->screen.spectrum[channel]); - sliders.voltageOffsetSlider->setLimits(int( scope->voltage.size() + channel ), -DIVS_VOLTAGE / 2, DIVS_VOLTAGE / 2); - sliders.voltageOffsetSlider->setStep(int( scope->voltage.size() + channel ), 0.2); - sliders.voltageOffsetSlider->setValue(int( scope->voltage.size() + channel ), scope->spectrum[channel].offset); - sliders.voltageOffsetSlider->setIndexVisible(unsigned(scope->voltage.size()) + channel, scope->spectrum[channel].used); + for ( ChannelID channel = 0; channel < scope->voltage.size(); ++channel ) { + sliders.voltageOffsetSlider->addSlider( scope->spectrum[ channel ].name, + int( scope->voltage.size() + channel ) ); + sliders.voltageOffsetSlider->setColor( unsigned( scope->voltage.size() ) + channel, + view->screen.spectrum[ channel ] ); + sliders.voltageOffsetSlider->setLimits( int( scope->voltage.size() + channel ), -DIVS_VOLTAGE / 2, + DIVS_VOLTAGE / 2 ); + sliders.voltageOffsetSlider->setStep( int( scope->voltage.size() + channel ), 0.2 ); + sliders.voltageOffsetSlider->setValue( int( scope->voltage.size() + channel ), + scope->spectrum[ channel ].offset ); + sliders.voltageOffsetSlider->setIndexVisible( unsigned( scope->voltage.size() ) + channel, + scope->spectrum[ channel ].used ); } // The triggerPosition slider - sliders.triggerOffsetSlider = new LevelSlider(Qt::DownArrow); + sliders.triggerOffsetSlider = new LevelSlider( Qt::DownArrow ); sliders.triggerOffsetSlider->addSlider(); - sliders.triggerOffsetSlider->setLimits(0, 0.0, 1.0); - sliders.triggerOffsetSlider->setStep(0, 0.2 / double(DIVS_TIME)); - sliders.triggerOffsetSlider->setValue(0, scope->trigger.offset ); - sliders.triggerOffsetSlider->setIndexVisible(0, true); + sliders.triggerOffsetSlider->setLimits( 0, 0.0, 1.0 ); + sliders.triggerOffsetSlider->setStep( 0, 0.2 / double( DIVS_TIME ) ); + sliders.triggerOffsetSlider->setValue( 0, scope->trigger.offset ); + sliders.triggerOffsetSlider->setIndexVisible( 0, true ); // The sliders for the trigger levels - sliders.triggerLevelSlider = new LevelSlider(Qt::LeftArrow); - for (ChannelID channel = 0; channel < spec->channels; ++channel) { - sliders.triggerLevelSlider->addSlider(int(channel)); - sliders.triggerLevelSlider->setColor(channel, - (channel == scope->trigger.source) - ? view->screen.voltage[channel] - : view->screen.voltage[channel].darker()); - adaptTriggerLevelSlider(sliders, channel); - sliders.triggerLevelSlider->setValue(int(channel), scope->voltage[channel].trigger); - sliders.triggerLevelSlider->setIndexVisible(channel, scope->voltage[channel].used); + sliders.triggerLevelSlider = new LevelSlider( Qt::LeftArrow ); + for ( ChannelID channel = 0; channel < spec->channels; ++channel ) { + sliders.triggerLevelSlider->addSlider( int( channel ) ); + sliders.triggerLevelSlider->setColor( channel, ( channel == scope->trigger.source ) + ? view->screen.voltage[ channel ] + : view->screen.voltage[ channel ].darker() ); + adaptTriggerLevelSlider( sliders, channel ); + sliders.triggerLevelSlider->setValue( int( channel ), scope->voltage[ channel ].trigger ); + sliders.triggerLevelSlider->setIndexVisible( channel, scope->voltage[ channel ].used ); } // The marker slider - sliders.markerSlider = new LevelSlider(Qt::UpArrow); - for (int marker = 0; marker < MARKER_COUNT; ++marker) { - sliders.markerSlider->addSlider(QString::number(marker + 1), marker); - sliders.markerSlider->setLimits(marker, MARGIN_LEFT, MARGIN_RIGHT); - sliders.markerSlider->setStep(marker, MARKER_STEP); - sliders.markerSlider->setValue(marker, scope->horizontal.cursor.pos[marker].x()); - sliders.markerSlider->setIndexVisible(unsigned(marker), true); + sliders.markerSlider = new LevelSlider( Qt::UpArrow ); + for ( int marker = 0; marker < MARKER_COUNT; ++marker ) { + sliders.markerSlider->addSlider( QString::number( marker + 1 ), marker ); + sliders.markerSlider->setLimits( marker, MARGIN_LEFT, MARGIN_RIGHT ); + sliders.markerSlider->setStep( marker, MARKER_STEP ); + sliders.markerSlider->setValue( marker, scope->horizontal.cursor.pos[ marker ].x() ); + sliders.markerSlider->setIndexVisible( unsigned( marker ), true ); } } /// \brief Set the trigger level sliders minimum and maximum to the new values. -void DsoWidget::adaptTriggerLevelSlider(DsoWidget::Sliders &sliders, ChannelID channel) { - //printf( "DW::adaptTriggerLevelSlider( %d )\n", channel ); - sliders.triggerLevelSlider->setLimits(int(channel), - (-DIVS_VOLTAGE / 2 - scope->voltage[channel].offset) * scope->gain(channel), - ( DIVS_VOLTAGE / 2 - scope->voltage[channel].offset) * scope->gain(channel) ); - sliders.triggerLevelSlider->setStep(int(channel), scope->gain(channel) * 0.05); - double value = sliders.triggerLevelSlider->value(int(channel)); - if ( bool(value) ) { // ignore when first called at init -// updateTriggerLevel(channel, value); +void DsoWidget::adaptTriggerLevelSlider( DsoWidget::Sliders &sliders, ChannelID channel ) { + // printf( "DW::adaptTriggerLevelSlider( %d )\n", channel ); + sliders.triggerLevelSlider->setLimits( + int( channel ), ( -DIVS_VOLTAGE / 2 - scope->voltage[ channel ].offset ) * scope->gain( channel ), + ( DIVS_VOLTAGE / 2 - scope->voltage[ channel ].offset ) * scope->gain( channel ) ); + sliders.triggerLevelSlider->setStep( int( channel ), scope->gain( channel ) * 0.05 ); + double value = sliders.triggerLevelSlider->value( int( channel ) ); + if ( bool( value ) ) { // ignore when first called at init + // updateTriggerLevel(channel, value); } } /// \brief Show/Hide a line of the measurement table. -void DsoWidget::setMeasurementVisible(ChannelID channel) { - bool visible = scope->voltage[channel].used || scope->spectrum[channel].used; - - measurementNameLabel[channel]->setVisible(visible); - measurementMiscLabel[channel]->setVisible(visible); - measurementGainLabel[channel]->setVisible(visible); - measurementVppLabel[channel]->setVisible(visible); - measurementRMSLabel[channel]->setVisible(visible); - measurementDCLabel[channel]->setVisible(visible); - measurementACLabel[channel]->setVisible(visible); - measurementdBLabel[channel]->setVisible(visible); - measurementFrequencyLabel[channel]->setVisible(visible); - if (!visible) { - measurementGainLabel[channel]->setText(QString()); - measurementVppLabel[channel]->setText(QString()); - measurementRMSLabel[channel]->setText(QString()); - measurementDCLabel[channel]->setText(QString()); - measurementACLabel[channel]->setText(QString()); - measurementdBLabel[channel]->setText(QString()); - measurementFrequencyLabel[channel]->setText(QString()); +void DsoWidget::setMeasurementVisible( ChannelID channel ) { + bool visible = scope->voltage[ channel ].used || scope->spectrum[ channel ].used; + + measurementNameLabel[ channel ]->setVisible( visible ); + measurementMiscLabel[ channel ]->setVisible( visible ); + measurementGainLabel[ channel ]->setVisible( visible ); + measurementVppLabel[ channel ]->setVisible( visible ); + measurementRMSLabel[ channel ]->setVisible( visible ); + measurementDCLabel[ channel ]->setVisible( visible ); + measurementACLabel[ channel ]->setVisible( visible ); + measurementdBLabel[ channel ]->setVisible( visible ); + measurementFrequencyLabel[ channel ]->setVisible( visible ); + if ( !visible ) { + measurementGainLabel[ channel ]->setText( QString() ); + measurementVppLabel[ channel ]->setText( QString() ); + measurementRMSLabel[ channel ]->setText( QString() ); + measurementDCLabel[ channel ]->setText( QString() ); + measurementACLabel[ channel ]->setText( QString() ); + measurementdBLabel[ channel ]->setText( QString() ); + measurementFrequencyLabel[ channel ]->setText( QString() ); } - measurementGainLabel[channel]->setVisible(scope->voltage[channel].used); - if (!scope->voltage[channel].used) { measurementGainLabel[channel]->setText(QString()); } + measurementGainLabel[ channel ]->setVisible( scope->voltage[ channel ].used ); + if ( !scope->voltage[ channel ].used ) { + measurementGainLabel[ channel ]->setText( QString() ); + } - measurementMagnitudeLabel[channel]->setVisible(scope->spectrum[channel].used); - if (!scope->spectrum[channel].used) { measurementMagnitudeLabel[channel]->setText(QString()); } + measurementMagnitudeLabel[ channel ]->setVisible( scope->spectrum[ channel ].used ); + if ( !scope->spectrum[ channel ].used ) { + measurementMagnitudeLabel[ channel ]->setText( QString() ); + } } /// \brief Update the label about the marker measurements void DsoWidget::updateMarkerDetails() { - double m1 = scope->horizontal.cursor.pos[0].x() + DIVS_TIME / 2; // zero at center -> zero at left margin - double m2 = scope->horizontal.cursor.pos[1].x() + DIVS_TIME / 2; // zero at center -> zero at left margin + double m1 = scope->horizontal.cursor.pos[ 0 ].x() + DIVS_TIME / 2; // zero at center -> zero at left margin + double m2 = scope->horizontal.cursor.pos[ 1 ].x() + DIVS_TIME / 2; // zero at center -> zero at left margin if ( m1 > m2 ) std::swap( m1, m2 ); double divs = m2 - m1; @@ -438,39 +444,41 @@ void DsoWidget::updateMarkerDetails() { bool freqUsed = false; int index = 0; - cursorDataGrid->updateInfo( unsigned( index++ ), true, QString(), - valueToString(time, UNIT_SECONDS, 3), valueToString( freq, UNIT_HERTZ, 3 ) ); + cursorDataGrid->updateInfo( unsigned( index++ ), true, QString(), valueToString( time, UNIT_SECONDS, 3 ), + valueToString( freq, UNIT_HERTZ, 3 ) ); - for (ChannelID channel = 0; channel < scope->voltage.size(); ++channel) { - if (scope->voltage[channel].used) { + for ( ChannelID channel = 0; channel < scope->voltage.size(); ++channel ) { + if ( scope->voltage[ channel ].used ) { timeUsed = true; // at least one voltage channel used -> show marker time details - QPointF p0 = scope->voltage[channel].cursor.pos[0]; - QPointF p1 = scope->voltage[channel].cursor.pos[1]; - cursorDataGrid->updateInfo( unsigned( index ), true, - scope->voltage[channel].cursor.shape != DsoSettingsScopeCursor::NONE ? tr("ON") : tr("OFF"), - valueToString(fabs(p1.x() - p0.x()) * scope->horizontal.timebase, UNIT_SECONDS, 4), - valueToString(fabs(p1.y() - p0.y()) * scope->gain(channel), UNIT_VOLTS, 4)); + QPointF p0 = scope->voltage[ channel ].cursor.pos[ 0 ]; + QPointF p1 = scope->voltage[ channel ].cursor.pos[ 1 ]; + cursorDataGrid->updateInfo( + unsigned( index ), true, + scope->voltage[ channel ].cursor.shape != DsoSettingsScopeCursor::NONE ? tr( "ON" ) : tr( "OFF" ), + valueToString( fabs( p1.x() - p0.x() ) * scope->horizontal.timebase, UNIT_SECONDS, 4 ), + valueToString( fabs( p1.y() - p0.y() ) * scope->gain( channel ), UNIT_VOLTS, 4 ) ); } else { cursorDataGrid->updateInfo( unsigned( index ), false ); } ++index; } - for (ChannelID channel = 0; channel < scope->spectrum.size(); ++channel) { - if (scope->spectrum[channel].used) { + for ( ChannelID channel = 0; channel < scope->spectrum.size(); ++channel ) { + if ( scope->spectrum[ channel ].used ) { freqUsed = true; // at least one spec channel used -> show marker freq details - QPointF p0 = scope->spectrum[channel].cursor.pos[0]; - QPointF p1 = scope->spectrum[channel].cursor.pos[1]; - cursorDataGrid->updateInfo( unsigned( index ), true, - scope->spectrum[channel].cursor.shape != DsoSettingsScopeCursor::NONE ? tr("ON") : tr("OFF"), - valueToString(fabs(p1.x() - p0.x()) * scope->horizontal.frequencybase, UNIT_HERTZ, 4), - valueToString(fabs(p1.y() - p0.y()) * scope->spectrum[channel].magnitude, UNIT_DECIBEL, 4)); + QPointF p0 = scope->spectrum[ channel ].cursor.pos[ 0 ]; + QPointF p1 = scope->spectrum[ channel ].cursor.pos[ 1 ]; + cursorDataGrid->updateInfo( + unsigned( index ), true, + scope->spectrum[ channel ].cursor.shape != DsoSettingsScopeCursor::NONE ? tr( "ON" ) : tr( "OFF" ), + valueToString( fabs( p1.x() - p0.x() ) * scope->horizontal.frequencybase, UNIT_HERTZ, 4 ), + valueToString( fabs( p1.y() - p0.y() ) * scope->spectrum[ channel ].magnitude, UNIT_DECIBEL, 4 ) ); } else { cursorDataGrid->updateInfo( unsigned( index ), false ); } ++index; } - if ( divs >= DIVS_TIME || ( m1 <= 0 && m2 <= 0) || ( m1 >= DIVS_TIME && m2 >= DIVS_TIME) ) { + if ( divs >= DIVS_TIME || ( m1 <= 0 && m2 <= 0 ) || ( m1 >= DIVS_TIME && m2 >= DIVS_TIME ) ) { // markers at left/right margins -> don't display markerInfoLabel->setVisible( false ); markerTimeLabel->setVisible( false ); @@ -483,41 +491,37 @@ void DsoWidget::updateMarkerDetails() { markerFrequencyLabel->setVisible( true ); markerTimebaseLabel->setVisible( view->zoom ); markerFrequencybaseLabel->setVisible( view->zoom ); - QString mInfo( tr( "Markers ") ); - QString mTime( tr( "Time: ") ); - QString mFreq( tr( "Frequency: ") ); - if (view->zoom) { + QString mInfo( tr( "Markers " ) ); + QString mTime( tr( "Time: " ) ); + QString mFreq( tr( "Frequency: " ) ); + if ( view->zoom ) { if ( divs != 0.0 ) mInfo = tr( "Zoom x%L1 " ).arg( DIVS_TIME / divs, -1, 'g', 3 ); else // avoid div by zero mInfo = tr( "Zoom --- " ); mTime = " t: "; mFreq = " f: "; - markerTimebaseLabel->setText(" " + valueToString( time / DIVS_TIME, UNIT_SECONDS, 3 ) + tr("/div")); + markerTimebaseLabel->setText( " " + valueToString( time / DIVS_TIME, UNIT_SECONDS, 3 ) + tr( "/div" ) ); markerTimebaseLabel->setVisible( timeUsed ); - markerFrequencybaseLabel->setText( " " + valueToString( freq / DIVS_TIME, UNIT_HERTZ, 3 ) + tr("/div")); + markerFrequencybaseLabel->setText( " " + valueToString( freq / DIVS_TIME, UNIT_HERTZ, 3 ) + tr( "/div" ) ); markerFrequencybaseLabel->setVisible( freqUsed ); } markerInfoLabel->setText( mInfo ); if ( timeUsed ) { mTime += QString( "%1" ).arg( valueToString( time0, UNIT_SECONDS, 3 ) ); if ( time > 0 ) - mTime += QString( " ... %1, Δt: %2 (%3) ") - .arg( valueToString( time1, UNIT_SECONDS, 3 ), - valueToString( time, UNIT_SECONDS, 3 ), - valueToString( 1/time, UNIT_HERTZ, 3) ) - ; + mTime += QString( " ... %1, Δt: %2 (%3) " ) + .arg( valueToString( time1, UNIT_SECONDS, 3 ), valueToString( time, UNIT_SECONDS, 3 ), + valueToString( 1 / time, UNIT_HERTZ, 3 ) ); markerTimeLabel->setText( mTime ); } else { markerTimeLabel->setText( "" ); } if ( freqUsed ) { - mFreq += QString( "%1" ).arg( valueToString( freq0, UNIT_HERTZ, 3 ) ); + mFreq += QString( "%1" ).arg( valueToString( freq0, UNIT_HERTZ, 3 ) ); if ( freq > 0 ) mFreq += QString( " ... %2, Δf: %3 " ) - .arg( valueToString( freq1, UNIT_HERTZ, 3 ), - valueToString( freq, UNIT_HERTZ, 3 ) ) - ; + .arg( valueToString( freq1, UNIT_HERTZ, 3 ), valueToString( freq, UNIT_HERTZ, 3 ) ); markerFrequencyLabel->setText( mFreq ); } else markerFrequencyLabel->setText( "" ); @@ -525,96 +529,97 @@ void DsoWidget::updateMarkerDetails() { } /// \brief Update the label about the trigger settings -void DsoWidget::updateSpectrumDetails(ChannelID channel) { - setMeasurementVisible(channel); +void DsoWidget::updateSpectrumDetails( ChannelID channel ) { + setMeasurementVisible( channel ); - if (scope->spectrum[channel].used) - measurementMagnitudeLabel[channel]->setText(valueToString(scope->spectrum[channel].magnitude, UNIT_DECIBEL, 3) + - tr("/div")); + if ( scope->spectrum[ channel ].used ) + measurementMagnitudeLabel[ channel ]->setText( + valueToString( scope->spectrum[ channel ].magnitude, UNIT_DECIBEL, 3 ) + tr( "/div" ) ); else - measurementMagnitudeLabel[channel]->setText(QString()); + measurementMagnitudeLabel[ channel ]->setText( QString() ); } /// \brief Update the label about the trigger settings void DsoWidget::updateTriggerDetails() { // Update the trigger details QPalette tablePalette = palette(); - tablePalette.setColor(QPalette::WindowText, view->screen.voltage[scope->trigger.source]); - settingsTriggerLabel->setPalette(tablePalette); - QString levelString = valueToString(scope->voltage[scope->trigger.source].trigger, UNIT_VOLTS, 3); - QString pretriggerString = tr("%L1%").arg( int( round(scope->trigger.offset * 100 ) ) ); - QString pre = Dso::slopeString(scope->trigger.slope); // trigger slope - QString post = pre; // opposite trigger slope + tablePalette.setColor( QPalette::WindowText, view->screen.voltage[ scope->trigger.source ] ); + settingsTriggerLabel->setPalette( tablePalette ); + QString levelString = valueToString( scope->voltage[ scope->trigger.source ].trigger, UNIT_VOLTS, 3 ); + QString pretriggerString = tr( "%L1%" ).arg( int( round( scope->trigger.offset * 100 ) ) ); + QString pre = Dso::slopeString( scope->trigger.slope ); // trigger slope + QString post = pre; // opposite trigger slope if ( scope->trigger.slope == Dso::Slope::Positive ) - post = Dso::slopeString( Dso::Slope:: Negative ); + post = Dso::slopeString( Dso::Slope::Negative ); else if ( scope->trigger.slope == Dso::Slope::Negative ) - post = Dso::slopeString( Dso::Slope:: Positive ); - QString pulseWidthString = bool( pulseWidth1 ) ? pre + valueToString( pulseWidth1, UNIT_SECONDS, 3) + post : ""; - pulseWidthString += bool( pulseWidth2 )? valueToString( pulseWidth2, UNIT_SECONDS, 3) + pre : ""; + post = Dso::slopeString( Dso::Slope::Positive ); + QString pulseWidthString = bool( pulseWidth1 ) ? pre + valueToString( pulseWidth1, UNIT_SECONDS, 3 ) + post : ""; + pulseWidthString += bool( pulseWidth2 ) ? valueToString( pulseWidth2, UNIT_SECONDS, 3 ) + pre : ""; if ( bool( pulseWidth1 ) && bool( pulseWidth2 ) ) { - int dutyCyle = int( 0.5 + ( 100.0 * pulseWidth1 ) / (pulseWidth1 + pulseWidth2) ); + int dutyCyle = int( 0.5 + ( 100.0 * pulseWidth1 ) / ( pulseWidth1 + pulseWidth2 ) ); pulseWidthString += " (" + QString::number( dutyCyle ) + "%)"; } settingsTriggerLabel->setText( tr( "%1 %2 %3 %4 %5" ) - .arg( scope->voltage[scope->trigger.source].name, - Dso::slopeString(scope->trigger.slope), - levelString, pretriggerString, pulseWidthString - ) - ); + .arg( scope->voltage[ scope->trigger.source ].name, + Dso::slopeString( scope->trigger.slope ), levelString, pretriggerString, + pulseWidthString ) ); } /// \brief Update the label about the trigger settings -void DsoWidget::updateVoltageDetails(ChannelID channel) { - if (channel >= scope->voltage.size()) return; +void DsoWidget::updateVoltageDetails( ChannelID channel ) { + if ( channel >= scope->voltage.size() ) + return; - setMeasurementVisible(channel); + setMeasurementVisible( channel ); - if (scope->voltage[channel].used) - measurementGainLabel[channel]->setText(valueToString(scope->gain(channel), UNIT_VOLTS, 3) + tr("/div")); + if ( scope->voltage[ channel ].used ) + measurementGainLabel[ channel ]->setText( valueToString( scope->gain( channel ), UNIT_VOLTS, 3 ) + + tr( "/div" ) ); else - measurementGainLabel[channel]->setText(QString()); + measurementGainLabel[ channel ]->setText( QString() ); } /// \brief Handles frequencybaseChanged signal from the horizontal dock. /// \param frequencybase The frequencybase used for displaying the trace. -void DsoWidget::updateFrequencybase(double frequencybase) { - settingsFrequencybaseLabel->setText(valueToString(frequencybase, UNIT_HERTZ, -1) + tr("/div")); +void DsoWidget::updateFrequencybase( double frequencybase ) { + settingsFrequencybaseLabel->setText( valueToString( frequencybase, UNIT_HERTZ, -1 ) + tr( "/div" ) ); updateMarkerDetails(); } /// \brief Updates the samplerate field after changing the samplerate. /// \param samplerate The samplerate set in the oscilloscope. -void DsoWidget::updateSamplerate(double newSamplerate) { +void DsoWidget::updateSamplerate( double newSamplerate ) { samplerate = newSamplerate; dotsOnScreen = unsigned( samplerate * timebase * DIVS_TIME + 0.99 ); - //printf( "DsoWidget::updateSamplerate( %g ) -> %d\n", samplerate, dotsOnScreen ); - settingsSamplerateLabel->setText(valueToString(samplerate, UNIT_SAMPLES, -1) + tr("/s")); + // printf( "DsoWidget::updateSamplerate( %g ) -> %d\n", samplerate, dotsOnScreen ); + settingsSamplerateLabel->setText( valueToString( samplerate, UNIT_SAMPLES, -1 ) + tr( "/s" ) ); } /// \brief Handles timebaseChanged signal from the horizontal dock. /// \param timebase The timebase used for displaying the trace. -void DsoWidget::updateTimebase(double newTimebase) { +void DsoWidget::updateTimebase( double newTimebase ) { timebase = newTimebase; dotsOnScreen = unsigned( samplerate * timebase * DIVS_TIME + 0.99 ); - //printf( "DsoWidget::updateTimebase( %g ) -> %d\n", timebase, dotsOnScreen ); - settingsTimebaseLabel->setText(valueToString(timebase, UNIT_SECONDS, -1) + tr("/div")); + // printf( "DsoWidget::updateTimebase( %g ) -> %d\n", timebase, dotsOnScreen ); + settingsTimebaseLabel->setText( valueToString( timebase, UNIT_SECONDS, -1 ) + tr( "/div" ) ); updateMarkerDetails(); } /// \brief Handles magnitudeChanged signal from the spectrum dock. /// \param channel The channel whose magnitude was changed. -void DsoWidget::updateSpectrumMagnitude(ChannelID channel) { updateSpectrumDetails(channel); } +void DsoWidget::updateSpectrumMagnitude( ChannelID channel ) { updateSpectrumDetails( channel ); } /// \brief Handles usedChanged signal from the spectrum dock. /// \param channel The channel whose used-state was changed. /// \param used The new used-state for the channel. -void DsoWidget::updateSpectrumUsed(ChannelID channel, bool used) { - if (channel >= unsigned( scope->voltage.size() ) ) return; +void DsoWidget::updateSpectrumUsed( ChannelID channel, bool used ) { + if ( channel >= unsigned( scope->voltage.size() ) ) + return; mainSliders.voltageOffsetSlider->setIndexVisible( unsigned( scope->voltage.size() ) + channel, used ); zoomSliders.voltageOffsetSlider->setIndexVisible( unsigned( scope->voltage.size() ) + channel, used ); - updateSpectrumDetails(channel); + updateSpectrumDetails( channel ); updateMarkerDetails(); } @@ -627,15 +632,14 @@ void DsoWidget::updateTriggerSlope() { updateTriggerDetails(); } /// \brief Handles sourceChanged signal from the trigger dock. void DsoWidget::updateTriggerSource() { // Change the colors of the trigger sliders - mainSliders.triggerOffsetSlider->setColor(0, view->screen.voltage[scope->trigger.source]); - zoomSliders.triggerOffsetSlider->setColor(0, view->screen.voltage[scope->trigger.source]); - - for (ChannelID channel = 0; channel < spec->channels; ++channel) { - QColor color = (channel == scope->trigger.source) - ? view->screen.voltage[channel] - : view->screen.voltage[channel].darker(); - mainSliders.triggerLevelSlider->setColor(channel, color); - zoomSliders.triggerLevelSlider->setColor(channel, color); + mainSliders.triggerOffsetSlider->setColor( 0, view->screen.voltage[ scope->trigger.source ] ); + zoomSliders.triggerOffsetSlider->setColor( 0, view->screen.voltage[ scope->trigger.source ] ); + + for ( ChannelID channel = 0; channel < spec->channels; ++channel ) { + QColor color = ( channel == scope->trigger.source ) ? view->screen.voltage[ channel ] + : view->screen.voltage[ channel ].darker(); + mainSliders.triggerLevelSlider->setColor( channel, color ); + zoomSliders.triggerLevelSlider->setColor( channel, color ); } updateTriggerDetails(); @@ -643,60 +647,61 @@ void DsoWidget::updateTriggerSource() { /// \brief Handles couplingChanged signal from the voltage dock. /// \param channel The channel whose coupling was changed. -void DsoWidget::updateVoltageCoupling(ChannelID channel) { +void DsoWidget::updateVoltageCoupling( ChannelID channel ) { if ( channel >= unsigned( scope->voltage.size() ) ) return; - measurementMiscLabel[channel]->setText(Dso::couplingString(scope->coupling(channel, spec))); + measurementMiscLabel[ channel ]->setText( Dso::couplingString( scope->coupling( channel, spec ) ) ); } /// \brief Handles modeChanged signal from the voltage dock. void DsoWidget::updateMathMode() { - measurementMiscLabel[spec->channels]->setText( - Dso::mathModeString(Dso::getMathMode(scope->voltage[spec->channels]))); + measurementMiscLabel[ spec->channels ]->setText( + Dso::mathModeString( Dso::getMathMode( scope->voltage[ spec->channels ] ) ) ); } /// \brief Handles gainChanged signal from the voltage dock. /// \param channel The channel whose gain was changed. -void DsoWidget::updateVoltageGain(ChannelID channel) { +void DsoWidget::updateVoltageGain( ChannelID channel ) { if ( channel >= unsigned( scope->voltage.size() ) ) return; - if (channel < spec->channels) { - adaptTriggerLevelSlider(mainSliders, channel); - adaptTriggerLevelSlider(zoomSliders, channel); + if ( channel < spec->channels ) { + adaptTriggerLevelSlider( mainSliders, channel ); + adaptTriggerLevelSlider( zoomSliders, channel ); } - updateVoltageDetails(channel); + updateVoltageDetails( channel ); } /// \brief Handles usedChanged signal from the voltage dock. /// \param channel The channel whose used-state was changed. /// \param used The new used-state for the channel. -void DsoWidget::updateVoltageUsed(ChannelID channel, bool used) { - if ( channel >= unsigned( scope->voltage.size() ) ) return; +void DsoWidget::updateVoltageUsed( ChannelID channel, bool used ) { + if ( channel >= unsigned( scope->voltage.size() ) ) + return; -// if (!used && cursorDataGrid->voltageCursors[channel].selector->isChecked()) cursorDataGrid->selectItem(0); + // if (!used && cursorDataGrid->voltageCursors[channel].selector->isChecked()) cursorDataGrid->selectItem(0); - mainSliders.voltageOffsetSlider->setIndexVisible(channel, used); - zoomSliders.voltageOffsetSlider->setIndexVisible(channel, used); + mainSliders.voltageOffsetSlider->setIndexVisible( channel, used ); + zoomSliders.voltageOffsetSlider->setIndexVisible( channel, used ); - mainSliders.triggerLevelSlider->setIndexVisible(channel, used); - zoomSliders.triggerLevelSlider->setIndexVisible(channel, used); + mainSliders.triggerLevelSlider->setIndexVisible( channel, used ); + zoomSliders.triggerLevelSlider->setIndexVisible( channel, used ); - setMeasurementVisible(channel); - updateVoltageDetails(channel); + setMeasurementVisible( channel ); + updateVoltageDetails( channel ); updateMarkerDetails(); } /// \brief Change the record length. -void DsoWidget::updateRecordLength(unsigned long size) { - settingsSamplesOnScreen->setText(valueToString(size, UNIT_SAMPLES, -1) + tr(" on screen") ); +void DsoWidget::updateRecordLength( unsigned long size ) { + settingsSamplesOnScreen->setText( valueToString( size, UNIT_SAMPLES, -1 ) + tr( " on screen" ) ); } /// \brief Show/hide the zoom view. -void DsoWidget::updateZoom(bool enabled) { - mainLayout->setRowStretch(zoomScopeRow, enabled ? 1 : 0); - zoomScope->setVisible(enabled); +void DsoWidget::updateZoom( bool enabled ) { + mainLayout->setRowStretch( zoomScopeRow, enabled ? 1 : 0 ); + zoomScope->setVisible( enabled ); - if (enabled) { + if ( enabled ) { zoomSliders.voltageOffsetSlider->show(); zoomSliders.triggerOffsetSlider->show(); zoomSliders.triggerLevelSlider->show(); @@ -707,72 +712,72 @@ void DsoWidget::updateZoom(bool enabled) { } // Show time-/frequencybase and zoom factor if the magnified scope is shown - markerLayout->setStretch(3, enabled ? 1 : 0); - markerTimebaseLabel->setVisible(enabled); - markerLayout->setStretch(4, enabled ? 1 : 0); - markerFrequencybaseLabel->setVisible(enabled); + markerLayout->setStretch( 3, enabled ? 1 : 0 ); + markerTimebaseLabel->setVisible( enabled ); + markerLayout->setStretch( 4, enabled ? 1 : 0 ); + markerFrequencybaseLabel->setVisible( enabled ); updateMarkerDetails(); repaint(); } /// \brief Prints analyzed data. -void DsoWidget::showNew(std::shared_ptr analysedData) { - mainScope->showData(analysedData); - zoomScope->showData(analysedData); +void DsoWidget::showNew( std::shared_ptr analysedData ) { + mainScope->showData( analysedData ); + zoomScope->showData( analysedData ); QPalette triggerLabelPalette = palette(); - triggerLabelPalette.setColor(QPalette::WindowText, Qt::black); - triggerLabelPalette.setColor(QPalette::Background, analysedData->softwareTriggerTriggered ? Qt::green : Qt::red); - swTriggerStatus->setPalette(triggerLabelPalette); - swTriggerStatus->setVisible(true); - updateRecordLength(dotsOnScreen); + triggerLabelPalette.setColor( QPalette::WindowText, Qt::black ); + triggerLabelPalette.setColor( QPalette::Background, analysedData->softwareTriggerTriggered ? Qt::green : Qt::red ); + swTriggerStatus->setPalette( triggerLabelPalette ); + swTriggerStatus->setVisible( true ); + updateRecordLength( dotsOnScreen ); pulseWidth1 = analysedData.get()->data( 0 )->pulseWidth1; pulseWidth2 = analysedData.get()->data( 0 )->pulseWidth2; updateTriggerDetails(); - for (ChannelID channel = 0; channel < scope->voltage.size(); ++channel) { - if (scope->voltage[channel].used && analysedData.get()->data(channel)) { + for ( ChannelID channel = 0; channel < scope->voltage.size(); ++channel ) { + if ( scope->voltage[ channel ].used && analysedData.get()->data( channel ) ) { // Vpp Amplitude string representation (3 significant digits) - measurementVppLabel[channel]->setText( - valueToString( analysedData.get()->data(channel)->vpp, UNIT_VOLTS, 3 ) + "pp" ); + measurementVppLabel[ channel ]->setText( + valueToString( analysedData.get()->data( channel )->vpp, UNIT_VOLTS, 3 ) + "pp" ); // RMS Amplitude string representation (3 significant digits) - measurementRMSLabel[channel]->setText( - valueToString( analysedData.get()->data(channel)->rms, UNIT_VOLTS, 3 ) + "rms" ); + measurementRMSLabel[ channel ]->setText( + valueToString( analysedData.get()->data( channel )->rms, UNIT_VOLTS, 3 ) + "rms" ); // DC Amplitude string representation (3 significant digits) - measurementDCLabel[channel]->setText( - valueToString( analysedData.get()->data(channel)->dc, UNIT_VOLTS, 3 ) + "=" ); + measurementDCLabel[ channel ]->setText( + valueToString( analysedData.get()->data( channel )->dc, UNIT_VOLTS, 3 ) + "=" ); // AC Amplitude string representation (3 significant digits) - measurementACLabel[channel]->setText( - valueToString( analysedData.get()->data(channel)->ac, UNIT_VOLTS, 3 ) + "~" ); + measurementACLabel[ channel ]->setText( + valueToString( analysedData.get()->data( channel )->ac, UNIT_VOLTS, 3 ) + "~" ); // dB Amplitude string representation (3 significant digits) - measurementdBLabel[channel]->setText( - valueToString( analysedData.get()->data(channel)->dB, UNIT_DECIBEL, 3 ) ); + measurementdBLabel[ channel ]->setText( + valueToString( analysedData.get()->data( channel )->dB, UNIT_DECIBEL, 3 ) ); // Frequency string representation (3 significant digits) - measurementFrequencyLabel[channel]->setText( - valueToString( analysedData.get()->data(channel)->frequency, UNIT_HERTZ, 4 ) ); + measurementFrequencyLabel[ channel ]->setText( + valueToString( analysedData.get()->data( channel )->frequency, UNIT_HERTZ, 4 ) ); // Highlight clipped channel QPalette validPalette; - if ( analysedData.get()->data(channel)->valid ) { // normal display - validPalette.setColor( QPalette::WindowText, view->screen.voltage[channel] ); + if ( analysedData.get()->data( channel )->valid ) { // normal display + validPalette.setColor( QPalette::WindowText, view->screen.voltage[ channel ] ); validPalette.setColor( QPalette::Background, view->screen.background ); } else { // warning - validPalette.setColor(QPalette::WindowText, Qt::black ); - validPalette.setColor(QPalette::Background, Qt::red ); + validPalette.setColor( QPalette::WindowText, Qt::black ); + validPalette.setColor( QPalette::Background, Qt::red ); } - measurementNameLabel[channel]->setPalette( validPalette ); + measurementNameLabel[ channel ]->setPalette( validPalette ); } } } -void DsoWidget::showEvent(QShowEvent *event) { - QWidget::showEvent(event); +void DsoWidget::showEvent( QShowEvent *event ) { + QWidget::showEvent( event ); // Apply settings and update measured values updateTriggerDetails(); - updateRecordLength(scope->horizontal.recordLength); - updateFrequencybase(scope->horizontal.frequencybase); - updateSamplerate(scope->horizontal.samplerate); - updateTimebase(scope->horizontal.timebase); - updateZoom(view->zoom); + updateRecordLength( scope->horizontal.recordLength ); + updateFrequencybase( scope->horizontal.frequencybase ); + updateSamplerate( scope->horizontal.samplerate ); + updateTimebase( scope->horizontal.timebase ); + updateZoom( view->zoom ); updateTriggerSource(); adaptTriggerOffsetSlider(); @@ -781,24 +786,26 @@ void DsoWidget::showEvent(QShowEvent *event) { /// \brief Handles valueChanged signal from the offset sliders. /// \param channel The channel whose offset was changed. /// \param value The new offset for the channel. -void DsoWidget::updateOffset(ChannelID channel, double value) { - if (channel < scope->voltage.size()) { - scope->voltage[channel].offset = value; +void DsoWidget::updateOffset( ChannelID channel, double value ) { + if ( channel < scope->voltage.size() ) { + scope->voltage[ channel ].offset = value; - if (channel < spec->channels) { - adaptTriggerLevelSlider(mainSliders, channel); - adaptTriggerLevelSlider(zoomSliders, channel); + if ( channel < spec->channels ) { + adaptTriggerLevelSlider( mainSliders, channel ); + adaptTriggerLevelSlider( zoomSliders, channel ); } - } else if (channel < scope->voltage.size() * 2) - scope->spectrum[channel - scope->voltage.size()].offset = value; + } else if ( channel < scope->voltage.size() * 2 ) + scope->spectrum[ channel - scope->voltage.size() ].offset = value; - if (channel < scope->voltage.size() * 2) { - if ( mainSliders.voltageOffsetSlider->value( int( channel ) ) != value ) { // double != comparison is safe in this case - const QSignalBlocker blocker(mainSliders.voltageOffsetSlider ); + if ( channel < scope->voltage.size() * 2 ) { + if ( mainSliders.voltageOffsetSlider->value( int( channel ) ) != + value ) { // double != comparison is safe in this case + const QSignalBlocker blocker( mainSliders.voltageOffsetSlider ); mainSliders.voltageOffsetSlider->setValue( int( channel ), value ); } - if ( zoomSliders.voltageOffsetSlider->value( int( channel ) ) != value ) { // double != comparison is safe in this case - const QSignalBlocker blocker(zoomSliders.voltageOffsetSlider ); + if ( zoomSliders.voltageOffsetSlider->value( int( channel ) ) != + value ) { // double != comparison is safe in this case + const QSignalBlocker blocker( zoomSliders.voltageOffsetSlider ); zoomSliders.voltageOffsetSlider->setValue( int( channel ), value ); } } @@ -807,19 +814,21 @@ void DsoWidget::updateOffset(ChannelID channel, double value) { } /// \brief Translate horizontal position (0..1) from main view to zoom view. -double DsoWidget::mainToZoom(double position) const { - double m1 = scope->getMarker(0); - double m2 = scope->getMarker(1); - if (m1 > m2) std::swap(m1, m2); - return ((position - 0.5) * DIVS_TIME - m1) / std::max( m2 - m1, 1e-9 ); +double DsoWidget::mainToZoom( double position ) const { + double m1 = scope->getMarker( 0 ); + double m2 = scope->getMarker( 1 ); + if ( m1 > m2 ) + std::swap( m1, m2 ); + return ( ( position - 0.5 ) * DIVS_TIME - m1 ) / std::max( m2 - m1, 1e-9 ); } /// \brief Translate horizontal position (0..1) from zoom view to main view. -double DsoWidget::zoomToMain(double position) const { - double m1 = scope->getMarker(0); - double m2 = scope->getMarker(1); - if (m1 > m2) std::swap(m1, m2); - return 0.5 + (m1 + position * (m2 - m1)) / DIVS_TIME; +double DsoWidget::zoomToMain( double position ) const { + double m1 = scope->getMarker( 0 ); + double m2 = scope->getMarker( 1 ); + if ( m1 > m2 ) + std::swap( m1, m2 ); + return 0.5 + ( m1 + position * ( m2 - m1 ) ) / DIVS_TIME; } /// \brief Handles signals affecting trigger position in the zoom view. @@ -827,16 +836,16 @@ void DsoWidget::adaptTriggerOffsetSlider() { double value = mainToZoom( scope->trigger.offset ); LevelSlider &slider = *zoomSliders.triggerOffsetSlider; - const QSignalBlocker blocker(slider); - if (slider.minimum(0) <= value && value <= slider.maximum(0)) { - slider.setEnabled(true); - slider.setValue(0, value); + const QSignalBlocker blocker( slider ); + if ( slider.minimum( 0 ) <= value && value <= slider.maximum( 0 ) ) { + slider.setEnabled( true ); + slider.setValue( 0, value ); } else { - slider.setEnabled(false); - if (value < slider.minimum(0)) { - slider.setValue(0, slider.minimum(0)); + slider.setEnabled( false ); + if ( value < slider.minimum( 0 ) ) { + slider.setValue( 0, slider.minimum( 0 ) ); } else { - slider.setValue(0, slider.maximum(0)); + slider.setValue( 0, slider.maximum( 0 ) ); } } } @@ -846,42 +855,45 @@ void DsoWidget::adaptTriggerOffsetSlider() { /// \param value The new triggerPosition in seconds relative to the first /// sample. void DsoWidget::updateTriggerOffset( int index, double value, bool mainView ) { - if (index != 0) return; + if ( index != 0 ) + return; - if (mainView) { + if ( mainView ) { scope->trigger.offset = value; adaptTriggerOffsetSlider(); } else { - scope->trigger.offset = zoomToMain(value); - const QSignalBlocker blocker(mainSliders.triggerOffsetSlider ); - mainSliders.triggerOffsetSlider->setValue(index, scope->trigger.offset ); + scope->trigger.offset = zoomToMain( value ); + const QSignalBlocker blocker( mainSliders.triggerOffsetSlider ); + mainSliders.triggerOffsetSlider->setValue( index, scope->trigger.offset ); } updateTriggerDetails(); updateMarkerDetails(); - emit triggerPositionChanged(scope->trigger.offset ); + emit triggerPositionChanged( scope->trigger.offset ); } /// \brief Handles valueChanged signal from the trigger level slider. /// \param channel The index of the slider. /// \param value The new trigger level. -void DsoWidget::updateTriggerLevel(ChannelID channel, double value) { - //printf("DW::updateTriggerLevel( %d, %g )\n", channel, value); - scope->voltage[channel].trigger = value; +void DsoWidget::updateTriggerLevel( ChannelID channel, double value ) { + // printf("DW::updateTriggerLevel( %d, %g )\n", channel, value); + scope->voltage[ channel ].trigger = value; - if ( mainSliders.triggerLevelSlider->value( int( channel ) ) != value ) { // double != comparison is safe in this case - const QSignalBlocker blocker(mainSliders.triggerLevelSlider); + if ( mainSliders.triggerLevelSlider->value( int( channel ) ) != + value ) { // double != comparison is safe in this case + const QSignalBlocker blocker( mainSliders.triggerLevelSlider ); mainSliders.triggerLevelSlider->setValue( int( channel ), value ); } - if ( zoomSliders.triggerLevelSlider->value( int( channel ) ) != value ) { // double != comparison is safe in this case - const QSignalBlocker blocker(zoomSliders.triggerLevelSlider); + if ( zoomSliders.triggerLevelSlider->value( int( channel ) ) != + value ) { // double != comparison is safe in this case + const QSignalBlocker blocker( zoomSliders.triggerLevelSlider ); zoomSliders.triggerLevelSlider->setValue( int( channel ), value ); } updateTriggerDetails(); - emit triggerLevelChanged(channel, value); + emit triggerLevelChanged( channel, value ); } /// \brief Handles valueChanged signal from the marker slider. @@ -896,51 +908,55 @@ void DsoWidget::updateMarker( unsigned marker, double value ) { /// \brief Update the sliders settings. void DsoWidget::updateSlidersSettings() { // The offset sliders for all possible channels - for (ChannelID channel = 0; channel < scope->voltage.size(); ++channel) { - updateOffset(channel, scope->voltage[channel].offset); - mainSliders.voltageOffsetSlider->setColor((channel), view->screen.voltage[channel]); - mainSliders.voltageOffsetSlider->setValue(int(channel), scope->voltage[channel].offset); - mainSliders.voltageOffsetSlider->setIndexVisible(channel, scope->voltage[channel].used); - zoomSliders.voltageOffsetSlider->setColor((channel), view->screen.voltage[channel]); - zoomSliders.voltageOffsetSlider->setValue(int(channel), scope->voltage[channel].offset); - zoomSliders.voltageOffsetSlider->setIndexVisible(channel, scope->voltage[channel].used); - - updateOffset(unsigned(scope->voltage.size() + channel), scope->spectrum[channel].offset); - mainSliders.voltageOffsetSlider->setColor(unsigned( scope->voltage.size() ) + channel, view->screen.spectrum[channel]); - mainSliders.voltageOffsetSlider->setValue(int( scope->voltage.size() + channel ), scope->spectrum[channel].offset); - mainSliders.voltageOffsetSlider->setIndexVisible(unsigned(scope->voltage.size()) + channel, scope->spectrum[channel].used); - zoomSliders.voltageOffsetSlider->setColor(unsigned( scope->voltage.size() ) + channel, view->screen.spectrum[channel]); - zoomSliders.voltageOffsetSlider->setValue(int( scope->voltage.size() + channel ), scope->spectrum[channel].offset); - zoomSliders.voltageOffsetSlider->setIndexVisible(unsigned(scope->voltage.size()) + channel, scope->spectrum[channel].used); + for ( ChannelID channel = 0; channel < scope->voltage.size(); ++channel ) { + updateOffset( channel, scope->voltage[ channel ].offset ); + mainSliders.voltageOffsetSlider->setColor( ( channel ), view->screen.voltage[ channel ] ); + mainSliders.voltageOffsetSlider->setValue( int( channel ), scope->voltage[ channel ].offset ); + mainSliders.voltageOffsetSlider->setIndexVisible( channel, scope->voltage[ channel ].used ); + zoomSliders.voltageOffsetSlider->setColor( ( channel ), view->screen.voltage[ channel ] ); + zoomSliders.voltageOffsetSlider->setValue( int( channel ), scope->voltage[ channel ].offset ); + zoomSliders.voltageOffsetSlider->setIndexVisible( channel, scope->voltage[ channel ].used ); + + updateOffset( unsigned( scope->voltage.size() + channel ), scope->spectrum[ channel ].offset ); + mainSliders.voltageOffsetSlider->setColor( unsigned( scope->voltage.size() ) + channel, + view->screen.spectrum[ channel ] ); + mainSliders.voltageOffsetSlider->setValue( int( scope->voltage.size() + channel ), + scope->spectrum[ channel ].offset ); + mainSliders.voltageOffsetSlider->setIndexVisible( unsigned( scope->voltage.size() ) + channel, + scope->spectrum[ channel ].used ); + zoomSliders.voltageOffsetSlider->setColor( unsigned( scope->voltage.size() ) + channel, + view->screen.spectrum[ channel ] ); + zoomSliders.voltageOffsetSlider->setValue( int( scope->voltage.size() + channel ), + scope->spectrum[ channel ].offset ); + zoomSliders.voltageOffsetSlider->setIndexVisible( unsigned( scope->voltage.size() ) + channel, + scope->spectrum[ channel ].used ); } // The trigger position slider - mainSliders.triggerOffsetSlider->setValue(0, scope->trigger.offset ); - updateTriggerOffset(0, scope->trigger.offset, true); - updateTriggerOffset(0, scope->trigger.offset, false); + mainSliders.triggerOffsetSlider->setValue( 0, scope->trigger.offset ); + updateTriggerOffset( 0, scope->trigger.offset, true ); + updateTriggerOffset( 0, scope->trigger.offset, false ); // The sliders for the trigger levels - for (ChannelID channel = 0; channel < spec->channels; ++channel) { - mainSliders.triggerLevelSlider->setValue(int(channel), scope->voltage[channel].trigger); - adaptTriggerLevelSlider(mainSliders, channel); - mainSliders.triggerLevelSlider->setColor(channel, - (channel == scope->trigger.source) - ? view->screen.voltage[channel] - : view->screen.voltage[channel].darker()); - mainSliders.triggerLevelSlider->setIndexVisible(channel, scope->voltage[channel].used); - zoomSliders.triggerLevelSlider->setValue(int(channel), scope->voltage[channel].trigger); - adaptTriggerLevelSlider(zoomSliders, channel); - zoomSliders.triggerLevelSlider->setColor(channel, - (channel == scope->trigger.source) - ? view->screen.voltage[channel] - : view->screen.voltage[channel].darker()); - zoomSliders.triggerLevelSlider->setIndexVisible(channel, scope->voltage[channel].used); + for ( ChannelID channel = 0; channel < spec->channels; ++channel ) { + mainSliders.triggerLevelSlider->setValue( int( channel ), scope->voltage[ channel ].trigger ); + adaptTriggerLevelSlider( mainSliders, channel ); + mainSliders.triggerLevelSlider->setColor( channel, ( channel == scope->trigger.source ) + ? view->screen.voltage[ channel ] + : view->screen.voltage[ channel ].darker() ); + mainSliders.triggerLevelSlider->setIndexVisible( channel, scope->voltage[ channel ].used ); + zoomSliders.triggerLevelSlider->setValue( int( channel ), scope->voltage[ channel ].trigger ); + adaptTriggerLevelSlider( zoomSliders, channel ); + zoomSliders.triggerLevelSlider->setColor( channel, ( channel == scope->trigger.source ) + ? view->screen.voltage[ channel ] + : view->screen.voltage[ channel ].darker() ); + zoomSliders.triggerLevelSlider->setIndexVisible( channel, scope->voltage[ channel ].used ); } updateTriggerDetails(); // The marker slider - for (int marker = 0; marker < MARKER_COUNT; ++marker) { - mainSliders.markerSlider->setValue(marker, scope->horizontal.cursor.pos[marker].x()); + for ( int marker = 0; marker < MARKER_COUNT; ++marker ) { + mainSliders.markerSlider->setValue( marker, scope->horizontal.cursor.pos[ marker ].x() ); } updateMarkerDetails(); } diff --git a/openhantek/src/dsowidget.h b/openhantek/src/dsowidget.h index 26871ce3..229da91e 100644 --- a/openhantek/src/dsowidget.h +++ b/openhantek/src/dsowidget.h @@ -2,15 +2,15 @@ #pragma once +#include #include #include #include -#include #include #include "glscope.h" -#include "levelslider.h" #include "hantekdso/controlspecification.h" +#include "levelslider.h" class SpectrumGenerator; struct DsoSettingsScope; @@ -24,10 +24,10 @@ class DsoWidget : public QWidget { public: struct Sliders { - LevelSlider *voltageOffsetSlider; ///< The sliders for the graph offsets - LevelSlider *triggerOffsetSlider; ///< The slider for the pretrigger - LevelSlider *triggerLevelSlider; ///< The sliders for the trigger level - LevelSlider *markerSlider; ///< The sliders for the markers + LevelSlider *voltageOffsetSlider; ///< The sliders for the graph offsets + LevelSlider *triggerOffsetSlider; ///< The slider for the pretrigger + LevelSlider *triggerLevelSlider; ///< The sliders for the trigger level + LevelSlider *markerSlider; ///< The sliders for the markers }; /// \brief Initializes the components of the oszilloscope-screen. @@ -35,29 +35,30 @@ class DsoWidget : public QWidget { /// \param dataAnalyzer The data analyzer that should be used as data source. /// \param parent The parent widget. /// \param flags Flags for the window manager. - DsoWidget(DsoSettingsScope* scope, DsoSettingsView* view, const Dso::ControlSpecification* spec, QWidget *parent = nullptr, Qt::WindowFlags flags = nullptr); + DsoWidget( DsoSettingsScope *scope, DsoSettingsView *view, const Dso::ControlSpecification *spec, + QWidget *parent = nullptr, Qt::WindowFlags flags = nullptr ); // Data arrived - void showNew(std::shared_ptr analysedData); + void showNew( std::shared_ptr analysedData ); protected: - virtual void showEvent(QShowEvent *event); - void setupSliders(Sliders &sliders); - void adaptTriggerLevelSlider(DsoWidget::Sliders &sliders, ChannelID channel); + virtual void showEvent( QShowEvent *event ); + void setupSliders( Sliders &sliders ); + void adaptTriggerLevelSlider( DsoWidget::Sliders &sliders, ChannelID channel ); void adaptTriggerOffsetSlider(); - void setMeasurementVisible(ChannelID channel); + void setMeasurementVisible( ChannelID channel ); void updateMarkerDetails(); - void updateSpectrumDetails(ChannelID channel); + void updateSpectrumDetails( ChannelID channel ); void updateTriggerDetails(); - void updateVoltageDetails(ChannelID channel); + void updateVoltageDetails( ChannelID channel ); - double mainToZoom(double position) const; - double zoomToMain(double position) const; + double mainToZoom( double position ) const; + double zoomToMain( double position ) const; Sliders mainSliders; Sliders zoomSliders; - QGridLayout *mainLayout; ///< The main layout for this widget + QGridLayout *mainLayout; ///< The main layout for this widget QHBoxLayout *settingsLayout; ///< The table for the settings info QLabel *settingsTriggerLabel; ///< The trigger details @@ -66,7 +67,7 @@ class DsoWidget : public QWidget { QLabel *settingsTimebaseLabel; ///< The timebase of the main scope QLabel *settingsFrequencybaseLabel; ///< The frequencybase of the main scope - QLabel *swTriggerStatus; ///< The status of SW trigger + QLabel *swTriggerStatus; ///< The status of SW trigger QHBoxLayout *markerLayout; ///< The table for the marker details QLabel *markerInfoLabel; ///< The info about the zoom factor @@ -75,7 +76,7 @@ class DsoWidget : public QWidget { QLabel *markerTimebaseLabel; ///< The timebase for the zoomed scope QLabel *markerFrequencybaseLabel; ///< The frequencybase for the zoomed scope - QGridLayout *measurementLayout; ///< The table for the signal details + QGridLayout *measurementLayout; ///< The table for the signal details std::vector measurementNameLabel; ///< The name of the channel std::vector measurementGainLabel; ///< The gain for the voltage (V/div) std::vector measurementMagnitudeLabel; ///< The magnitude for the spectrum (dB/div) @@ -89,12 +90,12 @@ class DsoWidget : public QWidget { DataGrid *cursorDataGrid; - DsoSettingsScope* scope; - DsoSettingsView* view; - const Dso::ControlSpecification* spec; + DsoSettingsScope *scope; + DsoSettingsView *view; + const Dso::ControlSpecification *spec; - GlScope *mainScope; ///< The main scope screen - GlScope *zoomScope; ///< The optional magnified scope screen + GlScope *mainScope; ///< The main scope screen + GlScope *zoomScope; ///< The optional magnified scope screen private: double samplerate; @@ -106,9 +107,9 @@ class DsoWidget : public QWidget { public slots: // Horizontal axis // void horizontalFormatChanged(HorizontalFormat format); - void updateFrequencybase(double frequencybase); - void updateSamplerate(double samplerate); - void updateTimebase(double timebase); + void updateFrequencybase( double frequencybase ); + void updateSamplerate( double samplerate ); + void updateTimebase( double timebase ); // Trigger void updateTriggerMode(); @@ -116,35 +117,35 @@ class DsoWidget : public QWidget { void updateTriggerSource(); // Spectrum - void updateSpectrumMagnitude(ChannelID channel); - void updateSpectrumUsed(ChannelID channel, bool used); + void updateSpectrumMagnitude( ChannelID channel ); + void updateSpectrumUsed( ChannelID channel, bool used ); // Vertical axis - void updateVoltageCoupling(ChannelID channel); + void updateVoltageCoupling( ChannelID channel ); void updateMathMode(); - void updateVoltageGain(ChannelID channel); - void updateVoltageUsed(ChannelID channel, bool used); + void updateVoltageGain( ChannelID channel ); + void updateVoltageUsed( ChannelID channel, bool used ); // Menus - void updateRecordLength(unsigned long size); + void updateRecordLength( unsigned long size ); // Scope control - void updateZoom(bool enabled); - void updateCursorGrid(bool enabled); + void updateZoom( bool enabled ); + void updateCursorGrid( bool enabled ); // Scope control void updateSlidersSettings(); private slots: // Sliders - void updateOffset(ChannelID channel, double value); - void updateTriggerOffset(int index, double value, bool mainView = true); - void updateTriggerLevel(ChannelID channel, double value); - void updateMarker( unsigned marker, double value); + void updateOffset( ChannelID channel, double value ); + void updateTriggerOffset( int index, double value, bool mainView = true ); + void updateTriggerLevel( ChannelID channel, double value ); + void updateMarker( unsigned marker, double value ); signals: // Sliders - void voltageOffsetChanged (ChannelID channel, double value); ///< A graph offset has been changed - void triggerPositionChanged(double value); ///< The pretrigger has been changed - void triggerLevelChanged(ChannelID channel, double value); ///< A trigger level has been changed + void voltageOffsetChanged( ChannelID channel, double value ); ///< A graph offset has been changed + void triggerPositionChanged( double value ); ///< The pretrigger has been changed + void triggerLevelChanged( ChannelID channel, double value ); ///< A trigger level has been changed }; diff --git a/openhantek/src/exporting/exportcsv.cpp b/openhantek/src/exporting/exportcsv.cpp index 077f9e3f..beb66512 100644 --- a/openhantek/src/exporting/exportcsv.cpp +++ b/openhantek/src/exporting/exportcsv.cpp @@ -1,51 +1,56 @@ // SPDX-License-Identifier: GPL-2.0+ #include "exportcsv.h" -#include "exporterregistry.h" -#include "post/ppresult.h" #include "dsosettings.h" +#include "exporterregistry.h" #include "iconfont/QtAwesome.h" +#include "post/ppresult.h" #include -#include #include #include #include +#include ExporterCSV::ExporterCSV() {} -void ExporterCSV::create(ExporterRegistry *newRegistry) { this->registry = newRegistry; data.reset(); } +void ExporterCSV::create( ExporterRegistry *newRegistry ) { + this->registry = newRegistry; + data.reset(); +} int ExporterCSV::faIcon() { return fa::filetexto; } -QString ExporterCSV::name() { return QCoreApplication::tr("Export CSV .."); } +QString ExporterCSV::name() { return QCoreApplication::tr( "Export CSV .." ); } ExporterInterface::Type ExporterCSV::type() { return Type::SnapshotExport; } -bool ExporterCSV::samples(const std::shared_ptr newData) { - data = std::move(newData); +bool ExporterCSV::samples( const std::shared_ptr newData ) { + data = std::move( newData ); return false; } bool ExporterCSV::save() { QStringList filters; - filters << QCoreApplication::tr("Comma-Separated Values (*.csv)"); + filters << QCoreApplication::tr( "Comma-Separated Values (*.csv)" ); - QFileDialog fileDialog(nullptr, QCoreApplication::tr("Export file .."), QString(), filters.join(";;")); - fileDialog.setFileMode(QFileDialog::AnyFile); - fileDialog.setAcceptMode(QFileDialog::AcceptSave); - if (fileDialog.exec() != QDialog::Accepted) return false; + QFileDialog fileDialog( nullptr, QCoreApplication::tr( "Export file .." ), QString(), filters.join( ";;" ) ); + fileDialog.setFileMode( QFileDialog::AnyFile ); + fileDialog.setAcceptMode( QFileDialog::AcceptSave ); + if ( fileDialog.exec() != QDialog::Accepted ) + return false; - QFile csvFile(fileDialog.selectedFiles().first()); - if (!csvFile.open(QIODevice::WriteOnly | QIODevice::Text)) return false; + QFile csvFile( fileDialog.selectedFiles().first() ); + if ( !csvFile.open( QIODevice::WriteOnly | QIODevice::Text ) ) + return false; - QTextStream csvStream(&csvFile); - csvStream.setRealNumberNotation(QTextStream::FixedNotation); - csvStream.setRealNumberPrecision(10); + QTextStream csvStream( &csvFile ); + csvStream.setRealNumberNotation( QTextStream::FixedNotation ); + csvStream.setRealNumberPrecision( 10 ); size_t chCount = registry->settings->scope.voltage.size(); - std::vector voltageData(size_t(chCount), nullptr); - std::vector spectrumData(size_t(chCount), nullptr); + std::vector voltageData( size_t( chCount ), nullptr ); + std::vector spectrumData( size_t( chCount ), nullptr ); size_t maxRow = 0; bool isSpectrumUsed = false; double timeInterval = 0; @@ -54,17 +59,17 @@ bool ExporterCSV::save() { // use semicolon as data separator if comma is already used as decimal separator - e.g. with german locale const char *sep = QLocale::system().decimalPoint() == ',' ? ";" : ","; - for (ChannelID channel = 0; channel < chCount; ++channel) { - if (data->data(channel)) { - if (registry->settings->scope.voltage[channel].used) { - voltageData[channel] = &(data->data(channel)->voltage); - maxRow = std::max(maxRow, voltageData[channel]->sample.size()); - timeInterval = data->data(channel)->voltage.interval; + for ( ChannelID channel = 0; channel < chCount; ++channel ) { + if ( data->data( channel ) ) { + if ( registry->settings->scope.voltage[ channel ].used ) { + voltageData[ channel ] = &( data->data( channel )->voltage ); + maxRow = std::max( maxRow, voltageData[ channel ]->sample.size() ); + timeInterval = data->data( channel )->voltage.interval; } - if (registry->settings->scope.spectrum[channel].used) { - spectrumData[channel] = &(data->data(channel)->spectrum); - maxRow = std::max(maxRow, spectrumData[channel]->sample.size()); - freqInterval = data->data(channel)->spectrum.interval; + if ( registry->settings->scope.spectrum[ channel ].used ) { + spectrumData[ channel ] = &( data->data( channel )->spectrum ); + maxRow = std::max( maxRow, spectrumData[ channel ]->sample.size() ); + freqInterval = data->data( channel )->spectrum.interval; isSpectrumUsed = true; } } @@ -72,39 +77,39 @@ bool ExporterCSV::save() { // Start with channel names csvStream << "\"t / s\""; - for (ChannelID channel = 0; channel < chCount; ++channel) { - if (voltageData[channel] != nullptr) { - csvStream << sep << "\"" << registry->settings->scope.voltage[channel].name << " / V\""; + for ( ChannelID channel = 0; channel < chCount; ++channel ) { + if ( voltageData[ channel ] != nullptr ) { + csvStream << sep << "\"" << registry->settings->scope.voltage[ channel ].name << " / V\""; } } - if (isSpectrumUsed) { + if ( isSpectrumUsed ) { csvStream << sep << "\"f / Hz\""; - for (ChannelID channel = 0; channel < chCount; ++channel) { - if (spectrumData[channel] != nullptr) { - csvStream << sep << "\"" << registry->settings->scope.spectrum[channel].name << " / dB\""; + for ( ChannelID channel = 0; channel < chCount; ++channel ) { + if ( spectrumData[ channel ] != nullptr ) { + csvStream << sep << "\"" << registry->settings->scope.spectrum[ channel ].name << " / dB\""; } } } csvStream << "\n"; - for (unsigned int row = 0; row < maxRow; ++row) { + for ( unsigned int row = 0; row < maxRow; ++row ) { csvStream << QLocale::system().toString( timeInterval * row ); - for (ChannelID channel = 0; channel < chCount; ++channel) { - if (voltageData[channel] != nullptr) { + for ( ChannelID channel = 0; channel < chCount; ++channel ) { + if ( voltageData[ channel ] != nullptr ) { csvStream << sep; - if (row < voltageData[channel]->sample.size()) { - csvStream << QLocale::system().toString( voltageData[channel]->sample[row] ); + if ( row < voltageData[ channel ]->sample.size() ) { + csvStream << QLocale::system().toString( voltageData[ channel ]->sample[ row ] ); } } } - if (isSpectrumUsed) { + if ( isSpectrumUsed ) { csvStream << sep << QLocale::system().toString( freqInterval * row ); - for (ChannelID channel = 0; channel < chCount; ++channel) { - if (spectrumData[channel] != nullptr) { + for ( ChannelID channel = 0; channel < chCount; ++channel ) { + if ( spectrumData[ channel ] != nullptr ) { csvStream << sep; - if (row < spectrumData[channel]->sample.size()) { - csvStream << QLocale::system().toString( spectrumData[channel]->sample[row] ); + if ( row < spectrumData[ channel ]->sample.size() ) { + csvStream << QLocale::system().toString( spectrumData[ channel ]->sample[ row ] ); } } } @@ -118,6 +123,4 @@ bool ExporterCSV::save() { } -float ExporterCSV::progress() { - return data ? 1.0f : 0; -} +float ExporterCSV::progress() { return data ? 1.0f : 0; } diff --git a/openhantek/src/exporting/exportcsv.h b/openhantek/src/exporting/exportcsv.h index c6e3a1cc..e8270709 100644 --- a/openhantek/src/exporting/exportcsv.h +++ b/openhantek/src/exporting/exportcsv.h @@ -3,17 +3,17 @@ #pragma once #include "exporterinterface.h" -class ExporterCSV : public ExporterInterface -{ -public: +class ExporterCSV : public ExporterInterface { + public: ExporterCSV(); - void create(ExporterRegistry *registry) override; + void create( ExporterRegistry *registry ) override; int faIcon() override; QString name() override; Type type() override; - bool samples(const std::shared_ptrnewData) override; + bool samples( const std::shared_ptr newData ) override; bool save() override; float progress() override; -private: + + private: std::shared_ptr data; }; diff --git a/openhantek/src/exporting/exporterinterface.h b/openhantek/src/exporting/exporterinterface.h index e804134b..7bee5935 100644 --- a/openhantek/src/exporting/exporterinterface.h +++ b/openhantek/src/exporting/exporterinterface.h @@ -15,15 +15,15 @@ class PPresult; * in the main routine to make an Exporter available. */ class ExporterInterface { -public: + public: /** - * Starts up this exporter. Aquires resources etc. Do not call this directly, it - * will be called by the exporter registry at some point. Release your resources in the - * destructor as usual. - * @param registry The exporter registry instance. This is used to obtain a reference - * to the settings. - */ - virtual void create(ExporterRegistry *registry) = 0; + * Starts up this exporter. Aquires resources etc. Do not call this directly, it + * will be called by the exporter registry at some point. Release your resources in the + * destructor as usual. + * @param registry The exporter registry instance. This is used to obtain a reference + * to the settings. + */ + virtual void create( ExporterRegistry *registry ) = 0; /** * @return Return the icon representation of this exporter. Will be used in graphical @@ -53,7 +53,7 @@ class ExporterInterface { * If it is a snapshot exporter, only one set of samples will be received. * @return Return true if you want to receive another sample or false if you are done (progres()==1). */ - virtual bool samples(const std::shared_ptr) = 0; + virtual bool samples( const std::shared_ptr ) = 0; /** * Exporter: Save your received data and perform any conversions necessary. @@ -73,6 +73,6 @@ class ExporterInterface { */ virtual float progress() = 0; -protected: + protected: ExporterRegistry *registry; }; diff --git a/openhantek/src/exporting/exporterprocessor.cpp b/openhantek/src/exporting/exporterprocessor.cpp index 0524867b..71c52dd3 100644 --- a/openhantek/src/exporting/exporterprocessor.cpp +++ b/openhantek/src/exporting/exporterprocessor.cpp @@ -3,6 +3,6 @@ #include "exporterprocessor.h" #include "exporterregistry.h" -ExporterProcessor::ExporterProcessor(ExporterRegistry *registry) : registry(registry) {} +ExporterProcessor::ExporterProcessor( ExporterRegistry *registry ) : registry( registry ) {} -void ExporterProcessor::process(PPresult *data) { registry->addRawSamples(data); } +void ExporterProcessor::process( PPresult *data ) { registry->addRawSamples( data ); } diff --git a/openhantek/src/exporting/exporterprocessor.h b/openhantek/src/exporting/exporterprocessor.h index 215a5071..3250a890 100644 --- a/openhantek/src/exporting/exporterprocessor.h +++ b/openhantek/src/exporting/exporterprocessor.h @@ -6,11 +6,11 @@ class ExporterRegistry; -class ExporterProcessor : public Processor -{ -public: - explicit ExporterProcessor(ExporterRegistry* registry); - void process(PPresult *) override; -private: - ExporterRegistry* registry; +class ExporterProcessor : public Processor { + public: + explicit ExporterProcessor( ExporterRegistry *registry ); + void process( PPresult * ) override; + + private: + ExporterRegistry *registry; }; diff --git a/openhantek/src/exporting/exporterregistry.cpp b/openhantek/src/exporting/exporterregistry.cpp index 365059ec..d84180b8 100644 --- a/openhantek/src/exporting/exporterregistry.cpp +++ b/openhantek/src/exporting/exporterregistry.cpp @@ -6,75 +6,77 @@ #include #include "controlspecification.h" -#include "post/ppresult.h" #include "dsosettings.h" +#include "post/ppresult.h" -ExporterRegistry::ExporterRegistry(const Dso::ControlSpecification *deviceSpecification, DsoSettings *settings, - QObject *parent) - : QObject(parent), deviceSpecification(deviceSpecification), settings(settings) {} +ExporterRegistry::ExporterRegistry( const Dso::ControlSpecification *deviceSpecification, DsoSettings *settings, + QObject *parent ) + : QObject( parent ), deviceSpecification( deviceSpecification ), settings( settings ) {} -bool ExporterRegistry::processData(std::shared_ptr &data, ExporterInterface *const &exporter) { - if (!exporter->samples(data)) { - waitToSaveExporters.insert(exporter); +bool ExporterRegistry::processData( std::shared_ptr &data, ExporterInterface *const &exporter ) { + if ( !exporter->samples( data ) ) { + waitToSaveExporters.insert( exporter ); emit exporterProgressChanged(); return true; } return false; } -void ExporterRegistry::addRawSamples(PPresult *d) { - if (settings->exporting.useProcessedSamples) return; - std::shared_ptr data(d); - enabledExporters.remove_if([&data, this](ExporterInterface *const &i) { return processData(data, i); }); +void ExporterRegistry::addRawSamples( PPresult *d ) { + if ( settings->exporting.useProcessedSamples ) + return; + std::shared_ptr data( d ); + enabledExporters.remove_if( [&data, this]( ExporterInterface *const &i ) { return processData( data, i ); } ); } -void ExporterRegistry::input(std::shared_ptr data) { - if (!settings->exporting.useProcessedSamples) return; - enabledExporters.remove_if([&data, this](ExporterInterface *const &i) { return processData(data, i); }); +void ExporterRegistry::input( std::shared_ptr data ) { + if ( !settings->exporting.useProcessedSamples ) + return; + enabledExporters.remove_if( [&data, this]( ExporterInterface *const &i ) { return processData( data, i ); } ); } -void ExporterRegistry::registerExporter(ExporterInterface *exporter) { - exporters.push_back(exporter); - exporter->create(this); +void ExporterRegistry::registerExporter( ExporterInterface *exporter ) { + exporters.push_back( exporter ); + exporter->create( this ); } -void ExporterRegistry::setExporterEnabled(ExporterInterface *exporter, bool enabled) { +void ExporterRegistry::setExporterEnabled( ExporterInterface *exporter, bool enabled ) { bool wasInList = false; - enabledExporters.remove_if([exporter, &wasInList](ExporterInterface *inlist) { - if (inlist == exporter) { + enabledExporters.remove_if( [exporter, &wasInList]( ExporterInterface *inlist ) { + if ( inlist == exporter ) { wasInList = true; return true; } else return false; - }); + } ); - if (enabled) { + if ( enabled ) { // If the exporter was waiting for the user save confirmation, // reset it instead. - auto localFind = waitToSaveExporters.find(exporter); - if (localFind != waitToSaveExporters.end()) { - waitToSaveExporters.erase(localFind); - exporter->create(this); + auto localFind = waitToSaveExporters.find( exporter ); + if ( localFind != waitToSaveExporters.end() ) { + waitToSaveExporters.erase( localFind ); + exporter->create( this ); } - enabledExporters.push_back(exporter); - } else if (wasInList) { + enabledExporters.push_back( exporter ); + } else if ( wasInList ) { // If exporter made some progress: Add to waiting for GUI list - if (exporter->progress() > 0) { - waitToSaveExporters.insert(exporter); + if ( exporter->progress() > 0 ) { + waitToSaveExporters.insert( exporter ); emit exporterProgressChanged(); } else // Reset exporter - exporter->create(this); + exporter->create( this ); } } void ExporterRegistry::checkForWaitingExporters() { - for (ExporterInterface *exporter : waitToSaveExporters) { - if (exporter->save()) { - emit exporterStatusChanged(exporter->name(), tr("Data saved")); + for ( ExporterInterface *exporter : waitToSaveExporters ) { + if ( exporter->save() ) { + emit exporterStatusChanged( exporter->name(), tr( "Data saved" ) ); } else { - emit exporterStatusChanged(exporter->name(), tr("No data exported")); + emit exporterStatusChanged( exporter->name(), tr( "No data exported" ) ); } - exporter->create(this); + exporter->create( this ); } waitToSaveExporters.clear(); } diff --git a/openhantek/src/exporting/exporterregistry.h b/openhantek/src/exporting/exporterregistry.h index 75da5820..9ef1bea0 100644 --- a/openhantek/src/exporting/exporterregistry.h +++ b/openhantek/src/exporting/exporterregistry.h @@ -24,16 +24,16 @@ class ExporterRegistry : public QObject { Q_OBJECT public: - explicit ExporterRegistry(const Dso::ControlSpecification *deviceSpecification, DsoSettings *settings, - QObject *parent = nullptr); + explicit ExporterRegistry( const Dso::ControlSpecification *deviceSpecification, DsoSettings *settings, + QObject *parent = nullptr ); // Sample input. This will proably be performed in the post processing // thread context. Do not open GUI dialogs or interrupt the control flow. - void addRawSamples(PPresult *data); - void input(std::shared_ptr data); + void addRawSamples( PPresult *data ); + void input( std::shared_ptr data ); - void registerExporter(ExporterInterface *exporter); - void setExporterEnabled(ExporterInterface *exporter, bool enabled); + void registerExporter( ExporterInterface *exporter ); + void setExporterEnabled( ExporterInterface *exporter, bool enabled ); void checkForWaitingExporters(); @@ -58,9 +58,9 @@ class ExporterRegistry : public QObject { /// /// @return Return true if the exporter has finished and want to be removed from the /// enabledExporters list. - bool processData(std::shared_ptr &data, ExporterInterface *const &exporter); + bool processData( std::shared_ptr &data, ExporterInterface *const &exporter ); signals: - void exporterStatusChanged(const QString &exporterName, const QString &status); + void exporterStatusChanged( const QString &exporterName, const QString &status ); void exporterProgressChanged(); }; diff --git a/openhantek/src/exporting/exportimage.cpp b/openhantek/src/exporting/exportimage.cpp index d5a35b83..6465a600 100644 --- a/openhantek/src/exporting/exportimage.cpp +++ b/openhantek/src/exporting/exportimage.cpp @@ -1,11 +1,11 @@ // SPDX-License-Identifier: GPL-2.0+ #include "exportimage.h" +#include "dsosettings.h" #include "exporterregistry.h" #include "iconfont/QtAwesome.h" #include "legacyexportdrawer.h" #include "post/ppresult.h" -#include "dsosettings.h" #include "viewsettings.h" #include @@ -14,55 +14,61 @@ ExporterImage::ExporterImage() {} -void ExporterImage::create(ExporterRegistry *newRegistry) { this->registry = newRegistry; data.reset(); } +void ExporterImage::create( ExporterRegistry *newRegistry ) { + this->registry = newRegistry; + data.reset(); +} int ExporterImage::faIcon() { return fa::image; } -QString ExporterImage::name() { return QCoreApplication::tr("Export Image/PDF .."); } +QString ExporterImage::name() { return QCoreApplication::tr( "Export Image/PDF .." ); } ExporterInterface::Type ExporterImage::type() { return Type::SnapshotExport; } -bool ExporterImage::samples(const std::shared_ptr newData) { - data = std::move(newData); +bool ExporterImage::samples( const std::shared_ptr newData ) { + data = std::move( newData ); return false; } bool ExporterImage::save() { QStringList filters; - filters << QCoreApplication::tr("Portable Document Format (*.pdf)") - << QCoreApplication::tr("Image (*.png *.xpm *.jpg)"); + filters << QCoreApplication::tr( "Portable Document Format (*.pdf)" ) + << QCoreApplication::tr( "Image (*.png *.xpm *.jpg)" ); - QFileDialog fileDialog(nullptr, QCoreApplication::tr("Export file .."), QString(), filters.join(";;")); - fileDialog.setFileMode(QFileDialog::AnyFile); - fileDialog.setAcceptMode(QFileDialog::AcceptSave); - if (fileDialog.exec() != QDialog::Accepted) return false; + QFileDialog fileDialog( nullptr, QCoreApplication::tr( "Export file .." ), QString(), filters.join( ";;" ) ); + fileDialog.setFileMode( QFileDialog::AnyFile ); + fileDialog.setAcceptMode( QFileDialog::AcceptSave ); + if ( fileDialog.exec() != QDialog::Accepted ) + return false; - bool isPdf = filters.indexOf(fileDialog.selectedNameFilter()) == 0; + bool isPdf = filters.indexOf( fileDialog.selectedNameFilter() ) == 0; std::unique_ptr paintDevice; - const DsoSettingsColorValues *colorValues = &(registry->settings->view.print); + const DsoSettingsColorValues *colorValues = &( registry->settings->view.print ); - if (!isPdf) { + if ( !isPdf ) { // We need a QPixmap for image-export - QPixmap *qPixmap = new QPixmap(registry->settings->exporting.imageSize); - qPixmap->fill(colorValues->background); - paintDevice = std::unique_ptr(qPixmap); + QPixmap *qPixmap = new QPixmap( registry->settings->exporting.imageSize ); + qPixmap->fill( colorValues->background ); + paintDevice = std::unique_ptr( qPixmap ); } else { // We need a QPrinter for printing, pdf- and ps-export - std::unique_ptr printer = std::unique_ptr(new QPrinter(QPrinter::HighResolution)); - printer->setOrientation(registry->settings->view.zoom ? QPrinter::Portrait : QPrinter::Landscape); - printer->setPageMargins(20, 20, 20, 20, QPrinter::Millimeter); - printer->setOutputFileName(fileDialog.selectedFiles().first()); - printer->setOutputFormat(QPrinter::PdfFormat); - paintDevice = std::move(printer); + std::unique_ptr printer = std::unique_ptr( new QPrinter( QPrinter::HighResolution ) ); + printer->setOrientation( registry->settings->view.zoom ? QPrinter::Portrait : QPrinter::Landscape ); + printer->setPageMargins( 20, 20, 20, 20, QPrinter::Millimeter ); + printer->setOutputFileName( fileDialog.selectedFiles().first() ); + printer->setOutputFormat( QPrinter::PdfFormat ); + paintDevice = std::move( printer ); } - if (!paintDevice) return false; + if ( !paintDevice ) + return false; - LegacyExportDrawer::exportSamples(data.get(), paintDevice.get(), registry->deviceSpecification, registry->settings, - false, colorValues); + LegacyExportDrawer::exportSamples( data.get(), paintDevice.get(), registry->deviceSpecification, registry->settings, + false, colorValues ); - if (!isPdf) static_cast(paintDevice.get())->save(fileDialog.selectedFiles().first()); + if ( !isPdf ) + static_cast( paintDevice.get() )->save( fileDialog.selectedFiles().first() ); return true; } diff --git a/openhantek/src/exporting/exportimage.h b/openhantek/src/exporting/exportimage.h index e2a5ef5c..e303aca3 100644 --- a/openhantek/src/exporting/exportimage.h +++ b/openhantek/src/exporting/exportimage.h @@ -3,17 +3,17 @@ #pragma once #include "exporterinterface.h" -class ExporterImage : public ExporterInterface -{ -public: +class ExporterImage : public ExporterInterface { + public: ExporterImage(); - void create(ExporterRegistry *newRegistry) override; + void create( ExporterRegistry *newRegistry ) override; int faIcon() override; QString name() override; Type type() override; - bool samples(const std::shared_ptrnewData) override; + bool samples( const std::shared_ptr newData ) override; bool save() override; float progress() override; -private: + + private: std::shared_ptr data; }; diff --git a/openhantek/src/exporting/exportprint.cpp b/openhantek/src/exporting/exportprint.cpp index fe526383..62e6e10c 100644 --- a/openhantek/src/exporting/exportprint.cpp +++ b/openhantek/src/exporting/exportprint.cpp @@ -1,11 +1,11 @@ // SPDX-License-Identifier: GPL-2.0+ #include "exportprint.h" +#include "dsosettings.h" #include "exporterregistry.h" #include "iconfont/QtAwesome.h" #include "legacyexportdrawer.h" #include "post/ppresult.h" -#include "dsosettings.h" #include "viewsettings.h" #include @@ -14,34 +14,39 @@ ExporterPrint::ExporterPrint() {} -void ExporterPrint::create(ExporterRegistry *newRegistry) { registry = newRegistry; data.reset(); } +void ExporterPrint::create( ExporterRegistry *newRegistry ) { + registry = newRegistry; + data.reset(); +} int ExporterPrint::faIcon() { return fa::print; } -QString ExporterPrint::name() { return QCoreApplication::tr("Print .."); } +QString ExporterPrint::name() { return QCoreApplication::tr( "Print .." ); } ExporterInterface::Type ExporterPrint::type() { return Type::SnapshotExport; } -bool ExporterPrint::samples(const std::shared_ptr newData) { - data = std::move(newData); +bool ExporterPrint::samples( const std::shared_ptr newData ) { + data = std::move( newData ); return false; } bool ExporterPrint::save() { // We need a QPrinter for printing, pdf- and ps-export - std::unique_ptr printer = std::unique_ptr(new QPrinter(QPrinter::HighResolution)); - printer->setOrientation(registry->settings->view.zoom ? QPrinter::Portrait : QPrinter::Landscape); - printer->setPageMargins(20, 20, 20, 20, QPrinter::Millimeter); + std::unique_ptr printer = std::unique_ptr( new QPrinter( QPrinter::HighResolution ) ); + printer->setOrientation( registry->settings->view.zoom ? QPrinter::Portrait : QPrinter::Landscape ); + printer->setPageMargins( 20, 20, 20, 20, QPrinter::Millimeter ); // Show the printing dialog - QPrintDialog dialog(printer.get()); - dialog.setWindowTitle(QCoreApplication::tr("Print oscillograph")); - if (dialog.exec() != QDialog::Accepted) { return false; } + QPrintDialog dialog( printer.get() ); + dialog.setWindowTitle( QCoreApplication::tr( "Print oscillograph" ) ); + if ( dialog.exec() != QDialog::Accepted ) { + return false; + } - const DsoSettingsColorValues *colorValues = &(registry->settings->view.print); + const DsoSettingsColorValues *colorValues = &( registry->settings->view.print ); - LegacyExportDrawer::exportSamples(data.get(), printer.get(), registry->deviceSpecification, registry->settings, - true, colorValues); + LegacyExportDrawer::exportSamples( data.get(), printer.get(), registry->deviceSpecification, registry->settings, + true, colorValues ); return true; } diff --git a/openhantek/src/exporting/exportprint.h b/openhantek/src/exporting/exportprint.h index 1404704f..4b0d344c 100644 --- a/openhantek/src/exporting/exportprint.h +++ b/openhantek/src/exporting/exportprint.h @@ -3,17 +3,17 @@ #pragma once #include "exporterinterface.h" -class ExporterPrint : public ExporterInterface -{ -public: +class ExporterPrint : public ExporterInterface { + public: ExporterPrint(); - void create(ExporterRegistry *newRegistry) override; + void create( ExporterRegistry *newRegistry ) override; int faIcon() override; QString name() override; Type type() override; - bool samples(const std::shared_ptrnewData) override; + bool samples( const std::shared_ptr newData ) override; bool save() override; float progress() override; -private: + + private: std::shared_ptr data; }; diff --git a/openhantek/src/exporting/exportsettings.h b/openhantek/src/exporting/exportsettings.h index e8f18c5e..9437d813 100644 --- a/openhantek/src/exporting/exportsettings.h +++ b/openhantek/src/exporting/exportsettings.h @@ -6,7 +6,7 @@ /// \brief Holds the export options of the program. struct DsoSettingsExport { - QSize imageSize = QSize(800, 600); ///< Size of exported images in pixels - unsigned exportSizeBytes = 1024*1024*10; ///< For exporters that save a continous stream. Default: 10 Megabytes - bool useProcessedSamples = true; ///< Export raw or processed samples + QSize imageSize = QSize( 800, 600 ); ///< Size of exported images in pixels + unsigned exportSizeBytes = 1024 * 1024 * 10; ///< For exporters that save a continous stream. Default: 10 Megabytes + bool useProcessedSamples = true; ///< Export raw or processed samples }; diff --git a/openhantek/src/exporting/legacyexportdrawer.cpp b/openhantek/src/exporting/legacyexportdrawer.cpp index 772995c8..62f13034 100644 --- a/openhantek/src/exporting/legacyexportdrawer.cpp +++ b/openhantek/src/exporting/legacyexportdrawer.cpp @@ -11,178 +11,181 @@ #include "legacyexportdrawer.h" #include "controlspecification.h" +#include "dsosettings.h" #include "post/graphgenerator.h" #include "post/ppresult.h" -#include "dsosettings.h" #include "utils/printutils.h" #include "viewconstants.h" -#define tr(msg) QCoreApplication::translate("Exporter", msg) +#define tr( msg ) QCoreApplication::translate( "Exporter", msg ) -bool LegacyExportDrawer::exportSamples(const PPresult *result, QPaintDevice* paintDevice, - const Dso::ControlSpecification *deviceSpecification, - const DsoSettings *settings, bool isPrinter, const DsoSettingsColorValues *colorValues) { +bool LegacyExportDrawer::exportSamples( const PPresult *result, QPaintDevice *paintDevice, + const Dso::ControlSpecification *deviceSpecification, + const DsoSettings *settings, bool isPrinter, + const DsoSettingsColorValues *colorValues ) { // Create a painter for our device - QPainter painter(paintDevice); + QPainter painter( paintDevice ); // Get line height QFont font; - QFontMetrics fontMetrics(font, paintDevice); + QFontMetrics fontMetrics( font, paintDevice ); double lineHeight = fontMetrics.height(); - painter.setBrush(Qt::SolidPattern); + painter.setBrush( Qt::SolidPattern ); // Draw the settings table - double stretchBase = double(paintDevice->width()) / 6; + double stretchBase = double( paintDevice->width() ) / 6; // Print trigger details double pulseWidth1 = result->data( 0 )->pulseWidth1; double pulseWidth2 = result->data( 0 )->pulseWidth2; - painter.setPen(colorValues->voltage[settings->scope.trigger.source]); - QString levelString = valueToString(settings->scope.voltage[settings->scope.trigger.source].trigger, UNIT_VOLTS, 3); - QString pretriggerString = tr("%L1%").arg(int(settings->scope.trigger.offset * 100 + 0.5)); - QString pre = Dso::slopeString(settings->scope.trigger.slope); // trigger slope - QString post = pre; // opposite trigger slope + painter.setPen( colorValues->voltage[ settings->scope.trigger.source ] ); + QString levelString = + valueToString( settings->scope.voltage[ settings->scope.trigger.source ].trigger, UNIT_VOLTS, 3 ); + QString pretriggerString = tr( "%L1%" ).arg( int( settings->scope.trigger.offset * 100 + 0.5 ) ); + QString pre = Dso::slopeString( settings->scope.trigger.slope ); // trigger slope + QString post = pre; // opposite trigger slope if ( settings->scope.trigger.slope == Dso::Slope::Positive ) - post = Dso::slopeString( Dso::Slope:: Negative ); + post = Dso::slopeString( Dso::Slope::Negative ); else if ( settings->scope.trigger.slope == Dso::Slope::Negative ) - post = Dso::slopeString( Dso::Slope:: Positive ); - QString pulseWidthString = bool( pulseWidth1 ) ? pre + valueToString( pulseWidth1, UNIT_SECONDS, 3) + post : ""; - pulseWidthString += bool( pulseWidth2 ) ? valueToString( pulseWidth2, UNIT_SECONDS, 3) + pre : ""; + post = Dso::slopeString( Dso::Slope::Positive ); + QString pulseWidthString = bool( pulseWidth1 ) ? pre + valueToString( pulseWidth1, UNIT_SECONDS, 3 ) + post : ""; + pulseWidthString += bool( pulseWidth2 ) ? valueToString( pulseWidth2, UNIT_SECONDS, 3 ) + pre : ""; if ( bool( pulseWidth1 ) && bool( pulseWidth2 ) ) { int dutyCyle = int( 0.5 + ( 100.0 * pulseWidth1 ) / ( pulseWidth1 + pulseWidth2 ) ); pulseWidthString += " (" + QString::number( dutyCyle ) + "%)"; } - painter.drawText(QRectF( 0, 0, 2 * stretchBase, lineHeight ), - tr( "%1 %2 %3 %4 %5" ) - .arg( settings->scope.voltage[settings->scope.trigger.source].name, - Dso::slopeString(settings->scope.trigger.slope), - levelString, pretriggerString, pulseWidthString - ) - ); + painter.drawText( QRectF( 0, 0, 2 * stretchBase, lineHeight ), + tr( "%1 %2 %3 %4 %5" ) + .arg( settings->scope.voltage[ settings->scope.trigger.source ].name, + Dso::slopeString( settings->scope.trigger.slope ), levelString, pretriggerString, + pulseWidthString ) ); double scopeHeight; { // DataAnalyser mutex lock // Print sample count - painter.setPen(colorValues->text); - painter.drawText(QRectF(stretchBase * 2, 0, stretchBase, lineHeight), tr("%1 S on screen").arg( - int( settings->scope.horizontal.samplerate * settings->scope.horizontal.timebase * DIVS_TIME + 0.99 ) - ), - QTextOption(Qt::AlignRight)); + painter.setPen( colorValues->text ); + painter.drawText( + QRectF( stretchBase * 2, 0, stretchBase, lineHeight ), + tr( "%1 S on screen" ) + .arg( int( settings->scope.horizontal.samplerate * settings->scope.horizontal.timebase * DIVS_TIME + + 0.99 ) ), + QTextOption( Qt::AlignRight ) ); // Print samplerate - painter.drawText(QRectF(stretchBase * 3, 0, stretchBase, lineHeight), - valueToString(settings->scope.horizontal.samplerate, UNIT_SAMPLES) + tr("/s"), - QTextOption(Qt::AlignRight)); + painter.drawText( QRectF( stretchBase * 3, 0, stretchBase, lineHeight ), + valueToString( settings->scope.horizontal.samplerate, UNIT_SAMPLES ) + tr( "/s" ), + QTextOption( Qt::AlignRight ) ); // Print timebase - painter.drawText(QRectF(stretchBase * 4, 0, stretchBase, lineHeight), - valueToString(settings->scope.horizontal.timebase, UNIT_SECONDS, 0) + tr("/div"), - QTextOption(Qt::AlignRight)); + painter.drawText( QRectF( stretchBase * 4, 0, stretchBase, lineHeight ), + valueToString( settings->scope.horizontal.timebase, UNIT_SECONDS, 0 ) + tr( "/div" ), + QTextOption( Qt::AlignRight ) ); // Print frequencybase - painter.drawText(QRectF(stretchBase * 5, 0, stretchBase, lineHeight), - valueToString(settings->scope.horizontal.frequencybase, UNIT_HERTZ, 0) + tr("/div"), - QTextOption(Qt::AlignRight)); + painter.drawText( QRectF( stretchBase * 5, 0, stretchBase, lineHeight ), + valueToString( settings->scope.horizontal.frequencybase, UNIT_HERTZ, 0 ) + tr( "/div" ), + QTextOption( Qt::AlignRight ) ); // Draw the measurement table - stretchBase = double(paintDevice->width() ) / 30; + stretchBase = double( paintDevice->width() ) / 30; int channelCount = 0; - for ( int channel = int(settings->scope.voltage.size() - 1); channel >= 0; channel--) { - if ((settings->scope.voltage[unsigned(channel)].used || settings->scope.spectrum[unsigned(channel)].used) && - result->data(unsigned(channel))) { + for ( int channel = int( settings->scope.voltage.size() - 1 ); channel >= 0; channel-- ) { + if ( ( settings->scope.voltage[ unsigned( channel ) ].used || + settings->scope.spectrum[ unsigned( channel ) ].used ) && + result->data( unsigned( channel ) ) ) { ++channelCount; - double top = double(paintDevice->height()) - channelCount * lineHeight; - double tPos=0.0, tWidth; + double top = double( paintDevice->height() ) - channelCount * lineHeight; + double tPos = 0.0, tWidth; // Print label tWidth = 2; - painter.setPen(colorValues->voltage[unsigned(channel)]); - painter.drawText( - QRectF( stretchBase * tPos, top, stretchBase * tWidth, lineHeight ), - settings->scope.voltage[unsigned(channel)].name ); + painter.setPen( colorValues->voltage[ unsigned( channel ) ] ); + painter.drawText( QRectF( stretchBase * tPos, top, stretchBase * tWidth, lineHeight ), + settings->scope.voltage[ unsigned( channel ) ].name ); // Print coupling/math mode tPos += tWidth; tWidth = 3.5; - if ( unsigned(channel) < deviceSpecification->channels ) + if ( unsigned( channel ) < deviceSpecification->channels ) painter.drawText( QRectF( stretchBase * tPos, top, stretchBase * tWidth, lineHeight ), - Dso::couplingString( settings->scope.coupling(unsigned(channel), deviceSpecification) ) ); + Dso::couplingString( settings->scope.coupling( unsigned( channel ), deviceSpecification ) ) ); else painter.drawText( QRectF( stretchBase * tPos, top, stretchBase * tWidth, lineHeight ), - Dso::mathModeString(Dso::getMathMode(settings->scope.voltage[unsigned(channel)]) ) ); + Dso::mathModeString( Dso::getMathMode( settings->scope.voltage[ unsigned( channel ) ] ) ) ); // Print voltage gain tPos += tWidth; tWidth = 3; - painter.drawText( - QRectF( stretchBase * tPos, top, stretchBase * tWidth, lineHeight ), - valueToString(settings->scope.gain(unsigned(channel)), UNIT_VOLTS, 0) + tr("/div"), - QTextOption(Qt::AlignRight) ); + painter.drawText( QRectF( stretchBase * tPos, top, stretchBase * tWidth, lineHeight ), + valueToString( settings->scope.gain( unsigned( channel ) ), UNIT_VOLTS, 0 ) + + tr( "/div" ), + QTextOption( Qt::AlignRight ) ); // Print spectrum magnitude tPos += tWidth; tWidth = 3; - if (settings->scope.spectrum[unsigned(channel)].used) { - painter.setPen(colorValues->spectrum[unsigned(channel)]); - painter.drawText( + if ( settings->scope.spectrum[ unsigned( channel ) ].used ) { + painter.setPen( colorValues->spectrum[ unsigned( channel ) ] ); + painter.drawText( QRectF( stretchBase * tPos, top, stretchBase * tWidth, lineHeight ), - valueToString(settings->scope.spectrum[unsigned(channel)].magnitude, UNIT_DECIBEL, 0) + - tr("/div"), QTextOption(Qt::AlignRight) ); + valueToString( settings->scope.spectrum[ unsigned( channel ) ].magnitude, UNIT_DECIBEL, 0 ) + + tr( "/div" ), + QTextOption( Qt::AlignRight ) ); } // Vpp Amplitude string representation (3 significant digits) tPos += tWidth; tWidth = 3; - painter.setPen(colorValues->text); + painter.setPen( colorValues->text ); painter.drawText( QRectF( stretchBase * tPos, top, stretchBase * tWidth, lineHeight ), - valueToString(result->data(unsigned(channel))->vpp, UNIT_VOLTS, 3) + "pp", - QTextOption(Qt::AlignRight) ); + valueToString( result->data( unsigned( channel ) )->vpp, UNIT_VOLTS, 3 ) + "pp", + QTextOption( Qt::AlignRight ) ); // RMS Amplitude string representation (3 significant digits) tPos += tWidth; tWidth = 3.5; - painter.setPen(colorValues->text); - painter.drawText(QRectF( stretchBase * tPos, top, stretchBase * tWidth, lineHeight ), - valueToString(result->data(unsigned(channel))->rms, UNIT_VOLTS, 3) + "rms", - QTextOption(Qt::AlignRight) ); + painter.setPen( colorValues->text ); + painter.drawText( QRectF( stretchBase * tPos, top, stretchBase * tWidth, lineHeight ), + valueToString( result->data( unsigned( channel ) )->rms, UNIT_VOLTS, 3 ) + "rms", + QTextOption( Qt::AlignRight ) ); // DC Amplitude string representation (3 significant digits) tPos += tWidth; tWidth = 3; - painter.setPen(colorValues->text); - painter.drawText(QRectF( stretchBase * tPos, top, stretchBase * tWidth, lineHeight ), - valueToString(result->data(unsigned(channel))->dc, UNIT_VOLTS, 3) + "=", - QTextOption(Qt::AlignRight) ); + painter.setPen( colorValues->text ); + painter.drawText( QRectF( stretchBase * tPos, top, stretchBase * tWidth, lineHeight ), + valueToString( result->data( unsigned( channel ) )->dc, UNIT_VOLTS, 3 ) + "=", + QTextOption( Qt::AlignRight ) ); // AC Amplitude string representation (3 significant digits) tPos += tWidth; tWidth = 3; - painter.setPen(colorValues->text); + painter.setPen( colorValues->text ); painter.drawText( QRectF( stretchBase * tPos, top, stretchBase * tWidth, lineHeight ), - valueToString(result->data(unsigned(channel))->ac, UNIT_VOLTS, 3) + "~", - QTextOption(Qt::AlignRight) ); + valueToString( result->data( unsigned( channel ) )->ac, UNIT_VOLTS, 3 ) + "~", + QTextOption( Qt::AlignRight ) ); // dB Amplitude string representation (3 significant digits) tPos += tWidth; tWidth = 3; - painter.setPen(colorValues->text); + painter.setPen( colorValues->text ); painter.drawText( QRectF( stretchBase * tPos, top, stretchBase * tWidth, lineHeight ), - valueToString(result->data(unsigned(channel))->dB, UNIT_DECIBEL, 3), - QTextOption(Qt::AlignRight) ); + valueToString( result->data( unsigned( channel ) )->dB, UNIT_DECIBEL, 3 ), + QTextOption( Qt::AlignRight ) ); // Frequency string representation (4 significant digits) tPos += tWidth; tWidth = 3; painter.drawText( QRectF( stretchBase * tPos, top, stretchBase * tWidth, lineHeight ), - valueToString(result->data(unsigned(channel))->frequency, UNIT_HERTZ, 4), - QTextOption(Qt::AlignRight) ); + valueToString( result->data( unsigned( channel ) )->frequency, UNIT_HERTZ, 4 ), + QTextOption( Qt::AlignRight ) ); } } // Draw the marker table - painter.setPen(colorValues->text); + painter.setPen( colorValues->text ); // Calculate variables needed for zoomed scope - double m1 = settings->scope.getMarker(0) + DIVS_TIME / 2; // zero at center -> zero at left margin - double m2 = settings->scope.getMarker(1) + DIVS_TIME / 2; // zero at center -> zero at left margin + double m1 = settings->scope.getMarker( 0 ) + DIVS_TIME / 2; // zero at center -> zero at left margin + double m2 = settings->scope.getMarker( 1 ) + DIVS_TIME / 2; // zero at center -> zero at left margin if ( m1 > m2 ) std::swap( m1, m2 ); double divs = m2 - m1; double zoomFactor = DIVS_TIME / divs; - double zoomOffset = (m1 + m2) / 2; + double zoomOffset = ( m1 + m2 ) / 2; double time1 = ( m1 - DIVS_TIME * settings->scope.trigger.offset ) * settings->scope.horizontal.timebase; double time2 = ( m2 - DIVS_TIME * settings->scope.trigger.offset ) * settings->scope.horizontal.timebase; double time = divs * settings->scope.horizontal.timebase; @@ -190,89 +193,89 @@ bool LegacyExportDrawer::exportSamples(const PPresult *result, QPaintDevice* pai double freq2 = m2 * settings->scope.horizontal.frequencybase; double freq = freq2 - freq1; - if (settings->view.zoom) { + if ( settings->view.zoom ) { stretchBase = double( paintDevice->width() ) / 9; scopeHeight = double( paintDevice->height() - ( channelCount + 5 ) * lineHeight ) / 2; double top = 2.5 * lineHeight + scopeHeight; - painter.drawText(QRectF(0, top, stretchBase, lineHeight), - tr("Zoom x%L1").arg(DIVS_TIME / divs, -1, 'g', 3)); - - painter.drawText(QRectF(stretchBase, top, stretchBase, lineHeight), - valueToString( time1, UNIT_SECONDS, 4 ), QTextOption(Qt::AlignRight)); - painter.drawText(QRectF(stretchBase * 2, top, stretchBase, lineHeight), - valueToString( time2, UNIT_SECONDS, 4 ), QTextOption(Qt::AlignRight)); - painter.drawText(QRectF(stretchBase * 3, top, stretchBase, lineHeight), - valueToString( time, UNIT_SECONDS, 4 ), QTextOption(Qt::AlignRight)); - painter.drawText(QRectF(stretchBase * 4, top, stretchBase, lineHeight), - valueToString( freq1, UNIT_HERTZ, 4 ), QTextOption(Qt::AlignRight)); - painter.drawText(QRectF(stretchBase * 5, top, stretchBase, lineHeight), - valueToString( freq2, UNIT_HERTZ, 4 ), QTextOption(Qt::AlignRight)); - painter.drawText(QRectF(stretchBase * 6, top, stretchBase, lineHeight), - valueToString( freq, UNIT_HERTZ, 4 ), QTextOption(Qt::AlignRight)); - - painter.drawText(QRectF(stretchBase * 7, top, stretchBase, lineHeight), - valueToString( time / DIVS_TIME, UNIT_SECONDS, 3 ) + tr("/div"), - QTextOption(Qt::AlignRight)); - painter.drawText(QRectF(stretchBase * 8, top, stretchBase, lineHeight), - valueToString( freq / DIVS_TIME, UNIT_HERTZ, 3 ) + - tr("/div"), - QTextOption(Qt::AlignRight)); + painter.drawText( QRectF( 0, top, stretchBase, lineHeight ), + tr( "Zoom x%L1" ).arg( DIVS_TIME / divs, -1, 'g', 3 ) ); + + painter.drawText( QRectF( stretchBase, top, stretchBase, lineHeight ), + valueToString( time1, UNIT_SECONDS, 4 ), QTextOption( Qt::AlignRight ) ); + painter.drawText( QRectF( stretchBase * 2, top, stretchBase, lineHeight ), + valueToString( time2, UNIT_SECONDS, 4 ), QTextOption( Qt::AlignRight ) ); + painter.drawText( QRectF( stretchBase * 3, top, stretchBase, lineHeight ), + valueToString( time, UNIT_SECONDS, 4 ), QTextOption( Qt::AlignRight ) ); + painter.drawText( QRectF( stretchBase * 4, top, stretchBase, lineHeight ), + valueToString( freq1, UNIT_HERTZ, 4 ), QTextOption( Qt::AlignRight ) ); + painter.drawText( QRectF( stretchBase * 5, top, stretchBase, lineHeight ), + valueToString( freq2, UNIT_HERTZ, 4 ), QTextOption( Qt::AlignRight ) ); + painter.drawText( QRectF( stretchBase * 6, top, stretchBase, lineHeight ), + valueToString( freq, UNIT_HERTZ, 4 ), QTextOption( Qt::AlignRight ) ); + + painter.drawText( QRectF( stretchBase * 7, top, stretchBase, lineHeight ), + valueToString( time / DIVS_TIME, UNIT_SECONDS, 3 ) + tr( "/div" ), + QTextOption( Qt::AlignRight ) ); + painter.drawText( QRectF( stretchBase * 8, top, stretchBase, lineHeight ), + valueToString( freq / DIVS_TIME, UNIT_HERTZ, 3 ) + tr( "/div" ), + QTextOption( Qt::AlignRight ) ); } else { stretchBase = double( paintDevice->width() ) / 8; - scopeHeight = double( paintDevice->height() ) - (channelCount + 4) * lineHeight; + scopeHeight = double( paintDevice->height() ) - ( channelCount + 4 ) * lineHeight; double top = 2.5 * lineHeight + scopeHeight; - painter.drawText(QRectF(0, top, stretchBase, lineHeight), tr("Marker 1/2")); - painter.drawText(QRectF(stretchBase, top, stretchBase, lineHeight), - "t1: " + valueToString( time1, UNIT_SECONDS, 4 ), QTextOption(Qt::AlignRight)); - painter.drawText(QRectF(stretchBase * 2, top, stretchBase, lineHeight), - "t2: " + valueToString( time2, UNIT_SECONDS, 4 ), QTextOption(Qt::AlignRight)); + painter.drawText( QRectF( 0, top, stretchBase, lineHeight ), tr( "Marker 1/2" ) ); + painter.drawText( QRectF( stretchBase, top, stretchBase, lineHeight ), + "t1: " + valueToString( time1, UNIT_SECONDS, 4 ), QTextOption( Qt::AlignRight ) ); + painter.drawText( QRectF( stretchBase * 2, top, stretchBase, lineHeight ), + "t2: " + valueToString( time2, UNIT_SECONDS, 4 ), QTextOption( Qt::AlignRight ) ); if ( bool( time ) ) { - painter.drawText(QRectF(stretchBase * 3, top, stretchBase, lineHeight), - "Δt: " + valueToString( time, UNIT_SECONDS, 4 ), QTextOption(Qt::AlignRight)); - painter.drawText(QRectF(stretchBase * 4, top, stretchBase, lineHeight), - " (=" + valueToString( 1/time, UNIT_HERTZ, 4 ) + ")", QTextOption(Qt::AlignLeft)); + painter.drawText( QRectF( stretchBase * 3, top, stretchBase, lineHeight ), + "Δt: " + valueToString( time, UNIT_SECONDS, 4 ), QTextOption( Qt::AlignRight ) ); + painter.drawText( QRectF( stretchBase * 4, top, stretchBase, lineHeight ), + " (=" + valueToString( 1 / time, UNIT_HERTZ, 4 ) + ")", + QTextOption( Qt::AlignLeft ) ); } - painter.drawText(QRectF(stretchBase * 5, top, stretchBase, lineHeight), - "f1: " + valueToString( freq1, UNIT_HERTZ, 4 ), QTextOption(Qt::AlignRight)); - painter.drawText(QRectF(stretchBase * 6, top, stretchBase, lineHeight), - "f2: " + valueToString( freq2, UNIT_HERTZ, 4 ), QTextOption(Qt::AlignRight)); + painter.drawText( QRectF( stretchBase * 5, top, stretchBase, lineHeight ), + "f1: " + valueToString( freq1, UNIT_HERTZ, 4 ), QTextOption( Qt::AlignRight ) ); + painter.drawText( QRectF( stretchBase * 6, top, stretchBase, lineHeight ), + "f2: " + valueToString( freq2, UNIT_HERTZ, 4 ), QTextOption( Qt::AlignRight ) ); if ( bool( freq ) ) - painter.drawText(QRectF(stretchBase * 7, top, stretchBase, lineHeight), - "Δf: " + valueToString( freq, UNIT_HERTZ, 4 ), QTextOption(Qt::AlignRight)); + painter.drawText( QRectF( stretchBase * 7, top, stretchBase, lineHeight ), + "Δf: " + valueToString( freq, UNIT_HERTZ, 4 ), QTextOption( Qt::AlignRight ) ); } // Draw the graphs - painter.setRenderHint(QPainter::Antialiasing); - painter.setBrush(Qt::NoBrush); + painter.setRenderHint( QPainter::Antialiasing ); + painter.setBrush( Qt::NoBrush ); - for (int zoomed = 0; zoomed < (settings->view.zoom ? 2 : 1); ++zoomed) { + for ( int zoomed = 0; zoomed < ( settings->view.zoom ? 2 : 1 ); ++zoomed ) { double m11 = paintDevice->width() / DIVS_TIME; double m22 = -scopeHeight / DIVS_VOLTAGE; double dx = double( paintDevice->width() ) / 2; double dy = scopeHeight / 2 + lineHeight * 1.5; if ( zoomed ) { // zoom (m11) and shift in x direction (dx), move down (dy) m11 = paintDevice->width() / DIVS_TIME * zoomFactor; - dx = double( paintDevice->width() ) / 2 - + ( 0.5 - zoomOffset / DIVS_TIME ) * zoomFactor * paintDevice->width(); + dx = double( paintDevice->width() ) / 2 + + ( 0.5 - zoomOffset / DIVS_TIME ) * zoomFactor * paintDevice->width(); dy = scopeHeight * 1.5 + lineHeight * 4; } // Set DIVS_TIME x DIVS_VOLTAGE matrix for (non-zoomed / zoomed) oscillograph // false: don't combine with current matrix -> replace - painter.setTransform( QTransform( QMatrix ( m11, 0, 0, m22, dx, dy ) ), false ); + painter.setTransform( QTransform( QMatrix( m11, 0, 0, m22, dx, dy ) ), false ); - switch (settings->scope.horizontal.format) { + switch ( settings->scope.horizontal.format ) { case Dso::GraphFormat::TY: // Add graphs for channels - for (ChannelID channel = 0; channel < settings->scope.voltage.size(); ++channel) { - if (settings->scope.voltage[unsigned(channel)].used && result->data(channel)) { - painter.setPen(QPen(colorValues->voltage[unsigned(channel)], 0)); + for ( ChannelID channel = 0; channel < settings->scope.voltage.size(); ++channel ) { + if ( settings->scope.voltage[ unsigned( channel ) ].used && result->data( channel ) ) { + painter.setPen( QPen( colorValues->voltage[ unsigned( channel ) ], 0 ) ); // What's the horizontal distance between sampling points? double horizontalFactor = - result->data(channel)->voltage.interval / settings->scope.horizontal.timebase; + result->data( channel )->voltage.interval / settings->scope.horizontal.timebase; // How many samples are visible? int dotsOnScreen = int( DIVS_TIME / horizontalFactor + 0.99 ); // round up // align displayed trace with trigger mark on screen ... @@ -280,38 +283,39 @@ bool LegacyExportDrawer::exportSamples(const PPresult *result, QPaintDevice* pai int preTrigSamples = int( settings->scope.trigger.offset * dotsOnScreen ); int leftmostSample = int( result->triggeredPosition ) - preTrigSamples; // 1st sample to show int rightmostSample = leftmostSample + dotsOnScreen; - int leftmostPosition = 0; // start position on display - if ( leftmostSample < 0 ) { // trig pos or time/div was increased + int leftmostPosition = 0; // start position on display + if ( leftmostSample < 0 ) { // trig pos or time/div was increased leftmostPosition = -leftmostSample; // trace can't start on left margin - leftmostSample = 0; // show as much as we have on left side + leftmostSample = 0; // show as much as we have on left side } int lastPosition = qMin( int( DIVS_TIME / horizontalFactor ), - int( result->data(channel)->voltage.sample.size() ) ); + int( result->data( channel )->voltage.sample.size() ) ); // Draw graph const unsigned binsPerDiv = 50; - QPointF *graph = new QPointF[ result->data(channel)->voltage.sample.size() + 1 ]; + QPointF *graph = new QPointF[ result->data( channel )->voltage.sample.size() + 1 ]; // skip leading samples to show the correct trigger position - auto sampleIterator = result->data(channel)->voltage.sample.cbegin() + leftmostSample; // -> visible samples - auto displayEnd = result->data(channel)->voltage.sample.cbegin() + rightmostSample; - auto sampleEnd = result->data(channel)->voltage.sample.cend(); + auto sampleIterator = + result->data( channel )->voltage.sample.cbegin() + leftmostSample; // -> visible samples + auto displayEnd = result->data( channel )->voltage.sample.cbegin() + rightmostSample; + auto sampleEnd = result->data( channel )->voltage.sample.cend(); int pointCount = 0; - double gain = settings->scope.gain(channel); - double offset = settings->scope.voltage[unsigned(channel)].offset; - unsigned bins[ int( binsPerDiv * DIVS_VOLTAGE ) ] = { 0 }; + double gain = settings->scope.gain( channel ); + double offset = settings->scope.voltage[ unsigned( channel ) ].offset; + unsigned bins[ int( binsPerDiv * DIVS_VOLTAGE ) ] = {0}; for ( int position = leftmostPosition; - position < dotsOnScreen && position < lastPosition - && sampleIterator < sampleEnd && sampleIterator < displayEnd; - ++position, ++sampleIterator) { + position < dotsOnScreen && position < lastPosition && sampleIterator < sampleEnd && + sampleIterator < displayEnd; + ++position, ++sampleIterator ) { double x = MARGIN_LEFT + position * horizontalFactor; double y = *sampleIterator / gain + offset; if ( !settings->scope.histogram ) { graph[ position - leftmostPosition ] = QPointF( x, y ); ++pointCount; } else { - int bin = int( round( binsPerDiv * ( y + DIVS_VOLTAGE / 2) ) ); + int bin = int( round( binsPerDiv * ( y + DIVS_VOLTAGE / 2 ) ) ); if ( bin > 0 && bin < binsPerDiv * DIVS_VOLTAGE ) // if trace is on screen - ++bins[ bin ]; // count value + ++bins[ bin ]; // count value if ( x < MARGIN_RIGHT - 1.1 ) { graph[ position - leftmostPosition ] = QPointF( x, y ); ++pointCount; @@ -333,65 +337,62 @@ bool LegacyExportDrawer::exportSamples(const PPresult *result, QPaintDevice* pai } for ( int bin = 0; bin < binsPerDiv * DIVS_VOLTAGE; ++bin ) { if ( bins[ bin ] ) { // show bar (= start and end point) if value exists - double y = double( bin ) / binsPerDiv - DIVS_VOLTAGE / 2 - double( channel ) / binsPerDiv / 2; + double y = double( bin ) / binsPerDiv - DIVS_VOLTAGE / 2 - + double( channel ) / binsPerDiv / 2; graph[ pointCount++ ] = QPointF( MARGIN_RIGHT, y ); graph[ pointCount++ ] = QPointF( MARGIN_RIGHT - bins[ bin ] / max, y ); } } - painter.drawLines( graph, pointCount/2 ); + painter.drawLines( graph, pointCount / 2 ); delete[] graph; } } } // Add spectrum graphs - for (ChannelID channel = 0; channel < settings->scope.spectrum.size(); ++channel) { - if (settings->scope.spectrum[unsigned(channel)].used && result->data(channel)) { - painter.setPen(QPen(colorValues->spectrum[unsigned(channel)], 0)); + for ( ChannelID channel = 0; channel < settings->scope.spectrum.size(); ++channel ) { + if ( settings->scope.spectrum[ unsigned( channel ) ].used && result->data( channel ) ) { + painter.setPen( QPen( colorValues->spectrum[ unsigned( channel ) ], 0 ) ); // What's the horizontal distance between sampling points? double horizontalFactor = - result->data(channel)->spectrum.interval / settings->scope.horizontal.frequencybase; + result->data( channel )->spectrum.interval / settings->scope.horizontal.frequencybase; // How many samples are visible? - unsigned int lastPosition = unsigned( qMin( int( DIVS_TIME / horizontalFactor ), - int(result->data(channel)->spectrum.sample.size() ) - 1 ) ); + unsigned int lastPosition = + unsigned( qMin( int( DIVS_TIME / horizontalFactor ), + int( result->data( channel )->spectrum.sample.size() ) - 1 ) ); // Draw graph - double magnitude = settings->scope.spectrum[unsigned(channel)].magnitude; - double offset = settings->scope.spectrum[unsigned(channel)].offset; - QPointF *graph = new QPointF[ result->data(channel)->spectrum.sample.size() + 1 ]; + double magnitude = settings->scope.spectrum[ unsigned( channel ) ].magnitude; + double offset = settings->scope.spectrum[ unsigned( channel ) ].offset; + QPointF *graph = new QPointF[ result->data( channel )->spectrum.sample.size() + 1 ]; - for (unsigned int position = 0; position <= lastPosition; ++position) { + for ( unsigned int position = 0; position <= lastPosition; ++position ) { graph[ position ] = - QPointF(MARGIN_LEFT + position * horizontalFactor, - result->data(channel)->spectrum.sample[position] / magnitude + offset - ); + QPointF( MARGIN_LEFT + position * horizontalFactor, + result->data( channel )->spectrum.sample[ position ] / magnitude + offset ); } - painter.drawPolyline( graph, int ( lastPosition + 1 ) ); + painter.drawPolyline( graph, int( lastPosition + 1 ) ); delete[] graph; } } break; case Dso::GraphFormat::XY: - if ( settings->scope.voltage[ 0 ].used && result->data( 0 ) - && settings->scope.voltage[ 1 ].used && result->data( 1 ) ) { + if ( settings->scope.voltage[ 0 ].used && result->data( 0 ) && settings->scope.voltage[ 1 ].used && + result->data( 1 ) ) { const double xGain = settings->scope.gain( 0 ); const double yGain = settings->scope.gain( 1 ); const double xOffset = ( settings->scope.trigger.offset - 0.5 ) * DIVS_TIME; const double yOffset = settings->scope.voltage[ 1 ].offset; - painter.setPen( QPen( colorValues->voltage[ 1 ], 0) ); + painter.setPen( QPen( colorValues->voltage[ 1 ], 0 ) ); const unsigned size = unsigned( std::min( int( result->data( 0 )->voltage.sample.size() ), - int( result->data( 1 )->voltage.sample.size() ) - ) - ); + int( result->data( 1 )->voltage.sample.size() ) ) ); // Draw graph QPointF *graph = new QPointF[ size ]; for ( unsigned int index = 0; index < size; ++index ) { - graph[ index ] = - QPointF( result->data( 0 )->voltage.sample[ index ] / xGain + xOffset, - result->data( 1 )->voltage.sample[ index ] / yGain + yOffset - ); + graph[ index ] = QPointF( result->data( 0 )->voltage.sample[ index ] / xGain + xOffset, + result->data( 1 )->voltage.sample[ index ] / yGain + yOffset ); } painter.drawPolyline( graph, int( size ) ); delete[] graph; @@ -402,11 +403,11 @@ bool LegacyExportDrawer::exportSamples(const PPresult *result, QPaintDevice* pai if ( !zoomed ) { // draw marker lines and trigger position const double trig = DIVS_TIME * ( settings->scope.trigger.offset - 0.5 ); const double tick = double( DIVS_TIME ) / 250.0; - const double top = DIVS_VOLTAGE/2; - const double bottom = -DIVS_VOLTAGE/2; - const double left = -DIVS_TIME/2; - //const double right = DIVS_TIME/2; - painter.setPen( QPen(colorValues->markers, 0) ); + const double top = DIVS_VOLTAGE / 2; + const double bottom = -DIVS_VOLTAGE / 2; + const double left = -DIVS_TIME / 2; + // const double right = DIVS_TIME/2; + painter.setPen( QPen( colorValues->markers, 0 ) ); // markers painter.drawLine( QLineF( m1 + left, bottom - 4 * tick, m1 + left, top ) ); painter.drawLine( QLineF( m2 + left, bottom - 4 * tick, m2 + left, top ) ); @@ -417,91 +418,92 @@ bool LegacyExportDrawer::exportSamples(const PPresult *result, QPaintDevice* pai } } // dataanalyser mutex release - drawGrids(painter, colorValues, lineHeight, scopeHeight, paintDevice->width(), - isPrinter, settings->view.zoom); + drawGrids( painter, colorValues, lineHeight, scopeHeight, paintDevice->width(), isPrinter, settings->view.zoom ); painter.end(); return true; } -void LegacyExportDrawer::drawGrids(QPainter &painter, const DsoSettingsColorValues *colorValues, double lineHeight, double scopeHeight, - int scopeWidth, bool isPrinter, bool zoom) { - painter.setRenderHint(QPainter::Antialiasing, false); - for (int zoomed = 0; zoomed < (zoom ? 2 : 1); ++zoomed) { +void LegacyExportDrawer::drawGrids( QPainter &painter, const DsoSettingsColorValues *colorValues, double lineHeight, + double scopeHeight, int scopeWidth, bool isPrinter, bool zoom ) { + painter.setRenderHint( QPainter::Antialiasing, false ); + for ( int zoomed = 0; zoomed < ( zoom ? 2 : 1 ); ++zoomed ) { // Set DIVS_TIME x DIVS_VOLTAGE matrix for oscillograph - painter.setTransform( QTransform( QMatrix( (scopeWidth - 1) / DIVS_TIME, 0, 0, -(scopeHeight - 1) / DIVS_VOLTAGE, - double(scopeWidth - 1) / 2, - (scopeHeight - 1) * (zoomed + 0.5) + lineHeight * 1.5 + lineHeight * 2.5 * zoomed) ), - false); + painter.setTransform( + QTransform( QMatrix( + ( scopeWidth - 1 ) / DIVS_TIME, 0, 0, -( scopeHeight - 1 ) / DIVS_VOLTAGE, double( scopeWidth - 1 ) / 2, + ( scopeHeight - 1 ) * ( zoomed + 0.5 ) + lineHeight * 1.5 + lineHeight * 2.5 * zoomed ) ), + false ); // Grid lines - painter.setPen(QPen(colorValues->grid, 0)); + painter.setPen( QPen( colorValues->grid, 0 ) ); - if (isPrinter) { + if ( isPrinter ) { // Draw vertical lines - for (int div = 1; div < DIVS_TIME / 2; ++div) { - for (int dot = 1; dot < DIVS_VOLTAGE / 2 * 5; ++dot) { - painter.drawLine(QPointF(double(-div) - 0.02, double(-dot) / 5), - QPointF(double(-div) + 0.02, double(-dot) / 5)); - painter.drawLine(QPointF(double(-div) - 0.02, double(dot) / 5), - QPointF(double(-div) + 0.02, double(dot) / 5)); - painter.drawLine(QPointF(double(div) - 0.02, double(-dot) / 5), - QPointF(double(div) + 0.02, double(-dot) / 5)); - painter.drawLine(QPointF(double(div) - 0.02, double(dot) / 5), - QPointF(double(div) + 0.02, double(dot) / 5)); + for ( int div = 1; div < DIVS_TIME / 2; ++div ) { + for ( int dot = 1; dot < DIVS_VOLTAGE / 2 * 5; ++dot ) { + painter.drawLine( QPointF( double( -div ) - 0.02, double( -dot ) / 5 ), + QPointF( double( -div ) + 0.02, double( -dot ) / 5 ) ); + painter.drawLine( QPointF( double( -div ) - 0.02, double( dot ) / 5 ), + QPointF( double( -div ) + 0.02, double( dot ) / 5 ) ); + painter.drawLine( QPointF( double( div ) - 0.02, double( -dot ) / 5 ), + QPointF( double( div ) + 0.02, double( -dot ) / 5 ) ); + painter.drawLine( QPointF( double( div ) - 0.02, double( dot ) / 5 ), + QPointF( double( div ) + 0.02, double( dot ) / 5 ) ); } } // Draw horizontal lines - for (int div = 1; div < DIVS_VOLTAGE / 2; ++div) { - for (int dot = 1; dot < DIVS_TIME / 2 * 5; ++dot) { - painter.drawLine(QPointF(double(-dot) / 5, double(-div) - 0.02), - QPointF(double(-dot) / 5, double(-div) + 0.02)); - painter.drawLine(QPointF(double(dot) / 5, double(-div) - 0.02), - QPointF(double(dot) / 5, double(-div) + 0.02)); - painter.drawLine(QPointF(double(-dot) / 5, double(div) - 0.02), - QPointF(double(-dot) / 5, double(div) + 0.02)); - painter.drawLine(QPointF(double(dot) / 5, double(div) - 0.02), - QPointF(double(dot) / 5, double(div) + 0.02)); + for ( int div = 1; div < DIVS_VOLTAGE / 2; ++div ) { + for ( int dot = 1; dot < DIVS_TIME / 2 * 5; ++dot ) { + painter.drawLine( QPointF( double( -dot ) / 5, double( -div ) - 0.02 ), + QPointF( double( -dot ) / 5, double( -div ) + 0.02 ) ); + painter.drawLine( QPointF( double( dot ) / 5, double( -div ) - 0.02 ), + QPointF( double( dot ) / 5, double( -div ) + 0.02 ) ); + painter.drawLine( QPointF( double( -dot ) / 5, double( div ) - 0.02 ), + QPointF( double( -dot ) / 5, double( div ) + 0.02 ) ); + painter.drawLine( QPointF( double( dot ) / 5, double( div ) - 0.02 ), + QPointF( double( dot ) / 5, double( div ) + 0.02 ) ); } } } else { // Draw vertical lines - for (int div = 1; div < DIVS_TIME / 2; ++div) { - for (int dot = 1; dot < DIVS_VOLTAGE / 2 * 5; ++dot) { - painter.drawPoint(QPointF(-div, double(-dot) / 5)); - painter.drawPoint(QPointF(-div, double(dot) / 5)); - painter.drawPoint(QPointF(div, double(-dot) / 5)); - painter.drawPoint(QPointF(div, double(dot) / 5)); + for ( int div = 1; div < DIVS_TIME / 2; ++div ) { + for ( int dot = 1; dot < DIVS_VOLTAGE / 2 * 5; ++dot ) { + painter.drawPoint( QPointF( -div, double( -dot ) / 5 ) ); + painter.drawPoint( QPointF( -div, double( dot ) / 5 ) ); + painter.drawPoint( QPointF( div, double( -dot ) / 5 ) ); + painter.drawPoint( QPointF( div, double( dot ) / 5 ) ); } } // Draw horizontal lines - for (int div = 1; div < DIVS_VOLTAGE / 2; ++div) { - for (int dot = 1; dot < DIVS_TIME / 2 * 5; ++dot) { - if (dot % 5 == 0) continue; // Already done by vertical lines - painter.drawPoint(QPointF(double(-dot) / 5, -div)); - painter.drawPoint(QPointF(double(dot) / 5, -div)); - painter.drawPoint(QPointF(double(-dot) / 5, div)); - painter.drawPoint(QPointF(double(dot) / 5, div)); + for ( int div = 1; div < DIVS_VOLTAGE / 2; ++div ) { + for ( int dot = 1; dot < DIVS_TIME / 2 * 5; ++dot ) { + if ( dot % 5 == 0 ) + continue; // Already done by vertical lines + painter.drawPoint( QPointF( double( -dot ) / 5, -div ) ); + painter.drawPoint( QPointF( double( dot ) / 5, -div ) ); + painter.drawPoint( QPointF( double( -dot ) / 5, div ) ); + painter.drawPoint( QPointF( double( dot ) / 5, div ) ); } } } // Axes - painter.setPen(QPen(colorValues->axes, 0)); - painter.drawLine(QPointF(-DIVS_TIME / 2, 0), QPointF(DIVS_TIME / 2, 0)); - painter.drawLine(QPointF(0, -DIVS_VOLTAGE / 2), QPointF(0, DIVS_VOLTAGE / 2)); - for (double div = 0.2; div <= DIVS_TIME / 2; div += 0.2) { - painter.drawLine(QPointF(div, -0.05), QPointF(div, 0.05)); - painter.drawLine(QPointF(-div, -0.05), QPointF(-div, 0.05)); + painter.setPen( QPen( colorValues->axes, 0 ) ); + painter.drawLine( QPointF( -DIVS_TIME / 2, 0 ), QPointF( DIVS_TIME / 2, 0 ) ); + painter.drawLine( QPointF( 0, -DIVS_VOLTAGE / 2 ), QPointF( 0, DIVS_VOLTAGE / 2 ) ); + for ( double div = 0.2; div <= DIVS_TIME / 2; div += 0.2 ) { + painter.drawLine( QPointF( div, -0.05 ), QPointF( div, 0.05 ) ); + painter.drawLine( QPointF( -div, -0.05 ), QPointF( -div, 0.05 ) ); } - for (double div = 0.2; div <= DIVS_VOLTAGE / 2; div += 0.2) { - painter.drawLine(QPointF(-0.05, div), QPointF(0.05, div)); - painter.drawLine(QPointF(-0.05, -div), QPointF(0.05, -div)); + for ( double div = 0.2; div <= DIVS_VOLTAGE / 2; div += 0.2 ) { + painter.drawLine( QPointF( -0.05, div ), QPointF( 0.05, div ) ); + painter.drawLine( QPointF( -0.05, -div ), QPointF( 0.05, -div ) ); } // Borders - painter.setPen(QPen(colorValues->border, 0)); - painter.drawRect(QRectF(-DIVS_TIME / 2, -DIVS_VOLTAGE / 2, DIVS_TIME, DIVS_VOLTAGE)); + painter.setPen( QPen( colorValues->border, 0 ) ); + painter.drawRect( QRectF( -DIVS_TIME / 2, -DIVS_VOLTAGE / 2, DIVS_TIME, DIVS_VOLTAGE ) ); } } diff --git a/openhantek/src/exporting/legacyexportdrawer.h b/openhantek/src/exporting/legacyexportdrawer.h index e9d3d3ce..0ca6f5af 100644 --- a/openhantek/src/exporting/legacyexportdrawer.h +++ b/openhantek/src/exporting/legacyexportdrawer.h @@ -2,16 +2,18 @@ #pragma once +#include "exportsettings.h" #include #include #include #include -#include "exportsettings.h" class DsoSettings; class PPresult; struct DsoSettingsColorValues; -namespace Dso { struct ControlSpecification; } +namespace Dso { +struct ControlSpecification; +} /// \brief Exports the oscilloscope screen to a file or prints it. /// TODO @@ -25,11 +27,11 @@ namespace Dso { struct ControlSpecification; } class LegacyExportDrawer { public: /// Draw the graphs coming from source and labels to the destination paintdevice. - static bool exportSamples(const PPresult *source, QPaintDevice* dest, - const Dso::ControlSpecification* deviceSpecification, - const DsoSettings *settings, bool isPrinter, const DsoSettingsColorValues *colorValues); + static bool exportSamples( const PPresult *source, QPaintDevice *dest, + const Dso::ControlSpecification *deviceSpecification, const DsoSettings *settings, + bool isPrinter, const DsoSettingsColorValues *colorValues ); private: - static void drawGrids(QPainter &painter, const DsoSettingsColorValues *colorValues, double lineHeight, double scopeHeight, - int scopeWidth, bool isPrinter, bool zoom); + static void drawGrids( QPainter &painter, const DsoSettingsColorValues *colorValues, double lineHeight, + double scopeHeight, int scopeWidth, bool isPrinter, bool zoom ); }; diff --git a/openhantek/src/glscope.cpp b/openhantek/src/glscope.cpp index 95f557b4..2a0ecb73 100644 --- a/openhantek/src/glscope.cpp +++ b/openhantek/src/glscope.cpp @@ -12,8 +12,8 @@ #include #include -#include #include +#include #include "glscope.h" @@ -23,39 +23,39 @@ #include "viewconstants.h" #include "viewsettings.h" -GlScope *GlScope::createNormal(DsoSettingsScope *scope, DsoSettingsView *view, QWidget *parent) { - GlScope *s = new GlScope(scope, view, parent); +GlScope *GlScope::createNormal( DsoSettingsScope *scope, DsoSettingsView *view, QWidget *parent ) { + GlScope *s = new GlScope( scope, view, parent ); s->zoomed = false; return s; } -GlScope *GlScope::createZoomed(DsoSettingsScope *scope, DsoSettingsView *view, QWidget *parent) { - GlScope *s = new GlScope(scope, view, parent); +GlScope *GlScope::createZoomed( DsoSettingsScope *scope, DsoSettingsView *view, QWidget *parent ) { + GlScope *s = new GlScope( scope, view, parent ); s->zoomed = true; return s; } -void GlScope::fixOpenGLversion(QSurfaceFormat::RenderableType t) { - QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts, true); +void GlScope::fixOpenGLversion( QSurfaceFormat::RenderableType t ) { + QCoreApplication::setAttribute( Qt::AA_ShareOpenGLContexts, true ); // Prefer full desktop OpenGL without fixed pipeline QSurfaceFormat format; // TODO: check from time to time if warning has gone, comment next line for now - format.setSamples(4); // antialiasing gives warning with some HW, Qt & OpenGL versions. - format.setProfile(QSurfaceFormat::CoreProfile); - if (t==QSurfaceFormat::OpenGLES) { - format.setVersion(2, 0); - format.setRenderableType(QSurfaceFormat::OpenGLES); - QCoreApplication::setAttribute(Qt::AA_UseOpenGLES, true); + format.setSamples( 4 ); // antialiasing gives warning with some HW, Qt & OpenGL versions. + format.setProfile( QSurfaceFormat::CoreProfile ); + if ( t == QSurfaceFormat::OpenGLES ) { + format.setVersion( 2, 0 ); + format.setRenderableType( QSurfaceFormat::OpenGLES ); + QCoreApplication::setAttribute( Qt::AA_UseOpenGLES, true ); } else { - format.setVersion(3, 2); - format.setRenderableType(QSurfaceFormat::OpenGL); + format.setVersion( 3, 2 ); + format.setRenderableType( QSurfaceFormat::OpenGL ); } - QSurfaceFormat::setDefaultFormat(format); + QSurfaceFormat::setDefaultFormat( format ); } -GlScope::GlScope(DsoSettingsScope *scope, DsoSettingsView *view, QWidget *parent) - : QOpenGLWidget(parent), scope(scope), view(view) { +GlScope::GlScope( DsoSettingsScope *scope, DsoSettingsView *view, QWidget *parent ) + : QOpenGLWidget( parent ), scope( scope ), view( view ) { // get OpenGL version to define appropriate OpenGLSL version // reason: // some not so new intel graphic driver report a very conservative version @@ -64,72 +64,78 @@ GlScope::GlScope(DsoSettingsScope *scope, DsoSettingsView *view, QWidget *parent surface.create(); QOpenGLContext context; context.create(); - context.makeCurrent(&surface); - QString glVersion = reinterpret_cast( context.functions()->glGetString(GL_VERSION) ); + context.makeCurrent( &surface ); + QString glVersion = reinterpret_cast( context.functions()->glGetString( GL_VERSION ) ); GLSLversion = glVersion >= "3.2" ? 150 : 120; // version string "3.2 xxxx" > "3.2" is true // qDebug() << glVersion; // qDebug() << GLSLversion; surface.destroy(); cursorInfo.clear(); - cursorInfo.push_back(&scope->horizontal.cursor); + cursorInfo.push_back( &scope->horizontal.cursor ); selectedCursor = 0; - for (ChannelID channel = 0; channel < scope->voltage.size(); ++channel) { - cursorInfo.push_back(&scope->voltage[channel].cursor); + for ( ChannelID channel = 0; channel < scope->voltage.size(); ++channel ) { + cursorInfo.push_back( &scope->voltage[ channel ].cursor ); } - for (ChannelID channel = 0; channel < scope->spectrum.size(); ++channel) { - cursorInfo.push_back(&scope->spectrum[channel].cursor); + for ( ChannelID channel = 0; channel < scope->spectrum.size(); ++channel ) { + cursorInfo.push_back( &scope->spectrum[ channel ].cursor ); } - vaMarker.resize(cursorInfo.size()); + vaMarker.resize( cursorInfo.size() ); } -GlScope::~GlScope() { /* virtual destructor necessary */ } +GlScope::~GlScope() { /* virtual destructor necessary */ +} -QPointF GlScope::eventToPosition(QMouseEvent *event) { +QPointF GlScope::eventToPosition( QMouseEvent *event ) { QPointF position( double( event->x() - width() / 2 ) * DIVS_TIME / double( width() ), double( height() / 2 - event->y() ) * DIVS_VOLTAGE / double( height() ) ); - if (zoomed) { - double m1 = scope->getMarker(0); - double m2 = scope->getMarker(1); - if (m1 > m2) std::swap(m1, m2); - position.setX(m1 + (0.5 + (position.x() / DIVS_TIME)) * (m2 - m1)); + if ( zoomed ) { + double m1 = scope->getMarker( 0 ); + double m2 = scope->getMarker( 1 ); + if ( m1 > m2 ) + std::swap( m1, m2 ); + position.setX( m1 + ( 0.5 + ( position.x() / DIVS_TIME ) ) * ( m2 - m1 ) ); } return position; } -void GlScope::mousePressEvent(QMouseEvent *event) { - if (!(zoomed && selectedCursor == 0) && event->button() == Qt::LeftButton) { - QPointF position = eventToPosition(event); +void GlScope::mousePressEvent( QMouseEvent *event ) { + if ( !( zoomed && selectedCursor == 0 ) && event->button() == Qt::LeftButton ) { + QPointF position = eventToPosition( event ); selectedMarker = NO_MARKER; - DsoSettingsScopeCursor *cursor = cursorInfo[selectedCursor]; + DsoSettingsScopeCursor *cursor = cursorInfo[ selectedCursor ]; // Capture nearest marker located within snap area (+/- 1% of full scale). - double dX0 = fabs(cursor->pos[0].x() - position.x()); - double dX1 = fabs(cursor->pos[1].x() - position.x()); - double dY0 = fabs(cursor->pos[0].y() - position.y()); - double dY1 = fabs(cursor->pos[1].y() - position.y()); + double dX0 = fabs( cursor->pos[ 0 ].x() - position.x() ); + double dX1 = fabs( cursor->pos[ 1 ].x() - position.x() ); + double dY0 = fabs( cursor->pos[ 0 ].y() - position.y() ); + double dY1 = fabs( cursor->pos[ 1 ].y() - position.y() ); - switch (cursor->shape) { + switch ( cursor->shape ) { case DsoSettingsScopeCursor::RECTANGULAR: - if (std::min(dX0, dX1) < 1.0 / DIVS_SUB && std::min(dY0, dY1) < 1.0 / DIVS_SUB) { + if ( std::min( dX0, dX1 ) < 1.0 / DIVS_SUB && std::min( dY0, dY1 ) < 1.0 / DIVS_SUB ) { // Do we need to swap Y-coords? - if ((dX0 < dX1 && dY0 > dY1) || (dX0 > dX1 && dY0 < dY1)) { - std::swap(cursor->pos[0].ry(), cursor->pos[1].ry()); + if ( ( dX0 < dX1 && dY0 > dY1 ) || ( dX0 > dX1 && dY0 < dY1 ) ) { + std::swap( cursor->pos[ 0 ].ry(), cursor->pos[ 1 ].ry() ); } - selectedMarker = (dX0 < dX1) ? 0 : 1; + selectedMarker = ( dX0 < dX1 ) ? 0 : 1; } break; case DsoSettingsScopeCursor::VERTICAL: - if (dX0 < dX1) { - if (dX0 < 1.0 / DIVS_SUB) selectedMarker = 0; + if ( dX0 < dX1 ) { + if ( dX0 < 1.0 / DIVS_SUB ) + selectedMarker = 0; } else { - if (dX1 < 1.0 / DIVS_SUB) selectedMarker = 1; + if ( dX1 < 1.0 / DIVS_SUB ) + selectedMarker = 1; } break; case DsoSettingsScopeCursor::HORIZONTAL: - if (dY0 < dY1) { - if (dY0 < 1.0 / DIVS_SUB) selectedMarker = 0; + if ( dY0 < dY1 ) { + if ( dY0 < 1.0 / DIVS_SUB ) + selectedMarker = 0; } else { - if (dY1 < 1.0 / DIVS_SUB) selectedMarker = 1; + if ( dY1 < 1.0 / DIVS_SUB ) + selectedMarker = 1; } break; case DsoSettingsScopeCursor::NONE: @@ -137,101 +143,102 @@ void GlScope::mousePressEvent(QMouseEvent *event) { default: break; } - if (selectedMarker != NO_MARKER) { - cursorInfo[selectedCursor]->pos[selectedMarker] = position; - if (selectedCursor == 0) emit markerMoved(selectedCursor, selectedMarker); + if ( selectedMarker != NO_MARKER ) { + cursorInfo[ selectedCursor ]->pos[ selectedMarker ] = position; + if ( selectedCursor == 0 ) + emit markerMoved( selectedCursor, selectedMarker ); } } event->accept(); } -void GlScope::mouseMoveEvent(QMouseEvent *event) { - if (!(zoomed && selectedCursor == 0) && (event->buttons() & Qt::LeftButton) != 0) { - QPointF position = eventToPosition(event); - if (selectedMarker == NO_MARKER) { - //qDebug() << "mouseMoveEvent"; +void GlScope::mouseMoveEvent( QMouseEvent *event ) { + if ( !( zoomed && selectedCursor == 0 ) && ( event->buttons() & Qt::LeftButton ) != 0 ) { + QPointF position = eventToPosition( event ); + if ( selectedMarker == NO_MARKER ) { + // qDebug() << "mouseMoveEvent"; // User started draging outside the snap area of any marker: // move all markers to current position and select last marker in the array. - for (unsigned marker = 0; marker < MARKER_COUNT; ++marker) { - cursorInfo[selectedCursor]->pos[marker] = position; - emit markerMoved(selectedCursor, marker); + for ( unsigned marker = 0; marker < MARKER_COUNT; ++marker ) { + cursorInfo[ selectedCursor ]->pos[ marker ] = position; + emit markerMoved( selectedCursor, marker ); selectedMarker = marker; } - } else if (selectedMarker < MARKER_COUNT) { - cursorInfo[selectedCursor]->pos[selectedMarker] = position; - emit markerMoved(selectedCursor, selectedMarker); + } else if ( selectedMarker < MARKER_COUNT ) { + cursorInfo[ selectedCursor ]->pos[ selectedMarker ] = position; + emit markerMoved( selectedCursor, selectedMarker ); } } event->accept(); } -void GlScope::mouseReleaseEvent(QMouseEvent *event) { - if (!(zoomed && selectedCursor == 0) && event->button() == Qt::LeftButton) { - QPointF position = eventToPosition(event); - if (selectedMarker < MARKER_COUNT) { - //qDebug() << "mouseReleaseEvent"; - cursorInfo[selectedCursor]->pos[selectedMarker] = position; - emit markerMoved(selectedCursor, selectedMarker); +void GlScope::mouseReleaseEvent( QMouseEvent *event ) { + if ( !( zoomed && selectedCursor == 0 ) && event->button() == Qt::LeftButton ) { + QPointF position = eventToPosition( event ); + if ( selectedMarker < MARKER_COUNT ) { + // qDebug() << "mouseReleaseEvent"; + cursorInfo[ selectedCursor ]->pos[ selectedMarker ] = position; + emit markerMoved( selectedCursor, selectedMarker ); } selectedMarker = NO_MARKER; } event->accept(); } -void GlScope::mouseDoubleClickEvent(QMouseEvent *event) { - if (!(zoomed && selectedCursor == 0) && (event->buttons() & Qt::LeftButton) != 0) { +void GlScope::mouseDoubleClickEvent( QMouseEvent *event ) { + if ( !( zoomed && selectedCursor == 0 ) && ( event->buttons() & Qt::LeftButton ) != 0 ) { // left double click positions two markers left and right of clicked pos with zoom=100 - QPointF position = eventToPosition(event); - if (selectedMarker == NO_MARKER) { - //qDebug() << "mouseDoubleClickEvent"; + QPointF position = eventToPosition( event ); + if ( selectedMarker == NO_MARKER ) { + // qDebug() << "mouseDoubleClickEvent"; // User double clicked outside the snap area of any marker: // move all markers but the last left of current position. unsigned marker; - for (marker = 0; marker < MARKER_COUNT-1; ++marker) { - cursorInfo[selectedCursor]->pos[marker] = position - QPointF( 0.05, 0 ); - emit markerMoved(selectedCursor, marker); + for ( marker = 0; marker < MARKER_COUNT - 1; ++marker ) { + cursorInfo[ selectedCursor ]->pos[ marker ] = position - QPointF( 0.05, 0 ); + emit markerMoved( selectedCursor, marker ); } // move last marker right of current position to make zoom=100. - cursorInfo[selectedCursor]->pos[marker] = position + QPointF( 0.05, 0 ); - emit markerMoved(selectedCursor, marker); + cursorInfo[ selectedCursor ]->pos[ marker ] = position + QPointF( 0.05, 0 ); + emit markerMoved( selectedCursor, marker ); // select no marker selectedMarker = NO_MARKER; } - } else if (!(zoomed && selectedCursor == 0) && (event->buttons() & Qt::RightButton) != 0) { + } else if ( !( zoomed && selectedCursor == 0 ) && ( event->buttons() & Qt::RightButton ) != 0 ) { // right double click moves all markers out of the way - cursorInfo[selectedCursor]->pos[0] = QPointF( MARGIN_LEFT, 0 ); - cursorInfo[selectedCursor]->pos[1] = QPointF( MARGIN_RIGHT, 0 ); - emit markerMoved(selectedCursor, 0); - emit markerMoved(selectedCursor, 1); -} + cursorInfo[ selectedCursor ]->pos[ 0 ] = QPointF( MARGIN_LEFT, 0 ); + cursorInfo[ selectedCursor ]->pos[ 1 ] = QPointF( MARGIN_RIGHT, 0 ); + emit markerMoved( selectedCursor, 0 ); + emit markerMoved( selectedCursor, 1 ); + } event->accept(); } -void GlScope::paintEvent(QPaintEvent *event) { +void GlScope::paintEvent( QPaintEvent *event ) { if ( shaderCompileSuccess ) { - QOpenGLWidget::paintEvent(event); + QOpenGLWidget::paintEvent( event ); } else if ( !zoomed ) { // draw error message on normal view if OpenGL failed QPainter painter( this ); painter.setRenderHint( QPainter::Antialiasing, true ); QFont font = painter.font(); font.setPointSize( 18 ); painter.setFont( font ); - painter.drawText( rect(), Qt::AlignCenter|Qt::TextWordWrap, errorMessage); + painter.drawText( rect(), Qt::AlignCenter | Qt::TextWordWrap, errorMessage ); } event->accept(); // consume the event } void GlScope::initializeGL() { - if (!QOpenGLShaderProgram::hasOpenGLShaderPrograms(context())) { - errorMessage = tr("System does not support OpenGL Shading Language (GLSL)"); + if ( !QOpenGLShaderProgram::hasOpenGLShaderPrograms( context() ) ) { + errorMessage = tr( "System does not support OpenGL Shading Language (GLSL)" ); return; } - if (m_program) { - qWarning() << tr("OpenGL init called twice!"); + if ( m_program ) { + qWarning() << tr( "OpenGL init called twice!" ); return; } - auto program = std::unique_ptr(new QOpenGLShaderProgram(context())); + auto program = std::unique_ptr( new QOpenGLShaderProgram( context() ) ); const char *vshaderES = R"( #version 100 @@ -281,128 +288,121 @@ void GlScope::initializeGL() { out vec4 flatColor; void main() { flatColor = colour; } )"; -//GLSLversion = 150; + // GLSLversion = 150; const char *vshaderDesktop = GLSLversion == 120 ? vshaderDesktop120 : vshaderDesktop150; const char *fshaderDesktop = GLSLversion == 120 ? fshaderDesktop120 : fshaderDesktop150; // qDebug() << "compile shaders"; // Compile vertex shader - bool usesOpenGL = QSurfaceFormat::defaultFormat().renderableType()==QSurfaceFormat::OpenGL; - if (!program->addShaderFromSourceCode(QOpenGLShader::Vertex, usesOpenGL ? vshaderDesktop : vshaderES) || - !program->addShaderFromSourceCode(QOpenGLShader::Fragment, usesOpenGL ? fshaderDesktop : fshaderES)) { - errorMessage = tr("Failed to compile OpenGL shader programs.\n") + program->log(); + bool usesOpenGL = QSurfaceFormat::defaultFormat().renderableType() == QSurfaceFormat::OpenGL; + if ( !program->addShaderFromSourceCode( QOpenGLShader::Vertex, usesOpenGL ? vshaderDesktop : vshaderES ) || + !program->addShaderFromSourceCode( QOpenGLShader::Fragment, usesOpenGL ? fshaderDesktop : fshaderES ) ) { + errorMessage = tr( "Failed to compile OpenGL shader programs.\n" ) + program->log(); return; } // Link shader pipeline - if (!program->link() || !program->bind()) { - errorMessage = tr("Failed to link/bind OpenGL shader programs.\n") + program->log(); + if ( !program->link() || !program->bind() ) { + errorMessage = tr( "Failed to link/bind OpenGL shader programs.\n" ) + program->log(); return; } - vertexLocation = program->attributeLocation("vertex"); - matrixLocation = program->uniformLocation("matrix"); - colorLocation = program->uniformLocation("colour"); + vertexLocation = program->attributeLocation( "vertex" ); + matrixLocation = program->uniformLocation( "matrix" ); + colorLocation = program->uniformLocation( "colour" ); - if (vertexLocation == -1 || colorLocation == -1 || matrixLocation == -1) { - qWarning() << tr("Failed to locate shader variable."); + if ( vertexLocation == -1 || colorLocation == -1 || matrixLocation == -1 ) { + qWarning() << tr( "Failed to locate shader variable." ); return; } program->bind(); auto *gl = context()->functions(); - gl->glDisable(GL_DEPTH_TEST); - gl->glEnable(GL_BLEND); + gl->glDisable( GL_DEPTH_TEST ); + gl->glEnable( GL_BLEND ); // Enable depth buffer - gl->glEnable(GL_DEPTH_TEST); + gl->glEnable( GL_DEPTH_TEST ); // Enable back face culling - gl->glEnable(GL_CULL_FACE); - gl->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + gl->glEnable( GL_CULL_FACE ); + gl->glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); QColor bg = view->screen.background; gl->glClearColor( GLfloat( bg.redF() ), GLfloat( bg.greenF() ), GLfloat( bg.blueF() ), GLfloat( bg.alphaF() ) ); - generateGrid(program.get()); + generateGrid( program.get() ); { m_vaoMarker.create(); - QOpenGLVertexArrayObject::Binder b(&m_vaoMarker); + QOpenGLVertexArrayObject::Binder b( &m_vaoMarker ); m_marker.create(); m_marker.bind(); - m_marker.setUsagePattern(QOpenGLBuffer::StaticDraw); - m_marker.allocate(int(vaMarker.size() * sizeof(Vertices))); - program->enableAttributeArray(vertexLocation); - program->setAttributeBuffer(vertexLocation, GL_FLOAT, 0, 3, 0); + m_marker.setUsagePattern( QOpenGLBuffer::StaticDraw ); + m_marker.allocate( int( vaMarker.size() * sizeof( Vertices ) ) ); + program->enableAttributeArray( vertexLocation ); + program->setAttributeBuffer( vertexLocation, GL_FLOAT, 0, 3, 0 ); } updateCursor(); - m_program = std::move(program); + m_program = std::move( program ); shaderCompileSuccess = true; } -void GlScope::showData(std::shared_ptr newData) { - if (!shaderCompileSuccess) return; +void GlScope::showData( std::shared_ptr newData ) { + if ( !shaderCompileSuccess ) + return; makeCurrent(); // Remove too much entries - while (view->digitalPhosphorDraws() < m_GraphHistory.size()) m_GraphHistory.pop_back(); + while ( view->digitalPhosphorDraws() < m_GraphHistory.size() ) + m_GraphHistory.pop_back(); // Add if missing - if (view->digitalPhosphorDraws() > m_GraphHistory.size()) { m_GraphHistory.resize(m_GraphHistory.size() + 1); } + if ( view->digitalPhosphorDraws() > m_GraphHistory.size() ) { + m_GraphHistory.resize( m_GraphHistory.size() + 1 ); + } // Move last item to front - m_GraphHistory.splice(m_GraphHistory.begin(), m_GraphHistory, std::prev(m_GraphHistory.end())); + m_GraphHistory.splice( m_GraphHistory.begin(), m_GraphHistory, std::prev( m_GraphHistory.end() ) ); // Add new entry - m_GraphHistory.front().writeData(newData.get(), m_program.get(), vertexLocation); + m_GraphHistory.front().writeData( newData.get(), m_program.get(), vertexLocation ); // doneCurrent(); update(); } -void GlScope::generateVertices(unsigned marker, const DsoSettingsScopeCursor &cursor) { +void GlScope::generateVertices( unsigned marker, const DsoSettingsScopeCursor &cursor ) { const float Z_ORDER = 1.0f; - switch (cursor.shape) { + switch ( cursor.shape ) { case DsoSettingsScopeCursor::NONE: - vaMarker[marker] = { - QVector3D(-DIVS_TIME, -DIVS_VOLTAGE, Z_ORDER), - QVector3D(-DIVS_TIME, DIVS_VOLTAGE, Z_ORDER), - QVector3D( DIVS_TIME, DIVS_VOLTAGE, Z_ORDER), - QVector3D( DIVS_TIME, -DIVS_VOLTAGE, Z_ORDER) - }; + vaMarker[ marker ] = { + QVector3D( -DIVS_TIME, -DIVS_VOLTAGE, Z_ORDER ), QVector3D( -DIVS_TIME, DIVS_VOLTAGE, Z_ORDER ), + QVector3D( DIVS_TIME, DIVS_VOLTAGE, Z_ORDER ), QVector3D( DIVS_TIME, -DIVS_VOLTAGE, Z_ORDER )}; break; case DsoSettingsScopeCursor::VERTICAL: - vaMarker[marker] = { - QVector3D(GLfloat( cursor.pos[0].x() ), -GLfloat( DIVS_VOLTAGE ), Z_ORDER), - QVector3D(GLfloat( cursor.pos[0].x() ), GLfloat( DIVS_VOLTAGE ), Z_ORDER), - QVector3D(GLfloat( cursor.pos[1].x() ), GLfloat( DIVS_VOLTAGE ), Z_ORDER), - QVector3D(GLfloat( cursor.pos[1].x() ), -GLfloat( DIVS_VOLTAGE ), Z_ORDER) - }; + vaMarker[ marker ] = {QVector3D( GLfloat( cursor.pos[ 0 ].x() ), -GLfloat( DIVS_VOLTAGE ), Z_ORDER ), + QVector3D( GLfloat( cursor.pos[ 0 ].x() ), GLfloat( DIVS_VOLTAGE ), Z_ORDER ), + QVector3D( GLfloat( cursor.pos[ 1 ].x() ), GLfloat( DIVS_VOLTAGE ), Z_ORDER ), + QVector3D( GLfloat( cursor.pos[ 1 ].x() ), -GLfloat( DIVS_VOLTAGE ), Z_ORDER )}; break; case DsoSettingsScopeCursor::HORIZONTAL: - vaMarker[marker] = { - QVector3D(-GLfloat( DIVS_TIME ), GLfloat( cursor.pos[0].y() ), Z_ORDER), - QVector3D( GLfloat( DIVS_TIME ), GLfloat( cursor.pos[0].y() ), Z_ORDER), - QVector3D( GLfloat( DIVS_TIME ), GLfloat( cursor.pos[1].y() ), Z_ORDER), - QVector3D(-GLfloat( DIVS_TIME ), GLfloat( cursor.pos[1].y() ), Z_ORDER) - }; + vaMarker[ marker ] = {QVector3D( -GLfloat( DIVS_TIME ), GLfloat( cursor.pos[ 0 ].y() ), Z_ORDER ), + QVector3D( GLfloat( DIVS_TIME ), GLfloat( cursor.pos[ 0 ].y() ), Z_ORDER ), + QVector3D( GLfloat( DIVS_TIME ), GLfloat( cursor.pos[ 1 ].y() ), Z_ORDER ), + QVector3D( -GLfloat( DIVS_TIME ), GLfloat( cursor.pos[ 1 ].y() ), Z_ORDER )}; break; case DsoSettingsScopeCursor::RECTANGULAR: - if ((cursor.pos[1].x() - cursor.pos[0].x()) * (cursor.pos[1].y() - cursor.pos[0].y()) > 0.0) { - vaMarker[marker] = { - QVector3D(GLfloat( cursor.pos[0].x() ), GLfloat( cursor.pos[0].y() ), Z_ORDER), - QVector3D(GLfloat( cursor.pos[1].x() ), GLfloat( cursor.pos[0].y() ), Z_ORDER), - QVector3D(GLfloat( cursor.pos[1].x() ), GLfloat( cursor.pos[1].y() ), Z_ORDER), - QVector3D(GLfloat( cursor.pos[0].x() ), GLfloat( cursor.pos[1].y() ), Z_ORDER) - }; + if ( ( cursor.pos[ 1 ].x() - cursor.pos[ 0 ].x() ) * ( cursor.pos[ 1 ].y() - cursor.pos[ 0 ].y() ) > 0.0 ) { + vaMarker[ marker ] = {QVector3D( GLfloat( cursor.pos[ 0 ].x() ), GLfloat( cursor.pos[ 0 ].y() ), Z_ORDER ), + QVector3D( GLfloat( cursor.pos[ 1 ].x() ), GLfloat( cursor.pos[ 0 ].y() ), Z_ORDER ), + QVector3D( GLfloat( cursor.pos[ 1 ].x() ), GLfloat( cursor.pos[ 1 ].y() ), Z_ORDER ), + QVector3D( GLfloat( cursor.pos[ 0 ].x() ), GLfloat( cursor.pos[ 1 ].y() ), Z_ORDER )}; } else { - vaMarker[marker] = { - QVector3D(GLfloat( cursor.pos[0].x() ), GLfloat( cursor.pos[0].y() ), Z_ORDER), - QVector3D(GLfloat( cursor.pos[0].x() ), GLfloat( cursor.pos[1].y() ), Z_ORDER), - QVector3D(GLfloat( cursor.pos[1].x() ), GLfloat( cursor.pos[1].y() ), Z_ORDER), - QVector3D(GLfloat( cursor.pos[1].x() ), GLfloat( cursor.pos[0].y() ), Z_ORDER) - }; + vaMarker[ marker ] = {QVector3D( GLfloat( cursor.pos[ 0 ].x() ), GLfloat( cursor.pos[ 0 ].y() ), Z_ORDER ), + QVector3D( GLfloat( cursor.pos[ 0 ].x() ), GLfloat( cursor.pos[ 1 ].y() ), Z_ORDER ), + QVector3D( GLfloat( cursor.pos[ 1 ].x() ), GLfloat( cursor.pos[ 1 ].y() ), Z_ORDER ), + QVector3D( GLfloat( cursor.pos[ 1 ].x() ), GLfloat( cursor.pos[ 0 ].y() ), Z_ORDER )}; } break; default: @@ -410,12 +410,13 @@ void GlScope::generateVertices(unsigned marker, const DsoSettingsScopeCursor &cu } } -void GlScope::updateCursor(unsigned index) { - if (index > 0) { - generateVertices(index, *cursorInfo[index]); - } else for (index = 0; index < cursorInfo.size(); ++index) { - generateVertices(index, *cursorInfo[index]); - } +void GlScope::updateCursor( unsigned index ) { + if ( index > 0 ) { + generateVertices( index, *cursorInfo[ index ] ); + } else + for ( index = 0; index < cursorInfo.size(); ++index ) { + generateVertices( index, *cursorInfo[ index ] ); + } // Write coordinates to GPU makeCurrent(); m_marker.bind(); @@ -423,49 +424,54 @@ void GlScope::updateCursor(unsigned index) { } void GlScope::paintGL() { - if (!shaderCompileSuccess) return; + if ( !shaderCompileSuccess ) + return; auto *gl = context()->functions(); // Clear OpenGL buffer and configure settings // TODO Don't clear if view->digitalPhosphorDraws()>1 - gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - gl->glLineWidth(1); + gl->glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); + gl->glLineWidth( 1 ); m_program->bind(); // Apply zoom settings via matrix transformation - if (zoomed) { + if ( zoomed ) { QMatrix4x4 m; - m.scale( QVector3D( GLfloat( DIVS_TIME ) / GLfloat( fabs( scope->getMarker(1) - scope->getMarker(0) ) ), 1.0f, 1.0f ) ); - m.translate( - GLfloat( scope->getMarker(0) + scope->getMarker(1) ) / 2, 0.0f, 0.0f ); - m_program->setUniformValue(matrixLocation, pmvMatrix * m); + m.scale( QVector3D( GLfloat( DIVS_TIME ) / GLfloat( fabs( scope->getMarker( 1 ) - scope->getMarker( 0 ) ) ), + 1.0f, 1.0f ) ); + m.translate( -GLfloat( scope->getMarker( 0 ) + scope->getMarker( 1 ) ) / 2, 0.0f, 0.0f ); + m_program->setUniformValue( matrixLocation, pmvMatrix * m ); } drawMarkers(); unsigned historyIndex = 0; - for (Graph &graph : m_GraphHistory) { - for (ChannelID channel = 0; channel < scope->voltage.size(); ++channel) { - if (scope->horizontal.format == Dso::GraphFormat::TY) { - drawSpectrumChannelGraph(channel, graph, int( historyIndex) ); + for ( Graph &graph : m_GraphHistory ) { + for ( ChannelID channel = 0; channel < scope->voltage.size(); ++channel ) { + if ( scope->horizontal.format == Dso::GraphFormat::TY ) { + drawSpectrumChannelGraph( channel, graph, int( historyIndex ) ); if ( scope->histogram ) { - drawHistogramChannelGraph(channel, graph, int( historyIndex) ); + drawHistogramChannelGraph( channel, graph, int( historyIndex ) ); } } - drawVoltageChannelGraph(channel, graph, int( historyIndex) ); + drawVoltageChannelGraph( channel, graph, int( historyIndex ) ); } ++historyIndex; } - if (zoomed) { m_program->setUniformValue(matrixLocation, pmvMatrix); } + if ( zoomed ) { + m_program->setUniformValue( matrixLocation, pmvMatrix ); + } drawGrid(); m_program->release(); } -void GlScope::resizeGL(int width, int height) { - if (!shaderCompileSuccess) return; +void GlScope::resizeGL( int width, int height ) { + if ( !shaderCompileSuccess ) + return; auto *gl = context()->functions(); gl->glViewport( 0, 0, GLint( width ), GLint( height ) ); @@ -474,12 +480,13 @@ void GlScope::resizeGL(int width, int height) { float pixelizationHeightCorrection = float( height ) / ( height - 1 ); pmvMatrix.setToIdentity(); - pmvMatrix.ortho( -float( DIVS_TIME ) / 2.0f * pixelizationWidthCorrection, float( DIVS_TIME ) / 2.0f * pixelizationWidthCorrection, + pmvMatrix.ortho( -float( DIVS_TIME ) / 2.0f * pixelizationWidthCorrection, + float( DIVS_TIME ) / 2.0f * pixelizationWidthCorrection, -float( DIVS_VOLTAGE ) / 2.0f * pixelizationHeightCorrection, - float( DIVS_VOLTAGE ) / 2.0f * pixelizationHeightCorrection, -1.0f, 1.0f); + float( DIVS_VOLTAGE ) / 2.0f * pixelizationHeightCorrection, -1.0f, 1.0f ); m_program->bind(); - m_program->setUniformValue(matrixLocation, pmvMatrix); + m_program->setUniformValue( matrixLocation, pmvMatrix ); m_program->release(); } @@ -487,8 +494,8 @@ void GlScope::resizeGL(int width, int height) { // section 0:grid, 1:axes, 2:border void GlScope::draw4Cross( std::vector &va, int section, float x, float y ) { const float d = 0.05f; // cross size - for ( int xSign : { -1, 1 } ) { - for ( int ySign : { -1, 1 } ) { + for ( int xSign : {-1, 1} ) { + for ( int ySign : {-1, 1} ) { gridDrawCounts[ section ] += 4; va.push_back( QVector3D( xSign * ( x - d ), ySign * y, 0 ) ); va.push_back( QVector3D( xSign * ( x + d ), ySign * y, 0 ) ); @@ -498,147 +505,149 @@ void GlScope::draw4Cross( std::vector &va, int section, float x, floa } } -void GlScope::generateGrid(QOpenGLShaderProgram *program) { - gridDrawCounts[0] = 0; - gridDrawCounts[1] = 0; - gridDrawCounts[2] = 0; +void GlScope::generateGrid( QOpenGLShaderProgram *program ) { + gridDrawCounts[ 0 ] = 0; + gridDrawCounts[ 1 ] = 0; + gridDrawCounts[ 2 ] = 0; m_grid.create(); m_grid.bind(); - m_grid.setUsagePattern(QOpenGLBuffer::StaticDraw); + m_grid.setUsagePattern( QOpenGLBuffer::StaticDraw ); std::vector vaGrid; { // Bind draw vertical lines - m_vaoGrid[0].create(); - QOpenGLVertexArrayObject::Binder b(&m_vaoGrid[0]); + m_vaoGrid[ 0 ].create(); + QOpenGLVertexArrayObject::Binder b( &m_vaoGrid[ 0 ] ); m_grid.bind(); - program->enableAttributeArray(vertexLocation); - program->setAttributeBuffer(vertexLocation, GL_FLOAT, 0, 3, 0); + program->enableAttributeArray( vertexLocation ); + program->setAttributeBuffer( vertexLocation, GL_FLOAT, 0, 3, 0 ); } // Draw vertical dot lines - for (int vDiv = 1; vDiv < DIVS_TIME / 2; ++vDiv ) { - for (int dot = 1; dot < DIVS_VOLTAGE / 2 * DIVS_SUB; ++dot) { + for ( int vDiv = 1; vDiv < DIVS_TIME / 2; ++vDiv ) { + for ( int dot = 1; dot < DIVS_VOLTAGE / 2 * DIVS_SUB; ++dot ) { float dotPosition = float( dot ) / DIVS_SUB; - gridDrawCounts[0] += 4; - vaGrid.push_back(QVector3D(-vDiv, -dotPosition, 0)); - vaGrid.push_back(QVector3D(-vDiv, dotPosition, 0)); - vaGrid.push_back(QVector3D( vDiv, -dotPosition, 0)); - vaGrid.push_back(QVector3D( vDiv, dotPosition, 0)); + gridDrawCounts[ 0 ] += 4; + vaGrid.push_back( QVector3D( -vDiv, -dotPosition, 0 ) ); + vaGrid.push_back( QVector3D( -vDiv, dotPosition, 0 ) ); + vaGrid.push_back( QVector3D( vDiv, -dotPosition, 0 ) ); + vaGrid.push_back( QVector3D( vDiv, dotPosition, 0 ) ); } } // Draw horizontal dot lines - for (int hDiv = 1; hDiv < DIVS_VOLTAGE / 2; ++hDiv ) { - for (int dot = 1; dot < DIVS_TIME / 2 * DIVS_SUB; ++dot) { - if (dot % DIVS_SUB == 0) continue; // Already done by vertical lines + for ( int hDiv = 1; hDiv < DIVS_VOLTAGE / 2; ++hDiv ) { + for ( int dot = 1; dot < DIVS_TIME / 2 * DIVS_SUB; ++dot ) { + if ( dot % DIVS_SUB == 0 ) + continue; // Already done by vertical lines float dotPosition = float( dot ) / DIVS_SUB; - gridDrawCounts[0] += 4; - vaGrid.push_back(QVector3D(-dotPosition, -hDiv, 0)); - vaGrid.push_back(QVector3D( dotPosition, -hDiv, 0)); - vaGrid.push_back(QVector3D(-dotPosition, hDiv, 0)); - vaGrid.push_back(QVector3D( dotPosition, hDiv, 0)); + gridDrawCounts[ 0 ] += 4; + vaGrid.push_back( QVector3D( -dotPosition, -hDiv, 0 ) ); + vaGrid.push_back( QVector3D( dotPosition, -hDiv, 0 ) ); + vaGrid.push_back( QVector3D( -dotPosition, hDiv, 0 ) ); + vaGrid.push_back( QVector3D( dotPosition, hDiv, 0 ) ); } } { // Bind draw axes - m_vaoGrid[1].create(); - QOpenGLVertexArrayObject::Binder b(&m_vaoGrid[1]); + m_vaoGrid[ 1 ].create(); + QOpenGLVertexArrayObject::Binder b( &m_vaoGrid[ 1 ] ); m_grid.bind(); - program->enableAttributeArray(vertexLocation); - program->setAttributeBuffer(vertexLocation, GL_FLOAT, int(vaGrid.size() * sizeof(QVector3D)), 3); + program->enableAttributeArray( vertexLocation ); + program->setAttributeBuffer( vertexLocation, GL_FLOAT, int( vaGrid.size() * sizeof( QVector3D ) ), 3 ); } // Axes // Horizontal axis - gridDrawCounts[1] += 2; - vaGrid.push_back(QVector3D(-DIVS_TIME / 2, 0, 0)); - vaGrid.push_back(QVector3D( DIVS_TIME / 2, 0, 0)); + gridDrawCounts[ 1 ] += 2; + vaGrid.push_back( QVector3D( -DIVS_TIME / 2, 0, 0 ) ); + vaGrid.push_back( QVector3D( DIVS_TIME / 2, 0, 0 ) ); // Vertical axis - gridDrawCounts[1] += 2; - vaGrid.push_back(QVector3D(0, -DIVS_VOLTAGE / 2, 0)); - vaGrid.push_back(QVector3D(0, DIVS_VOLTAGE / 2, 0)); + gridDrawCounts[ 1 ] += 2; + vaGrid.push_back( QVector3D( 0, -DIVS_VOLTAGE / 2, 0 ) ); + vaGrid.push_back( QVector3D( 0, DIVS_VOLTAGE / 2, 0 ) ); // Subdiv lines on horizontal axis - for (int line = 1; line < DIVS_TIME / 2 * DIVS_SUB; ++line) { + for ( int line = 1; line < DIVS_TIME / 2 * DIVS_SUB; ++line ) { float linePosition = float( line ) / DIVS_SUB; - gridDrawCounts[1] += 4; - vaGrid.push_back(QVector3D(linePosition, -0.05f, 0)); - vaGrid.push_back(QVector3D(linePosition, 0.05f, 0)); - vaGrid.push_back(QVector3D(-linePosition, -0.05f, 0)); - vaGrid.push_back(QVector3D(-linePosition, 0.05f, 0)); + gridDrawCounts[ 1 ] += 4; + vaGrid.push_back( QVector3D( linePosition, -0.05f, 0 ) ); + vaGrid.push_back( QVector3D( linePosition, 0.05f, 0 ) ); + vaGrid.push_back( QVector3D( -linePosition, -0.05f, 0 ) ); + vaGrid.push_back( QVector3D( -linePosition, 0.05f, 0 ) ); } // Subdiv lines on vertical axis - for (int line = 1; line < DIVS_VOLTAGE / 2 * DIVS_SUB; ++line) { + for ( int line = 1; line < DIVS_VOLTAGE / 2 * DIVS_SUB; ++line ) { float linePosition = float( line ) / DIVS_SUB; - gridDrawCounts[1] += 4; - vaGrid.push_back(QVector3D(-0.05f, linePosition, 0)); - vaGrid.push_back(QVector3D(0.05f, linePosition, 0)); - vaGrid.push_back(QVector3D(-0.05f, -linePosition, 0)); - vaGrid.push_back(QVector3D(0.05f, -linePosition, 0)); + gridDrawCounts[ 1 ] += 4; + vaGrid.push_back( QVector3D( -0.05f, linePosition, 0 ) ); + vaGrid.push_back( QVector3D( 0.05f, linePosition, 0 ) ); + vaGrid.push_back( QVector3D( -0.05f, -linePosition, 0 ) ); + vaGrid.push_back( QVector3D( 0.05f, -linePosition, 0 ) ); } // Draw vertical cross lines - for (int vDiv = 1; vDiv < DIVS_TIME / 2; ++vDiv ) { - for (int hDiv = 1; hDiv < DIVS_VOLTAGE / 2; ++hDiv ) { + for ( int vDiv = 1; vDiv < DIVS_TIME / 2; ++vDiv ) { + for ( int hDiv = 1; hDiv < DIVS_VOLTAGE / 2; ++hDiv ) { draw4Cross( vaGrid, 1, vDiv, hDiv ); } } // Draw horizontal cross lines - for (int hDiv = 1; hDiv < DIVS_VOLTAGE / 2; ++hDiv ) { - for (int vDiv = 1; vDiv < DIVS_TIME / 2; ++vDiv ) { - if ( vDiv % DIVS_SUB == 0) continue; // Already done by vertical lines + for ( int hDiv = 1; hDiv < DIVS_VOLTAGE / 2; ++hDiv ) { + for ( int vDiv = 1; vDiv < DIVS_TIME / 2; ++vDiv ) { + if ( vDiv % DIVS_SUB == 0 ) + continue; // Already done by vertical lines draw4Cross( vaGrid, 1, vDiv, hDiv ); } } { - m_vaoGrid[2].create(); - QOpenGLVertexArrayObject::Binder b(&m_vaoGrid[2]); + m_vaoGrid[ 2 ].create(); + QOpenGLVertexArrayObject::Binder b( &m_vaoGrid[ 2 ] ); m_grid.bind(); - program->enableAttributeArray(vertexLocation); - program->setAttributeBuffer(vertexLocation, GL_FLOAT, int(vaGrid.size() * sizeof(QVector3D)), 3); + program->enableAttributeArray( vertexLocation ); + program->setAttributeBuffer( vertexLocation, GL_FLOAT, int( vaGrid.size() * sizeof( QVector3D ) ), 3 ); } // Border - gridDrawCounts[2] += 4; - vaGrid.push_back(QVector3D(-DIVS_TIME / 2, -DIVS_VOLTAGE / 2, 0)); - vaGrid.push_back(QVector3D(DIVS_TIME / 2, -DIVS_VOLTAGE / 2, 0)); - vaGrid.push_back(QVector3D(DIVS_TIME / 2, DIVS_VOLTAGE / 2, 0)); - vaGrid.push_back(QVector3D(-DIVS_TIME / 2, DIVS_VOLTAGE / 2, 0)); + gridDrawCounts[ 2 ] += 4; + vaGrid.push_back( QVector3D( -DIVS_TIME / 2, -DIVS_VOLTAGE / 2, 0 ) ); + vaGrid.push_back( QVector3D( DIVS_TIME / 2, -DIVS_VOLTAGE / 2, 0 ) ); + vaGrid.push_back( QVector3D( DIVS_TIME / 2, DIVS_VOLTAGE / 2, 0 ) ); + vaGrid.push_back( QVector3D( -DIVS_TIME / 2, DIVS_VOLTAGE / 2, 0 ) ); - m_grid.allocate(&vaGrid[0], int(vaGrid.size() * sizeof(QVector3D))); + m_grid.allocate( &vaGrid[ 0 ], int( vaGrid.size() * sizeof( QVector3D ) ) ); m_grid.release(); } void GlScope::drawGrid() { auto *gl = context()->functions(); - gl->glLineWidth(1); + gl->glLineWidth( 1 ); // Grid - m_vaoGrid[0].bind(); - m_program->setUniformValue(colorLocation, view->screen.grid); - gl->glDrawArrays(GL_POINTS, 0, gridDrawCounts[0]); - m_vaoGrid[0].release(); + m_vaoGrid[ 0 ].bind(); + m_program->setUniformValue( colorLocation, view->screen.grid ); + gl->glDrawArrays( GL_POINTS, 0, gridDrawCounts[ 0 ] ); + m_vaoGrid[ 0 ].release(); // Axes and div crosses - m_vaoGrid[1].bind(); - m_program->setUniformValue(colorLocation, view->screen.axes); - gl->glDrawArrays(GL_LINES, 0, gridDrawCounts[1]); - m_vaoGrid[1].release(); + m_vaoGrid[ 1 ].bind(); + m_program->setUniformValue( colorLocation, view->screen.axes ); + gl->glDrawArrays( GL_LINES, 0, gridDrawCounts[ 1 ] ); + m_vaoGrid[ 1 ].release(); // Border - m_vaoGrid[2].bind(); - m_program->setUniformValue(colorLocation, view->screen.border); - gl->glDrawArrays(GL_LINE_LOOP, 0, gridDrawCounts[2]); - m_vaoGrid[2].release(); + m_vaoGrid[ 2 ].bind(); + m_program->setUniformValue( colorLocation, view->screen.border ); + gl->glDrawArrays( GL_LINE_LOOP, 0, gridDrawCounts[ 2 ] ); + m_vaoGrid[ 2 ].release(); } -void GlScope::drawVertices(QOpenGLFunctions *gl, unsigned marker, QColor color) { - m_program->setUniformValue(colorLocation, (marker == selectedCursor) ? color : color.darker()); - gl->glDrawArrays( GL_LINE_LOOP, GLint( marker * VERTICES_ARRAY_SIZE), GLint( VERTICES_ARRAY_SIZE ) ); - if (cursorInfo[marker]->shape == DsoSettingsScopeCursor::RECTANGULAR) { - color.setAlphaF(0.25); - m_program->setUniformValue(colorLocation, color.darker()); +void GlScope::drawVertices( QOpenGLFunctions *gl, unsigned marker, QColor color ) { + m_program->setUniformValue( colorLocation, ( marker == selectedCursor ) ? color : color.darker() ); + gl->glDrawArrays( GL_LINE_LOOP, GLint( marker * VERTICES_ARRAY_SIZE ), GLint( VERTICES_ARRAY_SIZE ) ); + if ( cursorInfo[ marker ]->shape == DsoSettingsScopeCursor::RECTANGULAR ) { + color.setAlphaF( 0.25 ); + m_program->setUniformValue( colorLocation, color.darker() ); gl->glDrawArrays( GL_TRIANGLE_FAN, GLint( marker * VERTICES_ARRAY_SIZE ), GLint( VERTICES_ARRAY_SIZE ) ); } } @@ -649,56 +658,59 @@ void GlScope::drawMarkers() { m_vaoMarker.bind(); unsigned marker = 0; - drawVertices(gl, marker, view->screen.markers); + drawVertices( gl, marker, view->screen.markers ); ++marker; - if (view->cursorsVisible) { - gl->glDepthMask(GL_FALSE); - for (ChannelID channel = 0; channel < scope->voltage.size(); ++channel, ++marker) { - if (scope->voltage[channel].used) { - drawVertices(gl, marker, view->screen.voltage[channel]); + if ( view->cursorsVisible ) { + gl->glDepthMask( GL_FALSE ); + for ( ChannelID channel = 0; channel < scope->voltage.size(); ++channel, ++marker ) { + if ( scope->voltage[ channel ].used ) { + drawVertices( gl, marker, view->screen.voltage[ channel ] ); } } - for (ChannelID channel = 0; channel < scope->spectrum.size(); ++channel, ++marker) { - if (scope->spectrum[channel].used) { - drawVertices(gl, marker, view->screen.spectrum[channel]); + for ( ChannelID channel = 0; channel < scope->spectrum.size(); ++channel, ++marker ) { + if ( scope->spectrum[ channel ].used ) { + drawVertices( gl, marker, view->screen.spectrum[ channel ] ); } } - gl->glDepthMask(GL_TRUE); + gl->glDepthMask( GL_TRUE ); } m_vaoMarker.release(); } -void GlScope::drawVoltageChannelGraph(ChannelID channel, Graph &graph, int historyIndex) { - if (!scope->voltage[channel].used) return; +void GlScope::drawVoltageChannelGraph( ChannelID channel, Graph &graph, int historyIndex ) { + if ( !scope->voltage[ channel ].used ) + return; - m_program->setUniformValue(colorLocation, view->screen.voltage[channel].darker(100 + 10 * historyIndex)); - Graph::VaoCount &v = graph.vaoVoltage[channel]; + m_program->setUniformValue( colorLocation, view->screen.voltage[ channel ].darker( 100 + 10 * historyIndex ) ); + Graph::VaoCount &v = graph.vaoVoltage[ channel ]; - QOpenGLVertexArrayObject::Binder b(v.first); - const GLenum dMode = (view->interpolation == Dso::INTERPOLATION_OFF) ? GL_POINTS : GL_LINE_STRIP; - context()->functions()->glDrawArrays(dMode, 0, v.second); + QOpenGLVertexArrayObject::Binder b( v.first ); + const GLenum dMode = ( view->interpolation == Dso::INTERPOLATION_OFF ) ? GL_POINTS : GL_LINE_STRIP; + context()->functions()->glDrawArrays( dMode, 0, v.second ); } -void GlScope::drawHistogramChannelGraph(ChannelID channel, Graph &graph, int historyIndex) { - if (!scope->voltage[channel].used) return; +void GlScope::drawHistogramChannelGraph( ChannelID channel, Graph &graph, int historyIndex ) { + if ( !scope->voltage[ channel ].used ) + return; - m_program->setUniformValue(colorLocation, view->screen.voltage[channel].darker(100 + 10 * historyIndex)); - Graph::VaoCount &h = graph.vaoHistogram[channel]; + m_program->setUniformValue( colorLocation, view->screen.voltage[ channel ].darker( 100 + 10 * historyIndex ) ); + Graph::VaoCount &h = graph.vaoHistogram[ channel ]; - QOpenGLVertexArrayObject::Binder b(h.first); - const GLenum dMode = (view->interpolation == Dso::INTERPOLATION_OFF) ? GL_POINTS : GL_LINES; - context()->functions()->glDrawArrays(dMode, 0, h.second); + QOpenGLVertexArrayObject::Binder b( h.first ); + const GLenum dMode = ( view->interpolation == Dso::INTERPOLATION_OFF ) ? GL_POINTS : GL_LINES; + context()->functions()->glDrawArrays( dMode, 0, h.second ); } -void GlScope::drawSpectrumChannelGraph(ChannelID channel, Graph &graph, int historyIndex) { - if (!scope->spectrum[channel].used) return; +void GlScope::drawSpectrumChannelGraph( ChannelID channel, Graph &graph, int historyIndex ) { + if ( !scope->spectrum[ channel ].used ) + return; - m_program->setUniformValue(colorLocation, view->screen.spectrum[channel].darker(100 + 10 * historyIndex)); - Graph::VaoCount &v = graph.vaoSpectrum[channel]; + m_program->setUniformValue( colorLocation, view->screen.spectrum[ channel ].darker( 100 + 10 * historyIndex ) ); + Graph::VaoCount &v = graph.vaoSpectrum[ channel ]; - QOpenGLVertexArrayObject::Binder b(v.first); - const GLenum dMode = (view->interpolation == Dso::INTERPOLATION_OFF) ? GL_POINTS : GL_LINE_STRIP; - context()->functions()->glDrawArrays(dMode, 0, v.second); + QOpenGLVertexArrayObject::Binder b( v.first ); + const GLenum dMode = ( view->interpolation == Dso::INTERPOLATION_OFF ) ? GL_POINTS : GL_LINE_STRIP; + context()->functions()->glDrawArrays( dMode, 0, v.second ); } diff --git a/openhantek/src/glscope.h b/openhantek/src/glscope.h index ad244a3f..8e121088 100644 --- a/openhantek/src/glscope.h +++ b/openhantek/src/glscope.h @@ -2,15 +2,15 @@ #pragma once -#include #include +#include -#include #include #include #include #include #include +#include #include "glscopegraph.h" #include "hantekdso/enums.h" @@ -26,31 +26,32 @@ class GlScope : public QOpenGLWidget { Q_OBJECT public: - static GlScope *createNormal(DsoSettingsScope *scope, DsoSettingsView *view, - QWidget *parent = nullptr); - static GlScope *createZoomed(DsoSettingsScope *scope, DsoSettingsView *view, - QWidget *parent = nullptr); + static GlScope *createNormal( DsoSettingsScope *scope, DsoSettingsView *view, QWidget *parent = nullptr ); + static GlScope *createZoomed( DsoSettingsScope *scope, DsoSettingsView *view, QWidget *parent = nullptr ); /** * We need at least OpenGL 3.2 with shader version 150 or * OpenGL ES 2.0 with shader version 100. */ - static void fixOpenGLversion(QSurfaceFormat::RenderableType t=QSurfaceFormat::DefaultRenderableType); + static void fixOpenGLversion( QSurfaceFormat::RenderableType t = QSurfaceFormat::DefaultRenderableType ); /** * Show new post processed data * @param data */ - void showData(std::shared_ptr newData); - void updateCursor(unsigned index = 0); - void cursorSelected(unsigned index) { selectedCursor = index; updateCursor(index); } + void showData( std::shared_ptr newData ); + void updateCursor( unsigned index = 0 ); + void cursorSelected( unsigned index ) { + selectedCursor = index; + updateCursor( index ); + } protected: /// \brief Initializes the scope widget. /// \param settings The settings that should be used. /// \param parent The parent widget. - GlScope(DsoSettingsScope *scope, DsoSettingsView *view, QWidget *parent = nullptr); + GlScope( DsoSettingsScope *scope, DsoSettingsView *view, QWidget *parent = nullptr ); ~GlScope() override; - GlScope(const GlScope&) = delete; + GlScope( const GlScope & ) = delete; /// \brief Initializes OpenGL output. void initializeGL() override; @@ -61,27 +62,27 @@ class GlScope : public QOpenGLWidget { /// \brief Resize the widget. /// \param width The new width of the widget. /// \param height The new height of the widget. - void resizeGL(int width, int height) override; + void resizeGL( int width, int height ) override; - void mousePressEvent(QMouseEvent *event) override; - void mouseMoveEvent(QMouseEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override; - void mouseDoubleClickEvent(QMouseEvent *event) override; - void paintEvent(QPaintEvent *event) override; + void mousePressEvent( QMouseEvent *event ) override; + void mouseMoveEvent( QMouseEvent *event ) override; + void mouseReleaseEvent( QMouseEvent *event ) override; + void mouseDoubleClickEvent( QMouseEvent *event ) override; + void paintEvent( QPaintEvent *event ) override; /// \brief Draw the grid. void drawGrid(); /// Draw vertical lines at marker positions void drawMarkers(); - void generateVertices(unsigned marker, const DsoSettingsScopeCursor &cursor); - void drawVertices(QOpenGLFunctions *gl, unsigned marker, QColor color); + void generateVertices( unsigned marker, const DsoSettingsScopeCursor &cursor ); + void drawVertices( QOpenGLFunctions *gl, unsigned marker, QColor color ); - void drawVoltageChannelGraph(ChannelID channel, Graph &graph, int historyIndex); - void drawHistogramChannelGraph(ChannelID channel, Graph &graph, int historyIndex); - void drawSpectrumChannelGraph(ChannelID channel, Graph &graph, int historyIndex); - QPointF eventToPosition(QMouseEvent *event); + void drawVoltageChannelGraph( ChannelID channel, Graph &graph, int historyIndex ); + void drawHistogramChannelGraph( ChannelID channel, Graph &graph, int historyIndex ); + void drawSpectrumChannelGraph( ChannelID channel, Graph &graph, int historyIndex ); + QPointF eventToPosition( QMouseEvent *event ); signals: - void markerMoved(unsigned cursorIndex, unsigned marker); + void markerMoved( unsigned cursorIndex, unsigned marker ); private: // User settings @@ -91,12 +92,12 @@ class GlScope : public QOpenGLWidget { // Marker const unsigned NO_MARKER = UINT_MAX; - #pragma pack(push, 1) +#pragma pack( push, 1 ) struct Vertices { QVector3D a, b, c, d; }; - #pragma pack(pop) - const unsigned VERTICES_ARRAY_SIZE = sizeof(Vertices) / sizeof(QVector3D); +#pragma pack( pop ) + const unsigned VERTICES_ARRAY_SIZE = sizeof( Vertices ) / sizeof( QVector3D ); std::vector vaMarker; unsigned selectedMarker = NO_MARKER; QOpenGLBuffer m_marker; @@ -108,9 +109,9 @@ class GlScope : public QOpenGLWidget { // Grid QOpenGLBuffer m_grid; - QOpenGLVertexArrayObject m_vaoGrid[3]; - GLsizei gridDrawCounts[3]; - void generateGrid(QOpenGLShaderProgram *program); + QOpenGLVertexArrayObject m_vaoGrid[ 3 ]; + GLsizei gridDrawCounts[ 3 ]; + void generateGrid( QOpenGLShaderProgram *program ); void draw4Cross( std::vector &va, int section, float x, float y ); diff --git a/openhantek/src/glscopegraph.cpp b/openhantek/src/glscopegraph.cpp index 528bfb09..bed4c645 100644 --- a/openhantek/src/glscopegraph.cpp +++ b/openhantek/src/glscopegraph.cpp @@ -3,84 +3,91 @@ #include "glscopegraph.h" #include -Graph::Graph() : buffer(QOpenGLBuffer::VertexBuffer) { +Graph::Graph() : buffer( QOpenGLBuffer::VertexBuffer ) { buffer.create(); - buffer.setUsagePattern(QOpenGLBuffer::DynamicDraw); + buffer.setUsagePattern( QOpenGLBuffer::DynamicDraw ); } -void Graph::writeData(PPresult *data, QOpenGLShaderProgram *program, int vertexLocation) { +void Graph::writeData( PPresult *data, QOpenGLShaderProgram *program, int vertexLocation ) { // Determine memory int neededMemory = 0; - for (ChannelGraph &cg : data->vaChannelVoltage) neededMemory += int( cg.size() * sizeof(QVector3D) ); - for (ChannelGraph &cg : data->vaChannelHistogram) neededMemory += int( cg.size() * sizeof(QVector3D) ); - for (ChannelGraph &cg : data->vaChannelSpectrum) neededMemory += int( cg.size() * sizeof(QVector3D) ); + for ( ChannelGraph &cg : data->vaChannelVoltage ) + neededMemory += int( cg.size() * sizeof( QVector3D ) ); + for ( ChannelGraph &cg : data->vaChannelHistogram ) + neededMemory += int( cg.size() * sizeof( QVector3D ) ); + for ( ChannelGraph &cg : data->vaChannelSpectrum ) + neededMemory += int( cg.size() * sizeof( QVector3D ) ); buffer.bind(); program->bind(); // Allocate space if necessary - if (neededMemory > allocatedMem) { - buffer.allocate(neededMemory); + if ( neededMemory > allocatedMem ) { + buffer.allocate( neededMemory ); allocatedMem = neededMemory; } // Write data to buffer int offset = 0; - vaoVoltage.resize(data->vaChannelVoltage.size()); - vaoHistogram.resize(data->vaChannelHistogram.size()); - vaoSpectrum.resize(data->vaChannelSpectrum.size()); - for (ChannelID channel = 0; channel < std::max( std::max(vaoVoltage.size(), vaoHistogram.size()), vaoSpectrum.size() ); ++channel) { + vaoVoltage.resize( data->vaChannelVoltage.size() ); + vaoHistogram.resize( data->vaChannelHistogram.size() ); + vaoSpectrum.resize( data->vaChannelSpectrum.size() ); + for ( ChannelID channel = 0; + channel < std::max( std::max( vaoVoltage.size(), vaoHistogram.size() ), vaoSpectrum.size() ); ++channel ) { int dataSize; // Voltage channel - if (channel < vaoVoltage.size()) { - VaoCount &v = vaoVoltage[channel]; - if (!v.first) { + if ( channel < vaoVoltage.size() ) { + VaoCount &v = vaoVoltage[ channel ]; + if ( !v.first ) { v.first = new QOpenGLVertexArrayObject; - if (!v.first->create()) throw new std::runtime_error("QOpenGLVertexArrayObject create failed"); + if ( !v.first->create() ) + throw new std::runtime_error( "QOpenGLVertexArrayObject create failed" ); } - ChannelGraph &gVoltage = data->vaChannelVoltage[channel]; + ChannelGraph &gVoltage = data->vaChannelVoltage[ channel ]; v.first->bind(); - dataSize = int(gVoltage.size() * sizeof(QVector3D)); - buffer.write(offset, gVoltage.data(), dataSize); - program->enableAttributeArray(vertexLocation); - program->setAttributeBuffer(vertexLocation, GL_FLOAT, offset, 3, 0); + dataSize = int( gVoltage.size() * sizeof( QVector3D ) ); + buffer.write( offset, gVoltage.data(), dataSize ); + program->enableAttributeArray( vertexLocation ); + program->setAttributeBuffer( vertexLocation, GL_FLOAT, offset, 3, 0 ); v.first->release(); v.second = int( gVoltage.size() ); offset += dataSize; } // Histogram channel - if (channel < vaoHistogram.size()) { - VaoCount &h = vaoHistogram[channel]; - if (!h.first) { + if ( channel < vaoHistogram.size() ) { + VaoCount &h = vaoHistogram[ channel ]; + if ( !h.first ) { h.first = new QOpenGLVertexArrayObject; - if (!h.first->create()) throw new std::runtime_error("QOpenGLVertexArrayObject create failed"); + if ( !h.first->create() ) + throw new std::runtime_error( "QOpenGLVertexArrayObject create failed" ); } - ChannelGraph &gHistogram = data->vaChannelHistogram[channel]; + ChannelGraph &gHistogram = data->vaChannelHistogram[ channel ]; h.first->bind(); - dataSize = int(gHistogram.size() * sizeof(QVector3D)); - buffer.write(offset, gHistogram.data(), dataSize); - program->enableAttributeArray(vertexLocation); - program->setAttributeBuffer(vertexLocation, GL_FLOAT, offset, 3, 0); + dataSize = int( gHistogram.size() * sizeof( QVector3D ) ); + buffer.write( offset, gHistogram.data(), dataSize ); + program->enableAttributeArray( vertexLocation ); + program->setAttributeBuffer( vertexLocation, GL_FLOAT, offset, 3, 0 ); h.first->release(); h.second = int( gHistogram.size() ); offset += dataSize; } // Spectrum channel - if (channel < vaoSpectrum.size()) { - VaoCount &s = vaoSpectrum[channel]; - if (!s.first) { + if ( channel < vaoSpectrum.size() ) { + VaoCount &s = vaoSpectrum[ channel ]; + if ( !s.first ) { s.first = new QOpenGLVertexArrayObject; - if (!s.first->create()) throw new std::runtime_error("QOpenGLVertexArrayObject create failed"); + if ( !s.first->create() ) + throw new std::runtime_error( "QOpenGLVertexArrayObject create failed" ); } - ChannelGraph &gSpectrum = data->vaChannelSpectrum[channel]; + ChannelGraph &gSpectrum = data->vaChannelSpectrum[ channel ]; s.first->bind(); - dataSize = int(gSpectrum.size() * sizeof(QVector3D)); - buffer.write(offset, gSpectrum.data(), dataSize); - program->enableAttributeArray(vertexLocation); - program->setAttributeBuffer(vertexLocation, GL_FLOAT, offset, 3, 0); + dataSize = int( gSpectrum.size() * sizeof( QVector3D ) ); + buffer.write( offset, gSpectrum.data(), dataSize ); + program->enableAttributeArray( vertexLocation ); + program->setAttributeBuffer( vertexLocation, GL_FLOAT, offset, 3, 0 ); s.first->release(); s.second = int( gSpectrum.size() ); offset += dataSize; @@ -91,17 +98,19 @@ void Graph::writeData(PPresult *data, QOpenGLShaderProgram *program, int vertexL } Graph::~Graph() { - for (auto &vao : vaoVoltage) { + for ( auto &vao : vaoVoltage ) { vao.first->destroy(); delete vao.first; } - for (auto &vao : vaoHistogram) { + for ( auto &vao : vaoHistogram ) { vao.first->destroy(); delete vao.first; } - for (auto &vao : vaoSpectrum) { + for ( auto &vao : vaoSpectrum ) { vao.first->destroy(); delete vao.first; } - if (buffer.isCreated()) { buffer.destroy(); } + if ( buffer.isCreated() ) { + buffer.destroy(); + } } diff --git a/openhantek/src/glscopegraph.h b/openhantek/src/glscopegraph.h index f3ac2453..c8196ce7 100644 --- a/openhantek/src/glscopegraph.h +++ b/openhantek/src/glscopegraph.h @@ -15,10 +15,10 @@ struct Graph { explicit Graph(); - Graph(const Graph &) = delete; - Graph(const Graph &&) = delete; + Graph( const Graph & ) = delete; + Graph( const Graph && ) = delete; ~Graph(); - void writeData(PPresult *data, QOpenGLShaderProgram *program, int vertexLocation); + void writeData( PPresult *data, QOpenGLShaderProgram *program, int vertexLocation ); typedef std::pair VaoCount; public: diff --git a/openhantek/src/hantekdso/controlsettings.cpp b/openhantek/src/hantekdso/controlsettings.cpp index 39f72e75..afde69a6 100644 --- a/openhantek/src/hantekdso/controlsettings.cpp +++ b/openhantek/src/hantekdso/controlsettings.cpp @@ -5,17 +5,13 @@ namespace Dso { -ControlSettings::ControlSettings(const ControlSamplerateLimits * limits, size_t channelCount) : cmdGetLimits() -{ +ControlSettings::ControlSettings( const ControlSamplerateLimits *limits, size_t channelCount ) : cmdGetLimits() { samplerate.limits = limits; - trigger.level.resize(channelCount); - voltage.resize(channelCount); + trigger.level.resize( channelCount ); + voltage.resize( channelCount ); calibrationValues = new Hantek::CalibrationValues; } -ControlSettings::~ControlSettings() -{ - delete calibrationValues; -} +ControlSettings::~ControlSettings() { delete calibrationValues; } -} +} // namespace Dso diff --git a/openhantek/src/hantekdso/controlsettings.h b/openhantek/src/hantekdso/controlsettings.h index 46930646..04c2c124 100644 --- a/openhantek/src/hantekdso/controlsettings.h +++ b/openhantek/src/hantekdso/controlsettings.h @@ -3,8 +3,8 @@ #pragma once #include "enums.h" -#include "hantekprotocol/types.h" #include "hantekprotocol/controlStructs.h" +#include "hantekprotocol/types.h" namespace Hantek { struct CalibrationValues; @@ -24,47 +24,47 @@ struct ControlSettingsSamplerateTarget { /// \brief Stores the current samplerate settings of the device. struct ControlSettingsSamplerate { ControlSettingsSamplerateTarget target; ///< The target samplerate values - const ControlSamplerateLimits * limits; ///< The samplerate limits + const ControlSamplerateLimits *limits; ///< The samplerate limits unsigned int downsampler = 1; ///< The variable downsampling factor double current = 1e8; ///< The current samplerate }; /// \brief Stores the current trigger settings of the device. struct ControlSettingsTrigger { - std::vector level; ///< The trigger level for each channel in V - double position = 0.0; ///< The current pretrigger position - unsigned int point = 0; ///< The trigger position in Hantek coding - Dso::TriggerMode mode = Dso::TriggerMode::AUTO; ///< The trigger mode - Dso::Slope slope = Dso::Slope::Positive; ///< The trigger slope - unsigned int source = 0; ///< The trigger source - bool smooth = false; ///< Don't trigger on glitches + std::vector level; ///< The trigger level for each channel in V + double position = 0.0; ///< The current pretrigger position + unsigned int point = 0; ///< The trigger position in Hantek coding + Dso::TriggerMode mode = Dso::TriggerMode::AUTO; ///< The trigger mode + Dso::Slope slope = Dso::Slope::Positive; ///< The trigger slope + unsigned int source = 0; ///< The trigger source + bool smooth = false; ///< Don't trigger on glitches }; /// \brief Stores the current amplification settings of the device. struct ControlSettingsVoltage { - double offset = 0.0; ///< The screen offset for each channel - unsigned gain = 0; ///< The gain id - bool used = false; ///< true, if the channel is used - bool inverted = false; ///< true, if the channel is inverted - double probeAttn = 1.0; ///< attenuation of probe + double offset = 0.0; ///< The screen offset for each channel + unsigned gain = 0; ///< The gain id + bool used = false; ///< true, if the channel is used + bool inverted = false; ///< true, if the channel is inverted + double probeAttn = 1.0; ///< attenuation of probe Dso::Coupling coupling = Dso::Coupling::DC; ///< The coupling }; /// \brief Stores the current settings of the device. struct ControlSettings { - ControlSettings(const ControlSamplerateLimits *limits, size_t channelCount); + ControlSettings( const ControlSamplerateLimits *limits, size_t channelCount ); ~ControlSettings(); - ControlSettings( const ControlSettings& ) = delete; - ControlSettings operator=( const ControlSettings& ) = delete; - ControlSettingsSamplerate samplerate; ///< The samplerate settings - std::vector voltage; ///< The amplification settings - ControlSettingsTrigger trigger; ///< The trigger settings - RecordLengthID recordLengthId = 1; ///< The id in the record length array - unsigned channelCount = 0; ///< Number of activated channels - unsigned swSampleMargin = 2000; ///< Software trigger, sample margin - Hantek::CalibrationValues *calibrationValues;///< Calibration data for the channel offsets & gains + ControlSettings( const ControlSettings & ) = delete; + ControlSettings operator=( const ControlSettings & ) = delete; + ControlSettingsSamplerate samplerate; ///< The samplerate settings + std::vector voltage; ///< The amplification settings + ControlSettingsTrigger trigger; ///< The trigger settings + RecordLengthID recordLengthId = 1; ///< The id in the record length array + unsigned channelCount = 0; ///< Number of activated channels + unsigned swSampleMargin = 2000; ///< Software trigger, sample margin + Hantek::CalibrationValues *calibrationValues; ///< Calibration data for the channel offsets & gains Hantek::ControlBeginCommand beginCommandControl; Hantek::ControlGetLimits cmdGetLimits; }; -} +} // namespace Dso diff --git a/openhantek/src/hantekdso/controlspecification.cpp b/openhantek/src/hantekdso/controlspecification.cpp index 9b8eb52a..bbffd9ab 100644 --- a/openhantek/src/hantekdso/controlspecification.cpp +++ b/openhantek/src/hantekdso/controlspecification.cpp @@ -2,7 +2,7 @@ #include "controlspecification.h" -Dso::ControlSpecification::ControlSpecification(unsigned channels) : channels(channels) { - voltageScale.resize(channels); - voltageOffset.resize(channels); +Dso::ControlSpecification::ControlSpecification( unsigned channels ) : channels( channels ) { + voltageScale.resize( channels ); + voltageOffset.resize( channels ); } diff --git a/openhantek/src/hantekdso/controlspecification.h b/openhantek/src/hantekdso/controlspecification.h index eabe7b5c..86473d90 100644 --- a/openhantek/src/hantekdso/controlspecification.h +++ b/openhantek/src/hantekdso/controlspecification.h @@ -63,10 +63,9 @@ struct ControlSpecification { // Features std::vector couplings = {Dso::Coupling::DC, Dso::Coupling::AC}; - std::vector triggerModes = {TriggerMode::AUTO, TriggerMode::NORMAL, - TriggerMode::SINGLE}; + std::vector triggerModes = {TriggerMode::AUTO, TriggerMode::NORMAL, TriggerMode::SINGLE}; int fixedUSBinLength = 0; QList calfreqSteps; }; -} +} // namespace Dso diff --git a/openhantek/src/hantekdso/dsomodel.cpp b/openhantek/src/hantekdso/dsomodel.cpp index 681f5c7c..61f43959 100644 --- a/openhantek/src/hantekdso/dsomodel.cpp +++ b/openhantek/src/hantekdso/dsomodel.cpp @@ -3,14 +3,11 @@ #include "dsomodel.h" #include "modelregistry.h" -DSOModel::DSOModel(int id, unsigned vendorID, unsigned productID, - unsigned vendorIDnoFirmware, unsigned productIDnoFirmware, - unsigned firmwareVersion, - const std::string &firmwareToken, const std::string &name, - const Dso::ControlSpecification &&specification) - : ID(id), vendorID(vendorID), productID(productID), - vendorIDnoFirmware(vendorIDnoFirmware), productIDnoFirmware(productIDnoFirmware), - firmwareVersion(firmwareVersion), - firmwareToken(firmwareToken), name(name), specification(specification) { - ModelRegistry::get()->add(this); +DSOModel::DSOModel( int id, unsigned vendorID, unsigned productID, unsigned vendorIDnoFirmware, + unsigned productIDnoFirmware, unsigned firmwareVersion, const std::string &firmwareToken, + const std::string &name, const Dso::ControlSpecification &&specification ) + : ID( id ), vendorID( vendorID ), productID( productID ), vendorIDnoFirmware( vendorIDnoFirmware ), + productIDnoFirmware( productIDnoFirmware ), firmwareVersion( firmwareVersion ), firmwareToken( firmwareToken ), + name( name ), specification( specification ) { + ModelRegistry::get()->add( this ); } diff --git a/openhantek/src/hantekdso/dsomodel.h b/openhantek/src/hantekdso/dsomodel.h index 2da69d0e..053cf584 100644 --- a/openhantek/src/hantekdso/dsomodel.h +++ b/openhantek/src/hantekdso/dsomodel.h @@ -32,10 +32,10 @@ class DSOModel { public: /// This model may need to modify the HantekDsoControl class to work correctly - virtual void applyRequirements(HantekDsoControl *) const = 0; - DSOModel(int id, unsigned vendorID, unsigned productID, unsigned vendorIDnoFirmware, unsigned productIDnoFirmware, - unsigned firmwareVersion, - const std::string &firmwareToken, const std::string &name, const Dso::ControlSpecification &&specification); + virtual void applyRequirements( HantekDsoControl * ) const = 0; + DSOModel( int id, unsigned vendorID, unsigned productID, unsigned vendorIDnoFirmware, unsigned productIDnoFirmware, + unsigned firmwareVersion, const std::string &firmwareToken, const std::string &name, + const Dso::ControlSpecification &&specification ); virtual ~DSOModel() = default; /// Return the device specifications inline const Dso::ControlSpecification *spec() const { return &specification; } diff --git a/openhantek/src/hantekdso/enums.cpp b/openhantek/src/hantekdso/enums.cpp index e4b9ddf1..1e0f3c08 100644 --- a/openhantek/src/hantekdso/enums.cpp +++ b/openhantek/src/hantekdso/enums.cpp @@ -4,9 +4,9 @@ #include namespace Dso { - Enum TriggerModeEnum; - Enum SlopeEnum; - Enum GraphFormatEnum; +Enum TriggerModeEnum; +Enum SlopeEnum; +Enum GraphFormatEnum; #if 0 /// \brief Return string representation of the given channel mode. @@ -23,74 +23,74 @@ namespace Dso { } #endif - /// \brief Return string representation of the given graph format. - /// \param format The ::GraphFormat that should be returned as string. - /// \return The string that should be used in labels etc. - QString graphFormatString(GraphFormat format) { - switch (format) { - case GraphFormat::TY: - return QCoreApplication::tr("T - Y"); - case GraphFormat::XY: - return QCoreApplication::tr("X - Y"); - } - return QString(); +/// \brief Return string representation of the given graph format. +/// \param format The ::GraphFormat that should be returned as string. +/// \return The string that should be used in labels etc. +QString graphFormatString( GraphFormat format ) { + switch ( format ) { + case GraphFormat::TY: + return QCoreApplication::tr( "T - Y" ); + case GraphFormat::XY: + return QCoreApplication::tr( "X - Y" ); } + return QString(); +} - /// \brief Return string representation of the given channel coupling. - /// \param coupling The ::Coupling that should be returned as string. - /// \return The string that should be used in labels etc. - QString couplingString(Coupling coupling) { - switch (coupling) { - case Coupling::AC: - return QCoreApplication::tr("AC"); - case Coupling::DC: - return QCoreApplication::tr("DC"); - case Coupling::GND: - return QCoreApplication::tr("GND"); - } - return QString(); +/// \brief Return string representation of the given channel coupling. +/// \param coupling The ::Coupling that should be returned as string. +/// \return The string that should be used in labels etc. +QString couplingString( Coupling coupling ) { + switch ( coupling ) { + case Coupling::AC: + return QCoreApplication::tr( "AC" ); + case Coupling::DC: + return QCoreApplication::tr( "DC" ); + case Coupling::GND: + return QCoreApplication::tr( "GND" ); } + return QString(); +} - /// \brief Return string representation of the given trigger mode. - /// \param mode The ::TriggerMode that should be returned as string. - /// \return The string that should be used in labels etc. - QString triggerModeString(TriggerMode mode) { - switch (mode) { - case TriggerMode::AUTO: - return QCoreApplication::tr("Auto"); - case TriggerMode::NORMAL: - return QCoreApplication::tr("Normal"); - case TriggerMode::SINGLE: - return QCoreApplication::tr("Single"); - } - return QString(); +/// \brief Return string representation of the given trigger mode. +/// \param mode The ::TriggerMode that should be returned as string. +/// \return The string that should be used in labels etc. +QString triggerModeString( TriggerMode mode ) { + switch ( mode ) { + case TriggerMode::AUTO: + return QCoreApplication::tr( "Auto" ); + case TriggerMode::NORMAL: + return QCoreApplication::tr( "Normal" ); + case TriggerMode::SINGLE: + return QCoreApplication::tr( "Single" ); } + return QString(); +} - /// \brief Return string representation of the given trigger slope. - /// \param slope The ::Slope that should be returned as string. - /// \return The string that should be used in labels etc. - QString slopeString(Slope slope) { - switch (slope) { +/// \brief Return string representation of the given trigger slope. +/// \param slope The ::Slope that should be returned as string. +/// \return The string that should be used in labels etc. +QString slopeString( Slope slope ) { + switch ( slope ) { #if defined Q_OS_WIN // avoid unicode mismatch - case Slope::Positive: - return QString::fromUtf8("/"); - case Slope::Negative: - return QString::fromUtf8("\\"); - case Slope::Both: - return QString::fromUtf8("X"); + case Slope::Positive: + return QString::fromUtf8( "/" ); + case Slope::Negative: + return QString::fromUtf8( "\\" ); + case Slope::Both: + return QString::fromUtf8( "X" ); #else - case Slope::Positive: - return QString::fromUtf8("\u2197"); // "↗" - case Slope::Negative: - return QString::fromUtf8("\u2198"); // "↘" - case Slope::Both: - return QString::fromUtf8("\u2928"); // "⤨" + case Slope::Positive: + return QString::fromUtf8( "\u2197" ); // "↗" + case Slope::Negative: + return QString::fromUtf8( "\u2198" ); // "↘" + case Slope::Both: + return QString::fromUtf8( "\u2928" ); // "⤨" #endif - default: - return QString(); - } + default: + return QString(); } +} #if 0 /// \brief Return string representation of the given graph interpolation mode. @@ -109,4 +109,4 @@ namespace Dso { } #endif -} +} // namespace Dso diff --git a/openhantek/src/hantekdso/enums.h b/openhantek/src/hantekdso/enums.h index c7d27dcb..4f5c6aad 100644 --- a/openhantek/src/hantekdso/enums.h +++ b/openhantek/src/hantekdso/enums.h @@ -36,7 +36,7 @@ enum class TriggerMode { AUTO, ///< Automatic without trigger event NORMAL, ///< Normal hardware trigger (or software trigger) mode SINGLE ///< Stop after the first trigger event -}; // +}; // extern Enum TriggerModeEnum; /// \enum Slope @@ -57,16 +57,16 @@ enum InterpolationMode { }; // QString channelModeString(ChannelMode mode); -QString graphFormatString(GraphFormat format); -QString couplingString(Coupling coupling); -QString triggerModeString(TriggerMode mode); -QString slopeString(Slope slope); +QString graphFormatString( GraphFormat format ); +QString couplingString( Coupling coupling ); +QString triggerModeString( TriggerMode mode ); +QString slopeString( Slope slope ); // QString interpolationModeString(InterpolationMode interpolation); -} +} // namespace Dso -Q_DECLARE_METATYPE(Dso::TriggerMode) -Q_DECLARE_METATYPE(Dso::Slope) -Q_DECLARE_METATYPE(Dso::Coupling) -Q_DECLARE_METATYPE(Dso::GraphFormat) -Q_DECLARE_METATYPE(Dso::ChannelMode) -Q_DECLARE_METATYPE(Dso::InterpolationMode) +Q_DECLARE_METATYPE( Dso::TriggerMode ) +Q_DECLARE_METATYPE( Dso::Slope ) +Q_DECLARE_METATYPE( Dso::Coupling ) +Q_DECLARE_METATYPE( Dso::GraphFormat ) +Q_DECLARE_METATYPE( Dso::ChannelMode ) +Q_DECLARE_METATYPE( Dso::InterpolationMode ) diff --git a/openhantek/src/hantekdso/errorcodes.h b/openhantek/src/hantekdso/errorcodes.h index 97aee670..da187f60 100644 --- a/openhantek/src/hantekdso/errorcodes.h +++ b/openhantek/src/hantekdso/errorcodes.h @@ -12,4 +12,4 @@ enum class ErrorCode { PARAMETER = -3 ///< Parameter out of range }; -} +} // namespace Dso diff --git a/openhantek/src/hantekdso/hantekdsocontrol.cpp b/openhantek/src/hantekdso/hantekdsocontrol.cpp index 8fafdfa2..f65dbc53 100644 --- a/openhantek/src/hantekdso/hantekdsocontrol.cpp +++ b/openhantek/src/hantekdso/hantekdsocontrol.cpp @@ -16,19 +16,20 @@ #include -#include "scopesettings.h" #include "hantekdsocontrol.h" #include "hantekprotocol/controlStructs.h" #include "models/modelDSO6022.h" +#include "scopesettings.h" #include "usb/usbdevice.h" using namespace Hantek; using namespace Dso; -HantekDsoControl::HantekDsoControl(USBDevice *device) - : device(device), specification(device->getModel()->spec()), - controlsettings(&(specification->samplerate.single), specification->channels) { - if (device == nullptr) throw new std::runtime_error("No usb device for HantekDsoControl"); +HantekDsoControl::HantekDsoControl( USBDevice *device ) + : device( device ), specification( device->getModel()->spec() ), + controlsettings( &( specification->samplerate.single ), specification->channels ) { + if ( device == nullptr ) + throw new std::runtime_error( "No usb device for HantekDsoControl" ); qRegisterMetaType(); @@ -36,14 +37,14 @@ HantekDsoControl::HantekDsoControl(USBDevice *device) device->overwriteInPacketLength( unsigned( specification->fixedUSBinLength ) ); // Apply special requirements by the devices model - device->getModel()->applyRequirements(this); + device->getModel()->applyRequirements( this ); retrieveChannelLevelData(); } HantekDsoControl::~HantekDsoControl() { - while (firstControlCommand) { + while ( firstControlCommand ) { ControlCommand *t = firstControlCommand->next; delete firstControlCommand; firstControlCommand = t; @@ -51,35 +52,37 @@ HantekDsoControl::~HantekDsoControl() { } -unsigned HantekDsoControl::updateSamplerate(unsigned downsampler) { - //qDebug() << "updateSamplerate( " << downsampler << ", " << isFastRate() << " )"; +unsigned HantekDsoControl::updateSamplerate( unsigned downsampler ) { + // qDebug() << "updateSamplerate( " << downsampler << ", " << isFastRate() << " )"; // Get samplerate limits const ControlSamplerateLimits *limits = isFastRate() ? &specification->samplerate.multi : &specification->samplerate.single; // Update settings - bool fastRateChanged = isFastRate() != (controlsettings.samplerate.limits == &specification->samplerate.multi); - if (fastRateChanged) { controlsettings.samplerate.limits = limits; } + bool fastRateChanged = isFastRate() != ( controlsettings.samplerate.limits == &specification->samplerate.multi ); + if ( fastRateChanged ) { + controlsettings.samplerate.limits = limits; + } controlsettings.samplerate.downsampler = downsampler; - if (downsampler) + if ( downsampler ) controlsettings.samplerate.current = controlsettings.samplerate.limits->base / - specification->bufferDividers[controlsettings.recordLengthId] / + specification->bufferDividers[ controlsettings.recordLengthId ] / downsampler; else controlsettings.samplerate.current = - controlsettings.samplerate.limits->max / specification->bufferDividers[controlsettings.recordLengthId]; + controlsettings.samplerate.limits->max / specification->bufferDividers[ controlsettings.recordLengthId ]; // Update dependencies - this->setTriggerOffset (controlsettings.trigger.position); + this->setTriggerOffset( controlsettings.trigger.position ); return downsampler; } void HantekDsoControl::restoreTargets() { - //qDebug() << "restoreTargets()"; - if (controlsettings.samplerate.target.samplerateSet == ControlSettingsSamplerateTarget::Samplerrate) + // qDebug() << "restoreTargets()"; + if ( controlsettings.samplerate.target.samplerateSet == ControlSettingsSamplerateTarget::Samplerrate ) this->setSamplerate(); else this->setRecordTime(); @@ -88,86 +91,89 @@ void HantekDsoControl::restoreTargets() { void HantekDsoControl::updateSamplerateLimits() { QList sampleSteps; - double limit = isFastRate() ? - specification->samplerate.single.max : specification->samplerate.multi.max; + double limit = isFastRate() ? specification->samplerate.single.max : specification->samplerate.multi.max; if ( controlsettings.samplerate.current > limit ) { setSamplerate( limit ); } - for (auto &v : specification->fixedSampleRates) { - if ( v.samplerate <= limit ) { sampleSteps << v.samplerate; } + for ( auto &v : specification->fixedSampleRates ) { + if ( v.samplerate <= limit ) { + sampleSteps << v.samplerate; + } } - //qDebug() << "HDC::updateSamplerateLimits " << sampleSteps; - emit samplerateSet(1, sampleSteps); + // qDebug() << "HDC::updateSamplerateLimits " << sampleSteps; + emit samplerateSet( 1, sampleSteps ); } -Dso::ErrorCode HantekDsoControl::setSamplerate(double samplerate) { - //printf( "HDC::setSamplerate( %g )\n", samplerate ); - if (!device->isConnected()) return Dso::ErrorCode::CONNECTION; +Dso::ErrorCode HantekDsoControl::setSamplerate( double samplerate ) { + // printf( "HDC::setSamplerate( %g )\n", samplerate ); + if ( !device->isConnected() ) + return Dso::ErrorCode::CONNECTION; - if (samplerate == 0.0) { + if ( samplerate == 0.0 ) { samplerate = controlsettings.samplerate.target.samplerate; } else { controlsettings.samplerate.target.samplerate = samplerate; controlsettings.samplerate.target.samplerateSet = ControlSettingsSamplerateTarget::Samplerrate; } unsigned sampleId; - for (sampleId = 0; sampleId < specification->fixedSampleRates.size() - 1; ++sampleId) { - if ( long(round(specification->fixedSampleRates[sampleId].samplerate)) == long(round(samplerate)) ) // dont compare double == double + for ( sampleId = 0; sampleId < specification->fixedSampleRates.size() - 1; ++sampleId ) { + if ( long( round( specification->fixedSampleRates[ sampleId ].samplerate ) ) == + long( round( samplerate ) ) ) // dont compare double == double break; } - modifyCommand(ControlCode::CONTROL_SETTIMEDIV) - ->setDiv(specification->fixedSampleRates[sampleId].id); + modifyCommand( ControlCode::CONTROL_SETTIMEDIV ) + ->setDiv( specification->fixedSampleRates[ sampleId ].id ); controlsettings.samplerate.current = samplerate; - setDownsampling( specification->fixedSampleRates[sampleId].downsampling ); + setDownsampling( specification->fixedSampleRates[ sampleId ].downsampling ); channelSetupChanged = true; // skip next raw samples block to avoid artefacts // Check for Roll mode - emit recordTimeChanged(double( getRecordLength() - controlsettings.swSampleMargin ) / - controlsettings.samplerate.current); - emit samplerateChanged(controlsettings.samplerate.current); + emit recordTimeChanged( double( getRecordLength() - controlsettings.swSampleMargin ) / + controlsettings.samplerate.current ); + emit samplerateChanged( controlsettings.samplerate.current ); return Dso::ErrorCode::NONE; } -Dso::ErrorCode HantekDsoControl::setRecordTime(double duration) { - //printf( "setRecordTime( %g )\n", duration ); - if (!device->isConnected()) +Dso::ErrorCode HantekDsoControl::setRecordTime( double duration ) { + // printf( "setRecordTime( %g )\n", duration ); + if ( !device->isConnected() ) return Dso::ErrorCode::CONNECTION; - if (duration == 0.0) { + if ( duration == 0.0 ) { duration = controlsettings.samplerate.target.duration; } else { controlsettings.samplerate.target.duration = duration; controlsettings.samplerate.target.samplerateSet = ControlSettingsSamplerateTarget::Duration; } - //printf( "duration = %g\n", duration ); + // printf( "duration = %g\n", duration ); double srLimit; if ( isFastRate() ) - srLimit = (specification->samplerate.single).max; + srLimit = ( specification->samplerate.single ).max; else - srLimit = (specification->samplerate.multi).max; + srLimit = ( specification->samplerate.multi ).max; // For now - we go for the SAMPLESIZE_USED (= 20000) size sampling, defined in model6022.h // Find highest samplerate using less equal half of these samples to obtain our duration. unsigned sampleId = 0; - for (unsigned id = 0; id < specification->fixedSampleRates.size(); ++id) { - double sRate = specification->fixedSampleRates[id].samplerate; - //qDebug() << "id:" << id << "sRate:" << sRate << "sRate*duration:" << sRate * duration; + for ( unsigned id = 0; id < specification->fixedSampleRates.size(); ++id ) { + double sRate = specification->fixedSampleRates[ id ].samplerate; + // qDebug() << "id:" << id << "sRate:" << sRate << "sRate*duration:" << sRate * duration; // Ensure that at least 1/2 of remaining samples are available for SW trigger algorithm // for stability reason avoid the highest sample rate as default if ( sRate < srLimit && sRate * duration <= SAMPLESIZE_USED / 2 ) { sampleId = id; } } - double samplerate = specification->fixedSampleRates[sampleId].samplerate; - //qDebug() << "HDC::sRT: sampleId:" << sampleId << srLimit << samplerate; + double samplerate = specification->fixedSampleRates[ sampleId ].samplerate; + // qDebug() << "HDC::sRT: sampleId:" << sampleId << srLimit << samplerate; // Usable sample value - modifyCommand(ControlCode::CONTROL_SETTIMEDIV) - ->setDiv(specification->fixedSampleRates[sampleId].id); + modifyCommand( ControlCode::CONTROL_SETTIMEDIV ) + ->setDiv( specification->fixedSampleRates[ sampleId ].id ); controlsettings.samplerate.current = samplerate; - setDownsampling( specification->fixedSampleRates[sampleId].downsampling ); + setDownsampling( specification->fixedSampleRates[ sampleId ].downsampling ); channelSetupChanged = true; // skip next raw samples block to avoid artefacts emit samplerateChanged( samplerate ); return Dso::ErrorCode::NONE; @@ -176,43 +182,42 @@ Dso::ErrorCode HantekDsoControl::setRecordTime(double duration) { Dso::ErrorCode HantekDsoControl::setCalFreq( double calfreq ) { unsigned int cf = unsigned( calfreq ) / 1000; // 1000, ..., 100000 -> 1, ..., 100 - if ( cf == 0 ) { // 50, 60, 100, 200, 500 -> 105, 106, 110, 120, 150 + if ( cf == 0 ) { // 50, 60, 100, 200, 500 -> 105, 106, 110, 120, 150 cf = 100 + unsigned( calfreq ) / 10; if ( 110 == cf ) // special case for sigrok FW (e.g. DDS120) 100Hz -> 0 cf = 0; } - //printf( "HDC::setCalFreq( %g ) -> %d\n", calfreq, cf ); + // printf( "HDC::setCalFreq( %g ) -> %d\n", calfreq, cf ); if ( !device->isConnected() ) return Dso::ErrorCode::CONNECTION; // control command for setting - modifyCommand( ControlCode::CONTROL_SETCALFREQ ) - ->setCalFreq( uint8_t( cf ) ); + modifyCommand( ControlCode::CONTROL_SETCALFREQ )->setCalFreq( uint8_t( cf ) ); return Dso::ErrorCode::NONE; } -Dso::ErrorCode HantekDsoControl::setChannelUsed(ChannelID channel, bool used) { - if (!device->isConnected()) +Dso::ErrorCode HantekDsoControl::setChannelUsed( ChannelID channel, bool used ) { + if ( !device->isConnected() ) return Dso::ErrorCode::CONNECTION; - if (channel >= specification->channels) + if ( channel >= specification->channels ) return Dso::ErrorCode::PARAMETER; // Update settings - controlsettings.voltage[channel].used = used; + controlsettings.voltage[ channel ].used = used; // Calculate the UsedChannels field for the command UsedChannels usedChannels = UsedChannels::USED_CH1; controlsettings.channelCount = 1; - if (controlsettings.voltage[1].used) { + if ( controlsettings.voltage[ 1 ].used ) { controlsettings.channelCount = 2; - if (controlsettings.voltage[0].used) { + if ( controlsettings.voltage[ 0 ].used ) { usedChannels = UsedChannels::USED_CH1CH2; } else { usedChannels = UsedChannels::USED_CH2; } } setFastRate( usedChannels == UsedChannels::USED_CH1 ); - //qDebug() << "usedChannels" << (int)usedChannels; - modifyCommand(ControlCode::CONTROL_SETNUMCHANNELS)->setDiv( isFastRate() ? 1 : 2 ); + // qDebug() << "usedChannels" << (int)usedChannels; + modifyCommand( ControlCode::CONTROL_SETNUMCHANNELS )->setDiv( isFastRate() ? 1 : 2 ); // Check if fast rate mode availability changed this->updateSamplerateLimits(); this->restoreTargets(); @@ -221,72 +226,72 @@ Dso::ErrorCode HantekDsoControl::setChannelUsed(ChannelID channel, bool used) { } -Dso::ErrorCode HantekDsoControl::setChannelInverted(ChannelID channel, bool inverted) { - if (!device->isConnected()) +Dso::ErrorCode HantekDsoControl::setChannelInverted( ChannelID channel, bool inverted ) { + if ( !device->isConnected() ) return Dso::ErrorCode::CONNECTION; - if (channel >= specification->channels) + if ( channel >= specification->channels ) return Dso::ErrorCode::PARAMETER; // Update settings - //printf("setChannelInverted %s\n", inverted?"true":"false"); - controlsettings.voltage[channel].inverted = inverted; + // printf("setChannelInverted %s\n", inverted?"true":"false"); + controlsettings.voltage[ channel ].inverted = inverted; return Dso::ErrorCode::NONE; } -Dso::ErrorCode HantekDsoControl::setGain(ChannelID channel, double gain) { - if (!device->isConnected()) +Dso::ErrorCode HantekDsoControl::setGain( ChannelID channel, double gain ) { + if ( !device->isConnected() ) return Dso::ErrorCode::CONNECTION; - if (channel >= specification->channels) + if ( channel >= specification->channels ) return Dso::ErrorCode::PARAMETER; - gain /= controlsettings.voltage[channel].probeAttn; // gain needs to be scaled by probe attenuation + gain /= controlsettings.voltage[ channel ].probeAttn; // gain needs to be scaled by probe attenuation // Find lowest gain voltage thats at least as high as the requested unsigned gainID; - for (gainID = 0; gainID < specification->gain.size() - 1; ++gainID) - if (specification->gain[gainID].gainSteps >= gain) + for ( gainID = 0; gainID < specification->gain.size() - 1; ++gainID ) + if ( specification->gain[ gainID ].gainSteps >= gain ) break; - if (channel == 0) { - modifyCommand(ControlCode::CONTROL_SETVOLTDIV_CH1) - ->setDiv(specification->gain[gainID].gainIndex); - } else if (channel == 1) { - modifyCommand(ControlCode::CONTROL_SETVOLTDIV_CH2) - ->setDiv(specification->gain[gainID].gainIndex); + if ( channel == 0 ) { + modifyCommand( ControlCode::CONTROL_SETVOLTDIV_CH1 ) + ->setDiv( specification->gain[ gainID ].gainIndex ); + } else if ( channel == 1 ) { + modifyCommand( ControlCode::CONTROL_SETVOLTDIV_CH2 ) + ->setDiv( specification->gain[ gainID ].gainIndex ); } else - qDebug("%s: Unsupported channel: %i\n", __func__, channel); - controlsettings.voltage[channel].gain = gainID; + qDebug( "%s: Unsupported channel: %i\n", __func__, channel ); + controlsettings.voltage[ channel ].gain = gainID; return Dso::ErrorCode::NONE; } -Dso::ErrorCode HantekDsoControl::setProbe(ChannelID channel, double probeAttn ) { - if (channel >= specification->channels) +Dso::ErrorCode HantekDsoControl::setProbe( ChannelID channel, double probeAttn ) { + if ( channel >= specification->channels ) return Dso::ErrorCode::PARAMETER; - controlsettings.voltage[channel].probeAttn = probeAttn; - //printf( "setProbe %g\n", probeAttn ); + controlsettings.voltage[ channel ].probeAttn = probeAttn; + // printf( "setProbe %g\n", probeAttn ); return Dso::ErrorCode::NONE; } -Dso::ErrorCode HantekDsoControl::setCoupling(ChannelID channel, Dso::Coupling coupling) { - if (!device->isConnected()) +Dso::ErrorCode HantekDsoControl::setCoupling( ChannelID channel, Dso::Coupling coupling ) { + if ( !device->isConnected() ) return Dso::ErrorCode::CONNECTION; - if (channel >= specification->channels) + if ( channel >= specification->channels ) return Dso::ErrorCode::PARAMETER; - if (hasCommand(ControlCode::CONTROL_SETCOUPLING)) // don't send command if it is not implemented (like on the 6022) - modifyCommand(ControlCode::CONTROL_SETCOUPLING) - ->setCoupling(channel, coupling == Dso::Coupling::DC); - controlsettings.voltage[channel].coupling = coupling; + if ( hasCommand( + ControlCode::CONTROL_SETCOUPLING ) ) // don't send command if it is not implemented (like on the 6022) + modifyCommand( ControlCode::CONTROL_SETCOUPLING ) + ->setCoupling( channel, coupling == Dso::Coupling::DC ); + controlsettings.voltage[ channel ].coupling = coupling; return Dso::ErrorCode::NONE; } - -Dso::ErrorCode HantekDsoControl::setTriggerMode(Dso::TriggerMode mode) { - if (!device->isConnected()) +Dso::ErrorCode HantekDsoControl::setTriggerMode( Dso::TriggerMode mode ) { + if ( !device->isConnected() ) return Dso::ErrorCode::CONNECTION; controlsettings.trigger.mode = mode; if ( Dso::TriggerMode::SINGLE != mode ) @@ -295,151 +300,151 @@ Dso::ErrorCode HantekDsoControl::setTriggerMode(Dso::TriggerMode mode) { } -Dso::ErrorCode HantekDsoControl::setTriggerSource(ChannelID channel, bool smooth) { - if (!device->isConnected()) +Dso::ErrorCode HantekDsoControl::setTriggerSource( ChannelID channel, bool smooth ) { + if ( !device->isConnected() ) return Dso::ErrorCode::CONNECTION; - //printf("setTriggerSource( %d, %d )\n", channel, smooth); + // printf("setTriggerSource( %d, %d )\n", channel, smooth); controlsettings.trigger.source = channel; controlsettings.trigger.smooth = smooth; return Dso::ErrorCode::NONE; } // trigger level in Volt -Dso::ErrorCode HantekDsoControl::setTriggerLevel(ChannelID channel, double level) { - if (!device->isConnected()) +Dso::ErrorCode HantekDsoControl::setTriggerLevel( ChannelID channel, double level ) { + if ( !device->isConnected() ) return Dso::ErrorCode::CONNECTION; - if (channel >= specification->channels) + if ( channel >= specification->channels ) return Dso::ErrorCode::PARAMETER; - //printf("setTriggerLevel( %d, %g )\n", channel, level); - controlsettings.trigger.level[channel] = level; + // printf("setTriggerLevel( %d, %g )\n", channel, level); + controlsettings.trigger.level[ channel ] = level; return Dso::ErrorCode::NONE; } -Dso::ErrorCode HantekDsoControl::setTriggerSlope(Dso::Slope slope) { - if (!device->isConnected()) +Dso::ErrorCode HantekDsoControl::setTriggerSlope( Dso::Slope slope ) { + if ( !device->isConnected() ) return Dso::ErrorCode::CONNECTION; - //printf("setTriggerSlope( %d )\n", (int)slope); + // printf("setTriggerSlope( %d )\n", (int)slope); controlsettings.trigger.slope = slope; return Dso::ErrorCode::NONE; } // set trigger position (0.0 - 1.0) -Dso::ErrorCode HantekDsoControl::setTriggerOffset (double position) { - if (!device->isConnected()) +Dso::ErrorCode HantekDsoControl::setTriggerOffset( double position ) { + if ( !device->isConnected() ) return Dso::ErrorCode::CONNECTION; - //printf("setTriggerPosition( %g )\n", position); + // printf("setTriggerPosition( %g )\n", position); controlsettings.trigger.position = position; return Dso::ErrorCode::NONE; } // Initialize the device with the current settings. -void HantekDsoControl::applySettings(DsoSettingsScope *scope) { - bool mathUsed = scope->anyUsed(specification->channels); - for (ChannelID channel = 0; channel < specification->channels; ++channel) { - setProbe(channel, scope->voltage[channel].probeAttn); - setGain(channel, scope->gain(channel) * DIVS_VOLTAGE); - setTriggerLevel(channel, scope->voltage[channel].trigger); - setChannelUsed(channel, mathUsed | scope->anyUsed(channel)); - setChannelInverted(channel, scope->voltage[channel].inverted); - setCoupling(channel, Dso::Coupling(scope->voltage[channel].couplingOrMathIndex)); +void HantekDsoControl::applySettings( DsoSettingsScope *scope ) { + bool mathUsed = scope->anyUsed( specification->channels ); + for ( ChannelID channel = 0; channel < specification->channels; ++channel ) { + setProbe( channel, scope->voltage[ channel ].probeAttn ); + setGain( channel, scope->gain( channel ) * DIVS_VOLTAGE ); + setTriggerLevel( channel, scope->voltage[ channel ].trigger ); + setChannelUsed( channel, mathUsed | scope->anyUsed( channel ) ); + setChannelInverted( channel, scope->voltage[ channel ].inverted ); + setCoupling( channel, Dso::Coupling( scope->voltage[ channel ].couplingOrMathIndex ) ); } - setRecordTime(scope->horizontal.timebase * DIVS_TIME); - setCalFreq(scope->horizontal.calfreq); - setTriggerMode(scope->trigger.mode); - setTriggerOffset (scope->trigger.offset); - setTriggerSlope(scope->trigger.slope); - setTriggerSource(scope->trigger.source, scope->trigger.smooth); + setRecordTime( scope->horizontal.timebase * DIVS_TIME ); + setCalFreq( scope->horizontal.calfreq ); + setTriggerMode( scope->trigger.mode ); + setTriggerOffset( scope->trigger.offset ); + setTriggerSlope( scope->trigger.slope ); + setTriggerSource( scope->trigger.source, scope->trigger.smooth ); } /// \brief Start sampling process. -void HantekDsoControl::enableSampling(bool enabled) { +void HantekDsoControl::enableSampling( bool enabled ) { sampling = enabled; updateSamplerateLimits(); - emit samplingStatusChanged(enabled); + emit samplingStatusChanged( enabled ); } unsigned HantekDsoControl::getRecordLength() const { unsigned rawsize = SAMPLESIZE_USED; - rawsize *= this->downsamplingNumber; // take more samples - rawsize = ( (rawsize + 1024) / 1024 + 2 ) * 1024; // adjust for skipping of minimal 2048 leading samples - //printf( "getRecordLength: %d\n", rawsize ); + rawsize *= this->downsamplingNumber; // take more samples + rawsize = ( ( rawsize + 1024 ) / 1024 + 2 ) * 1024; // adjust for skipping of minimal 2048 leading samples + // printf( "getRecordLength: %d\n", rawsize ); return rawsize; } Dso::ErrorCode HantekDsoControl::retrieveChannelLevelData() { // Get calibration data from EEPROM - //printf( "retrieveChannelLevelData()\n" ); + // printf( "retrieveChannelLevelData()\n" ); int errorCode = -1; if ( specification->hasCalibrationEEPROM ) - errorCode = device->controlRead(&controlsettings.cmdGetLimits); - if ( errorCode < 0) { + errorCode = device->controlRead( &controlsettings.cmdGetLimits ); + if ( errorCode < 0 ) { // invalidate the calibration values. - memset(controlsettings.calibrationValues, 0xFF, sizeof( CalibrationValues ) ); - QString message = tr("Couldn't get calibration data from oscilloscope's EEPROM. Use a config file for calibration!"); + memset( controlsettings.calibrationValues, 0xFF, sizeof( CalibrationValues ) ); + QString message = + tr( "Couldn't get calibration data from oscilloscope's EEPROM. Use a config file for calibration!" ); qWarning() << message; - emit statusMessage( message , 0); + emit statusMessage( message, 0 ); emit communicationError(); return Dso::ErrorCode::CONNECTION; } - memcpy(controlsettings.calibrationValues, controlsettings.cmdGetLimits.data(), - sizeof( CalibrationValues ) ); -// printf("HDC::cV: %lu, %d, %g\n", sizeof( CalibrationValues ), -// controlsettings.calibrationValues->off.ls.step[ 7 ][ 0 ] - 0x80, -// (controlsettings.calibrationValues->fine.ls.step[ 7 ][ 0 ] - 0x80) / 250.0 -// ); + memcpy( controlsettings.calibrationValues, controlsettings.cmdGetLimits.data(), sizeof( CalibrationValues ) ); + // printf("HDC::cV: %lu, %d, %g\n", sizeof( CalibrationValues ), + // controlsettings.calibrationValues->off.ls.step[ 7 ][ 0 ] - 0x80, + // (controlsettings.calibrationValues->fine.ls.step[ 7 ][ 0 ] - 0x80) / 250.0 + // ); return Dso::ErrorCode::NONE; } -std::vector HantekDsoControl::getSamples(unsigned &previousSampleCount) const { +std::vector HantekDsoControl::getSamples( unsigned &previousSampleCount ) const { int errorCode; - errorCode = device->controlWrite(getCommand(ControlCode::CONTROL_ACQUIIRE_HARD_DATA)); - if (errorCode < 0) { - qWarning() << "controlWrite: Getting sample data failed: " << libUsbErrorString(errorCode); + errorCode = device->controlWrite( getCommand( ControlCode::CONTROL_ACQUIIRE_HARD_DATA ) ); + if ( errorCode < 0 ) { + qWarning() << "controlWrite: Getting sample data failed: " << libUsbErrorString( errorCode ); emit communicationError(); return std::vector(); } unsigned rawSampleCount = this->getSampleCount(); - //printf( "getSamples, rawSampleCount %d\n", rawSampleCount ); + // printf( "getSamples, rawSampleCount %d\n", rawSampleCount ); // To make sure no samples will remain in the scope buffer, also check the // sample count before the last sampling started - if (rawSampleCount < previousSampleCount) { - std::swap(rawSampleCount, previousSampleCount); + if ( rawSampleCount < previousSampleCount ) { + std::swap( rawSampleCount, previousSampleCount ); } else { previousSampleCount = rawSampleCount; } // Save raw data to temporary buffer - std::vector data(rawSampleCount); + std::vector data( rawSampleCount ); int retval = device->bulkReadMulti( data.data(), rawSampleCount ); if ( retval < 0 ) { qWarning() << "bulkReadMulti: Getting sample data failed: " << libUsbErrorString( retval ); return std::vector(); } data.resize( size_t( retval ) ); - //printf( "bulkReadMulti( %d ) -> %d\n", rawSampleCount, retval ); + // printf( "bulkReadMulti( %d ) -> %d\n", rawSampleCount, retval ); static unsigned id = 0; ++id; - timestampDebug(QString("Received packet %1").arg(id)); + timestampDebug( QString( "Received packet %1" ).arg( id ) ); return data; } -void HantekDsoControl::convertRawDataToSamples(const std::vector &rawData, unsigned activeChannels) { +void HantekDsoControl::convertRawDataToSamples( const std::vector &rawData, unsigned activeChannels ) { if ( channelSetupChanged ) { // skip the next conversion to avoid artefacts due to channel switch channelSetupChanged = false; return; } - if ( isFastRate() != (1 == activeChannels) ) // avoid possible race condition + if ( isFastRate() != ( 1 == activeChannels ) ) // avoid possible race condition return; // The 1st two or three frames (512 byte) of the raw sample stream are unreliable @@ -450,21 +455,23 @@ void HantekDsoControl::convertRawDataToSamples(const std::vector const unsigned rawSampleCount = unsigned( rawData.size() ) / activeChannels; // TODO: is this needed? rawSampleCount should always be > SAMPLESIZE_USED (=20000) - const unsigned sampleCount = (rawSampleCount > 1024) ? ((rawSampleCount - 1024)/1000 - 1)*1000 : rawSampleCount; + const unsigned sampleCount = + ( rawSampleCount > 1024 ) ? ( ( rawSampleCount - 1024 ) / 1000 - 1 ) * 1000 : rawSampleCount; const unsigned rawDownsampling = sampleCount / SAMPLESIZE_USED; - //qDebug() << "HDC::cRDTS rawSampleCount sampleCount:" << rawSampleCount << sampleCount; - if ( 0 == rawSampleCount || 0 == sampleCount || 0 == rawDownsampling ) {// nothing to convert - qDebug() << "HDC::cRDTS rawSampleCount sampleCount rawDownsampling:" << rawSampleCount << sampleCount << rawDownsampling; + // qDebug() << "HDC::cRDTS rawSampleCount sampleCount:" << rawSampleCount << sampleCount; + if ( 0 == rawSampleCount || 0 == sampleCount || 0 == rawDownsampling ) { // nothing to convert + qDebug() << "HDC::cRDTS rawSampleCount sampleCount rawDownsampling:" << rawSampleCount << sampleCount + << rawDownsampling; return; } const unsigned skipSamples = rawSampleCount - sampleCount; - QWriteLocker locker(&result.lock); + QWriteLocker locker( &result.lock ); result.samplerate = controlsettings.samplerate.current; // Prepare result buffers - result.data.resize(specification->channels); - for (ChannelID channelCounter = 0; channelCounter < specification->channels; ++channelCounter) - result.data[channelCounter].clear(); + result.data.resize( specification->channels ); + for ( ChannelID channelCounter = 0; channelCounter < specification->channels; ++channelCounter ) + result.data[ channelCounter ].clear(); // The 1st two or three frames (512 byte) of the raw sample stream are unreliable // (Maybe because the common mode input voltage of ADC is handled far out of spec and has to settle) @@ -472,21 +479,21 @@ void HantekDsoControl::convertRawDataToSamples(const std::vector // rawSampleSize = ( ( n*20000 + 1024 ) / 1024 + 2) * 1024; // and skip over these samples to get 20000 samples (or n*20000) - //printf("sampleCount %u, downsampling %u\n", sampleCount, downsampling ); + // printf("sampleCount %u, downsampling %u\n", sampleCount, downsampling ); // Convert channel data // Channels are using their separate buffers - for (ChannelID channel = 0; channel < activeChannels; ++channel) { - const unsigned gainID = controlsettings.voltage[channel].gain; - const int voltageScale = specification->voltageScale[channel][gainID]; - const double gainStep = specification->gain[gainID].gainSteps; - const double probeAttn = controlsettings.voltage[channel].probeAttn; - const double sign = controlsettings.voltage[channel].inverted ? -1.0 : 1.0; + for ( ChannelID channel = 0; channel < activeChannels; ++channel ) { + const unsigned gainID = controlsettings.voltage[ channel ].gain; + const int voltageScale = specification->voltageScale[ channel ][ gainID ]; + const double gainStep = specification->gain[ gainID ].gainSteps; + const double probeAttn = controlsettings.voltage[ channel ].probeAttn; + const double sign = controlsettings.voltage[ channel ].inverted ? -1.0 : 1.0; // shift + individual offset for each channel and gain double gainCalibration = 1.0; double voltageOffset = specification->voltageOffset[ channel ][ gainID ]; - if ( !bool(voltageOffset) ) { // no config file value + if ( !bool( voltageOffset ) ) { // no config file value // get offset value from eeprom[ 8 .. 39 and (if available) 56 .. 87] int offsetRaw; int offsetFine; @@ -498,30 +505,30 @@ void HantekDsoControl::convertRawDataToSamples(const std::vector offsetFine = controlsettings.calibrationValues->fine.hs.step[ gainID ][ channel ]; } if ( offsetRaw && offsetRaw != 255 && offsetFine && offsetFine != 255 ) { // data valid - voltageOffset = offsetRaw + (offsetFine - 0x80) / 250.0; - } else { // no offset correction + voltageOffset = offsetRaw + ( offsetFine - 0x80 ) / 250.0; + } else { // no offset correction voltageOffset = 0x80; // ADC has "binary offset" format (0x80 = 0V) } int gain = controlsettings.calibrationValues->gain.step[ gainID ][ channel ]; if ( gain && gain != 255 ) { // data valid - gainCalibration = 1.0 + (gain - 0x80) / 500.0; + gainCalibration = 1.0 + ( gain - 0x80 ) / 500.0; } - //printf( "sDB %d, gC %f, ch %d, gID %d\n", shiftDataBuf, gainCalibration, channel, gainID ); + // printf( "sDB %d, gC %f, ch %d, gID %d\n", shiftDataBuf, gainCalibration, channel, gainID ); } // Convert data from the oscilloscope and write it into the sample buffer unsigned rawBufferPosition = 0; - result.data[channel].resize( sampleCount / rawDownsampling ); + result.data[ channel ].resize( sampleCount / rawDownsampling ); rawBufferPosition += skipSamples * activeChannels; // skip first unstable samples rawBufferPosition += channel; - result.clipped &= ~(0x01 << channel); // clear clipping flag + result.clipped &= ~( 0x01 << channel ); // clear clipping flag for ( unsigned index = 0; index < result.data[ channel ].size(); - ++index, rawBufferPosition += activeChannels * rawDownsampling ) { // advance either by one or two blocks + ++index, rawBufferPosition += activeChannels * rawDownsampling ) { // advance either by one or two blocks double sample = 0.0; for ( unsigned iii = 0; iii < rawDownsampling * activeChannels; iii += activeChannels ) { int rawSample = rawData[ rawBufferPosition + iii ]; // range 0...255 - if ( rawSample == 0x00 || rawSample == 0xFF ) // min or max -> clipped + if ( rawSample == 0x00 || rawSample == 0xFF ) // min or max -> clipped result.clipped |= 0x01 << channel; sample += double( rawSample ) - voltageOffset; } @@ -535,25 +542,28 @@ void HantekDsoControl::convertRawDataToSamples(const std::vector // search for trigger point from defined point, default startPos = 0; unsigned HantekDsoControl::searchTriggerPoint( Dso::Slope dsoSlope, unsigned int startPos ) { int slope; - if ( dsoSlope == Dso::Slope::Positive) + if ( dsoSlope == Dso::Slope::Positive ) slope = 1; else if ( dsoSlope == Dso::Slope::Negative ) slope = -1; - else return 0; + else + return 0; ChannelID channel = controlsettings.trigger.source; - const std::vector &samples = result.data[channel]; - unsigned sampleCount = unsigned( samples.size() ); ///< number of available samples + const std::vector &samples = result.data[ channel ]; + unsigned sampleCount = unsigned( samples.size() ); ///< number of available samples // printf("searchTriggerPoint( %d, %d )\n", (int)dsoSlope, startPos ); if ( startPos >= sampleCount ) return 0; - double level = controlsettings.trigger.level[channel]; + double level = controlsettings.trigger.level[ channel ]; double timeDisplay = controlsettings.samplerate.target.duration; // time for full screen width double sampleRate = controlsettings.samplerate.current; double samplesDisplay = timeDisplay * sampleRate; - unsigned preTrigSamples = startPos ? startPos : unsigned(controlsettings.trigger.position * samplesDisplay); // samples left of trigger - unsigned postTrigSamples = unsigned( sampleCount ) - (unsigned( samplesDisplay ) - preTrigSamples); // samples right of trigger + unsigned preTrigSamples = + startPos ? startPos : unsigned( controlsettings.trigger.position * samplesDisplay ); // samples left of trigger + unsigned postTrigSamples = + unsigned( sampleCount ) - ( unsigned( samplesDisplay ) - preTrigSamples ); // samples right of trigger // |-----------samples-----------| // available sample // |--disp--| // display size // |<<<<>|--------------------| // >> = right = (disp-pre) i.e. right of trigger on screen @@ -561,25 +571,27 @@ unsigned HantekDsoControl::searchTriggerPoint( Dso::Slope dsoSlope, unsigned int // |--(samp-(disp-pre))-------|>>| // |<<<<<|????????????????????|>>| // ?? = search for trigger in this range [left,right] - const unsigned swTriggerSampleSet = controlsettings.trigger.smooth ? 10 : 1; // check this number of samples before/after trigger point ... - const unsigned swTriggerThreshold = controlsettings.trigger.smooth ? 5 : 0; // ... and get at least this number below or above trigger + const unsigned swTriggerSampleSet = + controlsettings.trigger.smooth ? 10 : 1; // check this number of samples before/after trigger point ... + const unsigned swTriggerThreshold = + controlsettings.trigger.smooth ? 5 : 0; // ... and get at least this number below or above trigger if ( postTrigSamples > sampleCount - 2 * ( swTriggerSampleSet + 1 ) ) postTrigSamples = sampleCount - 2 * ( swTriggerSampleSet + 1 ); // printf( "pre: %d, post %d\n", preTrigSamples, postTrigSamples ); double prev = INT_MAX * slope; unsigned swTriggerStart = 0; - for (unsigned int i = preTrigSamples; i < postTrigSamples; i++) { - if ( slope * samples[i] >= slope * level && slope * prev < slope * level ) { // trigger condition met + for ( unsigned int i = preTrigSamples; i < postTrigSamples; i++ ) { + if ( slope * samples[ i ] >= slope * level && slope * prev < slope * level ) { // trigger condition met // check for the next few SampleSet samples, if they are also above/below the trigger value unsigned int before = 0; - for (unsigned int k = i - 1; k >= i - swTriggerSampleSet && k > 0; k--) { - if ( slope * samples[k] < slope * level ) + for ( unsigned int k = i - 1; k >= i - swTriggerSampleSet && k > 0; k-- ) { + if ( slope * samples[ k ] < slope * level ) before++; } unsigned int after = 0; - for (unsigned int k = i + 1; k <= i + swTriggerSampleSet && k < sampleCount; k++) { - if ( slope * samples[k] >= slope * level ) + for ( unsigned int k = i + 1; k <= i + swTriggerSampleSet && k < sampleCount; k++ ) { + if ( slope * samples[ k ] >= slope * level ) after++; } // if at least >Threshold (=5) samples before and after trig meet the condition, set trigger @@ -588,7 +600,7 @@ unsigned HantekDsoControl::searchTriggerPoint( Dso::Slope dsoSlope, unsigned int break; } } - prev = samples[i]; + prev = samples[ i ]; } return swTriggerStart; } @@ -601,18 +613,18 @@ unsigned HantekDsoControl::softwareTrigger() { if ( !controlsettings.voltage[ channel ].used || result.data.empty() ) { return result.triggerPosition = 0; } - //printf( "HDC::softwareTrigger()\n" ); + // printf( "HDC::softwareTrigger()\n" ); triggeredPositionRaw = 0; result.triggerPosition = 0; // not triggered result.pulseWidth1 = 0.0; result.pulseWidth2 = 0.0; - size_t sampleCount = result.data[ channel ].size(); // number of available samples + size_t sampleCount = result.data[ channel ].size(); // number of available samples double timeDisplay = controlsettings.samplerate.target.duration; // time for full screen width double sampleRate = controlsettings.samplerate.current; double samplesDisplay = timeDisplay * sampleRate; - //unsigned preTrigSamples = (unsigned)(controlsettings.trigger.position * samplesDisplay); - //printf( "sC %lu, tD %g, sR %g, sD %g\n", sampleCount, timeDisplay, sampleRate, samplesDisplay ); + // unsigned preTrigSamples = (unsigned)(controlsettings.trigger.position * samplesDisplay); + // printf( "sC %lu, tD %g, sR %g, sD %g\n", sampleCount, timeDisplay, sampleRate, samplesDisplay ); if ( samplesDisplay >= sampleCount ) { // For sure not enough samples to adjust for jitter. qDebug() << "Too few samples to make a steady picture. Decrease sample rate"; @@ -621,7 +633,7 @@ unsigned HantekDsoControl::softwareTrigger() { // search for trigger point in a range that leaves enough samples left and right of trigger for display // find also the alternate slope after trigger point -> calculate pulse width. - if ( controlsettings.trigger.slope != Dso::Slope::Both ) { + if ( controlsettings.trigger.slope != Dso::Slope::Both ) { triggeredPositionRaw = searchTriggerPoint( nextSlope = controlsettings.trigger.slope ); if ( triggeredPositionRaw ) { // triggered -> search also following other slope (calculate pulse width) if ( unsigned int slopePos2 = searchTriggerPoint( mirrorSlope( nextSlope ), triggeredPositionRaw ) ) { @@ -645,7 +657,7 @@ unsigned HantekDsoControl::softwareTrigger() { } } - if ( triggeredPositionRaw ) { // triggered + if ( triggeredPositionRaw ) { // triggered result.triggerPosition = triggeredPositionRaw; // align trace to trigger position } // printf( "nextSlope %c, triggerPositionRaw %d\n", "/\\"[(int)nextSlope], triggerPositionRaw ); @@ -654,27 +666,27 @@ unsigned HantekDsoControl::softwareTrigger() { bool HantekDsoControl::triggering() { - //printf( "HDC::triggering()\n" ); + // printf( "HDC::triggering()\n" ); static DSOsamples triggeredResult; // storage for last triggered trace samples - if ( result.triggerPosition ) { // live trace has triggered + if ( result.triggerPosition ) { // live trace has triggered // Use this trace and save it also triggeredResult.data = result.data; triggeredResult.samplerate = result.samplerate; triggeredResult.clipped = result.clipped; triggeredResult.triggerPosition = result.triggerPosition; - result.liveTrigger = true; // show green "TR" top left + result.liveTrigger = true; // show green "TR" top left } else if ( controlsettings.trigger.mode == Dso::TriggerMode::NORMAL ) { // Not triggered in NORMAL mode // Use saved trace (even if it is empty) - result.data = triggeredResult.data; + result.data = triggeredResult.data; result.samplerate = triggeredResult.samplerate; result.clipped = triggeredResult.clipped; result.triggerPosition = triggeredResult.triggerPosition; result.liveTrigger = false; // show red "TR" top left - } else { // Not triggered and not NORMAL mode + } else { // Not triggered and not NORMAL mode // Use the free running trace, discard history - triggeredResult.data.clear(); // discard trace + triggeredResult.data.clear(); // discard trace triggeredResult.triggerPosition = 0; // not triggered - result.liveTrigger = false; // show red "TR" top left + result.liveTrigger = false; // show red "TR" top left } return result.liveTrigger; } @@ -684,16 +696,16 @@ bool HantekDsoControl::triggering() { void HantekDsoControl::updateInterval() { // Check the current oscilloscope state everytime 25% of the time // the buffer should be refilled (-> acquireInterval in ms) - acquireInterval = int( SAMPLESIZE_USED * 250.0 / controlsettings.samplerate.current ); + acquireInterval = int( SAMPLESIZE_USED * 250.0 / controlsettings.samplerate.current ); // Slower update reduces CPU load but it worsens the triggering of rare events // Display can be filled at slower rate #ifdef __arm__ // RPi: Not more often than every 10 ms but at least once every 100 ms - acquireInterval = qBound(10, acquireInterval, 100); + acquireInterval = qBound( 10, acquireInterval, 100 ); displayInterval = 20; #else // Not more often than every 1 ms but at least once every 100 ms - acquireInterval = qBound(1, acquireInterval, 100); + acquireInterval = qBound( 1, acquireInterval, 100 ); displayInterval = 10; #endif } @@ -706,20 +718,20 @@ void HantekDsoControl::run() { static unsigned activeChannels = 2; // Send all pending control commands ControlCommand *controlCommand = firstControlCommand; - while (controlCommand) { - if (controlCommand->pending) { - timestampDebug(QString("Sending control command %1:%2") - .arg(QString::number(controlCommand->code, 16), - hexDump(controlCommand->data(), controlCommand->size()))); + while ( controlCommand ) { + if ( controlCommand->pending ) { + timestampDebug( QString( "Sending control command %1:%2" ) + .arg( QString::number( controlCommand->code, 16 ), + hexDump( controlCommand->data(), controlCommand->size() ) ) ); if ( controlCommand->code == uint8_t( ControlCode::CONTROL_SETNUMCHANNELS ) ) activeChannels = *controlCommand->data(); - errorCode = device->controlWrite(controlCommand); - if (errorCode < 0) { - qWarning("Sending control command %2x failed: %s", uint8_t( controlCommand->code ), - libUsbErrorString(errorCode).toLocal8Bit().data()); + errorCode = device->controlWrite( controlCommand ); + if ( errorCode < 0 ) { + qWarning( "Sending control command %2x failed: %s", uint8_t( controlCommand->code ), + libUsbErrorString( errorCode ).toLocal8Bit().data() ); - if (errorCode == LIBUSB_ERROR_NO_DEVICE) { + if ( errorCode == LIBUSB_ERROR_NO_DEVICE ) { emit communicationError(); return; } @@ -731,24 +743,24 @@ void HantekDsoControl::run() { // State machine for the device communication bool triggered = false; - std::vector rawData = this->getSamples(expectedSampleCount); + std::vector rawData = this->getSamples( expectedSampleCount ); if ( samplingStarted ) { - convertRawDataToSamples(rawData, activeChannels); // process new samples - softwareTrigger(); // detect trigger point - triggered = triggering(); // present either free running or last triggered trace + convertRawDataToSamples( rawData, activeChannels ); // process new samples + softwareTrigger(); // detect trigger point + triggered = triggering(); // present either free running or last triggered trace } // always run the display (slowly) to allow user interaction // ... but update immediately if new triggered data is available if ( ( triggered && !lastTriggered ) || ( delayDisplay += acquireInterval ) >= displayInterval ) { delayDisplay = 0; - emit samplesAvailable(&result); - //printf( "acquireInterval: %d, displayInterval: %d\n", acquireInterval, displayInterval ); + emit samplesAvailable( &result ); + // printf( "acquireInterval: %d, displayInterval: %d\n", acquireInterval, displayInterval ); } lastTriggered = triggered; // Stop sampling if we're in single trigger mode and have a triggered trace (txh No13) if ( controlsettings.trigger.mode == Dso::TriggerMode::SINGLE && samplingStarted && triggeredPositionRaw > 0 ) { - enableSampling(false); + enableSampling( false ); } // Sampling completed, restart it when necessary @@ -757,49 +769,49 @@ void HantekDsoControl::run() { if ( sampling ) { // Sampling hasn't started, update the expected sample count expectedSampleCount = this->getSampleCount(); - timestampDebug("Starting to capture"); + timestampDebug( "Starting to capture" ); samplingStarted = true; } updateInterval(); -#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) - QTimer::singleShot(acquireInterval, this, &HantekDsoControl::run); +#if ( QT_VERSION >= QT_VERSION_CHECK( 5, 4, 0 ) ) + QTimer::singleShot( acquireInterval, this, &HantekDsoControl::run ); #else - QTimer::singleShot(acquireInterval, this, SLOT(run())); + QTimer::singleShot( acquireInterval, this, SLOT( run() ) ); #endif } -void HantekDsoControl::addCommand(ControlCommand *newCommand, bool pending) { +void HantekDsoControl::addCommand( ControlCommand *newCommand, bool pending ) { newCommand->pending = pending; - control[newCommand->code] = newCommand; + control[ newCommand->code ] = newCommand; newCommand->next = firstControlCommand; firstControlCommand = newCommand; } -Dso::ErrorCode HantekDsoControl::stringCommand(const QString &commandString) { - if (!device->isConnected()) +Dso::ErrorCode HantekDsoControl::stringCommand( const QString &commandString ) { + if ( !device->isConnected() ) return Dso::ErrorCode::CONNECTION; - QStringList commandParts = commandString.split(' ', QString::SkipEmptyParts); + QStringList commandParts = commandString.split( ' ', QString::SkipEmptyParts ); - if (commandParts.count() < 1) + if ( commandParts.count() < 1 ) return Dso::ErrorCode::PARAMETER; - if (commandParts[0] != "send") + if ( commandParts[ 0 ] != "send" ) return Dso::ErrorCode::UNSUPPORTED; - if (commandParts.count() < 2) + if ( commandParts.count() < 2 ) return Dso::ErrorCode::PARAMETER; uint8_t codeIndex = 0; - hexParse(commandParts[2], &codeIndex, 1); - QString data = commandString.section(' ', 2, -1, QString::SectionSkipEmpty); + hexParse( commandParts[ 2 ], &codeIndex, 1 ); + QString data = commandString.section( ' ', 2, -1, QString::SectionSkipEmpty ); - if (commandParts[1] == "control") { - if (!control[codeIndex]) + if ( commandParts[ 1 ] == "control" ) { + if ( !control[ codeIndex ] ) return Dso::ErrorCode::UNSUPPORTED; - ControlCommand *c = modifyCommand(ControlCode( codeIndex ) ); - hexParse(data, c->data(), unsigned( c->size() ) ); + ControlCommand *c = modifyCommand( ControlCode( codeIndex ) ); + hexParse( data, c->data(), unsigned( c->size() ) ); return Dso::ErrorCode::NONE; } else return Dso::ErrorCode::UNSUPPORTED; diff --git a/openhantek/src/hantekdso/hantekdsocontrol.h b/openhantek/src/hantekdso/hantekdsocontrol.h index ae037298..c7486241 100644 --- a/openhantek/src/hantekdso/hantekdsocontrol.h +++ b/openhantek/src/hantekdso/hantekdsocontrol.h @@ -6,13 +6,13 @@ #include #include "controlsettings.h" -#include "scopesettings.h" #include "controlspecification.h" #include "dsosamples.h" #include "errorcodes.h" +#include "scopesettings.h" #include "states.h" -#include "viewconstants.h" #include "utils/printutils.h" +#include "viewconstants.h" #include "hantekprotocol/controlStructs.h" #include "hantekprotocol/definitions.h" @@ -69,18 +69,18 @@ class HantekDsoControl : public QObject { ///

/// \param command The command as string (Has to be parsed). /// \return See ::Dso::ErrorCode. - Dso::ErrorCode stringCommand(const QString &commandString); + Dso::ErrorCode stringCommand( const QString &commandString ); - void addCommand(ControlCommand *newCommand, bool pending = true); + void addCommand( ControlCommand *newCommand, bool pending = true ); - template T *modifyCommand(Hantek::ControlCode code) { + template T *modifyCommand( Hantek::ControlCode code ) { control[ uint8_t( code ) ]->pending = true; - return static_cast(control[ uint8_t( code ) ] ); + return static_cast( control[ uint8_t( code ) ] ); } - bool hasCommand(Hantek::ControlCode code) { return ( control[uint8_t(code)] != nullptr ); } + bool hasCommand( Hantek::ControlCode code ) { return ( control[ uint8_t( code ) ] != nullptr ); } - const ControlCommand *getCommand(Hantek::ControlCode code) const { return control[ uint8_t( code ) ]; } + const ControlCommand *getCommand( Hantek::ControlCode code ) const { return control[ uint8_t( code ) ]; } // Attic for no more used public procedures #if 0 @@ -148,13 +148,9 @@ class HantekDsoControl : public QObject { private: bool fastRate = true; - void setFastRate( bool fast ) { - fastRate = fast; - } + void setFastRate( bool fast ) { fastRate = fast; } - bool isFastRate() const { - return fastRate; - } + bool isFastRate() const { return fastRate; } unsigned getRecordLength() const; @@ -174,10 +170,10 @@ class HantekDsoControl : public QObject { /// \brief Calculates the trigger point from the CommandGetCaptureState data. /// \param value The data value that contains the trigger point. /// \return The calculated trigger point for the given data. - static unsigned calculateTriggerPoint(unsigned value); + static unsigned calculateTriggerPoint( unsigned value ); /// \brief Gets sample data from the oscilloscope - std::vector getSamples(unsigned &expectedSampleCount) const; + std::vector getSamples( unsigned &expectedSampleCount ) const; /// \brief Converts raw oscilloscope data to sample data void convertRawDataToSamples( const std::vector &rawData, unsigned numChannels ); @@ -187,7 +183,7 @@ class HantekDsoControl : public QObject { /// \param downsampler The downsampling factor. /// \param fastRate true, if one channel uses all buffers. /// \return The downsampling factor that has been set. - unsigned updateSamplerate(unsigned downsampler); + unsigned updateSamplerate( unsigned downsampler ); /// \brief Restore the samplerate/timebase targets after divider updates. void restoreTargets(); @@ -206,7 +202,7 @@ class HantekDsoControl : public QObject { bool triggering(); /// Pointers to control commands - ControlCommand *control[255] = { nullptr }; + ControlCommand *control[ 255 ] = {nullptr}; ControlCommand *firstControlCommand = nullptr; // Communication with device @@ -218,7 +214,7 @@ class HantekDsoControl : public QObject { Dso::ControlSettings controlsettings; ///< The current settings of the device // Results - unsigned downsamplingNumber = 1; ///< Number of downsamples to reduce sample rate + unsigned downsamplingNumber = 1; ///< Number of downsamples to reduce sample rate DSOsamples result; unsigned expectedSampleCount = 0; ///< The expected total number of samples at /// the last check before sampling started @@ -232,99 +228,99 @@ class HantekDsoControl : public QObject { /// \brief If sampling is disabled, no samplesAvailable() signals are send anymore, no samples /// are fetched from the device and no processing takes place. /// \param enabled Enables/Disables sampling - void enableSampling(bool enabled); + void enableSampling( bool enabled ); /// \brief Sets the samplerate of the oscilloscope. /// \param samplerate The samplerate that should be met (S/s), 0.0 to restore /// current samplerate. /// \return The samplerate that has been set, 0.0 on error. - Dso::ErrorCode setSamplerate(double samplerate = 0.0); + Dso::ErrorCode setSamplerate( double samplerate = 0.0 ); /// \brief Sets the time duration of one aquisition by adapting the samplerate. /// \param duration The record time duration that should be met (s), 0.0 to /// restore current record time. /// \return The record time duration that has been set, 0.0 on error. - Dso::ErrorCode setRecordTime(double duration = 0.0); + Dso::ErrorCode setRecordTime( double duration = 0.0 ); /// \brief Enables/disables filtering of the given channel. /// \param channel The channel that should be set. /// \param used true if the channel should be sampled. /// \return See ::Dso::ErrorCode. - Dso::ErrorCode setChannelUsed(ChannelID channel, bool used); + Dso::ErrorCode setChannelUsed( ChannelID channel, bool used ); /// \brief Enables/disables inverting of the given channel. /// \param channel The channel that should be set. /// \param used true if the channel is inverted. /// \return See ::Dso::ErrorCode. - Dso::ErrorCode setChannelInverted(ChannelID channel, bool inverted); + Dso::ErrorCode setChannelInverted( ChannelID channel, bool inverted ); /// \brief Sets the gain for the given channel. /// Get the actual gain by specification.gainSteps[gainId] /// \param channel The channel that should be set. /// \param gain The gain that should be met (V/div). /// \return The gain that has been set, ::Dso::ErrorCode on error. - Dso::ErrorCode setProbe(ChannelID channel, double probeAttn); + Dso::ErrorCode setProbe( ChannelID channel, double probeAttn ); /// \brief Sets the probe gain for the given channel. /// \param channel The channel that should be set. /// \param probeAttn gain of probe is set. /// \return error code. - Dso::ErrorCode setGain(ChannelID channel, double gain); + Dso::ErrorCode setGain( ChannelID channel, double gain ); /// \brief Sets the coupling for the given channel. /// \param channel The channel that should be set. /// \param coupling The coupling that should be set. /// \return error code. - Dso::ErrorCode setCoupling(ChannelID channel, Dso::Coupling coupling); + Dso::ErrorCode setCoupling( ChannelID channel, Dso::Coupling coupling ); /// \brief Set the trigger mode. /// \return See ::Dso::ErrorCode. - Dso::ErrorCode setTriggerMode(Dso::TriggerMode mode); + Dso::ErrorCode setTriggerMode( Dso::TriggerMode mode ); /// \brief Set the trigger source. /// \param id The channel that should be used as trigger. /// \return See ::Dso::ErrorCode. - Dso::ErrorCode setTriggerSource(ChannelID channel, bool smooth); + Dso::ErrorCode setTriggerSource( ChannelID channel, bool smooth ); /// \brief Set the trigger level. /// \param channel The channel that should be set. /// \param level The new trigger level (V). /// \return See ::Dso::ErrorCode. - Dso::ErrorCode setTriggerLevel(ChannelID channel, double level); + Dso::ErrorCode setTriggerLevel( ChannelID channel, double level ); /// \brief Set the trigger slope. /// \param slope The Slope that should cause a trigger. /// \return See ::Dso::ErrorCode. - Dso::ErrorCode setTriggerSlope(Dso::Slope slope); + Dso::ErrorCode setTriggerSlope( Dso::Slope slope ); /// \brief Set the trigger position. /// \param position The new trigger position (in s). /// \return The trigger position that has been set. - Dso::ErrorCode setTriggerOffset (double position); + Dso::ErrorCode setTriggerOffset( double position ); /// \brief Sets the calibration frequency of the oscilloscope. /// \param calfreq The calibration frequency. /// \return The tfrequency that has been set, ::Dso::ErrorCode on error. - Dso::ErrorCode setCalFreq(double calfreq = 0.0); + Dso::ErrorCode setCalFreq( double calfreq = 0.0 ); /// \brief Initializes the device with the current settings. - /// \param scope The settings for the oscilloscope. - void applySettings(DsoSettingsScope *scope); - + /// \param scope The settings for the oscilloscope. + void applySettings( DsoSettingsScope *scope ); + signals: - void samplingStatusChanged(bool enabled); ///< The oscilloscope started/stopped sampling/waiting for trigger - void statusMessage(const QString &message, int timeout); ///< Status message about the oscilloscope - void samplesAvailable(const DSOsamples *samples); ///< New sample data is available + void samplingStatusChanged( bool enabled ); ///< The oscilloscope started/stopped sampling/waiting for trigger + void statusMessage( const QString &message, int timeout ); ///< Status message about the oscilloscope + void samplesAvailable( const DSOsamples *samples ); ///< New sample data is available /// The available samplerate range has changed - void samplerateLimitsChanged(double minimum, double maximum); + void samplerateLimitsChanged( double minimum, double maximum ); /// The available samplerate for fixed samplerate devices has changed - void samplerateSet(int mode, QList sampleSteps); + void samplerateSet( int mode, QList sampleSteps ); - void recordTimeChanged(double duration); ///< The record time duration has changed - void samplerateChanged(double samplerate); ///< The samplerate has changed + void recordTimeChanged( double duration ); ///< The record time duration has changed + void samplerateChanged( double samplerate ); ///< The samplerate has changed void communicationError() const; }; -Q_DECLARE_METATYPE(DSOsamples *) +Q_DECLARE_METATYPE( DSOsamples * ) diff --git a/openhantek/src/hantekdso/modelregistry.cpp b/openhantek/src/hantekdso/modelregistry.cpp index 4606b3e2..fe822e79 100644 --- a/openhantek/src/hantekdso/modelregistry.cpp +++ b/openhantek/src/hantekdso/modelregistry.cpp @@ -7,6 +7,6 @@ ModelRegistry *ModelRegistry::get() { return &inst; } -void ModelRegistry::add(DSOModel *model) { supportedModels.push_back(model); } +void ModelRegistry::add( DSOModel *model ) { supportedModels.push_back( model ); } const std::list ModelRegistry::models() const { return supportedModels; } diff --git a/openhantek/src/hantekdso/modelregistry.h b/openhantek/src/hantekdso/modelregistry.h index bab46c36..f4e5063e 100644 --- a/openhantek/src/hantekdso/modelregistry.h +++ b/openhantek/src/hantekdso/modelregistry.h @@ -5,10 +5,11 @@ #include "dsomodel.h" class ModelRegistry { -public: + public: static ModelRegistry *get(); - void add(DSOModel* model); - const std::list models() const; -private: - std::list supportedModels; + void add( DSOModel *model ); + const std::list models() const; + + private: + std::list supportedModels; }; diff --git a/openhantek/src/hantekdso/models/modelDDS120.cpp b/openhantek/src/hantekdso/models/modelDDS120.cpp index 773b50de..b7ccad55 100644 --- a/openhantek/src/hantekdso/models/modelDDS120.cpp +++ b/openhantek/src/hantekdso/models/modelDDS120.cpp @@ -1,11 +1,11 @@ // SPDX-License-Identifier: GPL-2.0+ -#include -#include #include "modelDDS120.h" -#include "usb/usbdevice.h" -#include "hantekprotocol/controlStructs.h" #include "hantekdsocontrol.h" +#include "hantekprotocol/controlStructs.h" +#include "usb/usbdevice.h" +#include +#include #define VERBOSE 0 @@ -13,27 +13,27 @@ using namespace Hantek; static ModelDDS120 modelInstance_120; -static void initSpecifications(Dso::ControlSpecification& specification) { +static void initSpecifications( Dso::ControlSpecification &specification ) { // we drop 2K + 480 sample values due to unreliable start of stream // 20000 samples at 100kS/s = 200 ms gives enough to fill // the screen two times (for pre/post trigger) at 10ms/div = 100ms/screen // SAMPLESIZE defined in modelDDS120.h // adapt accordingly in HantekDsoControl::convertRawDataToSamples() - specification.bufferDividers = { 1000 , 1 , 1 }; + specification.bufferDividers = {1000, 1, 1}; // This data was based on testing and depends on divider. // The sample value at the top of the screen with gain error correction // TODO: check if 20x is possible for 1st and 2nd value // double the values accordingly 32 -> 64 & 80 -> 160 and change 10 -> 20 in specification.gain below - specification.voltageScale[0] = { 64 , 160 , 160 , 155 , 170 , 165 , 330 , 820 }; - specification.voltageScale[1] = { 64 , 160 , 160 , 155 , 170 , 165 , 330 , 820 }; + specification.voltageScale[ 0 ] = {64, 160, 160, 155, 170, 165, 330, 820}; + specification.voltageScale[ 1 ] = {64, 160, 160, 155, 170, 165, 330, 820}; // theoretical offset, will be corrected by individual config file - specification.voltageOffset[0] = { 0, 0, 0, 0, 0, 0, 0, 0 }; - specification.voltageOffset[1] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + specification.voltageOffset[ 0 ] = {0, 0, 0, 0, 0, 0, 0, 0}; + specification.voltageOffset[ 1 ] = {0, 0, 0, 0, 0, 0, 0, 0}; // read the real calibration values from file - const char* ranges[] = { "20mV", "50mV","100mV", "200mV", "500mV", "1000mV", "2000mV", "5000mV" }; - const char* channels[] = { "ch0", "ch1" }; - //printf( "read config file\n" ); + const char *ranges[] = {"20mV", "50mV", "100mV", "200mV", "500mV", "1000mV", "2000mV", "5000mV"}; + const char *channels[] = {"ch0", "ch1"}; + // printf( "read config file\n" ); const unsigned RANGES = 8; QSettings settings( QDir::homePath() + "/.config/OpenHantek/modelDDS120.conf", QSettings::IniFormat ); @@ -53,7 +53,7 @@ static void initSpecifications(Dso::ControlSpecification& specification) { for ( unsigned ch = 0; ch < 2; ch++ ) { settings.beginGroup( channels[ ch ] ); for ( unsigned iii = 0; iii < RANGES; iii++ ) { - //settings.setValue( ranges[ iii ], iii ); + // settings.setValue( ranges[ iii ], iii ); // set to 0x80 if no value from conf file int offset = settings.value( ranges[ iii ], "255" ).toInt(); if ( offset != 255 ) // value exists in config file @@ -69,47 +69,48 @@ static void initSpecifications(Dso::ControlSpecification& specification) { // Hantek has only 10x, 5x, 2x, 1x // TODO: check if 20x is possible for ID 0 and ID 1 // change 10 to 20 and double the values of specification.voltageLimit[] above - specification.gain = { // ID, HW gain, full scale voltage - { 20, 0.16}, // 0 20 160mV = 20mV/div - { 20, 0.40}, // 1 20 400mV = 50mV/div - { 10, 0.80}, // 2 10 800mV = 100mV/div - { 5, 1.60}, // 3 5 1.6V = 200mV/div - { 2, 4.00}, // 4 2 4.0V = 500mV/div - { 1, 8.00}, // 5 1 8.0V = 1V/div - { 1, 16.00}, // 6 1 16.0V = 2V/div - { 1, 40.00} // 7 1 40.0V = 5V/div + specification.gain = { + // ID, HW gain, full scale voltage + {20, 0.16}, // 0 20 160mV = 20mV/div + {20, 0.40}, // 1 20 400mV = 50mV/div + {10, 0.80}, // 2 10 800mV = 100mV/div + {5, 1.60}, // 3 5 1.6V = 200mV/div + {2, 4.00}, // 4 2 4.0V = 500mV/div + {1, 8.00}, // 5 1 8.0V = 1V/div + {1, 16.00}, // 6 1 16.0V = 2V/div + {1, 40.00} // 7 1 40.0V = 5V/div }; specification.samplerate.single.base = 1e6; specification.samplerate.single.max = 30e6; - specification.samplerate.single.recordLengths = { UINT_MAX }; + specification.samplerate.single.recordLengths = {UINT_MAX}; specification.samplerate.multi.base = 1e6; specification.samplerate.multi.max = 15e6; - specification.samplerate.multi.recordLengths = { UINT_MAX }; + specification.samplerate.multi.recordLengths = {UINT_MAX}; -// This model uses the sigrok firmware that has a slightly different coding for the sample rate than my Hantek6022API version. -// 10=100k, 20=200k, 50=500k, 11=10M (Hantek: 110=100k, 120=200k, 150=500k, 10=10M) + // This model uses the sigrok firmware that has a slightly different coding for the sample rate than my + // Hantek6022API version. 10=100k, 20=200k, 50=500k, 11=10M (Hantek: 110=100k, 120=200k, 150=500k, 10=10M) // 48M is unstable in 1 channel mode // 24M, 30M and 48M are unstable in 2 channel mode specification.fixedSampleRates = { - // samplerate, sampleId, downsampling - { 10e3, 1, 100}, // 100x downsampling from 1 MS/s! - { 20e3, 2, 100}, // 100x downsampling from 2 MS/s! - { 50e3, 5, 100}, // 100x downsampling from 5 MS/s! - {100e3, 8, 80}, // 80x downsampling from 8 MS/s - {200e3, 8, 40}, // 40x downsampling from 8 MS/s - {500e3, 8, 16}, // 16x downsampling from 8 MS/s - { 1e6, 8, 8}, // 8x downsampling from 8 MS/s - { 2e6, 8, 4}, // 4x downsampling from 8 MS/s - { 5e6, 15, 3}, // 3x downsampling from 15 MS/s - { 10e6, 11, 1}, // no downsampling, 11 means 10 MS/s - { 15e6, 15, 1}, // no downsampling - { 24e6, 24, 1}, // no downsampling - { 30e6, 30, 1}, // no downsampling - { 48e6, 48, 1} // no downsampling + // samplerate, sampleId, downsampling + {10e3, 1, 100}, // 100x downsampling from 1 MS/s! + {20e3, 2, 100}, // 100x downsampling from 2 MS/s! + {50e3, 5, 100}, // 100x downsampling from 5 MS/s! + {100e3, 8, 80}, // 80x downsampling from 8 MS/s + {200e3, 8, 40}, // 40x downsampling from 8 MS/s + {500e3, 8, 16}, // 16x downsampling from 8 MS/s + {1e6, 8, 8}, // 8x downsampling from 8 MS/s + {2e6, 8, 4}, // 4x downsampling from 8 MS/s + {5e6, 15, 3}, // 3x downsampling from 15 MS/s + {10e6, 11, 1}, // no downsampling, 11 means 10 MS/s + {15e6, 15, 1}, // no downsampling + {24e6, 24, 1}, // no downsampling + {30e6, 30, 1}, // no downsampling + {48e6, 48, 1} // no downsampling }; @@ -117,28 +118,25 @@ static void initSpecifications(Dso::ControlSpecification& specification) { specification.triggerModes = {Dso::TriggerMode::AUTO, Dso::TriggerMode::NORMAL, Dso::TriggerMode::SINGLE}; specification.fixedUSBinLength = 0; // use calibration frequency steps of modified sigrok FW (<= 20 kHz) - specification.calfreqSteps = { 50, 60, 100, 200, 500, 1000, 2000, 5000, 10000, 20000 }; + specification.calfreqSteps = {50, 60, 100, 200, 500, 1000, 2000, 5000, 10000, 20000}; specification.hasCalibrationEEPROM = false; } -static void applyRequirements_(HantekDsoControl *dsoControl) { - dsoControl->addCommand(new ControlSetVoltDIV_CH1()); // 0xE0 - dsoControl->addCommand(new ControlSetVoltDIV_CH2()); // 0xE1 - dsoControl->addCommand(new ControlSetTimeDIV()); // 0xE2 - dsoControl->addCommand(new ControlAcquireHardData()); // 0xE3 - dsoControl->addCommand(new ControlSetNumChannels()); // 0xE4 - dsoControl->addCommand(new ControlSetCoupling()); // 0xE5 - dsoControl->addCommand(new ControlSetCalFreq()); // 0xE6 +static void applyRequirements_( HantekDsoControl *dsoControl ) { + dsoControl->addCommand( new ControlSetVoltDIV_CH1() ); // 0xE0 + dsoControl->addCommand( new ControlSetVoltDIV_CH2() ); // 0xE1 + dsoControl->addCommand( new ControlSetTimeDIV() ); // 0xE2 + dsoControl->addCommand( new ControlAcquireHardData() ); // 0xE3 + dsoControl->addCommand( new ControlSetNumChannels() ); // 0xE4 + dsoControl->addCommand( new ControlSetCoupling() ); // 0xE5 + dsoControl->addCommand( new ControlSetCalFreq() ); // 0xE6 } // VID/PID active VID/PID no FW FW ver FW name Scope name // |------------| |------------| |----| |------| |------| -ModelDDS120::ModelDDS120() : DSOModel(ID, 0x04b5, 0x0120, 0x8102, 0x8102, 0x0100, "dds120", "DDS120", - Dso::ControlSpecification(2)) { - initSpecifications(specification); -} - -void ModelDDS120::applyRequirements(HantekDsoControl *dsoControl) const { - applyRequirements_(dsoControl); +ModelDDS120::ModelDDS120() + : DSOModel( ID, 0x04b5, 0x0120, 0x8102, 0x8102, 0x0100, "dds120", "DDS120", Dso::ControlSpecification( 2 ) ) { + initSpecifications( specification ); } +void ModelDDS120::applyRequirements( HantekDsoControl *dsoControl ) const { applyRequirements_( dsoControl ); } diff --git a/openhantek/src/hantekdso/models/modelDDS120.h b/openhantek/src/hantekdso/models/modelDDS120.h index 11c3803c..55999ad1 100644 --- a/openhantek/src/hantekdso/models/modelDDS120.h +++ b/openhantek/src/hantekdso/models/modelDDS120.h @@ -11,5 +11,5 @@ using namespace Hantek; struct ModelDDS120 : public DSOModel { static const int ID = 0x0120; ModelDDS120(); - void applyRequirements(HantekDsoControl* dsoControl) const override; + void applyRequirements( HantekDsoControl *dsoControl ) const override; }; diff --git a/openhantek/src/hantekdso/models/modelDSO6022.cpp b/openhantek/src/hantekdso/models/modelDSO6022.cpp index 7103017f..a36a48a7 100644 --- a/openhantek/src/hantekdso/models/modelDSO6022.cpp +++ b/openhantek/src/hantekdso/models/modelDSO6022.cpp @@ -1,11 +1,11 @@ // SPDX-License-Identifier: GPL-2.0+ -#include -#include #include "modelDSO6022.h" -#include "usb/usbdevice.h" -#include "hantekprotocol/controlStructs.h" #include "hantekdsocontrol.h" +#include "hantekprotocol/controlStructs.h" +#include "usb/usbdevice.h" +#include +#include #define VERBOSE 0 @@ -16,13 +16,13 @@ static ModelDSO6022BL modelInstance_6022bl; static ModelDSO2020 modelInstance_2020; -static void initSpecifications(Dso::ControlSpecification& specification) { +static void initSpecifications( Dso::ControlSpecification &specification ) { // we drop 2K + 480 sample values due to unreliable start of stream // 20000 samples at 100kS/s = 200 ms gives enough to fill // the screen two times (for pre/post trigger) at 10ms/div = 100ms/screen // SAMPLESIZE defined in modelDSO6022.h // adapt accordingly in HantekDsoControl::convertRawDataToSamples() - specification.bufferDividers = { 1000 , 1 , 1 }; + specification.bufferDividers = {1000, 1, 1}; // Define the scaling between ADC sample values and real input voltage // Everything is scaled on the full screen height (8 divs) // The voltage/div setting: 20m 50m 100m 200m 500m 1V 2V 5V @@ -34,16 +34,16 @@ static void initSpecifications(Dso::ControlSpecification& specification) { // Amplifier gain: x1 (ok), x2 (ok), x5.1 (2% too high), x10.1 (1% too high) // Overall resulting gain: x1 1% too low, x2 1% to low, x5 1% to high, x10 ok // The sample value for full screen (8 divs) with theoretical gain setting - specification.voltageScale[0] = { 40 , 100 , 200 , 202 , 198 , 198 , 396 , 990 }; - specification.voltageScale[1] = { 40 , 100 , 200 , 202 , 198 , 198 , 396 , 990 }; - specification.voltageOffset[0] = { 0, 0, 0, 0, 0, 0, 0, 0 }; - specification.voltageOffset[1] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + specification.voltageScale[ 0 ] = {40, 100, 200, 202, 198, 198, 396, 990}; + specification.voltageScale[ 1 ] = {40, 100, 200, 202, 198, 198, 396, 990}; + specification.voltageOffset[ 0 ] = {0, 0, 0, 0, 0, 0, 0, 0}; + specification.voltageOffset[ 1 ] = {0, 0, 0, 0, 0, 0, 0, 0}; // Gain and offset can be corrected by individual config values from EEPROM or file // read the real calibration values from file - const char* ranges[] = { "20mV", "50mV","100mV", "200mV", "500mV", "1000mV", "2000mV", "5000mV" }; - const char* channels[] = { "ch0", "ch1" }; - //printf( "read config file\n" ); + const char *ranges[] = {"20mV", "50mV", "100mV", "200mV", "500mV", "1000mV", "2000mV", "5000mV"}; + const char *channels[] = {"ch0", "ch1"}; + // printf( "read config file\n" ); const unsigned RANGES = 8; QSettings settings( QDir::homePath() + "/.config/OpenHantek/modelDSO6022.conf", QSettings::IniFormat ); @@ -52,7 +52,7 @@ static void initSpecifications(Dso::ControlSpecification& specification) { settings.beginGroup( channels[ ch ] ); for ( unsigned iii = 0; iii < RANGES; iii++ ) { double gain = settings.value( ranges[ iii ], "0.0" ).toDouble(); - //printf( "ch%d %s: gain = %g\n", ch, ranges[ iii ], gain ); + // printf( "ch%d %s: gain = %g\n", ch, ranges[ iii ], gain ); if ( bool( gain ) ) specification.voltageScale[ ch ][ iii ] /= gain; } @@ -66,7 +66,7 @@ static void initSpecifications(Dso::ControlSpecification& specification) { for ( unsigned iii = 0; iii < RANGES; iii++ ) { // set to 0x00 if no value from conf file int offset = settings.value( ranges[ iii ], "255" ).toInt(); - //printf( "ch%d %s: offset = %d\n", ch, ranges[ iii ], offset ); + // printf( "ch%d %s: offset = %d\n", ch, ranges[ iii ], offset ); if ( offset != 255 ) // value exists in config file specification.voltageOffset[ ch ][ iii ] = 0x80 - offset; } @@ -75,16 +75,7 @@ static void initSpecifications(Dso::ControlSpecification& specification) { settings.endGroup(); // offset // HW gain, voltage steps in V/screenheight (ranges 20,50,100,200,500,1000,2000,5000 mV) - specification.gain = { - {10, 0.16}, - {10, 0.40}, - {10, 0.80}, - { 5, 1.60}, - { 2, 4.00}, - { 1, 8.00}, - { 1, 16.00}, - { 1, 40.00} - }; + specification.gain = {{10, 0.16}, {10, 0.40}, {10, 0.80}, {5, 1.60}, {2, 4.00}, {1, 8.00}, {1, 16.00}, {1, 40.00}}; // Possible raw sample rates with custom fw from https://github.com/Ho-Ro/Hantek6022API // 20k, 50k, 64k, 100k, 200k, 500k, 1M, 2M, 3M, 4M, 5M, 6M, 8M, 10M, 12M, 15M, 16M, 24M, 30M (, 48M) @@ -95,38 +86,39 @@ static void initSpecifications(Dso::ControlSpecification& specification) { specification.samplerate.single.base = 1e6; specification.samplerate.single.max = 30e6; - specification.samplerate.single.recordLengths = { UINT_MAX }; + specification.samplerate.single.recordLengths = {UINT_MAX}; specification.samplerate.multi.base = 1e6; specification.samplerate.multi.max = 15e6; - specification.samplerate.multi.recordLengths = { UINT_MAX }; + specification.samplerate.multi.recordLengths = {UINT_MAX}; -// define VERY_SLOW_SAMPLES to get timebase up to 1s/div at the expense of very slow reaction time (up to 20 s) -//#define VERY_SLOW_SAMPLES - specification.fixedSampleRates = { // samplerate, sampleId, downsampling + // define VERY_SLOW_SAMPLES to get timebase up to 1s/div at the expense of very slow reaction time (up to 20 s) + //#define VERY_SLOW_SAMPLES + specification.fixedSampleRates = { + // samplerate, sampleId, downsampling #ifdef VERY_SLOW_SAMPLES - { 1e3, 110, 100}, // 100x downsampling from 100, 200, 500 kS/s! - { 2e3, 120, 100}, // - { 5e3, 150, 100}, // + {1e3, 110, 100}, // 100x downsampling from 100, 200, 500 kS/s! + {2e3, 120, 100}, // + {5e3, 150, 100}, // #endif - { 10e3, 1, 100}, // 100x downsampling from 1, 2, 5, 10 MS/s! - { 20e3, 2, 100}, // - { 50e3, 5, 100}, // - {100e3, 10, 100}, // - {200e3, 10, 50}, // 50x, 20x 10x, 5x, 2x downsampling from 10 MS/s - {500e3, 10, 20}, // - { 1e6, 10, 10}, // - { 2e6, 10, 5}, // - { 5e6, 10, 2}, // - { 10e6, 10, 1}, // no oversampling - { 12e6, 12, 1}, // - { 15e6, 15, 1}, // - { 24e6, 24, 1}, // - { 30e6, 30, 1}, // - { 48e6, 48, 1} // + {10e3, 1, 100}, // 100x downsampling from 1, 2, 5, 10 MS/s! + {20e3, 2, 100}, // + {50e3, 5, 100}, // + {100e3, 10, 100}, // + {200e3, 10, 50}, // 50x, 20x 10x, 5x, 2x downsampling from 10 MS/s + {500e3, 10, 20}, // + {1e6, 10, 10}, // + {2e6, 10, 5}, // + {5e6, 10, 2}, // + {10e6, 10, 1}, // no oversampling + {12e6, 12, 1}, // + {15e6, 15, 1}, // + {24e6, 24, 1}, // + {30e6, 30, 1}, // + {48e6, 48, 1} // }; #ifdef HANTEK_AC - // requires AC/DC HW mod like DDS120, enable with "cmake -D HANTEK_AC=1 .." + // requires AC/DC HW mod like DDS120, enable with "cmake -D HANTEK_AC=1 .." specification.couplings = {Dso::Coupling::DC, Dso::Coupling::AC}; #else specification.couplings = {Dso::Coupling::DC}; @@ -135,18 +127,18 @@ static void initSpecifications(Dso::ControlSpecification& specification) { specification.fixedUSBinLength = 0; // calibration frequency (requires >FW0206) - specification.calfreqSteps = { 50, 60, 100, 200, 500, 1e3, 2e3, 5e3, 10e3, 20e3, 50e3, 100e3 }; + specification.calfreqSteps = {50, 60, 100, 200, 500, 1e3, 2e3, 5e3, 10e3, 20e3, 50e3, 100e3}; specification.hasCalibrationEEPROM = true; } -static void applyRequirements_(HantekDsoControl *dsoControl) { - dsoControl->addCommand(new ControlSetVoltDIV_CH1()); // 0xE0 - dsoControl->addCommand(new ControlSetVoltDIV_CH2()); // 0xE1 - dsoControl->addCommand(new ControlSetTimeDIV()); // 0xE2 - dsoControl->addCommand(new ControlAcquireHardData()); // 0xE3 - dsoControl->addCommand(new ControlSetNumChannels()); // 0xE4 - dsoControl->addCommand(new ControlSetCoupling()); // 0xE5 (no effect w/o AC/DC HW mod) - dsoControl->addCommand(new ControlSetCalFreq()); // 0xE6 +static void applyRequirements_( HantekDsoControl *dsoControl ) { + dsoControl->addCommand( new ControlSetVoltDIV_CH1() ); // 0xE0 + dsoControl->addCommand( new ControlSetVoltDIV_CH2() ); // 0xE1 + dsoControl->addCommand( new ControlSetTimeDIV() ); // 0xE2 + dsoControl->addCommand( new ControlAcquireHardData() ); // 0xE3 + dsoControl->addCommand( new ControlSetNumChannels() ); // 0xE4 + dsoControl->addCommand( new ControlSetCoupling() ); // 0xE5 (no effect w/o AC/DC HW mod) + dsoControl->addCommand( new ControlSetCalFreq() ); // 0xE6 } @@ -154,38 +146,33 @@ static void applyRequirements_(HantekDsoControl *dsoControl) { // // VID/PID active VID/PID no FW FW ver FW name Scope name // |------------| |------------| |----| |---------| |----------| -ModelDSO6022BE::ModelDSO6022BE() : DSOModel(ID, 0x04b5, 0x6022, 0x04b4, 0x6022, 0x0206, "dso6022be", "DSO-6022BE", - Dso::ControlSpecification(2)) { - initSpecifications(specification); +ModelDSO6022BE::ModelDSO6022BE() + : DSOModel( ID, 0x04b5, 0x6022, 0x04b4, 0x6022, 0x0206, "dso6022be", "DSO-6022BE", + Dso::ControlSpecification( 2 ) ) { + initSpecifications( specification ); } -void ModelDSO6022BE::applyRequirements(HantekDsoControl *dsoControl) const { - applyRequirements_(dsoControl); -} +void ModelDSO6022BE::applyRequirements( HantekDsoControl *dsoControl ) const { applyRequirements_( dsoControl ); } // Hantek DSO-6022BL (scope or logic analyzer) -ModelDSO6022BL::ModelDSO6022BL() : DSOModel(ID, 0x04b5, 0x602a, 0x04b4, 0x602a, 0x0206, "dso6022bl", "DSO-6022BL", - Dso::ControlSpecification(2)) { - initSpecifications(specification); +ModelDSO6022BL::ModelDSO6022BL() + : DSOModel( ID, 0x04b5, 0x602a, 0x04b4, 0x602a, 0x0206, "dso6022bl", "DSO-6022BL", + Dso::ControlSpecification( 2 ) ) { + initSpecifications( specification ); } -void ModelDSO6022BL::applyRequirements(HantekDsoControl *dsoControl) const { - applyRequirements_(dsoControl); -} +void ModelDSO6022BL::applyRequirements( HantekDsoControl *dsoControl ) const { applyRequirements_( dsoControl ); } // Voltcraft DSO-2020 USB Oscilloscope (HW is identical to 6022) // Scope starts up as model DS-2020 (VID/PID = 04b4/2020) but loads 6022BE firmware and looks like a 6022BE -ModelDSO2020::ModelDSO2020() : DSOModel(ID, 0x04b5, 0x6022, 0x04b4, 0x2020, 0x0206, "dso6022be", "DSO-2020", - Dso::ControlSpecification(2)) { - initSpecifications(specification); -} - -void ModelDSO2020::applyRequirements(HantekDsoControl *dsoControl) const { - applyRequirements_(dsoControl); +ModelDSO2020::ModelDSO2020() + : DSOModel( ID, 0x04b5, 0x6022, 0x04b4, 0x2020, 0x0206, "dso6022be", "DSO-2020", Dso::ControlSpecification( 2 ) ) { + initSpecifications( specification ); } +void ModelDSO2020::applyRequirements( HantekDsoControl *dsoControl ) const { applyRequirements_( dsoControl ); } // two test cases with simple EZUSB board (LCsoft) without EEPROM or with Saleae VID/PID in EEPROM @@ -199,26 +186,23 @@ static ModelSaleae modelInstance_Saleae; // LCSOFT without EEPROM reports EzUSB VID/PID -ModelEzUSB::ModelEzUSB() : DSOModel(ID, 0x04b5, 0x6022, 0x04b4, 0x8613, 0x0206, "dso6022be", "LCsoft-EzUSB", - Dso::ControlSpecification(2)) { - initSpecifications(specification); -} - -void ModelEzUSB::applyRequirements(HantekDsoControl *dsoControl) const { - applyRequirements_(dsoControl); +ModelEzUSB::ModelEzUSB() + : DSOModel( ID, 0x04b5, 0x6022, 0x04b4, 0x8613, 0x0206, "dso6022be", "LCsoft-EzUSB", + Dso::ControlSpecification( 2 ) ) { + initSpecifications( specification ); } +void ModelEzUSB::applyRequirements( HantekDsoControl *dsoControl ) const { applyRequirements_( dsoControl ); } // Saleae VID/PID in EEPROM -ModelSaleae::ModelSaleae() : DSOModel(ID, 0x04b5, 0x6022, 0x0925, 0x3881, 0x0206, "dso6022be", "LCsoft-Saleae", - Dso::ControlSpecification(2)) { - initSpecifications(specification); +ModelSaleae::ModelSaleae() + : DSOModel( ID, 0x04b5, 0x6022, 0x0925, 0x3881, 0x0206, "dso6022be", "LCsoft-Saleae", + Dso::ControlSpecification( 2 ) ) { + initSpecifications( specification ); } -void ModelSaleae::applyRequirements(HantekDsoControl *dsoControl) const { - applyRequirements_(dsoControl); -} +void ModelSaleae::applyRequirements( HantekDsoControl *dsoControl ) const { applyRequirements_( dsoControl ); } #endif diff --git a/openhantek/src/hantekdso/models/modelDSO6022.h b/openhantek/src/hantekdso/models/modelDSO6022.h index dc4bb700..8afb1a36 100644 --- a/openhantek/src/hantekdso/models/modelDSO6022.h +++ b/openhantek/src/hantekdso/models/modelDSO6022.h @@ -11,14 +11,14 @@ using namespace Hantek; struct ModelDSO6022BE : public DSOModel { static const int ID = 0x6022; ModelDSO6022BE(); - void applyRequirements(HantekDsoControl* dsoControl) const override; + void applyRequirements( HantekDsoControl *dsoControl ) const override; }; struct ModelDSO6022BL : public DSOModel { static const int ID = 0x602a; ModelDSO6022BL(); - void applyRequirements(HantekDsoControl* dsoControl) const override; + void applyRequirements( HantekDsoControl *dsoControl ) const override; }; @@ -26,7 +26,7 @@ struct ModelDSO6022BL : public DSOModel { struct ModelDSO2020 : public DSOModel { static const int ID = 0x6022; ModelDSO2020(); - void applyRequirements(HantekDsoControl* dsoControl) const override; + void applyRequirements( HantekDsoControl *dsoControl ) const override; }; @@ -41,13 +41,13 @@ struct ModelDSO2020 : public DSOModel { struct ModelEzUSB : public DSOModel { static const int ID = 0x6022; ModelEzUSB(); - void applyRequirements(HantekDsoControl* dsoControl) const override; + void applyRequirements( HantekDsoControl *dsoControl ) const override; }; struct ModelSaleae : public DSOModel { static const int ID = 0x6022; ModelSaleae(); - void applyRequirements(HantekDsoControl* dsoControl) const override; + void applyRequirements( HantekDsoControl *dsoControl ) const override; }; #endif diff --git a/openhantek/src/hantekdso/states.h b/openhantek/src/hantekdso/states.h index a60af63a..2921c745 100644 --- a/openhantek/src/hantekdso/states.h +++ b/openhantek/src/hantekdso/states.h @@ -28,4 +28,4 @@ enum CaptureState { CAPTURE_ERROR = 1000 }; -} +} // namespace Hantek diff --git a/openhantek/src/hantekprotocol/controlStructs.cpp b/openhantek/src/hantekprotocol/controlStructs.cpp index 24f3afe8..3efe2bab 100644 --- a/openhantek/src/hantekprotocol/controlStructs.cpp +++ b/openhantek/src/hantekprotocol/controlStructs.cpp @@ -8,78 +8,73 @@ namespace Hantek { -ControlBeginCommand::ControlBeginCommand(CommandIndex index) - : ControlCommand(Hantek::ControlCode::CONTROL_BEGINCOMMAND, 10) { - data()[0] = 0x0f; - data()[1] = uint8_t(index); +ControlBeginCommand::ControlBeginCommand( CommandIndex index ) + : ControlCommand( Hantek::ControlCode::CONTROL_BEGINCOMMAND, 10 ) { + data()[ 0 ] = 0x0f; + data()[ 1 ] = uint8_t( index ); } -ControlGetSpeed::ControlGetSpeed() : ControlCommand(Hantek::ControlCode::CONTROL_GETSPEED, 10) { } +ControlGetSpeed::ControlGetSpeed() : ControlCommand( Hantek::ControlCode::CONTROL_GETSPEED, 10 ) {} // ConnectionSpeed ControlGetSpeed::getSpeed() { return (ConnectionSpeed)data()[0]; } -ControlSetVoltDIV_CH1::ControlSetVoltDIV_CH1() : ControlCommand(ControlCode::CONTROL_SETVOLTDIV_CH1, 1) { - this->setDiv(5); +ControlSetVoltDIV_CH1::ControlSetVoltDIV_CH1() : ControlCommand( ControlCode::CONTROL_SETVOLTDIV_CH1, 1 ) { + this->setDiv( 5 ); } -void ControlSetVoltDIV_CH1::setDiv(uint8_t val) { data()[0] = val; } +void ControlSetVoltDIV_CH1::setDiv( uint8_t val ) { data()[ 0 ] = val; } -ControlSetVoltDIV_CH2::ControlSetVoltDIV_CH2() : ControlCommand(ControlCode::CONTROL_SETVOLTDIV_CH2, 1) { - this->setDiv(5); +ControlSetVoltDIV_CH2::ControlSetVoltDIV_CH2() : ControlCommand( ControlCode::CONTROL_SETVOLTDIV_CH2, 1 ) { + this->setDiv( 5 ); } -void ControlSetVoltDIV_CH2::setDiv(uint8_t val) { data()[0] = val; } +void ControlSetVoltDIV_CH2::setDiv( uint8_t val ) { data()[ 0 ] = val; } -ControlSetTimeDIV::ControlSetTimeDIV() : ControlCommand(ControlCode::CONTROL_SETTIMEDIV, 1) { - this->setDiv(1); -} +ControlSetTimeDIV::ControlSetTimeDIV() : ControlCommand( ControlCode::CONTROL_SETTIMEDIV, 1 ) { this->setDiv( 1 ); } -void ControlSetTimeDIV::setDiv(uint8_t val) { data()[0] = val; } +void ControlSetTimeDIV::setDiv( uint8_t val ) { data()[ 0 ] = val; } -ControlSetNumChannels::ControlSetNumChannels() : ControlCommand(ControlCode::CONTROL_SETNUMCHANNELS, 1) { - this->setDiv(2); +ControlSetNumChannels::ControlSetNumChannels() : ControlCommand( ControlCode::CONTROL_SETNUMCHANNELS, 1 ) { + this->setDiv( 2 ); } -void ControlSetNumChannels::setDiv(uint8_t val) { data()[0] = val; } +void ControlSetNumChannels::setDiv( uint8_t val ) { data()[ 0 ] = val; } -ControlAcquireHardData::ControlAcquireHardData() : ControlCommand(ControlCode::CONTROL_ACQUIIRE_HARD_DATA, 1) { - data()[0] = 0x01; +ControlAcquireHardData::ControlAcquireHardData() : ControlCommand( ControlCode::CONTROL_ACQUIIRE_HARD_DATA, 1 ) { + data()[ 0 ] = 0x01; } -ControlGetLimits::ControlGetLimits() - : ControlCommand( ControlCode::CONTROL_VALUE, sizeof( CalibrationValues ) ) { - value = uint8_t(ControlValue::VALUE_OFFSETLIMITS); - data()[0] = 0x01; +ControlGetLimits::ControlGetLimits() : ControlCommand( ControlCode::CONTROL_VALUE, sizeof( CalibrationValues ) ) { + value = uint8_t( ControlValue::VALUE_OFFSETLIMITS ); + data()[ 0 ] = 0x01; } -ControlSetCalFreq::ControlSetCalFreq() : ControlCommand(ControlCode::CONTROL_SETCALFREQ, 1) { +ControlSetCalFreq::ControlSetCalFreq() : ControlCommand( ControlCode::CONTROL_SETCALFREQ, 1 ) { this->setCalFreq( 1 ); // 1kHz } -void ControlSetCalFreq::setCalFreq(uint8_t val) { data()[0] = val; } +void ControlSetCalFreq::setCalFreq( uint8_t val ) { data()[ 0 ] = val; } -ControlSetCoupling::ControlSetCoupling() - : ControlCommand(ControlCode::CONTROL_SETCOUPLING, 1) - , ch1Coupling(0x01) - , ch2Coupling(0x10) { - data()[0] = 0x11; +ControlSetCoupling::ControlSetCoupling() + : ControlCommand( ControlCode::CONTROL_SETCOUPLING, 1 ), ch1Coupling( 0x01 ), ch2Coupling( 0x10 ) { + data()[ 0 ] = 0x11; } -void ControlSetCoupling::setCoupling(ChannelID channel, bool dc) { - if (channel == 0) +void ControlSetCoupling::setCoupling( ChannelID channel, bool dc ) { + if ( channel == 0 ) ch1Coupling = dc ? 0x01 : 0x00; else ch2Coupling = dc ? 0x10 : 0x00; - data()[0] = 0xFF & ( ch2Coupling | ch1Coupling ); + data()[ 0 ] = 0xFF & ( ch2Coupling | ch1Coupling ); } -} +} // namespace Hantek diff --git a/openhantek/src/hantekprotocol/controlStructs.h b/openhantek/src/hantekprotocol/controlStructs.h index 7141d6f1..5ccca8e3 100644 --- a/openhantek/src/hantekprotocol/controlStructs.h +++ b/openhantek/src/hantekprotocol/controlStructs.h @@ -39,27 +39,27 @@ class ControlGetSpeed : public ControlCommand { ControlGetSpeed(); /// \brief Gets the speed of the connection. /// \return The speed level of the USB connection. -// ConnectionSpeed getSpeed(); + // ConnectionSpeed getSpeed(); }; struct ControlSetVoltDIV_CH1 : public ControlCommand { ControlSetVoltDIV_CH1(); - void setDiv(uint8_t val); + void setDiv( uint8_t val ); }; struct ControlSetVoltDIV_CH2 : public ControlCommand { ControlSetVoltDIV_CH2(); - void setDiv(uint8_t val); + void setDiv( uint8_t val ); }; struct ControlSetTimeDIV : public ControlCommand { ControlSetTimeDIV(); - void setDiv(uint8_t val); + void setDiv( uint8_t val ); }; struct ControlSetNumChannels : public ControlCommand { ControlSetNumChannels(); - void setDiv(uint8_t val); + void setDiv( uint8_t val ); }; struct ControlAcquireHardData : public ControlCommand { @@ -72,13 +72,13 @@ struct ControlGetLimits : public ControlCommand { struct ControlSetCalFreq : public ControlCommand { ControlSetCalFreq(); - void setCalFreq(uint8_t val); + void setCalFreq( uint8_t val ); }; struct ControlSetCoupling : public ControlCommand { ControlSetCoupling(); - void setCoupling(ChannelID channel, bool dc); + void setCoupling( ChannelID channel, bool dc ); uint8_t ch1Coupling, ch2Coupling; }; -} +} // namespace Hantek diff --git a/openhantek/src/hantekprotocol/controlcode.h b/openhantek/src/hantekprotocol/controlcode.h index d2a903a1..11da1130 100644 --- a/openhantek/src/hantekprotocol/controlcode.h +++ b/openhantek/src/hantekprotocol/controlcode.h @@ -52,8 +52,9 @@ enum class ControlCode : uint8_t { CONTROL_SETTIMEDIV = 0xe2, CONTROL_ACQUIIRE_HARD_DATA = 0xe3, CONTROL_SETNUMCHANNELS = 0xe4, - CONTROL_SETCOUPLING = 0xe5, // DC/AC not possible without hw modification on Hantek 6022, but implemented on Sainsmart DS120 + CONTROL_SETCOUPLING = + 0xe5, // DC/AC not possible without hw modification on Hantek 6022, but implemented on Sainsmart DS120 CONTROL_SETCALFREQ = 0xe6 }; -} +} // namespace Hantek diff --git a/openhantek/src/hantekprotocol/controlcommand.cpp b/openhantek/src/hantekprotocol/controlcommand.cpp index 6db15533..66c77046 100644 --- a/openhantek/src/hantekprotocol/controlcommand.cpp +++ b/openhantek/src/hantekprotocol/controlcommand.cpp @@ -2,4 +2,5 @@ #include "controlcommand.h" -ControlCommand::ControlCommand(Hantek::ControlCode code, unsigned size): std::vector(size), code( uint8_t(code) ) {} +ControlCommand::ControlCommand( Hantek::ControlCode code, unsigned size ) + : std::vector( size ), code( uint8_t( code ) ) {} diff --git a/openhantek/src/hantekprotocol/controlcommand.h b/openhantek/src/hantekprotocol/controlcommand.h index e2d97f75..e73ae36a 100644 --- a/openhantek/src/hantekprotocol/controlcommand.h +++ b/openhantek/src/hantekprotocol/controlcommand.h @@ -10,11 +10,12 @@ enum class ControlCode : uint8_t; } class ControlCommand : public std::vector { -protected: - ControlCommand(Hantek::ControlCode code, unsigned size); -public: + protected: + ControlCommand( Hantek::ControlCode code, unsigned size ); + + public: bool pending = false; uint8_t code; uint8_t value = 0; - ControlCommand* next = nullptr; + ControlCommand *next = nullptr; }; diff --git a/openhantek/src/hantekprotocol/controlvalue.h b/openhantek/src/hantekprotocol/controlvalue.h index 4cc10300..5cad02f2 100644 --- a/openhantek/src/hantekprotocol/controlvalue.h +++ b/openhantek/src/hantekprotocol/controlvalue.h @@ -44,5 +44,4 @@ enum class ControlValue : uint8_t { VALUE_ETSCORRECTION = 0x70 }; -} - +} // namespace Hantek diff --git a/openhantek/src/hantekprotocol/definitions.h b/openhantek/src/hantekprotocol/definitions.h index bc7d8c5d..874cd07e 100644 --- a/openhantek/src/hantekprotocol/definitions.h +++ b/openhantek/src/hantekprotocol/definitions.h @@ -18,7 +18,7 @@ enum class UsedChannels : uint8_t { USED_CH1CH2, ///< Channel 1 and 2 are both activated }; -#pragma pack(push, 1) +#pragma pack( push, 1 ) // The strct reflects the offset layout in EEPROM // All values are offset binariy bytes (0 -> 0x80) @@ -46,6 +46,6 @@ struct CalibrationValues { Offsets fine; }; -#pragma pack(pop) +#pragma pack( pop ) -} +} // namespace Hantek diff --git a/openhantek/src/iconfont/QtAwesome.cpp b/openhantek/src/iconfont/QtAwesome.cpp index 75202cc4..5b5b3894 100644 --- a/openhantek/src/iconfont/QtAwesome.cpp +++ b/openhantek/src/iconfont/QtAwesome.cpp @@ -19,9 +19,9 @@ QtAwesome *iconFont = new QtAwesome(); /// The font-awesome icon painter class QtAwesomeCharIconPainter : public QtAwesomeIconPainter { protected: - QStringList optionKeysForModeAndState(const QString &key, QIcon::Mode mode, QIcon::State state) { + QStringList optionKeysForModeAndState( const QString &key, QIcon::Mode mode, QIcon::State state ) { QString modePostfix; - switch (mode) { + switch ( mode ) { case QIcon::Disabled: modePostfix = "-disabled"; break; @@ -36,57 +36,66 @@ class QtAwesomeCharIconPainter : public QtAwesomeIconPainter { } QString statePostfix; - if (state == QIcon::Off) { statePostfix = "-off"; } + if ( state == QIcon::Off ) { + statePostfix = "-off"; + } // the keys that need to bet tested: key-mode-state | key-mode | key-state | key QStringList result; - if (!modePostfix.isEmpty()) { - if (!statePostfix.isEmpty()) { result.push_back(key + modePostfix + statePostfix); } - result.push_back(key + modePostfix); + if ( !modePostfix.isEmpty() ) { + if ( !statePostfix.isEmpty() ) { + result.push_back( key + modePostfix + statePostfix ); + } + result.push_back( key + modePostfix ); + } + if ( !statePostfix.isEmpty() ) { + result.push_back( key + statePostfix ); } - if (!statePostfix.isEmpty()) { result.push_back(key + statePostfix); } return result; } - QVariant optionValueForModeAndState(const QString &baseKey, QIcon::Mode mode, QIcon::State state, - const QVariantMap &options) { - foreach (QString key, optionKeysForModeAndState(baseKey, mode, state)) { - if (options.contains(key)) return options.value(key); + QVariant optionValueForModeAndState( const QString &baseKey, QIcon::Mode mode, QIcon::State state, + const QVariantMap &options ) { + foreach ( QString key, optionKeysForModeAndState( baseKey, mode, state ) ) { + if ( options.contains( key ) ) + return options.value( key ); } - return options.value(baseKey); + return options.value( baseKey ); } public: - virtual void paint(QtAwesome *awesome, QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state, - const QVariantMap &options) { - Q_UNUSED(mode); - Q_UNUSED(state); - Q_UNUSED(options); + virtual void paint( QtAwesome *awesome, QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state, + const QVariantMap &options ) { + Q_UNUSED( mode ); + Q_UNUSED( state ); + Q_UNUSED( options ); painter->save(); // set the default options - QColor color = optionValueForModeAndState("color", mode, state, options).value(); - QString text = optionValueForModeAndState("text", mode, state, options).toString(); + QColor color = optionValueForModeAndState( "color", mode, state, options ).value(); + QString text = optionValueForModeAndState( "text", mode, state, options ).toString(); - if (text.isEmpty() || color.red()==0) { + if ( text.isEmpty() || color.red() == 0 ) { qWarning() << "empty for" << mode << state << options; } - painter->setPen(color); + painter->setPen( color ); // add some 'padding' around the icon - int drawSize = qRound(rect.height() * options.value("scale-factor").toFloat()); + int drawSize = qRound( rect.height() * options.value( "scale-factor" ).toFloat() ); - painter->setFont(awesome->font(drawSize)); - painter->drawText(rect, text, QTextOption(Qt::AlignCenter | Qt::AlignVCenter)); + painter->setFont( awesome->font( drawSize ) ); + painter->drawText( rect, text, QTextOption( Qt::AlignCenter | Qt::AlignVCenter ) ); painter->restore(); - QVariant var = options.value("anim"); + QVariant var = options.value( "anim" ); QtAwesomeAnimation *anim = var.value(); - if (anim) { anim->setup(*painter, rect); } + if ( anim ) { + anim->setup( *painter, rect ); + } } }; @@ -95,27 +104,27 @@ class QtAwesomeCharIconPainter : public QtAwesomeIconPainter { /// The painter icon engine. class QtAwesomeIconPainterIconEngine : public QIconEngine { public: - QtAwesomeIconPainterIconEngine(QtAwesome *awesome, QtAwesomeIconPainter *painter, const QVariantMap &options) - : awesomeRef_(awesome), iconPainterRef_(painter), options_(options) {} + QtAwesomeIconPainterIconEngine( QtAwesome *awesome, QtAwesomeIconPainter *painter, const QVariantMap &options ) + : awesomeRef_( awesome ), iconPainterRef_( painter ), options_( options ) {} ~QtAwesomeIconPainterIconEngine() override {} QtAwesomeIconPainterIconEngine *clone() const override { - return new QtAwesomeIconPainterIconEngine(awesomeRef_, iconPainterRef_, options_); + return new QtAwesomeIconPainterIconEngine( awesomeRef_, iconPainterRef_, options_ ); } - void paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state) override { - Q_UNUSED(mode); - Q_UNUSED(state); - iconPainterRef_->paint(awesomeRef_, painter, rect, mode, state, options_); + void paint( QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state ) override { + Q_UNUSED( mode ); + Q_UNUSED( state ); + iconPainterRef_->paint( awesomeRef_, painter, rect, mode, state, options_ ); } - QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) override { - QPixmap pm(size); - pm.fill(Qt::transparent); // we need transparency + QPixmap pixmap( const QSize &size, QIcon::Mode mode, QIcon::State state ) override { + QPixmap pm( size ); + pm.fill( Qt::transparent ); // we need transparency { - QPainter p(&pm); - paint(&p, QRect(QPoint(0, 0), size), mode, state); + QPainter p( &pm ); + paint( &p, QRect( QPoint( 0, 0 ), size ), mode, state ); } return pm; } @@ -137,14 +146,14 @@ class QtAwesomeIconPainterIconEngine : public QIconEngine { //--------------------------------------------------------------------------------------- /// The default icon colors -QtAwesome::QtAwesome(QObject *parent) : QObject(parent), namedCodepoints_() { +QtAwesome::QtAwesome( QObject *parent ) : QObject( parent ), namedCodepoints_() { // initialize the default options - setDefaultOption("color", QColor(50, 50, 50)); - setDefaultOption("color-off", QColor(50, 50, 50)); - setDefaultOption("color-disabled", QColor(70, 70, 70, 60)); - setDefaultOption("color-active", QColor(10, 10, 10)); - setDefaultOption("color-selected", QColor(10, 10, 10)); - setDefaultOption("scale-factor", 1.0); + setDefaultOption( "color", QColor( 50, 50, 50 ) ); + setDefaultOption( "color-off", QColor( 50, 50, 50 ) ); + setDefaultOption( "color-disabled", QColor( 70, 70, 70, 60 ) ); + setDefaultOption( "color-active", QColor( 10, 10, 10 ) ); + setDefaultOption( "color-selected", QColor( 10, 10, 10 ) ); + setDefaultOption( "scale-factor", 1.0 ); fontIconPainter_ = new QtAwesomeCharIconPainter(); } @@ -152,11 +161,11 @@ QtAwesome::QtAwesome(QObject *parent) : QObject(parent), namedCodepoints_() { QtAwesome::~QtAwesome() { delete fontIconPainter_; // delete errorIconPainter_; - qDeleteAll(painterMap_); + qDeleteAll( painterMap_ ); } /// initializes the QtAwesome icon factory with the given fontname -void QtAwesome::init(const QString &fontname) { fontName_ = fontname; } +void QtAwesome::init( const QString &fontname ) { fontName_ = fontname; } struct FANameIcon { const char *name; @@ -957,23 +966,23 @@ bool QtAwesome::initFontAwesome() { static int fontAwesomeFontId = -1; // only load font-awesome once - if (fontAwesomeFontId < 0) { + if ( fontAwesomeFontId < 0 ) { // load the font file - QFile res(":/images/fontawesome-4.7.0.ttf"); - if (!res.open(QIODevice::ReadOnly)) { + QFile res( ":/images/fontawesome-4.7.0.ttf" ); + if ( !res.open( QIODevice::ReadOnly ) ) { qDebug() << "Font awesome font could not be loaded!"; return false; } - QByteArray fontData(res.readAll()); + QByteArray fontData( res.readAll() ); res.close(); // fetch the given font - fontAwesomeFontId = QFontDatabase::addApplicationFontFromData(fontData); + fontAwesomeFontId = QFontDatabase::addApplicationFontFromData( fontData ); } - QStringList loadedFontFamilies = QFontDatabase::applicationFontFamilies(fontAwesomeFontId); - if (!loadedFontFamilies.empty()) { - fontName_ = loadedFontFamilies.at(0); + QStringList loadedFontFamilies = QFontDatabase::applicationFontFamilies( fontAwesomeFontId ); + if ( !loadedFontFamilies.empty() ) { + fontName_ = loadedFontFamilies.at( 0 ); } else { qDebug() << "Font awesome font is empty?!"; fontAwesomeFontId = -1; // restore the font-awesome id @@ -982,29 +991,31 @@ bool QtAwesome::initFontAwesome() { // intialize the map QHash &m = namedCodepoints_; - for (unsigned i = 0; i < sizeof(faNameIconArray) / sizeof(FANameIcon); ++i) { - m.insert(faNameIconArray[i].name, faNameIconArray[i].icon); + for ( unsigned i = 0; i < sizeof( faNameIconArray ) / sizeof( FANameIcon ); ++i ) { + m.insert( faNameIconArray[ i ].name, faNameIconArray[ i ].icon ); } return true; } -void QtAwesome::addNamedCodepoint(const QString &name, int codePoint) { namedCodepoints_.insert(name, codePoint); } +void QtAwesome::addNamedCodepoint( const QString &name, int codePoint ) { namedCodepoints_.insert( name, codePoint ); } /// Sets a default option. These options are passed on to the icon painters -void QtAwesome::setDefaultOption(const QString &name, const QVariant &value) { defaultOptions_.insert(name, value); } +void QtAwesome::setDefaultOption( const QString &name, const QVariant &value ) { + defaultOptions_.insert( name, value ); +} /// Returns the default option for the given name -QVariant QtAwesome::defaultOption(const QString &name) { return defaultOptions_.value(name); } +QVariant QtAwesome::defaultOption( const QString &name ) { return defaultOptions_.value( name ); } // internal helper method to merge to option amps -static QVariantMap mergeOptions(const QVariantMap &defaults, const QVariantMap &override) { +static QVariantMap mergeOptions( const QVariantMap &defaults, const QVariantMap &override ) { QVariantMap result = defaults; - if (!override.isEmpty()) { - QMapIterator itr(override); - while (itr.hasNext()) { + if ( !override.isEmpty() ) { + QMapIterator itr( override ); + while ( itr.hasNext() ) { itr.next(); - result.insert(itr.key(), itr.value()); + result.insert( itr.key(), itr.value() ); } } return result; @@ -1014,16 +1025,21 @@ static QVariantMap mergeOptions(const QVariantMap &defaults, const QVariantMap & /// /// awesome->icon( icon_group ) /// -QIcon QtAwesome::icon(int character, const QVariantMap &options) { +QIcon QtAwesome::icon( int character, const QVariantMap &options ) { // create a merged QVariantMap to have default options and icon-specific options - QVariantMap optionMap = mergeOptions(defaultOptions_, options); - if (!optionMap.contains("text")) optionMap.insert("text", QChar(character)); - if (!optionMap.contains("text-active")) optionMap.insert("text-active", QChar(character)); - if (!optionMap.contains("text-selected")) optionMap.insert("text-selected", QChar(character)); - if (!optionMap.contains("text-disabled")) optionMap.insert("text-disabled", QChar(character)); - if (!optionMap.contains("text-off")) optionMap.insert("text-off", QChar(character)); + QVariantMap optionMap = mergeOptions( defaultOptions_, options ); + if ( !optionMap.contains( "text" ) ) + optionMap.insert( "text", QChar( character ) ); + if ( !optionMap.contains( "text-active" ) ) + optionMap.insert( "text-active", QChar( character ) ); + if ( !optionMap.contains( "text-selected" ) ) + optionMap.insert( "text-selected", QChar( character ) ); + if ( !optionMap.contains( "text-disabled" ) ) + optionMap.insert( "text-disabled", QChar( character ) ); + if ( !optionMap.contains( "text-off" ) ) + optionMap.insert( "text-off", QChar( character ) ); - return icon(fontIconPainter_, optionMap); + return icon( fontIconPainter_, optionMap ); } /// Creates an icon with the given name @@ -1032,30 +1048,34 @@ QIcon QtAwesome::icon(int character, const QVariantMap &options) { /// prefix /// @param name the name of the icon /// @param options extra option to pass to the icon renderer -QIcon QtAwesome::icon(const QString &name, const QVariantMap &options) { +QIcon QtAwesome::icon( const QString &name, const QVariantMap &options ) { // when it's a named codepoint - if (namedCodepoints_.count(name)) { return icon(namedCodepoints_.value(name), options); } + if ( namedCodepoints_.count( name ) ) { + return icon( namedCodepoints_.value( name ), options ); + } // create a merged QVariantMap to have default options and icon-specific options - QVariantMap optionMap = mergeOptions(defaultOptions_, options); + QVariantMap optionMap = mergeOptions( defaultOptions_, options ); // this method first tries to retrieve the icon - QtAwesomeIconPainter *painter = painterMap_.value(name); - if (!painter) { return QIcon(); } + QtAwesomeIconPainter *painter = painterMap_.value( name ); + if ( !painter ) { + return QIcon(); + } - return icon(painter, optionMap); + return icon( painter, optionMap ); } /// Create a dynamic icon by simlpy supplying a painter object /// The ownership of the painter is NOT transfered. /// @param painter a dynamic painter that is going to paint the icon /// @param optionmap the options to pass to the painter -QIcon QtAwesome::icon(QtAwesomeIconPainter *painter, const QVariantMap &optionMap) { +QIcon QtAwesome::icon( QtAwesomeIconPainter *painter, const QVariantMap &optionMap ) { // Warning, when you use memoryleak detection. You should turn it of for the next call // QIcon's placed in gui items are often cached and not deleted when my memory-leak detection checks for leaks. // I'm not sure if it's a Qt bug or something I do wrong - QtAwesomeIconPainterIconEngine *engine = new QtAwesomeIconPainterIconEngine(this, painter, optionMap); - return QIcon(engine); + QtAwesomeIconPainterIconEngine *engine = new QtAwesomeIconPainterIconEngine( this, painter, optionMap ); + return QIcon( engine ); } /// Adds a named icon-painter to the QtAwesome icon map @@ -1063,9 +1083,9 @@ QIcon QtAwesome::icon(QtAwesomeIconPainter *painter, const QVariantMap &optionMa /// /// @param name the name of the icon /// @param painter the icon painter to add for this name -void QtAwesome::give(const QString &name, QtAwesomeIconPainter *painter) { - delete painterMap_.value(name); // delete the old one - painterMap_.insert(name, painter); +void QtAwesome::give( const QString &name, QtAwesomeIconPainter *painter ) { + delete painterMap_.value( name ); // delete the old one + painterMap_.insert( name, painter ); } /// Creates/Gets the icon font with a given size in pixels. This can be usefull to use a label for displaying icons @@ -1073,8 +1093,8 @@ void QtAwesome::give(const QString &name, QtAwesomeIconPainter *painter) { /// /// QLabel* label = new QLabel( QChar( icon_group ) ); /// label->setFont( awesome->font(16) ) -QFont QtAwesome::font(int size) { - QFont font(fontName_); - font.setPixelSize(size); +QFont QtAwesome::font( int size ) { + QFont font( fontName_ ); + font.setPixelSize( size ); return font; } diff --git a/openhantek/src/iconfont/QtAwesome.h b/openhantek/src/iconfont/QtAwesome.h index 902652c8..0a909850 100644 --- a/openhantek/src/iconfont/QtAwesome.h +++ b/openhantek/src/iconfont/QtAwesome.h @@ -22,839 +22,838 @@ /// A list of all icon-names with the codepoint (unicode-value) on the right /// You can use the names on the page http://fortawesome.github.io/Font-Awesome/design.html namespace fa { - enum icon { - fa_500px = 0xf26e, - addressbook = 0xf2b9, - addressbooko = 0xf2ba, - addresscard = 0xf2bb, - addresscardo = 0xf2bc, - adjust = 0xf042, - adn = 0xf170, - aligncenter = 0xf037, - alignjustify = 0xf039, - alignleft = 0xf036, - alignright = 0xf038, - amazon = 0xf270, - ambulance = 0xf0f9, - americansignlanguageinterpreting = 0xf2a3, - anchor = 0xf13d, - android = 0xf17b, - angellist = 0xf209, - angledoubledown = 0xf103, - angledoubleleft = 0xf100, - angledoubleright = 0xf101, - angledoubleup = 0xf102, - angledown = 0xf107, - angleleft = 0xf104, - angleright = 0xf105, - angleup = 0xf106, - apple = 0xf179, - archive = 0xf187, - areachart = 0xf1fe, - arrowcircledown = 0xf0ab, - arrowcircleleft = 0xf0a8, - arrowcircleodown = 0xf01a, - arrowcircleoleft = 0xf190, - arrowcircleoright = 0xf18e, - arrowcircleoup = 0xf01b, - arrowcircleright = 0xf0a9, - arrowcircleup = 0xf0aa, - arrowdown = 0xf063, - arrowleft = 0xf060, - arrowright = 0xf061, - arrowup = 0xf062, - arrows = 0xf047, - arrowsalt = 0xf0b2, - arrowsh = 0xf07e, - arrowsv = 0xf07d, - aslinterpreting = 0xf2a3, - assistivelisteningsystems = 0xf2a2, - asterisk = 0xf069, - at = 0xf1fa, - audiodescription = 0xf29e, - automobile = 0xf1b9, - backward = 0xf04a, - balancescale = 0xf24e, - ban = 0xf05e, - bandcamp = 0xf2d5, - bank = 0xf19c, - barchart = 0xf080, - barcharto = 0xf080, - barcode = 0xf02a, - bars = 0xf0c9, - bath = 0xf2cd, - bathtub = 0xf2cd, - battery = 0xf240, - battery0 = 0xf244, - battery1 = 0xf243, - battery2 = 0xf242, - battery3 = 0xf241, - battery4 = 0xf240, - batteryempty = 0xf244, - batteryfull = 0xf240, - batteryhalf = 0xf242, - batteryquarter = 0xf243, - batterythreequarters = 0xf241, - bed = 0xf236, - beer = 0xf0fc, - behance = 0xf1b4, - behancesquare = 0xf1b5, - bell = 0xf0f3, - bello = 0xf0a2, - bellslash = 0xf1f6, - bellslasho = 0xf1f7, - bicycle = 0xf206, - binoculars = 0xf1e5, - birthdaycake = 0xf1fd, - bitbucket = 0xf171, - bitbucketsquare = 0xf172, - bitcoin = 0xf15a, - blacktie = 0xf27e, - blind = 0xf29d, - bluetooth = 0xf293, - bluetoothb = 0xf294, - bold = 0xf032, - bolt = 0xf0e7, - bomb = 0xf1e2, - book = 0xf02d, - bookmark = 0xf02e, - bookmarko = 0xf097, - braille = 0xf2a1, - briefcase = 0xf0b1, - btc = 0xf15a, - bug = 0xf188, - building = 0xf1ad, - buildingo = 0xf0f7, - bullhorn = 0xf0a1, - bullseye = 0xf140, - bus = 0xf207, - buysellads = 0xf20d, - cab = 0xf1ba, - calculator = 0xf1ec, - calendar = 0xf073, - calendarchecko = 0xf274, - calendarminuso = 0xf272, - calendaro = 0xf133, - calendarpluso = 0xf271, - calendartimeso = 0xf273, - camera = 0xf030, - cameraretro = 0xf083, - car = 0xf1b9, - caretdown = 0xf0d7, - caretleft = 0xf0d9, - caretright = 0xf0da, - caretsquareodown = 0xf150, - caretsquareoleft = 0xf191, - caretsquareoright = 0xf152, - caretsquareoup = 0xf151, - caretup = 0xf0d8, - cartarrowdown = 0xf218, - cartplus = 0xf217, - cc = 0xf20a, - ccamex = 0xf1f3, - ccdinersclub = 0xf24c, - ccdiscover = 0xf1f2, - ccjcb = 0xf24b, - ccmastercard = 0xf1f1, - ccpaypal = 0xf1f4, - ccstripe = 0xf1f5, - ccvisa = 0xf1f0, - certificate = 0xf0a3, - chain = 0xf0c1, - chainbroken = 0xf127, - check = 0xf00c, - checkcircle = 0xf058, - checkcircleo = 0xf05d, - checksquare = 0xf14a, - checksquareo = 0xf046, - chevroncircledown = 0xf13a, - chevroncircleleft = 0xf137, - chevroncircleright = 0xf138, - chevroncircleup = 0xf139, - chevrondown = 0xf078, - chevronleft = 0xf053, - chevronright = 0xf054, - chevronup = 0xf077, - child = 0xf1ae, - chrome = 0xf268, - circle = 0xf111, - circleo = 0xf10c, - circleonotch = 0xf1ce, - circlethin = 0xf1db, - clipboard = 0xf0ea, - clocko = 0xf017, - clone = 0xf24d, - close = 0xf00d, - cloud = 0xf0c2, - clouddownload = 0xf0ed, - cloudupload = 0xf0ee, - cny = 0xf157, - code = 0xf121, - codefork = 0xf126, - codepen = 0xf1cb, - codiepie = 0xf284, - coffee = 0xf0f4, - cog = 0xf013, - cogs = 0xf085, - columns = 0xf0db, - comment = 0xf075, - commento = 0xf0e5, - commenting = 0xf27a, - commentingo = 0xf27b, - comments = 0xf086, - commentso = 0xf0e6, - compass = 0xf14e, - compress = 0xf066, - connectdevelop = 0xf20e, - contao = 0xf26d, - copy = 0xf0c5, - copyright = 0xf1f9, - creativecommons = 0xf25e, - creditcard = 0xf09d, - creditcardalt = 0xf283, - crop = 0xf125, - crosshairs = 0xf05b, - css3 = 0xf13c, - cube = 0xf1b2, - cubes = 0xf1b3, - cut = 0xf0c4, - cutlery = 0xf0f5, - dashboard = 0xf0e4, - dashcube = 0xf210, - database = 0xf1c0, - deaf = 0xf2a4, - deafness = 0xf2a4, - dedent = 0xf03b, - delicious = 0xf1a5, - desktop = 0xf108, - deviantart = 0xf1bd, - diamond = 0xf219, - digg = 0xf1a6, - dollar = 0xf155, - dotcircleo = 0xf192, - download = 0xf019, - dribbble = 0xf17d, - driverslicense = 0xf2c2, - driverslicenseo = 0xf2c3, - dropbox = 0xf16b, - drupal = 0xf1a9, - edge = 0xf282, - edit = 0xf044, - eercast = 0xf2da, - eject = 0xf052, - ellipsish = 0xf141, - ellipsisv = 0xf142, - empire = 0xf1d1, - envelope = 0xf0e0, - envelopeo = 0xf003, - envelopeopen = 0xf2b6, - envelopeopeno = 0xf2b7, - envelopesquare = 0xf199, - envira = 0xf299, - eraser = 0xf12d, - etsy = 0xf2d7, - eur = 0xf153, - euro = 0xf153, - exchange = 0xf0ec, - exclamation = 0xf12a, - exclamationcircle = 0xf06a, - exclamationtriangle = 0xf071, - expand = 0xf065, - expeditedssl = 0xf23e, - externallink = 0xf08e, - externallinksquare = 0xf14c, - eye = 0xf06e, - eyeslash = 0xf070, - eyedropper = 0xf1fb, - fa = 0xf2b4, - facebook = 0xf09a, - facebookf = 0xf09a, - facebookofficial = 0xf230, - facebooksquare = 0xf082, - fastbackward = 0xf049, - fastforward = 0xf050, - fax = 0xf1ac, - feed = 0xf09e, - female = 0xf182, - fighterjet = 0xf0fb, - file = 0xf15b, - filearchiveo = 0xf1c6, - fileaudioo = 0xf1c7, - filecodeo = 0xf1c9, - fileexcelo = 0xf1c3, - fileimageo = 0xf1c5, - filemovieo = 0xf1c8, - fileo = 0xf016, - filepdfo = 0xf1c1, - filephotoo = 0xf1c5, - filepictureo = 0xf1c5, - filepowerpointo = 0xf1c4, - filesoundo = 0xf1c7, - filetext = 0xf15c, - filetexto = 0xf0f6, - filevideoo = 0xf1c8, - filewordo = 0xf1c2, - filezipo = 0xf1c6, - fileso = 0xf0c5, - film = 0xf008, - filter = 0xf0b0, - fire = 0xf06d, - fireextinguisher = 0xf134, - firefox = 0xf269, - firstorder = 0xf2b0, - flag = 0xf024, - flagcheckered = 0xf11e, - flago = 0xf11d, - flash = 0xf0e7, - flask = 0xf0c3, - flickr = 0xf16e, - floppyo = 0xf0c7, - folder = 0xf07b, - foldero = 0xf114, - folderopen = 0xf07c, - folderopeno = 0xf115, - font = 0xf031, - fontawesome = 0xf2b4, - fonticons = 0xf280, - fortawesome = 0xf286, - forumbee = 0xf211, - forward = 0xf04e, - foursquare = 0xf180, - freecodecamp = 0xf2c5, - frowno = 0xf119, - futbolo = 0xf1e3, - gamepad = 0xf11b, - gavel = 0xf0e3, - gbp = 0xf154, - ge = 0xf1d1, - gear = 0xf013, - gears = 0xf085, - genderless = 0xf22d, - getpocket = 0xf265, - gg = 0xf260, - ggcircle = 0xf261, - gift = 0xf06b, - git = 0xf1d3, - gitsquare = 0xf1d2, - github = 0xf09b, - githubalt = 0xf113, - githubsquare = 0xf092, - gitlab = 0xf296, - gittip = 0xf184, - glass = 0xf000, - glide = 0xf2a5, - glideg = 0xf2a6, - globe = 0xf0ac, - google = 0xf1a0, - googleplus = 0xf0d5, - googlepluscircle = 0xf2b3, - googleplusofficial = 0xf2b3, - googleplussquare = 0xf0d4, - googlewallet = 0xf1ee, - graduationcap = 0xf19d, - gratipay = 0xf184, - grav = 0xf2d6, - group = 0xf0c0, - hsquare = 0xf0fd, - hackernews = 0xf1d4, - handgrabo = 0xf255, - handlizardo = 0xf258, - handodown = 0xf0a7, - handoleft = 0xf0a5, - handoright = 0xf0a4, - handoup = 0xf0a6, - handpapero = 0xf256, - handpeaceo = 0xf25b, - handpointero = 0xf25a, - handrocko = 0xf255, - handscissorso = 0xf257, - handspocko = 0xf259, - handstopo = 0xf256, - handshakeo = 0xf2b5, - hardofhearing = 0xf2a4, - hashtag = 0xf292, - hddo = 0xf0a0, - header = 0xf1dc, - headphones = 0xf025, - heart = 0xf004, - hearto = 0xf08a, - heartbeat = 0xf21e, - history = 0xf1da, - home = 0xf015, - hospitalo = 0xf0f8, - hotel = 0xf236, - hourglass = 0xf254, - hourglass1 = 0xf251, - hourglass2 = 0xf252, - hourglass3 = 0xf253, - hourglassend = 0xf253, - hourglasshalf = 0xf252, - hourglasso = 0xf250, - hourglassstart = 0xf251, - houzz = 0xf27c, - html5 = 0xf13b, - icursor = 0xf246, - idbadge = 0xf2c1, - idcard = 0xf2c2, - idcardo = 0xf2c3, - ils = 0xf20b, - image = 0xf03e, - imdb = 0xf2d8, - inbox = 0xf01c, - indent = 0xf03c, - industry = 0xf275, - info = 0xf129, - infocircle = 0xf05a, - inr = 0xf156, - instagram = 0xf16d, - institution = 0xf19c, - internetexplorer = 0xf26b, - intersex = 0xf224, - ioxhost = 0xf208, - italic = 0xf033, - joomla = 0xf1aa, - jpy = 0xf157, - jsfiddle = 0xf1cc, - key = 0xf084, - keyboardo = 0xf11c, - krw = 0xf159, - language = 0xf1ab, - laptop = 0xf109, - lastfm = 0xf202, - lastfmsquare = 0xf203, - leaf = 0xf06c, - leanpub = 0xf212, - legal = 0xf0e3, - lemono = 0xf094, - leveldown = 0xf149, - levelup = 0xf148, - lifebouy = 0xf1cd, - lifebuoy = 0xf1cd, - lifering = 0xf1cd, - lifesaver = 0xf1cd, - lightbulbo = 0xf0eb, - linechart = 0xf201, - link = 0xf0c1, - linkedin = 0xf0e1, - linkedinsquare = 0xf08c, - linode = 0xf2b8, - fa_linux = 0xf17c, - list = 0xf03a, - listalt = 0xf022, - listol = 0xf0cb, - listul = 0xf0ca, - locationarrow = 0xf124, - lock = 0xf023, - longarrowdown = 0xf175, - longarrowleft = 0xf177, - longarrowright = 0xf178, - longarrowup = 0xf176, - lowvision = 0xf2a8, - magic = 0xf0d0, - magnet = 0xf076, - mailforward = 0xf064, - mailreply = 0xf112, - mailreplyall = 0xf122, - male = 0xf183, - map = 0xf279, - mapmarker = 0xf041, - mapo = 0xf278, - mappin = 0xf276, - mapsigns = 0xf277, - mars = 0xf222, - marsdouble = 0xf227, - marsstroke = 0xf229, - marsstrokeh = 0xf22b, - marsstrokev = 0xf22a, - maxcdn = 0xf136, - meanpath = 0xf20c, - medium = 0xf23a, - medkit = 0xf0fa, - meetup = 0xf2e0, - meho = 0xf11a, - mercury = 0xf223, - microchip = 0xf2db, - microphone = 0xf130, - microphoneslash = 0xf131, - minus = 0xf068, - minuscircle = 0xf056, - minussquare = 0xf146, - minussquareo = 0xf147, - mixcloud = 0xf289, - mobile = 0xf10b, - mobilephone = 0xf10b, - modx = 0xf285, - money = 0xf0d6, - moono = 0xf186, - mortarboard = 0xf19d, - motorcycle = 0xf21c, - mousepointer = 0xf245, - music = 0xf001, - navicon = 0xf0c9, - neuter = 0xf22c, - newspapero = 0xf1ea, - objectgroup = 0xf247, - objectungroup = 0xf248, - odnoklassniki = 0xf263, - odnoklassnikisquare = 0xf264, - opencart = 0xf23d, - openid = 0xf19b, - opera = 0xf26a, - optinmonster = 0xf23c, - outdent = 0xf03b, - pagelines = 0xf18c, - paintbrush = 0xf1fc, - paperplane = 0xf1d8, - paperplaneo = 0xf1d9, - paperclip = 0xf0c6, - paragraph = 0xf1dd, - paste = 0xf0ea, - pause = 0xf04c, - pausecircle = 0xf28b, - pausecircleo = 0xf28c, - paw = 0xf1b0, - paypal = 0xf1ed, - pencil = 0xf040, - pencilsquare = 0xf14b, - pencilsquareo = 0xf044, - percent = 0xf295, - phone = 0xf095, - phonesquare = 0xf098, - photo = 0xf03e, - pictureo = 0xf03e, - piechart = 0xf200, - piedpiper = 0xf2ae, - piedpiperalt = 0xf1a8, - piedpiperpp = 0xf1a7, - pinterest = 0xf0d2, - pinterestp = 0xf231, - pinterestsquare = 0xf0d3, - plane = 0xf072, - play = 0xf04b, - playcircle = 0xf144, - playcircleo = 0xf01d, - plug = 0xf1e6, - plus = 0xf067, - pluscircle = 0xf055, - plussquare = 0xf0fe, - plussquareo = 0xf196, - podcast = 0xf2ce, - poweroff = 0xf011, - print = 0xf02f, - producthunt = 0xf288, - puzzlepiece = 0xf12e, - qq = 0xf1d6, - qrcode = 0xf029, - question = 0xf128, - questioncircle = 0xf059, - questioncircleo = 0xf29c, - quora = 0xf2c4, - quoteleft = 0xf10d, - quoteright = 0xf10e, - ra = 0xf1d0, - random = 0xf074, - ravelry = 0xf2d9, - rebel = 0xf1d0, - recycle = 0xf1b8, - reddit = 0xf1a1, - redditalien = 0xf281, - redditsquare = 0xf1a2, - refresh = 0xf021, - registered = 0xf25d, - remove = 0xf00d, - renren = 0xf18b, - reorder = 0xf0c9, - repeat = 0xf01e, - reply = 0xf112, - replyall = 0xf122, - resistance = 0xf1d0, - retweet = 0xf079, - rmb = 0xf157, - road = 0xf018, - rocket = 0xf135, - rotateleft = 0xf0e2, - rotateright = 0xf01e, - rouble = 0xf158, - rss = 0xf09e, - rsssquare = 0xf143, - rub = 0xf158, - ruble = 0xf158, - rupee = 0xf156, - s15 = 0xf2cd, - safari = 0xf267, - save = 0xf0c7, - scissors = 0xf0c4, - scribd = 0xf28a, - search = 0xf002, - searchminus = 0xf010, - searchplus = 0xf00e, - sellsy = 0xf213, - send = 0xf1d8, - sendo = 0xf1d9, - server = 0xf233, - share = 0xf064, - sharealt = 0xf1e0, - sharealtsquare = 0xf1e1, - sharesquare = 0xf14d, - sharesquareo = 0xf045, - shekel = 0xf20b, - sheqel = 0xf20b, - shield = 0xf132, - ship = 0xf21a, - shirtsinbulk = 0xf214, - shoppingbag = 0xf290, - shoppingbasket = 0xf291, - shoppingcart = 0xf07a, - shower = 0xf2cc, - signin = 0xf090, - signlanguage = 0xf2a7, - signout = 0xf08b, - signal = 0xf012, - signing = 0xf2a7, - simplybuilt = 0xf215, - sitemap = 0xf0e8, - skyatlas = 0xf216, - skype = 0xf17e, - slack = 0xf198, - sliders = 0xf1de, - slideshare = 0xf1e7, - smileo = 0xf118, - snapchat = 0xf2ab, - snapchatghost = 0xf2ac, - snapchatsquare = 0xf2ad, - snowflakeo = 0xf2dc, - soccerballo = 0xf1e3, - sort = 0xf0dc, - sortalphaasc = 0xf15d, - sortalphadesc = 0xf15e, - sortamountasc = 0xf160, - sortamountdesc = 0xf161, - sortasc = 0xf0de, - sortdesc = 0xf0dd, - sortdown = 0xf0dd, - sortnumericasc = 0xf162, - sortnumericdesc = 0xf163, - sortup = 0xf0de, - soundcloud = 0xf1be, - spaceshuttle = 0xf197, - spinner = 0xf110, - spoon = 0xf1b1, - spotify = 0xf1bc, - square = 0xf0c8, - squareo = 0xf096, - stackexchange = 0xf18d, - stackoverflow = 0xf16c, - star = 0xf005, - starhalf = 0xf089, - starhalfempty = 0xf123, - starhalffull = 0xf123, - starhalfo = 0xf123, - staro = 0xf006, - steam = 0xf1b6, - steamsquare = 0xf1b7, - stepbackward = 0xf048, - stepforward = 0xf051, - stethoscope = 0xf0f1, - stickynote = 0xf249, - stickynoteo = 0xf24a, - stop = 0xf04d, - stopcircle = 0xf28d, - stopcircleo = 0xf28e, - streetview = 0xf21d, - strikethrough = 0xf0cc, - stumbleupon = 0xf1a4, - stumbleuponcircle = 0xf1a3, - subscript = 0xf12c, - subway = 0xf239, - suitcase = 0xf0f2, - suno = 0xf185, - superpowers = 0xf2dd, - superscript = 0xf12b, - support = 0xf1cd, - table = 0xf0ce, - tablet = 0xf10a, - tachometer = 0xf0e4, - tag = 0xf02b, - tags = 0xf02c, - tasks = 0xf0ae, - taxi = 0xf1ba, - telegram = 0xf2c6, - television = 0xf26c, - tencentweibo = 0xf1d5, - terminal = 0xf120, - textheight = 0xf034, - textwidth = 0xf035, - th = 0xf00a, - thlarge = 0xf009, - thlist = 0xf00b, - themeisle = 0xf2b2, - thermometer = 0xf2c7, - thermometer0 = 0xf2cb, - thermometer1 = 0xf2ca, - thermometer2 = 0xf2c9, - thermometer3 = 0xf2c8, - thermometer4 = 0xf2c7, - thermometerempty = 0xf2cb, - thermometerfull = 0xf2c7, - thermometerhalf = 0xf2c9, - thermometerquarter = 0xf2ca, - thermometerthreequarters = 0xf2c8, - thumbtack = 0xf08d, - thumbsdown = 0xf165, - thumbsodown = 0xf088, - thumbsoup = 0xf087, - thumbsup = 0xf164, - ticket = 0xf145, - times = 0xf00d, - timescircle = 0xf057, - timescircleo = 0xf05c, - timesrectangle = 0xf2d3, - timesrectangleo = 0xf2d4, - tint = 0xf043, - toggledown = 0xf150, - toggleleft = 0xf191, - toggleoff = 0xf204, - toggleon = 0xf205, - toggleright = 0xf152, - toggleup = 0xf151, - trademark = 0xf25c, - train = 0xf238, - transgender = 0xf224, - transgenderalt = 0xf225, - trash = 0xf1f8, - trasho = 0xf014, - tree = 0xf1bb, - trello = 0xf181, - tripadvisor = 0xf262, - trophy = 0xf091, - truck = 0xf0d1, - fa_try = 0xf195, - tty = 0xf1e4, - tumblr = 0xf173, - tumblrsquare = 0xf174, - turkishlira = 0xf195, - tv = 0xf26c, - twitch = 0xf1e8, - twitter = 0xf099, - twittersquare = 0xf081, - umbrella = 0xf0e9, - underline = 0xf0cd, - undo = 0xf0e2, - universalaccess = 0xf29a, - university = 0xf19c, - unlink = 0xf127, - unlock = 0xf09c, - unlockalt = 0xf13e, - unsorted = 0xf0dc, - upload = 0xf093, - usb = 0xf287, - usd = 0xf155, - user = 0xf007, - usercircle = 0xf2bd, - usercircleo = 0xf2be, - usermd = 0xf0f0, - usero = 0xf2c0, - userplus = 0xf234, - usersecret = 0xf21b, - usertimes = 0xf235, - users = 0xf0c0, - vcard = 0xf2bb, - vcardo = 0xf2bc, - venus = 0xf221, - venusdouble = 0xf226, - venusmars = 0xf228, - viacoin = 0xf237, - viadeo = 0xf2a9, - viadeosquare = 0xf2aa, - videocamera = 0xf03d, - vimeo = 0xf27d, - vimeosquare = 0xf194, - vine = 0xf1ca, - vk = 0xf189, - volumecontrolphone = 0xf2a0, - volumedown = 0xf027, - volumeoff = 0xf026, - volumeup = 0xf028, - warning = 0xf071, - wechat = 0xf1d7, - weibo = 0xf18a, - weixin = 0xf1d7, - whatsapp = 0xf232, - wheelchair = 0xf193, - wheelchairalt = 0xf29b, - wifi = 0xf1eb, - wikipediaw = 0xf266, - windowclose = 0xf2d3, - windowcloseo = 0xf2d4, - windowmaximize = 0xf2d0, - windowminimize = 0xf2d1, - windowrestore = 0xf2d2, - windows = 0xf17a, - won = 0xf159, - wordpress = 0xf19a, - wpbeginner = 0xf297, - wpexplorer = 0xf2de, - wpforms = 0xf298, - wrench = 0xf0ad, - xing = 0xf168, - xingsquare = 0xf169, - ycombinator = 0xf23b, - ycombinatorsquare = 0xf1d4, - yahoo = 0xf19e, - yc = 0xf23b, - ycsquare = 0xf1d4, - yelp = 0xf1e9, - yen = 0xf157, - yoast = 0xf2b1, - youtube = 0xf167, - youtubeplay = 0xf16a, - youtubesquare = 0xf166 - }; +enum icon { + fa_500px = 0xf26e, + addressbook = 0xf2b9, + addressbooko = 0xf2ba, + addresscard = 0xf2bb, + addresscardo = 0xf2bc, + adjust = 0xf042, + adn = 0xf170, + aligncenter = 0xf037, + alignjustify = 0xf039, + alignleft = 0xf036, + alignright = 0xf038, + amazon = 0xf270, + ambulance = 0xf0f9, + americansignlanguageinterpreting = 0xf2a3, + anchor = 0xf13d, + android = 0xf17b, + angellist = 0xf209, + angledoubledown = 0xf103, + angledoubleleft = 0xf100, + angledoubleright = 0xf101, + angledoubleup = 0xf102, + angledown = 0xf107, + angleleft = 0xf104, + angleright = 0xf105, + angleup = 0xf106, + apple = 0xf179, + archive = 0xf187, + areachart = 0xf1fe, + arrowcircledown = 0xf0ab, + arrowcircleleft = 0xf0a8, + arrowcircleodown = 0xf01a, + arrowcircleoleft = 0xf190, + arrowcircleoright = 0xf18e, + arrowcircleoup = 0xf01b, + arrowcircleright = 0xf0a9, + arrowcircleup = 0xf0aa, + arrowdown = 0xf063, + arrowleft = 0xf060, + arrowright = 0xf061, + arrowup = 0xf062, + arrows = 0xf047, + arrowsalt = 0xf0b2, + arrowsh = 0xf07e, + arrowsv = 0xf07d, + aslinterpreting = 0xf2a3, + assistivelisteningsystems = 0xf2a2, + asterisk = 0xf069, + at = 0xf1fa, + audiodescription = 0xf29e, + automobile = 0xf1b9, + backward = 0xf04a, + balancescale = 0xf24e, + ban = 0xf05e, + bandcamp = 0xf2d5, + bank = 0xf19c, + barchart = 0xf080, + barcharto = 0xf080, + barcode = 0xf02a, + bars = 0xf0c9, + bath = 0xf2cd, + bathtub = 0xf2cd, + battery = 0xf240, + battery0 = 0xf244, + battery1 = 0xf243, + battery2 = 0xf242, + battery3 = 0xf241, + battery4 = 0xf240, + batteryempty = 0xf244, + batteryfull = 0xf240, + batteryhalf = 0xf242, + batteryquarter = 0xf243, + batterythreequarters = 0xf241, + bed = 0xf236, + beer = 0xf0fc, + behance = 0xf1b4, + behancesquare = 0xf1b5, + bell = 0xf0f3, + bello = 0xf0a2, + bellslash = 0xf1f6, + bellslasho = 0xf1f7, + bicycle = 0xf206, + binoculars = 0xf1e5, + birthdaycake = 0xf1fd, + bitbucket = 0xf171, + bitbucketsquare = 0xf172, + bitcoin = 0xf15a, + blacktie = 0xf27e, + blind = 0xf29d, + bluetooth = 0xf293, + bluetoothb = 0xf294, + bold = 0xf032, + bolt = 0xf0e7, + bomb = 0xf1e2, + book = 0xf02d, + bookmark = 0xf02e, + bookmarko = 0xf097, + braille = 0xf2a1, + briefcase = 0xf0b1, + btc = 0xf15a, + bug = 0xf188, + building = 0xf1ad, + buildingo = 0xf0f7, + bullhorn = 0xf0a1, + bullseye = 0xf140, + bus = 0xf207, + buysellads = 0xf20d, + cab = 0xf1ba, + calculator = 0xf1ec, + calendar = 0xf073, + calendarchecko = 0xf274, + calendarminuso = 0xf272, + calendaro = 0xf133, + calendarpluso = 0xf271, + calendartimeso = 0xf273, + camera = 0xf030, + cameraretro = 0xf083, + car = 0xf1b9, + caretdown = 0xf0d7, + caretleft = 0xf0d9, + caretright = 0xf0da, + caretsquareodown = 0xf150, + caretsquareoleft = 0xf191, + caretsquareoright = 0xf152, + caretsquareoup = 0xf151, + caretup = 0xf0d8, + cartarrowdown = 0xf218, + cartplus = 0xf217, + cc = 0xf20a, + ccamex = 0xf1f3, + ccdinersclub = 0xf24c, + ccdiscover = 0xf1f2, + ccjcb = 0xf24b, + ccmastercard = 0xf1f1, + ccpaypal = 0xf1f4, + ccstripe = 0xf1f5, + ccvisa = 0xf1f0, + certificate = 0xf0a3, + chain = 0xf0c1, + chainbroken = 0xf127, + check = 0xf00c, + checkcircle = 0xf058, + checkcircleo = 0xf05d, + checksquare = 0xf14a, + checksquareo = 0xf046, + chevroncircledown = 0xf13a, + chevroncircleleft = 0xf137, + chevroncircleright = 0xf138, + chevroncircleup = 0xf139, + chevrondown = 0xf078, + chevronleft = 0xf053, + chevronright = 0xf054, + chevronup = 0xf077, + child = 0xf1ae, + chrome = 0xf268, + circle = 0xf111, + circleo = 0xf10c, + circleonotch = 0xf1ce, + circlethin = 0xf1db, + clipboard = 0xf0ea, + clocko = 0xf017, + clone = 0xf24d, + close = 0xf00d, + cloud = 0xf0c2, + clouddownload = 0xf0ed, + cloudupload = 0xf0ee, + cny = 0xf157, + code = 0xf121, + codefork = 0xf126, + codepen = 0xf1cb, + codiepie = 0xf284, + coffee = 0xf0f4, + cog = 0xf013, + cogs = 0xf085, + columns = 0xf0db, + comment = 0xf075, + commento = 0xf0e5, + commenting = 0xf27a, + commentingo = 0xf27b, + comments = 0xf086, + commentso = 0xf0e6, + compass = 0xf14e, + compress = 0xf066, + connectdevelop = 0xf20e, + contao = 0xf26d, + copy = 0xf0c5, + copyright = 0xf1f9, + creativecommons = 0xf25e, + creditcard = 0xf09d, + creditcardalt = 0xf283, + crop = 0xf125, + crosshairs = 0xf05b, + css3 = 0xf13c, + cube = 0xf1b2, + cubes = 0xf1b3, + cut = 0xf0c4, + cutlery = 0xf0f5, + dashboard = 0xf0e4, + dashcube = 0xf210, + database = 0xf1c0, + deaf = 0xf2a4, + deafness = 0xf2a4, + dedent = 0xf03b, + delicious = 0xf1a5, + desktop = 0xf108, + deviantart = 0xf1bd, + diamond = 0xf219, + digg = 0xf1a6, + dollar = 0xf155, + dotcircleo = 0xf192, + download = 0xf019, + dribbble = 0xf17d, + driverslicense = 0xf2c2, + driverslicenseo = 0xf2c3, + dropbox = 0xf16b, + drupal = 0xf1a9, + edge = 0xf282, + edit = 0xf044, + eercast = 0xf2da, + eject = 0xf052, + ellipsish = 0xf141, + ellipsisv = 0xf142, + empire = 0xf1d1, + envelope = 0xf0e0, + envelopeo = 0xf003, + envelopeopen = 0xf2b6, + envelopeopeno = 0xf2b7, + envelopesquare = 0xf199, + envira = 0xf299, + eraser = 0xf12d, + etsy = 0xf2d7, + eur = 0xf153, + euro = 0xf153, + exchange = 0xf0ec, + exclamation = 0xf12a, + exclamationcircle = 0xf06a, + exclamationtriangle = 0xf071, + expand = 0xf065, + expeditedssl = 0xf23e, + externallink = 0xf08e, + externallinksquare = 0xf14c, + eye = 0xf06e, + eyeslash = 0xf070, + eyedropper = 0xf1fb, + fa = 0xf2b4, + facebook = 0xf09a, + facebookf = 0xf09a, + facebookofficial = 0xf230, + facebooksquare = 0xf082, + fastbackward = 0xf049, + fastforward = 0xf050, + fax = 0xf1ac, + feed = 0xf09e, + female = 0xf182, + fighterjet = 0xf0fb, + file = 0xf15b, + filearchiveo = 0xf1c6, + fileaudioo = 0xf1c7, + filecodeo = 0xf1c9, + fileexcelo = 0xf1c3, + fileimageo = 0xf1c5, + filemovieo = 0xf1c8, + fileo = 0xf016, + filepdfo = 0xf1c1, + filephotoo = 0xf1c5, + filepictureo = 0xf1c5, + filepowerpointo = 0xf1c4, + filesoundo = 0xf1c7, + filetext = 0xf15c, + filetexto = 0xf0f6, + filevideoo = 0xf1c8, + filewordo = 0xf1c2, + filezipo = 0xf1c6, + fileso = 0xf0c5, + film = 0xf008, + filter = 0xf0b0, + fire = 0xf06d, + fireextinguisher = 0xf134, + firefox = 0xf269, + firstorder = 0xf2b0, + flag = 0xf024, + flagcheckered = 0xf11e, + flago = 0xf11d, + flash = 0xf0e7, + flask = 0xf0c3, + flickr = 0xf16e, + floppyo = 0xf0c7, + folder = 0xf07b, + foldero = 0xf114, + folderopen = 0xf07c, + folderopeno = 0xf115, + font = 0xf031, + fontawesome = 0xf2b4, + fonticons = 0xf280, + fortawesome = 0xf286, + forumbee = 0xf211, + forward = 0xf04e, + foursquare = 0xf180, + freecodecamp = 0xf2c5, + frowno = 0xf119, + futbolo = 0xf1e3, + gamepad = 0xf11b, + gavel = 0xf0e3, + gbp = 0xf154, + ge = 0xf1d1, + gear = 0xf013, + gears = 0xf085, + genderless = 0xf22d, + getpocket = 0xf265, + gg = 0xf260, + ggcircle = 0xf261, + gift = 0xf06b, + git = 0xf1d3, + gitsquare = 0xf1d2, + github = 0xf09b, + githubalt = 0xf113, + githubsquare = 0xf092, + gitlab = 0xf296, + gittip = 0xf184, + glass = 0xf000, + glide = 0xf2a5, + glideg = 0xf2a6, + globe = 0xf0ac, + google = 0xf1a0, + googleplus = 0xf0d5, + googlepluscircle = 0xf2b3, + googleplusofficial = 0xf2b3, + googleplussquare = 0xf0d4, + googlewallet = 0xf1ee, + graduationcap = 0xf19d, + gratipay = 0xf184, + grav = 0xf2d6, + group = 0xf0c0, + hsquare = 0xf0fd, + hackernews = 0xf1d4, + handgrabo = 0xf255, + handlizardo = 0xf258, + handodown = 0xf0a7, + handoleft = 0xf0a5, + handoright = 0xf0a4, + handoup = 0xf0a6, + handpapero = 0xf256, + handpeaceo = 0xf25b, + handpointero = 0xf25a, + handrocko = 0xf255, + handscissorso = 0xf257, + handspocko = 0xf259, + handstopo = 0xf256, + handshakeo = 0xf2b5, + hardofhearing = 0xf2a4, + hashtag = 0xf292, + hddo = 0xf0a0, + header = 0xf1dc, + headphones = 0xf025, + heart = 0xf004, + hearto = 0xf08a, + heartbeat = 0xf21e, + history = 0xf1da, + home = 0xf015, + hospitalo = 0xf0f8, + hotel = 0xf236, + hourglass = 0xf254, + hourglass1 = 0xf251, + hourglass2 = 0xf252, + hourglass3 = 0xf253, + hourglassend = 0xf253, + hourglasshalf = 0xf252, + hourglasso = 0xf250, + hourglassstart = 0xf251, + houzz = 0xf27c, + html5 = 0xf13b, + icursor = 0xf246, + idbadge = 0xf2c1, + idcard = 0xf2c2, + idcardo = 0xf2c3, + ils = 0xf20b, + image = 0xf03e, + imdb = 0xf2d8, + inbox = 0xf01c, + indent = 0xf03c, + industry = 0xf275, + info = 0xf129, + infocircle = 0xf05a, + inr = 0xf156, + instagram = 0xf16d, + institution = 0xf19c, + internetexplorer = 0xf26b, + intersex = 0xf224, + ioxhost = 0xf208, + italic = 0xf033, + joomla = 0xf1aa, + jpy = 0xf157, + jsfiddle = 0xf1cc, + key = 0xf084, + keyboardo = 0xf11c, + krw = 0xf159, + language = 0xf1ab, + laptop = 0xf109, + lastfm = 0xf202, + lastfmsquare = 0xf203, + leaf = 0xf06c, + leanpub = 0xf212, + legal = 0xf0e3, + lemono = 0xf094, + leveldown = 0xf149, + levelup = 0xf148, + lifebouy = 0xf1cd, + lifebuoy = 0xf1cd, + lifering = 0xf1cd, + lifesaver = 0xf1cd, + lightbulbo = 0xf0eb, + linechart = 0xf201, + link = 0xf0c1, + linkedin = 0xf0e1, + linkedinsquare = 0xf08c, + linode = 0xf2b8, + fa_linux = 0xf17c, + list = 0xf03a, + listalt = 0xf022, + listol = 0xf0cb, + listul = 0xf0ca, + locationarrow = 0xf124, + lock = 0xf023, + longarrowdown = 0xf175, + longarrowleft = 0xf177, + longarrowright = 0xf178, + longarrowup = 0xf176, + lowvision = 0xf2a8, + magic = 0xf0d0, + magnet = 0xf076, + mailforward = 0xf064, + mailreply = 0xf112, + mailreplyall = 0xf122, + male = 0xf183, + map = 0xf279, + mapmarker = 0xf041, + mapo = 0xf278, + mappin = 0xf276, + mapsigns = 0xf277, + mars = 0xf222, + marsdouble = 0xf227, + marsstroke = 0xf229, + marsstrokeh = 0xf22b, + marsstrokev = 0xf22a, + maxcdn = 0xf136, + meanpath = 0xf20c, + medium = 0xf23a, + medkit = 0xf0fa, + meetup = 0xf2e0, + meho = 0xf11a, + mercury = 0xf223, + microchip = 0xf2db, + microphone = 0xf130, + microphoneslash = 0xf131, + minus = 0xf068, + minuscircle = 0xf056, + minussquare = 0xf146, + minussquareo = 0xf147, + mixcloud = 0xf289, + mobile = 0xf10b, + mobilephone = 0xf10b, + modx = 0xf285, + money = 0xf0d6, + moono = 0xf186, + mortarboard = 0xf19d, + motorcycle = 0xf21c, + mousepointer = 0xf245, + music = 0xf001, + navicon = 0xf0c9, + neuter = 0xf22c, + newspapero = 0xf1ea, + objectgroup = 0xf247, + objectungroup = 0xf248, + odnoklassniki = 0xf263, + odnoklassnikisquare = 0xf264, + opencart = 0xf23d, + openid = 0xf19b, + opera = 0xf26a, + optinmonster = 0xf23c, + outdent = 0xf03b, + pagelines = 0xf18c, + paintbrush = 0xf1fc, + paperplane = 0xf1d8, + paperplaneo = 0xf1d9, + paperclip = 0xf0c6, + paragraph = 0xf1dd, + paste = 0xf0ea, + pause = 0xf04c, + pausecircle = 0xf28b, + pausecircleo = 0xf28c, + paw = 0xf1b0, + paypal = 0xf1ed, + pencil = 0xf040, + pencilsquare = 0xf14b, + pencilsquareo = 0xf044, + percent = 0xf295, + phone = 0xf095, + phonesquare = 0xf098, + photo = 0xf03e, + pictureo = 0xf03e, + piechart = 0xf200, + piedpiper = 0xf2ae, + piedpiperalt = 0xf1a8, + piedpiperpp = 0xf1a7, + pinterest = 0xf0d2, + pinterestp = 0xf231, + pinterestsquare = 0xf0d3, + plane = 0xf072, + play = 0xf04b, + playcircle = 0xf144, + playcircleo = 0xf01d, + plug = 0xf1e6, + plus = 0xf067, + pluscircle = 0xf055, + plussquare = 0xf0fe, + plussquareo = 0xf196, + podcast = 0xf2ce, + poweroff = 0xf011, + print = 0xf02f, + producthunt = 0xf288, + puzzlepiece = 0xf12e, + qq = 0xf1d6, + qrcode = 0xf029, + question = 0xf128, + questioncircle = 0xf059, + questioncircleo = 0xf29c, + quora = 0xf2c4, + quoteleft = 0xf10d, + quoteright = 0xf10e, + ra = 0xf1d0, + random = 0xf074, + ravelry = 0xf2d9, + rebel = 0xf1d0, + recycle = 0xf1b8, + reddit = 0xf1a1, + redditalien = 0xf281, + redditsquare = 0xf1a2, + refresh = 0xf021, + registered = 0xf25d, + remove = 0xf00d, + renren = 0xf18b, + reorder = 0xf0c9, + repeat = 0xf01e, + reply = 0xf112, + replyall = 0xf122, + resistance = 0xf1d0, + retweet = 0xf079, + rmb = 0xf157, + road = 0xf018, + rocket = 0xf135, + rotateleft = 0xf0e2, + rotateright = 0xf01e, + rouble = 0xf158, + rss = 0xf09e, + rsssquare = 0xf143, + rub = 0xf158, + ruble = 0xf158, + rupee = 0xf156, + s15 = 0xf2cd, + safari = 0xf267, + save = 0xf0c7, + scissors = 0xf0c4, + scribd = 0xf28a, + search = 0xf002, + searchminus = 0xf010, + searchplus = 0xf00e, + sellsy = 0xf213, + send = 0xf1d8, + sendo = 0xf1d9, + server = 0xf233, + share = 0xf064, + sharealt = 0xf1e0, + sharealtsquare = 0xf1e1, + sharesquare = 0xf14d, + sharesquareo = 0xf045, + shekel = 0xf20b, + sheqel = 0xf20b, + shield = 0xf132, + ship = 0xf21a, + shirtsinbulk = 0xf214, + shoppingbag = 0xf290, + shoppingbasket = 0xf291, + shoppingcart = 0xf07a, + shower = 0xf2cc, + signin = 0xf090, + signlanguage = 0xf2a7, + signout = 0xf08b, + signal = 0xf012, + signing = 0xf2a7, + simplybuilt = 0xf215, + sitemap = 0xf0e8, + skyatlas = 0xf216, + skype = 0xf17e, + slack = 0xf198, + sliders = 0xf1de, + slideshare = 0xf1e7, + smileo = 0xf118, + snapchat = 0xf2ab, + snapchatghost = 0xf2ac, + snapchatsquare = 0xf2ad, + snowflakeo = 0xf2dc, + soccerballo = 0xf1e3, + sort = 0xf0dc, + sortalphaasc = 0xf15d, + sortalphadesc = 0xf15e, + sortamountasc = 0xf160, + sortamountdesc = 0xf161, + sortasc = 0xf0de, + sortdesc = 0xf0dd, + sortdown = 0xf0dd, + sortnumericasc = 0xf162, + sortnumericdesc = 0xf163, + sortup = 0xf0de, + soundcloud = 0xf1be, + spaceshuttle = 0xf197, + spinner = 0xf110, + spoon = 0xf1b1, + spotify = 0xf1bc, + square = 0xf0c8, + squareo = 0xf096, + stackexchange = 0xf18d, + stackoverflow = 0xf16c, + star = 0xf005, + starhalf = 0xf089, + starhalfempty = 0xf123, + starhalffull = 0xf123, + starhalfo = 0xf123, + staro = 0xf006, + steam = 0xf1b6, + steamsquare = 0xf1b7, + stepbackward = 0xf048, + stepforward = 0xf051, + stethoscope = 0xf0f1, + stickynote = 0xf249, + stickynoteo = 0xf24a, + stop = 0xf04d, + stopcircle = 0xf28d, + stopcircleo = 0xf28e, + streetview = 0xf21d, + strikethrough = 0xf0cc, + stumbleupon = 0xf1a4, + stumbleuponcircle = 0xf1a3, + subscript = 0xf12c, + subway = 0xf239, + suitcase = 0xf0f2, + suno = 0xf185, + superpowers = 0xf2dd, + superscript = 0xf12b, + support = 0xf1cd, + table = 0xf0ce, + tablet = 0xf10a, + tachometer = 0xf0e4, + tag = 0xf02b, + tags = 0xf02c, + tasks = 0xf0ae, + taxi = 0xf1ba, + telegram = 0xf2c6, + television = 0xf26c, + tencentweibo = 0xf1d5, + terminal = 0xf120, + textheight = 0xf034, + textwidth = 0xf035, + th = 0xf00a, + thlarge = 0xf009, + thlist = 0xf00b, + themeisle = 0xf2b2, + thermometer = 0xf2c7, + thermometer0 = 0xf2cb, + thermometer1 = 0xf2ca, + thermometer2 = 0xf2c9, + thermometer3 = 0xf2c8, + thermometer4 = 0xf2c7, + thermometerempty = 0xf2cb, + thermometerfull = 0xf2c7, + thermometerhalf = 0xf2c9, + thermometerquarter = 0xf2ca, + thermometerthreequarters = 0xf2c8, + thumbtack = 0xf08d, + thumbsdown = 0xf165, + thumbsodown = 0xf088, + thumbsoup = 0xf087, + thumbsup = 0xf164, + ticket = 0xf145, + times = 0xf00d, + timescircle = 0xf057, + timescircleo = 0xf05c, + timesrectangle = 0xf2d3, + timesrectangleo = 0xf2d4, + tint = 0xf043, + toggledown = 0xf150, + toggleleft = 0xf191, + toggleoff = 0xf204, + toggleon = 0xf205, + toggleright = 0xf152, + toggleup = 0xf151, + trademark = 0xf25c, + train = 0xf238, + transgender = 0xf224, + transgenderalt = 0xf225, + trash = 0xf1f8, + trasho = 0xf014, + tree = 0xf1bb, + trello = 0xf181, + tripadvisor = 0xf262, + trophy = 0xf091, + truck = 0xf0d1, + fa_try = 0xf195, + tty = 0xf1e4, + tumblr = 0xf173, + tumblrsquare = 0xf174, + turkishlira = 0xf195, + tv = 0xf26c, + twitch = 0xf1e8, + twitter = 0xf099, + twittersquare = 0xf081, + umbrella = 0xf0e9, + underline = 0xf0cd, + undo = 0xf0e2, + universalaccess = 0xf29a, + university = 0xf19c, + unlink = 0xf127, + unlock = 0xf09c, + unlockalt = 0xf13e, + unsorted = 0xf0dc, + upload = 0xf093, + usb = 0xf287, + usd = 0xf155, + user = 0xf007, + usercircle = 0xf2bd, + usercircleo = 0xf2be, + usermd = 0xf0f0, + usero = 0xf2c0, + userplus = 0xf234, + usersecret = 0xf21b, + usertimes = 0xf235, + users = 0xf0c0, + vcard = 0xf2bb, + vcardo = 0xf2bc, + venus = 0xf221, + venusdouble = 0xf226, + venusmars = 0xf228, + viacoin = 0xf237, + viadeo = 0xf2a9, + viadeosquare = 0xf2aa, + videocamera = 0xf03d, + vimeo = 0xf27d, + vimeosquare = 0xf194, + vine = 0xf1ca, + vk = 0xf189, + volumecontrolphone = 0xf2a0, + volumedown = 0xf027, + volumeoff = 0xf026, + volumeup = 0xf028, + warning = 0xf071, + wechat = 0xf1d7, + weibo = 0xf18a, + weixin = 0xf1d7, + whatsapp = 0xf232, + wheelchair = 0xf193, + wheelchairalt = 0xf29b, + wifi = 0xf1eb, + wikipediaw = 0xf266, + windowclose = 0xf2d3, + windowcloseo = 0xf2d4, + windowmaximize = 0xf2d0, + windowminimize = 0xf2d1, + windowrestore = 0xf2d2, + windows = 0xf17a, + won = 0xf159, + wordpress = 0xf19a, + wpbeginner = 0xf297, + wpexplorer = 0xf2de, + wpforms = 0xf298, + wrench = 0xf0ad, + xing = 0xf168, + xingsquare = 0xf169, + ycombinator = 0xf23b, + ycombinatorsquare = 0xf1d4, + yahoo = 0xf19e, + yc = 0xf23b, + ycsquare = 0xf1d4, + yelp = 0xf1e9, + yen = 0xf157, + yoast = 0xf2b1, + youtube = 0xf167, + youtubeplay = 0xf16a, + youtubesquare = 0xf166 +}; } - //--------------------------------------------------------------------------------------- class QtAwesomeIconPainter; /// The main class for managing icons -/// This class requires a 2-phase construction. You must first create the class and then initialize it via an init* method -class QtAwesome : public QObject -{ -Q_OBJECT +/// This class requires a 2-phase construction. You must first create the class and then initialize it via an init* +/// method +class QtAwesome : public QObject { + Q_OBJECT -public: - explicit QtAwesome(QObject *parent = nullptr); + public: + explicit QtAwesome( QObject *parent = nullptr ); virtual ~QtAwesome(); - void init( const QString& fontname ); + void init( const QString &fontname ); bool initFontAwesome(); - void addNamedCodepoint( const QString& name, int codePoint ); - QHash namedCodePoints() { return namedCodepoints_; } + void addNamedCodepoint( const QString &name, int codePoint ); + QHash namedCodePoints() { return namedCodepoints_; } - void setDefaultOption( const QString& name, const QVariant& value ); - QVariant defaultOption( const QString& name ); + void setDefaultOption( const QString &name, const QVariant &value ); + QVariant defaultOption( const QString &name ); - QIcon icon( int character, const QVariantMap& options = QVariantMap() ); - QIcon icon( const QString& name, const QVariantMap& options = QVariantMap() ); - QIcon icon(QtAwesomeIconPainter* painter, const QVariantMap& optionMap = QVariantMap() ); + QIcon icon( int character, const QVariantMap &options = QVariantMap() ); + QIcon icon( const QString &name, const QVariantMap &options = QVariantMap() ); + QIcon icon( QtAwesomeIconPainter *painter, const QVariantMap &optionMap = QVariantMap() ); - void give( const QString& name, QtAwesomeIconPainter* painter ); + void give( const QString &name, QtAwesomeIconPainter *painter ); QFont font( int size ); /// Returns the font-name that is used as icon-map - QString fontName() { return fontName_ ; } + QString fontName() { return fontName_; } -private: - QString fontName_; ///< The font name used for this map - QHash namedCodepoints_; ///< A map with names mapped to code-points + private: + QString fontName_; ///< The font name used for this map + QHash namedCodepoints_; ///< A map with names mapped to code-points - QHash painterMap_; ///< A map of custom painters - QVariantMap defaultOptions_; ///< The default icon options - QtAwesomeIconPainter* fontIconPainter_; ///< A special painter fo painting codepoints + QHash painterMap_; ///< A map of custom painters + QVariantMap defaultOptions_; ///< The default icon options + QtAwesomeIconPainter *fontIconPainter_; ///< A special painter fo painting codepoints }; @@ -863,15 +862,15 @@ Q_OBJECT /// The QtAwesomeIconPainter is a specialized painter for painting icons /// your can implement an iconpainter to create custom font-icon code -class QtAwesomeIconPainter -{ -public: +class QtAwesomeIconPainter { + public: virtual ~QtAwesomeIconPainter() {} - virtual void paint( QtAwesome* awesome, QPainter* painter, const QRect& rect, QIcon::Mode mode, QIcon::State state, const QVariantMap& options ) = 0; + virtual void paint( QtAwesome *awesome, QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state, + const QVariantMap &options ) = 0; }; -Q_DECLARE_METATYPE(QtAwesomeAnimation*) +Q_DECLARE_METATYPE( QtAwesomeAnimation * ) -extern QtAwesome* iconFont; +extern QtAwesome *iconFont; #endif // QTAWESOME_H diff --git a/openhantek/src/iconfont/QtAwesomeAnim.cpp b/openhantek/src/iconfont/QtAwesomeAnim.cpp index fdc3b2a6..5e85e244 100644 --- a/openhantek/src/iconfont/QtAwesomeAnim.cpp +++ b/openhantek/src/iconfont/QtAwesomeAnim.cpp @@ -8,25 +8,25 @@ #include #include -QtAwesomeAnimation::QtAwesomeAnimation(QWidget *parentWidget, int interval, double step) - : parentWidgetRef_(parentWidget), timer_(nullptr), interval_(interval), step_(step), angle_(0.0) {} +QtAwesomeAnimation::QtAwesomeAnimation( QWidget *parentWidget, int interval, double step ) + : parentWidgetRef_( parentWidget ), timer_( nullptr ), interval_( interval ), step_( step ), angle_( 0.0 ) {} -void QtAwesomeAnimation::setup(QPainter &painter, const QRect &rect) { +void QtAwesomeAnimation::setup( QPainter &painter, const QRect &rect ) { // first time set the timer - if (!timer_) { + if ( !timer_ ) { timer_ = new QTimer(); - connect(timer_, SIGNAL(timeout()), this, SLOT(update())); - timer_->start(interval_); + connect( timer_, SIGNAL( timeout() ), this, SLOT( update() ) ); + timer_->start( interval_ ); } else { QPen pen = painter.pen(); - pen.setWidth(2); - pen.setColor(QColor(Qt::gray)); - painter.setPen(pen); - double val = 1 + sin(angle_) / 2; - if (val >= 0.5) - painter.drawArc(rect, 0 * 16, int(16 * (360 - (val - 0.5) * 2 * 360))); + pen.setWidth( 2 ); + pen.setColor( QColor( Qt::gray ) ); + painter.setPen( pen ); + double val = 1 + sin( angle_ ) / 2; + if ( val >= 0.5 ) + painter.drawArc( rect, 0 * 16, int( 16 * ( 360 - ( val - 0.5 ) * 2 * 360 ) ) ); else - painter.drawArc(rect, 0 * 16, int(16 * (val * 2) * 360)); + painter.drawArc( rect, 0 * 16, int( 16 * ( val * 2 ) * 360 ) ); } } diff --git a/openhantek/src/iconfont/QtAwesomeAnim.h b/openhantek/src/iconfont/QtAwesomeAnim.h index 05739271..80006474 100644 --- a/openhantek/src/iconfont/QtAwesomeAnim.h +++ b/openhantek/src/iconfont/QtAwesomeAnim.h @@ -13,21 +13,20 @@ class QWidget; /// /// Basic Animation Support for QtAwesome (Inspired by https://github.com/spyder-ide/qtawesome) /// -class QtAwesomeAnimation : public QObject -{ -Q_OBJECT +class QtAwesomeAnimation : public QObject { + Q_OBJECT -public: - QtAwesomeAnimation( QWidget* parentWidget, int interval=20, double step=0.01); + public: + QtAwesomeAnimation( QWidget *parentWidget, int interval = 20, double step = 0.01 ); - void setup( QPainter& painter, const QRect& rect ); + void setup( QPainter &painter, const QRect &rect ); -public slots: + public slots: void update(); -private: - QWidget* parentWidgetRef_; - QTimer* timer_; + private: + QWidget *parentWidgetRef_; + QTimer *timer_; int interval_; double step_; double angle_; diff --git a/openhantek/src/main.cpp b/openhantek/src/main.cpp index 94481dd7..3d2f8b9e 100644 --- a/openhantek/src/main.cpp +++ b/openhantek/src/main.cpp @@ -13,16 +13,16 @@ #endif #include #ifdef __FreeBSD__ - #include +#include #else - #include +#include #endif #include // Settings #include "dsosettings.h" -#include "viewsettings.h" #include "viewconstants.h" +#include "viewsettings.h" // DSO core logic #include "dsomodel.h" @@ -59,27 +59,27 @@ using namespace Hantek; /// \brief Initialize resources and translations and show the main window. -int main(int argc, char *argv[]) { +int main( int argc, char *argv[] ) { //////// Set application information //////// - QCoreApplication::setOrganizationName("OpenHantek"); - QCoreApplication::setOrganizationDomain("openhantek.org"); - QCoreApplication::setApplicationName("OpenHantek6022"); - QCoreApplication::setApplicationVersion(VERSION); - QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps, true); -#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) - QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true); + QCoreApplication::setOrganizationName( "OpenHantek" ); + QCoreApplication::setOrganizationDomain( "openhantek.org" ); + QCoreApplication::setApplicationName( "OpenHantek6022" ); + QCoreApplication::setApplicationVersion( VERSION ); + QCoreApplication::setAttribute( Qt::AA_UseHighDpiPixmaps, true ); +#if ( QT_VERSION >= QT_VERSION_CHECK( 5, 6, 0 ) ) + QCoreApplication::setAttribute( Qt::AA_EnableHighDpiScaling, true ); #endif bool useGLES = false; { - QCoreApplication parserApp(argc, argv); + QCoreApplication parserApp( argc, argv ); QCommandLineParser p; p.addHelpOption(); p.addVersionOption(); - QCommandLineOption useGlesOption("useGLES", QCoreApplication::tr("Use OpenGL ES instead of OpenGL")); - p.addOption(useGlesOption); - p.process(parserApp); - useGLES = p.isSet(useGlesOption); + QCommandLineOption useGlesOption( "useGLES", QCoreApplication::tr( "Use OpenGL ES instead of OpenGL" ) ); + p.addOption( useGlesOption ); + p.process( parserApp ); + useGLES = p.isSet( useGlesOption ); } #ifdef __arm__ @@ -89,7 +89,7 @@ int main(int argc, char *argv[]) { GlScope::fixOpenGLversion( useGLES ? QSurfaceFormat::OpenGLES : QSurfaceFormat::OpenGL ); - QApplication openHantekApplication(argc, argv); + QApplication openHantekApplication( argc, argv ); #ifdef __linux__ // Qt5 linux default @@ -109,7 +109,7 @@ int main(int argc, char *argv[]) { // or set the limits only for your user in /etc/security/limits.d: // - rtprio 99 struct sched_param schedParam; - schedParam.sched_priority = 49; // set RT priority level 50 + schedParam.sched_priority = 49; // set RT priority level 50 sched_setscheduler( 0, SCHED_FIFO, &schedParam ); // and RT FIFO scheduler // but ignore any error if user has no realtime rights #endif @@ -117,90 +117,91 @@ int main(int argc, char *argv[]) { //////// Load translations //////// QTranslator qtTranslator; QTranslator openHantekTranslator; - if (QLocale::system().name() != "en_US") { // somehow Qt on MacOS uses the german translation for en_US?! - if (qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { - openHantekApplication.installTranslator(&qtTranslator); + if ( QLocale::system().name() != "en_US" ) { // somehow Qt on MacOS uses the german translation for en_US?! + if ( qtTranslator.load( "qt_" + QLocale::system().name(), + QLibraryInfo::location( QLibraryInfo::TranslationsPath ) ) ) { + openHantekApplication.installTranslator( &qtTranslator ); } - if (openHantekTranslator.load(QLocale(), QLatin1String("openhantek"), QLatin1String("_"), - QLatin1String(":/translations"))) { - openHantekApplication.installTranslator(&openHantekTranslator); + if ( openHantekTranslator.load( QLocale(), QLatin1String( "openhantek" ), QLatin1String( "_" ), + QLatin1String( ":/translations" ) ) ) { + openHantekApplication.installTranslator( &openHantekTranslator ); } } //////// Find matching usb devices //////// libusb_context *context = nullptr; - int error = libusb_init(&context); - if (error) { - SelectSupportedDevice().showLibUSBFailedDialogModel(error); + int error = libusb_init( &context ); + if ( error ) { + SelectSupportedDevice().showLibUSBFailedDialogModel( error ); return -1; } - std::unique_ptr device = SelectSupportedDevice().showSelectDeviceModal(context); + std::unique_ptr device = SelectSupportedDevice().showSelectDeviceModal( context ); QString errorMessage; - if (device == nullptr || !device->connectDevice(errorMessage)) { - libusb_exit(context); + if ( device == nullptr || !device->connectDevice( errorMessage ) ) { + libusb_exit( context ); return -1; } //////// Create DSO control object and move it to a separate thread //////// QThread dsoControlThread; - dsoControlThread.setObjectName("dsoControlThread"); - HantekDsoControl dsoControl(device.get()); - dsoControl.moveToThread(&dsoControlThread); - QObject::connect(&dsoControlThread, &QThread::started, &dsoControl, &HantekDsoControl::run); - QObject::connect(&dsoControl, &HantekDsoControl::communicationError, QCoreApplication::instance(), - &QCoreApplication::quit); - QObject::connect(device.get(), &USBDevice::deviceDisconnected, QCoreApplication::instance(), - &QCoreApplication::quit); + dsoControlThread.setObjectName( "dsoControlThread" ); + HantekDsoControl dsoControl( device.get() ); + dsoControl.moveToThread( &dsoControlThread ); + QObject::connect( &dsoControlThread, &QThread::started, &dsoControl, &HantekDsoControl::run ); + QObject::connect( &dsoControl, &HantekDsoControl::communicationError, QCoreApplication::instance(), + &QCoreApplication::quit ); + QObject::connect( device.get(), &USBDevice::deviceDisconnected, QCoreApplication::instance(), + &QCoreApplication::quit ); //////// Create settings object //////// - DsoSettings settings(device->getModel()->spec()); + DsoSettings settings( device->getModel()->spec() ); //////// Create exporters //////// - ExporterRegistry exportRegistry(device->getModel()->spec(), &settings); + ExporterRegistry exportRegistry( device->getModel()->spec(), &settings ); ExporterCSV exporterCSV; ExporterImage exportImage; ExporterPrint exportPrint; - ExporterProcessor samplesToExportRaw(&exportRegistry); + ExporterProcessor samplesToExportRaw( &exportRegistry ); - exportRegistry.registerExporter(&exporterCSV); - exportRegistry.registerExporter(&exportImage); - exportRegistry.registerExporter(&exportPrint); + exportRegistry.registerExporter( &exporterCSV ); + exportRegistry.registerExporter( &exportImage ); + exportRegistry.registerExporter( &exportPrint ); //////// Create post processing objects //////// QThread postProcessingThread; - postProcessingThread.setObjectName("postProcessingThread"); - PostProcessing postProcessing(settings.scope.countChannels()); + postProcessingThread.setObjectName( "postProcessingThread" ); + PostProcessing postProcessing( settings.scope.countChannels() ); - SpectrumGenerator spectrumGenerator(&settings.scope, &settings.post); - MathChannelGenerator mathchannelGenerator(&settings.scope, device->getModel()->spec()->channels); - GraphGenerator graphGenerator(&settings.scope); + SpectrumGenerator spectrumGenerator( &settings.scope, &settings.post ); + MathChannelGenerator mathchannelGenerator( &settings.scope, device->getModel()->spec()->channels ); + GraphGenerator graphGenerator( &settings.scope ); - postProcessing.registerProcessor(&samplesToExportRaw); - postProcessing.registerProcessor(&mathchannelGenerator); - postProcessing.registerProcessor(&spectrumGenerator); - postProcessing.registerProcessor(&graphGenerator); + postProcessing.registerProcessor( &samplesToExportRaw ); + postProcessing.registerProcessor( &mathchannelGenerator ); + postProcessing.registerProcessor( &spectrumGenerator ); + postProcessing.registerProcessor( &graphGenerator ); - postProcessing.moveToThread(&postProcessingThread); - QObject::connect(&dsoControl, &HantekDsoControl::samplesAvailable, &postProcessing, &PostProcessing::input); - QObject::connect(&postProcessing, &PostProcessing::processingFinished, &exportRegistry, &ExporterRegistry::input, - Qt::DirectConnection); + postProcessing.moveToThread( &postProcessingThread ); + QObject::connect( &dsoControl, &HantekDsoControl::samplesAvailable, &postProcessing, &PostProcessing::input ); + QObject::connect( &postProcessing, &PostProcessing::processingFinished, &exportRegistry, &ExporterRegistry::input, + Qt::DirectConnection ); //////// Create main window //////// iconFont->initFontAwesome(); - MainWindow openHantekMainWindow(&dsoControl, &settings, &exportRegistry); - QObject::connect(&postProcessing, &PostProcessing::processingFinished, &openHantekMainWindow, - &MainWindow::showNewData); - QObject::connect(&exportRegistry, &ExporterRegistry::exporterProgressChanged, &openHantekMainWindow, - &MainWindow::exporterProgressChanged); - QObject::connect(&exportRegistry, &ExporterRegistry::exporterStatusChanged, &openHantekMainWindow, - &MainWindow::exporterStatusChanged); + MainWindow openHantekMainWindow( &dsoControl, &settings, &exportRegistry ); + QObject::connect( &postProcessing, &PostProcessing::processingFinished, &openHantekMainWindow, + &MainWindow::showNewData ); + QObject::connect( &exportRegistry, &ExporterRegistry::exporterProgressChanged, &openHantekMainWindow, + &MainWindow::exporterProgressChanged ); + QObject::connect( &exportRegistry, &ExporterRegistry::exporterStatusChanged, &openHantekMainWindow, + &MainWindow::exporterStatusChanged ); openHantekMainWindow.show(); //////// Start DSO thread and go into GUI main loop - dsoControl.enableSampling(true); + dsoControl.enableSampling( true ); postProcessingThread.start(); dsoControlThread.start(); int res = openHantekApplication.exec(); @@ -217,12 +218,12 @@ int main(int argc, char *argv[]) { std::cout << "stopped "; postProcessingThread.quit(); - postProcessingThread.wait(10000); + postProcessingThread.wait( 10000 ); std::cout << "after "; - if (context && device != nullptr) { - device.reset(); // causes libusb_close(), which must be called before libusb_exit() - libusb_exit(context); + if ( context && device != nullptr ) { + device.reset(); // causes libusb_close(), which must be called before libusb_exit() + libusb_exit( context ); } std::cout << openHantekMainWindow.elapsedTime.elapsed() / 1000 << " s\n"; diff --git a/openhantek/src/mainwindow.cpp b/openhantek/src/mainwindow.cpp index 56719396..6a4152d1 100644 --- a/openhantek/src/mainwindow.cpp +++ b/openhantek/src/mainwindow.cpp @@ -22,27 +22,27 @@ #include "dsosettings.h" +#include #include #include #include -#include #include #include "OH_VERSION.h" -MainWindow::MainWindow(HantekDsoControl *dsoControl, DsoSettings *settings, ExporterRegistry *exporterRegistry, - QWidget *parent) - : QMainWindow(parent), ui(new Ui::MainWindow), dsoSettings(settings), exporterRegistry(exporterRegistry) { +MainWindow::MainWindow( HantekDsoControl *dsoControl, DsoSettings *settings, ExporterRegistry *exporterRegistry, + QWidget *parent ) + : QMainWindow( parent ), ui( new Ui::MainWindow ), dsoSettings( settings ), exporterRegistry( exporterRegistry ) { QVariantMap colorMap; QString iconPath = QString( ":/images/" ); - if ( QPalette().color( QPalette::Window ).lightness() < 128 ) {// automatic light/dark icon switch - iconPath += "darktheme/"; // select top window icons accordingly - colorMap.insert( "color-off", QColor( 208, 208, 208 ) ); // light grey normal + if ( QPalette().color( QPalette::Window ).lightness() < 128 ) { // automatic light/dark icon switch + iconPath += "darktheme/"; // select top window icons accordingly + colorMap.insert( "color-off", QColor( 208, 208, 208 ) ); // light grey normal colorMap.insert( "color-active", QColor( 255, 255, 255 ) ); // white when selected } elapsedTime.start(); - ui->setupUi(this); + ui->setupUi( this ); iconPause = QIcon( iconPath + "pause.svg" ); iconPlay = QIcon( iconPath + "play.svg" ); ui->actionSampling->setIcon( iconPause ); @@ -50,37 +50,35 @@ MainWindow::MainWindow(HantekDsoControl *dsoControl, DsoSettings *settings, Expo ui->actionHistogram->setIcon( QIcon( iconPath + "histogram.svg" ) ); ui->actionZoom->setIcon( QIcon( iconPath + "zoom.svg" ) ); ui->actionMeasure->setIcon( QIcon( iconPath + "measure.svg" ) ); - ui->actionOpen->setIcon(iconFont->icon( fa::folderopen, colorMap ) ); - ui->actionSave->setIcon(iconFont->icon( fa::save, colorMap ) ); - ui->actionSettings->setIcon(iconFont->icon( fa::gear, colorMap ) ); - ui->actionManualCommand->setIcon(iconFont->icon( fa::edit, colorMap ) ); - ui->actionAbout->setIcon(iconFont->icon( fa::questioncircle, colorMap ) ); - ui->actionUserManual->setIcon(iconFont->icon( fa::filepdfo, colorMap ) ); + ui->actionOpen->setIcon( iconFont->icon( fa::folderopen, colorMap ) ); + ui->actionSave->setIcon( iconFont->icon( fa::save, colorMap ) ); + ui->actionSettings->setIcon( iconFont->icon( fa::gear, colorMap ) ); + ui->actionManualCommand->setIcon( iconFont->icon( fa::edit, colorMap ) ); + ui->actionAbout->setIcon( iconFont->icon( fa::questioncircle, colorMap ) ); + ui->actionUserManual->setIcon( iconFont->icon( fa::filepdfo, colorMap ) ); // Window title setWindowIcon( QIcon( ":/images/OpenHantek.svg" ) ); - setWindowTitle( - tr("OpenHantek6022 (%1) - Device %2 (FW%3)") - .arg( QString::fromStdString( VERSION), - QString::fromStdString(dsoControl->getDevice()->getModel()->name)) - .arg(dsoControl->getDevice()->getFwVersion(),4,16,QChar('0')) - ); - -#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) - setDockOptions(dockOptions() | QMainWindow::GroupedDragging); + setWindowTitle( tr( "OpenHantek6022 (%1) - Device %2 (FW%3)" ) + .arg( QString::fromStdString( VERSION ), + QString::fromStdString( dsoControl->getDevice()->getModel()->name ) ) + .arg( dsoControl->getDevice()->getFwVersion(), 4, 16, QChar( '0' ) ) ); + +#if ( QT_VERSION >= QT_VERSION_CHECK( 5, 6, 0 ) ) + setDockOptions( dockOptions() | QMainWindow::GroupedDragging ); #endif - for (auto *exporter : *exporterRegistry) { - QAction *action = new QAction(iconFont->icon( exporter->faIcon(), colorMap ), exporter->name(), this); - action->setCheckable(exporter->type() == ExporterInterface::Type::ContinousExport); - connect(action, &QAction::triggered, [exporter, exporterRegistry](bool checked) { + for ( auto *exporter : *exporterRegistry ) { + QAction *action = new QAction( iconFont->icon( exporter->faIcon(), colorMap ), exporter->name(), this ); + action->setCheckable( exporter->type() == ExporterInterface::Type::ContinousExport ); + connect( action, &QAction::triggered, [exporter, exporterRegistry]( bool checked ) { exporterRegistry->setExporterEnabled( - exporter, exporter->type() == ExporterInterface::Type::ContinousExport ? checked : true); - }); - ui->menuExport->addAction(action); + exporter, exporter->type() == ExporterInterface::Type::ContinousExport ? checked : true ); + } ); + ui->menuExport->addAction( action ); } - DsoSettingsScope *scope = &(dsoSettings->scope); + DsoSettingsScope *scope = &( dsoSettings->scope ); const Dso::ControlSpecification *spec = dsoControl->getDevice()->getModel()->spec(); registerDockMetaTypes(); @@ -91,298 +89,292 @@ MainWindow::MainWindow(HantekDsoControl *dsoControl, DsoSettings *settings, Expo HorizontalDock *horizontalDock; TriggerDock *triggerDock; SpectrumDock *spectrumDock; - voltageDock = new VoltageDock(scope, spec, this); - horizontalDock = new HorizontalDock(scope,spec, this); - triggerDock = new TriggerDock(scope, spec, this); - spectrumDock = new SpectrumDock(scope, this); + voltageDock = new VoltageDock( scope, spec, this ); + horizontalDock = new HorizontalDock( scope, spec, this ); + triggerDock = new TriggerDock( scope, spec, this ); + spectrumDock = new SpectrumDock( scope, this ); - addDockWidget(Qt::RightDockWidgetArea, voltageDock); - addDockWidget(Qt::RightDockWidgetArea, horizontalDock); - addDockWidget(Qt::RightDockWidgetArea, triggerDock); - addDockWidget(Qt::RightDockWidgetArea, spectrumDock); + addDockWidget( Qt::RightDockWidgetArea, voltageDock ); + addDockWidget( Qt::RightDockWidgetArea, horizontalDock ); + addDockWidget( Qt::RightDockWidgetArea, triggerDock ); + addDockWidget( Qt::RightDockWidgetArea, spectrumDock ); - restoreGeometry(dsoSettings->mainWindowGeometry); - restoreState(dsoSettings->mainWindowState); + restoreGeometry( dsoSettings->mainWindowGeometry ); + restoreState( dsoSettings->mainWindowState ); // Central oszilloscope widget - dsoWidget = new DsoWidget(&dsoSettings->scope, &dsoSettings->view, spec); - setCentralWidget(dsoWidget); + dsoWidget = new DsoWidget( &dsoSettings->scope, &dsoSettings->view, spec ); + setCentralWidget( dsoWidget ); // Command field inside the status bar - QLineEdit *commandEdit = new QLineEdit(this); + QLineEdit *commandEdit = new QLineEdit( this ); commandEdit->hide(); - statusBar()->addPermanentWidget(commandEdit, 1); + statusBar()->addPermanentWidget( commandEdit, 1 ); - connect(ui->actionManualCommand, &QAction::toggled, [ commandEdit](bool checked) { - commandEdit->setVisible(checked); - if (checked) + connect( ui->actionManualCommand, &QAction::toggled, [commandEdit]( bool checked ) { + commandEdit->setVisible( checked ); + if ( checked ) commandEdit->setFocus(); - }); + } ); - connect(commandEdit, &QLineEdit::returnPressed, [this, commandEdit, dsoControl]() { - Dso::ErrorCode errorCode = dsoControl->stringCommand(commandEdit->text()); + connect( commandEdit, &QLineEdit::returnPressed, [this, commandEdit, dsoControl]() { + Dso::ErrorCode errorCode = dsoControl->stringCommand( commandEdit->text() ); commandEdit->clear(); - this->ui->actionManualCommand->setChecked(false); - if (errorCode != Dso::ErrorCode::NONE) - statusBar()->showMessage(tr("Invalid command"), 3000); - }); + this->ui->actionManualCommand->setChecked( false ); + if ( errorCode != Dso::ErrorCode::NONE ) + statusBar()->showMessage( tr( "Invalid command" ), 3000 ); + } ); // Connect general signals - connect(dsoControl, &HantekDsoControl::statusMessage, statusBar(), &QStatusBar::showMessage); + connect( dsoControl, &HantekDsoControl::statusMessage, statusBar(), &QStatusBar::showMessage ); // Connect signals to DSO controller and widget - connect(horizontalDock, &HorizontalDock::samplerateChanged, [dsoControl, this]() { - dsoControl->setSamplerate(dsoSettings->scope.horizontal.samplerate); - this->dsoWidget->updateSamplerate(dsoSettings->scope.horizontal.samplerate); - }); - connect(horizontalDock, &HorizontalDock::timebaseChanged, [dsoControl, this]() { - dsoControl->setRecordTime(dsoSettings->scope.horizontal.timebase * DIVS_TIME); - this->dsoWidget->updateTimebase(dsoSettings->scope.horizontal.timebase); - }); - connect(horizontalDock, &HorizontalDock::frequencybaseChanged, dsoWidget, &DsoWidget::updateFrequencybase); - connect(dsoControl, &HantekDsoControl::samplerateChanged, [this, horizontalDock](double samplerate) { + connect( horizontalDock, &HorizontalDock::samplerateChanged, [dsoControl, this]() { + dsoControl->setSamplerate( dsoSettings->scope.horizontal.samplerate ); + this->dsoWidget->updateSamplerate( dsoSettings->scope.horizontal.samplerate ); + } ); + connect( horizontalDock, &HorizontalDock::timebaseChanged, [dsoControl, this]() { + dsoControl->setRecordTime( dsoSettings->scope.horizontal.timebase * DIVS_TIME ); + this->dsoWidget->updateTimebase( dsoSettings->scope.horizontal.timebase ); + } ); + connect( horizontalDock, &HorizontalDock::frequencybaseChanged, dsoWidget, &DsoWidget::updateFrequencybase ); + connect( dsoControl, &HantekDsoControl::samplerateChanged, [this, horizontalDock]( double samplerate ) { // The timebase was set, let's adapt the samplerate accordingly - //printf( "mainwindow::samplerateChanged( %g )\n", samplerate ); + // printf( "mainwindow::samplerateChanged( %g )\n", samplerate ); dsoSettings->scope.horizontal.samplerate = samplerate; - horizontalDock->setSamplerate(samplerate); - dsoWidget->updateSamplerate(samplerate); - }); - connect(horizontalDock, &HorizontalDock::calfreqChanged, [dsoControl, this]() { - dsoControl->setCalFreq(dsoSettings->scope.horizontal.calfreq); - }); - connect(horizontalDock, &HorizontalDock::formatChanged, [this]( Dso::GraphFormat format ) { - ui->actionHistogram->setEnabled( format == Dso::GraphFormat::TY ); - }); - - connect(triggerDock, &TriggerDock::modeChanged, dsoControl, &HantekDsoControl::setTriggerMode); - connect(triggerDock, &TriggerDock::modeChanged, dsoWidget, &DsoWidget::updateTriggerMode); - connect(triggerDock, &TriggerDock::sourceChanged, dsoControl, &HantekDsoControl::setTriggerSource); - connect(triggerDock, &TriggerDock::sourceChanged, dsoWidget, &DsoWidget::updateTriggerSource); - connect(triggerDock, &TriggerDock::slopeChanged, dsoControl, &HantekDsoControl::setTriggerSlope); - connect(triggerDock, &TriggerDock::slopeChanged, dsoWidget, &DsoWidget::updateTriggerSlope); - connect(dsoWidget, &DsoWidget::triggerPositionChanged, dsoControl, &HantekDsoControl::setTriggerOffset ); - connect(dsoWidget, &DsoWidget::triggerLevelChanged, dsoControl, &HantekDsoControl::setTriggerLevel); - - auto usedChanged = [this, dsoControl, spec](ChannelID channel) { - if (channel >= dsoSettings->scope.voltage.size()) + horizontalDock->setSamplerate( samplerate ); + dsoWidget->updateSamplerate( samplerate ); + } ); + connect( horizontalDock, &HorizontalDock::calfreqChanged, + [dsoControl, this]() { dsoControl->setCalFreq( dsoSettings->scope.horizontal.calfreq ); } ); + connect( horizontalDock, &HorizontalDock::formatChanged, + [this]( Dso::GraphFormat format ) { ui->actionHistogram->setEnabled( format == Dso::GraphFormat::TY ); } ); + + connect( triggerDock, &TriggerDock::modeChanged, dsoControl, &HantekDsoControl::setTriggerMode ); + connect( triggerDock, &TriggerDock::modeChanged, dsoWidget, &DsoWidget::updateTriggerMode ); + connect( triggerDock, &TriggerDock::sourceChanged, dsoControl, &HantekDsoControl::setTriggerSource ); + connect( triggerDock, &TriggerDock::sourceChanged, dsoWidget, &DsoWidget::updateTriggerSource ); + connect( triggerDock, &TriggerDock::slopeChanged, dsoControl, &HantekDsoControl::setTriggerSlope ); + connect( triggerDock, &TriggerDock::slopeChanged, dsoWidget, &DsoWidget::updateTriggerSlope ); + connect( dsoWidget, &DsoWidget::triggerPositionChanged, dsoControl, &HantekDsoControl::setTriggerOffset ); + connect( dsoWidget, &DsoWidget::triggerLevelChanged, dsoControl, &HantekDsoControl::setTriggerLevel ); + + auto usedChanged = [this, dsoControl, spec]( ChannelID channel ) { + if ( channel >= dsoSettings->scope.voltage.size() ) return; - bool mathUsed = dsoSettings->scope.anyUsed(spec->channels); + bool mathUsed = dsoSettings->scope.anyUsed( spec->channels ); // Normal channel, check if voltage/spectrum or math channel is used - if (channel < spec->channels) - dsoControl->setChannelUsed(channel, mathUsed | dsoSettings->scope.anyUsed(channel)); + if ( channel < spec->channels ) + dsoControl->setChannelUsed( channel, mathUsed | dsoSettings->scope.anyUsed( channel ) ); // Math channel, update all channels - else if (channel == spec->channels) { - for (ChannelID c = 0; c < spec->channels; ++c) - dsoControl->setChannelUsed(c, mathUsed | dsoSettings->scope.anyUsed(c)); + else if ( channel == spec->channels ) { + for ( ChannelID c = 0; c < spec->channels; ++c ) + dsoControl->setChannelUsed( c, mathUsed | dsoSettings->scope.anyUsed( c ) ); } }; - connect(voltageDock, &VoltageDock::usedChanged, usedChanged); - connect(spectrumDock, &SpectrumDock::usedChanged, usedChanged); + connect( voltageDock, &VoltageDock::usedChanged, usedChanged ); + connect( spectrumDock, &SpectrumDock::usedChanged, usedChanged ); - connect(voltageDock, &VoltageDock::modeChanged, dsoWidget, &DsoWidget::updateMathMode); - connect(voltageDock, &VoltageDock::gainChanged, [this, dsoControl, spec](ChannelID channel ) { - if (channel >= spec->channels) + connect( voltageDock, &VoltageDock::modeChanged, dsoWidget, &DsoWidget::updateMathMode ); + connect( voltageDock, &VoltageDock::gainChanged, [this, dsoControl, spec]( ChannelID channel ) { + if ( channel >= spec->channels ) return; - dsoControl->setGain(channel, dsoSettings->scope.gain(channel) * DIVS_VOLTAGE); - }); - connect(voltageDock, &VoltageDock::probeAttnChanged, [ dsoControl, spec](ChannelID channel, double probeAttn ) { - if (channel >= spec->channels) + dsoControl->setGain( channel, dsoSettings->scope.gain( channel ) * DIVS_VOLTAGE ); + } ); + connect( voltageDock, &VoltageDock::probeAttnChanged, [dsoControl, spec]( ChannelID channel, double probeAttn ) { + if ( channel >= spec->channels ) return; dsoControl->setProbe( channel, probeAttn ); - }); - connect(voltageDock, &VoltageDock::invertedChanged, [ dsoControl, spec](ChannelID channel, bool inverted) { - if (channel >= spec->channels) + } ); + connect( voltageDock, &VoltageDock::invertedChanged, [dsoControl, spec]( ChannelID channel, bool inverted ) { + if ( channel >= spec->channels ) return; dsoControl->setChannelInverted( channel, inverted ); - }); - connect(voltageDock, &VoltageDock::couplingChanged, dsoWidget, &DsoWidget::updateVoltageCoupling); - connect(voltageDock, &VoltageDock::couplingChanged, [ dsoControl, spec](ChannelID channel, Dso::Coupling coupling ) { - if (channel >= spec->channels) - return; - dsoControl->setCoupling( channel, coupling ); - }); - connect(voltageDock, &VoltageDock::gainChanged, dsoWidget, &DsoWidget::updateVoltageGain); - connect(voltageDock, &VoltageDock::usedChanged, dsoWidget, &DsoWidget::updateVoltageUsed); - connect(spectrumDock, &SpectrumDock::usedChanged, dsoWidget, &DsoWidget::updateSpectrumUsed); - connect(spectrumDock, &SpectrumDock::magnitudeChanged, dsoWidget, &DsoWidget::updateSpectrumMagnitude); + } ); + connect( voltageDock, &VoltageDock::couplingChanged, dsoWidget, &DsoWidget::updateVoltageCoupling ); + connect( voltageDock, &VoltageDock::couplingChanged, + [dsoControl, spec]( ChannelID channel, Dso::Coupling coupling ) { + if ( channel >= spec->channels ) + return; + dsoControl->setCoupling( channel, coupling ); + } ); + connect( voltageDock, &VoltageDock::gainChanged, dsoWidget, &DsoWidget::updateVoltageGain ); + connect( voltageDock, &VoltageDock::usedChanged, dsoWidget, &DsoWidget::updateVoltageUsed ); + connect( spectrumDock, &SpectrumDock::usedChanged, dsoWidget, &DsoWidget::updateSpectrumUsed ); + connect( spectrumDock, &SpectrumDock::magnitudeChanged, dsoWidget, &DsoWidget::updateSpectrumMagnitude ); // Started/stopped signals from oscilloscope - connect(dsoControl, &HantekDsoControl::samplingStatusChanged, [this](bool enabled) { - QSignalBlocker blocker(this->ui->actionSampling); - if (enabled) { + connect( dsoControl, &HantekDsoControl::samplingStatusChanged, [this]( bool enabled ) { + QSignalBlocker blocker( this->ui->actionSampling ); + if ( enabled ) { this->ui->actionSampling->setIcon( this->iconPause ); - this->ui->actionSampling->setText(tr("Stop")); - this->ui->actionSampling->setStatusTip(tr("Stop the oscilloscope")); + this->ui->actionSampling->setText( tr( "Stop" ) ); + this->ui->actionSampling->setStatusTip( tr( "Stop the oscilloscope" ) ); } else { this->ui->actionSampling->setIcon( this->iconPlay ); - this->ui->actionSampling->setText(tr("Start")); - this->ui->actionSampling->setStatusTip(tr("Start the oscilloscope")); + this->ui->actionSampling->setText( tr( "Start" ) ); + this->ui->actionSampling->setStatusTip( tr( "Start the oscilloscope" ) ); } - this->ui->actionSampling->setChecked(enabled); - }); - connect(this->ui->actionSampling, &QAction::triggered, dsoControl, &HantekDsoControl::enableSampling); - this->ui->actionSampling->setChecked(dsoControl->isSampling()); + this->ui->actionSampling->setChecked( enabled ); + } ); + connect( this->ui->actionSampling, &QAction::triggered, dsoControl, &HantekDsoControl::enableSampling ); + this->ui->actionSampling->setChecked( dsoControl->isSampling() ); - connect(dsoControl, &HantekDsoControl::samplerateLimitsChanged, horizontalDock, - &HorizontalDock::setSamplerateLimits); - connect(dsoControl, &HantekDsoControl::samplerateSet, horizontalDock, &HorizontalDock::setSamplerateSteps); + connect( dsoControl, &HantekDsoControl::samplerateLimitsChanged, horizontalDock, + &HorizontalDock::setSamplerateLimits ); + connect( dsoControl, &HantekDsoControl::samplerateSet, horizontalDock, &HorizontalDock::setSamplerateSteps ); // Load settings to GUI - connect(this, &MainWindow::settingsLoaded, voltageDock, &VoltageDock::loadSettings); - connect(this, &MainWindow::settingsLoaded, horizontalDock, &HorizontalDock::loadSettings); - connect(this, &MainWindow::settingsLoaded, spectrumDock, &SpectrumDock::loadSettings); - connect(this, &MainWindow::settingsLoaded, triggerDock, &TriggerDock::loadSettings); - connect(this, &MainWindow::settingsLoaded, dsoControl, &HantekDsoControl::applySettings); - connect(this, &MainWindow::settingsLoaded, dsoWidget, &DsoWidget::updateSlidersSettings); - - connect(ui->actionOpen, &QAction::triggered, [this, spec]() { - QString fileName = QFileDialog::getOpenFileName(this, tr("Open file"), "", tr("Settings (*.ini)")); - if (!fileName.isEmpty()) { - if (dsoSettings->setFilename(fileName)) { dsoSettings->load(); } - emit settingsLoaded(&dsoSettings->scope, spec); - - dsoWidget->updateTimebase(dsoSettings->scope.horizontal.timebase); - - for (ChannelID channel = 0; channel < spec->channels; ++channel) { - this->dsoWidget->updateVoltageUsed(channel, dsoSettings->scope.voltage[channel].used); - this->dsoWidget->updateSpectrumUsed(channel, dsoSettings->scope.spectrum[channel].used); + connect( this, &MainWindow::settingsLoaded, voltageDock, &VoltageDock::loadSettings ); + connect( this, &MainWindow::settingsLoaded, horizontalDock, &HorizontalDock::loadSettings ); + connect( this, &MainWindow::settingsLoaded, spectrumDock, &SpectrumDock::loadSettings ); + connect( this, &MainWindow::settingsLoaded, triggerDock, &TriggerDock::loadSettings ); + connect( this, &MainWindow::settingsLoaded, dsoControl, &HantekDsoControl::applySettings ); + connect( this, &MainWindow::settingsLoaded, dsoWidget, &DsoWidget::updateSlidersSettings ); + + connect( ui->actionOpen, &QAction::triggered, [this, spec]() { + QString fileName = QFileDialog::getOpenFileName( this, tr( "Open file" ), "", tr( "Settings (*.ini)" ) ); + if ( !fileName.isEmpty() ) { + if ( dsoSettings->setFilename( fileName ) ) { + dsoSettings->load(); + } + emit settingsLoaded( &dsoSettings->scope, spec ); + + dsoWidget->updateTimebase( dsoSettings->scope.horizontal.timebase ); + + for ( ChannelID channel = 0; channel < spec->channels; ++channel ) { + this->dsoWidget->updateVoltageUsed( channel, dsoSettings->scope.voltage[ channel ].used ); + this->dsoWidget->updateSpectrumUsed( channel, dsoSettings->scope.spectrum[ channel ].used ); } } - }); + } ); - connect(ui->actionSave, &QAction::triggered, [this]() { + connect( ui->actionSave, &QAction::triggered, [this]() { dsoSettings->mainWindowGeometry = saveGeometry(); dsoSettings->mainWindowState = saveState(); dsoSettings->save(); - }); + } ); - connect(ui->actionSave_as, &QAction::triggered, [this]() { - QString fileName = QFileDialog::getSaveFileName(this, tr("Save settings"), "", tr("Settings (*.ini)")); - if (fileName.isEmpty()) + connect( ui->actionSave_as, &QAction::triggered, [this]() { + QString fileName = QFileDialog::getSaveFileName( this, tr( "Save settings" ), "", tr( "Settings (*.ini)" ) ); + if ( fileName.isEmpty() ) return; - if (!fileName.endsWith(".ini")) - fileName.append(".ini"); + if ( !fileName.endsWith( ".ini" ) ) + fileName.append( ".ini" ); dsoSettings->mainWindowGeometry = saveGeometry(); dsoSettings->mainWindowState = saveState(); - dsoSettings->setFilename(fileName); + dsoSettings->setFilename( fileName ); dsoSettings->save(); - }); + } ); - connect(ui->actionExit, &QAction::triggered, this, &QWidget::close); + connect( ui->actionExit, &QAction::triggered, this, &QWidget::close ); - connect(ui->actionSettings, &QAction::triggered, [this]() { + connect( ui->actionSettings, &QAction::triggered, [this]() { dsoSettings->mainWindowGeometry = saveGeometry(); dsoSettings->mainWindowState = saveState(); - DsoConfigDialog *configDialog = new DsoConfigDialog(this->dsoSettings, this); - configDialog->setModal(true); + DsoConfigDialog *configDialog = new DsoConfigDialog( this->dsoSettings, this ); + configDialog->setModal( true ); configDialog->show(); - }); + } ); - connect(this->ui->actionDigital_phosphor, &QAction::toggled, [this](bool enabled) { + connect( this->ui->actionDigital_phosphor, &QAction::toggled, [this]( bool enabled ) { dsoSettings->view.digitalPhosphor = enabled; - if (dsoSettings->view.digitalPhosphor) - this->ui->actionDigital_phosphor->setStatusTip(tr("Disable fading of previous graphs")); + if ( dsoSettings->view.digitalPhosphor ) + this->ui->actionDigital_phosphor->setStatusTip( tr( "Disable fading of previous graphs" ) ); else - this->ui->actionDigital_phosphor->setStatusTip(tr("Enable fading of previous graphs")); - }); - this->ui->actionDigital_phosphor->setChecked(dsoSettings->view.digitalPhosphor); + this->ui->actionDigital_phosphor->setStatusTip( tr( "Enable fading of previous graphs" ) ); + } ); + this->ui->actionDigital_phosphor->setChecked( dsoSettings->view.digitalPhosphor ); - connect(ui->actionHistogram, &QAction::toggled, [this](bool enabled) { + connect( ui->actionHistogram, &QAction::toggled, [this]( bool enabled ) { dsoSettings->scope.histogram = enabled; - if (dsoSettings->scope.histogram) - this->ui->actionHistogram->setStatusTip(tr("Hide histogram")); + if ( dsoSettings->scope.histogram ) + this->ui->actionHistogram->setStatusTip( tr( "Hide histogram" ) ); else - this->ui->actionHistogram->setStatusTip(tr("Show histogram")); - }); - ui->actionHistogram->setChecked(dsoSettings->scope.histogram); + this->ui->actionHistogram->setStatusTip( tr( "Show histogram" ) ); + } ); + ui->actionHistogram->setChecked( dsoSettings->scope.histogram ); ui->actionHistogram->setEnabled( scope->horizontal.format == Dso::GraphFormat::TY ); - connect(ui->actionZoom, &QAction::toggled, [this](bool enabled) { + connect( ui->actionZoom, &QAction::toggled, [this]( bool enabled ) { dsoSettings->view.zoom = enabled; - if (dsoSettings->view.zoom) - this->ui->actionZoom->setStatusTip(tr("Hide magnified scope")); + if ( dsoSettings->view.zoom ) + this->ui->actionZoom->setStatusTip( tr( "Hide magnified scope" ) ); else - this->ui->actionZoom->setStatusTip(tr("Show magnified scope")); + this->ui->actionZoom->setStatusTip( tr( "Show magnified scope" ) ); - this->dsoWidget->updateZoom(enabled); - }); - ui->actionZoom->setChecked(dsoSettings->view.zoom); + this->dsoWidget->updateZoom( enabled ); + } ); + ui->actionZoom->setChecked( dsoSettings->view.zoom ); - connect(ui->actionMeasure, &QAction::toggled, [this](bool enabled) { + connect( ui->actionMeasure, &QAction::toggled, [this]( bool enabled ) { dsoSettings->view.cursorsVisible = enabled; - if (dsoSettings->view.cursorsVisible) - this->ui->actionMeasure->setStatusTip(tr("Hide measurements")); + if ( dsoSettings->view.cursorsVisible ) + this->ui->actionMeasure->setStatusTip( tr( "Hide measurements" ) ); else - this->ui->actionMeasure->setStatusTip(tr("Show measurements")); + this->ui->actionMeasure->setStatusTip( tr( "Show measurements" ) ); - this->dsoWidget->updateCursorGrid(enabled); - }); - ui->actionMeasure->setChecked(dsoSettings->view.cursorsVisible); + this->dsoWidget->updateCursorGrid( enabled ); + } ); + ui->actionMeasure->setChecked( dsoSettings->view.cursorsVisible ); - connect(ui->actionUserManual, &QAction::triggered, []() { + connect( ui->actionUserManual, &QAction::triggered, []() { QString usrManualPath( USR_MANUAL_PATH ); QFile userManual( usrManualPath ); if ( userManual.exists() ) QDesktopServices::openUrl( QUrl( "file://" + usrManualPath ) ); else - QDesktopServices::openUrl( QUrl( "https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/OpenHantek6022_User_Manual.pdf" ) ); - }); + QDesktopServices::openUrl( QUrl( + "https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/OpenHantek6022_User_Manual.pdf" ) ); + } ); - connect(ui->actionAbout, &QAction::triggered, [this]() { + connect( ui->actionAbout, &QAction::triggered, [this]() { QMessageBox::about( - this, tr("About OpenHantek6022 (%1)").arg(VERSION), - tr("

Open source software for Hantek6022 USB oscilloscopes

" - "

Copyright © 2010, 2011 Oliver Haag

" - "

Copyright © 2012-2020 OpenHantek community
" - "https://github.com/OpenHantek

" - "

Open source firmware copyright © 2019-2020 Ho-Ro
" - "https://github.com/Ho-Ro/Hantek6022API

") + - tr("

Running since %1 seconds.

" - ).arg( elapsedTime.elapsed() / 1000 ) - ); - }); - - emit settingsLoaded(&dsoSettings->scope, spec); - - dsoWidget->updateTimebase(dsoSettings->scope.horizontal.timebase); - - for (ChannelID channel = 0; channel < spec->channels; ++channel) { - this->dsoWidget->updateVoltageUsed(channel, dsoSettings->scope.voltage[channel].used); - this->dsoWidget->updateSpectrumUsed(channel, dsoSettings->scope.spectrum[channel].used); + this, tr( "About OpenHantek6022 (%1)" ).arg( VERSION ), + tr( "

Open source software for Hantek6022 USB oscilloscopes

" + "

Copyright © 2010, 2011 Oliver Haag

" + "

Copyright © 2012-2020 OpenHantek community
" + "https://github.com/OpenHantek

" + "

Open source firmware copyright © 2019-2020 Ho-Ro
" + "https://github.com/Ho-Ro/Hantek6022API

" ) + + tr( "

Running since %1 seconds.

" ).arg( elapsedTime.elapsed() / 1000 ) ); + } ); + + emit settingsLoaded( &dsoSettings->scope, spec ); + + dsoWidget->updateTimebase( dsoSettings->scope.horizontal.timebase ); + + for ( ChannelID channel = 0; channel < spec->channels; ++channel ) { + this->dsoWidget->updateVoltageUsed( channel, dsoSettings->scope.voltage[ channel ].used ); + this->dsoWidget->updateSpectrumUsed( channel, dsoSettings->scope.spectrum[ channel ].used ); } } -MainWindow::~MainWindow() { - delete ui; -} +MainWindow::~MainWindow() { delete ui; } -void MainWindow::showNewData(std::shared_ptr newData) { - dsoWidget->showNew( newData ); -} +void MainWindow::showNewData( std::shared_ptr newData ) { dsoWidget->showNew( newData ); } -void MainWindow::exporterStatusChanged(const QString &exporterName, const QString &status) { - ui->statusbar->showMessage(tr("%1: %2").arg(exporterName, status)); +void MainWindow::exporterStatusChanged( const QString &exporterName, const QString &status ) { + ui->statusbar->showMessage( tr( "%1: %2" ).arg( exporterName, status ) ); } -void MainWindow::exporterProgressChanged() { - exporterRegistry->checkForWaitingExporters(); -} +void MainWindow::exporterProgressChanged() { exporterRegistry->checkForWaitingExporters(); } /// \brief Save the settings before exiting. /// \param event The close event that should be handled. -void MainWindow::closeEvent(QCloseEvent *event) { - if (dsoSettings->alwaysSave) { +void MainWindow::closeEvent( QCloseEvent *event ) { + if ( dsoSettings->alwaysSave ) { dsoSettings->mainWindowGeometry = saveGeometry(); dsoSettings->mainWindowState = saveState(); dsoSettings->save(); } - QMainWindow::closeEvent(event); + QMainWindow::closeEvent( event ); } diff --git a/openhantek/src/mainwindow.h b/openhantek/src/mainwindow.h index fff5a81e..c3822bc1 100644 --- a/openhantek/src/mainwindow.h +++ b/openhantek/src/mainwindow.h @@ -2,8 +2,8 @@ #pragma once #include "post/ppresult.h" -#include #include +#include #include #include "scopesettings.h" @@ -29,18 +29,18 @@ class MainWindow : public QMainWindow { Q_OBJECT public: - explicit MainWindow(HantekDsoControl *dsoControl, DsoSettings *dsoSettings, ExporterRegistry *exporterRegistry, - QWidget *parent = nullptr); + explicit MainWindow( HantekDsoControl *dsoControl, DsoSettings *dsoSettings, ExporterRegistry *exporterRegistry, + QWidget *parent = nullptr ); ~MainWindow() override; QElapsedTimer elapsedTime; public slots: - void showNewData(std::shared_ptr newData); - void exporterStatusChanged(const QString &exporterName, const QString &status); + void showNewData( std::shared_ptr newData ); + void exporterStatusChanged( const QString &exporterName, const QString &status ); void exporterProgressChanged(); protected: - void closeEvent(QCloseEvent *event) override; + void closeEvent( QCloseEvent *event ) override; private: Ui::MainWindow *ui; @@ -55,5 +55,5 @@ class MainWindow : public QMainWindow { ExporterRegistry *exporterRegistry; signals: - void settingsLoaded(DsoSettingsScope *scope, const Dso::ControlSpecification *spec); + void settingsLoaded( DsoSettingsScope *scope, const Dso::ControlSpecification *spec ); }; diff --git a/openhantek/src/post/graphgenerator.cpp b/openhantek/src/post/graphgenerator.cpp index 20905402..db60e2ac 100644 --- a/openhantek/src/post/graphgenerator.cpp +++ b/openhantek/src/post/graphgenerator.cpp @@ -6,57 +6,60 @@ #include #include "graphgenerator.h" -#include "ppresult.h" #include "hantekdso/controlspecification.h" +#include "ppresult.h" #include "scopesettings.h" #include "utils/printutils.h" #include "viewconstants.h" #include "viewsettings.h" -static const SampleValues &useSpecSamplesOf(ChannelID channel, const PPresult *result, - const DsoSettingsScope *scope) { +static const SampleValues &useSpecSamplesOf( ChannelID channel, const PPresult *result, + const DsoSettingsScope *scope ) { static SampleValues emptyDefault; - if (!scope->spectrum[channel].used || !result->data(channel)) return emptyDefault; - return result->data(channel)->spectrum; + if ( !scope->spectrum[ channel ].used || !result->data( channel ) ) + return emptyDefault; + return result->data( channel )->spectrum; } -static const SampleValues &useVoltSamplesOf(ChannelID channel, const PPresult *result, - const DsoSettingsScope *scope) { +static const SampleValues &useVoltSamplesOf( ChannelID channel, const PPresult *result, + const DsoSettingsScope *scope ) { static SampleValues emptyDefault; - if (!scope->voltage[channel].used || !result->data(channel)) return emptyDefault; - return result->data(channel)->voltage; + if ( !scope->voltage[ channel ].used || !result->data( channel ) ) + return emptyDefault; + return result->data( channel )->voltage; } -GraphGenerator::GraphGenerator(const DsoSettingsScope *scope /*, const DsoSettingsView *view */) : scope(scope) /*, view(view) */{ +GraphGenerator::GraphGenerator( const DsoSettingsScope *scope /*, const DsoSettingsView *view */ ) + : scope( scope ) /*, view(view) */ { // printf( "GraphGenerator::GraphGenerator()\n" ); } -void GraphGenerator::process(PPresult *data) { - //printf( "GraphGenerator::process()\n" ); - if (scope->horizontal.format == Dso::GraphFormat::TY) { +void GraphGenerator::process( PPresult *data ) { + // printf( "GraphGenerator::process()\n" ); + if ( scope->horizontal.format == Dso::GraphFormat::TY ) { ready = true; - generateGraphsTYvoltage(data); - generateGraphsTYspectrum(data); + generateGraphsTYvoltage( data ); + generateGraphsTYspectrum( data ); } else - generateGraphsXY(data); + generateGraphsXY( data ); } -void GraphGenerator::generateGraphsTYvoltage(PPresult *result) { - //printf( "GraphGenerator::generateGraphsTYvoltage()\n" ); - result->vaChannelVoltage.resize(scope->voltage.size()); - result->vaChannelHistogram.resize(scope->voltage.size()); - for (ChannelID channel = 0; channel < scope->voltage.size(); ++channel) { - ChannelGraph &graphVoltage = result->vaChannelVoltage[channel]; - ChannelGraph &graphHistogram = result->vaChannelHistogram[channel]; - const SampleValues &samples = useVoltSamplesOf(channel, result, scope); +void GraphGenerator::generateGraphsTYvoltage( PPresult *result ) { + // printf( "GraphGenerator::generateGraphsTYvoltage()\n" ); + result->vaChannelVoltage.resize( scope->voltage.size() ); + result->vaChannelHistogram.resize( scope->voltage.size() ); + for ( ChannelID channel = 0; channel < scope->voltage.size(); ++channel ) { + ChannelGraph &graphVoltage = result->vaChannelVoltage[ channel ]; + ChannelGraph &graphHistogram = result->vaChannelHistogram[ channel ]; + const SampleValues &samples = useVoltSamplesOf( channel, result, scope ); // Check if this channel is used and available at the data analyzer - if (samples.sample.empty()) { + if ( samples.sample.empty() ) { // Delete all vector arrays graphVoltage.clear(); graphHistogram.clear(); @@ -64,19 +67,19 @@ void GraphGenerator::generateGraphsTYvoltage(PPresult *result) { } // time distance between sampling points - double horizontalFactor = (samples.interval / scope->horizontal.timebase); + double horizontalFactor = ( samples.interval / scope->horizontal.timebase ); // printf( "hF: %g\n", horizontalFactor ); unsigned dotsOnScreen = unsigned( ceil( DIVS_TIME / horizontalFactor ) ); - unsigned preTrigSamples = unsigned(scope->trigger.offset * dotsOnScreen); + unsigned preTrigSamples = unsigned( scope->trigger.offset * dotsOnScreen ); // align displayed trace with trigger mark on screen ... // ... also if trig pos or time/div was changed on a "frozen" or single trace - int leftmostSample = int( result->triggeredPosition); - if ( leftmostSample ) // adjust position if triggered, else start from sample[0] - leftmostSample -= preTrigSamples; // shift samples to show a stable trace - int leftmostPosition = 0; // start position on display - if ( leftmostSample < 0 ) { // trig pos or time/div was increased + int leftmostSample = int( result->triggeredPosition ); + if ( leftmostSample ) // adjust position if triggered, else start from sample[0] + leftmostSample -= preTrigSamples; // shift samples to show a stable trace + int leftmostPosition = 0; // start position on display + if ( leftmostSample < 0 ) { // trig pos or time/div was increased leftmostPosition = -leftmostSample; // trace can't start on left margin - leftmostSample = 0; // show as much as we have on left side + leftmostSample = 0; // show as much as we have on left side } const unsigned binsPerDiv = 50; @@ -85,33 +88,33 @@ void GraphGenerator::generateGraphsTYvoltage(PPresult *result) { graphVoltage.reserve( ++dotsOnScreen ); graphHistogram.reserve( int( 2 * ( binsPerDiv * DIVS_VOLTAGE ) ) ); - const double gain = scope->gain(channel); - const double offset = scope->voltage[channel].offset; + const double gain = scope->gain( channel ); + const double offset = scope->voltage[ channel ].offset; auto sampleIterator = samples.sample.cbegin() + leftmostSample; // -> visible samples auto sampleEnd = samples.sample.cend(); // printf("samples: %lu, dotsOnScreen: %d\n", samples.sample.size(), dotsOnScreen); - graphVoltage.clear(); // remove all previous dots and fill in new trace + graphVoltage.clear(); // remove all previous dots and fill in new trace graphHistogram.clear(); // remove all previous dots and fill in new trace - unsigned bins[ int( binsPerDiv * DIVS_VOLTAGE ) ] = { 0 }; - for (unsigned int position = unsigned(leftmostPosition); - position < dotsOnScreen && sampleIterator < sampleEnd; - ++position, ++sampleIterator) { + unsigned bins[ int( binsPerDiv * DIVS_VOLTAGE ) ] = {0}; + for ( unsigned int position = unsigned( leftmostPosition ); + position < dotsOnScreen && sampleIterator < sampleEnd; ++position, ++sampleIterator ) { double x = double( MARGIN_LEFT + position * horizontalFactor ); double y = *sampleIterator / gain + offset; if ( !scope->histogram ) { // show complete trace - graphVoltage.push_back(QVector3D( float( x ), float( y ), 0.0f )); + graphVoltage.push_back( QVector3D( float( x ), float( y ), 0.0f ) ); } else { // histogram replaces trace in rightmost div - int bin = int( round( binsPerDiv * ( y + DIVS_VOLTAGE / 2) ) ); + int bin = int( round( binsPerDiv * ( y + DIVS_VOLTAGE / 2 ) ) ); if ( bin > 0 && bin < binsPerDiv * DIVS_VOLTAGE ) // if trace is on screen - ++bins[ bin ]; // count value - if ( x < MARGIN_RIGHT - 1.1 ) { // show trace unless in last div + 10% margin - graphVoltage.push_back(QVector3D( float( x ), float( y ), 0.0f )); + ++bins[ bin ]; // count value + if ( x < MARGIN_RIGHT - 1.1 ) { // show trace unless in last div + 10% margin + graphVoltage.push_back( QVector3D( float( x ), float( y ), 0.0f ) ); } } } - if ( (scope->horizontal.format == Dso::GraphFormat::TY) && scope->histogram ) { // scale and display the histogram - double max = 0; // find max histo count + if ( ( scope->horizontal.format == Dso::GraphFormat::TY ) && + scope->histogram ) { // scale and display the histogram + double max = 0; // find max histo count for ( int bin = 0; bin < binsPerDiv * DIVS_VOLTAGE; ++bin ) { if ( bins[ bin ] > max ) { max = bins[ bin ]; @@ -129,16 +132,16 @@ void GraphGenerator::generateGraphsTYvoltage(PPresult *result) { } -void GraphGenerator::generateGraphsTYspectrum(PPresult *result) { - //printf( "GraphGenerator::generateGraphsTYspectrum()\n" ); +void GraphGenerator::generateGraphsTYspectrum( PPresult *result ) { + // printf( "GraphGenerator::generateGraphsTYspectrum()\n" ); ready = true; - result->vaChannelSpectrum.resize(scope->spectrum.size()); - for (ChannelID channel = 0; channel < scope->voltage.size(); ++channel) { - ChannelGraph &graphSpectrum = result->vaChannelSpectrum[channel]; - const SampleValues &samples = useSpecSamplesOf(channel, result, scope); + result->vaChannelSpectrum.resize( scope->spectrum.size() ); + for ( ChannelID channel = 0; channel < scope->voltage.size(); ++channel ) { + ChannelGraph &graphSpectrum = result->vaChannelSpectrum[ channel ]; + const SampleValues &samples = useSpecSamplesOf( channel, result, scope ); // Check if this channel is used and available at the data analyzer - if (samples.sample.empty()) { + if ( samples.sample.empty() ) { // Delete all vector arrays graphSpectrum.clear(); continue; @@ -148,30 +151,31 @@ void GraphGenerator::generateGraphsTYspectrum(PPresult *result) { size_t neededSize = sampleCount * 2; // Set size directly to avoid reallocations - graphSpectrum.reserve(neededSize); + graphSpectrum.reserve( neededSize ); // What's the horizontal distance between sampling points? double horizontalFactor = samples.interval / scope->horizontal.frequencybase; // Fill vector array std::vector::const_iterator dataIterator = samples.sample.begin(); - const double magnitude = scope->spectrum[channel].magnitude; - const double offset = scope->spectrum[channel].offset; + const double magnitude = scope->spectrum[ channel ].magnitude; + const double offset = scope->spectrum[ channel ].offset; - for (unsigned int position = 0; position < sampleCount; ++position) { + for ( unsigned int position = 0; position < sampleCount; ++position ) { graphSpectrum.push_back( QVector3D( float( position * horizontalFactor - DIVS_TIME / 2 ), - float( *(dataIterator++) / magnitude + offset), 0.0f ) ); + float( *( dataIterator++ ) / magnitude + offset ), 0.0f ) ); } } } -void GraphGenerator::generateGraphsXY(PPresult *result) { - //puts("generateGraphXY()"); +void GraphGenerator::generateGraphsXY( PPresult *result ) { + // puts("generateGraphXY()"); result->vaChannelVoltage.resize( scope->voltage.size() ); // Delete all spectrum graphs - for ( ChannelGraph &data : result->vaChannelSpectrum ) data.clear(); + for ( ChannelGraph &data : result->vaChannelSpectrum ) + data.clear(); // Generate voltage graphs for pairs of channels for ( ChannelID channel = 0; channel < scope->voltage.size(); channel += 2 ) { @@ -208,8 +212,8 @@ void GraphGenerator::generateGraphsXY(PPresult *result) { const double yOffset = scope->voltage[ yChannel ].offset; for ( unsigned int position = 0; position < sampleCount; ++position ) { - graphXY.push_back(QVector3D( float( *( xIterator++ ) / xGain + xOffset ), - float( *( yIterator++ ) / yGain + yOffset ), 0.0 ) ); + graphXY.push_back( QVector3D( float( *( xIterator++ ) / xGain + xOffset ), + float( *( yIterator++ ) / yGain + yOffset ), 0.0 ) ); } } } diff --git a/openhantek/src/post/graphgenerator.h b/openhantek/src/post/graphgenerator.h index 2e8dba87..fb21d08a 100644 --- a/openhantek/src/post/graphgenerator.h +++ b/openhantek/src/post/graphgenerator.h @@ -23,15 +23,15 @@ class GraphGenerator : public QObject, public Processor { Q_OBJECT public: - GraphGenerator(const DsoSettingsScope *scope ); + GraphGenerator( const DsoSettingsScope *scope ); private: - void generateGraphsTYvoltage(PPresult *result); - void generateGraphsTYspectrum(PPresult *result); - void generateGraphsXY(PPresult *result); + void generateGraphsTYvoltage( PPresult *result ); + void generateGraphsTYspectrum( PPresult *result ); + void generateGraphsXY( PPresult *result ); bool ready = false; const DsoSettingsScope *scope; // Processor interface - void process(PPresult *data) override; + void process( PPresult *data ) override; }; diff --git a/openhantek/src/post/mathchannelgenerator.cpp b/openhantek/src/post/mathchannelgenerator.cpp index 6098c9ad..bb25c42b 100644 --- a/openhantek/src/post/mathchannelgenerator.cpp +++ b/openhantek/src/post/mathchannelgenerator.cpp @@ -1,66 +1,67 @@ // SPDX-License-Identifier: GPL-2.0+ #include "mathchannelgenerator.h" -#include "scopesettings.h" -#include "post/postprocessingsettings.h" #include "enums.h" +#include "post/postprocessingsettings.h" +#include "scopesettings.h" -MathChannelGenerator::MathChannelGenerator(const DsoSettingsScope *scope, unsigned physicalChannels) - : physicalChannels(physicalChannels), scope(scope) {} +MathChannelGenerator::MathChannelGenerator( const DsoSettingsScope *scope, unsigned physicalChannels ) + : physicalChannels( physicalChannels ), scope( scope ) {} MathChannelGenerator::~MathChannelGenerator() {} -void MathChannelGenerator::process(PPresult *result) { - //printf( "MathChannelGenerator::process\n" ); +void MathChannelGenerator::process( PPresult *result ) { + // printf( "MathChannelGenerator::process\n" ); // Math channel enabled? - if (!scope->voltage[physicalChannels].used && !scope->spectrum[physicalChannels].used) + if ( !scope->voltage[ physicalChannels ].used && !scope->spectrum[ physicalChannels ].used ) return; - DataChannel *const channelData = result->modifyData(physicalChannels); + DataChannel *const channelData = result->modifyData( physicalChannels ); std::vector &resultData = channelData->voltage.sample; - const double sign = scope->voltage[physicalChannels].inverted ? -1.0 : 1.0; + const double sign = scope->voltage[ physicalChannels ].inverted ? -1.0 : 1.0; - if ( Dso::getMathMode( scope->voltage[physicalChannels] ) < Dso::MathMode::AC_CH1 ) { // binary operations - if ( result->data(0)->voltage.sample.empty() || result->data(1)->voltage.sample.empty() ) + if ( Dso::getMathMode( scope->voltage[ physicalChannels ] ) < Dso::MathMode::AC_CH1 ) { // binary operations + if ( result->data( 0 )->voltage.sample.empty() || result->data( 1 )->voltage.sample.empty() ) return; // Resize the sample vector - resultData.resize(std::min(result->data(0)->voltage.sample.size(), result->data(1)->voltage.sample.size())); + resultData.resize( + std::min( result->data( 0 )->voltage.sample.size(), result->data( 1 )->voltage.sample.size() ) ); // Set sampling interval - channelData->voltage.interval = result->data(0)->voltage.interval; + channelData->voltage.interval = result->data( 0 )->voltage.interval; // Calculate values and write them into the sample buffer - std::vector::const_iterator ch1Iterator = result->data(0)->voltage.sample.begin(); - std::vector::const_iterator ch2Iterator = result->data(1)->voltage.sample.begin(); - double (*calculate)( double, double ); + std::vector::const_iterator ch1Iterator = result->data( 0 )->voltage.sample.begin(); + std::vector::const_iterator ch2Iterator = result->data( 1 )->voltage.sample.begin(); + double ( *calculate )( double, double ); - switch (Dso::getMathMode(scope->voltage[physicalChannels])) { - case Dso::MathMode::ADD_CH1_CH2: - calculate = []( double val1, double val2 ) -> double { return val1 + val2; }; - break; - case Dso::MathMode::SUB_CH2_FROM_CH1: - calculate = []( double val1, double val2 ) -> double { return val1 - val2; }; - break; - case Dso::MathMode::SUB_CH1_FROM_CH2: - calculate = []( double val1, double val2 ) -> double { return val2 - val1; }; - break; - case Dso::MathMode::MUL_CH1_CH2: - // multiply e.g. voltage and current (measured with a 1 ohm shunt) to get momentary power - calculate = []( double val1, double val2 ) -> double { return val1 * val2; }; - break; - default: - calculate = []( double, double ) -> double { return 0.0; }; - break; + switch ( Dso::getMathMode( scope->voltage[ physicalChannels ] ) ) { + case Dso::MathMode::ADD_CH1_CH2: + calculate = []( double val1, double val2 ) -> double { return val1 + val2; }; + break; + case Dso::MathMode::SUB_CH2_FROM_CH1: + calculate = []( double val1, double val2 ) -> double { return val1 - val2; }; + break; + case Dso::MathMode::SUB_CH1_FROM_CH2: + calculate = []( double val1, double val2 ) -> double { return val2 - val1; }; + break; + case Dso::MathMode::MUL_CH1_CH2: + // multiply e.g. voltage and current (measured with a 1 ohm shunt) to get momentary power + calculate = []( double val1, double val2 ) -> double { return val1 * val2; }; + break; + default: + calculate = []( double, double ) -> double { return 0.0; }; + break; } - for (auto it = resultData.begin(), end = resultData.end(); it != end; ++it) { + for ( auto it = resultData.begin(), end = resultData.end(); it != end; ++it ) { *it = sign * calculate( *ch1Iterator++, *ch2Iterator++ ); } } else { // unary operators (calculate "AC coupling") unsigned src = 0; - if ( Dso::getMathMode( scope->voltage[physicalChannels] ) == Dso::MathMode::AC_CH1 ) + if ( Dso::getMathMode( scope->voltage[ physicalChannels ] ) == Dso::MathMode::AC_CH1 ) src = 0; - else if ( Dso::getMathMode( scope->voltage[physicalChannels] ) == Dso::MathMode::AC_CH2 ) + else if ( Dso::getMathMode( scope->voltage[ physicalChannels ] ) == Dso::MathMode::AC_CH2 ) src = 1; // Resize the sample vector @@ -71,7 +72,7 @@ void MathChannelGenerator::process(PPresult *result) { // calculate DC component of channel... double average = 0; for ( auto srcIt = result->data( src )->voltage.sample.begin(), - srcEnd = result->data( src )->voltage.sample.end(); + srcEnd = result->data( src )->voltage.sample.end(); srcIt != srcEnd; ++srcIt ) { average += *srcIt; } @@ -79,8 +80,7 @@ void MathChannelGenerator::process(PPresult *result) { // ... and remove DC component to get AC auto srcIt = result->data( src )->voltage.sample.begin(); - for ( auto dstIt = resultData.begin(), dstEnd = resultData.end(); - dstIt != dstEnd; ++srcIt, ++dstIt ) { + for ( auto dstIt = resultData.begin(), dstEnd = resultData.end(); dstIt != dstEnd; ++srcIt, ++dstIt ) { *dstIt = sign * ( *srcIt - average ); } } diff --git a/openhantek/src/post/mathchannelgenerator.h b/openhantek/src/post/mathchannelgenerator.h index f3a9d275..3ddc60b5 100644 --- a/openhantek/src/post/mathchannelgenerator.h +++ b/openhantek/src/post/mathchannelgenerator.h @@ -7,13 +7,13 @@ struct DsoSettingsScope; class PPresult; -class MathChannelGenerator : public Processor -{ -public: - MathChannelGenerator(const DsoSettingsScope *scope, unsigned physicalChannels); +class MathChannelGenerator : public Processor { + public: + MathChannelGenerator( const DsoSettingsScope *scope, unsigned physicalChannels ); virtual ~MathChannelGenerator(); - void process(PPresult *) override; -private: + void process( PPresult * ) override; + + private: const unsigned physicalChannels; const DsoSettingsScope *scope; }; diff --git a/openhantek/src/post/postprocessing.cpp b/openhantek/src/post/postprocessing.cpp index 6f7d6d21..4c2326a8 100644 --- a/openhantek/src/post/postprocessing.cpp +++ b/openhantek/src/post/postprocessing.cpp @@ -2,15 +2,15 @@ #include "postprocessing.h" -PostProcessing::PostProcessing(unsigned channelCount) : channelCount(channelCount) { +PostProcessing::PostProcessing( unsigned channelCount ) : channelCount( channelCount ) { qRegisterMetaType>(); } -void PostProcessing::registerProcessor(Processor *processor) { processors.push_back(processor); } +void PostProcessing::registerProcessor( Processor *processor ) { processors.push_back( processor ); } -void PostProcessing::convertData(const DSOsamples *source, PPresult *destination) { - //printf( "PostProcessing::convertData()\n" ); - QReadLocker locker(&source->lock); +void PostProcessing::convertData( const DSOsamples *source, PPresult *destination ) { + // printf( "PostProcessing::convertData()\n" ); + QReadLocker locker( &source->lock ); if ( source->triggerPosition ) { destination->softwareTriggerTriggered = source->liveTrigger; destination->triggeredPosition = source->triggerPosition; @@ -23,24 +23,26 @@ void PostProcessing::convertData(const DSOsamples *source, PPresult *destination destination->pulseWidth2 = 0; } - for (ChannelID channel = 0; channel < source->data.size(); ++channel) { - const std::vector &rawChannelData = source->data.at(channel); + for ( ChannelID channel = 0; channel < source->data.size(); ++channel ) { + const std::vector &rawChannelData = source->data.at( channel ); - if (rawChannelData.empty()) { continue; } - DataChannel *const channelData = destination->modifyData(channel); + if ( rawChannelData.empty() ) { + continue; + } + DataChannel *const channelData = destination->modifyData( channel ); channelData->voltage.interval = 1.0 / source->samplerate; channelData->voltage.sample = rawChannelData; - //printf( "PP CH%d: %d\n", channel+1, source->clipped ); - channelData->valid = ! ( source->clipped & (0x01 << channel) ); + // printf( "PP CH%d: %d\n", channel+1, source->clipped ); + channelData->valid = !( source->clipped & ( 0x01 << channel ) ); } } -void PostProcessing::input(const DSOsamples *data) { +void PostProcessing::input( const DSOsamples *data ) { // printf( "PostProcessing::input()\n" ); - currentData.reset(new PPresult(channelCount)); - convertData(data, currentData.get()); - for (Processor *p : processors) - p->process(currentData.get()); - std::shared_ptr res = std::move(currentData); - emit processingFinished(res); + currentData.reset( new PPresult( channelCount ) ); + convertData( data, currentData.get() ); + for ( Processor *p : processors ) + p->process( currentData.get() ); + std::shared_ptr res = std::move( currentData ); + emit processingFinished( res ); } diff --git a/openhantek/src/post/postprocessing.h b/openhantek/src/post/postprocessing.h index 8a329ade..094a4a35 100644 --- a/openhantek/src/post/postprocessing.h +++ b/openhantek/src/post/postprocessing.h @@ -28,7 +28,7 @@ class PostProcessing : public QObject { * of the processors. * @param processor */ - void registerProcessor(Processor *processor); + void registerProcessor( Processor *processor ); private: @@ -38,7 +38,7 @@ class PostProcessing : public QObject { std::vector processors; /// std::unique_ptr currentData; - static void convertData(const DSOsamples *source, PPresult *destination); + static void convertData( const DSOsamples *source, PPresult *destination ); public slots: /** @@ -46,10 +46,10 @@ class PostProcessing : public QObject { * this class object into another thread. * @param data */ - void input(const DSOsamples *data); + void input( const DSOsamples *data ); -signals: - void processingFinished(std::shared_ptr result); + signals: + void processingFinished( std::shared_ptr result ); }; -Q_DECLARE_METATYPE(std::shared_ptr) +Q_DECLARE_METATYPE( std::shared_ptr ) diff --git a/openhantek/src/post/postprocessingsettings.cpp b/openhantek/src/post/postprocessingsettings.cpp index b4087bd9..648628e1 100644 --- a/openhantek/src/post/postprocessingsettings.cpp +++ b/openhantek/src/post/postprocessingsettings.cpp @@ -13,20 +13,20 @@ Enum MathModeEnum; -template -inline MathMode getMathMode(T& t) { return MathMode(t.couplingOrMathIndex); } +template inline MathMode getMathMode( T &t ) { return MathMode( t.couplingOrMathIndex ); } /// \enum WindowFunction /// \brief The supported window functions. @@ -37,15 +36,15 @@ enum class WindowFunction : int { }; extern Enum WindowFunctionEnum; -QString mathModeString(MathMode mode); +QString mathModeString( MathMode mode ); // QString windowFunctionString(WindowFunction window); -} +} // namespace Dso -Q_DECLARE_METATYPE(Dso::MathMode) -Q_DECLARE_METATYPE(Dso::WindowFunction) +Q_DECLARE_METATYPE( Dso::MathMode ) +Q_DECLARE_METATYPE( Dso::WindowFunction ) struct DsoSettingsPostProcessing { Dso::WindowFunction spectrumWindow = Dso::WindowFunction::HAMMING; ///< Window function for DFT - double spectrumReference = 0.0; ///< Reference level for spectrum in dBu + double spectrumReference = 0.0; ///< Reference level for spectrum in dBu double spectrumLimit = -60.0; ///< Minimum magnitude of the spectrum (Avoids peaks) }; diff --git a/openhantek/src/post/ppresult.cpp b/openhantek/src/post/ppresult.cpp index de556b3b..e9ad8869 100644 --- a/openhantek/src/post/ppresult.cpp +++ b/openhantek/src/post/ppresult.cpp @@ -4,16 +4,16 @@ #include #include -PPresult::PPresult(unsigned int channelCount) { analyzedData.resize(channelCount); } +PPresult::PPresult( unsigned int channelCount ) { analyzedData.resize( channelCount ); } -const DataChannel *PPresult::data(ChannelID channel) const { - if (channel >= this->analyzedData.size()) +const DataChannel *PPresult::data( ChannelID channel ) const { + if ( channel >= this->analyzedData.size() ) return nullptr; - return &this->analyzedData[channel]; + return &this->analyzedData[ channel ]; } -DataChannel *PPresult::modifyData(ChannelID channel) { return &this->analyzedData[channel]; } +DataChannel *PPresult::modifyData( ChannelID channel ) { return &this->analyzedData[ channel ]; } -unsigned int PPresult::sampleCount() const { return unsigned(analyzedData[0].voltage.sample.size()); } +unsigned int PPresult::sampleCount() const { return unsigned( analyzedData[ 0 ].voltage.sample.size() ); } -unsigned int PPresult::channelCount() const { return unsigned(analyzedData.size()); } +unsigned int PPresult::channelCount() const { return unsigned( analyzedData.size() ); } diff --git a/openhantek/src/post/ppresult.h b/openhantek/src/post/ppresult.h index afdaebd2..bdb6ce18 100644 --- a/openhantek/src/post/ppresult.h +++ b/openhantek/src/post/ppresult.h @@ -2,11 +2,11 @@ #pragma once -#include #include +#include -#include #include "hantekprotocol/types.h" +#include /// \brief Struct for a array of sample values. struct SampleValues { @@ -16,17 +16,17 @@ struct SampleValues { /// \brief Struct for the analyzed data. struct DataChannel { - SampleValues voltage; ///< The time-domain voltage levels (V) - SampleValues spectrum; ///< The frequency-domain power levels (dB) - bool valid = true; ///< Not clipped, distorted, dropouts etc. - double vpp = 0.0; ///< The peak-to-peak voltage of the _displayed_ part of trace - double rms = 0.0; ///< The DC + AC rms value of the signal = sqrt( dc * dc + acc * ac ) - double dc = 0.0; ///< The DC bias of the signal - double ac = 0.0; ///< The AC rms value of the signal - double dB = 0.0; ///< The AC rms value as dB (dBV or other depending on config) - double frequency = 0.0; ///< The frequency of the signal - double pulseWidth1 = 0.0;///< The width of the triggered pulse - double pulseWidth2 = 0.0;///< The width of the following pulse + SampleValues voltage; ///< The time-domain voltage levels (V) + SampleValues spectrum; ///< The frequency-domain power levels (dB) + bool valid = true; ///< Not clipped, distorted, dropouts etc. + double vpp = 0.0; ///< The peak-to-peak voltage of the _displayed_ part of trace + double rms = 0.0; ///< The DC + AC rms value of the signal = sqrt( dc * dc + acc * ac ) + double dc = 0.0; ///< The DC bias of the signal + double ac = 0.0; ///< The AC rms value of the signal + double dB = 0.0; ///< The AC rms value as dB (dBV or other depending on config) + double frequency = 0.0; ///< The frequency of the signal + double pulseWidth1 = 0.0; ///< The width of the triggered pulse + double pulseWidth2 = 0.0; ///< The width of the following pulse }; typedef std::vector ChannelGraph; @@ -35,14 +35,14 @@ typedef std::vector ChannelsGraphs; /// Post processing results class PPresult { public: - explicit PPresult(unsigned int channelCount); + explicit PPresult( unsigned int channelCount ); /// \brief Returns the analyzed data. /// \param channel Channel, whose data should be returned. - const DataChannel *data(ChannelID channel) const; + const DataChannel *data( ChannelID channel ) const; /// \brief Returns the analyzed data. The data structure can be modifed. /// \param channel Channel, whose data should be returned. - DataChannel *modifyData(ChannelID channel); + DataChannel *modifyData( ChannelID channel ); /// \return The maximum sample count of the last analyzed data. This assumes there is at least one channel. unsigned int sampleCount() const; unsigned int channelCount() const; @@ -50,9 +50,9 @@ class PPresult { /// sw trigger status bool softwareTriggerTriggered = false; /// skip samples at start of channel to get triggered trace on screen - unsigned triggeredPosition = 0;///< Not triggered - double pulseWidth1 = 0.0;///< The width of the triggered pulse - double pulseWidth2 = 0.0;///< The width of the following pulse + unsigned triggeredPosition = 0; ///< Not triggered + double pulseWidth1 = 0.0; ///< The width of the triggered pulse + double pulseWidth2 = 0.0; ///< The width of the following pulse ChannelsGraphs vaChannelSpectrum; ChannelsGraphs vaChannelVoltage; diff --git a/openhantek/src/post/processor.h b/openhantek/src/post/processor.h index 73168c94..547975d2 100644 --- a/openhantek/src/post/processor.h +++ b/openhantek/src/post/processor.h @@ -5,6 +5,6 @@ #include "ppresult.h" class Processor { -public: - virtual void process(PPresult*) = 0; + public: + virtual void process( PPresult * ) = 0; }; diff --git a/openhantek/src/post/spectrumgenerator.cpp b/openhantek/src/post/spectrumgenerator.cpp index cd79333e..204da7b7 100644 --- a/openhantek/src/post/spectrumgenerator.cpp +++ b/openhantek/src/post/spectrumgenerator.cpp @@ -7,31 +7,32 @@ #include #include -#include #include "ppresult.h" #include "spectrumgenerator.h" +#include #include "dsosettings.h" #include "utils/printutils.h" #include "viewconstants.h" /// \brief Analyzes the data from the dso. -SpectrumGenerator::SpectrumGenerator(const DsoSettingsScope *scope, const DsoSettingsPostProcessing *postprocessing) - : scope(scope), postprocessing(postprocessing) {} +SpectrumGenerator::SpectrumGenerator( const DsoSettingsScope *scope, const DsoSettingsPostProcessing *postprocessing ) + : scope( scope ), postprocessing( postprocessing ) {} SpectrumGenerator::~SpectrumGenerator() { - if (lastWindowBuffer) fftw_free(lastWindowBuffer); + if ( lastWindowBuffer ) + fftw_free( lastWindowBuffer ); } -void SpectrumGenerator::process(PPresult *result) { +void SpectrumGenerator::process( PPresult *result ) { // Calculate frequencies and spectrums - for (ChannelID channel = 0; channel < result->channelCount(); ++channel) { - DataChannel *const channelData = result->modifyData(channel); + for ( ChannelID channel = 0; channel < result->channelCount(); ++channel ) { + DataChannel *const channelData = result->modifyData( channel ); - if (channelData->voltage.sample.empty()) { + if ( channelData->voltage.sample.empty() ) { // Clear unused channels channelData->spectrum.interval = 0; channelData->spectrum.sample.clear(); @@ -40,67 +41,71 @@ void SpectrumGenerator::process(PPresult *result) { // Calculate new window // scale all windows to display 1 Veff as 0 dBu reference level. size_t sampleCount = channelData->voltage.sample.size(); - if (!lastWindowBuffer || lastWindow != postprocessing->spectrumWindow || lastRecordLength != sampleCount) { - if (lastWindowBuffer) fftw_free(lastWindowBuffer); - lastWindowBuffer = fftw_alloc_real(sampleCount); - lastRecordLength = unsigned(sampleCount); + if ( !lastWindowBuffer || lastWindow != postprocessing->spectrumWindow || lastRecordLength != sampleCount ) { + if ( lastWindowBuffer ) + fftw_free( lastWindowBuffer ); + lastWindowBuffer = fftw_alloc_real( sampleCount ); + lastRecordLength = unsigned( sampleCount ); unsigned int windowEnd = lastRecordLength - 1; lastWindow = postprocessing->spectrumWindow; - double weight = 0.0; //calculate area under window fkt - switch (postprocessing->spectrumWindow) { + double weight = 0.0; // calculate area under window fkt + switch ( postprocessing->spectrumWindow ) { case Dso::WindowFunction::HAMMING: - for (unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition) - weight += *(lastWindowBuffer + windowPosition) = 0.54 - 0.46 * cos( 2.0 * M_PI * windowPosition / windowEnd ); + for ( unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition ) + weight += *( lastWindowBuffer + windowPosition ) = + 0.54 - 0.46 * cos( 2.0 * M_PI * windowPosition / windowEnd ); break; case Dso::WindowFunction::HANN: - for (unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition) - weight += *(lastWindowBuffer + windowPosition) = 0.5 * ( 1.0 - cos( 2.0 * M_PI * windowPosition / windowEnd ) ); + for ( unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition ) + weight += *( lastWindowBuffer + windowPosition ) = + 0.5 * ( 1.0 - cos( 2.0 * M_PI * windowPosition / windowEnd ) ); break; case Dso::WindowFunction::COSINE: - for (unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition) - weight += *(lastWindowBuffer + windowPosition) = sin( M_PI * windowPosition / windowEnd ); + for ( unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition ) + weight += *( lastWindowBuffer + windowPosition ) = sin( M_PI * windowPosition / windowEnd ); break; case Dso::WindowFunction::LANCZOS: - for (unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition) { - double sincParameter = (2.0 * windowPosition / windowEnd - 1.0) * M_PI; - if (sincParameter == 0) - weight += *(lastWindowBuffer + windowPosition) = 1; + for ( unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition ) { + double sincParameter = ( 2.0 * windowPosition / windowEnd - 1.0 ) * M_PI; + if ( sincParameter == 0 ) + weight += *( lastWindowBuffer + windowPosition ) = 1; else - weight += *(lastWindowBuffer + windowPosition) = sin( sincParameter ) / sincParameter; + weight += *( lastWindowBuffer + windowPosition ) = sin( sincParameter ) / sincParameter; } break; case Dso::WindowFunction::BARTLETT: - for (unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition) - weight += *(lastWindowBuffer + windowPosition) = - 2.0 / windowEnd * (windowEnd / 2 - std::abs( double( windowPosition - windowEnd / 2.0 ) ) ); + for ( unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition ) + weight += *( lastWindowBuffer + windowPosition ) = + 2.0 / windowEnd * ( windowEnd / 2 - std::abs( double( windowPosition - windowEnd / 2.0 ) ) ); break; case Dso::WindowFunction::TRIANGULAR: - for (unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition) - weight += *(lastWindowBuffer + windowPosition) = + for ( unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition ) + weight += *( lastWindowBuffer + windowPosition ) = 2.0 / lastRecordLength * - (lastRecordLength / 2 - std::abs( double(windowPosition - windowEnd / 2.0 ) ) ); + ( lastRecordLength / 2 - std::abs( double( windowPosition - windowEnd / 2.0 ) ) ); break; case Dso::WindowFunction::GAUSS: { const double sigma = 0.5; - for (unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition) { - double w = ( double( windowPosition ) - lastRecordLength / 2.0 ) / ( sigma * lastRecordLength / 2.0 ); + for ( unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition ) { + double w = + ( double( windowPosition ) - lastRecordLength / 2.0 ) / ( sigma * lastRecordLength / 2.0 ); w *= w; - weight += *(lastWindowBuffer + windowPosition) = exp( -w ); + weight += *( lastWindowBuffer + windowPosition ) = exp( -w ); } } break; case Dso::WindowFunction::BARTLETTHANN: - for (unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition) - weight += *(lastWindowBuffer + windowPosition) = 0.62 - - 0.48 * std::abs( double( windowPosition / windowEnd - 0.5 ) ) - - 0.38 * cos( 2.0 * M_PI * windowPosition / windowEnd ); + for ( unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition ) + weight += *( lastWindowBuffer + windowPosition ) = + 0.62 - 0.48 * std::abs( double( windowPosition / windowEnd - 0.5 ) ) - + 0.38 * cos( 2.0 * M_PI * windowPosition / windowEnd ); break; case Dso::WindowFunction::BLACKMAN: { double alpha = 0.16; - for (unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition) - weight += *(lastWindowBuffer + windowPosition) = (1 - alpha) / 2 - - 0.5 * cos(2.0 * M_PI * windowPosition / windowEnd) + - alpha / 2 * cos(4.0 * M_PI * windowPosition / windowEnd); + for ( unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition ) + weight += *( lastWindowBuffer + windowPosition ) = + ( 1 - alpha ) / 2 - 0.5 * cos( 2.0 * M_PI * windowPosition / windowEnd ) + + alpha / 2 * cos( 4.0 * M_PI * windowPosition / windowEnd ); } break; // case Dso::WindowFunction::WINDOW_KAISER: // TODO WINDOW_KAISER @@ -110,48 +115,49 @@ void SpectrumGenerator::process(PPresult *result) { // weight += *(window + windowPosition) = ...; // break; case Dso::WindowFunction::NUTTALL: - for (unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition) - weight += *(lastWindowBuffer + windowPosition) = 0.355768 - - 0.487396 * cos(2 * M_PI * windowPosition / windowEnd) + - 0.144232 * cos(4 * M_PI * windowPosition / windowEnd) - - 0.012604 * cos(6 * M_PI * windowPosition / windowEnd); + for ( unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition ) + weight += *( lastWindowBuffer + windowPosition ) = + 0.355768 - 0.487396 * cos( 2 * M_PI * windowPosition / windowEnd ) + + 0.144232 * cos( 4 * M_PI * windowPosition / windowEnd ) - + 0.012604 * cos( 6 * M_PI * windowPosition / windowEnd ); break; case Dso::WindowFunction::BLACKMANHARRIS: - for (unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition) - weight += *(lastWindowBuffer + windowPosition) = 0.35875 - - 0.48829 * cos(2 * M_PI * windowPosition / windowEnd) + - 0.14128 * cos(4 * M_PI * windowPosition / windowEnd) - - 0.01168 * cos(6 * M_PI * windowPosition / windowEnd); + for ( unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition ) + weight += *( lastWindowBuffer + windowPosition ) = + 0.35875 - 0.48829 * cos( 2 * M_PI * windowPosition / windowEnd ) + + 0.14128 * cos( 4 * M_PI * windowPosition / windowEnd ) - + 0.01168 * cos( 6 * M_PI * windowPosition / windowEnd ); break; case Dso::WindowFunction::BLACKMANNUTTALL: - for (unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition) - weight += *(lastWindowBuffer + windowPosition) = 0.3635819 - - 0.4891775 * cos(2 * M_PI * windowPosition / windowEnd) + - 0.1365995 * cos(4 * M_PI * windowPosition / windowEnd) - - 0.0106411 * cos(6 * M_PI * windowPosition / windowEnd); + for ( unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition ) + weight += *( lastWindowBuffer + windowPosition ) = + 0.3635819 - 0.4891775 * cos( 2 * M_PI * windowPosition / windowEnd ) + + 0.1365995 * cos( 4 * M_PI * windowPosition / windowEnd ) - + 0.0106411 * cos( 6 * M_PI * windowPosition / windowEnd ); break; case Dso::WindowFunction::FLATTOP: // wikipedia.de - for (unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition) - weight += *(lastWindowBuffer + windowPosition) = 1.0 - 1.93 * cos(2 * M_PI * windowPosition / windowEnd) + - 1.29 * cos(4 * M_PI * windowPosition / windowEnd) - - 0.388 * cos(6 * M_PI * windowPosition / windowEnd) + - 0.028 * cos(8 * M_PI * windowPosition / windowEnd); + for ( unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition ) + weight += *( lastWindowBuffer + windowPosition ) = + 1.0 - 1.93 * cos( 2 * M_PI * windowPosition / windowEnd ) + + 1.29 * cos( 4 * M_PI * windowPosition / windowEnd ) - + 0.388 * cos( 6 * M_PI * windowPosition / windowEnd ) + + 0.028 * cos( 8 * M_PI * windowPosition / windowEnd ); break; default: // Dso::WINDOW_RECTANGULAR - for (unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition) - weight += *(lastWindowBuffer + windowPosition) = 1.0; + for ( unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition ) + weight += *( lastWindowBuffer + windowPosition ) = 1.0; } // weight is the area below the window function - weight = lastRecordLength / weight; //normalise all windows equal to the rectangular window + weight = lastRecordLength / weight; // normalise all windows equal to the rectangular window // DFT transforms a 1V sin(ωt) signal to 1 = 0 dB, RMS = 0.707 V = sqrt(0.5) V (-3dBV) // If we want to scale to 0 dBu = 0 dBm @ 600 Ω, RMS = 0.775V = sqrt(1 mW * 600 Ω) // we must scale by sqrt(0.5/0.6) = -2.2 dB - weight *= sqrt(0.5); // scale display to 0 dBV -> 1V RMS = 0dB + weight *= sqrt( 0.5 ); // scale display to 0 dBV -> 1V RMS = 0dB // printf( "window %u, weight %g\n", (unsigned)postprocessing->spectrumWindow, weight ); // scale the windowed samples - for (unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition) - *(lastWindowBuffer + windowPosition) *= weight; + for ( unsigned int windowPosition = 0; windowPosition < lastRecordLength; ++windowPosition ) + *( lastWindowBuffer + windowPosition ) *= weight; } // Set sampling interval @@ -161,40 +167,41 @@ void SpectrumGenerator::process(PPresult *result) { unsigned int dftLength = unsigned( sampleCount ) / 2; // Reallocate memory for samples if the sample count has changed - channelData->spectrum.sample.resize(sampleCount); + channelData->spectrum.sample.resize( sampleCount ); // Create sample buffer and apply window - std::unique_ptr windowedValues = std::unique_ptr(new double[sampleCount]); + std::unique_ptr windowedValues = std::unique_ptr( new double[ sampleCount ] ); // calculate the peak-to-peak value of the displayed part of trace double min = INT_MAX; double max = INT_MIN; // TODO: adapt triggerPosition (left = tP - preTrig; right = left + dotsOnScreen) - double horizontalFactor = result->data(channel)->voltage.interval / scope->horizontal.timebase; + double horizontalFactor = result->data( channel )->voltage.interval / scope->horizontal.timebase; unsigned dotsOnScreen = unsigned( DIVS_TIME / horizontalFactor + 0.99 ); // round up - unsigned preTrigSamples = unsigned(scope->trigger.offset * dotsOnScreen); - int left = int(result->triggeredPosition) - int(preTrigSamples); // 1st sample to show - int right = left + int(dotsOnScreen); // last sample to show - if ( left < 0 ) // trig pos or time/div was increased - left = 0; // show as much as we have on left side - //unsigned right = result->triggerPosition + DIVS_TIME * scope->horizontal.timebase / channelData->voltage.interval; + unsigned preTrigSamples = unsigned( scope->trigger.offset * dotsOnScreen ); + int left = int( result->triggeredPosition ) - int( preTrigSamples ); // 1st sample to show + int right = left + int( dotsOnScreen ); // last sample to show + if ( left < 0 ) // trig pos or time/div was increased + left = 0; // show as much as we have on left side + // unsigned right = result->triggerPosition + DIVS_TIME * scope->horizontal.timebase / + // channelData->voltage.interval; if ( right >= int( sampleCount ) ) right = int( sampleCount ) - 1; for ( int position = left; // left side of trace - position <= right; // right side - ++position ) { + position <= right; // right side + ++position ) { if ( channelData->voltage.sample[ unsigned( position ) ] < min ) min = channelData->voltage.sample[ unsigned( position ) ]; if ( channelData->voltage.sample[ unsigned( position ) ] > max ) max = channelData->voltage.sample[ unsigned( position ) ]; } channelData->vpp = max - min; - //printf( "dots = %d, Vpp = %g\n", dots, channelData->vpp ); + // printf( "dots = %d, Vpp = %g\n", dots, channelData->vpp ); // calculate the average value double dc = 0.0; auto voltageIterator = channelData->voltage.sample.begin(); - for (unsigned int position = 0; position < sampleCount; ++position) { + for ( unsigned int position = 0; position < sampleCount; ++position ) { dc += *voltageIterator++; } dc /= sampleCount; @@ -203,13 +210,13 @@ void SpectrumGenerator::process(PPresult *result) { // now strip DC bias, calculate rms of AC component and apply window for fft to AC component double ac2 = 0.0; voltageIterator = channelData->voltage.sample.begin(); - for (unsigned int position = 0; position < sampleCount; ++position) { + for ( unsigned int position = 0; position < sampleCount; ++position ) { double ac_sample = *voltageIterator++ - dc; ac2 += ac_sample * ac_sample; - windowedValues[position] = lastWindowBuffer[position] * ac_sample; + windowedValues[ position ] = lastWindowBuffer[ position ] * ac_sample; } ac2 /= sampleCount; - channelData->ac = sqrt( ac2 ); // rms of AC component + channelData->ac = sqrt( ac2 ); // rms of AC component channelData->rms = sqrt( dc * dc + ac2 ); // total rms = U eff channelData->dB = 10.0 * log10( ac2 ) - postprocessing->spectrumReference; channelData->pulseWidth1 = result->pulseWidth1; @@ -220,10 +227,10 @@ void SpectrumGenerator::process(PPresult *result) { /// \todo Reuse plan and use FFTW_MEASURE to get fastest algorithm fftw_plan fftPlan; - fftPlan = fftw_plan_r2r_1d(int( sampleCount ), windowedValues.get(), - &channelData->spectrum.sample.front(), FFTW_R2HC, FFTW_ESTIMATE); - fftw_execute(fftPlan); - fftw_destroy_plan(fftPlan); + fftPlan = fftw_plan_r2r_1d( int( sampleCount ), windowedValues.get(), &channelData->spectrum.sample.front(), + FFTW_R2HC, FFTW_ESTIMATE ); + fftw_execute( fftPlan ); + fftw_destroy_plan( fftPlan ); // Do an autocorrelation to get the frequency of the signal // fft: f(t) ⊶ F(ω); calculate power spectrum |F(ω)|² @@ -237,7 +244,7 @@ void SpectrumGenerator::process(PPresult *result) { // create a copy of powerSpectrum because hc2r iDFT destroys spectrum input const double norm = 1.0 / dftLength / dftLength; - std::unique_ptr powerSpectrum = std::move(windowedValues); + std::unique_ptr powerSpectrum = std::move( windowedValues ); unsigned int position; // correct the (half-)complex values in spectrum (1st part real forward), (2nd part imag backwards) -> magnitude @@ -257,17 +264,18 @@ void SpectrumGenerator::process(PPresult *result) { powerSpectrum[ position ] = *fwd * norm; ++fwd; // Complex values, all zero for autocorrelation - for (++position; position < sampleCount; ++position) { + for ( ++position; position < sampleCount; ++position ) { powerSpectrum[ position ] = 0; } // skip mirrored 2nd half of result spectrum channelData->spectrum.sample.resize( dftLength + 1 ); // Do half-complex to real inverse transformation -> autocorrelation - std::unique_ptr correlation = std::unique_ptr(new double[sampleCount]); - fftPlan = fftw_plan_r2r_1d( int( sampleCount ), powerSpectrum.get(), correlation.get(), FFTW_HC2R, FFTW_ESTIMATE ); - fftw_execute(fftPlan); - fftw_destroy_plan(fftPlan); + std::unique_ptr correlation = std::unique_ptr( new double[ sampleCount ] ); + fftPlan = + fftw_plan_r2r_1d( int( sampleCount ), powerSpectrum.get(), correlation.get(), FFTW_HC2R, FFTW_ESTIMATE ); + fftw_execute( fftPlan ); + fftw_destroy_plan( fftPlan ); // Get the frequency from the correlation results unsigned int peakCorrPos = 0; @@ -275,40 +283,40 @@ void SpectrumGenerator::process(PPresult *result) { double maxCorr = 0; unsigned maxCorrPos = 0; // search from right to left for a max and remember this if a following min corr (<0) is found - for ( position = unsigned( sampleCount ) / 2; position > 1; --position ) { // go down to get leftmost peak (= max freq) - if ( correlation[position] > maxCorr ) { // find (local) max - maxCorr = correlation[position]; + for ( position = unsigned( sampleCount ) / 2; position > 1; + --position ) { // go down to get leftmost peak (= max freq) + if ( correlation[ position ] > maxCorr ) { // find (local) max + maxCorr = correlation[ position ]; maxCorrPos = position; minCorr = 0; // reset minimum to start new min search // printf( "max %d: %g\n", position, maxCorr ); - } else if ( correlation[position] < minCorr ) { // search for local min - minCorr = correlation[position]; + } else if ( correlation[ position ] < minCorr ) { // search for local min + minCorr = correlation[ position ]; maxCorr = 0; // reset max to start new max seach peakCorrPos = maxCorrPos; // printf( "min %d: %g\n", position, minCorr ); } } - correlation.reset(nullptr); + correlation.reset( nullptr ); // Finally calculate the real spectrum (it's also used for frequency display) // Convert values into dB (Relative to the reference level 0 dBV = 1V eff) - double offset = - postprocessing->spectrumReference - 20 * log10(dftLength); + double offset = -postprocessing->spectrumReference - 20 * log10( dftLength ); double offsetLimit = postprocessing->spectrumLimit - postprocessing->spectrumReference; double peakSpectrum = offsetLimit; // get a start value for peak search - unsigned int peakFreqPos = 0; // initial position of max spectrum peak + unsigned int peakFreqPos = 0; // initial position of max spectrum peak position = 0; - for (auto spectrumIterator = channelData->spectrum.sample.begin(), - spectrumEnd = channelData->spectrum.sample.end(); - spectrumIterator != spectrumEnd; - ++spectrumIterator, ++position) { + for ( auto spectrumIterator = channelData->spectrum.sample.begin(), + spectrumEnd = channelData->spectrum.sample.end(); + spectrumIterator != spectrumEnd; ++spectrumIterator, ++position ) { // spectrum is power spectrum, but show amplitude spectrum -> 10 * log... double value = 10 * log10( *spectrumIterator ) + offset; // Check if this value has to be limited - if (value < offsetLimit) + if ( value < offsetLimit ) value = offsetLimit; *spectrumIterator = value; // detect frequency peak - if ( value > peakSpectrum ) { + if ( value > peakSpectrum ) { peakSpectrum = value; peakFreqPos = position; } @@ -317,11 +325,11 @@ void SpectrumGenerator::process(PPresult *result) { // Calculate both peak frequencies (correlation and spectrum) in Hz double pF = channelData->spectrum.interval * peakFreqPos; double pC = 1.0 / ( channelData->voltage.interval * peakCorrPos ); - //printf( "pF %u: %d %g\n", channel, peakFreqPos, pF ); - //printf( "pC %u: %d %g\n", channel, peakCorrPos, pC ); + // printf( "pF %u: %d %g\n", channel, peakFreqPos, pF ); + // printf( "pC %u: %d %g\n", channel, peakCorrPos, pC ); if ( peakFreqPos > peakCorrPos // use frequency result if it is more granular than correlation - || peakFreqPos > 100 // or at least if it is granular enough (+- 1% resolution) - || peakCorrPos < 100 || peakCorrPos > sampleCount / 4 ) { // or if correlation is out of safe range + || peakFreqPos > 100 // or at least if it is granular enough (+- 1% resolution) + || peakCorrPos < 100 || peakCorrPos > sampleCount / 4 ) { // or if correlation is out of safe range channelData->frequency = pF; } else { // otherwise fall back to correlation channelData->frequency = pC; diff --git a/openhantek/src/post/spectrumgenerator.h b/openhantek/src/post/spectrumgenerator.h index f38ab472..422d1d1d 100644 --- a/openhantek/src/post/spectrumgenerator.h +++ b/openhantek/src/post/spectrumgenerator.h @@ -8,10 +8,10 @@ #include #include -#include "ppresult.h" #include "dsosamples.h" -#include "utils/printutils.h" #include "postprocessingsettings.h" +#include "ppresult.h" +#include "utils/printutils.h" #include "processor.h" @@ -23,15 +23,15 @@ struct DsoSettingsScope; /// time-/frequencysteps between two values. class SpectrumGenerator : public Processor { public: - SpectrumGenerator(const DsoSettingsScope* scope, const DsoSettingsPostProcessing* postprocessing); + SpectrumGenerator( const DsoSettingsScope *scope, const DsoSettingsPostProcessing *postprocessing ); virtual ~SpectrumGenerator(); private: - const DsoSettingsScope* scope; - const DsoSettingsPostProcessing* postprocessing; - unsigned int lastRecordLength = 0; ///< The record length of the previously analyzed data - Dso::WindowFunction lastWindow = Dso::WindowFunction(-1); ///< The previously used dft window function + const DsoSettingsScope *scope; + const DsoSettingsPostProcessing *postprocessing; + unsigned int lastRecordLength = 0; ///< The record length of the previously analyzed data + Dso::WindowFunction lastWindow = Dso::WindowFunction( -1 ); ///< The previously used dft window function double *lastWindowBuffer = nullptr; // Processor interface - void process(PPresult *data) override; + void process( PPresult *data ) override; }; diff --git a/openhantek/src/scopesettings.h b/openhantek/src/scopesettings.h index 8eea5ed6..e353cd5e 100644 --- a/openhantek/src/scopesettings.h +++ b/openhantek/src/scopesettings.h @@ -2,8 +2,8 @@ #pragma once -#include #include +#include #include "hantekdso/controlspecification.h" #include "hantekdso/enums.h" @@ -14,13 +14,8 @@ /// \brief Holds the cursor parameters struct DsoSettingsScopeCursor { - enum CursorShape { - NONE, - HORIZONTAL, - VERTICAL, - RECTANGULAR - } shape = NONE; - QPointF pos[MARKER_COUNT] = {{-1.0, -1.0}, {1.0, 1.0}}; ///< Position in div + enum CursorShape { NONE, HORIZONTAL, VERTICAL, RECTANGULAR } shape = NONE; + QPointF pos[ MARKER_COUNT ] = {{-1.0, -1.0}, {1.0, 1.0}}; ///< Position in div }; /// \brief Holds the settings for the horizontal axis. @@ -41,7 +36,7 @@ struct DsoSettingsScopeHorizontal { /// TODO Use ControlSettingsTrigger struct DsoSettingsScopeTrigger { Dso::TriggerMode mode = Dso::TriggerMode::AUTO; ///< Automatic, normal or single trigger - double offset = 0.5; ///< Horizontal position for pretrigger (middle of screen) + double offset = 0.5; ///< Horizontal position for pretrigger (middle of screen) Dso::Slope slope = Dso::Slope::Positive; ///< Rising or falling edge causes trigger unsigned int source = 0; ///< Channel that is used as trigger source bool smooth = false; ///< Don't trigger on glitches @@ -49,8 +44,8 @@ struct DsoSettingsScopeTrigger { /// \brief Base for DsoSettingsScopeSpectrum and DsoSettingsScopeVoltage struct DsoSettingsScopeChannel { - QString name; ///< Name of this channel - bool used = false; ///< true if the channel is turned on + QString name; ///< Name of this channel + bool used = false; ///< true if the channel is turned on DsoSettingsScopeCursor cursor; }; @@ -74,32 +69,34 @@ struct DsoSettingsScopeVoltage : public DsoSettingsScopeChannel { /// \brief Holds the settings for the oscilloscope. struct DsoSettingsScope { std::vector gainSteps = {2e-2, 5e-2, 1e-1, 2e-1, - 5e-1, 1e0, 2e0, 5e0}; ///< The selectable voltage gain steps in V/div - std::vector spectrum; ///< Spectrum analysis settings - std::vector voltage; ///< Settings for the normal graphs - DsoSettingsScopeHorizontal horizontal; ///< Settings for the horizontal axis - DsoSettingsScopeTrigger trigger; ///< Settings for the trigger + 5e-1, 1e0, 2e0, 5e0}; ///< The selectable voltage gain steps in V/div + std::vector spectrum; ///< Spectrum analysis settings + std::vector voltage; ///< Settings for the normal graphs + DsoSettingsScopeHorizontal horizontal; ///< Settings for the horizontal axis + DsoSettingsScopeTrigger trigger; ///< Settings for the trigger bool histogram = false; - double gain(unsigned channel) const { - return gainSteps[voltage[channel].gainStepIndex] * voltage[channel].probeAttn; + double gain( unsigned channel ) const { + return gainSteps[ voltage[ channel ].gainStepIndex ] * voltage[ channel ].probeAttn; } - bool anyUsed(ChannelID channel) { return voltage[channel].used | spectrum[channel].used; } + bool anyUsed( ChannelID channel ) { return voltage[ channel ].used | spectrum[ channel ].used; } - Dso::Coupling coupling(ChannelID channel, const Dso::ControlSpecification *deviceSpecification) const { - return deviceSpecification->couplings[voltage[channel].couplingOrMathIndex]; + Dso::Coupling coupling( ChannelID channel, const Dso::ControlSpecification *deviceSpecification ) const { + return deviceSpecification->couplings[ voltage[ channel ].couplingOrMathIndex ]; } // Channels, including math channels - unsigned countChannels() const { return unsigned(voltage.size()); } + unsigned countChannels() const { return unsigned( voltage.size() ); } - double getMarker(unsigned int marker) const { - double x = qBound( MARGIN_LEFT, marker < MARKER_COUNT ? horizontal.cursor.pos[marker].x() : 0.0, MARGIN_RIGHT ); + double getMarker( unsigned int marker ) const { + double x = + qBound( MARGIN_LEFT, marker < MARKER_COUNT ? horizontal.cursor.pos[ marker ].x() : 0.0, MARGIN_RIGHT ); return x; } - void setMarker(unsigned int marker, double value) { - if (marker < MARKER_COUNT) horizontal.cursor.pos[marker].setX(value); + void setMarker( unsigned int marker, double value ) { + if ( marker < MARKER_COUNT ) + horizontal.cursor.pos[ marker ].setX( value ); } }; diff --git a/openhantek/src/selectdevice/devicelistentry.h b/openhantek/src/selectdevice/devicelistentry.h index 768bfce0..e0b6b8e7 100644 --- a/openhantek/src/selectdevice/devicelistentry.h +++ b/openhantek/src/selectdevice/devicelistentry.h @@ -2,8 +2,8 @@ #pragma once -#include #include "usb/usbdevice.h" +#include /** * Represents an entry in the {@link DevicesListModel}. @@ -15,6 +15,7 @@ struct DeviceListEntry { bool needFirmware = false; QString errorMessage; QString getStatus() const { - return errorMessage.size()? errorMessage : (canConnect?"Ready":(needFirmware?"Firmware upload":"Cannot connect")); + return errorMessage.size() ? errorMessage + : ( canConnect ? "Ready" : ( needFirmware ? "Firmware upload" : "Cannot connect" ) ); } }; diff --git a/openhantek/src/selectdevice/deviceslistmodel.cpp b/openhantek/src/selectdevice/deviceslistmodel.cpp index dc6b94ea..1e015db9 100644 --- a/openhantek/src/selectdevice/deviceslistmodel.cpp +++ b/openhantek/src/selectdevice/deviceslistmodel.cpp @@ -1,88 +1,89 @@ // SPDX-License-Identifier: GPL-2.0+ #include "deviceslistmodel.h" +#include "dsomodel.h" #include "usb/finddevices.h" #include "usb/uploadFirmware.h" -#include "dsomodel.h" #include #include -DevicesListModel::DevicesListModel(FindDevices *findDevices) :findDevices(findDevices) {} +DevicesListModel::DevicesListModel( FindDevices *findDevices ) : findDevices( findDevices ) {} -int DevicesListModel::rowCount(const QModelIndex &) const -{ - return int(entries.size()); -} +int DevicesListModel::rowCount( const QModelIndex & ) const { return int( entries.size() ); } -int DevicesListModel::columnCount(const QModelIndex &) const -{ - return 2; -} +int DevicesListModel::columnCount( const QModelIndex & ) const { return 2; } -QVariant DevicesListModel::headerData(int section, Qt::Orientation orientation, int role) const -{ - if (orientation == Qt::Vertical) - return QAbstractTableModel::headerData(section, orientation, role); - if (role == Qt::DisplayRole) { - switch(section) { - case 0: return QObject::tr("Devicename"); - case 1: return QObject::tr("Status"); - default: return QVariant(); +QVariant DevicesListModel::headerData( int section, Qt::Orientation orientation, int role ) const { + if ( orientation == Qt::Vertical ) + return QAbstractTableModel::headerData( section, orientation, role ); + if ( role == Qt::DisplayRole ) { + switch ( section ) { + case 0: + return QObject::tr( "Devicename" ); + case 1: + return QObject::tr( "Status" ); + default: + return QVariant(); } } - return QAbstractTableModel::headerData(section, orientation, role); + return QAbstractTableModel::headerData( section, orientation, role ); } -QVariant DevicesListModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid()) return QVariant(); - const unsigned row = unsigned(index.row()); - if (role==Qt::UserRole) return QVariant::fromValue(entries[row].id); - if (role==Qt::UserRole+1) return QVariant::fromValue(entries[row].canConnect); - if (role==Qt::UserRole+2) return QVariant::fromValue(entries[row].needFirmware); - if (role==Qt::UserRole+3) return QVariant::fromValue(entries[row].errorMessage); +QVariant DevicesListModel::data( const QModelIndex &index, int role ) const { + if ( !index.isValid() ) + return QVariant(); + const unsigned row = unsigned( index.row() ); + if ( role == Qt::UserRole ) + return QVariant::fromValue( entries[ row ].id ); + if ( role == Qt::UserRole + 1 ) + return QVariant::fromValue( entries[ row ].canConnect ); + if ( role == Qt::UserRole + 2 ) + return QVariant::fromValue( entries[ row ].needFirmware ); + if ( role == Qt::UserRole + 3 ) + return QVariant::fromValue( entries[ row ].errorMessage ); - if (role == Qt::DisplayRole) { - if (index.column() == 0) { - return entries[row].name; - } else if (index.column() == 1) { - return entries[row].getStatus(); + if ( role == Qt::DisplayRole ) { + if ( index.column() == 0 ) { + return entries[ row ].name; + } else if ( index.column() == 1 ) { + return entries[ row ].getStatus(); } } - if (role == Qt::BackgroundRole) { - if (entries[row].canConnect) return QColor(Qt::darkGreen).lighter(); - else if (entries[row].needFirmware) return QColor(Qt::yellow).lighter(); + if ( role == Qt::BackgroundRole ) { + if ( entries[ row ].canConnect ) + return QColor( Qt::darkGreen ).lighter(); + else if ( entries[ row ].needFirmware ) + return QColor( Qt::yellow ).lighter(); } return QVariant(); } -void DevicesListModel::updateDeviceList() -{ +void DevicesListModel::updateDeviceList() { beginResetModel(); entries.clear(); endResetModel(); - const FindDevices::DeviceList* devices = findDevices->getDevices(); - beginInsertRows(QModelIndex(),0,int(devices->size())); - for (auto &i : *devices) { + const FindDevices::DeviceList *devices = findDevices->getDevices(); + beginInsertRows( QModelIndex(), 0, int( devices->size() ) ); + for ( auto &i : *devices ) { DeviceListEntry entry; - entry.name = QString::fromStdString(i.second->getModel()->name); + entry.name = QString::fromStdString( i.second->getModel()->name ); entry.id = i.first; - if (i.second->needsFirmware()) { + if ( i.second->needsFirmware() ) { UploadFirmware uf; - if (!uf.startUpload(i.second.get())) { + if ( !uf.startUpload( i.second.get() ) ) { entry.errorMessage = uf.getErrorMessage(); entry.needFirmware = false; // trigger error message } else entry.needFirmware = true; - } else if (i.second->connectDevice(entry.errorMessage)) { + } else if ( i.second->connectDevice( entry.errorMessage ) ) { entry.canConnect = true; i.second->disconnectFromDevice(); } else { entry.canConnect = false; } - entries.push_back(entry); + entries.push_back( entry ); } endInsertRows(); } diff --git a/openhantek/src/selectdevice/deviceslistmodel.h b/openhantek/src/selectdevice/deviceslistmodel.h index 501af020..5f1f8e87 100644 --- a/openhantek/src/selectdevice/deviceslistmodel.h +++ b/openhantek/src/selectdevice/deviceslistmodel.h @@ -2,8 +2,8 @@ #pragma once -#include #include "devicelistentry.h" +#include class FindDevices; @@ -11,16 +11,17 @@ class FindDevices; * Provides a Model for the Qt Model/View concept. The {@see FindDevices} is required * to update the list of available devices. */ -class DevicesListModel: public QAbstractTableModel { -public: - explicit DevicesListModel( FindDevices* findDevices ); +class DevicesListModel : public QAbstractTableModel { + public: + explicit DevicesListModel( FindDevices *findDevices ); // QAbstractItemModel interface - int rowCount(const QModelIndex &parent) const override; - int columnCount(const QModelIndex &parent) const override; - QVariant headerData(int section, Qt::Orientation orientation, int role) const override; - QVariant data(const QModelIndex &index, int role) const override; + int rowCount( const QModelIndex &parent ) const override; + int columnCount( const QModelIndex &parent ) const override; + QVariant headerData( int section, Qt::Orientation orientation, int role ) const override; + QVariant data( const QModelIndex &index, int role ) const override; void updateDeviceList(); -private: + + private: std::vector entries; - FindDevices* findDevices; + FindDevices *findDevices; }; diff --git a/openhantek/src/selectdevice/newdevicemodelfromexisting.cpp b/openhantek/src/selectdevice/newdevicemodelfromexisting.cpp index 83a7ac34..10ac4054 100644 --- a/openhantek/src/selectdevice/newdevicemodelfromexisting.cpp +++ b/openhantek/src/selectdevice/newdevicemodelfromexisting.cpp @@ -7,59 +7,56 @@ #include "rawdeviceslistmodel.h" #include +#include #include #include -#include -NewDeviceModelFromExisting::NewDeviceModelFromExisting(QWidget *parent) : - QDialog(parent), - ui(new Ui::NewDeviceModelFromExisting) -{ - ui->setupUi(this); - connect(ui->checkBox, &QCheckBox::stateChanged,[this](int state) { - ui->stackedWidget->setCurrentIndex(state==Qt::Checked ? 0: 1); - }); - ui->checkBox->setCheckState(Qt::Checked); - ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); +NewDeviceModelFromExisting::NewDeviceModelFromExisting( QWidget *parent ) + : QDialog( parent ), ui( new Ui::NewDeviceModelFromExisting ) { + ui->setupUi( this ); + connect( ui->checkBox, &QCheckBox::stateChanged, + [this]( int state ) { ui->stackedWidget->setCurrentIndex( state == Qt::Checked ? 0 : 1 ); } ); + ui->checkBox->setCheckState( Qt::Checked ); + ui->buttonBox->button( QDialogButtonBox::Ok )->setEnabled( false ); QStringList supportedModelsList; - for (const DSOModel* model: ModelRegistry::get()->models()) { - supportedModelsList.append(QString::fromStdString(model->name)); + for ( const DSOModel *model : ModelRegistry::get()->models() ) { + supportedModelsList.append( QString::fromStdString( model->name ) ); } - QStringListModel* model = new QStringListModel(this); - model->setStringList(supportedModelsList); - ui->cmbTemplateModel->setModel(model); + QStringListModel *model = new QStringListModel( this ); + model->setStringList( supportedModelsList ); + ui->cmbTemplateModel->setModel( model ); - RawDevicesListModel* deviceListModel = new RawDevicesListModel(context, this); - ui->cmbUSBdevices->setModel(deviceListModel); + RawDevicesListModel *deviceListModel = new RawDevicesListModel( context, this ); + ui->cmbUSBdevices->setModel( deviceListModel ); deviceListModel->updateDeviceList(); - connect(ui->btnRefresh, &QPushButton::clicked, [deviceListModel] { - deviceListModel->updateDeviceList(); - }); + connect( ui->btnRefresh, &QPushButton::clicked, [deviceListModel] { deviceListModel->updateDeviceList(); } ); - connect(ui->cmbUSBdevices, static_cast(&QComboBox::currentIndexChanged), [this](int index) { - if (index == -1) { - ui->stackedWidget->setCurrentIndex(2); - ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); - ui->checkBox->setEnabled(false); - return; - } - if (ui->cmbUSBdevices->currentData(RawDevicesListModel::AccessRole).toBool()) { - ui->checkBox->setEnabled(true); - ui->modelname->setText(ui->cmbUSBdevices->currentData(RawDevicesListModel::DeviceNameRole).toString()); - ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(ui->modelname->text().size()); - ui->stackedWidget->setCurrentIndex(ui->checkBox->isChecked() ? 0: 1); - } else { - ui->checkBox->setEnabled(false); - ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); - ui->stackedWidget->setCurrentIndex(3); - } - }); + connect( ui->cmbUSBdevices, static_cast( &QComboBox::currentIndexChanged ), + [this]( int index ) { + if ( index == -1 ) { + ui->stackedWidget->setCurrentIndex( 2 ); + ui->buttonBox->button( QDialogButtonBox::Ok )->setEnabled( false ); + ui->checkBox->setEnabled( false ); + return; + } + if ( ui->cmbUSBdevices->currentData( RawDevicesListModel::AccessRole ).toBool() ) { + ui->checkBox->setEnabled( true ); + ui->modelname->setText( + ui->cmbUSBdevices->currentData( RawDevicesListModel::DeviceNameRole ).toString() ); + ui->buttonBox->button( QDialogButtonBox::Ok )->setEnabled( ui->modelname->text().size() ); + ui->stackedWidget->setCurrentIndex( ui->checkBox->isChecked() ? 0 : 1 ); + } else { + ui->checkBox->setEnabled( false ); + ui->buttonBox->button( QDialogButtonBox::Ok )->setEnabled( false ); + ui->stackedWidget->setCurrentIndex( 3 ); + } + } ); - if (deviceListModel->rowCount(QModelIndex())) { - ui->cmbUSBdevices->setCurrentIndex(0); + if ( deviceListModel->rowCount( QModelIndex() ) ) { + ui->cmbUSBdevices->setCurrentIndex( 0 ); } } @@ -75,8 +72,7 @@ RawDeviceListEntry *NewDeviceModelFromExisting::getSelectedEntry() } #endif -void NewDeviceModelFromExisting::accept() -{ - QMessageBox::information(this,tr("Sorry"),tr("This is not yet implemented!")); +void NewDeviceModelFromExisting::accept() { + QMessageBox::information( this, tr( "Sorry" ), tr( "This is not yet implemented!" ) ); QDialog::accept(); } diff --git a/openhantek/src/selectdevice/newdevicemodelfromexisting.h b/openhantek/src/selectdevice/newdevicemodelfromexisting.h index f40e57ad..3f4272d2 100644 --- a/openhantek/src/selectdevice/newdevicemodelfromexisting.h +++ b/openhantek/src/selectdevice/newdevicemodelfromexisting.h @@ -2,10 +2,10 @@ #pragma once +#include "rawdevicelistentry.h" +#include "ui_newdevicemodelfromexisting.h" #include #include -#include "ui_newdevicemodelfromexisting.h" -#include "rawdevicelistentry.h" namespace Ui { class NewDeviceModelFromExisting; @@ -13,19 +13,18 @@ class NewDeviceModelFromExisting; struct libusb_context; -class NewDeviceModelFromExisting : public QDialog -{ +class NewDeviceModelFromExisting : public QDialog { Q_OBJECT -public: - explicit NewDeviceModelFromExisting(QWidget *parent = nullptr); -// void setUSBcontext(libusb_context* context); -// RawDeviceListEntry* getSelectedEntry(); -private: + public: + explicit NewDeviceModelFromExisting( QWidget *parent = nullptr ); + // void setUSBcontext(libusb_context* context); + // RawDeviceListEntry* getSelectedEntry(); + private: std::unique_ptr ui; - libusb_context* context = nullptr; + libusb_context *context = nullptr; // QDialog interface -public slots: + public slots: void accept() override; }; diff --git a/openhantek/src/selectdevice/rawdevicelistentry.h b/openhantek/src/selectdevice/rawdevicelistentry.h index e69972f3..5c098bcc 100644 --- a/openhantek/src/selectdevice/rawdevicelistentry.h +++ b/openhantek/src/selectdevice/rawdevicelistentry.h @@ -2,9 +2,9 @@ #pragma once -#include -#include "usb/usbdevice.h" #include "dsomodel.h" +#include "usb/usbdevice.h" +#include /** * Represents an entry in the {@link DevicesListModel}. */ @@ -12,7 +12,7 @@ struct RawDeviceListEntry { long productId; long vendorId; bool access; - DSOModel* baseModel=nullptr; + DSOModel *baseModel = nullptr; QString devicename; QString deviceinfo; }; diff --git a/openhantek/src/selectdevice/rawdeviceslistmodel.cpp b/openhantek/src/selectdevice/rawdeviceslistmodel.cpp index 48aed90c..b4328411 100644 --- a/openhantek/src/selectdevice/rawdeviceslistmodel.cpp +++ b/openhantek/src/selectdevice/rawdeviceslistmodel.cpp @@ -1,79 +1,85 @@ // SPDX-License-Identifier: GPL-2.0+ #include "rawdeviceslistmodel.h" +#include "dsomodel.h" #include "usb/finddevices.h" #include "usb/uploadFirmware.h" -#include "dsomodel.h" #include -RawDevicesListModel::RawDevicesListModel(libusb_context *context, QObject *parent) : QAbstractTableModel(parent), context(context) {} +RawDevicesListModel::RawDevicesListModel( libusb_context *context, QObject *parent ) + : QAbstractTableModel( parent ), context( context ) {} -int RawDevicesListModel::rowCount(const QModelIndex &) const { - return int(entries.size()); -} +int RawDevicesListModel::rowCount( const QModelIndex & ) const { return int( entries.size() ); } -int RawDevicesListModel::columnCount(const QModelIndex &) const { - return 1; -} +int RawDevicesListModel::columnCount( const QModelIndex & ) const { return 1; } -QVariant RawDevicesListModel::data(const QModelIndex &index, int role) const { - if (!index.isValid()) return QVariant(); - const unsigned row = unsigned(index.row()); - if (role==ProductIDRole) return QVariant::fromValue(entries[row].productId); - else if (role==VendorIDRole) return QVariant::fromValue(entries[row].vendorId); - else if (role==AccessRole) return QVariant::fromValue(entries[row].access); - else if (role==DeviceNameRole) return QVariant::fromValue(entries[row].devicename); - else if (role==EntryPointerRole) return QVariant::fromValue((void*)(&entries[row])); - else if (role==Qt::DisplayRole) return QVariant::fromValue(entries[row].deviceinfo); +QVariant RawDevicesListModel::data( const QModelIndex &index, int role ) const { + if ( !index.isValid() ) + return QVariant(); + const unsigned row = unsigned( index.row() ); + if ( role == ProductIDRole ) + return QVariant::fromValue( entries[ row ].productId ); + else if ( role == VendorIDRole ) + return QVariant::fromValue( entries[ row ].vendorId ); + else if ( role == AccessRole ) + return QVariant::fromValue( entries[ row ].access ); + else if ( role == DeviceNameRole ) + return QVariant::fromValue( entries[ row ].devicename ); + else if ( role == EntryPointerRole ) + return QVariant::fromValue( (void *)( &entries[ row ] ) ); + else if ( role == Qt::DisplayRole ) + return QVariant::fromValue( entries[ row ].deviceinfo ); return QVariant(); } -QString readUSBdescriptor(libusb_device_handle *handle, uint8_t index) { - unsigned char string[255]; - int ret = libusb_get_string_descriptor_ascii(handle, index, string, sizeof(string)); - if (ret > 0) - return QString::fromLatin1(reinterpret_cast(string), ret).trimmed(); +QString readUSBdescriptor( libusb_device_handle *handle, uint8_t index ) { + unsigned char string[ 255 ]; + int ret = libusb_get_string_descriptor_ascii( handle, index, string, sizeof( string ) ); + if ( ret > 0 ) + return QString::fromLatin1( reinterpret_cast( string ), ret ).trimmed(); else return QString(); } -void RawDevicesListModel::updateDeviceList() -{ +void RawDevicesListModel::updateDeviceList() { beginResetModel(); entries.clear(); endResetModel(); libusb_device **deviceList; - ssize_t deviceCount = libusb_get_device_list(context, &deviceList); - beginInsertRows(QModelIndex(),0,int(deviceCount)); + ssize_t deviceCount = libusb_get_device_list( context, &deviceList ); + beginInsertRows( QModelIndex(), 0, int( deviceCount ) ); - for (ssize_t deviceIterator = 0; deviceIterator < deviceCount; ++deviceIterator) { - libusb_device *device = deviceList[deviceIterator]; + for ( ssize_t deviceIterator = 0; deviceIterator < deviceCount; ++deviceIterator ) { + libusb_device *device = deviceList[ deviceIterator ]; RawDeviceListEntry entry; // Get device descriptor struct libusb_device_descriptor descriptor; - libusb_get_device_descriptor(device, &descriptor); + libusb_get_device_descriptor( device, &descriptor ); entry.productId = descriptor.idProduct; entry.vendorId = descriptor.idVendor; libusb_device_handle *handle = nullptr; - int ret = libusb_open(device, &handle); - if (ret != LIBUSB_SUCCESS) { + int ret = libusb_open( device, &handle ); + if ( ret != LIBUSB_SUCCESS ) { entry.access = false; - entry.deviceinfo = QObject::tr("%1:%2 - No access").arg(entry.vendorId,0,16).arg(entry.productId,0,16); + entry.deviceinfo = + QObject::tr( "%1:%2 - No access" ).arg( entry.vendorId, 0, 16 ).arg( entry.productId, 0, 16 ); } else { entry.access = true; - entry.devicename = readUSBdescriptor(handle, descriptor.iProduct); - entry.deviceinfo = QObject::tr("%1:%2 (%3 - %4)").arg(entry.vendorId,0,16).arg(entry.productId,0,16) - .arg(entry.devicename, readUSBdescriptor(handle, descriptor.iManufacturer)); - libusb_close(handle); + entry.devicename = readUSBdescriptor( handle, descriptor.iProduct ); + entry.deviceinfo = QObject::tr( "%1:%2 (%3 - %4)" ) + .arg( entry.vendorId, 0, 16 ) + .arg( entry.productId, 0, 16 ) + .arg( entry.devicename, readUSBdescriptor( handle, descriptor.iManufacturer ) ); + libusb_close( handle ); } - entries.push_back(entry); + entries.push_back( entry ); } - libusb_free_device_list(deviceList, true); + libusb_free_device_list( deviceList, true ); endInsertRows(); } diff --git a/openhantek/src/selectdevice/rawdeviceslistmodel.h b/openhantek/src/selectdevice/rawdeviceslistmodel.h index 0bbaa465..b9bb1d9f 100644 --- a/openhantek/src/selectdevice/rawdeviceslistmodel.h +++ b/openhantek/src/selectdevice/rawdeviceslistmodel.h @@ -2,31 +2,32 @@ #pragma once -#include #include "rawdevicelistentry.h" #include "usb/usbdevice.h" +#include /** * Provides a Model for the Qt Model/View concept. The {@see FindDevices} is required * to update the list of available devices. */ -class RawDevicesListModel: public QAbstractTableModel { -public: - RawDevicesListModel(libusb_context *context, QObject *parent = nullptr); +class RawDevicesListModel : public QAbstractTableModel { + public: + RawDevicesListModel( libusb_context *context, QObject *parent = nullptr ); // QAbstractItemModel interface - int rowCount(const QModelIndex &parent) const override; - int columnCount(const QModelIndex &parent) const override; - QVariant data(const QModelIndex &index, int role) const override; + int rowCount( const QModelIndex &parent ) const override; + int columnCount( const QModelIndex &parent ) const override; + QVariant data( const QModelIndex &index, int role ) const override; void updateDeviceList(); enum Roles { - ProductIDRole = Qt::UserRole+0, - VendorIDRole = Qt::UserRole+1, - AccessRole = Qt::UserRole+2, - DeviceNameRole = Qt::UserRole+3, - EntryPointerRole = Qt::UserRole+4 + ProductIDRole = Qt::UserRole + 0, + VendorIDRole = Qt::UserRole + 1, + AccessRole = Qt::UserRole + 2, + DeviceNameRole = Qt::UserRole + 3, + EntryPointerRole = Qt::UserRole + 4 }; -private: + + private: std::vector entries; libusb_context *context; }; diff --git a/openhantek/src/selectdevice/selectsupporteddevice.cpp b/openhantek/src/selectdevice/selectsupporteddevice.cpp index f0c02799..bc2160ec 100644 --- a/openhantek/src/selectdevice/selectsupporteddevice.cpp +++ b/openhantek/src/selectdevice/selectsupporteddevice.cpp @@ -2,103 +2,108 @@ #include "selectsupporteddevice.h" -#include #include #include +#include #include -#include "usb/uploadFirmware.h" -#include "usb/finddevices.h" -#include "dsomodel.h" #include "devicelistentry.h" #include "deviceslistmodel.h" -#include "newdevicemodelfromexisting.h" +#include "dsomodel.h" #include "modelregistry.h" +#include "newdevicemodelfromexisting.h" +#include "usb/finddevices.h" +#include "usb/uploadFirmware.h" #include "viewconstants.h" -SelectSupportedDevice::SelectSupportedDevice( QWidget *parent ) : - QDialog( parent ), ui( new Ui::SelectSupportedDevice ) -{ - ui->setupUi(this); +SelectSupportedDevice::SelectSupportedDevice( QWidget *parent ) + : QDialog( parent ), ui( new Ui::SelectSupportedDevice ) { + ui->setupUi( this ); #ifdef NEW_DEVICE_FROM_EXISTING_DIALOG - newDeviceFromExistingDialog = new NewDeviceModelFromExisting(this); + newDeviceFromExistingDialog = new NewDeviceModelFromExisting( this ); #endif - ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); - qRegisterMetaType("UniqueUSBid"); - connect(ui->buttonBox, &QDialogButtonBox::accepted, [this]() { - if (ui->cmbDevices->currentIndex()!=-1) { - selectedDevice = ui->cmbDevices->currentData(Qt::UserRole).value(); + ui->buttonBox->button( QDialogButtonBox::Ok )->setEnabled( false ); + qRegisterMetaType( "UniqueUSBid" ); + connect( ui->buttonBox, &QDialogButtonBox::accepted, [this]() { + if ( ui->cmbDevices->currentIndex() != -1 ) { + selectedDevice = ui->cmbDevices->currentData( Qt::UserRole ).value(); } QCoreApplication::instance()->quit(); - }); - connect(ui->buttonBox, &QDialogButtonBox::helpRequested, []() { + } ); + connect( ui->buttonBox, &QDialogButtonBox::helpRequested, []() { QString usrManualPath( USR_MANUAL_PATH ); QFile userManual( usrManualPath ); if ( userManual.exists() ) QDesktopServices::openUrl( QUrl( "file://" + usrManualPath ) ); else - QDesktopServices::openUrl( QUrl( "https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/OpenHantek6022_User_Manual.pdf" ) ); - }); + QDesktopServices::openUrl( QUrl( + "https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/OpenHantek6022_User_Manual.pdf" ) ); + } ); #ifdef NEW_DEVICE_FROM_EXISTING_DIALOG - connect(ui->btnAddDevice, &QPushButton::clicked, [this]() { - newDeviceFromExistingDialog->setModal(true); + connect( ui->btnAddDevice, &QPushButton::clicked, [this]() { + newDeviceFromExistingDialog->setModal( true ); newDeviceFromExistingDialog->show(); - }); + } ); #endif } -std::unique_ptr SelectSupportedDevice::showSelectDeviceModal(libusb_context *context) -{ -// newDeviceFromExistingDialog->setUSBcontext(context); - std::unique_ptr findDevices = std::unique_ptr(new FindDevices(context)); - std::unique_ptr model = std::unique_ptr(new DevicesListModel(findDevices.get())); - ui->cmbDevices->setModel(model.get()); - connect(ui->cmbDevices, static_cast(&QComboBox::currentIndexChanged), [this](int index) { - if (index == -1) { - ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); - return; - } - if (ui->cmbDevices->currentData( Qt::UserRole + 1 ).toBool()) { // canConnect - ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true); - ui->labelReadyState->setText( - tr("


The device is ready for use.

Please observe the " - "" - "user manual for safe operation.

")); - } else { - ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); - if (ui->cmbDevices->currentData( Qt::UserRole + 2 ).toBool()) { // needFirmware - ui->labelReadyState->setText(tr("

Upload in progress ...

" - "

If the upload takes more than 30 s, please close this window
and restart the program!

" - )); - } else { // something went wrong, inform user - ui->labelReadyState->setText( tr( "


Connection failed!

" ) - + ui->cmbDevices->currentData( Qt::UserRole + 3 ).toString() - ); - } - } - }); +std::unique_ptr SelectSupportedDevice::showSelectDeviceModal( libusb_context *context ) { + // newDeviceFromExistingDialog->setUSBcontext(context); + std::unique_ptr findDevices = std::unique_ptr( new FindDevices( context ) ); + std::unique_ptr model = + std::unique_ptr( new DevicesListModel( findDevices.get() ) ); + ui->cmbDevices->setModel( model.get() ); + connect( ui->cmbDevices, static_cast( &QComboBox::currentIndexChanged ), + [this]( int index ) { + if ( index == -1 ) { + ui->buttonBox->button( QDialogButtonBox::Ok )->setEnabled( false ); + return; + } + if ( ui->cmbDevices->currentData( Qt::UserRole + 1 ).toBool() ) { // canConnect + ui->buttonBox->button( QDialogButtonBox::Ok )->setEnabled( true ); + ui->labelReadyState->setText( + tr( "


The device is ready for use.

Please observe the " + "" + "user manual for safe operation.

" ) ); + } else { + ui->buttonBox->button( QDialogButtonBox::Ok )->setEnabled( false ); + if ( ui->cmbDevices->currentData( Qt::UserRole + 2 ).toBool() ) { // needFirmware + ui->labelReadyState->setText( tr( "

Upload in progress ...

" + "

If the upload takes more than 30 s, please close " + "this window
and restart the program!

" ) ); + } else { // something went wrong, inform user + ui->labelReadyState->setText( tr( "


Connection failed!

" ) + + ui->cmbDevices->currentData( Qt::UserRole + 3 ).toString() ); + } + } + } ); - QString messageNoDevices = tr("

OpenHantek6022 is searching for compatible devices ...

" - "

" - "Don't forget to switch your device into oscilloscope mode if it has multiple modes.

" - ); - #if defined(Q_OS_WIN) - messageNoDevices += tr("

Please make sure you have installed the windows usb driver correctly

"); - #elif defined(Q_OS_LINUX) - QFile libRules("/lib/udev/rules.d/60-hantek.rules"); - QFile etcRules("/etc/udev/rules.d/60-hantek.rules"); - if ( !libRules.exists() && !etcRules.exists() ) { - messageNoDevices += tr("

Please make sure you have copied the udev rules file to %1 for correct USB access permissions.

").arg(libRules.fileName()); - } - #endif - messageNoDevices += tr("

Visit the build and run instruction " - "website for help.

"); + QString messageNoDevices = + tr( "

OpenHantek6022 is searching for compatible devices ...

" + "

" + "Don't forget to switch your device into oscilloscope mode if it has multiple modes.

" ); +#if defined( Q_OS_WIN ) + messageNoDevices += tr( "

Please make sure you have installed the windows usb driver correctly

" ); +#elif defined( Q_OS_LINUX ) + QFile libRules( "/lib/udev/rules.d/60-hantek.rules" ); + QFile etcRules( "/etc/udev/rules.d/60-hantek.rules" ); + if ( !libRules.exists() && !etcRules.exists() ) { + messageNoDevices += tr( "

Please make sure you have copied the udev rules file to %1 for correct USB " + "access permissions.

" ) + .arg( libRules.fileName() ); + } +#endif + messageNoDevices += tr( + "

Visit the build and run instruction " + "website for help.

" ); updateSupportedDevices(); QTimer timer; - timer.setInterval(1000); - connect(&timer, &QTimer::timeout, [this, &model, &findDevices, &messageNoDevices]() { + timer.setInterval( 1000 ); + connect( &timer, &QTimer::timeout, [this, &model, &findDevices, &messageNoDevices]() { if ( findDevices->updateDeviceList() ) { // searching... model->updateDeviceList(); } @@ -106,40 +111,38 @@ std::unique_ptr SelectSupportedDevice::showSelectDeviceModal(libusb_c ui->cmbDevices->setCurrentIndex( 0 ); // HACK: "click()" the "OK" button (if enabled) to start the scope automatically if ( ui->buttonBox->button( QDialogButtonBox::Ok )->isEnabled() ) { // if scope is ready to run - ui->buttonBox->button( QDialogButtonBox::Ok )->click(); // start it without user activity + ui->buttonBox->button( QDialogButtonBox::Ok )->click(); // start it without user activity } } else { - ui->labelReadyState->setText(messageNoDevices); + ui->labelReadyState->setText( messageNoDevices ); } - }); + } ); timer.start(); - QCoreApplication::sendEvent(&timer, new QTimerEvent(timer.timerId())); // immediate timer event + QCoreApplication::sendEvent( &timer, new QTimerEvent( timer.timerId() ) ); // immediate timer event show(); QCoreApplication::instance()->exec(); timer.stop(); close(); - return findDevices->takeDevice(selectedDevice); + return findDevices->takeDevice( selectedDevice ); } -void SelectSupportedDevice::showLibUSBFailedDialogModel(int error) -{ - ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); +void SelectSupportedDevice::showLibUSBFailedDialogModel( int error ) { + ui->buttonBox->button( QDialogButtonBox::Ok )->setEnabled( false ); #ifdef NEW_DEVICE_FROM_EXISTING_DIALOG - ui->btnAddDevice->setEnabled(false); + ui->btnAddDevice->setEnabled( false ); #endif - ui->labelReadyState->setText(tr("Can't initalize USB: %1").arg(libUsbErrorString(error))); + ui->labelReadyState->setText( tr( "Can't initalize USB: %1" ).arg( libUsbErrorString( error ) ) ); show(); QCoreApplication::instance()->exec(); close(); } -void SelectSupportedDevice::updateSupportedDevices() -{ +void SelectSupportedDevice::updateSupportedDevices() { QString devices; - for (const DSOModel* model: ModelRegistry::get()->models()) { - devices.append(QString::fromStdString(model->name)).append(" "); + for ( const DSOModel *model : ModelRegistry::get()->models() ) { + devices.append( QString::fromStdString( model->name ) ).append( " " ); } - ui->labelSupportedDevices->setText(devices); + ui->labelSupportedDevices->setText( devices ); } diff --git a/openhantek/src/selectdevice/selectsupporteddevice.h b/openhantek/src/selectdevice/selectsupporteddevice.h index 62c7cf2d..a3248b1f 100644 --- a/openhantek/src/selectdevice/selectsupporteddevice.h +++ b/openhantek/src/selectdevice/selectsupporteddevice.h @@ -6,8 +6,8 @@ #include -#include #include "usb/usbdevice.h" +#include struct libusb_context; class NewDeviceModelFromExisting; @@ -23,20 +23,20 @@ class NewDeviceModelFromExisting; * An example to get a user selected device: * std::unique_ptr device = SelectDevice().showSelectDeviceModal(context); */ -class SelectSupportedDevice : public QDialog -{ +class SelectSupportedDevice : public QDialog { Q_OBJECT -public: - explicit SelectSupportedDevice(QWidget *parent = nullptr); - std::unique_ptr showSelectDeviceModal(libusb_context *context); - void showLibUSBFailedDialogModel(int error); -private: + public: + explicit SelectSupportedDevice( QWidget *parent = nullptr ); + std::unique_ptr showSelectDeviceModal( libusb_context *context ); + void showLibUSBFailedDialogModel( int error ); + + private: void updateDeviceList(); void updateSupportedDevices(); std::unique_ptr ui; UniqueUSBid selectedDevice = 0; #ifdef NEW_DEVICE_FROM_EXISTING_DIALOG - NewDeviceModelFromExisting* newDeviceFromExistingDialog; + NewDeviceModelFromExisting *newDeviceFromExistingDialog; #endif }; diff --git a/openhantek/src/usb/ezusb.cpp b/openhantek/src/usb/ezusb.cpp index 5f932790..8be33ffa 100644 --- a/openhantek/src/usb/ezusb.cpp +++ b/openhantek/src/usb/ezusb.cpp @@ -28,14 +28,14 @@ #include #ifdef __FreeBSD__ - #include +#include #else - #include +#include #endif #include "ezusb.h" -#define logerror(...) fprintf(stderr, __VA_ARGS__) +#define logerror( ... ) fprintf( stderr, __VA_ARGS__ ) /* * This file contains functions for uploading firmware into Cypress @@ -58,11 +58,12 @@ int verbose = 0; * return true if [addr,addr+len] includes external RAM * for Anchorchips EZ-USB or Cypress EZ-USB FX */ -static bool fx_is_external(uint32_t addr, size_t len) { +static bool fx_is_external( uint32_t addr, size_t len ) { /* with 8KB RAM, 0x0000-0x1b3f can be written * we can't tell if it's a 4KB device here */ - if (addr <= 0x1b3f) return ((addr + len) > 0x1b40); + if ( addr <= 0x1b3f ) + return ( ( addr + len ) > 0x1b40 ); /* there may be more RAM; unclear if we can write it. * some bulk buffers may be unused, 0x1b3f-0x1f3f @@ -75,13 +76,14 @@ static bool fx_is_external(uint32_t addr, size_t len) { * return true if [addr,addr+len] includes external RAM * for Cypress EZ-USB FX2 */ -static bool fx2_is_external(uint32_t addr, size_t len) { +static bool fx2_is_external( uint32_t addr, size_t len ) { /* 1st 8KB for data/code, 0x0000-0x1fff */ - if (addr <= 0x1fff) return ((addr + len) > 0x2000); + if ( addr <= 0x1fff ) + return ( ( addr + len ) > 0x2000 ); /* and 512 for data, 0xe000-0xe1ff */ - else if (addr >= 0xe000 && addr <= 0xe1ff) - return ((addr + len) > 0xe200); + else if ( addr >= 0xe000 && addr <= 0xe1ff ) + return ( ( addr + len ) > 0xe200 ); /* otherwise, it's certainly external */ else @@ -92,13 +94,14 @@ static bool fx2_is_external(uint32_t addr, size_t len) { * return true if [addr,addr+len] includes external RAM * for Cypress EZ-USB FX2LP */ -static bool fx2lp_is_external(uint32_t addr, size_t len) { +static bool fx2lp_is_external( uint32_t addr, size_t len ) { /* 1st 16KB for data/code, 0x0000-0x3fff */ - if (addr <= 0x3fff) return ((addr + len) > 0x4000); + if ( addr <= 0x3fff ) + return ( ( addr + len ) > 0x4000 ); /* and 512 for data, 0xe000-0xe1ff */ - else if (addr >= 0xe000 && addr <= 0xe1ff) - return ((addr + len) > 0xe200); + else if ( addr >= 0xe000 && addr <= 0xe1ff ) + return ( ( addr + len ) > 0xe200 ); /* otherwise, it's certainly external */ else @@ -120,60 +123,66 @@ static bool fx2lp_is_external(uint32_t addr, size_t len) { /* * Issues the specified vendor-specific write request. */ -static int ezusb_write(libusb_device_handle *device, const char *label, uint8_t opcode, uint32_t addr, - const unsigned char *data, size_t len) { +static int ezusb_write( libusb_device_handle *device, const char *label, uint8_t opcode, uint32_t addr, + const unsigned char *data, size_t len ) { int status; - if (verbose > 1) logerror("%s, addr 0x%08x len %4u (0x%04x)\n", label, addr, unsigned(len), unsigned(len) ); - status = libusb_control_transfer(device, LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, - opcode, addr & 0xFFFF, addr >> 16, const_cast(data), uint16_t(len), 1000); - if (status != signed(len) ) { - if (status < 0) - logerror("%s: %s\n", label, libusb_error_name(status)); + if ( verbose > 1 ) + logerror( "%s, addr 0x%08x len %4u (0x%04x)\n", label, addr, unsigned( len ), unsigned( len ) ); + status = libusb_control_transfer( + device, LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, opcode, addr & 0xFFFF, + addr >> 16, const_cast( data ), uint16_t( len ), 1000 ); + if ( status != signed( len ) ) { + if ( status < 0 ) + logerror( "%s: %s\n", label, libusb_error_name( status ) ); else - logerror("%s ==> %d\n", label, status); + logerror( "%s ==> %d\n", label, status ); } - return (status < 0) ? -EIO : 0; + return ( status < 0 ) ? -EIO : 0; } /* * Issues the specified vendor-specific read request. */ -static int ezusb_read(libusb_device_handle *device, const char *label, uint8_t opcode, uint32_t addr, - const unsigned char *data, size_t len) { +static int ezusb_read( libusb_device_handle *device, const char *label, uint8_t opcode, uint32_t addr, + const unsigned char *data, size_t len ) { int status; - if (verbose > 1) logerror("%s, addr 0x%08x len %4u (0x%04x)\n", label, addr, unsigned(len), unsigned(len) ); - status = libusb_control_transfer(device, LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, - opcode, addr & 0xFFFF, addr >> 16, const_cast(data), uint16_t(len), 1000); - if (status != signed(len)) { - if (status < 0) - logerror("%s: %s\n", label, libusb_error_name(status)); + if ( verbose > 1 ) + logerror( "%s, addr 0x%08x len %4u (0x%04x)\n", label, addr, unsigned( len ), unsigned( len ) ); + status = libusb_control_transfer( device, LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, + opcode, addr & 0xFFFF, addr >> 16, const_cast( data ), + uint16_t( len ), 1000 ); + if ( status != signed( len ) ) { + if ( status < 0 ) + logerror( "%s: %s\n", label, libusb_error_name( status ) ); else - logerror("%s ==> %d\n", label, status); + logerror( "%s ==> %d\n", label, status ); } - return (status < 0) ? -EIO : 0; + return ( status < 0 ) ? -EIO : 0; } /* * Modifies the CPUCS register to stop or reset the CPU. * Returns false on error. */ -static bool ezusb_cpucs(libusb_device_handle *device, uint32_t addr, bool doRun) { +static bool ezusb_cpucs( libusb_device_handle *device, uint32_t addr, bool doRun ) { int status; uint8_t data = doRun ? 0x00 : 0x01; - if (verbose) logerror("%s\n", data ? "stop CPU" : "reset CPU"); - status = libusb_control_transfer(device, LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, - RW_INTERNAL, addr & 0xFFFF, addr >> 16, &data, 1, 1000); - if ((status != 1) && - /* We may get an I/O error from libusb as the device disappears */ - ((!doRun) || (status != LIBUSB_ERROR_IO))) { + if ( verbose ) + logerror( "%s\n", data ? "stop CPU" : "reset CPU" ); + status = + libusb_control_transfer( device, LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, + RW_INTERNAL, addr & 0xFFFF, addr >> 16, &data, 1, 1000 ); + if ( ( status != 1 ) && + /* We may get an I/O error from libusb as the device disappears */ + ( ( !doRun ) || ( status != LIBUSB_ERROR_IO ) ) ) { const char *mesg = "can't modify CPUCS"; - if (status < 0) - logerror("%s: %s\n", mesg, libusb_error_name(status)); + if ( status < 0 ) + logerror( "%s: %s\n", mesg, libusb_error_name( status ) ); else - logerror("%s\n", mesg); + logerror( "%s\n", mesg ); return false; } else return true; @@ -183,19 +192,21 @@ static bool ezusb_cpucs(libusb_device_handle *device, uint32_t addr, bool doRun) * Send an FX3 jump to address command * Returns false on error. */ -static bool ezusb_fx3_jump(libusb_device_handle *device, uint32_t addr) { +static bool ezusb_fx3_jump( libusb_device_handle *device, uint32_t addr ) { int status; - if (verbose) logerror("transfer execution to Program Entry at 0x%08x\n", addr); - status = libusb_control_transfer(device, LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, - RW_INTERNAL, addr & 0xFFFF, addr >> 16, nullptr, 0, 1000); + if ( verbose ) + logerror( "transfer execution to Program Entry at 0x%08x\n", addr ); + status = + libusb_control_transfer( device, LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE, + RW_INTERNAL, addr & 0xFFFF, addr >> 16, nullptr, 0, 1000 ); /* We may get an I/O error from libusb as the device disappears */ - if ((status != 0) && (status != LIBUSB_ERROR_IO)) { + if ( ( status != 0 ) && ( status != LIBUSB_ERROR_IO ) ) { const char *mesg = "failed to send jump command"; - if (status < 0) - logerror("%s: %s\n", mesg, libusb_error_name(status)); + if ( status < 0 ) + logerror( "%s: %s\n", mesg, libusb_error_name( status ) ); else - logerror("%s\n", mesg); + logerror( "%s\n", mesg ); return false; } else return true; @@ -219,9 +230,10 @@ static bool ezusb_fx3_jump(libusb_device_handle *device, uint32_t addr) { * Caller is responsible for halting CPU as needed, such as when * overwriting a second stage loader. */ -static int parse_ihex(FILE *image, void *context, bool (*is_external)(uint32_t addr, size_t len), - int (*poke)(void *context, uint32_t addr, bool external, const unsigned char *data, size_t len)) { - unsigned char data[1023]; +static int parse_ihex( FILE *image, void *context, bool ( *is_external )( uint32_t addr, size_t len ), + int ( *poke )( void *context, uint32_t addr, bool external, const unsigned char *data, + size_t len ) ) { + unsigned char data[ 1023 ]; uint32_t data_addr = 0; size_t data_len = 0; int rc; @@ -238,100 +250,108 @@ static int parse_ihex(FILE *image, void *context, bool (*is_external)(uint32_t a * Note that EEPROM segments max out at 1023 bytes; the upload protocol * allows segments of up to 64 KBytes (more than a loader could handle). */ - for (;;) { - char buf[512], *cp; + for ( ;; ) { + char buf[ 512 ], *cp; char tmp, type; size_t len; unsigned idx, off; - cp = fgets(buf, sizeof(buf), image); - if (cp == nullptr) { - logerror("EOF without EOF record!\n"); + cp = fgets( buf, sizeof( buf ), image ); + if ( cp == nullptr ) { + logerror( "EOF without EOF record!\n" ); break; } /* EXTENSION: "# comment-till-end-of-line", for copyrights etc */ - if (buf[0] == '#') continue; + if ( buf[ 0 ] == '#' ) + continue; - if (buf[0] != ':') { - logerror("not an ihex record: %s", buf); + if ( buf[ 0 ] != ':' ) { + logerror( "not an ihex record: %s", buf ); return -2; } /* ignore any newline */ - cp = strchr(buf, '\n'); - if (cp) *cp = 0; + cp = strchr( buf, '\n' ); + if ( cp ) + *cp = 0; - if (verbose >= 3) logerror("** LINE: %s\n", buf); + if ( verbose >= 3 ) + logerror( "** LINE: %s\n", buf ); /* Read the length field (up to 16 bytes) */ - tmp = buf[3]; - buf[3] = 0; - len = strtoul(buf + 1, nullptr, 16); - buf[3] = tmp; + tmp = buf[ 3 ]; + buf[ 3 ] = 0; + len = strtoul( buf + 1, nullptr, 16 ); + buf[ 3 ] = tmp; /* Read the target offset (address up to 64KB) */ - tmp = buf[7]; - buf[7] = 0; - off = unsigned(strtoul(buf + 3, nullptr, 16)); - buf[7] = tmp; + tmp = buf[ 7 ]; + buf[ 7 ] = 0; + off = unsigned( strtoul( buf + 3, nullptr, 16 ) ); + buf[ 7 ] = tmp; /* Initialize data_addr */ - if (first_line) { + if ( first_line ) { data_addr = off; first_line = 0; } /* Read the record type */ - tmp = buf[9]; - buf[9] = 0; - type = char(strtoul(buf + 7, nullptr, 16)); - buf[9] = tmp; + tmp = buf[ 9 ]; + buf[ 9 ] = 0; + type = char( strtoul( buf + 7, nullptr, 16 ) ); + buf[ 9 ] = tmp; /* If this is an EOF record, then make it so. */ - if (type == 1) { - if (verbose >= 2) logerror("EOF on hexfile\n"); + if ( type == 1 ) { + if ( verbose >= 2 ) + logerror( "EOF on hexfile\n" ); break; } - if (type != 0) { - logerror("unsupported record type: %d\n", type); + if ( type != 0 ) { + logerror( "unsupported record type: %d\n", type ); return -3; } - if ((len * 2) + 11 > strlen(buf)) { - logerror("record too short?\n"); + if ( ( len * 2 ) + 11 > strlen( buf ) ) { + logerror( "record too short?\n" ); return -4; } /* flush the saved data if it's not contiguous, - * or when we've buffered as much as we can. - */ - if (data_len != 0 && (off != (data_addr + data_len) - /* || !merge */ - || (data_len + len) > sizeof(data))) { - if (is_external) external = is_external(data_addr, data_len); - rc = poke(context, data_addr, external, data, data_len); - if (rc < 0) return -1; + * or when we've buffered as much as we can. + */ + if ( data_len != 0 && ( off != ( data_addr + data_len ) + /* || !merge */ + || ( data_len + len ) > sizeof( data ) ) ) { + if ( is_external ) + external = is_external( data_addr, data_len ); + rc = poke( context, data_addr, external, data, data_len ); + if ( rc < 0 ) + return -1; data_addr = off; data_len = 0; } /* append to saved data, flush later */ - for (idx = 0, cp = buf + 9; idx < len; idx += 1, cp += 2) { - tmp = cp[2]; - cp[2] = 0; - data[data_len + idx] = uint8_t(strtoul(cp, nullptr, 16)); - cp[2] = tmp; + for ( idx = 0, cp = buf + 9; idx < len; idx += 1, cp += 2 ) { + tmp = cp[ 2 ]; + cp[ 2 ] = 0; + data[ data_len + idx ] = uint8_t( strtoul( cp, nullptr, 16 ) ); + cp[ 2 ] = tmp; } data_len += len; } /* flush any data remaining */ - if (data_len != 0) { - if (is_external) external = is_external(data_addr, data_len); - rc = poke(context, data_addr, external, data, data_len); - if (rc < 0) return -1; + if ( data_len != 0 ) { + if ( is_external ) + external = is_external( data_addr, data_len ); + rc = poke( context, data_addr, external, data, data_len ); + if ( rc < 0 ) + return -1; } return 0; } @@ -355,33 +375,37 @@ struct ram_poke_context { #define RETRY_LIMIT 5 -static int ram_poke(void *context, uint32_t addr, bool external, const unsigned char *data, size_t len) { - struct ram_poke_context *ctx = static_cast(context); +static int ram_poke( void *context, uint32_t addr, bool external, const unsigned char *data, size_t len ) { + struct ram_poke_context *ctx = static_cast( context ); int rc; unsigned retry = 0; - switch (ctx->mode) { + switch ( ctx->mode ) { case internal_only: /* CPU should be stopped */ - if (external) { - logerror("can't write %u bytes external memory at 0x%08x\n", unsigned(len), addr); + if ( external ) { + logerror( "can't write %u bytes external memory at 0x%08x\n", unsigned( len ), addr ); return -EINVAL; } break; case skip_internal: /* CPU must be running */ - if (!external) { - if (verbose >= 2) { logerror("SKIP on-chip RAM, %u bytes at 0x%08x\n", unsigned(len), addr); } + if ( !external ) { + if ( verbose >= 2 ) { + logerror( "SKIP on-chip RAM, %u bytes at 0x%08x\n", unsigned( len ), addr ); + } return 0; } break; case skip_external: /* CPU should be stopped */ - if (external) { - if (verbose >= 2) { logerror("SKIP external RAM, %u bytes at 0x%08x\n", unsigned(len), addr); } + if ( external ) { + if ( verbose >= 2 ) { + logerror( "SKIP external RAM, %u bytes at 0x%08x\n", unsigned( len ), addr ); + } return 0; } break; case _undef: default: - logerror("bug\n"); + logerror( "bug\n" ); return -EDOM; } @@ -391,10 +415,11 @@ static int ram_poke(void *context, uint32_t addr, bool external, const unsigned /* Retry this till we get a real error. Control messages are not * NAKed (just dropped) so time out means is a real problem. */ - while ((rc = ezusb_write(ctx->device, external ? "write external" : "write on-chip", - external ? RW_MEMORY : RW_INTERNAL, addr, data, len)) < 0 && - retry < RETRY_LIMIT) { - if (rc != LIBUSB_ERROR_TIMEOUT) break; + while ( ( rc = ezusb_write( ctx->device, external ? "write external" : "write on-chip", + external ? RW_MEMORY : RW_INTERNAL, addr, data, len ) ) < 0 && + retry < RETRY_LIMIT ) { + if ( rc != LIBUSB_ERROR_TIMEOUT ) + break; retry += 1; } return rc; @@ -404,108 +429,113 @@ static int ram_poke(void *context, uint32_t addr, bool external, const unsigned * Load a Cypress Image file into target RAM. * See http://www.cypress.com/?docID=41351 (AN76405 PDF) for more info. */ -static int fx3_load_ram(libusb_device_handle *device, const char *path) { +static int fx3_load_ram( libusb_device_handle *device, const char *path ) { uint32_t dCheckSum, dExpectedCheckSum, dAddress, i, dLen, dLength; uint32_t *dImageBuf; - unsigned char *bBuf, hBuf[4], blBuf[4], rBuf[4096]; + unsigned char *bBuf, hBuf[ 4 ], blBuf[ 4 ], rBuf[ 4096 ]; FILE *image; int ret = 0; - image = fopen(path, "rb"); - if (image == nullptr) { - logerror("unable to open '%s' for input\n", path); + image = fopen( path, "rb" ); + if ( image == nullptr ) { + logerror( "unable to open '%s' for input\n", path ); return -2; - } else if (verbose) - logerror("open firmware image %s for RAM upload\n", path); + } else if ( verbose ) + logerror( "open firmware image %s for RAM upload\n", path ); // Read header - if (fread(hBuf, sizeof(char), sizeof(hBuf), image) != sizeof(hBuf)) { - logerror("could not read image header"); + if ( fread( hBuf, sizeof( char ), sizeof( hBuf ), image ) != sizeof( hBuf ) ) { + logerror( "could not read image header" ); ret = -3; goto exit; } // check "CY" signature byte and format - if ((hBuf[0] != 'C') || (hBuf[1] != 'Y')) { - logerror("image doesn't have a CYpress signature\n"); + if ( ( hBuf[ 0 ] != 'C' ) || ( hBuf[ 1 ] != 'Y' ) ) { + logerror( "image doesn't have a CYpress signature\n" ); ret = -3; goto exit; } // Check bImageType - switch (hBuf[3]) { + switch ( hBuf[ 3 ] ) { case 0xB0: - if (verbose) logerror("normal FW binary %s image with checksum\n", (hBuf[2] & 0x01) ? "data" : "executable"); + if ( verbose ) + logerror( "normal FW binary %s image with checksum\n", ( hBuf[ 2 ] & 0x01 ) ? "data" : "executable" ); break; case 0xB1: - logerror("security binary image is not currently supported\n"); + logerror( "security binary image is not currently supported\n" ); ret = -3; goto exit; case 0xB2: - logerror("VID:PID image is not currently supported\n"); + logerror( "VID:PID image is not currently supported\n" ); ret = -3; goto exit; default: - logerror("invalid image type 0x%02X\n", hBuf[3]); + logerror( "invalid image type 0x%02X\n", hBuf[ 3 ] ); ret = -3; goto exit; } // Read the bootloader version - if (verbose) { - if ((ezusb_read(device, "read bootloader version", RW_INTERNAL, 0xFFFF0020, blBuf, 4) < 0)) { - logerror("Could not read bootloader version\n"); + if ( verbose ) { + if ( ( ezusb_read( device, "read bootloader version", RW_INTERNAL, 0xFFFF0020, blBuf, 4 ) < 0 ) ) { + logerror( "Could not read bootloader version\n" ); ret = -8; goto exit; } - logerror("FX3 bootloader version: 0x%02X%02X%02X%02X\n", blBuf[3], blBuf[2], blBuf[1], blBuf[0]); + logerror( "FX3 bootloader version: 0x%02X%02X%02X%02X\n", blBuf[ 3 ], blBuf[ 2 ], blBuf[ 1 ], blBuf[ 0 ] ); } dCheckSum = 0; - if (verbose) logerror("writing image...\n"); - while (1) { - if ((fread(&dLength, sizeof(uint32_t), 1, image) != 1) || // read dLength - (fread(&dAddress, sizeof(uint32_t), 1, image) != 1)) { // read dAddress - logerror("could not read image"); + if ( verbose ) + logerror( "writing image...\n" ); + while ( 1 ) { + if ( ( fread( &dLength, sizeof( uint32_t ), 1, image ) != 1 ) || // read dLength + ( fread( &dAddress, sizeof( uint32_t ), 1, image ) != 1 ) ) { // read dAddress + logerror( "could not read image" ); ret = -3; goto exit; } - if (dLength == 0) break; // done + if ( dLength == 0 ) + break; // done // coverity[tainted_data] - dImageBuf = static_cast(calloc(dLength, sizeof(uint32_t))); - if (dImageBuf == nullptr) { - logerror("could not allocate buffer for image chunk\n"); + dImageBuf = static_cast( calloc( dLength, sizeof( uint32_t ) ) ); + if ( dImageBuf == nullptr ) { + logerror( "could not allocate buffer for image chunk\n" ); ret = -4; goto exit; } // read sections - if (fread(dImageBuf, sizeof(uint32_t), dLength, image) != dLength) { - logerror("could not read image"); - free(dImageBuf); + if ( fread( dImageBuf, sizeof( uint32_t ), dLength, image ) != dLength ) { + logerror( "could not read image" ); + free( dImageBuf ); ret = -3; goto exit; } - for (i = 0; i < dLength; i++) dCheckSum += dImageBuf[i]; + for ( i = 0; i < dLength; i++ ) + dCheckSum += dImageBuf[ i ]; dLength <<= 2; // convert to Byte length - bBuf = reinterpret_cast(dImageBuf); + bBuf = reinterpret_cast( dImageBuf ); - while (dLength > 0) { + while ( dLength > 0 ) { dLen = 4096; // 4K max - if (dLen > dLength) dLen = dLength; - if ((ezusb_write(device, "write firmware", RW_INTERNAL, dAddress, bBuf, dLen) < 0) || - (ezusb_read(device, "read firmware", RW_INTERNAL, dAddress, rBuf, dLen) < 0)) { - logerror("R/W error\n"); - free(dImageBuf); + if ( dLen > dLength ) + dLen = dLength; + if ( ( ezusb_write( device, "write firmware", RW_INTERNAL, dAddress, bBuf, dLen ) < 0 ) || + ( ezusb_read( device, "read firmware", RW_INTERNAL, dAddress, rBuf, dLen ) < 0 ) ) { + logerror( "R/W error\n" ); + free( dImageBuf ); ret = -5; goto exit; } // Verify data: rBuf with bBuf - for (i = 0; i < dLen; i++) { - if (rBuf[i] != bBuf[i]) { - logerror("verify error"); - free(dImageBuf); + for ( i = 0; i < dLen; i++ ) { + if ( rBuf[ i ] != bBuf[ i ] ) { + logerror( "verify error" ); + free( dImageBuf ); ret = -6; goto exit; } @@ -515,21 +545,23 @@ static int fx3_load_ram(libusb_device_handle *device, const char *path) { bBuf += dLen; dAddress += dLen; } - free(dImageBuf); + free( dImageBuf ); } // read pre-computed checksum data - if ((fread(&dExpectedCheckSum, sizeof(uint32_t), 1, image) != 1) || (dCheckSum != dExpectedCheckSum)) { - logerror("checksum error\n"); + if ( ( fread( &dExpectedCheckSum, sizeof( uint32_t ), 1, image ) != 1 ) || ( dCheckSum != dExpectedCheckSum ) ) { + logerror( "checksum error\n" ); ret = -7; goto exit; } // transfer execution to Program Entry - if (!ezusb_fx3_jump(device, dAddress)) { ret = -6; } + if ( !ezusb_fx3_jump( device, dAddress ) ) { + ret = -6; + } exit: - fclose(image); + fclose( image ); return ret; } @@ -547,26 +579,27 @@ static int fx3_load_ram(libusb_device_handle *device, const char *path) { * memory is written, expecting a second stage loader to have already * been loaded. Then file is re-parsed and on-chip memory is written. */ -int ezusb_load_ram(libusb_device_handle *device, const char *path, int fx_type, int stage) { +int ezusb_load_ram( libusb_device_handle *device, const char *path, int fx_type, int stage ) { FILE *image; uint32_t cpucs_addr; - bool (*is_external)(uint32_t off, size_t len); + bool ( *is_external )( uint32_t off, size_t len ); struct ram_poke_context ctx; int status; int ret = 0; - if (fx_type == FX_TYPE_FX3) return fx3_load_ram(device, path); + if ( fx_type == FX_TYPE_FX3 ) + return fx3_load_ram( device, path ); - image = fopen(path, "rb"); - if (image == nullptr) { - logerror("%s: unable to open for input.\n", path); + image = fopen( path, "rb" ); + if ( image == nullptr ) { + logerror( "%s: unable to open for input.\n", path ); return -2; - } else if (verbose > 1) - logerror("open firmware image %s for RAM upload\n", path); + } else if ( verbose > 1 ) + logerror( "open firmware image %s for RAM upload\n", path ); /* EZ-USB original/FX and FX2 devices differ, apart from the 8051 core */ - switch (fx_type) { + switch ( fx_type ) { case FX_TYPE_FX2LP: cpucs_addr = 0xe600; is_external = fx2lp_is_external; @@ -582,11 +615,11 @@ int ezusb_load_ram(libusb_device_handle *device, const char *path, int fx_type, } /* use only first stage loader? */ - if (stage == 0) { + if ( stage == 0 ) { ctx.mode = internal_only; /* if required, halt the CPU while we overwrite its code/data */ - if (cpucs_addr && !ezusb_cpucs(device, cpucs_addr, false)) { + if ( cpucs_addr && !ezusb_cpucs( device, cpucs_addr, false ) ) { ret = -1; goto exit; } @@ -596,49 +629,52 @@ int ezusb_load_ram(libusb_device_handle *device, const char *path, int fx_type, ctx.mode = skip_internal; /* let CPU run; overwrite the 2nd stage loader later */ - if (verbose) logerror("2nd stage: write external memory\n"); + if ( verbose ) + logerror( "2nd stage: write external memory\n" ); } /* scan the image, first (maybe only) time */ ctx.device = device; ctx.total = ctx.count = 0; - status = parse_ihex(image, &ctx, is_external, ram_poke); - if (status < 0) { - logerror("unable to upload %s\n", path); + status = parse_ihex( image, &ctx, is_external, ram_poke ); + if ( status < 0 ) { + logerror( "unable to upload %s\n", path ); ret = status; goto exit; } /* second part of 2nd stage: rescan */ - if (stage) { + if ( stage ) { ctx.mode = skip_external; /* if needed, halt the CPU while we overwrite the 1st stage loader */ - if (cpucs_addr && !ezusb_cpucs(device, cpucs_addr, false)) { + if ( cpucs_addr && !ezusb_cpucs( device, cpucs_addr, false ) ) { ret = -1; goto exit; } /* at least write the interrupt vectors (at 0x0000) for reset! */ - rewind(image); - if (verbose) logerror("2nd stage: write on-chip memory\n"); - status = parse_ihex(image, &ctx, is_external, ram_poke); - if (status < 0) { - logerror("unable to completely upload %s\n", path); + rewind( image ); + if ( verbose ) + logerror( "2nd stage: write on-chip memory\n" ); + status = parse_ihex( image, &ctx, is_external, ram_poke ); + if ( status < 0 ) { + logerror( "unable to completely upload %s\n", path ); ret = status; goto exit; } } - if (verbose && (ctx.count != 0)) { - logerror("... WROTE: %d bytes, %d segments, avg %d\n", int(ctx.total), int(ctx.count), - int(ctx.total / ctx.count)); + if ( verbose && ( ctx.count != 0 ) ) { + logerror( "... WROTE: %d bytes, %d segments, avg %d\n", int( ctx.total ), int( ctx.count ), + int( ctx.total / ctx.count ) ); } /* if required, reset the CPU so it runs what we just uploaded */ - if (cpucs_addr && !ezusb_cpucs(device, cpucs_addr, true)) ret = -1; + if ( cpucs_addr && !ezusb_cpucs( device, cpucs_addr, true ) ) + ret = -1; exit: - fclose(image); + fclose( image ); return ret; } diff --git a/openhantek/src/usb/ezusb.h b/openhantek/src/usb/ezusb.h index 63679f3c..5047bbf6 100644 --- a/openhantek/src/usb/ezusb.h +++ b/openhantek/src/usb/ezusb.h @@ -16,7 +16,7 @@ * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License - * along with this program. If not, see . + * along with this program. If not, see . */ #include @@ -34,7 +34,7 @@ struct libusb_device_handle; * * The target processor is reset at the end of this upload. */ -extern int ezusb_load_ram(libusb_device_handle *device, const char *path, int fx_type, int stage); +extern int ezusb_load_ram( libusb_device_handle *device, const char *path, int fx_type, int stage ); /* Verbosity level (default 1). Can be increased or decreased with options v/q */ diff --git a/openhantek/src/usb/finddevices.cpp b/openhantek/src/usb/finddevices.cpp index 8835a2d9..c3004cbe 100644 --- a/openhantek/src/usb/finddevices.cpp +++ b/openhantek/src/usb/finddevices.cpp @@ -7,13 +7,13 @@ #include #include -#include #include "ezusb.h" #include "utils/printutils.h" +#include #ifdef __FreeBSD__ - #include +#include #else - #include +#include #endif #include "modelregistry.h" @@ -25,15 +25,15 @@ FindDevices::FindDevices( libusb_context *context ) : context( context ) {} // Iterate all devices on USB and keep track of all supported scopes int FindDevices::updateDeviceList() { libusb_device **deviceList; - ssize_t deviceCount = libusb_get_device_list(context, &deviceList); - if (deviceCount < 0) { - return int(deviceCount); + ssize_t deviceCount = libusb_get_device_list( context, &deviceList ); + if ( deviceCount < 0 ) { + return int( deviceCount ); } ++findIteration; int changes = 0; - for (ssize_t deviceIndex = 0; deviceIndex < deviceCount; ++deviceIndex ) { + for ( ssize_t deviceIndex = 0; deviceIndex < deviceCount; ++deviceIndex ) { libusb_device *device = deviceList[ deviceIndex ]; // Get device descriptor struct libusb_device_descriptor descriptor; @@ -45,27 +45,28 @@ int FindDevices::updateDeviceList() { const UniqueUSBid USBid = USBDevice::computeUSBdeviceID( device ); DeviceList::const_iterator inList = devices.find( USBid ); - if ( inList != devices.end()) { // already in list, update heartbeat only + if ( inList != devices.end() ) { // already in list, update heartbeat only inList->second->setFindIteration( findIteration ); continue; } // else check against all supported models for match - for (DSOModel* model : ModelRegistry::get()->models()) { + for ( DSOModel *model : ModelRegistry::get()->models() ) { // Check VID and PID for firmware flashed devices bool supported = descriptor.idVendor == model->vendorID && descriptor.idProduct == model->productID; // Devices without firmware have different VID/PIDs - supported |= descriptor.idVendor == model->vendorIDnoFirmware && descriptor.idProduct == model->productIDnoFirmware; - if (supported) { // put matching device into list + supported |= + descriptor.idVendor == model->vendorIDnoFirmware && descriptor.idProduct == model->productIDnoFirmware; + if ( supported ) { // put matching device into list ++changes; // printf( "+ %016lX %s\n", USBid, model->name.c_str() ); - devices[ USBid ] = std::unique_ptr(new USBDevice( model, device, findIteration ) ); + devices[ USBid ] = std::unique_ptr( new USBDevice( model, device, findIteration ) ); break; // stop after 1st supported model (there can be more models with identical VID/PID) } } } // Remove non existing devices - for ( DeviceList::iterator it=devices.begin(); it!=devices.end(); ) { + for ( DeviceList::iterator it = devices.begin(); it != devices.end(); ) { if ( it->second->getFindIteration() != findIteration ) { // heartbeat not up to date, no more on the bus ++changes; // printf( "- %016lX\n", it->first ); @@ -86,14 +87,10 @@ int FindDevices::updateDeviceList() { } -const FindDevices::DeviceList* FindDevices::getDevices() -{ - return &devices; -} +const FindDevices::DeviceList *FindDevices::getDevices() { return &devices; } -std::unique_ptr FindDevices::takeDevice( UniqueUSBid id ) -{ +std::unique_ptr FindDevices::takeDevice( UniqueUSBid id ) { DeviceList::iterator it = devices.find( id ); if ( it == devices.end() ) return nullptr; diff --git a/openhantek/src/usb/finddevices.h b/openhantek/src/usb/finddevices.h index a64825df..c6ebe6af 100644 --- a/openhantek/src/usb/finddevices.h +++ b/openhantek/src/usb/finddevices.h @@ -3,9 +3,9 @@ #pragma once #include -#include -#include #include +#include +#include #include "usbdevice.h" @@ -20,7 +20,7 @@ struct libusb_context; * * Do not close the given usb context before this class object is destroyed. */ -class FindDevices{ +class FindDevices { public: typedef std::map> DeviceList; explicit FindDevices( libusb_context *context ); @@ -33,7 +33,8 @@ class FindDevices{ * @param id The unique usb id for the current bus layout * @return A shared reference to the */ - std::unique_ptr takeDevice(UniqueUSBid id); + std::unique_ptr takeDevice( UniqueUSBid id ); + private: libusb_context *context; ///< The usb context used for this device DeviceList devices; diff --git a/openhantek/src/usb/uploadFirmware.cpp b/openhantek/src/usb/uploadFirmware.cpp index fb161864..29eda9b9 100644 --- a/openhantek/src/usb/uploadFirmware.cpp +++ b/openhantek/src/usb/uploadFirmware.cpp @@ -5,9 +5,9 @@ #include #include #ifdef __FreeBSD__ - #include +#include #else - #include +#include #endif #include @@ -19,23 +19,25 @@ #define TR( str ) ( QString( "UploadFirmware: " ) + QCoreApplication::translate( "UploadFirmware", str ) ) -bool UploadFirmware::startUpload(USBDevice *device) { - if (device->isConnected() || !device->needsFirmware()) return false; +bool UploadFirmware::startUpload( USBDevice *device ) { + if ( device->isConnected() || !device->needsFirmware() ) + return false; // Open device libusb_device_handle *handle; - int status = libusb_open(device->getRawDevice(), &handle); - if ( status != LIBUSB_SUCCESS) { + int status = libusb_open( device->getRawDevice(), &handle ); + if ( status != LIBUSB_SUCCESS ) { handle = nullptr; - errorMessage = TR("Couldn't open device: %1").arg(libUsbErrorString( status )); + errorMessage = TR( "Couldn't open device: %1" ).arg( libUsbErrorString( status ) ); return false; } // Write firmware from resources to temp files QFile firmwareRes( - QString(":/firmware/%1-firmware.hex").arg(QString::fromStdString(device->getModel()->firmwareToken))); - auto temp_firmware_path = std::unique_ptr(QTemporaryFile::createNativeFile(firmwareRes)); - if (!temp_firmware_path) return false; + QString( ":/firmware/%1-firmware.hex" ).arg( QString::fromStdString( device->getModel()->firmwareToken ) ) ); + auto temp_firmware_path = std::unique_ptr( QTemporaryFile::createNativeFile( firmwareRes ) ); + if ( !temp_firmware_path ) + return false; temp_firmware_path->open(); #ifdef __linux__ @@ -49,27 +51,26 @@ bool UploadFirmware::startUpload(USBDevice *device) { #endif // We need to claim the first interface (num=0) - status = libusb_claim_interface(handle, 0); - if (status != LIBUSB_SUCCESS) { - errorMessage = TR("libusb_claim_interface() failed: %1").arg(libusb_error_name(status)); - libusb_close(handle); + status = libusb_claim_interface( handle, 0 ); + if ( status != LIBUSB_SUCCESS ) { + errorMessage = TR( "libusb_claim_interface() failed: %1" ).arg( libusb_error_name( status ) ); + libusb_close( handle ); return false; } // Write firmware into internal RAM using first stage loader built into EZ-USB hardware - status = ezusb_load_ram(handle, temp_firmware_path->fileName().toUtf8().constData(), FX_TYPE_FX2LP, 0); - if (status != LIBUSB_SUCCESS) { - errorMessage = TR("Writing the main firmware failed: %1").arg(libusb_error_name(status)); - libusb_release_interface(handle, 0); - libusb_close(handle); + status = ezusb_load_ram( handle, temp_firmware_path->fileName().toUtf8().constData(), FX_TYPE_FX2LP, 0 ); + if ( status != LIBUSB_SUCCESS ) { + errorMessage = TR( "Writing the main firmware failed: %1" ).arg( libusb_error_name( status ) ); + libusb_release_interface( handle, 0 ); + libusb_close( handle ); return false; } - status = libusb_release_interface(handle, 0); - libusb_close(handle); + status = libusb_release_interface( handle, 0 ); + libusb_close( handle ); return status == LIBUSB_SUCCESS; } const QString &UploadFirmware::getErrorMessage() const { return errorMessage; } - diff --git a/openhantek/src/usb/uploadFirmware.h b/openhantek/src/usb/uploadFirmware.h index 1986f85e..10d10a85 100644 --- a/openhantek/src/usb/uploadFirmware.h +++ b/openhantek/src/usb/uploadFirmware.h @@ -12,8 +12,9 @@ class USBDevice; */ class UploadFirmware { public: - bool startUpload(USBDevice *device); + bool startUpload( USBDevice *device ); const QString &getErrorMessage() const; + private: QString errorMessage; }; diff --git a/openhantek/src/usb/usbdevice.cpp b/openhantek/src/usb/usbdevice.cpp index a4a0bd32..d785e15a 100644 --- a/openhantek/src/usb/usbdevice.cpp +++ b/openhantek/src/usb/usbdevice.cpp @@ -12,36 +12,36 @@ #include -QString libUsbErrorString(int error) { - switch (error) { +QString libUsbErrorString( int error ) { + switch ( error ) { case LIBUSB_SUCCESS: - return QCoreApplication::tr("Success (no error)"); + return QCoreApplication::tr( "Success (no error)" ); case LIBUSB_ERROR_IO: - return QCoreApplication::tr("Input/output error"); + return QCoreApplication::tr( "Input/output error" ); case LIBUSB_ERROR_INVALID_PARAM: - return QCoreApplication::tr("Invalid parameter"); + return QCoreApplication::tr( "Invalid parameter" ); case LIBUSB_ERROR_ACCESS: - return QCoreApplication::tr("Access denied (insufficient permissions)"); + return QCoreApplication::tr( "Access denied (insufficient permissions)" ); case LIBUSB_ERROR_NO_DEVICE: - return QCoreApplication::tr("No such device (it may have been disconnected)"); + return QCoreApplication::tr( "No such device (it may have been disconnected)" ); case LIBUSB_ERROR_NOT_FOUND: - return QCoreApplication::tr("Entity not found"); + return QCoreApplication::tr( "Entity not found" ); case LIBUSB_ERROR_BUSY: - return QCoreApplication::tr("Resource busy"); + return QCoreApplication::tr( "Resource busy" ); case LIBUSB_ERROR_TIMEOUT: - return QCoreApplication::tr("Operation timed out"); + return QCoreApplication::tr( "Operation timed out" ); case LIBUSB_ERROR_OVERFLOW: - return QCoreApplication::tr("Overflow"); + return QCoreApplication::tr( "Overflow" ); case LIBUSB_ERROR_PIPE: - return QCoreApplication::tr("Pipe error"); + return QCoreApplication::tr( "Pipe error" ); case LIBUSB_ERROR_INTERRUPTED: - return QCoreApplication::tr("System call interrupted (perhaps due to signal)"); + return QCoreApplication::tr( "System call interrupted (perhaps due to signal)" ); case LIBUSB_ERROR_NO_MEM: - return QCoreApplication::tr("Insufficient memory"); + return QCoreApplication::tr( "Insufficient memory" ); case LIBUSB_ERROR_NOT_SUPPORTED: - return QCoreApplication::tr("Operation not supported or unimplemented on this platform"); + return QCoreApplication::tr( "Operation not supported or unimplemented on this platform" ); default: - return QCoreApplication::tr("Other error"); + return QCoreApplication::tr( "Other error" ); } } @@ -58,10 +58,10 @@ UniqueUSBid USBDevice::computeUSBdeviceID( libusb_device *device ) { // Get device descriptor struct libusb_device_descriptor descriptor; - libusb_get_device_descriptor(device, &descriptor); + libusb_get_device_descriptor( device, &descriptor ); // collect values and arrange them UniqueUSBid uid = libusb_get_bus_number( device ) & 0x0F; // typically no more than 15 busses - const int treeSize = 7; // port tree max size is 7 + const int treeSize = 7; // port tree max size is 7 uint8_t ports[ treeSize ]; int nPorts = libusb_get_port_numbers( device, ports, sizeof( ports ) ); for ( int iii = 0; iii < treeSize; ++iii ) { @@ -77,51 +77,53 @@ UniqueUSBid USBDevice::computeUSBdeviceID( libusb_device *device ) { } -USBDevice::USBDevice(DSOModel *model, libusb_device *device, unsigned findIteration) - : model(model), device(device), findIteration(findIteration), uniqueUSBdeviceID( computeUSBdeviceID( device ) ) { - libusb_ref_device(device); - libusb_get_device_descriptor(device, &descriptor); +USBDevice::USBDevice( DSOModel *model, libusb_device *device, unsigned findIteration ) + : model( model ), device( device ), findIteration( findIteration ), + uniqueUSBdeviceID( computeUSBdeviceID( device ) ) { + libusb_ref_device( device ); + libusb_get_device_descriptor( device, &descriptor ); } -bool USBDevice::connectDevice(QString &errorMessage) { - if (needsFirmware()) +bool USBDevice::connectDevice( QString &errorMessage ) { + if ( needsFirmware() ) return false; - if (isConnected()) + if ( isConnected() ) return true; // Open device - int errorCode = libusb_open(device, &(handle)); - if (errorCode != LIBUSB_SUCCESS) { + int errorCode = libusb_open( device, &( handle ) ); + if ( errorCode != LIBUSB_SUCCESS ) { handle = nullptr; - errorMessage = QCoreApplication::translate("", "Couldn't open device: %1").arg(libUsbErrorString(errorCode)); + errorMessage = + QCoreApplication::translate( "", "Couldn't open device: %1" ).arg( libUsbErrorString( errorCode ) ); return false; } // Find and claim interface errorCode = LIBUSB_ERROR_NOT_FOUND; libusb_config_descriptor *configDescriptor; - libusb_get_config_descriptor(device, 0, &configDescriptor); - for (int interfaceIndex = 0; interfaceIndex < int(configDescriptor->bNumInterfaces); ++interfaceIndex) { - const libusb_interface *pInterface = &configDescriptor->interface[interfaceIndex]; - if (pInterface->num_altsetting < 1) + libusb_get_config_descriptor( device, 0, &configDescriptor ); + for ( int interfaceIndex = 0; interfaceIndex < int( configDescriptor->bNumInterfaces ); ++interfaceIndex ) { + const libusb_interface *pInterface = &configDescriptor->interface[ interfaceIndex ]; + if ( pInterface->num_altsetting < 1 ) continue; - const libusb_interface_descriptor *interfaceDescriptor = &pInterface->altsetting[0]; + const libusb_interface_descriptor *interfaceDescriptor = &pInterface->altsetting[ 0 ]; if ( interfaceDescriptor->bInterfaceClass == LIBUSB_CLASS_VENDOR_SPEC && - interfaceDescriptor->bInterfaceSubClass == 0 && interfaceDescriptor->bInterfaceProtocol == 0 ) { + interfaceDescriptor->bInterfaceSubClass == 0 && interfaceDescriptor->bInterfaceProtocol == 0 ) { errorCode = claimInterface( interfaceDescriptor ); break; } } - libusb_free_config_descriptor(configDescriptor); + libusb_free_config_descriptor( configDescriptor ); - if (errorCode != LIBUSB_SUCCESS) { - errorMessage = QString("%1 (%2:%3)") - .arg(libUsbErrorString(errorCode)) - .arg(libusb_get_bus_number(device), 3, 10, QLatin1Char('0')) - .arg(libusb_get_device_address(device), 3, 10, QLatin1Char('0')); + if ( errorCode != LIBUSB_SUCCESS ) { + errorMessage = QString( "%1 (%2:%3)" ) + .arg( libUsbErrorString( errorCode ) ) + .arg( libusb_get_bus_number( device ), 3, 10, QLatin1Char( '0' ) ) + .arg( libusb_get_device_address( device ), 3, 10, QLatin1Char( '0' ) ); return false; } @@ -132,16 +134,16 @@ bool USBDevice::connectDevice(QString &errorMessage) { USBDevice::~USBDevice() { disconnectFromDevice(); #if defined Q_OS_WIN - if (device != nullptr) - libusb_unref_device(device); + if ( device != nullptr ) + libusb_unref_device( device ); device = nullptr; #endif } int USBDevice::claimInterface( const libusb_interface_descriptor *interfaceDescriptor ) { - int errorCode = libusb_claim_interface(this->handle, interfaceDescriptor->bInterfaceNumber); - if (errorCode < 0) + int errorCode = libusb_claim_interface( this->handle, interfaceDescriptor->bInterfaceNumber ); + if ( errorCode < 0 ) return errorCode; nInterface = interfaceDescriptor->bInterfaceNumber; @@ -150,8 +152,8 @@ int USBDevice::claimInterface( const libusb_interface_descriptor *interfaceDescr const libusb_endpoint_descriptor *endpointDescriptor; this->outPacketLength = 0; this->inPacketLength = 0; - for (int endpoint = 0; endpoint < interfaceDescriptor->bNumEndpoints; ++endpoint) { - endpointDescriptor = &(interfaceDescriptor->endpoint[endpoint]); + for ( int endpoint = 0; endpoint < interfaceDescriptor->bNumEndpoints; ++endpoint ) { + endpointDescriptor = &( interfaceDescriptor->endpoint[ endpoint ] ); if ( endpointDescriptor->bEndpointAddress == HANTEK_EP_OUT ) { this->outPacketLength = endpointDescriptor->wMaxPacketSize; } else if ( endpointDescriptor->bEndpointAddress == HANTEK_EP_IN ) { @@ -163,21 +165,22 @@ int USBDevice::claimInterface( const libusb_interface_descriptor *interfaceDescr void USBDevice::disconnectFromDevice() { - if (!device) + if ( !device ) return; - if (this->handle) { + if ( this->handle ) { // Release claimed interface - if (nInterface != -1) libusb_release_interface(this->handle, nInterface); + if ( nInterface != -1 ) + libusb_release_interface( this->handle, nInterface ); nInterface = -1; // Close device handle - libusb_close(this->handle); + libusb_close( this->handle ); } this->handle = nullptr; #if !defined Q_OS_WIN - libusb_unref_device(device); + libusb_unref_device( device ); #endif emit deviceDisconnected(); @@ -188,26 +191,25 @@ bool USBDevice::isConnected() { return this->handle != nullptr; } bool USBDevice::needsFirmware() { - return this->descriptor.idProduct != model->productID - || this->descriptor.idVendor != model->vendorID - || this->descriptor.bcdDevice < model->firmwareVersion; + return this->descriptor.idProduct != model->productID || this->descriptor.idVendor != model->vendorID || + this->descriptor.bcdDevice < model->firmwareVersion; } -int USBDevice::bulkTransfer(unsigned char endpoint, const unsigned char *data, unsigned int length, int attempts, - unsigned int timeout) { - if (!this->handle) +int USBDevice::bulkTransfer( unsigned char endpoint, const unsigned char *data, unsigned int length, int attempts, + unsigned int timeout ) { + if ( !this->handle ) return LIBUSB_ERROR_NO_DEVICE; int errorCode = LIBUSB_ERROR_TIMEOUT; int transferred = 0; - for (int attempt = 0; (attempt < attempts || attempts == -1) && errorCode == LIBUSB_ERROR_TIMEOUT; ++attempt) - errorCode = - libusb_bulk_transfer(this->handle, endpoint, const_cast(data), int(length), &transferred, timeout); + for ( int attempt = 0; ( attempt < attempts || attempts == -1 ) && errorCode == LIBUSB_ERROR_TIMEOUT; ++attempt ) + errorCode = libusb_bulk_transfer( this->handle, endpoint, const_cast( data ), int( length ), + &transferred, timeout ); - if (errorCode == LIBUSB_ERROR_NO_DEVICE) + if ( errorCode == LIBUSB_ERROR_NO_DEVICE ) disconnectFromDevice(); - if (errorCode < 0) + if ( errorCode < 0 ) return errorCode; else return transferred; @@ -215,26 +217,27 @@ int USBDevice::bulkTransfer(unsigned char endpoint, const unsigned char *data, u #define BIG_BLOCK -int USBDevice::bulkReadMulti(unsigned char *data, unsigned length, int attempts) { - if (!this->handle) +int USBDevice::bulkReadMulti( unsigned char *data, unsigned length, int attempts ) { + if ( !this->handle ) return LIBUSB_ERROR_NO_DEVICE; - //printf("USBDevice::bulkReadMulti( %d )\n", length ); + // printf("USBDevice::bulkReadMulti( %d )\n", length ); #ifdef BIG_BLOCK // more stable if read as one big block - return this->bulkTransfer(HANTEK_EP_IN, data, length, attempts, HANTEK_TIMEOUT_MULTI * length / this->inPacketLength ); + return this->bulkTransfer( HANTEK_EP_IN, data, length, attempts, + HANTEK_TIMEOUT_MULTI * length / this->inPacketLength ); #else // unstable transfer if read in smaller chunks int errorCode = this->inPacketLength; unsigned int packet, received = 0; - for (packet = 0; received < length && errorCode == this->inPacketLength; ++packet) { - errorCode = this->bulkTransfer(HANTEK_EP_IN, data + packet * this->inPacketLength, - qMin(length - received, (unsigned int)this->inPacketLength), attempts, - HANTEK_TIMEOUT_MULTI); - if (errorCode > 0) + for ( packet = 0; received < length && errorCode == this->inPacketLength; ++packet ) { + errorCode = this->bulkTransfer( HANTEK_EP_IN, data + packet * this->inPacketLength, + qMin( length - received, (unsigned int)this->inPacketLength ), attempts, + HANTEK_TIMEOUT_MULTI ); + if ( errorCode > 0 ) received += (unsigned)errorCode; } - //printf( "total packets: %d, received: %d\n", packet, received ); - if (received > 0) + // printf( "total packets: %d, received: %d\n", packet, received ); + if ( received > 0 ) return (int)received; else return errorCode; @@ -242,19 +245,20 @@ int USBDevice::bulkReadMulti(unsigned char *data, unsigned length, int attempts) } -int USBDevice::controlTransfer(unsigned char type, unsigned char request, unsigned char *data, unsigned int length, - int value, int index, int attempts) { - if (!this->handle) +int USBDevice::controlTransfer( unsigned char type, unsigned char request, unsigned char *data, unsigned int length, + int value, int index, int attempts ) { + if ( !this->handle ) return LIBUSB_ERROR_NO_DEVICE; int errorCode = LIBUSB_ERROR_TIMEOUT; - //printf( "controlTransfer type %x request %x data[0] %d length %d value %d index %d attempts %d\n", - // type, request, data[0], length, value, index, attempts ); + // printf( "controlTransfer type %x request %x data[0] %d length %d value %d index %d attempts %d\n", + // type, request, data[0], length, value, index, attempts ); - for (int attempt = 0; (attempt < attempts || attempts == -1) && errorCode == LIBUSB_ERROR_TIMEOUT; ++attempt) - errorCode = libusb_control_transfer(this->handle, type, request, uint16_t(value), uint16_t(index), data, uint16_t(length), HANTEK_TIMEOUT); + for ( int attempt = 0; ( attempt < attempts || attempts == -1 ) && errorCode == LIBUSB_ERROR_TIMEOUT; ++attempt ) + errorCode = libusb_control_transfer( this->handle, type, request, uint16_t( value ), uint16_t( index ), data, + uint16_t( length ), HANTEK_TIMEOUT ); - if (errorCode == LIBUSB_ERROR_NO_DEVICE) + if ( errorCode == LIBUSB_ERROR_NO_DEVICE ) disconnectFromDevice(); return errorCode; } diff --git a/openhantek/src/usb/usbdevice.h b/openhantek/src/usb/usbdevice.h index fa3edff1..a0d62161 100644 --- a/openhantek/src/usb/usbdevice.h +++ b/openhantek/src/usb/usbdevice.h @@ -5,9 +5,9 @@ #include #include #ifdef __FreeBSD__ - #include +#include #else - #include +#include #endif #include @@ -21,7 +21,7 @@ typedef uint64_t UniqueUSBid; /// \brief Returns string representation for libusb errors. /// \param error The error code. /// \return String explaining the error. -QString libUsbErrorString(int error); +QString libUsbErrorString( int error ); /// \brief This class handles the USB communication with an usb device that has /// one in and one out endpoint. @@ -29,10 +29,10 @@ class USBDevice : public QObject { Q_OBJECT public: - explicit USBDevice(DSOModel* model, libusb_device *device, unsigned findIteration = 0); - USBDevice(const USBDevice&) = delete; + explicit USBDevice( DSOModel *model, libusb_device *device, unsigned findIteration = 0 ); + USBDevice( const USBDevice & ) = delete; ~USBDevice(); - bool connectDevice(QString &errorMessage); + bool connectDevice( QString &errorMessage ); void disconnectFromDevice(); /// \brief Check if the oscilloscope is connected. @@ -53,7 +53,7 @@ class USBDevice : public QObject { * Keep track of the find iteration on which this device was found * @param iteration The new iteration value */ - inline void setFindIteration(unsigned iteration) { findIteration = iteration; } + inline void setFindIteration( unsigned iteration ) { findIteration = iteration; } inline unsigned getFindIteration() const { return findIteration; } /// \brief Bulk transfer to/from the oscilloscope. @@ -64,16 +64,16 @@ class USBDevice : public QObject { /// \param timeout The timeout in ms. /// \return Number of transferred bytes on success, libusb error code on /// error. - int bulkTransfer(unsigned char endpoint, const unsigned char *data, unsigned int length, int attempts = HANTEK_ATTEMPTS, - unsigned int timeout = HANTEK_TIMEOUT); + int bulkTransfer( unsigned char endpoint, const unsigned char *data, unsigned int length, + int attempts = HANTEK_ATTEMPTS, unsigned int timeout = HANTEK_TIMEOUT ); /// \brief Bulk write to the oscilloscope. /// \param data Buffer for the sent/received data. /// \param length The length of the packet. /// \param attempts The number of attempts, that are done on timeouts. /// \return Number of sent bytes on success, libusb error code on error. - inline int bulkWrite(const unsigned char *data, unsigned int length, int attempts = HANTEK_ATTEMPTS) { - return bulkTransfer(HANTEK_EP_OUT, data, length, attempts); + inline int bulkWrite( const unsigned char *data, unsigned int length, int attempts = HANTEK_ATTEMPTS ) { + return bulkTransfer( HANTEK_EP_OUT, data, length, attempts ); } /// \brief Bulk read from the oscilloscope. @@ -81,9 +81,8 @@ class USBDevice : public QObject { /// \param length The length of the packet. /// \param attempts The number of attempts, that are done on timeouts. /// \return Number of received bytes on success, libusb error code on error. - template - inline int bulkRead(const T *command, int attempts = HANTEK_ATTEMPTS) { - return bulkTransfer(HANTEK_EP_IN, command->data(), command->size(), attempts); + template inline int bulkRead( const T *command, int attempts = HANTEK_ATTEMPTS ) { + return bulkTransfer( HANTEK_EP_IN, command->data(), command->size(), attempts ); } /// \brief Multi packet bulk read from the oscilloscope. @@ -91,7 +90,7 @@ class USBDevice : public QObject { /// \param length The length of data contained in the packets. /// \param attempts The number of attempts, that are done on timeouts. /// \return Number of received bytes on success, libusb error code on error. - int bulkReadMulti(unsigned char *data, unsigned length, int attempts = HANTEK_ATTEMPTS_MULTI); + int bulkReadMulti( unsigned char *data, unsigned length, int attempts = HANTEK_ATTEMPTS_MULTI ); /// \brief Control transfer to the oscilloscope. /// \param type The request type, also sets the direction of the transfer. @@ -102,27 +101,25 @@ class USBDevice : public QObject { /// \param index The index field of the packet. /// \param attempts The number of attempts, that are done on timeouts. /// \return Number of transferred bytes on success, libusb error code on error. - int controlTransfer(unsigned char type, unsigned char request, unsigned char *data, unsigned int length, int value, - int index, int attempts = HANTEK_ATTEMPTS); + int controlTransfer( unsigned char type, unsigned char request, unsigned char *data, unsigned int length, int value, + int index, int attempts = HANTEK_ATTEMPTS ); /// \brief Control write to the oscilloscope. /// \param command Buffer for the sent/received data. /// \return Number of sent bytes on success, libusb error code on error. - template - inline int controlWrite(const T *command) { - return controlTransfer(LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT, uint8_t(command->code), - const_cast(command->data()), unsigned(command->size()), command->value, 0, - HANTEK_ATTEMPTS); + template inline int controlWrite( const T *command ) { + return controlTransfer( LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT, uint8_t( command->code ), + const_cast( command->data() ), unsigned( command->size() ), + command->value, 0, HANTEK_ATTEMPTS ); } /// \brief Control read to the oscilloscope. /// \param command Buffer for the sent/received data. /// \return Number of received bytes on success, libusb error code on error. - template - inline int controlRead(const T *command) { - return controlTransfer(LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN, uint8_t(command->code), - const_cast(command->data()), unsigned(command->size()), command->value, 0, - HANTEK_ATTEMPTS); + template inline int controlRead( const T *command ) { + return controlTransfer( LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN, uint8_t( command->code ), + const_cast( command->data() ), unsigned( command->size() ), + command->value, 0, HANTEK_ATTEMPTS ); } /** @@ -148,15 +145,15 @@ class USBDevice : public QObject { * mode uses the maximum in length for transfer. Some devices do not support * that much data though and need an artification restriction. */ - inline void overwriteInPacketLength(unsigned len) { inPacketLength = len; } + inline void overwriteInPacketLength( unsigned len ) { inPacketLength = len; } protected: -// int claimInterface(const libusb_interface_descriptor *interfaceDescriptor, int endpointOut, int endPointIn); -// int claimInterface(const libusb_interface_descriptor *interfaceDescriptor, int endPointIn); + // int claimInterface(const libusb_interface_descriptor *interfaceDescriptor, int endpointOut, int endPointIn); + // int claimInterface(const libusb_interface_descriptor *interfaceDescriptor, int endPointIn); int claimInterface( const libusb_interface_descriptor *interfaceDescriptor ); // Device model data - DSOModel* model; + DSOModel *model; // Libusb specific variables struct libusb_device_descriptor descriptor; diff --git a/openhantek/src/usb/usbdevicedefinitions.h b/openhantek/src/usb/usbdevicedefinitions.h index efb20c91..919a020a 100644 --- a/openhantek/src/usb/usbdevicedefinitions.h +++ b/openhantek/src/usb/usbdevicedefinitions.h @@ -2,10 +2,10 @@ #pragma once -#define HANTEK_TIMEOUT 500 ///< Timeout for USB transfers in ms -#define HANTEK_TIMEOUT_MULTI 500 ///< Timeout for multi packet USB transfers in ms -#define HANTEK_ATTEMPTS 3 ///< The number of transfer attempts -#define HANTEK_ATTEMPTS_MULTI 1 ///< The number of multi packet transfer attempts +#define HANTEK_TIMEOUT 500 ///< Timeout for USB transfers in ms +#define HANTEK_TIMEOUT_MULTI 500 ///< Timeout for multi packet USB transfers in ms +#define HANTEK_ATTEMPTS 3 ///< The number of transfer attempts +#define HANTEK_ATTEMPTS_MULTI 1 ///< The number of multi packet transfer attempts #define HANTEK_EP_OUT 0x02 ///< OUT Endpoint for bulk transfers #define HANTEK_EP_IN 0x86 ///< IN Endpoint for bulk transfers diff --git a/openhantek/src/utils/enumclass.h b/openhantek/src/utils/enumclass.h index 944f2a5c..3ac4e698 100644 --- a/openhantek/src/utils/enumclass.h +++ b/openhantek/src/utils/enumclass.h @@ -2,40 +2,27 @@ #pragma once -template< typename T, T first, T last > -class Enum -{ -public: - class Iterator - { - public: - Iterator( int value ) : - m_value( value ) - { } - - T operator*( void ) const { - return T(m_value); - } - - void operator++( void ) { - ++m_value; - } - - bool operator!=( Iterator rhs ) { - return m_value != rhs.m_value; - } - - private: - int m_value; - }; +template class Enum { + public: + class Iterator { + public: + Iterator( int value ) : m_value( value ) {} + + T operator*(void)const { return T( m_value ); } + + void operator++( void ) { ++m_value; } + + bool operator!=( Iterator rhs ) { return m_value != rhs.m_value; } + + private: + int m_value; + }; }; -template< typename T, T first, T last > -typename Enum::Iterator begin( Enum ) { - return typename Enum::Iterator( int(first) ); +template typename Enum::Iterator begin( Enum ) { + return typename Enum::Iterator( int( first ) ); } -template< typename T, T first, T last > -typename Enum::Iterator end( Enum ) { - return typename Enum::Iterator( int(last) + 1 ); +template typename Enum::Iterator end( Enum ) { + return typename Enum::Iterator( int( last ) + 1 ); } diff --git a/openhantek/src/utils/printutils.cpp b/openhantek/src/utils/printutils.cpp index ff9864f2..9a014780 100644 --- a/openhantek/src/utils/printutils.cpp +++ b/openhantek/src/utils/printutils.cpp @@ -7,108 +7,115 @@ #include #ifdef __FreeBSD__ - #include +#include #else - #include +#include #endif #include "utils/printutils.h" -QString valueToString(double value, Unit unit, int precision) { - char format = (precision < 0) ? 'g' : 'f'; +QString valueToString( double value, Unit unit, int precision ) { + char format = ( precision < 0 ) ? 'g' : 'f'; - switch (unit) { + switch ( unit ) { case UNIT_VOLTS: { // Voltage string representation - int logarithm = int(floor(log10(fabs(value)))); - if (fabs(value) < 1e-3) - return QApplication::tr("%L1 µV").arg(value / 1e-6, 0, format, - (precision <= 0) ? precision - : qBound(0, precision - 7 - logarithm, precision)); - else if (fabs(value) < 1.0) - return QApplication::tr("%L1 mV").arg(value / 1e-3, 0, format, - (precision <= 0) ? precision : (precision - 4 - logarithm)); + int logarithm = int( floor( log10( fabs( value ) ) ) ); + if ( fabs( value ) < 1e-3 ) + return QApplication::tr( "%L1 µV" ) + .arg( value / 1e-6, 0, format, + ( precision <= 0 ) ? precision : qBound( 0, precision - 7 - logarithm, precision ) ); + else if ( fabs( value ) < 1.0 ) + return QApplication::tr( "%L1 mV" ) + .arg( value / 1e-3, 0, format, ( precision <= 0 ) ? precision : ( precision - 4 - logarithm ) ); else - return QApplication::tr("%L1 V").arg(value, 0, format, - (precision <= 0) ? precision : qMax(0, precision - 1 - logarithm)); + return QApplication::tr( "%L1 V" ).arg( + value, 0, format, ( precision <= 0 ) ? precision : qMax( 0, precision - 1 - logarithm ) ); } case UNIT_DECIBEL: // Power level string representation - return QApplication::tr("%L1 dB").arg( - value, 0, format, - (precision <= 0) ? precision : qBound(0, precision - 1 - int(floor(log10(fabs(value)))), precision)); + return QApplication::tr( "%L1 dB" ) + .arg( value, 0, format, + ( precision <= 0 ) ? precision + : qBound( 0, precision - 1 - int( floor( log10( fabs( value ) ) ) ), precision ) ); case UNIT_SECONDS: // Time string representation - if (fabs(value) < 1e-9) - return QApplication::tr("%L1 ps").arg( - value / 1e-12, 0, format, - (precision <= 0) ? precision : qBound(0, precision - 13 - int(floor(log10(fabs(value)))), precision)); - else if (fabs(value) < 1e-6) - return QApplication::tr("%L1 ns").arg(value / 1e-9, 0, format, - (precision <= 0) ? precision - : (precision - 10 - int(floor(log10(fabs(value)))))); - else if (fabs(value) < 1e-3) - return QApplication::tr("%L1 µs").arg(value / 1e-6, 0, format, - (precision <= 0) ? precision - : (precision - 7 - int(floor(log10(fabs(value)))))); - else if (fabs(value) < 1.0) - return QApplication::tr("%L1 ms").arg(value / 1e-3, 0, format, - (precision <= 0) ? precision - : (precision - 4 - int(floor(log10(fabs(value)))))); - else if (fabs(value) < 60) - return QApplication::tr("%L1 s").arg( - value, 0, format, (precision <= 0) ? precision : (precision - 1 - int(floor(log10(fabs(value)))))); - else if (fabs(value) < 3600) - return QApplication::tr("%L1 min").arg( - value / 60, 0, format, (precision <= 0) ? precision : (precision - 1 - int(floor(log10(value / 60))))); + if ( fabs( value ) < 1e-9 ) + return QApplication::tr( "%L1 ps" ) + .arg( value / 1e-12, 0, format, + ( precision <= 0 ) + ? precision + : qBound( 0, precision - 13 - int( floor( log10( fabs( value ) ) ) ), precision ) ); + else if ( fabs( value ) < 1e-6 ) + return QApplication::tr( "%L1 ns" ) + .arg( value / 1e-9, 0, format, + ( precision <= 0 ) ? precision : ( precision - 10 - int( floor( log10( fabs( value ) ) ) ) ) ); + else if ( fabs( value ) < 1e-3 ) + return QApplication::tr( "%L1 µs" ) + .arg( value / 1e-6, 0, format, + ( precision <= 0 ) ? precision : ( precision - 7 - int( floor( log10( fabs( value ) ) ) ) ) ); + else if ( fabs( value ) < 1.0 ) + return QApplication::tr( "%L1 ms" ) + .arg( value / 1e-3, 0, format, + ( precision <= 0 ) ? precision : ( precision - 4 - int( floor( log10( fabs( value ) ) ) ) ) ); + else if ( fabs( value ) < 60 ) + return QApplication::tr( "%L1 s" ).arg( + value, 0, format, + ( precision <= 0 ) ? precision : ( precision - 1 - int( floor( log10( fabs( value ) ) ) ) ) ); + else if ( fabs( value ) < 3600 ) + return QApplication::tr( "%L1 min" ) + .arg( value / 60, 0, format, + ( precision <= 0 ) ? precision : ( precision - 1 - int( floor( log10( value / 60 ) ) ) ) ); else - return QApplication::tr("%L1 h").arg( + return QApplication::tr( "%L1 h" ).arg( value / 3600, 0, format, - (precision <= 0) ? precision : qMax(0, precision - 1 - int(floor(log10(value / 3600))))); + ( precision <= 0 ) ? precision : qMax( 0, precision - 1 - int( floor( log10( value / 3600 ) ) ) ) ); case UNIT_HERTZ: { // Frequency string representation - int logarithm = int(floor(log10(fabs(value)))); - if (fabs(value) < 1e3) - return QApplication::tr("%L1 Hz").arg( - value, 0, format, (precision <= 0) ? precision : qBound(0, precision - 1 - logarithm, precision)); - else if (fabs(value) < 1e6) - return QApplication::tr("%L1 kHz").arg(value / 1e3, 0, format, - (precision <= 0) ? precision : precision + 2 - logarithm); - else if (fabs(value) < 1e9) - return QApplication::tr("%L1 MHz").arg(value / 1e6, 0, format, - (precision <= 0) ? precision : precision + 5 - logarithm); + int logarithm = int( floor( log10( fabs( value ) ) ) ); + if ( fabs( value ) < 1e3 ) + return QApplication::tr( "%L1 Hz" ) + .arg( value, 0, format, + ( precision <= 0 ) ? precision : qBound( 0, precision - 1 - logarithm, precision ) ); + else if ( fabs( value ) < 1e6 ) + return QApplication::tr( "%L1 kHz" ) + .arg( value / 1e3, 0, format, ( precision <= 0 ) ? precision : precision + 2 - logarithm ); + else if ( fabs( value ) < 1e9 ) + return QApplication::tr( "%L1 MHz" ) + .arg( value / 1e6, 0, format, ( precision <= 0 ) ? precision : precision + 5 - logarithm ); else - return QApplication::tr("%L1 GHz").arg(value / 1e9, 0, format, - (precision <= 0) ? precision : qMax(0, precision + 8 - logarithm)); + return QApplication::tr( "%L1 GHz" ) + .arg( value / 1e9, 0, format, ( precision <= 0 ) ? precision : qMax( 0, precision + 8 - logarithm ) ); } case UNIT_SAMPLES: { // Sample count string representation - int logarithm = int(floor(log10(fabs(value)))); - if (fabs(value) < 1e3) - return QApplication::tr("%L1 S").arg( - value, 0, format, (precision <= 0) ? precision : qBound(0, precision - 1 - logarithm, precision)); - else if (fabs(value) < 1e6) - return QApplication::tr("%L1 kS").arg(value / 1e3, 0, format, - (precision <= 0) ? precision : precision + 2 - logarithm); - else if (fabs(value) < 1e9) - return QApplication::tr("%L1 MS").arg(value / 1e6, 0, format, - (precision <= 0) ? precision : precision + 5 - logarithm); + int logarithm = int( floor( log10( fabs( value ) ) ) ); + if ( fabs( value ) < 1e3 ) + return QApplication::tr( "%L1 S" ).arg( + value, 0, format, ( precision <= 0 ) ? precision : qBound( 0, precision - 1 - logarithm, precision ) ); + else if ( fabs( value ) < 1e6 ) + return QApplication::tr( "%L1 kS" ) + .arg( value / 1e3, 0, format, ( precision <= 0 ) ? precision : precision + 2 - logarithm ); + else if ( fabs( value ) < 1e9 ) + return QApplication::tr( "%L1 MS" ) + .arg( value / 1e6, 0, format, ( precision <= 0 ) ? precision : precision + 5 - logarithm ); else - return QApplication::tr("%L1 GS").arg(value / 1e9, 0, format, - (precision <= 0) ? precision : qMax(0, precision + 8 - logarithm)); + return QApplication::tr( "%L1 GS" ) + .arg( value / 1e9, 0, format, ( precision <= 0 ) ? precision : qMax( 0, precision + 8 - logarithm ) ); } default: return QString(); } } -double stringToValue(const QString &text, Unit unit, bool *ok) { +double stringToValue( const QString &text, Unit unit, bool *ok ) { // Check if the text is empty int totalSize = text.size(); - if (!totalSize) { - if (ok) *ok = false; + if ( !totalSize ) { + if ( ok ) + *ok = false; return 0.0; } @@ -117,36 +124,40 @@ double stringToValue(const QString &text, Unit unit, bool *ok) { QLocale locale; bool decimalFound = false; bool exponentFound = false; - if (text[valueSize] == locale.negativeSign()) ++valueSize; - for (; valueSize < text.size(); ++valueSize) { - QChar character = text[valueSize]; + if ( text[ valueSize ] == locale.negativeSign() ) + ++valueSize; + for ( ; valueSize < text.size(); ++valueSize ) { + QChar character = text[ valueSize ]; - if (character.isDigit()) { - } else if (character == locale.decimalPoint() && decimalFound == false && exponentFound == false) { + if ( character.isDigit() ) { + } else if ( character == locale.decimalPoint() && decimalFound == false && exponentFound == false ) { decimalFound = true; - } else if (character == locale.exponential() && exponentFound == false) { + } else if ( character == locale.exponential() && exponentFound == false ) { exponentFound = true; - if (text[valueSize + 1] == locale.negativeSign()) ++valueSize; + if ( text[ valueSize + 1 ] == locale.negativeSign() ) + ++valueSize; } else { break; } } - QString valueString = text.left(valueSize); + QString valueString = text.left( valueSize ); bool valueOk = false; - double value = valueString.toDouble(&valueOk); - if (!valueOk) { - if (ok) *ok = false; + double value = valueString.toDouble( &valueOk ); + if ( !valueOk ) { + if ( ok ) + *ok = false; return value; } - QString unitString = text.right(text.size() - valueSize).trimmed(); + QString unitString = text.right( text.size() - valueSize ).trimmed(); - if (ok) *ok = true; - switch (unit) { + if ( ok ) + *ok = true; + switch ( unit ) { case UNIT_VOLTS: { // Voltage string decoding - if (unitString.startsWith("µ")) // my + if ( unitString.startsWith( "µ" ) ) // my return value * 1e-6; - else if (unitString.startsWith('m')) + else if ( unitString.startsWith( 'm' ) ) return value * 1e-3; else return value; @@ -157,75 +168,79 @@ double stringToValue(const QString &text, Unit unit, bool *ok) { case UNIT_SECONDS: // Time string decoding - if (unitString.startsWith('p')) + if ( unitString.startsWith( 'p' ) ) return value * 1e-12; - else if (unitString.startsWith('n')) + else if ( unitString.startsWith( 'n' ) ) return value * 1e-9; - else if (unitString.startsWith("µ")) // my + else if ( unitString.startsWith( "µ" ) ) // my return value * 1e-6; - else if (unitString.startsWith("min")) + else if ( unitString.startsWith( "min" ) ) return value * 60; - else if (unitString.startsWith('m')) + else if ( unitString.startsWith( 'm' ) ) return value * 1e-3; - else if (unitString.startsWith('h')) + else if ( unitString.startsWith( 'h' ) ) return value * 3600; else return value; case UNIT_HERTZ: // Frequency string decoding - if (unitString.startsWith('k')) + if ( unitString.startsWith( 'k' ) ) return value * 1e3; - else if (unitString.startsWith('M')) + else if ( unitString.startsWith( 'M' ) ) return value * 1e6; - else if (unitString.startsWith('G')) + else if ( unitString.startsWith( 'G' ) ) return value * 1e9; else return value; case UNIT_SAMPLES: // Sample count string decoding - if (unitString.startsWith('k')) + if ( unitString.startsWith( 'k' ) ) return value * 1e3; - else if (unitString.startsWith('M')) + else if ( unitString.startsWith( 'M' ) ) return value * 1e6; - else if (unitString.startsWith('G')) + else if ( unitString.startsWith( 'G' ) ) return value * 1e9; else return value; default: - if (ok) *ok = false; + if ( ok ) + *ok = false; return value; } } -QString hexDump(unsigned char *data, unsigned int length) { +QString hexDump( unsigned char *data, unsigned int length ) { QString dumpString, byteString; - for (unsigned int index = 0; index < length; ++index) dumpString.append(byteString.sprintf(" %02x", data[index])); + for ( unsigned int index = 0; index < length; ++index ) + dumpString.append( byteString.sprintf( " %02x", data[ index ] ) ); return dumpString; } -unsigned int hexParse(const QString dump, uint8_t *data, unsigned int length) { +unsigned int hexParse( const QString dump, uint8_t *data, unsigned int length ) { QString dumpString = dump; - dumpString.remove(' '); + dumpString.remove( ' ' ); QString byteString; unsigned int index; - for (index = 0; index < length; ++index) { - byteString = dumpString.mid(int(index) * 2, 2); + for ( index = 0; index < length; ++index ) { + byteString = dumpString.mid( int( index ) * 2, 2 ); // Check if we reached the end of the string - if (byteString.isNull()) break; + if ( byteString.isNull() ) + break; // Check for parsing errors bool ok; - uint8_t byte = uint8_t(byteString.toUShort(&ok, 16)); - if (!ok) break; + uint8_t byte = uint8_t( byteString.toUShort( &ok, 16 ) ); + if ( !ok ) + break; - data[index] = byte; + data[ index ] = byte; } return index; diff --git a/openhantek/src/utils/printutils.h b/openhantek/src/utils/printutils.h index cad08d56..01d4fced 100644 --- a/openhantek/src/utils/printutils.h +++ b/openhantek/src/utils/printutils.h @@ -17,7 +17,7 @@ enum Unit { UNIT_VOLTS, UNIT_DECIBEL, UNIT_SECONDS, UNIT_HERTZ, UNIT_SAMPLES, UN /// \param unit The unit for the value. /// \param precision Significant digits, 0 for integer, -1 for auto. /// \return String with the value and unit. -QString valueToString(double value, Unit unit, int precision = -1); +QString valueToString( double value, Unit unit, int precision = -1 ); /// \brief Converts string containing value and (prefix+)unit to double /// (Counterpart to valueToString). @@ -25,27 +25,28 @@ QString valueToString(double value, Unit unit, int precision = -1); /// \param unit The base unit of the value. /// \param ok Pointer to a success-flag, true on success, false on error. /// \return Decoded value. -double stringToValue(const QString &text, Unit unit, bool *ok = nullptr); +double stringToValue( const QString &text, Unit unit, bool *ok = nullptr ); /// \brief Returns the hex dump for the given data. /// \param data Pointer to the data bytes that should be dumped. /// \param length The length of the data array in bytes. /// \return String with the hex dump of the data. -QString hexDump(unsigned char *data, unsigned int length); +QString hexDump( unsigned char *data, unsigned int length ); /// \brief Returns the hex dump for the given data. /// \param dump The string with the hex dump of the data. /// \param data Pointer to the address where the data bytes should be saved. /// \param length The maximum length of the data array in bytes. /// \return The length of the saved data. -unsigned int hexParse(const QString dump, unsigned char *data, unsigned int length); +unsigned int hexParse( const QString dump, unsigned char *data, unsigned int length ); /// \brief Print debug information with timestamp. /// \param text Text that will be output via qDebug. #ifdef TIMESTAMPDEBUG -inline void timestampDebug(const QString& text) { - qDebug("%s: %s", QTime::currentTime().toString("hh:mm:ss.zzz").toLatin1().constData(), text.toLatin1().constData()); +inline void timestampDebug( const QString &text ) { + qDebug( "%s: %s", QTime::currentTime().toString( "hh:mm:ss.zzz" ).toLatin1().constData(), + text.toLatin1().constData() ); } #else -#define timestampDebug(ARG) +#define timestampDebug( ARG ) #endif diff --git a/openhantek/src/viewconstants.h b/openhantek/src/viewconstants.h index 4bc6e972..c4d84e54 100644 --- a/openhantek/src/viewconstants.h +++ b/openhantek/src/viewconstants.h @@ -8,11 +8,11 @@ #define DIVS_VOLTAGE 8.0 ///< Number of vertical screen divs #define DIVS_SUB 5 ///< Number of sub-divisions per div -#define MARGIN_LEFT (-DIVS_TIME / 2.0) -#define MARGIN_RIGHT (DIVS_TIME / 2.0) +#define MARGIN_LEFT ( -DIVS_TIME / 2.0 ) +#define MARGIN_RIGHT ( DIVS_TIME / 2.0 ) #define MARKER_COUNT 2 ///< Number of markers -#define MARKER_STEP (DIVS_TIME / 100.0) +#define MARKER_STEP ( DIVS_TIME / 100.0 ) // spacing between the individual entries of the docks #define DOCK_LAYOUT_SPACING 4 diff --git a/openhantek/src/viewsettings.h b/openhantek/src/viewsettings.h index 322d95fe..c0575280 100644 --- a/openhantek/src/viewsettings.h +++ b/openhantek/src/viewsettings.h @@ -28,14 +28,22 @@ struct DsoSettingsColorValues { /// \struct DsoSettingsView /// \brief Holds all view settings. struct DsoSettingsView { - DsoSettingsColorValues screen = {QColor(0xff, 0xff, 0xff, 0x7f), QColor(0x00, 0x00, 0x00, 0xff), // axes, background - QColor(0xff, 0xff, 0xff, 0xff), QColor(0xff, 0xff, 0xff, 0xbf), // border, grid - QColor(0xff, 0xff, 0xff, 0xbf), QColor(0xff, 0xff, 0xff, 0xff), // markers, text - std::vector(), std::vector()}; // spectrum, voltage - DsoSettingsColorValues print = {QColor(0x00, 0x00, 0x00, 0xbf), QColor(0x00, 0x00, 0x00, 0x00), // axes, background - QColor(0x00, 0x00, 0x00, 0xff), QColor(0x00, 0x00, 0x00, 0xbf), // border, grid - QColor(0x00, 0x00, 0x00, 0xbf), QColor(0x00, 0x00, 0x00, 0xff), // markers, text - std::vector(), std::vector()}; // spectrum, voltage + DsoSettingsColorValues screen = {QColor( 0xff, 0xff, 0xff, 0x7f ), + QColor( 0x00, 0x00, 0x00, 0xff ), // axes, background + QColor( 0xff, 0xff, 0xff, 0xff ), + QColor( 0xff, 0xff, 0xff, 0xbf ), // border, grid + QColor( 0xff, 0xff, 0xff, 0xbf ), + QColor( 0xff, 0xff, 0xff, 0xff ), // markers, text + std::vector(), + std::vector()}; // spectrum, voltage + DsoSettingsColorValues print = {QColor( 0x00, 0x00, 0x00, 0xbf ), + QColor( 0x00, 0x00, 0x00, 0x00 ), // axes, background + QColor( 0x00, 0x00, 0x00, 0xff ), + QColor( 0x00, 0x00, 0x00, 0xbf ), // border, grid + QColor( 0x00, 0x00, 0x00, 0xbf ), + QColor( 0x00, 0x00, 0x00, 0xff ), // markers, text + std::vector(), + std::vector()}; // spectrum, voltage bool antialiasing = true; ///< Antialiasing for the graphs bool digitalPhosphor = false; ///< true slowly fades out the previous graphs unsigned digitalPhosphorDepth = 8; ///< Number of channels shown at one time @@ -45,7 +53,5 @@ struct DsoSettingsView { Qt::ToolBarArea cursorGridPosition = Qt::RightToolBarArea; bool cursorsVisible = false; - unsigned digitalPhosphorDraws() const { - return digitalPhosphor ? digitalPhosphorDepth : 1; - } + unsigned digitalPhosphorDraws() const { return digitalPhosphor ? digitalPhosphorDepth : 1; } }; diff --git a/openhantek/src/widgets/colorbox.cpp b/openhantek/src/widgets/colorbox.cpp index bbc30a62..21814fe8 100644 --- a/openhantek/src/widgets/colorbox.cpp +++ b/openhantek/src/widgets/colorbox.cpp @@ -32,9 +32,9 @@ /// \brief Initializes the widget. /// \param color_ Initial color value. /// \param parent The parent widget. -ColorBox::ColorBox(QColor color_, QWidget *parent) : QPushButton(parent) { - setColor(color_); - connect(this, &QAbstractButton::clicked, this, &ColorBox::waitForColor); +ColorBox::ColorBox( QColor color_, QWidget *parent ) : QPushButton( parent ) { + setColor( color_ ); + connect( this, &QAbstractButton::clicked, this, &ColorBox::waitForColor ); } /// \brief Cleans up the widget. @@ -46,17 +46,18 @@ const QColor ColorBox::getColor() { return color; } /// \brief Sets the color. /// \param newColor The new color. -void ColorBox::setColor(QColor newColor) { +void ColorBox::setColor( QColor newColor ) { color = newColor; - setText(QString("#%1").arg(unsigned(color.rgba()), 8, 16, QChar('0'))); - setPalette(QPalette(color)); - emit colorChanged(color); + setText( QString( "#%1" ).arg( unsigned( color.rgba() ), 8, 16, QChar( '0' ) ) ); + setPalette( QPalette( color ) ); + emit colorChanged( color ); } /// \brief Wait for the color dialog and apply chosen color. void ColorBox::waitForColor() { setFocus(); - setDown(true); - QColor newColor = QColorDialog::getColor(color, this, nullptr, QColorDialog::ShowAlphaChannel); - if (newColor.isValid()) setColor(newColor); + setDown( true ); + QColor newColor = QColorDialog::getColor( color, this, nullptr, QColorDialog::ShowAlphaChannel ); + if ( newColor.isValid() ) + setColor( newColor ); } diff --git a/openhantek/src/widgets/colorbox.h b/openhantek/src/widgets/colorbox.h index a039fbae..49ff5dbc 100644 --- a/openhantek/src/widgets/colorbox.h +++ b/openhantek/src/widgets/colorbox.h @@ -10,18 +10,18 @@ class ColorBox : public QPushButton { Q_OBJECT public: - ColorBox(QColor color, QWidget *parent = nullptr); + ColorBox( QColor color, QWidget *parent = nullptr ); ~ColorBox(); const QColor getColor(); public slots: - void setColor(QColor color); + void setColor( QColor color ); void waitForColor(); private: QColor color; signals: - void colorChanged(QColor color); ///< The color has been changed + void colorChanged( QColor color ); ///< The color has been changed }; diff --git a/openhantek/src/widgets/datagrid.cpp b/openhantek/src/widgets/datagrid.cpp index b6478e97..012823b2 100644 --- a/openhantek/src/widgets/datagrid.cpp +++ b/openhantek/src/widgets/datagrid.cpp @@ -2,43 +2,40 @@ #include "datagrid.h" +#include #include #include #include -#include -DataGrid::DataGrid(QWidget *parent) : QGroupBox(parent) -{ +DataGrid::DataGrid( QWidget *parent ) : QGroupBox( parent ) { cursorsLayout = new QGridLayout(); - cursorsLayout->setSpacing(5); + cursorsLayout->setSpacing( 5 ); cursorsSelectorGroup = new QButtonGroup(); - cursorsSelectorGroup->setExclusive(true); + cursorsSelectorGroup->setExclusive( true ); - connect(cursorsSelectorGroup, - static_cast(&QButtonGroup::buttonPressed), [this] (unsigned index) { - emit itemSelected(index); - }); + connect( cursorsSelectorGroup, static_cast( &QButtonGroup::buttonPressed ), + [this]( unsigned index ) { emit itemSelected( index ); } ); - setLayout(cursorsLayout); - setFixedWidth(180); + setLayout( cursorsLayout ); + setFixedWidth( 180 ); } DataGrid::CursorInfo::CursorInfo() { selector = new QPushButton(); - selector->setCheckable(true); + selector->setCheckable( true ); shape = new QPushButton(); deltaXLabel = new QLabel(); - deltaXLabel->setAlignment(Qt::AlignRight); + deltaXLabel->setAlignment( Qt::AlignRight ); deltaYLabel = new QLabel(); - deltaYLabel->setAlignment(Qt::AlignRight); + deltaYLabel->setAlignment( Qt::AlignRight ); } -void DataGrid::CursorInfo::configure(const QString &text, const QColor &bgColor, const QColor &fgColor) { - palette.setColor(QPalette::Background, bgColor); - palette.setColor(QPalette::WindowText, fgColor); +void DataGrid::CursorInfo::configure( const QString &text, const QColor &bgColor, const QColor &fgColor ) { + palette.setColor( QPalette::Background, bgColor ); + palette.setColor( QPalette::WindowText, fgColor ); - selector->setText(text); - selector->setStyleSheet(QString(R"( + selector->setText( text ); + selector->setStyleSheet( QString( R"( QPushButton { color: %2; background-color: %1; @@ -52,75 +49,76 @@ void DataGrid::CursorInfo::configure(const QString &text, const QColor &bgColor, color: %3; border: 1px dotted %2; } - )").arg(bgColor.name(QColor::HexArgb), - fgColor.name(QColor::HexArgb), - fgColor.darker().name(QColor::HexArgb))); + )" ) + .arg( bgColor.name( QColor::HexArgb ), fgColor.name( QColor::HexArgb ), + fgColor.darker().name( QColor::HexArgb ) ) ); - shape->setStyleSheet(QString(R"( + shape->setStyleSheet( QString( R"( QPushButton { color: %2; background-color: %1; border: none } - )").arg(bgColor.name(QColor::HexArgb), - fgColor.name(QColor::HexArgb))); + )" ) + .arg( bgColor.name( QColor::HexArgb ), fgColor.name( QColor::HexArgb ) ) ); - deltaXLabel->setPalette(palette); - deltaYLabel->setPalette(palette); + deltaXLabel->setPalette( palette ); + deltaYLabel->setPalette( palette ); } -void DataGrid::setBackgroundColor(const QColor &bgColor) { +void DataGrid::setBackgroundColor( const QColor &bgColor ) { backgroundColor = bgColor; - for (auto it : items) { - it.configure(it.selector->text(), bgColor, it.palette.color(QPalette::WindowText)); + for ( auto it : items ) { + it.configure( it.selector->text(), bgColor, it.palette.color( QPalette::WindowText ) ); } } -void DataGrid::configureItem(unsigned index, const QColor &fgColor) { - if (index < items.size()) { - items[index].configure(items[index].selector->text(), backgroundColor, fgColor); +void DataGrid::configureItem( unsigned index, const QColor &fgColor ) { + if ( index < items.size() ) { + items[ index ].configure( items[ index ].selector->text(), backgroundColor, fgColor ); } } -int DataGrid::addItem(const QString &text, const QColor &fgColor) { - int index = int(items.size()); - items.resize(ulong(index + 1)); +int DataGrid::addItem( const QString &text, const QColor &fgColor ) { + int index = int( items.size() ); + items.resize( ulong( index + 1 ) ); - CursorInfo& info = items.at(ulong(index)); - info.configure(text, backgroundColor, fgColor); - cursorsSelectorGroup->addButton(info.selector, index); + CursorInfo &info = items.at( ulong( index ) ); + info.configure( text, backgroundColor, fgColor ); + cursorsSelectorGroup->addButton( info.selector, index ); - connect(info.shape, &QPushButton::clicked, [this, index] () { - emit itemUpdated( unsigned(index) ); - }); + connect( info.shape, &QPushButton::clicked, [this, index]() { emit itemUpdated( unsigned( index ) ); } ); - cursorsLayout->addWidget(info.selector, 3 * index, 0); - cursorsLayout->addWidget(info.shape, 3 * index, 1); - cursorsLayout->addWidget(info.deltaXLabel, 3 * index + 1, 0); - cursorsLayout->addWidget(info.deltaYLabel, 3 * index + 1, 1); - cursorsLayout->setRowMinimumHeight(3 * index + 2, 10); - cursorsLayout->setRowStretch(3 * index, 0); - cursorsLayout->setRowStretch(3 * index + 3, 1); + cursorsLayout->addWidget( info.selector, 3 * index, 0 ); + cursorsLayout->addWidget( info.shape, 3 * index, 1 ); + cursorsLayout->addWidget( info.deltaXLabel, 3 * index + 1, 0 ); + cursorsLayout->addWidget( info.deltaYLabel, 3 * index + 1, 1 ); + cursorsLayout->setRowMinimumHeight( 3 * index + 2, 10 ); + cursorsLayout->setRowStretch( 3 * index, 0 ); + cursorsLayout->setRowStretch( 3 * index + 3, 1 ); return index; } -void DataGrid::updateInfo(unsigned index, bool visible, const QString &strShape, const QString &strX, const QString &strY) { - if (index >= items.size()) return; - CursorInfo &info = items.at(index); - info.selector->setEnabled(visible); - if (visible) { - info.shape->setText(strShape); - info.deltaXLabel->setText(strX); - info.deltaYLabel->setText(strY); +void DataGrid::updateInfo( unsigned index, bool visible, const QString &strShape, const QString &strX, + const QString &strY ) { + if ( index >= items.size() ) + return; + CursorInfo &info = items.at( index ); + info.selector->setEnabled( visible ); + if ( visible ) { + info.shape->setText( strShape ); + info.deltaXLabel->setText( strX ); + info.deltaYLabel->setText( strY ); } else { - info.shape->setText(QString()); - info.deltaXLabel->setText(QString()); - info.deltaYLabel->setText(QString()); + info.shape->setText( QString() ); + info.deltaXLabel->setText( QString() ); + info.deltaYLabel->setText( QString() ); } } -void DataGrid::selectItem(unsigned index) { - if (index >= items.size()) return; - items[index].selector->setChecked(true); +void DataGrid::selectItem( unsigned index ) { + if ( index >= items.size() ) + return; + items[ index ].selector->setChecked( true ); } diff --git a/openhantek/src/widgets/datagrid.h b/openhantek/src/widgets/datagrid.h index 207d56a4..418752d3 100644 --- a/openhantek/src/widgets/datagrid.h +++ b/openhantek/src/widgets/datagrid.h @@ -10,37 +10,36 @@ class QButtonGroup; class QLabel; class QGridLayout; -class DataGrid : public QGroupBox -{ +class DataGrid : public QGroupBox { Q_OBJECT -public: - explicit DataGrid(QWidget *parent = nullptr); + public: + explicit DataGrid( QWidget *parent = nullptr ); struct CursorInfo { - QPalette palette; ///< The widget's palette - QPushButton *selector; ///< The name of the channel - QPushButton *shape; ///< The cursor shape - QLabel *deltaXLabel; ///< The horizontal distance between cursors - QLabel *deltaYLabel; ///< The vertical distance between cursors + QPalette palette; ///< The widget's palette + QPushButton *selector; ///< The name of the channel + QPushButton *shape; ///< The cursor shape + QLabel *deltaXLabel; ///< The horizontal distance between cursors + QLabel *deltaYLabel; ///< The vertical distance between cursors CursorInfo(); - void configure(const QString &text, const QColor &bgColor, const QColor &fgColor); + void configure( const QString &text, const QColor &bgColor, const QColor &fgColor ); }; - int addItem(const QString &text, const QColor &fgColor); - void setBackgroundColor(const QColor &bgColor); - void configureItem(unsigned index, const QColor &fgColor); - void updateInfo(unsigned index, bool visible, const QString &strShape = QString(), - const QString &strX = QString(), const QString &strY = QString()); + int addItem( const QString &text, const QColor &fgColor ); + void setBackgroundColor( const QColor &bgColor ); + void configureItem( unsigned index, const QColor &fgColor ); + void updateInfo( unsigned index, bool visible, const QString &strShape = QString(), const QString &strX = QString(), + const QString &strY = QString() ); -signals: - void itemSelected(unsigned index); - void itemUpdated(unsigned index); + signals: + void itemSelected( unsigned index ); + void itemUpdated( unsigned index ); -public slots: - void selectItem(unsigned index); + public slots: + void selectItem( unsigned index ); -private: + private: QColor backgroundColor; QButtonGroup *cursorsSelectorGroup; QGridLayout *cursorsLayout; diff --git a/openhantek/src/widgets/levelslider.cpp b/openhantek/src/widgets/levelslider.cpp index c0e63499..775e44f4 100644 --- a/openhantek/src/widgets/levelslider.cpp +++ b/openhantek/src/widgets/levelslider.cpp @@ -34,15 +34,15 @@ /// \brief Initializes the slider container. /// \param direction The side on which the sliders are shown. /// \param parent The parent widget. -LevelSlider::LevelSlider(Qt::ArrowType direction, QWidget *parent) : QWidget(parent) { +LevelSlider::LevelSlider( Qt::ArrowType direction, QWidget *parent ) : QWidget( parent ) { QFont font = this->font(); - font.setPointSize(int(font.pointSize() * 0.8)); - this->setFont(font); + font.setPointSize( int( font.pointSize() * 0.8 ) ); + this->setFont( font ); this->pressedSlider = -1; calculateWidth(); - setDirection(direction); + setDirection( direction ); } /// \brief Cleans up the widget. @@ -59,14 +59,15 @@ int LevelSlider::postMargin() const { return this->_postMargin; } /// \brief Add a new slider to the slider container. /// \param index The index where the slider should be inserted, 0 to append. /// \return The index of the slider, -1 on error. -int LevelSlider::addSlider(int index) { return this->addSlider("", index); } +int LevelSlider::addSlider( int index ) { return this->addSlider( "", index ); } /// \brief Add a new slider to the slider container. /// \param text The text that will be shown next to the slider. /// \param index The index where the slider should be inserted, 0 to append. /// \return The index of the slider, -1 on error. -int LevelSlider::addSlider(const QString& text, int index) { - if (index < -1) return -1; +int LevelSlider::addSlider( const QString &text, int index ) { + if ( index < -1 ) + return -1; LevelSliderParameters *parameters = new LevelSliderParameters; parameters->color = Qt::white; @@ -75,13 +76,13 @@ int LevelSlider::addSlider(const QString& text, int index) { parameters->value = 0x00; parameters->visible = false; - if (index == -1) { - this->slider.append(parameters); + if ( index == -1 ) { + this->slider.append( parameters ); index = this->slider.count() - 1; } else - this->slider.insert(index, parameters); + this->slider.insert( index, parameters ); - this->setText(index, text); + this->setText( index, text ); return index; } @@ -89,14 +90,15 @@ int LevelSlider::addSlider(const QString& text, int index) { /// \brief Remove a slider from the slider container. /// \param index The index of the slider that should be removed. /// \return The index of the removed slider, -1 on error. -int LevelSlider::removeSlider(int index) { - if (index < -1) return -1; +int LevelSlider::removeSlider( int index ) { + if ( index < -1 ) + return -1; - if (index == -1) { + if ( index == -1 ) { this->slider.removeLast(); index = this->slider.count(); } else { - this->slider.removeAt(index); + this->slider.removeAt( index ); } this->calculateWidth(); @@ -107,49 +109,53 @@ int LevelSlider::removeSlider(int index) { /// \brief Size hint for the widget. /// \return The recommended size for the widget. QSize LevelSlider::sizeHint() const { - if (this->_direction == Qt::RightArrow || this->_direction == Qt::LeftArrow) - return QSize(this->sliderWidth, 16); + if ( this->_direction == Qt::RightArrow || this->_direction == Qt::LeftArrow ) + return QSize( this->sliderWidth, 16 ); else - return QSize(16, this->sliderWidth); + return QSize( 16, this->sliderWidth ); } /// \brief Return the color of a slider. /// \param index The index of the slider whose color should be returned. /// \return The current color of the slider. -const QColor LevelSlider::color(int index) const { - if (index < 0 || index >= this->slider.count()) return Qt::black; +const QColor LevelSlider::color( int index ) const { + if ( index < 0 || index >= this->slider.count() ) + return Qt::black; - return this->slider[index]->color; + return this->slider[ index ]->color; } /// \brief Set the color of the slider. /// \param index The index of the slider whose color should be set. /// \param color The new color for the slider. /// \return The index of the slider, -1 on error. -void LevelSlider::setColor(unsigned index, QColor color) { - if (int(index) >= this->slider.count()) return; +void LevelSlider::setColor( unsigned index, QColor color ) { + if ( int( index ) >= this->slider.count() ) + return; - this->slider[int(index)]->color = color; + this->slider[ int( index ) ]->color = color; this->repaint(); } /// \brief Return the text shown beside a slider. /// \param index The index of the slider whose text should be returned. /// \return The current text of the slider. -const QString LevelSlider::text(int index) const { - if (index < 0 || index >= this->slider.count()) return QString(); +const QString LevelSlider::text( int index ) const { + if ( index < 0 || index >= this->slider.count() ) + return QString(); - return this->slider[index]->text; + return this->slider[ index ]->text; } /// \brief Set the text for a slider. /// \param index The index of the slider whose text should be set. /// \param text The text shown next to the slider. /// \return The index of the slider, -1 on error. -int LevelSlider::setText(int index, const QString &text) { - if (index < 0 || index >= this->slider.count()) return -1; +int LevelSlider::setText( int index, const QString &text ) { + if ( index < 0 || index >= this->slider.count() ) + return -1; - this->slider[index]->text = text; + this->slider[ index ]->text = text; this->calculateWidth(); return index; @@ -158,37 +164,41 @@ int LevelSlider::setText(int index, const QString &text) { /// \brief Return the visibility of a slider. /// \param index The index of the slider whose visibility should be returned. /// \return true if the slider is visible, false if it's hidden. -bool LevelSlider::visible(int index) const { - if (index < 0 || index >= this->slider.count()) return false; +bool LevelSlider::visible( int index ) const { + if ( index < 0 || index >= this->slider.count() ) + return false; - return this->slider[index]->visible; + return this->slider[ index ]->visible; } /// \brief Set the visibility of a slider. /// \param index The index of the slider whose visibility should be set. /// \param visible true to show the slider, false to hide it. /// \return The index of the slider, -1 on error. -void LevelSlider::setIndexVisible(unsigned index, bool visible) { - if (int(index) >= this->slider.count()) return; +void LevelSlider::setIndexVisible( unsigned index, bool visible ) { + if ( int( index ) >= this->slider.count() ) + return; - this->slider[int(index)]->visible = visible; + this->slider[ int( index ) ]->visible = visible; this->repaint(); } /// \brief Return the minimal value of the sliders. /// \return The value a slider has at the bottommost/leftmost position. -double LevelSlider::minimum(int index) const { - if (index < 0 || index >= this->slider.count()) return -1; +double LevelSlider::minimum( int index ) const { + if ( index < 0 || index >= this->slider.count() ) + return -1; - return this->slider[index]->minimum; + return this->slider[ index ]->minimum; } /// \brief Return the maximal value of the sliders. /// \return The value a slider has at the topmost/rightmost position. -double LevelSlider::maximum(int index) const { - if (index < 0 || index >= this->slider.count()) return -1; +double LevelSlider::maximum( int index ) const { + if ( index < 0 || index >= this->slider.count() ) + return -1; - return this->slider[index]->maximum; + return this->slider[ index ]->maximum; } /// \brief Set the maximal value of the sliders. @@ -196,61 +206,68 @@ double LevelSlider::maximum(int index) const { /// \param minimum The value a slider has at the bottommost/leftmost position. /// \param maximum The value a slider has at the topmost/rightmost position. /// \return -1 on error, fixValue result on success. -void LevelSlider::setLimits(int index, double minimum, double maximum) { - if (index < 0 || index >= this->slider.count()) return; +void LevelSlider::setLimits( int index, double minimum, double maximum ) { + if ( index < 0 || index >= this->slider.count() ) + return; - this->slider[index]->minimum = minimum; - this->slider[index]->maximum = maximum; - this->fixValue(index); - this->calculateRect(index); + this->slider[ index ]->minimum = minimum; + this->slider[ index ]->maximum = maximum; + this->fixValue( index ); + this->calculateRect( index ); this->repaint(); } /// \brief Return the step width of the sliders. /// \param index The index of the slider whose step width should be returned. /// \return The distance between the selectable slider positions. -double LevelSlider::step(int index) const { - if (index < 0 || index >= this->slider.count()) return -1; +double LevelSlider::step( int index ) const { + if ( index < 0 || index >= this->slider.count() ) + return -1; - return this->slider[index]->step; + return this->slider[ index ]->step; } /// \brief Set the step width of the sliders. /// \param index The index of the slider whose step width should be set. /// \param step The distance between the selectable slider positions. /// \return The new step width. -double LevelSlider::setStep(int index, double step) { - if (index < 0 || index >= this->slider.count()) return -1; +double LevelSlider::setStep( int index, double step ) { + if ( index < 0 || index >= this->slider.count() ) + return -1; - if (step > 0) this->slider[index]->step = step; + if ( step > 0 ) + this->slider[ index ]->step = step; - return this->slider[index]->step; + return this->slider[ index ]->step; } /// \brief Return the current position of a slider. /// \param index The index of the slider whose value should be returned. /// \return The value of the slider. -double LevelSlider::value(int index) const { - if (index < 0 || index >= this->slider.count()) return -1; +double LevelSlider::value( int index ) const { + if ( index < 0 || index >= this->slider.count() ) + return -1; - return this->slider[index]->value; + return this->slider[ index ]->value; } /// \brief Set the current position of a slider. /// \param index The index of the slider whose value should be set. /// \param value The new value of the slider. /// \return The new value of the slider. -void LevelSlider::setValue(int index, double value) { - if (index < 0 || index >= this->slider.count()) return; +void LevelSlider::setValue( int index, double value ) { + if ( index < 0 || index >= this->slider.count() ) + return; // Apply new value - this->slider[index]->value = value; - this->fixValue(index); + this->slider[ index ]->value = value; + this->fixValue( index ); - this->calculateRect(index); + this->calculateRect( index ); this->repaint(); - if (this->pressedSlider < 0) emit valueChanged(index, value); + if ( this->pressedSlider < 0 ) + emit valueChanged( index, value ); } /// \brief Return the direction of the sliders. @@ -260,12 +277,13 @@ Qt::ArrowType LevelSlider::direction() const { return this->_direction; } /// \brief Set the direction of the sliders. /// \param direction The side on which the sliders are shown. /// \return The index of the direction, -1 on error. -int LevelSlider::setDirection(Qt::ArrowType direction) { - if (direction < Qt::UpArrow || direction > Qt::RightArrow) return -1; +int LevelSlider::setDirection( Qt::ArrowType direction ) { + if ( direction < Qt::UpArrow || direction > Qt::RightArrow ) + return -1; this->_direction = direction; - if (this->_direction == Qt::RightArrow || this->_direction == Qt::LeftArrow) { + if ( this->_direction == Qt::RightArrow || this->_direction == Qt::LeftArrow ) { this->_preMargin = this->fontMetrics().lineSpacing(); this->_postMargin = 3; } else { @@ -278,67 +296,67 @@ int LevelSlider::setDirection(Qt::ArrowType direction) { /// \brief Move the slider if it's pressed. /// \param event The mouse event that should be handled. -void LevelSlider::mouseMoveEvent(QMouseEvent *event) { - if (this->pressedSlider < 0) { +void LevelSlider::mouseMoveEvent( QMouseEvent *event ) { + if ( this->pressedSlider < 0 ) { event->ignore(); return; } // Get new value double value; - if (this->_direction == Qt::RightArrow || this->_direction == Qt::LeftArrow) - value = this->slider[pressedSlider]->maximum - - (this->slider[pressedSlider]->maximum - this->slider[pressedSlider]->minimum) * - (double(event->y()) - this->_preMargin + 0.5) / - (this->height() - this->_preMargin - this->_postMargin - 1); + if ( this->_direction == Qt::RightArrow || this->_direction == Qt::LeftArrow ) + value = this->slider[ pressedSlider ]->maximum - + ( this->slider[ pressedSlider ]->maximum - this->slider[ pressedSlider ]->minimum ) * + ( double( event->y() ) - this->_preMargin + 0.5 ) / + ( this->height() - this->_preMargin - this->_postMargin - 1 ); else - value = this->slider[pressedSlider]->minimum + - (this->slider[pressedSlider]->maximum - this->slider[pressedSlider]->minimum) * - (double(event->x()) - this->_preMargin + 0.5) / - (this->width() - this->_preMargin - this->_postMargin - 1); + value = this->slider[ pressedSlider ]->minimum + + ( this->slider[ pressedSlider ]->maximum - this->slider[ pressedSlider ]->minimum ) * + ( double( event->x() ) - this->_preMargin + 0.5 ) / + ( this->width() - this->_preMargin - this->_postMargin - 1 ); // Move the slider - if (event->modifiers() & Qt::AltModifier) + if ( event->modifiers() & Qt::AltModifier ) // Alt allows every position - this->setValue(this->pressedSlider, value); + this->setValue( this->pressedSlider, value ); else // Set to nearest possible position - this->setValue(this->pressedSlider, - floor(value / this->slider[pressedSlider]->step + 0.5) * this->slider[pressedSlider]->step); + this->setValue( this->pressedSlider, floor( value / this->slider[ pressedSlider ]->step + 0.5 ) * + this->slider[ pressedSlider ]->step ); - emit valueChanged(pressedSlider, slider[pressedSlider]->value); + emit valueChanged( pressedSlider, slider[ pressedSlider ]->value ); event->accept(); } /// \brief Prepare slider for movement if the left mouse button is pressed. /// \param event The mouse event that should be handled. -void LevelSlider::mousePressEvent(QMouseEvent *event) { - if (!(event->button() & Qt::LeftButton)) { +void LevelSlider::mousePressEvent( QMouseEvent *event ) { + if ( !( event->button() & Qt::LeftButton ) ) { event->ignore(); return; } this->pressedSlider = -1; - for (int sliderId = 0; sliderId < this->slider.count(); ++sliderId) { - if (this->slider[sliderId]->visible && this->slider[sliderId]->rect.contains(event->pos())) { + for ( int sliderId = 0; sliderId < this->slider.count(); ++sliderId ) { + if ( this->slider[ sliderId ]->visible && this->slider[ sliderId ]->rect.contains( event->pos() ) ) { this->pressedSlider = sliderId; break; } } // Accept event if a slider was pressed - event->setAccepted(this->pressedSlider >= 0); + event->setAccepted( this->pressedSlider >= 0 ); } /// \brief Movement is done if the left mouse button is released. /// \param event The mouse event that should be handled. -void LevelSlider::mouseReleaseEvent(QMouseEvent *event) { - if (!(event->button() & Qt::LeftButton) || this->pressedSlider == -1) { +void LevelSlider::mouseReleaseEvent( QMouseEvent *event ) { + if ( !( event->button() & Qt::LeftButton ) || this->pressedSlider == -1 ) { event->ignore(); return; } - emit valueChanged(this->pressedSlider, this->slider[this->pressedSlider]->value); + emit valueChanged( this->pressedSlider, this->slider[ this->pressedSlider ]->value ); this->pressedSlider = -1; event->accept(); @@ -346,11 +364,11 @@ void LevelSlider::mouseReleaseEvent(QMouseEvent *event) { /// \brief Paint the widget. /// \param event The paint event that should be handled. -void LevelSlider::paintEvent(QPaintEvent *event) { - QPainter painter(this); +void LevelSlider::paintEvent( QPaintEvent *event ) { + QPainter painter( this ); Qt::Alignment alignment; - switch (this->_direction) { + switch ( this->_direction ) { case Qt::LeftArrow: alignment = Qt::AlignLeft | Qt::AlignBottom; break; @@ -365,80 +383,75 @@ void LevelSlider::paintEvent(QPaintEvent *event) { } QList::iterator sliderIt = this->slider.end(); - while (sliderIt != this->slider.begin()) { + while ( sliderIt != this->slider.begin() ) { --sliderIt; - if (!(*sliderIt)->visible) continue; + if ( !( *sliderIt )->visible ) + continue; - painter.setPen((*sliderIt)->color); + painter.setPen( ( *sliderIt )->color ); - if ((*sliderIt)->text.isEmpty()) { + if ( ( *sliderIt )->text.isEmpty() ) { QVector needlePoints; - QRect& sRect = (*sliderIt)->rect; + QRect &sRect = ( *sliderIt )->rect; const int W = this->sliderWidth; - switch (this->_direction) { + switch ( this->_direction ) { case Qt::LeftArrow: - needlePoints << QPoint(sRect.left() + 4, sRect.top() ) - << QPoint(sRect.left() + 1, sRect.top() + 3) - << QPoint(sRect.left() + 4, sRect.top() + 6) - << QPoint(sRect.left() + W, sRect.top() + 6) - << QPoint(sRect.left() + W, sRect.top() ); + needlePoints << QPoint( sRect.left() + 4, sRect.top() ) << QPoint( sRect.left() + 1, sRect.top() + 3 ) + << QPoint( sRect.left() + 4, sRect.top() + 6 ) + << QPoint( sRect.left() + W, sRect.top() + 6 ) << QPoint( sRect.left() + W, sRect.top() ); break; case Qt::UpArrow: - needlePoints << QPoint(sRect.left(), sRect.top() + 4) - << QPoint(sRect.left() + 3, sRect.top() + 1) - << QPoint(sRect.left() + 6, sRect.top() + 4) - << QPoint(sRect.left() + 6, sRect.top() + W) - << QPoint(sRect.left(), sRect.top() + W); + needlePoints << QPoint( sRect.left(), sRect.top() + 4 ) << QPoint( sRect.left() + 3, sRect.top() + 1 ) + << QPoint( sRect.left() + 6, sRect.top() + 4 ) + << QPoint( sRect.left() + 6, sRect.top() + W ) << QPoint( sRect.left(), sRect.top() + W ); break; case Qt::DownArrow: - needlePoints << QPoint(sRect.left(), sRect.top() + W - 5) - << QPoint(sRect.left() + 3, sRect.top() + W - 2) - << QPoint(sRect.left() + 6, sRect.top() + W - 5) - << QPoint(sRect.left() + 6, sRect.top() ) - << QPoint(sRect.left(), sRect.top() ); + needlePoints << QPoint( sRect.left(), sRect.top() + W - 5 ) + << QPoint( sRect.left() + 3, sRect.top() + W - 2 ) + << QPoint( sRect.left() + 6, sRect.top() + W - 5 ) + << QPoint( sRect.left() + 6, sRect.top() ) << QPoint( sRect.left(), sRect.top() ); break; case Qt::RightArrow: - needlePoints << QPoint(sRect.left() + W - 5, sRect.top() ) - << QPoint(sRect.left() + W - 2, sRect.top() + 3) - << QPoint(sRect.left() + W - 5, sRect.top() + 6) - << QPoint(sRect.left(), sRect.top() + 6) - << QPoint(sRect.left(), sRect.top() ); + needlePoints << QPoint( sRect.left() + W - 5, sRect.top() ) + << QPoint( sRect.left() + W - 2, sRect.top() + 3 ) + << QPoint( sRect.left() + W - 5, sRect.top() + 6 ) + << QPoint( sRect.left(), sRect.top() + 6 ) << QPoint( sRect.left(), sRect.top() ); break; default: break; } - painter.setBrush(QBrush((*sliderIt)->color, isEnabled() ? Qt::SolidPattern : Qt::NoBrush)); - painter.drawPolygon(QPolygon(needlePoints)); - painter.setBrush(Qt::NoBrush); + painter.setBrush( QBrush( ( *sliderIt )->color, isEnabled() ? Qt::SolidPattern : Qt::NoBrush ) ); + painter.drawPolygon( QPolygon( needlePoints ) ); + painter.setBrush( Qt::NoBrush ); } else { // Get rect for text and draw needle - QRect textRect = (*sliderIt)->rect; - if (this->_direction == Qt::UpArrow || this->_direction == Qt::DownArrow) { - textRect.setRight(textRect.right() - 1); - if (this->_direction == Qt::UpArrow) { - textRect.setTop(textRect.top() + 1); - painter.drawLine((*sliderIt)->rect.right(), 0, (*sliderIt)->rect.right(), 7); + QRect textRect = ( *sliderIt )->rect; + if ( this->_direction == Qt::UpArrow || this->_direction == Qt::DownArrow ) { + textRect.setRight( textRect.right() - 1 ); + if ( this->_direction == Qt::UpArrow ) { + textRect.setTop( textRect.top() + 1 ); + painter.drawLine( ( *sliderIt )->rect.right(), 0, ( *sliderIt )->rect.right(), 7 ); } else { - textRect.setBottom(textRect.bottom() - 1); - painter.drawLine((*sliderIt)->rect.right(), this->sliderWidth - 8, (*sliderIt)->rect.right(), - this->sliderWidth - 1); + textRect.setBottom( textRect.bottom() - 1 ); + painter.drawLine( ( *sliderIt )->rect.right(), this->sliderWidth - 8, ( *sliderIt )->rect.right(), + this->sliderWidth - 1 ); } } else { - textRect.setBottom(textRect.bottom() - 1); - if (this->_direction == Qt::LeftArrow) { - textRect.setLeft(textRect.left() + 1); - painter.drawLine(0, (*sliderIt)->rect.bottom(), 7, (*sliderIt)->rect.bottom()); + textRect.setBottom( textRect.bottom() - 1 ); + if ( this->_direction == Qt::LeftArrow ) { + textRect.setLeft( textRect.left() + 1 ); + painter.drawLine( 0, ( *sliderIt )->rect.bottom(), 7, ( *sliderIt )->rect.bottom() ); } else { - textRect.setRight(textRect.right() - 1); - painter.drawLine(this->sliderWidth - 8, (*sliderIt)->rect.bottom(), this->sliderWidth - 1, - (*sliderIt)->rect.bottom()); + textRect.setRight( textRect.right() - 1 ); + painter.drawLine( this->sliderWidth - 8, ( *sliderIt )->rect.bottom(), this->sliderWidth - 1, + ( *sliderIt )->rect.bottom() ); } } // Draw text - painter.drawText(textRect, int(alignment), (*sliderIt)->text); + painter.drawText( textRect, int( alignment ), ( *sliderIt )->text ); } } @@ -447,10 +460,11 @@ void LevelSlider::paintEvent(QPaintEvent *event) { /// \brief Resize the widget and adapt the slider positions. /// \param event The resize event that should be handled. -void LevelSlider::resizeEvent(QResizeEvent *event) { - Q_UNUSED(event); +void LevelSlider::resizeEvent( QResizeEvent *event ) { + Q_UNUSED( event ); - for (int sliderId = 0; sliderId < this->slider.count(); ++sliderId) this->calculateRect(sliderId); + for ( int sliderId = 0; sliderId < this->slider.count(); ++sliderId ) + this->calculateRect( sliderId ); this->repaint(); } @@ -458,75 +472,75 @@ void LevelSlider::resizeEvent(QResizeEvent *event) { /// \brief Calculate the drawing area for the slider for it's current value. /// \param sliderId The id of the slider whose rect should be calculated. /// \return The calculated rect. -QRect LevelSlider::calculateRect(int sliderId) { +QRect LevelSlider::calculateRect( int sliderId ) { // Is it a vertical slider? - if (this->_direction == Qt::RightArrow || this->_direction == Qt::LeftArrow) { + if ( this->_direction == Qt::RightArrow || this->_direction == Qt::LeftArrow ) { // Is it a triangular needle? - if (this->slider[sliderId]->text.isEmpty()) { - this->slider[sliderId]->rect = - QRect(0, // Start at the left side - // The needle should be center-aligned, 0.5 pixel offset for - // exact pixelization - int((this->height() - this->_preMargin - this->_postMargin - 1) * - (this->slider[sliderId]->maximum - this->slider[sliderId]->value) / - (this->slider[sliderId]->maximum - this->slider[sliderId]->minimum) + - 0.5) + - this->_preMargin - 3, - this->sliderWidth, // Fill the whole width - 7 // The needle is 7 px wide - ); + if ( this->slider[ sliderId ]->text.isEmpty() ) { + this->slider[ sliderId ]->rect = + QRect( 0, // Start at the left side + // The needle should be center-aligned, 0.5 pixel offset for + // exact pixelization + int( ( this->height() - this->_preMargin - this->_postMargin - 1 ) * + ( this->slider[ sliderId ]->maximum - this->slider[ sliderId ]->value ) / + ( this->slider[ sliderId ]->maximum - this->slider[ sliderId ]->minimum ) + + 0.5 ) + + this->_preMargin - 3, + this->sliderWidth, // Fill the whole width + 7 // The needle is 7 px wide + ); } // Or a thin needle with text? else { - this->slider[sliderId]->rect = - QRect(0, // Start at the left side - // The needle is at the bottom, the text above it, 0.5 pixel - // offset for exact pixelization - int((this->height() - this->_preMargin - this->_postMargin - 1) * - (this->slider[sliderId]->maximum - this->slider[sliderId]->value) / - (this->slider[sliderId]->maximum - this->slider[sliderId]->minimum) + - 0.5), - this->sliderWidth, // Fill the whole width - this->preMargin() + 1 // Use the full margin - ); + this->slider[ sliderId ]->rect = + QRect( 0, // Start at the left side + // The needle is at the bottom, the text above it, 0.5 pixel + // offset for exact pixelization + int( ( this->height() - this->_preMargin - this->_postMargin - 1 ) * + ( this->slider[ sliderId ]->maximum - this->slider[ sliderId ]->value ) / + ( this->slider[ sliderId ]->maximum - this->slider[ sliderId ]->minimum ) + + 0.5 ), + this->sliderWidth, // Fill the whole width + this->preMargin() + 1 // Use the full margin + ); } } // Or a horizontal slider? else { // Is it a triangular needle? - if (this->slider[sliderId]->text.isEmpty()) { - this->slider[sliderId]->rect = QRect( + if ( this->slider[ sliderId ]->text.isEmpty() ) { + this->slider[ sliderId ]->rect = QRect( // The needle should be center-aligned, 0.5 pixel offset for exact // pixelization - int((this->width() - this->_preMargin - this->_postMargin - 1) * - (this->slider[sliderId]->value - this->slider[sliderId]->minimum) / - (this->slider[sliderId]->maximum - this->slider[sliderId]->minimum) + - 0.5) + + int( ( this->width() - this->_preMargin - this->_postMargin - 1 ) * + ( this->slider[ sliderId ]->value - this->slider[ sliderId ]->minimum ) / + ( this->slider[ sliderId ]->maximum - this->slider[ sliderId ]->minimum ) + + 0.5 ) + this->_preMargin - 3, 0, // Start at the top 7, // The needle is 7 px wide this->sliderWidth // Fill the whole height - ); + ); } // Or a thin needle with text? else { - int sliderLength = this->fontMetrics().size(0, this->slider[sliderId]->text).width() + 2; - this->slider[sliderId]->rect = QRect( + int sliderLength = this->fontMetrics().size( 0, this->slider[ sliderId ]->text ).width() + 2; + this->slider[ sliderId ]->rect = QRect( // The needle is at the right side, the text before it, 0.5 pixel // offset for exact pixelization - int((this->width() - this->_preMargin - this->_postMargin - 1) * - (this->slider[sliderId]->value - this->slider[sliderId]->minimum) / - (this->slider[sliderId]->maximum - this->slider[sliderId]->minimum) + - 0.5) + + int( ( this->width() - this->_preMargin - this->_postMargin - 1 ) * + ( this->slider[ sliderId ]->value - this->slider[ sliderId ]->minimum ) / + ( this->slider[ sliderId ]->maximum - this->slider[ sliderId ]->minimum ) + + 0.5 ) + this->_preMargin - sliderLength + 1, 0, // Start at the top sliderLength, // The width depends on the text this->sliderWidth // Fill the whole height - ); + ); } } - return this->slider[sliderId]->rect; + return this->slider[ sliderId ]->rect; } /// \brief Search for the widest slider element. @@ -536,19 +550,19 @@ int LevelSlider::calculateWidth() { sliderWidth = 12; // Is it a vertical slider? - if (this->_direction == Qt::RightArrow || this->_direction == Qt::LeftArrow) { - for (QList::iterator sliderIt = slider.begin(); sliderIt != slider.end(); - ++sliderIt) { - int newSliderWidth = this->fontMetrics().size(0, (*sliderIt)->text).width(); + if ( this->_direction == Qt::RightArrow || this->_direction == Qt::LeftArrow ) { + for ( QList::iterator sliderIt = slider.begin(); sliderIt != slider.end(); + ++sliderIt ) { + int newSliderWidth = this->fontMetrics().size( 0, ( *sliderIt )->text ).width(); if ( newSliderWidth > sliderWidth ) sliderWidth = newSliderWidth; } } // Or a horizontal slider? else { - for (QList::iterator sliderIt = slider.begin(); sliderIt != slider.end(); - ++sliderIt) { - int newSliderWidth = this->fontMetrics().size(0, (*sliderIt)->text).height(); + for ( QList::iterator sliderIt = slider.begin(); sliderIt != slider.end(); + ++sliderIt ) { + int newSliderWidth = this->fontMetrics().size( 0, ( *sliderIt )->text ).height(); if ( newSliderWidth > sliderWidth ) sliderWidth = newSliderWidth; } @@ -560,14 +574,15 @@ int LevelSlider::calculateWidth() { /// \brief Fix the value if it's outside the limits. /// \param index The index of the slider who should be fixed. /// \return 0 when ok, -1 on error, 1 when increased and 2 when decreased. -void LevelSlider::fixValue(int index) { - if (index < 0 || index >= this->slider.count()) return; - - double lowest = qMin(this->slider[index]->minimum, this->slider[index]->maximum); - double highest = qMax(this->slider[index]->minimum, this->slider[index]->maximum); - if (this->slider[index]->value < lowest) { - this->slider[index]->value = lowest; - } else if (this->slider[index]->value > highest) { - this->slider[index]->value = highest; +void LevelSlider::fixValue( int index ) { + if ( index < 0 || index >= this->slider.count() ) + return; + + double lowest = qMin( this->slider[ index ]->minimum, this->slider[ index ]->maximum ); + double highest = qMax( this->slider[ index ]->minimum, this->slider[ index ]->maximum ); + if ( this->slider[ index ]->value < lowest ) { + this->slider[ index ]->value = lowest; + } else if ( this->slider[ index ]->value > highest ) { + this->slider[ index ]->value = highest; } } diff --git a/openhantek/src/widgets/levelslider.h b/openhantek/src/widgets/levelslider.h index 42a8c56d..aa571261 100644 --- a/openhantek/src/widgets/levelslider.h +++ b/openhantek/src/widgets/levelslider.h @@ -29,7 +29,7 @@ class LevelSlider : public QWidget { Q_OBJECT public: - LevelSlider(Qt::ArrowType direction = Qt::RightArrow, QWidget *parent = nullptr); + LevelSlider( Qt::ArrowType direction = Qt::RightArrow, QWidget *parent = nullptr ); ~LevelSlider(); QSize sizeHint() const; @@ -37,41 +37,41 @@ class LevelSlider : public QWidget { int preMargin() const; int postMargin() const; - int addSlider(int index = -1); - int addSlider(const QString &text, int index = -1); - int removeSlider(int index = -1); + int addSlider( int index = -1 ); + int addSlider( const QString &text, int index = -1 ); + int removeSlider( int index = -1 ); // Parameters for a specific slider - const QColor color(int index) const; - void setColor(unsigned index, QColor color); - const QString text(int index) const; - int setText(int index, const QString &text); - bool visible(int index) const; - void setIndexVisible(unsigned index, bool visible); - - double minimum(int index) const; - double maximum(int index) const; - void setLimits(int index, double minimum, double maximum); - double step(int index) const; - double setStep(int index, double step); - double value(int index) const; - void setValue(int index, double value); + const QColor color( int index ) const; + void setColor( unsigned index, QColor color ); + const QString text( int index ) const; + int setText( int index, const QString &text ); + bool visible( int index ) const; + void setIndexVisible( unsigned index, bool visible ); + + double minimum( int index ) const; + double maximum( int index ) const; + void setLimits( int index, double minimum, double maximum ); + double step( int index ) const; + double setStep( int index, double step ); + double value( int index ) const; + void setValue( int index, double value ); // Parameters for all sliders Qt::ArrowType direction() const; - int setDirection(Qt::ArrowType direction); + int setDirection( Qt::ArrowType direction ); protected: - void mouseMoveEvent(QMouseEvent *event); - void mousePressEvent(QMouseEvent *event); - void mouseReleaseEvent(QMouseEvent *event); + void mouseMoveEvent( QMouseEvent *event ); + void mousePressEvent( QMouseEvent *event ); + void mouseReleaseEvent( QMouseEvent *event ); - void paintEvent(QPaintEvent *event); - void resizeEvent(QResizeEvent *event); + void paintEvent( QPaintEvent *event ); + void resizeEvent( QResizeEvent *event ); - QRect calculateRect(int sliderId); + QRect calculateRect( int sliderId ); int calculateWidth(); - void fixValue(int index); + void fixValue( int index ); QList slider; ///< The parameters for each slider int pressedSlider; ///< The currently pressed (moved) slider @@ -83,5 +83,5 @@ class LevelSlider : public QWidget { int _postMargin; ///< The margin after the maximum slider position signals: - void valueChanged(int index, double value); ///< The value of a slider has changed + void valueChanged( int index, double value ); ///< The value of a slider has changed }; diff --git a/openhantek/src/widgets/sispinbox.cpp b/openhantek/src/widgets/sispinbox.cpp index fb26bb54..93e18d30 100644 --- a/openhantek/src/widgets/sispinbox.cpp +++ b/openhantek/src/widgets/sispinbox.cpp @@ -32,15 +32,15 @@ // class OpenHantekMainWindow /// \brief Initializes the SiSpinBox internals. /// \param parent The parent widget. -SiSpinBox::SiSpinBox(QWidget *parent) : QDoubleSpinBox(parent) { this->init(); } +SiSpinBox::SiSpinBox( QWidget *parent ) : QDoubleSpinBox( parent ) { this->init(); } /// \brief Initializes the SiSpinBox, allowing the user to choose the unit. /// \param unit The unit shown for the value in the spin box. /// \param parent The parent widget. -SiSpinBox::SiSpinBox(Unit unit, QWidget *parent) : QDoubleSpinBox(parent) { +SiSpinBox::SiSpinBox( Unit unit, QWidget *parent ) : QDoubleSpinBox( parent ) { this->init(); - this->setUnit(unit); + this->setUnit( unit ); this->setBackground(); } @@ -52,78 +52,87 @@ SiSpinBox::~SiSpinBox() {} /// \param input The content of the text box. /// \param pos The position of the cursor in the text box. /// \return Validity of the current text. -QValidator::State SiSpinBox::validate(QString &input, int &pos) const { - Q_UNUSED(pos); +QValidator::State SiSpinBox::validate( QString &input, int &pos ) const { + Q_UNUSED( pos ); bool ok; - double value = stringToValue(input, this->unit, &ok); + double value = stringToValue( input, this->unit, &ok ); - if (!ok) return QValidator::Invalid; + if ( !ok ) + return QValidator::Invalid; - if (input == this->textFromValue(value)) return QValidator::Acceptable; + if ( input == this->textFromValue( value ) ) + return QValidator::Acceptable; return QValidator::Intermediate; } /// \brief Parse value from input text. /// \param text The content of the text box. /// \return Value in base unit. -double SiSpinBox::valueFromText(const QString &text) const { return stringToValue(text, this->unit); } +double SiSpinBox::valueFromText( const QString &text ) const { return stringToValue( text, this->unit ); } /// \brief Get string representation of value. /// \param val Value in base unit. /// \return String representation containing value and (prefix+)unit. -QString SiSpinBox::textFromValue(double val) const { return valueToString(val, this->unit, -1) + this->unitPostfix; } +QString SiSpinBox::textFromValue( double val ) const { + return valueToString( val, this->unit, -1 ) + this->unitPostfix; +} /// \brief Fixes the text after the user finished changing it. /// \param input The content of the text box. -void SiSpinBox::fixup(QString &input) const { +void SiSpinBox::fixup( QString &input ) const { bool ok; - double value = stringToValue(input, this->unit, &ok); + double value = stringToValue( input, this->unit, &ok ); - if (!ok) value = this->value(); + if ( !ok ) + value = this->value(); - input = this->textFromValue(value); + input = this->textFromValue( value ); } /// \brief Increase/decrease the values in fixed steps. /// \param doStep The number of steps, positive means increase. -void SiSpinBox::stepBy(int doStep) { +void SiSpinBox::stepBy( int doStep ) { // Skip if we are already at a limit or if doStep is null - if (doStep == 0 || (doStep < 0 && this->value() <= this->minimum()) || - (doStep > 0 && this->value() >= this->maximum())) { + if ( doStep == 0 || ( doStep < 0 && this->value() <= this->minimum() ) || + ( doStep > 0 && this->value() >= this->maximum() ) ) { return; } int stepsCount = this->steps.size() - 1; if ( 0 == mode ) { // this is a regular 1/2/5.. spinbox double stepsSpan = this->steps.last() / this->steps.first(); double value = 0; - if (!this->steppedTo) { // No step done directly before this one, - // ... so we need to check where we are + if ( !this->steppedTo ) { // No step done directly before this one, + // ... so we need to check where we are // Get how often the steps have to be fully ran through - int stepsFully = int(floor(log(this->value() / this->steps.first()) / log(stepsSpan))); + int stepsFully = int( floor( log( this->value() / this->steps.first() ) / log( stepsSpan ) ) ); // And now the remaining multiple - double stepMultiple = this->value() / pow(stepsSpan, stepsFully); + double stepMultiple = this->value() / pow( stepsSpan, stepsFully ); // Now get the neighbours of the current value from our steps list int remainingSteps = 0; - for (; remainingSteps <= stepsCount; ++remainingSteps) { - if (this->steps[remainingSteps] > stepMultiple) break; + for ( ; remainingSteps <= stepsCount; ++remainingSteps ) { + if ( this->steps[ remainingSteps ] > stepMultiple ) + break; } - if (remainingSteps > 0) // Shouldn't happen, but double may have rounding errors + if ( remainingSteps > 0 ) // Shouldn't happen, but double may have rounding errors --remainingSteps; this->stepId = stepsFully * stepsCount + remainingSteps; // We need to do one step less down if we are inbetween two of them since // our step is lower than the value - if (doStep < 0 && this->steps[remainingSteps] < stepMultiple) ++this->stepId; + if ( doStep < 0 && this->steps[ remainingSteps ] < stepMultiple ) + ++this->stepId; } - int subStep = doStep / abs(doStep); - for (int i = 0; i != doStep; i += subStep) { + int subStep = doStep / abs( doStep ); + for ( int i = 0; i != doStep; i += subStep ) { this->stepId += subStep; int stepsId = this->stepId % stepsCount; - if (stepsId < 0) stepsId += stepsCount; - value = pow(stepsSpan, floor(double(this->stepId) / stepsCount)) * this->steps[stepsId]; - if (value <= this->minimum() || value >= this->maximum()) break; + if ( stepsId < 0 ) + stepsId += stepsCount; + value = pow( stepsSpan, floor( double( this->stepId ) / stepsCount ) ) * this->steps[ stepsId ]; + if ( value <= this->minimum() || value >= this->maximum() ) + break; } - this->setValue(value); + this->setValue( value ); this->steppedTo = true; } else { // irregular spinbox, e.g. sample rate ..10/12/15/24/30.., check always stepId = 0; @@ -139,8 +148,9 @@ void SiSpinBox::stepBy(int doStep) { /// \brief Set the unit for this spin box. /// \param newUnit The unit shown for the value in the spin box. /// \return true on success, false on invalid unit. -bool SiSpinBox::setUnit(Unit newUnit) { - if (newUnit >= UNIT_COUNT) return false; +bool SiSpinBox::setUnit( Unit newUnit ) { + if ( newUnit >= UNIT_COUNT ) + return false; this->unit = newUnit; return true; @@ -148,33 +158,33 @@ bool SiSpinBox::setUnit(Unit newUnit) { /// \brief Set the unit postfix for this spin box. /// \param postfix the string shown after the unit in the spin box. -void SiSpinBox::setUnitPostfix(const QString &postfix) { this->unitPostfix = postfix; } +void SiSpinBox::setUnitPostfix( const QString &postfix ) { this->unitPostfix = postfix; } /// \brief Set the steps the spin box will take. /// \param newSteps The steps, will be extended with the ratio from the start after /// the last element. -void SiSpinBox::setSteps(const QList &newSteps) { this->steps = newSteps; } +void SiSpinBox::setSteps( const QList &newSteps ) { this->steps = newSteps; } /// \brief Set the mode. /// \param mode The mode, the value 0 will have fixed interval, otherwise the /// value will have interval within steps itself. -void SiSpinBox::setMode(const int newMode) { this->mode = newMode; } +void SiSpinBox::setMode( const int newMode ) { this->mode = newMode; } /// \brief Generic initializations. void SiSpinBox::init() { - setMinimum(1e-12); - setMaximum(1e12); - setValue(1.0); - setDecimals(DBL_MAX_10_EXP + DBL_DIG); // Disable automatic rounding - setFocusPolicy(Qt::NoFocus); + setMinimum( 1e-12 ); + setMaximum( 1e12 ); + setValue( 1.0 ); + setDecimals( DBL_MAX_10_EXP + DBL_DIG ); // Disable automatic rounding + setFocusPolicy( Qt::NoFocus ); steps << 1.0 << 2.0 << 5.0 << 10.0; steppedTo = false; stepId = 0; mode = 0; - connect(this, static_cast(&QDoubleSpinBox::valueChanged), - this, &SiSpinBox::resetSteppedTo); + connect( this, static_cast( &QDoubleSpinBox::valueChanged ), this, + &SiSpinBox::resetSteppedTo ); } /// \brief Resets the ::steppedTo flag after the value has been changed. @@ -183,6 +193,6 @@ void SiSpinBox::resetSteppedTo() { this->steppedTo = false; } // fix Dark mode background introduced with MacOS 10.24 (mojave) void SiSpinBox::setBackground() { QPalette palette; - QColor background = palette.color(QPalette::Window); - this->setStyleSheet("background-color: " + background.name()); + QColor background = palette.color( QPalette::Window ); + this->setStyleSheet( "background-color: " + background.name() ); } diff --git a/openhantek/src/widgets/sispinbox.h b/openhantek/src/widgets/sispinbox.h index d917c7d1..5e39a209 100644 --- a/openhantek/src/widgets/sispinbox.h +++ b/openhantek/src/widgets/sispinbox.h @@ -15,19 +15,19 @@ class SiSpinBox : public QDoubleSpinBox { Q_OBJECT public: - explicit SiSpinBox(QWidget *parent = nullptr); - SiSpinBox(Unit unit, QWidget *parent = nullptr); + explicit SiSpinBox( QWidget *parent = nullptr ); + SiSpinBox( Unit unit, QWidget *parent = nullptr ); ~SiSpinBox(); - QValidator::State validate(QString &input, int &pos) const; - double valueFromText(const QString &text) const; - QString textFromValue(double val) const; - void fixup(QString &input) const; - void stepBy(int steps); - bool setUnit(Unit unit); - void setUnitPostfix(const QString &postfix); - void setSteps(const QList &steps); - void setMode(const int mode); + QValidator::State validate( QString &input, int &pos ) const; + double valueFromText( const QString &text ) const; + QString textFromValue( double val ) const; + void fixup( QString &input ) const; + void stepBy( int steps ); + bool setUnit( Unit unit ); + void setUnitPostfix( const QString &postfix ); + void setSteps( const QList &steps ); + void setMode( const int mode ); private: void init(); diff --git a/openhantek/translations/openhantek_de.ts b/openhantek/translations/openhantek_de.ts index e474aaa9..9e151b24 100644 --- a/openhantek/translations/openhantek_de.ts +++ b/openhantek/translations/openhantek_de.ts @@ -4,7 +4,7 @@ - + Couldn't open device: %1 Konnte Gerät %1 nicht öffnen @@ -57,53 +57,53 @@ Bartlett-Hann - + Blackman Blackman - + Nuttall Nuttall - + Blackman-Harris Blackman-Harris - + Blackman-Nuttall Blackman-Nuttall - + Flat top Flat Top - + <b>Window function</b> Fensterfunktion - + <b>Reference level</b><br/>0 dBu = -2.2 dBV<br/>0 dBm (@600 &Omega;) = -2.2 dBV<br/>0 dBm (@50 &Omega;) = -13 dBV <b>Referenzpegel</b><br/>0 dBu = -2.2 dBV<br/>0 dBm (@600 &Omega;) = -2.2 dBV<br/>0 dBm (@50 &Omega;) = -13 dBV - - + + dBV dBV - + <b>Minimum magnitude</b> Minimaler Pegel - + Spectrum Spektrum @@ -111,64 +111,64 @@ DsoConfigColorsPage - + Axes Achsen - + Background Hintergrund - + Border Rahmen - + Grid Gitternetz - + Markers Marker - + Text Text - + Screen and Print Colors Bildschirm- und Drucker-Farben - + Screen Bildschirm - + <hr width="100%"/> <hr width="100%"/> - + Print Drucker - - + + Channel Kanal - - + + Spectrum Spektrum @@ -219,37 +219,37 @@ DsoConfigFilePage - + Export Images with Screen Colors Exportiere Bilder mit Bildschirm-Farben - + Image width Bildbreite - + Image height Bildhöhe - + Export Export - + Save default settings on exit Standardeinstellung beim Beenden speichern - + Save default settings now Standardeinstellungen jetzt speichern - + Configuration Konfiguration @@ -257,47 +257,47 @@ DsoConfigScopePage - + Off Aus - + Linear Linear - + Interpolation Interpolation - + Digital phosphor depth Stufen für digitalen Phosphor - + Graph Graph - + Position Position - + Left Links - + Right Rechts - + Cursors Cursor @@ -305,12 +305,12 @@ DsoWidget - - - - - - + + + + + + /div /div @@ -325,59 +325,59 @@ Marker - - + + ON EIN - - + + OFF AUS - + Markers Merker - + Time: Zeit: - + Frequency: Frequenz: - + Zoom x%L1 Zoom x%L1 - + Zoom --- Zoom --- - + %L1% %L1% - + %1 %2 %3 %4 %5 %1 %2 %3 %4 %5 - + /s /s - + on screen angezeigt @@ -385,12 +385,12 @@ ExporterRegistry - + Data saved Daten gespeichert - + No data exported Keine Daten exportiert @@ -398,29 +398,29 @@ GlScope - + System does not support OpenGL Shading Language (GLSL) System unterstützt nicht OpenGL Shading Language (GLSL) - + OpenGL init called twice! OpenGL init wurde doppelt aufgerufen! - + Failed to compile OpenGL shader programs. Fehler beim Übersetzen der OpenGL Shader-Programme.\n - + Failed to link/bind OpenGL shader programs. Fehler beim Linken der OpenGL Shader-Programme. - + Failed to locate shader variable. Kann Shader-Variable nicht lokalisieren. @@ -436,7 +436,7 @@ Konnte Kanalpegeldaten des Oszilloskops nicht lesen - + Couldn't get calibration data from oscilloscope's EEPROM. Use a config file for calibration! Konnte Kalibrierdaten des Oszilloskops nicht lesen, benutze eine config-Datei für die Kalibrierung! @@ -477,42 +477,42 @@ LegacyExportDrawer - + %L1% %L1% - + %1 %2 %3 %4 %5 %1 %2 %3 %4 %5 - + %1 S on screen %1 S angezeigt - + /s /s - - - - - - + + + + + + /div /div - + Zoom x%L1 Zoom x%L1 - + Marker 1/2 Marker 1/2 @@ -645,89 +645,89 @@ Manuelles Kommando - + OpenHantek6022 (%1) - Device %2 (FW%3) OpenHantek6022 (%1) - Device %2 (FW%3) - + Invalid command Ungültiger Befehl - + Stop the oscilloscope Das Oszilloskop anhalten - + Stop Stop - + Start Start - + Start the oscilloscope Startet das Oszilloskop - + Open file Datei öffnen - - + + Settings (*.ini) Einstellungen (*.ini) - + Save settings Einstellungen speichern - + Disable fading of previous graphs Nachleuchten von vorigen Graphen deaktivieren - + Enable fading of previous graphs Nachleuchten von vorigen Graphen aktivieren - + Hide histogram Histogramm ausblenden - + Show histogram Histogramm einblenden - + Hide magnified scope Vergrößerte Anzeige ausblenden - + Show magnified scope Vergrößerte Anzeige anzeigen - + Hide measurements Messwerte ausblenden - + Show measurements Messwerte anzeigen @@ -747,7 +747,7 @@ <p>Programm läuft seit %1 Sekunden.</p> - + %1: %2 %1: %2 @@ -833,12 +833,12 @@ Kein Zugriff auf das USB-Gerät. Das Betriebssystem blockiert möglicherweise den Zugriff. Für Windows muss eventuell zuerst ein Treiber geladen werden. Für Linux ist eine udev-Datei erforderlich, die den Zugriff auf das Gerät erlaubt. - + Sorry Sorry - + This is not yet implemented! Dies ist noch nicht unterstützt! @@ -861,22 +861,22 @@ %L1 dB - + %L1 ps %L1 ps - + %L1 ns %L1 ns - + %L1 ms %L1 ms - + %L1 s %L1 s @@ -886,77 +886,77 @@ %L1 µV - + %L1 µs %L1 µs - + %L1 min %L1 min - + %L1 h %L1 h - + %L1 Hz %L1 Hz - + %L1 kHz %L1 kHz - + %L1 MHz %L1 MHz - + %L1 GHz %L1 GHz - + %L1 S %L1 S - + %L1 kS %L1 kS - + %L1 MS %L1 MS - + %L1 GS %L1 GS - + CH%1 CH%1 - + SP%1 SP%1 - + MATH MATH - + SPM SPM @@ -964,43 +964,43 @@ QCoreApplication - + Export CSV .. Exportiere CSV .. - + Comma-Separated Values (*.csv) Kommagetrennte Werte (*.csv) - + Export Image/PDF .. Exportiere Graphik/PDF .. - + Portable Document Format (*.pdf) Portables Dokumentenformat (*.pdf) - + Image (*.png *.xpm *.jpg) Bild (*.png *.xpm *.jpg) - - + + Export file .. Datei exportieren .. - + Print .. Drucken .. - + Print oscillograph Oszillogramm drucken @@ -1243,22 +1243,22 @@ QObject - + %1:%2 - No access %1:%2 - Kein Zugriff - + %1:%2 (%3 - %4) %1:%2 (%3 - %4) - + Devicename Gerätename - + Status Status @@ -1287,42 +1287,42 @@ ... - + <p><br/><b>The device is ready for use.</b></p><p>Please observe the <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/OpenHantek6022_User_Manual.pdf'>user manual</a> for safe operation.</p> <p><br/><b>Das Gerät ist bereit.</b></p><p>Das <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/OpenHantek6022_User_Manual.pdf'>Benutzerhandbuch</a> gibt Hinweise für den sicheren Gebrauch.</p> - + <p>Upload in progress ...</p><p><b>If the upload takes more than 30 s, please close this window <br/>and restart the program!</b></p> <p>Firmware wird geladen...</p><p><b>Sollte dies länger als 30 s dauern, bitte abbrechen <br/>und das Programm neu starten!</b></p> - + <p><br/><b>Connection failed!</b></p> <p><br/><b>Verbindungsfehler!</b></p> - + <p>OpenHantek6022 is searching for compatible devices ...</p><p><img align='right' height='200' src='qrc:///switch_6022BL.png'>Don't forget to switch your device into oscilloscope mode if it has multiple modes.</p> <p>OpenHantek6022 sucht nach kompatiblen Geräten ...</p><p><img align='right' height='150' src='qrc:///switch_6022BL.png'>Bitte das Gerät in den Oszilloskop-Modus schalten, falls es mehrere Funktionen besitzt.</p> - + <p>Please make sure you have installed the windows usb driver correctly</p> <p>Bitte sicherstellen, dass der korrekte Windows-Treiber installiert ist.</p> - + <p>Please make sure you have copied the udev rules file to <b>%1</b> for correct USB access permissions.</p> <p>Bitte sicherstellen, dass eine udev-Regel nach <b>%1</b> kopiert wurde um den USB-Zugriff zu ermöglichen.</p> - + <p>Visit the build and run instruction <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/build.md'>website</a> for help.</p> <p><a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/build.md'>Informationen</a> zur Erstellung des Programms.</p> - + Can't initalize USB: %1 Kann USB nicht initialisieren: %1 @@ -1330,7 +1330,7 @@ SpectrumDock - + Spectrum Spektrum @@ -1358,12 +1358,12 @@ Modus - + Slope Flanke - + Source Quelle diff --git a/openhantek/translations/openhantek_es.ts b/openhantek/translations/openhantek_es.ts index 884706c3..5ba6eadc 100644 --- a/openhantek/translations/openhantek_es.ts +++ b/openhantek/translations/openhantek_es.ts @@ -4,7 +4,7 @@ - + Couldn't open device: %1 No se pudo abrir dispositivo: %1 @@ -57,53 +57,53 @@ - + Blackman - + Nuttall - + Blackman-Harris - + Blackman-Nuttall - + Flat top - + <b>Window function</b> <b>Función de ventana</b> - + <b>Reference level</b><br/>0 dBu = -2.2 dBV<br/>0 dBm (@600 &Omega;) = -2.2 dBV<br/>0 dBm (@50 &Omega;) = -13 dBV <b>Nivel de referencia</b><br/>0 dBu = -2.2 dBV<br/>0 dBm (@600 &Omega;) = -2.2 dBV<br/>0 dBm (@50 &Omega;) = -13 dBV - - + + dBV - + <b>Minimum magnitude</b> <b>Magnitud mínima</b> - + Spectrum Espectro @@ -111,64 +111,64 @@ DsoConfigColorsPage - + <hr width="100%"/> - + Screen Pantalla - + Print Impresión - + Axes Ejes - + Background Fondo - + Border Borde - + Grid Rejilla - + Markers Marcadores - + Text Texto - - + + Channel Canal - - + + Spectrum Espectro - + Screen and Print Colors Pantalla y colores de impresión @@ -219,37 +219,37 @@ DsoConfigFilePage - + Export Images with Screen Colors Exportar imágenes con los colores de la pantalla - + Image width Ancho de la imagen - + Image height Altura de la imagen - + Export Exportar - + Save default settings on exit Guardar configuración predeterminada al salir - + Save default settings now Guardar configuración predeterminada ahora - + Configuration Configuración @@ -257,47 +257,47 @@ DsoConfigScopePage - + Off Desactivada - + Linear Lineal - + Interpolation Interpolación - + Digital phosphor depth Profundidad del fósforo digital - + Graph Gráfico - + Position Posición - + Left Izquierda - + Right Derecha - + Cursors Cursores @@ -315,69 +315,69 @@ Marcadores - - + + ON - - + + OFF - + Markers Marcadores - + Time: Tiempo: - + Frequency: Frecuencia: - + Zoom x%L1 - + Zoom --- - - - - - - + + + + + + /div - + %L1% - + %1 %2 %3 %4 %5 - + /s - + on screen en pantalla @@ -385,12 +385,12 @@ ExporterRegistry - + Data saved Datos guardados - + No data exported Ningún dato exportado @@ -398,29 +398,29 @@ GlScope - + System does not support OpenGL Shading Language (GLSL) El sistema no tiene OpenGL Shading Language (GLSL) - + OpenGL init called twice! ¡OpenGL init se ha llamado dos veces! - + Failed to compile OpenGL shader programs. Ha fallado al compilar programas OpenGL shader.\n - + Failed to link/bind OpenGL shader programs. Ha fallado al enlazar programas OpenGL shader.\n - + Failed to locate shader variable. Ha fallado al localizar la variable shader. @@ -432,7 +432,7 @@ No se pudieron obtener los datos de calibración del osciloscopio - + Couldn't get calibration data from oscilloscope's EEPROM. Use a config file for calibration! No se pudieron obtener los datos de calibración del osciloscopio. ¡Usa un archivo de configuración para la calibración! @@ -473,42 +473,42 @@ LegacyExportDrawer - + %L1% - + %1 %2 %3 %4 %5 - + %1 S on screen %1 S en pantalla - + /s - - - - - - + + + + + + /div - + Zoom x%L1 - + Marker 1/2 Marcador 1/2 @@ -562,7 +562,7 @@ - + Save settings Guardar configuración @@ -647,83 +647,83 @@ Orden manual - + OpenHantek6022 (%1) - Device %2 (FW%3) OpenHantek6022 (%1) - Dispositivo %2 (FW%3) - + Invalid command Orden no válida - + Stop Parar - + Stop the oscilloscope Parar el osciloscopio - + Start Iniciar - + Start the oscilloscope Iniciar el osciloscopio - + Open file Abrir archivo - - + + Settings (*.ini) Configuración (*.ini) - + Disable fading of previous graphs Desactivar desvanecimiento de los gráficos anteriores - + Enable fading of previous graphs Activar desvanecimiento de los gráficos anteriores - + Hide histogram Ocultar histograma - + Show histogram Mostrar histograma - + Hide magnified scope Ocultar osciloscopio aumentado - + Show magnified scope Mostrar osciloscopio aumentado - + Hide measurements Ocultar medidas - + Show measurements Mostrar medidas @@ -743,7 +743,7 @@ <p>El programa ha estado funcionando durante %1 segundos.</p> - + %1: %2 @@ -828,12 +828,12 @@ Acceso no permitido para el dispositivo USB seleccionado. Su sistema operativo puede haber impedido el acceso. En Windows puede que primero necesite instalar un controlador genérico. En Linux necesita instalar una regla udev para permitir el acceso al usuario actual. - + Sorry Lo siento - + This is not yet implemented! ¡Todavía no implementado! @@ -861,97 +861,97 @@ - + %L1 ps - + %L1 ns - + %L1 µs - + %L1 ms - + %L1 s - + %L1 min - + %L1 h - + %L1 Hz - + %L1 kHz - + %L1 MHz - + %L1 GHz - + %L1 S - + %L1 kS - + %L1 MS - + %L1 GS - + SP%1 - + CH%1 - + SPM - + MATH @@ -1194,43 +1194,43 @@ Lineal - + Print .. Imprimir... - + Print oscillograph Imprimir oscilógrafo - + Export Image/PDF .. Exportar imagen/PDF... - + Portable Document Format (*.pdf) Formato de documento portable (*.pdf) - + Image (*.png *.xpm *.jpg) Imagen (*.png *.xpm *.jpg) - - + + Export file .. Exportar archivo... - + Export CSV .. Exportar CSV... - + Comma-Separated Values (*.csv) Valores separados por coma (*.csv) @@ -1238,22 +1238,22 @@ QObject - + %1:%2 - No access %1:%2 - Sin acceso - + %1:%2 (%3 - %4) - + Devicename Nombre del dispositivo - + Status Estado @@ -1282,42 +1282,42 @@ - + <p><br/><b>The device is ready for use.</b></p><p>Please observe the <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/OpenHantek6022_User_Manual.pdf'>user manual</a> for safe operation.</p> <p><br/><b>El dispositivo está listo para su uso.</b></p><p>Lea con detenimiento el <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/OpenHantek6022_User_Manual.pdf'>manual del usuario</a> para una operacion segura.</p> - + <p>Upload in progress ...</p><p><b>If the upload takes more than 30 s, please close this window <br/>and restart the program!</b></p> <p>Carga en progreso ...</p><p><b>Si la carga durase más de 30 s, cierre esta ventana <br/>y reinicie el programa.</b></p> - + <p><br/><b>Connection failed!</b></p> <p><br/><b>Ha fallado la conexión.</b></p> - + <p>OpenHantek6022 is searching for compatible devices ...</p><p><img align='right' height='200' src='qrc:///switch_6022BL.png'>Don't forget to switch your device into oscilloscope mode if it has multiple modes.</p> <p>OpenHantek6022 está buscando dispositivos compatibles...</p><p><img align='right' height='200' src='qrc:///switch_6022BL.png'>No olvide cambiar su dispositivo al modo osciloscopio si tiene múltiples modos.</p> - + <p>Please make sure you have installed the windows usb driver correctly</p> <p>Asegúrese de que ha instalado el controlador USB de Windows correctamente</p> - + <p>Please make sure you have copied the udev rules file to <b>%1</b> for correct USB access permissions.</p> <p>Asegúrese de que ha copiado las reglas udev en <b>%1</b> para permisos de acceso USB correctos.</p> - + <p>Visit the build and run instruction <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/build.md'>website</a> for help.</p> <p>Visite las instrucciones de compilación y ejecución en el <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/build.md'>sitio web</a> para más ayuda.</p> - + Can't initalize USB: %1 No se puede inicializar USB: %1 @@ -1325,7 +1325,7 @@ SpectrumDock - + Spectrum Espectro @@ -1353,12 +1353,12 @@ Modo - + Slope Flanco - + Source Fuente diff --git a/openhantek/translations/openhantek_fr.ts b/openhantek/translations/openhantek_fr.ts index 53b69cd5..c94800b6 100644 --- a/openhantek/translations/openhantek_fr.ts +++ b/openhantek/translations/openhantek_fr.ts @@ -4,7 +4,7 @@ - + Couldn't open device: %1 Impossible d'ouvrir le périphérique : %1 @@ -57,53 +57,53 @@ Bartlett-Hann - + Blackman Blackman - + Nuttall Nuttall - + Blackman-Harris Blackman-Harris - + Blackman-Nuttall Blackman-Nuttall - + Flat top Flat Top - + <b>Window function</b> <b>Fenêtrage</b> - + <b>Reference level</b><br/>0 dBu = -2.2 dBV<br/>0 dBm (@600 &Omega;) = -2.2 dBV<br/>0 dBm (@50 &Omega;) = -13 dBV <b>Niveau de réference</b><br/>0 dBu = -2.2 dBV<br/>0 dBm (@600 &Omega;) = -2.2 dBV<br/>0 dBm (@50 &Omega;) = -13 dBV - - + + dBV - + <b>Minimum magnitude</b> <b>Amplitude minimum</b> - + Spectrum Spectre @@ -111,64 +111,64 @@ DsoConfigColorsPage - + <hr width="100%"/> - + Screen Ecran - + Print Impression - + Axes Axes - + Background Arrière-plan - + Border Bordure - + Grid Grille - + Markers Repères - + Text Texte - - + + Channel Canal - - + + Spectrum Spectre - + Screen and Print Colors Couleurs à l'écran et à l'impression @@ -219,37 +219,37 @@ DsoConfigFilePage - + Export Images with Screen Colors Exporter images avec couleurs de l'écran - + Image width Largeur d'image - + Image height Hauteur d'image - + Export Exporter - + Save default settings on exit Enregistrer les réglages en quittant - + Save default settings now Enregistrer les réglages maintenant - + Configuration Configuration @@ -257,47 +257,47 @@ DsoConfigScopePage - + Off - + Linear Linéaire - + Interpolation Interpolation - + Digital phosphor depth Profondeur de phosphore numérique - + Graph Graphe - + Position Position - + Left Gauche - + Right Droite - + Cursors Curseurs @@ -315,69 +315,69 @@ Repères - - - - - - + + + + + + /div /div - - + + ON - - + + OFF - + Markers Repères - + Time: Temps : - + Frequency: Fréquence : - + Zoom x%L1 - + Zoom --- - + %L1% - + %1 %2 %3 %4 %5 - + /s /s - + on screen à l'écran @@ -385,12 +385,12 @@ ExporterRegistry - + Data saved Données sauvegardées - + No data exported Aucune donnée exportée @@ -398,31 +398,31 @@ GlScope - + System does not support OpenGL Shading Language (GLSL) Le système ne supporte pas OpenGL Shading Language (GLSL) - + OpenGL init called twice! Double initialisation d'OpenGL ! - + Failed to compile OpenGL shader programs. Echec de compilation des programmes d'ombrage OpenGL. - + Failed to link/bind OpenGL shader programs. Echec de création des liens des programmes d'ombrage OpenGL. - + Failed to locate shader variable. Echec de localisation des variables d'ombrage. @@ -434,7 +434,7 @@ Impossible d'obtenir les données de niveau du canal depuis l'oscilloscope - + Couldn't get calibration data from oscilloscope's EEPROM. Use a config file for calibration! Impossible d'obtenir les données de niveau du canal depuis l'oscilloscope. Utilisez un fichier de configuration pour la calibration ! @@ -475,42 +475,42 @@ LegacyExportDrawer - + %L1% - + %1 %2 %3 %4 %5 - + %1 S on screen %1 E à l'écran - + /s /s - - - - - - + + + + + + /div /div - + Zoom x%L1 - + Marker 1/2 Repère 1/2 @@ -663,89 +663,89 @@ &Ligne de commande - + OpenHantek6022 (%1) - Device %2 (FW%3) OpenHantek6022 (%1) - %2 (FW%3) - + Invalid command Commande invalide - + Stop Arrêter - + Stop the oscilloscope Arrêter l'oscilloscope - + Start Démarrer - + Start the oscilloscope Démarrer l'oscilloscope - + Open file Ouvrir une configuration - - + + Settings (*.ini) Réglages (*.ini) - + Save settings Enregistrer les réglages - + Disable fading of previous graphs Désactiver l'estompage des graphes précédents - + Enable fading of previous graphs Activer l'estompage des graphes précédents - + Hide histogram Cacher l’histogramme - + Show histogram Montrer l’histogramme - + Hide magnified scope Cacher la vue agrandie - + Show magnified scope Montrer la vue agrandie - + Hide measurements Cacher les mesures - + Show measurements Montrer les mesures @@ -765,7 +765,7 @@ <p>Le programme est en cours depuis %1 secondes.</p> - + %1: %2 @@ -850,12 +850,12 @@ Aucun accès n'est autorisé pour le périphérique USB sélectionné. Votre système d'exploitation peut interdire cet accès. Sous Windows, vous devrez peut-être d'abord installer un pilote générique. Sous Linux, vous devez installer une règle udev pour autoriser l'accès pour l'utilisateur courant. - + Sorry Désolé - + This is not yet implemented! Ceci n'est pas encore développé ! @@ -883,97 +883,97 @@ - + %L1 ps - + %L1 ns - + %L1 µs - + %L1 ms - + %L1 s - + %L1 min - + %L1 h - + %L1 Hz - + %L1 kHz - + %L1 MHz - + %L1 GHz - + %L1 S %L1 E - + %L1 kS %L1 kE - + %L1 MS %L1 ME - + %L1 GS %L1 GE - + SP%1 - + CH%1 - + SPM SPM - + MATH @@ -1220,12 +1220,12 @@ &Imprimer... - + Print .. Imprimer .. - + Print oscillograph Imprimer l'oscillographe @@ -1234,23 +1234,23 @@ Exporter i&mage/PDF... - + Export Image/PDF .. Exporter image/PDF .. - + Portable Document Format (*.pdf) - + Image (*.png *.xpm *.jpg) - - + + Export file .. Exporter un fichier .. @@ -1263,12 +1263,12 @@ Exporter &CSV... - + Export CSV .. Exporter CSV .. - + Comma-Separated Values (*.csv) @@ -1276,22 +1276,22 @@ QObject - + %1:%2 - No access %1:%2 - aucun accès - + %1:%2 (%3 - %4) - + Devicename Nom de l'appareil - + Status Etat @@ -1352,42 +1352,42 @@ <p><br/><b>La connexion a échoué!</p> - + <p><br/><b>The device is ready for use.</b></p><p>Please observe the <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/OpenHantek6022_User_Manual.pdf'>user manual</a> for safe operation.</p> <p><br/><b>L'appareil est prêt à l'emploi.</b></p><p>Veuillez lire le <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/OpenHantek6022_User_Manual.pdf'>mode d'emploi</a> pour un fonctionnement sûr.</p> - + <p>Upload in progress ...</p><p><b>If the upload takes more than 30 s, please close this window <br/>and restart the program!</b></p> <p>Téléchargement en cours...</p><p><b>S'il dure plus de 30 s, fermez cette fenêtre <br/>et redémarrez le programme !</b></p> - + <p><br/><b>Connection failed!</b></p> <p><br/><b>La connexion a échoué !</b></p> - + <p>OpenHantek6022 is searching for compatible devices ...</p><p><img align='right' height='200' src='qrc:///switch_6022BL.png'>Don't forget to switch your device into oscilloscope mode if it has multiple modes.</p> <p>OpenHantek6022 recherche des périphériques compatibles...</p><p><img align='right' height='200' src='qrc:////switch_6022BL.png'>N'oubliez pas de passer votre appareil en mode oscilloscope s'il a plusieurs modes.</p> - + <p>Please make sure you have installed the windows usb driver correctly</p> <p>Assurez-vous d'avoir installé correctement le pilote USB de Windows</p> - + <p>Please make sure you have copied the udev rules file to <b>%1</b> for correct USB access permissions.</p> <p>Assurez-vous d'avoir copié le fichier de règles udev dans <b>%1</b> pour des permissions d'accès USB correctes.</p> - + <p>Visit the build and run instruction <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/build.md'>website</a> for help.</p> <p>Visitez la page d'instructions <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/build.md'>build and run</a> pour de l'aide.</p> - + Can't initalize USB: %1 Impossible d'initialiser l'USB: %1 @@ -1395,7 +1395,7 @@ SpectrumDock - + Spectrum Spectre @@ -1423,12 +1423,12 @@ Mode - + Slope Pente - + Source Source diff --git a/openhantek/translations/openhantek_it.ts b/openhantek/translations/openhantek_it.ts index cffb5bda..d94e13fd 100644 --- a/openhantek/translations/openhantek_it.ts +++ b/openhantek/translations/openhantek_it.ts @@ -4,7 +4,7 @@ - + Couldn't open device: %1 @@ -57,53 +57,53 @@ - + Blackman - + Nuttall - + Blackman-Harris - + Blackman-Nuttall - + Flat top - + <b>Window function</b> - + <b>Reference level</b><br/>0 dBu = -2.2 dBV<br/>0 dBm (@600 &Omega;) = -2.2 dBV<br/>0 dBm (@50 &Omega;) = -13 dBV - - + + dBV - + <b>Minimum magnitude</b> - + Spectrum @@ -111,64 +111,64 @@ DsoConfigColorsPage - + <hr width="100%"/> - + Screen - + Print - + Axes - + Background - + Border - + Grid - + Markers - + Text - - + + Channel - - + + Spectrum - + Screen and Print Colors @@ -219,37 +219,37 @@ DsoConfigFilePage - + Export Images with Screen Colors - + Image width - + Image height - + Export - + Save default settings on exit - + Save default settings now - + Configuration @@ -257,47 +257,47 @@ DsoConfigScopePage - + Off - + Linear - + Interpolation - + Digital phosphor depth - + Graph - + Position - + Left - + Right - + Cursors @@ -315,69 +315,69 @@ - - - - - - + + + + + + /div - - + + ON - - + + OFF - + Markers - + Time: - + Frequency: - + Zoom x%L1 - + Zoom --- - + %L1% - + %1 %2 %3 %4 %5 - + /s - + on screen @@ -385,12 +385,12 @@ ExporterRegistry - + Data saved - + No data exported @@ -398,29 +398,29 @@ GlScope - + System does not support OpenGL Shading Language (GLSL) - + OpenGL init called twice! - + Failed to compile OpenGL shader programs. - + Failed to link/bind OpenGL shader programs. - + Failed to locate shader variable. @@ -428,7 +428,7 @@ HantekDsoControl - + Couldn't get calibration data from oscilloscope's EEPROM. Use a config file for calibration! @@ -469,42 +469,42 @@ LegacyExportDrawer - + %L1% - + %1 %2 %3 %4 %5 - + %1 S on screen - + /s - - - - - - + + + + + + /div - + Zoom x%L1 - + Marker 1/2 @@ -637,89 +637,89 @@ - + OpenHantek6022 (%1) - Device %2 (FW%3) - + Invalid command - + Stop - + Stop the oscilloscope - + Start - + Start the oscilloscope - + Open file - - + + Settings (*.ini) - + Save settings - + Disable fading of previous graphs - + Enable fading of previous graphs - + Hide histogram - + Show histogram - + Hide magnified scope - + Show magnified scope - + Hide measurements - + Show measurements @@ -739,7 +739,7 @@ - + %1: %2 @@ -824,12 +824,12 @@ - + Sorry - + This is not yet implemented! @@ -857,97 +857,97 @@ - + %L1 ps - + %L1 ns - + %L1 µs - + %L1 ms - + %L1 s - + %L1 min - + %L1 h - + %L1 Hz - + %L1 kHz - + %L1 MHz - + %L1 GHz - + %L1 S - + %L1 kS - + %L1 MS - + %L1 GS - + SP%1 - + CH%1 - + SPM - + MATH @@ -1190,43 +1190,43 @@ - + Print .. - + Print oscillograph - + Export Image/PDF .. - + Portable Document Format (*.pdf) - + Image (*.png *.xpm *.jpg) - - + + Export file .. - + Export CSV .. - + Comma-Separated Values (*.csv) @@ -1234,22 +1234,22 @@ QObject - + %1:%2 - No access - + %1:%2 (%3 - %4) - + Devicename - + Status @@ -1314,42 +1314,42 @@ <p><br/><b>Il collegamento è fallito!</p> - + <p><br/><b>The device is ready for use.</b></p><p>Please observe the <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/OpenHantek6022_User_Manual.pdf'>user manual</a> for safe operation.</p> <p><br/><b>Il dispositivo è pronto all'uso.</b></p><p>Per un funzionamento sicuro, osservare il <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/OpenHantek6022_User_Manual.pdf'>manuale d'uso.</a> - + <p>Upload in progress ...</p><p><b>If the upload takes more than 30 s, please close this window <br/>and restart the program!</b></p> <p>Upload in corso ...</p><p><b>Se il caricamento richiede più di 30 s, si prega di chiudere questa finestra <br/>e riavviare il programma!</b></p> - + <p><br/><b>Connection failed!</b></p> <p><br/><b>Il collegamento è fallito!</b></p> - + <p>OpenHantek6022 is searching for compatible devices ...</p><p><img align='right' height='200' src='qrc:///switch_6022BL.png'>Don't forget to switch your device into oscilloscope mode if it has multiple modes.</p> <p>ApertoHantek6022 è alla ricerca di dispositivi compatibili...</p><p><img align='right' height='200' src='qrc:////switch_6022BL.png'>Non dimenticare di passare il dispositivo in modalità oscilloscopio se ha più modalità.</p> - + <p>Please make sure you have installed the windows usb driver correctly</p> <p>Assicurati di aver installato correttamente il driver usb di Windows.</p> - + <p>Please make sure you have copied the udev rules file to <b>%1</b> for correct USB access permissions.</p> <p>Assicurati di aver copiato il file delle regole udev in <b>%1</b> per ottenere le corrette autorizzazioni di accesso USB.</p> - + <p>Visit the build and run instruction <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/build.md'>website</a> for help.</p> <p>Visitare l'istruzione di compilazione ed esecuzione <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/build.md'>sito web site</a> per help.</p> - + Can't initalize USB: %1 Non può initalizzare USB: %1 @@ -1357,7 +1357,7 @@ SpectrumDock - + Spectrum @@ -1385,12 +1385,12 @@ - + Slope - + Source diff --git a/openhantek/translations/openhantek_pt.ts b/openhantek/translations/openhantek_pt.ts index 0c9a7d8e..2e2f10b7 100644 --- a/openhantek/translations/openhantek_pt.ts +++ b/openhantek/translations/openhantek_pt.ts @@ -4,7 +4,7 @@ - + Couldn't open device: %1 @@ -57,53 +57,53 @@ Bartlett-Hann - + Blackman Blackman - + Nuttall Nuttall - + Blackman-Harris Blackman-Harris - + Blackman-Nuttall Blackman-Nuttall - + Flat top Flat Top - + <b>Window function</b> - + <b>Reference level</b><br/>0 dBu = -2.2 dBV<br/>0 dBm (@600 &Omega;) = -2.2 dBV<br/>0 dBm (@50 &Omega;) = -13 dBV - - + + dBV - + <b>Minimum magnitude</b> - + Spectrum Espectro @@ -111,64 +111,64 @@ DsoConfigColorsPage - + Axes Eixos - + Background Fundo - + Border Borda - + Grid Grade - + Markers Marcadores - + Text Texto - + Screen and Print Colors - + Screen Tela - + <hr width="100%"/> - + Print - - + + Channel Canal - - + + Spectrum Espectro @@ -219,37 +219,37 @@ DsoConfigFilePage - + Export Images with Screen Colors Exportar imagens com cores de tela - + Image width Largura da imagem - + Image height Altura da imagem - + Export Exportar - + Save default settings on exit Salvar configuração padrão ao sair - + Save default settings now Salvar configuração padrão agora - + Configuration Configuração @@ -257,12 +257,12 @@ DsoConfigScopePage - + Off Desligado - + Linear Linear @@ -271,37 +271,37 @@ Sinc - + Interpolation Interpolação - + Digital phosphor depth Profundidade digital - + Graph Gráfico - + Position - + Left - + Right - + Cursors @@ -313,12 +313,12 @@ Zoom x%L1 - - - - - - + + + + + + /div /div @@ -333,54 +333,54 @@ Marcadores - - + + ON - - + + OFF - + Markers - + Time: - + Frequency: - + Zoom x%L1 - + Zoom --- - + %L1% %L1% - + %1 %2 %3 %4 %5 - + on screen @@ -397,7 +397,7 @@ %1 %2 %3 %4 - + /s /s @@ -409,12 +409,12 @@ ExporterRegistry - + Data saved - + No data exported @@ -422,29 +422,29 @@ GlScope - + System does not support OpenGL Shading Language (GLSL) - + OpenGL init called twice! - + Failed to compile OpenGL shader programs. - + Failed to link/bind OpenGL shader programs. - + Failed to locate shader variable. @@ -456,7 +456,7 @@ Não foi possível obter dados do canal do osciloscópio - + Couldn't get calibration data from oscilloscope's EEPROM. Use a config file for calibration! Não foi possível obter dados de calibração a partir da EEPROM do osciloscópio. Use um arquivo de configuração para a calibração! @@ -497,7 +497,7 @@ LegacyExportDrawer - + %L1% %L1% @@ -506,7 +506,7 @@ %1 %2 %3 %4 - + %1 %2 %3 %4 %5 %1 %2 %3 %4 %5 {1 ?} {2 ?} {3 ?} @@ -515,32 +515,32 @@ %1 S - + %1 S on screen - + /s /s - - - - - - + + + + + + /div /div - + Zoom x%L1 Zoom x%L1 - + Marker 1/2 Construtor 1/2 @@ -677,12 +677,12 @@ - + OpenHantek6022 (%1) - Device %2 (FW%3) - + Invalid command Comando inválido @@ -691,7 +691,7 @@ &Parar - + Stop the oscilloscope Parar osciloscópio @@ -700,74 +700,74 @@ &Iniciar - + Stop - + Start - + Start the oscilloscope Iniciar osciloscópio - + Open file Abrir arquivo - - + + Settings (*.ini) Configurações (*.ini) - + Save settings Salvar configurações - + Disable fading of previous graphs Desabilitar desaparecimento de gráficos anteriores - + Enable fading of previous graphs Habilitar desaparecimento de gráficos anteriores - + Hide histogram - + Show histogram - + Hide magnified scope Esconder/Ampliar osciloscópio - + Show magnified scope Mostrar osciloscópio ampliado - + Hide measurements - + Show measurements @@ -787,7 +787,7 @@ - + %1: %2 @@ -872,12 +872,12 @@ - + Sorry - + This is not yet implemented! @@ -900,22 +900,22 @@ %L1 dB - + %L1 ps %L1 ps - + %L1 ns %L1 ns - + %L1 ms %L1 ms - + %L1 s %L1 s @@ -925,77 +925,77 @@ - + %L1 µs - + %L1 min %L1 min - + %L1 h %L1 h - + %L1 Hz %L1 Hz - + %L1 kHz %L1 kHz - + %L1 MHz %L1 MHz - + %L1 GHz %L1 GHz - + %L1 S %L1 S - + %L1 kS %L1 kS - + %L1 MS %L1 MS - + %L1 GS %L1 GS - + CH%1 CH%1 - + SP%1 SP%1 - + MATH MATH - + SPM SPC @@ -1003,12 +1003,12 @@ QCoreApplication - + Export CSV .. - + Comma-Separated Values (*.csv) Separado por ponto e vírgula (*.csv) @@ -1017,33 +1017,33 @@ Exportar arquivo... - + Export Image/PDF .. - + Portable Document Format (*.pdf) - + Image (*.png *.xpm *.jpg) Imagem (*.png *.xpm *.jpg) - - + + Export file .. - + Print .. - + Print oscillograph Impressão @@ -1290,22 +1290,22 @@ QObject - + %1:%2 - No access - + %1:%2 (%3 - %4) - + Devicename - + Status @@ -1370,42 +1370,42 @@ <p><br/><b>Conexão falhou!</p> - + <p><br/><b>The device is ready for use.</b></p><p>Please observe the <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/OpenHantek6022_User_Manual.pdf'>user manual</a> for safe operation.</p> <p><br/><b>O dispositivo está pronto para uso.</b></p><p>Por favor, observe o <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/OpenHantek6022_User_Manual.pdf'> manual do usuário</a> para uma operação segura.</p> - + <p>Upload in progress ...</p><p><b>If the upload takes more than 30 s, please close this window <br/>and restart the program!</b></p> - + <p><br/><b>Connection failed!</b></p> <p><br/><b>Conexão falhou!</b></p> - + <p>OpenHantek6022 is searching for compatible devices ...</p><p><img align='right' height='200' src='qrc:///switch_6022BL.png'>Don't forget to switch your device into oscilloscope mode if it has multiple modes.</p> <p>OpenHantek6022 está procurando por dispositivos compatíveis ...</p><p><img align='right' height='200' src='qrc:///switch_6022BL.png'>Não se esqueça de mudar seu dispositivo no modo osciloscópio se ele tiver vários modos.</p> - + <p>Please make sure you have installed the windows usb driver correctly</p> <Por favor, certifique-se de que instalou o driver usb do Windows corretamente</p> - + <p>Please make sure you have copied the udev rules file to <b>%1</b> for correct USB access permissions.</p> <Por favor, tenha certeza de que você copiou o arquivo de regras do udev para <b>%1</b> para obter as permissões de acesso USB corretas.</p> - + <p>Visit the build and run instruction <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/build.md'>website</a> for help.</p> <p>Visita a instrução de compilação e execução <a href='https://github.com/OpenHantek/OpenHantek6022/blob/master/docs/build.md'>website</a> para ajuda.</p> - + Can't initalize USB: %1 Não é possível initalizar o USB: %1 @@ -1413,7 +1413,7 @@ SpectrumDock - + Spectrum Espectro @@ -1441,12 +1441,12 @@ Modo - + Slope Declive - + Source Fonte diff --git a/readme.md b/readme.md index 70aa9404..3992f919 100644 --- a/readme.md +++ b/readme.md @@ -104,16 +104,18 @@ We welcome any reported Github Issue if you have a problem with this software. S - Read [how to properly contribute to open source projects on GitHub][10]. - Create a separate branch other than *master* for your changes. It is not possible to directly commit to master on this repository. - Write [good commit messages][11]. + - [Sign-off][12] your commits. - Use the same [coding style and spacing][13] (install clang-format. Use make target: `make format` or execute directly from the openhantek directory: `clang-format -style=file src/*`). - - Open a [pull request][12] with a clear title and description. + - Open a [pull request][14] with a clear title and description. - Read [Add a new device](docs/adddevice.md) if you want to know how to add a device. - We recommend QtCreator as IDE on all platforms. It comes with CMake support, a decent compiler, and Qt out of the box. [10]: http://gun.io/blog/how-to-github-fork-branch-and-pull-request [11]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html -[12]: https://help.github.com/articles/using-pull-requests +[12]: https://github.com/probot/dco/blob/master/README.md [13]: http://llvm.org/docs/CodingStandards.html +[14]: https://help.github.com/articles/using-pull-requests ## Other DSO open source software * [Firmware used by OpenHantek and python bindings for 6022BE/BL](https://github.com/Ho-Ro/Hantek6022API)