From a01250e64a9601b7442009c9697942542aa5b10e Mon Sep 17 00:00:00 2001 From: Adrian Suciu Date: Tue, 10 Oct 2023 13:32:43 +0300 Subject: [PATCH] general: run tools/format.sh Signed-off-by: Adrian Suciu --- .clang-format | 2 +- CMakeLists.txt | 148 +- common/CMakeLists.txt | 43 +- common/include/common/common.h | 7 +- common/include/common/scopyconfig.h | 9 +- common/src/scopyconfig.cpp | 82 +- core/CMakeLists.txt | 80 +- core/include/core/application_restarter.h | 3 +- core/include/core/cmdlinehandler.h | 11 +- core/include/core/detachedtoolwindow.h | 10 +- core/include/core/detachedtoolwindowmanager.h | 16 +- core/include/core/device.h | 19 +- core/include/core/devicebrowser.h | 19 +- core/include/core/devicefactory.h | 12 +- core/include/core/deviceicon.h | 16 +- core/include/core/deviceiconimpl.h | 16 +- core/include/core/deviceimpl.h | 24 +- core/include/core/deviceloader.h | 9 +- core/include/core/devicemanager.h | 29 +- core/include/core/emuwidget.h | 9 +- core/include/core/iiodeviceimpl.h | 6 +- core/include/core/iiotabwidget.h | 12 +- core/include/core/infopagestack.h | 16 +- core/include/core/license_overlay.h | 13 +- core/include/core/logging_categories.h | 8 +- core/include/core/pluginenablewidget.h | 11 +- core/include/core/pluginfilter.h | 12 +- core/include/core/pluginmanager.h | 18 +- core/include/core/pluginrepository.h | 9 +- core/include/core/scanbuttoncontroller.h | 11 +- .../include/core/scannediiocontextcollector.h | 13 +- core/include/core/scopyaboutpage.h | 9 +- core/include/core/scopyhomeaddpage.h | 14 +- core/include/core/scopyhomeinfopage.h | 10 +- core/include/core/scopyhomepage.h | 13 +- core/include/core/scopymainwindow.h | 33 +- core/include/core/scopymainwindow_api.h | 5 +- core/include/core/scopypreferencespage.h | 8 +- core/include/core/toolbrowser.h | 10 +- core/include/core/toolmanager.h | 27 +- core/include/core/toolmenu.h | 13 +- core/include/core/toolmenuitem.h | 4 +- core/include/core/toolstack.h | 5 +- core/include/core/translationsrepository.h | 7 +- core/include/core/versioncheckoverlay.h | 12 +- core/src/application_restarter.cpp | 23 +- core/src/cmdlinehandler.cpp | 36 +- core/src/detachedtoolwindow.cpp | 42 +- core/src/detachedtoolwindowmanager.cpp | 18 +- core/src/devicebrowser.cpp | 96 +- core/src/devicefactory.cpp | 4 +- core/src/deviceiconimpl.cpp | 16 +- core/src/deviceimpl.cpp | 214 +- core/src/deviceloader.cpp | 32 +- core/src/devicemanager.cpp | 134 +- core/src/emuwidget.cpp | 61 +- core/src/iiodeviceimpl.cpp | 13 +- core/src/iiotabwidget.cpp | 93 +- core/src/infopagestack.cpp | 46 +- core/src/license_overlay.cpp | 29 +- core/src/pluginenablewidget.cpp | 15 +- core/src/pluginfilter.cpp | 19 +- core/src/pluginmanager.cpp | 91 +- core/src/pluginrepository.cpp | 31 +- core/src/scanbuttoncontroller.cpp | 17 +- core/src/scannediiocontextcollector.cpp | 37 +- core/src/scopyaboutpage.cpp | 41 +- core/src/scopyhomeaddpage.cpp | 55 +- core/src/scopyhomeinfopage.cpp | 25 +- core/src/scopyhomepage.cpp | 57 +- core/src/scopymainwindow.cpp | 279 +- core/src/scopymainwindow_api.cpp | 54 +- core/src/scopypreferencespage.cpp | 150 +- core/src/toolbrowser.cpp | 51 +- core/src/toolmanager.cpp | 125 +- core/src/toolmenu.cpp | 108 +- core/src/toolmenuitem.cpp | 67 +- core/src/toolstack.cpp | 15 +- core/src/translationsrepository.cpp | 40 +- core/src/versioncheckoverlay.cpp | 20 +- core/test/CMakeLists.txt | 29 +- core/test/tst_pluginmanager.cpp | 196 +- core/test/tst_pluginrepository.cpp | 11 +- core/test/tst_translationsrepository.cpp | 5 +- gr-util/CMakeLists.txt | 70 +- gr-util/include/gr-util/grdeviceaddon.h | 21 +- .../include/gr-util/griiocomplexchannelsrc.h | 15 +- gr-util/include/gr-util/griiodevicesource.h | 45 +- .../include/gr-util/griiofloatchannelsrc.h | 12 +- gr-util/include/gr-util/grproxyblock.h | 8 +- gr-util/include/gr-util/grscaleoffsetproc.h | 9 +- gr-util/include/gr-util/grsignalpath.h | 14 +- gr-util/include/gr-util/grsignalsrc.h | 8 +- gr-util/include/gr-util/grtimechanneladdon.h | 49 +- gr-util/include/gr-util/grtimeplotaddon.h | 30 +- .../include/gr-util/grtimeplotaddonsettings.h | 32 +- gr-util/include/gr-util/grtopblock.h | 18 +- gr-util/include/gr-util/measure.h | 37 +- .../include/gr-util/measurementcontroller.h | 36 +- gr-util/include/gr-util/time_sink_f.h | 15 +- gr-util/include/gr-util/time_sink_f_impl.h | 15 +- gr-util/include/gr-util/tooladdon.h | 15 +- gr-util/src/grdeviceaddon.cpp | 43 +- gr-util/src/griiocomplexchannelsrc.cpp | 30 +- gr-util/src/griiodevicesource.cpp | 131 +- gr-util/src/griiofloatchannelsrc.cpp | 43 +- gr-util/src/grproxyblock.cpp | 41 +- gr-util/src/grscaleoffsetproc.cpp | 26 +- gr-util/src/grsignalpath.cpp | 59 +- gr-util/src/grsignalsrc.cpp | 36 +- gr-util/src/grtimechanneladdon.cpp | 268 +- gr-util/src/grtimeplotaddon.cpp | 283 +- gr-util/src/grtimeplotaddonsettings.cpp | 203 +- gr-util/src/grtopblock.cpp | 64 +- gr-util/src/measure.cpp | 840 +++--- gr-util/src/measurementcontroller.cpp | 87 +- gr-util/src/time_sink_f_impl.cc | 154 +- gr-util/test/CMakeLists.txt | 5 +- gr-util/test/tst_grblocks.cpp | 447 +-- gui/CMakeLists.txt | 128 +- gui/gr-gui/CMakeLists.txt | 84 +- .../include/gr-gui/drop_untill_tag_arives.h | 18 +- gui/gr-gui/include/gr-gui/histogram_sink_f.h | 118 +- .../include/gr-gui/histogram_sink_f_impl.h | 67 +- gui/gr-gui/include/gr-gui/math.hpp | 60 +- gui/gr-gui/include/gr-gui/scope_sink_f.h | 45 +- gui/gr-gui/include/gr-gui/scope_sink_f_impl.h | 99 +- gui/gr-gui/include/gr-gui/waterfall_sink.h | 61 +- .../include/gr-gui/waterfall_sink_impl.h | 37 +- gui/gr-gui/include/gr-gui/xy_sink_c.h | 35 +- gui/gr-gui/include/gr-gui/xy_sink_c_impl.h | 63 +- gui/gr-gui/src/drop_untill_tag_arives.cpp | 64 +- gui/gr-gui/src/histogram_sink_f_impl.cc | 314 +- gui/gr-gui/src/math.cpp | 65 +- gui/gr-gui/src/scope_sink_f_impl.cc | 213 +- gui/gr-gui/src/waterfall_sink_impl.cc | 180 +- gui/gr-gui/src/xy_sink_c_impl.cc | 342 +-- gui/gr-gui/test/CMakeLists.txt | 18 +- gui/include/gui/BasicPlot.h | 16 +- gui/include/gui/ComboBoxLineEdit.h | 2 +- gui/include/gui/ConstellationDisplayPlot.h | 57 +- gui/include/gui/DisplayPlot.h | 1041 ++++--- gui/include/gui/FftDisplayPlot.h | 489 ++-- gui/include/gui/HistogramDisplayPlot.h | 140 +- gui/include/gui/TimeDomainDisplayPlot.h | 286 +- gui/include/gui/WaterfallDisplayPlot.h | 54 +- gui/include/gui/animationmanager.h | 18 +- gui/include/gui/animationpushbutton.h | 8 +- gui/include/gui/autoScaler.hpp | 64 +- gui/include/gui/average.h | 40 +- gui/include/gui/basemenu.h | 9 +- gui/include/gui/basemenuitem.h | 8 +- gui/include/gui/buffer_previewer.hpp | 18 +- gui/include/gui/channel_manager.hpp | 46 +- gui/include/gui/channel_widget.hpp | 30 +- gui/include/gui/checkbox_delegate.h | 29 +- gui/include/gui/completion_circle.h | 19 +- gui/include/gui/cursor.h | 16 +- gui/include/gui/cursor_readouts.h | 158 +- gui/include/gui/cursorcontroller.h | 4 +- gui/include/gui/customPushButton.h | 33 +- gui/include/gui/customScale.hpp | 8 +- gui/include/gui/customSwitch.h | 60 +- gui/include/gui/custom_menu_button.hpp | 16 +- gui/include/gui/customanimation.h | 13 +- gui/include/gui/customplotpositionbutton.h | 13 +- gui/include/gui/customqwtscaledraw.hpp | 10 +- gui/include/gui/db_click_buttons.hpp | 9 +- gui/include/gui/dbgraph.hpp | 41 +- gui/include/gui/dropdown_switch_list.h | 74 +- gui/include/gui/dynamicWidget.h | 8 +- gui/include/gui/extendingplotzoomer.h | 12 +- gui/include/gui/filemanager.h | 34 +- gui/include/gui/flexgridlayout.hpp | 15 +- gui/include/gui/generic_menu.hpp | 16 +- gui/include/gui/genericlogicplotcurve.h | 21 +- gui/include/gui/graticule.h | 12 +- gui/include/gui/handles_area.hpp | 19 +- gui/include/gui/handlesareaextension.h | 13 +- gui/include/gui/hcursor.h | 15 +- gui/include/gui/homepage_controls.h | 8 +- gui/include/gui/infopage.h | 15 +- gui/include/gui/infopagekeyvaluewidget.h | 12 +- gui/include/gui/instrumentnotes.h | 5 +- gui/include/gui/lcdNumber.hpp | 38 +- gui/include/gui/limitedplotzoomer.h | 9 +- gui/include/gui/linked_button.hpp | 7 +- gui/include/gui/logicdatacurve.h | 16 +- gui/include/gui/m2kmeasure.h | 327 ++- gui/include/gui/m2kmeasurement_gui.h | 35 +- gui/include/gui/mapstackedwidget.h | 14 +- gui/include/gui/marker_controller.h | 18 +- gui/include/gui/marker_table.hpp | 13 +- gui/include/gui/menu_anim.hpp | 118 +- gui/include/gui/menu_header.hpp | 14 +- gui/include/gui/mousewheelwidgetguard.h | 5 +- gui/include/gui/movingaverage.h | 4 +- gui/include/gui/nyquistGraph.hpp | 133 +- gui/include/gui/nyquistplotzoomer.h | 4 +- gui/include/gui/osc_adjuster.hpp | 73 +- gui/include/gui/osc_custom_scroll.h | 11 +- gui/include/gui/osc_export_settings.h | 15 +- gui/include/gui/osc_import_settings.h | 8 +- gui/include/gui/osc_scale_engine.h | 29 +- gui/include/gui/osc_scale_zoomer.h | 31 +- gui/include/gui/oscilloscope_plot.hpp | 469 +-- gui/include/gui/plot_line_handle.h | 55 +- gui/include/gui/plot_utils.hpp | 171 +- gui/include/gui/plotaxis.h | 17 +- gui/include/gui/plotaxishandle.h | 12 +- gui/include/gui/plotchannel.h | 20 +- gui/include/gui/plotcursors.h | 18 +- gui/include/gui/plotpickerwrapper.h | 14 +- gui/include/gui/plotwidget.h | 42 +- gui/include/gui/printableplot.h | 10 +- gui/include/gui/qtgui_types.h | 192 +- gui/include/gui/qwt_utils.h | 37 +- gui/include/gui/runsinglewidget.h | 9 +- gui/include/gui/semiexclusivebuttongroup.h | 5 +- gui/include/gui/settings_pair_widget.hpp | 12 +- gui/include/gui/sismograph.hpp | 155 +- gui/include/gui/smallOnOffSwitch.h | 72 +- gui/include/gui/smoothcurvefitter.h | 13 +- gui/include/gui/spectrumUpdateEvents.h | 346 +-- gui/include/gui/spectrum_marker.hpp | 18 +- gui/include/gui/spinbox_a.hpp | 65 +- gui/include/gui/startstoprangewidget.h | 14 +- gui/include/gui/stylehelper.h | 49 +- gui/include/gui/subsection_separator.hpp | 20 +- gui/include/gui/symbol.h | 59 +- gui/include/gui/symbol_controller.h | 7 +- gui/include/gui/tintedoverlay.h | 19 +- gui/include/gui/tool_view.hpp | 102 +- gui/include/gui/tool_view_builder.hpp | 9 +- gui/include/gui/tooltemplate.h | 13 +- gui/include/gui/trigger_mode.h | 22 +- gui/include/gui/tutorialbuilder.h | 42 +- gui/include/gui/tutorialchapter.h | 27 +- gui/include/gui/tutorialoverlay.h | 32 +- gui/include/gui/utils.h | 57 +- gui/include/gui/vcursor.h | 18 +- gui/include/gui/waterfallGlobalData.h | 72 +- gui/include/gui/widgets/cursorsettings.h | 5 +- gui/include/gui/widgets/hoverwidget.h | 22 +- gui/include/gui/widgets/measurementlabel.h | 26 +- gui/include/gui/widgets/measurementpanel.h | 48 +- gui/include/gui/widgets/measurementselector.h | 22 +- gui/include/gui/widgets/measurementsettings.h | 17 +- gui/include/gui/widgets/menubigswitch.h | 12 +- gui/include/gui/widgets/menucollapsesection.h | 30 +- gui/include/gui/widgets/menucombo.h | 17 +- gui/include/gui/widgets/menucontrolbutton.h | 37 +- gui/include/gui/widgets/menuheader.h | 10 +- gui/include/gui/widgets/menulineedit.h | 12 +- gui/include/gui/widgets/menuonoffswitch.h | 14 +- gui/include/gui/widgets/menusectionwidget.h | 19 +- .../gui/widgets/pagenavigationwidget.h | 8 +- gui/include/gui/widgets/plotcursorreadouts.h | 13 +- gui/include/gui/widgets/plotinfo.h | 51 +- gui/include/gui/widgets/popupwidget.h | 25 +- gui/include/gui/widgets/toolbuttons.h | 33 +- .../gui/widgets/verticalchannelmanager.h | 10 +- gui/include/gui/x_axis_scale_zoomer.h | 9 +- gui/res/stylesheets/templates/values.h | 4 +- gui/sigrok-gui/CMakeLists.txt | 73 +- .../include/sigrok-gui/annotation.h | 38 +- .../include/sigrok-gui/annotationcurve.h | 137 +- .../include/sigrok-gui/annotationdecoder.h | 89 +- .../include/sigrok-gui/binding/binding.hpp | 24 +- .../include/sigrok-gui/binding/decoder.hpp | 26 +- gui/sigrok-gui/include/sigrok-gui/decoder.h | 84 +- .../include/sigrok-gui/prop/bool.hpp | 7 +- .../include/sigrok-gui/prop/double.hpp | 23 +- .../include/sigrok-gui/prop/enum.hpp | 21 +- .../include/sigrok-gui/prop/int.hpp | 23 +- .../include/sigrok-gui/prop/property.hpp | 22 +- .../include/sigrok-gui/prop/string.hpp | 9 +- gui/sigrok-gui/include/sigrok-gui/row.h | 30 +- gui/sigrok-gui/include/sigrok-gui/rowdata.h | 59 +- gui/sigrok-gui/src/annotation.cpp | 62 +- gui/sigrok-gui/src/annotationcurve.cpp | 1202 ++++---- gui/sigrok-gui/src/annotationdecoder.cpp | 766 ++--- gui/sigrok-gui/src/binding/binding.cpp | 37 +- gui/sigrok-gui/src/binding/decoder.cpp | 119 +- gui/sigrok-gui/src/decoder.cpp | 170 +- gui/sigrok-gui/src/prop/bool.cpp | 49 +- gui/sigrok-gui/src/prop/double.cpp | 66 +- gui/sigrok-gui/src/prop/enum.cpp | 133 +- gui/sigrok-gui/src/prop/int.cpp | 106 +- gui/sigrok-gui/src/prop/property.cpp | 43 +- gui/sigrok-gui/src/prop/string.cpp | 47 +- gui/sigrok-gui/src/row.cpp | 61 +- gui/sigrok-gui/src/rowdata.cpp | 106 +- gui/sigrok-gui/test/CMakeLists.txt | 18 +- gui/src/BasicPlot.cpp | 129 +- gui/src/ComboBoxLineEdit.cpp | 29 +- gui/src/ConstellationDisplayPlot.cc | 333 +-- gui/src/DisplayPlot.cc | 1554 ++++------ gui/src/FftDisplayPlot.cc | 763 ++--- gui/src/HistogramDisplayPlot.cc | 991 +++---- gui/src/TimeDomainDisplayPlot.cc | 1099 ++++--- gui/src/WaterfallDisplayPlot.cc | 303 +- gui/src/animationmanager.cpp | 11 +- gui/src/animationpushbutton.cpp | 18 +- gui/src/autoScaler.cpp | 47 +- gui/src/average.cpp | 279 +- gui/src/basemenu.cpp | 70 +- gui/src/basemenuitem.cpp | 126 +- gui/src/buffer_previewer.cpp | 229 +- gui/src/channel_manager.cpp | 165 +- gui/src/channel_widget.cpp | 237 +- gui/src/checkbox_delegate.cpp | 27 +- gui/src/completion_circle.cpp | 113 +- gui/src/cursor.cpp | 43 +- gui/src/cursor_readouts.cpp | 379 ++- gui/src/cursorcontroller.cpp | 17 +- gui/src/customPushButton.cpp | 19 +- gui/src/customScale.cpp | 58 +- gui/src/customSwitch.cpp | 76 +- gui/src/custom_menu_button.cpp | 22 +- gui/src/customanimation.cpp | 24 +- gui/src/customplotpositionbutton.cpp | 51 +- gui/src/customqwtscaledraw.cpp | 14 +- gui/src/db_click_buttons.cpp | 90 +- gui/src/dbgraph.cpp | 253 +- gui/src/dropdown_switch_list.cpp | 89 +- gui/src/dynamicWidget.cpp | 8 +- gui/src/extendingplotzoomer.cpp | 106 +- gui/src/filemanager.cpp | 274 +- gui/src/flexgridlayout.cpp | 177 +- gui/src/generic_menu.cpp | 34 +- gui/src/genericlogicplotcurve.cpp | 134 +- gui/src/graticule.cpp | 85 +- gui/src/handles_area.cpp | 100 +- gui/src/handlesareaextension.cpp | 250 +- gui/src/hcursor.cpp | 61 +- gui/src/homepage_controls.cpp | 34 +- gui/src/infopage.cpp | 40 +- gui/src/infopagekeyvaluewidget.cpp | 12 +- gui/src/instrumentnotes.cpp | 25 +- gui/src/lcdNumber.cpp | 16 +- gui/src/limitedplotzoomer.cpp | 31 +- gui/src/linked_button.cpp | 15 +- gui/src/logicdatacurve.cpp | 319 +- gui/src/m2kmeasure.cpp | 1520 +++++----- gui/src/m2kmeasurement_gui.cpp | 186 +- gui/src/mapstackedwidget.cpp | 41 +- gui/src/marker_controller.cpp | 92 +- gui/src/marker_table.cpp | 50 +- gui/src/menu_anim.cpp | 80 +- gui/src/menu_header.cpp | 16 +- gui/src/mousewheelwidgetguard.cpp | 31 +- gui/src/movingaverage.cpp | 32 +- gui/src/nyquistGraph.cpp | 150 +- gui/src/nyquistplotzoomer.cpp | 17 +- gui/src/osc_adjuster.cpp | 126 +- gui/src/osc_custom_scroll.cpp | 51 +- gui/src/osc_export_settings.cpp | 112 +- gui/src/osc_import_settings.cpp | 14 +- gui/src/osc_scale_engine.cpp | 215 +- gui/src/osc_scale_zoomer.cpp | 31 +- gui/src/oscilloscope_plot.cpp | 1145 ++++---- gui/src/plot_line_handle.cpp | 340 +-- gui/src/plot_utils.cpp | 171 +- gui/src/plotaxis.cpp | 128 +- gui/src/plotaxishandle.cpp | 64 +- gui/src/plotchannel.cpp | 102 +- gui/src/plotcursors.cpp | 85 +- gui/src/plotpickerwrapper.cpp | 13 +- gui/src/plotwidget.cpp | 245 +- gui/src/printableplot.cpp | 46 +- gui/src/qwt_utils.cpp | 69 +- gui/src/runsinglewidget.cpp | 74 +- gui/src/settings_pair_widget.cpp | 12 +- gui/src/sismograph.cpp | 119 +- gui/src/smallOnOffSwitch.cpp | 118 +- gui/src/smoothcurvefitter.cpp | 18 +- gui/src/spectrumUpdateEvents.cc | 629 ++-- gui/src/spectrum_marker.cpp | 73 +- gui/src/spinbox_a.cpp | 716 ++--- gui/src/startstoprangewidget.cpp | 107 +- gui/src/stylehelper.cpp | 444 +-- gui/src/subsection_separator.cpp | 23 +- gui/src/symbol.cpp | 269 +- gui/src/symbol_controller.cpp | 174 +- gui/src/tintedoverlay.cpp | 41 +- gui/src/tool_view.cpp | 239 +- gui/src/tool_view_builder.cpp | 24 +- gui/src/tooltemplate.cpp | 136 +- gui/src/tutorialbuilder.cpp | 155 +- gui/src/tutorialchapter.cpp | 80 +- gui/src/tutorialoverlay.cpp | 85 +- gui/src/utils.cpp | 87 +- gui/src/vcursor.cpp | 59 +- gui/src/waterfallGlobalData.cc | 129 +- gui/src/widgets/cursorsettings.cpp | 35 +- gui/src/widgets/hoverwidget.cpp | 131 +- gui/src/widgets/measurementlabel.cpp | 124 +- gui/src/widgets/measurementpanel.cpp | 65 +- gui/src/widgets/measurementselector.cpp | 56 +- gui/src/widgets/measurementsettings.cpp | 53 +- gui/src/widgets/menubigswitch.cpp | 11 +- gui/src/widgets/menucollapsesection.cpp | 41 +- gui/src/widgets/menucombo.cpp | 23 +- gui/src/widgets/menucontrolbutton.cpp | 88 +- gui/src/widgets/menuheader.cpp | 13 +- gui/src/widgets/menulineedit.cpp | 11 +- gui/src/widgets/menuonoffswitch.cpp | 19 +- gui/src/widgets/menusectionwidget.cpp | 18 +- gui/src/widgets/pagenavigationwidget.cpp | 33 +- gui/src/widgets/plotcursorreadouts.cpp | 76 +- gui/src/widgets/plotinfo.cpp | 93 +- gui/src/widgets/popupwidget.cpp | 55 +- gui/src/widgets/semiexclusivebuttongroup.cpp | 22 +- gui/src/widgets/toolbuttons.cpp | 73 +- gui/src/widgets/verticalchannelmanager.cpp | 20 +- gui/src/x_axis_scale_zoomer.cpp | 17 +- gui/test/CMakeLists.txt | 19 +- iioutil/CMakeLists.txt | 61 +- iioutil/include/iioutil/command.h | 28 +- iioutil/include/iioutil/commandqueue.h | 13 +- .../include/iioutil/commandqueueprovider.h | 22 +- iioutil/include/iioutil/contextprovider.h | 25 +- iioutil/include/iioutil/cyclicaltask.h | 17 +- .../iioutil/iiocommand/iiobuffercancel.h | 15 +- .../iioutil/iiocommand/iiobufferdestroy.h | 17 +- .../iioutil/iiocommand/iiobufferpush.h | 16 +- .../iioutil/iiocommand/iiobufferrefill.h | 15 +- .../iiocommand/iiochannelattributeread.h | 35 +- .../iiocommand/iiochannelattributewrite.h | 16 +- .../iioutil/iiocommand/iiochannelenable.h | 18 +- .../iiocommand/iiodeviceattributeread.h | 29 +- .../iiocommand/iiodeviceattributewrite.h | 20 +- .../iiocommand/iiodevicecreatebuffer.h | 23 +- .../iioutil/iiocommand/iiodevicegettrigger.h | 19 +- .../iioutil/iiocommand/iiodevicesettrigger.h | 16 +- .../iioutil/iiocommand/iioregisterread.h | 35 +- iioutil/include/iioutil/iiopingtask.h | 13 +- iioutil/include/iioutil/iioscantask.h | 9 +- iioutil/src/commandqueue.cpp | 50 +- iioutil/src/commandqueueprovider.cpp | 29 +- iioutil/src/contextprovider.cpp | 42 +- iioutil/src/cyclicaltask.cpp | 26 +- iioutil/src/iiopingtask.cpp | 16 +- iioutil/src/iioscantask.cpp | 49 +- iioutil/test/CMakeLists.txt | 5 +- iioutil/test/tst_iiocommandqueue.cpp | 259 +- main.cpp | 69 +- pluginbase/CMakeLists.txt | 58 +- pluginbase/include/pluginbase/apiobject.h | 50 +- pluginbase/include/pluginbase/messagebroker.h | 10 +- pluginbase/include/pluginbase/plugin.h | 47 +- pluginbase/include/pluginbase/pluginbase.h | 82 +- pluginbase/include/pluginbase/preferences.h | 13 +- .../include/pluginbase/preferenceshelper.h | 19 +- .../include/pluginbase/resourcemanager.h | 14 +- pluginbase/include/pluginbase/scopyjs.h | 27 +- pluginbase/include/pluginbase/toolmenuentry.h | 59 +- .../include/pluginbase/versionchecker.h | 24 +- pluginbase/src/apiobject.cpp | 129 +- pluginbase/src/jsfileio.cpp | 25 +- pluginbase/src/jsfileio.h | 10 +- pluginbase/src/messagebroker.cpp | 35 +- pluginbase/src/pluginbase.cpp | 157 +- pluginbase/src/preferences.cpp | 58 +- pluginbase/src/preferenceshelper.cpp | 49 +- pluginbase/src/resourcemanager.cpp | 30 +- pluginbase/src/scopyjs.cpp | 130 +- pluginbase/src/versionchecker.cpp | 114 +- pluginbase/test/CMakeLists.txt | 5 +- pluginbase/test/tst_preferences.cpp | 14 +- plugins/CMakeLists.txt | 59 +- plugins/adc/CMakeLists.txt | 48 +- plugins/adc/include/adcplugin/adcplugin.h | 131 +- plugins/adc/src/adcinstrument.cpp | 154 +- plugins/adc/src/adcinstrument.h | 20 +- plugins/adc/src/adcplugin.cpp | 128 +- plugins/adc/test/CMakeLists.txt | 5 +- plugins/adc/test/tst_pluginloader.cpp | 51 +- plugins/bareminimumplugin/CMakeLists.txt | 41 +- .../include/bareminimumplugin/bareminimum.h | 12 +- plugins/bareminimumplugin/src/bareminimum.cpp | 23 +- plugins/bareminimumplugin/test/CMakeLists.txt | 5 +- .../test/tst_pluginloader.cpp | 51 +- plugins/datalogger/CMakeLists.txt | 65 +- .../dataloggerplugin/dataloggerplugin.h | 15 +- plugins/datalogger/src/datalogger.cpp | 298 +- plugins/datalogger/src/datalogger.hpp | 64 +- plugins/datalogger/src/datalogger_api.cpp | 53 +- plugins/datalogger/src/datalogger_api.h | 36 +- .../datalogger/src/dataloggercontroller.cpp | 89 +- .../datalogger/src/dataloggercontroller.hpp | 10 +- plugins/datalogger/src/dataloggermodel.cpp | 96 +- plugins/datalogger/src/dataloggermodel.h | 25 +- plugins/datalogger/src/dataloggerplugin.cpp | 68 +- .../datalogger/src/dataloggerreaderthread.cpp | 47 +- .../datalogger/src/dataloggerreaderthread.hpp | 22 +- .../src/gui/channelmonitorcomponent.cpp | 108 +- .../src/gui/channelmonitorcomponent.hpp | 14 +- .../src/gui/dataloggergenericmenu.cpp | 101 +- .../src/gui/dataloggergenericmenu.hpp | 13 +- plugins/datalogger/src/gui/dataloggerview.cpp | 119 +- plugins/datalogger/src/gui/dataloggerview.hpp | 20 +- plugins/datalogger/test/CMakeLists.txt | 5 +- plugins/datalogger/test/tst_pluginloader.cpp | 51 +- plugins/debugger/CMakeLists.txt | 51 +- .../include/debuggerplugin/debuggerplugin.h | 9 +- plugins/debugger/src/bitfieldwidget.cpp | 61 +- plugins/debugger/src/bitfieldwidget.h | 10 +- plugins/debugger/src/debuggercontroller.cpp | 126 +- plugins/debugger/src/debuggercontroller.h | 30 +- plugins/debugger/src/debuggerinstrument.cpp | 119 +- plugins/debugger/src/debuggerinstrument.h | 13 +- plugins/debugger/src/debuggerplugin.cpp | 28 +- plugins/debugger/src/registerwidget.cpp | 119 +- plugins/debugger/src/registerwidget.h | 19 +- plugins/debugger/src/regmapparser.cpp | 94 +- plugins/debugger/src/regmapparser.h | 21 +- plugins/debugger/test/CMakeLists.txt | 4 +- plugins/debugger/test/tst_pluginloader.cpp | 60 +- plugins/guitestplugin/CMakeLists.txt | 45 +- .../include/guitestplugin/guitestplugin.h | 11 +- plugins/guitestplugin/src/guitestplugin.cpp | 22 +- plugins/guitestplugin/test/CMakeLists.txt | 5 +- .../guitestplugin/test/tst_pluginloader.cpp | 51 +- plugins/m2k/CMakeLists.txt | 135 +- plugins/m2k/include/m2kplugin/m2kcontroller.h | 15 +- .../m2k/include/m2kplugin/m2kidentifytask.h | 6 +- plugins/m2k/include/m2kplugin/m2kplugin.h | 27 +- .../m2kplugin/m2kreadtemperaturetask.h | 7 +- plugins/m2k/src/m2kcontroller.cpp | 48 +- plugins/m2k/src/m2kidentifytask.cpp | 22 +- plugins/m2k/src/m2kplugin.cpp | 377 +-- plugins/m2k/src/m2kreadtemperaturetask.cpp | 22 +- plugins/m2k/src/old/adc_sample_conv.cpp | 48 +- plugins/m2k/src/old/adc_sample_conv.hpp | 33 +- plugins/m2k/src/old/calibration.cpp | 95 +- plugins/m2k/src/old/calibration.hpp | 26 +- plugins/m2k/src/old/calibration_api.cpp | 48 +- plugins/m2k/src/old/calibration_api.hpp | 6 +- .../m2k/src/old/cancel_dc_offset_block.cpp | 40 +- plugins/m2k/src/old/cancel_dc_offset_block.h | 19 +- plugins/m2k/src/old/detachdragzone.cpp | 40 +- plugins/m2k/src/old/detachdragzone.h | 8 +- .../m2k/src/old/digitalchannel_manager.cpp | 112 +- .../m2k/src/old/digitalchannel_manager.hpp | 19 +- plugins/m2k/src/old/digitalio.cpp | 216 +- plugins/m2k/src/old/digitalio.hpp | 41 +- plugins/m2k/src/old/digitalio_api.cpp | 56 +- plugins/m2k/src/old/digitalio_api.hpp | 15 +- plugins/m2k/src/old/dmm.cpp | 373 ++- plugins/m2k/src/old/dmm.hpp | 164 +- plugins/m2k/src/old/dmm_api.cpp | 148 +- plugins/m2k/src/old/dmm_api.hpp | 55 +- plugins/m2k/src/old/externalloadlineedit.cpp | 24 +- plugins/m2k/src/old/externalloadlineedit.h | 4 +- plugins/m2k/src/old/fft_block.cpp | 43 +- plugins/m2k/src/old/fft_block.hpp | 27 +- plugins/m2k/src/old/filter.cpp | 85 +- plugins/m2k/src/old/filter.hpp | 79 +- .../src/old/frequency_compensation_filter.h | 3 +- .../old/frequency_compensation_filter_impl.cc | 87 +- .../old/frequency_compensation_filter_impl.h | 13 +- plugins/m2k/src/old/hardware_trigger.cpp | 236 +- plugins/m2k/src/old/hardware_trigger.hpp | 46 +- plugins/m2k/src/old/iio_manager.cpp | 173 +- plugins/m2k/src/old/iio_manager.hpp | 70 +- plugins/m2k/src/old/logic_analyzer_sink.h | 4 +- .../m2k/src/old/logic_analyzer_sink_impl.cpp | 47 +- .../m2k/src/old/logic_analyzer_sink_impl.h | 6 +- .../src/old/logicanalyzer/decoder_table.cpp | 121 +- .../src/old/logicanalyzer/decoder_table.hpp | 51 +- .../old/logicanalyzer/decoder_table_item.cpp | 101 +- .../old/logicanalyzer/decoder_table_item.hpp | 60 +- .../old/logicanalyzer/decoder_table_model.cpp | 233 +- .../old/logicanalyzer/decoder_table_model.hpp | 108 +- .../src/old/logicanalyzer/logic_analyzer.cpp | 1499 +++++----- .../src/old/logicanalyzer/logic_analyzer.h | 59 +- .../old/logicanalyzer/logicanalyzer_api.cpp | 236 +- .../src/old/logicanalyzer/logicanalyzer_api.h | 23 +- .../src/old/logicanalyzer/logicgroupitem.cpp | 31 +- .../src/old/logicanalyzer/logicgroupitem.h | 3 +- .../m2k/src/old/m2kpluginExceptionHandler.h | 6 +- plugins/m2k/src/old/m2ktool.cpp | 77 +- plugins/m2k/src/old/m2ktool.hpp | 35 +- .../m2k/src/old/manual_calibration_api.cpp | 92 +- .../m2k/src/old/manual_calibration_api.hpp | 13 +- plugins/m2k/src/old/manualcalibration.cpp | 262 +- plugins/m2k/src/old/manualcalibration.h | 44 +- plugins/m2k/src/old/measure_settings.cpp | 617 ++-- plugins/m2k/src/old/measure_settings.h | 54 +- plugins/m2k/src/old/mixed_signal_sink.h | 11 +- .../m2k/src/old/mixed_signal_sink_impl.cpp | 94 +- plugins/m2k/src/old/mixed_signal_sink_impl.h | 13 +- plugins/m2k/src/old/network_analyzer.cpp | 902 +++--- plugins/m2k/src/old/network_analyzer.hpp | 127 +- plugins/m2k/src/old/network_analyzer_api.cpp | 192 +- plugins/m2k/src/old/network_analyzer_api.hpp | 29 +- .../src/old/networkanalyzerbufferviewer.cpp | 89 +- .../m2k/src/old/networkanalyzerbufferviewer.h | 21 +- plugins/m2k/src/old/osc_adc.cpp | 298 +- plugins/m2k/src/old/osc_adc.h | 54 +- plugins/m2k/src/old/osc_capture_params.cpp | 119 +- plugins/m2k/src/old/osc_capture_params.hpp | 7 +- plugins/m2k/src/old/oscilloscope.cpp | 2579 +++++++---------- plugins/m2k/src/old/oscilloscope.hpp | 877 +++--- plugins/m2k/src/old/oscilloscope_api.cpp | 589 ++-- plugins/m2k/src/old/oscilloscope_api.hpp | 229 +- .../patterngenerator/pattern_generator.cpp | 404 ++- .../old/patterngenerator/pattern_generator.h | 37 +- .../pattern_generator_api.cpp | 79 +- .../patterngenerator/pattern_generator_api.h | 17 +- .../patterngenerator/patterns/patterns.cpp | 2274 ++++++--------- .../patterngenerator/patterns/patterns.hpp | 226 +- plugins/m2k/src/old/power_controller.cpp | 138 +- plugins/m2k/src/old/power_controller.hpp | 119 +- plugins/m2k/src/old/power_controller_api.cpp | 70 +- plugins/m2k/src/old/power_controller_api.hpp | 12 +- .../m2k/src/old/saverestoretoolsettings.cpp | 6 +- plugins/m2k/src/old/saverestoretoolsettings.h | 3 +- plugins/m2k/src/old/signal_generator.cpp | 1548 +++++----- plugins/m2k/src/old/signal_generator.hpp | 155 +- plugins/m2k/src/old/signal_generator_api.cpp | 528 ++-- plugins/m2k/src/old/signal_generator_api.hpp | 158 +- plugins/m2k/src/old/signal_sample.cpp | 20 +- plugins/m2k/src/old/signal_sample.hpp | 34 +- plugins/m2k/src/old/spectrum_analyzer.cpp | 2108 ++++++-------- plugins/m2k/src/old/spectrum_analyzer.hpp | 125 +- plugins/m2k/src/old/spectrum_analyzer_api.cpp | 307 +- plugins/m2k/src/old/spectrum_analyzer_api.hpp | 58 +- plugins/m2k/src/old/state_updater.cpp | 71 +- plugins/m2k/src/old/state_updater.h | 4 +- plugins/m2k/src/old/statistic_widget.cpp | 96 +- plugins/m2k/src/old/statistic_widget.h | 12 +- .../m2k/src/old/stream_to_vector_overlap.h | 2 +- .../src/old/stream_to_vector_overlap_impl.cc | 41 +- .../src/old/stream_to_vector_overlap_impl.h | 8 +- plugins/m2k/src/old/timeout_block.cpp | 16 +- plugins/m2k/src/old/timeout_block.hpp | 35 +- plugins/m2k/src/old/trigger_settings.cpp | 321 +- plugins/m2k/src/old/trigger_settings.hpp | 255 +- plugins/m2k/test/CMakeLists.txt | 5 +- plugins/m2k/test/tst_pluginloader.cpp | 60 +- plugins/regmap/CMakeLists.txt | 87 +- .../include/regmapplugin/regmapplugin.h | 33 +- plugins/regmap/src/deviceregistermap.cpp | 277 +- plugins/regmap/src/deviceregistermap.hpp | 55 +- plugins/regmap/src/jsonformatedelement.cpp | 54 +- plugins/regmap/src/jsonformatedelement.hpp | 35 +- plugins/regmap/src/logging_categories.cpp | 44 +- plugins/regmap/src/logging_categories.h | 5 +- plugins/regmap/src/qtextspinbox.cpp | 34 +- plugins/regmap/src/qtextspinbox.hpp | 17 +- .../readwrite/fileregisterreadstrategy.cpp | 21 +- .../readwrite/fileregisterreadstrategy.hpp | 12 +- .../readwrite/fileregisterwritestrategy.cpp | 16 +- .../readwrite/fileregisterwritestrategy.hpp | 8 +- .../src/readwrite/iioregisterreadstrategy.cpp | 26 +- .../src/readwrite/iioregisterreadstrategy.hpp | 6 +- .../readwrite/iioregisterwritestrategy.cpp | 27 +- .../readwrite/iioregisterwritestrategy.hpp | 15 +- .../src/readwrite/iregisterreadstrategy.hpp | 5 +- .../src/readwrite/iregisterwritestrategy.hpp | 4 +- .../src/recycerview/irecyclerviewadapter.hpp | 11 +- .../regmap/src/recycerview/recyclerview.cpp | 308 +- .../regmap/src/recycerview/recyclerview.hpp | 68 +- .../src/recycerview/registermaptable.cpp | 140 +- .../src/recycerview/registermaptable.hpp | 34 +- .../bitfield/bitfielddetailedwidget.cpp | 341 ++- .../bitfield/bitfielddetailedwidget.hpp | 49 +- .../bitfielddetailedwidgetfactory.cpp | 19 +- .../bitfielddetailedwidgetfactory.hpp | 5 +- .../src/register/bitfield/bitfieldmodel.cpp | 120 +- .../src/register/bitfield/bitfieldmodel.hpp | 78 +- .../src/register/bitfield/bitfieldoption.cpp | 18 +- .../src/register/bitfield/bitfieldoption.hpp | 10 +- .../bitfield/bitfieldsimplewidget.cpp | 161 +- .../bitfield/bitfieldsimplewidget.hpp | 44 +- .../bitfield/bitfieldsimplewidgetfactory.cpp | 16 +- .../bitfield/bitfieldsimplewidgetfactory.hpp | 5 +- .../src/register/registerdetailedwidget.cpp | 185 +- .../src/register/registerdetailedwidget.hpp | 18 +- plugins/regmap/src/register/registermodel.cpp | 66 +- plugins/regmap/src/register/registermodel.hpp | 16 +- .../src/register/registersimplewidget.cpp | 241 +- .../src/register/registersimplewidget.hpp | 45 +- .../register/registersimplewidgetfactory.cpp | 33 +- .../register/registersimplewidgetfactory.hpp | 5 +- plugins/regmap/src/registercontroller.cpp | 200 +- plugins/regmap/src/registercontroller.hpp | 34 +- plugins/regmap/src/registermapinstrument.cpp | 263 +- plugins/regmap/src/registermapinstrument.hpp | 54 +- .../regmap/src/registermapsettingsmenu.cpp | 281 +- .../regmap/src/registermapsettingsmenu.hpp | 42 +- plugins/regmap/src/registermaptemplate.cpp | 55 +- plugins/regmap/src/registermaptemplate.hpp | 24 +- plugins/regmap/src/registermapvalues.cpp | 83 +- plugins/regmap/src/registermapvalues.hpp | 12 +- plugins/regmap/src/regmapplugin.cpp | 298 +- plugins/regmap/src/regmapstylehelper.cpp | 253 +- plugins/regmap/src/regmapstylehelper.hpp | 63 +- plugins/regmap/src/regreadwrite.cpp | 24 +- plugins/regmap/src/regreadwrite.hpp | 12 +- plugins/regmap/src/search.cpp | 23 +- plugins/regmap/src/search.hpp | 10 +- plugins/regmap/src/searchbarwidget.cpp | 31 +- plugins/regmap/src/searchbarwidget.hpp | 12 +- plugins/regmap/src/tabinfo.cpp | 28 +- plugins/regmap/src/tabinfo.hpp | 19 +- plugins/regmap/src/utils.cpp | 223 +- plugins/regmap/src/utils.hpp | 37 +- plugins/regmap/src/verticalscrollarea.cpp | 16 +- plugins/regmap/src/verticalscrollarea.hpp | 11 +- plugins/regmap/src/xmlfilemanager.cpp | 376 ++- plugins/regmap/src/xmlfilemanager.hpp | 24 +- plugins/regmap/test/CMakeLists.txt | 6 +- plugins/regmap/test/tst_pluginloader.cpp | 52 +- plugins/regmap/test/tst_swiot.cpp | 2 +- plugins/swiot/CMakeLists.txt | 63 +- plugins/swiot/include/swiot/swiotplugin.h | 16 +- .../swiot/src/config/configchannelview.cpp | 86 +- plugins/swiot/src/config/configchannelview.h | 20 +- plugins/swiot/src/config/configcontroller.cpp | 84 +- plugins/swiot/src/config/configcontroller.h | 15 +- plugins/swiot/src/config/configmodel.cpp | 288 +- plugins/swiot/src/config/configmodel.h | 27 +- plugins/swiot/src/config/drawarea.cpp | 38 +- plugins/swiot/src/config/drawarea.h | 15 +- plugins/swiot/src/config/swiotconfig.cpp | 96 +- plugins/swiot/src/config/swiotconfig.h | 60 +- plugins/swiot/src/externalpsreaderthread.cpp | 67 +- plugins/swiot/src/externalpsreaderthread.h | 11 +- .../swiot/src/runtime/ad74413r/ad74413r.cpp | 243 +- plugins/swiot/src/runtime/ad74413r/ad74413r.h | 46 +- .../src/runtime/ad74413r/bufferlogic.cpp | 262 +- .../swiot/src/runtime/ad74413r/bufferlogic.h | 35 +- .../swiot/src/runtime/ad74413r/buffermenu.cpp | 432 ++- .../swiot/src/runtime/ad74413r/buffermenu.h | 109 +- .../runtime/ad74413r/buffermenucontroller.cpp | 41 +- .../runtime/ad74413r/buffermenucontroller.h | 18 +- .../src/runtime/ad74413r/buffermenumodel.cpp | 118 +- .../src/runtime/ad74413r/buffermenumodel.h | 23 +- .../src/runtime/ad74413r/buffermenuview.cpp | 38 +- .../src/runtime/ad74413r/buffermenuview.h | 14 +- .../runtime/ad74413r/bufferplothandler.cpp | 200 +- .../src/runtime/ad74413r/bufferplothandler.h | 22 +- .../src/runtime/ad74413r/channelplotscale.cpp | 42 +- .../src/runtime/ad74413r/channelplotscale.h | 11 +- .../ad74413r/channelplotscalescontroller.cpp | 27 +- .../ad74413r/channelplotscalescontroller.h | 15 +- .../swiot/src/runtime/ad74413r/chnlinfo.cpp | 91 +- plugins/swiot/src/runtime/ad74413r/chnlinfo.h | 15 +- .../src/runtime/ad74413r/chnlinfobuilder.cpp | 7 +- .../src/runtime/ad74413r/chnlinfobuilder.h | 20 +- .../src/runtime/ad74413r/currentchnlinfo.cpp | 12 +- .../src/runtime/ad74413r/currentchnlinfo.h | 8 +- .../runtime/ad74413r/resistancechnlinfo.cpp | 10 +- .../src/runtime/ad74413r/resistancechnlinfo.h | 8 +- .../src/runtime/ad74413r/voltagechnlinfo.cpp | 13 +- .../src/runtime/ad74413r/voltagechnlinfo.h | 8 +- plugins/swiot/src/runtime/faults/faults.cpp | 88 +- plugins/swiot/src/runtime/faults/faults.h | 34 +- .../swiot/src/runtime/faults/faultsdevice.cpp | 154 +- .../swiot/src/runtime/faults/faultsdevice.h | 40 +- .../swiot/src/runtime/faults/faultsgroup.cpp | 120 +- .../swiot/src/runtime/faults/faultsgroup.h | 26 +- .../swiot/src/runtime/faults/faultspage.cpp | 49 +- plugins/swiot/src/runtime/faults/faultspage.h | 28 +- .../swiot/src/runtime/faults/faultwidget.cpp | 91 +- .../swiot/src/runtime/faults/faultwidget.h | 21 +- .../src/runtime/max14906/diocontroller.cpp | 42 +- .../src/runtime/max14906/diocontroller.h | 21 +- .../runtime/max14906/diodigitalchannel.cpp | 59 +- .../src/runtime/max14906/diodigitalchannel.h | 14 +- .../max14906/diodigitalchannelcontroller.cpp | 309 +- .../max14906/diodigitalchannelcontroller.h | 21 +- .../src/runtime/max14906/diosettingstab.cpp | 26 +- .../src/runtime/max14906/diosettingstab.h | 7 +- .../swiot/src/runtime/max14906/max14906.cpp | 194 +- plugins/swiot/src/runtime/max14906/max14906.h | 40 +- plugins/swiot/src/runtime/readerthread.cpp | 240 +- plugins/swiot/src/runtime/readerthread.h | 17 +- plugins/swiot/src/runtime/swiotruntime.cpp | 42 +- plugins/swiot/src/runtime/swiotruntime.h | 13 +- .../swiot/src/swiot_logging_categories.cpp | 1 - plugins/swiot/src/swiot_logging_categories.h | 3 +- plugins/swiot/src/swiotcontroller.cpp | 67 +- plugins/swiot/src/swiotcontroller.h | 15 +- plugins/swiot/src/swiotidentifytask.cpp | 52 +- plugins/swiot/src/swiotidentifytask.h | 6 +- plugins/swiot/src/swiotinfopage.cpp | 12 +- plugins/swiot/src/swiotinfopage.h | 15 +- plugins/swiot/src/swiotpingtask.cpp | 26 +- plugins/swiot/src/swiotpingtask.h | 13 +- plugins/swiot/src/swiotplugin.cpp | 220 +- .../swiot/src/swiotreadtemperaturetask.cpp | 104 +- plugins/swiot/src/swiotreadtemperaturetask.h | 15 +- plugins/swiot/src/swiotswitchctxtask.cpp | 51 +- plugins/swiot/src/swiotswitchctxtask.h | 7 +- plugins/swiot/test/CMakeLists.txt | 6 +- plugins/swiot/test/tst_pluginloader.cpp | 49 +- plugins/swiot/test/tst_swiot.cpp | 3 +- plugins/testplugin/CMakeLists.txt | 46 +- .../include/testplugin/testplugin.h | 29 +- plugins/testplugin/src/testplugin.cpp | 201 +- plugins/testplugin/src/testtool.cpp | 144 +- plugins/testplugin/src/testtool.h | 12 +- plugins/testplugin/test/CMakeLists.txt | 5 +- plugins/testplugin/test/tst_pluginloader.cpp | 51 +- plugins/testplugin2/CMakeLists.txt | 41 +- .../include/testplugin2/testpluginip.h | 14 +- plugins/testplugin2/src/testpluginip.cpp | 58 +- plugins/testplugin2/test/CMakeLists.txt | 5 +- plugins/testplugin2/test/tst_pluginloader.cpp | 47 +- tests/CMakeLists.txt | 1 - tools/format.sh | 1 + 816 files changed, 34819 insertions(+), 42242 deletions(-) diff --git a/.clang-format b/.clang-format index c6f323f680..170147d531 100644 --- a/.clang-format +++ b/.clang-format @@ -101,7 +101,7 @@ PenaltyExcessCharacter: 1000000 PenaltyReturnTypeOnItsOwnLine: 60 PointerAlignment: Right ReflowComments: true -SortIncludes: true +SortIncludes: false SortUsingDeclarations: true SpaceAfterCStyleCast: false SpaceAfterTemplateKeyword: true diff --git a/CMakeLists.txt b/CMakeLists.txt index ef244875f4..1e96b8088f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -23,29 +23,24 @@ include(GNUInstallDirs) find_package(QT NAMES Qt5 REQUIRED COMPONENTS Widgets) find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets LinguistTools) -if (Qt5Widgets_VERSION VERSION_LESS 5.15.2) +if(Qt5Widgets_VERSION VERSION_LESS 5.15.2) message(FATAL_ERROR "Minimum supported Qt 5.15.2") return() else() message(STATUS "Using Qt version: " ${Qt5Widgets_VERSION}) endif() -#message(QtVersion: ${QT_VERSION_MAJOR}:${QT_VERSION_MINOR}) +# message(QtVersion: ${QT_VERSION_MAJOR}:${QT_VERSION_MINOR}) +file(GLOB SRC_LIST *.cpp *.cc) +file(GLOB HEADER_LIST *.h *.hpp) +file(GLOB UI_LIST *.ui) -FILE(GLOB SRC_LIST *.cpp *.cc) -FILE(GLOB HEADER_LIST *.h *.hpp) -FILE(GLOB UI_LIST *.ui) - -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} -) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) include(ScopyAbout) configure_about(./resources/about) -FILE(GLOB SCOPY_RESOURCE_FILES gui/res/resources.qrc resources/aboutpage.qrc) +file(GLOB SCOPY_RESOURCE_FILES gui/res/resources.qrc resources/aboutpage.qrc) find_file(SCOPY_ICON_ICO icon.ico PATHS ${CMAKE_SOURCE_DIR}/gui/res) message(STATUS "SCOPY_RESOURCE_FILES: " ${SCOPY_RESOURCE_FILES}) @@ -59,7 +54,7 @@ endif() qt_add_resources(SCOPY_RESOURCES ${SCOPY_RESOURCE_FILES}) -if (WIN32) +if(WIN32) # Set .exe properties string(REPLACE "." "," SCOPY_FILEVERSION ${PROJECT_VERSION}) set(SCOPY_PRODUCTVERSION_STR ${PROJECT_VERSION}) @@ -71,26 +66,38 @@ endif() find_path( IIO_INCLUDE_DIRS NAMES iio.h - HINTS ${CMAKE_INSTALL_PREFIX}/include /include /usr/include /usr/local/include /opt/local/include - REQUIRED) + HINTS ${CMAKE_INSTALL_PREFIX}/include + /include + /usr/include + /usr/local/include + /opt/local/include + REQUIRED +) find_library( IIO_LIBRARIES NAMES iio libiio - HINTS ${CMAKE_INSTALL_PREFIX}/lib /usr/lib /usr/lib64 /usr/local/lib /usr/local/lib64 /opt/local/lib /opt/local/lib64 - REQUIRED) + HINTS ${CMAKE_INSTALL_PREFIX}/lib + /usr/lib + /usr/lib64 + /usr/local/lib + /usr/local/lib64 + /opt/local/lib + /opt/local/lib64 + REQUIRED +) message("IIO LIBRARIES: " ${IIO_LIBRARIES}) option(ENABLE_TESTING "Enable unit tests" ON) if(ENABLE_TESTING) - message(STATUS "Unit tests enabled") - add_subdirectory(tests) + message(STATUS "Unit tests enabled") + add_subdirectory(tests) endif() option(ENABLE_APPLICATION_BUNDLE "Enable application bundle for OSX" OFF) -if (APPLE) - set(ENABLE_APPLICATION_BUNDLE ON) - include(ScopyMacOS) +if(APPLE) + set(ENABLE_APPLICATION_BUNDLE ON) + include(ScopyMacOS) endif(APPLE) set(SCOPY_DLL_PATH ${CMAKE_INSTALL_LIBDIR}) @@ -110,35 +117,33 @@ add_subdirectory(plugins) set(SCOPY_DEPENDENCIES ${IIO_LIBRARIES}) if(${QT_VERSION_MAJOR} GREATER_EQUAL 6) - qt_add_executable(${PROJECT_NAME} - MANUAL_FINALIZATION - ${PROJECT_SOURCES} - ${SCOPY_RESOURCES} - ${SCOPY_DEPENDENCIES} - ${SCOPY_WIN32_RESOURCES} - ) -# Define target properties for Android with Qt 6 as: -# set_property(TARGET tool_launcher APPEND PROPERTY QT_ANDROID_PACKAGE_SOURCE_DIR -# ${CMAKE_CURRENT_SOURCE_DIR}/android) -# For more information, see https://doc.qt.io/qt-6/qt-add-executable.html#target-creation + qt_add_executable( + ${PROJECT_NAME} + MANUAL_FINALIZATION + ${PROJECT_SOURCES} + ${SCOPY_RESOURCES} + ${SCOPY_DEPENDENCIES} + ${SCOPY_WIN32_RESOURCES} + ) + # Define target properties for Android with Qt 6 as: set_property(TARGET tool_launcher APPEND PROPERTY + # QT_ANDROID_PACKAGE_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/android) For more information, see + # https://doc.qt.io/qt-6/qt-add-executable.html#target-creation else() - if(ANDROID) - add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} - ${SCOPY_RESOURCES} - ${SCOPY_DEPENDENCIES} - ) -# Define properties for Android with Qt 5 after find_package() calls as: -# set(ANDROID_PACKAGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android") - else() - add_executable(${PROJECT_NAME} WIN32 ${OSX_BUNDLE} - ${PROJECT_SOURCES} - ${SCOPY_RESOURCES} - ${SCOPY_DEPENDENCIES} - ${EXTRA_BUNDLE_FILES} - ${SCOPY_WIN32_RESOURCES} - ) - endif() + if(ANDROID) + add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES} ${SCOPY_RESOURCES} ${SCOPY_DEPENDENCIES}) + # Define properties for Android with Qt 5 after find_package() calls as: set(ANDROID_PACKAGE_SOURCE_DIR + # "${CMAKE_CURRENT_SOURCE_DIR}/android") + else() + add_executable( + ${PROJECT_NAME} WIN32 + ${OSX_BUNDLE} + ${PROJECT_SOURCES} + ${SCOPY_RESOURCES} + ${SCOPY_DEPENDENCIES} + ${EXTRA_BUNDLE_FILES} + ${SCOPY_WIN32_RESOURCES} + ) + endif() endif() list(FIND CMAKE_CXX_COMPILE_FEATURES cxx_constexpr OUT_CONSTEXPR) @@ -151,26 +156,24 @@ target_link_libraries(${PROJECT_NAME} PRIVATE Qt${QT_VERSION_MAJOR}::Widgets ${S # Compiler options target_compile_options(${PROJECT_NAME} PUBLIC -Wall) -#List of warnings to be treated as errors -target_compile_options(${PROJECT_NAME} PUBLIC - -Werror=return-type - -Werror=uninitialized - -Werror=init-self - -Werror=switch +# List of warnings to be treated as errors +target_compile_options( + ${PROJECT_NAME} PUBLIC -Werror=return-type -Werror=uninitialized -Werror=init-self -Werror=switch ) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/apple/Info.plist.cmakein ${CMAKE_CURRENT_BINARY_DIR}/Info.plist COPYONLY) -set_target_properties(${PROJECT_NAME} PROPERTIES - MACOSX_BUNDLE_GUI_IDENTIFIER scopy - MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION} - MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR} - MACOSX_BUNDLE TRUE - MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_BINARY_DIR}/Info.plist - WIN32_EXECUTABLE TRUE +set_target_properties( + ${PROJECT_NAME} + PROPERTIES MACOSX_BUNDLE_GUI_IDENTIFIER scopy + MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION} + MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR} + MACOSX_BUNDLE TRUE + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_BINARY_DIR}/Info.plist + WIN32_EXECUTABLE TRUE ) -if (ENABLE_APPLICATION_BUNDLE OR ${CMAKE_SYSTEM_NAME} MATCHES "Windows") - set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME Scopy) +if(ENABLE_APPLICATION_BUNDLE OR ${CMAKE_SYSTEM_NAME} MATCHES "Windows") + set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME Scopy) endif() configure_file(resources/qt.conf.cmakein ${CMAKE_CURRENT_BINARY_DIR}/qt.conf COPYONLY) @@ -178,7 +181,9 @@ configure_file(resources/scopy.desktop.cmakein ${CMAKE_CURRENT_BINARY_DIR}/scopy if(${CMAKE_SYSTEM_NAME} MATCHES "Linux") install(FILES ${CMAKE_CURRENT_BINARY_DIR}/scopy.desktop DESTINATION ${CMAKE_INSTALL_FULL_DATADIR}/applications) - install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/gui/res/icon_small.svg DESTINATION ${CMAKE_INSTALL_FULL_DATADIR}/icons/hicolor/scalable/apps RENAME scopy.svg) + install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/gui/res/icon_small.svg + DESTINATION ${CMAKE_INSTALL_FULL_DATADIR}/icons/hicolor/scalable/apps RENAME scopy.svg + ) install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/translations DESTINATION ${CMAKE_INSTALL_FULL_DATADIR}) endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") @@ -186,15 +191,14 @@ if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") duplicate_target(${PROJECT_NAME} Scopy-console) set_target_properties(Scopy-console PROPERTIES WIN32_EXECUTABLE FALSE) endif() -if (NOT ENABLE_APPLICATION_BUNDLE) - install(TARGETS ${PROJECT_NAME} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} - ) +if(NOT ENABLE_APPLICATION_BUNDLE) + install(TARGETS ${PROJECT_NAME} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ) endif() install(TARGETS ${PROJECT_NAME} BUNDLE DESTINATION .) if(QT_VERSION_MAJOR EQUAL 6) - qt_finalize_executable(${PROJECT_NAME}) + qt_finalize_executable(${PROJECT_NAME}) endif() diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 8e10f2c69e..098359de90 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -5,8 +5,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -23,42 +22,34 @@ set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) set(SCOPY_QT_COMPONENTS Core Widgets Concurrent) -FILE(GLOB SRC_LIST src/*.cpp src/*.cc) -FILE(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) -FILE(GLOB UI_LIST ui/*.ui) +file(GLOB SRC_LIST src/*.cpp src/*.cc) +file(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) +file(GLOB UI_LIST ui/*.ui) - -configure_file(include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h.cmakein - ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h @ONLY) +configure_file( + include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h.cmakein + ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h @ONLY +) set(SRC_LIST ${SRC_LIST} ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h) -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} -) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS ${SCOPY_QT_COMPONENTS} REQUIRED) -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) -target_include_directories(${PROJECT_NAME} PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}) +target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}) target_include_directories(${PROJECT_NAME} PUBLIC scopy-gui scopy-pluginbase scopyiioutil) foreach(comp ${SCOPY_QT_COMPONENTS}) - set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) + set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) endforeach() -target_link_libraries(${PROJECT_NAME} PUBLIC - ${SCOPY_QT_LIBRARIES} -) +target_link_libraries(${PROJECT_NAME} PUBLIC ${SCOPY_QT_LIBRARIES}) -install(TARGETS ${PROJECT_NAME} - LIBRARY DESTINATION ${SCOPY_DLL_PATH} - RUNTIME DESTINATION ${SCOPY_DLL_PATH}) \ No newline at end of file +install(TARGETS ${PROJECT_NAME} LIBRARY DESTINATION ${SCOPY_DLL_PATH} RUNTIME DESTINATION ${SCOPY_DLL_PATH}) diff --git a/common/include/common/common.h b/common/include/common/common.h index c116a2f517..9977eef47a 100644 --- a/common/include/common/common.h +++ b/common/include/common/common.h @@ -1,15 +1,14 @@ #ifndef COMMON_H #define COMMON_H -#include #include +#include #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) -namespace Qt -{ +namespace Qt { static auto endl = ::endl; static auto SkipEmptyParts = QString::SkipEmptyParts; -} +} // namespace Qt #endif #endif // COMMON_H diff --git a/common/include/common/scopyconfig.h b/common/include/common/scopyconfig.h index 269e41d11e..13fa879b96 100644 --- a/common/include/common/scopyconfig.h +++ b/common/include/common/scopyconfig.h @@ -1,12 +1,14 @@ #ifndef SCOPYCONFIG_H #define SCOPYCONFIG_H -#include #include "scopy-common_export.h" +#include + namespace scopy { -class SCOPY_COMMON_EXPORT config { +class SCOPY_COMMON_EXPORT config +{ public: static QString defaultPluginFolderPath(); static QString localPluginFolderPath(); @@ -23,8 +25,9 @@ class SCOPY_COMMON_EXPORT config { static QString dump(); static QString getUuid(); + private: inline static int uuid = 0; }; -} +} // namespace scopy #endif // SCOPYCONFIG_H diff --git a/common/src/scopyconfig.cpp b/common/src/scopyconfig.cpp index 238f3e7b71..9fa0450aa4 100644 --- a/common/src/scopyconfig.cpp +++ b/common/src/scopyconfig.cpp @@ -1,10 +1,12 @@ #include "scopyconfig.h" + #include "scopy-common_config.h" -#include + #include +#include +#include #include #include -#include QString scopy::config::defaultPluginFolderPath() { @@ -19,23 +21,20 @@ QString scopy::config::defaultPluginFolderPath() QString scopy::config::localPluginFolderPath() { - #if defined __APPLE__ - return QCoreApplication::applicationDirPath() + "/plugins/plugins"; - #endif +#if defined __APPLE__ + return QCoreApplication::applicationDirPath() + "/plugins/plugins"; +#endif return SCOPY_PLUGIN_BUILD_PATH; } -QString scopy::config::defaultTranslationFolderPath() -{ - return SCOPY_TRANSLATION_INSTALL_PATH; -} +QString scopy::config::defaultTranslationFolderPath() { return SCOPY_TRANSLATION_INSTALL_PATH; } QString scopy::config::localTranslationFolderPath() { - #if defined __APPLE__ - return QCoreApplication::applicationDirPath() + "/translations"; - #endif +#if defined __APPLE__ + return QCoreApplication::applicationDirPath() + "/translations"; +#endif return SCOPY_TRANSLATION_BUILD_PATH; } @@ -50,20 +49,11 @@ QString scopy::config::settingsFolderPath() return QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); } -QString scopy::config::executableFolderPath() -{ - return QCoreApplication::applicationDirPath(); -} +QString scopy::config::executableFolderPath() { return QCoreApplication::applicationDirPath(); } -QString scopy::config::version() -{ - return SCOPY_VERSION; -} +QString scopy::config::version() { return SCOPY_VERSION; } -QString scopy::config::gitCommit() -{ - return SCOPY_VERSION_GIT; -} +QString scopy::config::gitCommit() { return SCOPY_VERSION_GIT; } QString scopy::config::fullversion() { @@ -74,37 +64,41 @@ QString scopy::config::fullversion() return ver; } -QString scopy::config::os() -{ - return QSysInfo::prettyProductName(); -} +QString scopy::config::os() { return QSysInfo::prettyProductName(); } QString scopy::config::pcSpecs() { QString ret; - ret.append("build_abi: "+QSysInfo::buildAbi());ret.append("\n"); - ret.append("build_cpu: "+QSysInfo::buildCpuArchitecture());ret.append("\n"); - ret.append("host: "+QSysInfo::machineHostName());ret.append("\n"); - ret.append("arch: "+QSysInfo::currentCpuArchitecture());ret.append("\n"); - ret.append("kernel: "+ QSysInfo::kernelType());ret.append("\n"); - ret.append("kernel-ver: "+ QSysInfo::kernelVersion());ret.append("\n"); + ret.append("build_abi: " + QSysInfo::buildAbi()); + ret.append("\n"); + ret.append("build_cpu: " + QSysInfo::buildCpuArchitecture()); + ret.append("\n"); + ret.append("host: " + QSysInfo::machineHostName()); + ret.append("\n"); + ret.append("arch: " + QSysInfo::currentCpuArchitecture()); + ret.append("\n"); + ret.append("kernel: " + QSysInfo::kernelType()); + ret.append("\n"); + ret.append("kernel-ver: " + QSysInfo::kernelVersion()); + ret.append("\n"); return ret; } -QString scopy::config::dump() { +QString scopy::config::dump() +{ QString ret; ret = QString("ScopyConfig"); - ret+= QString("\n") + "DefaultPluginFolderPath: " + defaultPluginFolderPath() ; - ret+= QString("\n") + "PreferencesPluginFolderPath: " + preferencesFolderPath() ; - ret+= QString("\n") + "SettingsFolderPath: " + settingsFolderPath() ; - ret+= QString("\n") + "ExecutableFolderPath: " + executableFolderPath() ; - ret+= QString("\n") + "version: " + version() ; - ret+= QString("\n") + "gitCommit: " + gitCommit(); - ret+= QString("\n") + "fullversion: " + fullversion(); - ret+= QString("\n") + "os: " + os(); - ret+= QString("\n") + "pcSpecs: \n" + pcSpecs(); + ret += QString("\n") + "DefaultPluginFolderPath: " + defaultPluginFolderPath(); + ret += QString("\n") + "PreferencesPluginFolderPath: " + preferencesFolderPath(); + ret += QString("\n") + "SettingsFolderPath: " + settingsFolderPath(); + ret += QString("\n") + "ExecutableFolderPath: " + executableFolderPath(); + ret += QString("\n") + "version: " + version(); + ret += QString("\n") + "gitCommit: " + gitCommit(); + ret += QString("\n") + "fullversion: " + fullversion(); + ret += QString("\n") + "os: " + os(); + ret += QString("\n") + "pcSpecs: \n" + pcSpecs(); return ret; } diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index 63c27e5a9d..61a83be183 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -5,8 +5,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -24,12 +23,12 @@ set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) set(SCOPY_QT_COMPONENTS Core Widgets Concurrent Network) -FILE(GLOB SRC_LIST src/*.cpp src/*.cc) -FILE(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) -FILE(GLOB UI_LIST ui/*.ui) +file(GLOB SRC_LIST src/*.cpp src/*.cc) +file(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) +file(GLOB UI_LIST ui/*.ui) if(ENABLE_TESTING) - add_subdirectory(test) + add_subdirectory(test) endif() option(WITH_PYTHON "Enable Python" ON) @@ -42,12 +41,12 @@ if(${WITH_PYTHON}) set(WITH_PYTHON OFF) message(STATUS "Python not found") endif() - set(BUILD_PYTHON_LIBRARY_DIRS ${Python3_LIBRARY_DIRS}/${PYTHON_VERSION}) + set(BUILD_PYTHON_LIBRARY_DIRS ${Python3_LIBRARY_DIRS}/${PYTHON_VERSION}) endif() option(WITH_SIGROK "Search for libsigrokdecode" ON) if(WITH_SIGROK) -find_package(PkgConfig) + find_package(PkgConfig) set(PKG_CONFIG_USE_CMAKE_PREFIX_PATH ON) pkg_check_modules(GLIB REQUIRED glib-2.0) pkg_check_modules(LIBSIGROK_DECODE REQUIRED libsigrokdecode) @@ -58,56 +57,49 @@ find_package(PkgConfig) endif() endif() - option(SCOPY_DEV_MODE "Enable development specific scopy behavior - autoconnect to a context on start" FALSE) -configure_file(include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h.cmakein - ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h @ONLY) +configure_file( + include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h.cmakein + ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h @ONLY +) set(SRC_LIST ${SRC_LIST} ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h) -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} -) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS ${SCOPY_QT_COMPONENTS} REQUIRED) -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) -target_include_directories(${PROJECT_NAME} PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE} - ${GLIB_INCLUDE_DIRS} - ${GLIBCONFIG_INCLUDE_DIRS} - ${LIBSIGROK_DECODE_INCLUDE_DIRS} - ${Python3_INCLUDE_DIRS}) +target_include_directories( + ${PROJECT_NAME} + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE} + ${GLIB_INCLUDE_DIRS} + ${GLIBCONFIG_INCLUDE_DIRS} + ${LIBSIGROK_DECODE_INCLUDE_DIRS} + ${Python3_INCLUDE_DIRS} +) target_include_directories(${PROJECT_NAME} PUBLIC scopy-gui scopy-pluginbase scopy-iioutil scopy-common) foreach(comp ${SCOPY_QT_COMPONENTS}) - set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) + set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) endforeach() -target_link_libraries(${PROJECT_NAME} PUBLIC - ${SCOPY_QT_LIBRARIES} - scopy-common - scopy-gui - scopy-pluginbase - scopy-iioutil - ${LIBSIGROK_DECODE_LINK_LIBRARIES} - ${Python3_LIBRARIES}) - -install(TARGETS ${PROJECT_NAME} - LIBRARY DESTINATION ${SCOPY_DLL_PATH} - RUNTIME DESTINATION ${SCOPY_DLL_PATH}) - - - - - +target_link_libraries( + ${PROJECT_NAME} + PUBLIC ${SCOPY_QT_LIBRARIES} + scopy-common + scopy-gui + scopy-pluginbase + scopy-iioutil + ${LIBSIGROK_DECODE_LINK_LIBRARIES} + ${Python3_LIBRARIES} +) +install(TARGETS ${PROJECT_NAME} LIBRARY DESTINATION ${SCOPY_DLL_PATH} RUNTIME DESTINATION ${SCOPY_DLL_PATH}) diff --git a/core/include/core/application_restarter.h b/core/include/core/application_restarter.h index bbe85d37a4..c9fcc4231f 100644 --- a/core/include/core/application_restarter.h +++ b/core/include/core/application_restarter.h @@ -1,9 +1,10 @@ #ifndef APPLICATIONRESTARTER_H #define APPLICATIONRESTARTER_H +#include "scopy-core_export.h" + #include #include -#include "scopy-core_export.h" namespace scopy { class SCOPY_CORE_EXPORT ApplicationRestarter diff --git a/core/include/core/cmdlinehandler.h b/core/include/core/cmdlinehandler.h index 48bb4418b0..2fc79e4756 100644 --- a/core/include/core/cmdlinehandler.h +++ b/core/include/core/cmdlinehandler.h @@ -1,12 +1,12 @@ #ifndef CMDLINEHANDLER_H #define CMDLINEHANDLER_H -#include #include "scopy-core_export.h" #include "scopymainwindow_api.h" -namespace scopy -{ +#include + +namespace scopy { class SCOPY_CORE_EXPORT CmdLineHandler { public: @@ -16,9 +16,8 @@ class SCOPY_CORE_EXPORT CmdLineHandler private: static void logOutputHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg); - static FILE* logFile_; - + static FILE *logFile_; }; -} +} // namespace scopy #endif // CMDLINEHANDLER_H diff --git a/core/include/core/detachedtoolwindow.h b/core/include/core/detachedtoolwindow.h index 2df784d43e..e577cb2313 100644 --- a/core/include/core/detachedtoolwindow.h +++ b/core/include/core/detachedtoolwindow.h @@ -1,12 +1,15 @@ #ifndef DETACHEDTOOLWINDOW_H #define DETACHEDTOOLWINDOW_H +#include "scopy-core_export.h" + #include + #include -#include "scopy-core_export.h" namespace scopy { -class SCOPY_CORE_EXPORT DetachedToolWindow : public QWidget { +class SCOPY_CORE_EXPORT DetachedToolWindow : public QWidget +{ Q_OBJECT public: DetachedToolWindow(QWidget *parent, ToolMenuEntry *tme); @@ -14,6 +17,7 @@ class SCOPY_CORE_EXPORT DetachedToolWindow : public QWidget { void saveToolGeometry(ToolMenuEntry *tme, QWidget *w); void loadToolGeometry(ToolMenuEntry *tme, QWidget *w); + private: ToolMenuEntry *tme; QWidget *w; @@ -21,5 +25,5 @@ class SCOPY_CORE_EXPORT DetachedToolWindow : public QWidget { protected: void closeEvent(QCloseEvent *event) override; }; -} +} // namespace scopy #endif // DETACHEDTOOLWINDOW_H diff --git a/core/include/core/detachedtoolwindowmanager.h b/core/include/core/detachedtoolwindowmanager.h index ff7e7ed4a2..69845b0a4d 100644 --- a/core/include/core/detachedtoolwindowmanager.h +++ b/core/include/core/detachedtoolwindowmanager.h @@ -1,15 +1,18 @@ #ifndef DETACHEDTOOLMANAGER_H #define DETACHEDTOOLMANAGER_H -#include +#include "detachedtoolwindow.h" +#include "scopy-core_export.h" + #include +#include + #include -#include "scopy-core_export.h" -#include "detachedtoolwindow.h" namespace scopy { -class SCOPY_CORE_EXPORT DetachedToolWindowManager : public QObject { +class SCOPY_CORE_EXPORT DetachedToolWindowManager : public QObject +{ Q_OBJECT public: DetachedToolWindowManager(QObject *parent = nullptr); @@ -22,9 +25,10 @@ class SCOPY_CORE_EXPORT DetachedToolWindowManager : public QObject { public Q_SLOTS: void show(QString id); + private: - QMap map; + QMap map; }; -} +} // namespace scopy #endif // DETACHEDTOOLMANAGER_H diff --git a/core/include/core/device.h b/core/include/core/device.h index ae15479bc6..b1ed9a2b07 100644 --- a/core/include/core/device.h +++ b/core/include/core/device.h @@ -1,13 +1,15 @@ #ifndef DEVICE_H #define DEVICE_H -#include #include "pluginbase/toolmenuentry.h" #include "scopy-core_export.h" + +#include #include namespace scopy { -class SCOPY_CORE_EXPORT Device { +class SCOPY_CORE_EXPORT Device +{ public: virtual ~Device(){}; virtual QString id() = 0; @@ -15,9 +17,11 @@ class SCOPY_CORE_EXPORT Device { virtual QString displayName() = 0; virtual QString param() = 0; virtual QString displayParam() = 0; - virtual QWidget *icon() = 0;; - virtual QWidget *page() = 0;; - virtual QList toolList() = 0; + virtual QWidget *icon() = 0; + ; + virtual QWidget *page() = 0; + ; + virtual QList toolList() = 0; virtual void init() = 0; virtual void preload() = 0; virtual void loadPlugins() = 0; @@ -34,11 +38,10 @@ public Q_SLOTS: Q_SIGNALS: virtual void toolListChanged() = 0; virtual void connected() = 0; - virtual void disconnected() = 0; + virtual void disconnected() = 0; virtual void requestedRestart() = 0; virtual void requestTool(QString) = 0; - }; -} +} // namespace scopy #endif // DEVICE_H diff --git a/core/include/core/devicebrowser.h b/core/include/core/devicebrowser.h index 8b457489eb..f48ace626d 100644 --- a/core/include/core/devicebrowser.h +++ b/core/include/core/devicebrowser.h @@ -1,12 +1,14 @@ #ifndef DEVICEBROWSER_H #define DEVICEBROWSER_H -#include -#include +#include "scopy-core_export.h" + #include +#include #include +#include + #include -#include "scopy-core_export.h" namespace Ui { class DeviceBrowser; @@ -30,7 +32,7 @@ class SCOPY_CORE_EXPORT DeviceBrowser : public QWidget void requestDevice(QString id, int direction); void requestRemoveDevice(QString id); -public Q_SLOTS: +public Q_SLOTS: void nextDevice(); void prevDevice(); @@ -41,17 +43,16 @@ private Q_SLOTS: private: void initBtns(); - DeviceIcon* buildDeviceIcon(Device *d, QWidget *parent = nullptr); + DeviceIcon *buildDeviceIcon(Device *d, QWidget *parent = nullptr); Ui::DeviceBrowser *ui; QButtonGroup *bg; QHBoxLayout *layout; - QList list; + QList list; int currentIdx; int getIndexOfId(QString k); QString getIdOfIndex(int idx); - const char* devBrowserId = "DeviceBrowserId"; - + const char *devBrowserId = "DeviceBrowserId"; }; -} +} // namespace scopy #endif // DEVICEBROWSER_H diff --git a/core/include/core/devicefactory.h b/core/include/core/devicefactory.h index 0015d946cb..38f2b20f16 100644 --- a/core/include/core/devicefactory.h +++ b/core/include/core/devicefactory.h @@ -1,17 +1,17 @@ #ifndef DEVICEFACTORY_H #define DEVICEFACTORY_H -#include #include "deviceimpl.h" -namespace scopy { +#include +namespace scopy { -class DeviceFactory : public QObject { +class DeviceFactory : public QObject +{ Q_OBJECT public: - static DeviceImpl* build(QString param, PluginManager *pm, QString category = "",QObject *parent = nullptr); - + static DeviceImpl *build(QString param, PluginManager *pm, QString category = "", QObject *parent = nullptr); }; -} +} // namespace scopy #endif // DEVICEFACTORY_H diff --git a/core/include/core/deviceicon.h b/core/include/core/deviceicon.h index 5836fc18b9..2a24c56679 100644 --- a/core/include/core/deviceicon.h +++ b/core/include/core/deviceicon.h @@ -1,22 +1,26 @@ #ifndef DEVICEICON_H #define DEVICEICON_H +#include "scopy-core_export.h" + #include + #include -#include "scopy-core_export.h" namespace scopy { -class SCOPY_CORE_EXPORT DeviceIcon : public QAbstractButton { +class SCOPY_CORE_EXPORT DeviceIcon : public QAbstractButton +{ Q_OBJECT public: - DeviceIcon(QWidget *parent = nullptr) : QAbstractButton(parent) {}; - virtual ~DeviceIcon() {}; + DeviceIcon(QWidget *parent = nullptr) + : QAbstractButton(parent){}; + virtual ~DeviceIcon(){}; public Q_SLOTS: -// virtual Device* device() = 0; + // virtual Device* device() = 0; virtual void setConnected(bool) = 0; Q_SIGNALS: void refresh(); void forget(); }; -} +} // namespace scopy #endif // DEVICEICON_H diff --git a/core/include/core/deviceiconimpl.h b/core/include/core/deviceiconimpl.h index 784d077a2e..7098e083b4 100644 --- a/core/include/core/deviceiconimpl.h +++ b/core/include/core/deviceiconimpl.h @@ -1,16 +1,18 @@ #ifndef DEVICEICONIMPL_H #define DEVICEICONIMPL_H -#include -#include -#include #include "device.h" -#include "scopy-core_export.h" #include "gui/utils.h" +#include "scopy-core_export.h" + +#include #include +#include + +#include namespace Ui { - class DeviceButton; +class DeviceButton; }; namespace scopy { @@ -26,9 +28,7 @@ public Q_SLOTS: private: Ui::DeviceButton *ui; - - }; -} +} // namespace scopy #endif // DEVICEICONIMPL_H diff --git a/core/include/core/deviceimpl.h b/core/include/core/deviceimpl.h index 45e6a0322e..5bbcc2216c 100644 --- a/core/include/core/deviceimpl.h +++ b/core/include/core/deviceimpl.h @@ -1,22 +1,22 @@ #ifndef DEVICEIMPL_H #define DEVICEIMPL_H +#include "device.h" #include "pluginbase/plugin.h" +#include "pluginmanager.h" +#include "scopy-core_export.h" + +#include #include -#include "device.h" #include -#include -#include "scopy-core_export.h" -#include "pluginmanager.h" namespace scopy { - class SCOPY_CORE_EXPORT DeviceImpl : public QObject, public Device { Q_OBJECT public: - explicit DeviceImpl(QString param, PluginManager *p, QString category = "",QObject *parent = nullptr); + explicit DeviceImpl(QString param, PluginManager *p, QString category = "", QObject *parent = nullptr); virtual ~DeviceImpl(); // Device interface @@ -28,7 +28,7 @@ class SCOPY_CORE_EXPORT DeviceImpl : public QObject, public Device QString param() override; QWidget *icon() override; QWidget *page() override; - QList toolList() override; + QList toolList() override; virtual void init() override; virtual void preload() override; virtual void loadPlugins() override; @@ -45,7 +45,7 @@ public Q_SLOTS: virtual void hidePage() override; virtual void save(QSettings &) override; virtual void load(QSettings &) override; -// void forgetDev() override; + // void forgetDev() override; void onConnectionFailed(); Q_SIGNALS: void toolListChanged() override; @@ -55,6 +55,7 @@ public Q_SLOTS: void requestTool(QString) override; void connectionFailed(); void forget(); + protected: void removeDisabledPlugins(); void loadName(); @@ -65,8 +66,8 @@ public Q_SLOTS: protected: PluginManager *p; - QList m_plugins; - QList m_connectedPlugins; + QList m_plugins; + QList m_connectedPlugins; QString m_id; QString m_category; QString m_displayName; @@ -75,8 +76,7 @@ public Q_SLOTS: QWidget *m_icon; QWidget *m_page; QPushButton *connbtn, *discbtn; - }; -} +} // namespace scopy #endif // DEVICEIMPL_H diff --git a/core/include/core/deviceloader.h b/core/include/core/deviceloader.h index 8a94a62a4e..12ae5d2f83 100644 --- a/core/include/core/deviceloader.h +++ b/core/include/core/deviceloader.h @@ -1,13 +1,14 @@ #ifndef DEVICELOADER_H #define DEVICELOADER_H -#include #include "deviceimpl.h" -namespace scopy { +#include +namespace scopy { -class DeviceLoader : public QObject { +class DeviceLoader : public QObject +{ Q_OBJECT public: DeviceLoader(DeviceImpl *d, QObject *parent = nullptr); @@ -22,6 +23,6 @@ class DeviceLoader : public QObject { DeviceImpl *d; QObject *oldParent; }; -} +} // namespace scopy #endif // DEVICELOADER_H diff --git a/core/include/core/devicemanager.h b/core/include/core/devicemanager.h index 2f36c8c8e5..cc7cd29e56 100644 --- a/core/include/core/devicemanager.h +++ b/core/include/core/devicemanager.h @@ -1,23 +1,25 @@ #ifndef DEVICEMANAGER_H #define DEVICEMANAGER_H -#include -#include -#include #include "device.h" #include "deviceimpl.h" #include "pluginmanager.h" #include "scopy-core_export.h" +#include +#include +#include + namespace scopy { class SCOPY_CORE_EXPORT DeviceManager : public QObject { Q_OBJECT friend class ScopyMainWindow_API; + public: explicit DeviceManager(PluginManager *pm, QObject *parent = nullptr); ~DeviceManager(); - Device* getDevice(QString id); + Device *getDevice(QString id); void setExclusive(bool); bool getExclusive() const; @@ -33,8 +35,7 @@ public Q_SLOTS: void save(QSettings &s); void load(QSettings &s); -// void updateScan(QStringList ls); - + // void updateScan(QStringList ls); private Q_SLOTS: void changeToolListDevice(); @@ -43,28 +44,30 @@ private Q_SLOTS: void restartDevice(); Q_SIGNALS: - void deviceChangedToolList(QString, QList); + void deviceChangedToolList(QString, QList); void deviceAddStarted(QString); - void deviceAdded(QString, Device*); - void deviceRemoveStarted(QString, Device*); + void deviceAdded(QString, Device *); + void deviceRemoveStarted(QString, Device *); void deviceRemoved(QString); - void deviceConnected(QString id, Device*); - void deviceDisconnected(QString id, Device*); + void deviceConnected(QString id, Device *); + void deviceDisconnected(QString id, Device *); void requestDevice(QString id); void requestTool(QString id); + private: void connectDeviceToManager(DeviceImpl *d); void disconnectDeviceFromManager(DeviceImpl *d); + private: bool exclusive = false; QStringList scannedDev; QStringList connectedDev; - QMap map; + QMap map; PluginManager *pm; void disconnectDevice(QString id); void connectDevice(QString id); }; -} +} // namespace scopy #endif // DEVICEMANAGER_H diff --git a/core/include/core/emuwidget.h b/core/include/core/emuwidget.h index de237134a5..b1611df51e 100644 --- a/core/include/core/emuwidget.h +++ b/core/include/core/emuwidget.h @@ -1,10 +1,11 @@ #ifndef EMUWIDGET_H #define EMUWIDGET_H +#include "scopy-core_export.h" + #include #include -#include -#include "scopy-core_export.h" +#include namespace Ui { class EmuWidget; @@ -15,7 +16,6 @@ class SCOPY_CORE_EXPORT EmuWidget : public QWidget { Q_OBJECT public: - explicit EmuWidget(QString path = "", QWidget *parent = nullptr); ~EmuWidget(); @@ -43,8 +43,7 @@ private Q_SLOTS: bool m_enableDemo; QProcess *m_emuProcess; const QVector m_availableOptions{"adalm2000", "generic"}; - }; -} +} // namespace scopy #endif // EMUWIDGET_H diff --git a/core/include/core/iiodeviceimpl.h b/core/include/core/iiodeviceimpl.h index a8100451e9..df84dd062b 100644 --- a/core/include/core/iiodeviceimpl.h +++ b/core/include/core/iiodeviceimpl.h @@ -8,7 +8,9 @@ namespace scopy { class SCOPY_CORE_EXPORT IIODeviceImpl : public DeviceImpl { public: - explicit IIODeviceImpl(QString param, PluginManager *p ,QObject *parent = nullptr) : DeviceImpl(param, p, "iio", parent) {} + explicit IIODeviceImpl(QString param, PluginManager *p, QObject *parent = nullptr) + : DeviceImpl(param, p, "iio", parent) + {} ~IIODeviceImpl() {} virtual void init() override; @@ -16,6 +18,6 @@ class SCOPY_CORE_EXPORT IIODeviceImpl : public DeviceImpl QMap readDeviceInfo() override; }; -} +} // namespace scopy #endif // IIODEVICEIMPL_H diff --git a/core/include/core/iiotabwidget.h b/core/include/core/iiotabwidget.h index 8db68164ff..75bb2e2e2a 100644 --- a/core/include/core/iiotabwidget.h +++ b/core/include/core/iiotabwidget.h @@ -4,13 +4,11 @@ #include #include - namespace Ui { class IioTabWidget; } -namespace scopy -{ +namespace scopy { class IioTabWidget : public QWidget { @@ -25,12 +23,14 @@ public Q_SLOTS: Q_SIGNALS: void uriChanged(QString uri); void startVerify(QString uri, QString cat); + protected: void showEvent(QShowEvent *event) override; private Q_SLOTS: void scanFinished(); void futureScan(); void verifyBtnClicked(); + private: Ui::IioTabWidget *m_ui; QFutureWatcher *fwScan; @@ -44,9 +44,9 @@ private Q_SLOTS: void createBackEndCheckBox(QString backEnd); QString getSerialPath(); - const QVector availableBaudRates = {2400, 4800, 9600, 14400, 19200, 38400, 57600, 115200, 230400, 460800, 921600}; - + const QVector availableBaudRates = {2400, 4800, 9600, 14400, 19200, 38400, + 57600, 115200, 230400, 460800, 921600}; }; -} +} // namespace scopy #endif // IIOTABWIDGET_H diff --git a/core/include/core/infopagestack.h b/core/include/core/infopagestack.h index 12c5b67a4c..d54b9c31fe 100644 --- a/core/include/core/infopagestack.h +++ b/core/include/core/infopagestack.h @@ -2,11 +2,12 @@ #define INFOPAGESTACK_H #include "device.h" -#include "mapstackedwidget.h" -#include #include "gui/homepage_controls.h" +#include "mapstackedwidget.h" #include "scopy-core_export.h" +#include + namespace scopy { // implement slide to-from next/prev page - emits to button selection group @@ -15,15 +16,13 @@ class SCOPY_CORE_EXPORT InfoPageStack : public MapStackedWidget { Q_OBJECT public: - - explicit InfoPageStack(QWidget *parent = nullptr); ~InfoPageStack(); - void add(QString key, Device* d); + void add(QString key, Device *d); HomepageControls *getHomepageControls() const; - void add(QString key, QWidget* w) override; + void add(QString key, QWidget *w) override; bool remove(QString key) override; public Q_SLOTS: bool show(QString key) override; @@ -33,7 +32,7 @@ protected Q_SLOTS: void animationDone(); private: - QMap idDevMap; + QMap idDevMap; void slideInWidget(QWidget *newWidget, int direction); HomepageControls *hc; @@ -44,7 +43,6 @@ protected Q_SLOTS: QPoint now; int current; int next; - }; -} +} // namespace scopy #endif // INFOPAGESTACK_H diff --git a/core/include/core/license_overlay.h b/core/include/core/license_overlay.h index 4757f6d17f..31c1cb0530 100644 --- a/core/include/core/license_overlay.h +++ b/core/include/core/license_overlay.h @@ -7,22 +7,23 @@ #include - -namespace Ui { class LicenseDialogOverlay; } +namespace Ui { +class LicenseDialogOverlay; +} namespace scopy { -class SCOPY_CORE_EXPORT LicenseOverlay: public QWidget +class SCOPY_CORE_EXPORT LicenseOverlay : public QWidget { Q_OBJECT public: - LicenseOverlay(QWidget* parent = nullptr); + LicenseOverlay(QWidget *parent = nullptr); QString static getLicense(); void showOverlay(); QPushButton *getContinueBtn(); + private: QWidget *parent; gui::TintedOverlay *overlay; Ui::LicenseDialogOverlay *ui; }; -} +} // namespace scopy #endif // LICENSEOVERLAY_H - diff --git a/core/include/core/logging_categories.h b/core/include/core/logging_categories.h index d68dfa24d6..af14aea7e0 100644 --- a/core/include/core/logging_categories.h +++ b/core/include/core/logging_categories.h @@ -20,9 +20,10 @@ #ifndef LOGGING_CATEGORIES_H #define LOGGING_CATEGORIES_H -#include #include "scopy-core_export.h" +#include + #define QDEBUG_LOG_TIME //#define QDEBUG_LOG_DATE #define QDEBUG_LOG_MSG_TYPE @@ -30,10 +31,10 @@ //#define QDEBUG_CATEGORY #define QDEBUG_FUNCTION - #define QDEBUG_LOG_TIME_STR "%{time h:mm:ss.zzz}" #define QDEBUG_LOG_DATE_STR "%{time yyyyMMdd }" -#define QDEBUG_LOG_MSG_TYPE_STR "%{if-debug}D%{endif}%{if-info}I%{endif}%{if-warning}W%{endif}%{if-critical}C%{endif}%{if-fatal}F%{endif}" +#define QDEBUG_LOG_MSG_TYPE_STR \ + "%{if-debug}D%{endif}%{if-info}I%{endif}%{if-warning}W%{endif}%{if-critical}C%{endif}%{if-fatal}F%{endif}" #define QDEBUG_LOG_FILE_PREFIX_STR "file://" #define QDEBUG_LOG_FILE_NAME_STR "%{file}:" #define QDEBUG_LOG_LINE_NR_STR "%{line}" @@ -44,7 +45,6 @@ #define QDEBUG_PID_STR "%{pid}" #define QDEBUG_APP_STR "%{appname}" - #ifndef QT_NO_DEBUG_OUTPUT Q_DECLARE_LOGGING_CATEGORY(CAT_TOOL_LAUNCHER) Q_DECLARE_LOGGING_CATEGORY(CAT_OSCILLOSCOPE) diff --git a/core/include/core/pluginenablewidget.h b/core/include/core/pluginenablewidget.h index 90f3a9ca63..a9df1d750d 100644 --- a/core/include/core/pluginenablewidget.h +++ b/core/include/core/pluginenablewidget.h @@ -1,14 +1,16 @@ #ifndef PLUGINENABLEWIDGET_H #define PLUGINENABLEWIDGET_H -#include +#include "gui/utils.h" #include "qcheckbox.h" #include "qlabel.h" -#include "gui/utils.h" + +#include namespace scopy { -class PluginEnableWidget : public QWidget { +class PluginEnableWidget : public QWidget +{ Q_OBJECT QWIDGET_PAINT_EVENT_HELPER public: @@ -23,7 +25,6 @@ class PluginEnableWidget : public QWidget { QLabel *m_descriptionLabel; }; -} - +} // namespace scopy #endif // PLUGINENABLEWIDGET_H diff --git a/core/include/core/pluginfilter.h b/core/include/core/pluginfilter.h index 77de2553fc..9c0c0f4e8e 100644 --- a/core/include/core/pluginfilter.h +++ b/core/include/core/pluginfilter.h @@ -2,18 +2,18 @@ #define PLUGINFILTER_H #include - namespace scopy { class PluginFilter { -private : +private: PluginFilter(); + public: - static bool pluginInCategory(Plugin* p, QString category); // PluginFilter class (?) - static bool pluginInExclusionList(QList pl, Plugin *p); - static bool pluginForcedInclusionList(QList pl, Plugin *p); + static bool pluginInCategory(Plugin *p, QString category); // PluginFilter class (?) + static bool pluginInExclusionList(QList pl, Plugin *p); + static bool pluginForcedInclusionList(QList pl, Plugin *p); }; -} +} // namespace scopy #endif // PLUGINFILTER_H diff --git a/core/include/core/pluginmanager.h b/core/include/core/pluginmanager.h index 840804fd47..82447e800b 100644 --- a/core/include/core/pluginmanager.h +++ b/core/include/core/pluginmanager.h @@ -1,10 +1,12 @@ #ifndef PLUGINMANAGER_H #define PLUGINMANAGER_H -#include +#include "scopy-core_export.h" + #include +#include + #include -#include "scopy-core_export.h" namespace scopy { class SCOPY_CORE_EXPORT PluginManager : public QObject @@ -18,19 +20,19 @@ class SCOPY_CORE_EXPORT PluginManager : public QObject int count(); void sort(); void clear(); - QList getOriginalPlugins() const; - QList getPlugins(QString category = ""); - QList getCompatiblePlugins(QString param, QString category = ""); + QList getOriginalPlugins() const; + QList getPlugins(QString category = ""); + QList getCompatiblePlugins(QString param, QString category = ""); void setMetadata(QJsonObject metadata); QJsonObject metadata() const; private: - Plugin* loadPlugin(QString file); - QList list; + Plugin *loadPlugin(QString file); + QList list; QJsonObject m_metadata; void applyMetadata(Plugin *plugin, QJsonObject *metadata); bool pluginInCategory(Plugin *p, QString category); }; -} +} // namespace scopy #endif // PLUGINMANAGER_H diff --git a/core/include/core/pluginrepository.h b/core/include/core/pluginrepository.h index 87595bd328..c2923d910b 100644 --- a/core/include/core/pluginrepository.h +++ b/core/include/core/pluginrepository.h @@ -1,11 +1,12 @@ #ifndef PLUGINREPOSITORY_H #define PLUGINREPOSITORY_H -#include -#include #include "pluginmanager.h" #include "scopy-core_export.h" +#include +#include + namespace scopy { class SCOPY_CORE_EXPORT PluginRepository : public QObject @@ -15,12 +16,12 @@ class SCOPY_CORE_EXPORT PluginRepository : public QObject PluginRepository(QObject *parent); ~PluginRepository(); void init(QString location); - PluginManager *getPluginManager() {return pm;} + PluginManager *getPluginManager() { return pm; } private: PluginManager *pm; QJsonObject metadata; }; -} +} // namespace scopy #endif // PLUGINREPOSITORY_H diff --git a/core/include/core/scanbuttoncontroller.h b/core/include/core/scanbuttoncontroller.h index 42611a964c..cbf99bc057 100644 --- a/core/include/core/scanbuttoncontroller.h +++ b/core/include/core/scanbuttoncontroller.h @@ -1,29 +1,30 @@ #ifndef SCANBUTTONCONTROLLER_H #define SCANBUTTONCONTROLLER_H +#include "iioutil/cyclicaltask.h" +#include "scopy-core_export.h" + #include #include -#include "scopy-core_export.h" -#include "iioutil/cyclicaltask.h" namespace scopy { class SCOPY_CORE_EXPORT ScanButtonController : public QObject { Q_OBJECT public: - explicit ScanButtonController(CyclicalTask *cs , QPushButton *btn, QObject *parent); + explicit ScanButtonController(CyclicalTask *cs, QPushButton *btn, QObject *parent); ~ScanButtonController(); public Q_SLOTS: void enableScan(bool b); void startScan(); void stopScan(); + private: QPushButton *btn; CyclicalTask *cs; QMetaObject::Connection conn; - }; -} +} // namespace scopy #endif // SCANBUTTONCONTROLLER_H diff --git a/core/include/core/scannediiocontextcollector.h b/core/include/core/scannediiocontextcollector.h index df4bfb3e0a..41aba53c7a 100644 --- a/core/include/core/scannediiocontextcollector.h +++ b/core/include/core/scannediiocontextcollector.h @@ -1,11 +1,12 @@ #ifndef SCANNEDIIOCONTEXTCOLLECTOR_H #define SCANNEDIIOCONTEXTCOLLECTOR_H -#include -#include #include "device.h" #include "scopy-core_export.h" +#include +#include + namespace scopy { class SCOPY_CORE_EXPORT ScannedIIOContextCollector : public QObject { @@ -17,17 +18,17 @@ class SCOPY_CORE_EXPORT ScannedIIOContextCollector : public QObject public Q_SLOTS: void update(QStringList uris); void clearCache(); - void lock(QString, Device*); - void unlock(QString, Device*); + void lock(QString, Device *); + void unlock(QString, Device *); void removeDevice(QString id, Device *d); Q_SIGNALS: void foundDevice(QString cat, QString uri); void lostDevice(QString cat, QString uri); + private: QSet uris; QSet lockedUris; - }; -} +} // namespace scopy #endif // SCANNEDIIOCONTEXTCOLLECTOR_H diff --git a/core/include/core/scopyaboutpage.h b/core/include/core/scopyaboutpage.h index 5f36dd2279..c6838899f7 100644 --- a/core/include/core/scopyaboutpage.h +++ b/core/include/core/scopyaboutpage.h @@ -1,12 +1,12 @@ #ifndef SCOPYABOUTPAGE_H #define SCOPYABOUTPAGE_H +#include "scopy-core_export.h" + #include +#include #include #include -#include - -#include "scopy-core_export.h" namespace scopy { class SCOPY_CORE_EXPORT ScopyAboutPage : public QWidget @@ -17,12 +17,13 @@ class SCOPY_CORE_EXPORT ScopyAboutPage : public QWidget ~ScopyAboutPage(); void addHorizontalTab(QWidget *w, QString text); QWidget *buildPage(QString src); + private: void initUI(); void initNavigationWidget(QTextBrowser *browser); QTabWidget *tabWidget; QVBoxLayout *layout; }; -} +} // namespace scopy #endif // SCOPYABOUTPAGE_H diff --git a/core/include/core/scopyhomeaddpage.h b/core/include/core/scopyhomeaddpage.h index 5fd0fcd296..6a991ef9d0 100644 --- a/core/include/core/scopyhomeaddpage.h +++ b/core/include/core/scopyhomeaddpage.h @@ -1,17 +1,19 @@ #ifndef SCOPYHOMEADDPAGE_H #define SCOPYHOMEADDPAGE_H -#include #include "deviceimpl.h" +#include "emuwidget.h" +#include "iiotabwidget.h" #include "infopage.h" #include "pluginenablewidget.h" #include "pluginmanager.h" #include "scopy-core_export.h" -#include -#include "emuwidget.h" -#include "iiotabwidget.h" + #include +#include +#include + namespace Ui { class ScopyHomeAddPage; } @@ -57,7 +59,7 @@ private Q_SLOTS: InfoPage *deviceInfoPage; PluginManager *pluginManager; DeviceImpl *deviceImpl; - QList pluginDescriptionList; + QList pluginDescriptionList; }; -} +} // namespace scopy #endif // SCOPYHOMEADDPAGE_H diff --git a/core/include/core/scopyhomeinfopage.h b/core/include/core/scopyhomeinfopage.h index d4504b81fa..f11a4189ef 100644 --- a/core/include/core/scopyhomeinfopage.h +++ b/core/include/core/scopyhomeinfopage.h @@ -1,10 +1,12 @@ #ifndef SCOPYHOMEINFOPAGE_H #define SCOPYHOMEINFOPAGE_H -#include +#include "scopy-core_export.h" + #include +#include + #include -#include "scopy-core_export.h" namespace Ui { class ScopyHomeInfoPage; @@ -13,7 +15,7 @@ class ScopyHomeInfoPage; namespace scopy { class SCOPY_CORE_EXPORT ScopyHomeInfoPage : public QWidget { -Q_OBJECT + Q_OBJECT public: explicit ScopyHomeInfoPage(QWidget *parent = nullptr); @@ -24,6 +26,6 @@ Q_OBJECT void initReportButton(); }; -} +} // namespace scopy #endif // SCOPYHOMEINFOPAGE_H diff --git a/core/include/core/scopyhomepage.h b/core/include/core/scopyhomepage.h index 8a3b77cd69..61bb65e230 100644 --- a/core/include/core/scopyhomepage.h +++ b/core/include/core/scopyhomepage.h @@ -1,12 +1,13 @@ #ifndef SCOPYHOMEPAGE_H #define SCOPYHOMEPAGE_H +#include "device.h" #include "pluginmanager.h" +#include "scopy-core_export.h" #include "scopyhomeaddpage.h" -#include + #include -#include "scopy-core_export.h" -#include "device.h" +#include namespace Ui { class ScopyHomePage; @@ -20,7 +21,7 @@ class SCOPY_CORE_EXPORT ScopyHomePage : public QWidget public: explicit ScopyHomePage(QWidget *parent = nullptr, PluginManager *pm = nullptr); ~ScopyHomePage(); - QPushButton* scanControlBtn(); + QPushButton *scanControlBtn(); Q_SIGNALS: void requestAddDevice(QString cat, QString id); @@ -30,7 +31,7 @@ class SCOPY_CORE_EXPORT ScopyHomePage : public QWidget void newDeviceAvailable(DeviceImpl *d); public Q_SLOTS: - void addDevice(QString id, Device*); + void addDevice(QString id, Device *); void removeDevice(QString id); void viewDevice(QString id); void connectDevice(QString); @@ -40,6 +41,6 @@ public Q_SLOTS: Ui::ScopyHomePage *ui; ScopyHomeAddPage *add; }; -} +} // namespace scopy #endif // SCOPYHOMEPAGE_H diff --git a/core/include/core/scopymainwindow.h b/core/include/core/scopymainwindow.h index a5bcd15ce7..d7a6dbb85a 100644 --- a/core/include/core/scopymainwindow.h +++ b/core/include/core/scopymainwindow.h @@ -1,26 +1,28 @@ #ifndef SCOPYMAINWINDOW_H #define SCOPYMAINWINDOW_H -#include - -#include "license_overlay.h" -#include "scopyhomepage.h" -#include "devicemanager.h" -#include "scannediiocontextcollector.h" -#include "toolmanager.h" #include "detachedtoolwindowmanager.h" +#include "devicemanager.h" +#include "iioutil/cyclicaltask.h" +#include "iioutil/iioscantask.h" +#include "license_overlay.h" +#include "pluginbase/preferences.h" +#include "pluginbase/versionchecker.h" #include "pluginrepository.h" +#include "scannediiocontextcollector.h" #include "scopy-core_export.h" #include "scopyaboutpage.h" +#include "scopyhomepage.h" #include "scopypreferencespage.h" -#include "pluginbase/preferences.h" -#include "pluginbase/versionchecker.h" -#include "iioutil/cyclicaltask.h" -#include "iioutil/iioscantask.h" +#include "toolmanager.h" #include "versioncheckoverlay.h" +#include + QT_BEGIN_NAMESPACE -namespace Ui { class ScopyMainWindow; } +namespace Ui { +class ScopyMainWindow; +} QT_END_NAMESPACE namespace scopy { class ScopyMainWindow_API; @@ -50,8 +52,8 @@ public Q_SLOTS: void handlePreferences(QString, QVariant); private: - ScopyAboutPage* about; - ScopyPreferencesPage* prefPage; + ScopyAboutPage *about; + ScopyPreferencesPage *prefPage; PluginRepository *pr; ScopyHomePage *hp; DeviceManager *dm; @@ -72,8 +74,9 @@ public Q_SLOTS: void initPythonWIN32(); void loadDecoders(); void initApi(); + protected: void closeEvent(QCloseEvent *event) override; }; -} +} // namespace scopy #endif // SCOPYMAINWINDOW_H diff --git a/core/include/core/scopymainwindow_api.h b/core/include/core/scopymainwindow_api.h index e84bb1cb3c..50f13e2dbf 100644 --- a/core/include/core/scopymainwindow_api.h +++ b/core/include/core/scopymainwindow_api.h @@ -1,8 +1,8 @@ #ifndef SCOPYMAINWINDOW_API_H #define SCOPYMAINWINDOW_API_H -#include "scopymainwindow.h" #include "scopy-core_export.h" +#include "scopymainwindow.h" namespace scopy { class SCOPY_CORE_EXPORT ScopyMainWindow_API : public ApiObject @@ -21,11 +21,12 @@ class SCOPY_CORE_EXPORT ScopyMainWindow_API : public ApiObject Q_INVOKABLE void switchTool(QString devID, QString toolName); Q_INVOKABLE void switchTool(QString toolName); Q_INVOKABLE void runScript(QString content, QString fileName); + private: static bool sortByUUID(const QString &k1, const QString &k2); ScopyMainWindow *m_w; }; -} +} // namespace scopy #endif // SCOPYMAINWINDOW_API_H diff --git a/core/include/core/scopypreferencespage.h b/core/include/core/scopypreferencespage.h index 1442f5703d..bcc196d77a 100644 --- a/core/include/core/scopypreferencespage.h +++ b/core/include/core/scopypreferencespage.h @@ -1,9 +1,10 @@ #ifndef SCOPYPREFERENCESPAGE_H #define SCOPYPREFERENCESPAGE_H +#include "scopy-core_export.h" + #include #include -#include "scopy-core_export.h" namespace scopy { class SCOPY_CORE_EXPORT ScopyPreferencesPage : public QWidget @@ -12,10 +13,11 @@ class SCOPY_CORE_EXPORT ScopyPreferencesPage : public QWidget public: ScopyPreferencesPage(QWidget *parent = nullptr); ~ScopyPreferencesPage(); - QWidget* buildGeneralPreferencesPage(); + QWidget *buildGeneralPreferencesPage(); void addHorizontalTab(QWidget *w, QString text); private Q_SLOTS: void resetScopyPreferences(); + private: QTabWidget *tabWidget; void initRestartWidget(); @@ -26,5 +28,5 @@ private Q_SLOTS: void removeIniFiles(bool backup = true); void initUI(); }; -} +} // namespace scopy #endif // SCOPYPREFERENCESPAGE_H diff --git a/core/include/core/toolbrowser.h b/core/include/core/toolbrowser.h index 814ad5a949..2f611c022c 100644 --- a/core/include/core/toolbrowser.h +++ b/core/include/core/toolbrowser.h @@ -1,9 +1,11 @@ #ifndef TOOLBROWSER_H #define TOOLBROWSER_H +#include "scopy-core_export.h" + #include + #include -#include "scopy-core_export.h" namespace Ui { class ToolBrowser; @@ -12,12 +14,12 @@ class ToolBrowser; namespace scopy { class SCOPY_CORE_EXPORT ToolBrowser : public QWidget { - Q_OBJECT + Q_OBJECT public: explicit ToolBrowser(QWidget *parent = nullptr); ~ToolBrowser(); - ToolMenu* getToolMenu(); + ToolMenu *getToolMenu(); public Q_SLOTS: void toggleCollapse(); @@ -32,6 +34,6 @@ public Q_SLOTS: Ui::ToolBrowser *ui; void hideMenuText(bool collapesd); }; -} +} // namespace scopy #endif // TOOLBROWSER_H diff --git a/core/include/core/toolmanager.h b/core/include/core/toolmanager.h index f1e583e09d..646ff6662b 100644 --- a/core/include/core/toolmanager.h +++ b/core/include/core/toolmanager.h @@ -1,13 +1,14 @@ #ifndef TOOLMANAGER_H #define TOOLMANAGER_H -#include -#include -#include "toolmenu.h" #include "detachedtoolwindowmanager.h" #include "pluginbase/toolmenuentry.h" -#include "toolstack.h" #include "scopy-core_export.h" +#include "toolmenu.h" +#include "toolstack.h" + +#include +#include namespace scopy { @@ -15,13 +16,13 @@ class SCOPY_CORE_EXPORT ToolManager : public QObject { Q_OBJECT public: - ToolManager(ToolMenu* tm, ToolStack *ts, DetachedToolWindowManager *dwm,QObject *parent = nullptr); + ToolManager(ToolMenu *tm, ToolStack *ts, DetachedToolWindowManager *dwm, QObject *parent = nullptr); ~ToolManager(); public Q_SLOTS: - void addToolList(QString, QList); - void removeToolList(QString); - void changeToolListContents(QString, QList); + void addToolList(QString, QList); + void removeToolList(QString); + void changeToolListContents(QString, QList); void showToolList(QString); void hideToolList(QString); void lockToolList(QString); @@ -31,7 +32,7 @@ public Q_SLOTS: void updateToolEntry(); void updateToolAttached(bool old); - void updateTool(QWidget* old); + void updateTool(QWidget *old); void showTool(QString id); void toggleAttach(QString id); @@ -39,13 +40,13 @@ public Q_SLOTS: void requestTool(QString id); private: - void saveToolAttachedState(ToolMenuEntry *tme); void loadToolAttachedState(ToolMenuEntry *tme); - typedef struct { + typedef struct + { QString id; - QList tools; + QList tools; bool lock; } st; @@ -56,6 +57,6 @@ public Q_SLOTS: ToolStack *ts; DetachedToolWindowManager *dwm; }; -} +} // namespace scopy #endif // TOOLMANAGER_H diff --git a/core/include/core/toolmenu.h b/core/include/core/toolmenu.h index b2f293b1bd..bd31ae8806 100644 --- a/core/include/core/toolmenu.h +++ b/core/include/core/toolmenu.h @@ -22,12 +22,12 @@ #define TOOLMENU_H #include "gui/basemenu.h" +#include "scopy-core_export.h" #include "toolmenuitem.h" -#include -#include #include -#include "scopy-core_export.h" +#include +#include namespace scopy { /** @@ -38,7 +38,7 @@ class SCOPY_CORE_EXPORT ToolMenu : public BaseMenu Q_OBJECT public: explicit ToolMenu(QWidget *parent = nullptr); - ~ToolMenu(); + ~ToolMenu(); ToolMenuItem *getToolMenuItemFor(QString toolId); ToolMenuItem *addTool(QString id, QString name, QString icon, int position = -1); @@ -60,10 +60,9 @@ public Q_SLOTS: void attachSuccesful(QString); private: - QVector tools; + QVector tools; QButtonGroup *buttonGroup; - private Q_SLOTS: void _updateToolList(short from, short to); @@ -71,6 +70,6 @@ private Q_SLOTS: void _saveState(); void _loadState(); }; -} +} // namespace scopy #endif // TOOLMENU_H diff --git a/core/include/core/toolmenuitem.h b/core/include/core/toolmenuitem.h index 072dac5a1f..eb8893c48d 100644 --- a/core/include/core/toolmenuitem.h +++ b/core/include/core/toolmenuitem.h @@ -53,7 +53,6 @@ class SCOPY_CORE_EXPORT ToolMenuItem : public BaseMenuItem Q_SIGNALS: void doubleclick(); - public Q_SLOTS: void setDisabled(bool disabled); @@ -65,6 +64,7 @@ public Q_SLOTS: void dragLeaveEvent(QDragLeaveEvent *event); void mouseMoveEvent(QMouseEvent *event); + private: QPushButton *toolBtn; CustomPushButton *toolRunBtn; @@ -76,5 +76,5 @@ public Q_SLOTS: private: void _buildUI(); }; -} +} // namespace scopy #endif // TOOLMENUITEM_H diff --git a/core/include/core/toolstack.h b/core/include/core/toolstack.h index 523f5be681..2894b96b8d 100644 --- a/core/include/core/toolstack.h +++ b/core/include/core/toolstack.h @@ -2,9 +2,10 @@ #define TOOLSTACK_H #include "gui/mapstackedwidget.h" -#include #include "scopy-core_export.h" +#include + namespace Ui { class SCOPY_CORE_EXPORT ToolStack; } @@ -20,6 +21,6 @@ class SCOPY_CORE_EXPORT ToolStack : public MapStackedWidget explicit ToolStack(QWidget *parent = nullptr); ~ToolStack(); }; -} +} // namespace scopy #endif // TOOLSTACK_H diff --git a/core/include/core/translationsrepository.h b/core/include/core/translationsrepository.h index 1aa323c063..c132e28604 100644 --- a/core/include/core/translationsrepository.h +++ b/core/include/core/translationsrepository.h @@ -1,9 +1,10 @@ #ifndef TRANSLATIONS_CONTROLLER #define TRANSLATIONS_CONTROLLER -#include #include "scopy-core_export.h" +#include + namespace scopy { class SCOPY_CORE_EXPORT TranslationsRepository : public QObject { @@ -19,8 +20,8 @@ class SCOPY_CORE_EXPORT TranslationsRepository : public QObject void loadTranslations(QString language); private: - static TranslationsRepository * pinstance_; + static TranslationsRepository *pinstance_; }; -} +} // namespace scopy #endif // TRANSLATIONS_CONTROLLER diff --git a/core/include/core/versioncheckoverlay.h b/core/include/core/versioncheckoverlay.h index be5631c29a..ec46bfefe6 100644 --- a/core/include/core/versioncheckoverlay.h +++ b/core/include/core/versioncheckoverlay.h @@ -1,19 +1,21 @@ #ifndef SCOPY_VERSIONCHECKOVERLAY_H #define SCOPY_VERSIONCHECKOVERLAY_H +#include #include + #include -#include namespace scopy { -class VersionCheckOverlay : public PopupWidget { +class VersionCheckOverlay : public PopupWidget +{ Q_OBJECT public: - explicit VersionCheckOverlay(QWidget* parent = nullptr); + explicit VersionCheckOverlay(QWidget *parent = nullptr); ~VersionCheckOverlay(); void showOverlay(); }; -} +} // namespace scopy -#endif //SCOPY_VERSIONCHECKOVERLAY_H +#endif // SCOPY_VERSIONCHECKOVERLAY_H diff --git a/core/src/application_restarter.cpp b/core/src/application_restarter.cpp index e8d9761cfd..95ce205559 100644 --- a/core/src/application_restarter.cpp +++ b/core/src/application_restarter.cpp @@ -1,16 +1,16 @@ #include "application_restarter.h" #include -#include #include +#include #ifdef __ANDROID__ - #include +#include #endif using namespace scopy; -ApplicationRestarter* ApplicationRestarter::pinstance_{nullptr}; +ApplicationRestarter *ApplicationRestarter::pinstance_{nullptr}; ApplicationRestarter::ApplicationRestarter(const QString &executable) : m_executable(executable) @@ -20,24 +20,15 @@ ApplicationRestarter::ApplicationRestarter(const QString &executable) pinstance_ = this; } -ApplicationRestarter *ApplicationRestarter::GetInstance() -{ - return pinstance_; -} +ApplicationRestarter *ApplicationRestarter::GetInstance() { return pinstance_; } -void ApplicationRestarter::setArguments(const QStringList &arguments) -{ - m_arguments = arguments; -} +void ApplicationRestarter::setArguments(const QStringList &arguments) { m_arguments = arguments; } -QStringList ApplicationRestarter::getArguments() const -{ - return m_arguments; -} +QStringList ApplicationRestarter::getArguments() const { return m_arguments; } int ApplicationRestarter::restart(int exitCode) { - if (m_restart) { + if(m_restart) { #ifdef __ANDROID__ QAndroidJniObject activity = QtAndroid::androidActivity(); activity.callMethod("restart"); diff --git a/core/src/cmdlinehandler.cpp b/core/src/cmdlinehandler.cpp index d3a76e6c1a..d1bdddabab 100644 --- a/core/src/cmdlinehandler.cpp +++ b/core/src/cmdlinehandler.cpp @@ -2,17 +2,17 @@ using namespace scopy; -FILE* CmdLineHandler::logFile_{nullptr}; +FILE *CmdLineHandler::logFile_{nullptr}; int CmdLineHandler::handle(QCommandLineParser &parser, ScopyMainWindow_API &scopyApi) { bool acceptLicense = parser.isSet("accept-license"); - if (acceptLicense) { + if(acceptLicense) { scopyApi.acceptLicense(); } QString param = parser.value("connect"); - if (!param.isEmpty()) { + if(!param.isEmpty()) { QString deviceID = ""; deviceID = scopyApi.addDevice("", param); scopyApi.connectDevice(deviceID); @@ -23,53 +23,51 @@ int CmdLineHandler::handle(QCommandLineParser &parser, ScopyMainWindow_API &scop } QString scriptPath = parser.value("script"); - if (!scriptPath.isEmpty()) { + if(!scriptPath.isEmpty()) { QFile file(scriptPath); - if (!file.open(QFile::ReadOnly)) { + if(!file.open(QFile::ReadOnly)) { qCritical() << "Unable to open script file"; return EXIT_FAILURE; } QTextStream stream(&file); QString firstLine = stream.readLine(); - if (!firstLine.startsWith("#!")) + if(!firstLine.startsWith("#!")) stream.seek(0); QString content = stream.readAll(); file.close(); - QMetaObject::invokeMethod(&scopyApi, "runScript", Qt::QueuedConnection, - Q_ARG(QString, content), + QMetaObject::invokeMethod(&scopyApi, "runScript", Qt::QueuedConnection, Q_ARG(QString, content), Q_ARG(QString, scriptPath)); } return EXIT_SUCCESS; } - void CmdLineHandler::withLogFileOption(QCommandLineParser &parser) +void CmdLineHandler::withLogFileOption(QCommandLineParser &parser) { QString fileName = parser.value("logfile"); - if (!fileName.isEmpty()) { + if(!fileName.isEmpty()) { QString filePath = scopy::config::settingsFolderPath() + "/" + fileName; logFile_ = fopen(filePath.toStdString().c_str(), "w"); - if (logFile_) { + if(logFile_) { qInstallMessageHandler(logOutputHandler); } } - } +} - void CmdLineHandler::closeLogFile() - { - if (logFile_) { +void CmdLineHandler::closeLogFile() +{ + if(logFile_) { fclose(logFile_); - logFile_=nullptr; + logFile_ = nullptr; } - } +} void CmdLineHandler::logOutputHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QString message = qFormatLogMessage(type, context, msg); fprintf(stderr, "%s\n", message.toStdString().c_str()); - if (logFile_) { + if(logFile_) { fprintf(logFile_, "%s\n", message.toStdString().c_str()); } } - diff --git a/core/src/detachedtoolwindow.cpp b/core/src/detachedtoolwindow.cpp index 341a5fad5d..1949e7a630 100644 --- a/core/src/detachedtoolwindow.cpp +++ b/core/src/detachedtoolwindow.cpp @@ -1,14 +1,18 @@ #include "detachedtoolwindow.h" -#include -#include + #include +#include #include #include -Q_LOGGING_CATEGORY(CAT_DETACHEDTOOL,"DetachedToolWindow") +#include + +Q_LOGGING_CATEGORY(CAT_DETACHEDTOOL, "DetachedToolWindow") using namespace scopy; -DetachedToolWindow::DetachedToolWindow(QWidget *parent, ToolMenuEntry *tme) : QWidget(parent) { +DetachedToolWindow::DetachedToolWindow(QWidget *parent, ToolMenuEntry *tme) + : QWidget(parent) +{ this->tme = tme; @@ -17,49 +21,55 @@ DetachedToolWindow::DetachedToolWindow(QWidget *parent, ToolMenuEntry *tme) : QW lay->setMargin(0); w = tme->tool(); setWindowIcon(QApplication::windowIcon()); - setWindowTitle("Scopy - "+tme->pluginName()+" - " + tme->name()); + setWindowTitle("Scopy - " + tme->pluginName() + " - " + tme->name()); lay->addWidget(w); - loadToolGeometry(tme,this); + loadToolGeometry(tme, this); tme->tool()->show(); show(); } -DetachedToolWindow::~DetachedToolWindow() { - saveToolGeometry(tme,this); +DetachedToolWindow::~DetachedToolWindow() +{ + saveToolGeometry(tme, this); w->setParent(nullptr); } -void DetachedToolWindow::closeEvent(QCloseEvent *event) { - saveToolGeometry(tme,w); +void DetachedToolWindow::closeEvent(QCloseEvent *event) +{ + saveToolGeometry(tme, w); tme->setAttached(true); } -void DetachedToolWindow::saveToolGeometry(ToolMenuEntry *tme, QWidget *w) { +void DetachedToolWindow::saveToolGeometry(ToolMenuEntry *tme, QWidget *w) +{ Preferences *p = Preferences::GetInstance(); if(!p->get("general_save_attached").toBool()) return; QString prefId; if(w) { - prefId = tme->id()+"_geometry"; + prefId = tme->id() + "_geometry"; QRect geometry = w->geometry(); p->set(prefId, geometry); - qDebug(CAT_DETACHEDTOOL)<<"Saving " << prefId << " " << geometry; + qDebug(CAT_DETACHEDTOOL) << "Saving " << prefId << " " << geometry; } } -void DetachedToolWindow::loadToolGeometry(ToolMenuEntry *tme, QWidget *w) { +void DetachedToolWindow::loadToolGeometry(ToolMenuEntry *tme, QWidget *w) +{ Preferences *p = Preferences::GetInstance(); if(!p->get("general_save_attached").toBool()) return; QString prefId; if(w && !tme->attached()) { - prefId = tme->id()+"_geometry"; + prefId = tme->id() + "_geometry"; QRect geometry = p->get(prefId).toRect(); if(!geometry.isNull()) w->setGeometry(geometry); - qDebug(CAT_DETACHEDTOOL)<<"Loading " <tool()->geometry(); + qDebug(CAT_DETACHEDTOOL) << "Loading " << prefId << tme->tool()->geometry(); } } + +#include "moc_detachedtoolwindow.cpp" diff --git a/core/src/detachedtoolwindowmanager.cpp b/core/src/detachedtoolwindowmanager.cpp index 260d65909c..440e151a35 100644 --- a/core/src/detachedtoolwindowmanager.cpp +++ b/core/src/detachedtoolwindowmanager.cpp @@ -2,15 +2,18 @@ using namespace scopy; -DetachedToolWindowManager::DetachedToolWindowManager(QObject *parent) : QObject(parent) {} +DetachedToolWindowManager::DetachedToolWindowManager(QObject *parent) + : QObject(parent) +{} DetachedToolWindowManager::~DetachedToolWindowManager() {} -void DetachedToolWindowManager::add(QString id, ToolMenuEntry *tme) { +void DetachedToolWindowManager::add(QString id, ToolMenuEntry *tme) +{ if(map.contains(id)) { delete map.take(id); } - map.insert(id, new DetachedToolWindow(nullptr,tme)); + map.insert(id, new DetachedToolWindow(nullptr, tme)); } bool DetachedToolWindowManager::remove(QString id) @@ -22,7 +25,8 @@ bool DetachedToolWindowManager::remove(QString id) return false; } -void DetachedToolWindowManager::show(QString id) { +void DetachedToolWindowManager::show(QString id) +{ if(map.contains(id)) { map[id]->raise(); map[id]->show(); @@ -36,8 +40,6 @@ QWidget *DetachedToolWindowManager::getWidget(QString key) return nullptr; } +bool DetachedToolWindowManager::contains(QString key) { return map.contains(key); } -bool DetachedToolWindowManager::contains(QString key) { - return map.contains(key); -} - +#include "moc_detachedtoolwindowmanager.cpp" diff --git a/core/src/devicebrowser.cpp b/core/src/devicebrowser.cpp index 1be9d22a05..f04dd86b41 100644 --- a/core/src/devicebrowser.cpp +++ b/core/src/devicebrowser.cpp @@ -1,18 +1,21 @@ #include "devicebrowser.h" + +#include "deviceicon.h" #include "deviceiconimpl.h" +#include "dynamicWidget.h" +#include "stylehelper.h" + #include "ui_devicebrowser.h" -#include + #include -#include "deviceicon.h" -#include "stylehelper.h" -#include "dynamicWidget.h" +#include Q_LOGGING_CATEGORY(CAT_DEVBROWSER, "DeviceBrowser") using namespace scopy; -DeviceBrowser::DeviceBrowser(QWidget *parent) : - QWidget(parent), - ui(new Ui::DeviceBrowser) +DeviceBrowser::DeviceBrowser(QWidget *parent) + : QWidget(parent) + , ui(new Ui::DeviceBrowser) { qDebug(CAT_DEVBROWSER) << "ctor"; ui->setupUi(this); @@ -23,9 +26,9 @@ DeviceBrowser::DeviceBrowser(QWidget *parent) : initBtns(); - connect(ui->btnHome, SIGNAL(clicked()),this, SLOT(forwardRequestDeviceWithDirection())); - connect(ui->btnAdd, SIGNAL(clicked()),this, SLOT(forwardRequestDeviceWithDirection())); - connect(this,SIGNAL(requestDevice(QString,int)),this,SLOT(updateSelectedDeviceIdx(QString))); + connect(ui->btnHome, SIGNAL(clicked()), this, SLOT(forwardRequestDeviceWithDirection())); + connect(ui->btnAdd, SIGNAL(clicked()), this, SLOT(forwardRequestDeviceWithDirection())); + connect(this, SIGNAL(requestDevice(QString, int)), this, SLOT(updateSelectedDeviceIdx(QString))); } DeviceBrowser::~DeviceBrowser() @@ -38,13 +41,13 @@ void DeviceBrowser::initBtns() { StyleHelper::FrameBackgroundShadow(ui->containerHome); StyleHelper::FrameBackgroundShadow(ui->containerAdd); - + bg = new QButtonGroup(this); bg->addButton(ui->btnAdd); bg->addButton(ui->btnHome); - ui->btnHome->setProperty(devBrowserId,"home"); - ui->btnAdd->setProperty(devBrowserId,"add"); + ui->btnHome->setProperty(devBrowserId, "home"); + ui->btnAdd->setProperty(devBrowserId, "add"); list.append(ui->btnHome); list.append(ui->btnAdd); ui->btnHome->setChecked(true); @@ -62,24 +65,24 @@ QAbstractButton *DeviceBrowser::getDeviceWidgetFor(QString id) return nullptr; } -void DeviceBrowser::addDevice(QString id, Device *d,int position) +void DeviceBrowser::addDevice(QString id, Device *d, int position) { - qInfo(CAT_DEVBROWSER)<<"adding device " << id; - auto w = dynamic_cast(buildDeviceIcon(d, this)); - w->setProperty(devBrowserId,id); - layout->insertWidget(position,w); + qInfo(CAT_DEVBROWSER) << "adding device " << id; + auto w = dynamic_cast(buildDeviceIcon(d, this)); + w->setProperty(devBrowserId, id); + layout->insertWidget(position, w); bg->addButton(w); if(position == -1) list.append(w); else - list.insert(position,w); + list.insert(position, w); connect(w, &QAbstractButton::clicked, this, &DeviceBrowser::forwardRequestDeviceWithDirection); } void DeviceBrowser::removeDevice(QString id) { - qInfo(CAT_DEVBROWSER)<<"removing device " << id; + qInfo(CAT_DEVBROWSER) << "removing device " << id; QAbstractButton *w = getDeviceWidgetFor(id); layout->removeWidget(w); bg->removeButton(w); @@ -90,25 +93,22 @@ void DeviceBrowser::removeDevice(QString id) if(currentIdx == idx) { // removed currently selected device currentIdx = 0; - Q_EMIT requestDevice("home",-1); - } else if(currentIdx>idx) { + Q_EMIT requestDevice("home", -1); + } else if(currentIdx > idx) { currentIdx--; } } - int DeviceBrowser::getIndexOfId(QString k) { - for(int i = 0;iproperty(devBrowserId) == k) return i; } return -1; } -QString DeviceBrowser::getIdOfIndex(int idx){ - return (list[idx]->property(devBrowserId).toString()); -} +QString DeviceBrowser::getIdOfIndex(int idx) { return (list[idx]->property(devBrowserId).toString()); } void DeviceBrowser::nextDevice() { @@ -122,7 +122,7 @@ void DeviceBrowser::nextDevice() QString nextId = getIdOfIndex(nextIdx); Q_EMIT requestDevice(nextId, 1); // start animation - list[nextIdx]->setChecked(true); // set checked afterwards + list[nextIdx]->setChecked(true); // set checked afterwards } void DeviceBrowser::prevDevice() @@ -149,49 +149,47 @@ void DeviceBrowser::forwardRequestDeviceWithDirection() } void DeviceBrowser::updateSelectedDeviceIdx(QString k) -{ - int prevIdx = currentIdx; // local, just for debug +{ + int prevIdx = currentIdx; // local, just for debug currentIdx = getIndexOfId(k); - QWidget* prevDevice = getDeviceWidgetFor(getIdOfIndex(prevIdx)); - QWidget* currentDevice = getDeviceWidgetFor(getIdOfIndex(currentIdx)); + QWidget *prevDevice = getDeviceWidgetFor(getIdOfIndex(prevIdx)); + QWidget *currentDevice = getDeviceWidgetFor(getIdOfIndex(currentIdx)); // hackish -- the btnHome and btnAdd already have a background color so their container must display the shadow - if (currentDevice == ui->btnHome) + if(currentDevice == ui->btnHome) currentDevice = ui->containerHome; - if (currentDevice == ui->btnAdd) + if(currentDevice == ui->btnAdd) currentDevice = ui->containerAdd; - if (prevDevice == ui->btnHome) + if(prevDevice == ui->btnHome) prevDevice = ui->containerHome; - if (prevDevice == ui->btnAdd) + if(prevDevice == ui->btnAdd) prevDevice = ui->containerAdd; setDynamicProperty(prevDevice, "selected", false); setDynamicProperty(currentDevice, "selected", true); - qDebug(CAT_DEVBROWSER)<<"prev: " - << "["< current: " - << "["< current: " + << "[" << currentIdx << "] -" << getIdOfIndex(currentIdx); } -void DeviceBrowser::connectDevice(QString id) { - auto w = dynamic_cast(getDeviceWidgetFor(id)); +void DeviceBrowser::connectDevice(QString id) +{ + auto w = dynamic_cast(getDeviceWidgetFor(id)); w->setConnected(true); } -void DeviceBrowser::disconnectDevice(QString id) { - auto w = dynamic_cast(getDeviceWidgetFor(id)); +void DeviceBrowser::disconnectDevice(QString id) +{ + auto w = dynamic_cast(getDeviceWidgetFor(id)); w->setConnected(false); } -DeviceIcon* DeviceBrowser::buildDeviceIcon(Device *d, QWidget *parent) { - return new DeviceIconImpl(d, parent); -} +DeviceIcon *DeviceBrowser::buildDeviceIcon(Device *d, QWidget *parent) { return new DeviceIconImpl(d, parent); } /* auto &&is = ui->wInfoPageStack; @@ -212,7 +210,6 @@ DeviceIcon* DeviceBrowser::buildDeviceIcon(Device *d, QWidget *parent) { w1->setVisible(false); */ - /* ui->setupUi(this); auto &&is = ui->wInfoPageStack; @@ -233,5 +230,4 @@ DeviceIcon* DeviceBrowser::buildDeviceIcon(Device *d, QWidget *parent) { w1->setVisible(false); */ - #include "moc_devicebrowser.cpp" diff --git a/core/src/devicefactory.cpp b/core/src/devicefactory.cpp index 82f5e6211b..640e2ce25f 100644 --- a/core/src/devicefactory.cpp +++ b/core/src/devicefactory.cpp @@ -1,9 +1,9 @@ #include "devicefactory.h" + #include "iiodeviceimpl.h" using namespace scopy; - DeviceImpl *DeviceFactory::build(QString param, PluginManager *pm, QString category, QObject *parent) { QString cat = category.toLower(); @@ -13,3 +13,5 @@ DeviceImpl *DeviceFactory::build(QString param, PluginManager *pm, QString categ return new DeviceImpl(param, pm, category, parent); } } + +#include "moc_devicefactory.cpp" diff --git a/core/src/deviceiconimpl.cpp b/core/src/deviceiconimpl.cpp index fa3ac12079..8942bdc241 100644 --- a/core/src/deviceiconimpl.cpp +++ b/core/src/deviceiconimpl.cpp @@ -1,12 +1,15 @@ #include "deviceiconimpl.h" -#include -#include -#include -#include + #include "gui/dynamicWidget.h" #include "stylehelper.h" + #include "ui_devicebutton.h" +#include +#include +#include +#include + using namespace scopy; DeviceIconImpl::DeviceIconImpl(Device *d, QWidget *parent) : DeviceIcon{parent} @@ -17,12 +20,13 @@ DeviceIconImpl::DeviceIconImpl(Device *d, QWidget *parent) ui->description->setText(d->displayParam()); ui->name->setText(d->displayName()); ui->iconPlaceHolder->layout()->addWidget(d->icon()); - ui->iconPlaceHolder->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding ); + ui->iconPlaceHolder->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setCheckable(true); } -void DeviceIconImpl::setConnected(bool val) { +void DeviceIconImpl::setConnected(bool val) +{ setDynamicProperty(ui->line, "connected", val); // ensurePolished(); } diff --git a/core/src/deviceimpl.cpp b/core/src/deviceimpl.cpp index 4140d9928c..c4ec6dced0 100644 --- a/core/src/deviceimpl.cpp +++ b/core/src/deviceimpl.cpp @@ -1,38 +1,42 @@ #include "deviceimpl.h" + +#include "logging_categories.h" #include "pluginbase/preferences.h" #include "qboxlayout.h" #include "qpushbutton.h" +#include "qscrollarea.h" + +#include "ui_devicepage.h" + +#include #include -#include #include -#include +#include #include + #include #include -#include "qscrollarea.h" -#include "ui_devicepage.h" -#include "logging_categories.h" Q_LOGGING_CATEGORY(CAT_DEVICEIMPL, "Device") namespace scopy { -DeviceImpl::DeviceImpl(QString param, PluginManager *p, QString category ,QObject *parent) - : QObject{parent}, - m_param(param), - m_category(category), - p(p) +DeviceImpl::DeviceImpl(QString param, PluginManager *p, QString category, QObject *parent) + : QObject{parent} + , m_param(param) + , m_category(category) + , p(p) { - m_id = "dev_"+category+"_"+param+"_"+scopy::config::getUuid(); - qDebug(CAT_DEVICEIMPL)<< m_param <<"ctor"; + m_id = "dev_" + category + "_" + param + "_" + scopy::config::getUuid(); + qDebug(CAT_DEVICEIMPL) << m_param << "ctor"; } void DeviceImpl::init() { QElapsedTimer timer; timer.start(); - m_plugins = p->getCompatiblePlugins(m_param,m_category); - for (Plugin *p : qAsConst(m_plugins)) { - QObject* obj = dynamic_cast(p); + m_plugins = p->getCompatiblePlugins(m_param, m_category); + for(Plugin *p : qAsConst(m_plugins)) { + QObject *obj = dynamic_cast(p); if(obj) { obj->setParent(this); } else { @@ -42,13 +46,15 @@ void DeviceImpl::init() qInfo(CAT_BENCHMARK) << this->displayName() << " init took: " << timer.elapsed() << "ms"; } -void DeviceImpl::preload() { +void DeviceImpl::preload() +{ for(auto &p : m_plugins) { p->preload(); } } -void DeviceImpl::loadPlugins() { +void DeviceImpl::loadPlugins() +{ QElapsedTimer timer; timer.start(); removeDisabledPlugins(); @@ -58,58 +64,60 @@ void DeviceImpl::loadPlugins() { loadBadges(); loadPages(); loadToolList(); - if (m_plugins.isEmpty()) { + if(m_plugins.isEmpty()) { connbtn->hide(); } for(auto &p : m_plugins) { - connect(dynamic_cast(p),SIGNAL(connectDevice()),this,SLOT(connectDev())); - connect(dynamic_cast(p),SIGNAL(disconnectDevice()),this,SLOT(disconnectDev())); - connect(dynamic_cast(p),SIGNAL(toolListChanged()),this,SIGNAL(toolListChanged())); - connect(dynamic_cast(p),SIGNAL(restartDevice()),this,SIGNAL(requestedRestart())); - connect(dynamic_cast(p),SIGNAL(requestToolByUuid(QString)),this,SIGNAL(requestTool(QString))); + connect(dynamic_cast(p), SIGNAL(connectDevice()), this, SLOT(connectDev())); + connect(dynamic_cast(p), SIGNAL(disconnectDevice()), this, SLOT(disconnectDev())); + connect(dynamic_cast(p), SIGNAL(toolListChanged()), this, SIGNAL(toolListChanged())); + connect(dynamic_cast(p), SIGNAL(restartDevice()), this, SIGNAL(requestedRestart())); + connect(dynamic_cast(p), SIGNAL(requestToolByUuid(QString)), this, + SIGNAL(requestTool(QString))); p->postload(); } qInfo(CAT_BENCHMARK) << this->displayName() << " plugins load took: " << timer.elapsed() << "ms"; } -void DeviceImpl::unloadPlugins() { +void DeviceImpl::unloadPlugins() +{ QElapsedTimer timer; timer.start(); - QList::const_iterator pI = m_plugins.constEnd(); + QList::const_iterator pI = m_plugins.constEnd(); while(pI != m_plugins.constBegin()) { --pI; - disconnect(dynamic_cast(*pI),SIGNAL(connectDevice()),this,SLOT(connectDev())); - disconnect(dynamic_cast(*pI),SIGNAL(disconnectDevice()),this,SLOT(disconnectDev())); - disconnect(dynamic_cast(*pI),SIGNAL(toolListChanged()),this,SIGNAL(toolListChanged())); - disconnect(dynamic_cast(*pI),SIGNAL(restartDevice()),this,SIGNAL(requestedRestart())); - disconnect(dynamic_cast(*pI),SIGNAL(requestToolByUuid(QString)),this,SIGNAL(requestTool(QString))); + disconnect(dynamic_cast(*pI), SIGNAL(connectDevice()), this, SLOT(connectDev())); + disconnect(dynamic_cast(*pI), SIGNAL(disconnectDevice()), this, SLOT(disconnectDev())); + disconnect(dynamic_cast(*pI), SIGNAL(toolListChanged()), this, SIGNAL(toolListChanged())); + disconnect(dynamic_cast(*pI), SIGNAL(restartDevice()), this, SIGNAL(requestedRestart())); + disconnect(dynamic_cast(*pI), SIGNAL(requestToolByUuid(QString)), this, + SIGNAL(requestTool(QString))); (*pI)->unload(); - delete (*pI); + delete(*pI); } m_plugins.clear(); qInfo(CAT_BENCHMARK) << this->displayName() << " plugins unload took: " << timer.elapsed() << "ms"; } -bool DeviceImpl::verify() -{ - return true; -} +bool DeviceImpl::verify() { return true; } QMap DeviceImpl::readDeviceInfo() { QMap map; - return map; + return map; } -void DeviceImpl::removeDisabledPlugins() { - QMutableListIterator i(m_plugins); - while (i.hasNext()) { - if (i.next()->enabled() == false) +void DeviceImpl::removeDisabledPlugins() +{ + QMutableListIterator i(m_plugins); + while(i.hasNext()) { + if(i.next()->enabled() == false) i.remove(); } } -void DeviceImpl::loadName() { +void DeviceImpl::loadName() +{ if(m_plugins.count()) { m_displayName = m_plugins[0]->displayName(); m_displayParam = m_plugins[0]->displayParam(); @@ -118,22 +126,24 @@ void DeviceImpl::loadName() { } } -void DeviceImpl::loadIcons() { +void DeviceImpl::loadIcons() +{ m_icon = new QWidget(); m_icon->setFixedHeight(100); m_icon->setFixedWidth(100); new QHBoxLayout(m_icon); - for( auto &p : m_plugins) { + for(auto &p : m_plugins) { if(p->loadIcon()) { m_icon->layout()->addWidget(p->icon()); return; } } - new QLabel("No PLUGIN",m_icon); + new QLabel("No PLUGIN", m_icon); } -void DeviceImpl::loadPages() { +void DeviceImpl::loadPages() +{ m_page = new QWidget(); Ui::DevicePage *ui = new Ui::DevicePage(); ui->setupUi(m_page); @@ -146,31 +156,31 @@ void DeviceImpl::loadPages() { auto m_scrollAreaContents = ui->m_scrollAreaContents; auto m_scrollAreaLayout = ui->m_scrollAreaLayout; - connbtn->setProperty("device_page",true); - connbtn->setProperty("blue_button",true); + connbtn->setProperty("device_page", true); + connbtn->setProperty("blue_button", true); connbtn->setAutoDefault(true); m_buttonLayout->addWidget(connbtn); - discbtn->setProperty("device_page",true); - discbtn->setProperty("blue_button",true); + discbtn->setProperty("device_page", true); + discbtn->setProperty("blue_button", true); discbtn->setAutoDefault(true); m_buttonLayout->addWidget(discbtn); discbtn->setVisible(false); - connect(connbtn,&QPushButton::clicked,this,&DeviceImpl::connectDev); - connect(discbtn,&QPushButton::clicked,this,&DeviceImpl::disconnectDev); + connect(connbtn, &QPushButton::clicked, this, &DeviceImpl::connectDev); + connect(discbtn, &QPushButton::clicked, this, &DeviceImpl::disconnectDev); connect(this, &DeviceImpl::connectionFailed, this, &DeviceImpl::onConnectionFailed); for(auto &&p : plugins()) { if(p->loadExtraButtons()) { for(auto &&b : p->extraButtons()) { b->setProperty("blue_button", true); - b->setProperty("device_page",true); + b->setProperty("device_page", true); m_buttonLayout->addWidget(b); } } } - m_buttonLayout->addSpacerItem(new QSpacerItem(40,40,QSizePolicy::Expanding)); + m_buttonLayout->addSpacerItem(new QSpacerItem(40, 40, QSizePolicy::Expanding)); for(auto &&p : plugins()) { if(p->loadPage()) { @@ -179,7 +189,8 @@ void DeviceImpl::loadPages() { } } -void DeviceImpl::loadToolList() { +void DeviceImpl::loadToolList() +{ for(auto &&p : m_plugins) { p->loadToolList(); } @@ -202,7 +213,7 @@ void DeviceImpl::loadBadges() warningBtn->setMaximumSize(25, 25); warningBtn->setIcon(QIcon(":/gui/icons/warning.svg")); warningBtn->setToolTip(tr("The device is not available!\n" - "Verify the connection!")); + "Verify the connection!")); HoverWidget *warningHover = new HoverWidget(warningBtn, m_icon, m_icon); warningHover->setStyleSheet("background-color: transparent; border: 0px;"); warningHover->setAnchorPos(HoverPosition::HP_TOPRIGHT); @@ -212,48 +223,47 @@ void DeviceImpl::loadBadges() connect(this, &DeviceImpl::connected, warningHover, &HoverWidget::hide); } -void DeviceImpl::onConnectionFailed() -{ - disconnectDev(); -} +void DeviceImpl::onConnectionFailed() { disconnectDev(); } -QList DeviceImpl::plugins() const -{ - return m_plugins; -} +QList DeviceImpl::plugins() const { return m_plugins; } -void DeviceImpl::showPage() { +void DeviceImpl::showPage() +{ for(auto &&p : m_plugins) p->showPageCallback(); - if (connbtn->isHidden()) { + if(connbtn->isHidden()) { discbtn->setFocus(); } else { connbtn->setFocus(); } } -void DeviceImpl::hidePage() { +void DeviceImpl::hidePage() +{ for(auto &&p : m_plugins) p->hidePageCallback(); } -void DeviceImpl::save(QSettings &s) { - for(Plugin* p : qAsConst(m_plugins)) { +void DeviceImpl::save(QSettings &s) +{ + for(Plugin *p : qAsConst(m_plugins)) { s.beginGroup(p->name()); p->saveSettings(s); s.endGroup(); } } -void DeviceImpl::load(QSettings &s) { - for(Plugin* p : qAsConst(m_plugins)) { +void DeviceImpl::load(QSettings &s) +{ + for(Plugin *p : qAsConst(m_plugins)) { s.beginGroup(p->name()); p->loadSettings(s); s.endGroup(); } } -void DeviceImpl::connectDev() { +void DeviceImpl::connectDev() +{ QElapsedTimer pluginTimer; QElapsedTimer timer; timer.start(); @@ -263,20 +273,21 @@ void DeviceImpl::connectDev() { pluginTimer.start(); bool pluginConnectionSucceeded = p->onConnect(); qInfo(CAT_BENCHMARK) << p->name() << " connection took: " << pluginTimer.elapsed() << "ms"; - if (pluginConnectionSucceeded) { + if(pluginConnectionSucceeded) { if(pref->get("general_save_session").toBool()) { - QSettings s = QSettings(scopy::config::settingsFolderPath() + "/" +p->name() +".ini", QSettings::IniFormat); + QSettings s = QSettings(scopy::config::settingsFolderPath() + "/" + p->name() + ".ini", + QSettings::IniFormat); p->loadSettings(s); } m_connectedPlugins.push_back(p); } else { disconnectDevice = p->metadata().value("disconnectDevOnConnectFailure").toBool(); - if (disconnectDevice) { + if(disconnectDevice) { break; } } } - if (disconnectDevice || m_connectedPlugins.isEmpty()) { + if(disconnectDevice || m_connectedPlugins.isEmpty()) { Q_EMIT connectionFailed(); } else { connbtn->hide(); @@ -287,7 +298,8 @@ void DeviceImpl::connectDev() { qInfo(CAT_BENCHMARK) << this->displayName() << " device connection took: " << timer.elapsed() << "ms"; } -void DeviceImpl::disconnectDev() { +void DeviceImpl::disconnectDev() +{ QElapsedTimer pluginTimer; QElapsedTimer timer; timer.start(); @@ -296,7 +308,8 @@ void DeviceImpl::disconnectDev() { Preferences *pref = Preferences::GetInstance(); for(auto &&p : m_connectedPlugins) { if(pref->get("general_save_session").toBool()) { - QSettings s = QSettings(scopy::config::settingsFolderPath() + "/" +p->name() +".ini", QSettings::IniFormat); + QSettings s = QSettings(scopy::config::settingsFolderPath() + "/" + p->name() + ".ini", + QSettings::IniFormat); p->saveSettings(s); } pluginTimer.start(); @@ -309,51 +322,26 @@ void DeviceImpl::disconnectDev() { qInfo(CAT_BENCHMARK) << this->displayName() << " device disconnection took: " << timer.elapsed() << "ms"; } -DeviceImpl::~DeviceImpl() { - - qDebug(CAT_DEVICEIMPL)<< m_id <<"dtor"; -} - -QString DeviceImpl::id() -{ - return m_id; -} +DeviceImpl::~DeviceImpl() { qDebug(CAT_DEVICEIMPL) << m_id << "dtor"; } -QString DeviceImpl::displayName() -{ - return m_displayName; -} +QString DeviceImpl::id() { return m_id; } -QString DeviceImpl::category() -{ - return m_category; -} +QString DeviceImpl::displayName() { return m_displayName; } -QString DeviceImpl::displayParam() -{ - return m_displayParam; -} +QString DeviceImpl::category() { return m_category; } +QString DeviceImpl::displayParam() { return m_displayParam; } -QString DeviceImpl::param() -{ - return m_param; -} +QString DeviceImpl::param() { return m_param; } -QWidget *DeviceImpl::icon() -{ - return m_icon; -} +QWidget *DeviceImpl::icon() { return m_icon; } -QWidget *DeviceImpl::page() -{ - return m_page; -} +QWidget *DeviceImpl::page() { return m_page; } -QList DeviceImpl::toolList() +QList DeviceImpl::toolList() { static int i; - QList ret; + QList ret; for(auto &&p : m_plugins) { ret.append(p->toolList()); @@ -361,6 +349,6 @@ QList DeviceImpl::toolList() return ret; } -} +} // namespace scopy #include "moc_deviceimpl.cpp" diff --git a/core/src/deviceloader.cpp b/core/src/deviceloader.cpp index 6afeb9d666..63ba94681b 100644 --- a/core/src/deviceloader.cpp +++ b/core/src/deviceloader.cpp @@ -1,19 +1,18 @@ #include "deviceloader.h" + #include using namespace scopy; -DeviceLoader::DeviceLoader(DeviceImpl* d, QObject *parent) : d(d), QObject(parent) -{ +DeviceLoader::DeviceLoader(DeviceImpl *d, QObject *parent) + : d(d) + , QObject(parent) +{} -} +DeviceLoader::~DeviceLoader() {} -DeviceLoader::~DeviceLoader() +void DeviceLoader::init(bool async) { - -} - -void DeviceLoader::init(bool async) { if(async) { asyncInit(); } else { @@ -23,7 +22,7 @@ void DeviceLoader::init(bool async) { void DeviceLoader::asyncInit() { - QThread *th = QThread::create([=]{ + QThread *th = QThread::create([=] { // initializer thread d->init(); }); @@ -31,18 +30,25 @@ void DeviceLoader::asyncInit() d->setParent(nullptr); d->moveToThread(th); - connect(th,&QThread::destroyed, this,[=]() {; + connect( + th, &QThread::destroyed, this, + [=]() { + ; // back to main thread d->moveToThread(QThread::currentThread()); d->setParent(oldParent); Q_EMIT initialized(); - }, Qt::QueuedConnection); - connect(th,&QThread::finished, th, &QThread::deleteLater); + }, + Qt::QueuedConnection); + connect(th, &QThread::finished, th, &QThread::deleteLater); th->start(); } -void DeviceLoader::syncInit() { +void DeviceLoader::syncInit() +{ d->init(); Q_EMIT initialized(); } + +#include "moc_deviceloader.cpp" diff --git a/core/src/devicemanager.cpp b/core/src/devicemanager.cpp index 01ebe8bae6..7ffcdb43a9 100644 --- a/core/src/devicemanager.cpp +++ b/core/src/devicemanager.cpp @@ -1,28 +1,30 @@ #include "devicemanager.h" + +#include "QApplication" +#include "devicefactory.h" #include "deviceimpl.h" #include "deviceloader.h" #include "iiodeviceimpl.h" -#include -#include "devicefactory.h" -#include "QApplication" -#include + #include +#include #include +#include Q_LOGGING_CATEGORY(CAT_DEVICEMANAGER, "DeviceManager") using namespace scopy; DeviceManager::DeviceManager(PluginManager *pm, QObject *parent) - : QObject{parent}, pm(pm) + : QObject{parent} + , pm(pm) { - connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()),this,SLOT(disconnectAll())); + connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(disconnectAll())); } -DeviceManager::~DeviceManager() -{ -} +DeviceManager::~DeviceManager() {} -Device* DeviceManager::getDevice(QString id) { +Device *DeviceManager::getDevice(QString id) +{ Device *d = nullptr; if(map.contains(id)) { @@ -31,9 +33,10 @@ Device* DeviceManager::getDevice(QString id) { return d; } -void DeviceManager::addDevice(Device* d) { +void DeviceManager::addDevice(Device *d) +{ - DeviceImpl* di = dynamic_cast(d); + DeviceImpl *di = dynamic_cast(d); QString id = d->id(); map[id] = d; di->setParent(this); @@ -44,30 +47,31 @@ void DeviceManager::addDevice(Device* d) { QString DeviceManager::createDevice(QString category, QString param, bool async) { - qInfo(CAT_DEVICEMANAGER) <init(async); return d->id(); } - // This is only used by scan context collector - should I rethink this ? // Map all devices to uris in scan context collector -void DeviceManager::removeDevice(QString category, QString param) { +void DeviceManager::removeDevice(QString category, QString param) +{ - for(Device* d : qAsConst(map)) { + for(Device *d : qAsConst(map)) { if(d->category() == category && d->param() == param) { removeDeviceById(d->id()); return; } - } } @@ -80,13 +84,13 @@ void DeviceManager::removeDeviceById(QString id) } if(!map.contains(id)) { - qWarning(CAT_DEVICEMANAGER) << id <<"Device does not exist"; + qWarning(CAT_DEVICEMANAGER) << id << "Device does not exist"; return; } d = map.take(id); Q_EMIT deviceRemoveStarted(id, d); - disconnectDeviceFromManager(dynamic_cast(d)); + disconnectDeviceFromManager(dynamic_cast(d)); d->unloadPlugins(); delete(d); @@ -95,22 +99,23 @@ void DeviceManager::removeDeviceById(QString id) Q_EMIT deviceRemoved(id); } -void DeviceManager::connectDeviceToManager(DeviceImpl *d) { - connect(d,&DeviceImpl::connected,this,[=](){connectDevice(d->id());}); - connect(d,&DeviceImpl::disconnected,this,[=](){disconnectDevice(d->id());}); - connect(d,&DeviceImpl::forget,this,[=](){removeDeviceById(d->id());}); - connect(d,SIGNAL(requestedRestart()), this,SLOT(restartDevice())); - connect(d,SIGNAL(toolListChanged()),this,SLOT(changeToolListDevice())); - connect(d,SIGNAL(requestTool(QString)),this,SIGNAL(requestTool(QString))); - -} -void DeviceManager::disconnectDeviceFromManager(DeviceImpl *d) { - disconnect(d,SIGNAL(connected())); - disconnect(d,SIGNAL(disconnected())); - disconnect(d,SIGNAL(forget())); - disconnect(d,SIGNAL(requestedRestart()), this,SLOT(restartDevice())); - disconnect(d,SIGNAL(toolListChanged()),this,SLOT(changeToolListDevice())); - disconnect(d,SIGNAL(requestTool(QString)),this,SIGNAL(requestTool(QString))); +void DeviceManager::connectDeviceToManager(DeviceImpl *d) +{ + connect(d, &DeviceImpl::connected, this, [=]() { connectDevice(d->id()); }); + connect(d, &DeviceImpl::disconnected, this, [=]() { disconnectDevice(d->id()); }); + connect(d, &DeviceImpl::forget, this, [=]() { removeDeviceById(d->id()); }); + connect(d, SIGNAL(requestedRestart()), this, SLOT(restartDevice())); + connect(d, SIGNAL(toolListChanged()), this, SLOT(changeToolListDevice())); + connect(d, SIGNAL(requestTool(QString)), this, SIGNAL(requestTool(QString))); +} +void DeviceManager::disconnectDeviceFromManager(DeviceImpl *d) +{ + disconnect(d, SIGNAL(connected())); + disconnect(d, SIGNAL(disconnected())); + disconnect(d, SIGNAL(forget())); + disconnect(d, SIGNAL(requestedRestart()), this, SLOT(restartDevice())); + disconnect(d, SIGNAL(toolListChanged()), this, SLOT(changeToolListDevice())); + disconnect(d, SIGNAL(requestTool(QString)), this, SIGNAL(requestTool(QString))); } QString DeviceManager::restartDevice(QString id) @@ -143,26 +148,29 @@ void DeviceManager::load(QSettings &s) } } -void DeviceManager::changeToolListDevice() { - QString id = dynamic_cast(QObject::sender())->id(); +void DeviceManager::changeToolListDevice() +{ + QString id = dynamic_cast(QObject::sender())->id(); Q_EMIT deviceChangedToolList(id, map[id]->toolList()); } -void DeviceManager::connectDevice() { - QString id = dynamic_cast(QObject::sender())->id(); +void DeviceManager::connectDevice() +{ + QString id = dynamic_cast(QObject::sender())->id(); connectDevice(id); } -void DeviceManager::connectDevice(QString id) { - qDebug(CAT_DEVICEMANAGER)<<"connecting " << id << "..."; +void DeviceManager::connectDevice(QString id) +{ + qDebug(CAT_DEVICEMANAGER) << "connecting " << id << "..."; if(connectedDev.contains(id)) { - qDebug(CAT_DEVICEMANAGER)<<"connecting to the same device, disconnecting first .. "; + qDebug(CAT_DEVICEMANAGER) << "connecting to the same device, disconnecting first .. "; map[id]->disconnectDev(); } if(exclusive) { if(connectedDev.size() > 0) { - qDebug(CAT_DEVICEMANAGER)<<"exclusive mode, disconnecting all connected devices .. "; - for(int i = 0;idisconnectDev(); } } @@ -171,34 +179,30 @@ void DeviceManager::connectDevice(QString id) { Q_EMIT deviceConnected(id, map[id]); } - - -void DeviceManager::disconnectDevice() { - QString id = dynamic_cast(QObject::sender())->id(); +void DeviceManager::disconnectDevice() +{ + QString id = dynamic_cast(QObject::sender())->id(); disconnectDevice(id); } -void DeviceManager::disconnectDevice(QString id) { - qDebug(CAT_DEVICEMANAGER)<<"disconnecting "<< id << "..."; +void DeviceManager::disconnectDevice(QString id) +{ + qDebug(CAT_DEVICEMANAGER) << "disconnecting " << id << "..."; connectedDev.removeOne(id); Q_EMIT requestTool("home"); Q_EMIT deviceDisconnected(id, map[id]); } -void DeviceManager::setExclusive(bool val) { - exclusive = val; -} -bool DeviceManager::getExclusive() const { - return exclusive; -} +void DeviceManager::setExclusive(bool val) { exclusive = val; } +bool DeviceManager::getExclusive() const { return exclusive; } -void DeviceManager::restartDevice() { - QString id = dynamic_cast(QObject::sender())->id(); - qDebug(CAT_DEVICEMANAGER)<<"restarting "<< id << "..."; +void DeviceManager::restartDevice() +{ + QString id = dynamic_cast(QObject::sender())->id(); + qDebug(CAT_DEVICEMANAGER) << "restarting " << id << "..."; QString newId = restartDevice(id); -// connect(this,SIGNAL(deviceAdded(QString,Device*)),this,SIGNAL(requestDevice(QString))); -// Q_EMIT requestDevice(newId); + // connect(this,SIGNAL(deviceAdded(QString,Device*)),this,SIGNAL(requestDevice(QString))); + // Q_EMIT requestDevice(newId); } - #include "moc_devicemanager.cpp" diff --git a/core/src/emuwidget.cpp b/core/src/emuwidget.cpp index 5605a182f1..17351da467 100644 --- a/core/src/emuwidget.cpp +++ b/core/src/emuwidget.cpp @@ -1,12 +1,16 @@ #include "emuwidget.h" + #include "pluginbase/preferences.h" + #include "ui_emuwidget.h" -#include -#include + #include +#include +#include + #include -Q_LOGGING_CATEGORY(CAT_EMU_ADD_PAGE,"EmuAddPage") +Q_LOGGING_CATEGORY(CAT_EMU_ADD_PAGE, "EmuAddPage") using namespace scopy; EmuWidget::EmuWidget(QString path, QWidget *parent) @@ -21,19 +25,15 @@ EmuWidget::EmuWidget(QString path, QWidget *parent) connect(m_ui->comboBoxDemoOption, &QComboBox::currentTextChanged, this, &EmuWidget::onOptionChanged); init(); - connect(m_ui->btnEnableDemo, &QPushButton::clicked, this, &EmuWidget::onEnableDemoClicked); - connect(m_ui->btnXmlPathBrowse, &QPushButton::clicked, this, [=](){ - browseFile(m_ui->lineEditXmlPath); - }); - connect(m_ui->btnRxTxDeviceBrowse, &QPushButton::clicked, this, [=](){ - browseFile(m_ui->lineEditRxTxDevice); - }); + connect(m_ui->btnXmlPathBrowse, &QPushButton::clicked, this, [=]() { browseFile(m_ui->lineEditXmlPath); }); + connect(m_ui->btnRxTxDeviceBrowse, &QPushButton::clicked, this, + [=]() { browseFile(m_ui->lineEditRxTxDevice); }); } EmuWidget::~EmuWidget() { - if (m_emuProcess) { + if(m_emuProcess) { killEmuProcess(); } delete m_ui; @@ -41,12 +41,11 @@ EmuWidget::~EmuWidget() void EmuWidget::init() { - Preferences *p = Preferences::GetInstance(); - p->init("iio_emu_path", QCoreApplication::applicationDirPath()); + Preferences *p = Preferences::GetInstance(); + p->init("iio_emu_path", QCoreApplication::applicationDirPath()); m_emuPath = findEmuPath(); - m_emuPath.isEmpty() ? setStatusMessage("Can't find iio-emu in the system!") - : setStatusMessage(""); + m_emuPath.isEmpty() ? setStatusMessage("Can't find iio-emu in the system!") : setStatusMessage(""); this->setEnabled(!m_emuPath.isEmpty()); QMovie *loadingIcon(new QMovie(this)); @@ -58,7 +57,7 @@ void EmuWidget::init() m_ui->btnRxTxDeviceBrowse->setProperty("blue_button", QVariant(true)); m_ui->btnEnableDemo->setAutoDefault(true); m_ui->lineEditUri->setPlaceholderText("ip:127.0.0.1"); - for (const QString &item : m_availableOptions) { + for(const QString &item : m_availableOptions) { m_ui->comboBoxDemoOption->addItem(item); } } @@ -72,15 +71,15 @@ void EmuWidget::setStatusMessage(QString msg) void EmuWidget::onEnableDemoClicked() { m_ui->btnEnableDemo->startAnimation(); - if (!m_enableDemo) { + if(!m_enableDemo) { bool started = startIioEmuProcess(); - if (!started) { + if(!started) { stopEnableBtn("Enable Demo"); return; } stopEnableBtn("Disable Demo"); m_ui->widgetEnable->setEnabled(false); - if (m_ui->lineEditUri->text().isEmpty()) { + if(m_ui->lineEditUri->text().isEmpty()) { m_ui->lineEditUri->setText("ip:127.0.0.1"); } m_enableDemo = !m_enableDemo; @@ -95,7 +94,7 @@ QStringList EmuWidget::createArgList() QString option = m_ui->comboBoxDemoOption->currentText(); QStringList arguments; arguments.append(option); - if (option.compare("generic") == 0) { + if(option.compare("generic") == 0) { arguments.append(m_ui->lineEditXmlPath->text()); arguments.append(m_ui->lineEditRxTxDevice->text()); } @@ -105,13 +104,13 @@ QStringList EmuWidget::createArgList() QString EmuWidget::findEmuPath() { Preferences *p = Preferences::GetInstance(); - QString program = p->get("iio_emu_path").toString() + "/iio-emu"; - #ifdef WIN32 - program += ".exe"; - #endif + QString program = p->get("iio_emu_path").toString() + "/iio-emu"; +#ifdef WIN32 + program += ".exe"; +#endif - QFileInfo fi(program); - if (!fi.exists()) { + QFileInfo fi(program); + if(!fi.exists()) { program = ""; } return program; @@ -131,11 +130,11 @@ bool EmuWidget::startIioEmuProcess() m_emuProcess->start(); auto started = m_emuProcess->waitForStarted(); - if (!started) { + if(!started) { setStatusMessage("Server failed to start!"); qDebug(CAT_EMU_ADD_PAGE) << "Process failed to start"; } else { - qDebug(CAT_EMU_ADD_PAGE)<<"Process " << m_emuPath << "started"; + qDebug(CAT_EMU_ADD_PAGE) << "Process " << m_emuPath << "started"; } return started; } @@ -159,8 +158,8 @@ void EmuWidget::onOptionChanged(QString option) void EmuWidget::browseFile(QLineEdit *lineEditPath) { QString filePath = - QFileDialog::getOpenFileName(this, "Open a file", "directoryToOpen", - "All (*);;XML Files (*.xml);;Text Files (*.txt);;BIN Files (*.bin)"); + QFileDialog::getOpenFileName(this, "Open a file", "directoryToOpen", + "All (*);;XML Files (*.xml);;Text Files (*.txt);;BIN Files (*.bin)"); lineEditPath->setText(filePath); m_ui->btnEnableDemo->setFocus(); } @@ -170,3 +169,5 @@ void EmuWidget::showEvent(QShowEvent *event) QWidget::showEvent(event); m_ui->btnEnableDemo->setFocus(); } + +#include "moc_emuwidget.cpp" diff --git a/core/src/iiodeviceimpl.cpp b/core/src/iiodeviceimpl.cpp index 420c7d8ca4..52ba1515f6 100644 --- a/core/src/iiodeviceimpl.cpp +++ b/core/src/iiodeviceimpl.cpp @@ -1,5 +1,7 @@ #include "iiodeviceimpl.h" + #include "iioutil/contextprovider.h" + #include Q_LOGGING_CATEGORY(CAT_IIO_DEVICEIMPL, "IIODevice") @@ -19,7 +21,7 @@ void IIODeviceImpl::init() bool IIODeviceImpl::verify() { iio_context *ctx = ContextProvider::GetInstance()->open(m_param); - if (!ctx) { + if(!ctx) { return false; } ContextProvider::GetInstance()->close(m_param); @@ -28,15 +30,15 @@ bool IIODeviceImpl::verify() QMap IIODeviceImpl::readDeviceInfo() { - QMap contextAttributes; + QMap contextAttributes; iio_context *ctx = ContextProvider::GetInstance()->open(m_param); - if (!ctx) { + if(!ctx) { qWarning(CAT_IIO_DEVICEIMPL) << "Cannot read the device info! (unavailable context)"; } else { - for(int i=0;i IIODeviceImpl::readDeviceInfo() return contextAttributes; } - diff --git a/core/src/iiotabwidget.cpp b/core/src/iiotabwidget.cpp index 8220abc5b7..da985c96a8 100644 --- a/core/src/iiotabwidget.cpp +++ b/core/src/iiotabwidget.cpp @@ -1,11 +1,16 @@ #include "iiotabwidget.h" + +#include "iioutil/scopy-iioutil_config.h" #include "qtconcurrentrun.h" + #include "ui_iiotabwidget.h" + +#include + #include #include -#include + #include -#include "iioutil/scopy-iioutil_config.h" Q_LOGGING_CATEGORY(CAT_IIO_ADD_PAGE, "IIOTabWidget") @@ -20,39 +25,29 @@ IioTabWidget::IioTabWidget(QWidget *parent) verifyIioBackend(); connect(m_ui->btnVerify, &QPushButton::clicked, this, &IioTabWidget::verifyBtnClicked, Qt::QueuedConnection); - //scan + // scan fwScan = new QFutureWatcher(this); - connect(fwScan, &QFutureWatcher::started, m_ui->btnScan, &AnimationPushButton::startAnimation, Qt::QueuedConnection); + connect(fwScan, &QFutureWatcher::started, m_ui->btnScan, &AnimationPushButton::startAnimation, + Qt::QueuedConnection); connect(fwScan, &QFutureWatcher::finished, this, &IioTabWidget::scanFinished, Qt::QueuedConnection); connect(m_ui->btnScan, SIGNAL(clicked()), this, SLOT(futureScan()), Qt::QueuedConnection); - connect(m_ui->comboBoxContexts,&QComboBox::textActivated, this, [=](){ - Q_EMIT uriChanged(m_ui->comboBoxContexts->currentText()); - }); + connect(m_ui->comboBoxContexts, &QComboBox::textActivated, this, + [=]() { Q_EMIT uriChanged(m_ui->comboBoxContexts->currentText()); }); - //serial widget connections - connect(m_ui->comboBoxSerialPort, &QComboBox::textActivated, this, [=](){ - Q_EMIT uriChanged(getSerialPath()); - }); - connect(m_ui->comboBoxBaudRate, &QComboBox::textActivated, this, [=](){ - Q_EMIT uriChanged(getSerialPath()); - }); - connect(m_ui->editSerialFrameConfig, &QLineEdit::returnPressed, this, [=](){ - Q_EMIT uriChanged(getSerialPath()); - }); + // serial widget connections + connect(m_ui->comboBoxSerialPort, &QComboBox::textActivated, this, + [=]() { Q_EMIT uriChanged(getSerialPath()); }); + connect(m_ui->comboBoxBaudRate, &QComboBox::textActivated, this, [=]() { Q_EMIT uriChanged(getSerialPath()); }); + connect(m_ui->editSerialFrameConfig, &QLineEdit::returnPressed, this, + [=]() { Q_EMIT uriChanged(getSerialPath()); }); connect(this, &IioTabWidget::uriChanged, this, &IioTabWidget::updateUri); - connect(m_ui->editUri, &QLineEdit::returnPressed, this, [=](){ - Q_EMIT m_ui->btnVerify->clicked(); - }); - connect(m_ui->editUri, &QLineEdit::textChanged, this, [=](QString uri){ - m_ui->btnVerify->setEnabled(!uri.isEmpty()); - }); + connect(m_ui->editUri, &QLineEdit::returnPressed, this, [=]() { Q_EMIT m_ui->btnVerify->clicked(); }); + connect(m_ui->editUri, &QLineEdit::textChanged, this, + [=](QString uri) { m_ui->btnVerify->setEnabled(!uri.isEmpty()); }); } -IioTabWidget::~IioTabWidget() -{ - delete m_ui; -} +IioTabWidget::~IioTabWidget() { delete m_ui; } void IioTabWidget::init() { @@ -79,11 +74,11 @@ void IioTabWidget::init() m_ui->btnVerify->setEnabled(false); m_ui->btnScan->setProperty("blue_button", QVariant(true)); m_ui->btnScan->setIcon(QIcon(":/gui/icons/refresh.svg")); - m_ui->btnScan->setIconSize(QSize(25,25)); + m_ui->btnScan->setIconSize(QSize(25, 25)); addScanFeedbackMsg("No scanned contexts... Press the refresh button!"); m_ui->btnScan->setAutoDefault(true); m_ui->btnVerify->setAutoDefault(true); - for (int baudRate : availableBaudRates) { + for(int baudRate : availableBaudRates) { m_ui->comboBoxBaudRate->addItem(QString::number(baudRate)); } } @@ -96,9 +91,9 @@ void IioTabWidget::verifyIioBackend() #ifdef WITH_LIBSERIALPORT hasLibSerialPort = true; #endif - for (int i = 0; i < backEndsCount; i++) { + for(int i = 0; i < backEndsCount; i++) { QString backEnd(iio_get_backend(i)); - if (backEnd.compare("xml") == 0 || (!hasLibSerialPort && backEnd.compare("serial") == 0)) { + if(backEnd.compare("xml") == 0 || (!hasLibSerialPort && backEnd.compare("serial") == 0)) { continue; } createBackEndCheckBox(backEnd); @@ -112,17 +107,17 @@ void IioTabWidget::createBackEndCheckBox(QString backEnd) QCheckBox *cb = new QCheckBox(); cb->setText(backEnd); connect(cb, &QCheckBox::toggled, this, [=](bool en) { - if (en) { + if(en) { scanParamsList.push_back(backEnd + ":"); } else { scanParamsList.removeOne(backEnd + ":"); } - if (backEnd.compare("serial") == 0) { + if(backEnd.compare("serial") == 0) { m_ui->serialSettingsWidget->setEnabled(en); } - if (scanParamsList.empty()) { + if(scanParamsList.empty()) { m_ui->btnScan->setEnabled(false); - } else if (!m_ui->btnScan->isEnabled()) { + } else if(!m_ui->btnScan->isEnabled()) { m_ui->btnScan->setEnabled(true); } }); @@ -132,10 +127,11 @@ void IioTabWidget::createBackEndCheckBox(QString backEnd) void IioTabWidget::verifyBtnClicked() { - QRegExp ipRegex("^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$"); + QRegExp ipRegex("^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-" + "4][0-9]|25[0-5])$"); QString uri(m_ui->editUri->text()); bool isIp = uri.contains(ipRegex); - if (isIp && !m_ui->editUri->text().contains("ip:")) { + if(isIp && !m_ui->editUri->text().contains("ip:")) { m_ui->editUri->blockSignals(true); m_ui->editUri->setText("ip:" + uri); m_ui->editUri->blockSignals(false); @@ -148,8 +144,8 @@ void IioTabWidget::verifyBtnClicked() void IioTabWidget::onVerifyFinished(bool result) { m_ui->uriMessageLabel->clear(); - if (!result) { - m_ui->uriMessageLabel->setText("\""+m_ui->editUri->text() + "\" not a valid context!"); + if(!result) { + m_ui->uriMessageLabel->setText("\"" + m_ui->editUri->text() + "\" not a valid context!"); } m_ui->btnVerify->stopAnimation(); m_ui->btnScan->setEnabled(true); @@ -169,19 +165,19 @@ void IioTabWidget::scanFinished() m_ui->btnScan->stopAnimation(); m_ui->comboBoxContexts->clear(); m_ui->uriMessageLabel->clear(); - if (retCode < 0) { + if(retCode < 0) { addScanFeedbackMsg("Scan command failed!"); - qWarning(CAT_IIO_ADD_PAGE) <<"iio_scan_context_get_info_list error " << retCode; + qWarning(CAT_IIO_ADD_PAGE) << "iio_scan_context_get_info_list error " << retCode; return; } - if (scanList.isEmpty()) { + if(scanList.isEmpty()) { addScanFeedbackMsg("No scanned contexts available!"); return; } - if (!m_ui->comboBoxContexts->isEnabled()) { + if(!m_ui->comboBoxContexts->isEnabled()) { m_ui->comboBoxContexts->setEnabled(true); } - for (const auto &ctx: qAsConst(scanList)) { + for(const auto &ctx : qAsConst(scanList)) { m_ui->comboBoxContexts->addItem(ctx); } findAvailableSerialPorts(); @@ -190,11 +186,11 @@ void IioTabWidget::scanFinished() void IioTabWidget::findAvailableSerialPorts() { - if (scanParamsList.contains("serial:")) { + if(scanParamsList.contains("serial:")) { QVector portsName = IIOScanTask::getSerialPortsName(); m_ui->comboBoxSerialPort->clear(); - if (!portsName.empty()) { - for (const QString &port : portsName) { + if(!portsName.empty()) { + for(const QString &port : portsName) { m_ui->comboBoxSerialPort->addItem(port); } } @@ -214,7 +210,7 @@ void IioTabWidget::updateUri(QString uri) { m_ui->editUri->clear(); m_ui->editUri->setText(uri); - if (!uri.isEmpty()) { + if(!uri.isEmpty()) { m_ui->btnVerify->setFocus(); } } @@ -234,4 +230,3 @@ void IioTabWidget::showEvent(QShowEvent *event) } #include "moc_iiotabwidget.cpp" - diff --git a/core/src/infopagestack.cpp b/core/src/infopagestack.cpp index 18147ef2fa..f8588f3358 100644 --- a/core/src/infopagestack.cpp +++ b/core/src/infopagestack.cpp @@ -1,8 +1,11 @@ #include "infopagestack.h" + #include "gui/customanimation.h" -#include -#include + #include +#include +#include + #include using namespace scopy; @@ -23,32 +26,33 @@ InfoPageStack::InfoPageStack(QWidget *parent) next = 0; hc->setVisible(true); hc->raise(); - qDebug(CAT_INFOPAGESTACK)<<"ctor"; + qDebug(CAT_INFOPAGESTACK) << "ctor"; } InfoPageStack::~InfoPageStack() { this->removeEventFilter(hc); - qDebug(CAT_INFOPAGESTACK)<<"dtor"; + qDebug(CAT_INFOPAGESTACK) << "dtor"; } -void InfoPageStack::add(QString key, QWidget *w) { - MapStackedWidget::add(key,w); +void InfoPageStack::add(QString key, QWidget *w) +{ + MapStackedWidget::add(key, w); if(count() == 1) { hc->raise(); } hc->setVisible(count() > 1); } -void InfoPageStack::add(QString key, Device* d) +void InfoPageStack::add(QString key, Device *d) { QWidget *w = d->page(); add(key, w); - idDevMap.insert(key,d); - + idDevMap.insert(key, d); } -bool InfoPageStack::remove(QString key) { +bool InfoPageStack::remove(QString key) +{ bool ret = MapStackedWidget::remove(key); idDevMap.take(key); return ret; @@ -68,7 +72,8 @@ bool InfoPageStack::show(QString key) return ret; } -bool InfoPageStack::slideInKey(QString key, int direction) { +bool InfoPageStack::slideInKey(QString key, int direction) +{ QString oldKey = getKey(currentWidget()); if(idDevMap.contains(oldKey)) @@ -88,16 +93,16 @@ bool InfoPageStack::slideInKey(QString key, int direction) { void InfoPageStack::animationDone() { setCurrentIndex(next); -// widget(current)->hide(); -// widget(current)->move(now); + // widget(current)->hide(); + // widget(current)->move(now); active = false; hc->raise(); } void InfoPageStack::slideInWidget(QWidget *newWidget, int direction) { - if (active) { - if (this->next != indexOf(newWidget)) { + if(active) { + if(this->next != indexOf(newWidget)) { animationDone(); } else { return; @@ -107,7 +112,7 @@ void InfoPageStack::slideInWidget(QWidget *newWidget, int direction) int current = currentIndex(); int next = indexOf(newWidget); - if (current == next) { + if(current == next) { active = false; return; } @@ -116,8 +121,8 @@ void InfoPageStack::slideInWidget(QWidget *newWidget, int direction) int offsety = frameRect().height(); widget(next)->setGeometry(0, 0, offsetx, offsety); - if (direction < 0) { - offsetx = - offsetx; + if(direction < 0) { + offsetx = -offsetx; offsety = 0; } else { offsety = 0; @@ -154,9 +159,6 @@ void InfoPageStack::slideInWidget(QWidget *newWidget, int direction) animGroup->start(); } -HomepageControls *InfoPageStack::getHomepageControls() const -{ - return hc; -} +HomepageControls *InfoPageStack::getHomepageControls() const { return hc; } #include "moc_infopagestack.cpp" diff --git a/core/src/license_overlay.cpp b/core/src/license_overlay.cpp index ef5a66a4e6..c6c3f6f47a 100644 --- a/core/src/license_overlay.cpp +++ b/core/src/license_overlay.cpp @@ -1,23 +1,23 @@ #include "qabstractbutton.h" -#include -#include -#include - -#include +#include #include #include +#include #include #include #include + +#include +#include #include #include using namespace scopy; -LicenseOverlay::LicenseOverlay(QWidget* parent): - QWidget(parent), - parent(parent) +LicenseOverlay::LicenseOverlay(QWidget *parent) + : QWidget(parent) + , parent(parent) { overlay = new gui::TintedOverlay(parent); ui = new Ui::LicenseDialogOverlay(); @@ -28,14 +28,12 @@ LicenseOverlay::LicenseOverlay(QWidget* parent): StyleHelper::BlueButton(ui->btnExit, "btnExit"); StyleHelper::OverlayMenu(this, "licenseOverlay"); - Preferences::connect(ui->btnContinue, &QAbstractButton::clicked, [&] () { + Preferences::connect(ui->btnContinue, &QAbstractButton::clicked, [&]() { Preferences::GetInstance()->set("general_first_run", false); overlay->deleteLater(); deleteLater(); }); - Preferences::connect(ui->btnExit, &QAbstractButton::clicked, [&] () { - QCoreApplication::quit(); - }); + Preferences::connect(ui->btnExit, &QAbstractButton::clicked, [&]() { QCoreApplication::quit(); }); } void LicenseOverlay::showOverlay() @@ -47,10 +45,7 @@ void LicenseOverlay::showOverlay() this->move(parent->rect().center() - this->rect().center()); } -QPushButton *LicenseOverlay::getContinueBtn() -{ - return ui->btnContinue; -} +QPushButton *LicenseOverlay::getContinueBtn() { return ui->btnContinue; } QString LicenseOverlay::getLicense() { @@ -61,3 +56,5 @@ QString LicenseOverlay::getLicense() return text; } + +#include "moc_license_overlay.cpp" diff --git a/core/src/pluginenablewidget.cpp b/core/src/pluginenablewidget.cpp index 95dd14db60..e247698c19 100644 --- a/core/src/pluginenablewidget.cpp +++ b/core/src/pluginenablewidget.cpp @@ -1,4 +1,5 @@ #include "pluginenablewidget.h" + #include "qboxlayout.h" using namespace scopy; @@ -19,12 +20,11 @@ PluginEnableWidget::PluginEnableWidget(QWidget *parent) layout->setAlignment(m_checkBox, Qt::AlignTop); layout->addWidget(m_descriptionLabel); layout->setAlignment(m_descriptionLabel, Qt::AlignTop); - layout->setStretch(0,1); - layout->setStretch(1,3); + layout->setStretch(0, 1); + layout->setStretch(1, 3); } -PluginEnableWidget::~PluginEnableWidget() -{} +PluginEnableWidget::~PluginEnableWidget() {} void PluginEnableWidget::setDescription(QString description) { @@ -32,7 +32,6 @@ void PluginEnableWidget::setDescription(QString description) m_descriptionLabel->setText(description); } -QCheckBox *PluginEnableWidget::checkBox() const -{ - return m_checkBox; -} +QCheckBox *PluginEnableWidget::checkBox() const { return m_checkBox; } + +#include "moc_pluginenablewidget.cpp" diff --git a/core/src/pluginfilter.cpp b/core/src/pluginfilter.cpp index 18e1b47139..087a00941d 100644 --- a/core/src/pluginfilter.cpp +++ b/core/src/pluginfilter.cpp @@ -1,8 +1,10 @@ #include "pluginfilter.h" + #include namespace scopy { -bool PluginFilter::pluginInCategory(Plugin* p, QString category) { // PluginFilter class (?) +bool PluginFilter::pluginInCategory(Plugin *p, QString category) +{ // PluginFilter class (?) if(category.isEmpty()) // no category selected return true; if(!p->metadata().contains("category")) // plugin metadata does not have category @@ -18,16 +20,16 @@ bool PluginFilter::pluginInCategory(Plugin* p, QString category) { // PluginFilt if(v.toString() == category) { return true; } - } } return false; } -bool PluginFilter::pluginForcedInclusionList(QList pl, Plugin *p) { +bool PluginFilter::pluginForcedInclusionList(QList pl, Plugin *p) +{ bool ret = false; QStringList includeList; - for(Plugin* test : pl) { + for(Plugin *test : pl) { if(test->enabled() == false) continue; if(!test->metadata().contains("include-forced")) @@ -53,10 +55,11 @@ bool PluginFilter::pluginForcedInclusionList(QList pl, Plugin *p) { return ret; } -bool PluginFilter::pluginInExclusionList(QList pl, Plugin *p) { +bool PluginFilter::pluginInExclusionList(QList pl, Plugin *p) +{ bool ret = false; QStringList excludeList; - for(Plugin* test : pl) { + for(Plugin *test : pl) { if(test->enabled() == false) continue; if(!test->metadata().contains("exclude")) @@ -81,7 +84,7 @@ bool PluginFilter::pluginInExclusionList(QList pl, Plugin *p) { if(exclude.toLower() == p->name().toLower()) { ret = true; } - if(exclude.toLower() == QString("!"+p->name()).toLower()) { + if(exclude.toLower() == QString("!" + p->name()).toLower()) { ret = false; break; } @@ -89,4 +92,4 @@ bool PluginFilter::pluginInExclusionList(QList pl, Plugin *p) { return ret; } -} +} // namespace scopy diff --git a/core/src/pluginmanager.cpp b/core/src/pluginmanager.cpp index ebfb2a8b04..b51de77a80 100644 --- a/core/src/pluginmanager.cpp +++ b/core/src/pluginmanager.cpp @@ -1,38 +1,39 @@ #include "pluginmanager.h" + +#include "pluginfilter.h" #include "qpluginloader.h" -#include + #include -#include #include -#include "pluginfilter.h" +#include + +#include Q_LOGGING_CATEGORY(CAT_PLUGINMANAGER, "PluginManager") using namespace scopy; - struct less_than_key { - inline bool operator() (Plugin* p1, Plugin* p2) - { - return (p1->metadata()["priority"].toInt() < p2->metadata()["priority"].toInt()); - } + inline bool operator()(Plugin *p1, Plugin *p2) + { + return (p1->metadata()["priority"].toInt() < p2->metadata()["priority"].toInt()); + } }; - struct greater_than_key { - inline bool operator() (Plugin* p1, Plugin* p2) - { - return (p1->metadata()["priority"].toInt() > p2->metadata()["priority"].toInt()); - } + inline bool operator()(Plugin *p1, Plugin *p2) + { + return (p1->metadata()["priority"].toInt() > p2->metadata()["priority"].toInt()); + } }; -PluginManager::PluginManager(QObject *parent) : QObject(parent) -{ - -} +PluginManager::PluginManager(QObject *parent) + : QObject(parent) +{} -PluginManager::~PluginManager() { +PluginManager::~PluginManager() +{ for(Plugin *p : qAsConst(list)) { p->deinit(); } @@ -47,7 +48,7 @@ void PluginManager::add(QStringList pluginFileList) void PluginManager::add(QString pluginFileName) { - Plugin* p = nullptr; + Plugin *p = nullptr; p = loadPlugin(pluginFileName); if(p) { qInfo(CAT_PLUGINMANAGER) << "Found plugin:" << p->name() << "in " << pluginFileName; @@ -55,41 +56,38 @@ void PluginManager::add(QString pluginFileName) p->initMetadata(); applyMetadata(p, &m_metadata); p->init(); - QObject *obj = dynamic_cast(p); + QObject *obj = dynamic_cast(p); if(obj) obj->setParent(this); } } -int PluginManager::count() -{ - return list.count(); -} +int PluginManager::count() { return list.count(); } -void PluginManager::applyMetadata(Plugin* plugin, QJsonObject *metadata){ +void PluginManager::applyMetadata(Plugin *plugin, QJsonObject *metadata) +{ if(metadata->contains(plugin->name())) { plugin->setMetadata(metadata->value(plugin->name()).toObject()); } } -void PluginManager::sort() { - std::sort(list.begin(),list.end(),greater_than_key()); +void PluginManager::sort() +{ + std::sort(list.begin(), list.end(), greater_than_key()); qDebug(CAT_PLUGINMANAGER) << "New plugin order:"; - for(Plugin* plugin : qAsConst(list)) { + for(Plugin *plugin : qAsConst(list)) { qDebug(CAT_PLUGINMANAGER) << plugin->name(); } } -void PluginManager::clear() { - list.clear(); -} +void PluginManager::clear() { list.clear(); } QList PluginManager::getPlugins(QString category) { QList newlist; - for(Plugin* plugin : qAsConst(list)) { - if(!PluginFilter::pluginInCategory(plugin,category)) + for(Plugin *plugin : qAsConst(list)) { + if(!PluginFilter::pluginInCategory(plugin, category)) continue; Plugin *p = plugin->clone(); newlist.append(p); @@ -100,14 +98,14 @@ QList PluginManager::getPlugins(QString category) QList PluginManager::getCompatiblePlugins(QString param, QString category) { QList comp; - for(Plugin* plugin : qAsConst(list)) { - if(!PluginFilter::pluginInCategory(plugin,category)) + for(Plugin *plugin : qAsConst(list)) { + if(!PluginFilter::pluginInCategory(plugin, category)) continue; - bool enable = (!PluginFilter::pluginInExclusionList(comp,plugin)); + bool enable = (!PluginFilter::pluginInExclusionList(comp, plugin)); bool forcedInclusion = (PluginFilter::pluginForcedInclusionList(comp, plugin)); if(plugin->compatible(param, category) || forcedInclusion) { - Plugin* p = plugin->clone(); + Plugin *p = plugin->clone(); p->setParam(param, category); p->setEnabled(enable); comp.append(p); @@ -116,12 +114,9 @@ QList PluginManager::getCompatiblePlugins(QString param, QString categ return comp; } -void PluginManager::setMetadata(QJsonObject metadata) -{ - m_metadata = metadata; -} +void PluginManager::setMetadata(QJsonObject metadata) { m_metadata = metadata; } -Plugin* PluginManager::loadPlugin(QString file) +Plugin *PluginManager::loadPlugin(QString file) { bool ret; Plugin *original = nullptr; @@ -146,7 +141,7 @@ Plugin* PluginManager::loadPlugin(QString file) return nullptr; } - original = qobject_cast(qp.instance()); + original = qobject_cast(qp.instance()); if(!original) { qWarning(CAT_PLUGINMANAGER) << "Loaded library instance is not a Plugin*"; return nullptr; @@ -167,14 +162,8 @@ Plugin* PluginManager::loadPlugin(QString file) return clone; } -QList PluginManager::getOriginalPlugins() const -{ - return list; -} +QList PluginManager::getOriginalPlugins() const { return list; } -QJsonObject PluginManager::metadata() const -{ - return m_metadata; -} +QJsonObject PluginManager::metadata() const { return m_metadata; } #include "moc_pluginmanager.cpp" diff --git a/core/src/pluginrepository.cpp b/core/src/pluginrepository.cpp index 0a818b83b9..9024bd28ff 100644 --- a/core/src/pluginrepository.cpp +++ b/core/src/pluginrepository.cpp @@ -7,29 +7,26 @@ #include #include -#include #include #include +#include #include #include - -Q_LOGGING_CATEGORY(CAT_PLUGINREPOSTIORY,"PluginRepository"); +Q_LOGGING_CATEGORY(CAT_PLUGINREPOSTIORY, "PluginRepository"); using namespace scopy; -PluginRepository::PluginRepository(QObject *parent) : QObject(parent) +PluginRepository::PluginRepository(QObject *parent) + : QObject(parent) { pm = new PluginManager(this); } -PluginRepository::~PluginRepository() -{ - -} +PluginRepository::~PluginRepository() {} void PluginRepository::init(QString location) { - qInfo(CAT_PLUGINREPOSTIORY)<<"initializing plugins from: " << location; + qInfo(CAT_PLUGINREPOSTIORY) << "initializing plugins from: " << location; const QString pluginMetaFileName = "plugin.json"; QString pluginMetaFilePath = ""; QDir loc(location); @@ -54,10 +51,9 @@ void PluginRepository::init(QString location) if(err.error != QJsonParseError::NoError) { qCritical(CAT_PLUGINREPOSTIORY) << "JSON Parse error !" << err.errorString(); qCritical(CAT_PLUGINREPOSTIORY) << json; - qCritical(CAT_PLUGINREPOSTIORY) << QString(" ").repeated(err.offset)+"^"; - } - else { - qDebug(CAT_PLUGINREPOSTIORY) << "Found valid json @ "<setMetadata(metadata); @@ -65,10 +61,12 @@ void PluginRepository::init(QString location) #ifdef Q_OS_WINDOWS bool b = SetDllDirectoryA(QApplication::applicationDirPath().toStdString().c_str()); - if (!b) { + if(!b) { DWORD error = ::GetLastError(); std::string message = std::system_category().message(error); - qWarning(CAT_PLUGINREPOSTIORY) << "cannot add .exe folder to library search path - " << QString::fromStdString(message);; + qWarning(CAT_PLUGINREPOSTIORY) + << "cannot add .exe folder to library search path - " << QString::fromStdString(message); + ; } #endif @@ -77,7 +75,4 @@ void PluginRepository::init(QString location) pm->sort(); } - - - #include "moc_pluginrepository.cpp" diff --git a/core/src/scanbuttoncontroller.cpp b/core/src/scanbuttoncontroller.cpp index fe44f2633c..7b900b7bd3 100644 --- a/core/src/scanbuttoncontroller.cpp +++ b/core/src/scanbuttoncontroller.cpp @@ -2,30 +2,31 @@ using namespace scopy; -ScanButtonController::ScanButtonController(CyclicalTask *cs , QPushButton *btn, QObject *parent) +ScanButtonController::ScanButtonController(CyclicalTask *cs, QPushButton *btn, QObject *parent) : QObject{parent} { this->cs = cs; this->btn = btn; - conn = connect(this->btn,SIGNAL(toggled(bool)),this,SLOT(enableScan(bool))); -} -ScanButtonController::~ScanButtonController() { - disconnect(conn); + conn = connect(this->btn, SIGNAL(toggled(bool)), this, SLOT(enableScan(bool))); } +ScanButtonController::~ScanButtonController() { disconnect(conn); } -void ScanButtonController::enableScan(bool b) { +void ScanButtonController::enableScan(bool b) +{ if(b) startScan(); else stopScan(); } -void ScanButtonController::startScan() { +void ScanButtonController::startScan() +{ cs->start(2000); btn->setChecked(true); } -void ScanButtonController::stopScan() { +void ScanButtonController::stopScan() +{ cs->stop(); btn->setChecked(false); } diff --git a/core/src/scannediiocontextcollector.cpp b/core/src/scannediiocontextcollector.cpp index 13a9fb4648..934fe0ad88 100644 --- a/core/src/scannediiocontextcollector.cpp +++ b/core/src/scannediiocontextcollector.cpp @@ -1,4 +1,5 @@ #include "scannediiocontextcollector.h" + #include #include @@ -11,56 +12,48 @@ ScannedIIOContextCollector::ScannedIIOContextCollector(QObject *parent) qDebug(CAT_SCANCTXCOLLECTOR) << "ctor"; } -ScannedIIOContextCollector::~ScannedIIOContextCollector() -{ - qDebug(CAT_SCANCTXCOLLECTOR) << "dtor"; -} +ScannedIIOContextCollector::~ScannedIIOContextCollector() { qDebug(CAT_SCANCTXCOLLECTOR) << "dtor"; } void ScannedIIOContextCollector::update(QStringList list) { // Do we need to map Device* to uri in this class ? - QSet updatedUris = QSet(list.begin(),list.end()); + QSet updatedUris = QSet(list.begin(), list.end()); updatedUris = updatedUris + lockedUris; auto newUris = updatedUris - uris; auto deletedUris = uris - updatedUris; qDebug(CAT_SCANCTXCOLLECTOR) << "cached uris:" << uris; - for (const auto &uri : newUris) { + for(const auto &uri : newUris) { qInfo(CAT_SCANCTXCOLLECTOR) << "new device found: " << uri; -// if(!lockedUris.contains(uri)) - Q_EMIT foundDevice("iio",uri); - + // if(!lockedUris.contains(uri)) + Q_EMIT foundDevice("iio", uri); } - for (const auto &uri : deletedUris) { + for(const auto &uri : deletedUris) { qInfo(CAT_SCANCTXCOLLECTOR) << "to delete device: " << uri; -// if(!lockedUris.contains(uri)) - Q_EMIT lostDevice("iio",uri); - + // if(!lockedUris.contains(uri)) + Q_EMIT lostDevice("iio", uri); } uris = updatedUris; } -void ScannedIIOContextCollector::removeDevice(QString id, Device*d) { - uris.remove(d->param()); -} +void ScannedIIOContextCollector::removeDevice(QString id, Device *d) { uris.remove(d->param()); } -void ScannedIIOContextCollector::lock(QString uri, Device* d) { +void ScannedIIOContextCollector::lock(QString uri, Device *d) +{ if(uris.contains(d->param())) lockedUris.insert(d->param()); } -void ScannedIIOContextCollector::unlock(QString uri, Device *d) { +void ScannedIIOContextCollector::unlock(QString uri, Device *d) +{ if(uris.contains(d->param())) lockedUris.remove(d->param()); } -void ScannedIIOContextCollector::clearCache() -{ - uris.clear(); -} +void ScannedIIOContextCollector::clearCache() { uris.clear(); } #include "moc_scannediiocontextcollector.cpp" diff --git a/core/src/scopyaboutpage.cpp b/core/src/scopyaboutpage.cpp index 81a91b5cfe..3e0cd179ad 100644 --- a/core/src/scopyaboutpage.cpp +++ b/core/src/scopyaboutpage.cpp @@ -1,19 +1,23 @@ #include "scopyaboutpage.h" + #include "widgets/hoverwidget.h" #include "widgets/pagenavigationwidget.h" -#include -#include + #include #include +#include +#include + #include using namespace scopy; -ScopyAboutPage::ScopyAboutPage(QWidget *parent) : QWidget(parent) - , tabWidget(new QTabWidget(this)) - , layout(new QVBoxLayout(this)) +ScopyAboutPage::ScopyAboutPage(QWidget *parent) + : QWidget(parent) + , tabWidget(new QTabWidget(this)) + , layout(new QVBoxLayout(this)) { initUI(); - addHorizontalTab(buildPage(QString("qrc:/about.html")),"Scopy"); + addHorizontalTab(buildPage(QString("qrc:/about.html")), "Scopy"); } void ScopyAboutPage::initUI() @@ -26,7 +30,8 @@ void ScopyAboutPage::initUI() StyleHelper::TabWidgetEastMenu(tabWidget, "aboutPageTable"); } -QWidget* ScopyAboutPage::buildPage(QString src) { +QWidget *ScopyAboutPage::buildPage(QString src) +{ QWidget *page = new QWidget(this); QVBoxLayout *lay = new QVBoxLayout(page); QTextBrowser *browser = new QTextBrowser(page); @@ -35,7 +40,7 @@ QWidget* ScopyAboutPage::buildPage(QString src) { lay->setMargin(0); initNavigationWidget(browser); - if (QFile::exists(QString(src).replace("qrc:/", ":/"))) { + if(QFile::exists(QString(src).replace("qrc:/", ":/"))) { browser->setSource(src); } else { browser->setMarkdown(src); @@ -53,25 +58,24 @@ void ScopyAboutPage::initNavigationWidget(QTextBrowser *browser) QPushButton *backwardButton = navWidget->getBackwardBtn(); backwardButton->setEnabled(false); connect(backwardButton, SIGNAL(clicked()), browser, SLOT(backward())); - connect(browser, &QTextBrowser::backwardAvailable, backwardButton, [=](bool available){ - backwardButton->setEnabled(available); - }); + connect(browser, &QTextBrowser::backwardAvailable, backwardButton, + [=](bool available) { backwardButton->setEnabled(available); }); QPushButton *forwardButton = navWidget->getForwardBtn(); forwardButton->setEnabled(false); connect(forwardButton, SIGNAL(clicked()), browser, SLOT(forward())); - connect(browser, &QTextBrowser::forwardAvailable, forwardButton, [=](bool available){ - forwardButton->setEnabled(available); - }); + connect(browser, &QTextBrowser::forwardAvailable, forwardButton, + [=](bool available) { forwardButton->setEnabled(available); }); - HoverWidget* hover = new HoverWidget(navWidget, browser, browser); + HoverWidget *hover = new HoverWidget(navWidget, browser, browser); hover->setAnchorPos(HoverPosition::HP_TOPRIGHT); hover->setContentPos(HoverPosition::HP_BOTTOMLEFT); hover->setAnchorOffset(QPoint(-10, 0)); hover->show(); } -void ScopyAboutPage::addHorizontalTab(QWidget *w, QString text) { +void ScopyAboutPage::addHorizontalTab(QWidget *w, QString text) +{ // Hackish - so we don't override paint event tabWidget->addTab(w, ""); QLabel *lbl1 = new QLabel(); @@ -79,11 +83,8 @@ void ScopyAboutPage::addHorizontalTab(QWidget *w, QString text) { StyleHelper::TabWidgetLabel(lbl1, "tabWidgetLabel"); QTabBar *tabbar = tabWidget->tabBar(); tabbar->setTabButton(tabbar->count() - 1, QTabBar::RightSide, lbl1); - } -ScopyAboutPage::~ScopyAboutPage() { - -} +ScopyAboutPage::~ScopyAboutPage() {} #include "moc_scopyaboutpage.cpp" diff --git a/core/src/scopyhomeaddpage.cpp b/core/src/scopyhomeaddpage.cpp index d3aa34b0c7..3447142f78 100644 --- a/core/src/scopyhomeaddpage.cpp +++ b/core/src/scopyhomeaddpage.cpp @@ -1,19 +1,22 @@ #include "scopyhomeaddpage.h" #include "devicefactory.h" #include "deviceloader.h" + #include "ui_scopyhomeaddpage.h" -#include + #include #include +#include -Q_LOGGING_CATEGORY(CAT_HOME_ADD_PAGE,"ScopyHomeAddPage") +Q_LOGGING_CATEGORY(CAT_HOME_ADD_PAGE, "ScopyHomeAddPage") using namespace scopy; -ScopyHomeAddPage::ScopyHomeAddPage(QWidget *parent, PluginManager *pm) : - QWidget(parent), - ui(new Ui::ScopyHomeAddPage), - pluginManager(pm), deviceImpl(nullptr) +ScopyHomeAddPage::ScopyHomeAddPage(QWidget *parent, PluginManager *pm) + : QWidget(parent) + , ui(new Ui::ScopyHomeAddPage) + , pluginManager(pm) + , deviceImpl(nullptr) { ui->setupUi(this); this->setProperty("device_page", true); @@ -25,7 +28,7 @@ ScopyHomeAddPage::ScopyHomeAddPage(QWidget *parent, PluginManager *pm) : connect(ui->btnAdd, &QPushButton::clicked, this, &ScopyHomeAddPage::addBtnClicked); connect(ui->btnBack, &QPushButton::clicked, this, &ScopyHomeAddPage::backBtnClicked); - //verify iio device + // verify iio device fw = new QFutureWatcher(this); connect(fw, &QFutureWatcher::finished, this, &ScopyHomeAddPage::onVerifyFinished, Qt::QueuedConnection); connect(this, &ScopyHomeAddPage::verifyFinished, iioTabWidget, &IioTabWidget::onVerifyFinished); @@ -33,8 +36,8 @@ ScopyHomeAddPage::ScopyHomeAddPage(QWidget *parent, PluginManager *pm) : connect(emuWidget, &EmuWidget::emuDeviceAvailable, this, &ScopyHomeAddPage::onEmuDeviceAvailable); - connect(ui->stackedWidget, &QStackedWidget::currentChanged, this, [=](){ - if (ui->stackedWidget->currentWidget() == ui->addPage) { + connect(ui->stackedWidget, &QStackedWidget::currentChanged, this, [=]() { + if(ui->stackedWidget->currentWidget() == ui->addPage) { ui->btnAdd->setFocus(); } }); @@ -43,7 +46,7 @@ ScopyHomeAddPage::ScopyHomeAddPage(QWidget *parent, PluginManager *pm) : ScopyHomeAddPage::~ScopyHomeAddPage() { delete ui; - if (deviceImpl) { + if(deviceImpl) { delete deviceImpl; deviceImpl = nullptr; } @@ -64,7 +67,7 @@ void ScopyHomeAddPage::initAddPage() ui->btnAdd->setProperty("blue_button", QVariant(true)); ui->btnBack->setProperty("blue_button", QVariant(true)); - ui->btnAdd->setAutoDefault(true); + ui->btnAdd->setAutoDefault(true); } void ScopyHomeAddPage::initSubSections() @@ -75,7 +78,7 @@ void ScopyHomeAddPage::initSubSections() ui->deviceInfo->setLabel("Device info"); deviceInfoPage = new InfoPage(ui->deviceInfo->getContentWidget()); deviceInfoPage->setAdvancedMode(false); - deviceInfoPage->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); + deviceInfoPage->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); ui->deviceInfo->getContentWidget()->layout()->addWidget(deviceInfoPage); QSpacerItem *vSpacer = new QSpacerItem(40, 20, QSizePolicy::Minimum, QSizePolicy::Expanding); ui->deviceInfo->getContentWidget()->layout()->addItem(vSpacer); @@ -86,18 +89,18 @@ void ScopyHomeAddPage::futureVerify(QString uri, QString cat) removePluginsCheckBoxes(); deviceInfoPage->clear(); deviceImpl = DeviceFactory::build(uri, pluginManager, cat); - QFuture f = QtConcurrent::run(std::bind(&DeviceImpl::verify,deviceImpl)); + QFuture f = QtConcurrent::run(std::bind(&DeviceImpl::verify, deviceImpl)); fw->setFuture(f); } void ScopyHomeAddPage::onVerifyFinished() { bool result = fw->result(); - if (result) { + if(result) { loadDeviceInfoPage(); initializeDevice(); } else { - if (deviceImpl) { + if(deviceImpl) { delete deviceImpl; deviceImpl = nullptr; } @@ -108,34 +111,34 @@ void ScopyHomeAddPage::onVerifyFinished() void ScopyHomeAddPage::loadDeviceInfoPage() { QMap deviceInfoMap = deviceImpl->readDeviceInfo(); - foreach (const QString &key, deviceInfoMap.keys()){ + foreach(const QString &key, deviceInfoMap.keys()) { deviceInfoPage->update(key, deviceInfoMap[key]); } } void ScopyHomeAddPage::initializeDevice() { - if (deviceImpl) { - DeviceLoader* dl = new DeviceLoader(deviceImpl, this); + if(deviceImpl) { + DeviceLoader *dl = new DeviceLoader(deviceImpl, this); dl->init(); connect(dl, &DeviceLoader::initialized, this, &ScopyHomeAddPage::deviceLoaderInitialized); - connect(dl, &DeviceLoader::initialized, dl, &QObject::deleteLater); // don't forget to delete loader once we're done + connect(dl, &DeviceLoader::initialized, dl, + &QObject::deleteLater); // don't forget to delete loader once we're done } } void ScopyHomeAddPage::deviceLoaderInitialized() { QList plugins = deviceImpl->plugins(); - for (Plugin *p : qAsConst(plugins)) { - PluginEnableWidget *pluginDescription = new PluginEnableWidget(ui->devicePluginBrowser->getContentWidget()); + for(Plugin *p : qAsConst(plugins)) { + PluginEnableWidget *pluginDescription = + new PluginEnableWidget(ui->devicePluginBrowser->getContentWidget()); pluginDescription->setDescription(p->description()); pluginDescription->checkBox()->setText(p->name()); pluginDescription->checkBox()->setChecked(p->enabled()); ui->devicePluginBrowser->getContentWidget()->layout()->addWidget(pluginDescription); pluginDescriptionList.push_back(pluginDescription); - connect(pluginDescription->checkBox(), &QCheckBox::toggled, this, [=](bool en){ - p->setEnabled(en); - }); + connect(pluginDescription->checkBox(), &QCheckBox::toggled, this, [=](bool en) { p->setEnabled(en); }); } ui->stackedWidget->setCurrentWidget(ui->addPage); Q_EMIT verifyFinished(true); @@ -144,7 +147,7 @@ void ScopyHomeAddPage::deviceLoaderInitialized() void ScopyHomeAddPage::addBtnClicked() { bool connection = deviceImpl->verify(); - if (!connection) { + if(!connection) { ui->labelConnectionLost->setText("Connection with " + deviceImpl->param() + " has been lost!"); return; } @@ -166,7 +169,7 @@ void ScopyHomeAddPage::deviceAddedToUi(QString id) void ScopyHomeAddPage::backBtnClicked() { - if (deviceImpl) { + if(deviceImpl) { delete deviceImpl; deviceImpl = nullptr; } diff --git a/core/src/scopyhomeinfopage.cpp b/core/src/scopyhomeinfopage.cpp index fe10dac17f..e48e729b0f 100644 --- a/core/src/scopyhomeinfopage.cpp +++ b/core/src/scopyhomeinfopage.cpp @@ -1,24 +1,25 @@ #include "scopyhomeinfopage.h" -#include -#include + #include "ui_scopyhomeinfopage.h" +#include + +#include + using namespace scopy; -ScopyHomeInfoPage::ScopyHomeInfoPage(QWidget *parent) : - QWidget(parent), - ui(new Ui::ScopyHomeInfoPage) +ScopyHomeInfoPage::ScopyHomeInfoPage(QWidget *parent) + : QWidget(parent) + , ui(new Ui::ScopyHomeInfoPage) { ui->setupUi(this); -// initReportButton(); + // initReportButton(); } -ScopyHomeInfoPage::~ScopyHomeInfoPage() -{ - delete ui; -} +ScopyHomeInfoPage::~ScopyHomeInfoPage() { delete ui; } -void ScopyHomeInfoPage::initReportButton() { +void ScopyHomeInfoPage::initReportButton() +{ auto reportButton = new QPushButton("Report a bug"); StyleHelper::BlueButton(reportButton, "reportButton"); reportButton->setFixedSize(100, 40); @@ -30,7 +31,7 @@ void ScopyHomeInfoPage::initReportButton() { reportBtnHoverWidget->setVisible(true); reportBtnHoverWidget->raise(); - connect(reportButton, &QPushButton::clicked, [] () { + connect(reportButton, &QPushButton::clicked, []() { const QUrl url("https://wiki.analog.com/university/tools/m2k/scopy/report"); QDesktopServices::openUrl(url); }); diff --git a/core/src/scopyhomepage.cpp b/core/src/scopyhomepage.cpp index 4dbbad3a18..e48af187fe 100644 --- a/core/src/scopyhomepage.cpp +++ b/core/src/scopyhomepage.cpp @@ -1,14 +1,17 @@ #include "scopyhomepage.h" + #include "scopyhomeinfopage.h" + #include "ui_scopyhomepage.h" + #include -#include +#include using namespace scopy; -ScopyHomePage::ScopyHomePage(QWidget *parent, PluginManager *pm ) : - QWidget(parent), - ui(new Ui::ScopyHomePage) +ScopyHomePage::ScopyHomePage(QWidget *parent, PluginManager *pm) + : QWidget(parent) + , ui(new Ui::ScopyHomePage) { ui->setupUi(this); auto &&is = ui->wInfoPageStack; @@ -16,27 +19,22 @@ ScopyHomePage::ScopyHomePage(QWidget *parent, PluginManager *pm ) : auto &&db = ui->wDeviceBrowser; add = new ScopyHomeAddPage(this, pm); - is->add("home",new ScopyHomeInfoPage()); + is->add("home", new ScopyHomeInfoPage()); is->add("add", add); -// addDevice("dev1","dev1","descr1",new QPushButton("abc"),new QLabel("page1")); - connect(hc,SIGNAL(goLeft()),db,SLOT(prevDevice())); - connect(hc,SIGNAL(goRight()),db,SLOT(nextDevice())); - connect(db,SIGNAL(requestDevice(QString,int)),is,SLOT(slideInKey(QString,int))); - connect(db,SIGNAL(requestDevice(QString,int)),this,SIGNAL(requestDevice(QString))); - connect(this,SIGNAL(deviceAddedToUi(QString)),add,SLOT(deviceAddedToUi(QString))); + // addDevice("dev1","dev1","descr1",new QPushButton("abc"),new QLabel("page1")); + connect(hc, SIGNAL(goLeft()), db, SLOT(prevDevice())); + connect(hc, SIGNAL(goRight()), db, SLOT(nextDevice())); + connect(db, SIGNAL(requestDevice(QString, int)), is, SLOT(slideInKey(QString, int))); + connect(db, SIGNAL(requestDevice(QString, int)), this, SIGNAL(requestDevice(QString))); + connect(this, SIGNAL(deviceAddedToUi(QString)), add, SLOT(deviceAddedToUi(QString))); - connect(add,SIGNAL(requestAddDevice(QString,QString)),this,SIGNAL(requestAddDevice(QString,QString))); - connect(add,&ScopyHomeAddPage::requestDevice,this,[=](QString id){Q_EMIT db->requestDevice(id,-1);}); - connect(add, &ScopyHomeAddPage::newDeviceAvailable, this, [=](DeviceImpl *d){ - Q_EMIT newDeviceAvailable(d); - }); + connect(add, SIGNAL(requestAddDevice(QString, QString)), this, SIGNAL(requestAddDevice(QString, QString))); + connect(add, &ScopyHomeAddPage::requestDevice, this, [=](QString id) { Q_EMIT db->requestDevice(id, -1); }); + connect(add, &ScopyHomeAddPage::newDeviceAvailable, this, [=](DeviceImpl *d) { Q_EMIT newDeviceAvailable(d); }); } -ScopyHomePage::~ScopyHomePage() -{ - delete ui; -} +ScopyHomePage::~ScopyHomePage() { delete ui; } void ScopyHomePage::addDevice(QString id, Device *d) { @@ -47,30 +45,31 @@ void ScopyHomePage::addDevice(QString id, Device *d) Q_EMIT deviceAddedToUi(id); } -void ScopyHomePage::removeDevice(QString id) { +void ScopyHomePage::removeDevice(QString id) +{ auto &&is = ui->wInfoPageStack; auto &&db = ui->wDeviceBrowser; db->removeDevice(id); is->remove(id); } -void ScopyHomePage::viewDevice(QString id) { +void ScopyHomePage::viewDevice(QString id) +{ auto &&db = ui->wDeviceBrowser; - Q_EMIT db->requestDevice(id,-1); + Q_EMIT db->requestDevice(id, -1); } -void ScopyHomePage::connectDevice(QString id) { +void ScopyHomePage::connectDevice(QString id) +{ auto &&db = ui->wDeviceBrowser; db->connectDevice(id); - } -void ScopyHomePage::disconnectDevice(QString id) { +void ScopyHomePage::disconnectDevice(QString id) +{ auto &&db = ui->wDeviceBrowser; db->disconnectDevice(id); } -QPushButton* ScopyHomePage::scanControlBtn() { - return ui->btnScan; -} +QPushButton *ScopyHomePage::scanControlBtn() { return ui->btnScan; } #include "moc_scopyhomepage.cpp" diff --git a/core/src/scopymainwindow.cpp b/core/src/scopymainwindow.cpp index 75f254277f..3fa0d21a68 100644 --- a/core/src/scopymainwindow.cpp +++ b/core/src/scopymainwindow.cpp @@ -1,44 +1,45 @@ -#include -#include -#include -#include -#include -#include -#include +#include "scopymainwindow.h" +#include "animationmanager.h" +#include "device.h" +#include "iioutil/contextprovider.h" #include "logging_categories.h" +#include "pluginbase/messagebroker.h" +#include "pluginbase/preferences.h" +#include "pluginbase/scopyjs.h" +#include "popupwidget.h" #include "qmessagebox.h" -#include "scopymainwindow.h" -#include "animationmanager.h" - #include "scanbuttoncontroller.h" -#include "ui_scopymainwindow.h" -#include "scopyhomepage.h" +#include "scopy-core_config.h" #include "scopyaboutpage.h" +#include "scopyhomepage.h" #include "scopypreferencespage.h" -#include "device.h" -#include "pluginbase/preferences.h" -#include "pluginbase/scopyjs.h" -#include "iioutil/contextprovider.h" -#include "pluginbase/messagebroker.h" -#include "scopy-core_config.h" -#include "popupwidget.h" +#include "ui_scopymainwindow.h" + +#include +#include +#include +#include +#include +#include +#include + #include -#include -#include #include -#include -#include +#include #include +#include +#include +#include using namespace scopy; -Q_LOGGING_CATEGORY(CAT_SCOPY,"Scopy") +Q_LOGGING_CATEGORY(CAT_SCOPY, "Scopy") ScopyMainWindow::ScopyMainWindow(QWidget *parent) - : QMainWindow(parent) - , ui(new Ui::ScopyMainWindow) + : QMainWindow(parent) + , ui(new Ui::ScopyMainWindow) { QElapsedTimer timer; timer.start(); @@ -55,7 +56,8 @@ ScopyMainWindow::ScopyMainWindow(QWidget *parent) // get the version document auto vc = VersionChecker::GetInstance(); // get VersionCache instance - vc->subscribe(this, &ScopyMainWindow::receiveVersionDocument); // 'subscribe' to receive the version QJsonDocument + vc->subscribe(this, + &ScopyMainWindow::receiveVersionDocument); // 'subscribe' to receive the version QJsonDocument auto tb = ui->wToolBrowser; auto ts = ui->wsToolStack; @@ -63,7 +65,7 @@ ScopyMainWindow::ScopyMainWindow(QWidget *parent) scanTask = new IIOScanTask(this); scanTask->setScanParams("usb"); - scanCycle = new CyclicalTask(scanTask,this); + scanCycle = new CyclicalTask(scanTask, this); scc = new ScannedIIOContextCollector(this); pr = new PluginRepository(this); loadPluginsFromRepository(pr); @@ -75,55 +77,59 @@ ScopyMainWindow::ScopyMainWindow(QWidget *parent) initTranslations(); hp = new ScopyHomePage(this, pm); - ScanButtonController *sbc = new ScanButtonController(scanCycle,hp->scanControlBtn(),this); + ScanButtonController *sbc = new ScanButtonController(scanCycle, hp->scanControlBtn(), this); dm = new DeviceManager(pm, this); dm->setExclusive(true); dtm = new DetachedToolWindowManager(this); - toolman = new ToolManager(tm,ts,dtm,this); - toolman->addToolList("home",{}); - toolman->addToolList("add",{}); - - connect(tm,&ToolMenu::toggleAttach,toolman,&ToolManager::toggleAttach); - connect(tb,&ToolBrowser::collapsed,[=](bool coll){ ui->animHolder->setAnimMin(50); ui->animHolder->toggleMenu(!coll); }); - connect(tb,&ToolBrowser::requestTool,ts, &ToolStack::show); - connect(tb,&ToolBrowser::requestTool,dtm, &DetachedToolWindowManager::show); + toolman = new ToolManager(tm, ts, dtm, this); + toolman->addToolList("home", {}); + toolman->addToolList("add", {}); + + connect(tm, &ToolMenu::toggleAttach, toolman, &ToolManager::toggleAttach); + connect(tb, &ToolBrowser::collapsed, [=](bool coll) { + ui->animHolder->setAnimMin(50); + ui->animHolder->toggleMenu(!coll); + }); + connect(tb, &ToolBrowser::requestTool, ts, &ToolStack::show); + connect(tb, &ToolBrowser::requestTool, dtm, &DetachedToolWindowManager::show); ts->add("home", hp); ts->add("about", about); ts->add("preferences", prefPage); - connect(scanTask,SIGNAL(scanFinished(QStringList)),scc,SLOT(update(QStringList))); + connect(scanTask, SIGNAL(scanFinished(QStringList)), scc, SLOT(update(QStringList))); - connect(scc,SIGNAL(foundDevice(QString,QString)),dm,SLOT(createDevice(QString,QString))); - connect(scc,SIGNAL(lostDevice(QString,QString)),dm,SLOT(removeDevice(QString,QString))); + connect(scc, SIGNAL(foundDevice(QString, QString)), dm, SLOT(createDevice(QString, QString))); + connect(scc, SIGNAL(lostDevice(QString, QString)), dm, SLOT(removeDevice(QString, QString))); - connect(hp,SIGNAL(requestDevice(QString)),this,SLOT(requestTools(QString))); + connect(hp, SIGNAL(requestDevice(QString)), this, SLOT(requestTools(QString))); - connect(hp,SIGNAL(requestAddDevice(QString,QString)),dm,SLOT(createDevice(QString,QString))); - connect(dm,SIGNAL(deviceAdded(QString,Device*)),this,SLOT(addDeviceToUi(QString,Device*))); + connect(hp, SIGNAL(requestAddDevice(QString, QString)), dm, SLOT(createDevice(QString, QString))); + connect(dm, SIGNAL(deviceAdded(QString, Device *)), this, SLOT(addDeviceToUi(QString, Device *))); - connect(dm,SIGNAL(deviceRemoveStarted(QString,Device*)),scc,SLOT(removeDevice(QString,Device*))); - connect(dm,SIGNAL(deviceRemoveStarted(QString,Device*)),this,SLOT(removeDeviceFromUi(QString))); + connect(dm, SIGNAL(deviceRemoveStarted(QString, Device *)), scc, SLOT(removeDevice(QString, Device *))); + connect(dm, SIGNAL(deviceRemoveStarted(QString, Device *)), this, SLOT(removeDeviceFromUi(QString))); if(dm->getExclusive()) { // only for device manager exclusive mode - stop scan on connect - connect(dm,SIGNAL(deviceConnected(QString,Device*)),sbc,SLOT(stopScan())); - connect(dm,SIGNAL(deviceDisconnected(QString,Device*)),sbc,SLOT(startScan())); + connect(dm, SIGNAL(deviceConnected(QString, Device *)), sbc, SLOT(stopScan())); + connect(dm, SIGNAL(deviceDisconnected(QString, Device *)), sbc, SLOT(startScan())); } - connect(dm,SIGNAL(deviceConnected(QString,Device*)),scc,SLOT(lock(QString,Device*))); - connect(dm,SIGNAL(deviceConnected(QString,Device*)),toolman,SLOT(lockToolList(QString))); - connect(dm,SIGNAL(deviceConnected(QString,Device*)),hp,SLOT(connectDevice(QString))); - connect(dm,SIGNAL(deviceDisconnected(QString,Device*)),scc,SLOT(unlock(QString,Device*))); - connect(dm,SIGNAL(deviceDisconnected(QString,Device*)),toolman,SLOT(unlockToolList(QString))); - connect(dm,SIGNAL(deviceDisconnected(QString,Device*)),hp,SLOT(disconnectDevice(QString))); + connect(dm, SIGNAL(deviceConnected(QString, Device *)), scc, SLOT(lock(QString, Device *))); + connect(dm, SIGNAL(deviceConnected(QString, Device *)), toolman, SLOT(lockToolList(QString))); + connect(dm, SIGNAL(deviceConnected(QString, Device *)), hp, SLOT(connectDevice(QString))); + connect(dm, SIGNAL(deviceDisconnected(QString, Device *)), scc, SLOT(unlock(QString, Device *))); + connect(dm, SIGNAL(deviceDisconnected(QString, Device *)), toolman, SLOT(unlockToolList(QString))); + connect(dm, SIGNAL(deviceDisconnected(QString, Device *)), hp, SLOT(disconnectDevice(QString))); - connect(dm,SIGNAL(requestDevice(QString)),hp,SLOT(viewDevice(QString))); - connect(dm,SIGNAL(requestTool(QString)),toolman,SLOT(showTool(QString))); + connect(dm, SIGNAL(requestDevice(QString)), hp, SLOT(viewDevice(QString))); + connect(dm, SIGNAL(requestTool(QString)), toolman, SLOT(showTool(QString))); - connect(dm,SIGNAL(deviceChangedToolList(QString,QList)),toolman,SLOT(changeToolListContents(QString,QList))); + connect(dm, SIGNAL(deviceChangedToolList(QString, QList)), toolman, + SLOT(changeToolListContents(QString, QList))); sbc->startScan(); connect(tb, SIGNAL(requestSave()), this, SLOT(save())); @@ -147,14 +153,15 @@ ScopyMainWindow::ScopyMainWindow(QWidget *parent) qInfo(CAT_BENCHMARK) << "ScopyMainWindow constructor took: " << timer.elapsed() << "ms"; } -void ScopyMainWindow::save() { +void ScopyMainWindow::save() +{ QString selectedFilter; QString fileName = QFileDialog::getSaveFileName(this, tr("Save"), "", "", &selectedFilter); save(fileName); - } -void ScopyMainWindow::load() { +void ScopyMainWindow::load() +{ QString selectedFilter; QString fileName = QFileDialog::getOpenFileName(this, tr("Open"), "", "", &selectedFilter); load(fileName); @@ -172,16 +179,12 @@ void ScopyMainWindow::load(QString file) dm->load(s); } -void ScopyMainWindow::closeEvent(QCloseEvent *event) -{ - dm->disconnectAll(); -} +void ScopyMainWindow::closeEvent(QCloseEvent *event) { dm->disconnectAll(); } -void ScopyMainWindow::requestTools(QString id) { - toolman->showToolList(id); -} +void ScopyMainWindow::requestTools(QString id) { toolman->showToolList(id); } -ScopyMainWindow::~ScopyMainWindow(){ +ScopyMainWindow::~ScopyMainWindow() +{ scanCycle->stop(); delete ui; @@ -194,28 +197,27 @@ void ScopyMainWindow::initAboutPage(PluginManager *pm) about = new ScopyAboutPage(this); if(!pm) return; - QList plugin = pm->getOriginalPlugins(); - for(Plugin* p : plugin) { + QList plugin = pm->getOriginalPlugins(); + for(Plugin *p : plugin) { QString content = p->about(); if(!content.isEmpty()) { - about->addHorizontalTab(about->buildPage(content),p->name()); + about->addHorizontalTab(about->buildPage(content), p->name()); } } qInfo(CAT_BENCHMARK) << " Init about page took: " << timer.elapsed() << "ms"; } - void ScopyMainWindow::initPreferencesPage(PluginManager *pm) { prefPage = new ScopyPreferencesPage(this); if(!pm) return; - QList plugin = pm->getOriginalPlugins(); - for(Plugin* p : plugin) { + QList plugin = pm->getOriginalPlugins(); + for(Plugin *p : plugin) { p->initPreferences(); if(p->loadPreferencesPage()) { - prefPage->addHorizontalTab(p->preferencesPage(),p->name()); + prefPage->addHorizontalTab(p->preferencesPage(), p->name()); } } } @@ -230,7 +232,7 @@ void ScopyMainWindow::initPreferences() { QElapsedTimer timer; timer.start(); - QString preferencesPath = scopy::config::preferencesFolderPath() + "/preferences.ini"; + QString preferencesPath = scopy::config::preferencesFolderPath() + "/preferences.ini"; Preferences *p = Preferences::GetInstance(); p->setPreferencesFilename(preferencesPath); p->load(); @@ -250,15 +252,15 @@ void ScopyMainWindow::initPreferences() p->init("general_doubleclick_ctrl_opens_menu", true); p->init("general_check_online_version", false); - connect(p, SIGNAL(preferenceChanged(QString,QVariant)), this, SLOT(handlePreferences(QString,QVariant))); + connect(p, SIGNAL(preferenceChanged(QString, QVariant)), this, SLOT(handlePreferences(QString, QVariant))); - if (p->get("general_use_opengl").toBool()) { + if(p->get("general_use_opengl").toBool()) { loadOpenGL(); } - if(p->get("general_load_decoders").toBool()){ + if(p->get("general_load_decoders").toBool()) { loadDecoders(); } - if (p->get("general_first_run").toBool()) { + if(p->get("general_first_run").toBool()) { license = new LicenseOverlay(this); checkUpdate = new VersionCheckOverlay(this); @@ -268,14 +270,16 @@ void ScopyMainWindow::initPreferences() QString theme = p->get("general_theme").toString(); QString themeName = "scopy-" + theme; QIcon::setThemeName(themeName); - QIcon::setThemeSearchPaths({":/gui/icons/"+themeName}); + QIcon::setThemeSearchPaths({":/gui/icons/" + themeName}); qInfo(CAT_BENCHMARK) << "Init preferences took: " << timer.elapsed() << "ms"; } -void ScopyMainWindow::loadOpenGL() { +void ScopyMainWindow::loadOpenGL() +{ // this should be part of scopygui - // set surfaceFormat as in Qt example: HelloGL2 - https://code.qt.io/cgit/qt/qtbase.git/tree/examples/opengl/hellogl2/main.cpp?h=5.15#n81 + // set surfaceFormat as in Qt example: HelloGL2 - + // https://code.qt.io/cgit/qt/qtbase.git/tree/examples/opengl/hellogl2/main.cpp?h=5.15#n81 QSurfaceFormat fmt; // fmt.setDepthBufferSize(24); // QSurfaceFormat::setDefaultFormat(fmt); @@ -289,16 +293,16 @@ void ScopyMainWindow::loadOpenGL() { a->deleteLater(); } -void ScopyMainWindow::loadPluginsFromRepository(PluginRepository *pr){ +void ScopyMainWindow::loadPluginsFromRepository(PluginRepository *pr) +{ QElapsedTimer timer; timer.start(); // Check the local plugins folder first QDir pathDir(scopy::config::localPluginFolderPath()); - if (pathDir.exists()){ + if(pathDir.exists()) { pr->init(scopy::config::localPluginFolderPath()); - } - else{ + } else { pr->init(scopy::config::defaultPluginFolderPath()); } #ifndef Q_OS_ANDROID @@ -310,8 +314,8 @@ void ScopyMainWindow::loadPluginsFromRepository(PluginRepository *pr){ qInfo(CAT_BENCHMARK) << "Loading the plugins from the repository took: " << timer.elapsed() << "ms"; } - -void ScopyMainWindow::handlePreferences(QString str,QVariant val) { +void ScopyMainWindow::handlePreferences(QString str, QVariant val) +{ Preferences *p = Preferences::GetInstance(); if(str == "general_use_opengl") { @@ -328,7 +332,8 @@ void ScopyMainWindow::handlePreferences(QString str,QVariant val) { } } -void ScopyMainWindow::initPythonWIN32(){ +void ScopyMainWindow::initPythonWIN32() +{ #ifdef WIN32 QString pythonhome; QString pythonpath; @@ -340,65 +345,65 @@ void ScopyMainWindow::initPythonWIN32(){ QString scopypythonpath = qgetenv("SCOPY_PYTHONPATH"); pythonpath += scopypythonpath; - #ifdef SCOPY_DEV_MODE - pythonhome += QString(BUILD_PYTHON_LIBRARY_DIRS) +";"; - pythonpath += QString(BUILD_PYTHON_LIBRARY_DIRS) +";"; - pythonpath += QString(BUILD_PYTHON_LIBRARY_DIRS) + "\\plat-win;"; - pythonpath += QString(BUILD_PYTHON_LIBRARY_DIRS) + "\\lib-dynload;"; - pythonpath += QString(BUILD_PYTHON_LIBRARY_DIRS) + "\\site-packages;"; - #endif +#ifdef SCOPY_DEV_MODE + pythonhome += QString(BUILD_PYTHON_LIBRARY_DIRS) + ";"; + pythonpath += QString(BUILD_PYTHON_LIBRARY_DIRS) + ";"; + pythonpath += QString(BUILD_PYTHON_LIBRARY_DIRS) + "\\plat-win;"; + pythonpath += QString(BUILD_PYTHON_LIBRARY_DIRS) + "\\lib-dynload;"; + pythonpath += QString(BUILD_PYTHON_LIBRARY_DIRS) + "\\site-packages;"; +#endif qputenv("PYTHONHOME", pythonhome.toLocal8Bit()); qputenv("PYTHONPATH", pythonpath.toLocal8Bit()); - qInfo(CAT_SCOPY) <<"SCOPY_PYTHONPATH: " << scopypythonpath; - qInfo(CAT_SCOPY) <<"PYTHONHOME: " << qgetenv("PYTHONHOME"); - qInfo(CAT_SCOPY) <<"PYTHONPATH: " << qgetenv("PYTHONPATH"); + qInfo(CAT_SCOPY) << "SCOPY_PYTHONPATH: " << scopypythonpath; + qInfo(CAT_SCOPY) << "PYTHONHOME: " << qgetenv("PYTHONHOME"); + qInfo(CAT_SCOPY) << "PYTHONPATH: " << qgetenv("PYTHONPATH"); #endif } - void ScopyMainWindow::loadDecoders() { QElapsedTimer timer; timer.start(); - #if defined(WITH_SIGROK) && defined(WITH_PYTHON) - #if defined __APPLE__ - QString path = QCoreApplication::applicationDirPath() + "/decoders"; - #else - QString path = "decoders"; - #endif - - bool success = true; - static bool srd_loaded = false; - if (srd_loaded) { - srd_exit(); - } +#if defined(WITH_SIGROK) && defined(WITH_PYTHON) +#if defined __APPLE__ + QString path = QCoreApplication::applicationDirPath() + "/decoders"; +#else + QString path = "decoders"; +#endif - if (srd_init(path.toStdString().c_str()) != SRD_OK) { - qInfo(CAT_SCOPY) << "ERROR: libsigrokdecode init failed."; + bool success = true; + static bool srd_loaded = false; + if(srd_loaded) { + srd_exit(); + } + + if(srd_init(path.toStdString().c_str()) != SRD_OK) { + qInfo(CAT_SCOPY) << "ERROR: libsigrokdecode init failed."; + success = false; + } else { + srd_loaded = true; + /* Load the protocol decoders */ + srd_decoder_load_all(); + auto decoder = srd_decoder_get_by_id("parallel"); + + if(decoder == nullptr) { success = false; - } else { - srd_loaded = true; - /* Load the protocol decoders */ - srd_decoder_load_all(); - auto decoder = srd_decoder_get_by_id("parallel"); - - if (decoder == nullptr) { - success = false; - qInfo(CAT_SCOPY) << "ERROR: libsigrokdecode load the protocol decoders failed."; - } + qInfo(CAT_SCOPY) << "ERROR: libsigrokdecode load the protocol decoders failed."; } + } - if (!success) { - QMessageBox error(this); - error.setText(tr("ERROR: There was a problem initializing libsigrokdecode. Some features may be missing")); - error.exec(); - } - #else - qInfo(CAT_SCOPY) << "Python or libsigrokdecode are disabled, can't load decoders"; - #endif - qInfo(CAT_BENCHMARK) << "Loading the decoders took: " << timer.elapsed() << "ms"; + if(!success) { + QMessageBox error(this); + error.setText( + tr("ERROR: There was a problem initializing libsigrokdecode. Some features may be missing")); + error.exec(); + } +#else + qInfo(CAT_SCOPY) << "Python or libsigrokdecode are disabled, can't load decoders"; +#endif + qInfo(CAT_BENCHMARK) << "Loading the decoders took: " << timer.elapsed() << "ms"; } void ScopyMainWindow::initApi() @@ -411,8 +416,8 @@ void ScopyMainWindow::initApi() void ScopyMainWindow::addDeviceToUi(QString id, Device *d) { - toolman->addToolList(id,d->toolList()); - hp->addDevice(id,d); + toolman->addToolList(id, d->toolList()); + hp->addDevice(id, d); } void ScopyMainWindow::removeDeviceFromUi(QString id) @@ -421,9 +426,9 @@ void ScopyMainWindow::removeDeviceFromUi(QString id) hp->removeDevice(id); } -void ScopyMainWindow::receiveVersionDocument(QJsonDocument document) { +void ScopyMainWindow::receiveVersionDocument(QJsonDocument document) +{ qInfo(CAT_SCOPY) << "The upstream scopy version is" << document << "and the current one is" << SCOPY_VERSION; } - #include "moc_scopymainwindow.cpp" diff --git a/core/src/scopymainwindow_api.cpp b/core/src/scopymainwindow_api.cpp index 90dd28d124..d5f9fbb500 100644 --- a/core/src/scopymainwindow_api.cpp +++ b/core/src/scopymainwindow_api.cpp @@ -1,28 +1,26 @@ #include "scopymainwindow_api.h" -#include + #include "qapplication.h" + +#include using namespace scopy; Q_LOGGING_CATEGORY(CAT_SCOPY_API, "Scopy_API") - ScopyMainWindow_API::ScopyMainWindow_API(ScopyMainWindow *w) : ApiObject() , m_w(w) -{ -} +{} -ScopyMainWindow_API::~ScopyMainWindow_API() -{ -} +ScopyMainWindow_API::~ScopyMainWindow_API() {} void ScopyMainWindow_API::acceptLicense() { - if (m_w->license) { + if(m_w->license) { Q_EMIT m_w->license->getContinueBtn()->clicked(); } - if (m_w->checkUpdate) { + if(m_w->checkUpdate) { Q_EMIT m_w->checkUpdate->getExitBtn()->clicked(); } } @@ -44,12 +42,12 @@ bool ScopyMainWindow_API::connectDevice(int idx) bool successfulConnection = false; QList mapKeys = m_w->dm->map.keys(); std::sort(mapKeys.begin(), mapKeys.end(), sortByUUID); - if (idx < mapKeys.size()) { + if(idx < mapKeys.size()) { dev = m_w->dm->map[mapKeys[idx]]; } - if (dev) { + if(dev) { isConnected = m_w->dm->connectedDev.contains(dev->id()); - if (!isConnected) { + if(!isConnected) { dev->connectDev(); successfulConnection = true; } else { @@ -66,9 +64,9 @@ bool ScopyMainWindow_API::connectDevice(QString devID) Q_ASSERT(m_w->dm != nullptr); Device *dev = m_w->dm->getDevice(devID); bool successfulConnection = false; - if (dev) { + if(dev) { bool isConnected = m_w->dm->connectedDev.contains(dev->id()); - if (!isConnected) { + if(!isConnected) { dev->connectDev(); successfulConnection = true; } else { @@ -84,7 +82,7 @@ bool ScopyMainWindow_API::disconnectDevice(QString devID) { Q_ASSERT(m_w->dm != nullptr); Device *dev = m_w->dm->getDevice(devID); - if (dev) { + if(dev) { dev->disconnectDev(); } else { qWarning(CAT_SCOPY_API) << "Device with id " << devID << " is not available!"; @@ -97,11 +95,11 @@ bool ScopyMainWindow_API::disconnectDevice() { Q_ASSERT(m_w->dm != nullptr); QString devID = ""; - if (!m_w->dm->connectedDev.isEmpty()) { + if(!m_w->dm->connectedDev.isEmpty()) { devID = m_w->dm->connectedDev.back(); } Device *dev = m_w->dm->getDevice(devID); - if (dev) { + if(dev) { dev->disconnectDev(); } else { qWarning(CAT_SCOPY_API) << "Device with id " << devID << " is not available!"; @@ -114,15 +112,14 @@ void ScopyMainWindow_API::switchTool(QString devID, QString toolName) { Q_ASSERT(m_w->dm != nullptr); Device *dev = m_w->dm->getDevice(devID); - if (dev) { + if(dev) { ToolMenuEntry *tool = ToolMenuEntry::findToolMenuEntryByName(dev->toolList(), toolName); - if (!tool) { + if(!tool) { qWarning(CAT_SCOPY_API) << "Tool " << toolName << " doesn't exist for " << dev->displayName(); return; } Q_EMIT m_w->dm->requestTool(tool->uuid()); - } - else { + } else { qWarning(CAT_SCOPY_API) << "Device with id " << devID << " is not available!"; } } @@ -131,19 +128,18 @@ void ScopyMainWindow_API::switchTool(QString toolName) { Q_ASSERT(m_w->dm != nullptr); QString devID = ""; - if (!m_w->dm->connectedDev.isEmpty()) { + if(!m_w->dm->connectedDev.isEmpty()) { devID = m_w->dm->connectedDev.back(); } Device *dev = m_w->dm->getDevice(devID); - if (dev) { + if(dev) { ToolMenuEntry *tool = ToolMenuEntry::findToolMenuEntryByName(dev->toolList(), toolName); - if (!tool) { + if(!tool) { qWarning(CAT_SCOPY_API) << "Tool " << toolName << " doesn't exist for " << dev->displayName(); return; } Q_EMIT m_w->dm->requestTool(tool->uuid()); - } - else { + } else { qWarning(CAT_SCOPY_API) << "Device with id " << devID << " is not available!"; } } @@ -152,10 +148,10 @@ void ScopyMainWindow_API::runScript(QString content, QString fileName) { QJSValue val = ScopyJS::GetInstance()->engine()->evaluate(content, fileName); int ret = EXIT_SUCCESS; - if (val.isError()) { + if(val.isError()) { qWarning(CAT_SCOPY_API) << "Exception:" << val.toString(); ret = EXIT_FAILURE; - } else if (!val.isUndefined()) { + } else if(!val.isUndefined()) { qWarning(CAT_SCOPY_API) << val.toString(); } @@ -167,3 +163,5 @@ bool ScopyMainWindow_API::sortByUUID(const QString &k1, const QString &k2) { return k1.split("_").last() < k2.split("_").last(); } + +#include "moc_scopymainwindow_api.cpp" diff --git a/core/src/scopypreferencespage.cpp b/core/src/scopypreferencespage.cpp index f3a429730e..e1127b9871 100644 --- a/core/src/scopypreferencespage.cpp +++ b/core/src/scopypreferencespage.cpp @@ -1,20 +1,23 @@ #include "scopypreferencespage.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "pluginbase/preferenceshelper.h" + #include "application_restarter.h" -#include +#include "pluginbase/preferenceshelper.h" + +#include #include +#include +#include +#include #include +#include +#include +#include +#include +#include +#include + #include +#include #include #include #include @@ -22,15 +25,15 @@ Q_LOGGING_CATEGORY(CAT_PREFERENCESPAGE, "ScopyPreferencesPage"); using namespace scopy; -ScopyPreferencesPage::ScopyPreferencesPage(QWidget *parent) : - QWidget(parent) - , tabWidget(new QTabWidget(this)) - , layout(new QVBoxLayout(this)) +ScopyPreferencesPage::ScopyPreferencesPage(QWidget *parent) + : QWidget(parent) + , tabWidget(new QTabWidget(this)) + , layout(new QVBoxLayout(this)) { initUI(); initRestartWidget(); - addHorizontalTab(buildGeneralPreferencesPage(),"General"); + addHorizontalTab(buildGeneralPreferencesPage(), "General"); } void ScopyPreferencesPage::initUI() @@ -44,15 +47,16 @@ void ScopyPreferencesPage::initUI() StyleHelper::TabWidgetEastMenu(tabWidget, "preferencesTable"); } -void ScopyPreferencesPage::addHorizontalTab(QWidget *w, QString text) { +void ScopyPreferencesPage::addHorizontalTab(QWidget *w, QString text) +{ w->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - QWidget* pane = new QWidget(); - QHBoxLayout* lay = new QHBoxLayout(); + QWidget *pane = new QWidget(); + QHBoxLayout *lay = new QHBoxLayout(); lay->setMargin(10); pane->setLayout(lay); - QScrollArea* scrollArea = new QScrollArea(); + QScrollArea *scrollArea = new QScrollArea(); scrollArea->setWidget(w); scrollArea->setWidgetResizable(true); scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); @@ -65,14 +69,12 @@ void ScopyPreferencesPage::addHorizontalTab(QWidget *w, QString text) { lbl1->setText(text); QTabBar *tabbar = tabWidget->tabBar(); tabbar->setTabButton(tabbar->count() - 1, QTabBar::RightSide, lbl1); - } -ScopyPreferencesPage::~ScopyPreferencesPage() { - -} +ScopyPreferencesPage::~ScopyPreferencesPage() {} -void ScopyPreferencesPage::initRestartWidget() { +void ScopyPreferencesPage::initRestartWidget() +{ restartWidget = new QWidget(); QHBoxLayout *lay = new QHBoxLayout(); lay->setSpacing(0); @@ -80,9 +82,9 @@ void ScopyPreferencesPage::initRestartWidget() { restartWidget->setLayout(lay); restartWidget->setVisible(false); QLabel *lab = new QLabel("An application restart is required for these settings to take effect. "); - QSpacerItem *space1 = new QSpacerItem(6,20,QSizePolicy::Expanding,QSizePolicy::Fixed); - QSpacerItem *space2 = new QSpacerItem(6,20,QSizePolicy::Preferred,QSizePolicy::Fixed); - QPushButton* btn = new QPushButton("Restart"); + QSpacerItem *space1 = new QSpacerItem(6, 20, QSizePolicy::Expanding, QSizePolicy::Fixed); + QSpacerItem *space2 = new QSpacerItem(6, 20, QSizePolicy::Preferred, QSizePolicy::Fixed); + QPushButton *btn = new QPushButton("Restart"); StyleHelper::BlueButton(btn, "RestartBtn"); StyleHelper::BackgroundWidget(restartWidget, "restartWidget"); btn->setFixedWidth(100); @@ -93,28 +95,33 @@ void ScopyPreferencesPage::initRestartWidget() { lay->addSpacerItem(space1); layout->addWidget(restartWidget); - connect(btn, &QPushButton::clicked, btn, [](){ApplicationRestarter::triggerRestart();}); - connect(Preferences::GetInstance(), &Preferences::restartRequired, this, [=](){restartWidget->setVisible(true);}); + connect(btn, &QPushButton::clicked, btn, []() { ApplicationRestarter::triggerRestart(); }); + connect(Preferences::GetInstance(), &Preferences::restartRequired, this, + [=]() { restartWidget->setVisible(true); }); } -QWidget* ScopyPreferencesPage::buildSaveSessionPreference() { +QWidget *ScopyPreferencesPage::buildSaveSessionPreference() +{ Preferences *p = Preferences::GetInstance(); QWidget *w = new QWidget(this); QHBoxLayout *lay = new QHBoxLayout(w); lay->setMargin(0); - lay->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"general_save_session", "Save/Load Scopy session", this)); - lay->addSpacerItem(new QSpacerItem(40,40,QSizePolicy::Expanding,QSizePolicy::Fixed)); - lay->addWidget(new QLabel("Settings files location ",this)); - QPushButton *navigateBtn = new QPushButton("Open",this); + lay->addWidget( + PreferencesHelper::addPreferenceCheckBox(p, "general_save_session", "Save/Load Scopy session", this)); + lay->addSpacerItem(new QSpacerItem(40, 40, QSizePolicy::Expanding, QSizePolicy::Fixed)); + lay->addWidget(new QLabel("Settings files location ", this)); + QPushButton *navigateBtn = new QPushButton("Open", this); StyleHelper::BlueButton(navigateBtn, "navigateBtn"); navigateBtn->setMaximumWidth(80); - connect(navigateBtn,&QPushButton::clicked,this,[=]() {QDesktopServices::openUrl(scopy::config::settingsFolderPath()); }); + connect(navigateBtn, &QPushButton::clicked, this, + [=]() { QDesktopServices::openUrl(scopy::config::settingsFolderPath()); }); lay->addWidget(navigateBtn); return w; } -void ScopyPreferencesPage::removeIniFiles(bool backup) { +void ScopyPreferencesPage::removeIniFiles(bool backup) +{ QString dir = scopy::config::settingsFolderPath(); QDir loc(dir); QFileInfoList plugins = loc.entryInfoList(QDir::Files); @@ -124,45 +131,46 @@ void ScopyPreferencesPage::removeIniFiles(bool backup) { if(p.suffix() == "ini") settingsFiles.append(p.absoluteFilePath()); } - qInfo(CAT_PREFERENCESPAGE)<<"Removing ini files .. "; + qInfo(CAT_PREFERENCESPAGE) << "Removing ini files .. "; for(auto &&file : settingsFiles) { if(backup) { - QFile(file+".bak").remove(); - QFile(file).rename(file+".bak"); - qDebug(CAT_PREFERENCESPAGE)<<"Renamed" << file << "to" << file <<".bak"; + QFile(file + ".bak").remove(); + QFile(file).rename(file + ".bak"); + qDebug(CAT_PREFERENCESPAGE) << "Renamed" << file << "to" << file << ".bak"; } else { QFile(file).remove(); - qDebug(CAT_PREFERENCESPAGE)<<"Removed" << file; + qDebug(CAT_PREFERENCESPAGE) << "Removed" << file; } } } -void ScopyPreferencesPage::resetScopyPreferences() { +void ScopyPreferencesPage::resetScopyPreferences() +{ Preferences *p = Preferences::GetInstance(); removeIniFiles(); p->clear(); Q_EMIT Preferences::GetInstance()->restartRequired(); } -QWidget* ScopyPreferencesPage::buildResetScopyDefaultButton() { +QWidget *ScopyPreferencesPage::buildResetScopyDefaultButton() +{ QWidget *w = new QWidget(this); QHBoxLayout *lay = new QHBoxLayout(w); - QPushButton *resetBtn = new QPushButton("Reset",this); + QPushButton *resetBtn = new QPushButton("Reset", this); StyleHelper::BlueButton(resetBtn, "resetBtn"); resetBtn->setMaximumWidth(80); - connect(resetBtn,&QPushButton::clicked,this,&ScopyPreferencesPage::resetScopyPreferences); + connect(resetBtn, &QPushButton::clicked, this, &ScopyPreferencesPage::resetScopyPreferences); lay->addWidget(resetBtn); lay->setMargin(0); - lay->addSpacerItem(new QSpacerItem(6,40,QSizePolicy::Preferred, QSizePolicy::Fixed)); + lay->addSpacerItem(new QSpacerItem(6, 40, QSizePolicy::Preferred, QSizePolicy::Fixed)); lay->addWidget(new QLabel("Reset to settings and plugins to default")); - lay->addSpacerItem(new QSpacerItem(40,40,QSizePolicy::Expanding, QSizePolicy::Fixed)); - + lay->addSpacerItem(new QSpacerItem(40, 40, QSizePolicy::Expanding, QSizePolicy::Fixed)); return w; } -QWidget* ScopyPreferencesPage::buildGeneralPreferencesPage() +QWidget *ScopyPreferencesPage::buildGeneralPreferencesPage() { QWidget *page = new QWidget(this); QVBoxLayout *lay = new QVBoxLayout(page); @@ -175,34 +183,46 @@ QWidget* ScopyPreferencesPage::buildGeneralPreferencesPage() // General preferences MenuSectionWidget *generalWidget = new MenuSectionWidget(page); - MenuCollapseSection *generalSection = new MenuCollapseSection("General",MenuCollapseSection::MHCW_NONE, generalWidget); + MenuCollapseSection *generalSection = + new MenuCollapseSection("General", MenuCollapseSection::MHCW_NONE, generalWidget); generalWidget->contentLayout()->setSpacing(10); generalWidget->contentLayout()->addWidget(generalSection); generalSection->contentLayout()->setSpacing(10); lay->addWidget(generalWidget); - lay->addSpacerItem(new QSpacerItem(0,0,QSizePolicy::Minimum,QSizePolicy::Expanding)); + lay->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); generalSection->contentLayout()->addWidget(buildSaveSessionPreference()); - generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"general_save_attached", "Save/Load tool attached state", generalSection)); - generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"general_doubleclick_attach", "Doubleclick to attach/detach tool", generalSection)); - generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"general_doubleclick_ctrl_opens_menu", "Doubleclick control buttons to open menu", generalSection)); - generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"general_use_opengl", "Enable OpenGL plotting", generalSection)); - generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"general_use_animations", "Enable menu animations", generalSection)); - generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p, "general_check_online_version", "Enable automatic online check for updates.", generalSection)); - generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCombo(p,"general_theme", "Theme", {"default","light"}, generalSection)); - generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCombo(p,"general_language", "Language",t->getLanguages(), generalSection)); + generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox( + p, "general_save_attached", "Save/Load tool attached state", generalSection)); + generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox( + p, "general_doubleclick_attach", "Doubleclick to attach/detach tool", generalSection)); + generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox( + p, "general_doubleclick_ctrl_opens_menu", "Doubleclick control buttons to open menu", generalSection)); + generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox( + p, "general_use_opengl", "Enable OpenGL plotting", generalSection)); + generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox( + p, "general_use_animations", "Enable menu animations", generalSection)); + generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox( + p, "general_check_online_version", "Enable automatic online check for updates.", generalSection)); + generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCombo( + p, "general_theme", "Theme", {"default", "light"}, generalSection)); + generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCombo( + p, "general_language", "Language", t->getLanguages(), generalSection)); // Debug preferences MenuSectionWidget *debugWidget = new MenuSectionWidget(page); - MenuCollapseSection *debugSection = new MenuCollapseSection("Debug",MenuCollapseSection::MHCW_NONE, debugWidget); + MenuCollapseSection *debugSection = + new MenuCollapseSection("Debug", MenuCollapseSection::MHCW_NONE, debugWidget); debugWidget->contentLayout()->setSpacing(10); debugWidget->contentLayout()->addWidget(debugSection); debugSection->contentLayout()->setSpacing(10); lay->addWidget(debugWidget); - lay->addSpacerItem(new QSpacerItem(0,0,QSizePolicy::Minimum,QSizePolicy::Expanding)); + lay->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); - debugSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"general_show_plot_fps","Show plot FPS", debugSection)); - debugSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCombo(p,"general_plot_target_fps", "Plot target FPS", {"15","20","30","60"}, debugSection)); + debugSection->contentLayout()->addWidget( + PreferencesHelper::addPreferenceCheckBox(p, "general_show_plot_fps", "Show plot FPS", debugSection)); + debugSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCombo( + p, "general_plot_target_fps", "Plot target FPS", {"15", "20", "30", "60"}, debugSection)); debugSection->contentLayout()->addWidget(buildResetScopyDefaultButton()); return page; diff --git a/core/src/toolbrowser.cpp b/core/src/toolbrowser.cpp index 0a019d71e3..fd6ee728b3 100644 --- a/core/src/toolbrowser.cpp +++ b/core/src/toolbrowser.cpp @@ -1,47 +1,48 @@ #include "toolbrowser.h" + #include "ui_toolbrowser.h" + #include + #include using namespace scopy; -ToolBrowser::ToolBrowser(QWidget *parent) : - QWidget(parent), - ui(new Ui::ToolBrowser), - m_collapsed(false) +ToolBrowser::ToolBrowser(QWidget *parent) + : QWidget(parent) + , ui(new Ui::ToolBrowser) + , m_collapsed(false) { - ui->setupUi(this); + ui->setupUi(this); - ToolMenu *tm = ui->wToolMenu; + ToolMenu *tm = ui->wToolMenu; - tm->getButtonGroup()->addButton(ui->btnPreferences); - tm->getButtonGroup()->addButton(ui->btnAbout); + tm->getButtonGroup()->addButton(ui->btnPreferences); + tm->getButtonGroup()->addButton(ui->btnAbout); - ToolMenuItem* homeTmi = tm->createTool("home","Home",":/gui/icons/scopy-default/icons/tool_home.svg"); - homeTmi->setSeparator(true,true); + ToolMenuItem *homeTmi = tm->createTool("home", "Home", ":/gui/icons/scopy-default/icons/tool_home.svg"); + homeTmi->setSeparator(true, true); homeTmi->getToolRunBtn()->setVisible(false); homeTmi->setEnabled(true); ui->homePlaceholder->layout()->addWidget(homeTmi); Util::retainWidgetSizeWhenHidden(ui->logo); homeTmi->setDraggable(false); - connect(ui->btnCollapse, &QPushButton::clicked, this, &ToolBrowser::toggleCollapse); connect(ui->btnCollapseMini, &QPushButton::clicked, this, &ToolBrowser::toggleCollapse); - connect(ui->btnPreferences,&QPushButton::clicked,this,[=](){Q_EMIT requestTool("preferences");}); - connect(ui->btnAbout,&QPushButton::clicked,this,[=](){Q_EMIT requestTool("about");}); + connect(ui->btnPreferences, &QPushButton::clicked, this, [=]() { Q_EMIT requestTool("preferences"); }); + connect(ui->btnAbout, &QPushButton::clicked, this, [=]() { Q_EMIT requestTool("about"); }); - connect(ui->btnSave,&QPushButton::clicked,this,[=](){Q_EMIT requestSave();}); - connect(ui->btnLoad,&QPushButton::clicked,this,[=](){Q_EMIT requestLoad();}); + connect(ui->btnSave, &QPushButton::clicked, this, [=]() { Q_EMIT requestSave(); }); + connect(ui->btnLoad, &QPushButton::clicked, this, [=]() { Q_EMIT requestLoad(); }); - connect(tm,SIGNAL(requestToolSelect(QString)),this,SIGNAL(requestTool(QString))); + connect(tm, SIGNAL(requestToolSelect(QString)), this, SIGNAL(requestTool(QString))); } -ToolMenu* ToolBrowser::getToolMenu() { - return ui->wToolMenu; -} +ToolMenu *ToolBrowser::getToolMenu() { return ui->wToolMenu; } -void ToolBrowser::hideMenuText(bool collapsed) { +void ToolBrowser::hideMenuText(bool collapsed) +{ ToolMenu *tm = ui->wToolMenu; if(collapsed) { @@ -70,13 +71,10 @@ void ToolBrowser::toggleCollapse() Q_EMIT collapsed(m_collapsed); } -ToolBrowser::~ToolBrowser() -{ - delete ui; -} +ToolBrowser::~ToolBrowser() { delete ui; } -//TEST -/* +// TEST +/* ts->detachTool("home"); tm->addTool("home1","Home12",""); tm->addTool("home2","Home2",""); @@ -90,5 +88,4 @@ ToolBrowser::~ToolBrowser() ts->addTool("home3", new QLabel("home3")); */ - #include "moc_toolbrowser.cpp" diff --git a/core/src/toolmanager.cpp b/core/src/toolmanager.cpp index e5ec548a0a..beffb503a6 100644 --- a/core/src/toolmanager.cpp +++ b/core/src/toolmanager.cpp @@ -1,16 +1,19 @@ #include "toolmanager.h" -#include "pluginbase/preferences.h" + #include "dynamicWidget.h" -#include +#include "pluginbase/preferences.h" + #include #include -#include +#include +#include Q_LOGGING_CATEGORY(CAT_TOOLMANAGER, "ToolManager") using namespace scopy; -ToolManager::ToolManager(ToolMenu *tm, ToolStack *ts, DetachedToolWindowManager *dwm, QObject *parent ) : QObject(parent) +ToolManager::ToolManager(ToolMenu *tm, ToolStack *ts, DetachedToolWindowManager *dwm, QObject *parent) + : QObject(parent) { currentKey = ""; this->tm = tm; @@ -19,80 +22,80 @@ ToolManager::ToolManager(ToolMenu *tm, ToolStack *ts, DetachedToolWindowManager qDebug(CAT_TOOLMANAGER) << "ctor"; } -ToolManager::~ToolManager() { - qDebug(CAT_TOOLMANAGER) << "dtor"; -} +ToolManager::~ToolManager() { qDebug(CAT_TOOLMANAGER) << "dtor"; } -void ToolManager::addToolList(QString s, QList sl) { +void ToolManager::addToolList(QString s, QList sl) +{ qDebug(CAT_TOOLMANAGER) << "added" << s << "with " << sl.length() << "entries"; - map[s] = {s,sl,false}; + map[s] = {s, sl, false}; if(map.count() == 1) { qDebug(CAT_TOOLMANAGER) << "first item, currentkey = " << s; currentKey = s; showToolList(s); } for(ToolMenuEntry *tme : qAsConst(map[s].tools)) { - connect(tme,SIGNAL(updateToolAttached(bool)),this,SLOT(updateToolAttached(bool))); - connect(tme,SIGNAL(updateTool(QWidget*)),this,SLOT(updateTool(QWidget*))); + connect(tme, SIGNAL(updateToolAttached(bool)), this, SLOT(updateToolAttached(bool))); + connect(tme, SIGNAL(updateTool(QWidget *)), this, SLOT(updateTool(QWidget *))); } } -void ToolManager::removeToolList(QString s) { - qDebug(CAT_TOOLMANAGER) << "removing" < sl) { +void ToolManager::changeToolListContents(QString s, QList sl) +{ bool prev = map[s].lock; qInfo(CAT_TOOLMANAGER) << "changing" << s; removeToolList(s); - addToolList(s,sl); + addToolList(s, sl); if(prev == true || currentKey == s) { showToolList(s); } } -void ToolManager::showToolList(QString s) { +void ToolManager::showToolList(QString s) +{ if(!map[currentKey].lock) hideToolList(currentKey); currentKey = s; qDebug(CAT_TOOLMANAGER) << "showing" << s; - for(ToolMenuEntry *tme : qAsConst(map[s].tools)) - { + for(ToolMenuEntry *tme : qAsConst(map[s].tools)) { ToolMenuItem *m = tm->getToolMenuItemFor(tme->uuid()); - if( m == nullptr) { - m = tm->addTool(tme->uuid(),tme->name(),tme->icon()); - connect(tme,SIGNAL(updateToolEntry()),this,SLOT(updateToolEntry())); - connect(m->getToolRunBtn(),SIGNAL(toggled(bool)),tme,SIGNAL(runToggled(bool))); - connect(m->getToolRunBtn(),SIGNAL(clicked(bool)),tme,SIGNAL(runClicked(bool))); + if(m == nullptr) { + m = tm->addTool(tme->uuid(), tme->name(), tme->icon()); + connect(tme, SIGNAL(updateToolEntry()), this, SLOT(updateToolEntry())); + connect(m->getToolRunBtn(), SIGNAL(toggled(bool)), tme, SIGNAL(runToggled(bool))); + connect(m->getToolRunBtn(), SIGNAL(clicked(bool)), tme, SIGNAL(runClicked(bool))); } updateToolEntry(tme); } - } -void ToolManager::hideToolList(QString s) { +void ToolManager::hideToolList(QString s) +{ qDebug(CAT_TOOLMANAGER) << "hiding" << s; - for(ToolMenuEntry *tme : qAsConst(map[s].tools)) - { + for(ToolMenuEntry *tme : qAsConst(map[s].tools)) { if(tm->getToolMenuItemFor(tme->uuid()) != nullptr) { - disconnect(tme,SIGNAL(updateToolEntry()),this,SLOT(updateToolEntry())); + disconnect(tme, SIGNAL(updateToolEntry()), this, SLOT(updateToolEntry())); tm->removeTool(tme->uuid()); } } } -void ToolManager::lockToolList(QString s) { +void ToolManager::lockToolList(QString s) +{ map[s].lock = true; lockedToolLists.append(s); qDebug(CAT_TOOLMANAGER) << "locking" << s; @@ -101,17 +104,18 @@ void ToolManager::lockToolList(QString s) { } } -void ToolManager::unlockToolList(QString s){ +void ToolManager::unlockToolList(QString s) +{ map[s].lock = false; lockedToolLists.removeOne(s); qDebug(CAT_TOOLMANAGER) << "unlocking" << s; if(currentKey != s) { hideToolList(s); } - } -void ToolManager::updateToolEntry(ToolMenuEntry *tme) { +void ToolManager::updateToolEntry(ToolMenuEntry *tme) +{ auto m = tm->getToolMenuItemFor(tme->uuid()); m->setVisible(tme->visible()); m->setEnabled(tme->enabled()); @@ -120,18 +124,20 @@ void ToolManager::updateToolEntry(ToolMenuEntry *tme) { m->getToolRunBtn()->setEnabled(tme->runBtnVisible()); m->getToolRunBtn()->setChecked(tme->running()); Util::retainWidgetSizeWhenHidden(m, tme->visible()); - qDebug(CAT_TOOLMANAGER) << "updating toolmenuentry for " << tme->name() <<" - "<< tme->uuid(); + qDebug(CAT_TOOLMANAGER) << "updating toolmenuentry for " << tme->name() << " - " << tme->uuid(); } -void ToolManager::updateToolEntry() { - ToolMenuEntry* tme = dynamic_cast(QObject::sender()); +void ToolManager::updateToolEntry() +{ + ToolMenuEntry *tme = dynamic_cast(QObject::sender()); Q_ASSERT(tme); updateToolEntry(tme); } -void ToolManager::updateTool(QWidget* old) { +void ToolManager::updateTool(QWidget *old) +{ - ToolMenuEntry* tme = dynamic_cast(QObject::sender()); + ToolMenuEntry *tme = dynamic_cast(QObject::sender()); Q_ASSERT(tme); QString id = tme->uuid(); QWidget *tool = tme->tool(); @@ -147,20 +153,21 @@ void ToolManager::updateTool(QWidget* old) { } if(tool != nullptr) { // we have a new widget if(tme->attached()) { - ts->add(id,tool); + ts->add(id, tool); } else { - dwm->add(id,tme); + dwm->add(id, tme); } loadToolAttachedState(tme); } - qDebug(CAT_TOOLMANAGER) << "updating tool for " << tme->name() <<" - "<< id; + qDebug(CAT_TOOLMANAGER) << "updating tool for " << tme->name() << " - " << id; } -void ToolManager::updateToolAttached(bool oldAttach) { - ToolMenuEntry* tme = dynamic_cast(QObject::sender()); +void ToolManager::updateToolAttached(bool oldAttach) +{ + ToolMenuEntry *tme = dynamic_cast(QObject::sender()); Q_ASSERT(tme); - QWidget* tool = tme->tool(); + QWidget *tool = tme->tool(); QString id = tme->uuid(); if(tme->attached()) { @@ -168,7 +175,7 @@ void ToolManager::updateToolAttached(bool oldAttach) { if(dwm->contains(id)) { dwm->remove(id); } - ts->add(id,tool); + ts->add(id, tool); tm->attachSuccesful(id); } else { // tool is attached, it will detach @@ -188,23 +195,25 @@ void ToolManager::updateToolAttached(bool oldAttach) { // the selected tool just attached, so it will be at the top of the stack, therefore highlighted auto t = tm->getToolMenuItemFor(id); - if (t) { + if(t) { t->getToolBtn()->setChecked(true); setDynamicProperty(t, "selected", true); } } else { - // the top tool just detached, so we need to find the tool that is positioned at the new top of the stack. + // the top tool just detached, so we need to find the tool that is positioned at the new top of the + // stack. auto ts_current_widget = ts->currentWidget(); auto ts_current_widget_key = ts->getKey(ts_current_widget); auto t = tm->getToolMenuItemFor(ts_current_widget_key); - if (t) { + if(t) { t->getToolBtn()->toggle(); } } } -void ToolManager::showTool(QString s) { +void ToolManager::showTool(QString s) +{ auto toolmenuitem = tm->getToolMenuItemFor(s); if(toolmenuitem) toolmenuitem->getToolBtn()->setChecked(true); @@ -217,7 +226,7 @@ void ToolManager::toggleAttach(QString id) if(!p->get("general_doubleclick_attach").toBool()) return; for(auto &&toolist : map) { - for( auto &&tme : toolist.tools) { + for(auto &&tme : toolist.tools) { if(tme->uuid() == id) { tme->setAttached(!tme->attached()); } @@ -231,10 +240,10 @@ void ToolManager::saveToolAttachedState(ToolMenuEntry *tme) if(!p->get("general_save_attached").toBool()) return; QString prefId; - prefId = tme->id()+"_attached"; + prefId = tme->id() + "_attached"; bool attach = tme->attached(); p->set(prefId, attach); - qDebug(CAT_TOOLMANAGER)<<"Saving " << prefId << " " << attach; + qDebug(CAT_TOOLMANAGER) << "Saving " << prefId << " " << attach; } void ToolManager::loadToolAttachedState(ToolMenuEntry *tme) @@ -243,13 +252,13 @@ void ToolManager::loadToolAttachedState(ToolMenuEntry *tme) QString prefId; if(!p->get("general_save_attached").toBool()) return; -// QString prefGrp = m_name; + // QString prefGrp = m_name; - prefId = tme->id()+"_attached"; + prefId = tme->id() + "_attached"; p->init(prefId, tme->attached()); bool attach = p->get(prefId).toBool(); tme->setAttached(attach); - qDebug(CAT_TOOLMANAGER)<<"Loading " << prefId << " " << attach; + qDebug(CAT_TOOLMANAGER) << "Loading " << prefId << " " << attach; } #include "moc_toolmanager.cpp" diff --git a/core/src/toolmenu.cpp b/core/src/toolmenu.cpp index 46ef722786..d77943ba7e 100644 --- a/core/src/toolmenu.cpp +++ b/core/src/toolmenu.cpp @@ -19,34 +19,34 @@ */ #include "toolmenu.h" + #include "gui/dynamicWidget.h" #include using namespace scopy; -ToolMenu::ToolMenu(QWidget *parent): - BaseMenu(parent) +ToolMenu::ToolMenu(QWidget *parent) + : BaseMenu(parent) { buttonGroup = new QButtonGroup(this); - connect(this, &ToolMenu::itemMovedFromTo, - this, &ToolMenu::_updateToolList); + connect(this, &ToolMenu::itemMovedFromTo, this, &ToolMenu::_updateToolList); } - -ToolMenuItem* ToolMenu::getToolMenuItemFor(QString toolId) +ToolMenuItem *ToolMenu::getToolMenuItemFor(QString toolId) { - for(auto &&tool:tools) { + for(auto &&tool : tools) { if(tool->getId() == toolId) return tool; } return nullptr; } -ToolMenuItem *ToolMenu::createTool(QString id, QString name, QString icon, int position) { - ToolMenuItem *t = new ToolMenuItem(id,name,icon,this); - insertMenuItem(t,position); +ToolMenuItem *ToolMenu::createTool(QString id, QString name, QString icon, int position) +{ + ToolMenuItem *t = new ToolMenuItem(id, name, icon, this); + insertMenuItem(t, position); if(position == -1) { tools.append(t); } else { @@ -54,33 +54,28 @@ ToolMenuItem *ToolMenu::createTool(QString id, QString name, QString icon, int p } buttonGroup->addButton(t->getToolBtn()); - connect(t->getToolBtn(), &QPushButton::clicked, this, [=](){ - Q_EMIT requestToolSelect(t->getId()); - }); + connect(t->getToolBtn(), &QPushButton::clicked, this, [=]() { Q_EMIT requestToolSelect(t->getId()); }); - connect(t, &ToolMenuItem::doubleclick, this, [=](){ - Q_EMIT toggleAttach(t->getId()); - }); + connect(t, &ToolMenuItem::doubleclick, this, [=]() { Q_EMIT toggleAttach(t->getId()); }); - connect(t->getToolBtn(), &QPushButton::toggled, this, [=](bool on){ - if (buttonGroup->id(t->getToolBtn()) != -1) { + connect(t->getToolBtn(), &QPushButton::toggled, this, [=](bool on) { + if(buttonGroup->id(t->getToolBtn()) != -1) { setDynamicProperty(t, "selected", on); } }); - return t; } -ToolMenuItem* ToolMenu::addTool(QString id, QString name, QString icon, int position) +ToolMenuItem *ToolMenu::addTool(QString id, QString name, QString icon, int position) { - ToolMenuItem *t = createTool(id,name,icon,position); - insertMenuItem(t,position); - + ToolMenuItem *t = createTool(id, name, icon, position); + insertMenuItem(t, position); return t; } -void ToolMenu::detachSuccesful(QString tool) { +void ToolMenu::detachSuccesful(QString tool) +{ auto &&t = getToolMenuItemFor(tool); if(t) { setDynamicProperty(t, "selected", false); @@ -88,7 +83,8 @@ void ToolMenu::detachSuccesful(QString tool) { } } -void ToolMenu::attachSuccesful(QString tool) { +void ToolMenu::attachSuccesful(QString tool) +{ auto &&t = getToolMenuItemFor(tool); if(t) { buttonGroup->addButton(t->getToolBtn()); @@ -97,7 +93,7 @@ void ToolMenu::attachSuccesful(QString tool) { bool ToolMenu::removeTool(QString id) { - for(int i = 0;igetId() == id) { delete tools[i]; tools.remove(i); @@ -109,7 +105,7 @@ bool ToolMenu::removeTool(QString id) bool ToolMenu::removeTool(ToolMenuItem *tmi) { - for(int i = 0;i &ToolMenu::getTools() const -{ - return tools; -} +const QVector &ToolMenu::getTools() const { return tools; } -QButtonGroup *ToolMenu::getButtonGroup() const -{ - return buttonGroup; -} +QButtonGroup *ToolMenu::getButtonGroup() const { return buttonGroup; } void ToolMenu::_updateToolList(short from, short to) { - if (d_items == tools.size()) { + if(d_items == tools.size()) { auto toMove = tools[from]; tools.remove(from); tools.insert(to, toMove); } } -ToolMenu::~ToolMenu() -{ - _saveState(); -} +ToolMenu::~ToolMenu() { _saveState(); } -void ToolMenu::hideMenuText(bool val) { - for(auto &&tool: tools) { +void ToolMenu::hideMenuText(bool val) +{ + for(auto &&tool : tools) { tool->hideText(val); } - } void ToolMenu::_saveState() { -// QSettings settings; - -// settings.beginWriteArray("toolMenu/pos"); -// for (int i = 0; i < d_tools.size(); ++i) { -// settings.setArrayIndex(i); -// settings.setValue("idx", QVariant(d_tools[i].second)); -// } -// settings.endArray(); + // QSettings settings; + + // settings.beginWriteArray("toolMenu/pos"); + // for (int i = 0; i < d_tools.size(); ++i) { + // settings.setArrayIndex(i); + // settings.setValue("idx", QVariant(d_tools[i].second)); + // } + // settings.endArray(); } void ToolMenu::_loadState() { -// QSettings settings; - -// int n = settings.beginReadArray("toolMenu/pos"); -// for (int i = 0; i < n; ++i) { -// settings.setArrayIndex(i); -// d_positions.push_back(settings.value("idx").value()); -// } -// settings.endArray(); + // QSettings settings; + + // int n = settings.beginReadArray("toolMenu/pos"); + // for (int i = 0; i < n; ++i) { + // settings.setArrayIndex(i); + // d_positions.push_back(settings.value("idx").value()); + // } + // settings.endArray(); } - - - #include "moc_toolmenu.cpp" diff --git a/core/src/toolmenuitem.cpp b/core/src/toolmenuitem.cpp index 333443b9cb..da7f4a5033 100644 --- a/core/src/toolmenuitem.cpp +++ b/core/src/toolmenuitem.cpp @@ -20,23 +20,24 @@ #include "toolmenuitem.h" -#include -#include #include "gui/dynamicWidget.h" -#include "qdebug.h" #include "gui/utils.h" +#include "qdebug.h" + +#include #include +#include using namespace scopy; Q_LOGGING_CATEGORY(CAT_TOOLMENUITEM, "ToolMenuItem") -ToolMenuItem::ToolMenuItem(QString id, QString name, QString iconPath, QWidget *parent): - BaseMenuItem(parent), - toolBtn(nullptr), - toolRunBtn(nullptr), - id(id), - name(name), - iconPath(iconPath) +ToolMenuItem::ToolMenuItem(QString id, QString name, QString iconPath, QWidget *parent) + : BaseMenuItem(parent) + , toolBtn(nullptr) + , toolRunBtn(nullptr) + , id(id) + , name(name) + , iconPath(iconPath) { _buildUI(); @@ -51,22 +52,13 @@ ToolMenuItem::ToolMenuItem(QString id, QString name, QString iconPath, QWidget * #endif } -ToolMenuItem::~ToolMenuItem() -{ +ToolMenuItem::~ToolMenuItem() {} -} +QPushButton *ToolMenuItem::getToolBtn() const { return toolBtn; } -QPushButton *ToolMenuItem::getToolBtn() const -{ - return toolBtn; -} +QPushButton *ToolMenuItem::getToolRunBtn() const { return toolRunBtn; } -QPushButton *ToolMenuItem::getToolRunBtn() const -{ - return toolRunBtn; -} - -//void ToolMenuItem::setToolEnabled(bool enabled) +// void ToolMenuItem::setToolEnabled(bool enabled) //{ // BaseMenuItem::setVisible(enabled); // Util::retainWidgetSizeWhenHidden(this, enabled); @@ -75,7 +67,7 @@ QPushButton *ToolMenuItem::getToolRunBtn() const void ToolMenuItem::enableDoubleClick(bool enable) { - if (enable) { + if(enable) { toolBtn->installEventFilter(this); } else { toolBtn->removeEventFilter(this); @@ -91,10 +83,10 @@ void ToolMenuItem::setSeparator(bool top, bool bot) bool ToolMenuItem::eventFilter(QObject *watched, QEvent *event) { - if (event->type() == QEvent::MouseButtonDblClick) { + if(event->type() == QEvent::MouseButtonDblClick) { QMouseEvent *mouseEvent = static_cast(event); - if (mouseEvent->button() == Qt::LeftButton) { - if (isEnabled()) { + if(mouseEvent->button() == Qt::LeftButton) { + if(isEnabled()) { Q_EMIT doubleclick(); return true; } @@ -104,14 +96,14 @@ bool ToolMenuItem::eventFilter(QObject *watched, QEvent *event) return QObject::event(event); } -void ToolMenuItem::setName(QString str) { +void ToolMenuItem::setName(QString str) +{ this->name = str; toolBtn->setText(name); } - void ToolMenuItem::hideText(bool hidden) -{ +{ if(hidden) { toolBtn->setText(""); } else { @@ -119,10 +111,7 @@ void ToolMenuItem::hideText(bool hidden) } } -void ToolMenuItem::setDisabled(bool disabled) -{ - BaseMenuItem::setDisabled(disabled); -} +void ToolMenuItem::setDisabled(bool disabled) { BaseMenuItem::setDisabled(disabled); } void ToolMenuItem::mouseMoveEvent(QMouseEvent *event) { @@ -132,10 +121,7 @@ void ToolMenuItem::mouseMoveEvent(QMouseEvent *event) #endif } -const QString &ToolMenuItem::getId() const -{ - return id; -} +const QString &ToolMenuItem::getId() const { return id; } void ToolMenuItem::enterEvent(QEvent *event) { @@ -181,8 +167,7 @@ void ToolMenuItem::_buildUI() layout->setSpacing(0); layout->setContentsMargins(0, 0, 0, 0); toolBtn = new QPushButton(name); - toolBtn->setSizePolicy(QSizePolicy::Minimum, - QSizePolicy::Minimum); + toolBtn->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); toolRunBtn = new CustomPushButton(this); layout->addWidget(toolBtn); layout->addWidget(toolRunBtn); @@ -200,7 +185,7 @@ void ToolMenuItem::_buildUI() toolBtn->setFlat(true); toolRunBtn->setFlat(true); - qDebug(CAT_TOOLMENUITEM)<addWidget(toolOption); diff --git a/core/src/toolstack.cpp b/core/src/toolstack.cpp index bc9931d132..39c01e2ccf 100644 --- a/core/src/toolstack.cpp +++ b/core/src/toolstack.cpp @@ -1,20 +1,17 @@ #include "toolstack.h" + #include -#include #include +#include using namespace scopy; Q_LOGGING_CATEGORY(CAT_TOOLSTACK, "ToolStack") -ToolStack::ToolStack(QWidget *parent) : - MapStackedWidget(parent) -{ -} - -ToolStack::~ToolStack() -{ -} +ToolStack::ToolStack(QWidget *parent) + : MapStackedWidget(parent) +{} +ToolStack::~ToolStack() {} #include "moc_toolstack.cpp" diff --git a/core/src/translationsrepository.cpp b/core/src/translationsrepository.cpp index 6a8ee103af..8d6ebd6858 100644 --- a/core/src/translationsrepository.cpp +++ b/core/src/translationsrepository.cpp @@ -1,31 +1,29 @@ #include "translationsrepository.h" + #include "common/scopyconfig.h" + +#include #include #include #include + #include -#include -Q_LOGGING_CATEGORY(CAT_TRANSLATIONREPOSITORY,"ScopyTranslations"); +Q_LOGGING_CATEGORY(CAT_TRANSLATIONREPOSITORY, "ScopyTranslations"); using namespace scopy; -TranslationsRepository* TranslationsRepository::pinstance_{nullptr}; - -TranslationsRepository::TranslationsRepository(QObject *parent) : QObject(parent) -{ - -} +TranslationsRepository *TranslationsRepository::pinstance_{nullptr}; -TranslationsRepository::~TranslationsRepository() -{ +TranslationsRepository::TranslationsRepository(QObject *parent) + : QObject(parent) +{} -} +TranslationsRepository::~TranslationsRepository() {} TranslationsRepository *TranslationsRepository::GetInstance() { - if (pinstance_ == nullptr) - { + if(pinstance_ == nullptr) { pinstance_ = new TranslationsRepository(QApplication::instance()); // singleton has the app as parent } return pinstance_; @@ -35,7 +33,7 @@ QString TranslationsRepository::getTranslationsPath() { // Check the local plugins folder first QDir pathDir(config::localTranslationFolderPath()); - if (pathDir.exists()){ + if(pathDir.exists()) { return config::localTranslationFolderPath(); } @@ -46,12 +44,13 @@ QStringList TranslationsRepository::getLanguages() { QDir directory(TranslationsRepository::getTranslationsPath()); QStringList languages = directory.entryList(QStringList() << "*.qm", QDir::Files).replaceInStrings(".qm", ""); - for (const QString& lang: languages) { - if (lang.contains("_")) languages.removeOne(lang); + for(const QString &lang : languages) { + if(lang.contains("_")) + languages.removeOne(lang); } // no languages found - if (languages.empty()) { + if(languages.empty()) { languages.append("default"); } @@ -60,7 +59,7 @@ QStringList TranslationsRepository::getLanguages() void TranslationsRepository::loadTranslations(QString language) { - if (language == "default") { + if(language == "default") { qDebug(CAT_TRANSLATIONREPOSITORY) << "No languages loaded (default)"; return; } @@ -69,8 +68,8 @@ void TranslationsRepository::loadTranslations(QString language) QDir directory(TranslationsRepository::getTranslationsPath()); QFileInfoList languages = directory.entryInfoList(QStringList() << "*.qm", QDir::Files); - for (const QFileInfo& lang: languages) { - if (lang.fileName().endsWith("_" + language + ".qm") || lang.fileName() == language + ".qm") { + for(const QFileInfo &lang : languages) { + if(lang.fileName().endsWith("_" + language + ".qm") || lang.fileName() == language + ".qm") { translatorList.append(new QTranslator()); translatorList.last()->load(lang.filePath()); QApplication::installTranslator(translatorList.last()); @@ -80,5 +79,4 @@ void TranslationsRepository::loadTranslations(QString language) } } - #include "moc_translationsrepository.cpp" diff --git a/core/src/versioncheckoverlay.cpp b/core/src/versioncheckoverlay.cpp index c648d9e8ff..dfe188fad9 100644 --- a/core/src/versioncheckoverlay.cpp +++ b/core/src/versioncheckoverlay.cpp @@ -1,30 +1,32 @@ #include "versioncheckoverlay.h" -#include +#include using namespace scopy; -VersionCheckOverlay::VersionCheckOverlay(QWidget *parent) : PopupWidget(parent) { - setDescription("Do you want to automatically check for newer Scopy and m2k-firmware versions?\n\nYou can change this anytime from the Preferences menu."); +VersionCheckOverlay::VersionCheckOverlay(QWidget *parent) + : PopupWidget(parent) +{ + setDescription("Do you want to automatically check for newer Scopy and m2k-firmware versions?\n\nYou can " + "change this anytime from the Preferences menu."); m_exitButton->setText("No"); m_continueButton->setText("Yes"); enableTitleBar(false); enableTintedOverlay(true); - connect(this, &PopupWidget::continueButtonClicked, this, [this] () { + connect(this, &PopupWidget::continueButtonClicked, this, [this]() { scopy::Preferences::set("general_check_online_version", true); delete this; }); - connect(this, &PopupWidget::exitButtonClicked, this, [this] () { + connect(this, &PopupWidget::exitButtonClicked, this, [this]() { scopy::Preferences::set("general_check_online_version", false); delete this; }); } -VersionCheckOverlay::~VersionCheckOverlay() { - -} +VersionCheckOverlay::~VersionCheckOverlay() {} -void VersionCheckOverlay::showOverlay() { +void VersionCheckOverlay::showOverlay() +{ raise(); show(); diff --git a/core/test/CMakeLists.txt b/core/test/CMakeLists.txt index b4560d3821..9a040e8f07 100644 --- a/core/test/CMakeLists.txt +++ b/core/test/CMakeLists.txt @@ -2,10 +2,7 @@ cmake_minimum_required(VERSION 3.5) include(ScopyTest) -SETUP_SCOPY_TESTS( - pluginmanager - pluginrepository -) +setup_scopy_tests(pluginmanager pluginrepository) # test_translationsrepository if(ENABLE_TRANSLATION) @@ -22,28 +19,22 @@ if(ENABLE_TRANSLATION) # move test translation files to core/tests add_custom_command( TARGET ${TEST_GENERATETRANSLATIONS} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy - ${CMAKE_BINARY_DIR}/translations/test.qm - ${CMAKE_CURRENT_BINARY_DIR}/translations/test.qm + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/translations/test.qm + ${CMAKE_CURRENT_BINARY_DIR}/translations/test.qm ) add_custom_command( - TARGET ${TEST_GENERATETRANSLATIONS} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E remove - ${CMAKE_BINARY_DIR}/translations/test.qm + TARGET ${TEST_GENERATETRANSLATIONS} POST_BUILD COMMAND ${CMAKE_COMMAND} -E remove + ${CMAKE_BINARY_DIR}/translations/test.qm ) add_custom_command( TARGET ${TEST_GENERATETRANSLATIONS} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy - ${CMAKE_BINARY_DIR}/translations/test_test.qm - ${CMAKE_CURRENT_BINARY_DIR}/translations/test_test.qm + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/translations/test_test.qm + ${CMAKE_CURRENT_BINARY_DIR}/translations/test_test.qm ) add_custom_command( - TARGET ${TEST_GENERATETRANSLATIONS} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E remove - ${CMAKE_BINARY_DIR}/translations/test_test.qm + TARGET ${TEST_GENERATETRANSLATIONS} POST_BUILD COMMAND ${CMAKE_COMMAND} -E remove + ${CMAKE_BINARY_DIR}/translations/test_test.qm ) - SETUP_SCOPY_TESTS( - translationsrepository - ) + setup_scopy_tests(translationsrepository) endif() diff --git a/core/test/tst_pluginmanager.cpp b/core/test/tst_pluginmanager.cpp index d475b2401e..160ea0dc84 100644 --- a/core/test/tst_pluginmanager.cpp +++ b/core/test/tst_pluginmanager.cpp @@ -1,10 +1,11 @@ -#include -#include #include "core/pluginmanager.h" + +#include #include #include -#include #include +#include +#include using namespace scopy; @@ -23,12 +24,10 @@ private Q_SLOTS: void exclusionExceptLowercase(); private: - void initFileList(); QStringList libs; }; - #define NONPLUGIN_LIBRARY_LOCATION "../libscopycore.so" #define PLUGIN_LOCATION "../../plugins/plugins" @@ -42,56 +41,57 @@ void TST_PluginManager::loadLibs() { PluginManager *p = new PluginManager(this); p->add(libs); - QVERIFY2(p->count() > 0,"Load libs failed"); + QVERIFY2(p->count() > 0, "Load libs failed"); p->clear(); - QVERIFY2(p->count() == 0,"Clear libs failed"); + QVERIFY2(p->count() == 0, "Clear libs failed"); for(const auto &lib : qAsConst(libs)) { p->add(lib); } - QVERIFY2(p->count() > 0,"Add 1-by-1 failed"); + QVERIFY2(p->count() > 0, "Add 1-by-1 failed"); - QList plugins; - QList sortedplugins; + QList plugins; + QList sortedplugins; plugins = p->getPlugins(""); - QVERIFY2(plugins.count() == p->count(),"Plugin clone failed"); + QVERIFY2(plugins.count() == p->count(), "Plugin clone failed"); p->sort(); sortedplugins = p->getPlugins(""); for(auto p : qAsConst(plugins)) { for(auto q : qAsConst(sortedplugins)) { - if(p==q) + if(p == q) QFAIL("duplicates found in sortedplugins vs plugins"); } } - QVERIFY2(plugins.count() == sortedplugins.count(),"Subsequent call to get plugin gives different counts"); - for (int i = 1;imetadata()["priority"].toInt() < sortedplugins[i]->metadata()["priority"].toInt()) + QVERIFY2(plugins.count() == sortedplugins.count(), "Subsequent call to get plugin gives different counts"); + for(int i = 1; i < sortedplugins.count(); i++) { + if(sortedplugins[i - 1]->metadata()["priority"].toInt() < + sortedplugins[i]->metadata()["priority"].toInt()) QFAIL("Sort by priority failed"); } - QList usbPlugins = p->getCompatiblePlugins("usb:","test"); + QList usbPlugins = p->getCompatiblePlugins("usb:", "test"); for(auto &&p : usbPlugins) { QVERIFY2(p->param() == "usb:", "param not set to plugin"); } - QList ipPlugins = p->getCompatiblePlugins("ip:","test"); + QList ipPlugins = p->getCompatiblePlugins("ip:", "test"); bool found = false; QVERIFY2(ipPlugins.count() > 0, "No ip: plugins found"); for(auto &&p : ipPlugins) { - if(p->name()=="TestPluginIp") + if(p->name() == "TestPluginIp") found = true; } QVERIFY2(found, "TestPluginIp not found"); p->add(NONPLUGIN_LIBRARY_LOCATION); - QVERIFY2(p->count() == plugins.count(),"Added nonplugin library to manager"); + QVERIFY2(p->count() == plugins.count(), "Added nonplugin library to manager"); usbPlugins.clear(); - usbPlugins = p->getCompatiblePlugins("usb:","test"); + usbPlugins = p->getCompatiblePlugins("usb:", "test"); for(auto &&p : usbPlugins) { QVERIFY2(p->param() == "usb:", "param not set to plugin"); } @@ -103,64 +103,64 @@ void TST_PluginManager::metadataOps() { PluginManager *p = new PluginManager(this); p->add(libs); - QVERIFY2(p->count() > 0,"Load libs failed"); + QVERIFY2(p->count() > 0, "Load libs failed"); QString json = QString( - #include "testplugin.json" - ); +#include "testplugin.json" + ); QJsonParseError err; QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8(), &err); if(err.error != QJsonParseError::NoError) { qCritical() << "JSON Parse error !" << err.errorString(); qCritical() << json; - qCritical() << QString(" ").repeated(err.offset)+"^"; + qCritical() << QString(" ").repeated(err.offset) + "^"; } QJsonObject obj = doc.object(); p->clear(); p->setMetadata(obj); p->add(libs); p->sort(); - QVERIFY2(p->count() > 0,"Load libs failed"); + QVERIFY2(p->count() > 0, "Load libs failed"); auto plugins = p->getPlugins("test"); - QVERIFY2(plugins.count() >= 2,"Exactly 2 unit tests not found"); - qDebug()<name(); + QVERIFY2(plugins.count() >= 2, "Exactly 2 unit tests not found"); + qDebug() << plugins[0]->name(); - QVERIFY2(plugins[0]->name()=="TestPluginIp", "TestPluginIp is not loaded with highest priority"); - QVERIFY2(plugins[0]->metadata()["priority"]==1000, "TestPluginIp priority not overridden"); + QVERIFY2(plugins[0]->name() == "TestPluginIp", "TestPluginIp is not loaded with highest priority"); + QVERIFY2(plugins[0]->metadata()["priority"] == 1000, "TestPluginIp priority not overridden"); } void TST_PluginManager::exclusion() { PluginManager *p = new PluginManager(this); p->add(libs); - QVERIFY2(p->count() > 0,"Load libs failed"); + QVERIFY2(p->count() > 0, "Load libs failed"); QString json = QString( - #include "testpluginexclude.json" - ); +#include "testpluginexclude.json" + ); QJsonParseError err; QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8(), &err); if(err.error != QJsonParseError::NoError) { qCritical() << "JSON Parse error !" << err.errorString(); qCritical() << json; - qCritical() << QString(" ").repeated(err.offset)+"^"; + qCritical() << QString(" ").repeated(err.offset) + "^"; } QJsonObject obj = doc.object(); p->clear(); p->setMetadata(obj); p->add(libs); p->sort(); - QVERIFY2(p->count() > 0,"Load libs failed"); + QVERIFY2(p->count() > 0, "Load libs failed"); - auto plugins = p->getCompatiblePlugins("ip:","unittest"); - QVERIFY2(plugins.count() == 2,"Only TestPluginIp plugin compatible compatible"); - qDebug()<name(); - qDebug()<name(); + auto plugins = p->getCompatiblePlugins("ip:", "unittest"); + QVERIFY2(plugins.count() == 2, "Only TestPluginIp plugin compatible compatible"); + qDebug() << plugins[0]->name(); + qDebug() << plugins[1]->name(); - QVERIFY2(plugins[0]->name()=="TestPluginIp", "TestPlugin is the first plugin"); - QVERIFY2(plugins[0]->metadata()["exclude"]=="*", "TestPluginIp excludes everything"); - QVERIFY2(plugins[1]->name()=="TestPlugin", "TestPluginIp is the second plugin"); + QVERIFY2(plugins[0]->name() == "TestPluginIp", "TestPlugin is the first plugin"); + QVERIFY2(plugins[0]->metadata()["exclude"] == "*", "TestPluginIp excludes everything"); + QVERIFY2(plugins[1]->name() == "TestPlugin", "TestPluginIp is the second plugin"); QVERIFY2(plugins[0]->enabled() == true, "TestPluginIp not enabled"); QVERIFY2(plugins[1]->enabled() == false, "TestPlugin is enabled"); @@ -170,32 +170,32 @@ void TST_PluginManager::exclusionSpecificLowercase() { PluginManager *p = new PluginManager(this); p->add(libs); - QVERIFY2(p->count() > 0,"Load libs failed"); + QVERIFY2(p->count() > 0, "Load libs failed"); QString json = QString( - #include "testPluginExcludeSpecificLower.json" - ); +#include "testPluginExcludeSpecificLower.json" + ); QJsonParseError err; QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8(), &err); if(err.error != QJsonParseError::NoError) { qCritical() << "JSON Parse error !" << err.errorString(); qCritical() << json; - qCritical() << QString(" ").repeated(err.offset)+"^"; + qCritical() << QString(" ").repeated(err.offset) + "^"; } QJsonObject obj = doc.object(); p->clear(); p->setMetadata(obj); p->add(libs); p->sort(); - QVERIFY2(p->count() > 0,"Load libs failed"); + QVERIFY2(p->count() > 0, "Load libs failed"); - auto plugins = p->getCompatiblePlugins("ip:","unittest"); - QVERIFY2(plugins.count() == 2,"Exactly 1 unit tests not found"); - qDebug()<name(); + auto plugins = p->getCompatiblePlugins("ip:", "unittest"); + QVERIFY2(plugins.count() == 2, "Exactly 1 unit tests not found"); + qDebug() << plugins[0]->name(); - QVERIFY2(plugins[0]->name()=="TestPluginIp", "TestPluginIp is the first plugin"); + QVERIFY2(plugins[0]->name() == "TestPluginIp", "TestPluginIp is the first plugin"); QVERIFY2(plugins[0]->metadata()["exclude"].toArray()[0] == "testplugin", "TestPluginIP "); - QVERIFY2(plugins[1]->name()=="TestPlugin", "TestPlugin is the second plugin"); + QVERIFY2(plugins[1]->name() == "TestPlugin", "TestPlugin is the second plugin"); QVERIFY2(plugins[0]->enabled() == true, "TestPluginIp not enabled"); QVERIFY2(plugins[1]->enabled() == false, "TestPlugin is enabled"); @@ -205,32 +205,32 @@ void TST_PluginManager::exclusionSpecificUppercase() { PluginManager *p = new PluginManager(this); p->add(libs); - QVERIFY2(p->count() > 0,"Load libs failed"); + QVERIFY2(p->count() > 0, "Load libs failed"); QString json = QString( - #include "testPluginExcludeSpecificUpper.json" - ); +#include "testPluginExcludeSpecificUpper.json" + ); QJsonParseError err; QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8(), &err); if(err.error != QJsonParseError::NoError) { qCritical() << "JSON Parse error !" << err.errorString(); qCritical() << json; - qCritical() << QString(" ").repeated(err.offset)+"^"; + qCritical() << QString(" ").repeated(err.offset) + "^"; } QJsonObject obj = doc.object(); p->clear(); p->setMetadata(obj); p->add(libs); p->sort(); - QVERIFY2(p->count() > 0,"Load libs failed"); + QVERIFY2(p->count() > 0, "Load libs failed"); - auto plugins = p->getCompatiblePlugins("ip:","unittest"); - QVERIFY2(plugins.count() == 2,"Exactly 1 unit tests not found"); - qDebug()<name(); + auto plugins = p->getCompatiblePlugins("ip:", "unittest"); + QVERIFY2(plugins.count() == 2, "Exactly 1 unit tests not found"); + qDebug() << plugins[0]->name(); - QVERIFY2(plugins[0]->name()=="TestPluginIp", "TestPluginIp is the first plugin"); + QVERIFY2(plugins[0]->name() == "TestPluginIp", "TestPluginIp is the first plugin"); QVERIFY2(plugins[0]->metadata()["exclude"].toArray()[0] == "TESTPLUGIN", "TestPluginIP "); - QVERIFY2(plugins[1]->name()=="TestPlugin", "TestPlugin is the second plugin"); + QVERIFY2(plugins[1]->name() == "TestPlugin", "TestPlugin is the second plugin"); QVERIFY2(plugins[0]->enabled() == true, "TestPluginIp not enabled"); QVERIFY2(plugins[1]->enabled() == false, "TestPlugin is enabled"); @@ -240,96 +240,102 @@ void TST_PluginManager::exclusionExcept() { PluginManager *p = new PluginManager(this); p->add(libs); - QVERIFY2(p->count() > 0,"Load libs failed"); + QVERIFY2(p->count() > 0, "Load libs failed"); QString json = QString( - #include "testpluginexclude2.json" - ); +#include "testpluginexclude2.json" + ); QJsonParseError err; QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8(), &err); if(err.error != QJsonParseError::NoError) { qCritical() << "JSON Parse error !" << err.errorString(); qCritical() << json; - qCritical() << QString(" ").repeated(err.offset)+"^"; + qCritical() << QString(" ").repeated(err.offset) + "^"; } QJsonObject obj = doc.object(); p->clear(); p->setMetadata(obj); p->add(libs); p->sort(); - QVERIFY2(p->count() > 0,"Load libs failed"); + QVERIFY2(p->count() > 0, "Load libs failed"); - auto plugins = p->getCompatiblePlugins("ip:","unittest"); - QVERIFY2(plugins.count() == 2,"Exactly 1 unit tests not found"); - qDebug()<name(); + auto plugins = p->getCompatiblePlugins("ip:", "unittest"); + QVERIFY2(plugins.count() == 2, "Exactly 1 unit tests not found"); + qDebug() << plugins[0]->name(); - QVERIFY2(plugins[0]->name()=="TestPluginIp", "TestPluginIp is not loaded"); - QVERIFY2(plugins[0]->metadata()["exclude"].toArray()[0] == "*" && plugins[0]->metadata()["exclude"].toArray()[1]=="!TestPlugin", "TestPluginIP "); - QVERIFY2(plugins[1]->name()=="TestPlugin", "Second TestPlugin is not loaded"); + QVERIFY2(plugins[0]->name() == "TestPluginIp", "TestPluginIp is not loaded"); + QVERIFY2(plugins[0]->metadata()["exclude"].toArray()[0] == "*" && + plugins[0]->metadata()["exclude"].toArray()[1] == "!TestPlugin", + "TestPluginIP "); + QVERIFY2(plugins[1]->name() == "TestPlugin", "Second TestPlugin is not loaded"); } void TST_PluginManager::exclusionExceptUppercase() { PluginManager *p = new PluginManager(this); p->add(libs); - QVERIFY2(p->count() > 0,"Load libs failed"); + QVERIFY2(p->count() > 0, "Load libs failed"); QString json = QString( - #include "testPluginExcludeUpper.json" - ); +#include "testPluginExcludeUpper.json" + ); QJsonParseError err; QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8(), &err); if(err.error != QJsonParseError::NoError) { qCritical() << "JSON Parse error !" << err.errorString(); qCritical() << json; - qCritical() << QString(" ").repeated(err.offset)+"^"; + qCritical() << QString(" ").repeated(err.offset) + "^"; } QJsonObject obj = doc.object(); p->clear(); p->setMetadata(obj); p->add(libs); p->sort(); - QVERIFY2(p->count() > 0,"Load libs failed"); + QVERIFY2(p->count() > 0, "Load libs failed"); - auto plugins = p->getCompatiblePlugins("ip:","unittest"); - QVERIFY2(plugins.count() == 2,"Exactly 1 unit tests not found"); - qDebug()<name(); + auto plugins = p->getCompatiblePlugins("ip:", "unittest"); + QVERIFY2(plugins.count() == 2, "Exactly 1 unit tests not found"); + qDebug() << plugins[0]->name(); - QVERIFY2(plugins[0]->name()=="TestPluginIp", "TestPluginIp is not loaded"); - QVERIFY2(plugins[0]->metadata()["exclude"].toArray()[0] == "*" && plugins[0]->metadata()["exclude"].toArray()[1]=="!TESTPLUGIN", "TestPluginIP "); - QVERIFY2(plugins[1]->name()=="TestPlugin", "Second TestPlugin is not loaded"); + QVERIFY2(plugins[0]->name() == "TestPluginIp", "TestPluginIp is not loaded"); + QVERIFY2(plugins[0]->metadata()["exclude"].toArray()[0] == "*" && + plugins[0]->metadata()["exclude"].toArray()[1] == "!TESTPLUGIN", + "TestPluginIP "); + QVERIFY2(plugins[1]->name() == "TestPlugin", "Second TestPlugin is not loaded"); } void TST_PluginManager::exclusionExceptLowercase() { PluginManager *p = new PluginManager(this); p->add(libs); - QVERIFY2(p->count() > 0,"Load libs failed"); + QVERIFY2(p->count() > 0, "Load libs failed"); QString json = QString( - #include "testPluginExcludeLower.json" - ); +#include "testPluginExcludeLower.json" + ); QJsonParseError err; QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8(), &err); if(err.error != QJsonParseError::NoError) { qCritical() << "JSON Parse error !" << err.errorString(); qCritical() << json; - qCritical() << QString(" ").repeated(err.offset)+"^"; + qCritical() << QString(" ").repeated(err.offset) + "^"; } QJsonObject obj = doc.object(); p->clear(); p->setMetadata(obj); p->add(libs); p->sort(); - QVERIFY2(p->count() > 0,"Load libs failed"); + QVERIFY2(p->count() > 0, "Load libs failed"); - auto plugins = p->getCompatiblePlugins("ip:","unittest"); - QVERIFY2(plugins.count() == 2,"Exactly 1 unit tests not found"); - qDebug()<name(); + auto plugins = p->getCompatiblePlugins("ip:", "unittest"); + QVERIFY2(plugins.count() == 2, "Exactly 1 unit tests not found"); + qDebug() << plugins[0]->name(); - QVERIFY2(plugins[0]->name()=="TestPluginIp", "TestPluginIp is not loaded"); - QVERIFY2(plugins[0]->metadata()["exclude"].toArray()[0] == "*" && plugins[0]->metadata()["exclude"].toArray()[1]=="!testplugin", "TestPluginIP "); - QVERIFY2(plugins[1]->name()=="TestPlugin", "Second TestPlugin is not loaded"); + QVERIFY2(plugins[0]->name() == "TestPluginIp", "TestPluginIp is not loaded"); + QVERIFY2(plugins[0]->metadata()["exclude"].toArray()[0] == "*" && + plugins[0]->metadata()["exclude"].toArray()[1] == "!testplugin", + "TestPluginIP "); + QVERIFY2(plugins[1]->name() == "TestPlugin", "Second TestPlugin is not loaded"); } void TST_PluginManager::initFileList() @@ -339,7 +345,7 @@ void TST_PluginManager::initFileList() libs.clear(); for(const QString &file : files) { if(QLibrary::isLibrary(file)) { - qDebug()<<"Library: " << file; + qDebug() << "Library: " << file; libs.append(directory.absoluteFilePath(file)); } } diff --git a/core/test/tst_pluginrepository.cpp b/core/test/tst_pluginrepository.cpp index 127f3bca32..bef4ee58e0 100644 --- a/core/test/tst_pluginrepository.cpp +++ b/core/test/tst_pluginrepository.cpp @@ -1,7 +1,8 @@ -#include -#include #include "core/pluginrepository.h" + #include +#include +#include using namespace scopy; @@ -15,24 +16,20 @@ private Q_SLOTS: QStringList libs; }; - #define NONPLUGIN_LIBRARY_LOCATION "../libscopycore.so" #define PLUGIN_LOCATION "../../plugins/plugins" - void TST_PluginRepository::loadLibs() { PluginRepository *p = new PluginRepository(this); PluginManager *pm = p->getPluginManager(); QVERIFY(pm->metadata().isEmpty()); p->init(PLUGIN_LOCATION); -// QVERIFY(!pm->metadata().isEmpty()); - + // QVERIFY(!pm->metadata().isEmpty()); delete p; } - QTEST_MAIN(TST_PluginRepository) #include "tst_pluginrepository.moc" diff --git a/core/test/tst_translationsrepository.cpp b/core/test/tst_translationsrepository.cpp index 69a770040c..da9e7b4dd0 100644 --- a/core/test/tst_translationsrepository.cpp +++ b/core/test/tst_translationsrepository.cpp @@ -1,7 +1,8 @@ -#include -#include #include "core/translationsrepository.h" + #include +#include +#include using namespace scopy; diff --git a/gr-util/CMakeLists.txt b/gr-util/CMakeLists.txt index 183dacd5aa..9e57969a78 100644 --- a/gr-util/CMakeLists.txt +++ b/gr-util/CMakeLists.txt @@ -5,8 +5,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -21,49 +20,54 @@ set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_CXX_VISIBILITY_PRESET hidden) set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) -FILE(GLOB SRC_LIST src/*.cpp src/*.cc) -FILE(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) -FILE(GLOB UI_LIST ui/*.ui) +file(GLOB SRC_LIST src/*.cpp src/*.cc) +file(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) +file(GLOB UI_LIST ui/*.ui) if(ENABLE_TESTING) - add_subdirectory(test) + add_subdirectory(test) endif() -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} -) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED) -find_package(Gnuradio "3.10" REQUIRED COMPONENTS runtime analog blocks fft filter volk pmt iio) +find_package( + Gnuradio "3.10" REQUIRED + COMPONENTS runtime + analog + blocks + fft + filter + volk + pmt + iio +) find_package(gnuradio-scopy REQUIRED PATH_SUFFIXES scopy) -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) -target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE} - ${IIO_INCLUDE_DIRS} - scopy-gui +target_include_directories( + ${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE} ${IIO_INCLUDE_DIRS} scopy-gui ) -target_link_libraries(${PROJECT_NAME} PUBLIC Qt${QT_VERSION_MAJOR}::Core - scopy-iioutil - scopy-gui - scopy-gr-gui - gnuradio::gnuradio-runtime - gnuradio::gnuradio-analog - gnuradio::gnuradio-blocks - gnuradio::gnuradio-fft - gnuradio::gnuradio-filter - gnuradio::gnuradio-pmt - gnuradio::gnuradio-iio - gnuradio::gnuradio-scopy +target_link_libraries( + ${PROJECT_NAME} + PUBLIC Qt${QT_VERSION_MAJOR}::Core + scopy-iioutil + scopy-gui + scopy-gr-gui + gnuradio::gnuradio-runtime + gnuradio::gnuradio-analog + gnuradio::gnuradio-blocks + gnuradio::gnuradio-fft + gnuradio::gnuradio-filter + gnuradio::gnuradio-pmt + gnuradio::gnuradio-iio + gnuradio::gnuradio-scopy ) - - diff --git a/gr-util/include/gr-util/grdeviceaddon.h b/gr-util/include/gr-util/grdeviceaddon.h index 4cdcc4def1..aa7ed87b67 100644 --- a/gr-util/include/gr-util/grdeviceaddon.h +++ b/gr-util/include/gr-util/grdeviceaddon.h @@ -1,26 +1,28 @@ #ifndef GRDEVICEADDON_H #define GRDEVICEADDON_H -#include "tooladdon.h" #include "griiodevicesource.h" -#include #include "scopy-gr-util_export.h" +#include "tooladdon.h" + +#include namespace scopy::grutil { class GRTimeChannelAddon; -class SCOPY_GR_UTIL_EXPORT GRDeviceAddon : public QObject, public ToolAddon, public GRTopAddon { +class SCOPY_GR_UTIL_EXPORT GRDeviceAddon : public QObject, public ToolAddon, public GRTopAddon +{ Q_OBJECT public: GRDeviceAddon(GRIIODeviceSource *src, QObject *parent = nullptr); ~GRDeviceAddon(); QString getName() override; - QWidget* getWidget() override; + QWidget *getWidget() override; GRIIODeviceSource *src() const; void registerChannel(GRTimeChannelAddon *ch); - QList getRegisteredChannels(); + QList getRegisteredChannels(); Q_SIGNALS: void updateBufferSize(uint32_t); @@ -40,19 +42,18 @@ public Q_SLOTS: void postFlowBuild() override {} void preFlowTeardown() override {} void postFlowTeardown() override {} - void onChannelAdded(ToolAddon*) override; - void onChannelRemoved(ToolAddon*) override; + void onChannelAdded(ToolAddon *) override; + void onChannelRemoved(ToolAddon *) override; private: QString name; QWidget *widget; GRIIODeviceSource *m_src; - QList m_channels; + QList m_channels; private Q_SLOTS: void setBufferSize(uint32_t bufferSize); - }; -} +} // namespace scopy::grutil #endif // GRDEVICEADDON_H diff --git a/gr-util/include/gr-util/griiocomplexchannelsrc.h b/gr-util/include/gr-util/griiocomplexchannelsrc.h index bf605b9e5b..81d4a67735 100644 --- a/gr-util/include/gr-util/griiocomplexchannelsrc.h +++ b/gr-util/include/gr-util/griiocomplexchannelsrc.h @@ -1,18 +1,20 @@ #ifndef GRIIOCOMPLEXCHANNELSRC_H #define GRIIOCOMPLEXCHANNELSRC_H -#include "scopy-gr-util_export.h" -#include "grproxyblock.h" #include "griiodevicesource.h" +#include "grproxyblock.h" +#include "scopy-gr-util_export.h" -#include #include +#include namespace scopy::grutil { -class SCOPY_GR_UTIL_EXPORT GRIIOComplexChannelSrc : public GRIIOChannel { +class SCOPY_GR_UTIL_EXPORT GRIIOComplexChannelSrc : public GRIIOChannel +{ public: - GRIIOComplexChannelSrc(QString channelName, GRIIODeviceSource* dev, QString channelNameI, QString channelNameQ,QObject *parent = nullptr); + GRIIOComplexChannelSrc(QString channelName, GRIIODeviceSource *dev, QString channelNameI, QString channelNameQ, + QObject *parent = nullptr); void build_blks(GRTopBlock *top); void destroy_blks(GRTopBlock *top); @@ -25,7 +27,6 @@ class SCOPY_GR_UTIL_EXPORT GRIIOComplexChannelSrc : public GRIIOChannel { QString channelNameQ; gr::blocks::short_to_float::sptr s2f[2]; gr::blocks::float_to_complex::sptr f2c; - }; -} +} // namespace scopy::grutil #endif // GRIIOCOMPLEXCHANNELSRC_H diff --git a/gr-util/include/gr-util/griiodevicesource.h b/gr-util/include/gr-util/griiodevicesource.h index 88f1e1c8db..3591d00c54 100644 --- a/gr-util/include/gr-util/griiodevicesource.h +++ b/gr-util/include/gr-util/griiodevicesource.h @@ -3,40 +3,47 @@ #include "grproxyblock.h" #include "scopy-gr-util_export.h" -#include + #include +#include + namespace scopy::grutil { class GRIIODeviceSource; -//typedef GRProxyBlock GRIIOChannel; // TODO: create interface here -class SCOPY_GR_UTIL_EXPORT GRIIOChannel : public GRProxyBlock { +// typedef GRProxyBlock GRIIOChannel; // TODO: create interface here +class SCOPY_GR_UTIL_EXPORT GRIIOChannel : public GRProxyBlock +{ public: - GRIIOChannel(QString channelName, GRIIODeviceSource *dev, QObject *parent = nullptr) : GRProxyBlock(parent), channelName(channelName), dev(dev) { } - GRIIODeviceSource* getDeviceSrc() { return dev; } - QString getChannelName() { return channelName;} + GRIIOChannel(QString channelName, GRIIODeviceSource *dev, QObject *parent = nullptr) + : GRProxyBlock(parent) + , channelName(channelName) + , dev(dev) + {} + GRIIODeviceSource *getDeviceSrc() { return dev; } + QString getChannelName() { return channelName; } virtual bool sampleRateAvailable() { return false; } virtual double readSampleRate() { return -1; } - static QString findAttribute(QStringList possibleNames, iio_channel*); + static QString findAttribute(QStringList possibleNames, iio_channel *); protected: - QString channelName; - GRIIODeviceSource* dev; - + GRIIODeviceSource *dev; }; -class SCOPY_GR_UTIL_EXPORT GRIIODeviceSource : public GRProxyBlock { // is this a proxy block +class SCOPY_GR_UTIL_EXPORT GRIIODeviceSource : public GRProxyBlock +{ // is this a proxy block public: - GRIIODeviceSource(iio_context *ctx, QString deviceName, QString phyDeviceName, unsigned int buffersize = 0x400, QObject *parent = nullptr); + GRIIODeviceSource(iio_context *ctx, QString deviceName, QString phyDeviceName, unsigned int buffersize = 0x400, + QObject *parent = nullptr); void build_blks(GRTopBlock *top) override; void destroy_blks(GRTopBlock *top) override; - void connect_blk(GRTopBlock *top, GRProxyBlock*) override; + void connect_blk(GRTopBlock *top, GRProxyBlock *) override; void disconnect_blk(GRTopBlock *top) override; - void addChannel(GRIIOChannel*); - void removeChannel(GRIIOChannel*); + void addChannel(GRIIOChannel *); + void removeChannel(GRIIOChannel *); unsigned int getBuffersize() const; void setBuffersize(unsigned int newBuffersize); @@ -51,12 +58,12 @@ class SCOPY_GR_UTIL_EXPORT GRIIODeviceSource : public GRProxyBlock { // is this iio_device *iioDev() const; protected: - QList m_list; + QList m_list; std::vector m_channelNames; QString m_deviceName; QString m_phyDeviceName; iio_context *m_ctx; - iio_device* m_iioDev; + iio_device *m_iioDev; unsigned int m_buffersize; gr::iio::device_source::sptr src; @@ -65,8 +72,8 @@ class SCOPY_GR_UTIL_EXPORT GRIIODeviceSource : public GRProxyBlock { // is this QString m_sampleRateAttribute; void computeChannelNames(); void addChannelAtIndex(iio_device *dev, QString channelName); - void matchChannelToBlockOutputs(GRTopBlock* top); + void matchChannelToBlockOutputs(GRTopBlock *top); int getOutputIndex(QString ch); }; -} +} // namespace scopy::grutil #endif // GRIIODEVICESOURCE_H diff --git a/gr-util/include/gr-util/griiofloatchannelsrc.h b/gr-util/include/gr-util/griiofloatchannelsrc.h index c647dc1d04..42e2451097 100644 --- a/gr-util/include/gr-util/griiofloatchannelsrc.h +++ b/gr-util/include/gr-util/griiofloatchannelsrc.h @@ -1,13 +1,14 @@ #ifndef GRIIOFLOATCHANNELSRC_H #define GRIIOFLOATCHANNELSRC_H -#include "scopy-gr-util_export.h" #include "griiodevicesource.h" +#include "scopy-gr-util_export.h" namespace scopy::grutil { -class SCOPY_GR_UTIL_EXPORT GRIIOFloatChannelSrc : public GRIIOChannel { +class SCOPY_GR_UTIL_EXPORT GRIIOFloatChannelSrc : public GRIIOChannel +{ public: - GRIIOFloatChannelSrc(GRIIODeviceSource* dev,QString channelName,QObject *parent = nullptr); + GRIIOFloatChannelSrc(GRIIODeviceSource *dev, QString channelName, QObject *parent = nullptr); void build_blks(GRTopBlock *top); void destroy_blks(GRTopBlock *top); @@ -18,10 +19,11 @@ class SCOPY_GR_UTIL_EXPORT GRIIOFloatChannelSrc : public GRIIOChannel { protected: gr::basic_block_sptr x2f; + private: - const iio_data_format* fmt; + const iio_data_format *fmt; iio_channel *m_iioCh; QString m_sampleRateAttribute; }; -} +} // namespace scopy::grutil #endif // GRIIOFLOATCHANNELSRC_H diff --git a/gr-util/include/gr-util/grproxyblock.h b/gr-util/include/gr-util/grproxyblock.h index 92e88e998b..25b19ef5fe 100644 --- a/gr-util/include/gr-util/grproxyblock.h +++ b/gr-util/include/gr-util/grproxyblock.h @@ -1,8 +1,10 @@ #ifndef GRPROXYBLOCK_H #define GRPROXYBLOCK_H -#include #include "scopy-gr-util_export.h" + +#include + #include namespace scopy::grutil { @@ -34,9 +36,9 @@ class SCOPY_GR_UTIL_EXPORT GRProxyBlock : public QObject QList start_blk; // QList of (?) gr::basic_block_sptr end_blk; bool m_enabled; -// bool m_built; + // bool m_built; }; -} +} // namespace scopy::grutil #endif // GRPROXYBLOCK_H diff --git a/gr-util/include/gr-util/grscaleoffsetproc.h b/gr-util/include/gr-util/grscaleoffsetproc.h index f7149cead9..a475270b6e 100644 --- a/gr-util/include/gr-util/grscaleoffsetproc.h +++ b/gr-util/include/gr-util/grscaleoffsetproc.h @@ -2,12 +2,14 @@ #define GRSCALEOFFSETPROC_H #include "grproxyblock.h" +#include "scopy-gr-util_export.h" + #include #include -#include "scopy-gr-util_export.h" namespace scopy::grutil { -class SCOPY_GR_UTIL_EXPORT GRScaleOffsetProc : public GRProxyBlock { +class SCOPY_GR_UTIL_EXPORT GRScaleOffsetProc : public GRProxyBlock +{ public: GRScaleOffsetProc(QObject *parent = nullptr); void setScale(double sc); @@ -16,11 +18,10 @@ class SCOPY_GR_UTIL_EXPORT GRScaleOffsetProc : public GRProxyBlock { void destroy_blks(GRTopBlock *top); protected: - gr::blocks::add_const_ff::sptr add; gr::blocks::multiply_const_ff::sptr mul; double m_scale; double m_offset; }; -} +} // namespace scopy::grutil #endif // GRSCALEOFFSETPROC_H diff --git a/gr-util/include/gr-util/grsignalpath.h b/gr-util/include/gr-util/grsignalpath.h index cece9bf4e9..f264ca1996 100644 --- a/gr-util/include/gr-util/grsignalpath.h +++ b/gr-util/include/gr-util/grsignalpath.h @@ -1,18 +1,20 @@ #ifndef GRSIGNALPATH_H #define GRSIGNALPATH_H -#include #include "grproxyblock.h" #include "scopy-gr-util_export.h" +#include + namespace scopy::grutil { class GRTopBlock; class GRProxyBlock; -class SCOPY_GR_UTIL_EXPORT GRSignalPath : public GRProxyBlock { +class SCOPY_GR_UTIL_EXPORT GRSignalPath : public GRProxyBlock +{ Q_OBJECT public: GRSignalPath(QString name, QObject *parent = nullptr); - void append(GRProxyBlock* p); + void append(GRProxyBlock *p); void build_blks(); void destroy_blks(); virtual QList getGrStartPoint(); @@ -20,11 +22,11 @@ class SCOPY_GR_UTIL_EXPORT GRSignalPath : public GRProxyBlock { virtual void connect_blk(GRTopBlock *top, GRProxyBlock *src); virtual void disconnect_blk(GRTopBlock *top); QString name() const; - QList path(); + QList path(); protected: - QList list; + QList list; QString m_name; }; -} +} // namespace scopy::grutil #endif // GRSIGNALPATH_H diff --git a/gr-util/include/gr-util/grsignalsrc.h b/gr-util/include/gr-util/grsignalsrc.h index 2c289d5ecc..889cadb6e8 100644 --- a/gr-util/include/gr-util/grsignalsrc.h +++ b/gr-util/include/gr-util/grsignalsrc.h @@ -2,11 +2,13 @@ #define GRSIGNALSRC_H #include "grproxyblock.h" -#include #include "scopy-gr-util_export.h" +#include + namespace scopy::grutil { -class SCOPY_GR_UTIL_EXPORT GRSignalSrc : public GRProxyBlock { +class SCOPY_GR_UTIL_EXPORT GRSignalSrc : public GRProxyBlock +{ Q_OBJECT public: GRSignalSrc(QObject *parent = nullptr); @@ -30,5 +32,5 @@ class SCOPY_GR_UTIL_EXPORT GRSignalSrc : public GRProxyBlock { double m_amplitude; double m_offset; }; -} +} // namespace scopy::grutil #endif // GRSIGNALSRC_H diff --git a/gr-util/include/gr-util/grtimechanneladdon.h b/gr-util/include/gr-util/grtimechanneladdon.h index 99cd53c224..fc769c0260 100644 --- a/gr-util/include/gr-util/grtimechanneladdon.h +++ b/gr-util/include/gr-util/grtimechanneladdon.h @@ -1,43 +1,45 @@ #ifndef GRTIMECHANNELADDON_H #define GRTIMECHANNELADDON_H -#include "tooladdon.h" +#include "griiofloatchannelsrc.h" +#include "grscaleoffsetproc.h" #include "grsignalpath.h" #include "grtimeplotaddon.h" -#include "griiofloatchannelsrc.h" -#include "measurementcontroller.h" #include "measure.h" +#include "measurementcontroller.h" #include "measurementselector.h" +#include "scopy-gr-util_export.h" +#include "tooladdon.h" #include -#include "scopy-gr-util_export.h" + #include #include #include -#include "grscaleoffsetproc.h" #include - #include - namespace scopy::grutil { class GRDeviceAddon; -class SCOPY_GR_UTIL_EXPORT GRTimeChannelAddon : public QObject, public ToolAddon, public GRTopAddon { +class SCOPY_GR_UTIL_EXPORT GRTimeChannelAddon : public QObject, public ToolAddon, public GRTopAddon +{ Q_OBJECT public: - typedef enum { + typedef enum + { YMODE_COUNT, YMODE_FS, YMODE_SCALE } YMode; - GRTimeChannelAddon(QString ch, GRDeviceAddon* dev, GRTimePlotAddon* plotAddon, QPen pen, QObject *parent = nullptr); + GRTimeChannelAddon(QString ch, GRDeviceAddon *dev, GRTimePlotAddon *plotAddon, QPen pen, + QObject *parent = nullptr); ~GRTimeChannelAddon(); QString getName() override; - QWidget* getWidget() override; + QWidget *getWidget() override; void setDevice(GRDeviceAddon *d); - GRDeviceAddon* getDevice(); + GRDeviceAddon *getDevice(); QPen pen() const; bool enabled() const; @@ -56,31 +58,30 @@ public Q_SLOTS: void onDeinit() override; void preFlowBuild() override; - void onNewData(const float* xData, const float* yData, int size); + void onNewData(const float *xData, const float *yData, int size); - void onChannelAdded(ToolAddon*) override; - void onChannelRemoved(ToolAddon*) override; + void onChannelAdded(ToolAddon *) override; + void onChannelRemoved(ToolAddon *) override; void toggleAutoScale(); void autoscale(); void setYMode(YMode mode); Q_SIGNALS: - void enableMeasurement(MeasurementLabel*); - void disableMeasurement(MeasurementLabel*); + void enableMeasurement(MeasurementLabel *); + void disableMeasurement(MeasurementLabel *); void toggleAllMeasurement(bool b); void toggleAllStats(bool b); - void enableStat(StatsLabel*); - void disableStat(StatsLabel*); - + void enableStat(StatsLabel *); + void disableStat(StatsLabel *); private: QString m_channelName; - GRDeviceAddon* m_dev; - GRScaleOffsetProc* m_scOff; + GRDeviceAddon *m_dev; + GRScaleOffsetProc *m_scOff; GRSignalPath *m_signalPath; GRIIOFloatChannelSrc *m_grch; - GRTimePlotAddon* m_plotAddon; + GRTimePlotAddon *m_plotAddon; QPen m_pen; QTimer *m_autoScaleTimer; @@ -112,5 +113,5 @@ public Q_SLOTS: void createMeasurementMenu(QWidget *parent); QWidget *createMeasurementMenuSection(QString category, QWidget *parent); }; -} +} // namespace scopy::grutil #endif // GRTIMECHANNELADDON_H diff --git a/gr-util/include/gr-util/grtimeplotaddon.h b/gr-util/include/gr-util/grtimeplotaddon.h index fec5249129..fc22d0ef2c 100644 --- a/gr-util/include/gr-util/grtimeplotaddon.h +++ b/gr-util/include/gr-util/grtimeplotaddon.h @@ -3,17 +3,18 @@ #include "plotinfo.h" #include "scopy-gr-util_export.h" +#include "time_sink_f.h" #include "tooladdon.h" -#include +#include #include -#include "time_sink_f.h" -#include #include #include -#include #include +#include +#include + namespace scopy { class TimePlotHDivInfo; class TimePlotSamplingInfo; @@ -24,7 +25,8 @@ class GRTopBlock; class GRTimeChannelAddon; class GRTimePlotAddonSettings; -class SCOPY_GR_UTIL_EXPORT GRTimePlotAddon : public QObject, public ToolAddon, public GRTopAddon { +class SCOPY_GR_UTIL_EXPORT GRTimePlotAddon : public QObject, public ToolAddon, public GRTopAddon +{ Q_OBJECT public: GRTimePlotAddon(QString name, GRTopBlock *top, QObject *parent = nullptr); @@ -52,8 +54,8 @@ public Q_SLOTS: void postFlowStart() override; void preFlowStop() override; void postFlowStop() override; - void onChannelAdded(ToolAddon* t) override; - void onChannelRemoved(ToolAddon*) override; + void onChannelAdded(ToolAddon *t) override; + void onChannelRemoved(ToolAddon *) override; void replot(); void connectSignalPaths(); @@ -67,7 +69,7 @@ public Q_SLOTS: double sampleRate(); void setBufferSize(uint32_t size); void setPlotSize(uint32_t size); - void handlePreferences(QString,QVariant); + void handlePreferences(QString, QVariant); void setSingleShot(bool); void setFrameRate(double); void setXMode(int mode); @@ -77,7 +79,6 @@ private Q_SLOTS: void startPlotRefresh(); void drawPlot(); - private: QString name; QWidget *widget; @@ -86,8 +87,8 @@ private Q_SLOTS: PlotWidget *m_plotWidget; TimePlotInfo *m_info; time_sink_f::sptr time_sink; - QList grChannels; - QVBoxLayout* m_lay; + QList grChannels; + QVBoxLayout *m_lay; void setupBufferPreviewer(); QFuture refillFuture; @@ -95,7 +96,6 @@ private Q_SLOTS: QMetaObject::Connection futureWatcherConn; std::mutex refillMutex; - PlotSamplingInfo m_currentSamplingInfo; bool m_started; bool m_rollingMode; @@ -104,14 +104,14 @@ private Q_SLOTS: bool m_refreshTimerRunning; int m_xmode; - QMap time_channel_map; + QMap time_channel_map; void setRawSamplesPtr(); void updateXAxis(); void updateFrameRate(); void drawTags(); }; -} -} +} // namespace grutil +} // namespace scopy #endif // GRTIMEPLOTADDON_H diff --git a/gr-util/include/gr-util/grtimeplotaddonsettings.h b/gr-util/include/gr-util/grtimeplotaddonsettings.h index 14dbf34560..8ff8e0434d 100644 --- a/gr-util/include/gr-util/grtimeplotaddonsettings.h +++ b/gr-util/include/gr-util/grtimeplotaddonsettings.h @@ -1,21 +1,25 @@ #ifndef GRTIMEPLOTADDONSETTINGS_H #define GRTIMEPLOTADDONSETTINGS_H -#include "tooladdon.h" +#include "grtimeplotaddon.h" #include "scopy-gr-util_export.h" +#include "tooladdon.h" + #include -#include "grtimeplotaddon.h" + #include -#include #include +#include namespace scopy::grutil { class GRTimePlotAddon; class GRTimeChannelAddon; -class SCOPY_GR_UTIL_EXPORT GRTimePlotAddonSettings : public QObject, public ToolAddon, public GRTopAddon { +class SCOPY_GR_UTIL_EXPORT GRTimePlotAddonSettings : public QObject, public ToolAddon, public GRTopAddon +{ Q_OBJECT public: - typedef enum { + typedef enum + { XMODE_SAMPLES, XMODE_TIME, XMODE_OVERRIDE @@ -25,7 +29,7 @@ class SCOPY_GR_UTIL_EXPORT GRTimePlotAddonSettings : public QObject, public Tool ~GRTimePlotAddonSettings(); QString getName() override; - QWidget* getWidget() override; + QWidget *getWidget() override; uint32_t bufferSize() const; @@ -49,8 +53,8 @@ public Q_SLOTS: void onInit() override; void onDeinit() override; void preFlowBuild() override; - void onChannelAdded(ToolAddon* t) override; - void onChannelRemoved(ToolAddon*) override; + void onChannelAdded(ToolAddon *t) override; + void onChannelRemoved(ToolAddon *) override; void setBufferSize(uint32_t newBufferSize); void computeSampleRateAvailable(); @@ -64,12 +68,12 @@ public Q_SLOTS: void sampleRateChanged(double); private: - QWidget* createMenu(QWidget* parent = nullptr); - QWidget* createXAxisMenu(QWidget* parent = nullptr); + QWidget *createMenu(QWidget *parent = nullptr); + QWidget *createXAxisMenu(QWidget *parent = nullptr); private: - GRTimePlotAddon* m_plot; - QList grChannels; + GRTimePlotAddon *m_plot; + QList grChannels; QString name; QWidget *widget; QPen m_pen; @@ -83,7 +87,7 @@ public Q_SLOTS: MenuOnOffSwitch *m_rollingModeSw; MenuOnOffSwitch *m_syncBufferPlot; MenuOnOffSwitch *m_showTagsSw; - MenuOnOffSwitch* m_showLabels; + MenuOnOffSwitch *m_showLabels; MenuCombo *m_xModeCb; bool m_sampleRateAvailable; @@ -102,6 +106,6 @@ public Q_SLOTS: Q_PROPERTY(double sampleRate READ sampleRate WRITE setSampleRate NOTIFY sampleRateChanged) double readSampleRate(); }; -} +} // namespace scopy::grutil #endif // GRTIMEPLOTADDONSETTINGS_H diff --git a/gr-util/include/gr-util/grtopblock.h b/gr-util/include/gr-util/grtopblock.h index 8cc303a950..a489e93c03 100644 --- a/gr-util/include/gr-util/grtopblock.h +++ b/gr-util/include/gr-util/grtopblock.h @@ -1,12 +1,14 @@ #ifndef GRTOPBLOCK_H #define GRTOPBLOCK_H -#include -#include #include "griiodevicesource.h" #include "grsignalpath.h" #include "scopy-gr-util_export.h" +#include + +#include + namespace scopy::grutil { class SCOPY_GR_UTIL_EXPORT GRTopBlock : public QObject { @@ -14,9 +16,9 @@ class SCOPY_GR_UTIL_EXPORT GRTopBlock : public QObject public: GRTopBlock(QString name, QObject *parent = nullptr); ~GRTopBlock(); - void registerSignalPath(GRSignalPath* path); - void unregisterSignalPath(GRSignalPath* path); - QList signalPaths() { return m_signalPaths;} + void registerSignalPath(GRSignalPath *path); + void unregisterSignalPath(GRSignalPath *path); + QList signalPaths() { return m_signalPaths; } void registerIIODeviceSource(GRIIODeviceSource *); void unregisterIIODeviceSource(GRIIODeviceSource *); @@ -49,9 +51,9 @@ public Q_SLOTS: QString m_name; bool running; bool built; - QList m_signalPaths; - QList m_iioDeviceSources; + QList m_signalPaths; + QList m_iioDeviceSources; }; -} +} // namespace scopy::grutil #endif // GRTOPBLOCK_H diff --git a/gr-util/include/gr-util/measure.h b/gr-util/include/gr-util/measure.h index f9ec23d7a6..1cedadae47 100644 --- a/gr-util/include/gr-util/measure.h +++ b/gr-util/include/gr-util/measure.h @@ -21,11 +21,13 @@ #ifndef MEASURE_H #define MEASURE_H +#include "scopy-gr-util_export.h" + #include +#include #include + #include -#include -#include "scopy-gr-util_export.h" namespace scopy::grutil { class CrossingDetection; @@ -55,7 +57,8 @@ class SCOPY_GR_UTIL_EXPORT Statistic class SCOPY_GR_UTIL_EXPORT MeasurementData { public: - enum unitTypes { + enum unitTypes + { METRIC, TIME, PERCENTAGE, @@ -64,15 +67,15 @@ class SCOPY_GR_UTIL_EXPORT MeasurementData DECIBELS_TO_CARRIER }; - enum axisType { + enum axisType + { HORIZONTAL, VERTICAL, HORIZONTAL_F, VERTICAL_F }; - MeasurementData(const QString& name, axisType axis, - const QString& unit = ""); + MeasurementData(const QString &name, axisType axis, const QString &unit = ""); QString name() const; double value() const; @@ -107,7 +110,6 @@ class SCOPY_GR_UTIL_EXPORT MeasureModel : public QObject { Q_OBJECT public: - MeasureModel(const float *buffer = NULL, size_t length = 0, QObject *parent = nullptr); virtual ~MeasureModel(); @@ -128,7 +130,6 @@ class SCOPY_GR_UTIL_EXPORT MeasureModel : public QObject void setGatingEnabled(bool); void clearStats(); - QList> measurments(); std::shared_ptr measurement(int id); std::shared_ptr measurement(QString); @@ -155,8 +156,10 @@ class SCOPY_GR_UTIL_EXPORT MeasureModel : public QObject QList> m_measurements; }; -class SCOPY_GR_UTIL_EXPORT TimeMeasureModel : public MeasureModel { - enum defaultMeasurements { +class SCOPY_GR_UTIL_EXPORT TimeMeasureModel : public MeasureModel +{ + enum defaultMeasurements + { PERIOD = 0, FREQUENCY, MIN, @@ -191,14 +194,14 @@ class SCOPY_GR_UTIL_EXPORT TimeMeasureModel : public MeasureModel { void measure() override; private: - void measureTime(); - bool highLowFromHistogram(double &low, double &high, - double min, double max); + bool highLowFromHistogram(double &low, double &high, double min, double max); }; -class SCOPY_GR_UTIL_EXPORT SpectralMeasure : public MeasureModel { - enum defaultSpectralMeasurements { +class SCOPY_GR_UTIL_EXPORT SpectralMeasure : public MeasureModel +{ + enum defaultSpectralMeasurements + { NOISE_FLOOR = 0, SINAD, SNR, @@ -207,6 +210,7 @@ class SCOPY_GR_UTIL_EXPORT SpectralMeasure : public MeasureModel { SFDR, DEFAULT_SPECTRAL_MEASUREMENT_COUNT }; + public: SpectralMeasure(const float *buffer = NULL, size_t length = 0); ~SpectralMeasure(); @@ -216,12 +220,11 @@ class SCOPY_GR_UTIL_EXPORT SpectralMeasure : public MeasureModel { void setMask(std::vector mask); private: - int m_harmonics_number; std::vector m_mask; void measureSpectral(); }; -} +} // namespace scopy::grutil #endif // MEASURE_H diff --git a/gr-util/include/gr-util/measurementcontroller.h b/gr-util/include/gr-util/measurementcontroller.h index ee33f0f268..ffaa1ad6f2 100644 --- a/gr-util/include/gr-util/measurementcontroller.h +++ b/gr-util/include/gr-util/measurementcontroller.h @@ -1,17 +1,19 @@ #ifndef MEASUREMENTCONTROLLER_H #define MEASUREMENTCONTROLLER_H -#include -#include -#include #include "measure.h" #include "scopy-gr-util_export.h" +#include + +#include +#include namespace scopy::grutil { class GRTimeChannelAddon; -typedef struct { +typedef struct +{ QString name; QString icon; QString unit; @@ -25,21 +27,21 @@ class SCOPY_GR_UTIL_EXPORT MeasurementController : public QObject public: MeasurementController(QPen pen, MeasureModel *msr, QObject *parent = nullptr); virtual ~MeasurementController(); - - MeasurementLabel* findMeasurementLabel(QString name); - StatsLabel* findStatsLabel(QString name); - virtual QWidget* enableMeasurement(QString name); + + MeasurementLabel *findMeasurementLabel(QString name); + StatsLabel *findStatsLabel(QString name); + virtual QWidget *enableMeasurement(QString name); virtual void disableMeasurement(QString name); - virtual QWidget* enableStats(QString name); + virtual QWidget *enableStats(QString name); virtual void disableStats(QString name); void addMeasurement(MeasurementInfo v); QList availableMeasurements() const; Q_SIGNALS: - void measurementEnabled(MeasurementLabel*); - void measurementDisabled(MeasurementLabel*); + void measurementEnabled(MeasurementLabel *); + void measurementDisabled(MeasurementLabel *); void statsEnabled(StatsLabel *); void statsDisabled(StatsLabel *); @@ -49,15 +51,15 @@ class SCOPY_GR_UTIL_EXPORT MeasurementController : public QObject private: QPen m_pen; - QList m_statsLabels; - QList m_measureLabels; - + QList m_statsLabels; + QList m_measureLabels; }; -class SCOPY_GR_UTIL_EXPORT TimeChannelMeasurementController : public MeasurementController { +class SCOPY_GR_UTIL_EXPORT TimeChannelMeasurementController : public MeasurementController +{ public: - TimeChannelMeasurementController(TimeMeasureModel* msr, QPen m_pen, QObject *parent = nullptr); + TimeChannelMeasurementController(TimeMeasureModel *msr, QPen m_pen, QObject *parent = nullptr); }; -} +} // namespace scopy::grutil #endif // MEASUREMENTCONTROLLER_H diff --git a/gr-util/include/gr-util/time_sink_f.h b/gr-util/include/gr-util/time_sink_f.h index 3edb93943b..029ae4b72d 100644 --- a/gr-util/include/gr-util/time_sink_f.h +++ b/gr-util/include/gr-util/time_sink_f.h @@ -46,13 +46,16 @@ #include #endif -#include #include "scopy-gr-util_export.h" + +#include + #include namespace scopy { -typedef struct { +typedef struct +{ QString str; int offset; } PlotTag_t; @@ -63,13 +66,12 @@ class SCOPY_GR_UTIL_EXPORT time_sink_f : virtual public gr::sync_block // scopy::time_sink_f::sptr typedef std::shared_ptr sptr; - static sptr make(int size, float sampleRate, const std::string &name, - int nconnections ); + static sptr make(int size, float sampleRate, const std::string &name, int nconnections); virtual std::string name() const = 0; virtual void updateData() = 0; virtual const std::vector &time() const = 0; - virtual const std::vector > &data() const = 0; - virtual const std::vector > &tags() const = 0; + virtual const std::vector> &data() const = 0; + virtual const std::vector> &tags() const = 0; virtual void setRollingMode(bool) = 0; virtual bool rollingMode() = 0; virtual void setSingleShot(bool) = 0; @@ -77,7 +79,6 @@ class SCOPY_GR_UTIL_EXPORT time_sink_f : virtual public gr::sync_block virtual bool finishedAcquisition() = 0; virtual bool computeTags() = 0; virtual void setComputeTags(bool newComputeTags) = 0; - }; } /* namespace scopy */ diff --git a/gr-util/include/gr-util/time_sink_f_impl.h b/gr-util/include/gr-util/time_sink_f_impl.h index 74294add2d..d248a854c7 100644 --- a/gr-util/include/gr-util/time_sink_f_impl.h +++ b/gr-util/include/gr-util/time_sink_f_impl.h @@ -22,6 +22,7 @@ #define TIME_SINK_F_IMPL_H #include "time_sink_f.h" + #include namespace scopy { @@ -53,21 +54,17 @@ class time_sink_f_impl : public time_sink_f bool start() override; bool stop() override; - int work(int noutput_items, - gr_vector_const_void_star &input_items, - gr_vector_void_star &output_items) override; - - + int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) override; private: - std::vector > m_buffers; - std::vector< std::vector > m_localtags; - std::vector< std::deque > m_tags; + std::vector> m_buffers; + std::vector> m_localtags; + std::vector> m_tags; std::vector m_time; std::vector> m_data; - std::vector< std::vector > m_dataTags; + std::vector> m_dataTags; int m_size; float m_sampleRate; diff --git a/gr-util/include/gr-util/tooladdon.h b/gr-util/include/gr-util/tooladdon.h index bc0b23f8f2..6a63ff861a 100644 --- a/gr-util/include/gr-util/tooladdon.h +++ b/gr-util/include/gr-util/tooladdon.h @@ -1,13 +1,15 @@ #ifndef TOOLADDON_H #define TOOLADDON_H #include "scopy-gr-util_export.h" + #include namespace scopy { -class SCOPY_GR_UTIL_EXPORT ToolAddon { +class SCOPY_GR_UTIL_EXPORT ToolAddon +{ public: virtual QString getName() = 0; - virtual QWidget* getWidget() = 0; + virtual QWidget *getWidget() = 0; virtual void enable() {} virtual void disable() {} @@ -15,11 +17,12 @@ class SCOPY_GR_UTIL_EXPORT ToolAddon { virtual void onStop() {} virtual void onInit() {} virtual void onDeinit() {} - virtual void onChannelAdded(ToolAddon* ) {} - virtual void onChannelRemoved(ToolAddon* ) {} + virtual void onChannelAdded(ToolAddon *) {} + virtual void onChannelRemoved(ToolAddon *) {} }; -class SCOPY_GR_UTIL_EXPORT GRTopAddon { +class SCOPY_GR_UTIL_EXPORT GRTopAddon +{ public: virtual void preFlowBuild() {} virtual void postFlowBuild() {} @@ -30,7 +33,7 @@ class SCOPY_GR_UTIL_EXPORT GRTopAddon { virtual void preFlowTeardown() {} virtual void postFlowTeardown() {} }; -} +} // namespace scopy #define ToolAddon_iid "org.adi.Scopy.Plugins.ToolAddon/0.1" #define GRTopAddon_iid "org.adi.Scopy.Plugins.GRTopAddon/0.1" diff --git a/gr-util/src/grdeviceaddon.cpp b/gr-util/src/grdeviceaddon.cpp index d2301384eb..efe7a942e8 100644 --- a/gr-util/src/grdeviceaddon.cpp +++ b/gr-util/src/grdeviceaddon.cpp @@ -1,10 +1,12 @@ #include "grdeviceaddon.h" -#include +#include using namespace scopy::grutil; -GRDeviceAddon::GRDeviceAddon(GRIIODeviceSource *src, QObject *parent) : QObject(parent){ +GRDeviceAddon::GRDeviceAddon(GRIIODeviceSource *src, QObject *parent) + : QObject(parent) +{ name = src->deviceName(); widget = new QLabel("devicename" + src->deviceName()); m_src = src; @@ -13,13 +15,11 @@ GRDeviceAddon::GRDeviceAddon(GRIIODeviceSource *src, QObject *parent) : QObject( GRDeviceAddon::~GRDeviceAddon() {} -QString GRDeviceAddon::getName() { return name;} +QString GRDeviceAddon::getName() { return name; } -QWidget *GRDeviceAddon::getWidget() { return widget;} +QWidget *GRDeviceAddon::getWidget() { return widget; } -GRIIODeviceSource *GRDeviceAddon::src() const { - return m_src; -} +GRIIODeviceSource *GRDeviceAddon::src() const { return m_src; } void GRDeviceAddon::enable() {} @@ -33,35 +33,18 @@ void GRDeviceAddon::onInit() {} void GRDeviceAddon::onDeinit() {} -void GRDeviceAddon::preFlowStart() { -} +void GRDeviceAddon::preFlowStart() {} -void GRDeviceAddon::postFlowStart() { - -} - -void GRDeviceAddon::preFlowBuild() -{ -} +void GRDeviceAddon::postFlowStart() {} +void GRDeviceAddon::preFlowBuild() {} void GRDeviceAddon::onChannelAdded(ToolAddon *) {} void GRDeviceAddon::onChannelRemoved(ToolAddon *) {} -void GRDeviceAddon::setBufferSize(uint32_t bufferSize) -{ - m_src->setBuffersize(bufferSize); -} - -void GRDeviceAddon::registerChannel(GRTimeChannelAddon* ch) { - m_channels.append(ch); -} - -QList GRDeviceAddon::getRegisteredChannels() { - return m_channels; -} - - +void GRDeviceAddon::setBufferSize(uint32_t bufferSize) { m_src->setBuffersize(bufferSize); } +void GRDeviceAddon::registerChannel(GRTimeChannelAddon *ch) { m_channels.append(ch); } +QList GRDeviceAddon::getRegisteredChannels() { return m_channels; } diff --git a/gr-util/src/griiocomplexchannelsrc.cpp b/gr-util/src/griiocomplexchannelsrc.cpp index 56737aff99..a8efea9982 100644 --- a/gr-util/src/griiocomplexchannelsrc.cpp +++ b/gr-util/src/griiocomplexchannelsrc.cpp @@ -1,25 +1,29 @@ #include "griiocomplexchannelsrc.h" + #include "griiodevicesource.h" +#include "grlog.h" #include "grtopblock.h" + #include -#include "grlog.h" using namespace scopy::grutil; -GRIIOComplexChannelSrc::GRIIOComplexChannelSrc(QString channelName, GRIIODeviceSource *dev, QString channelNameI, QString channelNameQ, QObject *parent) : - GRIIOChannel(channelName, dev, parent), channelNameI(channelNameI), channelNameQ(channelNameQ) -{ -} +GRIIOComplexChannelSrc::GRIIOComplexChannelSrc(QString channelName, GRIIODeviceSource *dev, QString channelNameI, + QString channelNameQ, QObject *parent) + : GRIIOChannel(channelName, dev, parent) + , channelNameI(channelNameI) + , channelNameQ(channelNameQ) +{} void GRIIOComplexChannelSrc::build_blks(GRTopBlock *top) { - qDebug(SCOPY_GR_UTIL)<<"Building GRIIOComplexChannelSrc"; + qDebug(SCOPY_GR_UTIL) << "Building GRIIOComplexChannelSrc"; dev->addChannel(this); s2f[0] = gr::blocks::short_to_float::make(); s2f[1] = gr::blocks::short_to_float::make(); f2c = gr::blocks::float_to_complex::make(); - top->connect(s2f[0],0,f2c,0); - top->connect(s2f[1],0,f2c,1); + top->connect(s2f[0], 0, f2c, 0); + top->connect(s2f[1], 0, f2c, 1); start_blk.append(s2f[0]); start_blk.append(s2f[1]); end_blk = f2c; @@ -34,12 +38,6 @@ void GRIIOComplexChannelSrc::destroy_blks(GRTopBlock *top) start_blk.clear(); } -const QString &GRIIOComplexChannelSrc::getChannelNameI() const -{ - return channelNameI; -} +const QString &GRIIOComplexChannelSrc::getChannelNameI() const { return channelNameI; } -const QString &GRIIOComplexChannelSrc::getChannelNameQ() const -{ - return channelNameQ; -} +const QString &GRIIOComplexChannelSrc::getChannelNameQ() const { return channelNameQ; } diff --git a/gr-util/src/griiodevicesource.cpp b/gr-util/src/griiodevicesource.cpp index f0c091dba9..a80119a120 100644 --- a/gr-util/src/griiodevicesource.cpp +++ b/gr-util/src/griiodevicesource.cpp @@ -1,15 +1,17 @@ #include "griiodevicesource.h" -#include "griiofloatchannelsrc.h" + #include "griiocomplexchannelsrc.h" -#include "grtopblock.h" +#include "griiofloatchannelsrc.h" #include "grlog.h" +#include "grtopblock.h" using namespace scopy::grutil; -QString GRIIODeviceSource::findAttribute(QStringList possibleNames, iio_device* dev) { +QString GRIIODeviceSource::findAttribute(QStringList possibleNames, iio_device *dev) +{ const char *attr = nullptr; for(QString name : possibleNames) { - attr = iio_device_find_attr(dev,name.toStdString().c_str()); + attr = iio_device_find_attr(dev, name.toStdString().c_str()); if(attr) break; } @@ -17,10 +19,7 @@ QString GRIIODeviceSource::findAttribute(QStringList possibleNames, iio_device* return attributeName; } -iio_device *GRIIODeviceSource::iioDev() const -{ - return m_iioDev; -} +iio_device *GRIIODeviceSource::iioDev() const { return m_iioDev; } QString GRIIOChannel::findAttribute(QStringList possibleNames, iio_channel *ch) { @@ -34,59 +33,64 @@ QString GRIIOChannel::findAttribute(QStringList possibleNames, iio_channel *ch) return attributeName; } -GRIIODeviceSource::GRIIODeviceSource(iio_context *ctx, QString deviceName, QString phyDeviceName, unsigned int buffersize, QObject *parent) : - GRProxyBlock(parent), m_ctx(ctx), m_deviceName(deviceName), m_phyDeviceName(phyDeviceName), m_buffersize(buffersize) +GRIIODeviceSource::GRIIODeviceSource(iio_context *ctx, QString deviceName, QString phyDeviceName, + unsigned int buffersize, QObject *parent) + : GRProxyBlock(parent) + , m_ctx(ctx) + , m_deviceName(deviceName) + , m_phyDeviceName(phyDeviceName) + , m_buffersize(buffersize) { - m_iioDev = iio_context_find_device(m_ctx,m_deviceName.toStdString().c_str()); - m_sampleRateAttribute = findAttribute( { - "sample_rate", - "sampling_rate", - "sample_frequency", - "sampling_frequency", - }, m_iioDev); - - + m_iioDev = iio_context_find_device(m_ctx, m_deviceName.toStdString().c_str()); + m_sampleRateAttribute = findAttribute( + { + "sample_rate", + "sampling_rate", + "sample_frequency", + "sampling_frequency", + }, + m_iioDev); } -void GRIIODeviceSource::addChannelAtIndex(iio_device* iio_dev, QString channelName) { +void GRIIODeviceSource::addChannelAtIndex(iio_device *iio_dev, QString channelName) +{ std::string channel_name = channelName.toStdString(); - iio_channel* iio_ch = iio_device_find_channel(iio_dev, channel_name.c_str(), false); + iio_channel *iio_ch = iio_device_find_channel(iio_dev, channel_name.c_str(), false); int idx = iio_channel_get_index(iio_ch); m_channelNames[idx] = channel_name; } -void GRIIODeviceSource::computeChannelNames() { +void GRIIODeviceSource::computeChannelNames() +{ int max_channels = iio_device_get_channels_count(m_iioDev); - for(int i = 0;i(ch); + for(GRIIOChannel *ch : qAsConst(m_list)) { + GRIIOFloatChannelSrc *floatCh = dynamic_cast(ch); if(floatCh) { addChannelAtIndex(m_iioDev, floatCh->getChannelName()); } - GRIIOComplexChannelSrc* complexCh = dynamic_cast(ch); + GRIIOComplexChannelSrc *complexCh = dynamic_cast(ch); if(complexCh) { addChannelAtIndex(m_iioDev, complexCh->getChannelNameI()); addChannelAtIndex(m_iioDev, complexCh->getChannelNameQ()); } } - m_channelNames.erase(std::remove_if( - m_channelNames.begin(), - m_channelNames.end(), - [=](std::string x){return x.empty();}), - m_channelNames.end()); // clear empty channels - + m_channelNames.erase( + std::remove_if(m_channelNames.begin(), m_channelNames.end(), [=](std::string x) { return x.empty(); }), + m_channelNames.end()); // clear empty channels } -int GRIIODeviceSource::getOutputIndex(QString ch) { - for(int i = 0;i < m_channelNames.size();i++) { +int GRIIODeviceSource::getOutputIndex(QString ch) +{ + for(int i = 0; i < m_channelNames.size(); i++) { if(ch.toStdString() == m_channelNames[i]) return i; } @@ -115,38 +119,40 @@ double GRIIODeviceSource::readSampleRate() return -1; } -void GRIIODeviceSource::matchChannelToBlockOutputs(GRTopBlock *top) { - for(GRIIOChannel* ch : qAsConst(m_list)) { - GRIIOFloatChannelSrc* floatCh = dynamic_cast(ch); +void GRIIODeviceSource::matchChannelToBlockOutputs(GRTopBlock *top) +{ + for(GRIIOChannel *ch : qAsConst(m_list)) { + GRIIOFloatChannelSrc *floatCh = dynamic_cast(ch); if(floatCh) { auto start_sptr = floatCh->getGrStartPoint(); - top->connect(src, getOutputIndex(floatCh->getChannelName()),start_sptr[0],0); + top->connect(src, getOutputIndex(floatCh->getChannelName()), start_sptr[0], 0); } - GRIIOComplexChannelSrc* complexCh = dynamic_cast(ch); + GRIIOComplexChannelSrc *complexCh = dynamic_cast(ch); if(complexCh) { auto start_sptr = complexCh->getGrStartPoint(); - top->connect(src, getOutputIndex(complexCh->getChannelNameI()),start_sptr[0],0); - top->connect(src, getOutputIndex(complexCh->getChannelNameQ()),start_sptr[1],0); + top->connect(src, getOutputIndex(complexCh->getChannelNameI()), start_sptr[0], 0); + top->connect(src, getOutputIndex(complexCh->getChannelNameQ()), start_sptr[1], 0); } } } void GRIIODeviceSource::build_blks(GRTopBlock *top) { - qDebug(SCOPY_GR_UTIL)<<"Building GRIIODeviceSource"; + qDebug(SCOPY_GR_UTIL) << "Building GRIIODeviceSource"; if(m_list.count() == 0) return; computeChannelNames(); // create block - src = gr::iio::device_source::make_from(m_ctx, m_deviceName.toStdString(), m_channelNames, m_phyDeviceName.toStdString(), gr::iio::iio_param_vec_t(), m_buffersize); + src = gr::iio::device_source::make_from(m_ctx, m_deviceName.toStdString(), m_channelNames, + m_phyDeviceName.toStdString(), gr::iio::iio_param_vec_t(), + m_buffersize); src->set_output_multiple(m_buffersize); src->set_len_tag_key("buffer_start"); // match channels with blocks end_blk = src; - } void GRIIODeviceSource::destroy_blks(GRTopBlock *top) @@ -157,30 +163,15 @@ void GRIIODeviceSource::destroy_blks(GRTopBlock *top) end_blk = nullptr; } -void GRIIODeviceSource::connect_blk(GRTopBlock *top, GRProxyBlock *) -{ - matchChannelToBlockOutputs(top); -} +void GRIIODeviceSource::connect_blk(GRTopBlock *top, GRProxyBlock *) { matchChannelToBlockOutputs(top); } -void GRIIODeviceSource::disconnect_blk(GRTopBlock *top) -{ - top->getGrBlock()->disconnect(src); -} +void GRIIODeviceSource::disconnect_blk(GRTopBlock *top) { top->getGrBlock()->disconnect(src); } -void GRIIODeviceSource::addChannel(GRIIOChannel *ch) -{ - m_list.append(ch); -} +void GRIIODeviceSource::addChannel(GRIIOChannel *ch) { m_list.append(ch); } -void GRIIODeviceSource::removeChannel(GRIIOChannel *ch) -{ - m_list.removeAll(ch); -} +void GRIIODeviceSource::removeChannel(GRIIOChannel *ch) { m_list.removeAll(ch); } -unsigned int GRIIODeviceSource::getBuffersize() const -{ - return m_buffersize; -} +unsigned int GRIIODeviceSource::getBuffersize() const { return m_buffersize; } void GRIIODeviceSource::setBuffersize(unsigned int newBuffersize) { @@ -188,14 +179,6 @@ void GRIIODeviceSource::setBuffersize(unsigned int newBuffersize) Q_EMIT requestRebuild(); } -std::vector GRIIODeviceSource::channelNames() const -{ - return m_channelNames; -} - -QString GRIIODeviceSource::deviceName() const -{ - return m_deviceName; -} - +std::vector GRIIODeviceSource::channelNames() const { return m_channelNames; } +QString GRIIODeviceSource::deviceName() const { return m_deviceName; } diff --git a/gr-util/src/griiofloatchannelsrc.cpp b/gr-util/src/griiofloatchannelsrc.cpp index 0e88350d27..6d3d18dc41 100644 --- a/gr-util/src/griiofloatchannelsrc.cpp +++ b/gr-util/src/griiofloatchannelsrc.cpp @@ -1,31 +1,31 @@ #include "griiofloatchannelsrc.h" -#include "grlog.h" -#include "gnuradio/blocks/int_to_float.h" -#include "gnuradio/blocks/short_to_float.h" -#include "gnuradio/blocks/copy.h" #include "gnuradio/blocks/char_to_float.h" - +#include "gnuradio/blocks/copy.h" +#include "gnuradio/blocks/int_to_float.h" +#include "gnuradio/blocks/short_to_float.h" +#include "grlog.h" using namespace scopy::grutil; -GRIIOFloatChannelSrc::GRIIOFloatChannelSrc(GRIIODeviceSource *dev, QString channelName, QObject *parent) : - GRIIOChannel(channelName, dev, parent) +GRIIOFloatChannelSrc::GRIIOFloatChannelSrc(GRIIODeviceSource *dev, QString channelName, QObject *parent) + : GRIIOChannel(channelName, dev, parent) { m_iioCh = iio_device_find_channel(dev->iioDev(), channelName.toStdString().c_str(), false); - fmt = iio_channel_get_data_format(m_iioCh); - - m_sampleRateAttribute = findAttribute( { - "sample_rate", - "sampling_rate", - "sample_frequency", - "sampling_frequency", - }, m_iioCh); + fmt = iio_channel_get_data_format(m_iioCh); + m_sampleRateAttribute = findAttribute( + { + "sample_rate", + "sampling_rate", + "sample_frequency", + "sampling_frequency", + }, + m_iioCh); } void GRIIOFloatChannelSrc::build_blks(GRTopBlock *top) { - qDebug(SCOPY_GR_UTIL)<<"Building GRIIOFloatChannelSrc"; + qDebug(SCOPY_GR_UTIL) << "Building GRIIOFloatChannelSrc"; dev->addChannel(this); switch(fmt->length) { case 16: @@ -34,9 +34,9 @@ void GRIIOFloatChannelSrc::build_blks(GRTopBlock *top) case 32: x2f = gr::blocks::int_to_float::make(); break; - default: - qInfo(SCOPY_GR_UTIL)<<"creating copy block of size " << fmt->length/8; - x2f = gr::blocks::copy::make(fmt->length/8); + default: + qInfo(SCOPY_GR_UTIL) << "creating copy block of size " << fmt->length / 8; + x2f = gr::blocks::copy::make(fmt->length / 8); break; } end_blk = x2f; @@ -76,7 +76,4 @@ double GRIIOFloatChannelSrc::readSampleRate() } } -const iio_data_format *GRIIOFloatChannelSrc::getFmt() const -{ - return fmt; -} +const iio_data_format *GRIIOFloatChannelSrc::getFmt() const { return fmt; } diff --git a/gr-util/src/grproxyblock.cpp b/gr-util/src/grproxyblock.cpp index 25e864d691..974132ac64 100644 --- a/gr-util/src/grproxyblock.cpp +++ b/gr-util/src/grproxyblock.cpp @@ -1,47 +1,48 @@ #include "grproxyblock.h" -#include "grtopblock.h" + #include "grlog.h" +#include "grtopblock.h" using namespace scopy::grutil; -GRProxyBlock::GRProxyBlock(QObject *parent) : QObject(parent), m_enabled(true) {} +GRProxyBlock::GRProxyBlock(QObject *parent) + : QObject(parent) + , m_enabled(true) +{} GRProxyBlock::~GRProxyBlock() {} -void GRProxyBlock::build_blks(GRTopBlock *top) -{ +void GRProxyBlock::build_blks(GRTopBlock *top) {} -} +void GRProxyBlock::destroy_blks(GRTopBlock *top) { start_blk.clear(); } -void GRProxyBlock::destroy_blks(GRTopBlock *top) +void GRProxyBlock::connect_blk(GRTopBlock *top, GRProxyBlock *src) { - start_blk.clear(); -} - -void GRProxyBlock::connect_blk(GRTopBlock *top, GRProxyBlock *src) { if(src == nullptr) // block is a source return; int nrOfOutputs = src->getGrEndPoint()->output_signature()->min_streams(); - for(int i = 0; i < nrOfOutputs;i++) { + for(int i = 0; i < nrOfOutputs; i++) { int j = 0; int input = i; - for(j=0;jinput_signature()->max_streams(); if(input < nrinputs) break; input -= nrinputs; } - top->connect(src->getGrEndPoint(),i,start_blk[j],input); + top->connect(src->getGrEndPoint(), i, start_blk[j], input); } } -void GRProxyBlock::disconnect_blk(GRTopBlock *top) { - for(int i=0;igetGrBlock()->disconnect(start_blk[i]); } -void GRProxyBlock::setEnabled(bool v) { +void GRProxyBlock::setEnabled(bool v) +{ if(m_enabled == v) return; @@ -53,13 +54,7 @@ void GRProxyBlock::setEnabled(bool v) { bool GRProxyBlock::enabled() { return m_enabled; } -bool GRProxyBlock::built() -{ - return (!start_blk.isEmpty()) || (end_blk != nullptr); -} +bool GRProxyBlock::built() { return (!start_blk.isEmpty()) || (end_blk != nullptr); } QList GRProxyBlock::getGrStartPoint() { return start_blk; } gr::basic_block_sptr GRProxyBlock::getGrEndPoint() { return end_blk; } - - - diff --git a/gr-util/src/grscaleoffsetproc.cpp b/gr-util/src/grscaleoffsetproc.cpp index ae459d3365..f1a5818015 100644 --- a/gr-util/src/grscaleoffsetproc.cpp +++ b/gr-util/src/grscaleoffsetproc.cpp @@ -1,35 +1,41 @@ #include "grscaleoffsetproc.h" -#include "grtopblock.h" + #include "grlog.h" +#include "grtopblock.h" using namespace scopy::grutil; -GRScaleOffsetProc::GRScaleOffsetProc(QObject *parent) : GRProxyBlock(parent) {} +GRScaleOffsetProc::GRScaleOffsetProc(QObject *parent) + : GRProxyBlock(parent) +{} -void GRScaleOffsetProc::setScale(double sc) { +void GRScaleOffsetProc::setScale(double sc) +{ m_scale = sc; if(mul) mul->set_k(m_scale); } -void GRScaleOffsetProc::setOffset(double off) { +void GRScaleOffsetProc::setOffset(double off) +{ m_offset = off; if(add) add->set_k(m_offset); } -void GRScaleOffsetProc::build_blks(GRTopBlock *top) { - qDebug(SCOPY_GR_UTIL)<<"Building GRScaleOffsetProc"; +void GRScaleOffsetProc::build_blks(GRTopBlock *top) +{ + qDebug(SCOPY_GR_UTIL) << "Building GRScaleOffsetProc"; mul = gr::blocks::multiply_const_ff::make(m_scale); add = gr::blocks::add_const_ff::make(m_offset); - top->connect(mul,0,add,0); + top->connect(mul, 0, add, 0); start_blk.append(mul); - end_blk = add; + end_blk = add; } -void GRScaleOffsetProc::destroy_blks(GRTopBlock *top) { +void GRScaleOffsetProc::destroy_blks(GRTopBlock *top) +{ end_blk = nullptr; mul = nullptr; add = nullptr; start_blk.clear(); } - diff --git a/gr-util/src/grsignalpath.cpp b/gr-util/src/grsignalpath.cpp index 3e20e4f7fb..5f11b73222 100644 --- a/gr-util/src/grsignalpath.cpp +++ b/gr-util/src/grsignalpath.cpp @@ -1,30 +1,28 @@ #include "grsignalpath.h" -#include "grtopblock.h" + #include "grlog.h" +#include "grtopblock.h" using namespace scopy::grutil; -GRSignalPath::GRSignalPath(QString name, QObject *parent) : GRProxyBlock(parent), m_name(name) {} +GRSignalPath::GRSignalPath(QString name, QObject *parent) + : GRProxyBlock(parent) + , m_name(name) +{} - -void GRSignalPath::append(GRProxyBlock *p) { +void GRSignalPath::append(GRProxyBlock *p) +{ list.append(p); - connect(p,SIGNAL(requestRebuild()),this,SIGNAL(requestRebuild())); -} - -void GRSignalPath::build_blks() { - - + connect(p, SIGNAL(requestRebuild()), this, SIGNAL(requestRebuild())); } -void GRSignalPath::destroy_blks() { +void GRSignalPath::build_blks() {} - -} +void GRSignalPath::destroy_blks() {} QList GRSignalPath::getGrStartPoint() { - for(int i = 0;ienabled()) { return blk->getGrStartPoint(); @@ -35,7 +33,7 @@ QList GRSignalPath::getGrStartPoint() gr::basic_block_sptr GRSignalPath::getGrEndPoint() { - for(int i = list.count() - 1; i >= 0;i--) { + for(int i = list.count() - 1; i >= 0; i--) { auto blk = list[i]; if(blk->enabled()) { return blk->getGrEndPoint(); @@ -44,23 +42,26 @@ gr::basic_block_sptr GRSignalPath::getGrEndPoint() return nullptr; } -void GRSignalPath::connect_blk(GRTopBlock *top, GRProxyBlock *src) { - qDebug(SCOPY_GR_UTIL)<<"Start connecting GRSignalPath"; - GRProxyBlock* prevBlk = src; - for(GRProxyBlock* blk : qAsConst(list)) { - if(blk->enabled() && !blk->built() - || (blk == list[0] && list.count() > 1)) // - an enabled signal path always needs a source enabled - unless it's the only one I guess */ ) +void GRSignalPath::connect_blk(GRTopBlock *top, GRProxyBlock *src) +{ + qDebug(SCOPY_GR_UTIL) << "Start connecting GRSignalPath"; + GRProxyBlock *prevBlk = src; + for(GRProxyBlock *blk : qAsConst(list)) { + if(blk->enabled() && !blk->built() || + (blk == list[0] && list.count() > 1)) // - an enabled signal path always needs a source enabled - + // unless it's the only one I guess */ ) { blk->build_blks(top); blk->connect_blk(top, prevBlk); prevBlk = blk; } } - qDebug(SCOPY_GR_UTIL)<<"End connecting GRSignalPath"; + qDebug(SCOPY_GR_UTIL) << "End connecting GRSignalPath"; } -void GRSignalPath::disconnect_blk(GRTopBlock *top) { - for(GRProxyBlock* blk : qAsConst(list)) { +void GRSignalPath::disconnect_blk(GRTopBlock *top) +{ + for(GRProxyBlock *blk : qAsConst(list)) { if(blk->built()) { blk->disconnect_blk(top); blk->destroy_blks(top); @@ -68,12 +69,6 @@ void GRSignalPath::disconnect_blk(GRTopBlock *top) { } } -QString GRSignalPath::name() const -{ - return m_name; -} +QString GRSignalPath::name() const { return m_name; } -QList GRSignalPath::path() -{ - return list; -} +QList GRSignalPath::path() { return list; } diff --git a/gr-util/src/grsignalsrc.cpp b/gr-util/src/grsignalsrc.cpp index 45bf8f3302..b58cbd4540 100644 --- a/gr-util/src/grsignalsrc.cpp +++ b/gr-util/src/grsignalsrc.cpp @@ -1,14 +1,14 @@ #include "grsignalsrc.h" + #include "grlog.h" using namespace scopy::grutil; -GRSignalSrc::GRSignalSrc(QObject *parent) : GRProxyBlock(parent) {} - -GRSignalSrc::~GRSignalSrc() -{ +GRSignalSrc::GRSignalSrc(QObject *parent) + : GRProxyBlock(parent) +{} -} +GRSignalSrc::~GRSignalSrc() {} void GRSignalSrc::setWaveform(gr::analog::gr_waveform_t waveform) { @@ -17,45 +17,51 @@ void GRSignalSrc::setWaveform(gr::analog::gr_waveform_t waveform) sig->set_waveform(waveform); } -void GRSignalSrc::setSamplingFreq(double sr) { +void GRSignalSrc::setSamplingFreq(double sr) +{ m_sampling_frequency = sr; if(sig) sig->set_sampling_freq(m_sampling_frequency); } -void GRSignalSrc::setFreq(double f) { +void GRSignalSrc::setFreq(double f) +{ m_freq = f; if(sig) sig->set_frequency(m_freq); } -void GRSignalSrc::setPhase(double ph) { +void GRSignalSrc::setPhase(double ph) +{ m_phase = ph; if(sig) sig->set_phase(m_phase); } -void GRSignalSrc::setAmplitude(double ampl) { +void GRSignalSrc::setAmplitude(double ampl) +{ m_amplitude = ampl; if(sig) sig->set_amplitude(m_amplitude); } -void GRSignalSrc::setOffset(double off) { +void GRSignalSrc::setOffset(double off) +{ m_offset = off; if(sig) sig->set_offset(m_offset); } -void GRSignalSrc::build_blks(GRTopBlock *top) { - qDebug(SCOPY_GR_UTIL)<<"Building GRSignalSrc"; - sig = gr::analog::sig_source_f::make(m_sampling_frequency, m_waveform, m_freq,m_amplitude,m_offset,m_phase); +void GRSignalSrc::build_blks(GRTopBlock *top) +{ + qDebug(SCOPY_GR_UTIL) << "Building GRSignalSrc"; + sig = gr::analog::sig_source_f::make(m_sampling_frequency, m_waveform, m_freq, m_amplitude, m_offset, m_phase); start_blk.append(sig); end_blk = sig; } -void GRSignalSrc::destroy_blks(GRTopBlock *top) { +void GRSignalSrc::destroy_blks(GRTopBlock *top) +{ end_blk = nullptr; sig = nullptr; start_blk.clear(); - } diff --git a/gr-util/src/grtimechanneladdon.cpp b/gr-util/src/grtimechanneladdon.cpp index f3469abe8a..9d096885cf 100644 --- a/gr-util/src/grtimechanneladdon.cpp +++ b/gr-util/src/grtimechanneladdon.cpp @@ -1,26 +1,33 @@ #include "grtimechanneladdon.h" + #include "grdeviceaddon.h" -#include + +#include #include +#include #include -#include -#include #include -#include -#include -#include -#include #include +#include +#include +#include #include -#include +#include +#include #include Q_LOGGING_CATEGORY(CAT_GR_TIME_CHANNEL, "GRTimeChannel"); using namespace scopy::grutil; -GRTimeChannelAddon::GRTimeChannelAddon(QString ch, GRDeviceAddon *dev, GRTimePlotAddon *plotAddon, QPen pen, QObject *parent) - : QObject(parent), m_channelName(ch), m_dev(dev), m_plotAddon(plotAddon), m_pen(pen) { +GRTimeChannelAddon::GRTimeChannelAddon(QString ch, GRDeviceAddon *dev, GRTimePlotAddon *plotAddon, QPen pen, + QObject *parent) + : QObject(parent) + , m_channelName(ch) + , m_dev(dev) + , m_plotAddon(plotAddon) + , m_pen(pen) +{ int yPlotAxisPosition = Preferences::get("adc_plot_yaxis_label_position").toInt(); int yPlotAxisHandle = Preferences::get("adc_plot_yaxis_handle_position").toInt(); @@ -29,7 +36,7 @@ GRTimeChannelAddon::GRTimeChannelAddon(QString ch, GRDeviceAddon *dev, GRTimePlo m_enabled = false; m_autoscaleEnabled = false; m_signalPath = new GRSignalPath("time_" + dev->getName() + ch, this); - m_grch = new GRIIOFloatChannelSrc(dev->src(),ch,m_signalPath); + m_grch = new GRIIOFloatChannelSrc(dev->src(), ch, m_signalPath); m_signalPath->append(m_grch); m_scOff = new GRScaleOffsetProc(m_signalPath); m_signalPath->append(m_scOff); @@ -38,16 +45,17 @@ GRTimeChannelAddon::GRTimeChannelAddon(QString ch, GRDeviceAddon *dev, GRTimePlo m_signalPath->setEnabled(false); m_scaleAvailable = true; // query from GRIIOFloatChannel; - m_unit = "Volts"; // query from GRIIOFloatChannel; + m_unit = "Volts"; // query from GRIIOFloatChannel; setDevice(dev); name = m_grch->getChannelName(); - auto plot = plotAddon->plot();; + auto plot = plotAddon->plot(); + ; m_plotAxis = new PlotAxis(yPlotAxisPosition, plot, pen, this); - m_plotCh = new PlotChannel(name, pen, plot, plot->xAxis(), m_plotAxis,this); - m_plotAxisHandle = new PlotAxisHandle(pen, m_plotAxis, plot, yPlotAxisHandle,this); + m_plotCh = new PlotChannel(name, pen, plot, plot->xAxis(), m_plotAxis, this); + m_plotAxisHandle = new PlotAxisHandle(pen, m_plotAxis, plot, yPlotAxisHandle, this); m_plotCh->setHandle(m_plotAxisHandle); plot->addPlotAxisHandle(m_plotAxisHandle); plot->addPlotChannel(m_plotCh); @@ -55,14 +63,14 @@ GRTimeChannelAddon::GRTimeChannelAddon(QString ch, GRDeviceAddon *dev, GRTimePlo initMeasure(); widget = createMenu(); m_sampleRateAvailable = m_grch->sampleRateAvailable(); - } GRTimeChannelAddon::~GRTimeChannelAddon() {} -QWidget* GRTimeChannelAddon::createYAxisMenu(QWidget* parent) { +QWidget *GRTimeChannelAddon::createYAxisMenu(QWidget *parent) +{ MenuSectionWidget *yaxiscontainer = new MenuSectionWidget(parent); - MenuCollapseSection *yaxis = new MenuCollapseSection("Y-AXIS",MenuCollapseSection::MHCW_NONE, yaxiscontainer); + MenuCollapseSection *yaxis = new MenuCollapseSection("Y-AXIS", MenuCollapseSection::MHCW_NONE, yaxiscontainer); // Y-MODE m_ymodeCb = new MenuCombo("YMODE", yaxis); @@ -83,20 +91,21 @@ QWidget* GRTimeChannelAddon::createYAxisMenu(QWidget* parent) { m_ymin = new PositionSpinButton( { - {"V",1e0}, - {"k",1e3}, - {"M",1e6}, - {"G",1e9}, - },"YMin",(double)((long)(-1<<31)),(double)((long)1<<31),false,false,yMinMax); - + {"V", 1e0}, + {"k", 1e3}, + {"M", 1e6}, + {"G", 1e9}, + }, + "YMin", (double)((long)(-1 << 31)), (double)((long)1 << 31), false, false, yMinMax); m_ymax = new PositionSpinButton( - { - {"V",1e0}, - {"k",1e3}, - {"M",1e6}, - {"G",1e9}, - },"YMax",(double)((long)(-1<<31)),(double)((long)1<<31),false,false,yMinMax); + { + {"V", 1e0}, + {"k", 1e3}, + {"M", 1e6}, + {"G", 1e9}, + }, + "YMax", (double)((long)(-1 << 31)), (double)((long)1 << 31), false, false, yMinMax); yMinMaxLayout->addWidget(m_ymin); yMinMaxLayout->addWidget(m_ymax); @@ -115,38 +124,37 @@ QWidget* GRTimeChannelAddon::createYAxisMenu(QWidget* parent) { // Connects connect(m_ymin, &PositionSpinButton::valueChanged, m_plotAxis, &PlotAxis::setMin); - connect(m_plotAxis, &PlotAxis::minChanged, this, [=](){ + connect(m_plotAxis, &PlotAxis::minChanged, this, [=]() { QSignalBlocker b(m_ymin); m_ymin->setValue(m_plotAxis->min()); }); connect(m_ymax, &PositionSpinButton::valueChanged, m_plotAxis, &PlotAxis::setMax); - connect(m_plotAxis, &PlotAxis::maxChanged, this, [=](){ + connect(m_plotAxis, &PlotAxis::maxChanged, this, [=]() { QSignalBlocker b(m_ymax); m_ymax->setValue(m_plotAxis->max()); }); - connect(autoscale->onOffswitch(), &QAbstractButton::toggled, this, [=](bool b){ + connect(autoscale->onOffswitch(), &QAbstractButton::toggled, this, [=](bool b) { m_ymin->setEnabled(!b); m_ymax->setEnabled(!b); m_autoscaleEnabled = b; toggleAutoScale(); - - } ); + }); connect(cb, qOverload(&QComboBox::currentIndexChanged), this, [=](int idx) { auto mode = cb->itemData(idx).toInt(); setYMode(static_cast(mode)); }); - return yaxiscontainer; } -QWidget* GRTimeChannelAddon::createCurveMenu(QWidget* parent) { +QWidget *GRTimeChannelAddon::createCurveMenu(QWidget *parent) +{ MenuSectionWidget *curvecontainer = new MenuSectionWidget(parent); - MenuCollapseSection *curve = new MenuCollapseSection("CURVE",MenuCollapseSection::MHCW_NONE, curvecontainer); + MenuCollapseSection *curve = new MenuCollapseSection("CURVE", MenuCollapseSection::MHCW_NONE, curvecontainer); QWidget *curveSettings = new QWidget(curve); QHBoxLayout *curveSettingsLay = new QHBoxLayout(curveSettings); @@ -162,9 +170,8 @@ QWidget* GRTimeChannelAddon::createCurveMenu(QWidget* parent) { cbThickness->addItem("4"); cbThickness->addItem("5"); - connect(cbThickness, qOverload(&QComboBox::currentIndexChanged), this, [=](int idx) { - m_plotCh->setThickness(cbThickness->itemText(idx).toFloat()); - }); + connect(cbThickness, qOverload(&QComboBox::currentIndexChanged), this, + [=](int idx) { m_plotCh->setThickness(cbThickness->itemText(idx).toFloat()); }); MenuCombo *cbStyleW = new MenuCombo("Style", curve); auto cbStyle = cbStyleW->combo(); cbStyle->addItem("Lines", PlotChannel::PCS_LINES); @@ -172,11 +179,10 @@ QWidget* GRTimeChannelAddon::createCurveMenu(QWidget* parent) { cbStyle->addItem("Steps", PlotChannel::PCS_STEPS); cbStyle->addItem("Sticks", PlotChannel::PCS_STICKS); cbStyle->addItem("Smooth", PlotChannel::PCS_SMOOTH); - StyleHelper::MenuComboBox(cbStyle,"cbStyle"); + StyleHelper::MenuComboBox(cbStyle, "cbStyle"); - connect(cbStyle, qOverload(&QComboBox::currentIndexChanged), this, [=](int idx) { - m_plotCh->setStyle(cbStyle->itemData(idx).toInt()); - }); + connect(cbStyle, qOverload(&QComboBox::currentIndexChanged), this, + [=](int idx) { m_plotCh->setStyle(cbStyle->itemData(idx).toInt()); }); curveSettingsLay->addWidget(cbThicknessW); curveSettingsLay->addWidget(cbStyleW); @@ -186,23 +192,28 @@ QWidget* GRTimeChannelAddon::createCurveMenu(QWidget* parent) { return curvecontainer; } -void GRTimeChannelAddon::initMeasure() { - m_measureModel = new TimeMeasureModel(nullptr,0,this); +void GRTimeChannelAddon::initMeasure() +{ + m_measureModel = new TimeMeasureModel(nullptr, 0, this); m_measureController = new TimeChannelMeasurementController(m_measureModel, m_pen, this); m_measureModel->setAdcBitCount(grch()->getFmt()->bits); - connect(m_measureController, &TimeChannelMeasurementController::measurementEnabled, this, &GRTimeChannelAddon::enableMeasurement); - connect(m_measureController, &TimeChannelMeasurementController::measurementDisabled, this, &GRTimeChannelAddon::disableMeasurement); - connect(m_measureController, &TimeChannelMeasurementController::statsEnabled, this, &GRTimeChannelAddon::enableStat); - connect(m_measureController, &TimeChannelMeasurementController::statsDisabled, this, &GRTimeChannelAddon::disableStat); - + connect(m_measureController, &TimeChannelMeasurementController::measurementEnabled, this, + &GRTimeChannelAddon::enableMeasurement); + connect(m_measureController, &TimeChannelMeasurementController::measurementDisabled, this, + &GRTimeChannelAddon::disableMeasurement); + connect(m_measureController, &TimeChannelMeasurementController::statsEnabled, this, + &GRTimeChannelAddon::enableStat); + connect(m_measureController, &TimeChannelMeasurementController::statsDisabled, this, + &GRTimeChannelAddon::disableStat); } -QWidget* GRTimeChannelAddon::createMeasurementMenuSection(QString category, QWidget* parent) { - +QWidget *GRTimeChannelAddon::createMeasurementMenuSection(QString category, QWidget *parent) +{ MenuSectionWidget *measureContainer = new MenuSectionWidget(parent); - MenuCollapseSection *measureSection = new MenuCollapseSection("MEASUREMENT " + category,MenuCollapseSection::MHCW_ARROW, measureContainer); + MenuCollapseSection *measureSection = + new MenuCollapseSection("MEASUREMENT " + category, MenuCollapseSection::MHCW_ARROW, measureContainer); QScrollArea *measureScroll = new QScrollArea(measureSection); MeasurementSelector *measureSelector = new MeasurementSelector(); measureContainer->contentLayout()->addWidget(measureSection); @@ -215,30 +226,34 @@ QWidget* GRTimeChannelAddon::createMeasurementMenuSection(QString category, QWid for(auto &meas : m_measureController->availableMeasurements()) { if(meas.type.toUpper() == category.toUpper()) { measureSelector->addMeasurement(meas.name, meas.icon); - connect(measureSelector->measurement(meas.name)->measureCheckbox(), &QCheckBox::toggled, [=](bool b){ - if(b) - m_measureController->enableMeasurement(meas.name); - else - m_measureController->disableMeasurement(meas.name); - }); - - connect(measureSelector->measurement(meas.name)->statsCheckbox(), &QCheckBox::toggled, [=](bool b){ - if(b) - m_measureController->enableStats(meas.name); - else - m_measureController->disableStats(meas.name); - }); + connect(measureSelector->measurement(meas.name)->measureCheckbox(), &QCheckBox::toggled, + [=](bool b) { + if(b) + m_measureController->enableMeasurement(meas.name); + else + m_measureController->disableMeasurement(meas.name); + }); + + connect(measureSelector->measurement(meas.name)->statsCheckbox(), &QCheckBox::toggled, + [=](bool b) { + if(b) + m_measureController->enableStats(meas.name); + else + m_measureController->disableStats(meas.name); + }); } } measureSection->header()->setChecked(false); - connect(this, &GRTimeChannelAddon::toggleAllMeasurement, measureSelector, &MeasurementSelector::toggleAllMeasurement); + connect(this, &GRTimeChannelAddon::toggleAllMeasurement, measureSelector, + &MeasurementSelector::toggleAllMeasurement); connect(this, &GRTimeChannelAddon::toggleAllStats, measureSelector, &MeasurementSelector::toggleAllStats); return measureContainer; } -QWidget* GRTimeChannelAddon::createMenu(QWidget* parent) { +QWidget *GRTimeChannelAddon::createMenu(QWidget *parent) +{ QWidget *w = new QWidget(parent); QVBoxLayout *lay = new QVBoxLayout(w); @@ -252,7 +267,7 @@ QWidget* GRTimeChannelAddon::createMenu(QWidget* parent) { scroll->setWidgetResizable(true); scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - //if ScrollBarAlwaysOn - layScroll->setContentsMargins(0,0,6,0); + // if ScrollBarAlwaysOn - layScroll->setContentsMargins(0,0,6,0); scroll->setWidget(wScroll); @@ -261,8 +276,8 @@ QWidget* GRTimeChannelAddon::createMenu(QWidget* parent) { w->setLayout(lay); MenuHeaderWidget *header = new MenuHeaderWidget(m_channelName, m_pen, w); - QWidget* yaxismenu = createYAxisMenu(w); - QWidget* curvemenu = createCurveMenu(w); + QWidget *yaxismenu = createYAxisMenu(w); + QWidget *curvemenu = createCurveMenu(w); QWidget *hMeasure = createMeasurementMenuSection("HORIZONTAL", parent); QWidget *vMeasure = createMeasurementMenuSection("VERTICAL", parent); @@ -274,51 +289,57 @@ QWidget* GRTimeChannelAddon::createMenu(QWidget* parent) { layScroll->addWidget(hMeasure); layScroll->addWidget(vMeasure); - layScroll->addSpacerItem(new QSpacerItem(0,0,QSizePolicy::Minimum,QSizePolicy::Expanding)); - + layScroll->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); return w; } -QString GRTimeChannelAddon::getName() {return name;} +QString GRTimeChannelAddon::getName() { return name; } -QWidget *GRTimeChannelAddon::getWidget() {return widget;} +QWidget *GRTimeChannelAddon::getWidget() { return widget; } -void GRTimeChannelAddon::setDevice(GRDeviceAddon *d) { m_dev = d; d->registerChannel(this);} +void GRTimeChannelAddon::setDevice(GRDeviceAddon *d) +{ + m_dev = d; + d->registerChannel(this); +} -GRDeviceAddon* GRTimeChannelAddon::getDevice() { return m_dev;} +GRDeviceAddon *GRTimeChannelAddon::getDevice() { return m_dev; } -void GRTimeChannelAddon::enable() { - qInfo(CAT_GR_TIME_CHANNEL)<enable(); m_plotAxisHandle->handle()->setVisible(true); m_plotAxisHandle->handle()->raise(); m_signalPath->setEnabled(true); -// m_grch->setEnabled(true); + // m_grch->setEnabled(true); m_plotAddon->replot(); -// m_plotAddon->plot()->replot(); + // m_plotAddon->plot()->replot(); } - -void GRTimeChannelAddon::disable() { - qInfo(CAT_GR_TIME_CHANNEL())<disable(); m_plotAxisHandle->handle()->setVisible(false); m_signalPath->setEnabled(false); -// m_grch->setEnabled(false); + // m_grch->setEnabled(false); m_plotAddon->replot(); -// m_plotAddon->plot()->replot(); + // m_plotAddon->plot()->replot(); } -void GRTimeChannelAddon::onStart() { +void GRTimeChannelAddon::onStart() +{ m_running = true; m_measureModel->setSampleRate(m_plotAddon->sampleRate()); toggleAutoScale(); } -void GRTimeChannelAddon::onStop() { +void GRTimeChannelAddon::onStop() +{ m_running = false; toggleAutoScale(); if(m_autoscaleEnabled) { @@ -326,7 +347,8 @@ void GRTimeChannelAddon::onStop() { } } -void GRTimeChannelAddon::toggleAutoScale() { +void GRTimeChannelAddon::toggleAutoScale() +{ if(m_running && m_autoscaleEnabled) { m_autoScaleTimer->start(); } else { @@ -334,18 +356,21 @@ void GRTimeChannelAddon::toggleAutoScale() { } } -void GRTimeChannelAddon::autoscale() { +void GRTimeChannelAddon::autoscale() +{ double max = -1000000.0; double min = 1000000.0; - auto data = m_plotCh->curve()->data(); + auto data = m_plotCh->curve()->data(); for(int i = 0; i < data->size(); i++) { auto sample = data->sample(i).y(); - if(max < sample) max = sample; - if(min > sample) min = sample; + if(max < sample) + max = sample; + if(min > sample) + min = sample; } - qInfo(CAT_GR_TIME_CHANNEL)<<"Autoscaling channel " << m_channelName << "to (" <setMin(min); m_plotAxis->setMax(max); @@ -357,21 +382,21 @@ void GRTimeChannelAddon::setYMode(YMode mode) double offset = 0; double ymin = -1; double ymax = 1; - const iio_data_format* fmt = m_grch->getFmt(); + const iio_data_format *fmt = m_grch->getFmt(); switch(mode) { case YMODE_COUNT: scale = 1; if(fmt->is_signed) { - ymin = - 1<<(fmt->bits-1); - ymax = 1<<(fmt->bits-1); + ymin = -1 << (fmt->bits - 1); + ymax = 1 << (fmt->bits - 1); } else { - ymin = 0; - ymax = 1<<(fmt->bits); + ymin = 0; + ymax = 1 << (fmt->bits); } break; case YMODE_FS: - scale = 1.0/((1<bits)); + scale = 1.0 / ((1 << fmt->bits)); if(fmt->is_signed) { ymin = -0.5; ymax = 0.5; @@ -384,27 +409,19 @@ void GRTimeChannelAddon::setYMode(YMode mode) break; default: break; - } m_ymin->setValue(ymin); m_ymax->setValue(ymax); m_scOff->setScale(scale); m_scOff->setOffset(offset); - } -GRIIOFloatChannelSrc *GRTimeChannelAddon::grch() const -{ - return m_grch; -} - -bool GRTimeChannelAddon::sampleRateAvailable() const -{ - return m_sampleRateAvailable; -} +GRIIOFloatChannelSrc *GRTimeChannelAddon::grch() const { return m_grch; } +bool GRTimeChannelAddon::sampleRateAvailable() const { return m_sampleRateAvailable; } -void GRTimeChannelAddon::onInit() { +void GRTimeChannelAddon::onInit() +{ // Defaults m_ymin->setValue(-1.0); m_ymax->setValue(1.0); @@ -416,10 +433,10 @@ void GRTimeChannelAddon::onDeinit() {} void GRTimeChannelAddon::preFlowBuild() { double m_sampleRate = m_grch->readSampleRate(); - qInfo()<<"READ SAMPLE RATE" << m_sampleRate; + qInfo() << "READ SAMPLE RATE" << m_sampleRate; } -void GRTimeChannelAddon::onNewData(const float* xData, const float* yData, int size) +void GRTimeChannelAddon::onNewData(const float *xData, const float *yData, int size) { m_measureModel->setDataSource(yData, size); m_measureModel->measure(); @@ -429,21 +446,10 @@ void GRTimeChannelAddon::onChannelAdded(ToolAddon *) {} void GRTimeChannelAddon::onChannelRemoved(ToolAddon *) {} -PlotChannel *GRTimeChannelAddon::plotCh() const -{ - return m_plotCh; -} +PlotChannel *GRTimeChannelAddon::plotCh() const { return m_plotCh; } -GRSignalPath *GRTimeChannelAddon::signalPath() const -{ - return m_signalPath; -} +GRSignalPath *GRTimeChannelAddon::signalPath() const { return m_signalPath; } -QPen GRTimeChannelAddon::pen() const { - return m_pen; -} +QPen GRTimeChannelAddon::pen() const { return m_pen; } -bool GRTimeChannelAddon::enabled() const -{ - return m_enabled; -} +bool GRTimeChannelAddon::enabled() const { return m_enabled; } diff --git a/gr-util/src/grtimeplotaddon.cpp b/gr-util/src/grtimeplotaddon.cpp index 8db8364c04..a707a9d65a 100644 --- a/gr-util/src/grtimeplotaddon.cpp +++ b/gr-util/src/grtimeplotaddon.cpp @@ -1,19 +1,21 @@ #include "grtimeplotaddon.h" + #include "grtimeplotaddonsettings.h" #include "hoverwidget.h" + +#include +#include +#include + +#include +#include #include #include -#include #include -#include -#include -#include #include -#include -#include -#include -#include +#include #include +#include Q_LOGGING_CATEGORY(CAT_GRTIMEPLOT, "GRTimePlotAddon"); @@ -22,15 +24,15 @@ Q_LOGGING_CATEGORY(CAT_GRTIMEPLOT, "GRTimePlotAddon"); using namespace scopy; using namespace scopy::grutil; GRTimePlotAddon::GRTimePlotAddon(QString name, GRTopBlock *top, QObject *parent) - : QObject(parent), - m_top(top), - time_sink(nullptr), - m_rollingMode(false), - m_started(false), - m_singleShot(false), - m_showPlotTags(false), - m_refreshTimerRunning(false), - m_xmode(GRTimePlotAddonSettings::XMODE_SAMPLES) + : QObject(parent) + , m_top(top) + , time_sink(nullptr) + , m_rollingMode(false) + , m_started(false) + , m_singleShot(false) + , m_showPlotTags(false) + , m_refreshTimerRunning(false) + , m_xmode(GRTimePlotAddonSettings::XMODE_SAMPLES) { Preferences *p = Preferences::GetInstance(); @@ -42,12 +44,12 @@ GRTimePlotAddon::GRTimePlotAddon(QString name, GRTopBlock *top, QObject *parent) m_plotWidget = new PlotWidget(widget); widget->setLayout(m_lay); - m_plotWidget->xAxis()->setInterval(0,1); + m_plotWidget->xAxis()->setInterval(0, 1); m_plotWidget->leftHandlesArea()->setVisible(true); m_plotWidget->rightHandlesArea()->setVisible(true); m_plotWidget->bottomHandlesArea()->setVisible(true); m_plotWidget->xAxis()->setVisible(true); -// m_plotWidget->topHandlesArea()->setVisible(true); + // m_plotWidget->topHandlesArea()->setVisible(true); m_info = new TimePlotInfo(m_plotWidget, widget); m_plotWidget->addPlotInfoSlot(m_info); @@ -56,43 +58,46 @@ GRTimePlotAddon::GRTimePlotAddon(QString name, GRTopBlock *top, QObject *parent) m_plotTimer = new QTimer(this); m_plotTimer->setSingleShot(true); connect(m_plotTimer, &QTimer::timeout, this, &GRTimePlotAddon::replot); - connect(p, SIGNAL(preferenceChanged(QString,QVariant)), this, SLOT(handlePreferences(QString,QVariant))); + connect(p, SIGNAL(preferenceChanged(QString, QVariant)), this, SLOT(handlePreferences(QString, QVariant))); fw = new QFutureWatcher(this); - futureWatcherConn = connect(fw, &QFutureWatcher::finished, this, [=](){ + futureWatcherConn = connect( + fw, &QFutureWatcher::finished, this, + [=]() { drawPlot(); if(m_refreshTimerRunning) m_plotTimer->start(); - }, Qt::QueuedConnection); + }, + Qt::QueuedConnection); } -GRTimePlotAddon::~GRTimePlotAddon() { -} +GRTimePlotAddon::~GRTimePlotAddon() {} QString GRTimePlotAddon::getName() { return name; } QWidget *GRTimePlotAddon::getWidget() { return widget; } -PlotWidget *GRTimePlotAddon::plot() { return m_plotWidget;} +PlotWidget *GRTimePlotAddon::plot() { return m_plotWidget; } void GRTimePlotAddon::enable() {} void GRTimePlotAddon::disable() {} -void GRTimePlotAddon::stopPlotRefresh() { - qInfo(CAT_GRTIMEPLOT)<<"Stopped plotting"; +void GRTimePlotAddon::stopPlotRefresh() +{ + qInfo(CAT_GRTIMEPLOT) << "Stopped plotting"; m_refreshTimerRunning = false; #ifdef GUI_THREAD_SAMPLING #else refillFuture.cancel(); // disconnect(futureWatcherConn); -#endif +#endif m_plotTimer->stop(); } - -void GRTimePlotAddon::startPlotRefresh() { - qInfo(CAT_GRTIMEPLOT)<<"Start plotting"; +void GRTimePlotAddon::startPlotRefresh() +{ + qInfo(CAT_GRTIMEPLOT) << "Start plotting"; updateFrameRate(); m_refreshTimerRunning = true; @@ -104,34 +109,36 @@ void GRTimePlotAddon::startPlotRefresh() { m_plotTimer->start(); } -void GRTimePlotAddon::drawTags() { +void GRTimePlotAddon::drawTags() +{ - for(GRTimeChannelAddon* gr : qAsConst(grChannels)) { + for(GRTimeChannelAddon *gr : qAsConst(grChannels)) { gr->plotCh()->clearMarkers(); } if(!m_showPlotTags) return; - for(GRTimeChannelAddon* gr : qAsConst(grChannels)) { - if(gr->signalPath()->enabled()) { + for(GRTimeChannelAddon *gr : qAsConst(grChannels)) { + if(gr->signalPath()->enabled()) { - int index = time_channel_map.value(gr->signalPath()->name(),-1); + int index = time_channel_map.value(gr->signalPath()->name(), -1); if(index == -1) continue; - for(int j = 0; j < time_sink->tags()[index].size();j++) { + for(int j = 0; j < time_sink->tags()[index].size(); j++) { PlotTag_t tag = time_sink->tags()[index][j]; - auto *m = gr->plotCh()->buildMarker(tag.str, QwtSymbol::Diamond, tag.offset, time_sink->data()[index][tag.offset]); + auto *m = gr->plotCh()->buildMarker(tag.str, QwtSymbol::Diamond, tag.offset, + time_sink->data()[index][tag.offset]); gr->plotCh()->addMarker(m); } - } } } -void GRTimePlotAddon::drawPlot() { -// qInfo(CAT_GRTIMEPLOT)<<"Draw plot"; +void GRTimePlotAddon::drawPlot() +{ + // qInfo(CAT_GRTIMEPLOT)<<"Draw plot"; if(!time_sink) return; setRawSamplesPtr(); @@ -141,151 +148,147 @@ void GRTimePlotAddon::drawPlot() { Q_EMIT requestStop(); } -void GRTimePlotAddon::onStart() { +void GRTimePlotAddon::onStart() +{ if(!m_started) { QElapsedTimer tim; tim.start(); connect(this, &GRTimePlotAddon::requestRebuild, m_top, &GRTopBlock::rebuild, Qt::QueuedConnection); - connect(m_top,SIGNAL(builtSignalPaths()), this, SLOT(connectSignalPaths())); - connect(m_top,SIGNAL(teardownSignalPaths()), this, SLOT(tearDownSignalPaths())); + connect(m_top, SIGNAL(builtSignalPaths()), this, SLOT(connectSignalPaths())); + connect(m_top, SIGNAL(teardownSignalPaths()), this, SLOT(tearDownSignalPaths())); m_top->build(); m_top->start(); m_started = true; } - } - void GRTimePlotAddon::onStop() { - if(m_started) { +void GRTimePlotAddon::onStop() +{ + if(m_started) { drawPlot(); m_top->stop(); m_top->teardown(); disconnect(this, &GRTimePlotAddon::requestRebuild, m_top, &GRTopBlock::rebuild); - disconnect(m_top,SIGNAL(builtSignalPaths()), this, SLOT(connectSignalPaths())); - disconnect(m_top,SIGNAL(teardownSignalPaths()), this, SLOT(tearDownSignalPaths())); + disconnect(m_top, SIGNAL(builtSignalPaths()), this, SLOT(connectSignalPaths())); + disconnect(m_top, SIGNAL(teardownSignalPaths()), this, SLOT(tearDownSignalPaths())); m_started = false; } } - void GRTimePlotAddon::setRawSamplesPtr() { - for(GRTimeChannelAddon* gr : qAsConst(grChannels)) { - if(gr->signalPath()->enabled()) { +void GRTimePlotAddon::setRawSamplesPtr() +{ + for(GRTimeChannelAddon *gr : qAsConst(grChannels)) { + if(gr->signalPath()->enabled()) { - int index = time_channel_map.value(gr->signalPath()->name(),-1); + int index = time_channel_map.value(gr->signalPath()->name(), -1); if(index != -1) { - gr->plotCh()->curve()->setRawSamples( - time_sink->time().data(), - time_sink->data()[index].data(), - time_sink->data()[index].size()); + gr->plotCh()->curve()->setRawSamples(time_sink->time().data(), + time_sink->data()[index].data(), + time_sink->data()[index].size()); - gr->onNewData(time_sink->time().data(), - time_sink->data()[index].data(), - time_sink->data()[index].size()); + gr->onNewData(time_sink->time().data(), time_sink->data()[index].data(), + time_sink->data()[index].size()); } else { -// gr->plotCh()->curve()->setRawSamples( -// {}); // assign no data curve + // gr->plotCh()->curve()->setRawSamples( + // {}); // assign no data curve } - } - } - } + } + } +} - void GRTimePlotAddon::replot() { - if(!time_sink) - return; +void GRTimePlotAddon::replot() +{ + if(!time_sink) + return; #ifdef GUI_THREAD_SAMPLING - time_sink->updateData(); - drawPlot(); - if(m_refreshTimerRunning) + time_sink->updateData(); + drawPlot(); + if(m_refreshTimerRunning) m_plotTimer->start(); -#else - refillFuture = QtConcurrent::run([=]() { -// qInfo(CAT_GRTIMEPLOT)<<"UpdateData"; +#else + refillFuture = QtConcurrent::run([=]() { + // qInfo(CAT_GRTIMEPLOT)<<"UpdateData"; std::unique_lock lock(refillMutex); - time_sink->updateData(); - }); - fw->setFuture(refillFuture); + time_sink->updateData(); + }); + fw->setFuture(refillFuture); #endif - } - - void GRTimePlotAddon::updateBufferPreviewer() { - m_info->updateBufferPreviewer(); - } - - void GRTimePlotAddon::onInit() { - qDebug(CAT_GRTIMEPLOT)<<"Init"; - m_currentSamplingInfo.sampleRate = 1; - m_currentSamplingInfo.bufferSize = 32; - m_currentSamplingInfo.plotSize = 32; - updateBufferPreviewer(); -// m_top->build(); - } +} - void GRTimePlotAddon::onDeinit() { - qDebug(CAT_GRTIMEPLOT)<<"Deinit"; - onStop(); - } +void GRTimePlotAddon::updateBufferPreviewer() { m_info->updateBufferPreviewer(); } - void GRTimePlotAddon::preFlowStart() { +void GRTimePlotAddon::onInit() +{ + qDebug(CAT_GRTIMEPLOT) << "Init"; + m_currentSamplingInfo.sampleRate = 1; + m_currentSamplingInfo.bufferSize = 32; + m_currentSamplingInfo.plotSize = 32; + updateBufferPreviewer(); + // m_top->build(); +} - } +void GRTimePlotAddon::onDeinit() +{ + qDebug(CAT_GRTIMEPLOT) << "Deinit"; + onStop(); +} - void GRTimePlotAddon::postFlowStart() { - startPlotRefresh(); - } +void GRTimePlotAddon::preFlowStart() {} - void GRTimePlotAddon::preFlowStop() { - stopPlotRefresh(); - } +void GRTimePlotAddon::postFlowStart() { startPlotRefresh(); } - void GRTimePlotAddon::postFlowStop() { +void GRTimePlotAddon::preFlowStop() { stopPlotRefresh(); } - } +void GRTimePlotAddon::postFlowStop() {} -void GRTimePlotAddon::onChannelAdded(ToolAddon *t) { - auto ch = dynamic_cast (t); +void GRTimePlotAddon::onChannelAdded(ToolAddon *t) +{ + auto ch = dynamic_cast(t); if(ch) grChannels.append(ch); } -void GRTimePlotAddon::onChannelRemoved(ToolAddon *t) { - auto ch = dynamic_cast (t); +void GRTimePlotAddon::onChannelRemoved(ToolAddon *t) +{ + auto ch = dynamic_cast(t); if(ch) grChannels.removeAll(ch); } -void GRTimePlotAddon::connectSignalPaths() { - QList sigpaths; +void GRTimePlotAddon::connectSignalPaths() +{ + QList sigpaths; // for through grdevices - get sampleRate; std::unique_lock lock(refillMutex); for(auto &sigpath : m_top->signalPaths()) { - qDebug(CAT_GRTIMEPLOT)<<"Trying " << sigpath->name(); + qDebug(CAT_GRTIMEPLOT) << "Trying " << sigpath->name(); if(!sigpath->enabled()) continue; if(!sigpath->name().startsWith(name)) continue; sigpaths.append(sigpath); - qDebug(CAT_GRTIMEPLOT)<<"Appended " << sigpath->name(); - + qDebug(CAT_GRTIMEPLOT) << "Appended " << sigpath->name(); } - time_sink = time_sink_f::make(m_currentSamplingInfo.plotSize, m_currentSamplingInfo.sampleRate, name.toStdString(), sigpaths.count()); + time_sink = time_sink_f::make(m_currentSamplingInfo.plotSize, m_currentSamplingInfo.sampleRate, + name.toStdString(), sigpaths.count()); time_sink->setRollingMode(m_rollingMode); time_sink->setSingleShot(m_singleShot); time_sink->setComputeTags(m_showPlotTags); updateXAxis(); - int i=0; + int i = 0; time_channel_map.clear(); - for(GRTimeChannelAddon* gr : qAsConst(grChannels)) { + for(GRTimeChannelAddon *gr : qAsConst(grChannels)) { if(gr->signalPath()->enabled()) { m_top->connect(gr->signalPath()->getGrEndPoint(), 0, time_sink, i); - time_channel_map.insert(gr->signalPath()->name(),i); + time_channel_map.insert(gr->signalPath()->name(), i); if(m_currentSamplingInfo.plotSize >= 1000000) { gr->plotCh()->curve()->setPaintAttribute(QwtPlotCurve::ClipPolygons); gr->plotCh()->curve()->setPaintAttribute(QwtPlotCurve::ImageBuffer); @@ -300,15 +303,16 @@ void GRTimePlotAddon::connectSignalPaths() { } } -void GRTimePlotAddon::tearDownSignalPaths() { -} +void GRTimePlotAddon::tearDownSignalPaths() {} -void GRTimePlotAddon::onNewData() { +void GRTimePlotAddon::onNewData() +{ float sum0 = 0; - float sum1 = 0; + float sum1 = 0; } -void GRTimePlotAddon::updateXAxis() { +void GRTimePlotAddon::updateXAxis() +{ auto x = plot()->xAxis(); if(m_rollingMode) { // not normal mode - rolling mode @@ -335,7 +339,6 @@ void GRTimePlotAddon::setRollingMode(bool b) time_sink->setRollingMode(b); updateXAxis(); } - } void GRTimePlotAddon::setDrawPlotTags(bool b) @@ -347,25 +350,21 @@ void GRTimePlotAddon::setDrawPlotTags(bool b) drawPlot(); } -double GRTimePlotAddon::sampleRate() { - return m_currentSamplingInfo.sampleRate; -} +double GRTimePlotAddon::sampleRate() { return m_currentSamplingInfo.sampleRate; } -void GRTimePlotAddon::setSampleRate(double val) { - m_currentSamplingInfo.sampleRate = val; -} +void GRTimePlotAddon::setSampleRate(double val) { m_currentSamplingInfo.sampleRate = val; } void GRTimePlotAddon::setBufferSize(uint32_t size) { m_currentSamplingInfo.bufferSize = size; -// std::unique_lock lock(refillMutex); + // std::unique_lock lock(refillMutex); Q_EMIT requestRebuild(); } void GRTimePlotAddon::setPlotSize(uint32_t size) { m_currentSamplingInfo.plotSize = size; -// std::unique_lock lock(refillMutex); + // std::unique_lock lock(refillMutex); Q_EMIT requestRebuild(); } @@ -384,25 +383,19 @@ void GRTimePlotAddon::setSingleShot(bool b) } } -void GRTimePlotAddon::updateFrameRate() { +void GRTimePlotAddon::updateFrameRate() +{ Preferences *p = Preferences::GetInstance(); double framerate = p->get("general_plot_target_fps").toDouble(); setFrameRate(framerate); - -} - -void GRTimePlotAddon::setFrameRate(double val) { - int timeout = (1.0/val)*1000; - m_plotTimer->setInterval(timeout); } -void GRTimePlotAddon::setXMode(int mode) +void GRTimePlotAddon::setFrameRate(double val) { - m_xmode = mode; + int timeout = (1.0 / val) * 1000; + m_plotTimer->setInterval(timeout); } -int GRTimePlotAddon::xMode() -{ - return m_xmode; -} +void GRTimePlotAddon::setXMode(int mode) { m_xmode = mode; } +int GRTimePlotAddon::xMode() { return m_xmode; } diff --git a/gr-util/src/grtimeplotaddonsettings.cpp b/gr-util/src/grtimeplotaddonsettings.cpp index f676bd309f..0f160f4912 100644 --- a/gr-util/src/grtimeplotaddonsettings.cpp +++ b/gr-util/src/grtimeplotaddonsettings.cpp @@ -1,28 +1,34 @@ #include "grtimeplotaddonsettings.h" + #include "grtimechanneladdon.h" #include "plotaxis.h" #include "plotwidget.h" + +#include +#include + +#include +#include #include -#include #include -#include #include -#include -#include -#include +#include using namespace scopy::grutil; -GRTimePlotAddonSettings::GRTimePlotAddonSettings(GRTimePlotAddon *p, QObject *parent) : - QObject(parent),m_plot(p) { - name = p->getName()+"_settings"; +GRTimePlotAddonSettings::GRTimePlotAddonSettings(GRTimePlotAddon *p, QObject *parent) + : QObject(parent) + , m_plot(p) +{ + name = p->getName() + "_settings"; m_sampleRateAvailable = true; widget = createMenu(); } GRTimePlotAddonSettings::~GRTimePlotAddonSettings() {} -QWidget* GRTimePlotAddonSettings::createMenu(QWidget* parent) { +QWidget *GRTimePlotAddonSettings::createMenu(QWidget *parent) +{ QWidget *w = new QWidget(parent); QVBoxLayout *lay = new QVBoxLayout(w); lay->setMargin(0); @@ -32,23 +38,22 @@ QWidget* GRTimePlotAddonSettings::createMenu(QWidget* parent) { m_pen = QPen(StyleHelper::getColor("ScopyBlue")); MenuHeaderWidget *header = new MenuHeaderWidget("PLOT", m_pen, w); - QWidget* xaxismenu = createXAxisMenu(w); -// QWidget* curvemenu = createCurveMenu(w); + QWidget *xaxismenu = createXAxisMenu(w); + // QWidget* curvemenu = createCurveMenu(w); lay->addWidget(header); lay->addWidget(xaxismenu); -// lay->addWidget(curvemenu); - - lay->addSpacerItem(new QSpacerItem(0,0,QSizePolicy::Minimum,QSizePolicy::Expanding)); + // lay->addWidget(curvemenu); + lay->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); return w; } - -QWidget* GRTimePlotAddonSettings::createXAxisMenu(QWidget* parent) { +QWidget *GRTimePlotAddonSettings::createXAxisMenu(QWidget *parent) +{ MenuSectionWidget *xaxiscontainer = new MenuSectionWidget(parent); - MenuCollapseSection *xaxis = new MenuCollapseSection("X-AXIS",MenuCollapseSection::MHCW_NONE, xaxiscontainer); + MenuCollapseSection *xaxis = new MenuCollapseSection("X-AXIS", MenuCollapseSection::MHCW_NONE, xaxiscontainer); QWidget *bufferPlotSize = new QWidget(xaxis); QHBoxLayout *bufferPlotSizeLayout = new QHBoxLayout(bufferPlotSize); @@ -58,12 +63,13 @@ QWidget* GRTimePlotAddonSettings::createXAxisMenu(QWidget* parent) { m_bufferSizeSpin = new ScaleSpinButton( { - {"samples",1e0}, - {"ksamples",1e3}, - {"Msamples",1e6}, - },"Buffer Size",16,(double)((long)1<<31),false,false,bufferPlotSize); + {"samples", 1e0}, + {"ksamples", 1e3}, + {"Msamples", 1e6}, + }, + "Buffer Size", 16, (double)((long)1 << 31), false, false, bufferPlotSize); - connect(m_bufferSizeSpin, &ScaleSpinButton::valueChanged, this, [=](double val){ + connect(m_bufferSizeSpin, &ScaleSpinButton::valueChanged, this, [=](double val) { if(m_plotSizeSpin->value() < val) { m_plotSizeSpin->setValue(val); } @@ -74,16 +80,16 @@ QWidget* GRTimePlotAddonSettings::createXAxisMenu(QWidget* parent) { m_plotSizeSpin = new ScaleSpinButton( { - {"samples",1e0}, - {"ksamples",1e3}, - {"Msamples",1e6}, - {"Gsamples",1e9}, - },"Plot Size",16,(double)((long)1<<31),false,false,bufferPlotSize); - - connect(m_plotSizeSpin, &ScaleSpinButton::valueChanged, this, [=](double val){ setPlotSize((uint32_t)val);}); + {"samples", 1e0}, + {"ksamples", 1e3}, + {"Msamples", 1e6}, + {"Gsamples", 1e9}, + }, + "Plot Size", 16, (double)((long)1 << 31), false, false, bufferPlotSize); + + connect(m_plotSizeSpin, &ScaleSpinButton::valueChanged, this, [=](double val) { setPlotSize((uint32_t)val); }); connect(this, &GRTimePlotAddonSettings::plotSizeChanged, m_plot, &GRTimePlotAddon::setPlotSize); - bufferPlotSizeLayout->addWidget(m_bufferSizeSpin); bufferPlotSizeLayout->addWidget(m_plotSizeSpin); @@ -94,14 +100,16 @@ QWidget* GRTimePlotAddonSettings::createXAxisMenu(QWidget* parent) { if(b) { m_rollingModeSw->onOffswitch()->setChecked(false); m_plotSizeSpin->setValue(m_bufferSizeSpin->value()); - connect(m_bufferSizeSpin, &ScaleSpinButton::valueChanged, m_plotSizeSpin, &ScaleSpinButton::setValue); + connect(m_bufferSizeSpin, &ScaleSpinButton::valueChanged, m_plotSizeSpin, + &ScaleSpinButton::setValue); } else { - disconnect(m_bufferSizeSpin, &ScaleSpinButton::valueChanged, m_plotSizeSpin, &ScaleSpinButton::setValue); + disconnect(m_bufferSizeSpin, &ScaleSpinButton::valueChanged, m_plotSizeSpin, + &ScaleSpinButton::setValue); } - }); m_rollingModeSw = new MenuOnOffSwitch(tr("ROLLING MODE"), xaxis, false); - connect(m_rollingModeSw->onOffswitch(), &QAbstractButton::toggled, this, &GRTimePlotAddonSettings::setRollingMode); + connect(m_rollingModeSw->onOffswitch(), &QAbstractButton::toggled, this, + &GRTimePlotAddonSettings::setRollingMode); connect(this, &GRTimePlotAddonSettings::rollingModeChanged, m_plot, &GRTimePlotAddon::setRollingMode); QWidget *xMinMax = new QWidget(xaxis); @@ -112,37 +120,39 @@ QWidget* GRTimePlotAddonSettings::createXAxisMenu(QWidget* parent) { m_xmin = new PositionSpinButton( { - {"ns",1E-9}, - {"μs",1E-6}, - {"ms",1E-3}, - {"s",1e0}, - {"ks",1e3}, - {"Ms",1e6}, - {"Gs",1e9}, - },"XMin",(double)((-((long)1<<31))),(double)((long)1<<31),false,false,xMinMax); + {"ns", 1E-9}, + {"μs", 1E-6}, + {"ms", 1E-3}, + {"s", 1e0}, + {"ks", 1e3}, + {"Ms", 1e6}, + {"Gs", 1e9}, + }, + "XMin", (double)((-((long)1 << 31))), (double)((long)1 << 31), false, false, xMinMax); m_xmax = new PositionSpinButton( { - {"ns",1E-9}, - {"μs",1E-6}, - {"ms",1E-3}, - {"s",1e0}, - {"ks",1e3}, - {"Ms",1e6}, - {"Gs",1e9}, - },"XMax",(double)((-((long)1<<31))),(double)((long)1<<31),false,false,xMinMax); + {"ns", 1E-9}, + {"μs", 1E-6}, + {"ms", 1E-3}, + {"s", 1e0}, + {"ks", 1e3}, + {"Ms", 1e6}, + {"Gs", 1e9}, + }, + "XMax", (double)((-((long)1 << 31))), (double)((long)1 << 31), false, false, xMinMax); auto m_plotAxis = m_plot->plot()->xAxis(); // Connects connect(m_xmin, &PositionSpinButton::valueChanged, m_plotAxis, &PlotAxis::setMin); - connect(m_plotAxis, &PlotAxis::minChanged, this, [=](){ + connect(m_plotAxis, &PlotAxis::minChanged, this, [=]() { QSignalBlocker b(m_xmin); m_xmin->setValue(m_plotAxis->min()); m_plot->updateBufferPreviewer(); - }); + }); connect(m_xmax, &PositionSpinButton::valueChanged, m_plotAxis, &PlotAxis::setMax); - connect(m_plotAxis, &PlotAxis::maxChanged, this, [=](){ + connect(m_plotAxis, &PlotAxis::maxChanged, this, [=]() { QSignalBlocker b(m_xmax); m_xmax->setValue(m_plotAxis->max()); m_plot->updateBufferPreviewer(); @@ -185,20 +195,21 @@ QWidget* GRTimePlotAddonSettings::createXAxisMenu(QWidget* parent) { m_sampleRateSpin = new PositionSpinButton( { - {"Hz",1e0}, - {"kHz",1e3}, - {"MHz",1e6}, - {"GHz",1e9}, - },"SampleRate",1,(double)((long)1<<31),false,false,xaxis); + {"Hz", 1e0}, + {"kHz", 1e3}, + {"MHz", 1e6}, + {"GHz", 1e9}, + }, + "SampleRate", 1, (double)((long)1 << 31), false, false, xaxis); m_sampleRateSpin->setEnabled(false); - connect(m_sampleRateSpin, &PositionSpinButton::valueChanged, this, [=](double val){ setSampleRate(val);}); + connect(m_sampleRateSpin, &PositionSpinButton::valueChanged, this, [=](double val) { setSampleRate(val); }); connect(this, &GRTimePlotAddonSettings::sampleRateChanged, m_sampleRateSpin, &PositionSpinButton::setValue); connect(this, &GRTimePlotAddonSettings::sampleRateChanged, m_plot, &GRTimePlotAddon::setSampleRate); - m_showTagsSw = new MenuOnOffSwitch(tr("SHOW TAGS"), xaxis, false); - connect(m_showTagsSw->onOffswitch(), &QAbstractButton::toggled, this, &GRTimePlotAddonSettings::setShowPlotTags); + connect(m_showTagsSw->onOffswitch(), &QAbstractButton::toggled, this, + &GRTimePlotAddonSettings::setShowPlotTags); connect(this, &GRTimePlotAddonSettings::showPlotTagsChanged, m_plot, &GRTimePlotAddon::setDrawPlotTags); m_showLabels = new MenuOnOffSwitch("PLOT LABELS", xaxis); @@ -217,63 +228,51 @@ QWidget* GRTimePlotAddonSettings::createXAxisMenu(QWidget* parent) { xaxis->contentLayout()->addWidget(m_showLabels); xaxis->contentLayout()->setSpacing(10); - return xaxiscontainer; } -double GRTimePlotAddonSettings::sampleRate() const -{ - return m_sampleRate; -} +double GRTimePlotAddonSettings::sampleRate() const { return m_sampleRate; } void GRTimePlotAddonSettings::setSampleRate(double newSampleRate) { - if (qFuzzyCompare(m_sampleRate, newSampleRate)) + if(qFuzzyCompare(m_sampleRate, newSampleRate)) return; m_sampleRate = newSampleRate; Q_EMIT sampleRateChanged(m_sampleRate); } -bool GRTimePlotAddonSettings::showPlotTags() const -{ - return m_showPlotTags; -} +bool GRTimePlotAddonSettings::showPlotTags() const { return m_showPlotTags; } void GRTimePlotAddonSettings::setShowPlotTags(bool newShowPlotTags) { - if (m_showPlotTags == newShowPlotTags) + if(m_showPlotTags == newShowPlotTags) return; m_showPlotTags = newShowPlotTags; Q_EMIT showPlotTagsChanged(m_showPlotTags); } -bool GRTimePlotAddonSettings::rollingMode() const -{ - return m_rollingMode; -} +bool GRTimePlotAddonSettings::rollingMode() const { return m_rollingMode; } void GRTimePlotAddonSettings::setRollingMode(bool newRollingMode) { - if (m_rollingMode == newRollingMode) + if(m_rollingMode == newRollingMode) return; m_rollingMode = newRollingMode; Q_EMIT rollingModeChanged(newRollingMode); } -uint32_t GRTimePlotAddonSettings::plotSize() const -{ - return m_plotSize; -} +uint32_t GRTimePlotAddonSettings::plotSize() const { return m_plotSize; } void GRTimePlotAddonSettings::setPlotSize(uint32_t newPlotSize) { - if (m_plotSize == newPlotSize) + if(m_plotSize == newPlotSize) return; m_plotSize = newPlotSize; Q_EMIT plotSizeChanged(newPlotSize); } -void GRTimePlotAddonSettings::onInit() { +void GRTimePlotAddonSettings::onInit() +{ m_bufferSizeSpin->setValue(32); m_plotSizeSpin->setValue(32); m_xmin->setValue(0); @@ -281,28 +280,29 @@ void GRTimePlotAddonSettings::onInit() { m_syncBufferPlot->onOffswitch()->setChecked(true); m_showLabels->onOffswitch()->setChecked(false); m_xModeCb->combo()->setCurrentIndex(0); -// m_rollingModeSw->onOffswitch()->setChecked(false); + // m_rollingModeSw->onOffswitch()->setChecked(false); } -void GRTimePlotAddonSettings::onDeinit() { - -} +void GRTimePlotAddonSettings::onDeinit() {} -void GRTimePlotAddonSettings::onChannelAdded(ToolAddon *t) { - auto ch = dynamic_cast (t); +void GRTimePlotAddonSettings::onChannelAdded(ToolAddon *t) +{ + auto ch = dynamic_cast(t); if(ch) grChannels.append(ch); } -void GRTimePlotAddonSettings::onChannelRemoved(ToolAddon *t) { - auto ch = dynamic_cast (t); +void GRTimePlotAddonSettings::onChannelRemoved(ToolAddon *t) +{ + auto ch = dynamic_cast(t); if(ch) grChannels.removeAll(ch); } -double GRTimePlotAddonSettings::readSampleRate() { +double GRTimePlotAddonSettings::readSampleRate() +{ double sr = 1; - for(GRTimeChannelAddon* gr : grChannels ) { + for(GRTimeChannelAddon *gr : grChannels) { if(!gr->enabled()) continue; sr = gr->grch()->readSampleRate(); @@ -313,7 +313,7 @@ double GRTimePlotAddonSettings::readSampleRate() { void GRTimePlotAddonSettings::preFlowBuild() { - QComboBox* cb = m_xModeCb->combo(); + QComboBox *cb = m_xModeCb->combo(); if(cb->itemData(cb->currentIndex()) != XMODE_TIME) return; @@ -322,14 +322,11 @@ void GRTimePlotAddonSettings::preFlowBuild() setSampleRate(sr); } -uint32_t GRTimePlotAddonSettings::bufferSize() const -{ - return m_bufferSize; -} +uint32_t GRTimePlotAddonSettings::bufferSize() const { return m_bufferSize; } void GRTimePlotAddonSettings::setBufferSize(uint32_t newBufferSize) { - if (m_bufferSize == newBufferSize) + if(m_bufferSize == newBufferSize) return; m_bufferSize = newBufferSize; Q_EMIT bufferSizeChanged(newBufferSize); @@ -338,7 +335,7 @@ void GRTimePlotAddonSettings::setBufferSize(uint32_t newBufferSize) void GRTimePlotAddonSettings::computeSampleRateAvailable() { bool sampleRateAvailable = false; - for(GRTimeChannelAddon* gr : grChannels ) { + for(GRTimeChannelAddon *gr : grChannels) { if(!gr->enabled()) continue; if(gr->sampleRateAvailable()) { @@ -350,12 +347,12 @@ void GRTimePlotAddonSettings::computeSampleRateAvailable() void GRTimePlotAddonSettings::showPlotLabels(bool b) { - PlotWidget* plotWidget = m_plot->plot(); + PlotWidget *plotWidget = m_plot->plot(); plotWidget->setShowXAxisLabels(b); plotWidget->setShowYAxisLabels(b); plotWidget->showAxisLabels(); } -QString GRTimePlotAddonSettings::getName() { return name;} +QString GRTimePlotAddonSettings::getName() { return name; } -QWidget *GRTimePlotAddonSettings::getWidget() { return widget;} +QWidget *GRTimePlotAddonSettings::getWidget() { return widget; } diff --git a/gr-util/src/grtopblock.cpp b/gr-util/src/grtopblock.cpp index bfa5512c59..74947e0901 100644 --- a/gr-util/src/grtopblock.cpp +++ b/gr-util/src/grtopblock.cpp @@ -1,34 +1,37 @@ #include "grtopblock.h" + #include "grlog.h" + #include Q_LOGGING_CATEGORY(SCOPY_GR_UTIL, "GRManager") using namespace scopy::grutil; -GRTopBlock::GRTopBlock(QString name, QObject *parent) : QObject(parent), running(false), built(false) +GRTopBlock::GRTopBlock(QString name, QObject *parent) + : QObject(parent) + , running(false) + , built(false) { static int topblockid = 0; QString topblockname = m_name + QString::number(topblockid); topblockid++; - qInfo()<<"building" <disconnect_all(); Q_EMIT aboutToBuild(); - for (GRSignalPath* sig : qAsConst(m_signalPaths)) { - if(sig->enabled() ) { + for(GRSignalPath *sig : qAsConst(m_signalPaths)) { + if(sig->enabled()) { sig->connect_blk(this, nullptr); } } - for (GRIIODeviceSource* dev : qAsConst(m_iioDeviceSources)) { + for(GRIIODeviceSource *dev : qAsConst(m_iioDeviceSources)) { dev->build_blks(this); dev->connect_blk(this, nullptr); } @@ -64,18 +68,19 @@ void GRTopBlock::build() { built = true; } -void GRTopBlock::teardown() { +void GRTopBlock::teardown() +{ Q_EMIT aboutToTeardown(); built = false; - for (GRIIODeviceSource* dev : qAsConst(m_iioDeviceSources)) { + for(GRIIODeviceSource *dev : qAsConst(m_iioDeviceSources)) { if(dev->built()) { dev->disconnect_blk(this); dev->destroy_blks(this); } } - for(GRSignalPath* sig : qAsConst(m_signalPaths)) { + for(GRSignalPath *sig : qAsConst(m_signalPaths)) { sig->disconnect_blk(this); } @@ -85,21 +90,21 @@ void GRTopBlock::teardown() { void GRTopBlock::start() { - qInfo(SCOPY_GR_UTIL)<<"Starting top block"; + qInfo(SCOPY_GR_UTIL) << "Starting top block"; running = true; Q_EMIT aboutToStart(); top->start(); Q_EMIT started(); -// QtConcurrent::run([=]() { - this causes a race condition -// top->wait(); -// Q_EMIT finished(); -// }); + // QtConcurrent::run([=]() { - this causes a race condition + // top->wait(); + // Q_EMIT finished(); + // }); } void GRTopBlock::stop() { - qInfo(SCOPY_GR_UTIL)<<"Stopping top block"; + qInfo(SCOPY_GR_UTIL) << "Stopping top block"; Q_EMIT aboutToStop(); running = false; top->stop(); @@ -113,8 +118,9 @@ void GRTopBlock::run() top->wait(); } -void GRTopBlock::rebuild() { - qInfo(SCOPY_GR_UTIL)<<"Rebuilding top block"; +void GRTopBlock::rebuild() +{ + qInfo(SCOPY_GR_UTIL) << "Rebuilding top block"; bool wasRunning = false; if(running) { wasRunning = true; @@ -133,9 +139,9 @@ void GRTopBlock::rebuild() { void GRTopBlock::connect(gr::basic_block_sptr src, int srcPort, gr::basic_block_sptr dst, int dstPort) { - qDebug(SCOPY_GR_UTIL) << "Connecting " << QString::fromStdString(src->symbol_name()) << ":" << srcPort - << "to" << QString::fromStdString(dst->symbol_name()) << ":" << dstPort; - top->connect(src,srcPort,dst,dstPort); + qDebug(SCOPY_GR_UTIL) << "Connecting " << QString::fromStdString(src->symbol_name()) << ":" << srcPort << "to" + << QString::fromStdString(dst->symbol_name()) << ":" << dstPort; + top->connect(src, srcPort, dst, dstPort); } gr::top_block_sptr GRTopBlock::getGrBlock() { return top; } diff --git a/gr-util/src/measure.cpp b/gr-util/src/measure.cpp index 86ecedcaea..527c3c37d0 100644 --- a/gr-util/src/measure.cpp +++ b/gr-util/src/measure.cpp @@ -19,13 +19,14 @@ */ #include "measure.h" -#include -#include -#include + #include #include -#include +#include + +#include #include +#include using namespace scopy; @@ -33,15 +34,13 @@ namespace scopy::grutil { class CrossPoint { public: - CrossPoint(float value, size_t bufIndex, bool onRising, QString name): - m_value(value), - m_bufIdx(bufIndex), - m_onRising(onRising), - m_name(name) - + CrossPoint(float value, size_t bufIndex, bool onRising, QString name) + : m_value(value) + , m_bufIdx(bufIndex) + , m_onRising(onRising) + , m_name(name) - { - } + {} public: float m_value; @@ -53,7 +52,8 @@ class CrossPoint class HystLevelCross { public: - enum crossEvents { + enum crossEvents + { NO_CROSS = 0, POS_CROSS_LOW, POS_CROSS_HIGH, @@ -63,40 +63,35 @@ class HystLevelCross NEG_CROSS_FULL, }; - HystLevelCross() : - m_low_trhold_crossed(false), - m_high_trhold_crossed(false), - m_is_between_trholds(false) - { - } + HystLevelCross() + : m_low_trhold_crossed(false) + , m_high_trhold_crossed(false) + , m_is_between_trholds(false) + {} - bool isBetweenThresholds() - { - return m_is_between_trholds; - } + bool isBetweenThresholds() { return m_is_between_trholds; } virtual inline bool updateState(enum crossEvents crsEvent) = 0; - static inline enum crossEvents - get_crossing_type(double samp, double prevSamp, - double low_trhold, double high_trhold) + static inline enum crossEvents get_crossing_type(double samp, double prevSamp, double low_trhold, + double high_trhold) { enum crossEvents cross_type = NO_CROSS; - if (samp > prevSamp) { - if ((prevSamp <= low_trhold) && (samp >= low_trhold)) + if(samp > prevSamp) { + if((prevSamp <= low_trhold) && (samp >= low_trhold)) cross_type = POS_CROSS_LOW; - if ((prevSamp <= high_trhold) && (samp >= high_trhold)) { - if (cross_type == POS_CROSS_LOW) + if((prevSamp <= high_trhold) && (samp >= high_trhold)) { + if(cross_type == POS_CROSS_LOW) cross_type = POS_CROSS_FULL; else cross_type = POS_CROSS_HIGH; } - } else if (samp < prevSamp) { - if ((prevSamp >= low_trhold) && (samp <= low_trhold)) + } else if(samp < prevSamp) { + if((prevSamp >= low_trhold) && (samp <= low_trhold)) cross_type = NEG_CROSS_LOW; - if ((prevSamp >= high_trhold) && (samp <= high_trhold)) { - if (cross_type == NEG_CROSS_LOW) + if((prevSamp >= high_trhold) && (samp <= high_trhold)) { + if(cross_type == NEG_CROSS_LOW) cross_type = NEG_CROSS_FULL; else cross_type = NEG_CROSS_HIGH; @@ -119,24 +114,23 @@ class HystLevelCross bool m_is_between_trholds; }; -class HystLevelPosCross: public HystLevelCross +class HystLevelPosCross : public HystLevelCross { public: - HystLevelPosCross() : - HystLevelCross() - { - } + HystLevelPosCross() + : HystLevelCross() + {} inline bool updateState(enum crossEvents crsEvent) { bool level_crossed = false; - switch (crsEvent) { + switch(crsEvent) { case POS_CROSS_LOW: m_is_between_trholds = true; break; case POS_CROSS_HIGH: - if (m_is_between_trholds) { + if(m_is_between_trholds) { level_crossed = true; m_is_between_trholds = false; } @@ -154,24 +148,23 @@ class HystLevelPosCross: public HystLevelCross } }; -class HystLevelNegCross: public HystLevelCross +class HystLevelNegCross : public HystLevelCross { public: - HystLevelNegCross() : - HystLevelCross() - { - } + HystLevelNegCross() + : HystLevelCross() + {} inline bool updateState(enum crossEvents crsEvent) { bool level_crossed = false; - switch (crsEvent) { + switch(crsEvent) { case NEG_CROSS_HIGH: m_is_between_trholds = true; break; case NEG_CROSS_LOW: - if (m_is_between_trholds) { + if(m_is_between_trholds) { level_crossed = true; m_is_between_trholds = false; } @@ -192,59 +185,45 @@ class HystLevelNegCross: public HystLevelCross class CrossingDetection { public: - CrossingDetection(double level, double hysteresis_span, - const QString &name): - m_posCrossFound(false), - m_negCrossFound(false), - m_crossed(false), - m_posCrossPoint(0), - m_negCrossPoint(0), - m_level(level), - m_hysteresis_span(hysteresis_span), - m_low_level(level - hysteresis_span / 2), - m_high_level(level + hysteresis_span / 2), - m_name(name), - m_externList(NULL) - { - } - - double level() - { - return m_level; - } + CrossingDetection(double level, double hysteresis_span, const QString &name) + : m_posCrossFound(false) + , m_negCrossFound(false) + , m_crossed(false) + , m_posCrossPoint(0) + , m_negCrossPoint(0) + , m_level(level) + , m_hysteresis_span(hysteresis_span) + , m_low_level(level - hysteresis_span / 2) + , m_high_level(level + hysteresis_span / 2) + , m_name(name) + , m_externList(NULL) + {} + + double level() { return m_level; } void setLevel(double level) { - if (m_level != level) { + if(m_level != level) { m_level = level; m_low_level = level - m_hysteresis_span / 2; m_high_level = level + m_hysteresis_span / 2; } } - double hysteresisSpan() - { - return m_hysteresis_span; - } + double hysteresisSpan() { return m_hysteresis_span; } void setHysteresisSpan(double span) { - if (m_hysteresis_span != span) { + if(m_hysteresis_span != span) { m_hysteresis_span = span; m_low_level = m_level - span / 2; m_high_level = m_level + span / 2; } } - void setExternalList(QList *externList) - { - m_externList = externList; - } + void setExternalList(QList *externList) { m_externList = externList; } - QList detectedCrossings() - { - return m_detectedCrossings; - } + QList detectedCrossings() { return m_detectedCrossings; } inline void store_closest_val_to_cross_lvl(const float *data, size_t i, size_t &point) { @@ -253,7 +232,7 @@ class CrossingDetection double diff; size_t idx; - if (diff1 < diff2) { + if(diff1 < diff2) { idx = i - 1; diff = diff1; } else { @@ -262,7 +241,7 @@ class CrossingDetection } double old_diff = qAbs(data[point] - m_level); - if (diff < old_diff) + if(diff < old_diff) point = idx; } @@ -271,7 +250,7 @@ class CrossingDetection double diff1 = qAbs(data[i - 1] - m_level); double diff2 = qAbs(data[i] - m_level); - if (diff1 < diff2) + if(diff1 < diff2) point = i - 1; else point = i; @@ -279,49 +258,46 @@ class CrossingDetection inline void crossDetectStep(const float *data, size_t i) { - auto cross_type = HystLevelCross::get_crossing_type(data[i], - data[i - 1], m_low_level, m_high_level); + auto cross_type = HystLevelCross::get_crossing_type(data[i], data[i - 1], m_low_level, m_high_level); - if (m_posCross.isBetweenThresholds()) + if(m_posCross.isBetweenThresholds()) store_closest_val_to_cross_lvl(data, i, m_posCrossPoint); - if (m_negCross.isBetweenThresholds()) + if(m_negCross.isBetweenThresholds()) store_closest_val_to_cross_lvl(data, i, m_negCrossPoint); - if (cross_type != HystLevelCross::NO_CROSS) { - if (!m_posCrossFound) { + if(cross_type != HystLevelCross::NO_CROSS) { + if(!m_posCrossFound) { bool old_between_thresh = m_posCross.isBetweenThresholds(); m_crossed = m_posCross.updateState(cross_type); - if (!old_between_thresh && m_posCross.isBetweenThresholds()) + if(!old_between_thresh && m_posCross.isBetweenThresholds()) store_first_closest_val_to_cross_lvl(data, i, m_posCrossPoint); - if (m_crossed) { + if(m_crossed) { m_posCrossFound = true; m_negCrossFound = false; m_negCross.resetState(); - if (cross_type == HystLevelCross::POS_CROSS_FULL) + if(cross_type == HystLevelCross::POS_CROSS_FULL) m_posCrossPoint = i; m_detectedCrossings.push_back( - CrossPoint(data[m_posCrossPoint], m_posCrossPoint, - true, m_name + "R")); - if (m_externList) + CrossPoint(data[m_posCrossPoint], m_posCrossPoint, true, m_name + "R")); + if(m_externList) m_externList->push_back(m_detectedCrossings.last()); } } - if (!m_negCrossFound) { + if(!m_negCrossFound) { bool old_between_thresh = m_negCross.isBetweenThresholds(); m_crossed = m_negCross.updateState(cross_type); - if (!old_between_thresh && m_negCross.isBetweenThresholds()) + if(!old_between_thresh && m_negCross.isBetweenThresholds()) store_first_closest_val_to_cross_lvl(data, i, m_negCrossPoint); - if (m_crossed) { + if(m_crossed) { m_negCrossFound = true; m_posCrossFound = false; m_posCross.resetState(); - if (cross_type == HystLevelCross::NEG_CROSS_FULL) + if(cross_type == HystLevelCross::NEG_CROSS_FULL) m_negCrossPoint = i - 1; - m_detectedCrossings.push_back( - CrossPoint(data[m_negCrossPoint], m_negCrossPoint, - false, m_name + "F")); - if (m_externList) + m_detectedCrossings.push_back(CrossPoint(data[m_negCrossPoint], m_negCrossPoint, + false, m_name + "F")); + if(m_externList) m_externList->push_back(m_detectedCrossings.last()); } } @@ -350,18 +326,20 @@ class CrossingDetection QString m_name; }; -class SpectralDetection { +class SpectralDetection +{ public: - SpectralDetection(const float *data, ssize_t data_length, int harmonics_number): - m_data(data), - m_data_length(data_length), - m_harmonics_number(harmonics_number) + SpectralDetection(const float *data, ssize_t data_length, int harmonics_number) + : m_data(data) + , m_data_length(data_length) + , m_harmonics_number(harmonics_number) + {} + + void calculateSpectralDetectionParameters(double &spur, double &harm_dist, double &noise, double &average_noise, + double &signal) { - } - - void calculateSpectralDetectionParameters(double &spur, double &harm_dist, double &noise, - double &average_noise, double &signal) { - struct harmonic_tuple { + struct harmonic_tuple + { double harm_value; int harm_bin; }; @@ -380,33 +358,31 @@ class SpectralDetection { noise = average_noise * (m_data_length - 1); std::map harmonic; - for(int i = 0; i < m_harmonics_number; i++) - { + for(int i = 0; i < m_harmonics_number; i++) { struct harmonic_tuple harm; harm.harm_bin = m_harmonic_bins[i]; harm.harm_value = m_harmonics[i]; harm.harm_value -= average_noise * m_harmonic_bw[i]; - harmonic[i+1] = harm; + harmonic[i + 1] = harm; } spur -= average_noise * spur_bw; signal = harmonic[1].harm_value; - harm_dist = harmonic[2].harm_value + harmonic[3].harm_value + - harmonic[4].harm_value + harmonic[5].harm_value; - + harm_dist = harmonic[2].harm_value + harmonic[3].harm_value + harmonic[4].harm_value + + harmonic[5].harm_value; } private: - - std::vector calculateAutoMask() { + std::vector calculateAutoMask() + { const int BANDWIDTH_DIVIDER = 80; const int NUM_INITAL_NOISE_HARMS = 5; int bw = int(m_data_length / BANDWIDTH_DIVIDER); std::vector mask; mask.resize(m_data_length, 1); - for (int i = 0; i < NUM_INITAL_NOISE_HARMS; i++) + for(int i = 0; i < NUM_INITAL_NOISE_HARMS; i++) clearMask(mask, m_harmonic_bins[i] - bw, m_harmonic_bins[i] + bw); mask[0] = 0; @@ -416,31 +392,27 @@ class SpectralDetection { noise_est /= noise_bins; std::fill(mask.begin(), mask.end(), 1); - //clear mask la dc. + // clear mask la dc. clearMask(mask, 0, 1); int j; int low, high; double sum; - for(size_t i = 0; i < m_harmonic_bins.size(); i++) - { + for(size_t i = 0; i < m_harmonic_bins.size(); i++) { int h = m_harmonic_bins.at(i); if(mask[h] == 0) continue; j = 1; sum = 0.0F; - for(int s = h-j; s < h-j+3; s++) - { + for(int s = h - j; s < h - j + 3; s++) { sum += m_data[s]; } sum /= 3; - while ( h - j > 0 && mask[h-j] == 1 && - sum > noise_est ) { + while(h - j > 0 && mask[h - j] == 1 && sum > noise_est) { j++; sum = 0.0F; - for(int s = h-j; s < h-j+3; s++) - { + for(int s = h - j; s < h - j + 3; s++) { sum += m_data[s]; } sum /= 3; @@ -449,17 +421,14 @@ class SpectralDetection { j = 1; sum = 0.0F; - for(int s = h+j-2; s < h+j+1; s++) - { + for(int s = h + j - 2; s < h + j + 1; s++) { sum += m_data[s]; } sum /= 3; - while ( h + j < m_data_length && mask[h+j] == 1 && - sum > noise_est ) { + while(h + j < m_data_length && mask[h + j] == 1 && sum > noise_est) { j++; sum = 0.0F; - for(int s = h+j-2; s < h+j+1; s++) - { + for(int s = h + j - 2; s < h + j + 1; s++) { sum += m_data[s]; } sum /= 3; @@ -476,46 +445,38 @@ class SpectralDetection { int nyq = mask.size(); int n = 2 * (nyq - 1); std::vector indices; - for(int i = start; i <= end; i++) - { + for(int i = start; i <= end; i++) { int index_value = (i + n) % n; - if (index_value > nyq) + if(index_value > nyq) index_value = n - index_value; indices.push_back(index_value); } - for(std::vector::iterator it = indices.begin(); it != indices.end(); ++it) - { + for(std::vector::iterator it = indices.begin(); it != indices.end(); ++it) { mask.at(*it) = value; } } - void clearMask(std::vector &mask, int start, int end) - { - setMask(mask, start, end, 0); - } + void clearMask(std::vector &mask, int start, int end) { setMask(mask, start, end, 0); } - void maskedSubset(std::vector &indices, std::vector &new_mask, std::vector mask, int start, int end) + void maskedSubset(std::vector &indices, std::vector &new_mask, std::vector mask, int start, + int end) { int nyq = mask.size(); int n = 2 * (nyq - 1); std::vector mapped_subset; - for(int i = start; i < end; i++) - { + for(int i = start; i < end; i++) { int index_value = (i + n) % n; - if (index_value > nyq) + if(index_value > nyq) index_value = n - index_value; mapped_subset.push_back(index_value); } - for(size_t i = 0; i < mapped_subset.size(); i++) - { - if(mask.at(mapped_subset.at(i)) == 1) - { + for(size_t i = 0; i < mapped_subset.size(); i++) { + if(mask.at(mapped_subset.at(i)) == 1) { indices.push_back(mapped_subset.at(i)); new_mask.push_back(mask.at(mapped_subset.at(i))); } - } } @@ -529,9 +490,7 @@ class SpectralDetection { maskedSubset(indices, new_mask, mask, start, end); double sum = 0; - - for(std::vector::iterator it = indices.begin(); it != indices.end(); ++it) - { + for(std::vector::iterator it = indices.begin(); it != indices.end(); ++it) { sum = sum + (m_data[*it] * m_data[*it]); } @@ -549,9 +508,7 @@ class SpectralDetection { maskedSubset(indices, new_mask, mask, start, end); double sum = 0; - - for(std::vector::iterator it = indices.begin(); it != indices.end(); ++it) - { + for(std::vector::iterator it = indices.begin(); it != indices.end(); ++it) { sum = sum + (m_data[*it]); } @@ -570,8 +527,7 @@ class SpectralDetection { std::vector new_mask; maskedSubset(indices, new_mask, mask, start, end); - for(size_t i=0; i value) - { + for(int i = 0; i < size; i++) { + if(data[i] > value) { index = i; value = data[i]; } @@ -608,71 +562,63 @@ class SpectralDetection { std::fill(m_harmonic_bw.begin(), m_harmonic_bw.end(), 0); std::fill(m_harmonics.begin(), m_harmonics.end(), 0.0); - //find the fundamental bin (max value) from the data + // find the fundamental bin (max value) from the data int fund_bin = 0; double max = 0; getMax(m_data, m_data_length, fund_bin, max); m_harmonic_bins.at(0) = fund_bin; - for(int h = 1; h < max_harmonics + 1; h++) - { + for(int h = 1; h < max_harmonics + 1; h++) { std::vector mask; mask.resize(m_data_length, 0); int nominal_bin = h * fund_bin; int h_2 = static_cast(h / 2); - if(h > 1) - { + if(h > 1) { setMask(mask, nominal_bin - h_2, nominal_bin + h_2, 1); - for(int i = 0; i < h - 1; i++) - { + for(int i = 0; i < h - 1; i++) { clearMask(mask, m_harmonic_bins.at(i), m_harmonic_bins.at(i)); } int index; double value; maskedMax(index, value, mask); - m_harmonic_bins.at(h-1) = index; + m_harmonic_bins.at(h - 1) = index; } clearMask(mask, nominal_bin - h_2, nominal_bin + h_2); - setMask(mask, m_harmonic_bins.at(h-1) - BW, m_harmonic_bins.at(h-1) + BW, 1); - for(int i = 0; i < h - 1; i++) - { + setMask(mask, m_harmonic_bins.at(h - 1) - BW, m_harmonic_bins.at(h - 1) + BW, 1); + for(int i = 0; i < h - 1; i++) { clearMask(mask, m_harmonic_bins.at(i) - BW, m_harmonic_bins.at(i) + BW); } double val_harm; int val_hbws; maskedSumOfSquares(val_hbws, val_harm, mask); - m_harmonics[h-1] = val_harm; - m_harmonic_bw[h-1] = val_hbws; - + m_harmonics[h - 1] = val_harm; + m_harmonic_bw[h - 1] = val_hbws; } - } - void findSpur(double &spur, int& spur_bw, bool find_in_harmonics, int fund_bin) { + void findSpur(double &spur, int &spur_bw, bool find_in_harmonics, int fund_bin) + { if(find_in_harmonics == true) { int index = std::max_element(m_harmonics.begin() + 1, m_harmonics.end()) - m_harmonics.begin(); spur = *std::max_element(m_harmonics.begin() + 1, m_harmonics.end()); spur_bw = m_harmonic_bw[index + 1]; - } - else - { + } else { findSpurInData(spur, spur_bw, fund_bin); } } - void findSpurInData(double &spur, int& spur_bw, int fund_bin) { + void findSpurInData(double &spur, int &spur_bw, int fund_bin) + { std::vector mask; mask.resize(m_data_length, 1); - //clear mask la dc. + // clear mask la dc. clearMask(mask, 0, 1); clearMask(mask, fund_bin - BW, fund_bin + BW); int index = 0; - for(size_t i = 0; i < mask.size(); i++) - { - if(mask.at(i) == 1) - { + for(size_t i = 0; i < mask.size(); i++) { + if(mask.at(i) == 1) { index = i; break; } @@ -684,13 +630,10 @@ class SpectralDetection { int masked_index = 0; double value; - while(index < m_data_length) - { - if(mask.at(index) == 1) - { + while(index < m_data_length) { + if(mask.at(index) == 1) { maskedSumOfSquares(masked_index, value, mask, index - BW, index + BW); - if(value > max_value) - { + if(value > max_value) { max_value = value; max_index = index; } @@ -701,7 +644,7 @@ class SpectralDetection { int spur_bin; double spur_value; maskedMax(spur_bin, spur_value, mask, max_index - BW, max_index + BW); -// maskedSumOfSquares(spur_bw, spur, mask, spur_bin - BW, spur_bin + BW); + // maskedSumOfSquares(spur_bw, spur, mask, spur_bin - BW, spur_bin + BW); } private: @@ -714,34 +657,27 @@ class SpectralDetection { std::vector m_harmonics; int m_harmonics_number; std::vector m_mask; - }; - MeasureModel::MeasureModel(const float *buffer, size_t length, QObject *parent) - : QObject(parent), - m_buffer(buffer), - m_buf_length(length), - m_sample_rate(1.0), - m_adc_bit_count(0), - m_cross_level(0), - m_hysteresis_span(0), - m_histogram(nullptr), - m_cross_detect(nullptr), - m_gatingEnabled(false) + : QObject(parent) + , m_buffer(buffer) + , m_buf_length(length) + , m_sample_rate(1.0) + , m_adc_bit_count(0) + , m_cross_level(0) + , m_hysteresis_span(0) + , m_histogram(nullptr) + , m_cross_detect(nullptr) + , m_gatingEnabled(false) -{ +{} -} - -MeasureModel::~MeasureModel() -{ - -} +MeasureModel::~MeasureModel() {} void MeasureModel::clearMeasurements() { - for (int i = 0; i < m_measurements.size(); i++) + for(int i = 0; i < m_measurements.size(); i++) m_measurements[i]->setMeasured(false); } @@ -751,66 +687,60 @@ void MeasureModel::setDataSource(const float *buffer, size_t length) m_buf_length = length; } -TimeMeasureModel::TimeMeasureModel(const float *buffer, size_t length, QObject *parent) : MeasureModel(buffer, length, parent) { +TimeMeasureModel::TimeMeasureModel(const float *buffer, size_t length, QObject *parent) + : MeasureModel(buffer, length, parent) +{ // Create a set of measurements - m_measurements.push_back(std::make_shared(QObject::tr("Period"), - MeasurementData::HORIZONTAL, "s")); - m_measurements.push_back(std::make_shared(QObject::tr("Frequency"), - MeasurementData::HORIZONTAL, "Hz")); - m_measurements.push_back(std::make_shared(QObject::tr("Min"), - MeasurementData::VERTICAL, "V")); - m_measurements.push_back(std::make_shared(QObject::tr("Max"), - MeasurementData::VERTICAL, "V")); - m_measurements.push_back(std::make_shared(QObject::tr("Peak-peak"), - MeasurementData::VERTICAL, "V")); - m_measurements.push_back(std::make_shared(QObject::tr("Mean"), - MeasurementData::VERTICAL, "V")); - m_measurements.push_back(std::make_shared(QObject::tr("Cycle Mean"), - MeasurementData::VERTICAL, "V")); - m_measurements.push_back(std::make_shared(QObject::tr("RMS"), - MeasurementData::VERTICAL, "V")); - m_measurements.push_back(std::make_shared(QObject::tr("Cycle RMS"), - MeasurementData::VERTICAL, "V")); - m_measurements.push_back(std::make_shared(QObject::tr("AC RMS"), - MeasurementData::VERTICAL, "V")); - m_measurements.push_back(std::make_shared(QObject::tr("Area"), - MeasurementData::VERTICAL, "Vs")); - m_measurements.push_back(std::make_shared(QObject::tr("Cycle Area"), - MeasurementData::VERTICAL, "Vs")); - m_measurements.push_back(std::make_shared(QObject::tr("Low"), - MeasurementData::VERTICAL, "V")); - m_measurements.push_back(std::make_shared(QObject::tr("High"), - MeasurementData::VERTICAL, "V")); - m_measurements.push_back(std::make_shared(QObject::tr("Amplitude"), - MeasurementData::VERTICAL, "V")); - m_measurements.push_back(std::make_shared(QObject::tr("Middle"), - MeasurementData::VERTICAL, "V")); - m_measurements.push_back(std::make_shared(QObject::tr("+Over"), - MeasurementData::VERTICAL, "%")); - m_measurements.push_back(std::make_shared(QObject::tr("-Over"), - MeasurementData::VERTICAL, "%")); - m_measurements.push_back(std::make_shared(QObject::tr("Rise"), - MeasurementData::HORIZONTAL, "s")); - m_measurements.push_back(std::make_shared(QObject::tr("Fall"), - MeasurementData::HORIZONTAL, "s")); - m_measurements.push_back(std::make_shared(QObject::tr("+Width"), - MeasurementData::HORIZONTAL, "s")); - m_measurements.push_back(std::make_shared(QObject::tr("-Width"), - MeasurementData::HORIZONTAL, "s")); - m_measurements.push_back(std::make_shared(QObject::tr("+Duty"), - MeasurementData::HORIZONTAL, "%")); - m_measurements.push_back(std::make_shared(QObject::tr("-Duty"), - MeasurementData::HORIZONTAL, "%")); + m_measurements.push_back( + std::make_shared(QObject::tr("Period"), MeasurementData::HORIZONTAL, "s")); + m_measurements.push_back( + std::make_shared(QObject::tr("Frequency"), MeasurementData::HORIZONTAL, "Hz")); + m_measurements.push_back(std::make_shared(QObject::tr("Min"), MeasurementData::VERTICAL, "V")); + m_measurements.push_back(std::make_shared(QObject::tr("Max"), MeasurementData::VERTICAL, "V")); + m_measurements.push_back( + std::make_shared(QObject::tr("Peak-peak"), MeasurementData::VERTICAL, "V")); + m_measurements.push_back( + std::make_shared(QObject::tr("Mean"), MeasurementData::VERTICAL, "V")); + m_measurements.push_back( + std::make_shared(QObject::tr("Cycle Mean"), MeasurementData::VERTICAL, "V")); + m_measurements.push_back(std::make_shared(QObject::tr("RMS"), MeasurementData::VERTICAL, "V")); + m_measurements.push_back( + std::make_shared(QObject::tr("Cycle RMS"), MeasurementData::VERTICAL, "V")); + m_measurements.push_back( + std::make_shared(QObject::tr("AC RMS"), MeasurementData::VERTICAL, "V")); + m_measurements.push_back( + std::make_shared(QObject::tr("Area"), MeasurementData::VERTICAL, "Vs")); + m_measurements.push_back( + std::make_shared(QObject::tr("Cycle Area"), MeasurementData::VERTICAL, "Vs")); + m_measurements.push_back(std::make_shared(QObject::tr("Low"), MeasurementData::VERTICAL, "V")); + m_measurements.push_back( + std::make_shared(QObject::tr("High"), MeasurementData::VERTICAL, "V")); + m_measurements.push_back( + std::make_shared(QObject::tr("Amplitude"), MeasurementData::VERTICAL, "V")); + m_measurements.push_back( + std::make_shared(QObject::tr("Middle"), MeasurementData::VERTICAL, "V")); + m_measurements.push_back( + std::make_shared(QObject::tr("+Over"), MeasurementData::VERTICAL, "%")); + m_measurements.push_back( + std::make_shared(QObject::tr("-Over"), MeasurementData::VERTICAL, "%")); + m_measurements.push_back( + std::make_shared(QObject::tr("Rise"), MeasurementData::HORIZONTAL, "s")); + m_measurements.push_back( + std::make_shared(QObject::tr("Fall"), MeasurementData::HORIZONTAL, "s")); + m_measurements.push_back( + std::make_shared(QObject::tr("+Width"), MeasurementData::HORIZONTAL, "s")); + m_measurements.push_back( + std::make_shared(QObject::tr("-Width"), MeasurementData::HORIZONTAL, "s")); + m_measurements.push_back( + std::make_shared(QObject::tr("+Duty"), MeasurementData::HORIZONTAL, "%")); + m_measurements.push_back( + std::make_shared(QObject::tr("-Duty"), MeasurementData::HORIZONTAL, "%")); } -TimeMeasureModel::~TimeMeasureModel() -{ - -} +TimeMeasureModel::~TimeMeasureModel() {} -bool TimeMeasureModel::highLowFromHistogram(double &low, double &high, - double min, double max) +bool TimeMeasureModel::highLowFromHistogram(double &low, double &high, double min, double max) { bool success = false; int *hist = m_histogram; @@ -822,7 +752,7 @@ bool TimeMeasureModel::highLowFromHistogram(double &low, double &high, minRaw += hlf_scale; maxRaw += hlf_scale; - int middleRaw = minRaw + (maxRaw - minRaw) / 2; + int middleRaw = minRaw + (maxRaw - minRaw) / 2; auto lowIt = std::max_element(hist + minRaw, hist + middleRaw + 1); int lowRaw = std::distance(hist, lowIt); @@ -834,8 +764,7 @@ bool TimeMeasureModel::highLowFromHistogram(double &low, double &high, clearly identified (weight of a level should be 5 times greater than a peak weight - there probably is a better method) */ - if (hist[lowRaw] / 5.0 >= hist[minRaw] && - hist[highRaw] / 5.0 >= hist[maxRaw]) { + if(hist[lowRaw] / 5.0 >= hist[minRaw] && hist[highRaw] / 5.0 >= hist[maxRaw]) { low = lowRaw - hlf_scale; high = highRaw - hlf_scale; @@ -845,33 +774,25 @@ bool TimeMeasureModel::highLowFromHistogram(double &low, double &high, return success; } -SpectralMeasure::SpectralMeasure(const float *buffer, size_t length) : MeasureModel(buffer, length) { - //Spectral Measurements - m_measurements.push_back(std::make_shared("Noise_Floor", - MeasurementData::HORIZONTAL_F, "dB")); - m_measurements.push_back(std::make_shared("SINAD", - MeasurementData::HORIZONTAL_F, "dB")); - m_measurements.push_back(std::make_shared("SNR", - MeasurementData::HORIZONTAL_F, "dB")); - m_measurements.push_back(std::make_shared("THD", - MeasurementData::HORIZONTAL_F, "dB")); - m_measurements.push_back(std::make_shared("THDN", - MeasurementData::HORIZONTAL_F, "dB")); - m_measurements.push_back(std::make_shared("SFDR", - MeasurementData::VERTICAL_F, "dBc")); -} - -SpectralMeasure::~SpectralMeasure() +SpectralMeasure::SpectralMeasure(const float *buffer, size_t length) + : MeasureModel(buffer, length) { - + // Spectral Measurements + m_measurements.push_back(std::make_shared("Noise_Floor", MeasurementData::HORIZONTAL_F, "dB")); + m_measurements.push_back(std::make_shared("SINAD", MeasurementData::HORIZONTAL_F, "dB")); + m_measurements.push_back(std::make_shared("SNR", MeasurementData::HORIZONTAL_F, "dB")); + m_measurements.push_back(std::make_shared("THD", MeasurementData::HORIZONTAL_F, "dB")); + m_measurements.push_back(std::make_shared("THDN", MeasurementData::HORIZONTAL_F, "dB")); + m_measurements.push_back(std::make_shared("SFDR", MeasurementData::VERTICAL_F, "dBc")); } +SpectralMeasure::~SpectralMeasure() {} void TimeMeasureModel::measure() { clearMeasurements(); - if (!m_buffer || m_buf_length == 0) + if(!m_buffer || m_buf_length == 0) return; measureTime(); @@ -918,17 +839,17 @@ void TimeMeasureModel::measureTime() int startIndex; int endIndex; - if (qIsNaN(data[0])) { + if(qIsNaN(data[0])) { return; } - //if gating is enabled measure only on data between the gates - if(m_gatingEnabled){ - //make sure that start/end indexes are valid - if(m_startIndex < 0 || m_startIndex > m_buf_length){ + // if gating is enabled measure only on data between the gates + if(m_gatingEnabled) { + // make sure that start/end indexes are valid + if(m_startIndex < 0 || m_startIndex > m_buf_length) { m_startIndex = 0; } - if(m_endIndex < 0 || m_endIndex > m_buf_length ){ + if(m_endIndex < 0 || m_endIndex > m_buf_length) { m_endIndex = m_buf_length; } @@ -936,12 +857,11 @@ void TimeMeasureModel::measureTime() min = data[m_startIndex]; sum = data[m_startIndex]; sqr_sum = data[m_startIndex] * data[m_startIndex]; - startIndex = m_startIndex+1; + startIndex = m_startIndex + 1; endIndex = m_endIndex; count = (m_endIndex - m_startIndex) ?: 1; - } - else{ + } else { max = data[0]; min = data[0]; sum = data[0]; @@ -950,14 +870,13 @@ void TimeMeasureModel::measureTime() endIndex = data_length; } - m_cross_detect = new CrossingDetection(m_cross_level, m_hysteresis_span, - "P"); - if (using_histogram_method) + m_cross_detect = new CrossingDetection(m_cross_level, m_hysteresis_span, "P"); + if(using_histogram_method) m_histogram = new int[adc_span]{}; - for (ssize_t i = startIndex; i < endIndex; i++) { + for(ssize_t i = startIndex; i < endIndex; i++) { - if (qIsNaN(data[i])) { + if(qIsNaN(data[i])) { count--; continue; } @@ -965,12 +884,12 @@ void TimeMeasureModel::measureTime() m_cross_detect->crossDetectStep(data, i); // Min - if (data[i] < min) { + if(data[i] < min) { min = data[i]; } // Max - if (data[i] > max) { + if(data[i] > max) { max = data[i]; } @@ -981,11 +900,11 @@ void TimeMeasureModel::measureTime() sqr_sum += data[i] * data[i]; // Build histogram - if (using_histogram_method) { + if(using_histogram_method) { int raw = data[i]; raw += hlf_scale; - if (raw >= 0 && raw < adc_span) + if(raw >= 0 && raw < adc_span) m_histogram[raw] += 1; } } @@ -1006,15 +925,14 @@ void TimeMeasureModel::measureTime() m_measurements[RMS]->setValue(rms); // AC RMS - rms_ac = sqrt((sqr_sum - 2 * mean * sum + - count * mean * mean) / count); + rms_ac = sqrt((sqr_sum - 2 * mean * sum + count * mean * mean) / count); m_measurements[AC_RMS]->setValue(rms_ac); low = min; high = max; // Try to use Histogram method - if (using_histogram_method) + if(using_histogram_method) highLowFromHistogram(low, high, min, max); // Low, High, Middle, Amplitude, Overshoot positive/negative @@ -1033,7 +951,7 @@ void TimeMeasureModel::measureTime() overshoot_n = (low - min) / amplitude * 100; m_measurements[N_OVER]->setValue(overshoot_n); - if (m_histogram != NULL) { + if(m_histogram != NULL) { delete[] m_histogram; m_histogram = NULL; } @@ -1041,28 +959,25 @@ void TimeMeasureModel::measureTime() // Find Period / Frequency QList periodPoints = m_cross_detect->detectedCrossings(); int n = periodPoints.size(); - if (n > 2) { + if(n > 2) { double sample_period; double first_hlf_cycl = 0; double secnd_hlf_cycl = 0; int j = 0; int k = 0; - for (int i = 0; i < n - 1; i++) { - size_t diff = periodPoints[i + 1].m_bufIdx - - periodPoints[i].m_bufIdx; - if (i % 2) { + for(int i = 0; i < n - 1; i++) { + size_t diff = periodPoints[i + 1].m_bufIdx - periodPoints[i].m_bufIdx; + if(i % 2) { secnd_hlf_cycl += diff; j++; - } - else { + } else { first_hlf_cycl += diff; k++; } } - sample_period = first_hlf_cycl / (n / 2) + - secnd_hlf_cycl / ((n + 1) / 2 - 1); + sample_period = first_hlf_cycl / (n / 2) + secnd_hlf_cycl / ((n + 1) / 2 - 1); period = sample_period * (1 / m_sample_rate); m_measurements[PERIOD]->setValue(period); @@ -1090,40 +1005,39 @@ void TimeMeasureModel::measureTime() double period_sum = data[period_start]; double period_sqr_sum = data[period_start] * data[period_start]; - for (size_t i = period_start + 1; i <= period_start + 2 * length; i++) { - size_t idx = period_start + (i % length); + for(size_t i = period_start + 1; i <= period_start + 2 * length; i++) { + size_t idx = period_start + (i % length); cdLow.crossDetectStep(data, idx); cdMid.crossDetectStep(data, idx); cdHigh.crossDetectStep(data, idx); } - for (size_t i = period_start + 1; i <= period_end; i++) { + for(size_t i = period_start + 1; i <= period_end; i++) { period_sum += data[i]; period_sqr_sum += data[i] * data[i]; } - for (int i = 1; i < crossSequence.size(); i++) { + for(int i = 1; i < crossSequence.size(); i++) { CrossPoint &p0 = crossSequence[i - 1]; CrossPoint &p1 = crossSequence[i]; - if ((p1.m_bufIdx == p0.m_bufIdx) && (p1.m_onRising == p0.m_onRising)) { - if ((p0.m_name == "MR" && p1.m_name == "LR") || - (p0.m_name == "HR" && p1.m_name == "MR")) + if((p1.m_bufIdx == p0.m_bufIdx) && (p1.m_onRising == p0.m_onRising)) { + if((p0.m_name == "MR" && p1.m_name == "LR") || (p0.m_name == "HR" && p1.m_name == "MR")) crossSequence.swapItemsAt(i, i - 1); - else if ((p0.m_name == "MF" && p1.m_name == "HF") || - (p0.m_name == "LF" && p1.m_name == "MF")) + else if((p0.m_name == "MF" && p1.m_name == "HF") || + (p0.m_name == "LF" && p1.m_name == "MF")) crossSequence.swapItemsAt(i, i - 1); } } QString sequence = ""; - for (int i = 0; i < crossSequence.size(); i++) + for(int i = 0; i < crossSequence.size(); i++) sequence += crossSequence[i].m_name; QString periodSequence = "LRMRHRHFMFLF"; int pos = sequence.indexOf(periodSequence); - if (pos < 0) { + if(pos < 0) { qDebug() << "Unable to find 2 transitions for each of the 10%, 50%, 90% levels"; } else { pos /= 2; @@ -1134,42 +1048,39 @@ void TimeMeasureModel::measureTime() CrossPoint &midFalling = crossSequence[pos + 4]; CrossPoint &lowFalling = crossSequence[pos + 5]; - //Cycle Mean + // Cycle Mean cycle_mean = period_sum / length; m_measurements[CYCLE_MEAN]->setValue(cycle_mean); - //Cycle RMS + // Cycle RMS cycle_rms = sqrt(period_sqr_sum / length); m_measurements[CYCLE_RMS]->setValue(cycle_rms); - //Area + // Area area = sum * (1 / m_sample_rate); m_measurements[AREA]->setValue(area); - //Cycle Area + // Cycle Area cycle_area = period_sum * (1 / m_sample_rate); m_measurements[CYCLE_AREA]->setValue(cycle_area); // Rise Time - long long rise = (long long)(highRising.m_bufIdx - - lowRising.m_bufIdx); - if (rise < 0) + long long rise = (long long)(highRising.m_bufIdx - lowRising.m_bufIdx); + if(rise < 0) rise += length; rise_time = rise / m_sample_rate; m_measurements[RISE]->setValue(rise_time); // Fall Time - long long fall = (long long)(lowFalling.m_bufIdx - - highFalling.m_bufIdx); - if (fall < 0) + long long fall = (long long)(lowFalling.m_bufIdx - highFalling.m_bufIdx); + if(fall < 0) fall += length; fall_time = fall / m_sample_rate; m_measurements[FALL]->setValue(fall_time); // Positive Width - long long posWidth = (long long)(midFalling.m_bufIdx - - midRising.m_bufIdx); - if (posWidth < 0) + long long posWidth = (long long)(midFalling.m_bufIdx - midRising.m_bufIdx); + if(posWidth < 0) posWidth += length; width_p = posWidth / m_sample_rate; m_measurements[P_WIDTH]->setValue(width_p); @@ -1190,21 +1101,22 @@ void TimeMeasureModel::measureTime() delete m_cross_detect; m_cross_detect = NULL; - } -void SpectralMeasure::measure() { +void SpectralMeasure::measure() +{ clearMeasurements(); - if (!m_buffer || m_buf_length == 0) + if(!m_buffer || m_buf_length == 0) return; measureSpectral(); } -void SpectralMeasure::measureSpectral() { +void SpectralMeasure::measureSpectral() +{ - //TODO - reconsider computation of measurements + // TODO - reconsider computation of measurements double spur, harm_dist, noise, average_noise = 0, signal; SpectralDetection detection(m_buffer, m_buf_length, m_harmonics_number); @@ -1231,66 +1143,29 @@ void SpectralMeasure::measureSpectral() { m_measurements[SFDR]->setValue(sfdr); } -void SpectralMeasure::setMask(std::vector mask) -{ - std::vector m_mask = mask; -} +void SpectralMeasure::setMask(std::vector mask) { std::vector m_mask = mask; } +double MeasureModel::sampleRate() { return m_sample_rate; } -double MeasureModel::sampleRate() -{ - return m_sample_rate; -} +void MeasureModel::setSampleRate(double value) { m_sample_rate = value; } -void MeasureModel::setSampleRate(double value) -{ - m_sample_rate = value; -} +unsigned int MeasureModel::adcBitCount() { return m_adc_bit_count; } -unsigned int MeasureModel::adcBitCount() -{ - return m_adc_bit_count; -} +void MeasureModel::setAdcBitCount(unsigned int val) { m_adc_bit_count = val; } -void MeasureModel::setAdcBitCount(unsigned int val) -{ - m_adc_bit_count = val; -} +double MeasureModel::crossLevel() { return m_cross_level; } -double MeasureModel::crossLevel() -{ - return m_cross_level; -} +void MeasureModel::setCrossLevel(double value) { m_cross_level = value; } -void MeasureModel::setCrossLevel(double value) -{ - m_cross_level = value; -} +double MeasureModel::hysteresisSpan() { return m_hysteresis_span; } -double MeasureModel::hysteresisSpan() -{ - return m_hysteresis_span; -} +void MeasureModel::setHysteresisSpan(double value) { m_hysteresis_span = value; } -void MeasureModel::setHysteresisSpan(double value) -{ - m_hysteresis_span = value; -} +void MeasureModel::setStartIndex(int index) { m_startIndex = index; } +void MeasureModel::setEndIndex(int index) { m_endIndex = index; } -void MeasureModel::setStartIndex(int index) -{ - m_startIndex = index; -} - -void MeasureModel::setEndIndex(int index) -{ - m_endIndex = index; -} - -void MeasureModel::setGatingEnabled(bool enable){ - m_gatingEnabled = enable; -} +void MeasureModel::setGatingEnabled(bool enable) { m_gatingEnabled = enable; } void MeasureModel::clearStats() { @@ -1299,34 +1174,25 @@ void MeasureModel::clearStats() } } +QList> MeasureModel::measurments() { return m_measurements; } -QList> MeasureModel::measurments() -{ - return m_measurements; -} +std::shared_ptr MeasureModel::measurement(int id) { return m_measurements[id]; } -std::shared_ptr MeasureModel::measurement(int id) +std::shared_ptr MeasureModel::measurement(QString str) { - return m_measurements[id]; -} - -std::shared_ptr MeasureModel::measurement(QString str) { for(auto meas : m_measurements) { if(meas->name() == str) return meas; } return nullptr; - } - - int MeasureModel::activeMeasurementsCount() const { int count = 0; - for (int i = 0; i < m_measurements.size(); i++) - if (m_measurements[i]->enabled()) + for(int i = 0; i < m_measurements.size(); i++) + if(m_measurements[i]->enabled()) count++; return count; @@ -1336,40 +1202,33 @@ int MeasureModel::activeMeasurementsCount() const * Class MeasurementData implementation */ -MeasurementData::MeasurementData(const QString& name, axisType axis, - const QString& unit): - m_name(name), - m_value(0), - m_measured(false), - m_enabled(false), - m_unit(unit), - m_unitType(DIMENSIONLESS), - m_axis(axis), - m_statEnabled(false) +MeasurementData::MeasurementData(const QString &name, axisType axis, const QString &unit) + : m_name(name) + , m_value(0) + , m_measured(false) + , m_enabled(false) + , m_unit(unit) + , m_unitType(DIMENSIONLESS) + , m_axis(axis) + , m_statEnabled(false) { - if (unit.isEmpty()) + if(unit.isEmpty()) m_unitType = DIMENSIONLESS; - else if (unit == "%") + else if(unit == "%") m_unitType = PERCENTAGE; - else if (unit.toLower() == "s" || unit.toLower() == "seconds") + else if(unit.toLower() == "s" || unit.toLower() == "seconds") m_unitType = TIME; - else if ((unit.toLower() == "db" || unit.toLower() == "decibels")) + else if((unit.toLower() == "db" || unit.toLower() == "decibels")) m_unitType = DECIBELS; - else if ((unit.toLower() == "dbc" || unit.toLower() == "decibels_to_carrier")) + else if((unit.toLower() == "dbc" || unit.toLower() == "decibels_to_carrier")) m_unitType = DECIBELS_TO_CARRIER; else m_unitType = METRIC; } -QString MeasurementData::name() const -{ - return m_name; -} +QString MeasurementData::name() const { return m_name; } -double MeasurementData::value() const -{ - return m_value; -} +double MeasurementData::value() const { return m_value; } void MeasurementData::setValue(double value) { @@ -1379,45 +1238,21 @@ void MeasurementData::setValue(double value) m_stat.pushNewData(value); } -bool MeasurementData::measured() const -{ - return m_measured; -} +bool MeasurementData::measured() const { return m_measured; } -void MeasurementData::setMeasured(bool state) -{ - m_measured = state; -} +void MeasurementData::setMeasured(bool state) { m_measured = state; } -bool MeasurementData::enabled() const -{ - return m_enabled; -} +bool MeasurementData::enabled() const { return m_enabled; } -void MeasurementData::setEnabled(bool en) -{ - m_enabled = en; -} +void MeasurementData::setEnabled(bool en) { m_enabled = en; } -QString MeasurementData::unit() const -{ - return m_unit; -} +QString MeasurementData::unit() const { return m_unit; } -MeasurementData::unitTypes MeasurementData::unitType() const -{ - return m_unitType; -} +MeasurementData::unitTypes MeasurementData::unitType() const { return m_unitType; } -MeasurementData::axisType MeasurementData::axis() const -{ - return m_axis; -} +MeasurementData::axisType MeasurementData::axis() const { return m_axis; } -bool MeasurementData::statEnabled() const -{ - return m_statEnabled; -} +bool MeasurementData::statEnabled() const { return m_statEnabled; } void MeasurementData::setStatEnabled(bool newStatEnabled) { @@ -1426,40 +1261,33 @@ void MeasurementData::setStatEnabled(bool newStatEnabled) m_stat.clear(); } -void MeasurementData::clearStat() -{ - m_stat.clear(); -} +void MeasurementData::clearStat() { m_stat.clear(); } -Statistic MeasurementData::stat() const -{ - return m_stat; -} +Statistic MeasurementData::stat() const { return m_stat; } /* * Class Statistic implementation */ -Statistic::Statistic(): - m_sum(0), - m_min(0), - m_max(0), - m_dataCount(0), - m_average(0) -{ -} +Statistic::Statistic() + : m_sum(0) + , m_min(0) + , m_max(0) + , m_dataCount(0) + , m_average(0) +{} void Statistic::pushNewData(double data) { m_sum += data; - if (!m_dataCount) { + if(!m_dataCount) { m_min = data; m_max = data; } else { - if (data < m_min) + if(data < m_min) m_min = data; - else if (data > m_max) + else if(data > m_max) m_max = data; } @@ -1476,23 +1304,11 @@ void Statistic::clear() m_average = 0; } -double Statistic::average() const -{ - return m_average; -} +double Statistic::average() const { return m_average; } -double Statistic::min() const -{ - return m_min; -} +double Statistic::min() const { return m_min; } -double Statistic::max() const -{ - return m_max; -} +double Statistic::max() const { return m_max; } -double Statistic::numPushedData() const -{ - return m_dataCount; -} -} +double Statistic::numPushedData() const { return m_dataCount; } +} // namespace scopy::grutil diff --git a/gr-util/src/measurementcontroller.cpp b/gr-util/src/measurementcontroller.cpp index 9f15fbf3da..23cbce1962 100644 --- a/gr-util/src/measurementcontroller.cpp +++ b/gr-util/src/measurementcontroller.cpp @@ -1,18 +1,20 @@ #include "measurementcontroller.h" -#include "measure.h" + #include "gui/widgets/measurementlabel.h" +#include "measure.h" + #include + #include Q_LOGGING_CATEGORY(CAT_MEASUREMENT_CONTROLLER, "MeasurementController"); - namespace scopy::grutil { MeasurementController::MeasurementController(QPen pen, MeasureModel *msr, QObject *parent) - : QObject(parent), - m_measure(msr), - m_pen(pen) + : QObject(parent) + , m_measure(msr) + , m_pen(pen) { connect(m_measure, &MeasureModel::newMeasurementsAvailable, this, [=]() { for(auto lbl : m_measureLabels) { @@ -22,12 +24,10 @@ MeasurementController::MeasurementController(QPen pen, MeasureModel *msr, QObjec auto stat = m_measure->measurement(lbl->name())->stat(); lbl->setValue(stat.average(), stat.min(), stat.max()); } - } ); + }); } -MeasurementController::~MeasurementController() { - -} +MeasurementController::~MeasurementController() {} StatsLabel *MeasurementController::findStatsLabel(QString name) { @@ -49,9 +49,9 @@ MeasurementLabel *MeasurementController::findMeasurementLabel(QString name) return nullptr; } -QWidget* MeasurementController::enableMeasurement(QString name) +QWidget *MeasurementController::enableMeasurement(QString name) { - for( int i = 0; i < m_availableMeasurements.count(); i++) { + for(int i = 0; i < m_availableMeasurements.count(); i++) { auto meas = m_availableMeasurements[i]; if(meas.name == name) { @@ -97,7 +97,7 @@ void MeasurementController::disableMeasurement(QString name) QWidget *MeasurementController::enableStats(QString name) { - for( int i = 0; i < m_availableMeasurements.count(); i++) { + for(int i = 0; i < m_availableMeasurements.count(); i++) { auto meas = m_availableMeasurements[i]; if(meas.name == name) { @@ -143,41 +143,36 @@ void MeasurementController::disableStats(QString name) qInfo() << "Stat " << name << "removed"; } -void MeasurementController::addMeasurement(MeasurementInfo v) -{ - m_availableMeasurements.push_back(v); -} +void MeasurementController::addMeasurement(MeasurementInfo v) { m_availableMeasurements.push_back(v); } -QList MeasurementController::availableMeasurements() const -{ - return m_availableMeasurements; -} +QList MeasurementController::availableMeasurements() const { return m_availableMeasurements; } -TimeChannelMeasurementController::TimeChannelMeasurementController(TimeMeasureModel* msr, QPen m_pen, QObject *parent) - : MeasurementController(m_pen, msr, parent) { - addMeasurement({"Period",":/gui/icons/measurements/period.svg","", "time", "Horizontal"}); - addMeasurement({"Frequency",":/gui/icons/measurements/frequency.svg","Hz", "metric", "Horizontal"}); - addMeasurement({"Min",":/gui/icons/measurements/min.svg","V", "metric", "Vertical"}); - addMeasurement({"Max",":/gui/icons/measurements/max.svg","V", "metric", "Vertical"}); - addMeasurement({"Peak-peak",":/gui/icons/measurements/peak_to_peak.svg","V", "metric", "Vertical"}); - addMeasurement({"Cycle Mean",":/gui/icons/measurements/cycle_mean.svg","V", "metric", "Vertical"}); - addMeasurement({"RMS",":/gui/icons/measurements/rms.svg","V", "metric", "Vertical"}); - addMeasurement({"Cycle RMS",":/gui/icons/measurements/cycle_rms.svg","V", "metric", "Vertical"}); - addMeasurement({"AC RMS",":/gui/icons/measurements/rms.svg","V", "metric", "Vertical"}); - addMeasurement({"Area",":/gui/icons/measurements/area.svg","Vs", "metric", "Vertical"}); - addMeasurement({"Cycle Area",":/gui/icons/measurements/cycle_area.svg","Vs", "metric", "Vertical"}); - addMeasurement({"Low",":/gui/icons/measurements/low.svg","V", "metric", "Vertical"}); - addMeasurement({"High",":/gui/icons/measurements/high.svg","V", "metric", "Vertical"}); - addMeasurement({"Amplitude",":/gui/icons/measurements/amplitude.svg","V", "metric", "Vertical"}); - addMeasurement({"Middle",":/gui/icons/measurements/middle.svg","V", "metric", "Vertical"}); - addMeasurement({"+Over",":/gui/icons/measurements/p_overshoot.svg","%", "metric", "Vertical"}); - addMeasurement({"-Over",":/gui/icons/measurements/n_overshoot.svg","%", "metric", "Vertical"}); - addMeasurement({"Rise",":/gui/icons/measurements/rise_time.svg","s", "metric", "Horizontal"}); - addMeasurement({"Fall",":/gui/icons/measurements/fall_time.svg","s", "metric", "Horizontal"}); - addMeasurement({"+Width",":/gui/icons/measurements/p_width.svg","s", "metric", "Horizontal"}); - addMeasurement({"-Width",":/gui/icons/measurements/n_width.svg","s", "metric", "Horizontal"}); - addMeasurement({"+Duty",":/gui/icons/measurements/p_duty.svg","%", "metric", "Horizontal"}); - addMeasurement({"-Duty",":/gui/icons/measurements/n_duty.svg","%", "metric", "Horizontal"}); +TimeChannelMeasurementController::TimeChannelMeasurementController(TimeMeasureModel *msr, QPen m_pen, QObject *parent) + : MeasurementController(m_pen, msr, parent) +{ + addMeasurement({"Period", ":/gui/icons/measurements/period.svg", "", "time", "Horizontal"}); + addMeasurement({"Frequency", ":/gui/icons/measurements/frequency.svg", "Hz", "metric", "Horizontal"}); + addMeasurement({"Min", ":/gui/icons/measurements/min.svg", "V", "metric", "Vertical"}); + addMeasurement({"Max", ":/gui/icons/measurements/max.svg", "V", "metric", "Vertical"}); + addMeasurement({"Peak-peak", ":/gui/icons/measurements/peak_to_peak.svg", "V", "metric", "Vertical"}); + addMeasurement({"Cycle Mean", ":/gui/icons/measurements/cycle_mean.svg", "V", "metric", "Vertical"}); + addMeasurement({"RMS", ":/gui/icons/measurements/rms.svg", "V", "metric", "Vertical"}); + addMeasurement({"Cycle RMS", ":/gui/icons/measurements/cycle_rms.svg", "V", "metric", "Vertical"}); + addMeasurement({"AC RMS", ":/gui/icons/measurements/rms.svg", "V", "metric", "Vertical"}); + addMeasurement({"Area", ":/gui/icons/measurements/area.svg", "Vs", "metric", "Vertical"}); + addMeasurement({"Cycle Area", ":/gui/icons/measurements/cycle_area.svg", "Vs", "metric", "Vertical"}); + addMeasurement({"Low", ":/gui/icons/measurements/low.svg", "V", "metric", "Vertical"}); + addMeasurement({"High", ":/gui/icons/measurements/high.svg", "V", "metric", "Vertical"}); + addMeasurement({"Amplitude", ":/gui/icons/measurements/amplitude.svg", "V", "metric", "Vertical"}); + addMeasurement({"Middle", ":/gui/icons/measurements/middle.svg", "V", "metric", "Vertical"}); + addMeasurement({"+Over", ":/gui/icons/measurements/p_overshoot.svg", "%", "metric", "Vertical"}); + addMeasurement({"-Over", ":/gui/icons/measurements/n_overshoot.svg", "%", "metric", "Vertical"}); + addMeasurement({"Rise", ":/gui/icons/measurements/rise_time.svg", "s", "metric", "Horizontal"}); + addMeasurement({"Fall", ":/gui/icons/measurements/fall_time.svg", "s", "metric", "Horizontal"}); + addMeasurement({"+Width", ":/gui/icons/measurements/p_width.svg", "s", "metric", "Horizontal"}); + addMeasurement({"-Width", ":/gui/icons/measurements/n_width.svg", "s", "metric", "Horizontal"}); + addMeasurement({"+Duty", ":/gui/icons/measurements/p_duty.svg", "%", "metric", "Horizontal"}); + addMeasurement({"-Duty", ":/gui/icons/measurements/n_duty.svg", "%", "metric", "Horizontal"}); } /* @@ -191,4 +186,4 @@ static const std::map icons_spect = { }; */ -} +} // namespace scopy::grutil diff --git a/gr-util/src/time_sink_f_impl.cc b/gr-util/src/time_sink_f_impl.cc index 714bf5481e..33044cdba5 100644 --- a/gr-util/src/time_sink_f_impl.cc +++ b/gr-util/src/time_sink_f_impl.cc @@ -23,57 +23,56 @@ #include #endif -#include +#include "time_sink_f_impl.h" + #include #include +#include #include -#include -#include "time_sink_f_impl.h" #include +#include + Q_LOGGING_CATEGORY(CAT_TIME_SINK_F, "TimeSink_f"); using namespace gr; namespace scopy { -time_sink_f::sptr -time_sink_f::make(int size, float sampleRate, const std::string &name, - int nconnections ) +time_sink_f::sptr time_sink_f::make(int size, float sampleRate, const std::string &name, int nconnections) { - return gnuradio::get_initial_sptr - (new time_sink_f_impl(size, sampleRate, name, nconnections)); + return gnuradio::get_initial_sptr(new time_sink_f_impl(size, sampleRate, name, nconnections)); } -void time_sink_f_impl::generate_time_axis() { - qInfo(CAT_TIME_SINK_F)<< "Generating x-Axis"; +void time_sink_f_impl::generate_time_axis() +{ + qInfo(CAT_TIME_SINK_F) << "Generating x-Axis"; double timeoffset = 0; m_time.clear(); - for (int i = 0; i <= m_size;i++) { - m_time.push_back(timeoffset + i/m_sampleRate); + for(int i = 0; i <= m_size; i++) { + m_time.push_back(timeoffset + i / m_sampleRate); } } -time_sink_f_impl::time_sink_f_impl(int size, float sampleRate, const std::string &name, int nconnections ) - : sync_block("time_sink_f", - io_signature::make(nconnections, nconnections, sizeof(float)), - io_signature::make(0, 0, 0)), - m_size(size), - m_sampleRate(sampleRate), - m_name(name), - m_nconnections(nconnections), - m_rollingMode(false), - m_workFinished(false), - m_dataUpdated(false) +time_sink_f_impl::time_sink_f_impl(int size, float sampleRate, const std::string &name, int nconnections) + : sync_block("time_sink_f", io_signature::make(nconnections, nconnections, sizeof(float)), + io_signature::make(0, 0, 0)) + , m_size(size) + , m_sampleRate(sampleRate) + , m_name(name) + , m_nconnections(nconnections) + , m_rollingMode(false) + , m_workFinished(false) + , m_dataUpdated(false) { - qInfo(CAT_TIME_SINK_F)<<"ctor"; + qInfo(CAT_TIME_SINK_F) << "ctor"; // reserve memory for n buffers m_data.reserve(nconnections); m_dataTags.reserve(nconnections); m_tags.reserve(nconnections); - for (int i = 0; i < m_nconnections;i++) { + for(int i = 0; i < m_nconnections; i++) { m_buffers.push_back(std::deque()); m_data.push_back(std::vector()); m_localtags.push_back(std::vector()); @@ -83,23 +82,18 @@ time_sink_f_impl::time_sink_f_impl(int size, float sampleRate, const std::string m_data[i].reserve(size); } - m_time.reserve(size+1); + m_time.reserve(size + 1); generate_time_axis(); } -time_sink_f_impl::~time_sink_f_impl() { -qInfo(CAT_TIME_SINK_F)<<"dtor"; -} +time_sink_f_impl::~time_sink_f_impl() { qInfo(CAT_TIME_SINK_F) << "dtor"; } -bool time_sink_f_impl::check_topology(int ninputs, int noutputs) { - return ninputs == m_nconnections; -} +bool time_sink_f_impl::check_topology(int ninputs, int noutputs) { return ninputs == m_nconnections; } -std::string time_sink_f_impl::name() const { - return m_name; -} +std::string time_sink_f_impl::name() const { return m_name; } -void time_sink_f_impl::updateData() { +void time_sink_f_impl::updateData() +{ gr::thread::scoped_lock lock(d_setlock); for(int i = 0; i < m_nconnections; i++) { @@ -112,62 +106,41 @@ void time_sink_f_impl::updateData() { if(!m_computeTags) continue; - for(int j = 0 ;j < m_tags[i].size(); j++) { + for(int j = 0; j < m_tags[i].size(); j++) { PlotTag_t tag; std::stringstream s; s << m_tags[i][j].key << ": " << m_tags[i][j].value; tag.str = QString::fromStdString(s.str()); - qInfo()<<"nitems_read(i)" << nitems_read(i) << "tag.offset" << m_tags[i][j].offset;; + qInfo() << "nitems_read(i)" << nitems_read(i) << "tag.offset" << m_tags[i][j].offset; + ; tag.offset = nitems_read(i) - m_tags[i][j].offset; m_dataTags[i].push_back(tag); } } -// nitems_read(); + // nitems_read(); if(m_workFinished) { m_dataUpdated = true; } } -bool time_sink_f_impl::rollingMode() -{ - return m_rollingMode; -} +bool time_sink_f_impl::rollingMode() { return m_rollingMode; } -void time_sink_f_impl::setRollingMode(bool b) -{ - m_rollingMode = b; -} +void time_sink_f_impl::setRollingMode(bool b) { m_rollingMode = b; } -bool time_sink_f_impl::singleShot() -{ - return m_singleShot; -} +bool time_sink_f_impl::singleShot() { return m_singleShot; } -void time_sink_f_impl::setSingleShot(bool b) -{ - m_singleShot = b; -} +void time_sink_f_impl::setSingleShot(bool b) { m_singleShot = b; } -bool time_sink_f_impl::finishedAcquisition() -{ - return m_workFinished && m_dataUpdated; -} +bool time_sink_f_impl::finishedAcquisition() { return m_workFinished && m_dataUpdated; } -const std::vector &time_sink_f_impl::time() const { - return m_time; -} +const std::vector &time_sink_f_impl::time() const { return m_time; } -const std::vector > &time_sink_f_impl::data() const { - return m_data; -} +const std::vector> &time_sink_f_impl::data() const { return m_data; } -const std::vector > &time_sink_f_impl::tags() const -{ - return m_dataTags; -} +const std::vector> &time_sink_f_impl::tags() const { return m_dataTags; } bool time_sink_f_impl::start() { @@ -176,17 +149,12 @@ bool time_sink_f_impl::start() return true; } -bool time_sink_f_impl::stop() -{ - return true; -} - +bool time_sink_f_impl::stop() { return true; } -int time_sink_f_impl::work(int noutput_items, - gr_vector_const_void_star &input_items, - gr_vector_void_star &output_items) { +int time_sink_f_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) +{ -// qInfo(CAT_TIME_SINK_F)<<"Work"; + // qInfo(CAT_TIME_SINK_F)<<"Work"; gr::thread::scoped_lock lock(d_setlock); // Trigger on BUFFER_START (?) @@ -198,10 +166,10 @@ int time_sink_f_impl::work(int noutput_items, } if(!m_rollingMode) { - for(int i = 0; i < m_nconnections; i++) { + for(int i = 0; i < m_nconnections; i++) { if(m_buffers[i].size() >= m_size) { m_buffers[i].clear(); -// m_tags[i].clear(); + // m_tags[i].clear(); } } } @@ -213,38 +181,32 @@ int time_sink_f_impl::work(int noutput_items, } const float *in; - in = (const float*)input_items[i]; + in = (const float *)input_items[i]; m_buffers[i].push_front(in[j]); } - if(m_computeTags) - { + if(m_computeTags) { m_localtags[i].clear(); - get_tags_in_window(m_localtags[i],i,0,noutput_items); + get_tags_in_window(m_localtags[i], i, 0, noutput_items); m_tags[i].insert(m_tags[i].end(), m_localtags[i].begin(), m_localtags[i].end()); while(m_size < nitems_read(i) - m_tags[i].front().offset) { m_tags[i].pop_front(); } - } } return noutput_items; - } -bool time_sink_f_impl::computeTags() -{ - return m_computeTags; -} +bool time_sink_f_impl::computeTags() { return m_computeTags; } void time_sink_f_impl::setComputeTags(bool newComputeTags) { m_computeTags = newComputeTags; -// for(int i = 0; i < m_nconnections; i++) { -// m_dataTags[i].clear(); -// m_tags[i].clear(); -// m_localtags[i].clear(); -// } + // for(int i = 0; i < m_nconnections; i++) { + // m_dataTags[i].clear(); + // m_tags[i].clear(); + // m_localtags[i].clear(); + // } } -} /* namespace gr */ +} // namespace scopy diff --git a/gr-util/test/CMakeLists.txt b/gr-util/test/CMakeLists.txt index e5d3f517f3..c52a3653d9 100644 --- a/gr-util/test/CMakeLists.txt +++ b/gr-util/test/CMakeLists.txt @@ -2,7 +2,4 @@ cmake_minimum_required(VERSION 3.5) include(ScopyTest) -SETUP_SCOPY_TESTS( -grblocks -) - +setup_scopy_tests(grblocks) diff --git a/gr-util/test/tst_grblocks.cpp b/gr-util/test/tst_grblocks.cpp index f344cea8eb..721f2b91ba 100644 --- a/gr-util/test/tst_grblocks.cpp +++ b/gr-util/test/tst_grblocks.cpp @@ -1,17 +1,19 @@ -#include -#include "gr-util/grtopblock.h" -#include "gr-util/grsignalpath.h" #include "gr-util/grproxyblock.h" -#include +#include "gr-util/grsignalpath.h" +#include "gr-util/grtopblock.h" + #include #include -#include +#include + #include +#include +#include -#include #include #include #include +#include #include #include #include @@ -29,13 +31,15 @@ private Q_SLOTS: // these are tests void test4(); void test5(); -public Q_SLOTS: // these are actual slots +public Q_SLOTS: // these are actual slots void connectVectorSinks(); // return vec sinks - QVector computeSigSourceExpected(gr::analog::gr_waveform_t wave, float ampl, float offset, float sr, float freq, float scale_1, float offset_1); + QVector computeSigSourceExpected(gr::analog::gr_waveform_t wave, float ampl, float offset, float sr, + float freq, float scale_1, float offset_1); private: - void connectVectorSinks(GRTopBlock* top); // return vec sinks - struct test1Params { + void connectVectorSinks(GRTopBlock *top); // return vec sinks + struct test1Params + { const int nr_samples = 100; const float sig_ampl = 2; const float sig_offset = 0; @@ -53,12 +57,14 @@ public Q_SLOTS: // these are actual slots std::vector testOutputs_c; }; -void TST_GRBlocks::connectVectorSinks() { - GRTopBlock* sender = dynamic_cast(QObject::sender()); +void TST_GRBlocks::connectVectorSinks() +{ + GRTopBlock *sender = dynamic_cast(QObject::sender()); connectVectorSinks(sender); } -void TST_GRBlocks::connectVectorSinks(GRTopBlock* top) { +void TST_GRBlocks::connectVectorSinks(GRTopBlock *top) +{ testOutputs.clear(); gr::blocks::head::sptr head; @@ -68,14 +74,14 @@ void TST_GRBlocks::connectVectorSinks(GRTopBlock* top) { std::vector ret; - for( GRSignalPath* path : top->signalPaths()) { + for(GRSignalPath *path : top->signalPaths()) { if(!path->enabled()) continue; gr::basic_block_sptr endpoint = path->getGrEndPoint(); int size = endpoint->output_signature()->sizeof_stream_item(0); if(size == sizeof(float)) { - head = gr::blocks::head::make(size,t1.nr_samples*2-1); + head = gr::blocks::head::make(size, t1.nr_samples * 2 - 1); s2v = gr::blocks::stream_to_vector::make(size, t1.nr_samples); vec = gr::blocks::vector_sink_f::make(t1.nr_samples); @@ -85,7 +91,7 @@ void TST_GRBlocks::connectVectorSinks(GRTopBlock* top) { top->connect(s2v, 0, vec, 0); testOutputs.push_back(vec); } else if(size == sizeof(gr_complex)) { - head = gr::blocks::head::make(size,t1.nr_samples*2-1); + head = gr::blocks::head::make(size, t1.nr_samples * 2 - 1); s2v = gr::blocks::stream_to_vector::make(size, t1.nr_samples); vec_c = gr::blocks::vector_sink_c::make(t1.nr_samples); @@ -94,34 +100,37 @@ void TST_GRBlocks::connectVectorSinks(GRTopBlock* top) { top->connect(s2v, 0, vec_c, 0); testOutputs_c.push_back(vec_c); } - } + } } -QVector TST_GRBlocks::computeSigSourceExpected(gr::analog::gr_waveform_t wave, float ampl, float offset, float sr, float freq, float scale_1, float offset_1) { +QVector TST_GRBlocks::computeSigSourceExpected(gr::analog::gr_waveform_t wave, float ampl, float offset, + float sr, float freq, float scale_1, float offset_1) +{ QVector expected; auto period = int(t1.sig_sr / t1.sig_freq); auto pol_change = period / 2; - for(int i=0;isetFreq(t1.sig_freq); // change parameters after building + sin1->setFreq(t1.sig_freq); // change parameters after building scale_offset->setOffset(t1.offset_1); qInfo() << "modified scale_offset after build"; top.getGrBlock()->run(); // |sig_source| --> |multiply| --> |add| --> |head| --> |stream_to_vector| --> |vector_sink| QCOMPARE(QString::fromStdString(top.getGrBlock()->edge_list()), - QString("multiply_const_ff0:0->add_const_ff0:0\n" // Build order matters for edge_list - "sig_source0:0->multiply_const_ff0:0\n" - "add_const_ff0:0->head0:0\n" - "head0:0->stream_to_vector0:0\n" - "stream_to_vector0:0->vector_sink0:0\n")); - + QString("multiply_const_ff0:0->add_const_ff0:0\n" // Build order matters for edge_list + "sig_source0:0->multiply_const_ff0:0\n" + "add_const_ff0:0->head0:0\n" + "head0:0->stream_to_vector0:0\n" + "stream_to_vector0:0->vector_sink0:0\n")); - QVector expected = computeSigSourceExpected(gr::analog::GR_CONST_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq,t1.scale_1,t1.offset_1); + QVector expected = + computeSigSourceExpected(gr::analog::GR_CONST_WAVE, t1.sig_ampl, t1.sig_offset, t1.sig_sr, + t1.sig_freq, t1.scale_1, t1.offset_1); std::vector data = testOutputs[0]->data(); - QVector res = QVector(data.begin(),data.end()); + QVector res = QVector(data.begin(), data.end()); QCOMPARE(res, expected); } top.teardown(); scale_offset->setEnabled(false); // disabling requires rebuild - should this be handled internally (?) - qInfo()<<"disabled block in signal path"; + qInfo() << "disabled block in signal path"; top.build(); { connectVectorSinks(&top); top.getGrBlock()->run(); // |sig_source| --> |head| --> |stream_to_vector| --> |vector_sink| QCOMPARE(QString::fromStdString(top.getGrBlock()->edge_list()), - QString("sig_source1:0->head1:0\n" - "head1:0->stream_to_vector1:0\n" - "stream_to_vector1:0->vector_sink1:0\n")); - + QString("sig_source1:0->head1:0\n" + "head1:0->stream_to_vector1:0\n" + "stream_to_vector1:0->vector_sink1:0\n")); - QVector expected = computeSigSourceExpected(gr::analog::GR_CONST_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, 1, 0); + QVector expected = computeSigSourceExpected(gr::analog::GR_CONST_WAVE, t1.sig_ampl, + t1.sig_offset, t1.sig_sr, t1.sig_freq, 1, 0); std::vector data = testOutputs[0]->data(); - QVector res = QVector(data.begin(),data.end()); - qDebug()< res = QVector(data.begin(), data.end()); + qDebug() << res; - qDebug()<run(); QCOMPARE(QString::fromStdString(top.getGrBlock()->edge_list()), - QString("multiply_const_ff0:0->add_const_ff0:0\n" - "sig_source0:0->multiply_const_ff0:0\n" - "add_const_ff0:0->head0:0\n" - "head0:0->stream_to_vector0:0\n" - "stream_to_vector0:0->vector_sink0:0\n")); - + QString("multiply_const_ff0:0->add_const_ff0:0\n" + "sig_source0:0->multiply_const_ff0:0\n" + "add_const_ff0:0->head0:0\n" + "head0:0->stream_to_vector0:0\n" + "stream_to_vector0:0->vector_sink0:0\n")); - QVector expected = computeSigSourceExpected(gr::analog::GR_CONST_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, t1.scale_1, t1.offset_1); + QVector expected = + computeSigSourceExpected(gr::analog::GR_CONST_WAVE, t1.sig_ampl, t1.sig_offset, t1.sig_sr, + t1.sig_freq, t1.scale_1, t1.offset_1); std::vector data = testOutputs[0]->data(); - QVector res = QVector(data.begin(),data.end()); + QVector res = QVector(data.begin(), data.end()); QCOMPARE(res, expected); } } -void TST_GRBlocks::test3() { +void TST_GRBlocks::test3() +{ qInfo() << "This testcase verifies if multiple signalpaths work for the same topblock"; GRTopBlock top("aa", this); - GRSignalPath *ch1,*ch2,*ch3; + GRSignalPath *ch1, *ch2, *ch3; GRSignalSrc *sin1, *sin2; GRScaleOffsetProc *scale_offset_1; GRScaleOffsetProc *scale_offset_2; - ch1 = new GRSignalPath("iio1",&top); - ch2 = new GRSignalPath("iio2",&top); - ch3 = new GRSignalPath("iio3",&top); + ch1 = new GRSignalPath("iio1", &top); + ch2 = new GRSignalPath("iio2", &top); + ch3 = new GRSignalPath("iio3", &top); top.registerSignalPath(ch1); top.registerSignalPath(ch2); top.registerSignalPath(ch3); @@ -268,7 +280,6 @@ void TST_GRBlocks::test3() { scale_offset_1 = new GRScaleOffsetProc(ch2); scale_offset_2 = new GRScaleOffsetProc(ch3); - sin1->setWaveform(gr::analog::GR_CONST_WAVE); sin1->setSamplingFreq(t1.sig_sr); sin1->setAmplitude(t1.sig_ampl); @@ -285,7 +296,6 @@ void TST_GRBlocks::test3() { scale_offset_2->setOffset(t1.offset_2); scale_offset_2->setScale(t1.scale_2); - /* |sin1| --+------------------------- - ch1 * +---|scale_offset_1|------ - ch2 * |sin2| ------|scale_offset_2|------ - ch3 @@ -302,36 +312,38 @@ void TST_GRBlocks::test3() { connectVectorSinks(&top); top.getGrBlock()->run(); -// qDebug()<edge_list()); + // qDebug()<edge_list()); QCOMPARE(QString::fromStdString(top.getGrBlock()->edge_list()), - QString("multiply_const_ff0:0->add_const_ff0:0\n" - "sig_source0:0->multiply_const_ff0:0\n" - "multiply_const_ff1:0->add_const_ff1:0\n" - "sig_source1:0->multiply_const_ff1:0\n" - "sig_source0:0->head0:0\n" - "head0:0->stream_to_vector0:0\n" - "stream_to_vector0:0->vector_sink0:0\n" - "add_const_ff0:0->head1:0\n" - "head1:0->stream_to_vector1:0\n" - "stream_to_vector1:0->vector_sink1:0\n" - "add_const_ff1:0->head2:0\n" - "head2:0->stream_to_vector2:0\n" - "stream_to_vector2:0->vector_sink2:0\n")); - + QString("multiply_const_ff0:0->add_const_ff0:0\n" + "sig_source0:0->multiply_const_ff0:0\n" + "multiply_const_ff1:0->add_const_ff1:0\n" + "sig_source1:0->multiply_const_ff1:0\n" + "sig_source0:0->head0:0\n" + "head0:0->stream_to_vector0:0\n" + "stream_to_vector0:0->vector_sink0:0\n" + "add_const_ff0:0->head1:0\n" + "head1:0->stream_to_vector1:0\n" + "stream_to_vector1:0->vector_sink1:0\n" + "add_const_ff1:0->head2:0\n" + "head2:0->stream_to_vector2:0\n" + "stream_to_vector2:0->vector_sink2:0\n")); QVector> expectedAll; // constant no scale / offset block - expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, 1, 0)); + expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE, t1.sig_ampl, t1.sig_offset, + t1.sig_sr, t1.sig_freq, 1, 0)); // constant with scale and offset - expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, t1.scale_1, t1.offset_1)); + expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE, t1.sig_ampl, t1.sig_offset, + t1.sig_sr, t1.sig_freq, t1.scale_1, t1.offset_1)); // third channel square wave - expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_SQR_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, t1.scale_2, t1.offset_2)); + expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_SQR_WAVE, t1.sig_ampl, t1.sig_offset, + t1.sig_sr, t1.sig_freq, t1.scale_2, t1.offset_2)); - for(int i = 0; i < testOutputs.size();i++) { + for(int i = 0; i < testOutputs.size(); i++) { std::vector data = testOutputs[i]->data(); - QVector res = QVector(data.begin(),data.end()); - qDebug()<data(); + QVector res = QVector(data.begin(), data.end()); + qDebug() << expectedAll[i]; + qDebug() << testOutputs[i]->data(); QCOMPARE(res, expectedAll[i]); } } @@ -344,28 +356,29 @@ void TST_GRBlocks::test3() { connectVectorSinks(&top); top.getGrBlock()->run(); QCOMPARE(QString::fromStdString(top.getGrBlock()->edge_list()), - QString("sig_source2:0->head3:0\n" - "head3:0->stream_to_vector3:0\n" - "stream_to_vector3:0->vector_sink3:0\n" - "sig_source3:0->head4:0\n" - "head4:0->stream_to_vector4:0\n" - "stream_to_vector4:0->vector_sink4:0\n")); - + QString("sig_source2:0->head3:0\n" + "head3:0->stream_to_vector3:0\n" + "stream_to_vector3:0->vector_sink3:0\n" + "sig_source3:0->head4:0\n" + "head4:0->stream_to_vector4:0\n" + "stream_to_vector4:0->vector_sink4:0\n")); QVector> expectedAll; // constant no scale / offset block - expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, 1, 0)); + expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE, t1.sig_ampl, t1.sig_offset, + t1.sig_sr, t1.sig_freq, 1, 0)); // constant with scale and offset - expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_SQR_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, 1, 0)); + expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_SQR_WAVE, t1.sig_ampl, t1.sig_offset, + t1.sig_sr, t1.sig_freq, 1, 0)); - for(int i = 0; i < testOutputs.size();i++) { + for(int i = 0; i < testOutputs.size(); i++) { std::vector data = testOutputs[i]->data(); - QVector res = QVector(data.begin(),data.end()); + QVector res = QVector(data.begin(), data.end()); - qDebug()<data(); + qDebug() << expectedAll[i]; + qDebug() << testOutputs[i]->data(); QCOMPARE(res, expectedAll[i]); } @@ -373,11 +386,10 @@ void TST_GRBlocks::test3() { top.teardown(); - - qInfo()<<"This test verifies that a source can be accessed indirectly"; + qInfo() << "This test verifies that a source can be accessed indirectly"; ch1->setEnabled(false); // disable first signal path - ch2->setEnabled(true); // second signal path should use the first source indirectly + ch2->setEnabled(true); // second signal path should use the first source indirectly scale_offset_2->setEnabled(false); top.build(); @@ -386,51 +398,50 @@ void TST_GRBlocks::test3() { connectVectorSinks(&top); top.getGrBlock()->run(); - qDebug()<edge_list()); + qDebug() << QString::fromStdString(top.getGrBlock()->edge_list()); QCOMPARE(QString::fromStdString(top.getGrBlock()->edge_list()), - QString( - "multiply_const_ff0:0->add_const_ff0:0\n" - "sig_source0:0->multiply_const_ff0:0\n" - "add_const_ff0:0->head0:0\n" - "head0:0->stream_to_vector0:0\n" - "stream_to_vector0:0->vector_sink0:0\n" - "sig_source1:0->head1:0\n" - "head1:0->stream_to_vector1:0\n" - "stream_to_vector1:0->vector_sink1:0\n")); - + QString("multiply_const_ff0:0->add_const_ff0:0\n" + "sig_source0:0->multiply_const_ff0:0\n" + "add_const_ff0:0->head0:0\n" + "head0:0->stream_to_vector0:0\n" + "stream_to_vector0:0->vector_sink0:0\n" + "sig_source1:0->head1:0\n" + "head1:0->stream_to_vector1:0\n" + "stream_to_vector1:0->vector_sink1:0\n")); QVector> expectedAll; // constant no scale / offset block - expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, t1.scale_1, t1.offset_1)); + expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE, t1.sig_ampl, t1.sig_offset, + t1.sig_sr, t1.sig_freq, t1.scale_1, t1.offset_1)); // constant with scale and offset - expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_SQR_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, 1, 0)); + expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_SQR_WAVE, t1.sig_ampl, t1.sig_offset, + t1.sig_sr, t1.sig_freq, 1, 0)); - for(int i = 0; i < testOutputs.size();i++) { + for(int i = 0; i < testOutputs.size(); i++) { std::vector data = testOutputs[i]->data(); - QVector res = QVector(data.begin(),data.end()); + QVector res = QVector(data.begin(), data.end()); - qDebug()<data(); + qDebug() << expectedAll[i]; + qDebug() << testOutputs[i]->data(); QCOMPARE(res, expectedAll[i]); } } } - -void TST_GRBlocks::test4() { +void TST_GRBlocks::test4() +{ qInfo() << "This testcase verifies signal emission on building/teardown and how it can be leveraged to build " "sinks on demand"; GRTopBlock top("aa", this); - GRSignalPath *ch1,*ch2,*ch3; + GRSignalPath *ch1, *ch2, *ch3; GRSignalSrc *sin1, *sin2; GRScaleOffsetProc *scale_offset_1; GRScaleOffsetProc *scale_offset_2; - ch1 = new GRSignalPath("iio1", &top); top.registerSignalPath(ch1); ch2 = new GRSignalPath("iio2", &top); @@ -438,14 +449,12 @@ void TST_GRBlocks::test4() { ch3 = new GRSignalPath("iio3", &top); top.registerSignalPath(ch3); - sin1 = new GRSignalSrc(ch1); sin2 = new GRSignalSrc(ch2); scale_offset_1 = new GRScaleOffsetProc(ch2); scale_offset_2 = new GRScaleOffsetProc(ch3); - sin1->setWaveform(gr::analog::GR_CONST_WAVE); sin1->setSamplingFreq(t1.sig_sr); sin1->setAmplitude(t1.sig_ampl); @@ -462,7 +471,6 @@ void TST_GRBlocks::test4() { scale_offset_2->setOffset(t1.offset_2); scale_offset_2->setScale(t1.scale_2); - /* |sin1| --+------------------------- - ch1 * +---|scale_offset_1|------ - ch2 * |sin2| ------|scale_offset_2|------ - ch3 @@ -473,14 +481,14 @@ void TST_GRBlocks::test4() { ch3->append(sin2); ch3->append(scale_offset_2); - connect(&top,SIGNAL(builtSignalPaths()), this, SLOT(connectVectorSinks())); + connect(&top, SIGNAL(builtSignalPaths()), this, SLOT(connectVectorSinks())); top.build(); top.start(); { top.getGrBlock()->wait(); // for testing purposes - qDebug()<edge_list()); + qDebug() << QString::fromStdString(top.getGrBlock()->edge_list()); QCOMPARE(QString::fromStdString(top.getGrBlock()->edge_list()), QString("multiply_const_ff0:0->add_const_ff0:0\n" "sig_source0:0->multiply_const_ff0:0\n" @@ -496,28 +504,30 @@ void TST_GRBlocks::test4() { "head2:0->stream_to_vector2:0\n" "stream_to_vector2:0->vector_sink2:0\n")); - QVector> expectedAll; // constant no scale / offset block - expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, 1, 0)); + expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE, t1.sig_ampl, t1.sig_offset, + t1.sig_sr, t1.sig_freq, 1, 0)); // constant with scale and offset - expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, t1.scale_1, t1.offset_1)); + expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE, t1.sig_ampl, t1.sig_offset, + t1.sig_sr, t1.sig_freq, t1.scale_1, t1.offset_1)); // third channel square wave - expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_SQR_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, t1.scale_2, t1.offset_2)); + expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_SQR_WAVE, t1.sig_ampl, t1.sig_offset, + t1.sig_sr, t1.sig_freq, t1.scale_2, t1.offset_2)); - for(int i = 0; i < testOutputs.size();i++) { + for(int i = 0; i < testOutputs.size(); i++) { std::vector data = testOutputs[i]->data(); - QVector res = QVector(data.begin(),data.end()); - qDebug()<data(); + QVector res = QVector(data.begin(), data.end()); + qDebug() << expectedAll[i]; + qDebug() << testOutputs[i]->data(); QCOMPARE(res, expectedAll[i]); } } - QSignalSpy spy(&top,SIGNAL(builtSignalPaths())); + QSignalSpy spy(&top, SIGNAL(builtSignalPaths())); ch2->setEnabled(false); scale_offset_2->setEnabled(false); - QCOMPARE(spy.count(),2); // flowgraph rebuilt twice + QCOMPARE(spy.count(), 2); // flowgraph rebuilt twice { top.getGrBlock()->wait(); // for testing purposes QCOMPARE(QString::fromStdString(top.getGrBlock()->edge_list()), @@ -528,39 +538,40 @@ void TST_GRBlocks::test4() { "head1:0->stream_to_vector1:0\n" "stream_to_vector1:0->vector_sink1:0\n")); - QVector> expectedAll; // constant no scale / offset block - expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, 1, 0)); + expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE, t1.sig_ampl, t1.sig_offset, + t1.sig_sr, t1.sig_freq, 1, 0)); // constant with scale and offset - expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_SQR_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, 1, 0)); + expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_SQR_WAVE, t1.sig_ampl, t1.sig_offset, + t1.sig_sr, t1.sig_freq, 1, 0)); - for(int i = 0; i < testOutputs.size();i++) { + for(int i = 0; i < testOutputs.size(); i++) { std::vector data = testOutputs[i]->data(); - QVector res = QVector(data.begin(),data.end()); + QVector res = QVector(data.begin(), data.end()); - qDebug()<data(); + qDebug() << expectedAll[i]; + qDebug() << testOutputs[i]->data(); QCOMPARE(res, expectedAll[i]); } } top.stop(); top.teardown(); - QSignalSpy spy2(&top,SIGNAL(builtSignalPaths())); + QSignalSpy spy2(&top, SIGNAL(builtSignalPaths())); ch2->setEnabled(true); scale_offset_2->setEnabled(true); - QCOMPARE(spy2.count(),0); // flowgraph is not rebuilt because it was not built + QCOMPARE(spy2.count(), 0); // flowgraph is not rebuilt because it was not built top.build(); top.start(); - QCOMPARE(spy2.count(),1); // built only once + QCOMPARE(spy2.count(), 1); // built only once { top.getGrBlock()->wait(); // for testing purposes - qDebug()<edge_list()); + qDebug() << QString::fromStdString(top.getGrBlock()->edge_list()); QCOMPARE(QString::fromStdString(top.getGrBlock()->edge_list()), QString("multiply_const_ff0:0->add_const_ff0:0\n" "sig_source0:0->multiply_const_ff0:0\n" @@ -576,32 +587,33 @@ void TST_GRBlocks::test4() { "head2:0->stream_to_vector2:0\n" "stream_to_vector2:0->vector_sink2:0\n")); - QVector> expectedAll; // constant no scale / offset block - expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, 1, 0)); + expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE, t1.sig_ampl, t1.sig_offset, + t1.sig_sr, t1.sig_freq, 1, 0)); // constant with scale and offset - expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, t1.scale_1, t1.offset_1)); + expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_CONST_WAVE, t1.sig_ampl, t1.sig_offset, + t1.sig_sr, t1.sig_freq, t1.scale_1, t1.offset_1)); // third channel square wave - expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_SQR_WAVE,t1.sig_ampl,t1.sig_offset,t1.sig_sr,t1.sig_freq, t1.scale_2, t1.offset_2)); + expectedAll.push_back(computeSigSourceExpected(gr::analog::GR_SQR_WAVE, t1.sig_ampl, t1.sig_offset, + t1.sig_sr, t1.sig_freq, t1.scale_2, t1.offset_2)); - for(int i = 0; i < testOutputs.size();i++) { + for(int i = 0; i < testOutputs.size(); i++) { std::vector data = testOutputs[i]->data(); - QVector res = QVector(data.begin(),data.end()); - qDebug()<data(); + QVector res = QVector(data.begin(), data.end()); + qDebug() << expectedAll[i]; + qDebug() << testOutputs[i]->data(); QCOMPARE(res, expectedAll[i]); } } - - } -void TST_GRBlocks::test5() { +void TST_GRBlocks::test5() +{ qInfo() << "This testcase verifies iio-source"; GRTopBlock top("aa", this); - GRSignalPath *ch1,*ch2; + GRSignalPath *ch1, *ch2; GRSignalPath *ch3; GRIIOFloatChannelSrc *fch1; GRIIOFloatChannelSrc *fch2; @@ -616,69 +628,66 @@ void TST_GRBlocks::test5() { top.registerSignalPath(ch2); ch3 = new GRSignalPath("complex", &top); - - iio_context* ctx = iio_create_context_from_uri("ip:192.168.2.1"); + iio_context *ctx = iio_create_context_from_uri("ip:192.168.2.1"); if(!ctx) { QSKIP("No context. Skipping"); } - dev = new GRIIODeviceSource(ctx,"cf-ad9361-lpc","ad9361-phy",0x400,&top); + dev = new GRIIODeviceSource(ctx, "cf-ad9361-lpc", "ad9361-phy", 0x400, &top); if(!dev) { QSKIP("No pluto. Skipping"); } top.registerIIODeviceSource(dev); - fch1 = new GRIIOFloatChannelSrc(dev,"voltage0", ch1); - fch2 = new GRIIOFloatChannelSrc(dev,"voltage1", ch2); - cch1 = new GRIIOComplexChannelSrc("complex_voltage0/1",dev,"voltage0","voltage1",ch3); + fch1 = new GRIIOFloatChannelSrc(dev, "voltage0", ch1); + fch2 = new GRIIOFloatChannelSrc(dev, "voltage1", ch2); + cch1 = new GRIIOComplexChannelSrc("complex_voltage0/1", dev, "voltage0", "voltage1", ch3); ch1->append(fch1); ch2->append(fch2); ch3->append(cch1); - connect(&top,SIGNAL(builtSignalPaths()), this, SLOT(connectVectorSinks())); + connect(&top, SIGNAL(builtSignalPaths()), this, SLOT(connectVectorSinks())); top.build(); top.start(); - - { // create iio-source (two channel) + { // create iio-source (two channel) top.getGrBlock()->wait(); // for testing purposes - qDebug()<edge_list()); + qDebug() << QString::fromStdString(top.getGrBlock()->edge_list()); QCOMPARE(QString::fromStdString(top.getGrBlock()->edge_list()), - QString("device_source0:0->short_to_float0:0\n" - "device_source0:1->short_to_float1:0\n" - "short_to_float0:0->head0:0\n" - "head0:0->stream_to_vector0:0\n" - "stream_to_vector0:0->vector_sink0:0\n" - "short_to_float1:0->head1:0\n" - "head1:0->stream_to_vector1:0\n" - "stream_to_vector1:0->vector_sink1:0\n")); + QString("device_source0:0->short_to_float0:0\n" + "device_source0:1->short_to_float1:0\n" + "short_to_float0:0->head0:0\n" + "head0:0->stream_to_vector0:0\n" + "stream_to_vector0:0->vector_sink0:0\n" + "short_to_float1:0->head1:0\n" + "head1:0->stream_to_vector1:0\n" + "stream_to_vector1:0->vector_sink1:0\n")); std::vector expectedChannel; expectedChannel.push_back("voltage0"); expectedChannel.push_back("voltage1"); - QCOMPARE(expectedChannel,dev->channelNames()); - qDebug()<data(); + QCOMPARE(expectedChannel, dev->channelNames()); + qDebug() << testOutputs[0]->data(); } ch1->setEnabled(false); - { // create iio-source (one channel) + { // create iio-source (one channel) top.getGrBlock()->wait(); // for testing purposes - qDebug()<edge_list()); + qDebug() << QString::fromStdString(top.getGrBlock()->edge_list()); QCOMPARE(QString::fromStdString(top.getGrBlock()->edge_list()), - QString("device_source0:0->short_to_float0:0\n" - "short_to_float0:0->head0:0\n" - "head0:0->stream_to_vector0:0\n" - "stream_to_vector0:0->vector_sink0:0\n" - )); + QString("device_source0:0->short_to_float0:0\n" + "short_to_float0:0->head0:0\n" + "head0:0->stream_to_vector0:0\n" + "stream_to_vector0:0->vector_sink0:0\n")); std::vector expectedChannel; expectedChannel.push_back("voltage1"); - QCOMPARE(expectedChannel,dev->channelNames()); + QCOMPARE(expectedChannel, dev->channelNames()); - qDebug()<data(); + qDebug() << testOutputs[0]->data(); } top.stop(); top.teardown(); @@ -694,25 +703,25 @@ void TST_GRBlocks::test5() { top.build(); top.start(); - { // create iio-source (two channel - inverted) + { // create iio-source (two channel - inverted) top.getGrBlock()->wait(); // for testing purposes - qDebug()<edge_list()); + qDebug() << QString::fromStdString(top.getGrBlock()->edge_list()); QCOMPARE(QString::fromStdString(top.getGrBlock()->edge_list()), - QString("device_source0:1->short_to_float0:0\n" - "device_source0:0->short_to_float1:0\n" /* inversion occurs here */ - "short_to_float0:0->head0:0\n" - "head0:0->stream_to_vector0:0\n" - "stream_to_vector0:0->vector_sink0:0\n" - "short_to_float1:0->head1:0\n" - "head1:0->stream_to_vector1:0\n" - "stream_to_vector1:0->vector_sink1:0\n")); + QString("device_source0:1->short_to_float0:0\n" + "device_source0:0->short_to_float1:0\n" /* inversion occurs here */ + "short_to_float0:0->head0:0\n" + "head0:0->stream_to_vector0:0\n" + "stream_to_vector0:0->vector_sink0:0\n" + "short_to_float1:0->head1:0\n" + "head1:0->stream_to_vector1:0\n" + "stream_to_vector1:0->vector_sink1:0\n")); std::vector expectedChannel; expectedChannel.push_back("voltage0"); expectedChannel.push_back("voltage1"); - QCOMPARE(expectedChannel,dev->channelNames()); - qDebug()<data(); + QCOMPARE(expectedChannel, dev->channelNames()); + qDebug() << testOutputs[0]->data(); } top.stop(); @@ -723,53 +732,47 @@ void TST_GRBlocks::test5() { top.build(); top.start(); - { // create iio-source (one channel + complex) + { // create iio-source (one channel + complex) top.getGrBlock()->wait(); // for testing purposes - qDebug()<edge_list()); + qDebug() << QString::fromStdString(top.getGrBlock()->edge_list()); QCOMPARE(QString::fromStdString(top.getGrBlock()->edge_list()), - QString("short_to_float1:0->float_to_complex0:0\n" - "short_to_float2:0->float_to_complex0:1\n" - "device_source0:1->short_to_float0:0\n" - "device_source0:0->short_to_float1:0\n" - "device_source0:1->short_to_float2:0\n" - "short_to_float0:0->head0:0\n" - "head0:0->stream_to_vector0:0\n" - "stream_to_vector0:0->vector_sink0:0\n" - "float_to_complex0:0->head1:0\n" - "head1:0->stream_to_vector1:0\n" - "stream_to_vector1:0->vector_sink1:0\n")); + QString("short_to_float1:0->float_to_complex0:0\n" + "short_to_float2:0->float_to_complex0:1\n" + "device_source0:1->short_to_float0:0\n" + "device_source0:0->short_to_float1:0\n" + "device_source0:1->short_to_float2:0\n" + "short_to_float0:0->head0:0\n" + "head0:0->stream_to_vector0:0\n" + "stream_to_vector0:0->vector_sink0:0\n" + "float_to_complex0:0->head1:0\n" + "head1:0->stream_to_vector1:0\n" + "stream_to_vector1:0->vector_sink1:0\n")); std::vector expectedChannel; expectedChannel.push_back("voltage0"); expectedChannel.push_back("voltage1"); - QCOMPARE(expectedChannel,dev->channelNames()); - qDebug()<data(); + QCOMPARE(expectedChannel, dev->channelNames()); + qDebug() << testOutputs[0]->data(); } } - - - // tests: -// figure out lifecycle for build/connect/disconnect/teardown - just getEndPoint - and build if required - all goes recursively (?) - QoL change - not necessary rn +// figure out lifecycle for build/connect/disconnect/teardown - just getEndPoint - and build if required - all goes +// recursively (?) - QoL change - not necessary rn // add more blocks (?) // - dc blocker // - soft trigger // - head - // add math-test // add audio-test // add file-test - QTEST_MAIN(TST_GRBlocks) -//int main() { +// int main() { //} #include "tst_grblocks.moc" - - diff --git a/gui/CMakeLists.txt b/gui/CMakeLists.txt index 52e312f6fb..218078c959 100644 --- a/gui/CMakeLists.txt +++ b/gui/CMakeLists.txt @@ -4,8 +4,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -21,9 +20,25 @@ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) set(CMAKE_CXX_VISIBILITY_PRESET hidden) set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) -FILE(GLOB SRC_LIST src/*.cpp src/widgets/*.cpp src/*.cc src/binding/*.cpp src/prop/*.cpp) -FILE(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp include/${SCOPY_MODULE}/widgets/*.h include/${SCOPY_MODULE}/binding/*.hpp include/${SCOPY_MODULE}/prop/*.hpp) -FILE(GLOB UI_LIST ui/*.ui) +file( + GLOB + SRC_LIST + src/*.cpp + src/widgets/*.cpp + src/*.cc + src/binding/*.cpp + src/prop/*.cpp +) +file( + GLOB + HEADER_LIST + include/${SCOPY_MODULE}/*.h + include/${SCOPY_MODULE}/*.hpp + include/${SCOPY_MODULE}/widgets/*.h + include/${SCOPY_MODULE}/binding/*.hpp + include/${SCOPY_MODULE}/prop/*.hpp +) +file(GLOB UI_LIST ui/*.ui) message(${SRC_LIST}) message(${HEADER_LIST}) @@ -37,14 +52,33 @@ else() find_path( QWT_INCLUDE_DIRS NAMES qwt_global.h - HINTS ${CMAKE_INSTALL_PREFIX}/include /include /usr/local/include /usr/include /opt/local/include /sw/include/usr/local/lib/qwt.framework/Headers - PATH_SUFFIXES qwt-${QWT_QT_VERSION} qwt qwt6 qwt5 ${QWT_QT_VERSION}/qwt - REQUIRED) + HINTS ${CMAKE_INSTALL_PREFIX}/include + /include + /usr/local/include + /usr/include + /opt/local/include + /sw/include/usr/local/lib/qwt.framework/Headers + PATH_SUFFIXES + qwt-${QWT_QT_VERSION} + qwt + qwt6 + qwt5 + ${QWT_QT_VERSION}/qwt + REQUIRED + ) - find_library(QWT_LIBRARIES + find_library( + QWT_LIBRARIES NAMES qwt - HINTS ${CMAKE_INSTALL_PREFIX}/lib /usr/lib /usr/lib64 /usr/local/lib /usr/local/lib64 /opt/local/lib /opt/local/lib64 - REQUIRED) + HINTS ${CMAKE_INSTALL_PREFIX}/lib + /usr/lib + /usr/lib64 + /usr/local/lib + /usr/local/lib64 + /opt/local/lib + /opt/local/lib64 + REQUIRED + ) message("QWT LIBRARIES: " ${QWT_LIBRARIES}) endif() @@ -53,11 +87,7 @@ if(ENABLE_TESTING) add_subdirectory(test) endif() -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} -) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Widgets Xml Svg REQUIRED) option(SCOPY_ENABLE_GR_GUI "Build gnuradio addons for scopy-gui" ON) @@ -75,43 +105,43 @@ add_definitions(-DBOOST_ALL_DYN_LINK) find_package(Boost COMPONENTS system filesystem thread chrono REQUIRED) message(STATUS "Building " ${PROJECT_NAME}) -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} - ${PROJECT_RESOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES} ${PROJECT_RESOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) -configure_file(include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h.cmakein - ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h @ONLY) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) +configure_file( + include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h.cmakein + ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h @ONLY +) -target_include_directories(${PROJECT_NAME} INTERFACE - ${CMAKE_CURRENT_SOURCE_DIR}/include - ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/widgets +target_include_directories( + ${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include + ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/widgets +) +target_include_directories( + ${PROJECT_NAME} + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/ + ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/widgets + scopy-common + scopy-pluginbase + scopy-sigrok-gui ) -target_include_directories(${PROJECT_NAME} PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/ - ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/widgets - scopy-common - scopy-pluginbase - scopy-sigrok-gui - ) -target_include_directories(${PROJECT_NAME} PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE} - ${QWT_INCLUDE_DIRS} - ${Boost_INCLUDE_DIRS} - ) +target_include_directories( + ${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE} ${QWT_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS} +) -target_link_libraries(${PROJECT_NAME} PUBLIC - Qt${QT_VERSION_MAJOR}::Widgets - Qt${QT_VERSION_MAJOR}::Xml - Qt${QT_VERSION_MAJOR}::Svg - ${QWT_LIBRARIES} - ${Boost_LIBRARIES} - scopy-common - scopy-pluginbase +target_link_libraries( + ${PROJECT_NAME} + PUBLIC Qt${QT_VERSION_MAJOR}::Widgets + Qt${QT_VERSION_MAJOR}::Xml + Qt${QT_VERSION_MAJOR}::Svg + ${QWT_LIBRARIES} + ${Boost_LIBRARIES} + scopy-common + scopy-pluginbase ) -install(TARGETS ${PROJECT_NAME} - LIBRARY DESTINATION ${SCOPY_DLL_PATH} - RUNTIME DESTINATION ${SCOPY_DLL_PATH}) +install(TARGETS ${PROJECT_NAME} LIBRARY DESTINATION ${SCOPY_DLL_PATH} RUNTIME DESTINATION ${SCOPY_DLL_PATH}) diff --git a/gui/gr-gui/CMakeLists.txt b/gui/gr-gui/CMakeLists.txt index b75142b05f..facfe8c7aa 100644 --- a/gui/gr-gui/CMakeLists.txt +++ b/gui/gr-gui/CMakeLists.txt @@ -4,8 +4,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -20,55 +19,62 @@ set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_CXX_VISIBILITY_PRESET hidden) set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) -FILE(GLOB SRC_LIST src/*.cpp src/*.cc) -FILE(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp ) -FILE(GLOB UI_LIST ui/*.ui) - -find_package(Gnuradio "3.10" REQUIRED COMPONENTS runtime analog blocks fft filter volk pmt iio) +file(GLOB SRC_LIST src/*.cpp src/*.cc) +file(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) +file(GLOB UI_LIST ui/*.ui) + +find_package( + Gnuradio "3.10" REQUIRED + COMPONENTS runtime + analog + blocks + fft + filter + volk + pmt + iio +) find_package(gnuradio-scopy REQUIRED PATH_SUFFIXES scopy) if(ENABLE_TESTING) - add_subdirectory(test) + add_subdirectory(test) endif() -configure_file(include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h.cmakein - ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h @ONLY) - -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} +configure_file( + include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h.cmakein + ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h @ONLY ) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) + find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Widgets REQUIRED) message(STATUS "Building " ${PROJECT_NAME}) -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) -target_include_directories(${PROJECT_NAME} PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}include/${SCOPY_MODULE}/ - scopy-gui) -target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE} ${QWT_INCLUDE_DIRS}) - -target_link_libraries(${PROJECT_NAME} PUBLIC - ${QWT_LIBRARIES} - Qt${QT_VERSION_MAJOR}::Widgets - scopy-gui - gnuradio::gnuradio-runtime - gnuradio::gnuradio-analog - gnuradio::gnuradio-blocks - gnuradio::gnuradio-fft - gnuradio::gnuradio-filter - gnuradio::gnuradio-pmt - gnuradio::gnuradio-iio - gnuradio::gnuradio-scopy +target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}include/${SCOPY_MODULE}/ scopy-gui) +target_include_directories( + ${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE} ${QWT_INCLUDE_DIRS} +) + +target_link_libraries( + ${PROJECT_NAME} + PUBLIC ${QWT_LIBRARIES} + Qt${QT_VERSION_MAJOR}::Widgets + scopy-gui + gnuradio::gnuradio-runtime + gnuradio::gnuradio-analog + gnuradio::gnuradio-blocks + gnuradio::gnuradio-fft + gnuradio::gnuradio-filter + gnuradio::gnuradio-pmt + gnuradio::gnuradio-iio + gnuradio::gnuradio-scopy ) -install(TARGETS ${PROJECT_NAME} - LIBRARY DESTINATION ${SCOPY_DLL_PATH} - RUNTIME DESTINATION ${SCOPY_DLL_PATH}) \ No newline at end of file +install(TARGETS ${PROJECT_NAME} LIBRARY DESTINATION ${SCOPY_DLL_PATH} RUNTIME DESTINATION ${SCOPY_DLL_PATH}) diff --git a/gui/gr-gui/include/gr-gui/drop_untill_tag_arives.h b/gui/gr-gui/include/gr-gui/drop_untill_tag_arives.h index cb544c15f5..c4012883c9 100644 --- a/gui/gr-gui/include/gr-gui/drop_untill_tag_arives.h +++ b/gui/gr-gui/include/gr-gui/drop_untill_tag_arives.h @@ -25,20 +25,18 @@ class drop_untill_tag_arives : public gr::block { public: - explicit drop_untill_tag_arives(size_t itemsize); - ~drop_untill_tag_arives(); + explicit drop_untill_tag_arives(size_t itemsize); + ~drop_untill_tag_arives(); - void reset(); - void set_buffer_size(unsigned int buffer_size); + void reset(); + void set_buffer_size(unsigned int buffer_size); - int general_work(int noutput_items, - gr_vector_int &ninput_items_, - gr_vector_const_void_star &input_items, - gr_vector_void_star &output_items); + int general_work(int noutput_items, gr_vector_int &ninput_items_, gr_vector_const_void_star &input_items, + gr_vector_void_star &output_items); private: - std::vector d_buffer_size; - std::vector d_copied_items; + std::vector d_buffer_size; + std::vector d_copied_items; }; #endif // DROP_UNTILL_TAG_ARIVES_H diff --git a/gui/gr-gui/include/gr-gui/histogram_sink_f.h b/gui/gr-gui/include/gr-gui/histogram_sink_f.h index d90aa730da..1677817b00 100644 --- a/gui/gr-gui/include/gr-gui/histogram_sink_f.h +++ b/gui/gr-gui/include/gr-gui/histogram_sink_f.h @@ -42,76 +42,74 @@ #ifndef M2K_HISTOGRAM_SINK_F_H #define M2K_HISTOGRAM_SINK_F_H +#include "scopy-gr-gui_export.h" + #include + #include -#include "scopy-gr-gui_export.h" namespace scopy { - /*! - * \brief A graphical sink to display a histogram. - * \ingroup instrumentation_blk - * \ingroup qtgui_blk - * - * \details - * This is a QT-based graphical sink the displays a histogram of - * the data. - * - * This histogram allows you to set and change at runtime the - * number of points to plot at once and the number of bins in the - * histogram. Both x and y-axis have their own auto-scaling - * behavior. By default, auto-scaling the y-axis is turned on and - * continuously updates the y-axis max value based on the - * currently plotted histogram. - * - * The x-axis auto-scaling function only updates once when - * clicked. This resets the x-axis to the current range of minimum - * and maximum values represented in the histogram. It resets any - * values currently displayed because the location and width of - * the bins may have changed. - * - * The histogram also has an accumulate function that simply - * accumulates the data between calls to work. When accumulate is - * activated, the y-axis autoscaling is turned on by default as - * the values will quickly grow in the this direction. - */ - class SCOPY_GR_GUI_EXPORT histogram_sink_f : virtual public gr::sync_block - { - public: - // scopy::histogram_sink_f::sptr - typedef std::shared_ptr sptr; - - /*! - * \brief Build floating point histogram sink - * - * \param size number of points to plot at once - * \param bins number of bins to sort the data into - * \param xmin minimum x-axis value - * \param xmax maximum x-axis value - * \param name title for the plot - * \param nconnections number of signals connected to sink - * \param parent a QWidget parent object, if any - */ - static sptr make(int size, int bins, - double xmin, double xmax, - const std::string &name, - int nconnections=1, - QObject *plot=NULL); +/*! + * \brief A graphical sink to display a histogram. + * \ingroup instrumentation_blk + * \ingroup qtgui_blk + * + * \details + * This is a QT-based graphical sink the displays a histogram of + * the data. + * + * This histogram allows you to set and change at runtime the + * number of points to plot at once and the number of bins in the + * histogram. Both x and y-axis have their own auto-scaling + * behavior. By default, auto-scaling the y-axis is turned on and + * continuously updates the y-axis max value based on the + * currently plotted histogram. + * + * The x-axis auto-scaling function only updates once when + * clicked. This resets the x-axis to the current range of minimum + * and maximum values represented in the histogram. It resets any + * values currently displayed because the location and width of + * the bins may have changed. + * + * The histogram also has an accumulate function that simply + * accumulates the data between calls to work. When accumulate is + * activated, the y-axis autoscaling is turned on by default as + * the values will quickly grow in the this direction. + */ +class SCOPY_GR_GUI_EXPORT histogram_sink_f : virtual public gr::sync_block +{ +public: + // scopy::histogram_sink_f::sptr + typedef std::shared_ptr sptr; - virtual void exec_() = 0; + /*! + * \brief Build floating point histogram sink + * + * \param size number of points to plot at once + * \param bins number of bins to sort the data into + * \param xmin minimum x-axis value + * \param xmax maximum x-axis value + * \param name title for the plot + * \param nconnections number of signals connected to sink + * \param parent a QWidget parent object, if any + */ + static sptr make(int size, int bins, double xmin, double xmax, const std::string &name, int nconnections = 1, + QObject *plot = NULL); - public: + virtual void exec_() = 0; - virtual int nsamps() const = 0; - virtual int bins() const = 0; - virtual void reset() = 0; +public: + virtual int nsamps() const = 0; + virtual int bins() const = 0; + virtual void reset() = 0; - QApplication *d_qApplication; + QApplication *d_qApplication; - virtual void set_update_time(double t) = 0; - virtual void set_nsamps(const int newsize) = 0; - virtual void set_bins(const int bins) = 0; - }; + virtual void set_update_time(double t) = 0; + virtual void set_nsamps(const int newsize) = 0; + virtual void set_bins(const int bins) = 0; +}; } /* namespace scopy */ diff --git a/gui/gr-gui/include/gr-gui/histogram_sink_f_impl.h b/gui/gr-gui/include/gr-gui/histogram_sink_f_impl.h index 2e3288f904..feb0d7db59 100644 --- a/gui/gr-gui/include/gr-gui/histogram_sink_f_impl.h +++ b/gui/gr-gui/include/gr-gui/histogram_sink_f_impl.h @@ -42,56 +42,51 @@ #ifndef M2K_HISTOGRAM_SINK_F_IMPL_H #define M2K_HISTOGRAM_SINK_F_IMPL_H -#include - -#include "histogram_sink_f.h" #include "HistogramDisplayPlot.h" +#include "histogram_sink_f.h" + +#include namespace scopy { - class histogram_sink_f_impl : public histogram_sink_f - { - private: - void initialize(); +class histogram_sink_f_impl : public histogram_sink_f +{ +private: + void initialize(); - int d_size; - int d_bins; - double d_xmin, d_xmax; - std::string d_name; - int d_nconnections; + int d_size; + int d_bins; + double d_xmin, d_xmax; + std::string d_name; + int d_nconnections; - int d_index; - std::vector d_residbufs; + int d_index; + std::vector d_residbufs; - HistogramDisplayPlot *plot; + HistogramDisplayPlot *plot; - gr::high_res_timer_type d_update_time; - gr::high_res_timer_type d_last_time; + gr::high_res_timer_type d_update_time; + gr::high_res_timer_type d_last_time; - public: - histogram_sink_f_impl(int size, int bins, - double xmin, double xmax, - const std::string &name, - int nconnections, - QObject *plot=NULL); - ~histogram_sink_f_impl(); +public: + histogram_sink_f_impl(int size, int bins, double xmin, double xmax, const std::string &name, int nconnections, + QObject *plot = NULL); + ~histogram_sink_f_impl(); - bool check_topology(int ninputs, int noutputs); + bool check_topology(int ninputs, int noutputs); - void exec_(); + void exec_(); - void set_update_time(double t); - void set_nsamps(const int newsize); - void set_bins(const int bins); + void set_update_time(double t); + void set_nsamps(const int newsize); + void set_bins(const int bins); - int nsamps() const; - int bins() const; - void reset(); + int nsamps() const; + int bins() const; + void reset(); - int work(int noutput_items, - gr_vector_const_void_star &input_items, - gr_vector_void_star &output_items); - }; + int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); +}; } /* namespace scopy */ diff --git a/gui/gr-gui/include/gr-gui/math.hpp b/gui/gr-gui/include/gr-gui/math.hpp index a938c88427..a202ba8151 100644 --- a/gui/gr-gui/include/gr-gui/math.hpp +++ b/gui/gr-gui/include/gr-gui/math.hpp @@ -21,42 +21,42 @@ #ifndef SCOPY_MATH_HPP #define SCOPY_MATH_HPP +#include "scopy-gr-gui_export.h" + #include #include -#include "scopy-gr-gui_export.h" namespace Ui { - class Math; +class Math; } namespace scopy { - class SCOPY_GR_GUI_EXPORT Math : public QWidget - { - Q_OBJECT - - public: - explicit Math(QWidget *parent = nullptr, - unsigned int num_inputs = 1); - - public Q_SLOTS: - void setFunction(const QString& function); - - Q_SIGNALS: - void functionValid(const QString& function); - void stateReseted(); - - private Q_SLOTS: - void handleButton(); - void handleMenuButton(QAction *action); - void handleMenuButtonT(QAction *action); - void validateFunction(); - void resetState(); - void delLastChar(); - - private: - Ui::Math *ui; - unsigned int num_inputs; - }; -} +class SCOPY_GR_GUI_EXPORT Math : public QWidget +{ + Q_OBJECT + +public: + explicit Math(QWidget *parent = nullptr, unsigned int num_inputs = 1); + +public Q_SLOTS: + void setFunction(const QString &function); + +Q_SIGNALS: + void functionValid(const QString &function); + void stateReseted(); + +private Q_SLOTS: + void handleButton(); + void handleMenuButton(QAction *action); + void handleMenuButtonT(QAction *action); + void validateFunction(); + void resetState(); + void delLastChar(); + +private: + Ui::Math *ui; + unsigned int num_inputs; +}; +} // namespace scopy #endif /* SCOPY_MATH_HPP */ diff --git a/gui/gr-gui/include/gr-gui/scope_sink_f.h b/gui/gr-gui/include/gr-gui/scope_sink_f.h index 7453f9810d..c65b63d7b9 100644 --- a/gui/gr-gui/include/gr-gui/scope_sink_f.h +++ b/gui/gr-gui/include/gr-gui/scope_sink_f.h @@ -46,41 +46,40 @@ #include #endif +#include "scopy-gr-gui_export.h" #include "trigger_mode.h" + #include + #include -#include "scopy-gr-gui_export.h" namespace scopy { - class SCOPY_GR_GUI_EXPORT scope_sink_f : virtual public gr::sync_block - { - public: - // scopy::scope_sink_f::sptr - typedef std::shared_ptr sptr; +class SCOPY_GR_GUI_EXPORT scope_sink_f : virtual public gr::sync_block +{ +public: + // scopy::scope_sink_f::sptr + typedef std::shared_ptr sptr; - static sptr make(int size, double samp_rate, - const std::string &name, - int nconnections=1, - QObject *plot=NULL); + static sptr make(int size, double samp_rate, const std::string &name, int nconnections = 1, + QObject *plot = NULL); - virtual void exec_() = 0; + virtual void exec_() = 0; - virtual void set_update_time(double t) = 0; - virtual void set_nsamps(const int newsize) = 0; - virtual void set_samp_rate(const double samp_rate) = 0; + virtual void set_update_time(double t) = 0; + virtual void set_nsamps(const int newsize) = 0; + virtual void set_samp_rate(const double samp_rate) = 0; - virtual void set_trigger_mode(trigger_mode mode, int channel, - const std::string &tag_key="") = 0; + virtual void set_trigger_mode(trigger_mode mode, int channel, const std::string &tag_key = "") = 0; - virtual int nsamps() const = 0; - virtual std::string name() const = 0; - virtual void reset() = 0; - virtual void set_displayOneBuffer(bool) = 0; - virtual void clean_buffers() = 0; + virtual int nsamps() const = 0; + virtual std::string name() const = 0; + virtual void reset() = 0; + virtual void set_displayOneBuffer(bool) = 0; + virtual void clean_buffers() = 0; - QApplication *d_qApplication; - }; + QApplication *d_qApplication; +}; } /* namespace scopy */ diff --git a/gui/gr-gui/include/gr-gui/scope_sink_f_impl.h b/gui/gr-gui/include/gr-gui/scope_sink_f_impl.h index f93ca30cb1..b9e75b19bf 100644 --- a/gui/gr-gui/include/gr-gui/scope_sink_f_impl.h +++ b/gui/gr-gui/include/gr-gui/scope_sink_f_impl.h @@ -42,78 +42,71 @@ #ifndef M2K_SCOPE_SINK_F_IMPL_H #define M2K_SCOPE_SINK_F_IMPL_H -#include - -#include "scope_sink_f.h" -#include "TimeDomainDisplayPlot.h" #include "FftDisplayPlot.h" +#include "TimeDomainDisplayPlot.h" +#include "scope_sink_f.h" #include "scopy-gui_export.h" -namespace scopy { +#include - class scope_sink_f_impl : public scope_sink_f - { - private: - void initialize(); +namespace scopy { - int d_size, d_buffer_size; - double d_samp_rate; - std::string d_name; - int d_nconnections; +class scope_sink_f_impl : public scope_sink_f +{ +private: + void initialize(); - int d_index, d_start, d_end; - std::vector d_fbuffers; - std::vector d_buffers; - std::vector< std::vector > d_tags; + int d_size, d_buffer_size; + double d_samp_rate; + std::string d_name; + int d_nconnections; - QObject *plot; + int d_index, d_start, d_end; + std::vector d_fbuffers; + std::vector d_buffers; + std::vector> d_tags; - gr::high_res_timer_type d_update_time; - gr::high_res_timer_type d_last_time; + QObject *plot; - // Members used for triggering scope - trigger_mode d_trigger_mode; - int d_trigger_channel; - pmt::pmt_t d_trigger_tag_key; - bool d_triggered; + gr::high_res_timer_type d_update_time; + gr::high_res_timer_type d_last_time; - bool d_displayOneBuffer; - bool d_cleanBuffers; + // Members used for triggering scope + trigger_mode d_trigger_mode; + int d_trigger_channel; + pmt::pmt_t d_trigger_tag_key; + bool d_triggered; - void _reset(); - void _npoints_resize(); - void _adjust_tags(int adj); - void _test_trigger_tags(int nitems); + bool d_displayOneBuffer; + bool d_cleanBuffers; - public: - scope_sink_f_impl(int size, double samp_rate, - const std::string &name, - int nconnections, - QObject *plot = NULL); - ~scope_sink_f_impl(); + void _reset(); + void _npoints_resize(); + void _adjust_tags(int adj); + void _test_trigger_tags(int nitems); - bool check_topology(int ninputs, int noutputs); +public: + scope_sink_f_impl(int size, double samp_rate, const std::string &name, int nconnections, QObject *plot = NULL); + ~scope_sink_f_impl(); - void exec_(); + bool check_topology(int ninputs, int noutputs); - void set_update_time(double t); - void set_nsamps(const int size); - void set_samp_rate(const double samp_rate); - void set_trigger_mode(trigger_mode mode, int channel, - const std::string &tag_key=""); + void exec_(); - void set_displayOneBuffer(bool); + void set_update_time(double t); + void set_nsamps(const int size); + void set_samp_rate(const double samp_rate); + void set_trigger_mode(trigger_mode mode, int channel, const std::string &tag_key = ""); - int nsamps() const; - std::string name() const; - void reset(); - void clean_buffers(); + void set_displayOneBuffer(bool); + int nsamps() const; + std::string name() const; + void reset(); + void clean_buffers(); - int work(int noutput_items, - gr_vector_const_void_star &input_items, - gr_vector_void_star &output_items); - }; + int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); +}; } /* namespace scopy */ diff --git a/gui/gr-gui/include/gr-gui/waterfall_sink.h b/gui/gr-gui/include/gr-gui/waterfall_sink.h index aeb1d1f91f..a1d4e54e6f 100644 --- a/gui/gr-gui/include/gr-gui/waterfall_sink.h +++ b/gui/gr-gui/include/gr-gui/waterfall_sink.h @@ -47,13 +47,14 @@ #endif #include "WaterfallDisplayPlot.h" +#include "scopy-gr-gui_export.h" #include #include + #include -#include -#include "scopy-gr-gui_export.h" +#include namespace scopy { @@ -63,32 +64,26 @@ class SCOPY_GR_GUI_EXPORT waterfall_sink : virtual public gr::sync_block typedef std::shared_ptr sptr; /*! - * \brief Build a complex number waterfall sink. - * - * \param size size of the FFT to compute and display. If using - * the PDU message port to plot samples, the length of - * each PDU must be a multiple of the FFT size. - * \param wintype type of window to apply (see gr::fft::window::win_type) - * \param fc center frequency of signal (use for x-axis labels) - * \param bw bandwidth of signal (used to set x-axis labels) - * \param name title for the plot - * \param nconnections number of signals to be connected to the - * sink. The PDU message port is always available for a - * connection, and this value must be set to 0 if only - * the PDU message port is being used. - * \param parent a QWidget parent object, if any - */ - static sptr make(int size, - std::vector win, - double fc, - double bw, - const std::string& name, - int nconnections = 1, - WaterfallDisplayPlot* plot = NULL, - bool fft_shift = false); + * \brief Build a complex number waterfall sink. + * + * \param size size of the FFT to compute and display. If using + * the PDU message port to plot samples, the length of + * each PDU must be a multiple of the FFT size. + * \param wintype type of window to apply (see gr::fft::window::win_type) + * \param fc center frequency of signal (use for x-axis labels) + * \param bw bandwidth of signal (used to set x-axis labels) + * \param name title for the plot + * \param nconnections number of signals to be connected to the + * sink. The PDU message port is always available for a + * connection, and this value must be set to 0 if only + * the PDU message port is being used. + * \param parent a QWidget parent object, if any + */ + static sptr make(int size, std::vector win, double fc, double bw, const std::string &name, + int nconnections = 1, WaterfallDisplayPlot *plot = NULL, bool fft_shift = false); virtual void reset() = 0; - virtual QWidget* qwidget() = 0; + virtual QWidget *qwidget() = 0; virtual void clear_data() = 0; @@ -102,14 +97,14 @@ class SCOPY_GR_GUI_EXPORT waterfall_sink : virtual public gr::sync_block virtual void set_intensity_range(const double min, const double max) = 0; virtual void set_update_time(double t) = 0; - virtual void set_line_label(unsigned int which, const std::string& line) = 0; + virtual void set_line_label(unsigned int which, const std::string &line) = 0; virtual void set_line_alpha(unsigned int which, double alpha) = 0; /*! - * Pass "true" to this function to only show the positive half - * of the spectrum. By default, this plotter shows the full - * spectrum (positive and negative halves). - */ + * Pass "true" to this function to only show the positive half + * of the spectrum. By default, this plotter shows the full + * spectrum (positive and negative halves). + */ virtual void set_plot_pos_half(bool half) = 0; virtual double line_alpha(unsigned int which) = 0; @@ -120,9 +115,9 @@ class SCOPY_GR_GUI_EXPORT waterfall_sink : virtual public gr::sync_block virtual double min_intensity(unsigned int which) = 0; virtual double max_intensity(unsigned int which) = 0; virtual void disable_legend() = 0; - virtual void set_trigger_mode(trigger_mode mode, int channel, const std::string &tag_key="") = 0; + virtual void set_trigger_mode(trigger_mode mode, int channel, const std::string &tag_key = "") = 0; - QApplication* d_qApplication; + QApplication *d_qApplication; }; } /* namespace scopy */ diff --git a/gui/gr-gui/include/gr-gui/waterfall_sink_impl.h b/gui/gr-gui/include/gr-gui/waterfall_sink_impl.h index da5880b9c2..b93863a6b9 100644 --- a/gui/gr-gui/include/gr-gui/waterfall_sink_impl.h +++ b/gui/gr-gui/include/gr-gui/waterfall_sink_impl.h @@ -37,6 +37,7 @@ #include #include #include + #include using namespace gr; @@ -45,7 +46,7 @@ namespace scopy { class waterfall_sink_impl : public waterfall_sink { private: - void forecast(int noutput_items, gr_vector_int& ninput_items_required) override; + void forecast(int noutput_items, gr_vector_int &ninput_items_required) override; void initialize(); @@ -68,10 +69,10 @@ class waterfall_sink_impl : public waterfall_sink int d_index, d_start, d_end; - std::vector d_fbuffers; - std::vector d_buffers; + std::vector d_fbuffers; + std::vector d_buffers; - double* d_pdu_magbuf; + double *d_pdu_magbuf; volk::vector d_fbuf; // Required now for Qt; argc must be greater than 0 and argv @@ -80,8 +81,8 @@ class waterfall_sink_impl : public waterfall_sink // http://harmattan-dev.nokia.com/docs/library/html/qt4/qapplication.html char d_zero = 0; int d_argc = 1; - char* d_argv = &d_zero; - WaterfallDisplayPlot* d_main_gui = nullptr; + char *d_argv = &d_zero; + WaterfallDisplayPlot *d_main_gui = nullptr; gr::high_res_timer_type d_update_time; gr::high_res_timer_type d_last_time; @@ -90,14 +91,14 @@ class waterfall_sink_impl : public waterfall_sink void fftresize(); void resize_bufs(int size); void check_clicked(); - void fft(float* data_out, gr_complex* data_in, int size); + void fft(float *data_out, gr_complex *data_in, int size); void _test_trigger_tags(int nitems); void _adjust_tags(int adj); void _reset(); void set_displayOneBuffer(bool val); void clean_buffers(); - std::vector< std::vector > d_tags; + std::vector> d_tags; bool d_displayOneBuffer; bool d_cleanBuffers; @@ -108,21 +109,15 @@ class waterfall_sink_impl : public waterfall_sink pmt::pmt_t d_trigger_tag_key; public: - waterfall_sink_impl(int size, - std::vector win, - double fc, - double bw, - const std::string& name, - int nconnections, - WaterfallDisplayPlot* plot = NULL, - bool fft_shift = false); + waterfall_sink_impl(int size, std::vector win, double fc, double bw, const std::string &name, + int nconnections, WaterfallDisplayPlot *plot = NULL, bool fft_shift = false); ~waterfall_sink_impl(); void reset() override; bool check_topology(int ninputs, int noutputs) override; - QWidget* qwidget() override; + QWidget *qwidget() override; void clear_data() override; @@ -136,7 +131,7 @@ class waterfall_sink_impl : public waterfall_sink void set_update_time(double t) override; void set_time_per_fft(double t) override; - void set_line_label(unsigned int which, const std::string& label) override; + void set_line_label(unsigned int which, const std::string &label) override; void set_line_alpha(unsigned int which, double alpha) override; void set_plot_pos_half(bool half) override; @@ -148,13 +143,11 @@ class waterfall_sink_impl : public waterfall_sink double min_intensity(unsigned int which) override; double max_intensity(unsigned int which) override; - void set_trigger_mode(trigger_mode mode, int channel, const std::string &tag_key="") override; + void set_trigger_mode(trigger_mode mode, int channel, const std::string &tag_key = "") override; void disable_legend() override; - int work(int noutput_items, - gr_vector_const_void_star& input_items, - gr_vector_void_star& output_items) override; + int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) override; }; } /* namespace scopy */ diff --git a/gui/gr-gui/include/gr-gui/xy_sink_c.h b/gui/gr-gui/include/gr-gui/xy_sink_c.h index 8403c54887..5693ebc3ed 100644 --- a/gui/gr-gui/include/gr-gui/xy_sink_c.h +++ b/gui/gr-gui/include/gr-gui/xy_sink_c.h @@ -46,34 +46,33 @@ #include #endif +#include "scopy-gr-gui_export.h" + +#include #include + #include -#include -#include "scopy-gr-gui_export.h" namespace scopy { - class SCOPY_GR_GUI_EXPORT xy_sink_c : virtual public gr::sync_block - { - public: - // gr::qtgui::xy_sink_c::sptr - typedef std::shared_ptr sptr; +class SCOPY_GR_GUI_EXPORT xy_sink_c : virtual public gr::sync_block +{ +public: + // gr::qtgui::xy_sink_c::sptr + typedef std::shared_ptr sptr; - static sptr make(int size, - const std::string &name, - int nconnections=1, - QObject *plot=NULL); + static sptr make(int size, const std::string &name, int nconnections = 1, QObject *plot = NULL); - virtual void exec_() = 0; + virtual void exec_() = 0; - virtual void set_update_time(double t) = 0; - virtual void set_nsamps(const int newsize) = 0; + virtual void set_update_time(double t) = 0; + virtual void set_nsamps(const int newsize) = 0; - virtual int nsamps() const = 0; - virtual void reset() = 0; + virtual int nsamps() const = 0; + virtual void reset() = 0; - QApplication *d_qApplication; - }; + QApplication *d_qApplication; +}; } /* namespace scopy */ diff --git a/gui/gr-gui/include/gr-gui/xy_sink_c_impl.h b/gui/gr-gui/include/gr-gui/xy_sink_c_impl.h index d197848ef5..2ccffe1334 100644 --- a/gui/gr-gui/include/gr-gui/xy_sink_c_impl.h +++ b/gui/gr-gui/include/gr-gui/xy_sink_c_impl.h @@ -42,55 +42,50 @@ #ifndef M2K_XY_SINK_C_IMPL_H #define M2K_XY_SINK_C_IMPL_H -#include - -#include "xy_sink_c.h" #include "ConstellationDisplayPlot.h" +#include "xy_sink_c.h" + +#include namespace scopy { - class xy_sink_c_impl : public xy_sink_c - { - private: - void initialize(); +class xy_sink_c_impl : public xy_sink_c +{ +private: + void initialize(); - int d_size, d_buffer_size; - std::string d_name; - int d_nconnections; + int d_size, d_buffer_size; + std::string d_name; + int d_nconnections; - int d_index, d_start, d_end; - std::vector d_residbufs_real; - std::vector d_residbufs_imag; + int d_index, d_start, d_end; + std::vector d_residbufs_real; + std::vector d_residbufs_imag; - ConstellationDisplayPlot *plot; + ConstellationDisplayPlot *plot; - gr::high_res_timer_type d_update_time; - gr::high_res_timer_type d_last_time; + gr::high_res_timer_type d_update_time; + gr::high_res_timer_type d_last_time; - void _reset(); - void _npoints_resize(); + void _reset(); + void _npoints_resize(); - public: - xy_sink_c_impl(int size, - const std::string &name, - int nconnections, - QObject *plot=NULL); - ~xy_sink_c_impl(); +public: + xy_sink_c_impl(int size, const std::string &name, int nconnections, QObject *plot = NULL); + ~xy_sink_c_impl(); - bool check_topology(int ninputs, int noutputs); + bool check_topology(int ninputs, int noutputs); - void exec_(); + void exec_(); - void set_update_time(double t); - void set_nsamps(const int size); + void set_update_time(double t); + void set_nsamps(const int size); - int nsamps() const; - void reset(); + int nsamps() const; + void reset(); - int work(int noutput_items, - gr_vector_const_void_star &input_items, - gr_vector_void_star &output_items); - }; + int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); +}; } /* namespace scopy */ diff --git a/gui/gr-gui/src/drop_untill_tag_arives.cpp b/gui/gr-gui/src/drop_untill_tag_arives.cpp index 7f83360f31..93260405ca 100644 --- a/gui/gr-gui/src/drop_untill_tag_arives.cpp +++ b/gui/gr-gui/src/drop_untill_tag_arives.cpp @@ -19,67 +19,61 @@ */ #include "drop_untill_tag_arives.h" -drop_untill_tag_arives::drop_untill_tag_arives(size_t itemsize): - block("drop_untill_tags_arive", - gr::io_signature::make(1, 2, itemsize), - gr::io_signature::make(1, 2, itemsize)) +drop_untill_tag_arives::drop_untill_tag_arives(size_t itemsize) + : block("drop_untill_tags_arive", gr::io_signature::make(1, 2, itemsize), + gr::io_signature::make(1, 2, itemsize)) { /* By default there is no reason to further propagate tags */ set_tag_propagation_policy(TPP_DONT); d_copied_items.resize(2); // BAD - d_buffer_size.resize(2); // BAD + d_buffer_size.resize(2); // BAD - for (size_t i = 0; i < d_copied_items.size(); ++i) { + for(size_t i = 0; i < d_copied_items.size(); ++i) { d_copied_items[i] = 0; } } -drop_untill_tag_arives::~drop_untill_tag_arives() -{ - -} +drop_untill_tag_arives::~drop_untill_tag_arives() {} void drop_untill_tag_arives::reset() { - for (size_t i = 0; i < d_copied_items.size(); ++i) { + for(size_t i = 0; i < d_copied_items.size(); ++i) { d_copied_items[i] = 0; } } void drop_untill_tag_arives::set_buffer_size(unsigned int buffer_size) { - for (size_t i = 0; i < d_buffer_size.size(); ++i) { + for(size_t i = 0; i < d_buffer_size.size(); ++i) { d_buffer_size[i] = buffer_size; } } -int drop_untill_tag_arives::general_work(int noutput_items, - gr_vector_int &ninput_items_, - gr_vector_const_void_star &input_items, - gr_vector_void_star &output_items) +int drop_untill_tag_arives::general_work(int noutput_items, gr_vector_int &ninput_items_, + gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int processed_items = 0; - for (size_t i = 0; i < ninput_items_.size(); ++i) { -// std::cout << "Channel : " << i << std::endl; + for(size_t i = 0; i < ninput_items_.size(); ++i) { + // std::cout << "Channel : " << i << std::endl; - const float *in = static_cast(input_items[i]); - float *out = static_cast(output_items[i]); + const float *in = static_cast(input_items[i]); + float *out = static_cast(output_items[i]); int ninput_items = (int)std::min((int)d_buffer_size[i] - (int)d_copied_items[i], noutput_items); processed_items = ninput_items; - if (d_copied_items[i] >= d_buffer_size[i]) { + if(d_copied_items[i] >= d_buffer_size[i]) { bool stopFlowgraph = true; - for (size_t j = 0; j < d_copied_items.size(); ++j) { - if (d_copied_items[j] < d_buffer_size[j]) { + for(size_t j = 0; j < d_copied_items.size(); ++j) { + if(d_copied_items[j] < d_buffer_size[j]) { stopFlowgraph = false; } } - if (stopFlowgraph) { + if(stopFlowgraph) { consume(i, ninput_items); return -1; } else { @@ -88,17 +82,17 @@ int drop_untill_tag_arives::general_work(int noutput_items, } } -// // Get tags in range and print each tag key value pairs + index in buffer -// std::vector tags; -// uint64_t nr = nitems_read(i); -// get_tags_in_range(tags, i, nr, nr + noutput_items + 1); - -// if (tags.size()) { -// std::cout << "No of tags: " << tags.size() << " value: " << tags[0].offset -// << " Interval: " << nr << " - " << nr + noutput_items + 1 << std::endl; -// } else { -// std::cout << " Interval: " << nr << " - " << nr + noutput_items + 1 << std::endl; -// } + // // Get tags in range and print each tag key value pairs + index in buffer + // std::vector tags; + // uint64_t nr = nitems_read(i); + // get_tags_in_range(tags, i, nr, nr + noutput_items + 1); + + // if (tags.size()) { + // std::cout << "No of tags: " << tags.size() << " value: " << tags[0].offset + // << " Interval: " << nr << " - " << nr + noutput_items + 1 << + // std::endl; } else { std::cout << " Interval: " << nr << " - " << nr + // + noutput_items + 1 << std::endl; + // } // Copy in to out for now untill counter for this channel reached memcpy(out, in, sizeof(float) * ninput_items); diff --git a/gui/gr-gui/src/histogram_sink_f_impl.cc b/gui/gr-gui/src/histogram_sink_f_impl.cc index 9c8a40acbc..f9244fb5d0 100644 --- a/gui/gr-gui/src/histogram_sink_f_impl.cc +++ b/gui/gr-gui/src/histogram_sink_f_impl.cc @@ -45,198 +45,160 @@ #include "histogram_sink_f_impl.h" -#include - #include #include + +#include + +#include #include #include -#include using namespace gr; namespace scopy { - histogram_sink_f::sptr - histogram_sink_f::make(int size, int bins, - double xmin, double xmax, - const std::string &name, - int nconnections, - QObject *plot) - { - return gnuradio::get_initial_sptr - (new histogram_sink_f_impl(size, bins, xmin, xmax, name, - nconnections, plot)); - } - - histogram_sink_f_impl::histogram_sink_f_impl(int size, int bins, - double xmin, double xmax, - const std::string &name, - int nconnections, - QObject *plot) - : sync_block("histogram_sink_f", - io_signature::make(nconnections, nconnections, sizeof(float)), - io_signature::make(0, 0, 0)), - d_size(size), d_bins(bins), d_xmin(xmin), d_xmax(xmax), d_name(name), - d_nconnections(nconnections) - { - d_index = 0; - - for(int i = 0; i < d_nconnections; i++) { - d_residbufs.push_back((double*)volk_malloc(d_size*sizeof(double), - volk_get_alignment())); - memset(d_residbufs[i], 0, d_size*sizeof(double)); - } - - // Set alignment properties for VOLK - const int alignment_multiple = - volk_get_alignment() / sizeof(gr_complex); - set_alignment(std::max(1,alignment_multiple)); - - this->plot = (HistogramDisplayPlot*)plot; - initialize(); - } - - histogram_sink_f_impl::~histogram_sink_f_impl() - { - for(int i = 0; i < d_nconnections; i++) { - volk_free(d_residbufs[i]); - } - } - - bool - histogram_sink_f_impl::check_topology(int ninputs, int noutputs) - { - return ninputs == d_nconnections; - } - - void - histogram_sink_f_impl::initialize() - { - d_qApplication = NULL; - if(qApp != NULL) { - d_qApplication = qApp; - } - set_update_time(1/60.0); - - plot->setNumBins(d_bins); - plot->setXaxis(d_xmin, d_xmax); - - } - - void - histogram_sink_f_impl::exec_() - { - d_qApplication->exec(); - } - - void - histogram_sink_f_impl::set_update_time(double t) - { - //convert update time to ticks - gr::high_res_timer_type tps = gr::high_res_timer_tps(); - d_update_time = t * tps; - d_last_time = 0; - } - - void - histogram_sink_f_impl::set_nsamps(const int newsize) - { - gr::thread::scoped_lock lock(d_setlock); - - if(newsize != d_size) { - // Resize residbuf and replace data +histogram_sink_f::sptr histogram_sink_f::make(int size, int bins, double xmin, double xmax, const std::string &name, + int nconnections, QObject *plot) +{ + return gnuradio::get_initial_sptr(new histogram_sink_f_impl(size, bins, xmin, xmax, name, nconnections, plot)); +} + +histogram_sink_f_impl::histogram_sink_f_impl(int size, int bins, double xmin, double xmax, const std::string &name, + int nconnections, QObject *plot) + : sync_block("histogram_sink_f", io_signature::make(nconnections, nconnections, sizeof(float)), + io_signature::make(0, 0, 0)) + , d_size(size) + , d_bins(bins) + , d_xmin(xmin) + , d_xmax(xmax) + , d_name(name) + , d_nconnections(nconnections) +{ + d_index = 0; + for(int i = 0; i < d_nconnections; i++) { - volk_free(d_residbufs[i]); - d_residbufs[i] = (double*)volk_malloc(newsize*sizeof(double), - volk_get_alignment()); + d_residbufs.push_back((double *)volk_malloc(d_size * sizeof(double), volk_get_alignment())); + memset(d_residbufs[i], 0, d_size * sizeof(double)); + } + + // Set alignment properties for VOLK + const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); + set_alignment(std::max(1, alignment_multiple)); + + this->plot = (HistogramDisplayPlot *)plot; + initialize(); +} - memset(d_residbufs[i], 0, newsize*sizeof(double)); +histogram_sink_f_impl::~histogram_sink_f_impl() +{ + for(int i = 0; i < d_nconnections; i++) { + volk_free(d_residbufs[i]); } +} - // Set new size and reset buffer index - // (throws away any currently held data, but who cares?) - d_size = newsize; - d_index = 0; +bool histogram_sink_f_impl::check_topology(int ninputs, int noutputs) { return ninputs == d_nconnections; } - } - plot->setDataInterval(0, d_size); - } - - void - histogram_sink_f_impl::set_bins(const int bins) - { - gr::thread::scoped_lock lock(d_setlock); - d_bins = bins; - plot->setNumBins(d_bins); - } - - int - histogram_sink_f_impl::nsamps() const - { - return d_size; - } - - int - histogram_sink_f_impl::bins() const - { - return d_bins; - } - - void - histogram_sink_f_impl::reset() - { - d_index = 0; - } - - int - histogram_sink_f_impl::work(int noutput_items, - gr_vector_const_void_star &input_items, - gr_vector_void_star &output_items) - { - int n=0, j=0, idx=0; - const float *in = (const float*)input_items[idx]; - - for(int i=0; i < noutput_items; i+=d_size) { - unsigned int datasize = noutput_items - i; - unsigned int resid = d_size-d_index; - idx = 0; - - // If we have enough input for one full plot, do it - if(datasize >= resid) { - - // Fill up residbufs with d_size number of items - for(n = 0; n < d_nconnections; n++) { - in = (const float*)input_items[idx++]; - volk_32f_convert_64f_u(&d_residbufs[n][d_index], - &in[j], resid); - } - - // Update the plot if its time - if(gr::high_res_timer_now() - d_last_time > d_update_time) { - d_last_time = gr::high_res_timer_now(); - if (d_qApplication) - d_qApplication->postEvent(this->plot, - new HistogramUpdateEvent(d_residbufs, d_size)); - } - - d_index = 0; - j += resid; +void histogram_sink_f_impl::initialize() +{ + d_qApplication = NULL; + if(qApp != NULL) { + d_qApplication = qApp; + } + set_update_time(1 / 60.0); + + plot->setNumBins(d_bins); + plot->setXaxis(d_xmin, d_xmax); +} + +void histogram_sink_f_impl::exec_() { d_qApplication->exec(); } + +void histogram_sink_f_impl::set_update_time(double t) +{ + // convert update time to ticks + gr::high_res_timer_type tps = gr::high_res_timer_tps(); + d_update_time = t * tps; + d_last_time = 0; +} + +void histogram_sink_f_impl::set_nsamps(const int newsize) +{ + gr::thread::scoped_lock lock(d_setlock); + + if(newsize != d_size) { + // Resize residbuf and replace data + for(int i = 0; i < d_nconnections; i++) { + volk_free(d_residbufs[i]); + d_residbufs[i] = (double *)volk_malloc(newsize * sizeof(double), volk_get_alignment()); + + memset(d_residbufs[i], 0, newsize * sizeof(double)); + } + + // Set new size and reset buffer index + // (throws away any currently held data, but who cares?) + d_size = newsize; + d_index = 0; } - // Otherwise, copy what we received into the residbufs for next time - // because we set the output_multiple, this should never need to be called - else { - for(n = 0; n < d_nconnections; n++) { - in = (const float*)input_items[idx++]; - volk_32f_convert_64f_u(&d_residbufs[n][d_index], - &in[j], datasize); - } - d_index += datasize; - j += datasize; + plot->setDataInterval(0, d_size); +} + +void histogram_sink_f_impl::set_bins(const int bins) +{ + gr::thread::scoped_lock lock(d_setlock); + d_bins = bins; + plot->setNumBins(d_bins); +} + +int histogram_sink_f_impl::nsamps() const { return d_size; } + +int histogram_sink_f_impl::bins() const { return d_bins; } + +void histogram_sink_f_impl::reset() { d_index = 0; } + +int histogram_sink_f_impl::work(int noutput_items, gr_vector_const_void_star &input_items, + gr_vector_void_star &output_items) +{ + int n = 0, j = 0, idx = 0; + const float *in = (const float *)input_items[idx]; + + for(int i = 0; i < noutput_items; i += d_size) { + unsigned int datasize = noutput_items - i; + unsigned int resid = d_size - d_index; + idx = 0; + + // If we have enough input for one full plot, do it + if(datasize >= resid) { + + // Fill up residbufs with d_size number of items + for(n = 0; n < d_nconnections; n++) { + in = (const float *)input_items[idx++]; + volk_32f_convert_64f_u(&d_residbufs[n][d_index], &in[j], resid); + } + + // Update the plot if its time + if(gr::high_res_timer_now() - d_last_time > d_update_time) { + d_last_time = gr::high_res_timer_now(); + if(d_qApplication) + d_qApplication->postEvent(this->plot, + new HistogramUpdateEvent(d_residbufs, d_size)); + } + + d_index = 0; + j += resid; + } + // Otherwise, copy what we received into the residbufs for next time + // because we set the output_multiple, this should never need to be called + else { + for(n = 0; n < d_nconnections; n++) { + in = (const float *)input_items[idx++]; + volk_32f_convert_64f_u(&d_residbufs[n][d_index], &in[j], datasize); + } + d_index += datasize; + j += datasize; + } } - } - return j; - } + return j; +} } /* namespace scopy */ diff --git a/gui/gr-gui/src/math.cpp b/gui/gr-gui/src/math.cpp index d642e12f55..135ceacec8 100644 --- a/gui/gr-gui/src/math.cpp +++ b/gui/gr-gui/src/math.cpp @@ -18,22 +18,25 @@ * along with this program. If not, see . */ +#include "math.hpp" + #include "dynamicWidget.h" + #include "ui_math.h" -#include "math.hpp" +#include #include #include -#include - using namespace scopy; -Math::Math(QWidget *parent, unsigned int num_inputs) : QWidget(parent), - num_inputs(num_inputs), ui(new Ui::Math) +Math::Math(QWidget *parent, unsigned int num_inputs) + : QWidget(parent) + , num_inputs(num_inputs) + , ui(new Ui::Math) { - if (num_inputs == 0) + if(num_inputs == 0) throw std::runtime_error("Math widget used with zero inputs"); ui->setupUi(this); @@ -66,15 +69,14 @@ Math::Math(QWidget *parent, unsigned int num_inputs) : QWidget(parent), menuExp->addAction("sqrt"); ui->btnExp->setMenu(menuExp); - if (num_inputs > 1) { + if(num_inputs > 1) { QMenu *menuT = new QMenu(ui->btnT); - for (unsigned int i = 0; i < num_inputs; i++) + for(unsigned int i = 0; i < num_inputs; i++) menuT->addAction(QString("t%1").arg(i)); ui->btnT->setMenu(menuT); - connect(menuT, SIGNAL(triggered(QAction *)), - this, SLOT(handleMenuButtonT(QAction *))); + connect(menuT, SIGNAL(triggered(QAction *)), this, SLOT(handleMenuButtonT(QAction *))); } else { ui->btnT->setProperty("token", QVariant("t")); connect(ui->btnT, SIGNAL(clicked()), this, SLOT(handleButton())); @@ -126,26 +128,19 @@ Math::Math(QWidget *parent, unsigned int num_inputs) : QWidget(parent), connect(ui->btnDiv, SIGNAL(clicked()), this, SLOT(handleButton())); connect(ui->btnPow, SIGNAL(clicked()), this, SLOT(handleButton())); - connect(menuCos, SIGNAL(triggered(QAction *)), - this, SLOT(handleMenuButton(QAction *))); - connect(menuSin, SIGNAL(triggered(QAction *)), - this, SLOT(handleMenuButton(QAction *))); - connect(menuTan, SIGNAL(triggered(QAction *)), - this, SLOT(handleMenuButton(QAction *))); - connect(menuLog, SIGNAL(triggered(QAction *)), - this, SLOT(handleMenuButton(QAction *))); - connect(menuExp, SIGNAL(triggered(QAction *)), - this, SLOT(handleMenuButton(QAction *))); + connect(menuCos, SIGNAL(triggered(QAction *)), this, SLOT(handleMenuButton(QAction *))); + connect(menuSin, SIGNAL(triggered(QAction *)), this, SLOT(handleMenuButton(QAction *))); + connect(menuTan, SIGNAL(triggered(QAction *)), this, SLOT(handleMenuButton(QAction *))); + connect(menuLog, SIGNAL(triggered(QAction *)), this, SLOT(handleMenuButton(QAction *))); + connect(menuExp, SIGNAL(triggered(QAction *)), this, SLOT(handleMenuButton(QAction *))); connect(ui->btnClear, SIGNAL(clicked()), ui->function, SLOT(clear())); connect(ui->btnBackspace, SIGNAL(clicked()), this, SLOT(delLastChar())); connect(ui->btnApply, SIGNAL(clicked()), this, SLOT(validateFunction())); - connect(ui->function, SIGNAL(returnPressed()), - this, SLOT(validateFunction())); + connect(ui->function, SIGNAL(returnPressed()), this, SLOT(validateFunction())); - connect(ui->function, SIGNAL(textChanged(const QString&)), - this, SLOT(resetState())); + connect(ui->function, SIGNAL(textChanged(const QString &)), this, SLOT(resetState())); } void Math::handleButton() @@ -156,15 +151,9 @@ void Math::handleButton() ui->function->insert(token); } -void Math::handleMenuButton(QAction *action) -{ - ui->function->insert(action->text() + "("); -} +void Math::handleMenuButton(QAction *action) { ui->function->insert(action->text() + "("); } -void Math::handleMenuButtonT(QAction *action) -{ - ui->function->insert(action->text()); -} +void Math::handleMenuButtonT(QAction *action) { ui->function->insert(action->text()); } void Math::validateFunction() { @@ -177,7 +166,7 @@ void Math::validateFunction() setDynamicProperty(ui->function, "valid", true); setDynamicProperty(ui->btnApply, "valid", true); - } catch (std::exception ex) { + } catch(std::exception ex) { setDynamicProperty(ui->function, "invalid", true); setDynamicProperty(ui->btnApply, "invalid", true); } @@ -193,14 +182,8 @@ void Math::resetState() Q_EMIT stateReseted(); } -void Math::setFunction(const QString& function) -{ - ui->function->setText(function); -} +void Math::setFunction(const QString &function) { ui->function->setText(function); } -void Math::delLastChar() -{ - ui->function->backspace(); -} +void Math::delLastChar() { ui->function->backspace(); } #include "moc_math.cpp" diff --git a/gui/gr-gui/src/scope_sink_f_impl.cc b/gui/gr-gui/src/scope_sink_f_impl.cc index b8121be388..2ea5e8a112 100644 --- a/gui/gr-gui/src/scope_sink_f_impl.cc +++ b/gui/gr-gui/src/scope_sink_f_impl.cc @@ -44,72 +44,69 @@ #include #endif -#include +#include "scope_sink_f_impl.h" + #include #include -#include -#include -#include #include +#include +#include + #include -#include "scope_sink_f_impl.h" +#include +#include using namespace gr; namespace scopy { -scope_sink_f::sptr -scope_sink_f::make(int size, double samp_rate, - const std::string &name, - int nconnections, - QObject *plot) +scope_sink_f::sptr scope_sink_f::make(int size, double samp_rate, const std::string &name, int nconnections, + QObject *plot) { - return gnuradio::get_initial_sptr - (new scope_sink_f_impl(size, samp_rate, name, nconnections, plot)); + return gnuradio::get_initial_sptr(new scope_sink_f_impl(size, samp_rate, name, nconnections, plot)); } -scope_sink_f_impl::scope_sink_f_impl(int size, double samp_rate, - const std::string &name, - int nconnections, +scope_sink_f_impl::scope_sink_f_impl(int size, double samp_rate, const std::string &name, int nconnections, QObject *plot) - : sync_block("scope_sink_f", - io_signature::make(nconnections, nconnections, sizeof(float)), - io_signature::make(0, 0, 0)), - d_size(size), d_buffer_size(2*size), d_samp_rate(samp_rate), d_name(name), - d_nconnections(nconnections), d_index(0), d_start(0), d_end(size) + : sync_block("scope_sink_f", io_signature::make(nconnections, nconnections, sizeof(float)), + io_signature::make(0, 0, 0)) + , d_size(size) + , d_buffer_size(2 * size) + , d_samp_rate(samp_rate) + , d_name(name) + , d_nconnections(nconnections) + , d_index(0) + , d_start(0) + , d_end(size) { - for(int n = 0; n < d_nconnections; n++) { - d_buffers.push_back((double*)volk_malloc(d_buffer_size*sizeof(double), - volk_get_alignment())); - memset(d_buffers[n], 0, d_buffer_size*sizeof(double)); + d_buffers.push_back((double *)volk_malloc(d_buffer_size * sizeof(double), volk_get_alignment())); + memset(d_buffers[n], 0, d_buffer_size * sizeof(double)); - d_fbuffers.push_back((float*)volk_malloc(d_buffer_size*sizeof(float), - volk_get_alignment())); - memset(d_fbuffers[n], 0, d_buffer_size*sizeof(float)); + d_fbuffers.push_back((float *)volk_malloc(d_buffer_size * sizeof(float), volk_get_alignment())); + memset(d_fbuffers[n], 0, d_buffer_size * sizeof(float)); d_displayOneBuffer = true; d_cleanBuffers = true; } // Set alignment properties for VOLK - const int alignment_multiple = - volk_get_alignment() / sizeof(float); - set_alignment(std::max(1,alignment_multiple)); + const int alignment_multiple = volk_get_alignment() / sizeof(float); + set_alignment(std::max(1, alignment_multiple)); - d_tags = std::vector< std::vector >(d_nconnections); + d_tags = std::vector>(d_nconnections); initialize(); this->plot = plot; auto time_plot = dynamic_cast(plot); - if (time_plot) + if(time_plot) time_plot->setSampleRate(samp_rate, 1, ""); auto freq_plot = dynamic_cast(plot); - if (freq_plot) + if(freq_plot) freq_plot->setSampleRate(samp_rate, 1, ""); set_trigger_mode(TRIG_MODE_FREE, 0); @@ -123,14 +120,9 @@ scope_sink_f_impl::~scope_sink_f_impl() } } -bool -scope_sink_f_impl::check_topology(int ninputs, int noutputs) -{ - return ninputs == d_nconnections; -} +bool scope_sink_f_impl::check_topology(int ninputs, int noutputs) { return ninputs == d_nconnections; } -void -scope_sink_f_impl::initialize() +void scope_sink_f_impl::initialize() { d_qApplication = NULL; if(qApp != NULL) { @@ -138,26 +130,20 @@ scope_sink_f_impl::initialize() } // initialize update time to 60 times a second - set_update_time(1/60.0); + set_update_time(1 / 60.0); } -void -scope_sink_f_impl::exec_() -{ - d_qApplication->exec(); -} +void scope_sink_f_impl::exec_() { d_qApplication->exec(); } -void -scope_sink_f_impl::set_update_time(double t) +void scope_sink_f_impl::set_update_time(double t) { - //convert update time to ticks + // convert update time to ticks gr::high_res_timer_type tps = gr::high_res_timer_tps(); d_update_time = t * tps; d_last_time = 0; } -void -scope_sink_f_impl::set_trigger_mode(trigger_mode mode, int channel, const std::string &tag_key) +void scope_sink_f_impl::set_trigger_mode(trigger_mode mode, int channel, const std::string &tag_key) { gr::thread::scoped_lock lock(d_setlock); d_trigger_mode = mode; @@ -168,8 +154,7 @@ scope_sink_f_impl::set_trigger_mode(trigger_mode mode, int channel, const std::s _reset(); } -void -scope_sink_f_impl::set_nsamps(const int newsize) +void scope_sink_f_impl::set_nsamps(const int newsize) { if(newsize != d_size) { gr::thread::scoped_lock lock(d_setlock); @@ -177,62 +162,46 @@ scope_sink_f_impl::set_nsamps(const int newsize) // Set new size and reset buffer index // (throws away any currently held data, but who cares?) d_size = newsize; - d_buffer_size = 2*d_size; + d_buffer_size = 2 * d_size; // Resize buffers and replace data for(int n = 0; n < d_nconnections; n++) { volk_free(d_buffers[n]); - d_buffers[n] = (double*)volk_malloc(d_buffer_size*sizeof(double), - volk_get_alignment()); - memset(d_buffers[n], 0, d_buffer_size*sizeof(double)); + d_buffers[n] = (double *)volk_malloc(d_buffer_size * sizeof(double), volk_get_alignment()); + memset(d_buffers[n], 0, d_buffer_size * sizeof(double)); volk_free(d_fbuffers[n]); - d_fbuffers[n] = (float*)volk_malloc(d_buffer_size*sizeof(float), - volk_get_alignment()); - memset(d_fbuffers[n], 0, d_buffer_size*sizeof(float)); + d_fbuffers[n] = (float *)volk_malloc(d_buffer_size * sizeof(float), volk_get_alignment()); + memset(d_fbuffers[n], 0, d_buffer_size * sizeof(float)); } _reset(); } } -void -scope_sink_f_impl::set_samp_rate(const double samp_rate) +void scope_sink_f_impl::set_samp_rate(const double samp_rate) { gr::thread::scoped_lock(d_setlock); d_samp_rate = samp_rate; auto time_plot = dynamic_cast(this->plot); - if (time_plot) + if(time_plot) time_plot->setSampleRate(samp_rate, 1, ""); } -int -scope_sink_f_impl::nsamps() const -{ - return d_size; -} +int scope_sink_f_impl::nsamps() const { return d_size; } -std::string scope_sink_f_impl::name() const -{ - return d_name; -} +std::string scope_sink_f_impl::name() const { return d_name; } -void -scope_sink_f_impl::reset() +void scope_sink_f_impl::reset() { gr::thread::scoped_lock lock(d_setlock); _reset(); } -void -scope_sink_f_impl::set_displayOneBuffer(bool val) -{ - d_displayOneBuffer = val; -} +void scope_sink_f_impl::set_displayOneBuffer(bool val) { d_displayOneBuffer = val; } -void -scope_sink_f_impl::_reset() +void scope_sink_f_impl::_reset() { int n; @@ -255,16 +224,13 @@ scope_sink_f_impl::_reset() } } -void -scope_sink_f_impl::_test_trigger_tags(int nitems) +void scope_sink_f_impl::_test_trigger_tags(int nitems) { int trigger_index; uint64_t nr = nitems_read(d_trigger_channel); std::vector tags; - get_tags_in_range(tags, d_trigger_channel, - nr, nr + nitems + 1, - d_trigger_tag_key); + get_tags_in_range(tags, d_trigger_channel, nr, nr + nitems + 1, d_trigger_tag_key); if(tags.size() > 0) { d_triggered = true; trigger_index = tags[0].offset - nr; @@ -274,13 +240,9 @@ scope_sink_f_impl::_test_trigger_tags(int nitems) } } -void -scope_sink_f_impl::_npoints_resize() -{ -} +void scope_sink_f_impl::_npoints_resize() {} -void -scope_sink_f_impl::_adjust_tags(int adj) +void scope_sink_f_impl::_adjust_tags(int adj) { for(size_t n = 0; n < d_tags.size(); n++) { for(size_t t = 0; t < d_tags[n].size(); t++) { @@ -289,48 +251,43 @@ scope_sink_f_impl::_adjust_tags(int adj) } } -void -scope_sink_f_impl::clean_buffers() +void scope_sink_f_impl::clean_buffers() { gr::thread::scoped_lock lock(d_setlock); // Set new size and reset buffer index // (throws away any currently held data, but who cares?) - d_buffer_size = 2*d_size; + d_buffer_size = 2 * d_size; // Resize buffers and replace data for(int n = 0; n < d_nconnections; n++) { volk_free(d_buffers[n]); - d_buffers[n] = (double*)volk_malloc(d_buffer_size*sizeof(double), - volk_get_alignment()); - memset(d_buffers[n], 0, d_buffer_size*sizeof(double)); + d_buffers[n] = (double *)volk_malloc(d_buffer_size * sizeof(double), volk_get_alignment()); + memset(d_buffers[n], 0, d_buffer_size * sizeof(double)); volk_free(d_fbuffers[n]); - d_fbuffers[n] = (float*)volk_malloc(d_buffer_size*sizeof(float), - volk_get_alignment()); - memset(d_fbuffers[n], 0, d_buffer_size*sizeof(float)); + d_fbuffers[n] = (float *)volk_malloc(d_buffer_size * sizeof(float), volk_get_alignment()); + memset(d_fbuffers[n], 0, d_buffer_size * sizeof(float)); } _reset(); d_cleanBuffers = true; } -int -scope_sink_f_impl::work(int noutput_items, - gr_vector_const_void_star &input_items, - gr_vector_void_star &output_items) +int scope_sink_f_impl::work(int noutput_items, gr_vector_const_void_star &input_items, + gr_vector_void_star &output_items) { - int n=0, idx=0; + int n = 0, idx = 0; const float *in; _npoints_resize(); gr::thread::scoped_lock lock(d_setlock); - if (!d_displayOneBuffer && !d_cleanBuffers) { + if(!d_displayOneBuffer && !d_cleanBuffers) { return 0; } - int nfill = d_end - d_index; // how much room left in buffers + int nfill = d_end - d_index; // how much room left in buffers int nitems = std::min(noutput_items, nfill); // num items we can put in buffers int nItemsToSend = 0; @@ -344,16 +301,15 @@ scope_sink_f_impl::work(int noutput_items, // Copy data into the buffers. for(n = 0; n < d_nconnections; n++) { - in = (const float*)input_items[idx]; - memcpy(&d_fbuffers[n][d_index], &in[0], nitems*sizeof(float)); - volk_32f_convert_64f(&d_buffers[n][d_index], - &in[1], nitems); + in = (const float *)input_items[idx]; + memcpy(&d_fbuffers[n][d_index], &in[0], nitems * sizeof(float)); + volk_32f_convert_64f(&d_buffers[n][d_index], &in[1], nitems); uint64_t nr = nitems_read(idx); std::vector tags; get_tags_in_range(tags, idx, nr, nr + nitems + 1); for(size_t t = 0; t < tags.size(); t++) { - tags[t].offset = tags[t].offset - nr + (d_index-d_start-1); + tags[t].offset = tags[t].offset - nr + (d_index - d_start - 1); } d_tags[idx].insert(d_tags[idx].end(), tags.begin(), tags.end()); idx++; @@ -362,47 +318,44 @@ scope_sink_f_impl::work(int noutput_items, // If we've have a full d_size of items in the buffers, plot. if((d_end != 0 && !d_displayOneBuffer) || - ((d_triggered) && (d_index == d_end) && d_end != 0 && d_displayOneBuffer)) { + ((d_triggered) && (d_index == d_end) && d_end != 0 && d_displayOneBuffer)) { // Copy data to be plotted to start of buffers. for(n = 0; n < d_nconnections; n++) { - if (!d_displayOneBuffer) { + if(!d_displayOneBuffer) { nItemsToSend = d_index; - if (nItemsToSend >= d_size) { + if(nItemsToSend >= d_size) { nItemsToSend = d_size; d_cleanBuffers = false; } volk_32f_convert_64f(d_buffers[n], &d_fbuffers[n][d_start], nItemsToSend); } else { - //memmove(d_buffers[n], &d_buffers[n][d_start], d_size*sizeof(double)); + // memmove(d_buffers[n], &d_buffers[n][d_start], d_size*sizeof(double)); volk_32f_convert_64f(d_buffers[n], &d_fbuffers[n][d_start], d_size); nItemsToSend = d_size; } } // Plot if we are able to update - if((gr::high_res_timer_now() - d_last_time > d_update_time) - || !d_cleanBuffers) { + if((gr::high_res_timer_now() - d_last_time > d_update_time) || !d_cleanBuffers) { d_last_time = gr::high_res_timer_now(); - if (d_qApplication) { - qInfo()<postEvent(this->plot, - new IdentifiableTimeUpdateEvent(d_buffers, - nItemsToSend, - d_tags, - d_name)); + if(d_qApplication) { + qInfo() << QString::fromStdString(d_name); + + d_qApplication->postEvent( + this->plot, + new IdentifiableTimeUpdateEvent(d_buffers, nItemsToSend, d_tags, d_name)); } } // We've plotting, so reset the state - if (d_displayOneBuffer) { + if(d_displayOneBuffer) { _reset(); } } - if (d_displayOneBuffer && d_index == d_end) { + if(d_displayOneBuffer && d_index == d_end) { _reset(); } return nitems; } -} /* namespace gr */ +} // namespace scopy diff --git a/gui/gr-gui/src/waterfall_sink_impl.cc b/gui/gr-gui/src/waterfall_sink_impl.cc index 492851ebd1..1353cb658b 100644 --- a/gui/gr-gui/src/waterfall_sink_impl.cc +++ b/gui/gr-gui/src/waterfall_sink_impl.cc @@ -33,84 +33,64 @@ #include "spectrumUpdateEvents.h" #include "trigger_mode.h" +#include "waterfall_sink_impl.h" #include #include #include -#include "waterfall_sink_impl.h" - namespace scopy { -waterfall_sink::sptr -waterfall_sink::make(int fftsize, - std::vector win, - double fc, - double bw, - const std::string& name, - int nconnections, - WaterfallDisplayPlot* plot, - bool fft_shift) +waterfall_sink::sptr waterfall_sink::make(int fftsize, std::vector win, double fc, double bw, + const std::string &name, int nconnections, WaterfallDisplayPlot *plot, + bool fft_shift) { - return gnuradio::get_initial_sptr - (new waterfall_sink_impl(fftsize, win, fc, bw, name, nconnections, plot, fft_shift)); + return gnuradio::get_initial_sptr( + new waterfall_sink_impl(fftsize, win, fc, bw, name, nconnections, plot, fft_shift)); } -waterfall_sink_impl::waterfall_sink_impl(int fftsize, - std::vector win, - double fc, - double bw, - const std::string& name, - int nconnections, - WaterfallDisplayPlot* plot, +waterfall_sink_impl::waterfall_sink_impl(int fftsize, std::vector win, double fc, double bw, + const std::string &name, int nconnections, WaterfallDisplayPlot *plot, bool fft_shift) - : sync_block("waterfall_sink", - gr::io_signature::make(0, nconnections, sizeof(gr_complex)), - gr::io_signature::make(0, 0, 0)), - d_fftsize(0), - d_fft_shift(fftsize), - d_fftavg(1), - d_window(win), - d_center_freq(fc), - d_bandwidth(bw), - d_name(name), - d_nconnections(nconnections), - d_nrows(200), - d_port(pmt::mp("freq")), - d_port_bw(pmt::mp("bw")), - d_fft(std::make_unique(fftsize)), - d_fbuffers(d_nconnections), - d_buffers(d_nconnections), - d_fbuf(fftsize), - d_main_gui(plot), - do_shift(fft_shift), - d_tags(std::vector< std::vector >(d_nconnections)), - d_displayOneBuffer(true), - d_cleanBuffers(true), - d_trigger_mode(TRIG_MODE_TAG) + : sync_block("waterfall_sink", gr::io_signature::make(0, nconnections, sizeof(gr_complex)), + gr::io_signature::make(0, 0, 0)) + , d_fftsize(0) + , d_fft_shift(fftsize) + , d_fftavg(1) + , d_window(win) + , d_center_freq(fc) + , d_bandwidth(bw) + , d_name(name) + , d_nconnections(nconnections) + , d_nrows(200) + , d_port(pmt::mp("freq")) + , d_port_bw(pmt::mp("bw")) + , d_fft(std::make_unique(fftsize)) + , d_fbuffers(d_nconnections) + , d_buffers(d_nconnections) + , d_fbuf(fftsize) + , d_main_gui(plot) + , do_shift(fft_shift) + , d_tags(std::vector>(d_nconnections)) + , d_displayOneBuffer(true) + , d_cleanBuffers(true) + , d_trigger_mode(TRIG_MODE_TAG) { resize_bufs(fftsize); d_fftsize = fftsize; initialize(); } -waterfall_sink_impl::~waterfall_sink_impl() -{ - delete d_main_gui; -} +waterfall_sink_impl::~waterfall_sink_impl() { delete d_main_gui; } -bool waterfall_sink_impl::check_topology(int ninputs, int noutputs) -{ - return ninputs == d_nconnections; -} +bool waterfall_sink_impl::check_topology(int ninputs, int noutputs) { return ninputs == d_nconnections; } // requests buffers with a max size of 8191 (useful at large fft sizes) -void waterfall_sink_impl::forecast(int noutput_items, - gr_vector_int& ninput_items_required) +void waterfall_sink_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned int ninputs = ninput_items_required.size(); - for (unsigned int i = 0; i < ninputs; i++) { + for(unsigned int i = 0; i < ninputs; i++) { ninput_items_required[i] = std::min(d_fftsize, 8191); } } @@ -124,7 +104,7 @@ void waterfall_sink_impl::initialize() set_update_time(0.1); } -QWidget* waterfall_sink_impl::qwidget() { return d_main_gui; } +QWidget *waterfall_sink_impl::qwidget() { return d_main_gui; } void waterfall_sink_impl::clear_data() { d_main_gui->clearData(); } @@ -138,17 +118,13 @@ void waterfall_sink_impl::set_fft_size(const int fftsize) fftresize(); } -void waterfall_sink_impl::set_fft_window(const std::vector window) -{ - d_window = window; -} +void waterfall_sink_impl::set_fft_window(const std::vector window) { d_window = window; } int waterfall_sink_impl::fft_size() const { return d_fftsize; } float waterfall_sink_impl::fft_average() const { return d_fftavg; } -void waterfall_sink_impl::set_frequency_range(const double centerfreq, - const double bandwidth) +void waterfall_sink_impl::set_frequency_range(const double centerfreq, const double bandwidth) { clear_data(); d_center_freq = centerfreq; @@ -170,7 +146,7 @@ void waterfall_sink_impl::set_update_time(double t) d_last_time = 0; } -void waterfall_sink_impl::set_line_label(unsigned int which, const std::string& label) +void waterfall_sink_impl::set_line_label(unsigned int which, const std::string &label) { d_main_gui->setLineLabel(which, label.c_str()); } @@ -180,10 +156,7 @@ void waterfall_sink_impl::set_line_alpha(unsigned int which, double alpha) d_main_gui->setAlpha(which, (int)(255.0 * alpha)); } -void waterfall_sink_impl::set_size(int width, int height) -{ - d_main_gui->resize(QSize(width, height)); -} +void waterfall_sink_impl::set_size(int width, int height) { d_main_gui->resize(QSize(width, height)); } void waterfall_sink_impl::set_plot_pos_half(bool half) { @@ -191,29 +164,20 @@ void waterfall_sink_impl::set_plot_pos_half(bool half) d_main_gui->setPlotPosHalf(half); } -double waterfall_sink_impl::line_alpha(unsigned int which) -{ - return (double)(d_main_gui->getAlpha(which)) / 255.0; -} +double waterfall_sink_impl::line_alpha(unsigned int which) { return (double)(d_main_gui->getAlpha(which)) / 255.0; } void waterfall_sink_impl::auto_scale() { d_main_gui->autoScale(); } -double waterfall_sink_impl::min_intensity(unsigned int which) -{ - return d_main_gui->getMinIntensity(which); -} +double waterfall_sink_impl::min_intensity(unsigned int which) { return d_main_gui->getMinIntensity(which); } -double waterfall_sink_impl::max_intensity(unsigned int which) -{ - return d_main_gui->getMaxIntensity(which); -} +double waterfall_sink_impl::max_intensity(unsigned int which) { return d_main_gui->getMaxIntensity(which); } void waterfall_sink_impl::disable_legend() { d_main_gui->disableLegend(); } -void waterfall_sink_impl::fft(float* data_out, gr_complex* data_in, int size) +void waterfall_sink_impl::fft(float *data_out, gr_complex *data_in, int size) { // float to complex conversion - if (!d_window.empty()) { + if(!d_window.empty()) { volk_32fc_32f_multiply_32fc(d_fft->get_inbuf(), data_in, &d_window.front(), size); } else { memcpy(d_fft->get_inbuf(), data_in, sizeof(gr_complex) * size); @@ -221,10 +185,9 @@ void waterfall_sink_impl::fft(float* data_out, gr_complex* data_in, int size) d_fft->execute(); // compute the fft - volk_32fc_s32f_x2_power_spectral_density_32f( - data_out, d_fft->get_outbuf(), size, 1.0, size); + volk_32fc_s32f_x2_power_spectral_density_32f(data_out, d_fft->get_outbuf(), size, 1.0, size); - if (do_shift) { + if(do_shift) { d_fft_shift.shift(data_out, size); } } @@ -241,14 +204,12 @@ void waterfall_sink_impl::resize_bufs(int size) // Resize buffers and replace data for(int n = 0; n < d_nconnections; n++) { volk_free(d_buffers[n]); - d_buffers[n] = (double*)volk_malloc(d_fftsize*sizeof(double), - volk_get_alignment()); - memset(d_buffers[n], 0, d_fftsize*sizeof(double)); + d_buffers[n] = (double *)volk_malloc(d_fftsize * sizeof(double), volk_get_alignment()); + memset(d_buffers[n], 0, d_fftsize * sizeof(double)); volk_free(d_fbuffers[n]); - d_fbuffers[n] = (gr_complex*)volk_malloc(d_fftsize*sizeof(gr_complex), - volk_get_alignment()); - memset(d_fbuffers[n], 0, d_fftsize*sizeof(gr_complex)); + d_fbuffers[n] = (gr_complex *)volk_malloc(d_fftsize * sizeof(gr_complex), volk_get_alignment()); + memset(d_fbuffers[n], 0, d_fftsize * sizeof(gr_complex)); } _reset(); @@ -319,10 +280,7 @@ void waterfall_sink_impl::reset() _reset(); } -void waterfall_sink_impl::set_displayOneBuffer(bool val) -{ - d_displayOneBuffer = val; -} +void waterfall_sink_impl::set_displayOneBuffer(bool val) { d_displayOneBuffer = val; } void waterfall_sink_impl::_reset() { @@ -347,19 +305,18 @@ void waterfall_sink_impl::_reset() } } -int waterfall_sink_impl::work(int noutput_items, - gr_vector_const_void_star& input_items, - gr_vector_void_star& output_items) +int waterfall_sink_impl::work(int noutput_items, gr_vector_const_void_star &input_items, + gr_vector_void_star &output_items) { - int n=0, idx=0; + int n = 0, idx = 0; const gr_complex *in; gr::thread::scoped_lock lock(d_setlock); - if (!d_displayOneBuffer && !d_cleanBuffers) { + if(!d_displayOneBuffer && !d_cleanBuffers) { return 0; } - int nfill = d_end - d_index; // how much room left in buffers + int nfill = d_end - d_index; // how much room left in buffers int nitems = std::min(noutput_items, nfill); // num items we can put in buffers int nItemsToSend = 0; @@ -373,7 +330,7 @@ int waterfall_sink_impl::work(int noutput_items, // Copy data into the buffers. for(n = 0; n < d_nconnections; n++) { - in = (const gr_complex*)input_items[idx]; + in = (const gr_complex *)input_items[idx]; memcpy(d_fbuffers[n] + d_index, &in[0], sizeof(gr_complex) * nitems); uint64_t nr = nitems_read(idx); @@ -381,7 +338,7 @@ int waterfall_sink_impl::work(int noutput_items, get_tags_in_range(tags, idx, nr, nr + nitems + 1); for(size_t t = 0; t < tags.size(); t++) { - tags[t].offset = tags[t].offset - nr + (d_index-d_start-1); + tags[t].offset = tags[t].offset - nr + (d_index - d_start - 1); } d_tags[idx].insert(d_tags[idx].end(), tags.begin(), tags.end()); idx++; @@ -390,12 +347,12 @@ int waterfall_sink_impl::work(int noutput_items, // If we've have a full d_size of items in the buffers, plot. if((d_end != 0 && !d_displayOneBuffer) || - ((d_triggered) && (d_index == d_end) && d_end != 0 && d_displayOneBuffer)) { + ((d_triggered) && (d_index == d_end) && d_end != 0 && d_displayOneBuffer)) { // Copy data to be plotted to start of buffers. for(n = 0; n < d_nconnections; n++) { - if (!d_displayOneBuffer) { + if(!d_displayOneBuffer) { nItemsToSend = d_index; - if (nItemsToSend >= fft_size()) { + if(nItemsToSend >= fft_size()) { nItemsToSend = fft_size(); d_cleanBuffers = false; } @@ -404,25 +361,26 @@ int waterfall_sink_impl::work(int noutput_items, } fft(d_fbuf.data(), d_fbuffers[n], fft_size()); - for (int x = 0; x < fft_size(); x++) { - d_buffers[n][x] = (double)((1.0 - d_fftavg) * d_buffers[n][x] + - (d_fftavg)*d_fbuf[x]); + for(int x = 0; x < fft_size(); x++) { + d_buffers[n][x] = (double)((1.0 - d_fftavg) * d_buffers[n][x] + (d_fftavg)*d_fbuf[x]); } } // Plot if we are able to update if((gr::high_res_timer_now() - d_last_time > d_update_time) || !d_cleanBuffers) { d_last_time = gr::high_res_timer_now(); - d_qApplication->postEvent(d_main_gui, new WaterfallUpdateEvent(d_buffers, nItemsToSend, gr::high_res_timer_now() - d_last_time)); + d_qApplication->postEvent(d_main_gui, + new WaterfallUpdateEvent(d_buffers, nItemsToSend, + gr::high_res_timer_now() - d_last_time)); } // We've plotting, so reset the state - if (d_displayOneBuffer) { + if(d_displayOneBuffer) { _reset(); } } - if (d_displayOneBuffer && d_index == d_end) { + if(d_displayOneBuffer && d_index == d_end) { _reset(); } return nitems; diff --git a/gui/gr-gui/src/xy_sink_c_impl.cc b/gui/gr-gui/src/xy_sink_c_impl.cc index 991454d54a..a743cc3c81 100644 --- a/gui/gr-gui/src/xy_sink_c_impl.cc +++ b/gui/gr-gui/src/xy_sink_c_impl.cc @@ -43,206 +43,174 @@ #include #endif +#include "spectrumUpdateEvents.h" +#include "xy_sink_c_impl.h" + #include #include -#include -#include + #include -#include "xy_sink_c_impl.h" -#include"spectrumUpdateEvents.h" +#include +#include using namespace gr; namespace scopy { - xy_sink_c::sptr - xy_sink_c::make(int size, - const std::string &name, - int nconnections, - QObject *plot) - { - return gnuradio::get_initial_sptr - (new xy_sink_c_impl(size, name, nconnections, plot)); - } - - xy_sink_c_impl::xy_sink_c_impl(int size, - const std::string &name, - int nconnections, - QObject *plot) - : sync_block("xy_sink_c", - io_signature::make(nconnections, nconnections, sizeof(gr_complex)), - io_signature::make(0, 0, 0)), - d_size(size), d_buffer_size(2*size), d_name(name), - d_nconnections(nconnections), d_index(0), d_start(0), d_end(size) - { - - for(int i = 0; i < d_nconnections; i++) { - d_residbufs_real.push_back((double*)volk_malloc(d_buffer_size*sizeof(double), - volk_get_alignment())); - d_residbufs_imag.push_back((double*)volk_malloc(d_buffer_size*sizeof(double), - volk_get_alignment())); - memset(d_residbufs_real[i], 0, d_buffer_size*sizeof(double)); - memset(d_residbufs_imag[i], 0, d_buffer_size*sizeof(double)); - } - - // Set alignment properties for VOLK - const int alignment_multiple = - volk_get_alignment() / sizeof(gr_complex); - set_alignment(std::max(1,alignment_multiple)); - - initialize(); - this->plot = (ConstellationDisplayPlot*)plot; - } - - xy_sink_c_impl::~xy_sink_c_impl() - { - // d_main_gui is a qwidget destroyed with its parent - for(int i = 0; i < d_nconnections; i++) { - volk_free(d_residbufs_real[i]); - volk_free(d_residbufs_imag[i]); - } - } - - bool - xy_sink_c_impl::check_topology(int ninputs, int noutputs) - { - return ninputs == d_nconnections; - } - - void - xy_sink_c_impl::initialize() - { +xy_sink_c::sptr xy_sink_c::make(int size, const std::string &name, int nconnections, QObject *plot) +{ + return gnuradio::get_initial_sptr(new xy_sink_c_impl(size, name, nconnections, plot)); +} + +xy_sink_c_impl::xy_sink_c_impl(int size, const std::string &name, int nconnections, QObject *plot) + : sync_block("xy_sink_c", io_signature::make(nconnections, nconnections, sizeof(gr_complex)), + io_signature::make(0, 0, 0)) + , d_size(size) + , d_buffer_size(2 * size) + , d_name(name) + , d_nconnections(nconnections) + , d_index(0) + , d_start(0) + , d_end(size) +{ + + for(int i = 0; i < d_nconnections; i++) { + d_residbufs_real.push_back((double *)volk_malloc(d_buffer_size * sizeof(double), volk_get_alignment())); + d_residbufs_imag.push_back((double *)volk_malloc(d_buffer_size * sizeof(double), volk_get_alignment())); + memset(d_residbufs_real[i], 0, d_buffer_size * sizeof(double)); + memset(d_residbufs_imag[i], 0, d_buffer_size * sizeof(double)); + } + + // Set alignment properties for VOLK + const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); + set_alignment(std::max(1, alignment_multiple)); + + initialize(); + this->plot = (ConstellationDisplayPlot *)plot; +} + +xy_sink_c_impl::~xy_sink_c_impl() +{ + // d_main_gui is a qwidget destroyed with its parent + for(int i = 0; i < d_nconnections; i++) { + volk_free(d_residbufs_real[i]); + volk_free(d_residbufs_imag[i]); + } +} + +bool xy_sink_c_impl::check_topology(int ninputs, int noutputs) { return ninputs == d_nconnections; } + +void xy_sink_c_impl::initialize() +{ d_qApplication = NULL; - if(qApp != NULL) { - d_qApplication = qApp; - } - - set_update_time(1/60.0); - } - - void - xy_sink_c_impl::exec_() - { - d_qApplication->exec(); - } - - void - xy_sink_c_impl::set_update_time(double t) - { - //convert update time to ticks - gr::high_res_timer_type tps = gr::high_res_timer_tps(); - d_update_time = t * tps; - d_last_time = 0; - } - - void - xy_sink_c_impl::set_nsamps(const int newsize) - { - gr::thread::scoped_lock lock(d_setlock); - - if(newsize != d_size) { - // Set new size and reset buffer index - // (throws away any currently held data, but who cares?) - d_size = newsize; - d_buffer_size = 2*d_size; + if(qApp != NULL) { + d_qApplication = qApp; + } + + set_update_time(1 / 60.0); +} + +void xy_sink_c_impl::exec_() { d_qApplication->exec(); } + +void xy_sink_c_impl::set_update_time(double t) +{ + // convert update time to ticks + gr::high_res_timer_type tps = gr::high_res_timer_tps(); + d_update_time = t * tps; + d_last_time = 0; +} + +void xy_sink_c_impl::set_nsamps(const int newsize) +{ + gr::thread::scoped_lock lock(d_setlock); + + if(newsize != d_size) { + // Set new size and reset buffer index + // (throws away any currently held data, but who cares?) + d_size = newsize; + d_buffer_size = 2 * d_size; + d_index = 0; + + // Resize residbuf and replace data + for(int i = 0; i < d_nconnections; i++) { + volk_free(d_residbufs_real[i]); + volk_free(d_residbufs_imag[i]); + d_residbufs_real[i] = + (double *)volk_malloc(d_buffer_size * sizeof(double), volk_get_alignment()); + d_residbufs_imag[i] = + (double *)volk_malloc(d_buffer_size * sizeof(double), volk_get_alignment()); + + memset(d_residbufs_real[i], 0, d_buffer_size * sizeof(double)); + memset(d_residbufs_imag[i], 0, d_buffer_size * sizeof(double)); + } + + _reset(); + } +} + +int xy_sink_c_impl::nsamps() const { return d_size; } + +void xy_sink_c_impl::reset() +{ + gr::thread::scoped_lock lock(d_setlock); + _reset(); +} + +void xy_sink_c_impl::_reset() +{ + // Reset the start and end indices. + d_start = 0; + d_end = d_size; d_index = 0; +} - // Resize residbuf and replace data - for(int i = 0; i < d_nconnections; i++) { - volk_free(d_residbufs_real[i]); - volk_free(d_residbufs_imag[i]); - d_residbufs_real[i] = (double*)volk_malloc(d_buffer_size*sizeof(double), - volk_get_alignment()); - d_residbufs_imag[i] = (double*)volk_malloc(d_buffer_size*sizeof(double), - volk_get_alignment()); - - memset(d_residbufs_real[i], 0, d_buffer_size*sizeof(double)); - memset(d_residbufs_imag[i], 0, d_buffer_size*sizeof(double)); +void xy_sink_c_impl::_npoints_resize() {} + +int xy_sink_c_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) +{ + int n = 0; + const gr_complex *in; + + _npoints_resize(); + + int nfill = d_end - d_index; // how much room left in buffers + int nitems = std::min(noutput_items, nfill); // num items we can put in buffers + + // Copy data into the buffers. + for(n = 0; n < d_nconnections; n++) { + in = (const gr_complex *)input_items[n]; + volk_32fc_deinterleave_64f_x2(&d_residbufs_real[n][d_index], &d_residbufs_imag[n][d_index], &in[0], + nitems); + } + d_index += nitems; + + // If we have a full d_size of items in the buffers, plot. + if((d_index == d_end) && d_end != 0) { + // Copy data to be plotted to start of buffers. + for(n = 0; n < d_nconnections; n++) { + memmove(d_residbufs_real[n], &d_residbufs_real[n][d_start], d_size * sizeof(double)); + memmove(d_residbufs_imag[n], &d_residbufs_imag[n][d_start], d_size * sizeof(double)); + } + + // Plot if we are able to update + if(gr::high_res_timer_now() - d_last_time > d_update_time) { + d_last_time = gr::high_res_timer_now(); + if(d_qApplication) + d_qApplication->postEvent( + plot, new ConstUpdateEvent(d_residbufs_real, d_residbufs_imag, d_size)); + } + + // We've plotting, so reset the state + _reset(); + } + + // If we've filled up the buffers but haven't triggered, reset. + if(d_index == d_end) { + _reset(); } - _reset(); - } - } - - int - xy_sink_c_impl::nsamps() const - { - return d_size; - } - - void - xy_sink_c_impl::reset() - { - gr::thread::scoped_lock lock(d_setlock); - _reset(); - } - - void - xy_sink_c_impl::_reset() - { - // Reset the start and end indices. - d_start = 0; - d_end = d_size; - d_index = 0; - } - - void - xy_sink_c_impl::_npoints_resize() - { - } - - int - xy_sink_c_impl::work(int noutput_items, - gr_vector_const_void_star &input_items, - gr_vector_void_star &output_items) - { - int n=0; - const gr_complex *in; - - _npoints_resize(); - - int nfill = d_end - d_index; // how much room left in buffers - int nitems = std::min(noutput_items, nfill); // num items we can put in buffers - - // Copy data into the buffers. - for(n = 0; n < d_nconnections; n++) { - in = (const gr_complex*)input_items[n]; - volk_32fc_deinterleave_64f_x2(&d_residbufs_real[n][d_index], - &d_residbufs_imag[n][d_index], - &in[0], nitems); - } - d_index += nitems; - - - // If we have a full d_size of items in the buffers, plot. - if((d_index == d_end) && d_end != 0) { - // Copy data to be plotted to start of buffers. - for(n = 0; n < d_nconnections; n++) { - memmove(d_residbufs_real[n], &d_residbufs_real[n][d_start], d_size*sizeof(double)); - memmove(d_residbufs_imag[n], &d_residbufs_imag[n][d_start], d_size*sizeof(double)); - } - - // Plot if we are able to update - if(gr::high_res_timer_now() - d_last_time > d_update_time) { - d_last_time = gr::high_res_timer_now(); - if (d_qApplication) - d_qApplication->postEvent(plot, - new ConstUpdateEvent(d_residbufs_real, - d_residbufs_imag, - d_size)); - } - - // We've plotting, so reset the state - _reset(); - } - - // If we've filled up the buffers but haven't triggered, reset. - if(d_index == d_end) { - _reset(); - } - - return nitems; - } + return nitems; +} } /* namespace scopy */ diff --git a/gui/gr-gui/test/CMakeLists.txt b/gui/gr-gui/test/CMakeLists.txt index c749ff1584..72de46a83b 100644 --- a/gui/gr-gui/test/CMakeLists.txt +++ b/gui/gr-gui/test/CMakeLists.txt @@ -1,22 +1,18 @@ cmake_minimum_required(VERSION 3.5) function(SETUP_TESTS) - foreach(_testname ${ARGS}) - add_executable(_testname ${ARGS}) - add_test(NAME ${_testname} COMMAND ${_testname}) - target_link_libraries(${_testname} Qt${QT_VERSION_MAJOR}::Test) - endforeach() + foreach(_testname ${ARGS}) + add_executable(_testname ${ARGS}) + add_test(NAME ${_testname} COMMAND ${_testname}) + target_link_libraries(${_testname} Qt${QT_VERSION_MAJOR}::Test) + endforeach() endfunction() - # Tell CMake to run moc when necessary: set(CMAKE_AUTOMOC ON) -# As moc files are generated in the binary dir, tell CMake -# to always look for includes there: +# As moc files are generated in the binary dir, tell CMake to always look for includes there: set(CMAKE_INCLUDE_CURRENT_DIR ON) find_package(Qt${QT_VERSION_MAJOR}Test REQUIRED) -SETUP_TESTS( -) - +setup_tests() diff --git a/gui/include/gui/BasicPlot.h b/gui/include/gui/BasicPlot.h index dc59d75153..073ba3beed 100644 --- a/gui/include/gui/BasicPlot.h +++ b/gui/include/gui/BasicPlot.h @@ -2,19 +2,18 @@ #define BASICPLOT_H /*Qwt includes*/ -#include -#include #include +#include #include -#include +#include #include +#include #include - /*Qt includes*/ +#include #include #include -#include /*Own includes */ #include @@ -28,7 +27,7 @@ class SCOPY_GUI_EXPORT BasicPlot : public QwtPlot { Q_OBJECT public: - BasicPlot(QWidget* parent); + BasicPlot(QWidget *parent); public Q_SLOTS: void start(); @@ -47,6 +46,7 @@ public Q_SLOTS: protected: QTimer replotTimer; + private: static int staticPlotId; bool started; @@ -62,10 +62,8 @@ public Q_SLOTS: QwtText fpsTxt; QElapsedTimer fpsTimer; QElapsedTimer fpsLabelTimer; - - }; -} +} // namespace scopy #endif // BASICPLOT_H diff --git a/gui/include/gui/ComboBoxLineEdit.h b/gui/include/gui/ComboBoxLineEdit.h index d0680858db..16a58c66b3 100644 --- a/gui/include/gui/ComboBoxLineEdit.h +++ b/gui/include/gui/ComboBoxLineEdit.h @@ -36,6 +36,6 @@ protected Q_SLOTS: void enterEvent(QEvent *event); void leaveEvent(QEvent *event); }; -} +} // namespace scopy #endif // ComboBoxLineEdit_H diff --git a/gui/include/gui/ConstellationDisplayPlot.h b/gui/include/gui/ConstellationDisplayPlot.h index f676202b50..5eb905c939 100644 --- a/gui/include/gui/ConstellationDisplayPlot.h +++ b/gui/include/gui/ConstellationDisplayPlot.h @@ -42,13 +42,13 @@ #ifndef M2K_CONSTELLATION_DISPLAY_PLOT_H #define M2K_CONSTELLATION_DISPLAY_PLOT_H -#include -#include -#include - #include "DisplayPlot.h" -#include "spectrumUpdateEvents.h" #include "scopy-gui_export.h" +#include "spectrumUpdateEvents.h" + +#include +#include +#include namespace scopy { /*! @@ -57,47 +57,42 @@ namespace scopy { */ class SCOPY_GUI_EXPORT ConstellationDisplayPlot : public DisplayPlot { - Q_OBJECT + Q_OBJECT public: - ConstellationDisplayPlot(int nplots, QWidget*); - virtual ~ConstellationDisplayPlot(); + ConstellationDisplayPlot(int nplots, QWidget *); + virtual ~ConstellationDisplayPlot(); - void plotNewData(const std::vector &realDataPoints, - const std::vector &imagDataPoints, - const int64_t numDataPoints, - const double timeInterval); + void plotNewData(const std::vector &realDataPoints, const std::vector &imagDataPoints, + const int64_t numDataPoints, const double timeInterval); - // Old method to be removed - void plotNewData(const double* realDataPoints, - const double* imagDataPoints, - const int64_t numDataPoints, - const double timeInterval); + // Old method to be removed + void plotNewData(const double *realDataPoints, const double *imagDataPoints, const int64_t numDataPoints, + const double timeInterval); - void replot(); + void replot(); - void set_xaxis(double min, double max); - void set_yaxis(double min, double max); - void set_axis(double xmin, double xmax, - double ymin, double ymax); - void set_pen_size(int size); + void set_xaxis(double min, double max); + void set_yaxis(double min, double max); + void set_axis(double xmin, double xmax, double ymin, double ymax); + void set_pen_size(int size); public Q_SLOTS: - void setAutoScale(bool state); + void setAutoScale(bool state); - void customEvent(QEvent * e); + void customEvent(QEvent *e); private Q_SLOTS: - void newData(const QEvent*); + void newData(const QEvent *); private: - void _autoScale(double bottom, double top); + void _autoScale(double bottom, double top); - std::vector d_real_data; - std::vector d_imag_data; + std::vector d_real_data; + std::vector d_imag_data; - int64_t d_pen_size; + int64_t d_pen_size; }; -} //scopy +} // namespace scopy #endif /* M2K_CONSTELLATION_DISPLAY_PLOT_H */ diff --git a/gui/include/gui/DisplayPlot.h b/gui/include/gui/DisplayPlot.h index 65eb5f66c5..ecba40c45e 100644 --- a/gui/include/gui/DisplayPlot.h +++ b/gui/include/gui/DisplayPlot.h @@ -42,39 +42,41 @@ #ifndef M2K_DISPLAY_PLOT_H #define M2K_DISPLAY_PLOT_H -#include -#include -#include -#include -#include +#include "cursor_readouts.h" +#include "extendingplotzoomer.h" +#include "handles_area.hpp" +#include "osc_adjuster.hpp" +#include "plot_line_handle.h" +#include "plot_utils.hpp" +#include "plotpickerwrapper.h" +#include "printableplot.h" +#include "qwt_utils.h" +#include "scopy-gui_export.h" +#include "symbol_controller.h" + +#include +#include #include +#include #include #include -#include -#include -#include -#include +#include #include #include -#include -#include -#include +#include #include -#include "qwt_utils.h" -#include "osc_adjuster.hpp" -#include "plot_utils.hpp" -#include "extendingplotzoomer.h" -#include "printableplot.h" -#include "symbol_controller.h" -#include "plot_line_handle.h" -#include "cursor_readouts.h" -#include "handles_area.hpp" -#include "plotpickerwrapper.h" -#include -#include "scopy-gui_export.h" +#include +#include +#include +#include + +#include +#include +#include +#include typedef QList QColorList; -Q_DECLARE_METATYPE ( QColorList ) +Q_DECLARE_METATYPE(QColorList) #if QWT_VERSION < 0x060100 #include @@ -87,37 +89,34 @@ namespace scopy { class PlotAxisConfiguration; -class SCOPY_GUI_EXPORT ScaleDivisions: public QObject +class SCOPY_GUI_EXPORT ScaleDivisions : public QObject { -Q_OBJECT + Q_OBJECT public: - ScaleDivisions(): - m_divLowerLimit(1E-9), - m_divUpperLimit(1E9), - m_power(0.0), - m_magnitude_step(10.0), - m_templateSteps({1, 2, 5}), - m_currentStep(m_templateSteps.begin()) + ScaleDivisions() + : m_divLowerLimit(1E-9) + , m_divUpperLimit(1E9) + , m_power(0.0) + , m_magnitude_step(10.0) + , m_templateSteps({1, 2, 5}) + , m_currentStep(m_templateSteps.begin()) { updateDivision(); } - ScaleDivisions(const std::vector &steps): - m_divLowerLimit(1E-9), - m_divUpperLimit(1E9), - m_power(0.0), - m_magnitude_step(10.0), - m_templateSteps(steps), - m_currentStep(m_templateSteps.begin()) + ScaleDivisions(const std::vector &steps) + : m_divLowerLimit(1E-9) + , m_divUpperLimit(1E9) + , m_power(0.0) + , m_magnitude_step(10.0) + , m_templateSteps(steps) + , m_currentStep(m_templateSteps.begin()) { updateDivision(); } - ~ScaleDivisions() - { - - } + ~ScaleDivisions() {} void setDivisioList(const std::vector &newSteps) { @@ -126,40 +125,19 @@ Q_OBJECT updateDivision(); } - double divisionValue() - { - return m_currentDiv; - } + double divisionValue() { return m_currentDiv; } - void setMagnitudeStep(double newStep) - { - m_magnitude_step = newStep; - } + void setMagnitudeStep(double newStep) { m_magnitude_step = newStep; } - double magnitudeStep() - { - return m_magnitude_step; - } + double magnitudeStep() { return m_magnitude_step; } - void setLowerLimit(double limit) - { - m_divLowerLimit = limit; - } + void setLowerLimit(double limit) { m_divLowerLimit = limit; } - double lowerLimit() - { - return m_divLowerLimit; - } + double lowerLimit() { return m_divLowerLimit; } - void setUpperLimit(double limit) - { - m_divUpperLimit = limit; - } + void setUpperLimit(double limit) { m_divUpperLimit = limit; } - double upperLimit() - { - return m_divUpperLimit; - } + double upperLimit() { return m_divUpperLimit; } Q_SIGNALS: void divisionChanged(double division); @@ -170,13 +148,13 @@ public Q_SLOTS: std::vector::iterator templateStep; int power = m_power; - if (m_currentStep < m_templateSteps.end() - 1) { + if(m_currentStep < m_templateSteps.end() - 1) { templateStep = m_currentStep + 1; } else { templateStep = m_templateSteps.begin(); power++; } - if (division(templateStep, power) <= m_divUpperLimit) { + if(division(templateStep, power) <= m_divUpperLimit) { m_currentStep = templateStep; m_power = power; updateDivision(); @@ -188,13 +166,13 @@ public Q_SLOTS: std::vector::iterator templateStep; int power = m_power; - if (m_currentStep > m_templateSteps.begin()) { + if(m_currentStep > m_templateSteps.begin()) { templateStep = m_currentStep - 1; } else { templateStep = m_templateSteps.end() - 1; power--; } - if (division(templateStep, power) >= m_divLowerLimit) { + if(division(templateStep, power) >= m_divLowerLimit) { m_currentStep = templateStep; m_power = power; updateDivision(); @@ -222,520 +200,515 @@ public Q_SLOTS: } }; -struct cursorReadoutsText { - QString t1; - QString t2; - QString tDelta; - QString freq; - QString v1; - QString v2; - QString vDelta; +struct cursorReadoutsText +{ + QString t1; + QString t2; + QString tDelta; + QString freq; + QString v1; + QString v2; + QString vDelta; }; /*! * \brief QWidget base plot to build QTGUI plotting tools. * \ingroup qtgui_blk */ -class SCOPY_GUI_EXPORT DisplayPlot:public PrintablePlot +class SCOPY_GUI_EXPORT DisplayPlot : public PrintablePlot { - Q_OBJECT - - Q_PROPERTY ( QColor line_color1 READ getLineColor1 WRITE setLineColor1 ) - Q_PROPERTY ( QColor line_color2 READ getLineColor2 WRITE setLineColor2 ) - Q_PROPERTY ( QColor line_color3 READ getLineColor3 WRITE setLineColor3 ) - Q_PROPERTY ( QColor line_color4 READ getLineColor4 WRITE setLineColor4 ) - Q_PROPERTY ( QColor line_color5 READ getLineColor5 WRITE setLineColor5 ) - Q_PROPERTY ( QColor line_color6 READ getLineColor6 WRITE setLineColor6 ) - Q_PROPERTY ( QColor line_color7 READ getLineColor7 WRITE setLineColor7 ) - Q_PROPERTY ( QColor line_color8 READ getLineColor8 WRITE setLineColor8 ) - Q_PROPERTY ( QColor line_color9 READ getLineColor9 WRITE setLineColor9 ) - - Q_PROPERTY ( int line_width1 READ getLineWidth1 WRITE setLineWidth1 ) - Q_PROPERTY ( int line_width2 READ getLineWidth2 WRITE setLineWidth2 ) - Q_PROPERTY ( int line_width3 READ getLineWidth3 WRITE setLineWidth3 ) - Q_PROPERTY ( int line_width4 READ getLineWidth4 WRITE setLineWidth4 ) - Q_PROPERTY ( int line_width5 READ getLineWidth5 WRITE setLineWidth5 ) - Q_PROPERTY ( int line_width6 READ getLineWidth6 WRITE setLineWidth6 ) - Q_PROPERTY ( int line_width7 READ getLineWidth7 WRITE setLineWidth7 ) - Q_PROPERTY ( int line_width8 READ getLineWidth8 WRITE setLineWidth8 ) - Q_PROPERTY ( int line_width9 READ getLineWidth9 WRITE setLineWidth9 ) - - Q_PROPERTY ( Qt::PenStyle line_style1 READ getLineStyle1 WRITE setLineStyle1 ) - Q_PROPERTY ( Qt::PenStyle line_style2 READ getLineStyle2 WRITE setLineStyle2 ) - Q_PROPERTY ( Qt::PenStyle line_style3 READ getLineStyle3 WRITE setLineStyle3 ) - Q_PROPERTY ( Qt::PenStyle line_style4 READ getLineStyle4 WRITE setLineStyle4 ) - Q_PROPERTY ( Qt::PenStyle line_style5 READ getLineStyle5 WRITE setLineStyle5 ) - Q_PROPERTY ( Qt::PenStyle line_style6 READ getLineStyle6 WRITE setLineStyle6 ) - Q_PROPERTY ( Qt::PenStyle line_style7 READ getLineStyle7 WRITE setLineStyle7 ) - Q_PROPERTY ( Qt::PenStyle line_style8 READ getLineStyle8 WRITE setLineStyle8 ) - Q_PROPERTY ( Qt::PenStyle line_style9 READ getLineStyle9 WRITE setLineStyle9 ) - - typedef QwtSymbol::Style QwtSymbolStyle; - - Q_ENUMS ( QwtSymbolStyle ) - Q_PROPERTY ( QwtSymbolStyle line_marker1 READ getLineMarker1 WRITE setLineMarker1 ) - Q_PROPERTY ( QwtSymbolStyle line_marker2 READ getLineMarker2 WRITE setLineMarker2 ) - Q_PROPERTY ( QwtSymbolStyle line_marker3 READ getLineMarker3 WRITE setLineMarker3 ) - Q_PROPERTY ( QwtSymbolStyle line_marker4 READ getLineMarker4 WRITE setLineMarker4 ) - Q_PROPERTY ( QwtSymbolStyle line_marker5 READ getLineMarker5 WRITE setLineMarker5 ) - Q_PROPERTY ( QwtSymbolStyle line_marker6 READ getLineMarker6 WRITE setLineMarker6 ) - Q_PROPERTY ( QwtSymbolStyle line_marker7 READ getLineMarker7 WRITE setLineMarker7 ) - Q_PROPERTY ( QwtSymbolStyle line_marker8 READ getLineMarker8 WRITE setLineMarker8 ) - Q_PROPERTY ( QwtSymbolStyle line_marker9 READ getLineMarker9 WRITE setLineMarker9 ) - - Q_PROPERTY ( int marker_alpha1 READ getMarkerAlpha1 WRITE setMarkerAlpha1 ) - Q_PROPERTY ( int marker_alpha2 READ getMarkerAlpha2 WRITE setMarkerAlpha2 ) - Q_PROPERTY ( int marker_alpha3 READ getMarkerAlpha3 WRITE setMarkerAlpha3 ) - Q_PROPERTY ( int marker_alpha4 READ getMarkerAlpha4 WRITE setMarkerAlpha4 ) - Q_PROPERTY ( int marker_alpha5 READ getMarkerAlpha5 WRITE setMarkerAlpha5 ) - Q_PROPERTY ( int marker_alpha6 READ getMarkerAlpha6 WRITE setMarkerAlpha6 ) - Q_PROPERTY ( int marker_alpha7 READ getMarkerAlpha7 WRITE setMarkerAlpha7 ) - Q_PROPERTY ( int marker_alpha8 READ getMarkerAlpha8 WRITE setMarkerAlpha8 ) - Q_PROPERTY ( int marker_alpha9 READ getMarkerAlpha9 WRITE setMarkerAlpha9 ) - - Q_PROPERTY ( QColor zoomer_color READ getZoomerColor WRITE setZoomerColor ) - Q_PROPERTY ( QColor palette_color READ getPaletteColor WRITE setPaletteColor ) - Q_PROPERTY ( int yaxis_label_font_size READ getYaxisLabelFontSize WRITE setYaxisLabelFontSize ) - Q_PROPERTY ( int xaxis_label_font_size READ getXaxisLabelFontSize WRITE setXaxisLabelFontSize ) - Q_PROPERTY ( int axes_label_font_size READ getAxesLabelFontSize WRITE setAxesLabelFontSize ) + Q_OBJECT -public: + Q_PROPERTY(QColor line_color1 READ getLineColor1 WRITE setLineColor1) + Q_PROPERTY(QColor line_color2 READ getLineColor2 WRITE setLineColor2) + Q_PROPERTY(QColor line_color3 READ getLineColor3 WRITE setLineColor3) + Q_PROPERTY(QColor line_color4 READ getLineColor4 WRITE setLineColor4) + Q_PROPERTY(QColor line_color5 READ getLineColor5 WRITE setLineColor5) + Q_PROPERTY(QColor line_color6 READ getLineColor6 WRITE setLineColor6) + Q_PROPERTY(QColor line_color7 READ getLineColor7 WRITE setLineColor7) + Q_PROPERTY(QColor line_color8 READ getLineColor8 WRITE setLineColor8) + Q_PROPERTY(QColor line_color9 READ getLineColor9 WRITE setLineColor9) + + Q_PROPERTY(int line_width1 READ getLineWidth1 WRITE setLineWidth1) + Q_PROPERTY(int line_width2 READ getLineWidth2 WRITE setLineWidth2) + Q_PROPERTY(int line_width3 READ getLineWidth3 WRITE setLineWidth3) + Q_PROPERTY(int line_width4 READ getLineWidth4 WRITE setLineWidth4) + Q_PROPERTY(int line_width5 READ getLineWidth5 WRITE setLineWidth5) + Q_PROPERTY(int line_width6 READ getLineWidth6 WRITE setLineWidth6) + Q_PROPERTY(int line_width7 READ getLineWidth7 WRITE setLineWidth7) + Q_PROPERTY(int line_width8 READ getLineWidth8 WRITE setLineWidth8) + Q_PROPERTY(int line_width9 READ getLineWidth9 WRITE setLineWidth9) + + Q_PROPERTY(Qt::PenStyle line_style1 READ getLineStyle1 WRITE setLineStyle1) + Q_PROPERTY(Qt::PenStyle line_style2 READ getLineStyle2 WRITE setLineStyle2) + Q_PROPERTY(Qt::PenStyle line_style3 READ getLineStyle3 WRITE setLineStyle3) + Q_PROPERTY(Qt::PenStyle line_style4 READ getLineStyle4 WRITE setLineStyle4) + Q_PROPERTY(Qt::PenStyle line_style5 READ getLineStyle5 WRITE setLineStyle5) + Q_PROPERTY(Qt::PenStyle line_style6 READ getLineStyle6 WRITE setLineStyle6) + Q_PROPERTY(Qt::PenStyle line_style7 READ getLineStyle7 WRITE setLineStyle7) + Q_PROPERTY(Qt::PenStyle line_style8 READ getLineStyle8 WRITE setLineStyle8) + Q_PROPERTY(Qt::PenStyle line_style9 READ getLineStyle9 WRITE setLineStyle9) + + typedef QwtSymbol::Style QwtSymbolStyle; + + Q_ENUMS(QwtSymbolStyle) + Q_PROPERTY(QwtSymbolStyle line_marker1 READ getLineMarker1 WRITE setLineMarker1) + Q_PROPERTY(QwtSymbolStyle line_marker2 READ getLineMarker2 WRITE setLineMarker2) + Q_PROPERTY(QwtSymbolStyle line_marker3 READ getLineMarker3 WRITE setLineMarker3) + Q_PROPERTY(QwtSymbolStyle line_marker4 READ getLineMarker4 WRITE setLineMarker4) + Q_PROPERTY(QwtSymbolStyle line_marker5 READ getLineMarker5 WRITE setLineMarker5) + Q_PROPERTY(QwtSymbolStyle line_marker6 READ getLineMarker6 WRITE setLineMarker6) + Q_PROPERTY(QwtSymbolStyle line_marker7 READ getLineMarker7 WRITE setLineMarker7) + Q_PROPERTY(QwtSymbolStyle line_marker8 READ getLineMarker8 WRITE setLineMarker8) + Q_PROPERTY(QwtSymbolStyle line_marker9 READ getLineMarker9 WRITE setLineMarker9) + + Q_PROPERTY(int marker_alpha1 READ getMarkerAlpha1 WRITE setMarkerAlpha1) + Q_PROPERTY(int marker_alpha2 READ getMarkerAlpha2 WRITE setMarkerAlpha2) + Q_PROPERTY(int marker_alpha3 READ getMarkerAlpha3 WRITE setMarkerAlpha3) + Q_PROPERTY(int marker_alpha4 READ getMarkerAlpha4 WRITE setMarkerAlpha4) + Q_PROPERTY(int marker_alpha5 READ getMarkerAlpha5 WRITE setMarkerAlpha5) + Q_PROPERTY(int marker_alpha6 READ getMarkerAlpha6 WRITE setMarkerAlpha6) + Q_PROPERTY(int marker_alpha7 READ getMarkerAlpha7 WRITE setMarkerAlpha7) + Q_PROPERTY(int marker_alpha8 READ getMarkerAlpha8 WRITE setMarkerAlpha8) + Q_PROPERTY(int marker_alpha9 READ getMarkerAlpha9 WRITE setMarkerAlpha9) + + Q_PROPERTY(QColor zoomer_color READ getZoomerColor WRITE setZoomerColor) + Q_PROPERTY(QColor palette_color READ getPaletteColor WRITE setPaletteColor) + Q_PROPERTY(int yaxis_label_font_size READ getYaxisLabelFontSize WRITE setYaxisLabelFontSize) + Q_PROPERTY(int xaxis_label_font_size READ getXaxisLabelFontSize WRITE setXaxisLabelFontSize) + Q_PROPERTY(int axes_label_font_size READ getAxesLabelFontSize WRITE setAxesLabelFontSize) - DisplayPlot(int nplots, QWidget*, - bool isdBgraph = false, - unsigned int xNumDivs = 10, +public: + DisplayPlot(int nplots, QWidget *, bool isdBgraph = false, unsigned int xNumDivs = 10, unsigned int yNumDivs = 10, int qwtAxis = QwtAxis::YLeft); - virtual ~DisplayPlot(); - - virtual void replot() = 0; - - const QColor getLineColor1 () const; - const QColor getLineColor2 () const; - const QColor getLineColor3 () const; - const QColor getLineColor4 () const; - const QColor getLineColor5 () const; - const QColor getLineColor6 () const; - const QColor getLineColor7 () const; - const QColor getLineColor8 () const; - const QColor getLineColor9 () const; - - int getLineWidth1 () const; - int getLineWidth2 () const; - int getLineWidth3 () const; - int getLineWidth4 () const; - int getLineWidth5 () const; - int getLineWidth6 () const; - int getLineWidth7 () const; - int getLineWidth8 () const; - int getLineWidth9 () const; - - const Qt::PenStyle getLineStyle1 () const; - const Qt::PenStyle getLineStyle2 () const; - const Qt::PenStyle getLineStyle3 () const; - const Qt::PenStyle getLineStyle4 () const; - const Qt::PenStyle getLineStyle5 () const; - const Qt::PenStyle getLineStyle6 () const; - const Qt::PenStyle getLineStyle7 () const; - const Qt::PenStyle getLineStyle8 () const; - const Qt::PenStyle getLineStyle9 () const; - - const QwtSymbol::Style getLineMarker1 () const; - const QwtSymbol::Style getLineMarker2 () const; - const QwtSymbol::Style getLineMarker3 () const; - const QwtSymbol::Style getLineMarker4 () const; - const QwtSymbol::Style getLineMarker5 () const; - const QwtSymbol::Style getLineMarker6 () const; - const QwtSymbol::Style getLineMarker7 () const; - const QwtSymbol::Style getLineMarker8 () const; - const QwtSymbol::Style getLineMarker9 () const; - - int getMarkerAlpha1 () const; - int getMarkerAlpha2 () const; - int getMarkerAlpha3 () const; - int getMarkerAlpha4 () const; - int getMarkerAlpha5 () const; - int getMarkerAlpha6 () const; - int getMarkerAlpha7 () const; - int getMarkerAlpha8 () const; - int getMarkerAlpha9 () const; - - QColor getZoomerColor() const; - QColor getPaletteColor() const; - int getAxisLabelFontSize(int axisId) const; - int getYaxisLabelFontSize() const; - int getXaxisLabelFontSize() const; - int getAxesLabelFontSize() const; - - void DetachCurve(unsigned int curveIdx); - void AttachCurve(unsigned int curveIdx); - QwtPlotCurve *Curve(unsigned int curveIdx); - - - void zoomBaseUpdate(bool force = false); - - void setMinXaxisDivision(double minDivison); - double minXaxisDivision(); - void setMaxXaxisDivision(double maxDivison); - double maxXaxisDivision(); - - void setMinYaxisDivision(double minDivison); - double minYaxisDivision(); - void setMaxYaxisDivision(double maxDivison); - double maxYaxisDivision(); - - void setLeftVertAxesCount(int count); - void removeLeftVertAxis(unsigned int axis); - int leftVertAxesCount(); - - void setUsingLeftAxisScales(bool on); - bool usingLeftAxisScales(); - - // Make sure to create your won PlotNewData method in the derived - // class: - // void PlotNewData(...); - QwtPlotZoomer *getZoomer() const; - void setZoomerParams(bool bounded, int maxStackDepth); - - void bringCurveToFront(unsigned int curveIdx); - void enableColoredLabels(bool colored); - - void enableMouseGesturesOnScales(bool enable); - - void setDisplayScale(double value); - void setAllYAxis(double min, double max); - - HorizHandlesArea* bottomHandlesArea(); - QWidget *rightHandlesArea(); - QWidget *leftHandlesArea(); - virtual QWidget *topHandlesArea(); - VertBar* vBar1(); - VertBar* vBar2(); - bool isLogaritmicPlot() const; - void setPlotLogaritmic(bool ); - bool isLogaritmicYPlot() const; - void setPlotYLogaritmic(bool value); - void setXaxisMajorTicksPos(QList); - QList getXaxisMajorTicksPos() const; - void setYaxisMajorTicksPos(QList); - QList getYaxisMajorTicksPos() const; - QWidget* getPlotwithElements(); - - bool vertCursorsEnabled(); - bool horizCursorsEnabled(); - struct cursorReadoutsText allCursorReadouts() const; - void trackModeEnabled(bool enabled); - void repositionCursors(); - void toggleCursors(bool en); - virtual QString formatXValue(double value, int precision) const; - virtual QString formatYValue(double value, int precision) const; - - void setCursorAxes(QwtAxisId fixed_axis, QwtAxisId mobile_axis); - CursorReadouts *getCursorReadouts() const; - - VertBar *getVBar1() const; - VertBar *getVBar2() const; - HorizBar *getHBar1() const; - HorizBar *getHBar2() const; - - void adjustHandleAreasSize(bool cursors = false); + virtual ~DisplayPlot(); + + virtual void replot() = 0; + + const QColor getLineColor1() const; + const QColor getLineColor2() const; + const QColor getLineColor3() const; + const QColor getLineColor4() const; + const QColor getLineColor5() const; + const QColor getLineColor6() const; + const QColor getLineColor7() const; + const QColor getLineColor8() const; + const QColor getLineColor9() const; + + int getLineWidth1() const; + int getLineWidth2() const; + int getLineWidth3() const; + int getLineWidth4() const; + int getLineWidth5() const; + int getLineWidth6() const; + int getLineWidth7() const; + int getLineWidth8() const; + int getLineWidth9() const; + + const Qt::PenStyle getLineStyle1() const; + const Qt::PenStyle getLineStyle2() const; + const Qt::PenStyle getLineStyle3() const; + const Qt::PenStyle getLineStyle4() const; + const Qt::PenStyle getLineStyle5() const; + const Qt::PenStyle getLineStyle6() const; + const Qt::PenStyle getLineStyle7() const; + const Qt::PenStyle getLineStyle8() const; + const Qt::PenStyle getLineStyle9() const; + + const QwtSymbol::Style getLineMarker1() const; + const QwtSymbol::Style getLineMarker2() const; + const QwtSymbol::Style getLineMarker3() const; + const QwtSymbol::Style getLineMarker4() const; + const QwtSymbol::Style getLineMarker5() const; + const QwtSymbol::Style getLineMarker6() const; + const QwtSymbol::Style getLineMarker7() const; + const QwtSymbol::Style getLineMarker8() const; + const QwtSymbol::Style getLineMarker9() const; + + int getMarkerAlpha1() const; + int getMarkerAlpha2() const; + int getMarkerAlpha3() const; + int getMarkerAlpha4() const; + int getMarkerAlpha5() const; + int getMarkerAlpha6() const; + int getMarkerAlpha7() const; + int getMarkerAlpha8() const; + int getMarkerAlpha9() const; + + QColor getZoomerColor() const; + QColor getPaletteColor() const; + int getAxisLabelFontSize(int axisId) const; + int getYaxisLabelFontSize() const; + int getXaxisLabelFontSize() const; + int getAxesLabelFontSize() const; + + void DetachCurve(unsigned int curveIdx); + void AttachCurve(unsigned int curveIdx); + QwtPlotCurve *Curve(unsigned int curveIdx); + + void zoomBaseUpdate(bool force = false); + + void setMinXaxisDivision(double minDivison); + double minXaxisDivision(); + void setMaxXaxisDivision(double maxDivison); + double maxXaxisDivision(); + + void setMinYaxisDivision(double minDivison); + double minYaxisDivision(); + void setMaxYaxisDivision(double maxDivison); + double maxYaxisDivision(); + + void setLeftVertAxesCount(int count); + void removeLeftVertAxis(unsigned int axis); + int leftVertAxesCount(); + + void setUsingLeftAxisScales(bool on); + bool usingLeftAxisScales(); + + // Make sure to create your won PlotNewData method in the derived + // class: + // void PlotNewData(...); + QwtPlotZoomer *getZoomer() const; + void setZoomerParams(bool bounded, int maxStackDepth); + + void bringCurveToFront(unsigned int curveIdx); + void enableColoredLabels(bool colored); + + void enableMouseGesturesOnScales(bool enable); + + void setDisplayScale(double value); + void setAllYAxis(double min, double max); + + HorizHandlesArea *bottomHandlesArea(); + QWidget *rightHandlesArea(); + QWidget *leftHandlesArea(); + virtual QWidget *topHandlesArea(); + VertBar *vBar1(); + VertBar *vBar2(); + bool isLogaritmicPlot() const; + void setPlotLogaritmic(bool); + bool isLogaritmicYPlot() const; + void setPlotYLogaritmic(bool value); + void setXaxisMajorTicksPos(QList); + QList getXaxisMajorTicksPos() const; + void setYaxisMajorTicksPos(QList); + QList getYaxisMajorTicksPos() const; + QWidget *getPlotwithElements(); + + bool vertCursorsEnabled(); + bool horizCursorsEnabled(); + struct cursorReadoutsText allCursorReadouts() const; + void trackModeEnabled(bool enabled); + void repositionCursors(); + void toggleCursors(bool en); + virtual QString formatXValue(double value, int precision) const; + virtual QString formatYValue(double value, int precision) const; + + void setCursorAxes(QwtAxisId fixed_axis, QwtAxisId mobile_axis); + CursorReadouts *getCursorReadouts() const; + + VertBar *getVBar1() const; + VertBar *getVBar2() const; + HorizBar *getHBar1() const; + HorizBar *getHBar2() const; + + void adjustHandleAreasSize(bool cursors = false); public Q_SLOTS: - virtual void disableLegend(); - virtual void setYaxis(double min, double max); - virtual void setXaxis(double min, double max); - virtual void setLineLabel(int which, QString label); - virtual QString getLineLabel(int which); - virtual void setLineColor(int which, QColor color); - void setLineColor(int chnIdx, int colorIdx); - virtual QColor getLineColor(int which) const; - virtual void setLineWidth(int which, qreal width); - virtual int getLineWidth(int which) const; - virtual void setLineStyle(int which, Qt::PenStyle style); - virtual const Qt::PenStyle getLineStyle(int which) const; - virtual void setLineMarker(int which, QwtSymbol::Style marker); - virtual const QwtSymbol::Style getLineMarker(int which) const; - virtual void setMarkerAlpha(int which, int alpha); - virtual int getMarkerAlpha(int which) const; - - virtual void horizAxisScaleIncrease(); - virtual void horizAxisScaleDecrease(); - virtual void vertAxisScaleIncrease(); - virtual void vertAxisScaleDecrease(); - - void setActiveVertAxis(unsigned int axisIdx, bool selected = true); - int activeVertAxis(); - - void setVertOffset(double offset, int axisIdx = 0); - double VertOffset(int axisIdx = 0); - void setHorizOffset(double offset); - double HorizOffset(); - void setVertUnitsPerDiv(double upd, int axisIdx = 0); - double VertUnitsPerDiv(int axisIdx = 0); - void setHorizUnitsPerDiv(double upd); - double HorizUnitsPerDiv(); - - // Need a function for each curve for setting via stylesheet. - // Can't use preprocessor directives because we're inside a Q_OBJECT. - void setLineColor1 (QColor); - void setLineColor2 (QColor); - void setLineColor3 (QColor); - void setLineColor4 (QColor); - void setLineColor5 (QColor); - void setLineColor6 (QColor); - void setLineColor7 (QColor); - void setLineColor8 (QColor); - void setLineColor9 (QColor); - - void setLineWidth1 (int); - void setLineWidth2 (int); - void setLineWidth3 (int); - void setLineWidth4 (int); - void setLineWidth5 (int); - void setLineWidth6 (int); - void setLineWidth7 (int); - void setLineWidth8 (int); - void setLineWidth9 (int); - - void setLineStyle1 (Qt::PenStyle); - void setLineStyle2 (Qt::PenStyle); - void setLineStyle3 (Qt::PenStyle); - void setLineStyle4 (Qt::PenStyle); - void setLineStyle5 (Qt::PenStyle); - void setLineStyle6 (Qt::PenStyle); - void setLineStyle7 (Qt::PenStyle); - void setLineStyle8 (Qt::PenStyle); - void setLineStyle9 (Qt::PenStyle); - - void setLineMarker1 (QwtSymbol::Style); - void setLineMarker2 (QwtSymbol::Style); - void setLineMarker3 (QwtSymbol::Style); - void setLineMarker4 (QwtSymbol::Style); - void setLineMarker5 (QwtSymbol::Style); - void setLineMarker6 (QwtSymbol::Style); - void setLineMarker7 (QwtSymbol::Style); - void setLineMarker8 (QwtSymbol::Style); - void setLineMarker9 (QwtSymbol::Style); - - void setMarkerAlpha1 (int); - void setMarkerAlpha2 (int); - void setMarkerAlpha3 (int); - void setMarkerAlpha4 (int); - void setMarkerAlpha5 (int); - void setMarkerAlpha6 (int); - void setMarkerAlpha7 (int); - void setMarkerAlpha8 (int); - void setMarkerAlpha9 (int); - - void printWithNoBackground(const QString& toolName = "", bool editScaleDraw = true); - - void setZoomerColor(QColor c); - void setPaletteColor(QColor c); - void setAxisLabelFontSize(int axisId, int fs); - void setYaxisLabelFontSize(int fs); - void setXaxisLabelFontSize(int fs); - void setAxesLabelFontSize(int fs); - void setXaxisMouseGesturesEnabled(bool en); - void setYaxisMouseGesturesEnabled(int axisId, bool en); - - void setStop(bool on); - - void resizeSlot(QSize *s); - - // Because of the preprocessing of slots in QT, these are not - // easily separated by the version check. Make one for each - // version until it's worked out. - void onPickerPointSelected(const QPointF & p); - void onPickerPointSelected6(const QPointF & p); - - unsigned int xAxisNumDiv() const; - unsigned int yAxisNumDiv() const; - - void setVertCursorsEnabled(bool en); - void setHorizCursorsEnabled(bool en); - void setVertCursorsHandleEnabled(bool en); - void setCursorReadoutsVisible(bool en); - void setHorizCursorsLocked(bool value); - void setVertCursorsLocked(bool value); - - void setCursorReadoutsTransparency(int value); - void moveCursorReadouts(CustomPlotPositionButton::ReadoutsPosition position); + virtual void disableLegend(); + virtual void setYaxis(double min, double max); + virtual void setXaxis(double min, double max); + virtual void setLineLabel(int which, QString label); + virtual QString getLineLabel(int which); + virtual void setLineColor(int which, QColor color); + void setLineColor(int chnIdx, int colorIdx); + virtual QColor getLineColor(int which) const; + virtual void setLineWidth(int which, qreal width); + virtual int getLineWidth(int which) const; + virtual void setLineStyle(int which, Qt::PenStyle style); + virtual const Qt::PenStyle getLineStyle(int which) const; + virtual void setLineMarker(int which, QwtSymbol::Style marker); + virtual const QwtSymbol::Style getLineMarker(int which) const; + virtual void setMarkerAlpha(int which, int alpha); + virtual int getMarkerAlpha(int which) const; + + virtual void horizAxisScaleIncrease(); + virtual void horizAxisScaleDecrease(); + virtual void vertAxisScaleIncrease(); + virtual void vertAxisScaleDecrease(); + + void setActiveVertAxis(unsigned int axisIdx, bool selected = true); + int activeVertAxis(); + + void setVertOffset(double offset, int axisIdx = 0); + double VertOffset(int axisIdx = 0); + void setHorizOffset(double offset); + double HorizOffset(); + void setVertUnitsPerDiv(double upd, int axisIdx = 0); + double VertUnitsPerDiv(int axisIdx = 0); + void setHorizUnitsPerDiv(double upd); + double HorizUnitsPerDiv(); + + // Need a function for each curve for setting via stylesheet. + // Can't use preprocessor directives because we're inside a Q_OBJECT. + void setLineColor1(QColor); + void setLineColor2(QColor); + void setLineColor3(QColor); + void setLineColor4(QColor); + void setLineColor5(QColor); + void setLineColor6(QColor); + void setLineColor7(QColor); + void setLineColor8(QColor); + void setLineColor9(QColor); + + void setLineWidth1(int); + void setLineWidth2(int); + void setLineWidth3(int); + void setLineWidth4(int); + void setLineWidth5(int); + void setLineWidth6(int); + void setLineWidth7(int); + void setLineWidth8(int); + void setLineWidth9(int); + + void setLineStyle1(Qt::PenStyle); + void setLineStyle2(Qt::PenStyle); + void setLineStyle3(Qt::PenStyle); + void setLineStyle4(Qt::PenStyle); + void setLineStyle5(Qt::PenStyle); + void setLineStyle6(Qt::PenStyle); + void setLineStyle7(Qt::PenStyle); + void setLineStyle8(Qt::PenStyle); + void setLineStyle9(Qt::PenStyle); + + void setLineMarker1(QwtSymbol::Style); + void setLineMarker2(QwtSymbol::Style); + void setLineMarker3(QwtSymbol::Style); + void setLineMarker4(QwtSymbol::Style); + void setLineMarker5(QwtSymbol::Style); + void setLineMarker6(QwtSymbol::Style); + void setLineMarker7(QwtSymbol::Style); + void setLineMarker8(QwtSymbol::Style); + void setLineMarker9(QwtSymbol::Style); + + void setMarkerAlpha1(int); + void setMarkerAlpha2(int); + void setMarkerAlpha3(int); + void setMarkerAlpha4(int); + void setMarkerAlpha5(int); + void setMarkerAlpha6(int); + void setMarkerAlpha7(int); + void setMarkerAlpha8(int); + void setMarkerAlpha9(int); + + void printWithNoBackground(const QString &toolName = "", bool editScaleDraw = true); + + void setZoomerColor(QColor c); + void setPaletteColor(QColor c); + void setAxisLabelFontSize(int axisId, int fs); + void setYaxisLabelFontSize(int fs); + void setXaxisLabelFontSize(int fs); + void setAxesLabelFontSize(int fs); + void setXaxisMouseGesturesEnabled(bool en); + void setYaxisMouseGesturesEnabled(int axisId, bool en); + + void setStop(bool on); + + void resizeSlot(QSize *s); + + // Because of the preprocessing of slots in QT, these are not + // easily separated by the version check. Make one for each + // version until it's worked out. + void onPickerPointSelected(const QPointF &p); + void onPickerPointSelected6(const QPointF &p); + + unsigned int xAxisNumDiv() const; + unsigned int yAxisNumDiv() const; + + void setVertCursorsEnabled(bool en); + void setHorizCursorsEnabled(bool en); + void setVertCursorsHandleEnabled(bool en); + void setCursorReadoutsVisible(bool en); + void setHorizCursorsLocked(bool value); + void setVertCursorsLocked(bool value); + + void setCursorReadoutsTransparency(int value); + void moveCursorReadouts(CustomPlotPositionButton::ReadoutsPosition position); Q_SIGNALS: - void horizScaleDivisionChanged(double); - void vertScaleDivisionChanged(double); - void horizScaleOffsetChanged(double); - void vertScaleOffsetChanged(double); + void horizScaleDivisionChanged(double); + void vertScaleDivisionChanged(double); + void horizScaleOffsetChanged(double); + void vertScaleOffsetChanged(double); - void plotPointSelected(const QPointF p); + void plotPointSelected(const QPointF p); - // signals that the plot size changed - void plotSizeChanged(); + // signals that the plot size changed + void plotSizeChanged(); - void cursorReadoutsChanged(struct cursorReadoutsText); + void cursorReadoutsChanged(struct cursorReadoutsText); private Q_SLOTS: - void onHbar1PixelPosChanged(int); - void onHbar2PixelPosChanged(int); - void onVbar1PixelPosChanged(int); - void onVbar2PixelPosChanged(int); + void onHbar1PixelPosChanged(int); + void onHbar2PixelPosChanged(int); + void onVbar1PixelPosChanged(int); + void onVbar2PixelPosChanged(int); - void onHorizCursorHandle1Changed(int value); - void onVertCursorHandle1Changed(int value); - void onVertCursorHandle2Changed(int value); - void onHorizCursorHandle2Changed(int value); + void onHorizCursorHandle1Changed(int value); + void onVertCursorHandle1Changed(int value); + void onVertCursorHandle2Changed(int value); + void onHorizCursorHandle2Changed(int value); protected Q_SLOTS: - virtual void legendEntryChecked(QwtPlotItem *plotItem, bool on); - virtual void legendEntryChecked(const QVariant &plotItem, bool on, int index); + virtual void legendEntryChecked(QwtPlotItem *plotItem, bool on); + virtual void legendEntryChecked(const QVariant &plotItem, bool on, int index); - void onHorizAxisOffsetDecrease(); - void onHorizAxisOffsetIncrease(); - void onVertAxisOffsetDecrease(); - void onVertAxisOffsetIncrease(); + void onHorizAxisOffsetDecrease(); + void onHorizAxisOffsetIncrease(); + void onVertAxisOffsetDecrease(); + void onVertAxisOffsetIncrease(); - virtual void onHCursor1Moved(double); - virtual void onHCursor2Moved(double); - virtual void onVCursor1Moved(double); - virtual void onVCursor2Moved(double); + virtual void onHCursor1Moved(double); + virtual void onHCursor2Moved(double); + virtual void onVCursor1Moved(double); + virtual void onVCursor2Moved(double); - void _onXbottomAxisWidgetScaleDivChanged(); - void _onYleftAxisWidgetScaleDivChanged(); + void _onXbottomAxisWidgetScaleDivChanged(); + void _onYleftAxisWidgetScaleDivChanged(); #ifdef __ANDROID__ - void mousePressEvent(QMouseEvent *event); + void mousePressEvent(QMouseEvent *event); #endif public: - PlotLineHandleV *d_vCursorHandle1; - PlotLineHandleV *d_vCursorHandle2; - PlotLineHandleH *d_hCursorHandle1; - PlotLineHandleH *d_hCursorHandle2; + PlotLineHandleV *d_vCursorHandle1; + PlotLineHandleV *d_vCursorHandle2; + PlotLineHandleH *d_hCursorHandle1; + PlotLineHandleH *d_hCursorHandle2; protected: + enum PlotMarker + { + V1Marker = 0, + V2Marker, + H1Marker, + H2Marker + }; - enum PlotMarker - { - V1Marker = 0, - V2Marker, - H1Marker, - H2Marker - }; - - int m_qwtYAxis; - int d_nplots; - std::vector d_plot_curve; + int m_qwtYAxis; + int d_nplots; + std::vector d_plot_curve; - QString d_yAxisUnit; - QString d_xAxisUnit; + QString d_yAxisUnit; + QString d_xAxisUnit; - QwtPlotPanner* d_panner; - QVector d_zoomer; - QwtPlotGrid *d_grid; + QwtPlotPanner *d_panner; + QVector d_zoomer; + QwtPlotGrid *d_grid; - QwtDblClickPlotPicker *d_picker; + QwtDblClickPlotPicker *d_picker; - std::vector vertAxes; - PlotAxisConfiguration *horizAxis; + std::vector vertAxes; + PlotAxisConfiguration *horizAxis; - QVector scaleItems; + QVector scaleItems; - int64_t d_numPoints; + int64_t d_numPoints; - bool d_stop; + bool d_stop; - double d_displayScale; + double d_displayScale; - QList d_CurveColors; - QList d_printColors; + QList d_CurveColors; + QList d_printColors; - bool d_autoscale_state; - int d_activeVertAxis; + bool d_autoscale_state; + int d_activeVertAxis; - double d_xAxisMin; - double d_xAxisMax; - double d_yAxisMin; - double d_yAxisMax; - unsigned int d_xAxisNumDiv; - unsigned int d_yAxisNumDiv; - bool d_usingLeftAxisScales; + double d_xAxisMin; + double d_xAxisMax; + double d_yAxisMin; + double d_yAxisMax; + unsigned int d_xAxisNumDiv; + unsigned int d_yAxisNumDiv; + bool d_usingLeftAxisScales; - NumberSeries d_hScaleDivisions; - NumberSeries d_vScaleDivisions; + NumberSeries d_hScaleDivisions; + NumberSeries d_vScaleDivisions; - void setXaxisNumDiv(unsigned int); - void setYaxisNumDiv(unsigned int); - void bottomHorizAxisInit(); - virtual void configureAxis(int axisPos, int axisIdx); + void setXaxisNumDiv(unsigned int); + void setYaxisNumDiv(unsigned int); + void bottomHorizAxisInit(); + virtual void configureAxis(int axisPos, int axisIdx); - void resizeEvent(QResizeEvent *event); + void resizeEvent(QResizeEvent *event); - HorizHandlesArea *d_bottomHandlesArea; - VertHandlesArea *d_rightHandlesArea; - VertHandlesArea *d_leftHandlesArea; - HorizHandlesArea *d_topHandlesArea; + HorizHandlesArea *d_bottomHandlesArea; + VertHandlesArea *d_rightHandlesArea; + VertHandlesArea *d_leftHandlesArea; + HorizHandlesArea *d_topHandlesArea; - VertBar *d_vBar1; - VertBar *d_vBar2; - HorizBar *d_hBar1; - HorizBar *d_hBar2; - SymbolController *d_symbolCtrl; + VertBar *d_vBar1; + VertBar *d_vBar2; + HorizBar *d_hBar1; + HorizBar *d_hBar2; + SymbolController *d_symbolCtrl; - struct cursorReadoutsText d_cursorReadoutsText; - CursorReadouts *d_cursorReadouts; + struct cursorReadoutsText d_cursorReadoutsText; + CursorReadouts *d_cursorReadouts; - bool d_trackMode; - int d_selected_channel; - bool d_cursorsEnabled; + bool d_trackMode; + int d_selected_channel; + bool d_cursorsEnabled; - QwtPlotMarker *markerIntersection1; - QwtPlotMarker *markerIntersection2; + QwtPlotMarker *markerIntersection1; + QwtPlotMarker *markerIntersection2; - double getHorizontalCursorIntersection(double time); + double getHorizontalCursorIntersection(double time); private: - void AddAxisOffset(int axisPos, int axisIdx, double offset); - bool d_coloredLabels; - bool d_mouseGesturesEnabled; - - bool d_vertCursorsHandleEnabled; - bool d_vertCursorsEnabled; - bool d_horizCursorsEnabled; - bool horizCursorsLocked; - bool vertCursorsLocked; - - int pixelPosHandleHoriz1; - int pixelPosHandleHoriz2; - int pixelPosHandleVert1; - int pixelPosHandleVert2; - - bool d_isLogaritmicPlot; - bool d_isLogaritmicYPlot; - QList d_majorTicks; - QList d_majorTicksY; - bool d_cursorReadoutsVisible; - PrefixFormatter * d_formatter; - - void setupCursors(); - void setupReadouts(); - void displayIntersection(); - void setupDisplayPlotDiv(bool isdBgraph); - + void AddAxisOffset(int axisPos, int axisIdx, double offset); + bool d_coloredLabels; + bool d_mouseGesturesEnabled; + + bool d_vertCursorsHandleEnabled; + bool d_vertCursorsEnabled; + bool d_horizCursorsEnabled; + bool horizCursorsLocked; + bool vertCursorsLocked; + + int pixelPosHandleHoriz1; + int pixelPosHandleHoriz2; + int pixelPosHandleVert1; + int pixelPosHandleVert2; + + bool d_isLogaritmicPlot; + bool d_isLogaritmicYPlot; + QList d_majorTicks; + QList d_majorTicksY; + bool d_cursorReadoutsVisible; + PrefixFormatter *d_formatter; + + void setupCursors(); + void setupReadouts(); + void displayIntersection(); + void setupDisplayPlotDiv(bool isdBgraph); }; /* * OscScaleDraw class overrides the way the major values are being displayed. */ -class SCOPY_GUI_EXPORT OscScaleDraw: public QwtScaleDraw +class SCOPY_GUI_EXPORT OscScaleDraw : public QwtScaleDraw { public: - OscScaleDraw(const QString& unit_type = ""); - OscScaleDraw(PrefixFormatter *, const QString&); - QwtText label( double ) const; + OscScaleDraw(const QString &unit_type = ""); + OscScaleDraw(PrefixFormatter *, const QString &); + QwtText label(double) const; void setFloatPrecision(unsigned int numDigits); unsigned int getFloatPrecison() const; - void setUnitType(const QString& unit); + void setUnitType(const QString &unit); QString getUnitType() const; void setColor(QColor color); @@ -757,19 +730,17 @@ class SCOPY_GUI_EXPORT OscScaleDraw: public QwtScaleDraw mutable unsigned int m_nrTicks; mutable bool m_shouldDrawMiddleDelta; bool m_delta; - }; -class SCOPY_GUI_EXPORT OscPlotZoomer: public ExtendingPlotZoomer +class SCOPY_GUI_EXPORT OscPlotZoomer : public ExtendingPlotZoomer { Q_OBJECT public: OscPlotZoomer(QwtAxisId xAxis, QwtAxisId yAxis, QWidget *parent, bool doReplot); - OscPlotZoomer(QWidget*, bool doReplot = true); + OscPlotZoomer(QWidget *, bool doReplot = true); void cancel() { reset(); } - Q_SIGNALS: void zoomIn(); void zoomOut(); @@ -791,7 +762,7 @@ class SCOPY_GUI_EXPORT PlotAxisConfiguration PlotAxisConfiguration(int axisPos, int axisIdx, DisplayPlot *plot); ~PlotAxisConfiguration(); - QwtAxisId& axis(); + QwtAxisId &axis(); void setPtsPerDiv(double value); double ptsPerDiv(); @@ -818,25 +789,23 @@ class SCOPY_GUI_EXPORT PlotAxisConfiguration /* * EdgelessPlotScaleItem class ensures that the first and last major ticks are ignored */ -class SCOPY_GUI_EXPORT EdgelessPlotScaleItem: public QwtPlotScaleItem +class SCOPY_GUI_EXPORT EdgelessPlotScaleItem : public QwtPlotScaleItem { public: - explicit EdgelessPlotScaleItem( - QwtScaleDraw::Alignment = QwtScaleDraw::BottomScale, - const double pos = 0.0); + explicit EdgelessPlotScaleItem(QwtScaleDraw::Alignment = QwtScaleDraw::BottomScale, const double pos = 0.0); virtual void updateScaleDiv(const QwtScaleDiv &, const QwtScaleDiv &); }; /* * EdgelessPlotGrid class ensures that the first and last major ticks are ignored */ -class SCOPY_GUI_EXPORT EdgelessPlotGrid: public QwtPlotGrid +class SCOPY_GUI_EXPORT EdgelessPlotGrid : public QwtPlotGrid { public: explicit EdgelessPlotGrid(); virtual void updateScaleDiv(const QwtScaleDiv &, const QwtScaleDiv &); }; -} // scopy +} // namespace scopy #endif /* M2K_DISPLAY_PLOT_H */ diff --git a/gui/include/gui/FftDisplayPlot.h b/gui/include/gui/FftDisplayPlot.h index b0f76d3666..d5830c6c9b 100644 --- a/gui/include/gui/FftDisplayPlot.h +++ b/gui/include/gui/FftDisplayPlot.h @@ -22,265 +22,264 @@ #define FFT_DISPLAY_PLOT_H #include "DisplayPlot.h" -#include "spectrum_marker.hpp" -#include "symbol_controller.h" -#include "plot_line_handle.h" -#include "handles_area.hpp" #include "cursor_readouts.h" +#include "handles_area.hpp" +#include "plot_line_handle.h" #include "scopy-gui_export.h" +#include "spectrum_marker.hpp" +#include "symbol_controller.h" namespace scopy { - class SpectrumAverage; - class SpectrumMarker; - class MarkerController; -} +class SpectrumAverage; +class SpectrumMarker; +class MarkerController; +} // namespace scopy namespace scopy { - struct marker { - std::shared_ptr data; - std::shared_ptr ui; +struct marker +{ + std::shared_ptr data; + std::shared_ptr ui; +}; + +struct marker_data +{ + int type; + float x; + float y; + int bin; + bool active; + bool update_ui; + QString label; +}; + +class SCOPY_GUI_EXPORT FftDisplayPlot : public DisplayPlot +{ + Q_OBJECT + +public: + enum AverageType + { + SAMPLE = 0, + PEAK_HOLD = 1, + PEAK_HOLD_CONTINUOUS = 2, + MIN_HOLD = 3, + MIN_HOLD_CONTINUOUS = 4, + LINEAR_RMS = 5, + LINEAR_DB = 6, + EXPONENTIAL_RMS = 7, + EXPONENTIAL_DB = 8, }; - struct marker_data { - int type; - float x; - float y; - int bin; - bool active; - bool update_ui; - QString label; + enum MagnitudeType + { + DBFS = 0, + DBV = 1, + DBU = 2, + VPEAK = 3, + VRMS = 4, + VROOTHZ = 5 }; - class SCOPY_GUI_EXPORT FftDisplayPlot : public DisplayPlot + enum MarkerType { - Q_OBJECT - - public: - enum AverageType { - SAMPLE = 0, - PEAK_HOLD = 1, - PEAK_HOLD_CONTINUOUS = 2, - MIN_HOLD = 3, - MIN_HOLD_CONTINUOUS = 4, - LINEAR_RMS = 5, - LINEAR_DB = 6, - EXPONENTIAL_RMS = 7, - EXPONENTIAL_DB = 8, - }; - - enum MagnitudeType { - DBFS = 0, - DBV = 1, - DBU = 2, - VPEAK = 3, - VRMS = 4, - VROOTHZ = 5 - }; - - enum MarkerType { - MANUAL = 0, - PEAK = 1, - DELTA = 2, - FIXED = 3, - }; + MANUAL = 0, + PEAK = 1, + DELTA = 2, + FIXED = 3, + }; typedef std::shared_ptr average_sptr; - private: - QList> d_markers; - double* x_data; - std::vector y_data; - std::vector y_original_data; - - std::vector y_scale_factor; - - double d_start_frequency; - double d_stop_frequency; - double d_sampl_rate; - double d_preset_sampl_rate; - - bool d_firstInit; - - double m_sweepStart; - double m_sweepStop; - bool m_visiblePeakSearch; - bool d_logScaleEnabled; - double m_top; - double m_bottom; - - MetricPrefixFormatter dBFormatter; - MetricPrefixFormatter freqFormatter; - PrefixFormatter *d_formatter; - - std::vector d_ch_average_type; - std::vector d_ch_avg_obj; - std::vector d_current_avg_index; - - enum MagnitudeType d_presetMagType; - enum MagnitudeType d_magType; - - MarkerController *d_mrkCtrl; - QList d_num_markers; - - QList>> d_peaks; - QList>> d_freq_asc_sorted_peaks; - bool d_emitNewMkrData; - - QList d_markerColors; - - QMap d_ref_curves; - unsigned int n_ref_curves; - std::vector d_refXdata; - std::vector d_refYdata; - - std::vector d_win_coefficient_sum; - std::vector d_win_coefficient_sum_sqr; - unsigned int d_buffer_idx; - unsigned int d_nb_overlapping_avg; - std::vector> d_ps_avg; - - void setupReadouts(); - void updateHandleAreaPadding(); - - void plotData(const std::vector &pts, - uint64_t num_points); - void _resetXAxisPoints(); - - void resetAverages(); - void averageDataAndComputeMagnitude(std::vector - in_data, std::vector out_data, - uint64_t nb_points); - average_sptr getNewAvgObject(enum AverageType avg_type, - uint data_width, uint history, bool history_en); - - void add_marker(int chn); - void remove_marker(int chn, int which); - void marker_set_pos_source(uint chIdx, uint mkIdx, - std::shared_ptr &source_sptr); - void findPeaks(int chn); - void calculate_fixed_markers(int chn); - int getMarkerPos(const QList& marker_list, - std::shared_ptr &marker) const; - void detectMarkers(); - - QColor getChannelColor(); - - private Q_SLOTS: - void onMrkCtrlMarkerSelected(std::shared_ptr &); - void onMrkCtrlMarkerPosChanged(std::shared_ptr &); - void onMrkCtrlMarkerReleased(std::shared_ptr &); - - void onHCursor1Moved(double); - void onHCursor2Moved(double); - void onVCursor1Moved(double); - void onVCursor2Moved(double); - public: - explicit FftDisplayPlot(int nplots, QWidget *parent = nullptr); - ~FftDisplayPlot(); - - void initChannelMeasurement(int nplots); - std::vector getOrginal_data(); - std::vector getRef_data(); - int64_t getYdata_size(); - std::vector getScaleFactor(); - int64_t getNumPoints(); - - bool isReferenceWaveform(unsigned int chnIdx); - size_t getCurveSize(unsigned int chnIdx); - - // Scaling factors for plot samples (one per channel) - double channelScaleFactor(int chIdx) const; - void setScaleFactor(int chIdx, double scale); - - int64_t posAtFrequency(double freq, int chIdx = -1) const; - QString leftVerAxisUnit() const; - void setLeftVertAxisUnit(const QString& unit); - - QString btmHorAxisUnit() const; - void setBtmHorAxisUnit(const QString& unit); - - enum MagnitudeType magnitudeType() const; - void setMagnitudeType(enum MagnitudeType); - - enum AverageType averageType(uint chIdx) const; - uint averageHistory(uint chIdx) const; - void setAverage(uint chIdx, enum AverageType avg_type, - uint history, bool history_en = true); - void resetAverageHistory(); - void setStartStop(double start, double stop); - void setVisiblePeakSearch(bool enabled); - - // Markers - uint peakCount(uint chIdx) const; - void setPeakCount(uint chIdx, uint count); - - uint markerCount(uint chIdx) const; - void setMarkerCount(uint chIdx, uint count); - - bool markerEnabled(uint chIdx, uint mkIdx) const; - void setMarkerEnabled(uint chIdx, uint mkIdx, bool en); - - bool markerVisible(uint chIdx, uint mkIdx) const; - void setMarkerVisible(uint chIdx, uint mkIdx, bool en); - - double markerFrequency(uint chIdx, uint mkIdx) const; - double markerMagnitude(uint chIdx, uint mkIdx) const; - - void setMarkerAtFreq(uint chIdx, uint mkIdx, double pos); - - int markerType(uint chIdx, uint mkIdx) const; - - void marker_to_max_peak(uint chIdx, uint mkIdx); - void marker_to_next_higher_freq_peak(uint chIdx, uint mkIdx); - void marker_to_next_lower_freq_peak(uint chIdx, uint mkIdx); - void marker_to_next_higher_mag_peak(uint chIdx, uint mkIdx); - void marker_to_next_lower_mag_peak(uint chIdx, uint mkIdx); - - void updateMarkerUi(uint chIdx, uint mkIdx); - void updateMarkersUi(); - - void selectMarker(uint chIdx, uint mkIdx); - - void recalculateMagnitudes(); - void replot(); - void setZoomerEnabled(); - double sampleRate(); - void setNumPoints(uint64_t num_points); - - void registerReferenceWaveform(QString name, QVector xData, QVector yData); - void unregisterReferenceWaveform(QString name); - - void setWindowCoefficientSum(unsigned int ch, float sum, float sqr_sum); - void setNbOverlappingAverages(unsigned int nb_avg); - void useLogScaleY(bool log_scale); - - bool eventFilter(QObject *, QEvent *); - void enableXaxisLabels(); - void enableYaxisLabels(); - QString formatXValue(double value, int precision) const; - QString formatYValue(double value, int precision) const; - void setAmplitude(double top, double bottom); - void updateZoomerBase(); - Q_SIGNALS: - void channelAdded(int); - void newFFTData(); - void sampleRateUpdated(double); - void sampleCountUpdated(uint); - void newMarkerData(); - void markerSelected(uint chIdx, uint mkIdx); - void currentAverageIndex(unsigned int chnIdx, unsigned int avgIdx); - - public Q_SLOTS: - void setSampleRate(double sr, double units, - const std::string &strunits); - void presetSampleRate(double sr); - void useLogFreq(bool use_log_freq); - void customEvent(QEvent *e); - void showEvent(QShowEvent *event); - bool getLogScale() const; - void setSelectedChannel(int id); - }; -} +private: + QList> d_markers; + double *x_data; + std::vector y_data; + std::vector y_original_data; + + std::vector y_scale_factor; + + double d_start_frequency; + double d_stop_frequency; + double d_sampl_rate; + double d_preset_sampl_rate; + + bool d_firstInit; + + double m_sweepStart; + double m_sweepStop; + bool m_visiblePeakSearch; + bool d_logScaleEnabled; + double m_top; + double m_bottom; + + MetricPrefixFormatter dBFormatter; + MetricPrefixFormatter freqFormatter; + PrefixFormatter *d_formatter; + + std::vector d_ch_average_type; + std::vector d_ch_avg_obj; + std::vector d_current_avg_index; + + enum MagnitudeType d_presetMagType; + enum MagnitudeType d_magType; + + MarkerController *d_mrkCtrl; + QList d_num_markers; + + QList>> d_peaks; + QList>> d_freq_asc_sorted_peaks; + bool d_emitNewMkrData; + + QList d_markerColors; + + QMap d_ref_curves; + unsigned int n_ref_curves; + std::vector d_refXdata; + std::vector d_refYdata; + + std::vector d_win_coefficient_sum; + std::vector d_win_coefficient_sum_sqr; + unsigned int d_buffer_idx; + unsigned int d_nb_overlapping_avg; + std::vector> d_ps_avg; + + void setupReadouts(); + void updateHandleAreaPadding(); + + void plotData(const std::vector &pts, uint64_t num_points); + void _resetXAxisPoints(); + + void resetAverages(); + void averageDataAndComputeMagnitude(std::vector in_data, std::vector out_data, + uint64_t nb_points); + average_sptr getNewAvgObject(enum AverageType avg_type, uint data_width, uint history, bool history_en); + + void add_marker(int chn); + void remove_marker(int chn, int which); + void marker_set_pos_source(uint chIdx, uint mkIdx, std::shared_ptr &source_sptr); + void findPeaks(int chn); + void calculate_fixed_markers(int chn); + int getMarkerPos(const QList &marker_list, std::shared_ptr &marker) const; + void detectMarkers(); + + QColor getChannelColor(); + +private Q_SLOTS: + void onMrkCtrlMarkerSelected(std::shared_ptr &); + void onMrkCtrlMarkerPosChanged(std::shared_ptr &); + void onMrkCtrlMarkerReleased(std::shared_ptr &); + + void onHCursor1Moved(double); + void onHCursor2Moved(double); + void onVCursor1Moved(double); + void onVCursor2Moved(double); + +public: + explicit FftDisplayPlot(int nplots, QWidget *parent = nullptr); + ~FftDisplayPlot(); + + void initChannelMeasurement(int nplots); + std::vector getOrginal_data(); + std::vector getRef_data(); + int64_t getYdata_size(); + std::vector getScaleFactor(); + int64_t getNumPoints(); + + bool isReferenceWaveform(unsigned int chnIdx); + size_t getCurveSize(unsigned int chnIdx); + + // Scaling factors for plot samples (one per channel) + double channelScaleFactor(int chIdx) const; + void setScaleFactor(int chIdx, double scale); + + int64_t posAtFrequency(double freq, int chIdx = -1) const; + QString leftVerAxisUnit() const; + void setLeftVertAxisUnit(const QString &unit); + + QString btmHorAxisUnit() const; + void setBtmHorAxisUnit(const QString &unit); + + enum MagnitudeType magnitudeType() const; + void setMagnitudeType(enum MagnitudeType); + + enum AverageType averageType(uint chIdx) const; + uint averageHistory(uint chIdx) const; + void setAverage(uint chIdx, enum AverageType avg_type, uint history, bool history_en = true); + void resetAverageHistory(); + void setStartStop(double start, double stop); + void setVisiblePeakSearch(bool enabled); + + // Markers + uint peakCount(uint chIdx) const; + void setPeakCount(uint chIdx, uint count); + + uint markerCount(uint chIdx) const; + void setMarkerCount(uint chIdx, uint count); + + bool markerEnabled(uint chIdx, uint mkIdx) const; + void setMarkerEnabled(uint chIdx, uint mkIdx, bool en); + + bool markerVisible(uint chIdx, uint mkIdx) const; + void setMarkerVisible(uint chIdx, uint mkIdx, bool en); + + double markerFrequency(uint chIdx, uint mkIdx) const; + double markerMagnitude(uint chIdx, uint mkIdx) const; + + void setMarkerAtFreq(uint chIdx, uint mkIdx, double pos); + + int markerType(uint chIdx, uint mkIdx) const; + + void marker_to_max_peak(uint chIdx, uint mkIdx); + void marker_to_next_higher_freq_peak(uint chIdx, uint mkIdx); + void marker_to_next_lower_freq_peak(uint chIdx, uint mkIdx); + void marker_to_next_higher_mag_peak(uint chIdx, uint mkIdx); + void marker_to_next_lower_mag_peak(uint chIdx, uint mkIdx); + + void updateMarkerUi(uint chIdx, uint mkIdx); + void updateMarkersUi(); + + void selectMarker(uint chIdx, uint mkIdx); + + void recalculateMagnitudes(); + void replot(); + void setZoomerEnabled(); + double sampleRate(); + void setNumPoints(uint64_t num_points); + + void registerReferenceWaveform(QString name, QVector xData, QVector yData); + void unregisterReferenceWaveform(QString name); + + void setWindowCoefficientSum(unsigned int ch, float sum, float sqr_sum); + void setNbOverlappingAverages(unsigned int nb_avg); + void useLogScaleY(bool log_scale); + + bool eventFilter(QObject *, QEvent *); + void enableXaxisLabels(); + void enableYaxisLabels(); + QString formatXValue(double value, int precision) const; + QString formatYValue(double value, int precision) const; + void setAmplitude(double top, double bottom); + void updateZoomerBase(); +Q_SIGNALS: + void channelAdded(int); + void newFFTData(); + void sampleRateUpdated(double); + void sampleCountUpdated(uint); + void newMarkerData(); + void markerSelected(uint chIdx, uint mkIdx); + void currentAverageIndex(unsigned int chnIdx, unsigned int avgIdx); + +public Q_SLOTS: + void setSampleRate(double sr, double units, const std::string &strunits); + void presetSampleRate(double sr); + void useLogFreq(bool use_log_freq); + void customEvent(QEvent *e); + void showEvent(QShowEvent *event); + bool getLogScale() const; + void setSelectedChannel(int id); +}; +} // namespace scopy #endif /* FFT_DISPLAY_PLOT_H */ diff --git a/gui/include/gui/HistogramDisplayPlot.h b/gui/include/gui/HistogramDisplayPlot.h index 53f1a8ac1d..81fb35ef7e 100644 --- a/gui/include/gui/HistogramDisplayPlot.h +++ b/gui/include/gui/HistogramDisplayPlot.h @@ -41,123 +41,123 @@ #ifndef M2K_HISTOGRAM_DISPLAY_PLOT_H #define M2K_HISTOGRAM_DISPLAY_PLOT_H -#include -#include -#include - #include "DisplayPlot.h" -#include "spectrumUpdateEvents.h" #include "scopy-gui_export.h" +#include "spectrumUpdateEvents.h" #include -namespace scopy { +#include +#include +#include +namespace scopy { -class SCOPY_GUI_EXPORT HistogramScaleDraw: public QwtScaleDraw +class SCOPY_GUI_EXPORT HistogramScaleDraw : public QwtScaleDraw { public: HistogramScaleDraw(); - QwtText label( double ) const; + QwtText label(double) const; void setColor(const QColor &color); void setTotalSamples(unsigned int totalSamples); + private: unsigned int m_totalSamples; QColor m_color; }; -class Histogram: public QwtPlotHistogram +class Histogram : public QwtPlotHistogram { public: - Histogram(const QString& title, const QColor& color); - void setColor(const QColor& color); + Histogram(const QString &title, const QColor &color); + void setColor(const QColor &color); void setValues(const double *xData, const double *yData, unsigned int nr_bins); void setOrientation(Qt::Orientation orientation); int getMaxHeight(); private: QVector m_samples; - }; /*! * \brief QWidget for displaying time domain plots. * \ingroup qtgui_blk */ -class SCOPY_GUI_EXPORT HistogramDisplayPlot: public DisplayPlot +class SCOPY_GUI_EXPORT HistogramDisplayPlot : public DisplayPlot { - Q_OBJECT + Q_OBJECT public: - HistogramDisplayPlot(int nplots, QWidget*); - virtual ~HistogramDisplayPlot(); + HistogramDisplayPlot(int nplots, QWidget *); + virtual ~HistogramDisplayPlot(); - void plotNewData(const std::vector dataPoints, - const int64_t numDataPoints, const double timeInterval); + void plotNewData(const std::vector dataPoints, const int64_t numDataPoints, + const double timeInterval); - void replot(); + void replot(); - void setXaxisSpan(double start, double stop); - void setDataInterval(int min, int max); - void setOrientation(Qt::Orientation orientation); - Qt::Orientation getOrientation(); - bool isZoomed(); + void setXaxisSpan(double start, double stop); + void setDataInterval(int min, int max); + void setOrientation(Qt::Orientation orientation); + Qt::Orientation getOrientation(); + bool isZoomed(); public Q_SLOTS: - void setAutoScale(bool state); - void setAutoScaleX(); - void setSemilogx(bool en); - void setSemilogy(bool en); - void setAccumulate(bool en); + void setAutoScale(bool state); + void setAutoScaleX(); + void setSemilogx(bool en); + void setSemilogy(bool en); + void setAccumulate(bool en); - void setMarkerAlpha(int which, int alpha); - int getMarkerAlpha(int which) const; - void setLineColor(int which, QColor color); + void setMarkerAlpha(int which, int alpha); + int getMarkerAlpha(int which) const; + void setLineColor(int which, QColor color); - void setNumBins(int bins); - void setXaxis(double min, double max); + void setNumBins(int bins); + void setXaxis(double min, double max); - void customEvent(QEvent * e); + void customEvent(QEvent *e); - void enableChannel(unsigned int chIdx, bool enable); - void setYaxisSpan(unsigned int chIdx, double bot, double top); - void setSelectedChannel(unsigned int value); + void enableChannel(unsigned int chIdx, bool enable); + void setYaxisSpan(unsigned int chIdx, double bot, double top); + void setSelectedChannel(unsigned int value); private Q_SLOTS: - void newData(const QEvent*); + void newData(const QEvent *); + + void _onZoom(const QRectF &rect); - void _onZoom(const QRectF &rect); private: - void _resetXAxisPoints(double left, double right); - void _autoScaleY(double bottom, double top); - void _updateXScales(unsigned int totalSamples); - void _orientationChanged(); - void _resetZoom(); - - std::vector d_histograms; - std::vector rightVertAxes; - double d_height; - PrefixFormatter *d_pf; - - double* d_xdata; - std::vector d_ydata; - - int d_bins; - bool d_accum; - double d_xmin, d_xmax, d_left, d_right; - double d_width; - int d_minPos, d_maxPos; - - bool d_semilogx; - bool d_semilogy; - bool d_autoscalex_state; - bool stop; - bool d_zoomed; - - Qt::Orientation d_orientation; - std::vector horizAxes; - unsigned int d_selected_channel; + void _resetXAxisPoints(double left, double right); + void _autoScaleY(double bottom, double top); + void _updateXScales(unsigned int totalSamples); + void _orientationChanged(); + void _resetZoom(); + + std::vector d_histograms; + std::vector rightVertAxes; + double d_height; + PrefixFormatter *d_pf; + + double *d_xdata; + std::vector d_ydata; + + int d_bins; + bool d_accum; + double d_xmin, d_xmax, d_left, d_right; + double d_width; + int d_minPos, d_maxPos; + + bool d_semilogx; + bool d_semilogy; + bool d_autoscalex_state; + bool stop; + bool d_zoomed; + + Qt::Orientation d_orientation; + std::vector horizAxes; + unsigned int d_selected_channel; }; -} //scopy +} // namespace scopy #endif /* M2K_HISTOGRAM_DISPLAY_PLOT_H */ diff --git a/gui/include/gui/TimeDomainDisplayPlot.h b/gui/include/gui/TimeDomainDisplayPlot.h index 450cdaf0ae..70f3f8ef02 100644 --- a/gui/include/gui/TimeDomainDisplayPlot.h +++ b/gui/include/gui/TimeDomainDisplayPlot.h @@ -42,27 +42,30 @@ #ifndef M2K_TIME_DOMAIN_DISPLAY_PLOT_H #define M2K_TIME_DOMAIN_DISPLAY_PLOT_H -#include -#include -#include - #include "DisplayPlot.h" -#include "spectrumUpdateEvents.h" #include "scopy-gui_export.h" +#include "spectrumUpdateEvents.h" +#include +#include +#include namespace scopy { -class SCOPY_GUI_EXPORT Sink{ +class SCOPY_GUI_EXPORT Sink +{ public: - Sink(const std::string &name, unsigned int numChannels, unsigned long long channelsDataLength): - d_name(name), d_numChannels(numChannels), d_channelsDataLength(channelsDataLength) { } + Sink(const std::string &name, unsigned int numChannels, unsigned long long channelsDataLength) + : d_name(name) + , d_numChannels(numChannels) + , d_channelsDataLength(channelsDataLength) + {} std::string name() { return d_name; } unsigned int numChannels() { return d_numChannels; } unsigned int channelsDataLength() { return d_channelsDataLength; } - void setChannelsDataLength(unsigned long long num) { d_channelsDataLength = num; } + void setChannelsDataLength(unsigned long long num) { d_channelsDataLength = num; } private: std::string d_name; @@ -76,15 +79,14 @@ class SCOPY_GUI_EXPORT SinkManager SinkManager(); ~SinkManager(); - bool addSink(const std::string& name, unsigned int numChannels, unsigned long long channelsDataLength); - bool removeSink(const std::string& name); + bool addSink(const std::string &name, unsigned int numChannels, unsigned long long channelsDataLength); + bool removeSink(const std::string &name); unsigned int sinkListLength(); - Sink* sink(unsigned int index); - int indexOfSink(const std::string& name); - int sinkFirstChannelPos(const std::string& name); + Sink *sink(unsigned int index); + int indexOfSink(const std::string &name); + int sinkFirstChannelPos(const std::string &name); private: - std::vector d_sinkList; }; @@ -92,186 +94,184 @@ class SCOPY_GUI_EXPORT SinkManager * \brief QWidget for displaying time domain plots. * \ingroup qtgui_blk */ -class SCOPY_GUI_EXPORT TimeDomainDisplayPlot: public DisplayPlot +class SCOPY_GUI_EXPORT TimeDomainDisplayPlot : public DisplayPlot { - Q_OBJECT + Q_OBJECT - Q_PROPERTY ( QColor tag_text_color READ getTagTextColor WRITE setTagTextColor ) - Q_PROPERTY ( QColor tag_background_color READ getTagBackgroundColor WRITE setTagBackgroundColor ) - Q_PROPERTY ( Qt::BrushStyle tag_background_style READ getTagBackgroundStyle WRITE setTagBackgroundStyle ) + Q_PROPERTY(QColor tag_text_color READ getTagTextColor WRITE setTagTextColor) + Q_PROPERTY(QColor tag_background_color READ getTagBackgroundColor WRITE setTagBackgroundColor) + Q_PROPERTY(Qt::BrushStyle tag_background_style READ getTagBackgroundStyle WRITE setTagBackgroundStyle) public: - TimeDomainDisplayPlot(QWidget*, bool isdBgraph = false, unsigned int xNumDivs = 10, unsigned int yNumDivs = 10, - PrefixFormatter* pfXaxis = nullptr, PrefixFormatter* pfYaxis = nullptr, int qwtAxis = QwtAxis::YLeft); - virtual ~TimeDomainDisplayPlot(); + TimeDomainDisplayPlot(QWidget *, bool isdBgraph = false, unsigned int xNumDivs = 10, unsigned int yNumDivs = 10, + PrefixFormatter *pfXaxis = nullptr, PrefixFormatter *pfYaxis = nullptr, + int qwtAxis = QwtAxis::YLeft); + virtual ~TimeDomainDisplayPlot(); - void plotNewData(const std::string &sender, - const std::vector &dataPoints, - const int64_t numDataPoints, const double timeInterval/*, - const std::vector< std::vector > &tags \ - = std::vector< std::vector >()*/ - ); - void replot(); + void plotNewData(const std::string &sender, const std::vector &dataPoints, + const int64_t numDataPoints, const double timeInterval /*, + const std::vector< std::vector > &tags \ + = std::vector< std::vector >()*/ + ); + void replot(); - void stemPlot(bool en); + void stemPlot(bool en); - void setPlotLineStyle(unsigned int chIdx, unsigned int style); - int getPlotLineStyle(unsigned int chIdx) const; + void setPlotLineStyle(unsigned int chIdx, unsigned int style); + int getPlotLineStyle(unsigned int chIdx) const; - double sampleRate() const; + double sampleRate() const; - void setYaxisUnit(QString unitType, int axisIdx = 0); - QString yAxisUnit(void); - QString yAxisUnit(int axisIdx); + void setYaxisUnit(QString unitType, int axisIdx = 0); + QString yAxisUnit(void); + QString yAxisUnit(int axisIdx); - void setXaxisUnit(QString unitType); - QString xAxisUnit(void); + void setXaxisUnit(QString unitType); + QString xAxisUnit(void); - const QColor getTagTextColor(); - const QColor getTagBackgroundColor(); - const Qt::BrushStyle getTagBackgroundStyle(); + const QColor getTagTextColor(); + const QColor getTagBackgroundColor(); + const Qt::BrushStyle getTagBackgroundStyle(); - QString timeScaleValueFormat(double value, int precision) const; - QString timeScaleValueFormat(double value); - QString yAxisScaleValueFormat(double value, int precision) const; - QString yAxisScaleValueFormat(double value); + QString timeScaleValueFormat(double value, int precision) const; + QString timeScaleValueFormat(double value); + QString yAxisScaleValueFormat(double value, int precision) const; + QString yAxisScaleValueFormat(double value); - bool registerSink(std::string sinkUniqueNme, unsigned int numChannels, - unsigned long long channelsDataLength, bool curvesAttached = true); - bool unregisterSink(std::string sinkName); + bool registerSink(std::string sinkUniqueNme, unsigned int numChannels, unsigned long long channelsDataLength, + bool curvesAttached = true); + bool unregisterSink(std::string sinkName); - bool registerMathWaveform(const std::string &sinkUniqueNme, unsigned int numChannels, - unsigned long long channelsDataLength, bool curvesAttached = true); - bool unregisterMathWaveform(const std::string &sinkName); + bool registerMathWaveform(const std::string &sinkUniqueNme, unsigned int numChannels, + unsigned long long channelsDataLength, bool curvesAttached = true); + bool unregisterMathWaveform(const std::string &sinkName); - long dataStartingPoint() const; + long dataStartingPoint() const; - void addZoomer(unsigned int zoomerIdx); - void removeZoomer(unsigned int zoomerIdx); - void setXAxisNumPoints(unsigned int); + void addZoomer(unsigned int zoomerIdx); + void removeZoomer(unsigned int zoomerIdx); + void setXAxisNumPoints(unsigned int); - void registerReferenceWaveform(QString name, QVector xData, QVector yData); - void unregisterReferenceWaveform(QString name); - void addPreview(QVector> curvesToBePreviewed, double reftimebase, - double timebase, double timeposition); - void clearPreview(); - void realignReferenceWaveforms(double timebase, double timeposition); + void registerReferenceWaveform(QString name, QVector xData, QVector yData); + void unregisterReferenceWaveform(QString name); + void addPreview(QVector> curvesToBePreviewed, double reftimebase, double timebase, + double timeposition); + void clearPreview(); + void realignReferenceWaveforms(double timebase, double timeposition); - void addDigitalPlotCurve(QwtPlotCurve *curve, bool visible); - void removeDigitalPlotCurve(QwtPlotCurve *curve); - void enableDigitalPlotCurve(int curveId, bool enable); - QwtPlotCurve *getDigitalPlotCurve(int curveId); - int getNrDigitalPlotCurves() const; - bool getPlotGrTags() const; - void setPlotGrTags(bool val); + void addDigitalPlotCurve(QwtPlotCurve *curve, bool visible); + void removeDigitalPlotCurve(QwtPlotCurve *curve); + void enableDigitalPlotCurve(int curveId, bool enable); + QwtPlotCurve *getDigitalPlotCurve(int curveId); + int getNrDigitalPlotCurves() const; + bool getPlotGrTags() const; + void setPlotGrTags(bool val); - void configureAllYAxis(); + void configureAllYAxis(); Q_SIGNALS: - void channelAdded(int); - void newData(); - void filledScreen(bool, unsigned int); - void digitalPlotCurveAdded(int); + void channelAdded(int); + void newData(); + void filledScreen(bool, unsigned int); + void digitalPlotCurveAdded(int); public Q_SLOTS: - void setSampleRate(double sr, double units, - const std::string &strunits); + void setSampleRate(double sr, double units, const std::string &strunits); - void setAutoScale(bool state); - void setAutoScaleShot(); - void setSemilogx(bool en); - void setSemilogy(bool en); + void setAutoScale(bool state); + void setAutoScaleShot(); + void setSemilogx(bool en); + void setSemilogy(bool en); - void setLineWidthF(int which, qreal widthF); - qreal getLineWidthF(int which) const; + void setLineWidthF(int which, qreal widthF); + qreal getLineWidthF(int which) const; - void legendEntryChecked(QwtPlotItem *plotItem, bool on); - void legendEntryChecked(const QVariant &plotItem, bool on, int index); + void legendEntryChecked(QwtPlotItem *plotItem, bool on); + void legendEntryChecked(const QVariant &plotItem, bool on, int index); - void enableTagMarker(int which, bool en); + void enableTagMarker(int which, bool en); - void setYLabel(const std::string &label, - const std::string &unit="", - int axisIdx = 0); + void setYLabel(const std::string &label, const std::string &unit = "", int axisIdx = 0); - void attachTriggerLines(bool en); - void setTriggerLines(double x, double y); + void attachTriggerLines(bool en); + void setTriggerLines(double x, double y); - void setTagTextColor(QColor c); - void setTagBackgroundColor(QColor c); - void setTagBackgroundStyle(Qt::BrushStyle b); + void setTagTextColor(QColor c); + void setTagBackgroundColor(QColor c); + void setTagBackgroundStyle(Qt::BrushStyle b); - void setZoomerEnabled(bool en); - bool isZoomerEnabled(); - void setZoomerVertAxis(int index); + void setZoomerEnabled(bool en); + bool isZoomerEnabled(); + void setZoomerVertAxis(int index); - void customEvent(QEvent * e); + void customEvent(QEvent *e); - void cancelZoom(); + void cancelZoom(); - void setDataStartingPoint(long pos); - void resetXaxisOnNextReceivedData(); - void hideCurvesUntilNewData(); + void setDataStartingPoint(long pos); + void resetXaxisOnNextReceivedData(); + void hideCurvesUntilNewData(); - void updatePreview(double reftimebase, double timebase, double timeposition); + void updatePreview(double reftimebase, double timebase, double timeposition); protected: - virtual void configureAxis(int axisPos, int axisIdx, PrefixFormatter* prefixFormatter); - virtual void cleanUpJustBeforeChannelRemoval(int chnIdx); + virtual void configureAxis(int axisPos, int axisIdx, PrefixFormatter *prefixFormatter); + virtual void cleanUpJustBeforeChannelRemoval(int chnIdx); private Q_SLOTS: - void newData(const QEvent*); + void newData(const QEvent *); protected: - std::vector d_ydata; - std::vector d_xdata; - std::vector d_ref_ydata; - QVector> d_preview_xdata; - QVector> d_preview_ydata; - QVector d_preview_curves; - bool isReferenceWaveform(QwtPlotCurve *curve); - bool isMathWaveform(QwtPlotCurve *curve) const; - int countReferenceWaveform(int position); - QVector d_logic_curves; + std::vector d_ydata; + std::vector d_xdata; + std::vector d_ref_ydata; + QVector> d_preview_xdata; + QVector> d_preview_ydata; + QVector d_preview_curves; + bool isReferenceWaveform(QwtPlotCurve *curve); + bool isMathWaveform(QwtPlotCurve *curve) const; + int countReferenceWaveform(int position); + QVector d_logic_curves; + private: - void _resetXAxisPoints(double*& xAxis, unsigned long long numPoints, double sampleRate); - void _autoScale(double bottom, double top); -// void plotTags(const std::vector > &tags); + void _resetXAxisPoints(double *&xAxis, unsigned long long numPoints, double sampleRate); + void _autoScale(double bottom, double top); + // void plotTags(const std::vector > &tags); - double d_sample_rate; - double d_delay; - long d_data_starting_point; - std::vector d_sink_reset_x_axis_pts; + double d_sample_rate; + double d_delay; + long d_data_starting_point; + std::vector d_sink_reset_x_axis_pts; - bool d_semilogx; - bool d_semilogy; - bool d_autoscale_shot; - bool d_plotGrTags; + bool d_semilogx; + bool d_semilogy; + bool d_autoscale_shot; + bool d_plotGrTags; - std::vector< std::vector > d_tag_markers; - std::vector d_tag_markers_en; + std::vector> d_tag_markers; + std::vector d_tag_markers_en; - PrefixFormatter* d_xAxisFormatter; - PrefixFormatter* d_yAxisFormatter; + PrefixFormatter *d_xAxisFormatter; + PrefixFormatter *d_yAxisFormatter; - QColor d_tag_text_color; - QColor d_tag_background_color; - Qt::BrushStyle d_tag_background_style; + QColor d_tag_text_color; + QColor d_tag_background_color; + Qt::BrushStyle d_tag_background_style; - QwtPlotMarker *d_trigger_lines[2]; + QwtPlotMarker *d_trigger_lines[2]; - SinkManager d_sinkManager; + SinkManager d_sinkManager; - unsigned int d_nbPtsXAxis; - bool d_curves_hidden; + unsigned int d_nbPtsXAxis; + bool d_curves_hidden; - QColor getChannelColor(); + QColor getChannelColor(); - QMap d_ref_curves; - QMap d_math_curves; - int d_nb_ref_curves; - int getCurveNextTo(int pos); + QMap d_ref_curves; + QMap d_math_curves; + int d_nb_ref_curves; + int getCurveNextTo(int pos); }; -} //scopy +} // namespace scopy #endif /* M2K_TIME_DOMAIN_DISPLAY_PLOT_H */ diff --git a/gui/include/gui/WaterfallDisplayPlot.h b/gui/include/gui/WaterfallDisplayPlot.h index f15e8622a6..09769cdac7 100644 --- a/gui/include/gui/WaterfallDisplayPlot.h +++ b/gui/include/gui/WaterfallDisplayPlot.h @@ -30,16 +30,19 @@ #ifndef WATERFALL_DISPLAY_PLOT_H #define WATERFALL_DISPLAY_PLOT_H -#include #include "DisplayPlot.h" + +#include //#include "spectrum_analyzer.hpp" +#include "scopy-gui_export.h" #include "waterfallGlobalData.h" + +#include #include + #include #include #include -#include -#include "scopy-gui_export.h" #if QWT_VERSION < 0x060000 #include @@ -56,17 +59,19 @@ typedef QwtInterval QwtDoubleInterval; class SCOPY_GUI_EXPORT ColorMap_DefaultDark : public QwtLinearColorMap { public: - ColorMap_DefaultDark() : QwtLinearColorMap(Qt::black, Qt::white) + ColorMap_DefaultDark() + : QwtLinearColorMap(Qt::black, Qt::white) { addColorStop(0.16, Qt::black); - addColorStop(0.33, QColor(58, 36, 59)); // deep purple + addColorStop(0.33, QColor(58, 36, 59)); // deep purple addColorStop(0.5, QColor(74, 100, 255)); // scopy blue addColorStop(0.66, QColor(255, 144, 0)); // scopy orange addColorStop(0.83, Qt::white); } }; -enum { - INTENSITY_COLOR_MAP_TYPE_DEFAULT_DARK = 7 +enum +{ + INTENSITY_COLOR_MAP_TYPE_DEFAULT_DARK = 7 }; /*! @@ -79,31 +84,25 @@ class SCOPY_GUI_EXPORT WaterfallDisplayPlot : public DisplayPlot friend class SpectrumAnalyzer_API; Q_OBJECT - Q_PROPERTY(int intensity_color_map_type1 READ getIntensityColorMapType1 WRITE - setIntensityColorMapType1) - Q_PROPERTY(QColor low_intensity_color READ getUserDefinedLowIntensityColor WRITE - setUserDefinedLowIntensityColor) + Q_PROPERTY(int intensity_color_map_type1 READ getIntensityColorMapType1 WRITE setIntensityColorMapType1) + Q_PROPERTY( + QColor low_intensity_color READ getUserDefinedLowIntensityColor WRITE setUserDefinedLowIntensityColor) Q_PROPERTY(QColor high_intensity_color READ getUserDefinedHighIntensityColor WRITE - setUserDefinedHighIntensityColor) - Q_PROPERTY(int color_map_title_font_size READ getColorMapTitleFontSize WRITE - setColorMapTitleFontSize) - + setUserDefinedHighIntensityColor) + Q_PROPERTY(int color_map_title_font_size READ getColorMapTitleFontSize WRITE setColorMapTitleFontSize) public: - WaterfallDisplayPlot(int nplots, QWidget*); + WaterfallDisplayPlot(int nplots, QWidget *); ~WaterfallDisplayPlot() override; void resetAxis(bool resetData = true); - void setFrequencyRange(const double, - const double, - const double units = 1000.0, - const std::string& strunits = "kHz"); + void setFrequencyRange(const double, const double, const double units = 1000.0, + const std::string &strunits = "kHz"); double getStartFrequency() const; double getStopFrequency() const; - void plotNewData(const std::vector &dataPoints, - const int64_t numDataPoints, + void plotNewData(const std::vector &dataPoints, const int64_t numDataPoints, gr::high_res_timer_type acquisitionTime); void setIntensityRange(double minIntensity, double maxIntensity); @@ -151,8 +150,7 @@ class SCOPY_GUI_EXPORT WaterfallDisplayPlot : public DisplayPlot void useLogFreq(bool use_log_freq); void updateZoomerBase(); public Q_SLOTS: - void - setIntensityColorMapType(const unsigned int, const int, const QColor, const QColor); + void setIntensityColorMapType(const unsigned int, const int, const QColor, const QColor); void setIntensityColorMapType1(int); void setColorMapTitleFontSize(int tfs); void setUserDefinedLowIntensityColor(QColor); @@ -201,15 +199,15 @@ private Q_SLOTS: double d_last_draw_time; double d_center_plot_time; - std::vector d_data; + std::vector d_data; TimePrefixFormatter d_TimeFormatter; MetricPrefixFormatter freqFormatter; PrefixFormatter *d_formatter; #if QWT_VERSION < 0x060000 - std::vector d_spectrogram; + std::vector d_spectrogram; #else - std::vector d_spectrogram; + std::vector d_spectrogram; #endif std::vector d_intensity_color_map_type; @@ -217,6 +215,6 @@ private Q_SLOTS: QColor d_user_defined_high_intensity_color; int d_color_bar_title_font_size; }; -} +} // namespace scopy #endif /* WATERFALL_DISPLAY_PLOT_H */ diff --git a/gui/include/gui/animationmanager.h b/gui/include/gui/animationmanager.h index b6531139ed..987677b6fc 100644 --- a/gui/include/gui/animationmanager.h +++ b/gui/include/gui/animationmanager.h @@ -22,27 +22,29 @@ #define ANIMATIONMANAGER_H #include "scopy-gui_export.h" -#include + #include +#include + namespace scopy { class SCOPY_GUI_EXPORT AnimationManager : public QObject { - Q_OBJECT + Q_OBJECT public: - static AnimationManager& getInstance(); - void toggleAnimations(bool on); + static AnimationManager &getInstance(); + void toggleAnimations(bool on); - void registerAnimation(CustomAnimation *animation); + void registerAnimation(CustomAnimation *animation); Q_SIGNALS: - void toggle(bool); + void toggle(bool); private: AnimationManager(); - bool m_animationsEnabled; + bool m_animationsEnabled; }; -} +} // namespace scopy #endif // ANIMATIONMANAGER_H diff --git a/gui/include/gui/animationpushbutton.h b/gui/include/gui/animationpushbutton.h index dafc6799f3..ecd593abb6 100644 --- a/gui/include/gui/animationpushbutton.h +++ b/gui/include/gui/animationpushbutton.h @@ -1,12 +1,14 @@ #ifndef ANIMATIONPUSHBUTTON_H #define ANIMATIONPUSHBUTTON_H -#include #include "scopy-gui_export.h" + #include +#include namespace scopy { -class SCOPY_GUI_EXPORT AnimationPushButton : public QPushButton { +class SCOPY_GUI_EXPORT AnimationPushButton : public QPushButton +{ Q_OBJECT public: explicit AnimationPushButton(QWidget *parent = Q_NULLPTR); @@ -26,6 +28,6 @@ private Q_SLOTS: QString m_currentText; QIcon m_currentIcon; }; -} +} // namespace scopy #endif // ANIMATIONPUSHBUTTON_H diff --git a/gui/include/gui/autoScaler.hpp b/gui/include/gui/autoScaler.hpp index 1cab1ec231..165a707844 100644 --- a/gui/include/gui/autoScaler.hpp +++ b/gui/include/gui/autoScaler.hpp @@ -21,44 +21,42 @@ #ifndef AUTO_SCALER_HPP #define AUTO_SCALER_HPP -#include +#include "scopy-gui_export.h" +#include #include #include -#include "scopy-gui_export.h" namespace scopy { - class SCOPY_GUI_EXPORT AutoScaler : public QObject - { - Q_OBJECT; - - public: - explicit AutoScaler(QObject *parent, - const QVector &divs, - unsigned int timeout_ms = 3000); - ~AutoScaler(); - - Q_SIGNALS: - void updateScale(const QwtScaleDiv); - - public Q_SLOTS: - void setValue(double val); - void startTimer(); - void stopTimer(); - void setTimeout(int timeout_ms); - void addScaleDivs(QwtScaleDiv div); - - private Q_SLOTS: - void timeout(); - - private: - QVector divs; - QTimer timer; - double min, max, scale_min, scale_max; - const QwtScaleDiv *current_div; - - void changeScaleDiv(const QwtScaleDiv *div); - }; +class SCOPY_GUI_EXPORT AutoScaler : public QObject +{ + Q_OBJECT; + +public: + explicit AutoScaler(QObject *parent, const QVector &divs, unsigned int timeout_ms = 3000); + ~AutoScaler(); + +Q_SIGNALS: + void updateScale(const QwtScaleDiv); + +public Q_SLOTS: + void setValue(double val); + void startTimer(); + void stopTimer(); + void setTimeout(int timeout_ms); + void addScaleDivs(QwtScaleDiv div); + +private Q_SLOTS: + void timeout(); + +private: + QVector divs; + QTimer timer; + double min, max, scale_min, scale_max; + const QwtScaleDiv *current_div; + + void changeScaleDiv(const QwtScaleDiv *div); }; +}; // namespace scopy #endif /* AUTO_SCALER_HPP */ diff --git a/gui/include/gui/average.h b/gui/include/gui/average.h index 830677108b..d04d606906 100644 --- a/gui/include/gui/average.h +++ b/gui/include/gui/average.h @@ -21,19 +21,19 @@ #ifndef AVERAGE_H #define AVERAGE_H -#include #include "scopy-gui_export.h" -namespace scopy { +#include +namespace scopy { -class SCOPY_GUI_EXPORT SpectrumAverage { +class SCOPY_GUI_EXPORT SpectrumAverage +{ public: SpectrumAverage(unsigned int data_width, unsigned int history, bool history_en); virtual ~SpectrumAverage(); virtual void pushNewData(double *data) = 0; - virtual void getAverage(double *out_data, - unsigned int num_samples) const; + virtual void getAverage(double *out_data, unsigned int num_samples) const; virtual void reset() = 0; unsigned int dataWidth() const; unsigned int history() const; @@ -47,7 +47,7 @@ class SCOPY_GUI_EXPORT SpectrumAverage { double *m_average; }; -class SCOPY_GUI_EXPORT AverageHistoryOne: public SpectrumAverage +class SCOPY_GUI_EXPORT AverageHistoryOne : public SpectrumAverage { public: AverageHistoryOne(unsigned int data_width, unsigned history); @@ -57,7 +57,7 @@ class SCOPY_GUI_EXPORT AverageHistoryOne: public SpectrumAverage bool m_anyDataPushed; }; -class SCOPY_GUI_EXPORT AverageHistoryN: public SpectrumAverage +class SCOPY_GUI_EXPORT AverageHistoryN : public SpectrumAverage { public: AverageHistoryN(unsigned int data_width, unsigned int history); @@ -77,35 +77,35 @@ class SCOPY_GUI_EXPORT AverageHistoryN: public SpectrumAverage void setHistory(unsigned int) override; }; -class SCOPY_GUI_EXPORT PeakHoldContinuous: public AverageHistoryOne +class SCOPY_GUI_EXPORT PeakHoldContinuous : public AverageHistoryOne { public: PeakHoldContinuous(unsigned int data_width, unsigned int history); virtual void pushNewData(double *data); }; -class SCOPY_GUI_EXPORT MinHoldContinuous: public AverageHistoryOne +class SCOPY_GUI_EXPORT MinHoldContinuous : public AverageHistoryOne { public: MinHoldContinuous(unsigned int data_width, unsigned int history); virtual void pushNewData(double *data); }; -class SCOPY_GUI_EXPORT ExponentialRMS: public AverageHistoryOne +class SCOPY_GUI_EXPORT ExponentialRMS : public AverageHistoryOne { public: ExponentialRMS(unsigned int data_width, unsigned int history); virtual void pushNewData(double *data); }; -class SCOPY_GUI_EXPORT ExponentialAverage: public AverageHistoryOne +class SCOPY_GUI_EXPORT ExponentialAverage : public AverageHistoryOne { public: ExponentialAverage(unsigned int data_width, unsigned int history); virtual void pushNewData(double *data); }; -class SCOPY_GUI_EXPORT LinearRMSOne: public AverageHistoryOne +class SCOPY_GUI_EXPORT LinearRMSOne : public AverageHistoryOne { public: LinearRMSOne(unsigned int data_width, unsigned int history); @@ -117,7 +117,7 @@ class SCOPY_GUI_EXPORT LinearRMSOne: public AverageHistoryOne unsigned int m_inserted_count; }; -class SCOPY_GUI_EXPORT LinearAverageOne: public AverageHistoryOne +class SCOPY_GUI_EXPORT LinearAverageOne : public AverageHistoryOne { public: LinearAverageOne(unsigned int data_width, unsigned int history); @@ -129,7 +129,7 @@ class SCOPY_GUI_EXPORT LinearAverageOne: public AverageHistoryOne unsigned int m_inserted_count; }; -class SCOPY_GUI_EXPORT PeakHold: public AverageHistoryN +class SCOPY_GUI_EXPORT PeakHold : public AverageHistoryN { public: PeakHold(unsigned int data_width, unsigned int history); @@ -139,7 +139,7 @@ class SCOPY_GUI_EXPORT PeakHold: public AverageHistoryN double getPeakFromHistoryColumn(unsigned int col); }; -class SCOPY_GUI_EXPORT MinHold: public AverageHistoryN +class SCOPY_GUI_EXPORT MinHold : public AverageHistoryN { public: MinHold(unsigned int data_width, unsigned int history); @@ -149,28 +149,26 @@ class SCOPY_GUI_EXPORT MinHold: public AverageHistoryN double getMinFromHistoryColumn(unsigned int col); }; -class SCOPY_GUI_EXPORT LinearRMS: public AverageHistoryN +class SCOPY_GUI_EXPORT LinearRMS : public AverageHistoryN { public: LinearRMS(unsigned int data_width, unsigned int history); ~LinearRMS(); virtual void pushNewData(double *data); - virtual void getAverage(double *out_data, - unsigned int num_samples) const; + virtual void getAverage(double *out_data, unsigned int num_samples) const; virtual void reset(); private: double *m_sqr_sums; }; -class SCOPY_GUI_EXPORT LinearAverage: public AverageHistoryN +class SCOPY_GUI_EXPORT LinearAverage : public AverageHistoryN { public: LinearAverage(unsigned int data_width, unsigned int history); ~LinearAverage(); virtual void pushNewData(double *data); - virtual void getAverage(double *out_data, - unsigned int num_samples) const; + virtual void getAverage(double *out_data, unsigned int num_samples) const; virtual void reset(); private: diff --git a/gui/include/gui/basemenu.h b/gui/include/gui/basemenu.h index 1de9b0f544..b6b6f3b35f 100644 --- a/gui/include/gui/basemenu.h +++ b/gui/include/gui/basemenu.h @@ -21,9 +21,10 @@ #ifndef BASEMENU_H #define BASEMENU_H -#include -#include "scopy-gui_export.h" #include "basemenuitem.h" +#include "scopy-gui_export.h" + +#include namespace Ui { class BaseMenu; @@ -43,7 +44,7 @@ class SCOPY_GUI_EXPORT BaseMenu : public QWidget void removeMenuItem(BaseMenuItem *menuItem); void removeMenuItem(QVector items); - int positionOf(BaseMenuItem* menuItem); + int positionOf(BaseMenuItem *menuItem); void setMargins(int left, int top, int right, int bottom); @@ -66,6 +67,6 @@ public Q_SLOTS: int d_items; void _updateItemsPosition(); }; -} +} // namespace scopy #endif // BASEMENU_H diff --git a/gui/include/gui/basemenuitem.h b/gui/include/gui/basemenuitem.h index 0421c337de..526af86103 100644 --- a/gui/include/gui/basemenuitem.h +++ b/gui/include/gui/basemenuitem.h @@ -22,10 +22,11 @@ #define BASEMENUITEM_H #include "scopy-gui_export.h" -#include -#include + #include #include +#include +#include namespace Ui { class BaseMenuItem; @@ -76,7 +77,6 @@ class SCOPY_GUI_EXPORT BaseMenuItem : public QWidget void leaveEvent(QEvent *event); protected: - void _enableBotSeparator(bool enable); void _enableTopSeparator(bool enable); @@ -95,6 +95,6 @@ class SCOPY_GUI_EXPORT BaseMenuItem : public QWidget bool d_allowDrag; bool d_draggable; }; -} +} // namespace scopy #endif // BASEMENUITEM_H diff --git a/gui/include/gui/buffer_previewer.hpp b/gui/include/gui/buffer_previewer.hpp index 0d4934116c..8cfc645b35 100644 --- a/gui/include/gui/buffer_previewer.hpp +++ b/gui/include/gui/buffer_previewer.hpp @@ -22,19 +22,19 @@ #ifndef BUFFER_PREVIEWER_H #define BUFFER_PREVIEWER_H -#include #include "scopy-gui_export.h" -namespace scopy{ +#include + +namespace scopy { -class SCOPY_GUI_EXPORT BufferPreviewer: public QFrame +class SCOPY_GUI_EXPORT BufferPreviewer : public QFrame { Q_OBJECT public: explicit BufferPreviewer(QWidget *parent = 0); - explicit BufferPreviewer(int pixelsPerPeriod, double wavePhase, - QWidget *parent = 0); + explicit BufferPreviewer(int pixelsPerPeriod, double wavePhase, QWidget *parent = 0); virtual ~BufferPreviewer(); double waveformPos() const; @@ -103,18 +103,17 @@ class SCOPY_GUI_EXPORT BufferPreviewer: public QFrame bool m_cursorVisible; }; -class SCOPY_GUI_EXPORT AnalogBufferPreviewer: public BufferPreviewer +class SCOPY_GUI_EXPORT AnalogBufferPreviewer : public BufferPreviewer { public: explicit AnalogBufferPreviewer(QWidget *parent = 0); - explicit AnalogBufferPreviewer(int pixelsPerPeriod, double wavePhase, - QWidget *parent = 0); + explicit AnalogBufferPreviewer(int pixelsPerPeriod, double wavePhase, QWidget *parent = 0); protected: virtual void buildFullWaveform(QPointF *wavePoints, int numPts); }; -class SCOPY_GUI_EXPORT DigitalBufferPreviewer: public BufferPreviewer +class SCOPY_GUI_EXPORT DigitalBufferPreviewer : public BufferPreviewer { public: explicit DigitalBufferPreviewer(QWidget *parent = 0); @@ -124,6 +123,7 @@ class SCOPY_GUI_EXPORT DigitalBufferPreviewer: public BufferPreviewer protected: virtual void buildFullWaveform(QPointF *wavePoints, int numPts); + private: double m_noOfSteps; }; diff --git a/gui/include/gui/channel_manager.hpp b/gui/include/gui/channel_manager.hpp index c5e3492cc8..8e2ad4b1cc 100644 --- a/gui/include/gui/channel_manager.hpp +++ b/gui/include/gui/channel_manager.hpp @@ -1,15 +1,15 @@ #ifndef CHANNEL_MANAGER_HPP #define CHANNEL_MANAGER_HPP -#include -#include -#include -#include - #include "channel_widget.hpp" #include "customPushButton.h" #include "scopy-gui_export.h" +#include +#include +#include +#include + namespace scopy { namespace gui { @@ -25,22 +25,22 @@ class SCOPY_GUI_EXPORT ChannelManager : public QWidget public: explicit ChannelManager(ChannelsPositionEnum position = ChannelsPositionEnum::HORIZONTAL, - QWidget* parent = nullptr); + QWidget *parent = nullptr); ~ChannelManager(); - void build(QWidget* parent); - void insertAddBtn(QWidget* menu, bool dockable); + void build(QWidget *parent); + void insertAddBtn(QWidget *menu, bool dockable); - ChannelWidget* buildNewChannel(int chId, bool deletable, bool simplefied, QColor color, const QString& fullName, - const QString& shortName); - void removeChannel(ChannelWidget* ch); - QList getEnabledChannels(); + ChannelWidget *buildNewChannel(int chId, bool deletable, bool simplefied, QColor color, const QString &fullName, + const QString &shortName); + void removeChannel(ChannelWidget *ch); + QList getEnabledChannels(); - CustomPushButton* getAddChannelBtn(); - QList getChannelsList(); + CustomPushButton *getAddChannelBtn(); + QList getChannelsList(); int getChannelsCount(); - void setChannelAlignment(ChannelWidget* ch,Qt::Alignment alignment); + void setChannelAlignment(ChannelWidget *ch, Qt::Alignment alignment); void setChannelIdVisible(bool visible); const QString &getToolStatus() const; void setToolStatus(const QString &newToolStatus); @@ -50,7 +50,7 @@ class SCOPY_GUI_EXPORT ChannelManager : public QWidget const ChannelWidget *getChannelAt(int id); void updatePosition(ChannelsPositionEnum position); public Q_SLOTS: - void changeParent(QWidget* newParent); + void changeParent(QWidget *newParent); void toggleChannelManager(bool toggled); void onChannelSelected(bool toggled); @@ -58,7 +58,7 @@ public Q_SLOTS: void onChannelDeleted(); Q_SIGNALS: - void configureAddBtn(QWidget* menu, bool dockable); + void configureAddBtn(QWidget *menu, bool dockable); void positionChanged(ChannelsPositionEnum position); void channelManagerToggle(bool toggled); @@ -67,15 +67,15 @@ public Q_SLOTS: void deletedChannel(QString name); private: - QWidget* m_parent; - QWidget* header; - QScrollArea* m_scrollArea; - QWidget* m_channelsWidget; + QWidget *m_parent; + QWidget *header; + QScrollArea *m_scrollArea; + QWidget *m_channelsWidget; bool m_hasAddBtn; QPushButton *m_switchBtn; - CustomPushButton* m_addChannelBtn; + CustomPushButton *m_addChannelBtn; ChannelsPositionEnum m_position; - QList m_channelsList; + QList m_channelsList; bool m_channelIdVisible; QPushButton *toggleChannels; bool channelManagerToggled; diff --git a/gui/include/gui/channel_widget.hpp b/gui/include/gui/channel_widget.hpp index 204aad77a1..80ebaab85f 100644 --- a/gui/include/gui/channel_widget.hpp +++ b/gui/include/gui/channel_widget.hpp @@ -20,11 +20,12 @@ #ifndef CHANNEL_WIDGET_HPP #define CHANNEL_WIDGET_HPP -#include -#include -#include #include "scopy-gui_export.h" + +#include #include +#include +#include namespace Ui { class Channel; @@ -32,21 +33,20 @@ class Channel; namespace scopy { -class SCOPY_GUI_EXPORT ChannelWidget: public QWidget +class SCOPY_GUI_EXPORT ChannelWidget : public QWidget { Q_OBJECT public: - explicit ChannelWidget(int id, bool deletable, bool simplified, - QColor color, QWidget *parent = 0); + explicit ChannelWidget(int id, bool deletable, bool simplified, QColor color, QWidget *parent = 0); ~ChannelWidget(); - QAbstractButton* enableButton() const; - QAbstractButton* nameButton() const; - QAbstractButton* menuButton() const; - QAbstractButton* deleteButton() const; - QAbstractButton* toggleChannelsButton() const; + QAbstractButton *enableButton() const; + QAbstractButton *nameButton() const; + QAbstractButton *menuButton() const; + QAbstractButton *deleteButton() const; + QAbstractButton *toggleChannelsButton() const; int id() const; void setId(int); @@ -54,19 +54,19 @@ class SCOPY_GUI_EXPORT ChannelWidget: public QWidget QColor color() const; QString fullName() const; - void setFullName(const QString&); + void setFullName(const QString &); QString shortName() const; - void setShortName(const QString&); + void setShortName(const QString &); QString function() const; void setFunction(const QString &); bool isMathChannel() const; - void setMathChannel(const bool&); + void setMathChannel(const bool &); bool isReferenceChannel() const; - void setReferenceChannel(const bool&); + void setReferenceChannel(const bool &); void setMenuFloating(bool floating); diff --git a/gui/include/gui/checkbox_delegate.h b/gui/include/gui/checkbox_delegate.h index 45d158519a..6d2562e201 100644 --- a/gui/include/gui/checkbox_delegate.h +++ b/gui/include/gui/checkbox_delegate.h @@ -24,26 +24,23 @@ #include namespace scopy { - class CheckboxDelegate : public QStyledItemDelegate - { - Q_OBJECT +class CheckboxDelegate : public QStyledItemDelegate +{ + Q_OBJECT - public: - CheckboxDelegate(QObject *parent = 0); +public: + CheckboxDelegate(QObject *parent = 0); - QWidget *createEditor(QWidget *parent, - const QStyleOptionViewItem &option, - const QModelIndex &index) const Q_DECL_OVERRIDE; + QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, + const QModelIndex &index) const Q_DECL_OVERRIDE; - void setEditorData(QWidget *editor, - const QModelIndex &index) const Q_DECL_OVERRIDE; + void setEditorData(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE; - void setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const Q_DECL_OVERRIDE; + void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const Q_DECL_OVERRIDE; - private Q_SLOTS: - void commitDataToModel(); - }; -} +private Q_SLOTS: + void commitDataToModel(); +}; +} // namespace scopy #endif // CHECKBOX_DELEGATE_H diff --git a/gui/include/gui/completion_circle.h b/gui/include/gui/completion_circle.h index 9609188ddd..cc9621189b 100644 --- a/gui/include/gui/completion_circle.h +++ b/gui/include/gui/completion_circle.h @@ -21,18 +21,19 @@ #ifndef COMPLETIONCIRCLE_H #define COMPLETIONCIRCLE_H -#include #include "scopy-gui_export.h" +#include + namespace scopy { class SCOPY_GUI_EXPORT CompletionCircle : public QDial { Q_OBJECT Q_PROPERTY(bool inverted MEMBER invert_circle); + public: - explicit CompletionCircle(QWidget *parent = 0, - bool invert_circle = false); + explicit CompletionCircle(QWidget *parent = 0, bool invert_circle = false); double valueDouble(); double minimumDouble(); @@ -62,15 +63,15 @@ public Q_SLOTS: void keyPressEvent(QKeyEvent *ev); void wheelEvent(QWheelEvent *e); - bool pointInsideCircle(const QPoint&, int xc, int yc, int r); + bool pointInsideCircle(const QPoint &, int xc, int yc, int r); // Hide setter/getter of the int value - using QAbstractSlider::value; - using QAbstractSlider::setValue; - using QAbstractSlider::minimum; - using QAbstractSlider::setMinimum; using QAbstractSlider::maximum; + using QAbstractSlider::minimum; using QAbstractSlider::setMaximum; + using QAbstractSlider::setMinimum; + using QAbstractSlider::setValue; + using QAbstractSlider::value; private: double m_double_value; @@ -85,6 +86,6 @@ public Q_SLOTS: bool invert_circle; bool m_toggleable; }; -} +} // namespace scopy #endif // COMPLETIONCIRCLE_H diff --git a/gui/include/gui/cursor.h b/gui/include/gui/cursor.h index 8b5fa3df1d..cddda48295 100644 --- a/gui/include/gui/cursor.h +++ b/gui/include/gui/cursor.h @@ -1,16 +1,17 @@ #ifndef CURSOR_H #define CURSOR_H -#include #include "plotwidget.h" #include "scopy-gui_export.h" +#include namespace scopy { -class SCOPY_GUI_EXPORT Cursor : public QObject { +class SCOPY_GUI_EXPORT Cursor : public QObject +{ Q_OBJECT public: - Cursor(PlotWidget* p, PlotAxis *ax, QPen pen); + Cursor(PlotWidget *p, PlotAxis *ax, QPen pen); ~Cursor(); PlotLineHandle *cursorHandle() const; bool isVisible(); @@ -28,12 +29,11 @@ public Q_SLOTS: PlotAxis *m_axis; QwtPlot *m_plot; QPen m_pen; - SymbolController* m_symbolCtrl; - PlotLineHandle* m_cursorHandle; - Symbol* m_cursorBar; + SymbolController *m_symbolCtrl; + PlotLineHandle *m_cursorHandle; + Symbol *m_cursorBar; bool m_canLeavePlot; - }; -} +} // namespace scopy #endif // CURSOR_H diff --git a/gui/include/gui/cursor_readouts.h b/gui/include/gui/cursor_readouts.h index 5e561c7b35..8238bb3a0a 100644 --- a/gui/include/gui/cursor_readouts.h +++ b/gui/include/gui/cursor_readouts.h @@ -21,94 +21,94 @@ #ifndef CURSOR_READOUTS_H #define CURSOR_READOUTS_H -#include #include "customanimation.h" -#include -#include #include "customplotpositionbutton.h" #include "scopy-gui_export.h" +#include +#include +#include + class QwtPlot; namespace Ui { - class CursorReadouts; +class CursorReadouts; } - namespace scopy { - class SCOPY_GUI_EXPORT CursorReadouts: public QWidget - { - public: - CursorReadouts(QwtPlot *plot); - ~CursorReadouts(); - - const QwtPlot *plot() const; - QwtPlot *plot(); - - void setVoltageReadoutVisible(bool on); - bool isVoltageReadoutVisible(); - - void setTimeReadoutVisible(bool on); - bool isTimeReadoutVisible(); - - void setTopLeftStartingPoint(QPoint point); - QPoint topLeftStartingPoint(); - - void setTimeCursor1Text(const QString &); - QString timeCursor1Text(); - void setTimeCursor2Text(const QString &); - QString timeCursor2Text(); - void setTimeDeltaText(const QString &); - QString timeDeltaText(); - void setFreqDeltaText(const QString &); - QString freqDeltaText(); - void setVoltageCursor1Text(const QString &); - QString voltageCursor1Text(); - void setVoltageCursor2Text(const QString &); - QString voltageCursor2Text(); - void setVoltageDeltaText(const QString &); - QString voltageDeltaText(); - void setTimeDeltaVisible(bool); - void setFrequencyDeltaVisible(bool); - void setTimeCursor1LabelText(const QString &); - QString timeCursor1LabelText(); - void setTimeCursor2LabelText(const QString &); - QString timeCursor2LabelText(); - void setTimeDeltaLabelText(const QString &text); - void setVoltageCursor1LabelText(const QString &); - QString voltageCursor1LabelText(); - void setVoltageCursor2LabelText(const QString &); - QString voltageCursor2LabelText(); - void setDeltaVoltageLabelText(const QString &); - QString deltaVoltageLabelText(); - void setAxis(QwtAxisId hAxis,QwtAxisId vAxis); - virtual bool eventFilter(QObject *, QEvent *); - - void setTransparency(int value); - void moveToPosition(CustomPlotPositionButton::ReadoutsPosition position); - CustomPlotPositionButton::ReadoutsPosition getCurrentPosition(); - - void showEvent(QShowEvent *event); - private: - QPoint plotPointToPixelPoint(const QPointF &point) const; - void updateSizeAndPosition(bool resize = false); - - private: - Ui::CursorReadouts *ui; - bool d_voltage_rd_visible; - bool d_time_rd_visible; - bool freq_delta_visible; - QPoint d_topLeft; - void moveTopLeft(bool resize = false); - void moveTopRight(bool resize = false); - void moveBottomLeft(bool resize = false); - void moveBottomRight(bool resize = false); - CustomPlotPositionButton::ReadoutsPosition currentPosition; - CustomAnimation *anim, *anim2; - QRect lastTimeRect, lastVoltageRect; - QwtAxisId hAxis,vAxis; - }; -} - +class SCOPY_GUI_EXPORT CursorReadouts : public QWidget +{ +public: + CursorReadouts(QwtPlot *plot); + ~CursorReadouts(); + + const QwtPlot *plot() const; + QwtPlot *plot(); + + void setVoltageReadoutVisible(bool on); + bool isVoltageReadoutVisible(); + + void setTimeReadoutVisible(bool on); + bool isTimeReadoutVisible(); + + void setTopLeftStartingPoint(QPoint point); + QPoint topLeftStartingPoint(); + + void setTimeCursor1Text(const QString &); + QString timeCursor1Text(); + void setTimeCursor2Text(const QString &); + QString timeCursor2Text(); + void setTimeDeltaText(const QString &); + QString timeDeltaText(); + void setFreqDeltaText(const QString &); + QString freqDeltaText(); + void setVoltageCursor1Text(const QString &); + QString voltageCursor1Text(); + void setVoltageCursor2Text(const QString &); + QString voltageCursor2Text(); + void setVoltageDeltaText(const QString &); + QString voltageDeltaText(); + void setTimeDeltaVisible(bool); + void setFrequencyDeltaVisible(bool); + void setTimeCursor1LabelText(const QString &); + QString timeCursor1LabelText(); + void setTimeCursor2LabelText(const QString &); + QString timeCursor2LabelText(); + void setTimeDeltaLabelText(const QString &text); + void setVoltageCursor1LabelText(const QString &); + QString voltageCursor1LabelText(); + void setVoltageCursor2LabelText(const QString &); + QString voltageCursor2LabelText(); + void setDeltaVoltageLabelText(const QString &); + QString deltaVoltageLabelText(); + void setAxis(QwtAxisId hAxis, QwtAxisId vAxis); + virtual bool eventFilter(QObject *, QEvent *); + + void setTransparency(int value); + void moveToPosition(CustomPlotPositionButton::ReadoutsPosition position); + CustomPlotPositionButton::ReadoutsPosition getCurrentPosition(); + + void showEvent(QShowEvent *event); + +private: + QPoint plotPointToPixelPoint(const QPointF &point) const; + void updateSizeAndPosition(bool resize = false); + +private: + Ui::CursorReadouts *ui; + bool d_voltage_rd_visible; + bool d_time_rd_visible; + bool freq_delta_visible; + QPoint d_topLeft; + void moveTopLeft(bool resize = false); + void moveTopRight(bool resize = false); + void moveBottomLeft(bool resize = false); + void moveBottomRight(bool resize = false); + CustomPlotPositionButton::ReadoutsPosition currentPosition; + CustomAnimation *anim, *anim2; + QRect lastTimeRect, lastVoltageRect; + QwtAxisId hAxis, vAxis; +}; +} // namespace scopy #endif // CURSOR_READOUTS_H diff --git a/gui/include/gui/cursorcontroller.h b/gui/include/gui/cursorcontroller.h index 03bdd3de77..b1133080e7 100644 --- a/gui/include/gui/cursorcontroller.h +++ b/gui/include/gui/cursorcontroller.h @@ -1,8 +1,10 @@ #ifndef CURSORCONTROLLER_H #define CURSORCONTROLLER_H -#include #include "scopy-gui_export.h" + +#include + #include #include #include diff --git a/gui/include/gui/customPushButton.h b/gui/include/gui/customPushButton.h index 3ed3ae5270..8bdaff2918 100644 --- a/gui/include/gui/customPushButton.h +++ b/gui/include/gui/customPushButton.h @@ -21,30 +21,31 @@ #ifndef SCOPY_CUSTOM_PUSH_BUTTON_HPP #define SCOPY_CUSTOM_PUSH_BUTTON_HPP -#include #include "scopy-gui_export.h" +#include + class QMouseEvent; namespace scopy { - /* The CustomPushButton class behaves exactly like QPushButton. The only - * difference is, when it's part of a button group and is the active - * button, it is possible to disactivate it by clicking on it. */ +/* The CustomPushButton class behaves exactly like QPushButton. The only + * difference is, when it's part of a button group and is the active + * button, it is possible to disactivate it by clicking on it. */ - class SCOPY_GUI_EXPORT CustomPushButton : public QPushButton - { - Q_OBJECT +class SCOPY_GUI_EXPORT CustomPushButton : public QPushButton +{ + Q_OBJECT - public: - explicit CustomPushButton(QWidget *parent = Q_NULLPTR); - ~CustomPushButton(); +public: + explicit CustomPushButton(QWidget *parent = Q_NULLPTR); + ~CustomPushButton(); - protected: - void mouseReleaseEvent(QMouseEvent *event); +protected: + void mouseReleaseEvent(QMouseEvent *event); - public Q_SLOTS: - void setChecked(bool checked); - }; -} +public Q_SLOTS: + void setChecked(bool checked); +}; +} // namespace scopy #endif /* SCOPY_CUSTOM_PUSH_BUTTON_HPP */ diff --git a/gui/include/gui/customScale.hpp b/gui/include/gui/customScale.hpp index b0180df2bc..2203b2b1cb 100644 --- a/gui/include/gui/customScale.hpp +++ b/gui/include/gui/customScale.hpp @@ -21,11 +21,11 @@ #ifndef CUSTOM_SCALE_HPP #define CUSTOM_SCALE_HPP -#include - #include "autoScaler.hpp" #include "scopy-gui_export.h" +#include + namespace scopy { class SCOPY_GUI_EXPORT CustomScale : public QwtThermo { @@ -36,7 +36,7 @@ class SCOPY_GUI_EXPORT CustomScale : public QwtThermo ~CustomScale(); void setScaleForTemp(bool temp); - void addScale(double x1, double x2, int maxMajorSteps, int maxMinorSteps, double stepSize = 0.0 ); + void addScale(double x1, double x2, int maxMajorSteps, int maxMinorSteps, double stepSize = 0.0); bool getAutoScaler() const; void setAutoScaler(bool newAutoScaler); @@ -54,6 +54,6 @@ private Q_SLOTS: int m_currentScale; bool autoScale; }; -} +} // namespace scopy #endif /* CUSTOM_SCALE_HPP */ diff --git a/gui/include/gui/customSwitch.h b/gui/include/gui/customSwitch.h index 27ea3aeb6f..a87009c4c2 100644 --- a/gui/include/gui/customSwitch.h +++ b/gui/include/gui/customSwitch.h @@ -21,50 +21,50 @@ #ifndef CUSTOM_SWITCH_HPP #define CUSTOM_SWITCH_HPP -#include #include "customanimation.h" +#include "scopy-gui_export.h" + +#include #include #include -#include "scopy-gui_export.h" class QShowEvent; namespace scopy { - class SCOPY_GUI_EXPORT CustomSwitch : public QPushButton - { - Q_OBJECT +class SCOPY_GUI_EXPORT CustomSwitch : public QPushButton +{ + Q_OBJECT - Q_PROPERTY(int duration_ms MEMBER duration_ms - WRITE setDuration); + Q_PROPERTY(int duration_ms MEMBER duration_ms WRITE setDuration); - public: - explicit CustomSwitch(QWidget *parent = nullptr); - ~CustomSwitch(); +public: + explicit CustomSwitch(QWidget *parent = nullptr); + ~CustomSwitch(); - const QLabel &getOn() const; - void setOnText(const QString &on_); - void setOn(const QPixmap &pixmap); + const QLabel &getOn() const; + void setOnText(const QString &on_); + void setOn(const QPixmap &pixmap); - const QLabel &getOff() const; - void setOffText(const QString &off_); - void setOff(const QPixmap &pixmap); + const QLabel &getOff() const; + void setOffText(const QString &off_); + void setOff(const QPixmap &pixmap); - private: - QLabel on, off; - QWidget handle; - CustomAnimation anim; - int duration_ms; - bool polarity; +private: + QLabel on, off; + QWidget handle; + CustomAnimation anim; + int duration_ms; + bool polarity; - void setDuration(int ms); - void updateOnOffLabels(); + void setDuration(int ms); + void updateOnOffLabels(); - void showEvent(QShowEvent *event); - bool event(QEvent*); + void showEvent(QShowEvent *event); + bool event(QEvent *); - private Q_SLOTS: - void toggleAnim(bool enabled); - }; -} +private Q_SLOTS: + void toggleAnim(bool enabled); +}; +} // namespace scopy #endif /* CUSTOM_SWITCH_HPP */ diff --git a/gui/include/gui/custom_menu_button.hpp b/gui/include/gui/custom_menu_button.hpp index 5ef2c0078c..1ca79129cf 100644 --- a/gui/include/gui/custom_menu_button.hpp +++ b/gui/include/gui/custom_menu_button.hpp @@ -1,12 +1,12 @@ #ifndef CUSTOMMENUBUTTON_H #define CUSTOMMENUBUTTON_H +#include "customPushButton.h" + #include #include #include -#include "customPushButton.h" - using namespace scopy; namespace Ui { @@ -22,15 +22,15 @@ class CustomMenuButton : public QWidget public: explicit CustomMenuButton(QString labelText = nullptr, bool checkboxVisible = false, - bool checkBoxChecked = false, QWidget* parent = nullptr); - explicit CustomMenuButton(QWidget* parent = nullptr); + bool checkBoxChecked = false, QWidget *parent = nullptr); + explicit CustomMenuButton(QWidget *parent = nullptr); ~CustomMenuButton(); - void setLabel(const QString& text); + void setLabel(const QString &text); void setCheckboxVisible(bool visible); - CustomPushButton* getBtn(); - QCheckBox* getCheckBox(); + CustomPushButton *getBtn(); + QCheckBox *getCheckBox(); bool getCheckBoxState(); void setCheckBoxState(bool checked); void setMenuFloating(bool floating); @@ -39,7 +39,7 @@ public Q_SLOTS: void checkBoxToggled(bool toggled); private: - Ui::CustomMenuButton* m_ui; + Ui::CustomMenuButton *m_ui; bool m_floatingMenu; }; diff --git a/gui/include/gui/customanimation.h b/gui/include/gui/customanimation.h index bd2c803ad2..13c4da0ec9 100644 --- a/gui/include/gui/customanimation.h +++ b/gui/include/gui/customanimation.h @@ -21,9 +21,10 @@ #ifndef CUSTOMANIMATION_H #define CUSTOMANIMATION_H -#include #include "scopy-gui_export.h" +#include + namespace scopy { class SCOPY_GUI_EXPORT CustomAnimation : public QPropertyAnimation { @@ -32,14 +33,14 @@ class SCOPY_GUI_EXPORT CustomAnimation : public QPropertyAnimation CustomAnimation(QObject *target, const QByteArray &propertyName, QObject *parent = nullptr); ~CustomAnimation(); - void setDuration(int msec); + void setDuration(int msec); public Q_SLOTS: - void toggle(bool); + void toggle(bool); private: - bool m_enabled; - int m_duration; + bool m_enabled; + int m_duration; }; -} +} // namespace scopy #endif // CUSTOMANIMATION_H diff --git a/gui/include/gui/customplotpositionbutton.h b/gui/include/gui/customplotpositionbutton.h index 97b502d43c..7587695973 100644 --- a/gui/include/gui/customplotpositionbutton.h +++ b/gui/include/gui/customplotpositionbutton.h @@ -20,10 +20,11 @@ #ifndef CUSTOMPLOTPOSITIONBUTTON_H #define CUSTOMPLOTPOSITIONBUTTON_H -#include -#include #include "scopy-gui_export.h" +#include +#include + namespace Ui { class CustomPlotPositionButton; } @@ -34,8 +35,8 @@ class SCOPY_GUI_EXPORT CustomPlotPositionButton : public QWidget Q_OBJECT public: - - enum ReadoutsPosition { + enum ReadoutsPosition + { topLeft, topRight, bottomLeft, @@ -49,12 +50,10 @@ class SCOPY_GUI_EXPORT CustomPlotPositionButton : public QWidget Q_SIGNALS: void positionChanged(CustomPlotPositionButton::ReadoutsPosition position); - private: Ui::CustomPlotPositionButton *ui; QButtonGroup *btns; }; -} - +} // namespace scopy #endif // CUSTOMPLOTPOSITIONBUTTON_H diff --git a/gui/include/gui/customqwtscaledraw.hpp b/gui/include/gui/customqwtscaledraw.hpp index 2f19d1eb66..49e33270a5 100644 --- a/gui/include/gui/customqwtscaledraw.hpp +++ b/gui/include/gui/customqwtscaledraw.hpp @@ -1,12 +1,13 @@ #ifndef CUSTOMQWTSCALEDRAW_HPP #define CUSTOMQWTSCALEDRAW_HPP -#include +#include "plot_utils.hpp" +#include "scopy-gui_export.h" + #include #include #include -#include "plot_utils.hpp" -#include "scopy-gui_export.h" +#include namespace scopy { @@ -22,7 +23,6 @@ class SCOPY_GUI_EXPORT CustomQwtScaleDraw : public QwtScaleDraw private: QString m_unitOfMeasure; - }; -} +} // namespace scopy #endif // CUSTOMQWTSCALEDRAW_HPP diff --git a/gui/include/gui/db_click_buttons.hpp b/gui/include/gui/db_click_buttons.hpp index 700c238131..45f3aab4b1 100644 --- a/gui/include/gui/db_click_buttons.hpp +++ b/gui/include/gui/db_click_buttons.hpp @@ -20,11 +20,12 @@ #ifndef DB_CLICK_BUTTONS_HPP #define DB_CLICK_BUTTONS_HPP -#include -#include +#include "scopy-gui_export.h" + #include +#include #include -#include "scopy-gui_export.h" +#include namespace Ui { class DbClickButtons; @@ -32,7 +33,7 @@ class DbClickButtons; namespace scopy { -class SCOPY_GUI_EXPORT DbClickButtons: public QWidget +class SCOPY_GUI_EXPORT DbClickButtons : public QWidget { Q_OBJECT diff --git a/gui/include/gui/dbgraph.hpp b/gui/include/gui/dbgraph.hpp index cc95616a2a..31e2a15905 100644 --- a/gui/include/gui/dbgraph.hpp +++ b/gui/include/gui/dbgraph.hpp @@ -21,16 +21,16 @@ #ifndef DBGRAPH_HPP #define DBGRAPH_HPP +#include "DisplayPlot.h" +#include "cursor_readouts.h" +#include "plot_line_handle.h" +#include "scopy-gui_export.h" +#include "symbol_controller.h" + #include #include #include -#include "symbol_controller.h" -#include "plot_line_handle.h" -#include "cursor_readouts.h" -#include "DisplayPlot.h" -#include "scopy-gui_export.h" - namespace scopy { class OscScaleDraw; class PrefixFormatter; @@ -41,15 +41,9 @@ class SCOPY_GUI_EXPORT dBgraph : public DisplayPlot friend class NetworkAnalyzer_API; Q_OBJECT - Q_PROPERTY(int numSamples - READ getNumSamples - WRITE setNumSamples - ) + Q_PROPERTY(int numSamples READ getNumSamples WRITE setNumSamples) - Q_PROPERTY(QColor color - READ getColor - WRITE setColor - ) + Q_PROPERTY(QColor color READ getColor WRITE setColor) Q_PROPERTY(QString xaxis_title READ xTitle WRITE setXTitle); Q_PROPERTY(QString yaxis_title READ yTitle WRITE setYTitle); @@ -69,9 +63,8 @@ class SCOPY_GUI_EXPORT dBgraph : public DisplayPlot ~dBgraph(); - void setAxesScales(double xmin, double xmax, - double ymin, double ymax); - void setAxesTitles(const QString& x, const QString& y); + void setAxesScales(double xmin, double xmax, double ymin, double ymax); + void setAxesTitles(const QString &x, const QString &y); int getNumSamples() const; @@ -83,7 +76,7 @@ class SCOPY_GUI_EXPORT dBgraph : public DisplayPlot void setShowZero(bool en); const QwtScaleWidget *getAxisWidget(QwtAxisId id); - const QColor& getColor() const; + const QColor &getColor() const; double getThickness(); QString xTitle() const; QString yTitle() const; @@ -119,10 +112,10 @@ public Q_SLOTS: void reset(); void setNumSamples(int num); - void setColor(const QColor& color); + void setColor(const QColor &color); void setThickness(int index); - void setXTitle(const QString& title); - void setYTitle(const QString& title); + void setXTitle(const QString &title); + void setYTitle(const QString &title); void setXMin(double val); void setXMax(double val); void setYMin(double val); @@ -130,8 +123,8 @@ public Q_SLOTS: QString xUnit() const; QString yUnit() const; - void setXUnit(const QString& unit); - void setYUnit(const QString& unit); + void setXUnit(const QString &unit); + void setYUnit(const QString &unit); void useLogFreq(bool use_log_freq); void useDeltaLabel(bool use_delta); @@ -183,6 +176,6 @@ protected Q_SLOTS: void setupVerticalBars(); void setupReadouts(); }; -} +} // namespace scopy #endif /* DBGRAPH_HPP */ diff --git a/gui/include/gui/dropdown_switch_list.h b/gui/include/gui/dropdown_switch_list.h index ae3fb58af8..e7619efd02 100644 --- a/gui/include/gui/dropdown_switch_list.h +++ b/gui/include/gui/dropdown_switch_list.h @@ -21,58 +21,58 @@ #ifndef DROPDOWN_SWITCH_LIST_H #define DROPDOWN_SWITCH_LIST_H -#include #include "ComboBoxLineEdit.h" #include "scopy-gui_export.h" +#include + class QStandardItemModel; class QTreeView; namespace scopy { - class SCOPY_GUI_EXPORT DropdownSwitchList: public QComboBox - { - Q_OBJECT +class SCOPY_GUI_EXPORT DropdownSwitchList : public QComboBox +{ + Q_OBJECT - public: - DropdownSwitchList(int switchColCount = 1, QWidget *parent = 0); +public: + DropdownSwitchList(int switchColCount = 1, QWidget *parent = 0); - QString title() const; - void setTitle(const QString& title); + QString title() const; + void setTitle(const QString &title); - QString columnTitle(int col) const; - void setColumnTitle(int col, const QString& title); + QString columnTitle(int col) const; + void setColumnTitle(int col, const QString &title); - int switchColumnCount() const; + int switchColumnCount() const; - void addDropdownElement(const QIcon&, const QString&); - void addDropdownElement(const QIcon&, const QString&, - const QVariant& user_data); + void addDropdownElement(const QIcon &, const QString &); + void addDropdownElement(const QIcon &, const QString &, const QVariant &user_data); - void removeItem(int index); - void showPopup() override; - void hidePopup() override; + void removeItem(int index); + void showPopup() override; + void hidePopup() override; - protected Q_SLOTS: - void mousePressEvent(QMouseEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override; - void enterEvent(QEvent *event) override; - void leaveEvent(QEvent *event) override; +protected Q_SLOTS: + void mousePressEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + void enterEvent(QEvent *event) override; + void leaveEvent(QEvent *event) override; - private Q_SLOTS: - void resetIndex(int); +private Q_SLOTS: + void resetIndex(int); - private: - QString m_title; - int m_rows; - int m_columns; - QStandardItemModel *m_model; - QTreeView *m_treeView; - QStringList m_colTitles; - bool m_popVisible; - bool m_mouseInside; - bool m_mousePressed; - ComboBoxLineEdit *m_lineEdit; - }; -} +private: + QString m_title; + int m_rows; + int m_columns; + QStandardItemModel *m_model; + QTreeView *m_treeView; + QStringList m_colTitles; + bool m_popVisible; + bool m_mouseInside; + bool m_mousePressed; + ComboBoxLineEdit *m_lineEdit; +}; +} // namespace scopy #endif // DROPDOWN_SWITCH_LIST_H diff --git a/gui/include/gui/dynamicWidget.h b/gui/include/gui/dynamicWidget.h index b7eb15aff4..d4957cb7cf 100644 --- a/gui/include/gui/dynamicWidget.h +++ b/gui/include/gui/dynamicWidget.h @@ -26,10 +26,8 @@ class QWidget; namespace scopy { - void SCOPY_GUI_EXPORT setDynamicProperty(QWidget *widget, - const char *property, bool set); - bool SCOPY_GUI_EXPORT getDynamicProperty(QWidget *widget, - const char *property); -} +void SCOPY_GUI_EXPORT setDynamicProperty(QWidget *widget, const char *property, bool set); +bool SCOPY_GUI_EXPORT getDynamicProperty(QWidget *widget, const char *property); +} // namespace scopy #endif /* DYNAMIC_WIDGET_HPP */ diff --git a/gui/include/gui/extendingplotzoomer.h b/gui/include/gui/extendingplotzoomer.h index 582b33afee..8b9ceabfd1 100644 --- a/gui/include/gui/extendingplotzoomer.h +++ b/gui/include/gui/extendingplotzoomer.h @@ -21,16 +21,16 @@ #define EXTENDINGPLOTZOOMER_H #include "limitedplotzoomer.h" +#include "scopy-gui_export.h" #include -#include "scopy-gui_export.h" namespace scopy { class SCOPY_GUI_EXPORT ExtendingPlotZoomer : public LimitedPlotZoomer { public: - explicit ExtendingPlotZoomer(QwtAxisId xAxis, QwtAxisId yAxis, QWidget*, bool doReplot = false); - explicit ExtendingPlotZoomer(QWidget*, bool doReplot = false); + explicit ExtendingPlotZoomer(QwtAxisId xAxis, QwtAxisId yAxis, QWidget *, bool doReplot = false); + explicit ExtendingPlotZoomer(QWidget *, bool doReplot = false); virtual ~ExtendingPlotZoomer(); protected: @@ -43,9 +43,9 @@ class SCOPY_GUI_EXPORT ExtendingPlotZoomer : public LimitedPlotZoomer mutable bool extendWidth; mutable bool extendHeight; - QVector cornerMarkers; - QVector extendMarkers; + QVector cornerMarkers; + QVector extendMarkers; }; -} +} // namespace scopy #endif // EXTENDINGPLOTZOOMER_H diff --git a/gui/include/gui/filemanager.h b/gui/include/gui/filemanager.h index c29943d435..72f25e931f 100644 --- a/gui/include/gui/filemanager.h +++ b/gui/include/gui/filemanager.h @@ -21,31 +21,33 @@ #ifndef FILEMANAGER_H #define FILEMANAGER_H +#include "scopy-gui_export.h" + #include -#include #include +#include #include #include -#include "scopy-gui_export.h" - namespace scopy { class SCOPY_GUI_EXPORT FileManager { public: - - enum FilePurpose { + enum FilePurpose + { EXPORT, IMPORT }; - enum FileFormat { + enum FileFormat + { RAW, SCOPY }; - enum FileType { + enum FileType + { CSV, TXT }; @@ -75,15 +77,14 @@ class SCOPY_GUI_EXPORT FileManager void performDecoderWrite(bool skip_empty_lines = false); QStringList getAdditionalInformation() const; - void setAdditionalInformation(const QString& value); + void setAdditionalInformation(const QString &value); FileFormat getFormat() const; void setFormat(const FileFormat &value); - void writeToFile(bool overwrite, QMap> data); + void writeToFile(bool overwrite, QMap> data); private: - QVector> data; QVector> decoder_data; QStringList columnNames; @@ -97,20 +98,23 @@ class SCOPY_GUI_EXPORT FileManager QString separator; QString toolName; QStringList additionalInformation; - }; -class ScopyFileHeader { +class ScopyFileHeader +{ public: static bool hasValidHeader(QVector> data); static QStringList getHeader(); }; -class FileManagerException : public std::runtime_error { +class FileManagerException : public std::runtime_error +{ public: - FileManagerException(const char* msg) : std::runtime_error(msg) {} + FileManagerException(const char *msg) + : std::runtime_error(msg) + {} ~FileManagerException() throw() {} }; -} +} // namespace scopy #endif // FILEMANAGER_H diff --git a/gui/include/gui/flexgridlayout.hpp b/gui/include/gui/flexgridlayout.hpp index 0d800c6844..872b1acc53 100644 --- a/gui/include/gui/flexgridlayout.hpp +++ b/gui/include/gui/flexgridlayout.hpp @@ -1,11 +1,12 @@ #ifndef FLEXGRIDLAYOUT_HPP #define FLEXGRIDLAYOUT_HPP -#include -#include +#include "scopy-gui_export.h" + #include #include -#include "scopy-gui_export.h" +#include +#include namespace scopy { class SCOPY_GUI_EXPORT FlexGridLayout : public QWidget @@ -19,7 +20,7 @@ class SCOPY_GUI_EXPORT FlexGridLayout : public QWidget void toggleAll(bool toggled); void addWidget(int index); void removeWidget(int index); - QWidget* getWidget(int index); + QWidget *getWidget(int index); bool isWidgetActive(int index); int addQWidgetToList(QWidget *widget); @@ -47,13 +48,13 @@ public Q_SLOTS: int row; double colWidth; double availableWidth; - std::vector m_widgetList; + std::vector m_widgetList; QVector m_activeWidgetList; QGridLayout *m_gridLayout; QSpacerItem *m_hspacer; QSpacerItem *m_vspacer; - //resize related + // resize related bool updatePending; void redrawWidgets(); void recomputeColCount(); @@ -61,5 +62,5 @@ public Q_SLOTS: void resizeEvent(QResizeEvent *event) override; void repositionWidgets(int index, int row, int col); }; -} +} // namespace scopy #endif // FLEXGRIDLAYOUT_HPP diff --git a/gui/include/gui/generic_menu.hpp b/gui/include/gui/generic_menu.hpp index 88d621cc1e..6533dd44b3 100644 --- a/gui/include/gui/generic_menu.hpp +++ b/gui/include/gui/generic_menu.hpp @@ -1,12 +1,12 @@ #ifndef GENERICMENU_HPP #define GENERICMENU_HPP -#include - #include "basemenu.h" #include "menu_header.hpp" -#include "subsection_separator.hpp" #include "scopy-gui_export.h" +#include "subsection_separator.hpp" + +#include namespace scopy { namespace gui { @@ -16,14 +16,14 @@ class SCOPY_GUI_EXPORT GenericMenu : public QWidget Q_OBJECT public: - explicit GenericMenu(QWidget* parent = nullptr); + explicit GenericMenu(QWidget *parent = nullptr); ~GenericMenu(); virtual void setMenuButton(bool toggled){}; void initInteractiveMenu(); - void setMenuHeader(const QString& title, const QColor* lineColor, bool hasEnableBtn); - void insertSection(SubsectionSeparator* section); + void setMenuHeader(const QString &title, const QColor *lineColor, bool hasEnableBtn); + void insertSection(SubsectionSeparator *section); void addNewHeaderWidget(QWidget *widget); void setMenuWidget(QWidget *widget); @@ -35,8 +35,8 @@ class SCOPY_GUI_EXPORT GenericMenu : public QWidget void menuVisibilityChanged(bool toggled); private: - MenuHeader* m_menuHeader; - BaseMenu* m_menu; + MenuHeader *m_menuHeader; + BaseMenu *m_menu; int m_lastOpenPosition; }; diff --git a/gui/include/gui/genericlogicplotcurve.h b/gui/include/gui/genericlogicplotcurve.h index 50b3951910..5404c019d5 100644 --- a/gui/include/gui/genericlogicplotcurve.h +++ b/gui/include/gui/genericlogicplotcurve.h @@ -18,17 +18,17 @@ * along with this program. If not, see . */ - #ifndef GENERICLOGICPLOTCURVE_H #define GENERICLOGICPLOTCURVE_H -#include +#include "scopy-gui_export.h" #include #include -#include "scopy-gui_export.h" +#include -enum class LogicPlotCurveType : int { +enum class LogicPlotCurveType : int +{ Data = 0, Annotations = 1, }; @@ -37,9 +37,10 @@ class SCOPY_GUI_EXPORT GenericLogicPlotCurve : public QObject, public QwtPlotCur { Q_OBJECT public: - GenericLogicPlotCurve(const QString &name = {}, const QString &id = {}, LogicPlotCurveType type = LogicPlotCurveType::Data, - double pixelOffset = 0.0, double traceHeight = 0.0, double sampleRate = 0.0, - double timeTriggerOffset = 0.0, uint64_t bufferSize = 0.0); + GenericLogicPlotCurve(const QString &name = {}, const QString &id = {}, + LogicPlotCurveType type = LogicPlotCurveType::Data, double pixelOffset = 0.0, + double traceHeight = 0.0, double sampleRate = 0.0, double timeTriggerOffset = 0.0, + uint64_t bufferSize = 0.0); QString getName() const; QString getId() const; @@ -75,15 +76,15 @@ class SCOPY_GUI_EXPORT GenericLogicPlotCurve : public QObject, public QwtPlotCur // Check if the point is on the curve. When invoked by the CapturePlot // this point is already mapped to the plot's bounds. - virtual bool testHit(const QPointF& p) const { return false; } + virtual bool testHit(const QPointF &p) const { return false; } // Map screen point to curve point - QPointF screenPosToCurvePoint(const QPoint& pos) const; + QPointF screenPosToCurvePoint(const QPoint &pos) const; Q_SIGNALS: void nameChanged(QString); void pixelOffsetChanged(double); - void clicked(const QPointF& p); + void clicked(const QPointF &p); protected: QString m_name; diff --git a/gui/include/gui/graticule.h b/gui/include/gui/graticule.h index 530a5fff0a..09cb381a11 100644 --- a/gui/include/gui/graticule.h +++ b/gui/include/gui/graticule.h @@ -21,10 +21,11 @@ #ifndef GRATICULE_H #define GRATICULE_H +#include "scopy-gui_export.h" + #include #include #include -#include "scopy-gui_export.h" namespace scopy { @@ -48,16 +49,13 @@ public Q_SLOTS: QwtPlotScaleItem *horizScale2; }; -class SCOPY_GUI_EXPORT GraticulePlotScaleItem: public QwtPlotScaleItem +class SCOPY_GUI_EXPORT GraticulePlotScaleItem : public QwtPlotScaleItem { public: - explicit GraticulePlotScaleItem( - QwtScaleDraw::Alignment = QwtScaleDraw::BottomScale, - const double pos = 0.0); + explicit GraticulePlotScaleItem(QwtScaleDraw::Alignment = QwtScaleDraw::BottomScale, const double pos = 0.0); virtual void updateScaleDiv(const QwtScaleDiv &, const QwtScaleDiv &); }; -} - +} // namespace scopy #endif // GRATICULE_H diff --git a/gui/include/gui/handles_area.hpp b/gui/include/gui/handles_area.hpp index 1d3b485c3b..8010a148fc 100644 --- a/gui/include/gui/handles_area.hpp +++ b/gui/include/gui/handles_area.hpp @@ -21,17 +21,18 @@ #ifndef HANDLES_AREA_H #define HANDLES_AREA_H +#include "handlesareaextension.h" +#include "scopy-gui_export.h" + #include + #include #include -#include "handlesareaextension.h" -#include "scopy-gui_export.h" - class QPoint; class PlotLineHandle; -class SCOPY_GUI_EXPORT HandlesArea: public QWidget +class SCOPY_GUI_EXPORT HandlesArea : public QWidget { Q_OBJECT @@ -49,7 +50,7 @@ class SCOPY_GUI_EXPORT HandlesArea: public QWidget void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE; virtual void resizeMask(QSize) = 0; - void paintEvent(QPaintEvent* event) Q_DECL_OVERRIDE; + void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; protected: QWidget *canvas; @@ -59,7 +60,7 @@ class SCOPY_GUI_EXPORT HandlesArea: public QWidget std::vector> m_extensions; }; -class SCOPY_GUI_EXPORT VertHandlesArea: public HandlesArea +class SCOPY_GUI_EXPORT VertHandlesArea : public HandlesArea { Q_OBJECT public: @@ -81,7 +82,7 @@ class SCOPY_GUI_EXPORT VertHandlesArea: public HandlesArea int largest_child_height; }; -class SCOPY_GUI_EXPORT HorizHandlesArea: public HandlesArea +class SCOPY_GUI_EXPORT HorizHandlesArea : public HandlesArea { Q_OBJECT public: @@ -103,12 +104,14 @@ class SCOPY_GUI_EXPORT HorizHandlesArea: public HandlesArea int largest_child_width; }; -class SCOPY_GUI_EXPORT GateHandlesArea: public HorizHandlesArea +class SCOPY_GUI_EXPORT GateHandlesArea : public HorizHandlesArea { public: GateHandlesArea(QWidget *parent = 0); + protected: void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE; + private: }; diff --git a/gui/include/gui/handlesareaextension.h b/gui/include/gui/handlesareaextension.h index 270bec1a96..9348c2cdc4 100644 --- a/gui/include/gui/handlesareaextension.h +++ b/gui/include/gui/handlesareaextension.h @@ -1,9 +1,10 @@ #ifndef HANDLESAREAEXTENSION_H #define HANDLESAREAEXTENSION_H -#include #include "scopy-gui_export.h" +#include + class QwtPlot; class SCOPY_GUI_EXPORT HandlesAreaExtension @@ -17,11 +18,13 @@ class SCOPY_GUI_EXPORT HandlesAreaExtension // return true if this will be the last extension to be drawn no matter // the number of extensions installed virtual bool draw(QPainter *painter, QWidget *owner) = 0; + protected: QwtPlot *m_plot; }; -class SCOPY_GUI_EXPORT XBottomRuller: public HandlesAreaExtension { +class SCOPY_GUI_EXPORT XBottomRuller : public HandlesAreaExtension +{ public: XBottomRuller(QwtPlot *plot); virtual ~XBottomRuller() = default; @@ -29,7 +32,8 @@ class SCOPY_GUI_EXPORT XBottomRuller: public HandlesAreaExtension { virtual bool draw(QPainter *painter, QWidget *owner) Q_DECL_OVERRIDE; }; -class SCOPY_GUI_EXPORT YLeftRuller: public HandlesAreaExtension { +class SCOPY_GUI_EXPORT YLeftRuller : public HandlesAreaExtension +{ public: YLeftRuller(QwtPlot *plot); virtual ~YLeftRuller() = default; @@ -37,7 +41,8 @@ class SCOPY_GUI_EXPORT YLeftRuller: public HandlesAreaExtension { virtual bool draw(QPainter *painter, QWidget *owner) Q_DECL_OVERRIDE; }; -class SCOPY_GUI_EXPORT XTopRuller: public HandlesAreaExtension { +class SCOPY_GUI_EXPORT XTopRuller : public HandlesAreaExtension +{ public: XTopRuller(QwtPlot *plot); virtual ~XTopRuller() = default; diff --git a/gui/include/gui/hcursor.h b/gui/include/gui/hcursor.h index 75322970f0..88ddbcf02d 100644 --- a/gui/include/gui/hcursor.h +++ b/gui/include/gui/hcursor.h @@ -1,18 +1,21 @@ #ifndef HCURSOR_H #define HCURSOR_H -#include -#include "plotwidget.h" #include "plotaxis.h" +#include "plotwidget.h" #include "scopy-gui_export.h" + +#include + #include namespace scopy { - -class SCOPY_GUI_EXPORT HCursor : public Cursor { +class SCOPY_GUI_EXPORT HCursor : public Cursor +{ Q_OBJECT public: - explicit HCursor(PlotWidget* p, PlotAxis *ax, bool bottom = true, QPen pen = QPen(QColor(155, 155, 155), 1, Qt::DashLine)); + explicit HCursor(PlotWidget *p, PlotAxis *ax, bool bottom = true, + QPen pen = QPen(QColor(155, 155, 155), 1, Qt::DashLine)); ~HCursor(); double computePosition(int pos); @@ -23,6 +26,6 @@ class SCOPY_GUI_EXPORT HCursor : public Cursor { Q_SIGNALS: void update(); }; -} +} // namespace scopy #endif // HCURSOR_H diff --git a/gui/include/gui/homepage_controls.h b/gui/include/gui/homepage_controls.h index 22f932ca3c..1f6993a629 100644 --- a/gui/include/gui/homepage_controls.h +++ b/gui/include/gui/homepage_controls.h @@ -21,11 +21,13 @@ #ifndef HOMEPAGE_CONTROLS_H #define HOMEPAGE_CONTROLS_H -#include +#include "scopy-gui_export.h" + #include +#include + #include #include -#include "scopy-gui_export.h" namespace scopy { class SCOPY_GUI_EXPORT HomepageControls : public HoverWidget @@ -49,5 +51,5 @@ public Q_SLOTS: PageNavigationWidget *controls; void connectSignals(); }; -} +} // namespace scopy #endif // HOMEPAGE_CONTROLS_H diff --git a/gui/include/gui/infopage.h b/gui/include/gui/infopage.h index c5dfff4ce3..5bfb3b4876 100644 --- a/gui/include/gui/infopage.h +++ b/gui/include/gui/infopage.h @@ -1,13 +1,13 @@ #ifndef INFOPAGE_H #define INFOPAGE_H -#include -#include -#include -#include #include "infopagekeyvaluewidget.h" #include "scopy-gui_export.h" +#include +#include +#include +#include namespace scopy { @@ -29,10 +29,9 @@ class SCOPY_GUI_EXPORT InfoPage : public QWidget bool m_advancedMode; QVBoxLayout *lay; QMap keyMap; - QMap map; - QMap wmap; + QMap map; + QMap wmap; }; - -} +} // namespace scopy #endif // INFOPAGE_H diff --git a/gui/include/gui/infopagekeyvaluewidget.h b/gui/include/gui/infopagekeyvaluewidget.h index 93a4e103e9..a557a04033 100644 --- a/gui/include/gui/infopagekeyvaluewidget.h +++ b/gui/include/gui/infopagekeyvaluewidget.h @@ -1,19 +1,21 @@ #ifndef INFOPAGEKEYVALUEWIDGET_H #define INFOPAGEKEYVALUEWIDGET_H -#include +#include "scopy-gui_export.h" + #include #include -#include "scopy-gui_export.h" +#include namespace scopy { -class SCOPY_GUI_EXPORT InfoPageKeyValueWidget : public QWidget { +class SCOPY_GUI_EXPORT InfoPageKeyValueWidget : public QWidget +{ public: - InfoPageKeyValueWidget(QString key, QString value, QWidget *parent = nullptr ); + InfoPageKeyValueWidget(QString key, QString value, QWidget *parent = nullptr); void updateValue(QString value); QLabel *keyWidget; QLabel *valueWidget; }; -} +} // namespace scopy #endif // INFOPAGEKEYVALUEWIDGET_H diff --git a/gui/include/gui/instrumentnotes.h b/gui/include/gui/instrumentnotes.h index a235be9820..6887d2e9c2 100644 --- a/gui/include/gui/instrumentnotes.h +++ b/gui/include/gui/instrumentnotes.h @@ -1,9 +1,10 @@ #ifndef INSTRUMENTNOTES_H #define INSTRUMENTNOTES_H -#include #include "scopy-gui_export.h" +#include + namespace Ui { class InstrumentNotes; } @@ -23,6 +24,6 @@ public Q_SLOTS: private: Ui::InstrumentNotes *ui; }; -} +} // namespace scopy #endif // INSTRUMENTNOTES_H diff --git a/gui/include/gui/lcdNumber.hpp b/gui/include/gui/lcdNumber.hpp index b2220bc706..671a4c039a 100644 --- a/gui/include/gui/lcdNumber.hpp +++ b/gui/include/gui/lcdNumber.hpp @@ -21,27 +21,27 @@ #ifndef LCD_NUMBER_HPP #define LCD_NUMBER_HPP -#include #include "scopy-gui_export.h" +#include + namespace scopy { - class SCOPY_GUI_EXPORT LcdNumber : public QLCDNumber - { - Q_OBJECT - - public: - explicit LcdNumber(QWidget *parent = 0, - unsigned precision = 3); - ~LcdNumber() {} - - public Q_SLOTS: - void display(double num); - void setPrecision(unsigned precision); - unsigned getPrecision(); - - private: - unsigned precision; - }; -} +class SCOPY_GUI_EXPORT LcdNumber : public QLCDNumber +{ + Q_OBJECT + +public: + explicit LcdNumber(QWidget *parent = 0, unsigned precision = 3); + ~LcdNumber() {} + +public Q_SLOTS: + void display(double num); + void setPrecision(unsigned precision); + unsigned getPrecision(); + +private: + unsigned precision; +}; +} // namespace scopy #endif /* LCD_NUMBER_HPP */ diff --git a/gui/include/gui/limitedplotzoomer.h b/gui/include/gui/limitedplotzoomer.h index b655649f77..e7adcc05c7 100644 --- a/gui/include/gui/limitedplotzoomer.h +++ b/gui/include/gui/limitedplotzoomer.h @@ -20,15 +20,16 @@ #ifndef LIMITEDPLOTZOOMER_H #define LIMITEDPLOTZOOMER_H -#include #include "scopy-gui_export.h" +#include + namespace scopy { class SCOPY_GUI_EXPORT LimitedPlotZoomer : public QwtPlotZoomer { public: - LimitedPlotZoomer(QwtAxisId xAxis, QwtAxisId yAxis, QWidget*, bool doReplot = false); - LimitedPlotZoomer(QWidget*, bool doReplot = false); + LimitedPlotZoomer(QwtAxisId xAxis, QwtAxisId yAxis, QWidget *, bool doReplot = false); + LimitedPlotZoomer(QWidget *, bool doReplot = false); void resetZoom(); void popZoom(); @@ -42,6 +43,6 @@ class SCOPY_GUI_EXPORT LimitedPlotZoomer : public QwtPlotZoomer bool m_boundVertical; bool m_updateBaseNextZoom; }; -} +} // namespace scopy #endif // LIMITEDPLOTZOOMER_H diff --git a/gui/include/gui/linked_button.hpp b/gui/include/gui/linked_button.hpp index 2e1cbea75d..410eabb642 100644 --- a/gui/include/gui/linked_button.hpp +++ b/gui/include/gui/linked_button.hpp @@ -1,9 +1,10 @@ #ifndef LINKEDBUTTON_HPP #define LINKEDBUTTON_HPP -#include #include "scopy-gui_export.h" +#include + namespace scopy { class SCOPY_GUI_EXPORT LinkedButton : public QPushButton @@ -11,7 +12,7 @@ class SCOPY_GUI_EXPORT LinkedButton : public QPushButton Q_OBJECT public: - explicit LinkedButton(QWidget* parent = Q_NULLPTR); + explicit LinkedButton(QWidget *parent = Q_NULLPTR); void setUrl(QString url); @@ -21,6 +22,6 @@ class SCOPY_GUI_EXPORT LinkedButton : public QPushButton public Q_SLOTS: void openUrl(); }; -} +} // namespace scopy #endif // LINKEDBUTTON_HPP diff --git a/gui/include/gui/logicdatacurve.h b/gui/include/gui/logicdatacurve.h index 6cd204dc23..eff4e57128 100644 --- a/gui/include/gui/logicdatacurve.h +++ b/gui/include/gui/logicdatacurve.h @@ -18,7 +18,6 @@ * along with this program. If not, see . */ - #ifndef LOGICDATACURVE_H #define LOGICDATACURVE_H @@ -32,7 +31,7 @@ class SCOPY_GUI_EXPORT LogicDataCurve : public GenericLogicPlotCurve public: LogicDataCurve(uint16_t *data, uint8_t bit); - virtual void setData(uint16_t*); + virtual void setData(uint16_t *); virtual void dataAvailable(uint64_t from, uint64_t to, uint16_t *data) override; virtual void reset() override; @@ -40,19 +39,15 @@ class SCOPY_GUI_EXPORT LogicDataCurve : public GenericLogicPlotCurve void setDisplaySampling(bool display); - protected: - void drawLines( QPainter *painter, - const QwtScaleMap &xMap, const QwtScaleMap &yMap, - const QRectF &canvasRect, int from, int to ) const override; + void drawLines(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &canvasRect, + int from, int to) const override; private: - void getSubsampledEdges(std::vector > &edges, const QwtScaleMap &xMap) const; - uint64_t edgeAtX(int x, const std::vector > &edges) const; - + void getSubsampledEdges(std::vector> &edges, const QwtScaleMap &xMap) const; + uint64_t edgeAtX(int x, const std::vector> &edges) const; private: - // pointer to data which this curve listens to uint16_t *m_data; // bit to watch in each sample from m_data @@ -67,7 +62,6 @@ class SCOPY_GUI_EXPORT LogicDataCurve : public GenericLogicPlotCurve bool m_displaySampling; mutable std::mutex m_dataAvailableMutex; - }; #endif // LOGICDATACURVE_H diff --git a/gui/include/gui/m2kmeasure.h b/gui/include/gui/m2kmeasure.h index 4596b42c8a..470832f5d4 100644 --- a/gui/include/gui/m2kmeasure.h +++ b/gui/include/gui/m2kmeasure.h @@ -21,182 +21,187 @@ #ifndef M2KMEASURE_H #define M2KMEASURE_H +#include "scopy-gui_export.h" + #include #include + #include -#include "scopy-gui_export.h" namespace scopy { class M2kCrossingDetection; class SCOPY_GUI_EXPORT M2kMeasurementData +{ +public: + enum unitTypes { - public: - enum unitTypes { - METRIC, - TIME, - PERCENTAGE, - DIMENSIONLESS, - DECIBELS, - DECIBELS_TO_CARRIER - }; - - enum axisType { - HORIZONTAL, - VERTICAL, - HORIZONTAL_F, - VERTICAL_F - }; - - M2kMeasurementData(const QString& name, axisType axis, - const QString& unit = "", int channel = -1); - - QString name() const; - double value() const; - void setValue(double value); - bool measured() const; - void setMeasured(bool state); - bool enabled() const; - void setEnabled(bool en); - QString unit() const; - enum unitTypes unitType() const; - int channel() const; - void setChannel(int); - enum axisType axis() const; - - private: - QString m_name; - double m_value; - bool m_measured; - bool m_enabled; - QString m_unit; - enum unitTypes m_unitType; - int m_channel; - enum axisType m_axis; + METRIC, + TIME, + PERCENTAGE, + DIMENSIONLESS, + DECIBELS, + DECIBELS_TO_CARRIER }; - class SCOPY_GUI_EXPORT M2kMeasure + enum axisType { - public: - enum defaultMeasurements { - PERIOD = 0, - FREQUENCY, - MIN, - MAX, - PEAK_PEAK, - MEAN, - CYCLE_MEAN, - RMS, - CYCLE_RMS, - AC_RMS, - AREA, - CYCLE_AREA, - LOW, - HIGH, - AMPLITUDE, - MIDDLE, - P_OVER, - N_OVER, - RISE, - FALL, - P_WIDTH, - N_WIDTH, - P_DUTY, - N_DUTY, - DEFAULT_MEASUREMENT_COUNT - }; - - enum defaultSpectralMeasurements { - NOISE_FLOOR = 0, - SINAD, - SNR, - THD, - THDN, - SFDR, - DEFAULT_SPECTRAL_MEASUREMENT_COUNT - }; - - M2kMeasure(int channel, double *buffer = NULL, size_t length = 0, - const std::function &conversion = nullptr, bool isTimeDomain = true); - - void setDataSource(double *buffer, size_t length); - void measure(); - - void measureTimeDomain(); - void measureSpectral(); - - double sampleRate(); - void setSampleRate(double); - unsigned int adcBitCount(); - void setAdcBitCount(unsigned int); - double crossLevel(); - void setCrossLevel(double); - double hysteresisSpan(); - void setHysteresisSpan(double); - int channel() const; - void setChannel(int); - void setStartIndex(int); - void setEndIndex(int); - void setGatingEnabled(bool); - - void setHarmonicNumber(int harmonics_number); - void setMask(std::vector mask); - - QList> measurments(); - std::shared_ptr measurement(int id); - int activeMeasurementsCount() const; - - void setConversionFunction(const std::function &fp); - - std::vector LoadMaskfromFile(std::string file_name); - - private: - bool highLowFromHistogram(double &low, double &high, - double min, double max); - void clearMeasurements(); - - private: - int m_channel; - double *m_buffer; - ssize_t m_buf_length; - double m_sample_rate; - unsigned int m_adc_bit_count; - double m_cross_level; - double m_hysteresis_span; - int m_startIndex; - int m_endIndex; - int m_gatingEnabled; - int *m_histogram; - M2kCrossingDetection *m_cross_detect; - - int m_harmonics_number; - std::vector m_mask; - bool m_isTimeDomain; - - QList> m_measurements; - std::function m_conversion_function; + HORIZONTAL, + VERTICAL, + HORIZONTAL_F, + VERTICAL_F }; - class SCOPY_GUI_EXPORT M2kStatistic + M2kMeasurementData(const QString &name, axisType axis, const QString &unit = "", int channel = -1); + + QString name() const; + double value() const; + void setValue(double value); + bool measured() const; + void setMeasured(bool state); + bool enabled() const; + void setEnabled(bool en); + QString unit() const; + enum unitTypes unitType() const; + int channel() const; + void setChannel(int); + enum axisType axis() const; + +private: + QString m_name; + double m_value; + bool m_measured; + bool m_enabled; + QString m_unit; + enum unitTypes m_unitType; + int m_channel; + enum axisType m_axis; +}; + +class SCOPY_GUI_EXPORT M2kMeasure +{ +public: + enum defaultMeasurements { - public: - M2kStatistic(); - - void pushNewData(double data); - void clear(); - - double average() const; - double min() const; - double max() const; - double numPushedData() const; - - private: - double m_sum; - double m_min; - double m_max; - double m_dataCount; - double m_average; + PERIOD = 0, + FREQUENCY, + MIN, + MAX, + PEAK_PEAK, + MEAN, + CYCLE_MEAN, + RMS, + CYCLE_RMS, + AC_RMS, + AREA, + CYCLE_AREA, + LOW, + HIGH, + AMPLITUDE, + MIDDLE, + P_OVER, + N_OVER, + RISE, + FALL, + P_WIDTH, + N_WIDTH, + P_DUTY, + N_DUTY, + DEFAULT_MEASUREMENT_COUNT }; -} + + enum defaultSpectralMeasurements + { + NOISE_FLOOR = 0, + SINAD, + SNR, + THD, + THDN, + SFDR, + DEFAULT_SPECTRAL_MEASUREMENT_COUNT + }; + + M2kMeasure(int channel, double *buffer = NULL, size_t length = 0, + const std::function &conversion = nullptr, + bool isTimeDomain = true); + + void setDataSource(double *buffer, size_t length); + void measure(); + + void measureTimeDomain(); + void measureSpectral(); + + double sampleRate(); + void setSampleRate(double); + unsigned int adcBitCount(); + void setAdcBitCount(unsigned int); + double crossLevel(); + void setCrossLevel(double); + double hysteresisSpan(); + void setHysteresisSpan(double); + int channel() const; + void setChannel(int); + void setStartIndex(int); + void setEndIndex(int); + void setGatingEnabled(bool); + + void setHarmonicNumber(int harmonics_number); + void setMask(std::vector mask); + + QList> measurments(); + std::shared_ptr measurement(int id); + int activeMeasurementsCount() const; + + void setConversionFunction(const std::function &fp); + + std::vector LoadMaskfromFile(std::string file_name); + +private: + bool highLowFromHistogram(double &low, double &high, double min, double max); + void clearMeasurements(); + +private: + int m_channel; + double *m_buffer; + ssize_t m_buf_length; + double m_sample_rate; + unsigned int m_adc_bit_count; + double m_cross_level; + double m_hysteresis_span; + int m_startIndex; + int m_endIndex; + int m_gatingEnabled; + int *m_histogram; + M2kCrossingDetection *m_cross_detect; + + int m_harmonics_number; + std::vector m_mask; + bool m_isTimeDomain; + + QList> m_measurements; + std::function m_conversion_function; +}; + +class SCOPY_GUI_EXPORT M2kStatistic +{ +public: + M2kStatistic(); + + void pushNewData(double data); + void clear(); + + double average() const; + double min() const; + double max() const; + double numPushedData() const; + +private: + double m_sum; + double m_min; + double m_max; + double m_dataCount; + double m_average; +}; +} // namespace scopy #endif // M2KMEASURE_H diff --git a/gui/include/gui/m2kmeasurement_gui.h b/gui/include/gui/m2kmeasurement_gui.h index c6a7bc2850..92d024960e 100644 --- a/gui/include/gui/m2kmeasurement_gui.h +++ b/gui/include/gui/m2kmeasurement_gui.h @@ -21,6 +21,7 @@ #define M2KMEASUREMENT_GUI_H #include "plot_utils.hpp" + #include class QLabel; @@ -38,9 +39,9 @@ class SCOPY_GUI_EXPORT M2kMeasurementGui QString name() const; QString value() const; - void setLabelsColor(const QColor& color); + void setLabelsColor(const QColor &color); virtual void init(QLabel *name, QLabel *value); - virtual void update(const M2kMeasurementData& data, double displayScale) = 0; + virtual void update(const M2kMeasurementData &data, double displayScale) = 0; protected: QString m_name; @@ -50,63 +51,63 @@ class SCOPY_GUI_EXPORT M2kMeasurementGui int m_minValLableWidth; }; -class SCOPY_GUI_EXPORT M2kMetricMeasurementGui: public M2kMeasurementGui +class SCOPY_GUI_EXPORT M2kMetricMeasurementGui : public M2kMeasurementGui { public: M2kMetricMeasurementGui(); virtual void init(QLabel *name, QLabel *value); - virtual void update(const M2kMeasurementData& data, double displayScale); + virtual void update(const M2kMeasurementData &data, double displayScale); protected: MetricPrefixFormatter m_formatter; }; -class SCOPY_GUI_EXPORT M2kTimeMeasurementGui: public M2kMeasurementGui +class SCOPY_GUI_EXPORT M2kTimeMeasurementGui : public M2kMeasurementGui { public: M2kTimeMeasurementGui(); virtual void init(QLabel *name, QLabel *value); - virtual void update(const M2kMeasurementData& data, double displayScale); + virtual void update(const M2kMeasurementData &data, double displayScale); protected: TimePrefixFormatter m_formatter; }; -class SCOPY_GUI_EXPORT M2kPercentageMeasurementGui: public M2kMeasurementGui +class SCOPY_GUI_EXPORT M2kPercentageMeasurementGui : public M2kMeasurementGui { public: M2kPercentageMeasurementGui(); virtual void init(QLabel *name, QLabel *value); - virtual void update(const M2kMeasurementData& data, double displayScale); + virtual void update(const M2kMeasurementData &data, double displayScale); }; -class SCOPY_GUI_EXPORT M2kDecibelsMeasurementGui: public M2kMeasurementGui +class SCOPY_GUI_EXPORT M2kDecibelsMeasurementGui : public M2kMeasurementGui { public: M2kDecibelsMeasurementGui(); - virtual void init(QLabel *name, QLabel *value); - virtual void update(const M2kMeasurementData& data, double displayScale); + virtual void init(QLabel *name, QLabel *value); + virtual void update(const M2kMeasurementData &data, double displayScale); }; -class SCOPY_GUI_EXPORT M2kDecibelstoCarrierMeasurementGui: public M2kMeasurementGui +class SCOPY_GUI_EXPORT M2kDecibelstoCarrierMeasurementGui : public M2kMeasurementGui { public: M2kDecibelstoCarrierMeasurementGui(); - virtual void init(QLabel *name, QLabel *value); - virtual void update(const M2kMeasurementData& data, double displayScale); + virtual void init(QLabel *name, QLabel *value); + virtual void update(const M2kMeasurementData &data, double displayScale); }; -class SCOPY_GUI_EXPORT M2kDimensionlessMeasurementGui: public M2kMeasurementGui +class SCOPY_GUI_EXPORT M2kDimensionlessMeasurementGui : public M2kMeasurementGui { public: M2kDimensionlessMeasurementGui(); - - virtual void update(const M2kMeasurementData& data, double displayScale); + + virtual void update(const M2kMeasurementData &data, double displayScale); }; } // namespace scopy diff --git a/gui/include/gui/mapstackedwidget.h b/gui/include/gui/mapstackedwidget.h index fc798861c8..27c7ce915f 100644 --- a/gui/include/gui/mapstackedwidget.h +++ b/gui/include/gui/mapstackedwidget.h @@ -1,10 +1,11 @@ #ifndef MAPSTACKEDWIDGET_H #define MAPSTACKEDWIDGET_H -#include -#include #include "scopy-gui_export.h" +#include +#include + namespace scopy { class SCOPY_GUI_EXPORT MapStackedWidget : public QStackedWidget { @@ -17,13 +18,12 @@ class SCOPY_GUI_EXPORT MapStackedWidget : public QStackedWidget virtual bool remove(QString key); virtual QString getKey(QWidget *w); virtual bool contains(QString key); - virtual QWidget* get(QString key); + virtual QWidget *get(QString key); public Q_SLOTS: virtual bool show(QString key); + protected: - QMap map; + QMap map; }; -} +} // namespace scopy #endif // MAPSTACKEDWIDGET_H - - diff --git a/gui/include/gui/marker_controller.h b/gui/include/gui/marker_controller.h index 60b79f0925..e405916619 100644 --- a/gui/include/gui/marker_controller.h +++ b/gui/include/gui/marker_controller.h @@ -20,11 +20,13 @@ #ifndef MARKER_CONTROLLER_H #define MARKER_CONTROLLER_H -#include +#include "scopy-gui_export.h" + #include +#include #include + #include -#include "scopy-gui_export.h" class QwtPlotPicker; @@ -32,7 +34,7 @@ namespace scopy { class SpectrumMarker; -class SCOPY_GUI_EXPORT MarkerController: public QObject +class SCOPY_GUI_EXPORT MarkerController : public QObject { Q_OBJECT @@ -40,8 +42,8 @@ class SCOPY_GUI_EXPORT MarkerController: public QObject typedef std::shared_ptr marker_sptr; explicit MarkerController(QwtPlot *plot); - MarkerController(const MarkerController&) = delete; - void operator=(const MarkerController&) = delete; + MarkerController(const MarkerController &) = delete; + void operator=(const MarkerController &) = delete; bool enabled() const; void setEnabled(bool en); @@ -56,9 +58,9 @@ class SCOPY_GUI_EXPORT MarkerController: public QObject QwtPlot *plot(); Q_SIGNALS: - void markerSelected(std::shared_ptr&); - void markerPositionChanged(std::shared_ptr&); - void markerReleased(std::shared_ptr&); + void markerSelected(std::shared_ptr &); + void markerPositionChanged(std::shared_ptr &); + void markerReleased(std::shared_ptr &); private Q_SLOTS: void onPickerSelected(QPointF); diff --git a/gui/include/gui/marker_table.hpp b/gui/include/gui/marker_table.hpp index 2e5a9447c8..468ecb04a5 100644 --- a/gui/include/gui/marker_table.hpp +++ b/gui/include/gui/marker_table.hpp @@ -20,9 +20,10 @@ #ifndef MARKER_TABLE_HPP #define MARKER_TABLE_HPP -#include #include "scopy-gui_export.h" +#include + class QStandardItemModel; namespace Ui { @@ -39,15 +40,15 @@ class SCOPY_GUI_EXPORT MarkerTable : public QWidget explicit MarkerTable(QWidget *parent = 0); ~MarkerTable(); - void addMarker(int mkIdx, int chIdx, const QString& name, - double frequency, double magnitude, const QString& type); + void addMarker(int mkIdx, int chIdx, const QString &name, double frequency, double magnitude, + const QString &type); void removeMarker(int mkIdx, int chIdx); - void updateMarker(int mkIdx, int chIdx, double frequency, - double magnitude, const QString& type); + void updateMarker(int mkIdx, int chIdx, double frequency, double magnitude, const QString &type); bool isMarker(int mkIdx, int chIdx); private: - enum Columns { + enum Columns + { COL_ID = 0, COL_NAME = 1, COL_CH = 2, diff --git a/gui/include/gui/menu_anim.hpp b/gui/include/gui/menu_anim.hpp index eea42af63c..979dfb03ea 100644 --- a/gui/include/gui/menu_anim.hpp +++ b/gui/include/gui/menu_anim.hpp @@ -22,66 +22,70 @@ #define MENU_ANIM_HPP #include "customanimation.h" +#include "scopy-gui_export.h" + #include #include -#include "scopy-gui_export.h" namespace scopy { - class SCOPY_GUI_EXPORT MenuAnim : public QWidget - { - Q_OBJECT - - public: - explicit MenuAnim(QByteArray minAnimationProperty, QByteArray maxAnimationProperty, QWidget *parent = nullptr); - ~MenuAnim() {} - - bool animInProgress() const; - - int getAnimationDuration() const; - void setAnimationDuration(int newAnimationDuration); - - void setAnimMin(int min); - void setAnimMax(int max); - - protected: - virtual int getImplicitMin() = 0; - virtual int getImplicitMax() = 0; - Q_SIGNALS: - void finished(bool opened); - - public Q_SLOTS: - void toggleMenu(bool open); - - private Q_SLOTS: - void closeAnimFinished(); - void openAnimFinished(); - - private: - CustomAnimation close_anim_max, close_anim_min, - open_anim_max, open_anim_min; - int min_val; - int max_val; - int animationDuration; - bool animInProg; - }; - - class SCOPY_GUI_EXPORT MenuVAnim : public MenuAnim { - Q_OBJECT - public: - explicit MenuVAnim(QWidget *parent = nullptr); - protected: - int getImplicitMin() override; - int getImplicitMax() override; - }; - - class SCOPY_GUI_EXPORT MenuHAnim : public MenuAnim { - Q_OBJECT - public: - explicit MenuHAnim(QWidget *parent = nullptr); - protected: - int getImplicitMin() override; - int getImplicitMax() override; - }; -} +class SCOPY_GUI_EXPORT MenuAnim : public QWidget +{ + Q_OBJECT + +public: + explicit MenuAnim(QByteArray minAnimationProperty, QByteArray maxAnimationProperty, QWidget *parent = nullptr); + ~MenuAnim() {} + + bool animInProgress() const; + + int getAnimationDuration() const; + void setAnimationDuration(int newAnimationDuration); + + void setAnimMin(int min); + void setAnimMax(int max); + +protected: + virtual int getImplicitMin() = 0; + virtual int getImplicitMax() = 0; +Q_SIGNALS: + void finished(bool opened); + +public Q_SLOTS: + void toggleMenu(bool open); + +private Q_SLOTS: + void closeAnimFinished(); + void openAnimFinished(); + +private: + CustomAnimation close_anim_max, close_anim_min, open_anim_max, open_anim_min; + int min_val; + int max_val; + int animationDuration; + bool animInProg; +}; + +class SCOPY_GUI_EXPORT MenuVAnim : public MenuAnim +{ + Q_OBJECT +public: + explicit MenuVAnim(QWidget *parent = nullptr); + +protected: + int getImplicitMin() override; + int getImplicitMax() override; +}; + +class SCOPY_GUI_EXPORT MenuHAnim : public MenuAnim +{ + Q_OBJECT +public: + explicit MenuHAnim(QWidget *parent = nullptr); + +protected: + int getImplicitMin() override; + int getImplicitMax() override; +}; +} // namespace scopy #endif /* MENU_ANIM_HPP */ diff --git a/gui/include/gui/menu_header.hpp b/gui/include/gui/menu_header.hpp index 17da9148e2..596a4930a4 100644 --- a/gui/include/gui/menu_header.hpp +++ b/gui/include/gui/menu_header.hpp @@ -16,13 +16,13 @@ class MenuHeader : public QWidget Q_OBJECT public: - explicit MenuHeader(QWidget* parent = nullptr); - explicit MenuHeader(const QString& label = nullptr, const QColor* color = new QColor("#4A64FF"), - bool enableBtnVisible = false, QWidget* parent = nullptr); + explicit MenuHeader(QWidget *parent = nullptr); + explicit MenuHeader(const QString &label = nullptr, const QColor *color = new QColor("#4A64FF"), + bool enableBtnVisible = false, QWidget *parent = nullptr); ~MenuHeader(); private: - Ui::MenuHeader* m_ui; + Ui::MenuHeader *m_ui; public Q_SLOTS: void setEnabledBtnState(bool state); @@ -31,11 +31,11 @@ public Q_SLOTS: void enableBtnToggled(bool state); public: - void setLabel(const QString& text); - void setLineColor(const QColor* color); + void setLabel(const QString &text); + void setLineColor(const QColor *color); void setEnableBtnVisible(bool visible); - QPushButton* getEnableBtn(); + QPushButton *getEnableBtn(); void addNewHeaderWidget(QWidget *widget); }; } // namespace gui diff --git a/gui/include/gui/mousewheelwidgetguard.h b/gui/include/gui/mousewheelwidgetguard.h index 1030d512b5..4a53fb780b 100644 --- a/gui/include/gui/mousewheelwidgetguard.h +++ b/gui/include/gui/mousewheelwidgetguard.h @@ -21,9 +21,10 @@ #ifndef MOUSEWHEELWIDGETGUARD #define MOUSEWHEELWIDGETGUARD -#include #include "scopy-gui_export.h" +#include + namespace scopy { class SCOPY_GUI_EXPORT MouseWheelWidgetGuard : public QObject @@ -36,6 +37,6 @@ class SCOPY_GUI_EXPORT MouseWheelWidgetGuard : public QObject bool eventFilter(QObject *, QEvent *) override; }; -} +} // namespace scopy #endif diff --git a/gui/include/gui/movingaverage.h b/gui/include/gui/movingaverage.h index 6592d085c1..2e9e7ae8d7 100644 --- a/gui/include/gui/movingaverage.h +++ b/gui/include/gui/movingaverage.h @@ -1,9 +1,10 @@ #ifndef MOVINGAVERAGE_H #define MOVINGAVERAGE_H -#include #include "scopy-gui_export.h" +#include + class SCOPY_GUI_EXPORT MovingAverage { public: @@ -19,7 +20,6 @@ class SCOPY_GUI_EXPORT MovingAverage QVector history; int capacity; double sum; - }; #endif // MOVINGAVERAGE_H diff --git a/gui/include/gui/nyquistGraph.hpp b/gui/include/gui/nyquistGraph.hpp index 59e6c0be74..00fe8d2a71 100644 --- a/gui/include/gui/nyquistGraph.hpp +++ b/gui/include/gui/nyquistGraph.hpp @@ -23,82 +23,75 @@ #include "dbgraph.hpp" #include "nyquistplotzoomer.h" +#include "scopy-gui_export.h" +#include +#include #include -#include #include - -#include -#include -#include "scopy-gui_export.h" +#include class QwtPolarGrid; namespace scopy { - class NyquistSamplesArray; - - class SCOPY_GUI_EXPORT NyquistGraph : public QwtPolarPlot - { - Q_OBJECT - - Q_PROPERTY(int numSamples - READ getNumSamples - WRITE setNumSamples - ); - - Q_PROPERTY(double min MEMBER mag_min WRITE setMin); - Q_PROPERTY(double max MEMBER mag_max WRITE setMax); - Q_PROPERTY(QColor color READ getColor WRITE setColor); - Q_PROPERTY(QColor bg_color READ getBgColor WRITE setBgColor); - Q_PROPERTY(QFont font_azimuth - READ getFontAzimuth WRITE setFontAzimuth); - Q_PROPERTY(QFont font_radius - READ getFontRadius WRITE setFontRadius); - - public: - explicit NyquistGraph(QWidget *parent = nullptr); - ~NyquistGraph(); - - const QColor getColor() const; - const QColor& getBgColor() const; - int getNumSamples() const; - double getThickness() const; - - QFont getFontAzimuth() const; - QFont getFontRadius() const; - - void enableZooming(QPushButton *bntZoomIn, QPushButton *btnZoomOut); - - public Q_SLOTS: - void setColor(const QColor& color); - void setBgColor(const QColor& color); - void setNumSamples(int num); - void plot(double x, double y); - void reset(); - void setThickness(int value); - - void setMin(double min); - void setMax(double max); - - void setFontAzimuth(const QFont& font); - void setFontRadius(const QFont& font); - - void mousePressEvent(QMouseEvent *event); - void mouseReleaseEvent(QMouseEvent *event); - void enterEvent(QEvent *event); - void leaveEvent(QEvent *event); - - private: - double mag_min, mag_max; - unsigned int numSamples; - NyquistSamplesArray *samples; - QwtPolarGrid *grid; - QwtPolarCurve curve; - QwtPolarPanner *panner; - NyquistPlotZoomer *zoomer; - double m_thickness; - - }; -} +class NyquistSamplesArray; + +class SCOPY_GUI_EXPORT NyquistGraph : public QwtPolarPlot +{ + Q_OBJECT + + Q_PROPERTY(int numSamples READ getNumSamples WRITE setNumSamples); + + Q_PROPERTY(double min MEMBER mag_min WRITE setMin); + Q_PROPERTY(double max MEMBER mag_max WRITE setMax); + Q_PROPERTY(QColor color READ getColor WRITE setColor); + Q_PROPERTY(QColor bg_color READ getBgColor WRITE setBgColor); + Q_PROPERTY(QFont font_azimuth READ getFontAzimuth WRITE setFontAzimuth); + Q_PROPERTY(QFont font_radius READ getFontRadius WRITE setFontRadius); + +public: + explicit NyquistGraph(QWidget *parent = nullptr); + ~NyquistGraph(); + + const QColor getColor() const; + const QColor &getBgColor() const; + int getNumSamples() const; + double getThickness() const; + + QFont getFontAzimuth() const; + QFont getFontRadius() const; + + void enableZooming(QPushButton *bntZoomIn, QPushButton *btnZoomOut); + +public Q_SLOTS: + void setColor(const QColor &color); + void setBgColor(const QColor &color); + void setNumSamples(int num); + void plot(double x, double y); + void reset(); + void setThickness(int value); + + void setMin(double min); + void setMax(double max); + + void setFontAzimuth(const QFont &font); + void setFontRadius(const QFont &font); + + void mousePressEvent(QMouseEvent *event); + void mouseReleaseEvent(QMouseEvent *event); + void enterEvent(QEvent *event); + void leaveEvent(QEvent *event); + +private: + double mag_min, mag_max; + unsigned int numSamples; + NyquistSamplesArray *samples; + QwtPolarGrid *grid; + QwtPolarCurve curve; + QwtPolarPanner *panner; + NyquistPlotZoomer *zoomer; + double m_thickness; +}; +} // namespace scopy #endif /* NYQUISTGRAPH_HPP */ diff --git a/gui/include/gui/nyquistplotzoomer.h b/gui/include/gui/nyquistplotzoomer.h index 849651fd0b..c58fce4a9e 100644 --- a/gui/include/gui/nyquistplotzoomer.h +++ b/gui/include/gui/nyquistplotzoomer.h @@ -26,7 +26,7 @@ namespace scopy { class NyquistPlotZoomer : public QwtPolarMagnifier { public: - NyquistPlotZoomer(QwtPolarCanvas* parent); + NyquistPlotZoomer(QwtPolarCanvas *parent); public: void zoomIn(); @@ -37,6 +37,6 @@ class NyquistPlotZoomer : public QwtPolarMagnifier private: int zoom_count; }; -} +} // namespace scopy #endif // NYQUISTPLOTZOOMER_H diff --git a/gui/include/gui/osc_adjuster.hpp b/gui/include/gui/osc_adjuster.hpp index 0b703b29b9..8a5034b429 100644 --- a/gui/include/gui/osc_adjuster.hpp +++ b/gui/include/gui/osc_adjuster.hpp @@ -21,21 +21,22 @@ #ifndef M2K_OSC_ADJUSTER_H #define M2K_OSC_ADJUSTER_H -#include +#include "scopy-gui_export.h" + #include #include +#include #include -#include "scopy-gui_export.h" class QWidget; class QMouseEvent; class QWheelEvent; -class SCOPY_GUI_EXPORT OscAdjuster: public QObject +class SCOPY_GUI_EXPORT OscAdjuster : public QObject { Q_OBJECT public: - explicit OscAdjuster(QWidget*, QwtAxisId axisId); + explicit OscAdjuster(QWidget *, QwtAxisId axisId); virtual ~OscAdjuster(); QWidget *parentWidget(); @@ -75,19 +76,15 @@ class SCOPY_GUI_EXPORT OscAdjuster: public QObject QwtAxisId d_axisId; }; -class SCOPY_GUI_EXPORT VertMouseGestures: public OscAdjuster +class SCOPY_GUI_EXPORT VertMouseGestures : public OscAdjuster { Q_OBJECT public: - explicit VertMouseGestures(QWidget *parent, QwtAxisId axisId): - OscAdjuster(parent, axisId) - { - } + explicit VertMouseGestures(QWidget *parent, QwtAxisId axisId) + : OscAdjuster(parent, axisId) + {} - virtual ~VertMouseGestures() - { - - } + virtual ~VertMouseGestures() {} Q_SIGNALS: void upMovement(double); @@ -96,25 +93,24 @@ class SCOPY_GUI_EXPORT VertMouseGestures: public OscAdjuster protected: virtual void rescale(double factor) { - factor = qAbs( factor ); - if ( factor == 1.0 || factor == 0.0 ) + factor = qAbs(factor); + if(factor == 1.0 || factor == 0.0) return; - if (factor > 1.0) + if(factor > 1.0) Q_EMIT upMovement(factor); else Q_EMIT downMovement(factor); } virtual void widgetMouseMoveEvent(QMouseEvent *mouseEvent) { - if (!d_mousePressed) + if(!d_mousePressed) return; const int dy = mouseEvent->pos().y() - d_mousePos.y(); - if (dy != 0) - { + if(dy != 0) { double f = d_mouseFactor; - if (dy < 0) + if(dy < 0) f = 1 / f; rescale(f); @@ -124,19 +120,15 @@ class SCOPY_GUI_EXPORT VertMouseGestures: public OscAdjuster } }; -class SCOPY_GUI_EXPORT HorizMouseGestures: public OscAdjuster +class SCOPY_GUI_EXPORT HorizMouseGestures : public OscAdjuster { Q_OBJECT public: - explicit HorizMouseGestures(QWidget *parent, QwtAxisId axisId): - OscAdjuster(parent, axisId) - { - } + explicit HorizMouseGestures(QWidget *parent, QwtAxisId axisId) + : OscAdjuster(parent, axisId) + {} - virtual ~HorizMouseGestures() - { - - } + virtual ~HorizMouseGestures() {} Q_SIGNALS: void leftMovement(double); @@ -145,11 +137,11 @@ class SCOPY_GUI_EXPORT HorizMouseGestures: public OscAdjuster protected: virtual void rescale(double factor) { - factor = qAbs( factor ); - if ( factor == 1.0 || factor == 0.0 ) + factor = qAbs(factor); + if(factor == 1.0 || factor == 0.0) return; - if (factor > 1.0) + if(factor > 1.0) Q_EMIT leftMovement(factor); else Q_EMIT rightMovement(factor); @@ -157,20 +149,19 @@ class SCOPY_GUI_EXPORT HorizMouseGestures: public OscAdjuster virtual void widgetMouseMoveEvent(QMouseEvent *mouseEvent) { - if ( !d_mousePressed ) + if(!d_mousePressed) return; - const int dx = mouseEvent->pos().x() - d_mousePos.x(); - if ( dx != 0 ) - { + const int dx = mouseEvent->pos().x() - d_mousePos.x(); + if(dx != 0) { double f = d_mouseFactor; - if ( dx < 0 ) - f = 1 / f; + if(dx < 0) + f = 1 / f; - rescale( f ); - } + rescale(f); + } - d_mousePos = mouseEvent->pos(); + d_mousePos = mouseEvent->pos(); } }; diff --git a/gui/include/gui/osc_custom_scroll.h b/gui/include/gui/osc_custom_scroll.h index 007ceb06d7..36181ee22f 100644 --- a/gui/include/gui/osc_custom_scroll.h +++ b/gui/include/gui/osc_custom_scroll.h @@ -20,11 +20,12 @@ #ifndef OSCCUSTOMSCROLL_H #define OSCCUSTOMSCROLL_H -#include +#include "scopy-gui_export.h" + #include -#include +#include #include -#include "scopy-gui_export.h" +#include namespace scopy { class SCOPY_GUI_EXPORT OscCustomScrollArea : public QScrollArea @@ -41,9 +42,9 @@ public Q_SLOTS: private: QScroller *scroll; bool inside; - //QScrollBar *bar; + // QScrollBar *bar; bool disableCursor; }; -} +} // namespace scopy #endif // OSCCUSTOMSCROLL_H diff --git a/gui/include/gui/osc_export_settings.h b/gui/include/gui/osc_export_settings.h index d69fa4772e..35f40c7894 100644 --- a/gui/include/gui/osc_export_settings.h +++ b/gui/include/gui/osc_export_settings.h @@ -21,13 +21,14 @@ #define OSC_EXPORT_SETTINGS_H /* Qt includes */ -#include -#include -#include -#include -#include #include "scopy-gui_export.h" +#include +#include +#include +#include +#include + /* Local includes */ #include "dropdown_switch_list.h" @@ -49,7 +50,7 @@ class SCOPY_GUI_EXPORT ExportSettings : public QWidget public Q_SLOTS: void addChannel(int id, QString name); void removeChannel(int id); - void onExportChannelChanged(QStandardItem*); + void onExportChannelChanged(QStandardItem *); QPushButton *getExportButton(); QPushButton *getExportAllButton(); @@ -68,6 +69,6 @@ public Q_SLOTS: int nr_channels; QMap oldSettings; }; -} +} // namespace scopy #endif // OSC_EXPORT_SETTINGS_H diff --git a/gui/include/gui/osc_import_settings.h b/gui/include/gui/osc_import_settings.h index 911e105e9d..a5462991cc 100644 --- a/gui/include/gui/osc_import_settings.h +++ b/gui/include/gui/osc_import_settings.h @@ -31,12 +31,12 @@ class ExportSettings; namespace scopy { class SCOPY_GUI_EXPORT ImportSettings : public ExportSettings { - Q_OBJECT + Q_OBJECT public: - ImportSettings(QWidget *parent = 0); - ~ImportSettings(); + ImportSettings(QWidget *parent = 0); + ~ImportSettings(); }; -} +} // namespace scopy #endif // OSC_IMPORT_SETTINGS_H diff --git a/gui/include/gui/osc_scale_engine.h b/gui/include/gui/osc_scale_engine.h index 67831d0393..affaf525bd 100644 --- a/gui/include/gui/osc_scale_engine.h +++ b/gui/include/gui/osc_scale_engine.h @@ -21,10 +21,11 @@ #ifndef M2K_OSC_SCALE_ENGINE_H #define M2K_OSC_SCALE_ENGINE_H -#include #include "scopy-gui_export.h" -class SCOPY_GUI_EXPORT OscScaleEngine: public QwtLinearScaleEngine +#include + +class SCOPY_GUI_EXPORT OscScaleEngine : public QwtLinearScaleEngine { public: OscScaleEngine(); @@ -35,27 +36,25 @@ class SCOPY_GUI_EXPORT OscScaleEngine: public QwtLinearScaleEngine void setMinorTicksCount(uint minorTicks); uint minorTicksCount(); - void showZero(bool en); - virtual void autoScale( int maxSteps, - double &x1, double &x2, double &stepSize ) const; + void showZero(bool en); + virtual void autoScale(int maxSteps, double &x1, double &x2, double &stepSize) const; - virtual QwtScaleDiv divideScale(double x1, double x2, int maxMajorSteps, - int maxMinorSteps, double stepSize = 0.0) const; + virtual QwtScaleDiv divideScale(double x1, double x2, int maxMajorSteps, int maxMinorSteps, + double stepSize = 0.0) const; protected: - void buildTicks( - const QwtInterval &, double stepSize, int maxMinSteps, - QList ticks[QwtScaleDiv::NTickTypes] ) const; + void buildTicks(const QwtInterval &, double stepSize, int maxMinSteps, + QList ticks[QwtScaleDiv::NTickTypes]) const; + + void buildMinorTicks(const QList &majorTicks, int maxMinorSteps, double stepSize, + QList &minorTicks, QList &mediumTicks) const; - void buildMinorTicks( const QList& majorTicks, - int maxMinorSteps, double stepSize, - QList &minorTicks, QList &mediumTicks ) const; + QList buildMajorTicks(const QwtInterval &interval, double stepSize) const; - QList buildMajorTicks(const QwtInterval &interval, double stepSize) const; private: uint m_majorTicks; // number of major ticks a scale should have uint m_minorTicks; // number of minor ticks between two major ticks - bool m_showZero; + bool m_showZero; }; #endif /* M2K_OSC_SCALE_ENGINE_H */ diff --git a/gui/include/gui/osc_scale_zoomer.h b/gui/include/gui/osc_scale_zoomer.h index 0891910ed8..be9b67f0dc 100644 --- a/gui/include/gui/osc_scale_zoomer.h +++ b/gui/include/gui/osc_scale_zoomer.h @@ -21,29 +21,30 @@ #ifndef OSC_SCALE_ZOOMER_H #define OSC_SCALE_ZOOMER_H -#include #include "limitedplotzoomer.h" #include "scopy-gui_export.h" +#include + namespace scopy { - class SCOPY_GUI_EXPORT OscScaleZoomer : public LimitedPlotZoomer - { - Q_OBJECT +class SCOPY_GUI_EXPORT OscScaleZoomer : public LimitedPlotZoomer +{ + Q_OBJECT - Q_PROPERTY(QColor color READ getColor WRITE setColor); + Q_PROPERTY(QColor color READ getColor WRITE setColor); - public: - explicit OscScaleZoomer(QWidget *parent); - ~OscScaleZoomer(); +public: + explicit OscScaleZoomer(QWidget *parent); + ~OscScaleZoomer(); - void cancel(); + void cancel(); - QColor getColor() const; - void setColor(const QColor& color); + QColor getColor() const; + void setColor(const QColor &color); - private: - QwtText trackerText(const QPoint& pos) const; - }; -} +private: + QwtText trackerText(const QPoint &pos) const; +}; +} // namespace scopy #endif /* OSC_SCALE_ZOOMER_H */ diff --git a/gui/include/gui/oscilloscope_plot.hpp b/gui/include/gui/oscilloscope_plot.hpp index 9a2daaea07..2b2ee9a192 100644 --- a/gui/include/gui/oscilloscope_plot.hpp +++ b/gui/include/gui/oscilloscope_plot.hpp @@ -22,281 +22,282 @@ #define M2K_OSCILLOSCOPE_PLOT_H #include "TimeDomainDisplayPlot.h" -#include "m2kmeasure.h" #include "customplotpositionbutton.h" +#include "genericlogicplotcurve.h" #include "graticule.h" - -#include +#include "m2kmeasure.h" +#include "qstackedwidget.h" +#include "scopy-gui_export.h" #include -#include "genericlogicplotcurve.h" -#include "scopy-gui_export.h" -#include "qstackedwidget.h" - +#include class QLabel; namespace scopy { - class Oscilloscope_API; - class PlotWidget; - - class SCOPY_GUI_EXPORT OscilloscopePlot : public TimeDomainDisplayPlot +class Oscilloscope_API; +class PlotWidget; + +class SCOPY_GUI_EXPORT OscilloscopePlot : public TimeDomainDisplayPlot +{ + Q_OBJECT + +public: + OscilloscopePlot(QWidget *parent, bool isdBgraph = false, unsigned int xNumDivs = 10, unsigned int yNumDiv = 10, + PrefixFormatter *pfXaxis = nullptr, PrefixFormatter *pfYaxis = nullptr, + int qwtAxis = QwtAxis::YLeft); + ~OscilloscopePlot(); +}; + +class SCOPY_GUI_EXPORT CapturePlot : public OscilloscopePlot +{ + friend class Oscilloscope_API; + friend class LogicAnalyzer_API; + friend class Channel_API; + + Q_OBJECT + +public: + enum TriggerState { - Q_OBJECT - - public: - OscilloscopePlot(QWidget *parent, bool isdBgraph = false, unsigned int xNumDivs = 10, - unsigned int yNumDiv = 10, PrefixFormatter* pfXaxis = nullptr, PrefixFormatter* pfYaxis = nullptr, int qwtAxis = QwtAxis::YLeft); - ~OscilloscopePlot(); + Waiting, + Triggered, + Stop, + Auto, }; - class SCOPY_GUI_EXPORT CapturePlot: public OscilloscopePlot - { - friend class Oscilloscope_API; - friend class LogicAnalyzer_API; - friend class Channel_API; +public: + CapturePlot(QWidget *parent, bool isdBgraph = false, unsigned int xNumDivs = 10, unsigned int yNumDivs = 10, + PrefixFormatter *pfXaxis = nullptr, PrefixFormatter *pfYaxis = nullptr, + int qwtAxis = QwtAxis::YLeft); + ~CapturePlot(); - Q_OBJECT + void replot(); - public: - enum TriggerState { - Waiting, - Triggered, - Stop, - Auto, - }; + HorizBar *levelTriggerA(); + HorizBar *levelTriggerB(); - public: - CapturePlot(QWidget *parent, bool isdBgraph = false, unsigned int xNumDivs = 10, unsigned int yNumDivs = 10, - PrefixFormatter* pfXaxis = nullptr, PrefixFormatter* pfYaxis = nullptr, int qwtAxis = QwtAxis::YLeft); - ~CapturePlot(); + QWidget *topArea(); + QWidget *topHandlesArea(); - void replot(); + void setBonusWidthForHistogram(int width); - HorizBar *levelTriggerA(); - HorizBar *levelTriggerB(); + bool triggerAEnabled(); + bool triggerBEnabled(); + int selectedChannel(); + bool measurementsEnabled(); - QWidget *topArea(); - QWidget *topHandlesArea(); + void setOffsetWidgetVisible(int chnIdx, bool visible); + void removeOffsetWidgets(int chnIdx); + void removeLeftVertAxis(unsigned int axis); - void setBonusWidthForHistogram(int width); + QList *getMeasurements(); + void measure(); + int activeMeasurementsCount(int chnIdx); + QList> measurements(int chnIdx); + std::shared_ptr measurement(int id, int chnIdx); - bool triggerAEnabled(); - bool triggerBEnabled(); - int selectedChannel(); - bool measurementsEnabled(); + OscPlotZoomer *getZoomer(); + void setOffsetInterval(double minValue, double maxValue); + double getMaxOffsetValue(); + double getMinOffsetValue(); - void setOffsetWidgetVisible(int chnIdx, bool visible); - void removeOffsetWidgets(int chnIdx); - void removeLeftVertAxis(unsigned int axis); - - QList* getMeasurements(); - void measure(); - int activeMeasurementsCount(int chnIdx); - QList> measurements(int chnIdx); - std::shared_ptr measurement(int id, int chnIdx); - - OscPlotZoomer* getZoomer(); - void setOffsetInterval(double minValue, double maxValue); - double getMaxOffsetValue(); - double getMinOffsetValue(); - - void bringCurveToFront(unsigned int curveIdx); - - void setTimeBaseZoomed(bool zoomed); - - void enableLabels(bool enabled); - bool eventFilter(QObject *, QEvent *); - void setActiveVertAxis(unsigned int axisIdx, bool selected = true); - void showYAxisWidget(unsigned int axisIdx, bool en); - void enableAxisLabels(bool enabled); + void bringCurveToFront(unsigned int curveIdx); - void setDisplayScale(double value); - - void setTimeTriggerInterval(double min, double max); - bool labelsEnabled(); - - void setGraticuleEnabled(bool enabled); - void setGatingEnabled(bool enabled); + void setTimeBaseZoomed(bool zoomed); - void computeMeasurementsForChannel(unsigned int chnIdx, unsigned int sampleRate); + void enableLabels(bool enabled); + bool eventFilter(QObject *, QEvent *); + void setActiveVertAxis(unsigned int axisIdx, bool selected = true); + void showYAxisWidget(unsigned int axisIdx, bool en); + void enableAxisLabels(bool enabled); - void setConversionFunction(const std::function &fp); + void setDisplayScale(double value); - void enableXaxisLabels(); - void enableTimeTrigger(bool enable); - QString getChannelName(int chIdx) const; - void setChannelName(const QString &name, int chIdx); + void setTimeTriggerInterval(double min, double max); + bool labelsEnabled(); - QString formatXValue(double value, int precision) const; - QString formatYValue(double value, int precision) const; + void setGraticuleEnabled(bool enabled); + void setGatingEnabled(bool enabled); - CursorReadouts * getCursorReadouts() const; + void computeMeasurementsForChannel(unsigned int chnIdx, unsigned int sampleRate); - // Get the curve at the given point. May return nullptr. - GenericLogicPlotCurve* curveAt(const QPoint& pos) const; + void setConversionFunction(const std::function &fp); - void setAllAxes(int ch_id); - VertBar* getMeasurementGateBar1(); - VertBar* getMeasurementGateBar2(); - - QList getOffsetHandles() const; + void enableXaxisLabels(); + void enableTimeTrigger(bool enable); + QString getChannelName(int chIdx) const; + void setChannelName(const QString &name, int chIdx); - void setStatusWidget(QWidget *newStatusWidget); - - Q_SIGNALS: - void timeTriggerValueChanged(double); - void channelOffsetChanged(unsigned int, double); - void measurementsAvailable(); - void canvasSizeChanged(); - void leftGateChanged(double); - void rightGateChanged(double); - void channelSelected(int, bool); + QString formatXValue(double value, int precision) const; + QString formatYValue(double value, int precision) const; - // These are only emitted if you set setMouseTracking(true) (not done by default) - void mouseButtonPress(const QMouseEvent *event); - void mouseButtonRelease(const QMouseEvent *event); - void mouseMove(const QMouseEvent *event); + CursorReadouts *getCursorReadouts() const; - public Q_SLOTS: - void setTriggerAEnabled(bool en); - void setTriggerBEnabled(bool en); - void setSelectedChannel(int id); - void setMeasuremensEnabled(bool en); - void setPeriodDetectLevel(int chnIdx, double lvl); - void setPeriodDetectHyst(int chnIdx, double hyst); - void setTimeBaseLabelValue(double timebase); - void setBufferSizeLabelValue(int numSamples); - void setSampleRatelabelValue(double sampleRate); - void setTriggerState(int triggerState); - void setMaxBufferSizeErrorLabel(bool reached, const QString &customWarning = ""); + // Get the curve at the given point. May return nullptr. + GenericLogicPlotCurve *curveAt(const QPoint &pos) const; - void showEvent(QShowEvent *event); - void printWithNoBackground(const QString& toolName = "", bool editScaleDraw = true); - - int getAnalogChannels() const; + void setAllAxes(int ch_id); + VertBar *getMeasurementGateBar1(); + VertBar *getMeasurementGateBar2(); - /* digital channels */ - void onDigitalChannelAdded(int chnIdx); - void setChannelSelectable(int chnIdx, bool selectable); - void removeDigitalPlotCurve(QwtPlotCurve *curve); - void setOffsetHandleVisible(int chIdx, bool visible); - - /* channel group */ - void addToGroup(int currentGroup, int toAdd); - void beginGroupSelection(); - bool endGroupSelection(bool moveAnnotationCurvesLast = false); // TODO: toggle group selection - QVector getGroupOfChannel(int chnIdx); - QVector> getAllGroups(); - void removeFromGroup(int chnIdx, int removedChnIdx, bool &didGroupVanish); - void positionInGroupChanged(int chnIdx, int from, int to); - void setGroups(const QVector> &groups); - - protected: - virtual void cleanUpJustBeforeChannelRemoval(int chnIdx); + QList getOffsetHandles() const; - private: - M2kMeasure* measureOfChannel(int chnIdx) const; - void updateBufferSizeSampleRateLabel(int nsamples, double sr); - void updateHandleAreaPadding(bool); - void updateGateMargins(); + void setStatusWidget(QWidget *newStatusWidget); - private Q_SLOTS: - void onChannelAdded(int); - void onNewDataReceived(); +Q_SIGNALS: + void timeTriggerValueChanged(double); + void channelOffsetChanged(unsigned int, double); + void measurementsAvailable(); + void canvasSizeChanged(); + void leftGateChanged(double); + void rightGateChanged(double); + void channelSelected(int, bool); - void onGateBar1PixelPosChanged(int); - void onGateBar2PixelPosChanged(int); - - void onGateBar1Moved(double); - void onGateBar2Moved(double); + // These are only emitted if you set setMouseTracking(true) (not done by default) + void mouseButtonPress(const QMouseEvent *event); + void mouseButtonRelease(const QMouseEvent *event); + void mouseMove(const QMouseEvent *event); - void onTimeTriggerHandlePosChanged(int); - void onTimeTriggerHandleGrabbed(bool); - - void onTriggerAHandleGrabbed(bool); - void onTriggerBHandleGrabbed(bool); - - void handleInGroupChangedPosition(int position); - - void onHCursor1Moved(double); - void onHCursor2Moved(double); - void onVCursor1Moved(double); - void onVCursor2Moved(double); - - private: - std::function m_conversion_function; - - bool d_triggerAEnabled; - bool d_triggerBEnabled; - bool d_measurementsEnabled; - bool d_labelsEnabled; - - QStackedWidget *d_topWidget; - GateHandlesArea *d_topGateHandlesArea; - int d_bonusWidth; - - QWidget *m_statusWidget; - QLabel *d_timeBaseLabel; - QLabel *d_sampleRateLabel; - QLabel *d_triggerStateLabel; - QLabel *d_maxBufferError; - - int d_bufferSizeLabelVal; - double d_sampleRateLabelVal; - - QList d_offsetBars; - QList d_offsetHandles; - - // Channel grouping - QVector> d_groupHandles; - bool d_startedGrouping; - QVector d_groupMarkers; - - PlotGateHandle *d_hGatingHandle1; - PlotGateHandle *d_hGatingHandle2; - - VertBar *d_gateBar1; - VertBar *d_gateBar2; - - VertBar *d_timeTriggerBar; - HorizBar *d_levelTriggerABar; - HorizBar *d_levelTriggerBBar; - FreePlotLineHandleH *d_timeTriggerHandle; - FreePlotLineHandleV *d_levelTriggerAHandle; - FreePlotLineHandleV *d_levelTriggerBHandle; - - MetricPrefixFormatter d_cursorMetricFormatter; - TimePrefixFormatter d_cursorTimeFormatter; +public Q_SLOTS: + void setTriggerAEnabled(bool en); + void setTriggerBEnabled(bool en); + void setSelectedChannel(int id); + void setMeasuremensEnabled(bool en); + void setPeriodDetectLevel(int chnIdx, double lvl); + void setPeriodDetectHyst(int chnIdx, double hyst); + void setTimeBaseLabelValue(double timebase); + void setBufferSizeLabelValue(int numSamples); + void setSampleRatelabelValue(double sampleRate); + void setTriggerState(int triggerState); + void setMaxBufferSizeErrorLabel(bool reached, const QString &customWarning = ""); - QPen d_trigAactiveLinePen; - QPen d_trigAinactiveLinePen; - QPen d_trigBactiveLinePen; - QPen d_trigBinactiveLinePen; - QPen d_timeTriggerInactiveLinePen; - QPen d_timeTriggerActiveLinePen; - - QList d_measureObjs; - - double value_v1, value_v2, value_h1, value_h2; - double value_gateLeft, value_gateRight; - double d_minOffsetValue, d_maxOffsetValue; - double d_timeTriggerMinValue, d_timeTriggerMaxValue; - - bool displayGraticule; - Graticule *graticule; + void showEvent(QShowEvent *event); + void printWithNoBackground(const QString &toolName = "", bool editScaleDraw = true); + + int getAnalogChannels() const; - QwtPlotShapeItem *leftGate, *rightGate; - QRectF leftGateRect, rightGateRect; - bool d_gatingEnabled; + /* digital channels */ + void onDigitalChannelAdded(int chnIdx); + void setChannelSelectable(int chnIdx, bool selectable); + void removeDigitalPlotCurve(QwtPlotCurve *curve); + void setOffsetHandleVisible(int chIdx, bool visible); + + /* channel group */ + void addToGroup(int currentGroup, int toAdd); + void beginGroupSelection(); + bool endGroupSelection(bool moveAnnotationCurvesLast = false); // TODO: toggle group selection + QVector getGroupOfChannel(int chnIdx); + QVector> getAllGroups(); + void removeFromGroup(int chnIdx, int removedChnIdx, bool &didGroupVanish); + void positionInGroupChanged(int chnIdx, int from, int to); + void setGroups(const QVector> &groups); + +protected: + virtual void cleanUpJustBeforeChannelRemoval(int chnIdx); - QPair d_xAxisInterval; - int d_currentHandleInitPx; - void pushBackNewOffsetWidgets(RoundedHandleV *chOffsetHdl, HorizBar *chOffsetBar); +private: + M2kMeasure *measureOfChannel(int chnIdx) const; + void updateBufferSizeSampleRateLabel(int nsamples, double sr); + void updateHandleAreaPadding(bool); + void updateGateMargins(); - QVector plot_logic_curves; - }; -} +private Q_SLOTS: + void onChannelAdded(int); + void onNewDataReceived(); + + void onGateBar1PixelPosChanged(int); + void onGateBar2PixelPosChanged(int); + + void onGateBar1Moved(double); + void onGateBar2Moved(double); + + void onTimeTriggerHandlePosChanged(int); + void onTimeTriggerHandleGrabbed(bool); + + void onTriggerAHandleGrabbed(bool); + void onTriggerBHandleGrabbed(bool); + + void handleInGroupChangedPosition(int position); + + void onHCursor1Moved(double); + void onHCursor2Moved(double); + void onVCursor1Moved(double); + void onVCursor2Moved(double); + +private: + std::function m_conversion_function; + + bool d_triggerAEnabled; + bool d_triggerBEnabled; + bool d_measurementsEnabled; + bool d_labelsEnabled; + + QStackedWidget *d_topWidget; + GateHandlesArea *d_topGateHandlesArea; + int d_bonusWidth; + + QWidget *m_statusWidget; + QLabel *d_timeBaseLabel; + QLabel *d_sampleRateLabel; + QLabel *d_triggerStateLabel; + QLabel *d_maxBufferError; + + int d_bufferSizeLabelVal; + double d_sampleRateLabelVal; + + QList d_offsetBars; + QList d_offsetHandles; + + // Channel grouping + QVector> d_groupHandles; + bool d_startedGrouping; + QVector d_groupMarkers; + + PlotGateHandle *d_hGatingHandle1; + PlotGateHandle *d_hGatingHandle2; + + VertBar *d_gateBar1; + VertBar *d_gateBar2; + + VertBar *d_timeTriggerBar; + HorizBar *d_levelTriggerABar; + HorizBar *d_levelTriggerBBar; + FreePlotLineHandleH *d_timeTriggerHandle; + FreePlotLineHandleV *d_levelTriggerAHandle; + FreePlotLineHandleV *d_levelTriggerBHandle; + + MetricPrefixFormatter d_cursorMetricFormatter; + TimePrefixFormatter d_cursorTimeFormatter; + + QPen d_trigAactiveLinePen; + QPen d_trigAinactiveLinePen; + QPen d_trigBactiveLinePen; + QPen d_trigBinactiveLinePen; + QPen d_timeTriggerInactiveLinePen; + QPen d_timeTriggerActiveLinePen; + + QList d_measureObjs; + + double value_v1, value_v2, value_h1, value_h2; + double value_gateLeft, value_gateRight; + double d_minOffsetValue, d_maxOffsetValue; + double d_timeTriggerMinValue, d_timeTriggerMaxValue; + + bool displayGraticule; + Graticule *graticule; + + QwtPlotShapeItem *leftGate, *rightGate; + QRectF leftGateRect, rightGateRect; + bool d_gatingEnabled; + + QPair d_xAxisInterval; + int d_currentHandleInitPx; + void pushBackNewOffsetWidgets(RoundedHandleV *chOffsetHdl, HorizBar *chOffsetBar); + + QVector plot_logic_curves; +}; +} // namespace scopy #endif /* M2K_OSCILLOSCOPE_PLOT_H */ diff --git a/gui/include/gui/plot_line_handle.h b/gui/include/gui/plot_line_handle.h index a29aea9785..43f2f1fafb 100644 --- a/gui/include/gui/plot_line_handle.h +++ b/gui/include/gui/plot_line_handle.h @@ -21,14 +21,16 @@ #ifndef PLOT_LINE_HANDLE_H #define PLOT_LINE_HANDLE_H -#include +#include "scopy-gui_export.h" + #include +#include + #include -#include "scopy-gui_export.h" class HandlesArea; -class SCOPY_GUI_EXPORT PlotLineHandle: public QWidget +class SCOPY_GUI_EXPORT PlotLineHandle : public QWidget { Q_OBJECT @@ -42,8 +44,8 @@ class SCOPY_GUI_EXPORT PlotLineHandle: public QWidget virtual void moveWithinParent(int x, int y) = 0; virtual void setPosition(int) = 0; int position(); - void setPen(const QPen&); - const QPen& pen(); + void setPen(const QPen &); + const QPen &pen(); Q_SIGNALS: void positionChanged(int); @@ -72,7 +74,8 @@ class SCOPY_GUI_EXPORT PlotLineHandle: public QWidget void setGrabbed(bool); }; -class SCOPY_GUI_EXPORT PlotGateHandle: public PlotLineHandle{ +class SCOPY_GUI_EXPORT PlotGateHandle : public PlotLineHandle +{ public: PlotGateHandle(const QPixmap &handleIcon, QWidget *parent = 0); void triggerMove(); @@ -87,10 +90,12 @@ class SCOPY_GUI_EXPORT PlotGateHandle: public PlotLineHandle{ int getCurrentPos(); bool reachedLimit(); void setOtherCursorPosition(int position); + protected: void paintEvent(QPaintEvent *event); int originPosToCenter(int origin); int centerPosToOrigin(int center); + private: int m_position; int m_otherCursorPos; @@ -100,11 +105,10 @@ class SCOPY_GUI_EXPORT PlotGateHandle: public PlotLineHandle{ scopy::TimePrefixFormatter d_timeFormatter; }; -class SCOPY_GUI_EXPORT PlotLineHandleH: public PlotLineHandle +class SCOPY_GUI_EXPORT PlotLineHandleH : public PlotLineHandle { public: - PlotLineHandleH(const QPixmap &handleIcon, QWidget *parent = 0, - bool facingBottom = false); + PlotLineHandleH(const QPixmap &handleIcon, QWidget *parent = 0, bool facingBottom = false); void triggerMove(); void setPosition(int); void setPositionSilenty(int); @@ -122,11 +126,10 @@ class SCOPY_GUI_EXPORT PlotLineHandleH: public PlotLineHandle bool m_facingBottom; }; -class SCOPY_GUI_EXPORT PlotLineHandleV: public PlotLineHandle +class SCOPY_GUI_EXPORT PlotLineHandleV : public PlotLineHandle { public: - PlotLineHandleV(const QPixmap &handleIcon, QWidget *parent = 0, - bool facingRight = false); + PlotLineHandleV(const QPixmap &handleIcon, QWidget *parent = 0, bool facingRight = false); void triggerMove(); void setPosition(int); void setPositionSilenty(int); @@ -143,14 +146,11 @@ class SCOPY_GUI_EXPORT PlotLineHandleV: public PlotLineHandle bool m_facingRight; }; -class SCOPY_GUI_EXPORT FreePlotLineHandleH: public PlotLineHandleH +class SCOPY_GUI_EXPORT FreePlotLineHandleH : public PlotLineHandleH { public: - - FreePlotLineHandleH(const QPixmap &handleIcon, - const QPixmap &beyondLeftIcon, - const QPixmap &beyondRightIcon, - QWidget *parent = 0, bool facingRight = false); + FreePlotLineHandleH(const QPixmap &handleIcon, const QPixmap &beyondLeftIcon, const QPixmap &beyondRightIcon, + QWidget *parent = 0, bool facingRight = false); void moveWithinParent(int x, int y); protected: @@ -163,15 +163,11 @@ class SCOPY_GUI_EXPORT FreePlotLineHandleH: public PlotLineHandleH bool m_isBeyondLeft; }; -class SCOPY_GUI_EXPORT FreePlotLineHandleV: public PlotLineHandleV +class SCOPY_GUI_EXPORT FreePlotLineHandleV : public PlotLineHandleV { public: - - FreePlotLineHandleV(const QPixmap &handleIcon, - const QPixmap &beyondTopIcon, - const QPixmap &beyondBottomIcon, - QWidget *parent = 0, bool facingRight = false, - const QString &name = {}); + FreePlotLineHandleV(const QPixmap &handleIcon, const QPixmap &beyondTopIcon, const QPixmap &beyondBottomIcon, + QWidget *parent = 0, bool facingRight = false, const QString &name = {}); void moveWithinParent(int x, int y); void setName(const QString &name); @@ -188,15 +184,12 @@ class SCOPY_GUI_EXPORT FreePlotLineHandleV: public PlotLineHandleV QString m_name; }; -class SCOPY_GUI_EXPORT RoundedHandleV: public FreePlotLineHandleV +class SCOPY_GUI_EXPORT RoundedHandleV : public FreePlotLineHandleV { Q_OBJECT public: - RoundedHandleV(const QPixmap &handleIcon, - const QPixmap &beyondTopIcon, - const QPixmap &beyondBottomIcon, - QWidget *parent = 0, bool facingRight = false, - const QString& name = {}, + RoundedHandleV(const QPixmap &handleIcon, const QPixmap &beyondTopIcon, const QPixmap &beyondBottomIcon, + QWidget *parent = 0, bool facingRight = false, const QString &name = {}, bool selectable = false); QColor roundRectColor(); diff --git a/gui/include/gui/plot_utils.hpp b/gui/include/gui/plot_utils.hpp index 7b30ef5aa4..8e2a9566af 100644 --- a/gui/include/gui/plot_utils.hpp +++ b/gui/include/gui/plot_utils.hpp @@ -21,92 +21,93 @@ #ifndef PLOT_UTILS_HPP #define PLOT_UTILS_HPP -#include -#include -#include #include "scopy-gui_export.h" +#include +#include + +#include + namespace scopy { - class SCOPY_GUI_EXPORT PrefixFormatter : public QObject - { +class SCOPY_GUI_EXPORT PrefixFormatter : public QObject +{ Q_OBJECT - public: - PrefixFormatter(const std::vector>&, QObject *parent = nullptr); - virtual ~PrefixFormatter(); - void setTwoDecimalMode(bool); - bool getTwoDecimalMode(); - virtual QString format(double value, QString unitType, int precision) const; - void getFormatAttributes(double value, QString& prefix, double& scale) const; - - QString getFormatedMeasureUnit(double value); - double getFormatedValue(double value); - - bool getTrimZeroes() const; - void setTrimZeroes(bool trimZeroes); - - protected: - virtual QString buildString(double value, QString prefix, QString unitType, int precision) const; - int findPrefixIndex(double value) const; - - private: - std::vector> m_prefixes; - int m_defaultPrefixIndex; - bool m_twoDecimalMode; - bool m_trimZeroes; - }; - - class SCOPY_GUI_EXPORT MetricPrefixFormatter: public PrefixFormatter - { - public: - MetricPrefixFormatter(QObject *parent = nullptr); - }; - - class SCOPY_GUI_EXPORT TimePrefixFormatter: public PrefixFormatter - { - public: - TimePrefixFormatter(QObject *parent = nullptr); - }; - - /* - * CLASS NumberSeries contains a series of number that is being built - * upon contruction. The series is being build by the following rules: - * limits: [lower, upper] - * step: {step1, step2, ..., stepN} X stepPower - * E.g. powerStep = 10, steps = {1, 2, 5} -> ..., 0.1, 0.2, 0.5, 1.0, - * 2.0, 5.0, 10.0, 20.0, 50.0, ... - */ - class SCOPY_GUI_EXPORT NumberSeries - { - public: - NumberSeries(double lower = 1E-3, double upper = 1E3, - unsigned int powerStep = 10, - const std::vector& steps = {1, 2, 5}); - ~NumberSeries(); - - const std::vector& getNumbers(); - - double getNumberAfter(double value); - double getNumberBefore(double value); - - void setLower(double value); - double lower(); - - void setUpper(double value); - double upper(); - - void setPowerStep(unsigned int value); - unsigned int stepPower(); - - protected: - void buildNumberSeries(); - - private: - double m_lowerLimit; - double m_upperLimit; - int m_powerStep; - std::vector m_templateSteps; - std::vectorm_numbers; - }; -} - -#endif //PLOT_UTILS_HPP +public: + PrefixFormatter(const std::vector> &, QObject *parent = nullptr); + virtual ~PrefixFormatter(); + void setTwoDecimalMode(bool); + bool getTwoDecimalMode(); + virtual QString format(double value, QString unitType, int precision) const; + void getFormatAttributes(double value, QString &prefix, double &scale) const; + + QString getFormatedMeasureUnit(double value); + double getFormatedValue(double value); + + bool getTrimZeroes() const; + void setTrimZeroes(bool trimZeroes); + +protected: + virtual QString buildString(double value, QString prefix, QString unitType, int precision) const; + int findPrefixIndex(double value) const; + +private: + std::vector> m_prefixes; + int m_defaultPrefixIndex; + bool m_twoDecimalMode; + bool m_trimZeroes; +}; + +class SCOPY_GUI_EXPORT MetricPrefixFormatter : public PrefixFormatter +{ +public: + MetricPrefixFormatter(QObject *parent = nullptr); +}; + +class SCOPY_GUI_EXPORT TimePrefixFormatter : public PrefixFormatter +{ +public: + TimePrefixFormatter(QObject *parent = nullptr); +}; + +/* + * CLASS NumberSeries contains a series of number that is being built + * upon contruction. The series is being build by the following rules: + * limits: [lower, upper] + * step: {step1, step2, ..., stepN} X stepPower + * E.g. powerStep = 10, steps = {1, 2, 5} -> ..., 0.1, 0.2, 0.5, 1.0, + * 2.0, 5.0, 10.0, 20.0, 50.0, ... + */ +class SCOPY_GUI_EXPORT NumberSeries +{ +public: + NumberSeries(double lower = 1E-3, double upper = 1E3, unsigned int powerStep = 10, + const std::vector &steps = {1, 2, 5}); + ~NumberSeries(); + + const std::vector &getNumbers(); + + double getNumberAfter(double value); + double getNumberBefore(double value); + + void setLower(double value); + double lower(); + + void setUpper(double value); + double upper(); + + void setPowerStep(unsigned int value); + unsigned int stepPower(); + +protected: + void buildNumberSeries(); + +private: + double m_lowerLimit; + double m_upperLimit; + int m_powerStep; + std::vector m_templateSteps; + std::vector m_numbers; +}; +} // namespace scopy + +#endif // PLOT_UTILS_HPP diff --git a/gui/include/gui/plotaxis.h b/gui/include/gui/plotaxis.h index 6242e921ff..a1170c3b7a 100644 --- a/gui/include/gui/plotaxis.h +++ b/gui/include/gui/plotaxis.h @@ -1,16 +1,19 @@ #ifndef PLOTAXIS_H #define PLOTAXIS_H -#include "scopy-gui_export.h" -#include -#include "plotwidget.h" -#include #include "osc_scale_engine.h" #include "plotaxishandle.h" +#include "plotwidget.h" +#include "scopy-gui_export.h" + #include +#include + +#include namespace scopy { -class SCOPY_GUI_EXPORT PlotAxis : public QObject { +class SCOPY_GUI_EXPORT PlotAxis : public QObject +{ Q_OBJECT public: PlotAxis(int position, PlotWidget *p, QPen pen, QObject *parent = nullptr); @@ -19,7 +22,7 @@ class SCOPY_GUI_EXPORT PlotAxis : public QObject { int position(); bool isHorizontal(); bool isVertical(); - QwtPlot* plot(); + QwtPlot *plot(); void setDivs(double); void setInterval(double min, double max); @@ -65,5 +68,5 @@ public Q_SLOTS: Q_PROPERTY(double max READ max WRITE setMax NOTIFY maxChanged) Q_PROPERTY(double min READ min WRITE setMin NOTIFY minChanged) }; -} +} // namespace scopy #endif // PLOTAXIS_H diff --git a/gui/include/gui/plotaxishandle.h b/gui/include/gui/plotaxishandle.h index 66f4543b5c..66227f1023 100644 --- a/gui/include/gui/plotaxishandle.h +++ b/gui/include/gui/plotaxishandle.h @@ -1,17 +1,18 @@ #ifndef PLOTAXISHANDLE_H #define PLOTAXISHANDLE_H -#include "plotwidget.h" -#include #include "plot_line_handle.h" +#include "plotwidget.h" #include "scopy-gui_export.h" +#include + namespace scopy { class SCOPY_GUI_EXPORT PlotAxisHandle : public QObject { Q_OBJECT public: - PlotAxisHandle(QPen pen, PlotAxis* ax, PlotWidget *p, int position, QObject *parent = nullptr); + PlotAxisHandle(QPen pen, PlotAxis *ax, PlotWidget *p, int position, QObject *parent = nullptr); ~PlotAxisHandle(); RoundedHandleV *handle() const; PlotAxis *axis() const; @@ -22,8 +23,7 @@ class SCOPY_GUI_EXPORT PlotAxisHandle : public QObject QPen m_pen; HorizBar *m_chOffsetBar; RoundedHandleV *m_handle; - SymbolController* m_symbolCtrl; - + SymbolController *m_symbolCtrl; }; -} +} // namespace scopy #endif // PLOTAXISHANDLE_H diff --git a/gui/include/gui/plotchannel.h b/gui/include/gui/plotchannel.h index 3c103130e6..9a5b99571f 100644 --- a/gui/include/gui/plotchannel.h +++ b/gui/include/gui/plotchannel.h @@ -1,21 +1,24 @@ #ifndef PLOTCHANNEL_H #define PLOTCHANNEL_H -#include -#include -#include #include "scopy-gui_export.h" + #include +#include +#include +#include #include namespace scopy { class PlotAxis; class PlotWidget; class PlotAxisHandle; -class SCOPY_GUI_EXPORT PlotChannel : public QObject { +class SCOPY_GUI_EXPORT PlotChannel : public QObject +{ Q_OBJECT public: - typedef enum { + typedef enum + { PCS_LINES = 0, PCS_DOTS, PCS_STEPS, @@ -23,7 +26,8 @@ class SCOPY_GUI_EXPORT PlotChannel : public QObject { PCS_SMOOTH } PlotCurveStyle; - PlotChannel(QString name, QPen pen, PlotWidget *plot, PlotAxis* xAxis, PlotAxis *yAxis, QObject *parent = nullptr); + PlotChannel(QString name, QPen pen, PlotWidget *plot, PlotAxis *xAxis, PlotAxis *yAxis, + QObject *parent = nullptr); ~PlotChannel(); QwtPlotCurve *curve() const; @@ -54,13 +58,13 @@ public Q_SLOTS: PlotAxis *m_xAxis, *m_yAxis; PlotAxisHandle *m_handle; QwtPlotCurve *m_curve; - QList m_markers; + QList m_markers; QwtSymbol *symbol; PlotWidget *m_plotWidget; QwtPlot *m_plot; QPen m_pen; float *m_data; }; -} +} // namespace scopy #endif // PLOTCHANNEL_H diff --git a/gui/include/gui/plotcursors.h b/gui/include/gui/plotcursors.h index 029af9d1d0..d9484c6b87 100644 --- a/gui/include/gui/plotcursors.h +++ b/gui/include/gui/plotcursors.h @@ -1,25 +1,26 @@ #ifndef PLOTCURSORS_H #define PLOTCURSORS_H -#include #include "plotwidget.h" -#include #include "scopy-gui_export.h" + +#include +#include + #include #include namespace scopy { - class SCOPY_GUI_EXPORT PlotCursors : public QObject { Q_OBJECT public: - PlotCursors(PlotWidget* plot); + PlotCursors(PlotWidget *plot); ~PlotCursors(); void displayIntersection(); -public Q_SLOTS: +public Q_SLOTS: void setVisible(bool visible); void horizSetVisible(bool visible); void vertSetVisible(bool visible); @@ -35,8 +36,8 @@ public Q_SLOTS: private: PlotWidget *m_plot; - QPair m_vCursors; - QPair m_hCursors; + QPair m_vCursors; + QPair m_hCursors; QwtPlotMarker *plotMarker1; QwtPlotMarker *plotMarker2; bool m_tracking; @@ -46,7 +47,6 @@ public Q_SLOTS: void updateTracking(); double getHorizIntersectionAt(double pos); }; -} +} // namespace scopy #endif // PLOTCURSORS_H - diff --git a/gui/include/gui/plotpickerwrapper.h b/gui/include/gui/plotpickerwrapper.h index 6a929041da..034bc2f274 100644 --- a/gui/include/gui/plotpickerwrapper.h +++ b/gui/include/gui/plotpickerwrapper.h @@ -21,19 +21,21 @@ #ifndef PLOTPICKERWRAPPER_H #define PLOTPICKERWRAPPER_H -#include -#include -#include -#include -#include #include "scopy-gui_export.h" +#include +#include +#include +#include +#include + class SCOPY_GUI_EXPORT PlotPickerWrapper : public QwtPlotPicker { public: PlotPickerWrapper(QwtAxisId xAxis, QwtAxisId yAxis, QWidget *); - QPointF pointCoordinates(const QPoint& pos) const; + QPointF pointCoordinates(const QPoint &pos) const; + private: }; diff --git a/gui/include/gui/plotwidget.h b/gui/include/gui/plotwidget.h index de42ae40f4..2bc060444d 100644 --- a/gui/include/gui/plotwidget.h +++ b/gui/include/gui/plotwidget.h @@ -1,30 +1,33 @@ #ifndef PLOT_H #define PLOT_H -#include +#include "handles_area.hpp" #include "plotchannel.h" -#include -#include #include "scopy-gui_export.h" -#include -#include "handles_area.hpp" + #include +#include +#include #include + #include +#include +#include namespace scopy { class PlotAxis; class PlotAxisHandle; - -typedef struct _PlotSamplingInfo{ - _PlotSamplingInfo() { startingPoint = 0;} +typedef struct _PlotSamplingInfo +{ + _PlotSamplingInfo() { startingPoint = 0; } uint32_t bufferSize; uint32_t plotSize; double sampleRate; double startingPoint; } PlotSamplingInfo; -class SCOPY_GUI_EXPORT PlotWidget : public QWidget { +class SCOPY_GUI_EXPORT PlotWidget : public QWidget +{ Q_OBJECT public: PlotWidget(QWidget *parent = nullptr); @@ -34,7 +37,7 @@ class SCOPY_GUI_EXPORT PlotWidget : public QWidget { void removePlotChannel(PlotChannel *ch); QList &plotAxis(int position); - PlotAxis* xAxis(); + PlotAxis *xAxis(); PlotAxis *yAxis(); void addPlotAxis(PlotAxis *ax); @@ -66,9 +69,9 @@ class SCOPY_GUI_EXPORT PlotWidget : public QWidget { void addPlotInfoSlot(QWidget *w); public Q_SLOTS: void replot(); - void selectChannel(PlotChannel*); + void selectChannel(PlotChannel *); void showAxisLabels(); - void hideAxisLabels(); + void hideAxisLabels(); Q_SIGNALS: void canvasSizeChanged(); @@ -77,18 +80,16 @@ public Q_SLOTS: void mouseButtonRelease(const QMouseEvent *event); void mouseMove(const QMouseEvent *event); - private: - QwtPlot *m_plot; QwtPlotZoomer *m_zoomer; QGridLayout *m_layout; - QList m_plotChannels; - QList m_scaleItems; + QList m_plotChannels; + QList m_scaleItems; - QList m_plotAxis[QwtAxis::AxisPositions]; - QList m_plotAxisHandles[QwtAxis::AxisPositions]; + QList m_plotAxis[QwtAxis::AxisPositions]; + QList m_plotAxisHandles[QwtAxis::AxisPositions]; PlotAxis *m_xAxis; PlotAxis *m_yAxis; @@ -103,7 +104,7 @@ public Q_SLOTS: bool m_showYAxisLabels; SymbolController *m_symbolCtrl; - PlotChannel* m_selectedChannel; + PlotChannel *m_selectedChannel; /* Adjacent areas */ HorizHandlesArea *m_bottomHandlesArea; @@ -121,7 +122,6 @@ public Q_SLOTS: void hideDefaultAxis(); }; - -} +} // namespace scopy #endif // PLOT_H diff --git a/gui/include/gui/printableplot.h b/gui/include/gui/printableplot.h index 09b237a3c8..4cd3959748 100644 --- a/gui/include/gui/printableplot.h +++ b/gui/include/gui/printableplot.h @@ -22,14 +22,16 @@ #define PRINTABLEPLOT_H /*Qwt includes*/ +#include #include #include -#include /*Qt includes*/ +#include "scopy-gui_export.h" + #include + #include -#include "scopy-gui_export.h" namespace scopy { class SCOPY_GUI_EXPORT PrintablePlot : public BasicPlot @@ -42,13 +44,13 @@ class SCOPY_GUI_EXPORT PrintablePlot : public BasicPlot void setUseNativeDialog(bool nativeDialog); public Q_SLOTS: - void printPlot(const QString& toolName = ""); + void printPlot(const QString &toolName = ""); private: QwtPlotRenderer d_plotRenderer; QwtLegend *legendDisplay; bool d_useNativeDialog; }; -} +} // namespace scopy #endif // PRINTABLEPLOT_H diff --git a/gui/include/gui/qtgui_types.h b/gui/include/gui/qtgui_types.h index 677829b8fe..54f16f7b82 100644 --- a/gui/include/gui/qtgui_types.h +++ b/gui/include/gui/qtgui_types.h @@ -20,7 +20,6 @@ * Boston, MA 02110-1301, USA. */ - // copy of gnuradio/qtgui/qtgui_types.h file // used in waterfall plot @@ -28,22 +27,24 @@ #define QTGUI_TYPES_H #include + #include #include namespace gr { namespace qtgui { -enum data_type_t { - INT = 0, - FLOAT, - DOUBLE, - COMPLEX, - STRING, - INT_VEC, - FLOAT_VEC, - DOUBLE_VEC, - COMPLEX_VEC, +enum data_type_t +{ + INT = 0, + FLOAT, + DOUBLE, + COMPLEX, + STRING, + INT_VEC, + FLOAT_VEC, + DOUBLE_VEC, + COMPLEX_VEC, }; } /* namespace qtgui */ @@ -52,58 +53,54 @@ enum data_type_t { class FreqOffsetAndPrecisionClass { public: - FreqOffsetAndPrecisionClass(const int freqPrecision) - { - _frequencyPrecision = freqPrecision; - _centerFrequency = 0; - } + FreqOffsetAndPrecisionClass(const int freqPrecision) + { + _frequencyPrecision = freqPrecision; + _centerFrequency = 0; + } - virtual ~FreqOffsetAndPrecisionClass() {} + virtual ~FreqOffsetAndPrecisionClass() {} - virtual unsigned int getFrequencyPrecision() const { return _frequencyPrecision; } + virtual unsigned int getFrequencyPrecision() const { return _frequencyPrecision; } - virtual void setFrequencyPrecision(const unsigned int newPrecision) - { - _frequencyPrecision = newPrecision; - } + virtual void setFrequencyPrecision(const unsigned int newPrecision) { _frequencyPrecision = newPrecision; } - virtual double getCenterFrequency() const { return _centerFrequency; } + virtual double getCenterFrequency() const { return _centerFrequency; } - virtual void setCenterFrequency(const double newFreq) { _centerFrequency = newFreq; } + virtual void setCenterFrequency(const double newFreq) { _centerFrequency = newFreq; } protected: private: - unsigned int _frequencyPrecision; - double _centerFrequency; + unsigned int _frequencyPrecision; + double _centerFrequency; }; class TimeScaleData { public: - TimeScaleData() - { - _zeroTime = 0; - _secondsPerLine = 1.0; - } - - virtual ~TimeScaleData() {} + TimeScaleData() + { + _zeroTime = 0; + _secondsPerLine = 1.0; + } - virtual gr::high_res_timer_type getZeroTime() const { return _zeroTime; } + virtual ~TimeScaleData() {} - virtual void setZeroTime(const gr::high_res_timer_type newTime) - { - _zeroTime = newTime - gr::high_res_timer_epoch(); - } + virtual gr::high_res_timer_type getZeroTime() const { return _zeroTime; } - virtual void setSecondsPerLine(const double newTime) { _secondsPerLine = newTime; } + virtual void setZeroTime(const gr::high_res_timer_type newTime) + { + _zeroTime = newTime - gr::high_res_timer_epoch(); + } - virtual double getSecondsPerLine() const { return _secondsPerLine; } + virtual void setSecondsPerLine(const double newTime) { _secondsPerLine = newTime; } + virtual double getSecondsPerLine() const { return _secondsPerLine; } protected: private: - gr::high_res_timer_type _zeroTime; - double _secondsPerLine; + gr::high_res_timer_type _zeroTime; + double _secondsPerLine; }; /*********************************************************************** @@ -112,17 +109,14 @@ class TimeScaleData class FreqDisplayScaleDraw : public QwtScaleDraw, FreqOffsetAndPrecisionClass { public: - FreqDisplayScaleDraw(const unsigned int precision) - : QwtScaleDraw(), FreqOffsetAndPrecisionClass(precision) - { - } + FreqDisplayScaleDraw(const unsigned int precision) + : QwtScaleDraw() + , FreqOffsetAndPrecisionClass(precision) + {} - virtual QwtText label(double value) const - { - return QString("%1").arg(value, 0, 'f', getFrequencyPrecision()); - } + virtual QwtText label(double value) const { return QString("%1").arg(value, 0, 'f', getFrequencyPrecision()); } - virtual void initiateUpdate(void) { invalidateCache(); } + virtual void initiateUpdate(void) { invalidateCache(); } protected: private: @@ -131,89 +125,99 @@ class FreqDisplayScaleDraw : public QwtScaleDraw, FreqOffsetAndPrecisionClass namespace gr { namespace qtgui { -enum graph_t { - NUM_GRAPH_NONE = 0, - NUM_GRAPH_HORIZ, - NUM_GRAPH_VERT, +enum graph_t +{ + NUM_GRAPH_NONE = 0, + NUM_GRAPH_HORIZ, + NUM_GRAPH_VERT, }; } /* namespace qtgui */ } /* namespace gr */ - -enum { - INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR = 0, - INTENSITY_COLOR_MAP_TYPE_WHITE_HOT = 1, - INTENSITY_COLOR_MAP_TYPE_BLACK_HOT = 2, - INTENSITY_COLOR_MAP_TYPE_INCANDESCENT = 3, - INTENSITY_COLOR_MAP_TYPE_USER_DEFINED = 4, - INTENSITY_COLOR_MAP_TYPE_SUNSET = 5, - INTENSITY_COLOR_MAP_TYPE_COOL = 6, +enum +{ + INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR = 0, + INTENSITY_COLOR_MAP_TYPE_WHITE_HOT = 1, + INTENSITY_COLOR_MAP_TYPE_BLACK_HOT = 2, + INTENSITY_COLOR_MAP_TYPE_INCANDESCENT = 3, + INTENSITY_COLOR_MAP_TYPE_USER_DEFINED = 4, + INTENSITY_COLOR_MAP_TYPE_SUNSET = 5, + INTENSITY_COLOR_MAP_TYPE_COOL = 6, }; class ColorMap_MultiColor : public QwtLinearColorMap { public: - ColorMap_MultiColor() : QwtLinearColorMap(Qt::darkCyan, Qt::white) - { - addColorStop(0.25, Qt::cyan); - addColorStop(0.5, Qt::yellow); - addColorStop(0.75, Qt::red); - } + ColorMap_MultiColor() + : QwtLinearColorMap(Qt::darkCyan, Qt::white) + { + addColorStop(0.25, Qt::cyan); + addColorStop(0.5, Qt::yellow); + addColorStop(0.75, Qt::red); + } }; class ColorMap_WhiteHot : public QwtLinearColorMap { public: - ColorMap_WhiteHot() : QwtLinearColorMap(Qt::black, Qt::white) {} + ColorMap_WhiteHot() + : QwtLinearColorMap(Qt::black, Qt::white) + {} }; class ColorMap_BlackHot : public QwtLinearColorMap { public: - ColorMap_BlackHot() : QwtLinearColorMap(Qt::white, Qt::black) {} + ColorMap_BlackHot() + : QwtLinearColorMap(Qt::white, Qt::black) + {} }; class ColorMap_Incandescent : public QwtLinearColorMap { public: - ColorMap_Incandescent() : QwtLinearColorMap(Qt::black, Qt::white) - { - addColorStop(0.5, Qt::darkRed); - } + ColorMap_Incandescent() + : QwtLinearColorMap(Qt::black, Qt::white) + { + addColorStop(0.5, Qt::darkRed); + } }; class ColorMap_Sunset : public QwtLinearColorMap { public: - ColorMap_Sunset() : QwtLinearColorMap(QColor(0, 0, 0, 0), QColor(255, 255, 193, 255)) - { - addColorStop(0.167, QColor(86, 0, 153, 45)); - addColorStop(0.333, QColor(147, 51, 119, 91)); - addColorStop(0.500, QColor(226, 51, 71, 140)); - addColorStop(0.667, QColor(255, 109, 0, 183)); - addColorStop(0.833, QColor(255, 183, 0, 221)); - } + ColorMap_Sunset() + : QwtLinearColorMap(QColor(0, 0, 0, 0), QColor(255, 255, 193, 255)) + { + addColorStop(0.167, QColor(86, 0, 153, 45)); + addColorStop(0.333, QColor(147, 51, 119, 91)); + addColorStop(0.500, QColor(226, 51, 71, 140)); + addColorStop(0.667, QColor(255, 109, 0, 183)); + addColorStop(0.833, QColor(255, 183, 0, 221)); + } }; class ColorMap_Cool : public QwtLinearColorMap { public: - ColorMap_Cool() : QwtLinearColorMap(QColor(0, 0, 0, 0), QColor(255, 255, 255, 255)) - { - addColorStop(0.167, QColor(0, 0, 127, 25)); - addColorStop(0.333, QColor(0, 63, 153, 86)); - addColorStop(0.500, QColor(76, 114, 178, 127)); - addColorStop(0.667, QColor(153, 165, 204, 178)); - addColorStop(0.833, QColor(204, 216, 229, 211)); - } + ColorMap_Cool() + : QwtLinearColorMap(QColor(0, 0, 0, 0), QColor(255, 255, 255, 255)) + { + addColorStop(0.167, QColor(0, 0, 127, 25)); + addColorStop(0.333, QColor(0, 63, 153, 86)); + addColorStop(0.500, QColor(76, 114, 178, 127)); + addColorStop(0.667, QColor(153, 165, 204, 178)); + addColorStop(0.833, QColor(204, 216, 229, 211)); + } }; class ColorMap_UserDefined : public QwtLinearColorMap { public: - ColorMap_UserDefined(QColor low, QColor high) : QwtLinearColorMap(low, high) {} + ColorMap_UserDefined(QColor low, QColor high) + : QwtLinearColorMap(low, high) + {} }; #endif // QTGUI_TYPES_H - diff --git a/gui/include/gui/qwt_utils.h b/gui/include/gui/qwt_utils.h index 501a7bc9be..e8fddc7698 100644 --- a/gui/include/gui/qwt_utils.h +++ b/gui/include/gui/qwt_utils.h @@ -1,42 +1,41 @@ #ifndef QWT_UTILS_H #define QWT_UTILS_H -#include -#include -#include -#include -#include -#include #include "scopy-gui_export.h" +#include +#include +#include +#include +#include +#include -class SCOPY_GUI_EXPORT QwtDblClickPlotPicker: public QwtPlotPicker +class SCOPY_GUI_EXPORT QwtDblClickPlotPicker : public QwtPlotPicker { public: #if QWT_VERSION < 0x060100 - QwtDblClickPlotPicker(QwtPlotCanvas *); -#else /* QWT_VERSION < 0x060100 */ - QwtDblClickPlotPicker(QWidget *); + QwtDblClickPlotPicker(QwtPlotCanvas *); +#else /* QWT_VERSION < 0x060100 */ + QwtDblClickPlotPicker(QWidget *); #endif /* QWT_VERSION < 0x060100 */ - ~QwtDblClickPlotPicker(); + ~QwtDblClickPlotPicker(); - virtual QwtPickerMachine * stateMachine(int) const; + virtual QwtPickerMachine *stateMachine(int) const; }; -class SCOPY_GUI_EXPORT QwtPickerDblClickPointMachine: public QwtPickerMachine +class SCOPY_GUI_EXPORT QwtPickerDblClickPointMachine : public QwtPickerMachine { public: - QwtPickerDblClickPointMachine(); - ~QwtPickerDblClickPointMachine(); + QwtPickerDblClickPointMachine(); + ~QwtPickerDblClickPointMachine(); #if QWT_VERSION < 0x060000 - virtual CommandList + virtual CommandList #else - virtual QList + virtual QList #endif - transition( const QwtEventPattern &eventPattern, - const QEvent *e); + transition(const QwtEventPattern &eventPattern, const QEvent *e); }; #endif // QWT_UTILS_H diff --git a/gui/include/gui/runsinglewidget.h b/gui/include/gui/runsinglewidget.h index 858a2ff35d..448374d579 100644 --- a/gui/include/gui/runsinglewidget.h +++ b/gui/include/gui/runsinglewidget.h @@ -21,9 +21,10 @@ #ifndef RUNSINGLEWIDGET_H #define RUNSINGLEWIDGET_H +#include "scopy-gui_export.h" + #include #include -#include "scopy-gui_export.h" namespace Ui { class RunSingleWidget; @@ -47,8 +48,8 @@ class SCOPY_GUI_EXPORT RunSingleWidget : public QWidget bool singleButtonChecked() const; bool runButtonChecked() const; - QPushButton* getRunButton(); - QPushButton* getSingleButton(); + QPushButton *getRunButton(); + QPushButton *getSingleButton(); public Q_SLOTS: void toggle(bool); @@ -65,6 +66,6 @@ private Q_SLOTS: bool d_singleButtonEnabled; bool d_runButtonEnabled; }; -} +} // namespace scopy #endif // RUNSINGLEWIDGET_H diff --git a/gui/include/gui/semiexclusivebuttongroup.h b/gui/include/gui/semiexclusivebuttongroup.h index 645c00cb9c..f41d102617 100644 --- a/gui/include/gui/semiexclusivebuttongroup.h +++ b/gui/include/gui/semiexclusivebuttongroup.h @@ -1,9 +1,10 @@ #ifndef SEMIEXCLUSIVEBUTTONGROUP_H #define SEMIEXCLUSIVEBUTTONGROUP_H +#include "scopy-gui_export.h" + #include #include -#include "scopy-gui_export.h" namespace scopy { class SCOPY_GUI_EXPORT SemiExclusiveButtonGroup : public QButtonGroup @@ -29,5 +30,5 @@ protected Q_SLOTS: bool m_exclusive; QAbstractButton *m_lastBtn; }; -} +} // namespace scopy #endif // SEMIEXCLUSIVEBUTTONGROUP_H diff --git a/gui/include/gui/settings_pair_widget.hpp b/gui/include/gui/settings_pair_widget.hpp index 9aa593da8c..3dfa333dde 100644 --- a/gui/include/gui/settings_pair_widget.hpp +++ b/gui/include/gui/settings_pair_widget.hpp @@ -1,11 +1,11 @@ #ifndef SETTINGSCUSTOMWIDGET_H #define SETTINGSCUSTOMWIDGET_H +#include "customPushButton.h" + #include #include -#include "customPushButton.h" - using namespace scopy; namespace Ui { @@ -19,14 +19,14 @@ class SettingsPairWidget : public QWidget Q_OBJECT public: - explicit SettingsPairWidget(QWidget* parent = nullptr); + explicit SettingsPairWidget(QWidget *parent = nullptr); ~SettingsPairWidget(); - CustomPushButton* getGeneralSettingsBtn(); - QPushButton* getSettingsBtn(); + CustomPushButton *getGeneralSettingsBtn(); + QPushButton *getSettingsBtn(); private: - Ui::SettingsPairWidget* m_ui; + Ui::SettingsPairWidget *m_ui; }; } // namespace gui } // namespace scopy diff --git a/gui/include/gui/sismograph.hpp b/gui/include/gui/sismograph.hpp index 2259572032..34daa8400a 100644 --- a/gui/include/gui/sismograph.hpp +++ b/gui/include/gui/sismograph.hpp @@ -21,95 +21,86 @@ #ifndef SISMOGRAPH_HPP #define SISMOGRAPH_HPP +#include "autoScaler.hpp" +#include "customqwtscaledraw.hpp" +#include "scopy-gui_export.h" + +#include #include #include -#include - #include #include -#include "autoScaler.hpp" -#include "scopy-gui_export.h" -#include "customqwtscaledraw.hpp" - namespace scopy { - class SCOPY_GUI_EXPORT Sismograph : public QwtPlot +class SCOPY_GUI_EXPORT Sismograph : public QwtPlot +{ + Q_OBJECT + + Q_PROPERTY(int numSamples READ getNumSamples WRITE setNumSamples) + + Q_PROPERTY(double sampleRate READ getSampleRate WRITE setSampleRate) + + Q_PROPERTY(PlotDirection plotDirection READ getPlotDirection WRITE setPlotDirection) + +public: + explicit Sismograph(QWidget *parent = nullptr); + ~Sismograph(); + + enum PlotDirection : bool { - Q_OBJECT - - Q_PROPERTY(int numSamples - READ getNumSamples - WRITE setNumSamples - ) - - Q_PROPERTY(double sampleRate - READ getSampleRate - WRITE setSampleRate - ) - - Q_PROPERTY(PlotDirection plotDirection - READ getPlotDirection - WRITE setPlotDirection - ) - - public: - explicit Sismograph(QWidget *parent = nullptr); - ~Sismograph(); - - enum PlotDirection : bool { - LEFT_TO_RIGHT = false, - RIGHT_TO_LEFT = true - }; - - int getNumSamples() const; - void setNumSamples(int num); - - Sismograph::PlotDirection getPlotDirection() const; - void setPlotDirection(PlotDirection plotDirection); - - double getSampleRate() const; - void setSampleRate(double rate); - - void setUnitOfMeasure(QString unitOfMeasureName,QString unitOfMeasureSymbol); - void setPlotAxisXTitle(const QString& title); - - bool getAutoscale() const; - void setAutoscale(bool newAutoscale); - void addScale(double x1, double x2, int maxMajorSteps, int maxMinorSteps, double stepSize = 0.0 ); - - public Q_SLOTS: - void plot(double sample); - void reset(); - void setColor(const QColor& color); - void updateScale(const QwtScaleDiv); - void updateYScale(double max, double min); - void setLineWidth(qreal width); - void setLineStyle(Qt::PenStyle lineStyle); - void setHistoryDuration(double time); - - private: - QwtPlotCurve curve; - unsigned int numSamples; - double sampleRate; - double interval; - AutoScaler *scaler; - double m_currentScale; - QString m_unitOfMeasureName; - QString m_unitOfMeasureSymbol; - CustomQwtScaleDraw* scaleLabel; - double m_currentMaxValue; - - QVector ydata; - QVector xdata; - - void updateScale(); - double findMaxInFifo(); - bool autoscale; - enum PlotDirection plotDirection; - - Q_SIGNALS: - void dataChanged(std::vector data); + LEFT_TO_RIGHT = false, + RIGHT_TO_LEFT = true }; -} + + int getNumSamples() const; + void setNumSamples(int num); + + Sismograph::PlotDirection getPlotDirection() const; + void setPlotDirection(PlotDirection plotDirection); + + double getSampleRate() const; + void setSampleRate(double rate); + + void setUnitOfMeasure(QString unitOfMeasureName, QString unitOfMeasureSymbol); + void setPlotAxisXTitle(const QString &title); + + bool getAutoscale() const; + void setAutoscale(bool newAutoscale); + void addScale(double x1, double x2, int maxMajorSteps, int maxMinorSteps, double stepSize = 0.0); + +public Q_SLOTS: + void plot(double sample); + void reset(); + void setColor(const QColor &color); + void updateScale(const QwtScaleDiv); + void updateYScale(double max, double min); + void setLineWidth(qreal width); + void setLineStyle(Qt::PenStyle lineStyle); + void setHistoryDuration(double time); + +private: + QwtPlotCurve curve; + unsigned int numSamples; + double sampleRate; + double interval; + AutoScaler *scaler; + double m_currentScale; + QString m_unitOfMeasureName; + QString m_unitOfMeasureSymbol; + CustomQwtScaleDraw *scaleLabel; + double m_currentMaxValue; + + QVector ydata; + QVector xdata; + + void updateScale(); + double findMaxInFifo(); + bool autoscale; + enum PlotDirection plotDirection; + +Q_SIGNALS: + void dataChanged(std::vector data); +}; +} // namespace scopy #endif /* SISMOGRAPH_HPP */ diff --git a/gui/include/gui/smallOnOffSwitch.h b/gui/include/gui/smallOnOffSwitch.h index d4cb2b223c..cbccfad4a7 100644 --- a/gui/include/gui/smallOnOffSwitch.h +++ b/gui/include/gui/smallOnOffSwitch.h @@ -21,55 +21,55 @@ #ifndef SMALL_ON_OFF_SWITCH_HPP #define SMALL_ON_OFF_SWITCH_HPP -#include #include "customanimation.h" +#include "scopy-gui_export.h" + +#include +#include #include #include -#include -#include "scopy-gui_export.h" class QShowEvent; namespace scopy { - class SCOPY_GUI_EXPORT SmallOnOffSwitch : public QPushButton - { - Q_OBJECT +class SCOPY_GUI_EXPORT SmallOnOffSwitch : public QPushButton +{ + Q_OBJECT - Q_PROPERTY(int duration_ms MEMBER duration_ms - WRITE setDuration); + Q_PROPERTY(int duration_ms MEMBER duration_ms WRITE setDuration); - Q_PROPERTY(QColor color_start MEMBER color_start); - Q_PROPERTY(QColor color_end MEMBER color_end); - Q_PROPERTY(QColor color MEMBER color WRITE setHandleColor); + Q_PROPERTY(QColor color_start MEMBER color_start); + Q_PROPERTY(QColor color_end MEMBER color_end); + Q_PROPERTY(QColor color MEMBER color WRITE setHandleColor); - public: - explicit SmallOnOffSwitch(QWidget *parent = nullptr); - ~SmallOnOffSwitch(); +public: + explicit SmallOnOffSwitch(QWidget *parent = nullptr); + ~SmallOnOffSwitch(); - private: - QColor color_start, color_end, color; - QLabel on, off; - QWidget handle; - CustomAnimation anim; - CustomAnimation color_anim; - QString stylesheet; - int duration_ms; - bool show_icon; - bool bothValid; +private: + QColor color_start, color_end, color; + QLabel on, off; + QWidget handle; + CustomAnimation anim; + CustomAnimation color_anim; + QString stylesheet; + int duration_ms; + bool show_icon; + bool bothValid; - void setDuration(int ms); - void setHandleColor(const QColor& color); - void updateOnOffLabels(); + void setDuration(int ms); + void setHandleColor(const QColor &color); + void updateOnOffLabels(); - bool event(QEvent *e); - void showEvent(QShowEvent *event); - void paintEvent(QPaintEvent *); + bool event(QEvent *e); + void showEvent(QShowEvent *event); + void paintEvent(QPaintEvent *); - private Q_SLOTS: - void toggleAnim(bool enabled); - Q_SIGNALS: - void animationDone(); - }; -} +private Q_SLOTS: + void toggleAnim(bool enabled); +Q_SIGNALS: + void animationDone(); +}; +} // namespace scopy #endif /* SMALL_ON_OFF_SWITCH_HPP */ diff --git a/gui/include/gui/smoothcurvefitter.h b/gui/include/gui/smoothcurvefitter.h index 3a61353917..37469d6f0a 100644 --- a/gui/include/gui/smoothcurvefitter.h +++ b/gui/include/gui/smoothcurvefitter.h @@ -21,11 +21,12 @@ #ifndef SMOOTHCURVEFITTER_H #define SMOOTHCURVEFITTER_H -#include +#include "scopy-gui_export.h" #include #include -#include "scopy-gui_export.h" + +#include namespace scopy { class SCOPY_GUI_EXPORT SmoothCurveFitter : public QwtCurveFitter @@ -33,12 +34,12 @@ class SCOPY_GUI_EXPORT SmoothCurveFitter : public QwtCurveFitter public: SmoothCurveFitter(); - virtual QPolygonF fitCurve( const QPolygonF &points ) const; - virtual QPainterPath fitCurvePath( const QPolygonF &points ) const; + virtual QPolygonF fitCurve(const QPolygonF &points) const; + virtual QPainterPath fitCurvePath(const QPolygonF &points) const; private: - std::unique_ptr d_spline; + std::unique_ptr d_spline; }; -} +} // namespace scopy #endif // SMOOTHCURVEFITTER_H diff --git a/gui/include/gui/spectrumUpdateEvents.h b/gui/include/gui/spectrumUpdateEvents.h index 28d1c0fb3f..28d8cfdf59 100644 --- a/gui/include/gui/spectrumUpdateEvents.h +++ b/gui/include/gui/spectrumUpdateEvents.h @@ -21,330 +21,292 @@ #ifndef M2K_SPECTRUM_UPDATE_EVENTS_H #define M2K_SPECTRUM_UPDATE_EVENTS_H -#include +#include "scopy-gui_export.h" + +#include +#include + #include #include + #include +#include #include -#include -#include #include -#include "scopy-gui_export.h" static const int SpectrumUpdateEventType = 10005; static const int SpectrumWindowCaptionEventType = 10008; static const int SpectrumWindowResetEventType = 10009; static const int SpectrumFrequencyRangeEventType = 10010; -class SCOPY_GUI_EXPORT SpectrumUpdateEvent:public QEvent{ +class SCOPY_GUI_EXPORT SpectrumUpdateEvent : public QEvent +{ public: - SpectrumUpdateEvent(const float* fftPoints, - const uint64_t numFFTDataPoints, - const double* realTimeDomainPoints, - const double* imagTimeDomainPoints, - const uint64_t numTimeDomainDataPoints, - const gr::high_res_timer_type dataTimestamp, - const bool repeatDataFlag, - const bool lastOfMultipleUpdateFlag, - const gr::high_res_timer_type generatedTimestamp, - const int droppedFFTFrames); - - ~SpectrumUpdateEvent(); - - const float* getFFTPoints() const; - const double* getRealTimeDomainPoints() const; - const double* getImagTimeDomainPoints() const; - uint64_t getNumFFTDataPoints() const; - uint64_t getNumTimeDomainDataPoints() const; - gr::high_res_timer_type getDataTimestamp() const; - bool getRepeatDataFlag() const; - bool getLastOfMultipleUpdateFlag() const; - gr::high_res_timer_type getEventGeneratedTimestamp() const; - int getDroppedFFTFrames() const; + SpectrumUpdateEvent(const float *fftPoints, const uint64_t numFFTDataPoints, const double *realTimeDomainPoints, + const double *imagTimeDomainPoints, const uint64_t numTimeDomainDataPoints, + const gr::high_res_timer_type dataTimestamp, const bool repeatDataFlag, + const bool lastOfMultipleUpdateFlag, const gr::high_res_timer_type generatedTimestamp, + const int droppedFFTFrames); + + ~SpectrumUpdateEvent(); + + const float *getFFTPoints() const; + const double *getRealTimeDomainPoints() const; + const double *getImagTimeDomainPoints() const; + uint64_t getNumFFTDataPoints() const; + uint64_t getNumTimeDomainDataPoints() const; + gr::high_res_timer_type getDataTimestamp() const; + bool getRepeatDataFlag() const; + bool getLastOfMultipleUpdateFlag() const; + gr::high_res_timer_type getEventGeneratedTimestamp() const; + int getDroppedFFTFrames() const; protected: - private: - float* _fftPoints; - double* _realDataTimeDomainPoints; - double* _imagDataTimeDomainPoints; - uint64_t _numFFTDataPoints; - uint64_t _numTimeDomainDataPoints; - gr::high_res_timer_type _dataTimestamp; - bool _repeatDataFlag; - bool _lastOfMultipleUpdateFlag; - gr::high_res_timer_type _eventGeneratedTimestamp; - int _droppedFFTFrames; + float *_fftPoints; + double *_realDataTimeDomainPoints; + double *_imagDataTimeDomainPoints; + uint64_t _numFFTDataPoints; + uint64_t _numTimeDomainDataPoints; + gr::high_res_timer_type _dataTimestamp; + bool _repeatDataFlag; + bool _lastOfMultipleUpdateFlag; + gr::high_res_timer_type _eventGeneratedTimestamp; + int _droppedFFTFrames; }; -class SCOPY_GUI_EXPORT SpectrumWindowCaptionEvent:public QEvent{ +class SCOPY_GUI_EXPORT SpectrumWindowCaptionEvent : public QEvent +{ public: - SpectrumWindowCaptionEvent(const QString&); - ~SpectrumWindowCaptionEvent(); - QString getLabel(); + SpectrumWindowCaptionEvent(const QString &); + ~SpectrumWindowCaptionEvent(); + QString getLabel(); protected: - private: - QString _labelString; + QString _labelString; }; -class SCOPY_GUI_EXPORT SpectrumWindowResetEvent:public QEvent{ +class SCOPY_GUI_EXPORT SpectrumWindowResetEvent : public QEvent +{ public: - SpectrumWindowResetEvent(); - ~SpectrumWindowResetEvent(); + SpectrumWindowResetEvent(); + ~SpectrumWindowResetEvent(); protected: - private: - }; -class SCOPY_GUI_EXPORT SpectrumFrequencyRangeEvent:public QEvent{ +class SCOPY_GUI_EXPORT SpectrumFrequencyRangeEvent : public QEvent +{ public: - SpectrumFrequencyRangeEvent(const double, const double, const double); - ~SpectrumFrequencyRangeEvent(); - double GetCenterFrequency()const; - double GetStartFrequency()const; - double GetStopFrequency()const; + SpectrumFrequencyRangeEvent(const double, const double, const double); + ~SpectrumFrequencyRangeEvent(); + double GetCenterFrequency() const; + double GetStartFrequency() const; + double GetStopFrequency() const; protected: - private: - double _centerFrequency; - double _startFrequency; - double _stopFrequency; + double _centerFrequency; + double _startFrequency; + double _stopFrequency; }; - -class SCOPY_GUI_EXPORT TimeUpdateEvent: public QEvent +class SCOPY_GUI_EXPORT TimeUpdateEvent : public QEvent { public: - TimeUpdateEvent(const std::vector &timeDomainPoints, - const uint64_t numTimeDomainDataPoints, - const std::vector< std::vector > &tags); + TimeUpdateEvent(const std::vector &timeDomainPoints, const uint64_t numTimeDomainDataPoints, + const std::vector> &tags); - ~TimeUpdateEvent(); + ~TimeUpdateEvent(); - int which() const; - const std::vector getTimeDomainPoints() const; - uint64_t getNumTimeDomainDataPoints() const; - bool getRepeatDataFlag() const; + int which() const; + const std::vector getTimeDomainPoints() const; + uint64_t getNumTimeDomainDataPoints() const; + bool getRepeatDataFlag() const; - const std::vector< std::vector > getTags() const; + const std::vector> getTags() const; - static QEvent::Type Type() - { return QEvent::Type(SpectrumUpdateEventType); } + static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); } protected: - private: - size_t _nplots; - std::vector _dataTimeDomainPoints; - uint64_t _numTimeDomainDataPoints; - std::vector< std::vector > _tags; + size_t _nplots; + std::vector _dataTimeDomainPoints; + uint64_t _numTimeDomainDataPoints; + std::vector> _tags; }; - /********************************************************************/ - -class SCOPY_GUI_EXPORT IdentifiableTimeUpdateEvent: public TimeUpdateEvent +class SCOPY_GUI_EXPORT IdentifiableTimeUpdateEvent : public TimeUpdateEvent { public: - IdentifiableTimeUpdateEvent(const std::vector &timeDomainPoints, - const uint64_t numTimeDomainDataPoints, - const std::vector< std::vector > &tags, - const std::string &senderName); + IdentifiableTimeUpdateEvent(const std::vector &timeDomainPoints, + const uint64_t numTimeDomainDataPoints, + const std::vector> &tags, const std::string &senderName); - ~IdentifiableTimeUpdateEvent(); + ~IdentifiableTimeUpdateEvent(); - std::string senderName(); + std::string senderName(); protected: - private: - std::string _senderName; + std::string _senderName; }; - /********************************************************************/ - -class SCOPY_GUI_EXPORT FreqUpdateEvent: public QEvent +class SCOPY_GUI_EXPORT FreqUpdateEvent : public QEvent { public: - FreqUpdateEvent(const std::vector &dataPoints, - const uint64_t numDataPoints); + FreqUpdateEvent(const std::vector &dataPoints, const uint64_t numDataPoints); - ~FreqUpdateEvent(); + ~FreqUpdateEvent(); - int which() const; - const std::vector getPoints() const; - uint64_t getNumDataPoints() const; - bool getRepeatDataFlag() const; + int which() const; + const std::vector getPoints() const; + uint64_t getNumDataPoints() const; + bool getRepeatDataFlag() const; - static QEvent::Type Type() - { return QEvent::Type(SpectrumUpdateEventType); } + static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); } protected: - private: - size_t _nplots; - std::vector _dataPoints; - uint64_t _numDataPoints; + size_t _nplots; + std::vector _dataPoints; + uint64_t _numDataPoints; }; - -class SCOPY_GUI_EXPORT SetFreqEvent:public QEvent +class SCOPY_GUI_EXPORT SetFreqEvent : public QEvent { public: - SetFreqEvent(const double, const double); - ~SetFreqEvent(); - double getCenterFrequency() const; - double getBandwidth() const; + SetFreqEvent(const double, const double); + ~SetFreqEvent(); + double getCenterFrequency() const; + double getBandwidth() const; private: - double _centerFrequency; - double _bandwidth; + double _centerFrequency; + double _bandwidth; }; - /********************************************************************/ - -class SCOPY_GUI_EXPORT ConstUpdateEvent: public QEvent +class SCOPY_GUI_EXPORT ConstUpdateEvent : public QEvent { public: - ConstUpdateEvent(const std::vector &realDataPoints, - const std::vector &imagDataPoints, - const uint64_t numDataPoints); + ConstUpdateEvent(const std::vector &realDataPoints, const std::vector &imagDataPoints, + const uint64_t numDataPoints); - ~ConstUpdateEvent(); + ~ConstUpdateEvent(); - int which() const; - const std::vector getRealPoints() const; - const std::vector getImagPoints() const; - uint64_t getNumDataPoints() const; - bool getRepeatDataFlag() const; + int which() const; + const std::vector getRealPoints() const; + const std::vector getImagPoints() const; + uint64_t getNumDataPoints() const; + bool getRepeatDataFlag() const; - static QEvent::Type Type() - { return QEvent::Type(SpectrumUpdateEventType); } + static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); } protected: - private: - size_t _nplots; - std::vector _realDataPoints; - std::vector _imagDataPoints; - uint64_t _numDataPoints; + size_t _nplots; + std::vector _realDataPoints; + std::vector _imagDataPoints; + uint64_t _numDataPoints; }; -class SCOPY_GUI_EXPORT WaterfallUpdateEvent: public QEvent +class SCOPY_GUI_EXPORT WaterfallUpdateEvent : public QEvent { public: - WaterfallUpdateEvent(const std::vector &dataPoints, - const uint64_t numDataPoints, - const gr::high_res_timer_type dataTimestamp); + WaterfallUpdateEvent(const std::vector &dataPoints, const uint64_t numDataPoints, + const gr::high_res_timer_type dataTimestamp); - ~WaterfallUpdateEvent() override; + ~WaterfallUpdateEvent() override; - int which() const; - const std::vector getPoints() const; - uint64_t getNumDataPoints() const; - bool getRepeatDataFlag() const; + int which() const; + const std::vector getPoints() const; + uint64_t getNumDataPoints() const; + bool getRepeatDataFlag() const; - gr::high_res_timer_type getDataTimestamp() const; + gr::high_res_timer_type getDataTimestamp() const; - static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); } + static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); } protected: private: - size_t _nplots; - std::vector _dataPoints; - uint64_t _numDataPoints; + size_t _nplots; + std::vector _dataPoints; + uint64_t _numDataPoints; - gr::high_res_timer_type _dataTimestamp; + gr::high_res_timer_type _dataTimestamp; }; /********************************************************************/ - -class SCOPY_GUI_EXPORT TimeRasterUpdateEvent: public QEvent +class SCOPY_GUI_EXPORT TimeRasterUpdateEvent : public QEvent { public: - TimeRasterUpdateEvent(const std::vector &dataPoints, - const uint64_t numDataPoints); - ~TimeRasterUpdateEvent(); + TimeRasterUpdateEvent(const std::vector &dataPoints, const uint64_t numDataPoints); + ~TimeRasterUpdateEvent(); - int which() const; - const std::vector getPoints() const; - uint64_t getNumDataPoints() const; - bool getRepeatDataFlag() const; + int which() const; + const std::vector getPoints() const; + uint64_t getNumDataPoints() const; + bool getRepeatDataFlag() const; - static QEvent::Type Type() - { return QEvent::Type(SpectrumUpdateEventType); } + static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); } protected: - private: - size_t _nplots; - std::vector _dataPoints; - uint64_t _numDataPoints; + size_t _nplots; + std::vector _dataPoints; + uint64_t _numDataPoints; }; - /********************************************************************/ - -class SCOPY_GUI_EXPORT HistogramUpdateEvent: public QEvent +class SCOPY_GUI_EXPORT HistogramUpdateEvent : public QEvent { public: - HistogramUpdateEvent(const std::vector &points, - const uint64_t npoints); + HistogramUpdateEvent(const std::vector &points, const uint64_t npoints); - ~HistogramUpdateEvent(); + ~HistogramUpdateEvent(); - int which() const; - const std::vector getDataPoints() const; - uint64_t getNumDataPoints() const; - bool getRepeatDataFlag() const; + int which() const; + const std::vector getDataPoints() const; + uint64_t getNumDataPoints() const; + bool getRepeatDataFlag() const; - static QEvent::Type Type() - { return QEvent::Type(SpectrumUpdateEventType); } + static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); } protected: - private: - size_t _nplots; - std::vector _points; - uint64_t _npoints; + size_t _nplots; + std::vector _points; + uint64_t _npoints; }; - /********************************************************************/ - -class SCOPY_GUI_EXPORT NumberUpdateEvent: public QEvent +class SCOPY_GUI_EXPORT NumberUpdateEvent : public QEvent { public: - NumberUpdateEvent(const std::vector &samples); - ~NumberUpdateEvent(); + NumberUpdateEvent(const std::vector &samples); + ~NumberUpdateEvent(); - int which() const; - const std::vector getSamples() const; + int which() const; + const std::vector getSamples() const; - static QEvent::Type Type() - { return QEvent::Type(SpectrumUpdateEventType); } + static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); } protected: - private: - size_t _nplots; - std::vector _samples; + size_t _nplots; + std::vector _samples; }; - - #endif /* M2K_SPECTRUM_UPDATE_EVENTS_H */ diff --git a/gui/include/gui/spectrum_marker.hpp b/gui/include/gui/spectrum_marker.hpp index 627b142193..3067b4e771 100644 --- a/gui/include/gui/spectrum_marker.hpp +++ b/gui/include/gui/spectrum_marker.hpp @@ -21,22 +21,22 @@ #ifndef SPECTRUM_MARKER_H #define SPECTRUM_MARKER_H -#include -#include #include "scopy-gui_export.h" +#include +#include + namespace scopy { -class SCOPY_GUI_EXPORT SpectrumMarker: public QwtPlotMarker +class SCOPY_GUI_EXPORT SpectrumMarker : public QwtPlotMarker { public: - SpectrumMarker(const QString& title, bool movable = true); - SpectrumMarker(const QString &title, QwtAxisId xAxis, QwtAxisId yAxis, - bool movable = true); + SpectrumMarker(const QString &title, bool movable = true); + SpectrumMarker(const QString &title, QwtAxisId xAxis, QwtAxisId yAxis, bool movable = true); virtual ~SpectrumMarker(); QColor defaultColor() const; - void setDefaultColor(const QColor&); + void setDefaultColor(const QColor &); bool selected() const; void setSelected(bool on); @@ -44,8 +44,8 @@ class SCOPY_GUI_EXPORT SpectrumMarker: public QwtPlotMarker bool movable() const; void setMovable(bool on); - QPoint plotValueToPixels(const QPointF& point) const; - QPointF plotPixelsToValue(const QPoint& point) const; + QPoint plotValueToPixels(const QPointF &point) const; + QPointF plotPixelsToValue(const QPoint &point) const; QRect boundingRectPixels() const; diff --git a/gui/include/gui/spinbox_a.hpp b/gui/include/gui/spinbox_a.hpp index 0f74e0a4ce..2f95687354 100644 --- a/gui/include/gui/spinbox_a.hpp +++ b/gui/include/gui/spinbox_a.hpp @@ -21,15 +21,16 @@ #ifndef SPIN_BOX_A_H #define SPIN_BOX_A_H -#include -#include -#include -#include - #include "plot_utils.hpp" #include "scopy-gui_export.h" #include "utils.h" +#include +#include +#include + +#include + class QHBoxLayout; class QVBoxLayout; class QPushButton; @@ -69,11 +70,9 @@ class SCOPY_GUI_EXPORT SpinBoxA : public QWidget public: explicit SpinBoxA(QWidget *parent = nullptr); - explicit SpinBoxA(std::vector >units, - const QString& name = "", - double min_value = 0.0, double max_value = 0.0, - bool hasProgressWidget = true, - bool invertCircle = false, QWidget *parent = 0); + explicit SpinBoxA(std::vector> units, const QString &name = "", + double min_value = 0.0, double max_value = 0.0, bool hasProgressWidget = true, + bool invertCircle = false, QWidget *parent = 0); ~SpinBoxA(); QPushButton *upButton(); @@ -107,7 +106,7 @@ class SCOPY_GUI_EXPORT SpinBoxA : public QWidget void triggerCircleRedraw(); QString getName() const; - void setName(const QString& name); + void setName(const QString &name); void setDisplayScale(double value); @@ -140,9 +139,9 @@ protected Q_SLOTS: protected: virtual bool eventFilter(QObject *obj, QEvent *event); - double findUnitOfValue(double val,int *posInUnitsList = NULL); - void setUnits(const QStringList& map); - bool isUnitMatched(const QString& unit, double value); + double findUnitOfValue(double val, int *posInUnitsList = NULL); + void setUnits(const QStringList &map); + bool isUnitMatched(const QString &unit, double value); protected: Ui::SpinBoxA *ui; @@ -152,7 +151,7 @@ protected Q_SLOTS: double m_min_value; double m_max_value; int m_decimal_count; - std::vector > m_units; + std::vector> m_units; QRegExpValidator *m_validator; double m_displayScale; #ifdef SPINBOX_API @@ -207,23 +206,21 @@ class SpinBoxA_API : public ApiObject void setFineModeAvailable(bool available); QString getName() const; - void setName(const QString& name); + void setName(const QString &name); private: SpinBoxA *sba; }; #endif -class SCOPY_GUI_EXPORT ScaleSpinButton: public SpinBoxA +class SCOPY_GUI_EXPORT ScaleSpinButton : public SpinBoxA { Q_OBJECT public: explicit ScaleSpinButton(QWidget *parent = nullptr); - explicit ScaleSpinButton(std::vector >units, - const QString& name = "", - double min_value = 0.0, double max_value = 0.0, - bool hasProgressWidget = true, - bool invertCircle = false, QWidget *parent = 0, std::vector steps = {1,2,5}); + explicit ScaleSpinButton(std::vector> units, const QString &name = "", + double min_value = 0.0, double max_value = 0.0, bool hasProgressWidget = true, + bool invertCircle = false, QWidget *parent = 0, std::vector steps = {1, 2, 5}); int getIntegerDivider(); void setIntegerDivider(int integer = 0); @@ -245,16 +242,14 @@ public Q_SLOTS: int integer_step; }; -class SCOPY_GUI_EXPORT PositionSpinButton: public SpinBoxA +class SCOPY_GUI_EXPORT PositionSpinButton : public SpinBoxA { Q_OBJECT public: explicit PositionSpinButton(QWidget *parent = nullptr); - explicit PositionSpinButton(std::vector >units, - const QString& name ="", - double min_value = 0.0, double max_value = 0.0, - bool hasProgressWidget = true, - bool invertCircle = false, QWidget *parent = 0); + explicit PositionSpinButton(std::vector> units, const QString &name = "", + double min_value = 0.0, double max_value = 0.0, bool hasProgressWidget = true, + bool invertCircle = false, QWidget *parent = 0); double step(); void setStep(double); @@ -267,17 +262,14 @@ public Q_SLOTS: double m_step; }; - -class SCOPY_GUI_EXPORT PhaseSpinButton: public SpinBoxA +class SCOPY_GUI_EXPORT PhaseSpinButton : public SpinBoxA { Q_OBJECT public: explicit PhaseSpinButton(QWidget *parent = nullptr); - explicit PhaseSpinButton(std::vector >units, - const QString& name ="", - double min_value = 0.0, double max_value = 360.0, - bool hasProgressWidget = true, - bool invertCircle = false, QWidget *parent = 0); + explicit PhaseSpinButton(std::vector> units, const QString &name = "", + double min_value = 0.0, double max_value = 360.0, bool hasProgressWidget = true, + bool invertCircle = false, QWidget *parent = 0); void setStep(double); @@ -309,9 +301,8 @@ public Q_SLOTS: bool m_inSeconds; double m_scale; int m_indexValue; - }; -} +} // namespace scopy #endif // SPIN_BOX_A_H diff --git a/gui/include/gui/startstoprangewidget.h b/gui/include/gui/startstoprangewidget.h index 0716af6210..152740ebb4 100644 --- a/gui/include/gui/startstoprangewidget.h +++ b/gui/include/gui/startstoprangewidget.h @@ -21,10 +21,10 @@ #ifndef STARTSTOPRANGEWIDGET_H #define STARTSTOPRANGEWIDGET_H -#include - -#include "spinbox_a.hpp" #include "scopy-gui_export.h" +#include "spinbox_a.hpp" + +#include namespace Ui { class StartStopRangeWidget; @@ -36,10 +36,8 @@ class SCOPY_GUI_EXPORT StartStopRangeWidget : public QWidget Q_OBJECT public: - explicit StartStopRangeWidget(double min = 1.0, double max = 5e07, - double minSpan = 1000, - bool hasProgressWidget = false, - QWidget *parent = nullptr); + explicit StartStopRangeWidget(double min = 1.0, double max = 5e07, double minSpan = 1000, + bool hasProgressWidget = false, QWidget *parent = nullptr); ~StartStopRangeWidget(); double getStartValue() const; @@ -79,6 +77,6 @@ private Q_SLOTS: double maxValue; double minSpan; }; -} +} // namespace scopy #endif // STARTSTOPRANGEWIDGET_H diff --git a/gui/include/gui/stylehelper.h b/gui/include/gui/stylehelper.h index 3554362068..3afd3356a2 100644 --- a/gui/include/gui/stylehelper.h +++ b/gui/include/gui/stylehelper.h @@ -2,19 +2,18 @@ #define STYLEHELPER_H #include "widgets/hoverwidget.h" -#include -#include + #include -#include +#include #include +#include +#include +#include +#include #include #include - -#include -#include - // Forward declarations namespace scopy { class SmallOnOffSwitch; @@ -23,10 +22,11 @@ class SpinBoxA; class MeasurementLabel; class StatsLabel; class MeasurementSelectorItem; -} +} // namespace scopy namespace scopy { -class SCOPY_GUI_EXPORT StyleHelper : public QObject { +class SCOPY_GUI_EXPORT StyleHelper : public QObject +{ Q_OBJECT protected: StyleHelper(QObject *parent = nullptr); @@ -37,19 +37,20 @@ class SCOPY_GUI_EXPORT StyleHelper : public QObject { StyleHelper(StyleHelper &other) = delete; void operator=(const StyleHelper &) = delete; static StyleHelper *GetInstance(); + public: static void initColorMap(); static QString getColor(QString id); - static void SquareToggleButtonWithIcon(QPushButton* btn, QString objectName, bool checkable = false); - static void BlueButton(QPushButton *btn, QString objectName=""); - static void SmallBlueButton(QPushButton *btn, QString objectName=""); - static void BlueSquareCheckbox(QCheckBox *chk, QString objectName = ""); + static void SquareToggleButtonWithIcon(QPushButton *btn, QString objectName, bool checkable = false); + static void BlueButton(QPushButton *btn, QString objectName = ""); + static void SmallBlueButton(QPushButton *btn, QString objectName = ""); + static void BlueSquareCheckbox(QCheckBox *chk, QString objectName = ""); static void CollapseCheckbox(QCheckBox *chk, QString objectName = ""); static void ColoredCircleCheckbox(QCheckBox *chk, QColor color, QString objectName = ""); static void ColoredSquareCheckbox(QCheckBox *chk, QColor color, QString objectName = ""); - static void MenuMediumLabel(QLabel * lbl, QString objectName = ""); + static void MenuMediumLabel(QLabel *lbl, QString objectName = ""); static void MenuControlButton(QPushButton *btn, QString objectName = "", bool checkable = true); - static void MenuControlWidget(QWidget* w, QColor color, QString objectName = ""); + static void MenuControlWidget(QWidget *w, QColor color, QString objectName = ""); static void MenuLargeLabel(QLabel *lbl, QString objectName = ""); static void MenuHeaderLine(QFrame *line, QPen pen, QString objectName = ""); static void MenuHeaderWidget(QWidget *w, QString objectName = ""); @@ -79,19 +80,21 @@ class SCOPY_GUI_EXPORT StyleHelper : public QObject { static void BackgroundWidget(QWidget *w, QString objectName = ""); static void TabWidgetLabel(QLabel *w, QString objectName = ""); static void TutorialChapterTitleLabel(QLabel *w, QString objectName = ""); - static void MeasurementPanelLabel(MeasurementLabel* w, QString objectName = ""); - static void StatsPanelLabel(StatsLabel* w, QString objectName = ""); - static void MeasurementSelectorItemWidget(QString iconPath, MeasurementSelectorItem* w, QString objectName = ""); + static void MeasurementPanelLabel(MeasurementLabel *w, QString objectName = ""); + static void StatsPanelLabel(StatsLabel *w, QString objectName = ""); + static void MeasurementSelectorItemWidget(QString iconPath, MeasurementSelectorItem *w, + QString objectName = ""); static void TimePlotHDivInfo(QLabel *w, QString objectName = ""); static void TimePlotSamplingInfo(QLabel *w, QString objectName = ""); - static void DeviceIconBackgroundShadow(QAbstractButton* w, QString objectName = ""); - static void FrameBackgroundShadow(QFrame* w, QString objectName = ""); + static void DeviceIconBackgroundShadow(QAbstractButton *w, QString objectName = ""); + static void FrameBackgroundShadow(QFrame *w, QString objectName = ""); static void HoverWidget(QWidget *w, bool draggable = false, QString objectName = ""); static void TransparentWidget(QWidget *w, QString objectName = ""); + private: - QMap colorMap; - static StyleHelper * pinstance_; + QMap colorMap; + static StyleHelper *pinstance_; }; -} +} // namespace scopy #endif // STYLEHELPER_H diff --git a/gui/include/gui/subsection_separator.hpp b/gui/include/gui/subsection_separator.hpp index f1026715ac..d10ce6ea8a 100644 --- a/gui/include/gui/subsection_separator.hpp +++ b/gui/include/gui/subsection_separator.hpp @@ -1,10 +1,11 @@ #ifndef SUBSECTIONSEPARATOR_H #define SUBSECTIONSEPARATOR_H +#include "scopy-gui_export.h" + #include #include #include -#include "scopy-gui_export.h" namespace Ui { class SubsectionSeparator; @@ -17,29 +18,28 @@ class SCOPY_GUI_EXPORT SubsectionSeparator : public QWidget Q_OBJECT public: - explicit SubsectionSeparator(QWidget* parent = nullptr); - explicit SubsectionSeparator(const QString& text, const bool buttonVisible = false, QWidget* parent = nullptr); + explicit SubsectionSeparator(QWidget *parent = nullptr); + explicit SubsectionSeparator(const QString &text, const bool buttonVisible = false, QWidget *parent = nullptr); ~SubsectionSeparator(); private: - Ui::SubsectionSeparator* m_ui; + Ui::SubsectionSeparator *m_ui; public: - QPushButton* getButton(); + QPushButton *getButton(); void setButtonVisible(bool buttonVisible); bool getButtonChecked(); void setButtonChecked(bool checked); - QLabel* getLabel(); - void setLabel(const QString& text); + QLabel *getLabel(); + void setLabel(const QString &text); void setLabelVisible(bool visible); void setLineVisible(bool visible); - void setContent(QWidget* content); - QWidget* getContentWidget(); - + void setContent(QWidget *content); + QWidget *getContentWidget(); }; } // namespace gui } // namespace scopy diff --git a/gui/include/gui/symbol.h b/gui/include/gui/symbol.h index b5c3d5b51e..ea1563a6bd 100644 --- a/gui/include/gui/symbol.h +++ b/gui/include/gui/symbol.h @@ -21,27 +21,27 @@ #ifndef M2K_SYMBOL_H #define M2K_SYMBOL_H -#include -#include #include "scopy-gui_export.h" -class SCOPY_GUI_EXPORT Symbol: public QObject +#include +#include + +class SCOPY_GUI_EXPORT Symbol : public QObject { Q_OBJECT public: - Symbol(QObject *parent, const QSize& size, QwtAxisId fixedAxis, - QwtAxisId mobileAxis, bool opposedToFixed = false, - bool floats = false); + Symbol(QObject *parent, const QSize &size, QwtAxisId fixedAxis, QwtAxisId mobileAxis, + bool opposedToFixed = false, bool floats = false); virtual ~Symbol(); const QwtPlot *plot() const; QwtPlot *plot(); - void setSurface(const QRect& rect); + void setSurface(const QRect &rect); QRect surface(); - void setAnchor(const QPoint& anchor); + void setAnchor(const QPoint &anchor); QPoint anchor(); void setPlotCoord(const QPointF &pos); @@ -68,8 +68,8 @@ class SCOPY_GUI_EXPORT Symbol: public QObject void setVisible(bool en); bool isVisible(); - void setPen(const QPen&); - const QPen& pen(); + void setPen(const QPen &); + const QPen &pen(); QPointF invTransform(const QPointF &) const; QPointF transform(const QPointF &) const; @@ -94,29 +94,30 @@ protected Q_SLOTS: protected: QRect d_surface; - QPoint d_anchor; // sets which point of d_surface to point exactly to d_plotCoord. Default point is: top-left of d_surface (d_anchor = (0, 0)) + QPoint d_anchor; // sets which point of d_surface to point exactly to d_plotCoord. Default point is: top-left of + // d_surface (d_anchor = (0, 0)) QPointF d_plotCoord; // Position of symbol in plot coordinates bool d_selected; - QwtAxisId d_fixedAxis; // The axis on which the symbol must not move + QwtAxisId d_fixedAxis; // The axis on which the symbol must not move QwtAxisId d_mobileAxis; // The axis on which the symbol can be shifted - double d_stepSize; // Symbol position can take only values that are a multiple of d_stepSize. If d_stepSize = 0 symbol pos can take any value. - bool d_oppToFixed; // If symbol should be placed diametrically opposed to the fixed axis - bool d_floats; // If symbols floats on top of the plot or is attached to the plot - bool d_within_plot; // If symbol position can only be within the plot visible area + double d_stepSize; // Symbol position can take only values that are a multiple of d_stepSize. If d_stepSize = 0 + // symbol pos can take any value. + bool d_oppToFixed; // If symbol should be placed diametrically opposed to the fixed axis + bool d_floats; // If symbols floats on top of the plot or is attached to the plot + bool d_within_plot; // If symbol position can only be within the plot visible area bool d_visible; QPen d_pen; }; -class SCOPY_GUI_EXPORT VertDebugSymbol: public Symbol +class SCOPY_GUI_EXPORT VertDebugSymbol : public Symbol { Q_OBJECT public: - VertDebugSymbol(QObject *parent, const QSize& size, - bool opposedToFixed = false, bool floats = false); + VertDebugSymbol(QObject *parent, const QSize &size, bool opposedToFixed = false, bool floats = false); void draw(QPainter *painter) const; @@ -134,16 +135,14 @@ public Q_SLOTS: private Q_SLOTS: void onBasePositionChanged(double, double); void onBasePixelPositionChanged(int, int); - }; -class SCOPY_GUI_EXPORT HorizDebugSymbol: public Symbol +class SCOPY_GUI_EXPORT HorizDebugSymbol : public Symbol { Q_OBJECT public: - HorizDebugSymbol(QObject *parent, const QSize& size, - bool opposedToFixed = false, bool floats = false); + HorizDebugSymbol(QObject *parent, const QSize &size, bool opposedToFixed = false, bool floats = false); void draw(QPainter *painter) const; @@ -152,7 +151,7 @@ class SCOPY_GUI_EXPORT HorizDebugSymbol: public Symbol Q_SIGNALS: void positionChanged(double); - void pixelPositionChanged(int); + void pixelPositionChanged(int); public Q_SLOTS: void setPosition(double horizPos); @@ -163,12 +162,12 @@ private Q_SLOTS: void onBasePixelPositionChanged(int, int); }; -class SCOPY_GUI_EXPORT TriggerLevelCursor: public VertDebugSymbol +class SCOPY_GUI_EXPORT TriggerLevelCursor : public VertDebugSymbol { Q_OBJECT public: - TriggerLevelCursor(QObject *parent, const QPixmap& pixmap); + TriggerLevelCursor(QObject *parent, const QPixmap &pixmap); void draw(QPainter *painter) const; @@ -176,12 +175,12 @@ class SCOPY_GUI_EXPORT TriggerLevelCursor: public VertDebugSymbol QPixmap d_cursorPixmap; }; -class SCOPY_GUI_EXPORT TriggerDelayCursor: public HorizDebugSymbol +class SCOPY_GUI_EXPORT TriggerDelayCursor : public HorizDebugSymbol { Q_OBJECT public: - TriggerDelayCursor(QObject *parent, const QPixmap& pixmap); + TriggerDelayCursor(QObject *parent, const QPixmap &pixmap); void draw(QPainter *painter) const; @@ -189,7 +188,7 @@ class SCOPY_GUI_EXPORT TriggerDelayCursor: public HorizDebugSymbol QPixmap d_cursorPixmap; }; -class SCOPY_GUI_EXPORT HorizBar: public VertDebugSymbol +class SCOPY_GUI_EXPORT HorizBar : public VertDebugSymbol { Q_OBJECT @@ -199,7 +198,7 @@ class SCOPY_GUI_EXPORT HorizBar: public VertDebugSymbol void draw(QPainter *painter) const; }; -class SCOPY_GUI_EXPORT VertBar: public HorizDebugSymbol +class SCOPY_GUI_EXPORT VertBar : public HorizDebugSymbol { Q_OBJECT diff --git a/gui/include/gui/symbol_controller.h b/gui/include/gui/symbol_controller.h index 20d104869f..95df1f0eb5 100644 --- a/gui/include/gui/symbol_controller.h +++ b/gui/include/gui/symbol_controller.h @@ -21,14 +21,15 @@ #ifndef M2K_SYMBOL_CONTROLLER_H #define M2K_SYMBOL_CONTROLLER_H +#include "scopy-gui_export.h" +#include "symbol.h" + #include #include -#include "symbol.h" -#include "scopy-gui_export.h" class QwtPlot; -class SCOPY_GUI_EXPORT SymbolController: public QObject +class SCOPY_GUI_EXPORT SymbolController : public QObject { Q_OBJECT diff --git a/gui/include/gui/tintedoverlay.h b/gui/include/gui/tintedoverlay.h index a51d57f556..0ec1ade4ad 100644 --- a/gui/include/gui/tintedoverlay.h +++ b/gui/include/gui/tintedoverlay.h @@ -1,19 +1,21 @@ #ifndef TINTEDOVERLAY_H #define TINTEDOVERLAY_H -#include +#include "scopy-gui_export.h" + +#include +#include #include #include #include -#include -#include -#include "scopy-gui_export.h" +#include namespace scopy::gui { -class SCOPY_GUI_EXPORT TintedOverlay : public QWidget { +class SCOPY_GUI_EXPORT TintedOverlay : public QWidget +{ Q_OBJECT public: - explicit TintedOverlay(QWidget *parent = nullptr, QColor color = QColor(0,0,0,220)); + explicit TintedOverlay(QWidget *parent = nullptr, QColor color = QColor(0, 0, 0, 220)); ~TintedOverlay(); const QList &getHoles() const; @@ -26,10 +28,9 @@ class SCOPY_GUI_EXPORT TintedOverlay : public QWidget { private: QWidget *parent; - QList holes; + QList holes; QColor color; }; -} - +} // namespace scopy::gui #endif // TINTEDOVERLAY_H diff --git a/gui/include/gui/tool_view.hpp b/gui/include/gui/tool_view.hpp index 7303008956..145f544879 100644 --- a/gui/include/gui/tool_view.hpp +++ b/gui/include/gui/tool_view.hpp @@ -1,22 +1,22 @@ #ifndef TOOL_VIEW_HPP #define TOOL_VIEW_HPP -#include -#include -#include -#include -#include -#include - #include "channel_manager.hpp" #include "channel_widget.hpp" -#include "custom_menu_button.hpp" #include "customPushButton.h" +#include "custom_menu_button.hpp" #include "generic_menu.hpp" #include "linked_button.hpp" #include "menu_anim.hpp" #include "scopy-gui_export.h" +#include +#include +#include +#include +#include +#include + namespace Ui { class ToolView; } @@ -31,98 +31,102 @@ class SCOPY_GUI_EXPORT ToolView : public QWidget Q_OBJECT public: - explicit ToolView(QWidget* parent = nullptr); + explicit ToolView(QWidget *parent = nullptr); ~ToolView(); - LinkedButton* getHelpBtn(); + LinkedButton *getHelpBtn(); void setHelpBtnVisible(bool visible); - void setUrlHelpBtn(const QString& url); + void setUrlHelpBtn(const QString &url); - QPushButton* getPrintBtn(); + QPushButton *getPrintBtn(); void setPrintBtnVisible(bool visible); - QPushButton* getRunBtn(); + QPushButton *getRunBtn(); void setRunBtnVisible(bool visible); - QPushButton* getSingleBtn(); + QPushButton *getSingleBtn(); void setSingleBtnVisible(bool visible); - QWidget* getTopExtraWidget(); + QWidget *getTopExtraWidget(); void setVisibleTopExtraWidget(bool visible); - void addTopExtraWidget(QWidget* widget); + void addTopExtraWidget(QWidget *widget); - QWidget* getBottomExtraWidget(); + QWidget *getBottomExtraWidget(); void setVisibleBottomExtraWidget(bool visible); - void addBottomExtraWidget(QWidget* widget); + void addBottomExtraWidget(QWidget *widget); - QWidget* getCentralWidget(); - QStackedWidget* getStackedWidget(); + QWidget *getCentralWidget(); + QStackedWidget *getStackedWidget(); - CustomPushButton* getGeneralSettingsBtn(); - QPushButton* getSettingsBtn(); + CustomPushButton *getGeneralSettingsBtn(); + QPushButton *getSettingsBtn(); void setPairSettingsVisible(bool visible); void setInstrumentNotesVisible(bool visible); - void setFixedMenu(QWidget* menu, bool dockable); - void setGeneralSettingsMenu(QWidget* menu, bool dockable); + void setFixedMenu(QWidget *menu, bool dockable); + void setGeneralSettingsMenu(QWidget *menu, bool dockable); - ChannelWidget* buildNewChannel(ChannelManager* channelManager, GenericMenu* menu, bool dockable, int chId, - bool deletable, bool simplified, QColor color, const QString& fullName, - const QString& shortName); - void buildChannelGroup(ChannelManager* channelManager,ChannelWidget* mainChannal, std::vector channelGroup); - CustomMenuButton *buildNewInstrumentMenu(GenericMenu* menu, bool dockable, const QString& name, bool checkBoxVisible = false, - bool checkBoxChecked = false); + ChannelWidget *buildNewChannel(ChannelManager *channelManager, GenericMenu *menu, bool dockable, int chId, + bool deletable, bool simplified, QColor color, const QString &fullName, + const QString &shortName); + void buildChannelGroup(ChannelManager *channelManager, ChannelWidget *mainChannal, + std::vector channelGroup); + CustomMenuButton *buildNewInstrumentMenu(GenericMenu *menu, bool dockable, const QString &name, + bool checkBoxVisible = false, bool checkBoxChecked = false); - void addFixedCentralWidget(QWidget* widget, int row = -1, int column = -1,int rowspan = -1, int columnspan = -1); - int addDockableCentralWidget(QWidget* widget, Qt::DockWidgetArea area, const QString& dockerName); - QDockWidget *addDockableTabbedWidget(QWidget* plot, const QString &dockerName); - int addFixedTabbedWidget(QWidget* widget, const QString& title, int plotId = -1, int row = -1, int column = -1,int rowspan = -1, int columnspan = -1); + void addFixedCentralWidget(QWidget *widget, int row = -1, int column = -1, int rowspan = -1, + int columnspan = -1); + int addDockableCentralWidget(QWidget *widget, Qt::DockWidgetArea area, const QString &dockerName); + QDockWidget *addDockableTabbedWidget(QWidget *plot, const QString &dockerName); + int addFixedTabbedWidget(QWidget *widget, const QString &title, int plotId = -1, int row = -1, int column = -1, + int rowspan = -1, int columnspan = -1); void setWidgetVisibility(int widgetId, bool visible); bool isWidgetHidden(int widgetId); void setHeaderVisibility(bool visible); - scopy::MenuHAnim* addMenuToStack(); - void setStackedWidget(QStackedWidget* sw); + scopy::MenuHAnim *addMenuToStack(); + void setStackedWidget(QStackedWidget *sw); int getNewID(); void addPlotInfoWidget(QWidget *widget); QWidget *getPlotInfoWidget(); + private: void configureLastOpenedMenu(); - void buildChannelsContainer(ChannelManager* channelManager, ChannelsPositionEnum position); - void toggleRightMenu(CustomPushButton* btn, bool checked); + void buildChannelsContainer(ChannelManager *channelManager, ChannelsPositionEnum position); + void toggleRightMenu(CustomPushButton *btn, bool checked); void settingsPanelUpdate(int id); void rightMenuFinished(bool opened); - QDockWidget* createDetachableMenu(QWidget* menu, int& id); - QDockWidget* createDockableWidget(QWidget* widget, const QString& dockerName); + QDockWidget *createDetachableMenu(QWidget *menu, int &id); + QDockWidget *createDockableWidget(QWidget *widget, const QString &dockerName); public Q_SLOTS: void triggerRightMenuToggle(bool checked); - void configureAddMathBtn(QWidget* menu, bool dockable); + void configureAddMathBtn(QWidget *menu, bool dockable); Q_SIGNALS: - void changeParent(QWidget* newParent); + void changeParent(QWidget *newParent); void channelDisabled(bool disabled); void instrumentMenuDisabled(bool disabled); private: - Ui::ToolView* m_ui; + Ui::ToolView *m_ui; QButtonGroup m_group; QButtonGroup m_channelsGroup; // selected state of each channel - QQueue> m_menuButtonActions; - QList m_menuOrder; + QQueue> m_menuButtonActions; + QList m_menuOrder; int m_generalSettingsMenuId; - QMainWindow* m_centralMainWindow; - QList m_docksList; - QList m_centralFixedWidgets; - QMap m_menuList; + QMainWindow *m_centralMainWindow; + QList m_docksList; + QList m_centralFixedWidgets; + QMap m_menuList; int m_nextMenuIndex; void initPlotInfoWidget(); diff --git a/gui/include/gui/tool_view_builder.hpp b/gui/include/gui/tool_view_builder.hpp index eef11d339c..b1b82eb8d4 100644 --- a/gui/include/gui/tool_view_builder.hpp +++ b/gui/include/gui/tool_view_builder.hpp @@ -1,8 +1,8 @@ #ifndef TOOLBUILDER_HPP #define TOOLBUILDER_HPP -#include "tool_view.hpp" #include "scopy-gui_export.h" +#include "tool_view.hpp" namespace scopy { namespace gui { @@ -29,12 +29,13 @@ struct ToolViewRecipe class SCOPY_GUI_EXPORT ToolViewBuilder { public: - ToolViewBuilder(const ToolViewRecipe& recipe, ChannelManager* channelManager = nullptr, QWidget* parent = nullptr); + ToolViewBuilder(const ToolViewRecipe &recipe, ChannelManager *channelManager = nullptr, + QWidget *parent = nullptr); - ToolView* build(); + ToolView *build(); private: - ToolView* m_toolView; + ToolView *m_toolView; }; } // namespace gui } // namespace scopy diff --git a/gui/include/gui/tooltemplate.h b/gui/include/gui/tooltemplate.h index db20458492..2ec1fb15bf 100644 --- a/gui/include/gui/tooltemplate.h +++ b/gui/include/gui/tooltemplate.h @@ -1,21 +1,24 @@ #ifndef TOOLBUILDER_H #define TOOLBUILDER_H -#include #include "mapstackedwidget.h" #include "scopy-gui_export.h" +#include + namespace Ui { class ToolTemplate; } namespace scopy { -enum ToolTemplateAlignment { +enum ToolTemplateAlignment +{ TTA_LEFT, TTA_RIGHT }; -enum ToolTemplateContainer { +enum ToolTemplateContainer +{ TTC_LEFT, TTC_RIGHT, TTC_TOP, @@ -61,10 +64,10 @@ class SCOPY_GUI_EXPORT ToolTemplate : public QWidget void addWidgetToCentralContainerHelper(QWidget *w); public Q_SLOTS: void requestMenu(QString); + private: Ui::ToolTemplate *m_ui; - }; -} +} // namespace scopy #endif // TOOLBUILDER_H diff --git a/gui/include/gui/trigger_mode.h b/gui/include/gui/trigger_mode.h index bf9da10195..771e9ee1e4 100644 --- a/gui/include/gui/trigger_mode.h +++ b/gui/include/gui/trigger_mode.h @@ -21,16 +21,18 @@ #ifndef M2K_TRIGGER_MODE_H #define M2K_TRIGGER_MODE_H - enum trigger_mode { - TRIG_MODE_FREE, - TRIG_MODE_AUTO, - TRIG_MODE_NORM, - TRIG_MODE_TAG, - }; +enum trigger_mode +{ + TRIG_MODE_FREE, + TRIG_MODE_AUTO, + TRIG_MODE_NORM, + TRIG_MODE_TAG, +}; - enum trigger_slope { - TRIG_SLOPE_POS, - TRIG_SLOPE_NEG, - }; +enum trigger_slope +{ + TRIG_SLOPE_POS, + TRIG_SLOPE_NEG, +}; #endif /* M2K_TRIGGER_MODE_H */ diff --git a/gui/include/gui/tutorialbuilder.h b/gui/include/gui/tutorialbuilder.h index 3093e5dfc9..667c249da4 100644 --- a/gui/include/gui/tutorialbuilder.h +++ b/gui/include/gui/tutorialbuilder.h @@ -18,30 +18,32 @@ * along with this program. If not, see . */ - #ifndef SCOPY_TUTORIALBUILDER_H #define SCOPY_TUTORIALBUILDER_H -#include - #include "scopy-gui_export.h" #include "tutorialoverlay.h" +#include + namespace scopy::gui { -class SCOPY_GUI_EXPORT TutorialBuilder : public scopy::gui::TutorialOverlay { +class SCOPY_GUI_EXPORT TutorialBuilder : public scopy::gui::TutorialOverlay +{ Q_OBJECT public: /** * @brief This acts as a wrapper to the scopy::gui::TutorialOverlay class that is meant to simplify adding * chapters in order. * @param topWidget The topmost widget that contains all the children widgets that will be part of the tutorial. - * @param jsonFile A json file that describes each chapter and attributes related to it (e.g. description, order). + * @param jsonFile A json file that describes each chapter and attributes related to it (e.g. description, + * order). * @param jsonEntry The entry in the jsonFile that represents the current tutorial. * @param parent The widget that will receive the tinted overlay meant to highlight tutorial subjects. * @inherit scopy::gui::TutorialOverlay * */ - explicit TutorialBuilder(QWidget* topWidget, const QString& jsonFile, QString jsonEntry, QWidget* parent = nullptr); - explicit TutorialBuilder(QWidget* parent = nullptr); + explicit TutorialBuilder(QWidget *topWidget, const QString &jsonFile, QString jsonEntry, + QWidget *parent = nullptr); + explicit TutorialBuilder(QWidget *parent = nullptr); QString getJsonFileName() const; void setJsonFileName(const QString &jsonFile); @@ -72,19 +74,20 @@ class SCOPY_GUI_EXPORT TutorialBuilder : public scopy::gui::TutorialOverlay { public Q_SLOTS: /** - * @brief Calls collectChapters() and readTutorialRequirements() before calling the start() method from the - * base class. - * */ + * @brief Calls collectChapters() and readTutorialRequirements() before calling the start() method from the + * base class. + * */ void start() override; private: QFile m_jsonFile; QString m_jsonEntry; - QWidget* m_topWidget; + QWidget *m_topWidget; - struct ChapterInstructions { + struct ChapterInstructions + { // map representing the widget property string related to the tutorial and the related widget - QMap widgets; + QMap widgets; // this is a name of the widget from the map declared above, the description of the chapter will // be anchored to this widget @@ -96,7 +99,7 @@ public Q_SLOTS: HoverPosition content; }; - QMap m_chapters; + QMap m_chapters; /** * @brief Searches for the ChapterInstructions entries that have the name field matching the name parameter @@ -104,15 +107,16 @@ public Q_SLOTS: * @throws std::runtime_error Thrown when the name is not found in the m_chapters QMap * @return The list of pointers to the ChapterInstructions that were found with this name * */ - QList getChapterInstructionFromName(const QString& name); + QList getChapterInstructionFromName(const QString &name); /** - * @brief Converts a QString to the corresponding HoverPosition value (e.g. "HP_TOPLEFT" -> scopy::HoverPosition::HP_TOPLEFT) + * @brief Converts a QString to the corresponding HoverPosition value (e.g. "HP_TOPLEFT" -> + * scopy::HoverPosition::HP_TOPLEFT) * @param position QString that matches an entry of HoverPosition * @return HoverPosition entry, if there is no match, the default value of CENTER will be returned * */ - static HoverPosition convertStringToHoverPosition(const QString& position) noexcept; + static HoverPosition convertStringToHoverPosition(const QString &position) noexcept; }; -} +} // namespace scopy::gui -#endif //SCOPY_TUTORIALBUILDER_H +#endif // SCOPY_TUTORIALBUILDER_H diff --git a/gui/include/gui/tutorialchapter.h b/gui/include/gui/tutorialchapter.h index 827bb02d63..793bac3970 100644 --- a/gui/include/gui/tutorialchapter.h +++ b/gui/include/gui/tutorialchapter.h @@ -18,36 +18,31 @@ * along with this program. If not, see . */ - #ifndef TUTORIALCHAPTER_H #define TUTORIALCHAPTER_H -#include #include +#include + #include #include namespace scopy::gui { -class SCOPY_GUI_EXPORT TutorialChapter : public QObject { +class SCOPY_GUI_EXPORT TutorialChapter : public QObject +{ Q_OBJECT public: TutorialChapter(QObject *parent = nullptr); ~TutorialChapter(); - static TutorialChapter* build( - const QList& subjects, - const QString& description, - QWidget* mainSubject, - int x_offset, - int y_offset, - HoverPosition anchor, - HoverPosition content, - QObject *parent = nullptr); + static TutorialChapter *build(const QList &subjects, const QString &description, + QWidget *mainSubject, int x_offset, int y_offset, HoverPosition anchor, + HoverPosition content, QObject *parent = nullptr); - void addSubject( QWidget* s); + void addSubject(QWidget *s); - QList subjects; - QWidget* mainSubject; // the main subject is the widget that will act as the anchor for the overlay + QList subjects; + QWidget *mainSubject; // the main subject is the widget that will act as the anchor for the overlay QString description; int x_offset; int y_offset; @@ -76,5 +71,5 @@ class SCOPY_GUI_EXPORT TutorialChapter : public QObject { void chapterStarted(); void chapterFinished(); }; -} +} // namespace scopy::gui #endif // TUTORIALCHAPTER_H diff --git a/gui/include/gui/tutorialoverlay.h b/gui/include/gui/tutorialoverlay.h index fe1f481896..f718c6998f 100644 --- a/gui/include/gui/tutorialoverlay.h +++ b/gui/include/gui/tutorialoverlay.h @@ -18,16 +18,17 @@ * along with this program. If not, see . */ - #ifndef TUTORIALOVERLAY_H #define TUTORIALOVERLAY_H -#include +#include "scopy-gui_export.h" #include "tintedoverlay.h" #include "tutorialchapter.h" -#include #include "widgets/popupwidget.h" -#include "scopy-gui_export.h" + +#include + +#include namespace Ui { class Tutorial; @@ -42,16 +43,12 @@ class SCOPY_GUI_EXPORT TutorialOverlay : public QWidget explicit TutorialOverlay(QWidget *parent = nullptr); ~TutorialOverlay(); - TutorialChapter* addChapter( - const QList& subjects, - const QString& description, - QWidget* mainWidget = nullptr, - int x_offset = 0, - int y_offset = 0, - HoverPosition anchor = HoverPosition::HP_CENTER, - HoverPosition content = HoverPosition::HP_CENTER); - TutorialChapter* addChapter(QWidget* subject, QString description); - void addChapter(TutorialChapter* ch); + TutorialChapter *addChapter(const QList &subjects, const QString &description, + QWidget *mainWidget = nullptr, int x_offset = 0, int y_offset = 0, + HoverPosition anchor = HoverPosition::HP_CENTER, + HoverPosition content = HoverPosition::HP_CENTER); + TutorialChapter *addChapter(QWidget *subject, QString description); + void addChapter(TutorialChapter *ch); const QString &getTitle() const; void setTitle(const QString &newTitle); @@ -79,16 +76,15 @@ public Q_SLOTS: void cleanupChapter(); bool eventFilter(QObject *watched, QEvent *event) override; - QList chapter; + QList chapter; QWidget *parent; TintedOverlay *overlay; - QList highlights; + QList highlights; HoverWidget *m_hoverWidget; QString title; int cnt; PopupWidget *m_popupWidget; }; -} - +} // namespace scopy::gui #endif // TUTORIALOVERLAY_H diff --git a/gui/include/gui/utils.h b/gui/include/gui/utils.h index 96c7c3ba8d..182980301d 100644 --- a/gui/include/gui/utils.h +++ b/gui/include/gui/utils.h @@ -21,37 +21,37 @@ #ifndef GUI_UTILS_H #define GUI_UTILS_H -#include -#include -#include -#include +#include "scopy-gui_export.h" + +#include #include #include -#include -#include #include - -#include -#include -#include #include -#include "scopy-gui_export.h" +#include +#include +#include #include +#include +#include +#include + +#include +#include class SCOPY_GUI_EXPORT Util { public: static void retainWidgetSizeWhenHidden(QWidget *w, bool retain = true); - static void setWidgetNrOfChars(QWidget *w, int minNrOfChars, int maxNrOfChars=0); + static void setWidgetNrOfChars(QWidget *w, int minNrOfChars, int maxNrOfChars = 0); static QString loadStylesheetFromFile(const QString &path); static bool compareNatural(const std::string &a, const std::string &b); - static QWidget* findContainingWindow(QWidget* w); - static const QList getColors() {return {"#F44336", "#4DAF50", "#E91E63", "#9C27B0", - "#3F51B5", "#2096F3", "#795448", "#02BCD4", - "#019688", "#673AB7", "#8BC34A", "#CDDC39", - "#FFEB3B", "#FFC108", "#FF9800", "#FF5721", - "#03A9F4", "#9E9E9E", "#607D8B", "#FFFFFF" - }; + static QWidget *findContainingWindow(QWidget *w); + static const QList getColors() + { + return {"#F44336", "#4DAF50", "#E91E63", "#9C27B0", "#3F51B5", "#2096F3", "#795448", + "#02BCD4", "#019688", "#673AB7", "#8BC34A", "#CDDC39", "#FFEB3B", "#FFC108", + "#FF9800", "#FF5721", "#03A9F4", "#9E9E9E", "#607D8B", "#FFFFFF"}; } static void SetAttrRecur(QDomElement &elem, QString strtagname, QString strattr, QString strattrval); static QPixmap ChangeSVGColor(QString iconPath, QString color, float opacity); @@ -62,20 +62,21 @@ class SCOPY_GUI_EXPORT Util class SCOPY_GUI_EXPORT DockerUtils : public QObject { public: - static QDockWidget* createDockWidget(QMainWindow* mainWindow, QWidget* widget, const QString& title = ""); - static void configureTopBar(QDockWidget* docker); + static QDockWidget *createDockWidget(QMainWindow *mainWindow, QWidget *widget, const QString &title = ""); + static void configureTopBar(QDockWidget *docker); }; // https://forum.qt.io/topic/25142/solved-applying-style-on-derived-widget-with-custom-property-failes/2 // https://doc.qt.io/qt-5/stylesheet-reference.html -#define QWIDGET_PAINT_EVENT_HELPER \ -public:\ - void paintEvent(QPaintEvent *e) override {\ - QStyleOption opt;\ - opt.init(this);\ - QPainter p(this);\ - style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);\ +#define QWIDGET_PAINT_EVENT_HELPER \ +public: \ + void paintEvent(QPaintEvent *e) override \ + { \ + QStyleOption opt; \ + opt.init(this); \ + QPainter p(this); \ + style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); \ } #endif /* GUI_UTILS_H */ diff --git a/gui/include/gui/vcursor.h b/gui/include/gui/vcursor.h index 6b6ae54ee9..46c0b8e5c3 100644 --- a/gui/include/gui/vcursor.h +++ b/gui/include/gui/vcursor.h @@ -1,19 +1,23 @@ #ifndef VCURSOR_H #define VCURSOR_H -#include -#include "plotwidget.h" #include "plotaxis.h" +#include "plotwidget.h" #include "scopy-gui_export.h" + +#include + #include namespace scopy { - -class SCOPY_GUI_EXPORT VCursor : public Cursor { +class SCOPY_GUI_EXPORT VCursor : public Cursor +{ Q_OBJECT public: - explicit VCursor(PlotWidget* p, PlotAxis *ax, bool right = true, QPen pen = QPen(QColor(155, 155, 155), 1, Qt::DashLine)); - ~VCursor();; + explicit VCursor(PlotWidget *p, PlotAxis *ax, bool right = true, + QPen pen = QPen(QColor(155, 155, 155), 1, Qt::DashLine)); + ~VCursor(); + ; double computePosition(int pos); double getPosition(); @@ -23,6 +27,6 @@ class SCOPY_GUI_EXPORT VCursor : public Cursor { Q_SIGNALS: void update(); }; -} +} // namespace scopy #endif // VCURSOR_H diff --git a/gui/include/gui/waterfallGlobalData.h b/gui/include/gui/waterfallGlobalData.h index d3c5b08873..36d65f3937 100644 --- a/gui/include/gui/waterfallGlobalData.h +++ b/gui/include/gui/waterfallGlobalData.h @@ -30,73 +30,77 @@ #ifndef WATERFALL_GLOBAL_DATA_HPP #define WATERFALL_GLOBAL_DATA_HPP +#include "scopy-gui_export.h" + #include + #include -#include "scopy-gui_export.h" #if QWT_VERSION >= 0x060000 -#include #include +#include + typedef QwtInterval QwtDoubleInterval; #endif -enum WaterfallFlowDirection { - UP, - DOWN +enum WaterfallFlowDirection +{ + UP, + DOWN }; class SCOPY_GUI_EXPORT WaterfallData : public QwtRasterData { public: - WaterfallData(const double, const double, const uint64_t, const unsigned int); - ~WaterfallData() override; + WaterfallData(const double, const double, const uint64_t, const unsigned int); + ~WaterfallData() override; - virtual void reset(); - virtual void copy(const WaterfallData*); + virtual void reset(); + virtual void copy(const WaterfallData *); - virtual void - resizeData(const double, const double, const uint64_t, const int history = 0); + virtual void resizeData(const double, const double, const uint64_t, const int history = 0); - virtual QwtRasterData* copy() const; + virtual QwtRasterData *copy() const; #if QWT_VERSION < 0x060000 - virtual QwtDoubleInterval range() const; - virtual void setRange(const QwtDoubleInterval&); + virtual QwtDoubleInterval range() const; + virtual void setRange(const QwtDoubleInterval &); #elif QWT_VERSION >= 0x060200 - virtual QwtInterval interval(Qt::Axis) const; - void setInterval(Qt::Axis, const QwtInterval&); + virtual QwtInterval interval(Qt::Axis) const; + void setInterval(Qt::Axis, const QwtInterval &); #endif - double value(double x, double y) const override; + double value(double x, double y) const override; + + virtual uint64_t getNumFFTPoints() const; + virtual void addFFTData(const double *, const uint64_t); - virtual uint64_t getNumFFTPoints() const; - virtual void addFFTData(const double*, const uint64_t); + virtual const std::deque> getSpectrumDataBuffer() const; + virtual void setSpectrumDataBuffer(const std::deque>); - virtual const std::deque> getSpectrumDataBuffer() const; - virtual void setSpectrumDataBuffer(const std::deque>); + virtual int getNumLinesToUpdate() const; + virtual void setNumLinesToUpdate(const int); + virtual void incrementNumLinesToUpdate(); - virtual int getNumLinesToUpdate() const; - virtual void setNumLinesToUpdate(const int); - virtual void incrementNumLinesToUpdate(); + void setFlowDirection(WaterfallFlowDirection direction); + WaterfallFlowDirection getFlowDirection(); - void setFlowDirection(WaterfallFlowDirection direction); - WaterfallFlowDirection getFlowDirection(); protected: - std::deque> _spectrumData; - uint64_t _fftPoints; - uint64_t _historyLength; - int _numLinesToUpdate; - WaterfallFlowDirection flow_direction; + std::deque> _spectrumData; + uint64_t _fftPoints; + uint64_t _historyLength; + int _numLinesToUpdate; + WaterfallFlowDirection flow_direction; #if QWT_VERSION < 0x060000 - QwtDoubleInterval _intensityRange; + QwtDoubleInterval _intensityRange; #else - QwtInterval _intensityRange; + QwtInterval _intensityRange; #endif #if QWT_VERSION >= 0x060200 - QwtInterval d_intervals[3]; + QwtInterval d_intervals[3]; #endif private: diff --git a/gui/include/gui/widgets/cursorsettings.h b/gui/include/gui/widgets/cursorsettings.h index 889af7cf74..405700f90d 100644 --- a/gui/include/gui/widgets/cursorsettings.h +++ b/gui/include/gui/widgets/cursorsettings.h @@ -1,10 +1,11 @@ #ifndef CURSORSETTINGS_H #define CURSORSETTINGS_H +#include +#include + #include #include -#include -#include #include #include diff --git a/gui/include/gui/widgets/hoverwidget.h b/gui/include/gui/widgets/hoverwidget.h index c84afcc07c..6003668661 100644 --- a/gui/include/gui/widgets/hoverwidget.h +++ b/gui/include/gui/widgets/hoverwidget.h @@ -1,14 +1,16 @@ #ifndef HOVERWIDGET_H #define HOVERWIDGET_H -#include -#include -#include #include "scopy-gui_export.h" #include "utils.h" +#include +#include +#include + namespace scopy { -enum HoverPosition { +enum HoverPosition +{ HP_LEFT, HP_TOPLEFT, HP_TOP, @@ -20,7 +22,8 @@ enum HoverPosition { HP_CENTER, }; -class SCOPY_GUI_EXPORT HoverWidget : public QWidget { +class SCOPY_GUI_EXPORT HoverWidget : public QWidget +{ Q_OBJECT QWIDGET_PAINT_EVENT_HELPER public: @@ -45,11 +48,12 @@ class SCOPY_GUI_EXPORT HoverWidget : public QWidget { void setDraggable(bool draggable); void setRelative(bool relative); void setRelativeOffset(QPointF offset); + private: QHBoxLayout *m_lay; - QWidget* m_parent; - QWidget* m_anchor; - QWidget* m_content; + QWidget *m_parent; + QWidget *m_anchor; + QWidget *m_content; QPoint m_anchorOffset; HoverPosition m_anchorPos; HoverPosition m_contentPos; @@ -69,5 +73,5 @@ class SCOPY_GUI_EXPORT HoverWidget : public QWidget { void mouseReleaseEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override; }; -} +} // namespace scopy #endif // HOVERWIDGET_H diff --git a/gui/include/gui/widgets/measurementlabel.h b/gui/include/gui/widgets/measurementlabel.h index e33fd62fea..6669ce21f3 100644 --- a/gui/include/gui/widgets/measurementlabel.h +++ b/gui/include/gui/widgets/measurementlabel.h @@ -21,11 +21,13 @@ #define MEASUREMENT_GUI_H #include "plot_utils.hpp" -#include -#include + +#include #include #include -#include +#include +#include + #include #include @@ -33,20 +35,21 @@ namespace scopy { class MeasurementData; -class SCOPY_GUI_EXPORT MeasurementLabel : public QWidget { +class SCOPY_GUI_EXPORT MeasurementLabel : public QWidget +{ friend class scopy::StyleHelper; Q_OBJECT; + public: MeasurementLabel(QWidget *parent = nullptr); ~MeasurementLabel(); - void setName(QString str); void setUnit(QString str); void setPrecision(int val); void setColor(QColor color); void setValue(double val); - void setMeasurementValueFormatter(PrefixFormatter* f); + void setMeasurementValueFormatter(PrefixFormatter *f); QString name() const; QColor color() const; @@ -60,12 +63,12 @@ class SCOPY_GUI_EXPORT MeasurementLabel : public QWidget { int m_precision; QLabel *m_nameLabel; QLabel *m_valueLabel; - PrefixFormatter * m_formatter; + PrefixFormatter *m_formatter; int m_idx; }; - -class SCOPY_GUI_EXPORT StatsLabel : public QWidget { +class SCOPY_GUI_EXPORT StatsLabel : public QWidget +{ friend class scopy::StyleHelper; Q_OBJECT; QWIDGET_PAINT_EVENT_HELPER @@ -73,13 +76,12 @@ class SCOPY_GUI_EXPORT StatsLabel : public QWidget { StatsLabel(QWidget *parent = nullptr); ~StatsLabel(); - void setName(QString str); void setUnit(QString str); void setPrecision(int val); void setColor(QColor color); void setValue(double avg, double min, double max); - void setMeasurementValueFormatter(PrefixFormatter* f); + void setMeasurementValueFormatter(PrefixFormatter *f); QString name() const; QColor color() const; @@ -95,7 +97,7 @@ class SCOPY_GUI_EXPORT StatsLabel : public QWidget { QLabel *m_avgLabel; QLabel *m_minLabel; QLabel *m_maxLabel; - PrefixFormatter * m_formatter; + PrefixFormatter *m_formatter; int m_idx; }; diff --git a/gui/include/gui/widgets/measurementpanel.h b/gui/include/gui/widgets/measurementpanel.h index 36e6b6a27b..166752ccde 100644 --- a/gui/include/gui/widgets/measurementpanel.h +++ b/gui/include/gui/widgets/measurementpanel.h @@ -1,11 +1,12 @@ #ifndef MEASUREMENTPANEL_H #define MEASUREMENTPANEL_H -#include -#include #include "scopy-gui_export.h" #include "utils.h" + #include +#include +#include namespace Ui { class MeasurementsPanel; @@ -15,12 +16,14 @@ namespace scopy { class MeasurementLabel; class StatsLabel; -class VerticalWidgetStack : public QWidget { +class VerticalWidgetStack : public QWidget +{ Q_OBJECT public: - VerticalWidgetStack(QWidget *parent = nullptr) { + VerticalWidgetStack(QWidget *parent = nullptr) + { lay = new QVBoxLayout(this); - setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Expanding); + setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Expanding); setLayout(lay); lay->setMargin(0); lay->setSpacing(6); @@ -28,20 +31,18 @@ class VerticalWidgetStack : public QWidget { lay->addSpacerItem(spacer); stackSize = 4; } - ~VerticalWidgetStack() { - - } - void addWidget(QWidget *w) { + ~VerticalWidgetStack() {} + void addWidget(QWidget *w) + { int idx = lay->indexOf(spacer); - lay->insertWidget(idx,w,Qt::AlignTop | Qt::AlignLeft); + lay->insertWidget(idx, w, Qt::AlignTop | Qt::AlignLeft); m_widgets.append(w); } - void setStackSize(int val) { - stackSize = val; - } + void setStackSize(int val) { stackSize = val; } - void reparentWidgets(QWidget *parent = nullptr) { + void reparentWidgets(QWidget *parent = nullptr) + { for(QWidget *w : m_widgets) { lay->removeWidget(w); w->setParent(parent); @@ -49,15 +50,13 @@ class VerticalWidgetStack : public QWidget { m_widgets.clear(); } - bool full() { - return(lay->count() > stackSize); - } + bool full() { return (lay->count() > stackSize); } private: QVBoxLayout *lay; QSpacerItem *spacer; int stackSize; - QList m_widgets; + QList m_widgets; }; class SCOPY_GUI_EXPORT MeasurementsPanel : public QWidget @@ -75,12 +74,11 @@ public Q_SLOTS: private: QHBoxLayout *panelLayout; - QList m_labels; - QList m_stacks; + QList m_labels; + QList m_stacks; QWidget *m_cursor; QSpacerItem *spacer; void addWidget(QWidget *meas); - }; class SCOPY_GUI_EXPORT StatsPanel : public QWidget @@ -94,12 +92,10 @@ public Q_SLOTS: void addStat(StatsLabel *stat); void removeStat(StatsLabel *stat); void updateOrder(); - void sort(int sortType); // hackish + void sort(int sortType); // hackish private: QHBoxLayout *panelLayout; - QList m_labels; - - + QList m_labels; }; -} +} // namespace scopy #endif // MEASUREMENTPANEL_H diff --git a/gui/include/gui/widgets/measurementselector.h b/gui/include/gui/widgets/measurementselector.h index 30ca3f485b..4bc5b7c43f 100644 --- a/gui/include/gui/widgets/measurementselector.h +++ b/gui/include/gui/widgets/measurementselector.h @@ -1,19 +1,21 @@ #ifndef MEASUREMENTSELECTOR_H #define MEASUREMENTSELECTOR_H -#include -#include #include "scopy-gui_export.h" -#include -#include + +#include #include +#include +#include +#include namespace scopy { - -class SCOPY_GUI_EXPORT MeasurementSelectorItem : public QWidget { +class SCOPY_GUI_EXPORT MeasurementSelectorItem : public QWidget +{ Q_OBJECT friend class StyleHelper; + public: MeasurementSelectorItem(QString name, QString icon, QWidget *parent); ~MeasurementSelectorItem(); @@ -26,7 +28,6 @@ class SCOPY_GUI_EXPORT MeasurementSelectorItem : public QWidget { QLabel *m_name; QCheckBox *m_measureCheckbox; QCheckBox *m_statsCheckbox; - }; class SCOPY_GUI_EXPORT MeasurementSelector : public QWidget @@ -38,16 +39,15 @@ class SCOPY_GUI_EXPORT MeasurementSelector : public QWidget void addMeasurement(QString name, QString icon); void removeMeasurement(QString name); - MeasurementSelectorItem* measurement(QString name); + MeasurementSelectorItem *measurement(QString name); void toggleAllMeasurement(bool b); void toggleAllStats(bool b); private: - QMap m_map; + QMap m_map; QVBoxLayout *lay; - }; -} +} // namespace scopy #endif // MEASUREMENTSELECTOR_H diff --git a/gui/include/gui/widgets/measurementsettings.h b/gui/include/gui/widgets/measurementsettings.h index 8bd44235a3..1fd71f0bd0 100644 --- a/gui/include/gui/widgets/measurementsettings.h +++ b/gui/include/gui/widgets/measurementsettings.h @@ -1,16 +1,19 @@ #ifndef MEASUREMENTSETTINGS_H #define MEASUREMENTSETTINGS_H -#include -#include -#include #include "scopy-gui_export.h" +#include +#include +#include + namespace scopy { -class SCOPY_GUI_EXPORT MeasurementSettings : public QWidget { +class SCOPY_GUI_EXPORT MeasurementSettings : public QWidget +{ Q_OBJECT public: - typedef enum { + typedef enum + { MPM_SORT_CHANNEL, MPM_SORT_TYPE } MeasurementSortingType; @@ -24,9 +27,7 @@ class SCOPY_GUI_EXPORT MeasurementSettings : public QWidget { void sortStats(MeasurementSortingType type); void enableMeasurementPanel(bool b); void enableStatsPanel(bool b); - - }; -} +} // namespace scopy #endif // MEASUREMENTSETTINGS_H diff --git a/gui/include/gui/widgets/menubigswitch.h b/gui/include/gui/widgets/menubigswitch.h index 7b10653b78..b2c3d5d1eb 100644 --- a/gui/include/gui/widgets/menubigswitch.h +++ b/gui/include/gui/widgets/menubigswitch.h @@ -1,16 +1,18 @@ #ifndef MENUBIGSWITCH_H #define MENUBIGSWITCH_H -#include -#include -#include #include +#include + #include +#include #include +#include namespace scopy { -class SCOPY_GUI_EXPORT MenuBigSwitch : public QWidget { +class SCOPY_GUI_EXPORT MenuBigSwitch : public QWidget +{ Q_OBJECT QWIDGET_PAINT_EVENT_HELPER public: @@ -23,5 +25,5 @@ class SCOPY_GUI_EXPORT MenuBigSwitch : public QWidget { private: CustomSwitch *m_switch; }; -} +} // namespace scopy #endif // MENUBIGSWITCH_H diff --git a/gui/include/gui/widgets/menucollapsesection.h b/gui/include/gui/widgets/menucollapsesection.h index 65372adbe8..5cc90487ac 100644 --- a/gui/include/gui/widgets/menucollapsesection.h +++ b/gui/include/gui/widgets/menucollapsesection.h @@ -2,33 +2,35 @@ #define MENUCOLLAPSESECTION_H #include -#include -#include -#include -#include #include #include +#include +#include + +#include #include +#include namespace scopy { -class SCOPY_GUI_EXPORT MenuCollapseSection : public QWidget { +class SCOPY_GUI_EXPORT MenuCollapseSection : public QWidget +{ Q_OBJECT QWIDGET_PAINT_EVENT_HELPER public: - typedef enum { + typedef enum + { MHCW_ARROW, MHCW_ONOFF, MHCW_NONE } MenuHeaderCollapseStyle; - MenuCollapseSection(QString title, - MenuCollapseSection::MenuHeaderCollapseStyle style = MHCW_ARROW, - QWidget *parent = nullptr); + MenuCollapseSection(QString title, MenuCollapseSection::MenuHeaderCollapseStyle style = MHCW_ARROW, + QWidget *parent = nullptr); ~MenuCollapseSection(); QAbstractButton *header(); - QVBoxLayout* contentLayout() const; + QVBoxLayout *contentLayout() const; private: QVBoxLayout *m_lay; @@ -37,19 +39,19 @@ class SCOPY_GUI_EXPORT MenuCollapseSection : public QWidget { QVBoxLayout *m_contLayout; }; - -class SCOPY_GUI_EXPORT MenuCollapseHeader : public QAbstractButton { +class SCOPY_GUI_EXPORT MenuCollapseHeader : public QAbstractButton +{ Q_OBJECT QWIDGET_PAINT_EVENT_HELPER public: MenuCollapseHeader(QString title, MenuCollapseSection::MenuHeaderCollapseStyle style, QWidget *parent); ~MenuCollapseHeader(); + private: QAbstractButton *m_ctrl; QLabel *m_label; QHBoxLayout *lay; - }; -} +} // namespace scopy #endif // MENUCOLLAPSESECTION_H diff --git a/gui/include/gui/widgets/menucombo.h b/gui/include/gui/widgets/menucombo.h index c0d1a3378f..fee949df32 100644 --- a/gui/include/gui/widgets/menucombo.h +++ b/gui/include/gui/widgets/menucombo.h @@ -1,16 +1,18 @@ #ifndef MENUCOMBO_H #define MENUCOMBO_H -#include -#include -#include -#include #include +#include #include +#include + +#include +#include namespace scopy { -class SCOPY_GUI_EXPORT MenuCombo : public QWidget { +class SCOPY_GUI_EXPORT MenuCombo : public QWidget +{ Q_OBJECT QWIDGET_PAINT_EVENT_HELPER public: @@ -25,7 +27,8 @@ class SCOPY_GUI_EXPORT MenuCombo : public QWidget { QComboBox *m_combo; }; -class SCOPY_GUI_EXPORT MenuComboWidget : public QWidget { +class SCOPY_GUI_EXPORT MenuComboWidget : public QWidget +{ Q_OBJECT QWIDGET_PAINT_EVENT_HELPER public: @@ -39,6 +42,6 @@ class SCOPY_GUI_EXPORT MenuComboWidget : public QWidget { MenuCombo *m_combo; QPen m_pen; }; -} +} // namespace scopy #endif // MENUCOMBO_H diff --git a/gui/include/gui/widgets/menucontrolbutton.h b/gui/include/gui/widgets/menucontrolbutton.h index 8e0b31e90a..976d5ca4ca 100644 --- a/gui/include/gui/widgets/menucontrolbutton.h +++ b/gui/include/gui/widgets/menucontrolbutton.h @@ -2,24 +2,28 @@ #define MENUCONTROLBUTTON_H #include "scopy-gui_export.h" -#include + #include -#include -#include #include -#include +#include #include +#include +#include + +#include namespace scopy { - class SCOPY_GUI_EXPORT MenuControlButton : public QAbstractButton { +class SCOPY_GUI_EXPORT MenuControlButton : public QAbstractButton +{ Q_OBJECT QWIDGET_PAINT_EVENT_HELPER public: - typedef enum { - CS_CIRCLE, - CS_SQUARE, - CS_BLUESQUARE, - CS_COLLAPSE, + typedef enum + { + CS_CIRCLE, + CS_SQUARE, + CS_BLUESQUARE, + CS_COLLAPSE, } CheckboxStyle; MenuControlButton(QWidget *parent = nullptr); @@ -32,9 +36,8 @@ namespace scopy { void setDoubleClickToOpenMenu(bool b); void setOpenMenuChecksThis(bool b); - QCheckBox* checkBox(); - QPushButton* button(); - + QCheckBox *checkBox(); + QPushButton *button(); Q_SIGNALS: void doubleClicked(); @@ -57,9 +60,8 @@ namespace scopy { void mousePressEvent(QMouseEvent *event) override; }; - - -class SCOPY_GUI_EXPORT CollapsableMenuControlButton : public QWidget { +class SCOPY_GUI_EXPORT CollapsableMenuControlButton : public QWidget +{ Q_OBJECT public: CollapsableMenuControlButton(QWidget *parent = nullptr); @@ -73,8 +75,7 @@ class SCOPY_GUI_EXPORT CollapsableMenuControlButton : public QWidget { QWidget *m_container; QVBoxLayout *m_contLayout; QVBoxLayout *m_lay; - }; -} +} // namespace scopy #endif // MENUCONTROLBUTTON_H diff --git a/gui/include/gui/widgets/menuheader.h b/gui/include/gui/widgets/menuheader.h index 0c3fe4bf4a..35f51beb1b 100644 --- a/gui/include/gui/widgets/menuheader.h +++ b/gui/include/gui/widgets/menuheader.h @@ -1,13 +1,15 @@ #ifndef MENUHEADER_H #define MENUHEADER_H -#include +#include #include + +#include #include -#include namespace scopy { -class SCOPY_GUI_EXPORT MenuHeaderWidget : public QWidget { +class SCOPY_GUI_EXPORT MenuHeaderWidget : public QWidget +{ Q_OBJECT QWIDGET_PAINT_EVENT_HELPER public: @@ -22,6 +24,6 @@ class SCOPY_GUI_EXPORT MenuHeaderWidget : public QWidget { QFrame *m_line; QPen m_pen; }; -} +} // namespace scopy #endif // MENUHEADER_H diff --git a/gui/include/gui/widgets/menulineedit.h b/gui/include/gui/widgets/menulineedit.h index 8b41d508f5..8e9cc41ce1 100644 --- a/gui/include/gui/widgets/menulineedit.h +++ b/gui/include/gui/widgets/menulineedit.h @@ -1,15 +1,17 @@ #ifndef MENULINEEDIT_H #define MENULINEEDIT_H -#include -#include -#include #include #include +#include + +#include #include +#include namespace scopy { -class SCOPY_GUI_EXPORT MenuLineEdit : public QWidget { +class SCOPY_GUI_EXPORT MenuLineEdit : public QWidget +{ Q_OBJECT QWIDGET_PAINT_EVENT_HELPER public: @@ -22,6 +24,6 @@ class SCOPY_GUI_EXPORT MenuLineEdit : public QWidget { private: QLineEdit *m_edit; }; -} +} // namespace scopy #endif // MENULINEEDIT_H diff --git a/gui/include/gui/widgets/menuonoffswitch.h b/gui/include/gui/widgets/menuonoffswitch.h index fa094d09a2..d160090ff1 100644 --- a/gui/include/gui/widgets/menuonoffswitch.h +++ b/gui/include/gui/widgets/menuonoffswitch.h @@ -1,16 +1,18 @@ #ifndef MENUONOFFSWITCH_H #define MENUONOFFSWITCH_H -#include -#include -#include -#include #include +#include +#include + +#include #include +#include namespace scopy { -class SCOPY_GUI_EXPORT MenuOnOffSwitch : public QWidget { +class SCOPY_GUI_EXPORT MenuOnOffSwitch : public QWidget +{ Q_OBJECT QWIDGET_PAINT_EVENT_HELPER public: @@ -24,6 +26,6 @@ class SCOPY_GUI_EXPORT MenuOnOffSwitch : public QWidget { QLabel *m_label; QAbstractButton *m_switch; }; -} +} // namespace scopy #endif // MENUONOFFSWITCH_H diff --git a/gui/include/gui/widgets/menusectionwidget.h b/gui/include/gui/widgets/menusectionwidget.h index dc1bc06379..6040745dda 100644 --- a/gui/include/gui/widgets/menusectionwidget.h +++ b/gui/include/gui/widgets/menusectionwidget.h @@ -1,13 +1,15 @@ #ifndef MENUSECTIONWIDGET_H #define MENUSECTIONWIDGET_H +#include +#include +#include + #include #include -#include -#include -#include namespace scopy { -class SCOPY_GUI_EXPORT MenuSectionWidget : public QWidget { +class SCOPY_GUI_EXPORT MenuSectionWidget : public QWidget +{ Q_OBJECT QWIDGET_PAINT_EVENT_HELPER public: @@ -19,10 +21,11 @@ class SCOPY_GUI_EXPORT MenuSectionWidget : public QWidget { QVBoxLayout *m_layout; }; -class SCOPY_GUI_EXPORT MenuVScrollArea : public QScrollArea { +class SCOPY_GUI_EXPORT MenuVScrollArea : public QScrollArea +{ Q_OBJECT -// QWIDGET_PAINT_EVENT_HELPER - public: + // QWIDGET_PAINT_EVENT_HELPER +public: MenuVScrollArea(QWidget *parent = nullptr); ~MenuVScrollArea(); QVBoxLayout *contentLayout() const; @@ -31,5 +34,5 @@ class SCOPY_GUI_EXPORT MenuVScrollArea : public QScrollArea { QVBoxLayout *m_layout; }; -} +} // namespace scopy #endif // MENUSECTIONWIDGET_H diff --git a/gui/include/gui/widgets/pagenavigationwidget.h b/gui/include/gui/widgets/pagenavigationwidget.h index 5ce53e5543..f68d3132da 100644 --- a/gui/include/gui/widgets/pagenavigationwidget.h +++ b/gui/include/gui/widgets/pagenavigationwidget.h @@ -1,12 +1,14 @@ #ifndef NAVIGATIONWIDGET_H #define NAVIGATIONWIDGET_H +#include "scopy-gui_export.h" + #include #include -#include "scopy-gui_export.h" namespace scopy { -class SCOPY_GUI_EXPORT PageNavigationWidget : public QWidget { +class SCOPY_GUI_EXPORT PageNavigationWidget : public QWidget +{ Q_OBJECT public: PageNavigationWidget(bool hasHome = false, bool hasOpen = false, QWidget *parent = nullptr); @@ -27,5 +29,5 @@ class SCOPY_GUI_EXPORT PageNavigationWidget : public QWidget { void initUI(QWidget *parent); }; -} +} // namespace scopy #endif // NAVIGATIONWIDGET_H diff --git a/gui/include/gui/widgets/plotcursorreadouts.h b/gui/include/gui/widgets/plotcursorreadouts.h index dcb7104921..e642675a92 100644 --- a/gui/include/gui/widgets/plotcursorreadouts.h +++ b/gui/include/gui/widgets/plotcursorreadouts.h @@ -1,11 +1,12 @@ #ifndef PLOTCURSORREADOUTS_H #define PLOTCURSORREADOUTS_H -#include +#include #include -#include +#include + #include -#include +#include #include namespace scopy { @@ -31,14 +32,14 @@ public Q_SLOTS: private: QWidget *vert_contents; QWidget *horiz_contents; - double v1,v2,h1,h2; - QLabel *V1_val,*V2_val,*H1_val,*H2_val; + double v1, v2, h1, h2; + QLabel *V1_val, *V2_val, *H1_val, *H2_val; QLabel *deltaV_val, *deltaH_val; QLabel *invDeltaH_val; PrefixFormatter *formatter; void initContent(); }; -} +} // namespace scopy #endif // PLOTCURSORREADOUTS_H diff --git a/gui/include/gui/widgets/plotinfo.h b/gui/include/gui/widgets/plotinfo.h index ea6bd843e6..86a3626a3d 100644 --- a/gui/include/gui/widgets/plotinfo.h +++ b/gui/include/gui/widgets/plotinfo.h @@ -1,17 +1,20 @@ #ifndef PLOTINFO_H #define PLOTINFO_H -#include #include "buffer_previewer.hpp" +#include "plotwidget.h" + #include -#include +#include + #include #include -#include "plotwidget.h" +#include namespace scopy { -class SCOPY_GUI_EXPORT TimePlotHDivInfo : public QLabel { +class SCOPY_GUI_EXPORT TimePlotHDivInfo : public QLabel +{ Q_OBJECT public: TimePlotHDivInfo(QWidget *parent = nullptr); @@ -24,7 +27,8 @@ public Q_SLOTS: MetricPrefixFormatter *m_mpf; }; -class SCOPY_GUI_EXPORT TimePlotSamplingInfo : public QLabel { +class SCOPY_GUI_EXPORT TimePlotSamplingInfo : public QLabel +{ Q_OBJECT public: TimePlotSamplingInfo(QWidget *parent = nullptr); @@ -37,23 +41,22 @@ public Q_SLOTS: MetricPrefixFormatter *m_mpf; }; - -class SCOPY_GUI_EXPORT TimePlotStatusInfo : public QLabel { +class SCOPY_GUI_EXPORT TimePlotStatusInfo : public QLabel +{ Q_OBJECT public: TimePlotStatusInfo(QWidget *parent = nullptr); virtual ~TimePlotStatusInfo(); }; -class SCOPY_GUI_EXPORT TimePlotVDivInfo : public QWidget { +class SCOPY_GUI_EXPORT TimePlotVDivInfo : public QWidget +{}; -}; - - -class SCOPY_GUI_EXPORT PlotBufferPreviewerController : public QWidget { +class SCOPY_GUI_EXPORT PlotBufferPreviewerController : public QWidget +{ Q_OBJECT public: - explicit PlotBufferPreviewerController(PlotWidget* p, BufferPreviewer *b, QWidget *parent = nullptr); + explicit PlotBufferPreviewerController(PlotWidget *p, BufferPreviewer *b, QWidget *parent = nullptr); ~PlotBufferPreviewerController(); void updateDataLimits(double min, double max); @@ -67,32 +70,30 @@ public Q_SLOTS: double m_bufferPrevData; void setupBufferPreviewer(); - PlotWidget* m_plot; - BufferPreviewer* m_bufferPreviewer; - - + PlotWidget *m_plot; + BufferPreviewer *m_bufferPreviewer; }; -class SCOPY_GUI_EXPORT TimePlotInfo : public QWidget { +class SCOPY_GUI_EXPORT TimePlotInfo : public QWidget +{ Q_OBJECT public: - TimePlotInfo(PlotWidget* plot, QWidget *parent = nullptr); + TimePlotInfo(PlotWidget *plot, QWidget *parent = nullptr); virtual ~TimePlotInfo(); public Q_SLOTS: void update(PlotSamplingInfo info); void updateBufferPreviewer(); + private: - PlotWidget* m_plot; + PlotWidget *m_plot; TimePlotHDivInfo *m_hdiv; - TimePlotSamplingInfo* m_sampling; + TimePlotSamplingInfo *m_sampling; TimePlotStatusInfo *m_status; PlotBufferPreviewerController *m_bufferController; - AnalogBufferPreviewer* m_bufferPreviewer; - - + AnalogBufferPreviewer *m_bufferPreviewer; }; -} +} // namespace scopy #endif // PLOTINFO_H diff --git a/gui/include/gui/widgets/popupwidget.h b/gui/include/gui/widgets/popupwidget.h index cb98c9a7a9..3bb90921ef 100644 --- a/gui/include/gui/widgets/popupwidget.h +++ b/gui/include/gui/widgets/popupwidget.h @@ -18,22 +18,23 @@ * along with this program. If not, see . */ - #ifndef SCOPY_POPUPWIDGET_H #define SCOPY_POPUPWIDGET_H -#include +#include "scopy-gui_export.h" +#include "tintedoverlay.h" + #include #include #include -#include "tintedoverlay.h" -#include "scopy-gui_export.h" +#include namespace scopy { -class SCOPY_GUI_EXPORT PopupWidget : public QWidget { +class SCOPY_GUI_EXPORT PopupWidget : public QWidget +{ Q_OBJECT public: - explicit PopupWidget(QWidget* parent = nullptr); + explicit PopupWidget(QWidget *parent = nullptr); ~PopupWidget(); void initUI(); @@ -45,13 +46,13 @@ class SCOPY_GUI_EXPORT PopupWidget : public QWidget { void enableTintedOverlay(bool enable = true); QString getDescription(); - void setDescription(const QString& description); + void setDescription(const QString &description); QString getTitle(); - void setTitle(const QString& title); + void setTitle(const QString &title); - QPushButton* getExitBtn(); - QPushButton* getContinueBtn(); + QPushButton *getExitBtn(); + QPushButton *getContinueBtn(); Q_SIGNALS: void continueButtonClicked(); @@ -65,6 +66,6 @@ class SCOPY_GUI_EXPORT PopupWidget : public QWidget { QPushButton *m_exitButton; QPushButton *m_continueButton; }; -} +} // namespace scopy -#endif //SCOPY_POPUPWIDGET_H +#endif // SCOPY_POPUPWIDGET_H diff --git a/gui/include/gui/widgets/toolbuttons.h b/gui/include/gui/widgets/toolbuttons.h index 5fa81d2154..37a1ed5eb7 100644 --- a/gui/include/gui/widgets/toolbuttons.h +++ b/gui/include/gui/widgets/toolbuttons.h @@ -1,21 +1,25 @@ #ifndef TOOLBUTTONS_H #define TOOLBUTTONS_H -#include -#include -#include #include "semiexclusivebuttongroup.h" + +#include + #include +#include +#include namespace scopy { -class SCOPY_GUI_EXPORT PrintBtn : public QPushButton { +class SCOPY_GUI_EXPORT PrintBtn : public QPushButton +{ Q_OBJECT public: PrintBtn(QWidget *parent = nullptr); }; -class SCOPY_GUI_EXPORT OpenLastMenuBtn : public QPushButton { +class SCOPY_GUI_EXPORT OpenLastMenuBtn : public QPushButton +{ Q_OBJECT public: OpenLastMenuBtn(MenuHAnim *menu, bool opened, QWidget *parent = nullptr); @@ -27,31 +31,34 @@ class SCOPY_GUI_EXPORT OpenLastMenuBtn : public QPushButton { }; /* Refactor these as Stylehelper ? */ -class SCOPY_GUI_EXPORT GearBtn : public QPushButton { +class SCOPY_GUI_EXPORT GearBtn : public QPushButton +{ Q_OBJECT public: GearBtn(QWidget *parent = nullptr); }; -class SCOPY_GUI_EXPORT InfoBtn : public QPushButton { +class SCOPY_GUI_EXPORT InfoBtn : public QPushButton +{ Q_OBJECT public: InfoBtn(QWidget *parent = nullptr); }; - -class SCOPY_GUI_EXPORT RunBtn : public QPushButton { +class SCOPY_GUI_EXPORT RunBtn : public QPushButton +{ Q_OBJECT public: - RunBtn (QWidget *parent = nullptr); + RunBtn(QWidget *parent = nullptr); }; -class SCOPY_GUI_EXPORT SingleShotBtn : public QPushButton { +class SCOPY_GUI_EXPORT SingleShotBtn : public QPushButton +{ Q_OBJECT public: - SingleShotBtn (QWidget *parent = nullptr); + SingleShotBtn(QWidget *parent = nullptr); }; -} +} // namespace scopy #endif diff --git a/gui/include/gui/widgets/verticalchannelmanager.h b/gui/include/gui/widgets/verticalchannelmanager.h index 11434a1fe4..d3a9d56a0f 100644 --- a/gui/include/gui/widgets/verticalchannelmanager.h +++ b/gui/include/gui/widgets/verticalchannelmanager.h @@ -1,22 +1,24 @@ #ifndef VERTICALCHANNELMANAGER_H #define VERTICALCHANNELMANAGER_H -#include #include +#include + #include namespace scopy { -class SCOPY_GUI_EXPORT VerticalChannelManager : public QWidget { +class SCOPY_GUI_EXPORT VerticalChannelManager : public QWidget +{ Q_OBJECT public: VerticalChannelManager(QWidget *parent = nullptr); ~VerticalChannelManager(); - void add(QWidget* ch); + void add(QWidget *ch); private: QSpacerItem *spacer; QVBoxLayout *lay; }; -} +} // namespace scopy #endif // VERTICALCHANNELMANAGER_H diff --git a/gui/include/gui/x_axis_scale_zoomer.h b/gui/include/gui/x_axis_scale_zoomer.h index d066acd85d..9e4c4c4f44 100644 --- a/gui/include/gui/x_axis_scale_zoomer.h +++ b/gui/include/gui/x_axis_scale_zoomer.h @@ -21,9 +21,10 @@ #ifndef X_AXIS_SCALE_ZOOMER_H #define X_AXIS_SCALE_ZOOMER_H -#include #include "osc_scale_zoomer.h" +#include + namespace scopy { class XAxisScaleZoomer : public OscScaleZoomer { @@ -33,8 +34,8 @@ class XAxisScaleZoomer : public OscScaleZoomer ~XAxisScaleZoomer(); protected: - virtual void zoom(const QRectF&); - virtual QwtText trackerText( const QPoint& p ) const; + virtual void zoom(const QRectF &); + virtual QwtText trackerText(const QPoint &p) const; }; -} +} // namespace scopy #endif // X_AXIS_SCALE_ZOOMER_H diff --git a/gui/res/stylesheets/templates/values.h b/gui/res/stylesheets/templates/values.h index 5f2b3486b7..de84a4add3 100644 --- a/gui/res/stylesheets/templates/values.h +++ b/gui/res/stylesheets/templates/values.h @@ -1,7 +1,7 @@ #ifdef __ANDROID__ - #define INDICATOR_SIZE 18px +#define INDICATOR_SIZE 18px #endif #ifndef __ANDROID__ - #define INDICATOR_SIZE 14px +#define INDICATOR_SIZE 14px #endif diff --git a/gui/sigrok-gui/CMakeLists.txt b/gui/sigrok-gui/CMakeLists.txt index 62b1bc2ed1..455d7517a1 100644 --- a/gui/sigrok-gui/CMakeLists.txt +++ b/gui/sigrok-gui/CMakeLists.txt @@ -4,8 +4,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -26,58 +25,64 @@ pkg_check_modules(GLIB REQUIRED glib-2.0) pkg_check_modules(LIBSIGROK_DECODE REQUIRED libsigrokdecode) pkg_get_variable(LIBSIGROK_DECODERS_DIR libsigrokdecode decodersdir) -FILE(GLOB SRC_LIST src/*.cpp src/*.cc src/binding/*.cpp src/prop/*.cpp) -FILE(GLOB HEADER_LIST +file( + GLOB + SRC_LIST + src/*.cpp + src/*.cc + src/binding/*.cpp + src/prop/*.cpp +) +file( + GLOB + HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp include/${SCOPY_MODULE}/binding/*.hpp - include/${SCOPY_MODULE}/prop/*.hpp ) + include/${SCOPY_MODULE}/prop/*.hpp +) -FILE(GLOB UI_LIST ui/*.ui) +file(GLOB UI_LIST ui/*.ui) if(ENABLE_TESTING) - add_subdirectory(test) + add_subdirectory(test) endif() -configure_file(include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h.cmakein - ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h @ONLY) - -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} +configure_file( + include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h.cmakein + ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h @ONLY ) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) + find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Widgets REQUIRED) message(STATUS "Building " ${PROJECT_NAME}) -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) -target_include_directories(${PROJECT_NAME} INTERFACE - ${CMAKE_CURRENT_SOURCE_DIR}/include - ${LIBSIGROK_DECODE_INCLUDE_DIRS}) +target_include_directories( + ${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include ${LIBSIGROK_DECODE_INCLUDE_DIRS} +) -target_include_directories(${PROJECT_NAME} PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}include/${SCOPY_MODULE}/ - ${CMAKE_CURRENT_SOURCE_DIR}include/${SCOPY_MODULE}/binding - ${CMAKE_CURRENT_SOURCE_DIR}include/${SCOPY_MODULE}/prop - ${LIBSIGROK_DECODE_INCLUDE_DIRS} - scopy-gui) +target_include_directories( + ${PROJECT_NAME} + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}include/${SCOPY_MODULE}/ + ${CMAKE_CURRENT_SOURCE_DIR}include/${SCOPY_MODULE}/binding + ${CMAKE_CURRENT_SOURCE_DIR}include/${SCOPY_MODULE}/prop + ${LIBSIGROK_DECODE_INCLUDE_DIRS} + scopy-gui +) target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}) -target_link_libraries(${PROJECT_NAME} PUBLIC - Qt${QT_VERSION_MAJOR}::Widgets - scopy-gui - ${LIBSIGROK_DECODE_LINK_LIBRARIES} +target_link_libraries( + ${PROJECT_NAME} PUBLIC Qt${QT_VERSION_MAJOR}::Widgets scopy-gui ${LIBSIGROK_DECODE_LINK_LIBRARIES} ) set(SCOPY_SIGROK_GUI ON PARENT_SCOPE) -install(TARGETS ${PROJECT_NAME} - LIBRARY DESTINATION ${SCOPY_DLL_PATH} - RUNTIME DESTINATION ${SCOPY_DLL_PATH}) \ No newline at end of file +install(TARGETS ${PROJECT_NAME} LIBRARY DESTINATION ${SCOPY_DLL_PATH} RUNTIME DESTINATION ${SCOPY_DLL_PATH}) diff --git a/gui/sigrok-gui/include/sigrok-gui/annotation.h b/gui/sigrok-gui/include/sigrok-gui/annotation.h index dc16b605a6..94d0f7fdfa 100644 --- a/gui/sigrok-gui/include/sigrok-gui/annotation.h +++ b/gui/sigrok-gui/include/sigrok-gui/annotation.h @@ -37,16 +37,15 @@ * along with this program. If not, see . */ - #ifndef ANNOTATION_H #define ANNOTATION_H -#include -#include +#include "scopy-sigrok-gui_export.h" #include -#include "scopy-sigrok-gui_export.h" +#include +#include struct srd_proto_data; class Row; @@ -56,28 +55,27 @@ using std::vector; class SCOPY_SIGROK_GUI_EXPORT Annotation { public: - typedef uint32_t Class; + typedef uint32_t Class; public: - Annotation() = default; - Annotation(const Annotation &other) = default; - Annotation(const srd_proto_data *const pdata, const Row *row); + Annotation() = default; + Annotation(const Annotation &other) = default; + Annotation(const srd_proto_data *const pdata, const Row *row); - uint64_t start_sample() const; - uint64_t end_sample() const; - Class ann_class() const; - const vector& annotations() const; - const Row* row() const; + uint64_t start_sample() const; + uint64_t end_sample() const; + Class ann_class() const; + const vector &annotations() const; + const Row *row() const; - bool operator<(const Annotation &other) const; + bool operator<(const Annotation &other) const; private: - uint64_t start_sample_; - uint64_t end_sample_; - Class ann_class_; - vector annotations_; - const Row *row_; - + uint64_t start_sample_; + uint64_t end_sample_; + Class ann_class_; + vector annotations_; + const Row *row_; }; #endif // ANNOTATION_H diff --git a/gui/sigrok-gui/include/sigrok-gui/annotationcurve.h b/gui/sigrok-gui/include/sigrok-gui/annotationcurve.h index d490853db1..728561f734 100644 --- a/gui/sigrok-gui/include/sigrok-gui/annotationcurve.h +++ b/gui/sigrok-gui/include/sigrok-gui/annotationcurve.h @@ -18,47 +18,43 @@ * along with this program. If not, see . */ - #ifndef ANNOTATIONCURVE_H #define ANNOTATIONCURVE_H +#include "annotation.h" +#include "genericlogicplotcurve.h" +#include "row.h" +#include "rowdata.h" +#include "scopy-sigrok-gui_export.h" + +#include #include #include - #include #include -#include - -#include "annotation.h" -#include "row.h" -#include "rowdata.h" -#include "genericlogicplotcurve.h" -#include "scopy-sigrok-gui_export.h" - namespace scopy { namespace logic { class Decoder; } -} - +} // namespace scopy namespace scopy { namespace bind { class Decoder; } -} +} // namespace scopy namespace scopy { class AnnotationDecoder; - -struct AnnotationQueryResult { - uint64_t index; - const Annotation* ann; - inline bool isValid() const { return ann != nullptr; } +struct AnnotationQueryResult +{ + uint64_t index; + const Annotation *ann; + inline bool isValid() const { return ann != nullptr; } }; class SCOPY_SIGROK_GUI_EXPORT AnnotationCurve : public GenericLogicPlotCurve @@ -71,27 +67,27 @@ class SCOPY_SIGROK_GUI_EXPORT AnnotationCurve : public GenericLogicPlotCurve Q_SIGNALS: void decoderMenuChanged(); - // Emitted when an annotation is clicked - void annotationClicked(AnnotationQueryResult result); + // Emitted when an annotation is clicked + void annotationClicked(AnnotationQueryResult result); public: - static void annotationCallback(srd_proto_data *pdata, void *annotationCurve); + static void annotationCallback(srd_proto_data *pdata, void *annotationCurve); - virtual void dataAvailable(uint64_t from, uint64_t to, uint16_t *data) override; + virtual void dataAvailable(uint64_t from, uint64_t to, uint16_t *data) override; - void setClassRows(const std::map, Row> &classRows); - void setAnnotationRows(const std::map &annotationRows); - const std::map& getAnnotationRows() const; + void setClassRows(const std::map, Row> &classRows); + void setAnnotationRows(const std::map &annotationRows); + const std::map &getAnnotationRows() const; - void sort_rows(); + void sort_rows(); - uint64_t getMaxAnnotationCount(int index = -1); + uint64_t getMaxAnnotationCount(int index = -1); - void newAnnotations(); + void newAnnotations(); - virtual void reset() override; + virtual void reset() override; - QWidget * getCurrentDecoderStackMenu(); + QWidget *getCurrentDecoderStackMenu(); void stackDecoder(std::shared_ptr decoder); std::vector> getDecoderStack(); @@ -101,72 +97,61 @@ class SCOPY_SIGROK_GUI_EXPORT AnnotationCurve : public GenericLogicPlotCurve AnnotationDecoder *getAnnotationDecoder(); std::vector> getDecoderBindings(); - // Get the annotation at the given point - AnnotationQueryResult annotationAt(const QPointF& p) const; - bool testHit(const QPointF& p) const override; + // Get the annotation at the given point + AnnotationQueryResult annotationAt(const QPointF &p) const; + bool testHit(const QPointF &p) const override; - void drawAnnotation(int row, const Annotation &ann, QPainter *painter, - const QwtScaleMap &xMap, const QwtScaleMap &yMap, - const QRectF &canvasRect, const QwtPointMapper &mapper, - const QwtInterval &interval, const QSizeF &titleSize) const; + void drawAnnotation(int row, const Annotation &ann, QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, const QRectF &canvasRect, const QwtPointMapper &mapper, + const QwtInterval &interval, const QSizeF &titleSize) const; - void drawBlock(int row, uint64_t start, uint64_t end, QPainter *painter, - const QwtScaleMap &xMap, const QwtScaleMap &yMap, - const QRectF &canvasRect, const QwtPointMapper &mapper) const; + void drawBlock(int row, uint64_t start, uint64_t end, QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, const QRectF &canvasRect, const QwtPointMapper &mapper) const; - void drawAnnotationInfo(int row, uint64_t start, uint64_t end, QPainter *painter, - const QwtScaleMap &xMap, const QwtScaleMap &yMap, - const QRectF &canvasRect) const; + void drawAnnotationInfo(int row, uint64_t start, uint64_t end, QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, const QRectF &canvasRect) const; - const double m_infoHeight = 17 * 2; + const double m_infoHeight = 17 * 2; - int getState(); + int getState(); - QString fromTitleToRowType(QString title) const; + QString fromTitleToRowType(QString title) const; - void setState(int st); + void setState(int st); protected: - void drawLines( QPainter *painter, - const QwtScaleMap &xMap, const QwtScaleMap &yMap, - const QRectF &canvasRect, int from, int to ) const override; + void drawLines(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &canvasRect, + int from, int to) const override; private: - void fillAnnotationCurve(int row, uint32_t annClass, QPainter *painter, - const QwtScaleMap &xMap, const QwtScaleMap &yMap, - const QRectF &canvasRect, QPolygonF &polygon) const; - - void closePolyline(int row, uint32_t annClass, QPainter *painter, - const QwtScaleMap &xMap, const QwtScaleMap &yMap, - QPolygonF &polygon ) const; + void fillAnnotationCurve(int row, uint32_t annClass, QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, const QRectF &canvasRect, QPolygonF &polygon) const; - void drawTwoSampleAnnotation(int row, const Annotation &ann, QPainter *painter, - const QwtScaleMap &xMap, const QwtScaleMap &yMap, - const QRectF &canvasRect, const QwtPointMapper &mapper, - const QwtInterval &interval, const QSizeF &titleSize) const; + void closePolyline(int row, uint32_t annClass, QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, QPolygonF &polygon) const; - void drawOneSampleAnnotation(int row, const Annotation &ann, QPainter *painter, - const QwtScaleMap &xMap, const QwtScaleMap &yMap, - const QRectF &canvasRect, const QwtPointMapper &mapper, - const QwtInterval &interval, const QSizeF &titleSize) const; - - QString formatSeconds(double time) const; + void drawTwoSampleAnnotation(int row, const Annotation &ann, QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, const QRectF &canvasRect, const QwtPointMapper &mapper, + const QwtInterval &interval, const QSizeF &titleSize) const; + void drawOneSampleAnnotation(int row, const Annotation &ann, QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, const QRectF &canvasRect, const QwtPointMapper &mapper, + const QwtInterval &interval, const QSizeF &titleSize) const; + QString formatSeconds(double time) const; private: + AnnotationDecoder *m_annotationDecoder; + mutable std::mutex m_mutex; - AnnotationDecoder *m_annotationDecoder; - mutable std::mutex m_mutex; - - std::map, Row> m_classRows; - std::map m_annotationRows; + std::map, Row> m_classRows; + std::map m_annotationRows; - std::vector> m_bindings; + std::vector> m_bindings; - mutable int m_visibleRows; - mutable int state = -1; + mutable int m_visibleRows; + mutable int state = -1; }; -} +} // namespace scopy #endif // ANNOTATIONCURVE_H diff --git a/gui/sigrok-gui/include/sigrok-gui/annotationdecoder.h b/gui/sigrok-gui/include/sigrok-gui/annotationdecoder.h index 34734e49cc..285e16f082 100644 --- a/gui/sigrok-gui/include/sigrok-gui/annotationdecoder.h +++ b/gui/sigrok-gui/include/sigrok-gui/annotationdecoder.h @@ -18,76 +18,75 @@ * along with this program. If not, see . */ - #ifndef ANNOTATIONDECODER_H #define ANNOTATIONDECODER_H +#include "annotationcurve.h" +#include "decoder.h" +#include "scopy-sigrok-gui_export.h" + +#include + #include +#include +#include #include -#include #include -#include #include -#include -#include - -#include - -#include "annotationcurve.h" -#include "decoder.h" -#include "scopy-sigrok-gui_export.h" +#include +#include namespace scopy { class SCOPY_SIGROK_GUI_EXPORT AnnotationDecoder { public: - AnnotationDecoder(AnnotationCurve *annotationCurve, std::shared_ptr initialDecoder); - ~AnnotationDecoder(); + AnnotationDecoder(AnnotationCurve *annotationCurve, std::shared_ptr initialDecoder); + ~AnnotationDecoder(); - void stackDecoder(std::shared_ptr decoder); - void unstackDecoder(std::shared_ptr decoder); + void stackDecoder(std::shared_ptr decoder); + void unstackDecoder(std::shared_ptr decoder); - void startDecode(); - void stopDecode(); + void startDecode(); + void stopDecode(); - void dataAvailable(uint64_t from, uint64_t to, uint16_t *data); + void dataAvailable(uint64_t from, uint64_t to, uint16_t *data); - std::vector> getDecoderStack(); + std::vector> getDecoderStack(); - void assignChannel(uint16_t chId, uint16_t bitId); - void unassignChannel(uint16_t chId); + void assignChannel(uint16_t chId, uint16_t bitId); + void unassignChannel(uint16_t chId); - std::vector getDecoderChannels(); + std::vector getDecoderChannels(); - void reset(); + void reset(); - int getNrOfChannels() const; -private: - void stackChanged(); + int getNrOfChannels() const; - void decodeProc(); +private: + void stackChanged(); + void decodeProc(); private: - AnnotationCurve *m_annotationCurve; - uint64_t m_lastSample; - uint16_t *m_data; - - struct srd_session *m_srdSession; - std::vector> m_stack; - std::map, Row> m_class_rows; - std::map m_annotation_rows; - std::vector m_channels; - - std::thread *m_decodeThread; - std::atomic m_decodeCanceled; - std::mutex m_newDataMutex; - std::condition_variable m_newDataCv; - static std::mutex g_sessionMutex; - std::queue> m_newDataQueue; - void initDecoderChannels(); + AnnotationCurve *m_annotationCurve; + uint64_t m_lastSample; + uint16_t *m_data; + + struct srd_session *m_srdSession; + std::vector> m_stack; + std::map, Row> m_class_rows; + std::map m_annotation_rows; + std::vector m_channels; + + std::thread *m_decodeThread; + std::atomic m_decodeCanceled; + std::mutex m_newDataMutex; + std::condition_variable m_newDataCv; + static std::mutex g_sessionMutex; + std::queue> m_newDataQueue; + void initDecoderChannels(); }; -} +} // namespace scopy #endif // ANNOTATIONDECODER_H diff --git a/gui/sigrok-gui/include/sigrok-gui/binding/binding.hpp b/gui/sigrok-gui/include/sigrok-gui/binding/binding.hpp index dbddbe2445..b251af3cdd 100644 --- a/gui/sigrok-gui/include/sigrok-gui/binding/binding.hpp +++ b/gui/sigrok-gui/include/sigrok-gui/binding/binding.hpp @@ -37,19 +37,19 @@ * along with this program. If not, see . */ - #ifndef PULSEVIEW_PV_BINDING_BINDING_HPP #define PULSEVIEW_PV_BINDING_BINDING_HPP +#include "scopy-sigrok-gui_export.h" + +#include +#include + #include #include #include #include -#include -#include -#include "scopy-sigrok-gui_export.h" - using std::map; using std::shared_ptr; using std::vector; @@ -66,18 +66,18 @@ class Property; namespace bind { -class SCOPY_SIGROK_GUI_EXPORT Binding: public QObject +class SCOPY_SIGROK_GUI_EXPORT Binding : public QObject { Q_OBJECT public: - const vector< shared_ptr >& properties(); + const vector> &properties(); void commit(); void add_properties_to_form(QFormLayout *layout, bool auto_commit = false); - QWidget* get_property_form(QWidget *parent, bool auto_commit = false); + QWidget *get_property_form(QWidget *parent, bool auto_commit = false); void update_property_widgets(); @@ -87,11 +87,11 @@ protected Q_SLOTS: void on_help_clicked(); protected: - vector< shared_ptr > properties_; - map help_labels_; + vector> properties_; + map help_labels_; }; -} // namespace binding -} // namespace pv +} // namespace bind +} // namespace scopy #endif // PULSEVIEW_PV_BINDING_BINDING_HPP diff --git a/gui/sigrok-gui/include/sigrok-gui/binding/decoder.hpp b/gui/sigrok-gui/include/sigrok-gui/binding/decoder.hpp index db1e6ff9fd..2b3a917052 100644 --- a/gui/sigrok-gui/include/sigrok-gui/binding/decoder.hpp +++ b/gui/sigrok-gui/include/sigrok-gui/binding/decoder.hpp @@ -37,15 +37,12 @@ * along with this program. If not, see . */ - #ifndef PULSEVIEW_PV_BINDING_DECODER_HPP #define PULSEVIEW_PV_BINDING_DECODER_HPP -#include "binding.hpp" - -#include "../prop/property.hpp" - #include "../annotationdecoder.h" +#include "../prop/property.hpp" +#include "binding.hpp" #include "scopy-sigrok-gui_export.h" using std::shared_ptr; @@ -56,7 +53,7 @@ namespace scopy { namespace logic { class Decoder; } -} +} // namespace scopy namespace scopy { @@ -65,14 +62,15 @@ namespace bind { class SCOPY_SIGROK_GUI_EXPORT Decoder : public Binding { public: - Decoder(scopy::AnnotationDecoder *annDec, - shared_ptr decoder); + Decoder(scopy::AnnotationDecoder *annDec, shared_ptr decoder); static QVariant gVariantToQVariant(GVariant *value); + private: - static shared_ptr bind_enum(const QString &name, - const QString &desc, const srd_decoder_option *option, - prop::Property::Getter getter, prop::Property::Setter setter); + static shared_ptr bind_enum(const QString &name, const QString &desc, + const srd_decoder_option *option, + prop::Property::Getter getter, + prop::Property::Setter setter); QVariant getter(const char *id); @@ -80,10 +78,10 @@ class SCOPY_SIGROK_GUI_EXPORT Decoder : public Binding private: scopy::AnnotationDecoder *m_annDecoder; - shared_ptr decoder_; + shared_ptr decoder_; }; -} // namespace binding -} // namespace pv +} // namespace bind +} // namespace scopy #endif // PULSEVIEW_PV_BINDING_DECODER_HPP diff --git a/gui/sigrok-gui/include/sigrok-gui/decoder.h b/gui/sigrok-gui/include/sigrok-gui/decoder.h index 9012c842bc..7a516d819d 100644 --- a/gui/sigrok-gui/include/sigrok-gui/decoder.h +++ b/gui/sigrok-gui/include/sigrok-gui/decoder.h @@ -37,28 +37,26 @@ * along with this program. If not, see . */ - #ifndef DECODER_H #define DECODER_H -#include -#include -#include -#include - -#include -#include -#include - #include "annotation.h" #include "row.h" #include "rowdata.h" #include "scopy-sigrok-gui_export.h" +#include + +#include +#include +#include +#include +#include + using std::map; +using std::shared_ptr; using std::string; using std::vector; -using std::shared_ptr; struct srd_decoder; struct srd_decoder_inst; @@ -69,26 +67,26 @@ namespace scopy { namespace logic { class Decoder; } -} +} // namespace scopy struct SCOPY_SIGROK_GUI_EXPORT DecodeChannel { - uint16_t id; ///< Global numerical ID for the decode channels in the stack - uint16_t bit_id; ///< Tells which bit within a sample represents this channel - const bool is_optional; - bool assigned_signal; - const QString name, desc; - int initial_pin_state; + uint16_t id; ///< Global numerical ID for the decode channels in the stack + uint16_t bit_id; ///< Tells which bit within a sample represents this channel + const bool is_optional; + bool assigned_signal; + const QString name, desc; + int initial_pin_state; const shared_ptr decoder_; - const srd_channel *pdch_; + const srd_channel *pdch_; }; struct SCOPY_SIGROK_GUI_EXPORT DecodeSegment { - map annotation_rows; -// pv::util::Timestamp start_time; - double samplerate; - int64_t samples_decoded_incl, samples_decoded_excl; + map annotation_rows; + // pv::util::Timestamp start_time; + double samplerate; + int64_t samples_decoded_incl, samples_decoded_excl; }; namespace scopy { @@ -97,39 +95,39 @@ namespace logic { class SCOPY_SIGROK_GUI_EXPORT Decoder { public: - Decoder(const srd_decoder *const dec); + Decoder(const srd_decoder *const dec); - virtual ~Decoder(); + virtual ~Decoder(); - const srd_decoder* decoder() const; + const srd_decoder *decoder() const; - bool shown() const; - void show(bool show = true); + bool shown() const; + void show(bool show = true); - const vector& channels() const; - void set_channels(vector channels); + const vector &channels() const; + void set_channels(vector channels); - const map& options() const; + const map &options() const; - void set_option(const char *id, GVariant *value); + void set_option(const char *id, GVariant *value); - void apply_all_options(); + void apply_all_options(); - bool have_required_channels() const; + bool have_required_channels() const; - srd_decoder_inst* create_decoder_inst(srd_session *session); - void invalidate_decoder_inst(); + srd_decoder_inst *create_decoder_inst(srd_session *session); + void invalidate_decoder_inst(); private: - const srd_decoder *const decoder_; + const srd_decoder *const decoder_; - bool shown_; + bool shown_; - vector channels_; - map options_; - srd_decoder_inst *decoder_inst_; + vector channels_; + map options_; + srd_decoder_inst *decoder_inst_; }; -} -} +} // namespace logic +} // namespace scopy #endif // DECODER_H diff --git a/gui/sigrok-gui/include/sigrok-gui/prop/bool.hpp b/gui/sigrok-gui/include/sigrok-gui/prop/bool.hpp index 1c5f260299..a2220fbe8d 100644 --- a/gui/sigrok-gui/include/sigrok-gui/prop/bool.hpp +++ b/gui/sigrok-gui/include/sigrok-gui/prop/bool.hpp @@ -37,7 +37,6 @@ * along with this program. If not, see . */ - #ifndef PULSEVIEW_PV_PROP_BOOL_HPP #define PULSEVIEW_PV_PROP_BOOL_HPP @@ -58,7 +57,7 @@ class SCOPY_SIGROK_GUI_EXPORT Bool : public Property virtual ~Bool() = default; - QWidget* get_widget(QWidget *parent, bool auto_commit); + QWidget *get_widget(QWidget *parent, bool auto_commit); bool labeled_widget() const; void update_widget(); @@ -71,7 +70,7 @@ private Q_SLOTS: QCheckBox *check_box_; }; -} // namespace prop -} // namespace pv +} // namespace prop +} // namespace scopy #endif // PULSEVIEW_PV_PROP_BOOL_HPP diff --git a/gui/sigrok-gui/include/sigrok-gui/prop/double.hpp b/gui/sigrok-gui/include/sigrok-gui/prop/double.hpp index 02b2ff1d38..4a2173f8a9 100644 --- a/gui/sigrok-gui/include/sigrok-gui/prop/double.hpp +++ b/gui/sigrok-gui/include/sigrok-gui/prop/double.hpp @@ -37,17 +37,15 @@ * along with this program. If not, see . */ - #ifndef PULSEVIEW_PV_PROP_DOUBLE_HPP #define PULSEVIEW_PV_PROP_DOUBLE_HPP -#include - -#include - #include "property.hpp" #include "scopy-sigrok-gui_export.h" +#include +#include + using std::pair; class QDoubleSpinBox; @@ -60,15 +58,12 @@ class SCOPY_SIGROK_GUI_EXPORT Double : public Property Q_OBJECT public: - Double(QString name, QString desc, int decimals, QString suffix, - std::optional< pair > range, - std::optional step, - Getter getter, - Setter setter); + Double(QString name, QString desc, int decimals, QString suffix, std::optional> range, + std::optional step, Getter getter, Setter setter); virtual ~Double() = default; - QWidget* get_widget(QWidget *parent, bool auto_commit); + QWidget *get_widget(QWidget *parent, bool auto_commit); void update_widget(); void commit(); @@ -79,13 +74,13 @@ private Q_SLOTS: private: const int decimals_; const QString suffix_; - const std::optional< pair > range_; + const std::optional> range_; const std::optional step_; QDoubleSpinBox *spin_box_; }; -} // namespace prop -} // namespace pv +} // namespace prop +} // namespace scopy #endif // PULSEVIEW_PV_PROP_DOUBLE_HPP diff --git a/gui/sigrok-gui/include/sigrok-gui/prop/enum.hpp b/gui/sigrok-gui/include/sigrok-gui/prop/enum.hpp index 5074ac3a70..54ab83fc59 100644 --- a/gui/sigrok-gui/include/sigrok-gui/prop/enum.hpp +++ b/gui/sigrok-gui/include/sigrok-gui/prop/enum.hpp @@ -37,17 +37,16 @@ * along with this program. If not, see . */ - #ifndef PULSEVIEW_PV_PROP_ENUM_HPP #define PULSEVIEW_PV_PROP_ENUM_HPP -#include -#include - #include "property.hpp" +#include "scopy-sigrok-gui_export.h" #include -#include "scopy-sigrok-gui_export.h" + +#include +#include using std::pair; using std::vector; @@ -64,13 +63,11 @@ class SCOPY_SIGROK_GUI_EXPORT Enum : public Property Q_OBJECT; public: - Enum(QString name, QString desc, - vector > values, - Getter getter, Setter setter); + Enum(QString name, QString desc, vector> values, Getter getter, Setter setter); virtual ~Enum() = default; - QWidget* get_widget(QWidget *parent, bool auto_commit); + QWidget *get_widget(QWidget *parent, bool auto_commit); void update_widget(); void commit(); @@ -80,7 +77,7 @@ private Q_SLOTS: void on_value_changed(int); private: - const vector< pair > values_; + const vector> values_; bool is_range_; QComboBox *selector_; @@ -90,7 +87,7 @@ private Q_SLOTS: QLabel *slider_label_; }; -} // namespace prop -} // namespace pv +} // namespace prop +} // namespace scopy #endif // PULSEVIEW_PV_PROP_ENUM_HPP diff --git a/gui/sigrok-gui/include/sigrok-gui/prop/int.hpp b/gui/sigrok-gui/include/sigrok-gui/prop/int.hpp index aee293d1ae..766fff6902 100644 --- a/gui/sigrok-gui/include/sigrok-gui/prop/int.hpp +++ b/gui/sigrok-gui/include/sigrok-gui/prop/int.hpp @@ -37,18 +37,16 @@ * along with this program. If not, see . */ - #ifndef PULSEVIEW_PV_PROP_INT_HPP #define PULSEVIEW_PV_PROP_INT_HPP -#include - -#include - #include "property.hpp" -#include #include "scopy-sigrok-gui_export.h" +#include +#include +#include + using std::pair; class QSpinBox; @@ -61,13 +59,12 @@ class SCOPY_SIGROK_GUI_EXPORT Int : public Property Q_OBJECT; public: - Int(QString name, QString desc, QString suffix, - std::optional< pair > range, - Getter getter, Setter setter, GVariantClass gvarClass); + Int(QString name, QString desc, QString suffix, std::optional> range, Getter getter, + Setter setter, GVariantClass gvarClass); virtual ~Int() = default; - QWidget* get_widget(QWidget *parent, bool auto_commit); + QWidget *get_widget(QWidget *parent, bool auto_commit); void update_widget(); void commit(); @@ -77,14 +74,14 @@ private Q_SLOTS: private: const QString suffix_; - const std::optional< pair > range_; + const std::optional> range_; QVariant value_; QSpinBox *spin_box_; GVariantClass gvar_class_type_; }; -} // namespace prop -} // namespace pv +} // namespace prop +} // namespace scopy #endif // PULSEVIEW_PV_PROP_INT_HPP diff --git a/gui/sigrok-gui/include/sigrok-gui/prop/property.hpp b/gui/sigrok-gui/include/sigrok-gui/prop/property.hpp index 290477503a..703274010e 100644 --- a/gui/sigrok-gui/include/sigrok-gui/prop/property.hpp +++ b/gui/sigrok-gui/include/sigrok-gui/prop/property.hpp @@ -37,16 +37,16 @@ * along with this program. If not, see . */ - #ifndef PULSEVIEW_PV_PROP_PROPERTY_HPP #define PULSEVIEW_PV_PROP_PROPERTY_HPP -#include +#include "scopy-sigrok-gui_export.h" #include -#include #include -#include "scopy-sigrok-gui_export.h" +#include + +#include using std::function; @@ -60,20 +60,20 @@ class SCOPY_SIGROK_GUI_EXPORT Property : public QObject Q_OBJECT; public: - typedef function Getter; - typedef function Setter; + typedef function Getter; + typedef function Setter; protected: Property(QString name, QString desc, Getter getter, Setter setter); public: - const QString& name() const; - const QString& desc() const; + const QString &name() const; + const QString &desc() const; QVariant get() const; void set(QVariant val); - virtual QWidget* get_widget(QWidget *parent, bool auto_commit = false) = 0; + virtual QWidget *get_widget(QWidget *parent, bool auto_commit = false) = 0; virtual bool labeled_widget() const; virtual void update_widget() = 0; @@ -88,7 +88,7 @@ class SCOPY_SIGROK_GUI_EXPORT Property : public QObject QString desc_; }; -} // namespace prop -} // namespace pv +} // namespace prop +} // namespace scopy #endif // PULSEVIEW_PV_PROP_PROPERTY_HPP diff --git a/gui/sigrok-gui/include/sigrok-gui/prop/string.hpp b/gui/sigrok-gui/include/sigrok-gui/prop/string.hpp index a6252ac470..b11b2fd052 100644 --- a/gui/sigrok-gui/include/sigrok-gui/prop/string.hpp +++ b/gui/sigrok-gui/include/sigrok-gui/prop/string.hpp @@ -37,7 +37,6 @@ * along with this program. If not, see . */ - #ifndef PULSEVIEW_PV_PROP_STRING_HPP #define PULSEVIEW_PV_PROP_STRING_HPP @@ -56,19 +55,19 @@ class SCOPY_SIGROK_GUI_EXPORT String : public Property public: String(QString name, QString desc, Getter getter, Setter setter); - QWidget* get_widget(QWidget *parent, bool auto_commit); + QWidget *get_widget(QWidget *parent, bool auto_commit); void update_widget(); void commit(); private Q_SLOTS: - void onTextEdited(const QString&); + void onTextEdited(const QString &); private: QLineEdit *line_edit_; }; -} // namespace prop -} // namespace pv +} // namespace prop +} // namespace scopy #endif // PULSEVIEW_PV_PROP_STRING_HPP diff --git a/gui/sigrok-gui/include/sigrok-gui/row.h b/gui/sigrok-gui/include/sigrok-gui/row.h index 7033da309a..223586c773 100644 --- a/gui/sigrok-gui/include/sigrok-gui/row.h +++ b/gui/sigrok-gui/include/sigrok-gui/row.h @@ -37,37 +37,35 @@ * along with this program. If not, see . */ - #ifndef ROW_H #define ROW_H -#include +#include "scopy-sigrok-gui_export.h" #include -#include "scopy-sigrok-gui_export.h" + +#include class SCOPY_SIGROK_GUI_EXPORT Row { public: - Row(); + Row(); - Row(int index, const srd_decoder *decoder, - const srd_decoder_annotation_row *row = nullptr); + Row(int index, const srd_decoder *decoder, const srd_decoder_annotation_row *row = nullptr); - const srd_decoder* decoder() const; - const srd_decoder_annotation_row* row() const; + const srd_decoder *decoder() const; + const srd_decoder_annotation_row *row() const; - const QString title() const; - const QString class_name() const; - int index() const; + const QString title() const; + const QString class_name() const; + int index() const; - bool operator<(const Row &other) const; + bool operator<(const Row &other) const; private: - int index_; - const srd_decoder *decoder_; - const srd_decoder_annotation_row *row_; - + int index_; + const srd_decoder *decoder_; + const srd_decoder_annotation_row *row_; }; #endif // ROW_H diff --git a/gui/sigrok-gui/include/sigrok-gui/rowdata.h b/gui/sigrok-gui/include/sigrok-gui/rowdata.h index ca21da281d..c61d9a36e3 100644 --- a/gui/sigrok-gui/include/sigrok-gui/rowdata.h +++ b/gui/sigrok-gui/include/sigrok-gui/rowdata.h @@ -37,61 +37,56 @@ * along with this program. If not, see . */ - #ifndef ROWDATA_H #define ROWDATA_H -#include - #include "annotation.h" +#include "scopy-sigrok-gui_export.h" -#include +#include #include -#include "scopy-sigrok-gui_export.h" +#include class Row; class SCOPY_SIGROK_GUI_EXPORT RowData { public: - RowData() = default; + RowData() = default; public: - uint64_t get_max_sample() const; + uint64_t get_max_sample() const; - uint64_t size() const { - return annotations_.size(); - } + uint64_t size() const { return annotations_.size(); } - /** - * Extracts annotations between the given sample range into a vector. - * Note: The annotations are unsorted and only annotations that fully - * fit into the sample range are considered. - */ - void get_annotation_subset( - vector &dest, - uint64_t start_sample, uint64_t end_sample) const; + /** + * Extracts annotations between the given sample range into a vector. + * Note: The annotations are unsorted and only annotations that fully + * fit into the sample range are considered. + */ + void get_annotation_subset(vector &dest, uint64_t start_sample, uint64_t end_sample) const; - vector get_annotations() const; + vector get_annotations() const; - void emplace_annotation(srd_proto_data *pdata, const Row *row); + void emplace_annotation(srd_proto_data *pdata, const Row *row); - std::pair get_annotation_subset(uint64_t start_sample, - uint64_t end_sample) const; + std::pair get_annotation_subset(uint64_t start_sample, uint64_t end_sample) const; - Annotation getAnnAt(uint64_t index) const; - const Annotation* annAt(uint64_t index) const; + Annotation getAnnAt(uint64_t index) const; + const Annotation *annAt(uint64_t index) const; - void sort_annotations(); + void sort_annotations(); private: - struct annotation_compare { - bool operator() (const Annotation &a, const Annotation &b) const { - return a.start_sample() < b.start_sample(); - } - }; - - std::vector annotations_; + struct annotation_compare + { + bool operator()(const Annotation &a, const Annotation &b) const + { + return a.start_sample() < b.start_sample(); + } + }; + + std::vector annotations_; }; #endif // ROWDATA_H diff --git a/gui/sigrok-gui/src/annotation.cpp b/gui/sigrok-gui/src/annotation.cpp index 340f8e8d4c..ec5640064d 100644 --- a/gui/sigrok-gui/src/annotation.cpp +++ b/gui/sigrok-gui/src/annotation.cpp @@ -37,61 +37,43 @@ * along with this program. If not, see . */ - #include "annotation.h" + #include -extern "C" { +extern "C" +{ #include } #include -Annotation::Annotation(const srd_proto_data *const pdata, const Row *row) : - start_sample_(pdata->start_sample), - end_sample_(pdata->end_sample), - row_(row) +Annotation::Annotation(const srd_proto_data *const pdata, const Row *row) + : start_sample_(pdata->start_sample) + , end_sample_(pdata->end_sample) + , row_(row) { - assert(pdata); - const srd_proto_data_annotation *const pda = - (const srd_proto_data_annotation*)pdata->data; - assert(pda); + assert(pdata); + const srd_proto_data_annotation *const pda = (const srd_proto_data_annotation *)pdata->data; + assert(pda); - ann_class_ = (Class)(pda->ann_class); + ann_class_ = (Class)(pda->ann_class); - const char *const *annotations = (char**)pda->ann_text; - while (*annotations) { - annotations_.push_back(QString::fromUtf8(*annotations)); - annotations++; - } + const char *const *annotations = (char **)pda->ann_text; + while(*annotations) { + annotations_.push_back(QString::fromUtf8(*annotations)); + annotations++; + } } -uint64_t Annotation::start_sample() const -{ - return start_sample_; -} +uint64_t Annotation::start_sample() const { return start_sample_; } -uint64_t Annotation::end_sample() const -{ - return end_sample_; -} +uint64_t Annotation::end_sample() const { return end_sample_; } -Annotation::Class Annotation::ann_class() const -{ - return ann_class_; -} +Annotation::Class Annotation::ann_class() const { return ann_class_; } -const vector& Annotation::annotations() const -{ - return annotations_; -} +const vector &Annotation::annotations() const { return annotations_; } -const Row* Annotation::row() const -{ - return row_; -} +const Row *Annotation::row() const { return row_; } -bool Annotation::operator<(const Annotation &other) const -{ - return (start_sample_ < other.start_sample_); -} +bool Annotation::operator<(const Annotation &other) const { return (start_sample_ < other.start_sample_); } diff --git a/gui/sigrok-gui/src/annotationcurve.cpp b/gui/sigrok-gui/src/annotationcurve.cpp index cacfacc36f..cef8ca3411 100644 --- a/gui/sigrok-gui/src/annotationcurve.cpp +++ b/gui/sigrok-gui/src/annotationcurve.cpp @@ -18,173 +18,162 @@ * along with this program. If not, see . */ - #include "annotationcurve.h" #include "annotationdecoder.h" - #include "binding/decoder.hpp" -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include +#include +#include +#include #include -#include #include -#include -#include #include +#include +#include +#include +#include +#include +#include +#include -#include - -#include +#include +#include using namespace scopy; using namespace scopy::logic; AnnotationCurve::AnnotationCurve(std::shared_ptr initialDecoder) - : GenericLogicPlotCurve(initialDecoder->decoder()->name, initialDecoder->decoder()->id, LogicPlotCurveType::Annotations) + : GenericLogicPlotCurve(initialDecoder->decoder()->name, initialDecoder->decoder()->id, + LogicPlotCurveType::Annotations) , m_visibleRows(0) { - setSamples(QVector({0.0}), QVector({0.0})), - setRenderHint(RenderAntialiased, true); - setBrush(QBrush(Qt::red)); - setBaseline(0.0); + setSamples(QVector({0.0}), QVector({0.0})), setRenderHint(RenderAntialiased, true); + setBrush(QBrush(Qt::red)); + setBaseline(0.0); - m_annotationDecoder = new AnnotationDecoder(this, initialDecoder); + m_annotationDecoder = new AnnotationDecoder(this, initialDecoder); - m_bindings.emplace_back(std::make_shared(m_annotationDecoder, initialDecoder)); + m_bindings.emplace_back(std::make_shared(m_annotationDecoder, initialDecoder)); - connect(this, &AnnotationCurve::clicked, [=](const QPointF&p) { - const auto result = annotationAt(p); - if (result.isValid()) { - Q_EMIT annotationClicked(result); - } - }); + connect(this, &AnnotationCurve::clicked, [=](const QPointF &p) { + const auto result = annotationAt(p); + if(result.isValid()) { + Q_EMIT annotationClicked(result); + } + }); } -AnnotationCurve::~AnnotationCurve() -{ - delete m_annotationDecoder; -} +AnnotationCurve::~AnnotationCurve() { delete m_annotationDecoder; } void AnnotationCurve::annotationCallback(srd_proto_data *pdata, void *annotationCurve) { - if (!pdata) { - qDebug() << "Error pdata nullptr!"; - return; - } - if (!annotationCurve) { - qDebug() << "Error logic_analyzer nullptr!"; - return; - } - - AnnotationCurve *const curve = static_cast(annotationCurve); - if (!curve) { - qDebug() << "Error logicAnalyzer nullptr!"; - return; - } - - if (!pdata->pdo) { - qDebug() << "Error pdata->pdo nullptr!"; - return; - } - - if (!pdata->pdo->di) { - qDebug() << "Error pdata->pdo->di nullptr"; - return; - } - - const srd_decoder *const decc = pdata->pdo->di->decoder; - - if (!decc) { - qDebug() << "Error decc nullptr"; - return; - } - - const srd_proto_data_annotation *const pda = - (const srd_proto_data_annotation*)pdata->data; - - if (!pda) { - qDebug() << "Error pda nullptr"; - return; - } - - // Find format of current received annotation - const auto format = pda->ann_class; - - // Find the row associated with this format - const auto r = curve->m_classRows.find(std::make_pair(decc, format)); - - auto row_iter = curve->m_annotationRows.end(); - - if (r != curve->m_classRows.end()) { - row_iter = curve->m_annotationRows.find((*r).second); - } else { - row_iter = curve->m_annotationRows.find(Row(0, decc)); - } - - if (row_iter == curve->m_annotationRows.end()) { - qDebug() << "Unexpected annotation for decoder: " << decc << " , format = " << format; - return; - } - - std::unique_lock lock(curve->m_mutex); - - (*row_iter).second.emplace_annotation(pdata, &((*row_iter).first)); -// qDebug() << "Pushed annotation with format: " << format << " to row: " << (*row_iter).first.index(); + if(!pdata) { + qDebug() << "Error pdata nullptr!"; + return; + } + if(!annotationCurve) { + qDebug() << "Error logic_analyzer nullptr!"; + return; + } + + AnnotationCurve *const curve = static_cast(annotationCurve); + if(!curve) { + qDebug() << "Error logicAnalyzer nullptr!"; + return; + } + + if(!pdata->pdo) { + qDebug() << "Error pdata->pdo nullptr!"; + return; + } + + if(!pdata->pdo->di) { + qDebug() << "Error pdata->pdo->di nullptr"; + return; + } + + const srd_decoder *const decc = pdata->pdo->di->decoder; + + if(!decc) { + qDebug() << "Error decc nullptr"; + return; + } + + const srd_proto_data_annotation *const pda = (const srd_proto_data_annotation *)pdata->data; + + if(!pda) { + qDebug() << "Error pda nullptr"; + return; + } + + // Find format of current received annotation + const auto format = pda->ann_class; + + // Find the row associated with this format + const auto r = curve->m_classRows.find(std::make_pair(decc, format)); + + auto row_iter = curve->m_annotationRows.end(); + + if(r != curve->m_classRows.end()) { + row_iter = curve->m_annotationRows.find((*r).second); + } else { + row_iter = curve->m_annotationRows.find(Row(0, decc)); + } + + if(row_iter == curve->m_annotationRows.end()) { + qDebug() << "Unexpected annotation for decoder: " << decc << " , format = " << format; + return; + } + + std::unique_lock lock(curve->m_mutex); + + (*row_iter).second.emplace_annotation(pdata, &((*row_iter).first)); + // qDebug() << "Pushed annotation with format: " << format << " to row: " << (*row_iter).first.index(); } void AnnotationCurve::dataAvailable(uint64_t from, uint64_t to, uint16_t *data) { - if (from == 0) { + if(from == 0) { reset(); } - m_annotationDecoder->dataAvailable(from, to, data); + m_annotationDecoder->dataAvailable(from, to, data); } void AnnotationCurve::setClassRows(const std::map, Row> &classRows) { - m_classRows = classRows; + m_classRows = classRows; } void AnnotationCurve::setAnnotationRows(const std::map &annotationRows) { - m_annotationRows = annotationRows; + m_annotationRows = annotationRows; } -const std::map & AnnotationCurve::getAnnotationRows() const -{ - return m_annotationRows; -} +const std::map &AnnotationCurve::getAnnotationRows() const { return m_annotationRows; } void AnnotationCurve::sort_rows() { - for (auto it = m_annotationRows.begin(); it != m_annotationRows.end(); ++it) { - it->second.sort_annotations(); - } + for(auto it = m_annotationRows.begin(); it != m_annotationRows.end(); ++it) { + it->second.sort_annotations(); + } } void AnnotationCurve::newAnnotations() { - QMetaObject::invokeMethod(plot(), "replot"); - state = 1; + QMetaObject::invokeMethod(plot(), "replot"); + state = 1; } void AnnotationCurve::reset() { - std::unique_lock lock(m_mutex); + std::unique_lock lock(m_mutex); - m_classRows.clear(); - m_annotationRows.clear(); + m_classRows.clear(); + m_annotationRows.clear(); m_annotationDecoder->reset(); m_visibleRows = 0; state = 0; @@ -192,280 +181,267 @@ void AnnotationCurve::reset() QWidget *AnnotationCurve::getCurrentDecoderStackMenu() { - // for each decoder append it s binding - std::vector> stack = m_annotationDecoder->getDecoderStack(); - - QWidget *widget = new QWidget(); - QGridLayout *grid = new QGridLayout(); - grid->setContentsMargins(0, 0, 0, 0); - grid->setColumnStretch(0, 1); - widget->setLayout(grid); - QFormLayout *layout = new QFormLayout(); - layout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); - layout->setFormAlignment(Qt::AlignTop); - layout->setLabelAlignment(Qt::AlignLeft); - grid->addLayout(layout, 1, 0, 1, 2); - - - auto getSubTitleFrame = [=](){ - QFrame *line = new QFrame(); - line->setObjectName(QString::fromUtf8("line_4")); -// sizePolicy8.setHeightForWidth(line->sizePolicy().hasHeightForWidth()); -// line->setSizePolicy(sizePolicy8); - line->setMaximumSize(QSize(16777215, 1)); - line->setStyleSheet(QString::fromUtf8("border: 1px solid rgba(255, 255, 255, 70);")); - line->setFrameShape(QFrame::HLine); - line->setFrameShadow(QFrame::Sunken); - - return line; - }; - - auto channels = m_annotationDecoder->getDecoderChannels(); - - QVBoxLayout *qvbl = new QVBoxLayout(); - QLabel *title = new QLabel(stack.front()->decoder()->name); - qvbl->addWidget(title); - qvbl->addWidget(getSubTitleFrame()); - layout->addRow(qvbl); - - for (auto &ch : channels) { - QWidget *chls = new QWidget(widget); - QHBoxLayout *lay = new QHBoxLayout(chls); - lay->setContentsMargins(0, 0, 0, 0); - chls->setLayout(lay); - QString required = (ch->is_optional ? "" : "*"); - QLabel *label = new QLabel(ch->name + "(" + ch->desc + ")" + required, chls); - label->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - lay->insertWidget(0, label); - QComboBox *box = new QComboBox(chls); - lay->insertSpacerItem(1, new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); - lay->insertWidget(2, box); - box->addItem(QString("x")); - for (int i = 0; i < 16; ++i) { - box->addItem(QString::number(i)); - } - - if (!ch->assigned_signal) { - box->setCurrentIndex(0); - } else { - box->setCurrentIndex(ch->bit_id + 1); - } + // for each decoder append it s binding + std::vector> stack = m_annotationDecoder->getDecoderStack(); + + QWidget *widget = new QWidget(); + QGridLayout *grid = new QGridLayout(); + grid->setContentsMargins(0, 0, 0, 0); + grid->setColumnStretch(0, 1); + widget->setLayout(grid); + QFormLayout *layout = new QFormLayout(); + layout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); + layout->setFormAlignment(Qt::AlignTop); + layout->setLabelAlignment(Qt::AlignLeft); + grid->addLayout(layout, 1, 0, 1, 2); + + auto getSubTitleFrame = [=]() { + QFrame *line = new QFrame(); + line->setObjectName(QString::fromUtf8("line_4")); + // sizePolicy8.setHeightForWidth(line->sizePolicy().hasHeightForWidth()); + // line->setSizePolicy(sizePolicy8); + line->setMaximumSize(QSize(16777215, 1)); + line->setStyleSheet(QString::fromUtf8("border: 1px solid rgba(255, 255, 255, 70);")); + line->setFrameShape(QFrame::HLine); + line->setFrameShadow(QFrame::Sunken); + + return line; + }; + + auto channels = m_annotationDecoder->getDecoderChannels(); + + QVBoxLayout *qvbl = new QVBoxLayout(); + QLabel *title = new QLabel(stack.front()->decoder()->name); + qvbl->addWidget(title); + qvbl->addWidget(getSubTitleFrame()); + layout->addRow(qvbl); + + for(auto &ch : channels) { + QWidget *chls = new QWidget(widget); + QHBoxLayout *lay = new QHBoxLayout(chls); + lay->setContentsMargins(0, 0, 0, 0); + chls->setLayout(lay); + QString required = (ch->is_optional ? "" : "*"); + QLabel *label = new QLabel(ch->name + "(" + ch->desc + ")" + required, chls); + label->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + lay->insertWidget(0, label); + QComboBox *box = new QComboBox(chls); + lay->insertSpacerItem(1, new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); + lay->insertWidget(2, box); + box->addItem(QString("x")); + for(int i = 0; i < 16; ++i) { + box->addItem(QString::number(i)); + } + + if(!ch->assigned_signal) { + box->setCurrentIndex(0); + } else { + box->setCurrentIndex(ch->bit_id + 1); + } - QObject::connect(box, QOverload::of(&QComboBox::currentIndexChanged), [=](int index){ - if (index == 0) { - m_annotationDecoder->unassignChannel(ch->id); - } else { - m_annotationDecoder->assignChannel(ch->id, index - 1); - } - }); - layout->addRow(label, box); -// layout->addRow(chls); - } - - m_bindings.clear(); - - for (const auto &dec : stack) { - if (dec != stack.front()) { - QVBoxLayout *qvbl = new QVBoxLayout(); - QLabel *title = new QLabel(dec->decoder()->name); - QHBoxLayout *qhbl = new QHBoxLayout(); - qhbl->addWidget(title); - qhbl->addSpacerItem(new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum)); - QPushButton *deleteBtn = new QPushButton(); - deleteBtn->setFlat(true); - deleteBtn->setIcon(QIcon(":/gui/icons/close_hovered.svg")); - deleteBtn->setMaximumSize(QSize(16, 16)); - qhbl->addWidget(deleteBtn); - qvbl->addLayout(qhbl); - qvbl->addWidget(getSubTitleFrame()); - layout->addRow(qvbl); - - connect(deleteBtn, &QPushButton::clicked, [=](){ - m_classRows.clear(); - m_annotationRows.clear(); - m_annotationDecoder->unstackDecoder(dec); - Q_EMIT decoderMenuChanged(); + QObject::connect(box, QOverload::of(&QComboBox::currentIndexChanged), [=](int index) { + if(index == 0) { + m_annotationDecoder->unassignChannel(ch->id); + } else { + m_annotationDecoder->assignChannel(ch->id, index - 1); + } }); - } + layout->addRow(label, box); + // layout->addRow(chls); + } - m_bindings.emplace_back(std::make_shared(m_annotationDecoder, dec)); - m_bindings.back()->add_properties_to_form(layout, true); - } + m_bindings.clear(); + + for(const auto &dec : stack) { + if(dec != stack.front()) { + QVBoxLayout *qvbl = new QVBoxLayout(); + QLabel *title = new QLabel(dec->decoder()->name); + QHBoxLayout *qhbl = new QHBoxLayout(); + qhbl->addWidget(title); + qhbl->addSpacerItem(new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum)); + QPushButton *deleteBtn = new QPushButton(); + deleteBtn->setFlat(true); + deleteBtn->setIcon(QIcon(":/gui/icons/close_hovered.svg")); + deleteBtn->setMaximumSize(QSize(16, 16)); + qhbl->addWidget(deleteBtn); + qvbl->addLayout(qhbl); + qvbl->addWidget(getSubTitleFrame()); + layout->addRow(qvbl); + + connect(deleteBtn, &QPushButton::clicked, [=]() { + m_classRows.clear(); + m_annotationRows.clear(); + m_annotationDecoder->unstackDecoder(dec); + Q_EMIT decoderMenuChanged(); + }); + } + + m_bindings.emplace_back(std::make_shared(m_annotationDecoder, dec)); + m_bindings.back()->add_properties_to_form(layout, true); + } - return widget; + return widget; } void AnnotationCurve::stackDecoder(std::shared_ptr decoder) { - m_annotationDecoder->stackDecoder(decoder); + m_annotationDecoder->stackDecoder(decoder); - m_bindings.clear(); - std::vector> stack = m_annotationDecoder->getDecoderStack(); - for (const auto &dec : stack) { - m_bindings.emplace_back(std::make_shared(m_annotationDecoder, dec)); - } + m_bindings.clear(); + std::vector> stack = m_annotationDecoder->getDecoderStack(); + for(const auto &dec : stack) { + m_bindings.emplace_back(std::make_shared(m_annotationDecoder, dec)); + } } -std::vector > AnnotationCurve::getDecoderStack() +std::vector> AnnotationCurve::getDecoderStack() { return m_annotationDecoder->getDecoderStack(); } -int AnnotationCurve::getVisibleRows() const -{ - return m_visibleRows; -} +int AnnotationCurve::getVisibleRows() const { return m_visibleRows; } -double AnnotationCurve::getHeightOffset() const -{ - return getTraceHeight() * getVisibleRows(); -} +double AnnotationCurve::getHeightOffset() const { return getTraceHeight() * getVisibleRows(); } -AnnotationDecoder *AnnotationCurve::getAnnotationDecoder() -{ - return m_annotationDecoder; -} +AnnotationDecoder *AnnotationCurve::getAnnotationDecoder() { return m_annotationDecoder; } -std::vector > AnnotationCurve::getDecoderBindings() -{ - return m_bindings; -} +std::vector> AnnotationCurve::getDecoderBindings() { return m_bindings; } -void AnnotationCurve::drawLines(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &canvasRect, int from, int to) const +void AnnotationCurve::drawLines(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, + const QRectF &canvasRect, int from, int to) const { -// qDebug() << "Draw called for annotation curve"; + // qDebug() << "Draw called for annotation curve"; - std::unique_lock lock(m_mutex); + std::unique_lock lock(m_mutex); - QElapsedTimer timer; - timer.start(); + QElapsedTimer timer; + timer.start(); - QwtPointMapper mapper; - mapper.setFlag( QwtPointMapper::RoundPoints, QwtPainter::roundingAlignment( painter ) ); - mapper.setBoundingRect(canvasRect); + QwtPointMapper mapper; + mapper.setFlag(QwtPointMapper::RoundPoints, QwtPainter::roundingAlignment(painter)); + mapper.setBoundingRect(canvasRect); - const QwtInterval interval = plot()->axisInterval(QwtAxis::XBottom); + const QwtInterval interval = plot()->axisInterval(QwtAxis::XBottom); - QStringList titles; + QStringList titles; painter->save(); const QString fontFamily = QApplication::font().family(); painter->setFont(QFont(fontFamily, 10)); + int currentRowOnPlot = 0; + for(size_t row = 0; row < m_annotationRows.size(); ++row) { + auto it = std::find_if( + m_annotationRows.begin(), m_annotationRows.end(), + [row](const std::pair &t) -> bool { return t.first.index() == row; }); + + if(it == m_annotationRows.end()) { + // Something bad happened here. Might signal wrong classes/row+rowdata + // assignment when initializing this curve for decoding!!!! + // Q_ASSERT(false); + continue; + } + + // skip rows with no annotations to be drawn + if(!(*it).second.size()) { + continue; + } + + uint64_t start, stop; - int currentRowOnPlot = 0; - for (size_t row = 0; row < m_annotationRows.size(); ++row) { - auto it = std::find_if(m_annotationRows.begin(), m_annotationRows.end(), - [row](const std::pair &t) -> bool{ - return t.first.index() == row; - }); - - if (it == m_annotationRows.end()) { - // Something bad happened here. Might signal wrong classes/row+rowdata - // assignment when initializing this curve for decoding!!!! -// Q_ASSERT(false); - continue; - } - - // skip rows with no annotations to be drawn - if (!(*it).second.size()) { - continue; - } - - uint64_t start, stop; - - std::tie(start, stop) = (*it).second.get_annotation_subset(fromTimeToSample(interval.minValue()), - fromTimeToSample(interval.maxValue())); - - - // Get title of this row - // TODO: Send size to draw annotation in order to avoid drawing text under the title!!! - // Cache size of row title!!!! This does not change!!! - QString title = (*it).first.title(); - QSizeF size = QwtText(title).textSize(painter->font()); - - titles.push_back(title); - - uint64_t previous_end = -1; - uint64_t annotations_in_block = 0; - uint64_t block_start = 0; - - Annotation prev_ann; - - const double min_ann_label_width = QFontMetrics(QFont("Times", 10, QFont::Bold)).horizontalAdvance("XX"); - - for (; start <= stop; ++start) { - Annotation ann = ((*it).second.getAnnAt(start)); - - const double annotation_width = xMap.transform(fromSampleToTime(ann.end_sample())) - xMap.transform(fromSampleToTime(ann.start_sample())); - - bool shouldDraw = false; - - if (annotation_width >= min_ann_label_width) { - shouldDraw = true; - } - - const double delta = (previous_end != -1 ? - xMap.transform(fromSampleToTime(ann.end_sample())) - xMap.transform(fromSampleToTime(previous_end)) : - 0.0); - - if (qAbs(delta) > 1.5 || shouldDraw) { - if (annotations_in_block == 1) { - drawAnnotation(currentRowOnPlot, prev_ann, painter, - xMap, yMap, canvasRect, mapper, interval, size); - } else if (annotations_in_block > 0) { - drawBlock(currentRowOnPlot, block_start, previous_end, painter, - xMap, yMap, canvasRect, mapper); - } - - annotations_in_block = 0; - } - - if (shouldDraw) { - drawAnnotation(currentRowOnPlot, ann, painter, - xMap, yMap, canvasRect, mapper, interval, size); - previous_end = -1; - annotations_in_block = 0; - } else { - previous_end = ann.end_sample(); - prev_ann = ann; - - if (!annotations_in_block) { - block_start = ann.start_sample(); - } - - annotations_in_block++; - } - - // Draw final blocks / annotations - // We need to do this here becaus prev_ann will be a reference - // to an object created in this for-loop - if (start == stop) { - if (annotations_in_block == 1) { - drawAnnotation(currentRowOnPlot, prev_ann, painter, - xMap, yMap, canvasRect, mapper, interval, size); - } else if (annotations_in_block > 0) { - drawBlock(currentRowOnPlot, block_start, previous_end, painter, - xMap, yMap, canvasRect, mapper); - } - } - } - - // Draw next row. There is no need to leave empty row on screen - // if no annotations are generated for it - currentRowOnPlot++; - } - if (state == 1) { - state = 2; - } - - m_visibleRows = currentRowOnPlot; + std::tie(start, stop) = (*it).second.get_annotation_subset(fromTimeToSample(interval.minValue()), + fromTimeToSample(interval.maxValue())); + + // Get title of this row + // TODO: Send size to draw annotation in order to avoid drawing text under the title!!! + // Cache size of row title!!!! This does not change!!! + QString title = (*it).first.title(); + QSizeF size = QwtText(title).textSize(painter->font()); + + titles.push_back(title); + + uint64_t previous_end = -1; + uint64_t annotations_in_block = 0; + uint64_t block_start = 0; + + Annotation prev_ann; + + const double min_ann_label_width = + QFontMetrics(QFont("Times", 10, QFont::Bold)).horizontalAdvance("XX"); + + for(; start <= stop; ++start) { + Annotation ann = ((*it).second.getAnnAt(start)); + + const double annotation_width = xMap.transform(fromSampleToTime(ann.end_sample())) - + xMap.transform(fromSampleToTime(ann.start_sample())); + + bool shouldDraw = false; + + if(annotation_width >= min_ann_label_width) { + shouldDraw = true; + } + + const double delta = (previous_end != -1 ? xMap.transform(fromSampleToTime(ann.end_sample())) - + xMap.transform(fromSampleToTime(previous_end)) + : 0.0); + + if(qAbs(delta) > 1.5 || shouldDraw) { + if(annotations_in_block == 1) { + drawAnnotation(currentRowOnPlot, prev_ann, painter, xMap, yMap, canvasRect, + mapper, interval, size); + } else if(annotations_in_block > 0) { + drawBlock(currentRowOnPlot, block_start, previous_end, painter, xMap, yMap, + canvasRect, mapper); + } + + annotations_in_block = 0; + } + + if(shouldDraw) { + drawAnnotation(currentRowOnPlot, ann, painter, xMap, yMap, canvasRect, mapper, interval, + size); + previous_end = -1; + annotations_in_block = 0; + } else { + previous_end = ann.end_sample(); + prev_ann = ann; + + if(!annotations_in_block) { + block_start = ann.start_sample(); + } + + annotations_in_block++; + } + + // Draw final blocks / annotations + // We need to do this here becaus prev_ann will be a reference + // to an object created in this for-loop + if(start == stop) { + if(annotations_in_block == 1) { + drawAnnotation(currentRowOnPlot, prev_ann, painter, xMap, yMap, canvasRect, + mapper, interval, size); + } else if(annotations_in_block > 0) { + drawBlock(currentRowOnPlot, block_start, previous_end, painter, xMap, yMap, + canvasRect, mapper); + } + } + } + + // Draw next row. There is no need to leave empty row on screen + // if no annotations are generated for it + currentRowOnPlot++; + } + if(state == 1) { + state = 2; + } + + m_visibleRows = currentRowOnPlot; painter->save(); QColor painterColor; - if (QIcon::themeName() == "scopy-default") { + if(QIcon::themeName() == "scopy-default") { painterColor = Qt::white; } else { painterColor = Qt::black; @@ -474,7 +450,7 @@ void AnnotationCurve::drawLines(QPainter *painter, const QwtScaleMap &xMap, cons painter->setPen(QPen(QBrush(painterColor), 2)); int currentTitleIndex = 0; const int pixOffsetFromCanvasMargin = 5; - for (const QString &title : titles) { + for(const QString &title : titles) { QSizeF size = QwtText(title).textSize(painter->font()); double HeightInPoints = yMap.invTransform(m_traceHeight) - yMap.invTransform(0); @@ -482,10 +458,11 @@ void AnnotationCurve::drawLines(QPainter *painter, const QwtScaleMap &xMap, cons QRectF textRect(QPointF(0.0, 0.0), size); - textRect.moveCenter(QPointF(xMap.transform(interval.minValue()), - yMap.transform(offset + HeightInPoints / 2.0))); + textRect.moveCenter( + QPointF(xMap.transform(interval.minValue()), yMap.transform(offset + HeightInPoints / 2.0))); - textRect.setBottomLeft(textRect.bottomLeft() + QPointF(size.width() / 2.0 + pixOffsetFromCanvasMargin, 0)); + textRect.setBottomLeft(textRect.bottomLeft() + + QPointF(size.width() / 2.0 + pixOffsetFromCanvasMargin, 0)); textRect.setTopRight(textRect.topRight() + QPointF(size.width() / 2.0 + pixOffsetFromCanvasMargin, 0)); painter->drawText(textRect, title); currentTitleIndex++; @@ -495,42 +472,40 @@ void AnnotationCurve::drawLines(QPainter *painter, const QwtScaleMap &xMap, cons painter->restore(); } -void AnnotationCurve::drawBlock(int row, uint64_t start, uint64_t end, QPainter *painter, - const QwtScaleMap &xMap, const QwtScaleMap &yMap, - const QRectF &canvasRect, const QwtPointMapper &mapper) const { +void AnnotationCurve::drawBlock(int row, uint64_t start, uint64_t end, QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, const QRectF &canvasRect, const QwtPointMapper &mapper) const +{ - double HeightInPoints = yMap.invTransform(m_traceHeight) - yMap.invTransform(0); - double offset = m_pixelOffset + row * (HeightInPoints); + double HeightInPoints = yMap.invTransform(m_traceHeight) - yMap.invTransform(0); + double offset = m_pixelOffset + row * (HeightInPoints); - double width = xMap.transform(fromSampleToTime(end)) - xMap.transform(fromSampleToTime(start)); + double width = xMap.transform(fromSampleToTime(end)) - xMap.transform(fromSampleToTime(start)); - const int r = 20 / 4; + const int r = 20 / 4; - const QRectF rect(QPointF(xMap.transform(fromSampleToTime(start)), yMap.transform(offset)), QSizeF(width, m_traceHeight)); + const QRectF rect(QPointF(xMap.transform(fromSampleToTime(start)), yMap.transform(offset)), + QSizeF(width, m_traceHeight)); - painter->save(); + painter->save(); - painter->setPen(Qt::gray); - painter->setBrush(QBrush(Qt::gray, Qt::Dense4Pattern)); - painter->drawRoundedRect(rect, r, r); + painter->setPen(Qt::gray); + painter->setBrush(QBrush(Qt::gray, Qt::Dense4Pattern)); + painter->drawRoundedRect(rect, r, r); - painter->restore(); + painter->restore(); } QString AnnotationCurve::formatSeconds(double sec) const { QString string; auto time = abs(sec); - if (time > 1) { + if(time > 1) { string = QString("%1 s").arg(sec); - } - else if (time > 0.001) { + } else if(time > 0.001) { string = QString("%1 ms").arg(sec * 10E+2); - } - else if (time > 0.000001) { + } else if(time > 0.000001) { string = QString("%1 μs").arg(sec * 10E+5); - } - else { + } else { string = QString("%1 ns").arg(sec * 10E+8); } @@ -539,20 +514,23 @@ QString AnnotationCurve::formatSeconds(double sec) const void AnnotationCurve::drawAnnotationInfo(int row, uint64_t start, uint64_t end, QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, - const QRectF &canvasRect) const { + const QRectF &canvasRect) const +{ const double infoHeightInPoints = yMap.invTransform(m_infoHeight) - yMap.invTransform(0); const double infoWidthRatio = 0.09; double HeightInPoints = yMap.invTransform(m_traceHeight) - yMap.invTransform(0); - double offset = m_pixelOffset + (row) * (HeightInPoints) - infoHeightInPoints; + double offset = m_pixelOffset + (row) * (HeightInPoints)-infoHeightInPoints; double width = xMap.transform(fromSampleToTime(end)) - xMap.transform(fromSampleToTime(start)); QRectF rect; - if (start != end) { - rect = QRectF(QPointF(xMap.transform(fromSampleToTime(start)), yMap.transform(offset)), QSizeF(width, m_infoHeight)); + if(start != end) { + rect = QRectF(QPointF(xMap.transform(fromSampleToTime(start)), yMap.transform(offset)), + QSizeF(width, m_infoHeight)); } else { - rect = QRectF(QPointF(canvasRect.x() + canvasRect.width() * infoWidthRatio, yMap.transform(offset)), QSizeF(canvasRect.width() * (1 - infoWidthRatio * 2), m_infoHeight)); + rect = QRectF(QPointF(canvasRect.x() + canvasRect.width() * infoWidthRatio, yMap.transform(offset)), + QSizeF(canvasRect.width() * (1 - infoWidthRatio * 2), m_infoHeight)); } painter->save(); @@ -567,23 +545,21 @@ void AnnotationCurve::drawAnnotationInfo(int row, uint64_t start, uint64_t end, QString info_time = " start: " + formatSeconds(fromSampleToTime(start)); QString info_delta_time = " duration: " + formatSeconds(fromSampleToTime(end) - fromSampleToTime(start)); - painter->drawText(rect, Qt::AlignLeft|Qt::AlignTop, info_time); - painter->drawText(rect, Qt::AlignLeft|Qt::AlignBottom, info_delta_time); + painter->drawText(rect, Qt::AlignLeft | Qt::AlignTop, info_time); + painter->drawText(rect, Qt::AlignLeft | Qt::AlignBottom, info_delta_time); QString info_sample = QString("start sample: %1 ").arg(QString::fromStdString(std::to_string(start))); - QString info_delta_sample = QString("sample count: %1 ").arg(QString::fromStdString(std::to_string(end - start))); + QString info_delta_sample = + QString("sample count: %1 ").arg(QString::fromStdString(std::to_string(end - start))); - painter->drawText(rect, Qt::AlignRight|Qt::AlignTop, info_sample); - painter->drawText(rect, Qt::AlignRight|Qt::AlignBottom, info_delta_sample); + painter->drawText(rect, Qt::AlignRight | Qt::AlignTop, info_sample); + painter->drawText(rect, Qt::AlignRight | Qt::AlignBottom, info_delta_sample); painter->setPen(QPen(QBrush(Qt::black), 1)); painter->restore(); } -void AnnotationCurve::setState(int st) -{ - state = st; -} +void AnnotationCurve::setState(int st) { state = st; } int AnnotationCurve::getState() { @@ -597,90 +573,81 @@ int AnnotationCurve::getState() QString AnnotationCurve::fromTitleToRowType(QString title) const { - return (title.indexOf(':')) ? title.mid(title.indexOf(':') + 1) - : title; + return (title.indexOf(':')) ? title.mid(title.indexOf(':') + 1) : title; } -void AnnotationCurve::drawAnnotation(int row, const Annotation &ann, QPainter *painter, - const QwtScaleMap &xMap, const QwtScaleMap &yMap, - const QRectF &canvasRect, const QwtPointMapper &mapper, - const QwtInterval &interval, const QSizeF &titleSize) const { -// qDebug() << "Drawing annotation for row: " << row << " having the text " << ann.annotations().back(); - if (ann.start_sample() != ann.end_sample()) { - drawTwoSampleAnnotation(row, ann, painter, - xMap, yMap, canvasRect, mapper, interval, titleSize); - } else { - drawOneSampleAnnotation(row, ann, painter, - xMap, yMap, canvasRect, mapper, interval, titleSize); - } +void AnnotationCurve::drawAnnotation(int row, const Annotation &ann, QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, const QRectF &canvasRect, const QwtPointMapper &mapper, + const QwtInterval &interval, const QSizeF &titleSize) const +{ + // qDebug() << "Drawing annotation for row: " << row << " having the text " << ann.annotations().back(); + if(ann.start_sample() != ann.end_sample()) { + drawTwoSampleAnnotation(row, ann, painter, xMap, yMap, canvasRect, mapper, interval, titleSize); + } else { + drawOneSampleAnnotation(row, ann, painter, xMap, yMap, canvasRect, mapper, interval, titleSize); + } } -void AnnotationCurve::fillAnnotationCurve(int row, uint32_t annClass, QPainter *painter, - const QwtScaleMap &xMap, const QwtScaleMap &yMap, - const QRectF &canvasRect, QPolygonF &polygon ) const +void AnnotationCurve::fillAnnotationCurve(int row, uint32_t annClass, QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, const QRectF &canvasRect, QPolygonF &polygon) const { - if ( brush().style() == Qt::NoBrush ) - return; + if(brush().style() == Qt::NoBrush) + return; - closePolyline(row, annClass, painter, xMap, yMap, polygon ); - if ( polygon.count() <= 2 ) // a line can't be filled - return; + closePolyline(row, annClass, painter, xMap, yMap, polygon); + if(polygon.count() <= 2) // a line can't be filled + return; - QBrush br = brush(); - QColor color; - const int h = (55 * annClass) % 360; - const int s = 180; - const int v = 170; - color.setHsl(h, s, v); - br.setColor(color); + QBrush br = brush(); + QColor color; + const int h = (55 * annClass) % 360; + const int s = 180; + const int v = 170; + color.setHsl(h, s, v); + br.setColor(color); + painter->save(); + painter->setPen(Qt::NoPen); + painter->setBrush(br); - painter->save(); - - painter->setPen( Qt::NoPen ); - painter->setBrush( br ); - - QwtPainter::drawPolygon( painter, polygon ); + QwtPainter::drawPolygon(painter, polygon); - painter->restore(); + painter->restore(); } void AnnotationCurve::closePolyline(int row, uint32_t annClass, QPainter *painter, const QwtScaleMap &xMap, - const QwtScaleMap &yMap, QPolygonF &polygon) const + const QwtScaleMap &yMap, QPolygonF &polygon) const { - if ( polygon.size() < 2 ) - return; - - const bool doAlign = QwtPainter::roundingAlignment( painter ); - - double HeightInPoints = yMap.invTransform(m_traceHeight) - yMap.invTransform(0); - double baseline = m_pixelOffset + row * (HeightInPoints) + HeightInPoints / 2.0; - - if ( orientation() == Qt::Vertical ) - { - if ( yMap.transformation() ) - baseline = yMap.transformation()->bounded( baseline ); - - double refY = yMap.transform( baseline ); - if ( doAlign ) - refY = qRound( refY ); - - polygon += QPointF( polygon.last().x(), refY ); - polygon += QPointF( polygon.first().x(), refY ); - } - else - { - if ( xMap.transformation() ) - baseline = xMap.transformation()->bounded( baseline ); - - double refX = xMap.transform( baseline ); - if ( doAlign ) - refX = qRound( refX ); - - polygon += QPointF( refX, polygon.last().y() ); - polygon += QPointF( refX, polygon.first().y() ); - } + if(polygon.size() < 2) + return; + + const bool doAlign = QwtPainter::roundingAlignment(painter); + + double HeightInPoints = yMap.invTransform(m_traceHeight) - yMap.invTransform(0); + double baseline = m_pixelOffset + row * (HeightInPoints) + HeightInPoints / 2.0; + + if(orientation() == Qt::Vertical) { + if(yMap.transformation()) + baseline = yMap.transformation()->bounded(baseline); + + double refY = yMap.transform(baseline); + if(doAlign) + refY = qRound(refY); + + polygon += QPointF(polygon.last().x(), refY); + polygon += QPointF(polygon.first().x(), refY); + } else { + if(xMap.transformation()) + baseline = xMap.transformation()->bounded(baseline); + + double refX = xMap.transform(baseline); + if(doAlign) + refX = qRound(refX); + + polygon += QPointF(refX, polygon.last().y()); + polygon += QPointF(refX, polygon.first().y()); + } } uint64_t AnnotationCurve::getMaxAnnotationCount(int index) @@ -689,12 +656,12 @@ uint64_t AnnotationCurve::getMaxAnnotationCount(int index) uint64_t count = 0; std::map decoder(getAnnotationRows()); - for (it = m_annotationRows.begin(); it != m_annotationRows.end(); it++) { + for(it = m_annotationRows.begin(); it != m_annotationRows.end(); it++) { auto temp_annotations = it->second.get_annotations(); - if (it->first.index() == index) { + if(it->first.index() == index) { return temp_annotations.size(); } - if (count < temp_annotations.size()) { + if(count < temp_annotations.size()) { count = temp_annotations.size(); } } @@ -705,208 +672,207 @@ uint64_t AnnotationCurve::getMaxAnnotationCount(int index) void AnnotationCurve::drawTwoSampleAnnotation(int row, const Annotation &ann, QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &canvasRect, const QwtPointMapper &mapper, - const QwtInterval &interval, const QSizeF &titleSize) const + const QwtInterval &interval, const QSizeF &titleSize) const { - // DRAW MULTI POINT ANNOTATION - - double first = fromSampleToTime(ann.start_sample()); - double last = fromSampleToTime(ann.end_sample()); - - double firstPlus1Px = xMap.invTransform(xMap.transform(first) + 3); - double lastMinus1Px = xMap.invTransform(xMap.transform(last) - 3); + // DRAW MULTI POINT ANNOTATION - double HeightInPoints = yMap.invTransform(m_traceHeight) - yMap.invTransform(0); - double offset = m_pixelOffset + row * (HeightInPoints); + double first = fromSampleToTime(ann.start_sample()); + double last = fromSampleToTime(ann.end_sample()); - QVector displayedData; - displayedData += QPointF(first, offset + HeightInPoints / 2.0); - displayedData += QPointF(firstPlus1Px, offset); - displayedData += QPointF(lastMinus1Px, offset); - displayedData += QPointF(last, offset + HeightInPoints / 2.0); - displayedData += QPointF(lastMinus1Px, offset + HeightInPoints); - displayedData += QPointF(firstPlus1Px, offset + HeightInPoints); - displayedData += QPointF(first, offset + HeightInPoints / 2.0); + double firstPlus1Px = xMap.invTransform(xMap.transform(first) + 3); + double lastMinus1Px = xMap.invTransform(xMap.transform(last) - 3); - QwtPointSeriesData *d = new QwtPointSeriesData(displayedData); - QPolygonF polyline = mapper.toPolygonF(xMap, yMap, d, 0, displayedData.size() - 1); - - delete d; + double HeightInPoints = yMap.invTransform(m_traceHeight) - yMap.invTransform(0); + double offset = m_pixelOffset + row * (HeightInPoints); - fillAnnotationCurve(row, ann.ann_class(), painter, xMap, yMap, canvasRect, polyline); + QVector displayedData; + displayedData += QPointF(first, offset + HeightInPoints / 2.0); + displayedData += QPointF(firstPlus1Px, offset); + displayedData += QPointF(lastMinus1Px, offset); + displayedData += QPointF(last, offset + HeightInPoints / 2.0); + displayedData += QPointF(lastMinus1Px, offset + HeightInPoints); + displayedData += QPointF(firstPlus1Px, offset + HeightInPoints); + displayedData += QPointF(first, offset + HeightInPoints / 2.0); - QwtPainter::drawPolyline(painter, polyline); + QwtPointSeriesData *d = new QwtPointSeriesData(displayedData); + QPolygonF polyline = mapper.toPolygonF(xMap, yMap, d, 0, displayedData.size() - 1); - // END DRAW MULTI POINT annotation + delete d; - // DRAW LABEL - const double bonus = xMap.invTransform(titleSize.width() + 5) - xMap.invTransform(0); + fillAnnotationCurve(row, ann.ann_class(), painter, xMap, yMap, canvasRect, polyline); - if (interval.minValue() + bonus > displayedData[0].x()) { - displayedData[0].setX(interval.minValue() + bonus); - } + QwtPainter::drawPolyline(painter, polyline); - if (interval.maxValue() < displayedData[3].x()) { - displayedData[3].setX(interval.maxValue()); - } + // END DRAW MULTI POINT annotation - const double maxWidth = xMap.transform(displayedData[3].x()) - xMap.transform(displayedData[0].x()); - if (maxWidth <= 0) { - return; // There is no room to draw text - } + // DRAW LABEL + const double bonus = xMap.invTransform(titleSize.width() + 5) - xMap.invTransform(0); - QPointF drawTextPoint = (displayedData[3] + displayedData[0]) / 2.0; + if(interval.minValue() + bonus > displayedData[0].x()) { + displayedData[0].setX(interval.minValue() + bonus); + } - double x = xMap.transform(drawTextPoint.x()); - double y = yMap.transform(drawTextPoint.y()); + if(interval.maxValue() < displayedData[3].x()) { + displayedData[3].setX(interval.maxValue()); + } - painter->save(); - painter->setPen(QPen(QBrush(Qt::black), 20)); + const double maxWidth = xMap.transform(displayedData[3].x()) - xMap.transform(displayedData[0].x()); + if(maxWidth <= 0) { + return; // There is no room to draw text + } - // TODO: add text that corresponds to given annotation (maybe pass Annotation instead of first/last) - // See in list of strings available for annotation which one fits due to plotting size. Also if there is space - // draw the text centered if the annotation goes beyond plot limits, make it fit the visible area (left/right shift - // from center) - QSizeF size = QwtText("").textSize(painter->font()); - QString text = ""; - for (auto it = ann.annotations().begin(); it != ann.annotations().end(); ++it) { - QString str = *it; - QSizeF sz = QwtText(str).textSize(painter->font()); - if (sz.width() < maxWidth) { - text = str; - size = sz; - break; // found something - } - } + QPointF drawTextPoint = (displayedData[3] + displayedData[0]) / 2.0; + double x = xMap.transform(drawTextPoint.x()); + double y = yMap.transform(drawTextPoint.y()); - QRectF textRect(QPointF(0.0, 0.0), size); - textRect.moveCenter(QPointF(x, y)); + painter->save(); + painter->setPen(QPen(QBrush(Qt::black), 20)); + + // TODO: add text that corresponds to given annotation (maybe pass Annotation instead of first/last) + // See in list of strings available for annotation which one fits due to plotting size. Also if there is space + // draw the text centered if the annotation goes beyond plot limits, make it fit the visible area (left/right + // shift from center) + QSizeF size = QwtText("").textSize(painter->font()); + QString text = ""; + for(auto it = ann.annotations().begin(); it != ann.annotations().end(); ++it) { + QString str = *it; + QSizeF sz = QwtText(str).textSize(painter->font()); + if(sz.width() < maxWidth) { + text = str; + size = sz; + break; // found something + } + } - painter->drawText(textRect, text); + QRectF textRect(QPointF(0.0, 0.0), size); + textRect.moveCenter(QPointF(x, y)); - painter->restore(); + painter->drawText(textRect, text); - // END DRAW LABEL + painter->restore(); + // END DRAW LABEL } void AnnotationCurve::drawOneSampleAnnotation(int row, const Annotation &ann, QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &canvasRect, const QwtPointMapper &mapper, - const QwtInterval &interval, const QSizeF &titleSize) const { - double xx = xMap.transform(fromSampleToTime(ann.start_sample())); - // 20 px - double HeightInPoints = yMap.invTransform(m_traceHeight) - yMap.invTransform(0); - double yy = yMap.transform(m_pixelOffset + row * (HeightInPoints) + HeightInPoints / 2.0); -/* double w = xMap.transform(6); - double h = yMap.transform(6); */// TODO: compute height to fit class text and + const QwtInterval &interval, const QSizeF &titleSize) const +{ + double xx = xMap.transform(fromSampleToTime(ann.start_sample())); + // 20 px + double HeightInPoints = yMap.invTransform(m_traceHeight) - yMap.invTransform(0); + double yy = yMap.transform(m_pixelOffset + row * (HeightInPoints) + HeightInPoints / 2.0); + /* double w = xMap.transform(6); + double h = yMap.transform(6); */// TODO: compute height to fit class text and // compute text font to fit height (balance between this two rules) - QBrush br = brush(); - QColor color; - const int h = (55 * ann.ann_class()) % 360; - const int s = 180; - const int v = 170; - color.setHsl(h, s, v); - br.setColor(color); - - painter->save(); - painter->setBrush(br); - painter->drawEllipse(QPointF(xx, yy), m_traceHeight / 2.0, m_traceHeight / 2.0); - painter->restore(); + QBrush br = brush(); + QColor color; + const int h = (55 * ann.ann_class()) % 360; + const int s = 180; + const int v = 170; + color.setHsl(h, s, v); + br.setColor(color); + painter->save(); + painter->setBrush(br); + painter->drawEllipse(QPointF(xx, yy), m_traceHeight / 2.0, m_traceHeight / 2.0); + painter->restore(); - painter->save(); - painter->setPen(QPen(QBrush(Qt::black), 20)); + painter->save(); + painter->setPen(QPen(QBrush(Qt::black), 20)); - const double bonus = xMap.invTransform(titleSize.width() + 5) - xMap.invTransform(0); - const double WidthInPoints = xMap.invTransform(m_traceHeight) - xMap.invTransform(0); + const double bonus = xMap.invTransform(titleSize.width() + 5) - xMap.invTransform(0); + const double WidthInPoints = xMap.invTransform(m_traceHeight) - xMap.invTransform(0); - double x1 = fromSampleToTime(ann.start_sample()) - WidthInPoints / 2.0; - double x2 = fromSampleToTime(ann.start_sample()) + WidthInPoints / 2.0; + double x1 = fromSampleToTime(ann.start_sample()) - WidthInPoints / 2.0; + double x2 = fromSampleToTime(ann.start_sample()) + WidthInPoints / 2.0; - if (interval.minValue() + bonus > x1) { - x1 = interval.minValue() + bonus; - } + if(interval.minValue() + bonus > x1) { + x1 = interval.minValue() + bonus; + } - if (interval.maxValue() < x2) { - x2 = interval.maxValue(); - } + if(interval.maxValue() < x2) { + x2 = interval.maxValue(); + } - QSizeF size = QwtText("").textSize(painter->font()); - QString text = ""; + QSizeF size = QwtText("").textSize(painter->font()); + QString text = ""; - const double maxWidth = (xMap.transform(x2) - xMap.transform(x1)) / 2.0; - for (auto it = ann.annotations().begin(); it != ann.annotations().end(); ++it) { - QString str = *it; - QSizeF sz = QwtText(str).textSize(painter->font()); + const double maxWidth = (xMap.transform(x2) - xMap.transform(x1)) / 2.0; + for(auto it = ann.annotations().begin(); it != ann.annotations().end(); ++it) { + QString str = *it; + QSizeF sz = QwtText(str).textSize(painter->font()); - if (sz.width() < maxWidth) { - text = str; - size = sz; - break; // found something + if(sz.width() < maxWidth) { + text = str; + size = sz; + break; // found something + } } - } - QRectF textRect(QPointF(0.0, 0.0), size); - textRect.moveCenter(QPointF(xx, yy)); + QRectF textRect(QPointF(0.0, 0.0), size); + textRect.moveCenter(QPointF(xx, yy)); - painter->drawText(textRect, text); - - painter->restore(); + painter->drawText(textRect, text); + painter->restore(); } -AnnotationQueryResult AnnotationCurve::annotationAt(const QPointF& p) const +AnnotationQueryResult AnnotationCurve::annotationAt(const QPointF &p) const { - if (m_visibleRows == 0) return {0, nullptr}; - - const auto plt = plot(); - if (plt == nullptr) return {0, nullptr}; - const uint64_t sample = fromTimeToSample(p.x()); - - const auto &ymap = plt->canvasMap(yAxis().pos); - // NOTE: Row height is negative - const double rowHeight = ymap.invTransform(m_traceHeight) - ymap.invTransform(0); - - int empty_ann_count = 0; - for (int index = 0; index <= m_annotationRows.size(); index ++) { - for (const auto &entry: m_annotationRows) { - if (entry.first.index() != index) continue; - const Row &row = entry.first; - const RowData &data = entry.second; - - const auto maxY = m_pixelOffset + (row.index() - empty_ann_count) * rowHeight; - const auto minY = maxY + rowHeight; - - const auto y = p.y(); - if (data.size() == 0) { - empty_ann_count ++; - continue; - } - if (y < minY or y > maxY) continue; - uint64_t prev_end_sample = 0, next_start_sample = 0; - for (uint64_t i = 0; i < data.size(); i++) { - const Annotation *ann = data.annAt(i); - next_start_sample = (i + 1 == data.size()) ? sample + (sample - prev_end_sample)/2 - : data.annAt(i + 1)->start_sample(); - if (ann->end_sample() - ann->start_sample() < 2 && - sample + (sample - prev_end_sample)/2 >= ann->start_sample() and sample - (next_start_sample - sample)/2 <= ann->end_sample()) { - return {i, ann}; - } - if (sample >= ann->start_sample() and sample <= ann->end_sample()) { - return {i, ann}; - } - prev_end_sample = ann->end_sample(); - } - } - } - return {0, nullptr}; + if(m_visibleRows == 0) + return {0, nullptr}; + + const auto plt = plot(); + if(plt == nullptr) + return {0, nullptr}; + const uint64_t sample = fromTimeToSample(p.x()); + + const auto &ymap = plt->canvasMap(yAxis().pos); + // NOTE: Row height is negative + const double rowHeight = ymap.invTransform(m_traceHeight) - ymap.invTransform(0); + + int empty_ann_count = 0; + for(int index = 0; index <= m_annotationRows.size(); index++) { + for(const auto &entry : m_annotationRows) { + if(entry.first.index() != index) + continue; + const Row &row = entry.first; + const RowData &data = entry.second; + + const auto maxY = m_pixelOffset + (row.index() - empty_ann_count) * rowHeight; + const auto minY = maxY + rowHeight; + + const auto y = p.y(); + if(data.size() == 0) { + empty_ann_count++; + continue; + } + if(y < minY or y > maxY) + continue; + uint64_t prev_end_sample = 0, next_start_sample = 0; + for(uint64_t i = 0; i < data.size(); i++) { + const Annotation *ann = data.annAt(i); + next_start_sample = (i + 1 == data.size()) ? sample + (sample - prev_end_sample) / 2 + : data.annAt(i + 1)->start_sample(); + if(ann->end_sample() - ann->start_sample() < 2 && + sample + (sample - prev_end_sample) / 2 >= ann->start_sample() and + sample - (next_start_sample - sample) / 2 <= ann->end_sample()) { + return {i, ann}; + } + if(sample >= ann->start_sample() and sample <= ann->end_sample()) { + return {i, ann}; + } + prev_end_sample = ann->end_sample(); + } + } + } + return {0, nullptr}; } -bool AnnotationCurve::testHit(const QPointF& p) const -{ - return annotationAt(p).isValid(); -} +bool AnnotationCurve::testHit(const QPointF &p) const { return annotationAt(p).isValid(); } #include "moc_annotationcurve.cpp" diff --git a/gui/sigrok-gui/src/annotationdecoder.cpp b/gui/sigrok-gui/src/annotationdecoder.cpp index bae0eaecf2..27978b0da1 100644 --- a/gui/sigrok-gui/src/annotationdecoder.cpp +++ b/gui/sigrok-gui/src/annotationdecoder.cpp @@ -18,11 +18,12 @@ * along with this program. If not, see . */ - #include "annotationdecoder.h" -#include + #include + #include +#include using namespace scopy; @@ -32,125 +33,137 @@ std::mutex AnnotationDecoder::g_sessionMutex; void AnnotationDecoder::initDecoderChannels() { - uint16_t id = 0; - - // Copy existing entries, create new as needed - const srd_decoder* srd_d = m_stack.front()->decoder(); - const GSList *l; - - // Mandatory channels - for (l = srd_d->channels; l; l = l->next) { - const struct srd_channel *const pdch = (struct srd_channel *)l->data; - bool ch_added = false; - - if (!ch_added) { - // Create new entry without a mapped signal - DecodeChannel ch = {id++, 0, false, false, - QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc), - SRD_INITIAL_PIN_SAME_AS_SAMPLE0, m_stack.front(), pdch}; - m_channels.push_back(ch); - } - } - - // Optional channels - int optIndex = 0; - for (l = srd_d->opt_channels; l; l = l->next) { - const struct srd_channel *const pdch = (struct srd_channel *)l->data; - bool ch_added = false; - - if (!ch_added) { - // Create new entry without a mapped signal - DecodeChannel ch = {id++, 0, true, false, - QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc), - SRD_INITIAL_PIN_SAME_AS_SAMPLE0, m_stack.front(), pdch}; - m_channels.push_back(ch); - } - - optIndex++; - } + uint16_t id = 0; + + // Copy existing entries, create new as needed + const srd_decoder *srd_d = m_stack.front()->decoder(); + const GSList *l; + + // Mandatory channels + for(l = srd_d->channels; l; l = l->next) { + const struct srd_channel *const pdch = (struct srd_channel *)l->data; + bool ch_added = false; + + if(!ch_added) { + // Create new entry without a mapped signal + DecodeChannel ch = {id++, + 0, + false, + false, + QString::fromUtf8(pdch->name), + QString::fromUtf8(pdch->desc), + SRD_INITIAL_PIN_SAME_AS_SAMPLE0, + m_stack.front(), + pdch}; + m_channels.push_back(ch); + } + } + + // Optional channels + int optIndex = 0; + for(l = srd_d->opt_channels; l; l = l->next) { + const struct srd_channel *const pdch = (struct srd_channel *)l->data; + bool ch_added = false; + + if(!ch_added) { + // Create new entry without a mapped signal + DecodeChannel ch = {id++, + 0, + true, + false, + QString::fromUtf8(pdch->name), + QString::fromUtf8(pdch->desc), + SRD_INITIAL_PIN_SAME_AS_SAMPLE0, + m_stack.front(), + pdch}; + m_channels.push_back(ch); + } + + optIndex++; + } } AnnotationDecoder::AnnotationDecoder(AnnotationCurve *annotationCurve, std::shared_ptr initialDecoder) - : m_annotationCurve(annotationCurve) - , m_decodeThread(nullptr) - , m_srdSession(nullptr) - , m_decodeCanceled(false) - , m_lastSample(0) + : m_annotationCurve(annotationCurve) + , m_decodeThread(nullptr) + , m_srdSession(nullptr) + , m_decodeCanceled(false) + , m_lastSample(0) { - // 1. Get stacked decoder from annotation Curve - // 2. Configure curve (channels and annotations) - // 3. spawn thread for decoding and make it wait + // 1. Get stacked decoder from annotation Curve + // 2. Configure curve (channels and annotations) + // 3. spawn thread for decoding and make it wait - // m_annotationCurve->getDecoder() + // m_annotationCurve->getDecoder() - m_stack.push_back(initialDecoder); + m_stack.push_back(initialDecoder); - initDecoderChannels(); + initDecoderChannels(); - stackChanged(); - startDecode(); + stackChanged(); + startDecode(); } AnnotationDecoder::~AnnotationDecoder() { - if (m_srdSession) { - m_decodeCanceled = true; - srd_session_terminate_reset(m_srdSession); - { - std::unique_lock lock(m_newDataMutex); - m_newDataCv.notify_one(); - } - - srd_session_metadata_set(m_srdSession, SRD_CONF_SAMPLERATE, - g_variant_new_uint64(m_annotationCurve->getSampleRate())); - for (const std::shared_ptr &dec : m_stack) { - dec->apply_all_options(); - } + if(m_srdSession) { + m_decodeCanceled = true; + srd_session_terminate_reset(m_srdSession); + { + std::unique_lock lock(m_newDataMutex); + m_newDataCv.notify_one(); + } + + srd_session_metadata_set(m_srdSession, SRD_CONF_SAMPLERATE, + g_variant_new_uint64(m_annotationCurve->getSampleRate())); + for(const std::shared_ptr &dec : m_stack) { + dec->apply_all_options(); + } } stopDecode(); } void AnnotationDecoder::stackDecoder(std::shared_ptr decoder) { - if (m_srdSession) { - m_decodeCanceled = true; - srd_session_terminate_reset(m_srdSession); - { - std::unique_lock lock(m_newDataMutex); - m_newDataCv.notify_one(); - } - - srd_session_metadata_set(m_srdSession, SRD_CONF_SAMPLERATE, - g_variant_new_uint64(m_annotationCurve->getSampleRate())); -// qDebug() << "SampleRate: " << m_annotationCurve->getSampleRate(); - for (const std::shared_ptr &dec : m_stack) { - dec->apply_all_options(); - } - } - - m_stack.push_back(decoder); - - // reconfigure stack - stackChanged(); - startDecode(); + if(m_srdSession) { + m_decodeCanceled = true; + srd_session_terminate_reset(m_srdSession); + { + std::unique_lock lock(m_newDataMutex); + m_newDataCv.notify_one(); + } + + srd_session_metadata_set(m_srdSession, SRD_CONF_SAMPLERATE, + g_variant_new_uint64(m_annotationCurve->getSampleRate())); + // qDebug() << "SampleRate: " << m_annotationCurve->getSampleRate(); + for(const std::shared_ptr &dec : m_stack) { + dec->apply_all_options(); + } + } + + m_stack.push_back(decoder); + + // reconfigure stack + stackChanged(); + startDecode(); } void AnnotationDecoder::unstackDecoder(std::shared_ptr decoder) { - if (m_srdSession) { - m_decodeCanceled = true; - srd_session_terminate_reset(m_srdSession); - { - std::unique_lock lock(m_newDataMutex); - m_newDataCv.notify_one(); - } - - srd_session_metadata_set(m_srdSession, SRD_CONF_SAMPLERATE, - g_variant_new_uint64(m_annotationCurve->getSampleRate())); - // qDebug() << "SampleRate: " << m_annotationCurve->getSampleRate(); - for (const std::shared_ptr &dec : m_stack) { - dec->apply_all_options(); - } + if(m_srdSession) { + m_decodeCanceled = true; + srd_session_terminate_reset(m_srdSession); + { + std::unique_lock lock(m_newDataMutex); + m_newDataCv.notify_one(); + } + + srd_session_metadata_set(m_srdSession, SRD_CONF_SAMPLERATE, + g_variant_new_uint64(m_annotationCurve->getSampleRate())); + // qDebug() << "SampleRate: " << m_annotationCurve->getSampleRate(); + for(const std::shared_ptr &dec : m_stack) { + dec->apply_all_options(); + } } qDebug() << "stack size before deleting: " << m_stack.size(); @@ -166,107 +179,105 @@ void AnnotationDecoder::unstackDecoder(std::shared_ptr decoder) void AnnotationDecoder::startDecode() { -// qDebug() << "Start decode!"; - // TODO: cancel mechanism - - if (m_srdSession) { - m_decodeCanceled = true; - srd_session_terminate_reset(m_srdSession); - { - std::unique_lock lock(m_newDataMutex); - m_newDataCv.notify_one(); - } - - srd_session_metadata_set(m_srdSession, SRD_CONF_SAMPLERATE, - g_variant_new_uint64(m_annotationCurve->getSampleRate())); -// qDebug() << "SampleRate: " << m_annotationCurve->getSampleRate(); - for (const std::shared_ptr &dec : m_stack) { - dec->apply_all_options(); - } - } - - if (m_lastSample != 0) { - -// m_annotationCurve->reset(); - // set curves class rows and annotation rows - m_annotationCurve->setClassRows(m_class_rows); - m_annotationCurve->setAnnotationRows(m_annotation_rows); - - std::unique_lock lock(m_newDataMutex); - { - // clear the current queue content - std::queue> empty; - m_newDataQueue.swap(empty); - } - uint64_t q = m_lastSample / MAX_CHUNK_SIZE; - uint64_t r = m_lastSample % MAX_CHUNK_SIZE; - for (uint64_t i = 0; i < q; ++ i) { - m_newDataQueue.emplace(0 + i * MAX_CHUNK_SIZE, MAX_CHUNK_SIZE * (i + 1)); - } - - if (r != 0) { - m_newDataQueue.emplace(MAX_CHUNK_SIZE * q, MAX_CHUNK_SIZE * q + r); - } - } - - - if (srd_session_start(m_srdSession) != SRD_OK) { - qDebug() << "srd_session_start returned error!"; - } else { -// qDebug() << "srd_session_start returned SRD_OK"; - } - - if (m_decodeThread) { - m_decodeThread->join(); - delete m_decodeThread; - } - - m_decodeCanceled = false; - m_decodeThread = new std::thread(&AnnotationDecoder::decodeProc, this); - - m_newDataCv.notify_one(); -// qDebug() << "finished start decode"; + // qDebug() << "Start decode!"; + // TODO: cancel mechanism + + if(m_srdSession) { + m_decodeCanceled = true; + srd_session_terminate_reset(m_srdSession); + { + std::unique_lock lock(m_newDataMutex); + m_newDataCv.notify_one(); + } + + srd_session_metadata_set(m_srdSession, SRD_CONF_SAMPLERATE, + g_variant_new_uint64(m_annotationCurve->getSampleRate())); + // qDebug() << "SampleRate: " << m_annotationCurve->getSampleRate(); + for(const std::shared_ptr &dec : m_stack) { + dec->apply_all_options(); + } + } + + if(m_lastSample != 0) { + + // m_annotationCurve->reset(); + // set curves class rows and annotation rows + m_annotationCurve->setClassRows(m_class_rows); + m_annotationCurve->setAnnotationRows(m_annotation_rows); + + std::unique_lock lock(m_newDataMutex); + { + // clear the current queue content + std::queue> empty; + m_newDataQueue.swap(empty); + } + uint64_t q = m_lastSample / MAX_CHUNK_SIZE; + uint64_t r = m_lastSample % MAX_CHUNK_SIZE; + for(uint64_t i = 0; i < q; ++i) { + m_newDataQueue.emplace(0 + i * MAX_CHUNK_SIZE, MAX_CHUNK_SIZE * (i + 1)); + } + + if(r != 0) { + m_newDataQueue.emplace(MAX_CHUNK_SIZE * q, MAX_CHUNK_SIZE * q + r); + } + } + + if(srd_session_start(m_srdSession) != SRD_OK) { + qDebug() << "srd_session_start returned error!"; + } else { + // qDebug() << "srd_session_start returned SRD_OK"; + } + + if(m_decodeThread) { + m_decodeThread->join(); + delete m_decodeThread; + } + + m_decodeCanceled = false; + m_decodeThread = new std::thread(&AnnotationDecoder::decodeProc, this); + + m_newDataCv.notify_one(); + // qDebug() << "finished start decode"; } void AnnotationDecoder::stopDecode() { -// qDebug() << "stop decoder!"; - m_decodeCanceled = true; - { - std::unique_lock lock(m_newDataMutex); - m_newDataCv.notify_one(); - } - if (m_decodeThread) { - if (m_decodeThread->joinable()) - m_decodeThread->join(); - delete m_decodeThread; - m_decodeThread = nullptr; - } - - std::lock_guard srd_lock(g_sessionMutex); - - if (m_srdSession) { - srd_session_destroy(m_srdSession); - m_srdSession = nullptr; - } - - for (const shared_ptr &dec : m_stack) { - dec->invalidate_decoder_inst(); - } - -// qDebug() << "finished stop decoder"; + // qDebug() << "stop decoder!"; + m_decodeCanceled = true; + { + std::unique_lock lock(m_newDataMutex); + m_newDataCv.notify_one(); + } + if(m_decodeThread) { + if(m_decodeThread->joinable()) + m_decodeThread->join(); + delete m_decodeThread; + m_decodeThread = nullptr; + } + + std::lock_guard srd_lock(g_sessionMutex); + + if(m_srdSession) { + srd_session_destroy(m_srdSession); + m_srdSession = nullptr; + } + + for(const shared_ptr &dec : m_stack) { + dec->invalidate_decoder_inst(); + } + + // qDebug() << "finished stop decoder"; } void AnnotationDecoder::dataAvailable(uint64_t from, uint64_t to, uint16_t *data) -{ -// Emplace new data segment in a queue as new data might arrive -// faster than libsigrokdecode can process +{ + // Emplace new data segment in a queue as new data might arrive + // faster than libsigrokdecode can process m_data = data; - if (from != to) { + if(from != to) { std::unique_lock lock(m_newDataMutex); - m_lastSample = to; m_newDataQueue.emplace(from, to); @@ -275,53 +286,50 @@ void AnnotationDecoder::dataAvailable(uint64_t from, uint64_t to, uint16_t *data } } -std::vector > AnnotationDecoder::getDecoderStack() -{ - return m_stack; -} +std::vector> AnnotationDecoder::getDecoderStack() { return m_stack; } void AnnotationDecoder::unassignChannel(uint16_t chId) { - if (m_srdSession) { - m_decodeCanceled = true; - srd_session_terminate_reset(m_srdSession); - { - std::unique_lock lock(m_newDataMutex); - m_newDataCv.notify_one(); - } - - srd_session_metadata_set(m_srdSession, SRD_CONF_SAMPLERATE, - g_variant_new_uint64(m_annotationCurve->getSampleRate())); -// qDebug() << "SampleRate: " << m_annotationCurve->getSampleRate(); - for (const std::shared_ptr &dec : m_stack) { - dec->apply_all_options(); - } - } - - for (auto & ch : m_channels) { - if (ch.id == chId) { - ch.assigned_signal = false; - break; - } - } - - stackChanged(); - startDecode(); + if(m_srdSession) { + m_decodeCanceled = true; + srd_session_terminate_reset(m_srdSession); + { + std::unique_lock lock(m_newDataMutex); + m_newDataCv.notify_one(); + } + + srd_session_metadata_set(m_srdSession, SRD_CONF_SAMPLERATE, + g_variant_new_uint64(m_annotationCurve->getSampleRate())); + // qDebug() << "SampleRate: " << m_annotationCurve->getSampleRate(); + for(const std::shared_ptr &dec : m_stack) { + dec->apply_all_options(); + } + } + + for(auto &ch : m_channels) { + if(ch.id == chId) { + ch.assigned_signal = false; + break; + } + } + + stackChanged(); + startDecode(); } std::vector AnnotationDecoder::getDecoderChannels() { - vector chls; - for (DecodeChannel &ch : m_channels) { - chls.push_back(&ch); - } + vector chls; + for(DecodeChannel &ch : m_channels) { + chls.push_back(&ch); + } - return chls; + return chls; } void AnnotationDecoder::reset() { -// std::unique_lock lock(m_newDataMutex); + // std::unique_lock lock(m_newDataMutex); m_lastSample = 0; stopDecode(); @@ -331,186 +339,180 @@ void AnnotationDecoder::reset() void AnnotationDecoder::assignChannel(uint16_t chId, uint16_t bitId) { - if (m_srdSession) { - m_decodeCanceled = true; - srd_session_terminate_reset(m_srdSession); - { - std::unique_lock lock(m_newDataMutex); - m_newDataCv.notify_one(); - } - - srd_session_metadata_set(m_srdSession, SRD_CONF_SAMPLERATE, - g_variant_new_uint64(m_annotationCurve->getSampleRate())); -// qDebug() << "SampleRate: " << m_annotationCurve->getSampleRate(); - for (const std::shared_ptr &dec : m_stack) { - dec->apply_all_options(); - } - } - - qDebug() << "Assigning to chId: " << chId << " bitid: " << bitId; - - for (auto & ch : m_channels) { - if (ch.id == chId) { - ch.bit_id = bitId; - ch.assigned_signal = true; - break; - } - } - - for (auto &ch : m_channels) { - qDebug() << "ch: " << ch.id << " has ch assigned: " << ch.assigned_signal << " with bitid: " << ch.bit_id; - } - - stackChanged(); - startDecode(); -} + if(m_srdSession) { + m_decodeCanceled = true; + srd_session_terminate_reset(m_srdSession); + { + std::unique_lock lock(m_newDataMutex); + m_newDataCv.notify_one(); + } + + srd_session_metadata_set(m_srdSession, SRD_CONF_SAMPLERATE, + g_variant_new_uint64(m_annotationCurve->getSampleRate())); + // qDebug() << "SampleRate: " << m_annotationCurve->getSampleRate(); + for(const std::shared_ptr &dec : m_stack) { + dec->apply_all_options(); + } + } -int AnnotationDecoder::getNrOfChannels() const -{ - return m_channels.size(); + qDebug() << "Assigning to chId: " << chId << " bitid: " << bitId; + + for(auto &ch : m_channels) { + if(ch.id == chId) { + ch.bit_id = bitId; + ch.assigned_signal = true; + break; + } + } + + for(auto &ch : m_channels) { + qDebug() << "ch: " << ch.id << " has ch assigned: " << ch.assigned_signal + << " with bitid: " << ch.bit_id; + } + + stackChanged(); + startDecode(); } +int AnnotationDecoder::getNrOfChannels() const { return m_channels.size(); } + void AnnotationDecoder::stackChanged() { - stopDecode(); - - std::lock_guard srd_lock(g_sessionMutex); - - if (srd_session_new(&m_srdSession) != SRD_OK) { - qDebug() << "srd_session_new returned error!"; - } else { -// qDebug() << "srd_session_new returned SRD_OK"; - } - - vector chls; - for (DecodeChannel &ch : m_channels) { - chls.push_back(&ch); - } - - m_stack.front()->set_channels(chls); - - srd_decoder_inst *prev_di = nullptr; - for (const shared_ptr& dec : m_stack) { - srd_decoder_inst *const di = dec->create_decoder_inst(m_srdSession); - if (prev_di) - srd_inst_stack(m_srdSession, prev_di, di); - - prev_di = di; - } - - // Map out all annotation classes - int row_index = 0; - for (const shared_ptr& dec : m_stack) { - assert(dec); - const srd_decoder *const decc = dec->decoder(); - assert(dec->decoder()); - - for (const GSList *l = decc->annotation_rows; l; l = l->next) { - const srd_decoder_annotation_row *const ann_row = - (srd_decoder_annotation_row *)l->data; - assert(ann_row); - - const Row row(row_index++, decc, ann_row); - - int count = 0; - for (const GSList *ll = ann_row->ann_classes; - ll; ll = ll->next) { - m_class_rows[std::make_pair(decc, - GPOINTER_TO_INT(ll->data))] = row; - count ++; - } - } - } - - int index = 0; - for (const shared_ptr& dec : m_stack) { - assert(dec); - const srd_decoder *const decc = dec->decoder(); - assert(dec->decoder()); - -// int index = 0; - // Add a row for the decoder if it doesn't have a row list - if (!decc->annotation_rows) - (m_annotation_rows)[Row(index++, decc)] = RowData(); - - // Add the decoder rows - for (const GSList *l = decc->annotation_rows; l; l = l->next) { - const srd_decoder_annotation_row *const ann_row = - (srd_decoder_annotation_row *)l->data; - assert(ann_row); - - const Row row(index++, decc, ann_row); - - // Add a new empty row data object - (m_annotation_rows)[row] = RowData(); - } - } - - // set curves class rows and annotation rows - m_annotationCurve->setClassRows(m_class_rows); - m_annotationCurve->setAnnotationRows(m_annotation_rows); - - // register curve to receive new annotations from libsigrokdecode - srd_pd_output_callback_add(m_srdSession, SRD_OUTPUT_ANN, - AnnotationCurve::annotationCallback, m_annotationCurve); + stopDecode(); + + std::lock_guard srd_lock(g_sessionMutex); + + if(srd_session_new(&m_srdSession) != SRD_OK) { + qDebug() << "srd_session_new returned error!"; + } else { + // qDebug() << "srd_session_new returned SRD_OK"; + } + + vector chls; + for(DecodeChannel &ch : m_channels) { + chls.push_back(&ch); + } + + m_stack.front()->set_channels(chls); + + srd_decoder_inst *prev_di = nullptr; + for(const shared_ptr &dec : m_stack) { + srd_decoder_inst *const di = dec->create_decoder_inst(m_srdSession); + if(prev_di) + srd_inst_stack(m_srdSession, prev_di, di); + + prev_di = di; + } + + // Map out all annotation classes + int row_index = 0; + for(const shared_ptr &dec : m_stack) { + assert(dec); + const srd_decoder *const decc = dec->decoder(); + assert(dec->decoder()); + + for(const GSList *l = decc->annotation_rows; l; l = l->next) { + const srd_decoder_annotation_row *const ann_row = (srd_decoder_annotation_row *)l->data; + assert(ann_row); + + const Row row(row_index++, decc, ann_row); + + int count = 0; + for(const GSList *ll = ann_row->ann_classes; ll; ll = ll->next) { + m_class_rows[std::make_pair(decc, GPOINTER_TO_INT(ll->data))] = row; + count++; + } + } + } + + int index = 0; + for(const shared_ptr &dec : m_stack) { + assert(dec); + const srd_decoder *const decc = dec->decoder(); + assert(dec->decoder()); + + // int index = 0; + // Add a row for the decoder if it doesn't have a row list + if(!decc->annotation_rows) + (m_annotation_rows)[Row(index++, decc)] = RowData(); + + // Add the decoder rows + for(const GSList *l = decc->annotation_rows; l; l = l->next) { + const srd_decoder_annotation_row *const ann_row = (srd_decoder_annotation_row *)l->data; + assert(ann_row); + + const Row row(index++, decc, ann_row); + + // Add a new empty row data object + (m_annotation_rows)[row] = RowData(); + } + } + + // set curves class rows and annotation rows + m_annotationCurve->setClassRows(m_class_rows); + m_annotationCurve->setAnnotationRows(m_annotation_rows); + + // register curve to receive new annotations from libsigrokdecode + srd_pd_output_callback_add(m_srdSession, SRD_OUTPUT_ANN, AnnotationCurve::annotationCallback, + m_annotationCurve); } void AnnotationDecoder::decodeProc() { - while (!m_decodeCanceled) { + while(!m_decodeCanceled) { - std::unique_lock lock(m_newDataMutex); + std::unique_lock lock(m_newDataMutex); - // Wait for data -// if (m_newDataQueue.empty()) { - m_newDataCv.wait(lock, [&]{return !m_newDataQueue.empty() || m_decodeCanceled;}); -// } + // Wait for data + // if (m_newDataQueue.empty()) { + m_newDataCv.wait(lock, [&] { return !m_newDataQueue.empty() || m_decodeCanceled; }); + // } - if (m_decodeCanceled) { -// qDebug() << "cancel requested!"; - break; - } + if(m_decodeCanceled) { + // qDebug() << "cancel requested!"; + break; + } - for (const shared_ptr & dec : m_stack) { - if (!dec->have_required_channels()) { -// qDebug() << "not having required channels!"; - // TODO: SET ERROR MESSAGE - m_annotationCurve->setState(-2); + for(const shared_ptr &dec : m_stack) { + if(!dec->have_required_channels()) { + // qDebug() << "not having required channels!"; + // TODO: SET ERROR MESSAGE + m_annotationCurve->setState(-2); - return; - } - } + return; + } + } - // TODO: CHECK FOR ERRORS + // TODO: CHECK FOR ERRORS -// qDebug() << "exit wait!"; + // qDebug() << "exit wait!"; - uint64_t start, stop; - std::tie(start, stop) = m_newDataQueue.front(); - m_newDataQueue.pop(); - lock.unlock(); // unlock to allow new data to enter the queue + uint64_t start, stop; + std::tie(start, stop) = m_newDataQueue.front(); + m_newDataQueue.pop(); + lock.unlock(); // unlock to allow new data to enter the queue - uint64_t chunkSize = stop - start; - std::unique_ptr chunk(new uint16_t[chunkSize]); + uint64_t chunkSize = stop - start; + std::unique_ptr chunk(new uint16_t[chunkSize]); - uint16_t *data = m_data; + uint16_t *data = m_data; - if (!data) { - continue; - } + if(!data) { + continue; + } - memcpy(chunk.get(), data + start, chunkSize * sizeof(uint16_t)); + memcpy(chunk.get(), data + start, chunkSize * sizeof(uint16_t)); -// qDebug() << "send data!"; - std::lock_guard srd_lock(g_sessionMutex); + // qDebug() << "send data!"; + std::lock_guard srd_lock(g_sessionMutex); - if (srd_session_send(m_srdSession, start, stop, reinterpret_cast( - chunk.get()), chunkSize, sizeof(uint16_t)) != SRD_OK) { -// qDebug() << "No bueno!"; - } + if(srd_session_send(m_srdSession, start, stop, reinterpret_cast(chunk.get()), chunkSize, + sizeof(uint16_t)) != SRD_OK) { + // qDebug() << "No bueno!"; + } - // Notify curve that annotations are now available to be drawn on the plot - // srd_session_send blocks untill all samples are processed - m_annotationCurve->newAnnotations(); - } + // Notify curve that annotations are now available to be drawn on the plot + // srd_session_send blocks untill all samples are processed + m_annotationCurve->newAnnotations(); + } } diff --git a/gui/sigrok-gui/src/binding/binding.cpp b/gui/sigrok-gui/src/binding/binding.cpp index dac42da39c..67973c8a27 100644 --- a/gui/sigrok-gui/src/binding/binding.cpp +++ b/gui/sigrok-gui/src/binding/binding.cpp @@ -37,8 +37,9 @@ * along with this program. If not, see . */ +#include "binding/binding.hpp" -#include +#include "prop/property.hpp" #include #include @@ -46,9 +47,7 @@ #include #include -#include "prop/property.hpp" - -#include "binding/binding.hpp" +#include using std::shared_ptr; using std::string; @@ -57,14 +56,11 @@ using std::vector; namespace scopy { namespace bind { -const vector< shared_ptr >& Binding::properties() -{ - return properties_; -} +const vector> &Binding::properties() { return properties_; } void Binding::commit() { - for (shared_ptr p : properties_) { + for(shared_ptr p : properties_) { assert(p); p->commit(); } @@ -76,13 +72,13 @@ void Binding::add_properties_to_form(QFormLayout *layout, bool auto_commit) help_labels_.clear(); - for (shared_ptr p : properties_) { + for(shared_ptr p : properties_) { assert(p); QWidget *widget; QLabel *help_lbl = nullptr; - if (p->desc().isEmpty()) { + if(p->desc().isEmpty()) { widget = p->get_widget(layout->parentWidget(), auto_commit); } else { @@ -90,8 +86,7 @@ void Binding::add_properties_to_form(QFormLayout *layout, bool auto_commit) help_btn->setFlat(true); help_btn->setIcon(QIcon::fromTheme("info")); help_btn->setToolTip(p->desc()); - connect(help_btn, SIGNAL(clicked(bool)), - this, SLOT(on_help_clicked())); + connect(help_btn, SIGNAL(clicked(bool)), this, SLOT(on_help_clicked())); QHBoxLayout *layout = new QHBoxLayout(); layout->setContentsMargins(0, 0, 0, 0); @@ -107,7 +102,7 @@ void Binding::add_properties_to_form(QFormLayout *layout, bool auto_commit) help_labels_[help_btn] = help_lbl; } - if (p->labeled_widget()) { + if(p->labeled_widget()) { layout->addRow(widget); } else { auto *lbl = new QLabel(p->name()); @@ -116,12 +111,12 @@ void Binding::add_properties_to_form(QFormLayout *layout, bool auto_commit) layout->setSpacing(10); } - if (help_lbl) + if(help_lbl) layout->addRow(help_lbl); } } -QWidget* Binding::get_property_form(QWidget *parent, bool auto_commit) +QWidget *Binding::get_property_form(QWidget *parent, bool auto_commit) { QWidget *const form = new QWidget(parent); QFormLayout *const layout = new QFormLayout(form); @@ -132,7 +127,7 @@ QWidget* Binding::get_property_form(QWidget *parent, bool auto_commit) void Binding::update_property_widgets() { - for (shared_ptr p : properties_) { + for(shared_ptr p : properties_) { assert(p); p->update_widget(); } @@ -140,7 +135,7 @@ void Binding::update_property_widgets() QString Binding::print_variant(QVariant qvar) { - if (!qvar.isValid()) { + if(!qvar.isValid()) { return QString::fromStdString("(null)"); } else { return qvar.toString(); @@ -149,14 +144,14 @@ QString Binding::print_variant(QVariant qvar) void Binding::on_help_clicked() { - QPushButton *btn = qobject_cast(QObject::sender()); + QPushButton *btn = qobject_cast(QObject::sender()); assert(btn); QLabel *lbl = help_labels_.at(btn); lbl->setVisible(!lbl->isVisible()); } -} // namespace binding -} // namespace scopy +} // namespace bind +} // namespace scopy #include "binding/moc_binding.cpp" diff --git a/gui/sigrok-gui/src/binding/decoder.cpp b/gui/sigrok-gui/src/binding/decoder.cpp index f0f35b4b90..7ecc614c1e 100644 --- a/gui/sigrok-gui/src/binding/decoder.cpp +++ b/gui/sigrok-gui/src/binding/decoder.cpp @@ -37,20 +37,20 @@ * along with this program. If not, see . */ - -#include +#include "binding/decoder.hpp" #include "prop/double.hpp" #include "prop/enum.hpp" #include "prop/int.hpp" #include "prop/string.hpp" -#include "binding/decoder.hpp" -#include #include -using std::nullopt; +#include +#include + using std::map; +using std::nullopt; using std::pair; using std::shared_ptr; using std::string; @@ -62,45 +62,37 @@ using scopy::prop::Int; using scopy::prop::Property; using scopy::prop::String; - namespace scopy { namespace bind { -Decoder::Decoder( - scopy::AnnotationDecoder *annDecoder, - shared_ptr decoder) : - m_annDecoder(annDecoder), - decoder_(decoder) +Decoder::Decoder(scopy::AnnotationDecoder *annDecoder, shared_ptr decoder) + : m_annDecoder(annDecoder) + , decoder_(decoder) { assert(decoder_); const srd_decoder *const dec = decoder_->decoder(); assert(dec); - for (GSList *l = dec->options; l; l = l->next) { - const srd_decoder_option *const opt = - (srd_decoder_option*)l->data; + for(GSList *l = dec->options; l; l = l->next) { + const srd_decoder_option *const opt = (srd_decoder_option *)l->data; const QString name = QString::fromUtf8(opt->desc); - const Property::Getter get = [&, opt]() { - return getter(opt->id); }; - const Property::Setter set = [&, opt](QVariant value) { - setter(opt->id, value); }; + const Property::Getter get = [&, opt]() { return getter(opt->id); }; + const Property::Setter set = [&, opt](QVariant value) { setter(opt->id, value); }; shared_ptr prop; - if (opt->values) + if(opt->values) prop = bind_enum(name, "", opt, get, set); - else if (g_variant_is_of_type(opt->def, G_VARIANT_TYPE("d"))) - prop = shared_ptr(new Double(name, "", 2, "", - std::nullopt, std::nullopt, get, set)); - else if (g_variant_is_of_type(opt->def, G_VARIANT_TYPE("x"))) + else if(g_variant_is_of_type(opt->def, G_VARIANT_TYPE("d"))) + prop = shared_ptr(new Double(name, "", 2, "", std::nullopt, std::nullopt, get, set)); + else if(g_variant_is_of_type(opt->def, G_VARIANT_TYPE("x"))) prop = shared_ptr( new Int(name, "", "", std::nullopt, get, set, g_variant_classify(opt->def))); - else if (g_variant_is_of_type(opt->def, G_VARIANT_TYPE("s"))) - prop = shared_ptr( - new String(name, "", get, set)); + else if(g_variant_is_of_type(opt->def, G_VARIANT_TYPE("s"))) + prop = shared_ptr(new String(name, "", get, set)); else continue; @@ -108,15 +100,12 @@ Decoder::Decoder( } } - -shared_ptr Decoder::bind_enum( - const QString &name, const QString &desc, - const srd_decoder_option *option, - Property::Getter getter, Property::Setter setter) +shared_ptr Decoder::bind_enum(const QString &name, const QString &desc, const srd_decoder_option *option, + Property::Getter getter, Property::Setter setter) { - vector< pair > values; - for (GSList *l = option->values; l; l = l->next) { - QVariant var = gVariantToQVariant((GVariant*)l->data); + vector> values; + for(GSList *l = option->values; l; l = l->next) { + QVariant var = gVariantToQVariant((GVariant *)l->data); values.emplace_back(var, print_variant(var)); } @@ -125,11 +114,11 @@ shared_ptr Decoder::bind_enum( QVariant Decoder::gVariantToQVariant(GVariant *value) { - if (!value) + if(!value) return QVariant(); auto classify = g_variant_classify(value); - switch (classify) { + switch(classify) { case G_VARIANT_CLASS_BOOLEAN: return QVariant::fromValue(bool(g_variant_get_boolean(value))); case G_VARIANT_CLASS_BYTE: @@ -160,19 +149,19 @@ QVariant Decoder::gVariantToQVariant(GVariant *value) } case G_VARIANT_CLASS_TUPLE: { // we only handle the (dd) case in enum type property (just 2 children) - if (g_variant_n_children(value) == 2) { + if(g_variant_n_children(value) == 2) { std::vector doubleVector; - for (int i = 0; i < g_variant_n_children(value); i++) { + for(int i = 0; i < g_variant_n_children(value); i++) { GVariant *childVariant = g_variant_get_child_value(value, i); QVariant qVariant = gVariantToQVariant(childVariant); - if (qVariant.isValid()) { + if(qVariant.isValid()) { g_variant_unref(childVariant); return QVariant(); } doubleVector.push_back(qVariant.toDouble()); g_variant_unref(childVariant); } - if (doubleVector.size() != 2) { + if(doubleVector.size() != 2) { return QVariant(); } return QVariant::fromValue>( @@ -182,7 +171,7 @@ QVariant Decoder::gVariantToQVariant(GVariant *value) } default: { const GVariantType *type = g_variant_get_type(value); - if (g_variant_type_equal(type, G_VARIANT_TYPE_BYTESTRING)) { + if(g_variant_type_equal(type, G_VARIANT_TYPE_BYTESTRING)) { return QVariant::fromValue(QByteArray(g_variant_get_bytestring(value))); } } @@ -191,7 +180,6 @@ QVariant Decoder::gVariantToQVariant(GVariant *value) return QVariant(); } - QVariant Decoder::getter(const char *id) { GVariant *val = nullptr; @@ -200,19 +188,18 @@ QVariant Decoder::getter(const char *id) assert(decoder_); // Get the value from the hash table if it is already present - const map& options = decoder_->options(); + const map &options = decoder_->options(); const auto iter = options.find(id); - if (iter != options.end()) { + if(iter != options.end()) { val = (*iter).second; } else { assert(decoder_->decoder()); // Get the default value if not - for (GSList *l = decoder_->decoder()->options; l; l = l->next) { - const srd_decoder_option *const opt = - (srd_decoder_option*)l->data; - if (strcmp(opt->id, id) == 0) { + for(GSList *l = decoder_->decoder()->options; l; l = l->next) { + const srd_decoder_option *const opt = (srd_decoder_option *)l->data; + if(strcmp(opt->id, id) == 0) { val = opt->def; break; } @@ -231,39 +218,37 @@ void Decoder::setter(const char *id, QVariant value) QString prop_val = ""; QMetaType::Type type = static_cast(value.type()); - if (type == QMetaType::QString) { + if(type == QMetaType::QString) { variant = g_variant_new_string(value.toString().toUtf8().constData()); - } else if (type == QMetaType::Bool) { + } else if(type == QMetaType::Bool) { variant = g_variant_new_boolean(value.toBool()); - } else if (type == QMetaType::Char) { + } else if(type == QMetaType::Char) { variant = g_variant_new_byte(value.toChar().toLatin1()); - } else if (type == QMetaType::Short) { + } else if(type == QMetaType::Short) { variant = g_variant_new_int16(value.value()); - } else if (type == QMetaType::UShort) { + } else if(type == QMetaType::UShort) { variant = g_variant_new_uint16(value.value()); - } else if (type == QMetaType::Int) { + } else if(type == QMetaType::Int) { variant = g_variant_new_int32(value.value()); - } else if (type == QMetaType::UInt) { + } else if(type == QMetaType::UInt) { variant = g_variant_new_uint32(value.value()); - } else if (type == QMetaType::Long) { + } else if(type == QMetaType::Long) { variant = g_variant_new_int64(value.value()); - } else if (type == QMetaType::LongLong) { + } else if(type == QMetaType::LongLong) { variant = g_variant_new_int64(value.value()); - } else if (type == QMetaType::ULong) { + } else if(type == QMetaType::ULong) { variant = g_variant_new_uint64(value.value()); - } else if (type == QMetaType::ULongLong) { + } else if(type == QMetaType::ULongLong) { variant = g_variant_new_uint64(value.value()); - } else if (type == QMetaType::Double) { + } else if(type == QMetaType::Double) { variant = g_variant_new_double(value.toDouble()); } else { // Check if we got a tuple (dd) from the decoders bool pairDD = value.canConvert>(); - if (pairDD) { + if(pairDD) { auto pairData = value.value>(); - GVariant *tupleVariants[] = { - g_variant_new_double(pairData.first), - g_variant_new_double(pairData.second) - }; + GVariant *tupleVariants[] = {g_variant_new_double(pairData.first), + g_variant_new_double(pairData.second)}; variant = g_variant_new_tuple(tupleVariants, 2); } else { variant = g_variant_new_string(value.toString().toUtf8().constData()); @@ -275,5 +260,5 @@ void Decoder::setter(const char *id, QVariant value) m_annDecoder->startDecode(); } -} // namespace binding -} // namespace scopy +} // namespace bind +} // namespace scopy diff --git a/gui/sigrok-gui/src/decoder.cpp b/gui/sigrok-gui/src/decoder.cpp index 91e6b2a329..3155276962 100644 --- a/gui/sigrok-gui/src/decoder.cpp +++ b/gui/sigrok-gui/src/decoder.cpp @@ -39,10 +39,10 @@ #include "decoder.h" -#include - #include + #include +#include using std::map; using std::string; @@ -50,141 +50,115 @@ using std::string; using namespace scopy; using namespace scopy::logic; -Decoder::Decoder(const srd_decoder *const dec) : - decoder_(dec), - shown_(true), - decoder_inst_(nullptr) -{ - -} +Decoder::Decoder(const srd_decoder *const dec) + : decoder_(dec) + , shown_(true) + , decoder_inst_(nullptr) +{} Decoder::~Decoder() { - for (auto& option : options_) - g_variant_unref(option.second); + for(auto &option : options_) + g_variant_unref(option.second); } -const srd_decoder* Decoder::decoder() const -{ - return decoder_; -} +const srd_decoder *Decoder::decoder() const { return decoder_; } -bool Decoder::shown() const -{ - return shown_; -} +bool Decoder::shown() const { return shown_; } -void Decoder::show(bool show) -{ - shown_ = show; -} +void Decoder::show(bool show) { shown_ = show; } -const vector& Decoder::channels() const -{ - return channels_; -} +const vector &Decoder::channels() const { return channels_; } -void Decoder::set_channels(vector channels) -{ - channels_ = channels; -} +void Decoder::set_channels(vector channels) { channels_ = channels; } -const map& Decoder::options() const -{ - return options_; -} +const map &Decoder::options() const { return options_; } void Decoder::set_option(const char *id, GVariant *value) { - assert(value); - g_variant_ref(value); - options_[id] = value; + assert(value); + g_variant_ref(value); + options_[id] = value; - // If we have a decoder instance, apply option value immediately - apply_all_options(); + // If we have a decoder instance, apply option value immediately + apply_all_options(); } void Decoder::apply_all_options() { - if (decoder_inst_) { - GHashTable *const opt_hash = g_hash_table_new_full(g_str_hash, - g_str_equal, g_free, (GDestroyNotify)g_variant_unref); - - for (const auto& option : options_) { - GVariant *const value = option.second; - g_variant_ref(value); - g_hash_table_replace(opt_hash, (void*)g_strdup( - option.first.c_str()), value); - } - - srd_inst_option_set(decoder_inst_, opt_hash); - g_hash_table_destroy(opt_hash); - } + if(decoder_inst_) { + GHashTable *const opt_hash = + g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify)g_variant_unref); + + for(const auto &option : options_) { + GVariant *const value = option.second; + g_variant_ref(value); + g_hash_table_replace(opt_hash, (void *)g_strdup(option.first.c_str()), value); + } + + srd_inst_option_set(decoder_inst_, opt_hash); + g_hash_table_destroy(opt_hash); + } } bool Decoder::have_required_channels() const { - for (DecodeChannel *ch : channels_) - if (!ch->assigned_signal && !ch->is_optional) - return false; + for(DecodeChannel *ch : channels_) + if(!ch->assigned_signal && !ch->is_optional) + return false; - return true; + return true; } -srd_decoder_inst* Decoder::create_decoder_inst(srd_session *session) +srd_decoder_inst *Decoder::create_decoder_inst(srd_session *session) { - GHashTable *const opt_hash = g_hash_table_new_full(g_str_hash, - g_str_equal, g_free, (GDestroyNotify)g_variant_unref); + GHashTable *const opt_hash = + g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify)g_variant_unref); - for (const auto& option : options_) { - GVariant *const value = option.second; - g_variant_ref(value); - g_hash_table_replace(opt_hash, (void*)g_strdup( - option.first.c_str()), value); - } + for(const auto &option : options_) { + GVariant *const value = option.second; + g_variant_ref(value); + g_hash_table_replace(opt_hash, (void *)g_strdup(option.first.c_str()), value); + } - if (decoder_inst_) - qDebug() << "WARNING: previous decoder instance" << decoder_inst_ << "exists"; + if(decoder_inst_) + qDebug() << "WARNING: previous decoder instance" << decoder_inst_ << "exists"; - decoder_inst_ = srd_inst_new(session, decoder_->id, opt_hash); - g_hash_table_destroy(opt_hash); + decoder_inst_ = srd_inst_new(session, decoder_->id, opt_hash); + g_hash_table_destroy(opt_hash); - if (!decoder_inst_) - return nullptr; + if(!decoder_inst_) + return nullptr; - // Setup the channels - GArray *const init_pin_states = g_array_sized_new(false, true, - sizeof(uint8_t), channels_.size()); + // Setup the channels + GArray *const init_pin_states = g_array_sized_new(false, true, sizeof(uint8_t), channels_.size()); - g_array_set_size(init_pin_states, channels_.size()); + g_array_set_size(init_pin_states, channels_.size()); - GHashTable *const channels = g_hash_table_new_full(g_str_hash, - g_str_equal, g_free, (GDestroyNotify)g_variant_unref); + GHashTable *const channels = + g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify)g_variant_unref); - for (DecodeChannel *ch : channels_) { - if (!ch->assigned_signal) - continue; + for(DecodeChannel *ch : channels_) { + if(!ch->assigned_signal) + continue; - init_pin_states->data[ch->id] = ch->initial_pin_state; + init_pin_states->data[ch->id] = ch->initial_pin_state; - GVariant *const gvar = g_variant_new_int32(ch->bit_id); // bit_id = bit position - g_variant_ref_sink(gvar); - // key is channel name (pdch->id), value is bit position in each sample (gvar) - g_hash_table_insert(channels, ch->pdch_->id, gvar); - } + GVariant *const gvar = g_variant_new_int32(ch->bit_id); // bit_id = bit position + g_variant_ref_sink(gvar); + // key is channel name (pdch->id), value is bit position in each sample (gvar) + g_hash_table_insert(channels, ch->pdch_->id, gvar); + } - srd_inst_channel_set_all(decoder_inst_, channels); + srd_inst_channel_set_all(decoder_inst_, channels); -// g_hash_table_remove_all(channels); -// g_hash_table_unref(channels); + // g_hash_table_remove_all(channels); + // g_hash_table_unref(channels); - srd_inst_initial_pins_set_all(decoder_inst_, init_pin_states); - g_array_free(init_pin_states, true); + srd_inst_initial_pins_set_all(decoder_inst_, init_pin_states); + g_array_free(init_pin_states, true); - return decoder_inst_; + return decoder_inst_; } -void Decoder::invalidate_decoder_inst() -{ - decoder_inst_ = nullptr; -} +void Decoder::invalidate_decoder_inst() { decoder_inst_ = nullptr; } diff --git a/gui/sigrok-gui/src/prop/bool.cpp b/gui/sigrok-gui/src/prop/bool.cpp index c358fa52ae..dd8a123340 100644 --- a/gui/sigrok-gui/src/prop/bool.cpp +++ b/gui/sigrok-gui/src/prop/bool.cpp @@ -37,36 +37,34 @@ * along with this program. If not, see . */ - -#include +#include "prop/bool.hpp" #include #include -#include "prop/bool.hpp" +#include namespace scopy { namespace prop { -Bool::Bool(QString name, QString desc, Getter getter, Setter setter) : - Property(name, desc, getter, setter), - check_box_(nullptr) -{ -} +Bool::Bool(QString name, QString desc, Getter getter, Setter setter) + : Property(name, desc, getter, setter) + , check_box_(nullptr) +{} -QWidget* Bool::get_widget(QWidget *parent, bool auto_commit) +QWidget *Bool::get_widget(QWidget *parent, bool auto_commit) { - if (check_box_) + if(check_box_) return check_box_; - if (!getter_) + if(!getter_) return nullptr; try { QVariant variant = getter_(); - if (!variant.isValid()) + if(!variant.isValid()) return nullptr; - } catch (const std::exception &e) { + } catch(const std::exception &e) { qWarning() << tr("Querying config key %1 resulted in %2").arg(name_, e.what()); return nullptr; } @@ -76,28 +74,24 @@ QWidget* Bool::get_widget(QWidget *parent, bool auto_commit) update_widget(); - if (auto_commit) - connect(check_box_, SIGNAL(stateChanged(int)), - this, SLOT(on_state_changed(int))); + if(auto_commit) + connect(check_box_, SIGNAL(stateChanged(int)), this, SLOT(on_state_changed(int))); return check_box_; } -bool Bool::labeled_widget() const -{ - return true; -} +bool Bool::labeled_widget() const { return true; } void Bool::update_widget() { - if (!check_box_) + if(!check_box_) return; QVariant variant; try { variant = getter_(); - } catch (const std::exception &e) { + } catch(const std::exception &e) { qWarning() << tr("Querying config key %1 resulted in %2").arg(name_, e.what()); return; } @@ -111,18 +105,15 @@ void Bool::commit() { assert(setter_); - if (!check_box_) + if(!check_box_) return; setter_(QVariant(check_box_->checkState() == Qt::Checked)); } -void Bool::on_state_changed(int) -{ - commit(); -} +void Bool::on_state_changed(int) { commit(); } -} // namespace prop -} // namespace pv +} // namespace prop +} // namespace scopy #include "prop/moc_bool.cpp" diff --git a/gui/sigrok-gui/src/prop/double.cpp b/gui/sigrok-gui/src/prop/double.cpp index 582b4cd4b4..42fd49fba1 100644 --- a/gui/sigrok-gui/src/prop/double.cpp +++ b/gui/sigrok-gui/src/prop/double.cpp @@ -37,13 +37,12 @@ * along with this program. If not, see . */ - -#include +#include "prop/double.hpp" #include #include -#include "prop/double.hpp" +#include using std::optional; using std::pair; @@ -51,36 +50,29 @@ using std::pair; namespace scopy { namespace prop { -Double::Double(QString name, - QString desc, - int decimals, - QString suffix, - optional< pair > range, - optional step, - Getter getter, - Setter setter) : - Property(name, desc, getter, setter), - decimals_(decimals), - suffix_(suffix), - range_(range), - step_(step), - spin_box_(nullptr) +Double::Double(QString name, QString desc, int decimals, QString suffix, optional> range, + optional step, Getter getter, Setter setter) + : Property(name, desc, getter, setter) + , decimals_(decimals) + , suffix_(suffix) + , range_(range) + , step_(step) + , spin_box_(nullptr) +{} + +QWidget *Double::get_widget(QWidget *parent, bool auto_commit) { -} - -QWidget* Double::get_widget(QWidget *parent, bool auto_commit) -{ - if (spin_box_) + if(spin_box_) return spin_box_; - if (!getter_) + if(!getter_) return nullptr; try { QVariant variant = getter_(); - if (!variant.isValid()) + if(!variant.isValid()) return nullptr; - } catch (const std::exception &e) { + } catch(const std::exception &e) { qWarning() << tr("Querying config key %1 resulted in %2").arg(name_, e.what()); return nullptr; } @@ -88,30 +80,29 @@ QWidget* Double::get_widget(QWidget *parent, bool auto_commit) spin_box_ = new QDoubleSpinBox(parent); spin_box_->setDecimals(decimals_); spin_box_->setSuffix(suffix_); - if (range_) + if(range_) spin_box_->setRange(range_->first, range_->second); - if (step_) + if(step_) spin_box_->setSingleStep(*step_); update_widget(); - if (auto_commit) - connect(spin_box_, SIGNAL(valueChanged(double)), - this, SLOT(on_value_changed(double))); + if(auto_commit) + connect(spin_box_, SIGNAL(valueChanged(double)), this, SLOT(on_value_changed(double))); return spin_box_; } void Double::update_widget() { - if (!spin_box_) + if(!spin_box_) return; QVariant variant; try { variant = getter_(); - } catch (const std::exception &e) { + } catch(const std::exception &e) { qWarning() << tr("Querying config key %1 resulted in %2").arg(name_, e.what()); return; } @@ -126,18 +117,15 @@ void Double::commit() { assert(setter_); - if (!spin_box_) + if(!spin_box_) return; setter_(QVariant(spin_box_->value())); } -void Double::on_value_changed(double) -{ - commit(); -} +void Double::on_value_changed(double) { commit(); } -} // namespace prop -} // namespace pv +} // namespace prop +} // namespace scopy #include "prop/moc_double.cpp" diff --git a/gui/sigrok-gui/src/prop/enum.cpp b/gui/sigrok-gui/src/prop/enum.cpp index c0003f54ac..a88f869406 100644 --- a/gui/sigrok-gui/src/prop/enum.cpp +++ b/gui/sigrok-gui/src/prop/enum.cpp @@ -37,12 +37,7 @@ * along with this program. If not, see . */ - -#include -#include -#include -#include -#include +#include "prop/enum.hpp" #include #include @@ -50,7 +45,11 @@ #include #include -#include "prop/enum.hpp" +#include +#include +#include +#include +#include using std::abs; // Note that "using std::isnan;" is _not_ put here since that would break @@ -62,16 +61,14 @@ using std::vector; namespace scopy { namespace prop { -Enum::Enum(QString name, QString desc, - vector > values, - Getter getter, Setter setter) : - Property(name, desc, getter, setter), - values_(values), - is_range_(false), - selector_(nullptr), - slider_layout_widget_(nullptr), - slider_(nullptr), - slider_label_(nullptr) +Enum::Enum(QString name, QString desc, vector> values, Getter getter, Setter setter) + : Property(name, desc, getter, setter) + , values_(values) + , is_range_(false) + , selector_(nullptr) + , slider_layout_widget_(nullptr) + , slider_(nullptr) + , slider_label_(nullptr) { // Try to determine whether the values make up a range, created by e.g. // std_gvar_min_max_step_thresholds() @@ -79,14 +76,14 @@ Enum::Enum(QString name, QString desc, vector deltas; double prev_value = 0; - for (const pair &v : values_) { + for(const pair &v : values_) { double value; QMetaType::Type type = static_cast(v.first.type()); - if (type == QMetaType::Double) { + if(type == QMetaType::Double) { value = v.first.toDouble(); } else { bool pairDD = v.first.canConvert>(); - if (pairDD) { + if(pairDD) { auto pair = v.first.value>(); value = pair.first; } else { @@ -97,53 +94,53 @@ Enum::Enum(QString name, QString desc, prev_value = value; } - if (deltas.size() > 0) { + if(deltas.size() > 0) { bool constant_delta = true; double prev_delta = numeric_limits::quiet_NaN(); bool skip_first = true; - for (double delta : deltas) { + for(double delta : deltas) { // First value is incorrect, it's the delta to 0 since no // previous value existed yet - if (skip_first) { + if(skip_first) { skip_first = false; continue; } - if (std::isnan(prev_delta)) + if(std::isnan(prev_delta)) prev_delta = delta; // 2*DBL_EPSILON doesn't work here, so use a workaround - if (abs(delta - prev_delta) > (delta/10)) + if(abs(delta - prev_delta) > (delta / 10)) constant_delta = false; prev_delta = delta; } - if (constant_delta) + if(constant_delta) is_range_ = true; } } -QWidget* Enum::get_widget(QWidget *parent, bool auto_commit) +QWidget *Enum::get_widget(QWidget *parent, bool auto_commit) { - if (!getter_) + if(!getter_) return nullptr; QVariant variant; try { - variant = getter_(); - } catch (const std::exception &e) { + variant = getter_(); + } catch(const std::exception &e) { qWarning() << tr("Querying config key %1 resulted in %2").arg(name_, e.what()); return nullptr; } - if (!variant.isValid()) + if(!variant.isValid()) return nullptr; - if (is_range_) { + if(is_range_) { // Use slider - if (slider_layout_widget_) + if(slider_layout_widget_) return slider_layout_widget_; slider_ = new QSlider(); @@ -163,28 +160,26 @@ QWidget* Enum::get_widget(QWidget *parent, bool auto_commit) update_widget(); - if (auto_commit) - connect(slider_, SIGNAL(valueChanged(int)), - this, SLOT(on_value_changed(int))); + if(auto_commit) + connect(slider_, SIGNAL(valueChanged(int)), this, SLOT(on_value_changed(int))); return slider_layout_widget_; } else { // Use combo box - if (selector_) + if(selector_) return selector_; selector_ = new QComboBox(parent); - for (unsigned int i = 0; i < values_.size(); i++) { + for(unsigned int i = 0; i < values_.size(); i++) { const pair &v = values_[i]; selector_->addItem(v.second, v.first); } update_widget(); - if (auto_commit) - connect(selector_, SIGNAL(currentIndexChanged(int)), - this, SLOT(on_current_index_changed(int))); + if(auto_commit) + connect(selector_, SIGNAL(currentIndexChanged(int)), this, SLOT(on_current_index_changed(int))); return selector_; } @@ -196,32 +191,32 @@ void Enum::update_widget() try { variant = getter_(); - } catch (const std::exception &e) { + } catch(const std::exception &e) { qWarning() << tr("Querying config key %1 resulted in %2").arg(name_, e.what()); return; } assert(variant.isValid()); - if (is_range_) { + if(is_range_) { // Use slider - if (!slider_layout_widget_) + if(!slider_layout_widget_) return; - for (unsigned int i = 0; i < values_.size(); i++) { + for(unsigned int i = 0; i < values_.size(); i++) { const pair &v = values_[i]; - if (v.first.type() == QVariant::Double) { + if(v.first.type() == QVariant::Double) { double a = variant.toDouble(); double b = v.first.toDouble(); - if (abs(a - b) <= 2 * DBL_EPSILON) { + if(abs(a - b) <= 2 * DBL_EPSILON) { slider_->setValue(i); slider_label_->setText(v.second); } } else { bool pairDD = v.first.canConvert>(); - if (pairDD) { + if(pairDD) { double a1, a2, b1, b2; auto pair_old = variant.value>(); a1 = pair_old.first; @@ -229,8 +224,7 @@ void Enum::update_widget() auto pair_new = v.first.value>(); b1 = pair_new.first; b2 = pair_new.second; - if ((abs(a1 - b1) <= 2 * DBL_EPSILON) && - (abs(a2 - b2) <= 2 * DBL_EPSILON)) { + if((abs(a1 - b1) <= 2 * DBL_EPSILON) && (abs(a2 - b2) <= 2 * DBL_EPSILON)) { slider_->setValue(i); slider_label_->setText(v.second); } @@ -243,20 +237,20 @@ void Enum::update_widget() } else { // Use combo box - if (!selector_) + if(!selector_) return; - for (unsigned int i = 0; i < values_.size(); i++) { + for(unsigned int i = 0; i < values_.size(); i++) { const pair &v = values_[i]; - if (static_cast(v.first.type()) == QMetaType::Double) { + if(static_cast(v.first.type()) == QMetaType::Double) { double a = variant.toDouble(); double b = v.first.toDouble(); - if (abs(a - b) <= 2 * DBL_EPSILON) { + if(abs(a - b) <= 2 * DBL_EPSILON) { selector_->setCurrentIndex(i); } } else { bool pairDD = v.first.canConvert>(); - if (pairDD) { + if(pairDD) { double a1, a2, b1, b2; auto pair_old = variant.value>(); a1 = pair_old.first; @@ -264,13 +258,12 @@ void Enum::update_widget() auto pair_new = v.first.value>(); b1 = pair_new.first; b2 = pair_new.second; - if ((abs(a1 - b1) <= 2 * DBL_EPSILON) && - (abs(a2 - b2) <= 2 * DBL_EPSILON)) { + if((abs(a1 - b1) <= 2 * DBL_EPSILON) && (abs(a2 - b2) <= 2 * DBL_EPSILON)) { selector_->setCurrentIndex(i); } } else { -// Handle all other types - if (v.first == variant) { + // Handle all other types + if(v.first == variant) { selector_->setCurrentIndex(i); } } @@ -283,9 +276,9 @@ void Enum::commit() { assert(setter_); - if (is_range_) { + if(is_range_) { // Use slider - if (!slider_layout_widget_) + if(!slider_layout_widget_) return; setter_(values_.at(slider_->value()).first); @@ -293,11 +286,11 @@ void Enum::commit() update_widget(); } else { // Use combo box - if (!selector_) + if(!selector_) return; const int index = selector_->currentIndex(); - if (index < 0) + if(index < 0) return; setter_(selector_->itemData(index).value()); @@ -307,17 +300,11 @@ void Enum::commit() } } -void Enum::on_current_index_changed(int) -{ - commit(); -} +void Enum::on_current_index_changed(int) { commit(); } -void Enum::on_value_changed(int) -{ - commit(); -} +void Enum::on_value_changed(int) { commit(); } -} // namespace prop -} // namespace pv +} // namespace prop +} // namespace scopy #include "prop/moc_enum.cpp" diff --git a/gui/sigrok-gui/src/prop/int.cpp b/gui/sigrok-gui/src/prop/int.cpp index 008cc4edc2..6c95bbc28b 100644 --- a/gui/sigrok-gui/src/prop/int.cpp +++ b/gui/sigrok-gui/src/prop/int.cpp @@ -37,57 +37,51 @@ * along with this program. If not, see . */ - -#include -#include +#include "prop/int.hpp" #include #include -#include "prop/int.hpp" -using std::optional; +#include +#include + using std::max; using std::min; +using std::optional; using std::pair; namespace scopy { namespace prop { -Int::Int(QString name, - QString desc, - QString suffix, - optional< pair > range, - Getter getter, - Setter setter, - GVariantClass gvarClass) : - Property(name, desc, getter, setter), - suffix_(suffix), - range_(range), - spin_box_(nullptr), - gvar_class_type_(gvarClass) -{ -} +Int::Int(QString name, QString desc, QString suffix, optional> range, Getter getter, + Setter setter, GVariantClass gvarClass) + : Property(name, desc, getter, setter) + , suffix_(suffix) + , range_(range) + , spin_box_(nullptr) + , gvar_class_type_(gvarClass) +{} -QWidget* Int::get_widget(QWidget *parent, bool auto_commit) +QWidget *Int::get_widget(QWidget *parent, bool auto_commit) { int64_t range_min = 0; uint64_t range_max = 0; - if (spin_box_) + if(spin_box_) return spin_box_; - if (!getter_) + if(!getter_) return nullptr; try { value_ = getter_(); - } catch (const std::exception &e) { + } catch(const std::exception &e) { qWarning() << tr("Querying config key %1 resulted in %2").arg(name_, e.what()); return nullptr; } QVariant variant = value_; - if (!variant.isValid()) + if(!variant.isValid()) return nullptr; spin_box_ = new QSpinBox(parent); @@ -96,19 +90,19 @@ QWidget* Int::get_widget(QWidget *parent, bool auto_commit) QVariant::Type type = variant.type(); assert(type); - if (gvar_class_type_ == G_VARIANT_CLASS_BYTE) { + if(gvar_class_type_ == G_VARIANT_CLASS_BYTE) { range_min = 0, range_max = UINT8_MAX; - } else if (gvar_class_type_ == G_VARIANT_CLASS_INT16) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_INT16) { range_min = 0, range_max = INT16_MAX; - } else if (gvar_class_type_ == G_VARIANT_CLASS_UINT16) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_UINT16) { range_min = 0, range_max = UINT16_MAX; - } else if (gvar_class_type_ == G_VARIANT_CLASS_INT32) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_INT32) { range_min = 0, range_max = INT32_MAX; - } else if (gvar_class_type_ == G_VARIANT_CLASS_UINT32) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_UINT32) { range_min = 0, range_max = UINT32_MAX; - } else if (gvar_class_type_ == G_VARIANT_CLASS_INT64) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_INT64) { range_min = 0, range_max = INT64_MAX; - } else if (gvar_class_type_ == G_VARIANT_CLASS_UINT64) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_UINT64) { range_min = 0, range_max = UINT64_MAX; } else { assert(false); @@ -122,28 +116,27 @@ QWidget* Int::get_widget(QWidget *parent, bool auto_commit) range_min = max(range_min, (int64_t)INT_MIN); range_max = min(range_max, (uint64_t)INT_MAX); - if (range_) + if(range_) spin_box_->setRange((int)range_->first, (int)range_->second); else spin_box_->setRange((int)range_min, (int)range_max); update_widget(); - if (auto_commit) - connect(spin_box_, SIGNAL(valueChanged(int)), - this, SLOT(on_value_changed(int))); + if(auto_commit) + connect(spin_box_, SIGNAL(valueChanged(int)), this, SLOT(on_value_changed(int))); return spin_box_; } void Int::update_widget() { - if (!spin_box_) + if(!spin_box_) return; try { value_ = getter_(); - } catch (const std::exception &e) { + } catch(const std::exception &e) { qWarning() << tr("Querying config key %1 resulted in %2").arg(name_, e.what()); return; } @@ -156,19 +149,19 @@ void Int::update_widget() int64_t int_val = 0; - if (gvar_class_type_ == G_VARIANT_CLASS_BYTE) { + if(gvar_class_type_ == G_VARIANT_CLASS_BYTE) { int_val = variant.value(); - } else if (gvar_class_type_ == G_VARIANT_CLASS_INT16) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_INT16) { int_val = variant.value(); - } else if (gvar_class_type_ == G_VARIANT_CLASS_UINT16) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_UINT16) { int_val = variant.value(); - } else if (gvar_class_type_ == G_VARIANT_CLASS_INT32) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_INT32) { int_val = variant.value(); - } else if (gvar_class_type_ == G_VARIANT_CLASS_UINT32) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_UINT32) { int_val = variant.value(); - } else if (gvar_class_type_ == G_VARIANT_CLASS_INT64) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_INT64) { int_val = variant.value(); - } else if (gvar_class_type_ == G_VARIANT_CLASS_UINT64) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_UINT64) { int_val = variant.value(); } else { assert(false); @@ -181,7 +174,7 @@ void Int::commit() { assert(setter_); - if (!spin_box_) + if(!spin_box_) return; QVariant variant = value_; @@ -192,19 +185,19 @@ void Int::commit() auto spin_val = spin_box_->value(); - if (gvar_class_type_ == G_VARIANT_CLASS_BYTE) { + if(gvar_class_type_ == G_VARIANT_CLASS_BYTE) { value_ = QVariant::fromValue(spin_val); - } else if (gvar_class_type_ == G_VARIANT_CLASS_INT16) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_INT16) { value_ = QVariant::fromValue(spin_val); - } else if (gvar_class_type_ == G_VARIANT_CLASS_UINT16) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_UINT16) { value_ = QVariant::fromValue(spin_val); - } else if (gvar_class_type_ == G_VARIANT_CLASS_INT32) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_INT32) { value_ = QVariant::fromValue(spin_val); - } else if (gvar_class_type_ == G_VARIANT_CLASS_UINT32) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_UINT32) { value_ = QVariant::fromValue(spin_val); - } else if (gvar_class_type_ == G_VARIANT_CLASS_INT64) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_INT64) { value_ = QVariant::fromValue(spin_val); - } else if (gvar_class_type_ == G_VARIANT_CLASS_UINT64) { + } else if(gvar_class_type_ == G_VARIANT_CLASS_UINT64) { value_ = QVariant::fromValue(spin_val); } else { assert(false); @@ -213,12 +206,9 @@ void Int::commit() setter_(value_); } -void Int::on_value_changed(int) -{ - commit(); -} +void Int::on_value_changed(int) { commit(); } -} // namespace prop -} // namespace pv +} // namespace prop +} // namespace scopy #include "prop/moc_int.cpp" diff --git a/gui/sigrok-gui/src/prop/property.cpp b/gui/sigrok-gui/src/prop/property.cpp index 30ec0cadb3..6ea7e9a455 100644 --- a/gui/sigrok-gui/src/prop/property.cpp +++ b/gui/sigrok-gui/src/prop/property.cpp @@ -37,46 +37,29 @@ * along with this program. If not, see . */ - #include "prop/property.hpp" namespace scopy { namespace prop { -Property::Property(QString name, QString desc, Getter getter, Setter setter) : - getter_(getter), - setter_(setter), - name_(name), - desc_(desc) -{ -} +Property::Property(QString name, QString desc, Getter getter, Setter setter) + : getter_(getter) + , setter_(setter) + , name_(name) + , desc_(desc) +{} -const QString& Property::name() const -{ - return name_; -} +const QString &Property::name() const { return name_; } -const QString& Property::desc() const -{ - return desc_; -} +const QString &Property::desc() const { return desc_; } -QVariant Property::get() const -{ - return getter_(); -} +QVariant Property::get() const { return getter_(); } -void Property::set(QVariant val) -{ - return setter_(val); -} +void Property::set(QVariant val) { return setter_(val); } -bool Property::labeled_widget() const -{ - return false; -} +bool Property::labeled_widget() const { return false; } -} // namespace prop -} // namespace pv +} // namespace prop +} // namespace scopy #include "prop/moc_property.cpp" diff --git a/gui/sigrok-gui/src/prop/string.cpp b/gui/sigrok-gui/src/prop/string.cpp index e691b4e733..ef2c8c9a51 100644 --- a/gui/sigrok-gui/src/prop/string.cpp +++ b/gui/sigrok-gui/src/prop/string.cpp @@ -37,42 +37,37 @@ * along with this program. If not, see . */ - -#include +#include "prop/string.hpp" #include #include #include -#include "prop/string.hpp" +#include using std::string; namespace scopy { namespace prop { -String::String(QString name, - QString desc, - Getter getter, - Setter setter) : - Property(name, desc, getter, setter), - line_edit_(nullptr) -{ -} +String::String(QString name, QString desc, Getter getter, Setter setter) + : Property(name, desc, getter, setter) + , line_edit_(nullptr) +{} -QWidget* String::get_widget(QWidget *parent, bool auto_commit) +QWidget *String::get_widget(QWidget *parent, bool auto_commit) { - if (line_edit_) + if(line_edit_) return line_edit_; - if (!getter_) + if(!getter_) return nullptr; try { QVariant variant = getter_(); - if (!variant.isValid()) + if(!variant.isValid()) return nullptr; - } catch (const std::exception &e) { + } catch(const std::exception &e) { qWarning() << tr("Querying config key %1 resulted in %2").arg(name_, e.what()); return nullptr; } @@ -81,23 +76,22 @@ QWidget* String::get_widget(QWidget *parent, bool auto_commit) update_widget(); - if (auto_commit) - connect(line_edit_, SIGNAL(textEdited(const QString&)), - this, SLOT(on_text_edited(const QString&))); + if(auto_commit) + connect(line_edit_, SIGNAL(textEdited(const QString &)), this, SLOT(on_text_edited(const QString &))); return line_edit_; } void String::update_widget() { - if (!line_edit_) + if(!line_edit_) return; QVariant variant; try { variant = getter_(); - } catch (const std::exception &e) { + } catch(const std::exception &e) { qWarning() << tr("Querying config key %1 resulted in %2").arg(name_, e.what()); return; } @@ -112,19 +106,16 @@ void String::commit() { assert(setter_); - if (!line_edit_) + if(!line_edit_) return; QString ba = line_edit_->text(); setter_(QVariant(ba)); } -void String::onTextEdited(const QString&) -{ - commit(); -} +void String::onTextEdited(const QString &) { commit(); } -} // namespace prop -} // namespace pv +} // namespace prop +} // namespace scopy #include "prop/moc_string.cpp" diff --git a/gui/sigrok-gui/src/row.cpp b/gui/sigrok-gui/src/row.cpp index ebf893c0bb..d15c0ddb13 100644 --- a/gui/sigrok-gui/src/row.cpp +++ b/gui/sigrok-gui/src/row.cpp @@ -37,61 +37,46 @@ * along with this program. If not, see . */ - #include "row.h" #include -Row::Row() : - decoder_(nullptr), - row_(nullptr) -{ -} +Row::Row() + : decoder_(nullptr) + , row_(nullptr) +{} -Row::Row(int index, const srd_decoder *decoder, const srd_decoder_annotation_row *row) : - index_(index), - decoder_(decoder), - row_(row) -{ -} +Row::Row(int index, const srd_decoder *decoder, const srd_decoder_annotation_row *row) + : index_(index) + , decoder_(decoder) + , row_(row) +{} -const srd_decoder* Row::decoder() const -{ - return decoder_; -} +const srd_decoder *Row::decoder() const { return decoder_; } -const srd_decoder_annotation_row* Row::row() const -{ - return row_; -} +const srd_decoder_annotation_row *Row::row() const { return row_; } const QString Row::title() const { - if (decoder_ && decoder_->name && row_ && row_->desc) - return QString("%1: %2") - .arg(QString::fromUtf8(decoder_->name), - QString::fromUtf8(row_->desc)); - if (decoder_ && decoder_->name) - return QString::fromUtf8(decoder_->name); - if (row_ && row_->desc) - return QString::fromUtf8(row_->desc); - return QString(); + if(decoder_ && decoder_->name && row_ && row_->desc) + return QString("%1: %2").arg(QString::fromUtf8(decoder_->name), QString::fromUtf8(row_->desc)); + if(decoder_ && decoder_->name) + return QString::fromUtf8(decoder_->name); + if(row_ && row_->desc) + return QString::fromUtf8(row_->desc); + return QString(); } const QString Row::class_name() const { - if (row_ && row_->desc) - return QString::fromUtf8(row_->desc); - return QString(); + if(row_ && row_->desc) + return QString::fromUtf8(row_->desc); + return QString(); } -int Row::index() const -{ - return index_; -} +int Row::index() const { return index_; } bool Row::operator<(const Row &other) const { - return (decoder_ < other.decoder_) || - (decoder_ == other.decoder_ && row_ < other.row_); + return (decoder_ < other.decoder_) || (decoder_ == other.decoder_ && row_ < other.row_); } diff --git a/gui/sigrok-gui/src/rowdata.cpp b/gui/sigrok-gui/src/rowdata.cpp index 572f7f3203..9e07dfe0ab 100644 --- a/gui/sigrok-gui/src/rowdata.cpp +++ b/gui/sigrok-gui/src/rowdata.cpp @@ -43,80 +43,64 @@ uint64_t RowData::get_max_sample() const { - if (annotations_.empty()) - return 0; - return annotations_.back().end_sample(); -// return 0; + if(annotations_.empty()) + return 0; + return annotations_.back().end_sample(); + // return 0; } -void RowData::get_annotation_subset( - vector &dest, - uint64_t start_sample, uint64_t end_sample) const +void RowData::get_annotation_subset(vector &dest, uint64_t start_sample, uint64_t end_sample) const { - for (const auto& annotation : annotations_) - if (annotation.end_sample() > start_sample && - annotation.start_sample() <= end_sample) - dest.push_back(annotation); + for(const auto &annotation : annotations_) + if(annotation.end_sample() > start_sample && annotation.start_sample() <= end_sample) + dest.push_back(annotation); } -vector RowData::get_annotations() const { - return annotations_; -} +vector RowData::get_annotations() const { return annotations_; } -Annotation RowData::getAnnAt(uint64_t index) const { +Annotation RowData::getAnnAt(uint64_t index) const { return annotations_[index]; } - return annotations_[index]; -} +const Annotation *RowData::annAt(uint64_t index) const { return &annotations_[index]; } -const Annotation* RowData::annAt(uint64_t index) const +void RowData::sort_annotations() { - return &annotations_[index]; -} - -void RowData::sort_annotations() { - // Use stable_sort to keep the annotations having - // the same start sample in the same order as - // they came from libsigrokdecode - std::stable_sort(annotations_.begin(), annotations_.end(), [](const Annotation &a, const Annotation &b){ - return a.start_sample() < b.start_sample(); - }); + // Use stable_sort to keep the annotations having + // the same start sample in the same order as + // they came from libsigrokdecode + std::stable_sort(annotations_.begin(), annotations_.end(), + [](const Annotation &a, const Annotation &b) { return a.start_sample() < b.start_sample(); }); } std::pair RowData::get_annotation_subset(uint64_t start_sample, uint64_t end_sample) const { -// qDebug() << start_sample << " " << end_sample; - - uint64_t first = 0, last = 0; - - bool found = false; - for (size_t i = 0; i < annotations_.size(); ++i) { - if (annotations_[i].end_sample() > start_sample && - annotations_[i].start_sample() <= end_sample) { - if (!found) { - first = i; - found = true; - } else { - last = i; - } - } - } - - if (!last && first > 0) { - last = (first < annotations_.size() - 1) ? first + 1 - : first; - } - - // let s adjust the edges a bit - if (first > 0) first--; - if (last < annotations_.size() - 1) last++; - - return std::make_pair(first, last); + // qDebug() << start_sample << " " << end_sample; + + uint64_t first = 0, last = 0; + + bool found = false; + for(size_t i = 0; i < annotations_.size(); ++i) { + if(annotations_[i].end_sample() > start_sample && annotations_[i].start_sample() <= end_sample) { + if(!found) { + first = i; + found = true; + } else { + last = i; + } + } + } + + if(!last && first > 0) { + last = (first < annotations_.size() - 1) ? first + 1 : first; + } + + // let s adjust the edges a bit + if(first > 0) + first--; + if(last < annotations_.size() - 1) + last++; + + return std::make_pair(first, last); } -void RowData::emplace_annotation(srd_proto_data *pdata, const Row *row) -{ - annotations_.emplace_back(pdata, row); -} - - +void RowData::emplace_annotation(srd_proto_data *pdata, const Row *row) { annotations_.emplace_back(pdata, row); } diff --git a/gui/sigrok-gui/test/CMakeLists.txt b/gui/sigrok-gui/test/CMakeLists.txt index c749ff1584..72de46a83b 100644 --- a/gui/sigrok-gui/test/CMakeLists.txt +++ b/gui/sigrok-gui/test/CMakeLists.txt @@ -1,22 +1,18 @@ cmake_minimum_required(VERSION 3.5) function(SETUP_TESTS) - foreach(_testname ${ARGS}) - add_executable(_testname ${ARGS}) - add_test(NAME ${_testname} COMMAND ${_testname}) - target_link_libraries(${_testname} Qt${QT_VERSION_MAJOR}::Test) - endforeach() + foreach(_testname ${ARGS}) + add_executable(_testname ${ARGS}) + add_test(NAME ${_testname} COMMAND ${_testname}) + target_link_libraries(${_testname} Qt${QT_VERSION_MAJOR}::Test) + endforeach() endfunction() - # Tell CMake to run moc when necessary: set(CMAKE_AUTOMOC ON) -# As moc files are generated in the binary dir, tell CMake -# to always look for includes there: +# As moc files are generated in the binary dir, tell CMake to always look for includes there: set(CMAKE_INCLUDE_CURRENT_DIR ON) find_package(Qt${QT_VERSION_MAJOR}Test REQUIRED) -SETUP_TESTS( -) - +setup_tests() diff --git a/gui/src/BasicPlot.cpp b/gui/src/BasicPlot.cpp index 410a29f13b..58a18162f9 100644 --- a/gui/src/BasicPlot.cpp +++ b/gui/src/BasicPlot.cpp @@ -1,42 +1,44 @@ #include "BasicPlot.h" -#include -#include #include - #include -Q_LOGGING_CATEGORY(CAT_GUI_PLOT,"Plot") +#include +#include +Q_LOGGING_CATEGORY(CAT_GUI_PLOT, "Plot") namespace scopy { int BasicPlot::staticPlotId = 0; -BasicPlot::BasicPlot(QWidget* parent) : QwtPlot(parent), started(false), debug(false), replotFrameRate(60) +BasicPlot::BasicPlot(QWidget *parent) + : QwtPlot(parent) + , started(false) + , debug(false) + , replotFrameRate(60) { - useOpenGlCanvas = true;//= getToolLauncherInstance()->isOpenGlLoaded(); - connect(&replotTimer,SIGNAL(timeout()),this,SLOT(replotNow())); + useOpenGlCanvas = true; //= getToolLauncherInstance()->isOpenGlLoaded(); + connect(&replotTimer, SIGNAL(timeout()), this, SLOT(replotNow())); if(useOpenGlCanvas) { - QwtPlotOpenGLCanvas* plotCanvas = qobject_cast< QwtPlotOpenGLCanvas* >( canvas() ); - if ( plotCanvas == NULL ) - { + QwtPlotOpenGLCanvas *plotCanvas = qobject_cast(canvas()); + if(plotCanvas == NULL) { plotCanvas = new QwtPlotOpenGLCanvas(this); - plotCanvas->setPaintAttribute(QwtPlotAbstractGLCanvas::BackingStore ); + plotCanvas->setPaintAttribute(QwtPlotAbstractGLCanvas::BackingStore); #ifdef IMMEDIATE_PAINT plotCanvas->setPaintAttribute(QwtPlotAbstractGLCanvas::ImmediatePaint, true); #endif - setCanvas( plotCanvas ); + setCanvas(plotCanvas); } else { ; } } else { - QwtPlotCanvas *plotCanvas = qobject_cast( canvas() ); + QwtPlotCanvas *plotCanvas = qobject_cast(canvas()); plotCanvas->setPaintAttribute(QwtPlotCanvas::BackingStore, true); #ifdef IMMEDIATE_PAINT plotCanvas->setPaintAttribute(QwtPlotCanvas::ImmediatePaint, true); #endif } - qDebug(CAT_GUI_PLOT)< fpsLabelRefreshTime) { QString rendering = (useOpenGlCanvas) ? "OpenGl rendering" : "Software rendering"; - fpsTxt.setText(rendering + "\n" + - "instrument: " + QString::number(1000.0 / instrumentCycleAvg) + " fps / " + QString::number(instrumentCycleAvg) + " ms" + "\n" + fpsTxt.setText(rendering + "\n" + "instrument: " + QString::number(1000.0 / instrumentCycleAvg) + + " fps / " + QString::number(instrumentCycleAvg) + " ms" + "\n" #ifdef IMMEDIATE_PAINT - + "plot: " + QString::number(replotTheoreticalFpsAvg) + "fps / " + QString::number(replotDurationAvg) + " ms" + + "plot: " + QString::number(replotTheoreticalFpsAvg) + "fps / " + + QString::number(replotDurationAvg) + " ms" #endif - ); + ); fpsLabel.setText(fpsTxt); fpsLabelTimer.restart(); } } -void BasicPlot::replot() { +void BasicPlot::replot() +{ #ifdef IMMEDIATE_PAINT - if(!replotTimer.isActive()) { - replotTimer.setSingleShot(true); - replotTimer.start(1000.0/replotFrameRate); - } - else - { - if(debug) qDebug(CAT_GUI_PLOT)<. */ - #ifndef CONSTELLATION_DISPLAY_PLOT_C #define CONSTELLATION_DISPLAY_PLOT_C -#include -#include -#include -#include - #include "ConstellationDisplayPlot.h" + #include "scopy-gui_export.h" +#include +#include +#include + +#include + using namespace scopy; -class SCOPY_GUI_EXPORT ConstellationDisplayZoomer: public QwtPlotZoomer +class SCOPY_GUI_EXPORT ConstellationDisplayZoomer : public QwtPlotZoomer { public: #if QWT_VERSION < 0x060100 - ConstellationDisplayZoomer(QwtPlotCanvas* canvas) -#else /* QWT_VERSION < 0x060100 */ - ConstellationDisplayZoomer(QWidget* canvas) + ConstellationDisplayZoomer(QwtPlotCanvas *canvas) +#else /* QWT_VERSION < 0x060100 */ + ConstellationDisplayZoomer(QWidget *canvas) #endif /* QWT_VERSION < 0x060100 */ - : QwtPlotZoomer(canvas) - { - setTrackerMode(QwtPicker::AlwaysOn); - } - - virtual ~ConstellationDisplayZoomer(){ + : QwtPlotZoomer(canvas) + { + setTrackerMode(QwtPicker::AlwaysOn); + } - } + virtual ~ConstellationDisplayZoomer() {} - virtual void updateTrackerText(){ - updateDisplay(); - } + virtual void updateTrackerText() { updateDisplay(); } protected: - using QwtPlotZoomer::trackerText; - virtual QwtText trackerText( const QPoint& p ) const - { - QPointF dp = QwtPlotZoomer::invTransform(p); - QwtText t(QString("(%1, %2)").arg(dp.x(), 0, 'f', 4). - arg(dp.y(), 0, 'f', 4)); - return t; - } + using QwtPlotZoomer::trackerText; + virtual QwtText trackerText(const QPoint &p) const + { + QPointF dp = QwtPlotZoomer::invTransform(p); + QwtText t(QString("(%1, %2)").arg(dp.x(), 0, 'f', 4).arg(dp.y(), 0, 'f', 4)); + return t; + } }; -ConstellationDisplayPlot::ConstellationDisplayPlot(int nplots, QWidget* parent) - : DisplayPlot(nplots, parent) +ConstellationDisplayPlot::ConstellationDisplayPlot(int nplots, QWidget *parent) + : DisplayPlot(nplots, parent) { - resize(parent->width(), parent->height()); + resize(parent->width(), parent->height()); - d_numPoints = 1024; - d_pen_size = 5; + d_numPoints = 1024; + d_pen_size = 5; - d_zoomer.push_back(new ConstellationDisplayZoomer(canvas())); + d_zoomer.push_back(new ConstellationDisplayZoomer(canvas())); #if QWT_VERSION < 0x060000 - d_zoomer[0]->setSelectionFlags(QwtPicker::RectSelection | QwtPicker::DragSelection); + d_zoomer[0]->setSelectionFlags(QwtPicker::RectSelection | QwtPicker::DragSelection); #endif - d_zoomer[0]->setMousePattern(QwtEventPattern::MouseSelect2, - Qt::RightButton, Qt::ControlModifier); - d_zoomer[0]->setMousePattern(QwtEventPattern::MouseSelect3, - Qt::RightButton); + d_zoomer[0]->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); + d_zoomer[0]->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); - const QColor c(Qt::darkRed); - d_zoomer[0]->setRubberBandPen(c); - d_zoomer[0]->setTrackerPen(c); + const QColor c(Qt::darkRed); + d_zoomer[0]->setRubberBandPen(c); + d_zoomer[0]->setTrackerPen(c); -// setAxisScaleEngine(QwtAxis::XBottom, new QwtLinearScaleEngine); -// set_xaxis(-2.0, 2.0); -// setAxisTitle(QwtAxis::XBottom, "In-phase"); + // setAxisScaleEngine(QwtAxis::XBottom, new QwtLinearScaleEngine); + // set_xaxis(-2.0, 2.0); + // setAxisTitle(QwtAxis::XBottom, "In-phase"); -// setAxisScaleEngine(QwtAxis::YLeft, new QwtLinearScaleEngine); -// set_yaxis(-2.0, 2.0); -// setAxisTitle(QwtAxis::YLeft, "Quadrature"); - updateAxes(); + // setAxisScaleEngine(QwtAxis::YLeft, new QwtLinearScaleEngine); + // set_yaxis(-2.0, 2.0); + // setAxisTitle(QwtAxis::YLeft, "Quadrature"); + updateAxes(); - // Setup dataPoints and plot vectors - // Automatically deleted when parent is deleted - for(int i = 0; i < d_nplots; i++) { - d_real_data.push_back(new double[d_numPoints]); - d_imag_data.push_back(new double[d_numPoints]); - memset(d_real_data[i], 0x0, d_numPoints*sizeof(double)); - memset(d_imag_data[i], 0x0, d_numPoints*sizeof(double)); + // Setup dataPoints and plot vectors + // Automatically deleted when parent is deleted + for(int i = 0; i < d_nplots; i++) { + d_real_data.push_back(new double[d_numPoints]); + d_imag_data.push_back(new double[d_numPoints]); + memset(d_real_data[i], 0x0, d_numPoints * sizeof(double)); + memset(d_imag_data[i], 0x0, d_numPoints * sizeof(double)); - d_plot_curve.push_back(new QwtPlotCurve(QString("Data %1").arg(i))); - d_plot_curve[i]->attach(this); - d_plot_curve[i]->setPen(QPen(d_CurveColors[i])); + d_plot_curve.push_back(new QwtPlotCurve(QString("Data %1").arg(i))); + d_plot_curve[i]->attach(this); + d_plot_curve[i]->setPen(QPen(d_CurveColors[i])); - QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, - QBrush(d_CurveColors[i]), - QPen(d_CurveColors[i]), QSize(7,7)); + QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(d_CurveColors[i]), QPen(d_CurveColors[i]), + QSize(7, 7)); #if QWT_VERSION < 0x060000 - d_plot_curve[i]->setRawData(d_real_data[i], d_imag_data[i], d_numPoints); - d_plot_curve[i]->setSymbol(*symbol); + d_plot_curve[i]->setRawData(d_real_data[i], d_imag_data[i], d_numPoints); + d_plot_curve[i]->setSymbol(*symbol); #else - d_plot_curve[i]->setRawSamples(d_real_data[i], d_imag_data[i], d_numPoints); - d_plot_curve[i]->setSymbol(symbol); + d_plot_curve[i]->setRawSamples(d_real_data[i], d_imag_data[i], d_numPoints); + d_plot_curve[i]->setSymbol(symbol); #endif - setLineStyle(i, Qt::NoPen); - setLineMarker(i, QwtSymbol::Ellipse); - } + setLineStyle(i, Qt::NoPen); + setLineMarker(i, QwtSymbol::Ellipse); + } } ConstellationDisplayPlot::~ConstellationDisplayPlot() { - for(int i = 0; i < d_nplots; i++) { - delete [] d_real_data[i]; - delete [] d_imag_data[i]; - } + for(int i = 0; i < d_nplots; i++) { + delete[] d_real_data[i]; + delete[] d_imag_data[i]; + } - // d_plot_curves deleted when parent deleted - // d_zoomer and d_panner deleted when parent deleted + // d_plot_curves deleted when parent deleted + // d_zoomer and d_panner deleted when parent deleted } -void -ConstellationDisplayPlot::set_xaxis(double min, double max) -{ - setXaxis(min, max); -} +void ConstellationDisplayPlot::set_xaxis(double min, double max) { setXaxis(min, max); } -void -ConstellationDisplayPlot::set_yaxis(double min, double max) -{ - setYaxis(min, max); -} - -void -ConstellationDisplayPlot::set_axis(double xmin, double xmax, - double ymin, double ymax) -{ - set_xaxis(xmin, xmax); - set_yaxis(ymin, ymax); -} +void ConstellationDisplayPlot::set_yaxis(double min, double max) { setYaxis(min, max); } -void -ConstellationDisplayPlot::set_pen_size(int size) +void ConstellationDisplayPlot::set_axis(double xmin, double xmax, double ymin, double ymax) { - if(size > 0 && size < 30){ - d_pen_size = size; - for(int i = 0; i < d_nplots; i++) { - d_plot_curve[i]->setPen(QPen(Qt::blue, d_pen_size, Qt::SolidLine, - Qt::RoundCap, Qt::RoundJoin)); - } - } + set_xaxis(xmin, xmax); + set_yaxis(ymin, ymax); } -void -ConstellationDisplayPlot::replot() +void ConstellationDisplayPlot::set_pen_size(int size) { - BasicPlot::replot(); + if(size > 0 && size < 30) { + d_pen_size = size; + for(int i = 0; i < d_nplots; i++) { + d_plot_curve[i]->setPen(QPen(Qt::blue, d_pen_size, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); + } + } } +void ConstellationDisplayPlot::replot() { BasicPlot::replot(); } -void -ConstellationDisplayPlot::plotNewData(const std::vector &realDataPoints, - const std::vector &imagDataPoints, - const int64_t numDataPoints, - const double timeInterval) +void ConstellationDisplayPlot::plotNewData(const std::vector &realDataPoints, + const std::vector &imagDataPoints, const int64_t numDataPoints, + const double timeInterval) { - if(!d_stop) { - if((numDataPoints > 0)) { - if(numDataPoints != d_numPoints) { - d_numPoints = numDataPoints; + if(!d_stop) { + if((numDataPoints > 0)) { + if(numDataPoints != d_numPoints) { + d_numPoints = numDataPoints; - for(int i = 0; i < d_nplots; i++) { - delete [] d_real_data[i]; - delete [] d_imag_data[i]; - d_real_data[i] = new double[d_numPoints]; - d_imag_data[i] = new double[d_numPoints]; + for(int i = 0; i < d_nplots; i++) { + delete[] d_real_data[i]; + delete[] d_imag_data[i]; + d_real_data[i] = new double[d_numPoints]; + d_imag_data[i] = new double[d_numPoints]; #if QWT_VERSION < 0x060000 - d_plot_curve[i]->setRawData(d_real_data[i], d_imag_data[i], d_numPoints); + d_plot_curve[i]->setRawData(d_real_data[i], d_imag_data[i], d_numPoints); #else - d_plot_curve[i]->setRawSamples(d_real_data[i], d_imag_data[i], d_numPoints); + d_plot_curve[i]->setRawSamples(d_real_data[i], d_imag_data[i], d_numPoints); #endif + } + } + + for(int i = 0; i < d_nplots; i++) { + memcpy(d_real_data[i], realDataPoints[i], numDataPoints * sizeof(double)); + memcpy(d_imag_data[i], imagDataPoints[i], numDataPoints * sizeof(double)); + } + + if(d_autoscale_state) { + double bottom = 1e20, top = -1e20; + for(int n = 0; n < d_nplots; n++) { + for(int64_t point = 0; point < numDataPoints; point++) { + double b = std::min(realDataPoints[n][point], imagDataPoints[n][point]); + double t = std::max(realDataPoints[n][point], imagDataPoints[n][point]); + if(b < bottom) { + bottom = b; + } + if(t > top) { + top = t; + } + } + } + _autoScale(bottom, top); + } + + replot(); + } } - } - - for(int i = 0; i < d_nplots; i++) { - memcpy(d_real_data[i], realDataPoints[i], numDataPoints*sizeof(double)); - memcpy(d_imag_data[i], imagDataPoints[i], numDataPoints*sizeof(double)); - } - - if(d_autoscale_state) { - double bottom=1e20, top=-1e20; - for(int n = 0; n < d_nplots; n++) { - for(int64_t point = 0; point < numDataPoints; point++) { - double b = std::min(realDataPoints[n][point], imagDataPoints[n][point]); - double t = std::max(realDataPoints[n][point], imagDataPoints[n][point]); - if(b < bottom) { - bottom = b; - } - if(t > top) { - top = t; - } - } - } - _autoScale(bottom, top); - } - - replot(); - - } - } } -void -ConstellationDisplayPlot::plotNewData(const double* realDataPoints, - const double* imagDataPoints, - const int64_t numDataPoints, - const double timeInterval) +void ConstellationDisplayPlot::plotNewData(const double *realDataPoints, const double *imagDataPoints, + const int64_t numDataPoints, const double timeInterval) { - std::vector vecRealDataPoints; - std::vector vecImagDataPoints; - vecRealDataPoints.push_back((double*)realDataPoints); - vecImagDataPoints.push_back((double*)imagDataPoints); - plotNewData(vecRealDataPoints, vecImagDataPoints, - numDataPoints, timeInterval); + std::vector vecRealDataPoints; + std::vector vecImagDataPoints; + vecRealDataPoints.push_back((double *)realDataPoints); + vecImagDataPoints.push_back((double *)imagDataPoints); + plotNewData(vecRealDataPoints, vecImagDataPoints, numDataPoints, timeInterval); } -void -ConstellationDisplayPlot::newData(const QEvent* updateEvent) +void ConstellationDisplayPlot::newData(const QEvent *updateEvent) { - ConstUpdateEvent *tevent = (ConstUpdateEvent*)updateEvent; - const std::vector realDataPoints = tevent->getRealPoints(); - const std::vector imagDataPoints = tevent->getImagPoints(); - const uint64_t numDataPoints = tevent->getNumDataPoints(); - - this->plotNewData(realDataPoints, - imagDataPoints, - numDataPoints, - 0); -} + ConstUpdateEvent *tevent = (ConstUpdateEvent *)updateEvent; + const std::vector realDataPoints = tevent->getRealPoints(); + const std::vector imagDataPoints = tevent->getImagPoints(); + const uint64_t numDataPoints = tevent->getNumDataPoints(); -void -ConstellationDisplayPlot::customEvent(QEvent * e) -{ - if(e->type() == ConstUpdateEvent::Type()) { - newData(e); - } + this->plotNewData(realDataPoints, imagDataPoints, numDataPoints, 0); } -void -ConstellationDisplayPlot::_autoScale(double bottom, double top) +void ConstellationDisplayPlot::customEvent(QEvent *e) { - // Auto scale the x- and y-axis with a margin of 20% - double b = bottom - fabs(bottom)*0.20; - double t = top + fabs(top)*0.20; - set_axis(b, t, b, t); + if(e->type() == ConstUpdateEvent::Type()) { + newData(e); + } } -void -ConstellationDisplayPlot::setAutoScale(bool state) +void ConstellationDisplayPlot::_autoScale(double bottom, double top) { - d_autoscale_state = state; + // Auto scale the x- and y-axis with a margin of 20% + double b = bottom - fabs(bottom) * 0.20; + double t = top + fabs(top) * 0.20; + set_axis(b, t, b, t); } +void ConstellationDisplayPlot::setAutoScale(bool state) { d_autoscale_state = state; } + #endif /* CONSTELLATION_DISPLAY_PLOT_C */ diff --git a/gui/src/DisplayPlot.cc b/gui/src/DisplayPlot.cc index b730e877b5..40b756c239 100644 --- a/gui/src/DisplayPlot.cc +++ b/gui/src/DisplayPlot.cc @@ -40,67 +40,63 @@ */ #include "DisplayPlot.h" + #include "osc_scale_engine.h" -#include -#include -#include +#include +#include +#include +#include +#include +#include #include -#include #include +#include +#include +#include +#include +#include -#include -#include -#include #include #include #include -#include -#include -#include -#include using namespace scopy; -static QwtScaleDiv getEdgelessScaleDiv(const QwtScaleDiv& from_scaleDiv); +static QwtScaleDiv getEdgelessScaleDiv(const QwtScaleDiv &from_scaleDiv); /* * OscScaleDraw class implementation */ -OscScaleDraw::OscScaleDraw(const QString &unit) : QwtScaleDraw(), - m_floatPrecision(3), - m_unit(unit), - m_formatter(NULL), - m_color(Qt::gray), - m_displayScale(1), - m_shouldDrawMiddleDelta(false), - m_nrTicks(0), - m_delta(false) +OscScaleDraw::OscScaleDraw(const QString &unit) + : QwtScaleDraw() + , m_floatPrecision(3) + , m_unit(unit) + , m_formatter(NULL) + , m_color(Qt::gray) + , m_displayScale(1) + , m_shouldDrawMiddleDelta(false) + , m_nrTicks(0) + , m_delta(false) { enableComponent(QwtAbstractScaleDraw::Backbone, false); enableComponent(QwtAbstractScaleDraw::Ticks, false); } -OscScaleDraw::OscScaleDraw(PrefixFormatter *formatter, const QString& unit) : - OscScaleDraw(unit) +OscScaleDraw::OscScaleDraw(PrefixFormatter *formatter, const QString &unit) + : OscScaleDraw(unit) { m_formatter = formatter; } -void OscScaleDraw::setFloatPrecision(unsigned int numDigits) -{ - m_floatPrecision = numDigits; -} +void OscScaleDraw::setFloatPrecision(unsigned int numDigits) { m_floatPrecision = numDigits; } -unsigned int OscScaleDraw::getFloatPrecison() const -{ - return m_floatPrecision; -} +unsigned int OscScaleDraw::getFloatPrecison() const { return m_floatPrecision; } -void OscScaleDraw::setUnitType(const QString& unit) +void OscScaleDraw::setUnitType(const QString &unit) { - if (m_unit != unit) { + if(m_unit != unit) { m_unit = unit; // Trigger a new redraw of scale labels since there's a new unit that needs to be redrawn @@ -108,30 +104,17 @@ void OscScaleDraw::setUnitType(const QString& unit) } } -QString OscScaleDraw::getUnitType() const -{ - return m_unit; -} +QString OscScaleDraw::getUnitType() const { return m_unit; } -void OscScaleDraw::setColor(QColor color) -{ - m_color = color; -} +void OscScaleDraw::setColor(QColor color) { m_color = color; } -void OscScaleDraw::setDisplayScale(double value) -{ - m_displayScale = value; -} +void OscScaleDraw::setDisplayScale(double value) { m_displayScale = value; } - -void OscScaleDraw::setFormatter(PrefixFormatter *formatter) -{ - m_formatter = formatter; -} +void OscScaleDraw::setFormatter(PrefixFormatter *formatter) { m_formatter = formatter; } void OscScaleDraw::enableDeltaLabel(bool enable) { - if (enable != m_delta) { + if(enable != m_delta) { m_delta = enable; // Trigger a new redraw of the scale @@ -148,11 +131,11 @@ void OscScaleDraw::draw(QPainter *painter, const QPalette &palette) const QList ticks = scaleDiv().ticks(QwtScaleDiv::MajorTick); QList labels; - for (int i = 0; i < ticks.size(); ++i){ + for(int i = 0; i < ticks.size(); ++i) { QRect bounds = boundingLabelRect(painter->font(), ticks[i]); int half = painter->font().pointSize() / 4; - if (orientation() == Qt::Horizontal) + if(orientation() == Qt::Horizontal) bounds.adjust(-half, 0, half, 0); else bounds.adjust(0, -half / 2, 0, half / 2); @@ -166,58 +149,57 @@ void OscScaleDraw::draw(QPainter *painter, const QPalette &palette) const do { overlap = false; - for(int i = 1; i < labels.size(); ++i){ + for(int i = 1; i < labels.size(); ++i) { QRect last_rectangle = labels.at(i - 1); QRect current_rectangle = labels.at(i); - if (current_rectangle.intersects(last_rectangle)){ + if(current_rectangle.intersects(last_rectangle)) { overlap = true; break; } } - if (overlap) { - if (m_delta) { + if(overlap) { + if(m_delta) { // If the middle delta label is to be drawn we are sure that // ticks.size() is an odd number int center = midLabelPos; - for (int i = center - 1; i >= 0; i -= 2) { + for(int i = center - 1; i >= 0; i -= 2) { // Remove the tick and make sure to update the center // label position ticks.removeAt(i); labels.removeAt(i); --center; } - for (int j = center + 1; j < ticks.size(); j += 1) { + for(int j = center + 1; j < ticks.size(); j += 1) { ticks.removeAt(j); labels.removeAt(j); } } else { - for (int i = 1; i < ticks.size(); ++i) { + for(int i = 1; i < ticks.size(); ++i) { ticks.removeAt(i); labels.removeAt(i); } } } - } while (overlap); + } while(overlap); double delta = -INFINITY; - if (m_delta && m_nrTicks > midLabelPos) { + if(m_delta && m_nrTicks > midLabelPos) { delta = scaleDiv().ticks(QwtScaleDiv::MajorTick)[midLabelPos]; drawLabel(painter, delta); } - for (const auto &tick : qAsConst(ticks)) { - if (tick != delta) { + for(const auto &tick : qAsConst(ticks)) { + if(tick != delta) { drawLabel(painter, tick); } } } - -QwtText OscScaleDraw::label( double value ) const +QwtText OscScaleDraw::label(double value) const { QString prefix; double scale = 1.0; @@ -232,20 +214,21 @@ QwtText OscScaleDraw::label( double value ) const int mid = (m_nrTicks / 2 + 1); - if (m_delta) { + if(m_delta) { int current = 0; - while (value > (lower + current * step)) current++; + while(value > (lower + current * step)) + current++; int position = current + 1; - if (position == mid){ + if(position == mid) { // center label with extra precision center = true; bonusPrecision = 1; - } else if (position < mid){ + } else if(position < mid) { sign = "-"; // negative delta label value = step * (mid - position); - } else if (position > mid) { + } else if(position > mid) { sign = "+"; // positive delta label value = step * (position - mid); @@ -254,34 +237,34 @@ QwtText OscScaleDraw::label( double value ) const value *= m_displayScale; - if (m_formatter) { + if(m_formatter) { m_formatter->getFormatAttributes(value, prefix, scale); } - if (orientation() == Qt::Vertical) { + if(orientation() == Qt::Vertical) { double absVal = value > 0 ? value : -value; - if (absVal > 1e-2 && prefix == "m") { + if(absVal > 1e-2 && prefix == "m") { scale = 1.0; prefix = ""; - } else if (absVal > 1e-5 && prefix == "μ") { + } else if(absVal > 1e-5 && prefix == "μ") { scale = 1e-3; prefix = "m"; - } else if (absVal > 1e-8 && prefix == "n") { + } else if(absVal > 1e-8 && prefix == "n") { scale = 1e-6; prefix = "μ"; - } else if (absVal > 1e-11 && prefix == "p") { + } else if(absVal > 1e-11 && prefix == "p") { scale = 1e-9; prefix = "n"; } } - QwtText text(sign + QLocale().toString(value / scale, 'f', m_floatPrecision + bonusPrecision) - + ' ' + prefix + m_unit); + QwtText text(sign + QLocale().toString(value / scale, 'f', m_floatPrecision + bonusPrecision) + ' ' + prefix + + m_unit); - if (m_color != Qt::gray) + if(m_color != Qt::gray) text.setColor(m_color); - if (center) { - text.setColor(QColor(255, 255,255)); + if(center) { + text.setColor(QColor(255, 255, 255)); } return text; @@ -290,141 +273,132 @@ QwtText OscScaleDraw::label( double value ) const /* * EdgelessPlotScaleItem class implementation */ -EdgelessPlotScaleItem::EdgelessPlotScaleItem( - QwtScaleDraw::Alignment alignment, const double pos ): - QwtPlotScaleItem(alignment, pos) -{ -} +EdgelessPlotScaleItem::EdgelessPlotScaleItem(QwtScaleDraw::Alignment alignment, const double pos) + : QwtPlotScaleItem(alignment, pos) +{} -void EdgelessPlotScaleItem::updateScaleDiv( const QwtScaleDiv& xScaleDiv, - const QwtScaleDiv& yScaleDiv ) +void EdgelessPlotScaleItem::updateScaleDiv(const QwtScaleDiv &xScaleDiv, const QwtScaleDiv &yScaleDiv) { - QwtPlotScaleItem::updateScaleDiv(getEdgelessScaleDiv(xScaleDiv), - getEdgelessScaleDiv(yScaleDiv)); + QwtPlotScaleItem::updateScaleDiv(getEdgelessScaleDiv(xScaleDiv), getEdgelessScaleDiv(yScaleDiv)); } /* * EdgelessPlotGrid class implementation */ -EdgelessPlotGrid::EdgelessPlotGrid(): - QwtPlotGrid() -{ -} +EdgelessPlotGrid::EdgelessPlotGrid() + : QwtPlotGrid() +{} -void EdgelessPlotGrid::updateScaleDiv( const QwtScaleDiv& xScaleDiv, - const QwtScaleDiv& yScaleDiv ) +void EdgelessPlotGrid::updateScaleDiv(const QwtScaleDiv &xScaleDiv, const QwtScaleDiv &yScaleDiv) { - QwtPlotGrid::updateScaleDiv(getEdgelessScaleDiv(xScaleDiv), - getEdgelessScaleDiv(yScaleDiv)); + QwtPlotGrid::updateScaleDiv(getEdgelessScaleDiv(xScaleDiv), getEdgelessScaleDiv(yScaleDiv)); } -OscPlotZoomer::OscPlotZoomer(QwtAxisId xAxis, QwtAxisId yAxis, QWidget *parent, bool doReplot) : - ExtendingPlotZoomer(xAxis, yAxis, parent, doReplot), - lastIndex(-1){ - -} +OscPlotZoomer::OscPlotZoomer(QwtAxisId xAxis, QwtAxisId yAxis, QWidget *parent, bool doReplot) + : ExtendingPlotZoomer(xAxis, yAxis, parent, doReplot) + , lastIndex(-1) +{} -OscPlotZoomer::OscPlotZoomer(QWidget *parent, bool doReplot) : - ExtendingPlotZoomer(parent, doReplot), - lastIndex(-1) -{ -} +OscPlotZoomer::OscPlotZoomer(QWidget *parent, bool doReplot) + : ExtendingPlotZoomer(parent, doReplot) + , lastIndex(-1) +{} void OscPlotZoomer::rescale() { DisplayPlot *plt = static_cast(plot()); - if ( !plt ) - return; + if(!plt) + return; - if (!plt->canvas()->isVisible()) + if(!plt->canvas()->isVisible()) return; const QStack &stack = zoomStack(); int index = zoomRectIndex(); const QRectF &rect = stack[index]; bool isZoomOut = false; - if ( rect != scaleRect() ) - { + if(rect != scaleRect()) { - double x1 = rect.left(); - double x2 = rect.right(); - double y1 = rect.top(); - double y2 = rect.bottom(); + double x1 = rect.left(); + double x2 = rect.right(); + double y1 = rect.top(); + double y2 = rect.bottom(); - if ( !plt->axisScaleDiv( xAxis() ).isIncreasing() ){ - qSwap( x1, x2 ); - } + if(!plt->axisScaleDiv(xAxis()).isIncreasing()) { + qSwap(x1, x2); + } - if ( !plt->axisScaleDiv( yAxis() ).isIncreasing() ) - qSwap( y1, y2 ); + if(!plt->axisScaleDiv(yAxis()).isIncreasing()) + qSwap(y1, y2); - double width = fabs(x1 - x2); - double height = fabs(y1 - y2); + double width = fabs(x1 - x2); + double height = fabs(y1 - y2); - if (height == 0 || width == 0) { - return; - } + if(height == 0 || width == 0) { + return; + } - if (lastIndex < index) { - Q_EMIT zoomIn(); - } - else { - Q_EMIT zoomOut(); - isZoomOut = true; - } - lastIndex = index; + if(lastIndex < index) { + Q_EMIT zoomIn(); + } else { + Q_EMIT zoomOut(); + isZoomOut = true; + } + lastIndex = index; - const bool doReplot = plt->autoReplot(); - plt->setAutoReplot( false ); + const bool doReplot = plt->autoReplot(); + plt->setAutoReplot(false); - if (yAxis().id == 0) { - plt->setHorizUnitsPerDiv(width / plt->xAxisNumDiv()); - plt->setHorizOffset(x1 + (width / 2)); - } + if(yAxis().id == 0) { + plt->setHorizUnitsPerDiv(width / plt->xAxisNumDiv()); + plt->setHorizOffset(x1 + (width / 2)); + } - plt->setVertUnitsPerDiv(height / plt->yAxisNumDiv(), yAxis().id); - plt->setVertOffset(y1 + (height / 2), yAxis().id); + plt->setVertUnitsPerDiv(height / plt->yAxisNumDiv(), yAxis().id); + plt->setVertOffset(y1 + (height / 2), yAxis().id); - plt->setAutoReplot( doReplot ); + plt->setAutoReplot(doReplot); - plt->replot(); + plt->replot(); - Q_EMIT zoomFinished(isZoomOut); + Q_EMIT zoomFinished(isZoomOut); } } /* * PlotAxisConfiguration */ -PlotAxisConfiguration::PlotAxisConfiguration(int axisPos, int axisIdx, DisplayPlot *plot): - d_axis(QwtAxisId(axisPos, axisIdx)), d_plot(plot), d_hoverCursorShape(Qt::ArrowCursor) +PlotAxisConfiguration::PlotAxisConfiguration(int axisPos, int axisIdx, DisplayPlot *plot) + : d_axis(QwtAxisId(axisPos, axisIdx)) + , d_plot(plot) + , d_hoverCursorShape(Qt::ArrowCursor) { - //we don't use this variable -// Qt::CursorShape shape; + // we don't use this variable + // Qt::CursorShape shape; -// switch (axisPos) { -// case QwtAxis::YLeft: -// shape = Qt::CursorShape::SizeVerCursor; -// break; + // switch (axisPos) { + // case QwtAxis::YLeft: + // shape = Qt::CursorShape::SizeVerCursor; + // break; -// case QwtAxis::XBottom: -// shape = Qt::CursorShape::SizeHorCursor; -// break; + // case QwtAxis::XBottom: + // shape = Qt::CursorShape::SizeHorCursor; + // break; -// default: -// return; -// } + // default: + // return; + // } // Set cursor shape when hovering over the axis - //setCursorShapeOnHover(shape); + // setCursorShapeOnHover(shape); // Avoid jumping when labels with more/less digits // appear/disappear when scrolling vertically - if (axisPos == QwtAxis::YRight || axisPos == QwtAxis::YLeft) { + if(axisPos == QwtAxis::YRight || axisPos == QwtAxis::YLeft) { const QFontMetrics fm(d_plot->axisWidget(d_axis)->font()); QwtScaleDraw *scaleDraw = d_plot->axisScaleDraw(d_axis); - scaleDraw->setMinimumExtent(fm.horizontalAdvance("100.00") ); + scaleDraw->setMinimumExtent(fm.horizontalAdvance("100.00")); } // TO DO: Move this to a stylesheet file. @@ -437,63 +411,42 @@ PlotAxisConfiguration::PlotAxisConfiguration(int axisPos, int axisIdx, DisplayPl d_ptsPerDiv = 1.0; d_offset = 0.0; - if (axisPos == QwtAxis::YLeft || axisPos == QwtAxis::YRight) { + if(axisPos == QwtAxis::YLeft || axisPos == QwtAxis::YRight) { d_mouseGestures = new VertMouseGestures(d_plot->axisWidget(d_axis), d_axis); d_mouseGestures->setEnabled(false); - QObject::connect(this->d_mouseGestures, SIGNAL(wheelDown(int)), - d_plot, SLOT(vertAxisScaleIncrease())); - QObject::connect(this->d_mouseGestures, SIGNAL(wheelUp(int)), - d_plot, SLOT(vertAxisScaleDecrease())); + QObject::connect(this->d_mouseGestures, SIGNAL(wheelDown(int)), d_plot, SLOT(vertAxisScaleIncrease())); + QObject::connect(this->d_mouseGestures, SIGNAL(wheelUp(int)), d_plot, SLOT(vertAxisScaleDecrease())); - QObject::connect(this->d_mouseGestures, SIGNAL(upMovement(double)), - d_plot, SLOT(onVertAxisOffsetDecrease())); - QObject::connect(this->d_mouseGestures, SIGNAL(downMovement(double)), - d_plot, SLOT(onVertAxisOffsetIncrease())); - } else if (axisPos == QwtAxis::XBottom) { + QObject::connect(this->d_mouseGestures, SIGNAL(upMovement(double)), d_plot, + SLOT(onVertAxisOffsetDecrease())); + QObject::connect(this->d_mouseGestures, SIGNAL(downMovement(double)), d_plot, + SLOT(onVertAxisOffsetIncrease())); + } else if(axisPos == QwtAxis::XBottom) { d_mouseGestures = new HorizMouseGestures(d_plot->axisWidget(d_axis), d_axis); d_mouseGestures->setEnabled(false); - QObject::connect(this->d_mouseGestures, SIGNAL(wheelDown(int)), - d_plot, SLOT(horizAxisScaleIncrease())); - QObject::connect(this->d_mouseGestures, SIGNAL(wheelUp(int)), - d_plot, SLOT(horizAxisScaleDecrease())); + QObject::connect(this->d_mouseGestures, SIGNAL(wheelDown(int)), d_plot, SLOT(horizAxisScaleIncrease())); + QObject::connect(this->d_mouseGestures, SIGNAL(wheelUp(int)), d_plot, SLOT(horizAxisScaleDecrease())); - QObject::connect(this->d_mouseGestures, SIGNAL(rightMovement(double)), - d_plot, SLOT(onHorizAxisOffsetDecrease())); - QObject::connect(this->d_mouseGestures, SIGNAL(leftMovement(double)), - d_plot, SLOT(onHorizAxisOffsetIncrease())); + QObject::connect(this->d_mouseGestures, SIGNAL(rightMovement(double)), d_plot, + SLOT(onHorizAxisOffsetDecrease())); + QObject::connect(this->d_mouseGestures, SIGNAL(leftMovement(double)), d_plot, + SLOT(onHorizAxisOffsetIncrease())); } } -PlotAxisConfiguration::~PlotAxisConfiguration() -{ -} +PlotAxisConfiguration::~PlotAxisConfiguration() {} -QwtAxisId& PlotAxisConfiguration::axis() -{ - return d_axis; -} +QwtAxisId &PlotAxisConfiguration::axis() { return d_axis; } -void PlotAxisConfiguration::setPtsPerDiv(double value) -{ - d_ptsPerDiv = value; -} +void PlotAxisConfiguration::setPtsPerDiv(double value) { d_ptsPerDiv = value; } -double PlotAxisConfiguration::ptsPerDiv() -{ - return d_ptsPerDiv; -} +double PlotAxisConfiguration::ptsPerDiv() { return d_ptsPerDiv; } -void PlotAxisConfiguration::setOffset(double value) -{ - d_offset = value; -} +void PlotAxisConfiguration::setOffset(double value) { d_offset = value; } -double PlotAxisConfiguration::offset() -{ - return d_offset; -} +double PlotAxisConfiguration::offset() { return d_offset; } void PlotAxisConfiguration::setCursorShapeOnHover(Qt::CursorShape shape) { @@ -506,7 +459,7 @@ void PlotAxisConfiguration::setMouseGesturesEnabled(bool en) { d_mouseGestures->setEnabled(en); QwtScaleWidget *scaleWidget = d_plot->axisWidget(d_axis); - if (en) { + if(en) { scaleWidget->setCursor(d_hoverCursorShape); } else { scaleWidget->setCursor(QCursor()); @@ -516,28 +469,30 @@ void PlotAxisConfiguration::setMouseGesturesEnabled(bool en) /* * DisplayPlot class */ -DisplayPlot::DisplayPlot(int nplots, QWidget* parent, bool isdBgraph, - unsigned int xNumDivs, unsigned int yNumDivs, int qwtAxis) - : PrintablePlot(parent), d_nplots(nplots), d_stop(false), - d_coloredLabels(false), d_mouseGesturesEnabled(false), - d_displayScale(1), d_xAxisNumDiv(1), d_trackMode(false), - d_cursorsEnabled(false), d_isLogaritmicPlot(false), - d_isLogaritmicYPlot(false), - d_yAxisNumDiv(1), - m_qwtYAxis(qwtAxis) -{ - - d_CurveColors << QColor("#ff7200") << QColor("#9013fe") << QColor(Qt::green) - << QColor(Qt::cyan) << QColor(Qt::magenta) - << QColor(Qt::yellow) << QColor(Qt::gray) << QColor(Qt::darkRed) - << QColor(Qt::darkGreen) << QColor(Qt::darkBlue) << QColor(Qt::darkGray) - << QColor(Qt::black); - - d_printColors << QColor("#ff7200") << QColor("#9013fe") << QColor(Qt::green) - << QColor(Qt::cyan) << QColor(Qt::magenta) - << QColor(Qt::yellow) << QColor(Qt::gray) << QColor(Qt::darkRed) - << QColor(Qt::darkGreen) << QColor(Qt::darkBlue) << QColor(Qt::darkGray) - << QColor(Qt::black); +DisplayPlot::DisplayPlot(int nplots, QWidget *parent, bool isdBgraph, unsigned int xNumDivs, unsigned int yNumDivs, + int qwtAxis) + : PrintablePlot(parent) + , d_nplots(nplots) + , d_stop(false) + , d_coloredLabels(false) + , d_mouseGesturesEnabled(false) + , d_displayScale(1) + , d_xAxisNumDiv(1) + , d_trackMode(false) + , d_cursorsEnabled(false) + , d_isLogaritmicPlot(false) + , d_isLogaritmicYPlot(false) + , d_yAxisNumDiv(1) + , m_qwtYAxis(qwtAxis) +{ + + d_CurveColors << QColor("#ff7200") << QColor("#9013fe") << QColor(Qt::green) << QColor(Qt::cyan) + << QColor(Qt::magenta) << QColor(Qt::yellow) << QColor(Qt::gray) << QColor(Qt::darkRed) + << QColor(Qt::darkGreen) << QColor(Qt::darkBlue) << QColor(Qt::darkGray) << QColor(Qt::black); + + d_printColors << QColor("#ff7200") << QColor("#9013fe") << QColor(Qt::green) << QColor(Qt::cyan) + << QColor(Qt::magenta) << QColor(Qt::yellow) << QColor(Qt::gray) << QColor(Qt::darkRed) + << QColor(Qt::darkGreen) << QColor(Qt::darkBlue) << QColor(Qt::darkGray) << QColor(Qt::black); qRegisterMetaType("QColorList"); resize(parent->width(), parent->height()); @@ -576,23 +531,21 @@ DisplayPlot::DisplayPlot(int nplots, QWidget* parent, bool isdBgraph, d_picker = new QwtDblClickPlotPicker(canvas()); #if QWT_VERSION < 0x060000 - connect(d_picker, SIGNAL(selected(const QPointF &)), - this, SLOT(onPickerPointSelected(const QPointF &))); + connect(d_picker, SIGNAL(selected(const QPointF &)), this, SLOT(onPickerPointSelected(const QPointF &))); #else d_picker->setStateMachine(new QwtPickerDblClickPointMachine()); - connect(d_picker, SIGNAL(selected(const QPointF &)), - this, SLOT(onPickerPointSelected6(const QPointF &))); + connect(d_picker, SIGNAL(selected(const QPointF &)), this, SLOT(onPickerPointSelected6(const QPointF &))); #endif // Configure horizontal axis bottomHorizAxisInit(); - QColor plotColor; - if (QIcon::themeName() == "scopy-default") { - plotColor = QColor("#6E6E6F"); - } else { - plotColor = QColor("#D3D3D3"); - } + QColor plotColor; + if(QIcon::themeName() == "scopy-default") { + plotColor = QColor("#6E6E6F"); + } else { + plotColor = QColor("#D3D3D3"); + } // One vertical axis by default setLeftVertAxesCount(1); @@ -606,9 +559,9 @@ DisplayPlot::DisplayPlot(int nplots, QWidget* parent, bool isdBgraph, this->plotLayout()->setCanvasMargin(0, QwtAxis::XTop); this->plotLayout()->setCanvasMargin(0, QwtAxis::XBottom); - ((QFrame*) canvas())->setLineWidth(0); + ((QFrame *)canvas())->setLineWidth(0); - //Set up the grid and the legend for all displayplots, but dBgraph + // Set up the grid and the legend for all displayplots, but dBgraph setupDisplayPlotDiv(isdBgraph); d_symbolCtrl = new SymbolController(this); @@ -621,8 +574,8 @@ DisplayPlot::DisplayPlot(int nplots, QWidget* parent, bool isdBgraph, d_bottomHandlesArea->setMinimumHeight(50); d_rightHandlesArea->setMinimumWidth(50); -// d_bottomHandlesArea->setLargestChildWidth(60); -// d_rightHandlesArea->setLargestChildHeight(60); + // d_bottomHandlesArea->setLargestChildWidth(60); + // d_rightHandlesArea->setLargestChildHeight(60); d_rightHandlesArea->setMinimumHeight(this->minimumHeight()); d_rightHandlesArea->setBottomPadding(50); @@ -630,14 +583,10 @@ DisplayPlot::DisplayPlot(int nplots, QWidget* parent, bool isdBgraph, markerIntersection1 = new QwtPlotMarker(); markerIntersection2 = new QwtPlotMarker(); - markerIntersection1->setSymbol(new QwtSymbol( - QwtSymbol::Ellipse, QColor(237, 28, 36), - QPen(QColor(255, 255 ,255, 140), 2, Qt::SolidLine), - QSize(5, 5))); - markerIntersection2->setSymbol(new QwtSymbol( - QwtSymbol::Ellipse, QColor(237, 28, 36), - QPen(QColor(255, 255 ,255, 140), 2, Qt::SolidLine), - QSize(5, 5))); + markerIntersection1->setSymbol(new QwtSymbol(QwtSymbol::Ellipse, QColor(237, 28, 36), + QPen(QColor(255, 255, 255, 140), 2, Qt::SolidLine), QSize(5, 5))); + markerIntersection2->setSymbol(new QwtSymbol(QwtSymbol::Ellipse, QColor(237, 28, 36), + QPen(QColor(255, 255, 255, 140), 2, Qt::SolidLine), QSize(5, 5))); d_selected_channel = -1; @@ -645,86 +594,83 @@ DisplayPlot::DisplayPlot(int nplots, QWidget* parent, bool isdBgraph, setupReadouts(); } +void DisplayPlot::setupDisplayPlotDiv(bool isdBgraph) +{ + if(!isdBgraph) { -void DisplayPlot::setupDisplayPlotDiv(bool isdBgraph) { - if(!isdBgraph) - { - - // Avoid jumping when labels with more/less digits - // appear/disappear when scrolling vertically - QwtLegend* legendDisplay = new QwtLegend(this); + // Avoid jumping when labels with more/less digits + // appear/disappear when scrolling vertically + QwtLegend *legendDisplay = new QwtLegend(this); #if QWT_VERSION < 0x060100 - legendDisplay->setItemMode(QwtLegend::CheckableItem); - insertLegend(legendDisplay); - connect(this, SIGNAL(legendChecked(QwtPlotItem *, bool)), - this, SLOT(legendEntryChecked(QwtPlotItem *, bool))); -#else /* QWT_VERSION < 0x060100 */ - legendDisplay->setDefaultItemMode(QwtLegendData::Checkable); - insertLegend(legendDisplay); - connect(legendDisplay, SIGNAL(checked(const QVariant&, bool, int)), - this, SLOT(legendEntryChecked(const QVariant&, bool, int))); + legendDisplay->setItemMode(QwtLegend::CheckableItem); + insertLegend(legendDisplay); + connect(this, SIGNAL(legendChecked(QwtPlotItem *, bool)), this, + SLOT(legendEntryChecked(QwtPlotItem *, bool))); +#else /* QWT_VERSION < 0x060100 */ + legendDisplay->setDefaultItemMode(QwtLegendData::Checkable); + insertLegend(legendDisplay); + connect(legendDisplay, SIGNAL(checked(const QVariant &, bool, int)), this, + SLOT(legendEntryChecked(const QVariant &, bool, int))); #endif /* QWT_VERSION < 0x060100 */ - for (unsigned int i = 0; i < 4; i++) { - QwtScaleDraw::Alignment scale = - static_cast(i); - auto scaleItem = new EdgelessPlotScaleItem(scale); - - scaleItem->scaleDraw()->setAlignment(scale); - scaleItem->scaleDraw()->enableComponent(QwtAbstractScaleDraw::Backbone, false); - scaleItem->scaleDraw()->enableComponent(QwtAbstractScaleDraw::Labels, false); - scaleItem->setFont(this->axisWidget(m_qwtYAxis)->font()); - - QPalette palette = scaleItem->palette(); - palette.setBrush(QPalette::WindowText, QColor(0x6E6E6F)); - palette.setBrush(QPalette::Text, QColor(0x6E6E6F)); - scaleItem->setPalette(palette); - scaleItem->setBorderDistance(0); - scaleItem->attach(this); - scaleItems.push_back(scaleItem); - scaleItem->setZ(200); - } + for(unsigned int i = 0; i < 4; i++) { + QwtScaleDraw::Alignment scale = static_cast(i); + auto scaleItem = new EdgelessPlotScaleItem(scale); + + scaleItem->scaleDraw()->setAlignment(scale); + scaleItem->scaleDraw()->enableComponent(QwtAbstractScaleDraw::Backbone, false); + scaleItem->scaleDraw()->enableComponent(QwtAbstractScaleDraw::Labels, false); + scaleItem->setFont(this->axisWidget(m_qwtYAxis)->font()); + + QPalette palette = scaleItem->palette(); + palette.setBrush(QPalette::WindowText, QColor(0x6E6E6F)); + palette.setBrush(QPalette::Text, QColor(0x6E6E6F)); + scaleItem->setPalette(palette); + scaleItem->setBorderDistance(0); + scaleItem->attach(this); + scaleItems.push_back(scaleItem); + scaleItem->setZ(200); + } - // Plot needs a grid - d_grid = new EdgelessPlotGrid(); - QColor majorPenColor("#353537"); - d_grid->setYAxis(m_qwtYAxis); - d_grid->setMajorPen(majorPenColor, 1.0, Qt::DashLine); - d_grid->attach(this); - } + // Plot needs a grid + d_grid = new EdgelessPlotGrid(); + QColor majorPenColor("#353537"); + d_grid->setYAxis(m_qwtYAxis); + d_grid->setMajorPen(majorPenColor, 1.0, Qt::DashLine); + d_grid->attach(this); + } } - DisplayPlot::~DisplayPlot() { markerIntersection1->detach(); markerIntersection2->detach(); - // d_zoomer and d_panner deleted when parent deleted - // Since some curves may not be attached to the plot they won't get deleted - for (auto it = d_plot_curve.begin(); it != d_plot_curve.end() ; ++it) { - QwtPlotCurve * qpc = (*it); - qpc->detach(); - delete qpc; - } - - // delete vertAxes - for (auto it = vertAxes.begin(); it != vertAxes.end(); ++it) { - delete *it; - } - - for (auto it = scaleItems.begin(); it != scaleItems.end(); ++it) { - delete *it; - } + // d_zoomer and d_panner deleted when parent deleted + // Since some curves may not be attached to the plot they won't get deleted + for(auto it = d_plot_curve.begin(); it != d_plot_curve.end(); ++it) { + QwtPlotCurve *qpc = (*it); + qpc->detach(); + delete qpc; + } + + // delete vertAxes + for(auto it = vertAxes.begin(); it != vertAxes.end(); ++it) { + delete *it; + } + + for(auto it = scaleItems.begin(); it != scaleItems.end(); ++it) { + delete *it; + } delete markerIntersection1; delete markerIntersection2; delete horizAxis; } -QWidget* DisplayPlot::getPlotwithElements() +QWidget *DisplayPlot::getPlotwithElements() { - QWidget* widget = new QWidget(); + QWidget *widget = new QWidget(); QGridLayout *gridplot = new QGridLayout(); gridplot->addWidget(topHandlesArea(), 0, 0, 1, 3); @@ -756,25 +702,18 @@ void DisplayPlot::setCursorAxes(QwtAxisId fixed_axis, QwtAxisId mobile_axis) d_hBar2->setFixedAxis(fixed_axis); } -void DisplayPlot::setupCursors() { +void DisplayPlot::setupCursors() +{ d_vBar1 = new VertBar(this, true); d_vBar2 = new VertBar(this, true); d_hBar1 = new HorizBar(this, true); d_hBar2 = new HorizBar(this, true); - d_vCursorHandle1 = new PlotLineHandleV( - QPixmap(":/gui/icons/v_cursor_handle.svg"), - d_rightHandlesArea); - d_vCursorHandle2 = new PlotLineHandleV( - QPixmap(":/gui/icons/v_cursor_handle.svg"), - d_rightHandlesArea); - d_hCursorHandle1 = new PlotLineHandleH( - QPixmap(":/gui/icons/h_cursor_handle.svg"), - d_bottomHandlesArea); - d_hCursorHandle2 = new PlotLineHandleH( - QPixmap(":/gui/icons/h_cursor_handle.svg"), - d_bottomHandlesArea); + d_vCursorHandle1 = new PlotLineHandleV(QPixmap(":/gui/icons/v_cursor_handle.svg"), d_rightHandlesArea); + d_vCursorHandle2 = new PlotLineHandleV(QPixmap(":/gui/icons/v_cursor_handle.svg"), d_rightHandlesArea); + d_hCursorHandle1 = new PlotLineHandleH(QPixmap(":/gui/icons/h_cursor_handle.svg"), d_bottomHandlesArea); + d_hCursorHandle2 = new PlotLineHandleH(QPixmap(":/gui/icons/h_cursor_handle.svg"), d_bottomHandlesArea); d_vertCursorsHandleEnabled = true; @@ -808,49 +747,38 @@ void DisplayPlot::setupCursors() { horizCursorsLocked = false; /* When a handle position changes the bar follows */ - connect(d_vCursorHandle1, SIGNAL(positionChanged(int)), - SLOT(onVertCursorHandle1Changed(int))); - connect(d_vCursorHandle2, SIGNAL(positionChanged(int)), - SLOT(onVertCursorHandle2Changed(int))); - connect(d_hCursorHandle1, SIGNAL(positionChanged(int)), - SLOT(onHorizCursorHandle1Changed(int))); - connect(d_hCursorHandle2, SIGNAL(positionChanged(int)), - SLOT(onHorizCursorHandle2Changed(int))); + connect(d_vCursorHandle1, SIGNAL(positionChanged(int)), SLOT(onVertCursorHandle1Changed(int))); + connect(d_vCursorHandle2, SIGNAL(positionChanged(int)), SLOT(onVertCursorHandle2Changed(int))); + connect(d_hCursorHandle1, SIGNAL(positionChanged(int)), SLOT(onHorizCursorHandle1Changed(int))); + connect(d_hCursorHandle2, SIGNAL(positionChanged(int)), SLOT(onHorizCursorHandle2Changed(int))); /* When bar position changes due to plot resizes update the handle */ - connect(d_hBar1, SIGNAL(pixelPositionChanged(int)), - SLOT(onHbar1PixelPosChanged(int))); - connect(d_hBar2, SIGNAL(pixelPositionChanged(int)), - SLOT(onHbar2PixelPosChanged(int))); - connect(d_vBar1, SIGNAL(pixelPositionChanged(int)), - SLOT(onVbar1PixelPosChanged(int))); - connect(d_vBar2, SIGNAL(pixelPositionChanged(int)), - SLOT(onVbar2PixelPosChanged(int))); + connect(d_hBar1, SIGNAL(pixelPositionChanged(int)), SLOT(onHbar1PixelPosChanged(int))); + connect(d_hBar2, SIGNAL(pixelPositionChanged(int)), SLOT(onHbar2PixelPosChanged(int))); + connect(d_vBar1, SIGNAL(pixelPositionChanged(int)), SLOT(onVbar1PixelPosChanged(int))); + connect(d_vBar2, SIGNAL(pixelPositionChanged(int)), SLOT(onVbar2PixelPosChanged(int))); } -void DisplayPlot::setupReadouts() { +void DisplayPlot::setupReadouts() +{ d_cursorReadoutsVisible = false; d_cursorReadouts = new CursorReadouts(this); - d_cursorReadouts->setAxis(QwtAxis::XTop,m_qwtYAxis); + d_cursorReadouts->setAxis(QwtAxis::XTop, m_qwtYAxis); d_cursorReadouts->setTopLeftStartingPoint(QPoint(8, 8)); d_cursorReadouts->setTimeReadoutVisible(false); d_cursorReadouts->setVoltageReadoutVisible(false); /* Update Cursor Readouts */ - connect(d_hBar1, SIGNAL(positionChanged(double)), - SLOT(onHCursor1Moved(double))); - connect(d_hBar2, SIGNAL(positionChanged(double)), - SLOT(onHCursor2Moved(double))); - connect(d_vBar1, SIGNAL(positionChanged(double)), - SLOT(onVCursor1Moved(double))); - connect(d_vBar2, SIGNAL(positionChanged(double)), - SLOT(onVCursor2Moved(double))); + connect(d_hBar1, SIGNAL(positionChanged(double)), SLOT(onHCursor1Moved(double))); + connect(d_hBar2, SIGNAL(positionChanged(double)), SLOT(onHCursor2Moved(double))); + connect(d_vBar1, SIGNAL(positionChanged(double)), SLOT(onVCursor1Moved(double))); + connect(d_vBar2, SIGNAL(positionChanged(double)), SLOT(onVCursor2Moved(double))); } void DisplayPlot::onVertCursorHandle1Changed(int value) { - if (vertCursorsLocked) { + if(vertCursorsLocked) { int position2 = value - (pixelPosHandleVert1 - pixelPosHandleVert2); pixelPosHandleVert2 = position2; d_hBar2->setPixelPosition(position2); @@ -862,7 +790,7 @@ void DisplayPlot::onVertCursorHandle1Changed(int value) void DisplayPlot::onVertCursorHandle2Changed(int value) { - if (vertCursorsLocked) { + if(vertCursorsLocked) { int position1 = value + (pixelPosHandleVert1 - pixelPosHandleVert2); pixelPosHandleVert1 = position1; d_hBar1->setPixelPosition(position1); @@ -871,10 +799,9 @@ void DisplayPlot::onVertCursorHandle2Changed(int value) d_hBar2->setPixelPosition(value); } - void DisplayPlot::onHorizCursorHandle1Changed(int value) { - if (horizCursorsLocked) { + if(horizCursorsLocked) { int position2 = value - (pixelPosHandleHoriz1 - pixelPosHandleHoriz2); pixelPosHandleHoriz2 = position2; d_vBar2->setPixelPosition(position2); @@ -885,7 +812,7 @@ void DisplayPlot::onHorizCursorHandle1Changed(int value) void DisplayPlot::onHorizCursorHandle2Changed(int value) { - if (horizCursorsLocked) { + if(horizCursorsLocked) { int position1 = value + (pixelPosHandleHoriz1 - pixelPosHandleHoriz2); pixelPosHandleHoriz1 = position1; d_vBar1->setPixelPosition(position1); @@ -894,35 +821,17 @@ void DisplayPlot::onHorizCursorHandle2Changed(int value) d_vBar2->setPixelPosition(value); } -VertBar* DisplayPlot::vBar1() -{ - return d_vBar1; -} +VertBar *DisplayPlot::vBar1() { return d_vBar1; } -VertBar* DisplayPlot::vBar2() -{ - return d_vBar2; -} +VertBar *DisplayPlot::vBar2() { return d_vBar2; } -HorizHandlesArea* DisplayPlot::bottomHandlesArea() -{ - return d_bottomHandlesArea; -} +HorizHandlesArea *DisplayPlot::bottomHandlesArea() { return d_bottomHandlesArea; } -QWidget * DisplayPlot::rightHandlesArea() -{ - return d_rightHandlesArea; -} +QWidget *DisplayPlot::rightHandlesArea() { return d_rightHandlesArea; } -QWidget * DisplayPlot::leftHandlesArea() -{ - return d_leftHandlesArea; -} +QWidget *DisplayPlot::leftHandlesArea() { return d_leftHandlesArea; } -QWidget * DisplayPlot::topHandlesArea() -{ - return d_topHandlesArea; -} +QWidget *DisplayPlot::topHandlesArea() { return d_topHandlesArea; } QString DisplayPlot::formatXValue(double value, int precision) const { @@ -934,15 +843,9 @@ QString DisplayPlot::formatYValue(double value, int precision) const return d_formatter->format(value, d_yAxisUnit, precision); } -void DisplayPlot::onHbar1PixelPosChanged(int pos) -{ - d_vCursorHandle1->setPositionSilenty(pos); -} +void DisplayPlot::onHbar1PixelPosChanged(int pos) { d_vCursorHandle1->setPositionSilenty(pos); } -void DisplayPlot::onHbar2PixelPosChanged(int pos) -{ - d_vCursorHandle2->setPositionSilenty(pos); -} +void DisplayPlot::onHbar2PixelPosChanged(int pos) { d_vCursorHandle2->setPositionSilenty(pos); } void DisplayPlot::onVbar1PixelPosChanged(int pos) { @@ -956,10 +859,7 @@ void DisplayPlot::onVbar2PixelPosChanged(int pos) displayIntersection(); } -struct cursorReadoutsText DisplayPlot::allCursorReadouts() const -{ - return d_cursorReadoutsText; -} +struct cursorReadoutsText DisplayPlot::allCursorReadouts() const { return d_cursorReadoutsText; } void DisplayPlot::onVCursor1Moved(double value) { @@ -993,7 +893,6 @@ void DisplayPlot::onVCursor2Moved(double value) Q_EMIT cursorReadoutsChanged(d_cursorReadoutsText); } - void DisplayPlot::onHCursor1Moved(double value) { QString text; @@ -1006,7 +905,7 @@ void DisplayPlot::onHCursor1Moved(double value) double valueCursor2 = d_hBar2->plotCoord().x(); - double diff = value - (valueCursor2 * d_displayScale) ; + double diff = value - (valueCursor2 * d_displayScale); text = d_formatter->format(diff, "", 3); d_cursorReadouts->setVoltageDeltaText(error ? "-" : text); d_cursorReadoutsText.vDelta = error ? "-" : text; @@ -1036,26 +935,24 @@ void DisplayPlot::onHCursor2Moved(double value) void DisplayPlot::setVertCursorsEnabled(bool en) { - if (d_vertCursorsEnabled != en) { + if(d_vertCursorsEnabled != en) { d_vertCursorsEnabled = en; d_vBar1->setVisible(en); d_vBar2->setVisible(en); d_hCursorHandle1->setVisible(en); d_hCursorHandle2->setVisible(en); - d_cursorReadouts->setTimeReadoutVisible(en && - d_cursorReadoutsVisible); + d_cursorReadouts->setTimeReadoutVisible(en && d_cursorReadoutsVisible); } } void DisplayPlot::toggleCursors(bool en) { - if (d_cursorsEnabled != en) { + if(d_cursorsEnabled != en) { d_cursorsEnabled = en; d_vBar1->setVisible(en); d_vBar2->setVisible(en); - if(d_vertCursorsHandleEnabled) - { + if(d_vertCursorsHandleEnabled) { d_hCursorHandle1->setVisible(en); d_hCursorHandle2->setVisible(en); } @@ -1063,7 +960,7 @@ void DisplayPlot::toggleCursors(bool en) d_cursorReadouts->setTimeReadoutVisible(en); d_cursorReadouts->setVoltageReadoutVisible(en); - if (en) { + if(en) { onVCursor1Moved(d_vBar1->plotCoord().x()); onVCursor2Moved(d_vBar2->plotCoord().x()); } else { @@ -1074,79 +971,46 @@ void DisplayPlot::toggleCursors(bool en) } } -bool DisplayPlot::isLogaritmicPlot() const -{ - return d_isLogaritmicPlot; -} +bool DisplayPlot::isLogaritmicPlot() const { return d_isLogaritmicPlot; } -void DisplayPlot::setPlotLogaritmic(bool value) -{ - d_isLogaritmicPlot = value; -} +void DisplayPlot::setPlotLogaritmic(bool value) { d_isLogaritmicPlot = value; } -bool DisplayPlot::isLogaritmicYPlot() const -{ - return d_isLogaritmicYPlot; -} +bool DisplayPlot::isLogaritmicYPlot() const { return d_isLogaritmicYPlot; } -void DisplayPlot::setPlotYLogaritmic(bool value) -{ - d_isLogaritmicYPlot = value; -} +void DisplayPlot::setPlotYLogaritmic(bool value) { d_isLogaritmicYPlot = value; } -void DisplayPlot::setVertCursorsHandleEnabled(bool en) -{ - d_vertCursorsHandleEnabled = en; -} +void DisplayPlot::setVertCursorsHandleEnabled(bool en) { d_vertCursorsHandleEnabled = en; } -bool DisplayPlot::vertCursorsEnabled() -{ - return d_vertCursorsEnabled; -} +bool DisplayPlot::vertCursorsEnabled() { return d_vertCursorsEnabled; } void DisplayPlot::setHorizCursorsEnabled(bool en) { - if (d_horizCursorsEnabled != en) { + if(d_horizCursorsEnabled != en) { d_horizCursorsEnabled = en; d_hBar1->setVisible(en); d_hBar2->setVisible(en); d_vCursorHandle1->setVisible(en); d_vCursorHandle2->setVisible(en); - d_cursorReadouts->setVoltageReadoutVisible(en && - d_cursorReadoutsVisible); + d_cursorReadouts->setVoltageReadoutVisible(en && d_cursorReadoutsVisible); } } -bool DisplayPlot::horizCursorsEnabled() -{ - return d_horizCursorsEnabled; -} +bool DisplayPlot::horizCursorsEnabled() { return d_horizCursorsEnabled; } void DisplayPlot::setCursorReadoutsVisible(bool en) { - if (d_cursorReadoutsVisible != en) { + if(d_cursorReadoutsVisible != en) { d_cursorReadoutsVisible = en; - d_cursorReadouts->setVoltageReadoutVisible(en && - d_vertCursorsEnabled ); - d_cursorReadouts->setTimeReadoutVisible(en && - d_horizCursorsEnabled ); + d_cursorReadouts->setVoltageReadoutVisible(en && d_vertCursorsEnabled); + d_cursorReadouts->setTimeReadoutVisible(en && d_horizCursorsEnabled); } } -void DisplayPlot::setHorizCursorsLocked(bool value) -{ - horizCursorsLocked = value; -} +void DisplayPlot::setHorizCursorsLocked(bool value) { horizCursorsLocked = value; } -void DisplayPlot::setVertCursorsLocked(bool value) -{ - vertCursorsLocked = value; -} +void DisplayPlot::setVertCursorsLocked(bool value) { vertCursorsLocked = value; } -void DisplayPlot::setCursorReadoutsTransparency(int value) -{ - d_cursorReadouts->setTransparency(value); -} +void DisplayPlot::setCursorReadoutsTransparency(int value) { d_cursorReadouts->setTransparency(value); } void DisplayPlot::moveCursorReadouts(CustomPlotPositionButton::ReadoutsPosition position) { @@ -1156,13 +1020,13 @@ void DisplayPlot::moveCursorReadouts(CustomPlotPositionButton::ReadoutsPosition void DisplayPlot::trackModeEnabled(bool enabled) { d_trackMode = !enabled; - if (d_horizCursorsEnabled) { + if(d_horizCursorsEnabled) { d_hBar1->setVisible(enabled); d_hBar2->setVisible(enabled); d_vCursorHandle1->setVisible(enabled); d_vCursorHandle2->setVisible(enabled); } - if (d_trackMode) { + if(d_trackMode) { onVCursor1Moved(d_vBar1->plotCoord().x()); onVCursor2Moved(d_vBar2->plotCoord().x()); displayIntersection(); @@ -1177,7 +1041,7 @@ void DisplayPlot::trackModeEnabled(bool enabled) void DisplayPlot::displayIntersection() { - if (!d_trackMode) { + if(!d_trackMode) { return; } @@ -1185,26 +1049,22 @@ void DisplayPlot::displayIntersection() bool attachmk1 = true; bool attachmk2 = true; - intersectionCursor1 = getHorizontalCursorIntersection(d_vBar1->plotCoord().x()); intersectionCursor2 = getHorizontalCursorIntersection(d_vBar2->plotCoord().x()); - if (intersectionCursor1 == -1000000){ + if(intersectionCursor1 == -1000000) { attachmk1 = false; } - if (intersectionCursor2 == -1000000) { + if(intersectionCursor2 == -1000000) { attachmk2 = false; } bool value = isAxisValid(QwtAxisId(QwtAxis::YLeft, d_selected_channel)); - if(value) - { + if(value) { markerIntersection1->setAxes(QwtAxis::XBottom, QwtAxisId(QwtAxis::YLeft, d_selected_channel)); markerIntersection2->setAxes(QwtAxis::XBottom, QwtAxisId(QwtAxis::YLeft, d_selected_channel)); - } - else - { + } else { markerIntersection1->setAxes(QwtAxis::XBottom, QwtAxisId(QwtAxis::YLeft, 0)); markerIntersection2->setAxes(QwtAxis::XBottom, QwtAxisId(QwtAxis::YLeft, 0)); } @@ -1212,12 +1072,12 @@ void DisplayPlot::displayIntersection() markerIntersection1->setValue(d_vBar1->plotCoord().x(), intersectionCursor1); markerIntersection2->setValue(d_vBar2->plotCoord().x(), intersectionCursor2); - if (attachmk1) { + if(attachmk1) { markerIntersection1->attach(this); } else { markerIntersection1->detach(); } - if (attachmk2) { + if(attachmk2) { markerIntersection2->attach(this); } else { markerIntersection2->detach(); @@ -1230,7 +1090,7 @@ double DisplayPlot::getHorizontalCursorIntersection(double time) { int n = Curve(d_selected_channel)->data()->size(); - if (n == 0) { + if(n == 0) { return -1; } else { double leftTime, rightTime, leftCustom, rightCustom; @@ -1240,33 +1100,33 @@ double DisplayPlot::getHorizontalCursorIntersection(double time) int left = 0; int right = n - 1; - if (Curve(d_selected_channel)->data()->sample(right).x() < time || - Curve(d_selected_channel)->data()->sample(left).x() > time) { + if(Curve(d_selected_channel)->data()->sample(right).x() < time || + Curve(d_selected_channel)->data()->sample(left).x() > time) { return -1; } - while (left <= right) { + while(left <= right) { int mid = (left + right) / 2; double xData = Curve(d_selected_channel)->data()->sample(mid).x(); - if (xData == time) { - if (mid > 0) { + if(xData == time) { + if(mid > 0) { leftIndex = mid - 1; rightIndex = mid; } break; - } else if (xData < time) { + } else if(xData < time) { left = mid + 1; } else { right = mid - 1; } } - if ((leftIndex == -1 || rightIndex == -1) && left > 0) { + if((leftIndex == -1 || rightIndex == -1) && left > 0) { leftIndex = left - 1; rightIndex = left; } - if (leftIndex == -1 || rightIndex == -1) { + if(leftIndex == -1 || rightIndex == -1) { return -1; } @@ -1276,8 +1136,7 @@ double DisplayPlot::getHorizontalCursorIntersection(double time) leftCustom = Curve(d_selected_channel)->data()->sample(leftIndex).y(); rightCustom = Curve(d_selected_channel)->data()->sample(rightIndex).y(); - double value = (rightCustom - leftCustom) / (rightTime - leftTime) * - (time - leftTime) + leftCustom; + double value = (rightCustom - leftCustom) / (rightTime - leftTime) * (time - leftTime) + leftCustom; return value; } @@ -1290,112 +1149,98 @@ void DisplayPlot::repositionCursors() displayIntersection(); } -void -DisplayPlot::disableLegend() +void DisplayPlot::disableLegend() { - // Haven't found a good way to toggle it on/off - insertLegend(NULL); + // Haven't found a good way to toggle it on/off + insertLegend(NULL); } -void -DisplayPlot::setAllYAxis(double min, double max) +void DisplayPlot::setAllYAxis(double min, double max) { - for (unsigned int i = 0; i < vertAxes.size(); ++i) { + for(unsigned int i = 0; i < vertAxes.size(); ++i) { setAxisScale(QwtAxisId(m_qwtYAxis, i), min, max); } - if (!d_autoscale_state) { - for (int i = 0; i < d_zoomer.size(); ++i) + if(!d_autoscale_state) { + for(int i = 0; i < d_zoomer.size(); ++i) d_zoomer[i]->setZoomBase(); } } -void -DisplayPlot::setYaxis(double min, double max) +void DisplayPlot::setYaxis(double min, double max) { - setAxisScale(m_qwtYAxis, min, max); - if(!d_autoscale_state) { - for (unsigned int i = 0; i < d_zoomer.size(); ++i) - d_zoomer[i]->setZoomBase(); - } + setAxisScale(m_qwtYAxis, min, max); + if(!d_autoscale_state) { + for(unsigned int i = 0; i < d_zoomer.size(); ++i) + d_zoomer[i]->setZoomBase(); + } } -void -DisplayPlot::setXaxis(double min, double max) +void DisplayPlot::setXaxis(double min, double max) { - setAxisScale(QwtAxis::XBottom, min, max); - for (unsigned int i = 0; i < d_zoomer.size(); ++i) - d_zoomer[i]->setZoomBase(); + setAxisScale(QwtAxis::XBottom, min, max); + for(unsigned int i = 0; i < d_zoomer.size(); ++i) + d_zoomer[i]->setZoomBase(); } -void -DisplayPlot::setLineLabel(int which, QString label) -{ - d_plot_curve[which]->setTitle(label); -} +void DisplayPlot::setLineLabel(int which, QString label) { d_plot_curve[which]->setTitle(label); } -QString -DisplayPlot::getLineLabel(int which) -{ - return d_plot_curve[which]->title().text(); -} +QString DisplayPlot::getLineLabel(int which) { return d_plot_curve[which]->title().text(); } void DisplayPlot::setLineColor(int chnIdx, int colorIdx) { - if (colorIdx >= d_CurveColors.size()) { - colorIdx = d_CurveColors.size() - 1; - } else if (colorIdx < 0) { - colorIdx = 0; - } - setLineColor(chnIdx, d_CurveColors.at(colorIdx)); + if(colorIdx >= d_CurveColors.size()) { + colorIdx = d_CurveColors.size() - 1; + } else if(colorIdx < 0) { + colorIdx = 0; + } + setLineColor(chnIdx, d_CurveColors.at(colorIdx)); } -void -DisplayPlot::setLineColor(int which, QColor color) +void DisplayPlot::setLineColor(int which, QColor color) { - if (which < d_plot_curve.size()) { - // Set the color of the pen - QPen pen(d_plot_curve[which]->pen()); - pen.setColor(color); - d_plot_curve[which]->setPen(pen); - // And set the color of the markers + if(which < d_plot_curve.size()) { + // Set the color of the pen + QPen pen(d_plot_curve[which]->pen()); + pen.setColor(color); + d_plot_curve[which]->setPen(pen); + // And set the color of the markers #if QWT_VERSION < 0x060000 - //d_plot_curve[which]->setBrush(QBrush(QColor(color))); - d_plot_curve[which]->setPen(pen); - QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); - setLineMarker(which, sym.style()); + // d_plot_curve[which]->setBrush(QBrush(QColor(color))); + d_plot_curve[which]->setPen(pen); + QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); + setLineMarker(which, sym.style()); #else - QwtSymbol *sym = (QwtSymbol*)d_plot_curve[which]->symbol(); - if(sym) { - sym->setColor(color); - sym->setPen(pen); - d_plot_curve[which]->setSymbol(sym); - } + QwtSymbol *sym = (QwtSymbol *)d_plot_curve[which]->symbol(); + if(sym) { + sym->setColor(color); + sym->setPen(pen); + d_plot_curve[which]->setSymbol(sym); + } #endif - } + } } -QColor -DisplayPlot::getLineColor(int which) const +QColor DisplayPlot::getLineColor(int which) const { - // If that plot doesn't exist then return black. - if (which < d_plot_curve.size()) - return d_plot_curve[which]->pen().color(); - return QColor("black"); + // If that plot doesn't exist then return black. + if(which < d_plot_curve.size()) + return d_plot_curve[which]->pen().color(); + return QColor("black"); } // Use a preprocessor macro to create a bunch of hooks for Q_PROPERTY and hence the stylesheet. -#define SETUPLINE(i, im1) \ - void DisplayPlot::setLineColor ## i (QColor c) {setLineColor(im1, c);} \ - const QColor DisplayPlot::getLineColor ## i () const {return getLineColor(im1);} \ - void DisplayPlot::setLineWidth ## i (int width) {setLineWidth(im1, width);} \ - int DisplayPlot::getLineWidth ## i () const {return getLineWidth(im1);} \ - void DisplayPlot::setLineStyle ## i (Qt::PenStyle ps) {setLineStyle(im1, ps);} \ - const Qt::PenStyle DisplayPlot::getLineStyle ## i () const {return getLineStyle(im1);} \ - void DisplayPlot::setLineMarker ## i (QwtSymbol::Style ms) {setLineMarker(im1, ms);} \ - const QwtSymbol::Style DisplayPlot::getLineMarker ## i () const {return getLineMarker(im1);} \ - void DisplayPlot::setMarkerAlpha ## i (int alpha) {setMarkerAlpha(im1, alpha);} \ - int DisplayPlot::getMarkerAlpha ## i () const {return getMarkerAlpha(im1);} +#define SETUPLINE(i, im1) \ + void DisplayPlot::setLineColor##i(QColor c) { setLineColor(im1, c); } \ + const QColor DisplayPlot::getLineColor##i() const { return getLineColor(im1); } \ + void DisplayPlot::setLineWidth##i(int width) { setLineWidth(im1, width); } \ + int DisplayPlot::getLineWidth##i() const { return getLineWidth(im1); } \ + void DisplayPlot::setLineStyle##i(Qt::PenStyle ps) { setLineStyle(im1, ps); } \ + const Qt::PenStyle DisplayPlot::getLineStyle##i() const { return getLineStyle(im1); } \ + void DisplayPlot::setLineMarker##i(QwtSymbol::Style ms) { setLineMarker(im1, ms); } \ + const QwtSymbol::Style DisplayPlot::getLineMarker##i() const { return getLineMarker(im1); } \ + void DisplayPlot::setMarkerAlpha##i(int alpha) { setMarkerAlpha(im1, alpha); } \ + int DisplayPlot::getMarkerAlpha##i() const { return getMarkerAlpha(im1); } SETUPLINE(1, 0) SETUPLINE(2, 1) SETUPLINE(3, 2) @@ -1406,293 +1251,263 @@ SETUPLINE(7, 6) SETUPLINE(8, 7) SETUPLINE(9, 8) -void -DisplayPlot::setZoomerColor(QColor c) { - for (unsigned int i = 0; i < d_zoomer.size(); ++i) { - d_zoomer[i]->setRubberBandPen(c); - d_zoomer[i]->setTrackerPen(c); - } +void DisplayPlot::setZoomerColor(QColor c) +{ + for(unsigned int i = 0; i < d_zoomer.size(); ++i) { + d_zoomer[i]->setRubberBandPen(c); + d_zoomer[i]->setTrackerPen(c); + } } -QColor -DisplayPlot::getZoomerColor() const { - return d_zoomer[0]->rubberBandPen().color(); -} +QColor DisplayPlot::getZoomerColor() const { return d_zoomer[0]->rubberBandPen().color(); } -void -DisplayPlot::setPaletteColor(QColor c) { - QPalette palette; - palette.setColor(canvas()->backgroundRole(), c); - canvas()->setPalette(palette); +void DisplayPlot::setPaletteColor(QColor c) +{ + QPalette palette; + palette.setColor(canvas()->backgroundRole(), c); + canvas()->setPalette(palette); } -QColor -DisplayPlot::getPaletteColor() const { - return canvas()->palette().color(canvas()->backgroundRole()); -} +QColor DisplayPlot::getPaletteColor() const { return canvas()->palette().color(canvas()->backgroundRole()); } -void -DisplayPlot::setAxisLabelFontSize(int axisId, int fs) { - QwtText axis_title = QwtText(axisWidget(axisId)->title()); - QFont font = QFont(axis_title.font()); - font.setPointSize(fs); - axis_title.setFont(font); - axisWidget(axisId)->setTitle(axis_title); +void DisplayPlot::setAxisLabelFontSize(int axisId, int fs) +{ + QwtText axis_title = QwtText(axisWidget(axisId)->title()); + QFont font = QFont(axis_title.font()); + font.setPointSize(fs); + axis_title.setFont(font); + axisWidget(axisId)->setTitle(axis_title); } -int -DisplayPlot::getAxisLabelFontSize(int axisId) const { - return axisWidget(axisId)->title().font().pointSize(); -} +int DisplayPlot::getAxisLabelFontSize(int axisId) const { return axisWidget(axisId)->title().font().pointSize(); } -void -DisplayPlot::setYaxisLabelFontSize(int fs) { - if (m_qwtYAxis == QwtAxis::YLeft) { +void DisplayPlot::setYaxisLabelFontSize(int fs) +{ + if(m_qwtYAxis == QwtAxis::YLeft) { setAxisLabelFontSize(QwtAxis::YLeft, fs); } else { setAxisLabelFontSize(QwtAxis::YRight, fs); } } -void -DisplayPlot::printWithNoBackground(const QString& toolName, bool editScaleDraw) +void DisplayPlot::printWithNoBackground(const QString &toolName, bool editScaleDraw) { - OscScaleDraw *scaleDraw = static_cast(this->axisScaleDraw(QwtAxisId(m_qwtYAxis, d_activeVertAxis))); - QStack colors; - for (int i = 0; i < d_plot_curve.size(); ++i) { - colors.push_back(getLineColor(i)); - setLineColor(i, d_printColors[i]); - } + OscScaleDraw *scaleDraw = + static_cast(this->axisScaleDraw(QwtAxisId(m_qwtYAxis, d_activeVertAxis))); + QStack colors; + for(int i = 0; i < d_plot_curve.size(); ++i) { + colors.push_back(getLineColor(i)); + setLineColor(i, d_printColors[i]); + } - if (editScaleDraw) { - scaleDraw->setColor(getLineColor(d_activeVertAxis)); - scaleDraw->invalidateCache(); - } + if(editScaleDraw) { + scaleDraw->setColor(getLineColor(d_activeVertAxis)); + scaleDraw->invalidateCache(); + } - PrintablePlot::printPlot(toolName); + PrintablePlot::printPlot(toolName); - for (int i = d_plot_curve.size() - 1; i >= 0; --i) { - setLineColor(i, colors.pop()); - } - if (editScaleDraw) { - scaleDraw->setColor(getLineColor(d_activeVertAxis)); - scaleDraw->invalidateCache(); - } + for(int i = d_plot_curve.size() - 1; i >= 0; --i) { + setLineColor(i, colors.pop()); + } + if(editScaleDraw) { + scaleDraw->setColor(getLineColor(d_activeVertAxis)); + scaleDraw->invalidateCache(); + } } -int -DisplayPlot::getYaxisLabelFontSize() const { - int fs = getAxisLabelFontSize(m_qwtYAxis); - return fs; +int DisplayPlot::getYaxisLabelFontSize() const +{ + int fs = getAxisLabelFontSize(m_qwtYAxis); + return fs; } -void -DisplayPlot::setXaxisLabelFontSize(int fs) { - setAxisLabelFontSize(QwtAxis::XBottom, fs); -} +void DisplayPlot::setXaxisLabelFontSize(int fs) { setAxisLabelFontSize(QwtAxis::XBottom, fs); } -int -DisplayPlot::getXaxisLabelFontSize() const { - int fs = getAxisLabelFontSize(QwtAxis::XBottom); - return fs; +int DisplayPlot::getXaxisLabelFontSize() const +{ + int fs = getAxisLabelFontSize(QwtAxis::XBottom); + return fs; } -void -DisplayPlot::setAxesLabelFontSize(int fs) { - setAxisLabelFontSize(m_qwtYAxis, fs); - setAxisLabelFontSize(QwtAxis::XBottom, fs); +void DisplayPlot::setAxesLabelFontSize(int fs) +{ + setAxisLabelFontSize(m_qwtYAxis, fs); + setAxisLabelFontSize(QwtAxis::XBottom, fs); } -int -DisplayPlot::getAxesLabelFontSize() const { - // Returns 0 if all axes do not have the same font size. - int fs = getAxisLabelFontSize(m_qwtYAxis); - if (getAxisLabelFontSize(QwtAxis::XBottom) != fs) - return 0; - return fs; +int DisplayPlot::getAxesLabelFontSize() const +{ + // Returns 0 if all axes do not have the same font size. + int fs = getAxisLabelFontSize(m_qwtYAxis); + if(getAxisLabelFontSize(QwtAxis::XBottom) != fs) + return 0; + return fs; } -void -DisplayPlot::setLineWidth(int which, qreal width) +void DisplayPlot::setLineWidth(int which, qreal width) { - if(which < d_nplots) { - // Set the new line width - QPen pen(d_plot_curve[which]->pen()); - pen.setWidthF(width); - d_plot_curve[which]->setPen(pen); + if(which < d_nplots) { + // Set the new line width + QPen pen(d_plot_curve[which]->pen()); + pen.setWidthF(width); + d_plot_curve[which]->setPen(pen); - // Scale the marker size proportionally + // Scale the marker size proportionally #if QWT_VERSION < 0x060000 - QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); - sym.setSize(7+10*log10(1.0*width), 7+10*log10(1.0*width)); - d_plot_curve[which]->setSymbol(sym); + QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); + sym.setSize(7 + 10 * log10(1.0 * width), 7 + 10 * log10(1.0 * width)); + d_plot_curve[which]->setSymbol(sym); #else - QwtSymbol *sym = (QwtSymbol*)d_plot_curve[which]->symbol(); - if(sym) { - sym->setSize(7+10*log10(1.0*width), 7+10*log10(1.0*width)); - d_plot_curve[which]->setSymbol(sym); - } + QwtSymbol *sym = (QwtSymbol *)d_plot_curve[which]->symbol(); + if(sym) { + sym->setSize(7 + 10 * log10(1.0 * width), 7 + 10 * log10(1.0 * width)); + d_plot_curve[which]->setSymbol(sym); + } #endif - } + } } -int -DisplayPlot::getLineWidth(int which) const { - if (which < d_nplots) { - return d_plot_curve[which]->pen().width(); - } - else { - return 0; - } +int DisplayPlot::getLineWidth(int which) const +{ + if(which < d_nplots) { + return d_plot_curve[which]->pen().width(); + } else { + return 0; + } } -void -DisplayPlot::setLineStyle(int which, Qt::PenStyle style) +void DisplayPlot::setLineStyle(int which, Qt::PenStyle style) { - if(which < d_nplots) { - QPen pen(d_plot_curve[which]->pen()); - pen.setStyle(style); - d_plot_curve[which]->setPen(pen); - } + if(which < d_nplots) { + QPen pen(d_plot_curve[which]->pen()); + pen.setStyle(style); + d_plot_curve[which]->setPen(pen); + } } -const Qt::PenStyle -DisplayPlot::getLineStyle(int which) const +const Qt::PenStyle DisplayPlot::getLineStyle(int which) const { - if(which < d_nplots) { - return d_plot_curve[which]->pen().style(); - } - else { - return Qt::SolidLine; - } + if(which < d_nplots) { + return d_plot_curve[which]->pen().style(); + } else { + return Qt::SolidLine; + } } -void -DisplayPlot::setLineMarker(int which, QwtSymbol::Style marker) +void DisplayPlot::setLineMarker(int which, QwtSymbol::Style marker) { - if(which < d_nplots) { + if(which < d_nplots) { #if QWT_VERSION < 0x060000 - QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); - QPen pen(d_plot_curve[which]->pen()); - QBrush brush(pen.color()); - sym.setStyle(marker); - sym.setPen(pen); - sym.setBrush(brush); - d_plot_curve[which]->setSymbol(sym); + QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); + QPen pen(d_plot_curve[which]->pen()); + QBrush brush(pen.color()); + sym.setStyle(marker); + sym.setPen(pen); + sym.setBrush(brush); + d_plot_curve[which]->setSymbol(sym); #else - QwtSymbol *sym = (QwtSymbol*)d_plot_curve[which]->symbol(); - if(sym) { - sym->setStyle(marker); - d_plot_curve[which]->setSymbol(sym); - } + QwtSymbol *sym = (QwtSymbol *)d_plot_curve[which]->symbol(); + if(sym) { + sym->setStyle(marker); + d_plot_curve[which]->setSymbol(sym); + } #endif - } + } } -const QwtSymbol::Style -DisplayPlot::getLineMarker(int which) const +const QwtSymbol::Style DisplayPlot::getLineMarker(int which) const { - if(which < d_nplots) { + if(which < d_nplots) { #if QWT_VERSION < 0x060000 - QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); - return sym.style(); + QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); + return sym.style(); #else - QwtSymbol *sym = (QwtSymbol*)d_plot_curve[which]->symbol(); - return sym->style(); + QwtSymbol *sym = (QwtSymbol *)d_plot_curve[which]->symbol(); + return sym->style(); #endif - } - else { - return QwtSymbol::NoSymbol; - } + } else { + return QwtSymbol::NoSymbol; + } } -void -DisplayPlot::setMarkerAlpha(int which, int alpha) +void DisplayPlot::setMarkerAlpha(int which, int alpha) { - if (which < d_nplots) { - // Get the pen color - QPen pen(d_plot_curve[which]->pen()); - QColor color = pen.color(); + if(which < d_nplots) { + // Get the pen color + QPen pen(d_plot_curve[which]->pen()); + QColor color = pen.color(); - // Set new alpha and update pen - color.setAlpha(alpha); - pen.setColor(color); - d_plot_curve[which]->setPen(pen); + // Set new alpha and update pen + color.setAlpha(alpha); + pen.setColor(color); + d_plot_curve[which]->setPen(pen); - // And set the new color for the markers + // And set the new color for the markers #if QWT_VERSION < 0x060000 - QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); - setLineMarker(which, sym.style()); + QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); + setLineMarker(which, sym.style()); #else - QwtSymbol *sym = (QwtSymbol*)d_plot_curve[which]->symbol(); - if(sym) { - sym->setColor(color); - sym->setPen(pen); - d_plot_curve[which]->setSymbol(sym); - } + QwtSymbol *sym = (QwtSymbol *)d_plot_curve[which]->symbol(); + if(sym) { + sym->setColor(color); + sym->setPen(pen); + d_plot_curve[which]->setSymbol(sym); + } #endif - } + } } -int -DisplayPlot::getMarkerAlpha(int which) const +int DisplayPlot::getMarkerAlpha(int which) const { - if(which < d_nplots) { - return d_plot_curve[which]->pen().color().alpha(); - } - else { - return 0; - } + if(which < d_nplots) { + return d_plot_curve[which]->pen().color().alpha(); + } else { + return 0; + } } -void -DisplayPlot::setStop(bool on) -{ - d_stop = on; -} +void DisplayPlot::setStop(bool on) { d_stop = on; } -void -DisplayPlot::resizeSlot( QSize *s ) +void DisplayPlot::resizeSlot(QSize *s) { - // -10 is to spare some room for the legend and x-axis label - resize(s->width()-10, s->height()-10); + // -10 is to spare some room for the legend and x-axis label + resize(s->width() - 10, s->height() - 10); } -void DisplayPlot::legendEntryChecked(QwtPlotItem* plotItem, bool on) +void DisplayPlot::legendEntryChecked(QwtPlotItem *plotItem, bool on) { - plotItem->setVisible(!on); - replot(); + plotItem->setVisible(!on); + replot(); } void DisplayPlot::legendEntryChecked(const QVariant &plotItem, bool on, int index) { #if QWT_VERSION < 0x060100 - std::runtime_error("DisplayPlot::legendEntryChecked with QVariant not enabled in this version of QWT.\n"); + std::runtime_error("DisplayPlot::legendEntryChecked with QVariant not enabled in this version of QWT.\n"); #else - QwtPlotItem *p = infoToItem(plotItem); - legendEntryChecked(p, on); + QwtPlotItem *p = infoToItem(plotItem); + legendEntryChecked(p, on); #endif /* QWT_VERSION < 0x060100 */ } -void -DisplayPlot::onPickerPointSelected(const QPointF & p) +void DisplayPlot::onPickerPointSelected(const QPointF &p) { - QPointF point = p; - //fprintf(stderr,"onPickerPointSelected %f %f\n", point.x(), point.y()); - Q_EMIT plotPointSelected(point); + QPointF point = p; + // fprintf(stderr,"onPickerPointSelected %f %f\n", point.x(), point.y()); + Q_EMIT plotPointSelected(point); } -void -DisplayPlot::onPickerPointSelected6(const QPointF & p) +void DisplayPlot::onPickerPointSelected6(const QPointF &p) { - QPointF point = p; - //fprintf(stderr,"onPickerPointSelected %f %f\n", point.x(), point.y()); - Q_EMIT plotPointSelected(point); + QPointF point = p; + // fprintf(stderr,"onPickerPointSelected %f %f\n", point.x(), point.y()); + Q_EMIT plotPointSelected(point); } void DisplayPlot::zoomBaseUpdate(bool force) { - for (unsigned int i = 0; i < d_zoomer.size(); ++i) + for(unsigned int i = 0; i < d_zoomer.size(); ++i) d_zoomer[i]->setZoomBase(force); } @@ -1702,7 +1517,7 @@ void DisplayPlot::AddAxisOffset(int axisPos, int axisIdx, double offset) double max = 1; double ptsPerDiv = 1; - switch (axisPos) { + switch(axisPos) { case QwtAxis::YRight: ptsPerDiv = vertAxes[axisIdx]->ptsPerDiv(); min = d_yAxisMin * ptsPerDiv; @@ -1722,8 +1537,7 @@ void DisplayPlot::AddAxisOffset(int axisPos, int axisIdx, double offset) QwtAxisId axisId(axisPos, axisIdx); - setAxisScale(axisId, min + offset, max + offset, - axisStepSize(axisId)); + setAxisScale(axisId, min + offset, max + offset, axisStepSize(axisId)); } void DisplayPlot::setVertOffset(double offset, int axisIdx) @@ -1734,7 +1548,7 @@ void DisplayPlot::setVertOffset(double offset, int axisIdx) double DisplayPlot::VertOffset(int axisIdx) { - if ((axisIdx >= 0) && (axisIdx < vertAxes.size())) + if((axisIdx >= 0) && (axisIdx < vertAxes.size())) return vertAxes[axisIdx]->offset(); return 0; } @@ -1745,10 +1559,7 @@ void DisplayPlot::setHorizOffset(double offset) horizAxis->setOffset(offset); } -double DisplayPlot::HorizOffset() -{ - return horizAxis->offset(); -} +double DisplayPlot::HorizOffset() { return horizAxis->offset(); } void DisplayPlot::setVertUnitsPerDiv(double upd, int axisIdx) { @@ -1756,7 +1567,7 @@ void DisplayPlot::setVertUnitsPerDiv(double upd, int axisIdx) double ptsPerDiv = vertAxes[axisIdx]->ptsPerDiv(); double offset = vertAxes[axisIdx]->offset(); - if (ptsPerDiv != upd) { + if(ptsPerDiv != upd) { vertAxes[axisIdx]->setPtsPerDiv(upd); min = (d_yAxisMin * upd) + offset; max = (d_yAxisMax * upd) + offset; @@ -1765,10 +1576,7 @@ void DisplayPlot::setVertUnitsPerDiv(double upd, int axisIdx) } } -double DisplayPlot::VertUnitsPerDiv(int axisIdx) -{ - return vertAxes[axisIdx]->ptsPerDiv(); -} +double DisplayPlot::VertUnitsPerDiv(int axisIdx) { return vertAxes[axisIdx]->ptsPerDiv(); } void DisplayPlot::setHorizUnitsPerDiv(double upd) { @@ -1776,7 +1584,7 @@ void DisplayPlot::setHorizUnitsPerDiv(double upd) double ptsPerDiv = horizAxis->ptsPerDiv(); double offset = horizAxis->offset(); - if (ptsPerDiv != upd) { + if(ptsPerDiv != upd) { horizAxis->setPtsPerDiv(upd); min = (d_xAxisMin * upd) + offset; max = (d_xAxisMax * upd) + offset; @@ -1785,21 +1593,15 @@ void DisplayPlot::setHorizUnitsPerDiv(double upd) } } -void DisplayPlot::enableColoredLabels(bool colored) -{ - d_coloredLabels = colored; -} +void DisplayPlot::enableColoredLabels(bool colored) { d_coloredLabels = colored; } -void DisplayPlot::enableMouseGesturesOnScales(bool enable) -{ - d_mouseGesturesEnabled = enable; -} +void DisplayPlot::enableMouseGesturesOnScales(bool enable) { d_mouseGesturesEnabled = enable; } void DisplayPlot::setDisplayScale(double value) { d_displayScale = value; OscScaleDraw *osd = nullptr; - osd = static_cast(axisWidget(QwtAxisId(m_qwtYAxis, d_activeVertAxis))->scaleDraw()); + osd = static_cast(axisWidget(QwtAxisId(m_qwtYAxis, d_activeVertAxis))->scaleDraw()); osd->setDisplayScale(d_displayScale); osd->invalidateCache(); axisWidget(QwtAxisId(m_qwtYAxis, d_activeVertAxis))->update(); @@ -1809,20 +1611,20 @@ void DisplayPlot::setActiveVertAxis(unsigned int axisIdx, bool selected) { int numAxes = this->axesCount(m_qwtYAxis); - if (axisIdx >= numAxes) + if(axisIdx >= numAxes) return; d_activeVertAxis = axisIdx; - if (d_usingLeftAxisScales && selected) { - for (int i = 0; i < numAxes; i++) { - this->setAxisVisible(QwtAxisId(m_qwtYAxis, i), - (i == axisIdx)); + if(d_usingLeftAxisScales && selected) { + for(int i = 0; i < numAxes; i++) { + this->setAxisVisible(QwtAxisId(m_qwtYAxis, i), (i == axisIdx)); } } - if (d_coloredLabels && selected) { - OscScaleDraw *scaleDraw = static_cast(this->axisScaleDraw(QwtAxisId(m_qwtYAxis, axisIdx))); + if(d_coloredLabels && selected) { + OscScaleDraw *scaleDraw = + static_cast(this->axisScaleDraw(QwtAxisId(m_qwtYAxis, axisIdx))); scaleDraw->setColor(getLineColor(axisIdx)); scaleDraw->invalidateCache(); } @@ -1861,26 +1663,20 @@ void DisplayPlot::adjustHandleAreasSize(bool cursors) d_bottomHandlesArea->setLeftPadding(left_width); } -int DisplayPlot::activeVertAxis() -{ - return d_activeVertAxis; -} +int DisplayPlot::activeVertAxis() { return d_activeVertAxis; } -double DisplayPlot::HorizUnitsPerDiv() -{ - return horizAxis->ptsPerDiv(); -} +double DisplayPlot::HorizUnitsPerDiv() { return horizAxis->ptsPerDiv(); } void DisplayPlot::DetachCurve(unsigned int curveIdx) { - if (curveIdx < this->d_plot_curve.size()) { + if(curveIdx < this->d_plot_curve.size()) { this->d_plot_curve[curveIdx]->detach(); } } void DisplayPlot::AttachCurve(unsigned int curveIdx) { - if (curveIdx < this->d_plot_curve.size()) { + if(curveIdx < this->d_plot_curve.size()) { this->d_plot_curve[curveIdx]->attach((QwtPlot *)this); } } @@ -1893,55 +1689,31 @@ void DisplayPlot::bringCurveToFront(unsigned int curveIdx) replot(); } -QwtPlotCurve * DisplayPlot::Curve(unsigned int curveIdx) +QwtPlotCurve *DisplayPlot::Curve(unsigned int curveIdx) { QwtPlotCurve *curve = NULL; - if (curveIdx < this->d_plot_curve.size()) + if(curveIdx < this->d_plot_curve.size()) curve = d_plot_curve[curveIdx]; return curve; } -void DisplayPlot::setMinXaxisDivision(double minDivison) -{ - this->d_hScaleDivisions.setLower(minDivison); -} +void DisplayPlot::setMinXaxisDivision(double minDivison) { this->d_hScaleDivisions.setLower(minDivison); } -double DisplayPlot::minXaxisDivision() -{ - return this->d_hScaleDivisions.lower(); -} +double DisplayPlot::minXaxisDivision() { return this->d_hScaleDivisions.lower(); } -void DisplayPlot::setMaxXaxisDivision(double maxDivison) -{ - this->d_hScaleDivisions.setUpper(maxDivison); -} +void DisplayPlot::setMaxXaxisDivision(double maxDivison) { this->d_hScaleDivisions.setUpper(maxDivison); } -double DisplayPlot::maxXaxisDivision() -{ - return this->d_hScaleDivisions.upper(); -} +double DisplayPlot::maxXaxisDivision() { return this->d_hScaleDivisions.upper(); } -void DisplayPlot::setMinYaxisDivision(double minDivison) -{ - this->d_vScaleDivisions.setLower(minDivison); -} +void DisplayPlot::setMinYaxisDivision(double minDivison) { this->d_vScaleDivisions.setLower(minDivison); } -double DisplayPlot::minYaxisDivision() -{ - return this->d_vScaleDivisions.lower(); -} +double DisplayPlot::minYaxisDivision() { return this->d_vScaleDivisions.lower(); } -void DisplayPlot::setMaxYaxisDivision(double maxDivision) -{ - this->d_vScaleDivisions.setUpper(maxDivision); -} +void DisplayPlot::setMaxYaxisDivision(double maxDivision) { this->d_vScaleDivisions.setUpper(maxDivision); } -double DisplayPlot::maxYaxisDivision() -{ - return this->d_vScaleDivisions.upper(); -} +double DisplayPlot::maxYaxisDivision() { return this->d_vScaleDivisions.upper(); } void DisplayPlot::onHorizAxisOffsetDecrease() { @@ -1951,7 +1723,7 @@ void DisplayPlot::onHorizAxisOffsetDecrease() offset -= scale / xAxisNumDiv(); // a value very close to 0.0 is explicitely set to 0.0 - if ( qwtFuzzyCompare( offset, 0.0, scale / xAxisNumDiv() ) == 0 ) + if(qwtFuzzyCompare(offset, 0.0, scale / xAxisNumDiv()) == 0) offset = 0; this->setHorizOffset(offset); @@ -1967,7 +1739,7 @@ void DisplayPlot::onHorizAxisOffsetIncrease() offset += scale / xAxisNumDiv(); // a value very close to 0.0 is explicitely set to 0.0 - if ( qwtFuzzyCompare( offset, 0.0, scale / xAxisNumDiv() ) == 0 ) + if(qwtFuzzyCompare(offset, 0.0, scale / xAxisNumDiv()) == 0) offset = 0; this->setHorizOffset(offset); @@ -1979,7 +1751,7 @@ void DisplayPlot::onVertAxisOffsetDecrease() { OscAdjuster *osc_adj = dynamic_cast(QObject::sender()); - if (!osc_adj) + if(!osc_adj) return; double offset = this->VertOffset(osc_adj->axisId().id); @@ -1987,7 +1759,7 @@ void DisplayPlot::onVertAxisOffsetDecrease() offset -= scale / yAxisNumDiv(); // a value very close to 0.0 is explicitely set to 0.0 - if ( qwtFuzzyCompare( offset, 0.0, scale / yAxisNumDiv() ) == 0 ) + if(qwtFuzzyCompare(offset, 0.0, scale / yAxisNumDiv()) == 0) offset = 0; this->setVertOffset(offset, osc_adj->axisId().id); @@ -1999,7 +1771,7 @@ void DisplayPlot::onVertAxisOffsetIncrease() { OscAdjuster *osc_adj = dynamic_cast(QObject::sender()); - if (!osc_adj) + if(!osc_adj) return; double offset = this->VertOffset(osc_adj->axisId().id); @@ -2008,7 +1780,7 @@ void DisplayPlot::onVertAxisOffsetIncrease() offset += scale / yAxisNumDiv(); // a value very close to 0.0 is explicitely set to 0.0 - if ( qwtFuzzyCompare( offset, 0.0, scale / yAxisNumDiv() ) == 0 ) + if(qwtFuzzyCompare(offset, 0.0, scale / yAxisNumDiv()) == 0) offset = 0; this->setVertOffset(offset, osc_adj->axisId().id); @@ -2022,7 +1794,7 @@ void DisplayPlot::_onXbottomAxisWidgetScaleDivChanged() QwtScaleWidget *axis_widget = dynamic_cast(QObject::sender()); OscScaleDraw *scale_draw = dynamic_cast(axis_widget->scaleDraw()); - if (scale_draw) { + if(scale_draw) { scale_draw->invalidateCache(); axis_widget->update(); } @@ -2033,7 +1805,7 @@ void DisplayPlot::_onYleftAxisWidgetScaleDivChanged() QwtScaleWidget *axis_widget = dynamic_cast(QObject::sender()); OscScaleDraw *scale_draw = dynamic_cast(axis_widget->scaleDraw()); - if (scale_draw) { + if(scale_draw) { scale_draw->invalidateCache(); axis_widget->update(); } @@ -2042,8 +1814,8 @@ void DisplayPlot::_onYleftAxisWidgetScaleDivChanged() #ifdef __ANDROID__ void DisplayPlot::mousePressEvent(QMouseEvent *event) { - if (event->type() == QEvent::MouseButtonDblClick) { - for (unsigned int i = 0; i < d_zoomer.size(); ++i) { + if(event->type() == QEvent::MouseButtonDblClick) { + for(unsigned int i = 0; i < d_zoomer.size(); ++i) { OscPlotZoomer *zoomer = static_cast(d_zoomer[i]); zoomer->popZoom(); } @@ -2053,7 +1825,7 @@ void DisplayPlot::mousePressEvent(QMouseEvent *event) QwtPlotZoomer *DisplayPlot::getZoomer() const { - if (d_zoomer.isEmpty()) + if(d_zoomer.isEmpty()) return nullptr; return d_zoomer[0]; @@ -2061,11 +1833,11 @@ QwtPlotZoomer *DisplayPlot::getZoomer() const void DisplayPlot::setZoomerParams(bool bounded, int maxStackDepth) { - if (d_zoomer.isEmpty()) { + if(d_zoomer.isEmpty()) { return; } - auto zoomer = dynamic_cast(d_zoomer[0]); + auto zoomer = dynamic_cast(d_zoomer[0]); zoomer->setMaxStackDepth(maxStackDepth); zoomer->setBoundVertical(bounded); } @@ -2075,7 +1847,7 @@ void DisplayPlot::horizAxisScaleIncrease() double div = HorizUnitsPerDiv(); double newDiv = d_hScaleDivisions.getNumberAfter(div); - if (newDiv != div) { + if(newDiv != div) { setHorizUnitsPerDiv(newDiv); replot(); } @@ -2086,7 +1858,7 @@ void DisplayPlot::horizAxisScaleDecrease() double div = HorizUnitsPerDiv(); double newDiv = d_hScaleDivisions.getNumberBefore(div); - if (newDiv != div) { + if(newDiv != div) { setHorizUnitsPerDiv(newDiv); replot(); } @@ -2096,13 +1868,13 @@ void DisplayPlot::vertAxisScaleIncrease() { OscAdjuster *osc_adj = dynamic_cast(QObject::sender()); - if (!osc_adj) + if(!osc_adj) return; double div = VertUnitsPerDiv(osc_adj->axisId().id); double newDiv = d_vScaleDivisions.getNumberAfter(div); - if (newDiv != div) { + if(newDiv != div) { setVertUnitsPerDiv(newDiv, osc_adj->axisId().id); replot(); } @@ -2112,13 +1884,13 @@ void DisplayPlot::vertAxisScaleDecrease() { OscAdjuster *osc_adj = dynamic_cast(QObject::sender()); - if (!osc_adj) + if(!osc_adj) return; double div = VertUnitsPerDiv(osc_adj->axisId().id); double newDiv = d_vScaleDivisions.getNumberBefore(div); - if (newDiv != div) { + if(newDiv != div) { setVertUnitsPerDiv(newDiv, osc_adj->axisId().id); replot(); } @@ -2128,25 +1900,23 @@ void DisplayPlot::removeLeftVertAxis(unsigned int axis) { const unsigned int numAxis = vertAxes.size(); - if (axis >= numAxis) + if(axis >= numAxis) return; setAxesCount(m_qwtYAxis, numAxis - 1); - for (unsigned int i = axis + 1; i < numAxis; i++) + for(unsigned int i = axis + 1; i < numAxis; i++) vertAxes[i]->axis().id = i - 1; delete vertAxes[axis]; vertAxes.erase(vertAxes.begin() + axis, vertAxes.begin() + axis + 1); - for (unsigned int i = axis; i < numAxis - 1; i++) { + for(unsigned int i = axis; i < numAxis - 1; i++) { double ptsPerDiv = vertAxes[i]->ptsPerDiv(); double offset = vertAxes[i]->offset(); - setAxisScale(QwtAxisId(m_qwtYAxis, i), - (d_yAxisMin * ptsPerDiv) + offset, - (d_yAxisMax * ptsPerDiv) + offset, - ptsPerDiv); + setAxisScale(QwtAxisId(m_qwtYAxis, i), (d_yAxisMin * ptsPerDiv) + offset, + (d_yAxisMax * ptsPerDiv) + offset, ptsPerDiv); } } @@ -2156,35 +1926,25 @@ void DisplayPlot::setLeftVertAxesCount(int count) const int numAxis = vertAxes.size(); - for (int i = count; i < numAxis; i++) { + for(int i = count; i < numAxis; i++) { delete vertAxes[i]; } vertAxes.resize(count); - for (int i = numAxis; i < count; i++) { + for(int i = numAxis; i < count; i++) { vertAxes[i] = new PlotAxisConfiguration(m_qwtYAxis, i, this); configureAxis(m_qwtYAxis, i); - this->setAxisVisible(QwtAxisId(m_qwtYAxis, i), - d_usingLeftAxisScales); - connect(axisWidget(vertAxes[i]->axis()), SIGNAL(scaleDivChanged()), - this, SLOT(_onYleftAxisWidgetScaleDivChanged())); + this->setAxisVisible(QwtAxisId(m_qwtYAxis, i), d_usingLeftAxisScales); + connect(axisWidget(vertAxes[i]->axis()), SIGNAL(scaleDivChanged()), this, + SLOT(_onYleftAxisWidgetScaleDivChanged())); } } -int DisplayPlot::leftVertAxesCount() -{ - return vertAxes.size(); -} +int DisplayPlot::leftVertAxesCount() { return vertAxes.size(); } -void DisplayPlot::setUsingLeftAxisScales(bool on) -{ - d_usingLeftAxisScales = on; -} +void DisplayPlot::setUsingLeftAxisScales(bool on) { d_usingLeftAxisScales = on; } -bool DisplayPlot::usingLeftAxisScales() -{ - return d_usingLeftAxisScales; -} +bool DisplayPlot::usingLeftAxisScales() { return d_usingLeftAxisScales; } void DisplayPlot::configureAxis(int axisPos, int axisIdx) { @@ -2206,39 +1966,24 @@ void DisplayPlot::resizeEvent(QResizeEvent *event) Q_EMIT plotSizeChanged(); } -VertBar *DisplayPlot::getVBar1() const -{ - return d_vBar1; -} +VertBar *DisplayPlot::getVBar1() const { return d_vBar1; } -VertBar *DisplayPlot::getVBar2() const -{ - return d_vBar2; -} -HorizBar *DisplayPlot::getHBar1() const -{ - return d_hBar1; -} -HorizBar *DisplayPlot::getHBar2() const -{ - return d_hBar2; -} +VertBar *DisplayPlot::getVBar2() const { return d_vBar2; } +HorizBar *DisplayPlot::getHBar1() const { return d_hBar1; } +HorizBar *DisplayPlot::getHBar2() const { return d_hBar2; } -CursorReadouts *DisplayPlot::getCursorReadouts() const -{ - return d_cursorReadouts; -} +CursorReadouts *DisplayPlot::getCursorReadouts() const { return d_cursorReadouts; } void DisplayPlot::bottomHorizAxisInit() { horizAxis = new PlotAxisConfiguration(QwtAxis::XBottom, 0, this); horizAxis->setMouseGesturesEnabled(d_mouseGesturesEnabled); configureAxis(QwtAxis::XBottom, 0); - connect(axisWidget(horizAxis->axis()), SIGNAL(scaleDivChanged()), - this, SLOT(_onXbottomAxisWidgetScaleDivChanged())); + connect(axisWidget(horizAxis->axis()), SIGNAL(scaleDivChanged()), this, + SLOT(_onXbottomAxisWidgetScaleDivChanged())); } -static QwtScaleDiv getEdgelessScaleDiv(const QwtScaleDiv& from_scaleDiv) +static QwtScaleDiv getEdgelessScaleDiv(const QwtScaleDiv &from_scaleDiv) { double lowerBound; double upperBound; @@ -2251,69 +1996,48 @@ static QwtScaleDiv getEdgelessScaleDiv(const QwtScaleDiv& from_scaleDiv) minorTicks = from_scaleDiv.ticks(QwtScaleDiv::MinorTick); mediumTicks = from_scaleDiv.ticks(QwtScaleDiv::MediumTick); majorTicks = from_scaleDiv.ticks(QwtScaleDiv::MajorTick); - if (majorTicks.size() >= 2) { + if(majorTicks.size() >= 2) { majorTicks.erase(majorTicks.begin()); majorTicks.erase(majorTicks.end() - 1); } return QwtScaleDiv(lowerBound, upperBound, minorTicks, mediumTicks, majorTicks); } -void DisplayPlot::setXaxisMajorTicksPos(QList ticks) -{ - d_majorTicks = ticks; -} +void DisplayPlot::setXaxisMajorTicksPos(QList ticks) { d_majorTicks = ticks; } -QList DisplayPlot::getXaxisMajorTicksPos() const -{ - return d_majorTicks; -} +QList DisplayPlot::getXaxisMajorTicksPos() const { return d_majorTicks; } -void DisplayPlot::setYaxisMajorTicksPos(QList ticks) -{ - d_majorTicksY = ticks; -} +void DisplayPlot::setYaxisMajorTicksPos(QList ticks) { d_majorTicksY = ticks; } -QList DisplayPlot::getYaxisMajorTicksPos() const -{ - return d_majorTicksY; -} +QList DisplayPlot::getYaxisMajorTicksPos() const { return d_majorTicksY; } -unsigned int DisplayPlot::xAxisNumDiv() const -{ - return d_xAxisNumDiv; -} +unsigned int DisplayPlot::xAxisNumDiv() const { return d_xAxisNumDiv; } void DisplayPlot::setXaxisNumDiv(unsigned int num) { - if (d_xAxisNumDiv != num) { + if(d_xAxisNumDiv != num) { d_xAxisNumDiv = num; d_xAxisMin = -(double)num / 2; d_xAxisMax = (double)num / 2; } } -unsigned int DisplayPlot::yAxisNumDiv() const -{ - return d_yAxisNumDiv; -} +unsigned int DisplayPlot::yAxisNumDiv() const { return d_yAxisNumDiv; } void DisplayPlot::setYaxisNumDiv(unsigned int num) { - if (d_yAxisNumDiv != num) { + if(d_yAxisNumDiv != num) { d_yAxisNumDiv = num; d_yAxisMin = -(double)num / 2; d_yAxisMax = (double)num / 2; } } -void DisplayPlot::setXaxisMouseGesturesEnabled(bool en) -{ - horizAxis->setMouseGesturesEnabled(en); -} +void DisplayPlot::setXaxisMouseGesturesEnabled(bool en) { horizAxis->setMouseGesturesEnabled(en); } void DisplayPlot::setYaxisMouseGesturesEnabled(int axisId, bool en) { - if (axisId < vertAxes.size()) { + if(axisId < vertAxes.size()) { vertAxes[axisId]->setMouseGesturesEnabled(en); } } diff --git a/gui/src/FftDisplayPlot.cc b/gui/src/FftDisplayPlot.cc index 9dc7d1e319..6471a41fef 100644 --- a/gui/src/FftDisplayPlot.cc +++ b/gui/src/FftDisplayPlot.cc @@ -19,12 +19,13 @@ */ #include "FftDisplayPlot.h" -#include "spectrumUpdateEvents.h" + #include "average.h" -#include "spectrum_marker.hpp" -#include "marker_controller.h" #include "limitedplotzoomer.h" +#include "marker_controller.h" #include "osc_scale_engine.h" +#include "spectrumUpdateEvents.h" +#include "spectrum_marker.hpp" #include #include @@ -34,58 +35,53 @@ using namespace scopy; -class FftDisplayZoomer: public LimitedPlotZoomer +class FftDisplayZoomer : public LimitedPlotZoomer { public: #if QWT_VERSION < 0x060100 - FftDisplayZoomer(QwtPlotCanvas* canvas) -#else /* QWT_VERSION < 0x060100 */ - FftDisplayZoomer(QWidget* canvas) + FftDisplayZoomer(QwtPlotCanvas *canvas) +#else /* QWT_VERSION < 0x060100 */ + FftDisplayZoomer(QWidget *canvas) #endif /* QWT_VERSION < 0x060100 */ - : LimitedPlotZoomer(canvas) - { - setTrackerMode(QwtPicker::AlwaysOn); - } - - virtual ~FftDisplayZoomer(){ + : LimitedPlotZoomer(canvas) + { + setTrackerMode(QwtPicker::AlwaysOn); + } - } + virtual ~FftDisplayZoomer() {} - virtual void updateTrackerText(){ - updateDisplay(); - } + virtual void updateTrackerText() { updateDisplay(); } protected: - using QwtPlotZoomer::trackerText; - virtual QwtText trackerText( const QPoint& p ) const - { - QPointF dp = QwtPlotZoomer::invTransform(p); - QwtText t(QString("(%1, %2)").arg(dp.x(), 0, 'f', 4). - arg(dp.y(), 0, 'f', 4)); - return t; - } + using QwtPlotZoomer::trackerText; + virtual QwtText trackerText(const QPoint &p) const + { + QPointF dp = QwtPlotZoomer::invTransform(p); + QwtText t(QString("(%1, %2)").arg(dp.x(), 0, 'f', 4).arg(dp.y(), 0, 'f', 4)); + return t; + } }; -FftDisplayPlot::FftDisplayPlot(int nplots, QWidget *parent) : - DisplayPlot(nplots, parent), - d_start_frequency(0), - d_stop_frequency(1000), - d_sampl_rate(1), - d_preset_sampl_rate(d_sampl_rate), - d_presetMagType(MagnitudeType::DBFS), - d_mrkCtrl(nullptr), - d_emitNewMkrData(true), - m_visiblePeakSearch(true), - d_logScaleEnabled(false), - d_buffer_idx(0), - d_nb_overlapping_avg(1), - n_ref_curves(0) +FftDisplayPlot::FftDisplayPlot(int nplots, QWidget *parent) + : DisplayPlot(nplots, parent) + , d_start_frequency(0) + , d_stop_frequency(1000) + , d_sampl_rate(1) + , d_preset_sampl_rate(d_sampl_rate) + , d_presetMagType(MagnitudeType::DBFS) + , d_mrkCtrl(nullptr) + , d_emitNewMkrData(true) + , m_visiblePeakSearch(true) + , d_logScaleEnabled(false) + , d_buffer_idx(0) + , d_nb_overlapping_avg(1) + , n_ref_curves(0) { // TO DO: Add more colors d_markerColors << QColor(255, 242, 0) << QColor(210, 155, 210); d_zoomer.push_back(nullptr); - for (unsigned int i = 0; i < nplots; i++) { + for(unsigned int i = 0; i < nplots; i++) { auto plot = new QwtPlotCurve(QString("CH %1").arg(i + 1)); plot->setPaintAttribute(QwtPlotCurve::ClipPolygons); plot->setPaintAttribute(QwtPlotCurve::ImageBuffer); @@ -103,10 +99,8 @@ FftDisplayPlot::FftDisplayPlot(int nplots, QWidget *parent) : d_num_markers.push_back(0); d_markers.push_back(QList()); - d_peaks.push_back( - QList>()); - d_freq_asc_sorted_peaks.push_back( - QList>()); + d_peaks.push_back(QList>()); + d_freq_asc_sorted_peaks.push_back(QList>()); d_current_avg_index.push_back(0); } y_scale_factor.resize(nplots); @@ -138,27 +132,17 @@ FftDisplayPlot::FftDisplayPlot(int nplots, QWidget *parent) : d_mrkCtrl = new MarkerController(this); - connect(d_mrkCtrl, - SIGNAL(markerSelected(std::shared_ptr&)), - this, - SLOT(onMrkCtrlMarkerSelected(std::shared_ptr&)) - ); - connect(d_mrkCtrl, - SIGNAL(markerPositionChanged(std::shared_ptr&)), - this, - SLOT(onMrkCtrlMarkerPosChanged(std::shared_ptr&)) - ); - connect(d_mrkCtrl, - SIGNAL(markerReleased(std::shared_ptr&)), - this, - SLOT(onMrkCtrlMarkerReleased(std::shared_ptr&)) - ); - - - setMinXaxisDivision(1); // A minimum division of 1 Hz - setMaxXaxisDivision(5E6); // A maximum division of 5 MHz - setMinYaxisDivision(1E-3); // A minimum division of 1 mdB - setMaxYaxisDivision(100); // A maximum division of 100 dB + connect(d_mrkCtrl, SIGNAL(markerSelected(std::shared_ptr &)), this, + SLOT(onMrkCtrlMarkerSelected(std::shared_ptr &))); + connect(d_mrkCtrl, SIGNAL(markerPositionChanged(std::shared_ptr &)), this, + SLOT(onMrkCtrlMarkerPosChanged(std::shared_ptr &))); + connect(d_mrkCtrl, SIGNAL(markerReleased(std::shared_ptr &)), this, + SLOT(onMrkCtrlMarkerReleased(std::shared_ptr &))); + + setMinXaxisDivision(1); // A minimum division of 1 Hz + setMaxXaxisDivision(5E6); // A maximum division of 5 MHz + setMinYaxisDivision(1E-3); // A minimum division of 1 mdB + setMaxYaxisDivision(100); // A maximum division of 100 dB setVertUnitsPerDiv(20); setVertOffset(-VertUnitsPerDiv() * 5); @@ -185,23 +169,23 @@ FftDisplayPlot::FftDisplayPlot(int nplots, QWidget *parent) : FftDisplayPlot::~FftDisplayPlot() { - for (uint c = 0; c < d_nplots + n_ref_curves; c++) { - for (uint i = 0; i < d_markers[c].size(); i++) { + for(uint c = 0; c < d_nplots + n_ref_curves; c++) { + for(uint i = 0; i < d_markers[c].size(); i++) { d_markers[c][i].ui->detach(); } } - if (x_data) + if(x_data) delete[] x_data; - for (unsigned int i = 0; i < d_nplots; i++) { - if (y_data[i]) + for(unsigned int i = 0; i < d_nplots; i++) { + if(y_data[i]) delete[] y_data[i]; - if (y_original_data[i]) + if(y_original_data[i]) delete[] y_original_data[i]; } - for (unsigned int i = 0; i < n_ref_curves; ++i) { + for(unsigned int i = 0; i < n_ref_curves; ++i) { delete d_refXdata[i]; delete d_refYdata[i]; } @@ -212,13 +196,11 @@ FftDisplayPlot::~FftDisplayPlot() canvas()->removeEventFilter(d_symbolCtrl); } -void FftDisplayPlot::initChannelMeasurement(int nplots) { - Q_EMIT channelAdded(nplots); -} +void FftDisplayPlot::initChannelMeasurement(int nplots) { Q_EMIT channelAdded(nplots); } void FftDisplayPlot::replot() { - if (!d_leftHandlesArea || !d_bottomHandlesArea) { + if(!d_leftHandlesArea || !d_bottomHandlesArea) { return; } @@ -230,14 +212,11 @@ void FftDisplayPlot::replot() bool FftDisplayPlot::isReferenceWaveform(unsigned int chnIdx) { - QwtPlotCurve *curve = Curve(chnIdx); - return d_ref_curves.values().contains(curve); + QwtPlotCurve *curve = Curve(chnIdx); + return d_ref_curves.values().contains(curve); } -size_t FftDisplayPlot::getCurveSize(unsigned int chnIdx) -{ - return Curve(chnIdx)->data()->size(); -} +size_t FftDisplayPlot::getCurveSize(unsigned int chnIdx) { return Curve(chnIdx)->data()->size(); } QString FftDisplayPlot::formatXValue(double value, int precision) const { @@ -270,7 +249,7 @@ void FftDisplayPlot::updateHandleAreaPadding() d_leftHandlesArea->update(); d_bottomHandlesArea->setLeftPadding(d_leftHandlesArea->width()); - //update handle position to avoid cursors getting out of the plot bounds when changing the padding; + // update handle position to avoid cursors getting out of the plot bounds when changing the padding; d_hCursorHandle1->updatePosition(); d_hCursorHandle2->updatePosition(); d_vCursorHandle1->updatePosition(); @@ -281,8 +260,8 @@ void FftDisplayPlot::onHCursor1Moved(double value) { QString text; bool error = false; - if (d_trackMode) { - if (value == ERROR_VALUE) { + if(d_trackMode) { + if(value == ERROR_VALUE) { error = true; } } @@ -293,7 +272,7 @@ void FftDisplayPlot::onHCursor1Moved(double value) d_cursorReadoutsText.t1 = error ? "-" : text; double valueCursor2; - if (d_trackMode) { + if(d_trackMode) { valueCursor2 = getHorizontalCursorIntersection(d_vBar2->plotCoord().x()); } else { valueCursor2 = d_hBar2->plotCoord().y(); @@ -311,8 +290,8 @@ void FftDisplayPlot::onHCursor2Moved(double value) { QString text; bool error = false; - if (d_trackMode) { - if (value == ERROR_VALUE) { + if(d_trackMode) { + if(value == ERROR_VALUE) { error = true; } } @@ -323,7 +302,7 @@ void FftDisplayPlot::onHCursor2Moved(double value) d_cursorReadoutsText.t2 = error ? "-" : text; double valueCursor1; - if (d_trackMode) { + if(d_trackMode) { valueCursor1 = getHorizontalCursorIntersection(d_vBar1->plotCoord().x()); } else { valueCursor1 = d_hBar1->plotCoord().y(); @@ -349,7 +328,7 @@ void FftDisplayPlot::onVCursor1Moved(double value) d_cursorReadouts->setTimeDeltaText(text); d_cursorReadoutsText.vDelta = text; - if (d_trackMode) { + if(d_trackMode) { onHCursor1Moved(getHorizontalCursorIntersection(d_vBar1->plotCoord().x())); } @@ -368,7 +347,7 @@ void FftDisplayPlot::onVCursor2Moved(double value) d_cursorReadouts->setTimeDeltaText(text); d_cursorReadoutsText.vDelta = text; - if (d_trackMode) { + if(d_trackMode) { onHCursor2Moved(getHorizontalCursorIntersection(d_vBar2->plotCoord().x())); } @@ -387,16 +366,15 @@ void FftDisplayPlot::enableYaxisLabels() bool FftDisplayPlot::eventFilter(QObject *object, QEvent *event) { - if (object == canvas() && event->type() == QEvent::Resize) { + if(object == canvas() && event->type() == QEvent::Resize) { updateHandleAreaPadding(); - //force cursor handles to emit position changed - //when the plot canvas is being resized + // force cursor handles to emit position changed + // when the plot canvas is being resized d_hCursorHandle1->triggerMove(); d_hCursorHandle2->triggerMove(); d_vCursorHandle1->triggerMove(); d_vCursorHandle2->triggerMove(); - } return QObject::eventFilter(object, event); } @@ -411,7 +389,7 @@ void FftDisplayPlot::showEvent(QShowEvent *event) void FftDisplayPlot::setSelectedChannel(int id) { - if (d_selected_channel != id) { + if(d_selected_channel != id) { d_selected_channel = id; } } @@ -423,42 +401,36 @@ void FftDisplayPlot::setZoomerEnabled() if(!d_zoomer[0]) { d_zoomer[0] = new FftDisplayZoomer(canvas()); - QFont font; - font.setPointSize(10); - font.setWeight(75); + QFont font; + font.setPointSize(10); + font.setWeight(75); d_zoomer[0]->setTrackerFont(font); #if QWT_VERSION < 0x060000 d_zoomer[0]->setSelectionFlags(QwtPicker::RectSelection | QwtPicker::DragSelection); #endif - d_zoomer[0]->setMousePattern(QwtEventPattern::MouseSelect2, - Qt::RightButton, Qt::ControlModifier); - d_zoomer[0]->setMousePattern(QwtEventPattern::MouseSelect3, - Qt::RightButton); + d_zoomer[0]->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); + d_zoomer[0]->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); - const QColor c("#999999"); + const QColor c("#999999"); d_zoomer[0]->setRubberBandPen(c); d_zoomer[0]->setTrackerPen(c); - } + } } -void FftDisplayPlot::setNumPoints(uint64_t num_points) -{ - d_numPoints = num_points; -} +void FftDisplayPlot::setNumPoints(uint64_t num_points) { d_numPoints = num_points; } QColor FftDisplayPlot::getChannelColor() { - for (QList::const_iterator it = d_CurveColors.cbegin(); - it != d_CurveColors.cend(); ++it) { + for(QList::const_iterator it = d_CurveColors.cbegin(); it != d_CurveColors.cend(); ++it) { bool used = false; - for (std::vector::const_iterator it2 = d_plot_curve.cbegin(); - !used && it2 != d_plot_curve.cend(); ++it2) + for(std::vector::const_iterator it2 = d_plot_curve.cbegin(); + !used && it2 != d_plot_curve.cend(); ++it2) used = (*it2)->pen().color() == (*it); - if (!used) + if(!used) return *it; } @@ -479,8 +451,7 @@ void FftDisplayPlot::registerReferenceWaveform(QString name, QVector xDa curve->setPen(QPen(color)); curve->setRenderHint(QwtPlotItem::RenderAntialiased); - QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(color), - QPen(color), QSize(7,7)); + QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(color), QPen(color), QSize(7, 7)); curve->setSymbol(symbol); @@ -491,13 +462,11 @@ void FftDisplayPlot::registerReferenceWaveform(QString name, QVector xDa d_num_markers.push_back(0); d_markers.push_back(QList()); - d_peaks.push_back( - QList>()); - d_freq_asc_sorted_peaks.push_back( - QList>()); + d_peaks.push_back(QList>()); + d_freq_asc_sorted_peaks.push_back(QList>()); setMarkerCount(d_num_markers.size() - 1, 5); - for (int m = 0; m < 5; m++) { + for(int m = 0; m < 5; m++) { setMarkerEnabled(d_num_markers.size() - 1, m, false); } setPeakCount(d_num_markers.size() - 1, 10); @@ -514,15 +483,15 @@ void FftDisplayPlot::unregisterReferenceWaveform(QString name) { int chIdx = -1; - for (size_t i = 0; i < d_plot_curve.size(); ++i) { - if (d_plot_curve[i] == d_ref_curves[name]) { + for(size_t i = 0; i < d_plot_curve.size(); ++i) { + if(d_plot_curve[i] == d_ref_curves[name]) { chIdx = i; } } auto it = std::find(d_plot_curve.begin(), d_plot_curve.end(), d_ref_curves[name]); - if (it == d_plot_curve.end()) { + if(it == d_plot_curve.end()) { return; } @@ -553,14 +522,14 @@ void FftDisplayPlot::setWindowCoefficientSum(unsigned int ch, float sum, float s void FftDisplayPlot::useLogScaleY(bool log_scale) { - if (log_scale) { + if(log_scale) { setPlotYLogaritmic(true); QwtLogScaleEngine *scaleEngine = new QwtLogScaleEngine(); - setAxisScaleEngine(QwtAxis::YLeft, (QwtScaleEngine *)scaleEngine); -// OscScaleDraw *yScaleDraw = new OscScaleDraw(&dBFormatter, "V/√Hz"); -// yScaleDraw->enableComponent(QwtAbstractScaleDraw::Ticks, true); -// yScaleDraw->setFloatPrecision(2); -// setAxisScaleDraw(QwtAxis::YLeft, yScaleDraw); + setAxisScaleEngine(QwtAxis::YLeft, (QwtScaleEngine *)scaleEngine); + // OscScaleDraw *yScaleDraw = new OscScaleDraw(&dBFormatter, "V/√Hz"); + // yScaleDraw->enableComponent(QwtAbstractScaleDraw::Ticks, true); + // yScaleDraw->setFloatPrecision(2); + // setAxisScaleDraw(QwtAxis::YLeft, yScaleDraw); replot(); auto div = axisScaleDiv(QwtAxis::YLeft); setYaxisMajorTicksPos(div.ticks(2)); @@ -568,9 +537,9 @@ void FftDisplayPlot::useLogScaleY(bool log_scale) setPlotYLogaritmic(false); OscScaleEngine *scaleEngine = new OscScaleEngine(); this->setAxisScaleEngine(QwtAxis::YLeft, (QwtScaleEngine *)scaleEngine); -// OscScaleDraw *yScaleDraw = new OscScaleDraw(&dBFormatter, ""); -// yScaleDraw->setFloatPrecision(2); -// setAxisScaleDraw(QwtAxis::YLeft, yScaleDraw); + // OscScaleDraw *yScaleDraw = new OscScaleDraw(&dBFormatter, ""); + // yScaleDraw->setFloatPrecision(2); + // setAxisScaleDraw(QwtAxis::YLeft, yScaleDraw); replot(); auto div = axisScaleDiv(QwtAxis::YLeft); setYaxisNumDiv((div.ticks(2)).size()); @@ -581,7 +550,7 @@ void FftDisplayPlot::useLogScaleY(bool log_scale) void FftDisplayPlot::useLogFreq(bool use_log_freq) { - if (use_log_freq) { + if(use_log_freq) { setPlotLogaritmic(true); setAxisScaleEngine(QwtAxis::XBottom, new QwtLogScaleEngine); replot(); @@ -599,38 +568,26 @@ void FftDisplayPlot::useLogFreq(bool use_log_freq) replot(); } -std::vector FftDisplayPlot::getOrginal_data() { - return y_original_data; -} +std::vector FftDisplayPlot::getOrginal_data() { return y_original_data; } -int64_t FftDisplayPlot::getYdata_size() { - return y_data.size(); -} +int64_t FftDisplayPlot::getYdata_size() { return y_data.size(); } -std::vector FftDisplayPlot::getRef_data() { - return d_refYdata; -} +std::vector FftDisplayPlot::getRef_data() { return d_refYdata; } -std::vector FftDisplayPlot::getScaleFactor() { - return y_scale_factor; -} +std::vector FftDisplayPlot::getScaleFactor() { return y_scale_factor; } -int64_t FftDisplayPlot::getNumPoints() -{ - return d_numPoints; -} +int64_t FftDisplayPlot::getNumPoints() { return d_numPoints; } -void FftDisplayPlot::plotData(const std::vector &pts, - uint64_t num_points) +void FftDisplayPlot::plotData(const std::vector &pts, uint64_t num_points) { uint64_t halfNumPoints = num_points / 2; -// uint64_t halfNumPoints = num_points; + // uint64_t halfNumPoints = num_points; bool numPointsChanged = false; bool samplRateChanged = false; bool magTypeChanged = false; // Update sample rate if required - if (d_sampl_rate != d_preset_sampl_rate) { + if(d_sampl_rate != d_preset_sampl_rate) { d_sampl_rate = d_preset_sampl_rate; d_start_frequency = 0; d_stop_frequency = d_sampl_rate / 2; @@ -639,69 +596,65 @@ void FftDisplayPlot::plotData(const std::vector &pts, Q_EMIT sampleRateUpdated(d_sampl_rate); } - if (d_magType != d_presetMagType) { + if(d_magType != d_presetMagType) { d_magType = d_presetMagType; magTypeChanged = true; } - if (d_stop || halfNumPoints == 0) + if(d_stop || halfNumPoints == 0) return; - if (halfNumPoints != d_numPoints || d_firstInit) { + if(halfNumPoints != d_numPoints || d_firstInit) { d_firstInit = false; d_numPoints = halfNumPoints; numPointsChanged = true; Q_EMIT sampleCountUpdated(d_numPoints); - if (x_data) - delete []x_data; + if(x_data) + delete[] x_data; x_data = new double[halfNumPoints]; - for (unsigned int i = 0; i < d_nplots; i++) { - if (y_data[i]) + for(unsigned int i = 0; i < d_nplots; i++) { + if(y_data[i]) delete[] y_data[i]; - if (y_original_data[i]) + if(y_original_data[i]) delete[] y_original_data[i]; y_data[i] = new double[halfNumPoints]; y_original_data[i] = new double[halfNumPoints]; #if QWT_VERSION < 0x060000 - d_plot_curve[i]->setRawData(x_data, - y_data[i], halfNumPoints); + d_plot_curve[i]->setRawData(x_data, y_data[i], halfNumPoints); #else - d_plot_curve[i]->setRawSamples(x_data, - y_data[i], halfNumPoints); + d_plot_curve[i]->setRawSamples(x_data, y_data[i], halfNumPoints); #endif } // Resize the average objects to the new number of points - for (size_t i = 0; i < d_ch_avg_obj.size(); i++) { - if (!d_ch_avg_obj[i]) + for(size_t i = 0; i < d_ch_avg_obj.size(); i++) { + if(!d_ch_avg_obj[i]) continue; uint size = d_ch_avg_obj[i]->dataWidth(); - if (size == halfNumPoints) + if(size == halfNumPoints) continue; uint h = d_ch_avg_obj[i]->history(); bool h_en = d_ch_avg_obj[i]->historyEnabled(); - d_ch_avg_obj[i] = getNewAvgObject( - d_ch_average_type[i], halfNumPoints, h, h_en); + d_ch_avg_obj[i] = getNewAvgObject(d_ch_average_type[i], halfNumPoints, h, h_en); } } // We store the received data before touching it - for (unsigned int i = 0; i < d_nplots; i++) { - memcpy(y_original_data[i], pts[i], - halfNumPoints * sizeof(double)); + for(unsigned int i = 0; i < d_nplots; i++) { + memcpy(y_original_data[i], pts[i], halfNumPoints * sizeof(double)); } // When the magnitude type changes, we reset the data that is // being stored in the average objects - if (magTypeChanged) { + if(magTypeChanged) { resetAverageHistory(); } @@ -709,13 +662,13 @@ void FftDisplayPlot::plotData(const std::vector &pts, _resetXAxisPoints(); - if (numPointsChanged) { + if(numPointsChanged) { // When the number of points change but the start and stop freq // stay the same, we need to update the position of fixed markers - for (int c = 0; c < d_nplots; c++) { - for (int m = 0; m < d_markers[c].size(); m++) { + for(int c = 0; c < d_nplots; c++) { + for(int m = 0; m < d_markers[c].size(); m++) { auto marker = d_markers[c][m]; - if (!marker.data || marker.data->type != 0) + if(!marker.data || marker.data->type != 0) continue; marker.data->bin = posAtFrequency(marker.data->x); @@ -723,21 +676,20 @@ void FftDisplayPlot::plotData(const std::vector &pts, } } } - if (samplRateChanged) { + if(samplRateChanged) { // When the sample rate changes, the frequency of each bin // chhanges. Markers need to be updated so that they point to // the same frequency as before. - for (int c = 0; c < d_nplots; c++) { - for (int m = 0; m < d_markers[c].size(); m++) { + for(int c = 0; c < d_nplots; c++) { + for(int m = 0; m < d_markers[c].size(); m++) { auto marker = d_markers[c][m]; - if (!marker.data || marker.data->type != 0) + if(!marker.data || marker.data->type != 0) continue; - if (marker.data->x > d_stop_frequency) { + if(marker.data->x > d_stop_frequency) { marker.data->bin = d_numPoints - 1; } else { - marker.data->bin = posAtFrequency( - marker.data->x); + marker.data->bin = posAtFrequency(marker.data->x); } marker.data->x = x_data[marker.data->bin]; @@ -752,24 +704,24 @@ void FftDisplayPlot::plotData(const std::vector &pts, Q_EMIT newFFTData(); } -void FftDisplayPlot::averageDataAndComputeMagnitude(std::vector - in_data, std::vector out_data, uint64_t nb_points) +void FftDisplayPlot::averageDataAndComputeMagnitude(std::vector in_data, std::vector out_data, + uint64_t nb_points) { std::vector source; - if (d_buffer_idx == 0) { + if(d_buffer_idx == 0) { d_ps_avg.resize(d_nplots); } - for (unsigned int i = 0; i < d_nplots; i++) { + for(unsigned int i = 0; i < d_nplots; i++) { bool needs_dB_avg = false; d_current_avg_index[i] += 1; - if (averageHistory(i) > 0) { + if(averageHistory(i) > 0) { d_current_avg_index[i] %= averageHistory(i); } Q_EMIT currentAverageIndex(i, d_current_avg_index[i]); - switch (d_ch_average_type[i]) { + switch(d_ch_average_type[i]) { case LINEAR_DB: case EXPONENTIAL_DB: needs_dB_avg = true; @@ -784,33 +736,25 @@ void FftDisplayPlot::averageDataAndComputeMagnitude(std::vector break; } - - if (d_buffer_idx == 0) { + if(d_buffer_idx == 0) { d_ps_avg[i].resize(nb_points); } - for (int s = 0; s < nb_points; s++) { - //dB Full-Scale - switch (d_magType) { + for(int s = 0; s < nb_points; s++) { + // dB Full-Scale + switch(d_magType) { case DBFS: - out_data[i][s] = 10 * log10((source[i][s] / - (2048 * 2048)) / - (nb_points * nb_points)); + out_data[i][s] = 10 * log10((source[i][s] / (2048 * 2048)) / (nb_points * nb_points)); break; case DBV: - out_data[i][s] = 10 * log10(source[i][s]) + - 20 * log10(y_scale_factor[i]) - - 20 * log10(nb_points) - - 20 * log10(sqrt(2)); + out_data[i][s] = 10 * log10(source[i][s]) + 20 * log10(y_scale_factor[i]) - + 20 * log10(nb_points) - 20 * log10(sqrt(2)); break; case DBU: - out_data[i][s] = 10 * log10(source[i][s]) + - 20 * log10(y_scale_factor[i]) - - 20 * log10(nb_points) - - 20 * log10(sqrt(2) * 0.77459667); + out_data[i][s] = 10 * log10(source[i][s]) + 20 * log10(y_scale_factor[i]) - + 20 * log10(nb_points) - 20 * log10(sqrt(2) * 0.77459667); break; case VPEAK: - out_data[i][s] = sqrt(source[i][s]) * - y_scale_factor[i] / nb_points; + out_data[i][s] = sqrt(source[i][s]) * y_scale_factor[i] / nb_points; break; case VRMS: /* Another formula for this would be @@ -820,18 +764,17 @@ void FftDisplayPlot::averageDataAndComputeMagnitude(std::vector * when we apply the window compensation (before the FFT, or after. * With the current version, this is applied before (in calcCoherentPowerGain) */ - out_data[i][s] = sqrt(source[i][s]) * - y_scale_factor[i] / sqrt(2) / nb_points; + out_data[i][s] = sqrt(source[i][s]) * y_scale_factor[i] / sqrt(2) / nb_points; break; case VROOTHZ: - auto ps_rms = sqrt(source[i][s]) * y_scale_factor[i] / sqrt(2) / nb_points; + auto ps_rms = sqrt(source[i][s]) * y_scale_factor[i] / sqrt(2) / nb_points; d_ps_avg[i][s] = sqrt((d_ps_avg[i][s] * d_ps_avg[i][s]) + (ps_rms * ps_rms)); - if (d_buffer_idx == (d_nb_overlapping_avg - 1)) { + if(d_buffer_idx == (d_nb_overlapping_avg - 1)) { d_ps_avg[i][s] = d_ps_avg[i][s] / sqrt(d_nb_overlapping_avg); auto ls_rms = d_ps_avg[i][s]; auto enbw = d_sampl_rate * d_win_coefficient_sum_sqr[i] / - (d_win_coefficient_sum[i] * d_win_coefficient_sum[i]); + (d_win_coefficient_sum[i] * d_win_coefficient_sum[i]); auto ls_d_rms = ls_rms / sqrt(enbw); out_data[i][s] = ls_d_rms; } @@ -839,12 +782,12 @@ void FftDisplayPlot::averageDataAndComputeMagnitude(std::vector }; } - if (needs_dB_avg) { + if(needs_dB_avg) { d_ch_avg_obj[i]->pushNewData(out_data[i]); d_ch_avg_obj[i]->getAverage(out_data[i], nb_points); } } - if (d_buffer_idx == (d_nb_overlapping_avg - 1)) { + if(d_buffer_idx == (d_nb_overlapping_avg - 1)) { d_ps_avg.clear(); d_buffer_idx = 0; } else { @@ -854,8 +797,7 @@ void FftDisplayPlot::averageDataAndComputeMagnitude(std::vector void FftDisplayPlot::_resetXAxisPoints() { - double fft_bin_size = (d_stop_frequency - d_start_frequency) - / static_cast(d_numPoints); + double fft_bin_size = (d_stop_frequency - d_start_frequency) / static_cast(d_numPoints); double freqValue = d_start_frequency; for(int64_t loc = 0; loc < d_numPoints; loc++) { @@ -867,9 +809,8 @@ void FftDisplayPlot::_resetXAxisPoints() int64_t FftDisplayPlot::posAtFrequency(double freq, int chIdx) const { int64_t pos = 0; - if (chIdx < d_nplots) { - double fft_bin_size = (d_stop_frequency - d_start_frequency) - / static_cast(d_numPoints); + if(chIdx < d_nplots) { + double fft_bin_size = (d_stop_frequency - d_start_frequency) / static_cast(d_numPoints); pos = qRound64((freq - d_start_frequency) / (fft_bin_size)); } else { @@ -877,8 +818,7 @@ int64_t FftDisplayPlot::posAtFrequency(double freq, int chIdx) const unsigned int num_points = d_plot_curve[chIdx]->data()->size(); double stop_frequency = d_refXdata[chIdx - d_nplots][num_points - 1]; double start_frequency = d_refYdata[chIdx - d_nplots][0]; - double fft_bin_size = (stop_frequency - start_frequency) - / static_cast(num_points); + double fft_bin_size = (stop_frequency - start_frequency) / static_cast(num_points); pos = qRound64((freq - start_frequency) / (fft_bin_size)); } @@ -901,26 +841,20 @@ void FftDisplayPlot::updateZoomerBase() getZoomer()->setZoomBase(rect); getZoomer()->QwtPlotZoomer::zoom(rect); getZoomer()->blockSignals(false); - } void FftDisplayPlot::customEvent(QEvent *e) { - if (e->type() == TimeUpdateEvent::Type()) { + if(e->type() == TimeUpdateEvent::Type()) { TimeUpdateEvent *ev = static_cast(e); - this->plotData(ev->getTimeDomainPoints(), - ev->getNumTimeDomainDataPoints()); + this->plotData(ev->getTimeDomainPoints(), ev->getNumTimeDomainDataPoints()); } } -bool FftDisplayPlot::getLogScale() const -{ - return d_logScaleEnabled; -} +bool FftDisplayPlot::getLogScale() const { return d_logScaleEnabled; } -void FftDisplayPlot::setSampleRate(double sr, double units, - const std::string &strunits) +void FftDisplayPlot::setSampleRate(double sr, double units, const std::string &strunits) { d_start_frequency = 0; d_stop_frequency = sr / 2; @@ -930,19 +864,13 @@ void FftDisplayPlot::setSampleRate(double sr, double units, _resetXAxisPoints(); } -double FftDisplayPlot::sampleRate() -{ - return d_sampl_rate; -} +double FftDisplayPlot::sampleRate() { return d_sampl_rate; } -void FftDisplayPlot::presetSampleRate(double sr) -{ - d_preset_sampl_rate = sr; -} +void FftDisplayPlot::presetSampleRate(double sr) { d_preset_sampl_rate = sr; } FftDisplayPlot::AverageType FftDisplayPlot::averageType(uint chIdx) const { - if (chIdx < d_ch_average_type.size()) + if(chIdx < d_ch_average_type.size()) return d_ch_average_type[chIdx]; return SAMPLE; @@ -952,23 +880,21 @@ uint FftDisplayPlot::averageHistory(uint chIdx) const { uint history = 0; - if (chIdx < d_ch_average_type.size()) - if (d_ch_avg_obj[chIdx]) + if(chIdx < d_ch_average_type.size()) + if(d_ch_avg_obj[chIdx]) history = d_ch_avg_obj[chIdx]->history(); return history; } -void FftDisplayPlot::setAverage(uint chIdx, enum AverageType avg_type, - uint history, bool history_en) +void FftDisplayPlot::setAverage(uint chIdx, enum AverageType avg_type, uint history, bool history_en) { - if (chIdx >= d_ch_average_type.size()) { + if(chIdx >= d_ch_average_type.size()) { return; } - - if (d_ch_avg_obj[chIdx] && (history != d_ch_avg_obj[chIdx]->history()) - && (history_en == d_ch_avg_obj[chIdx]->historyEnabled())) { + if(d_ch_avg_obj[chIdx] && (history != d_ch_avg_obj[chIdx]->history()) && + (history_en == d_ch_avg_obj[chIdx]->historyEnabled())) { d_ch_avg_obj[chIdx]->setHistory(history); } else { d_ch_average_type[chIdx] = avg_type; @@ -980,71 +906,61 @@ void FftDisplayPlot::setAverage(uint chIdx, enum AverageType avg_type, void FftDisplayPlot::resetAverageHistory() { - for (size_t i = 0; i < d_ch_avg_obj.size(); i++) - if (d_ch_avg_obj[i]) + for(size_t i = 0; i < d_ch_avg_obj.size(); i++) + if(d_ch_avg_obj[i]) d_ch_avg_obj[i]->reset(); - for (size_t i = 0; i < d_current_avg_index.size(); i++) { + for(size_t i = 0; i < d_current_avg_index.size(); i++) { d_current_avg_index[i] = 0; Q_EMIT currentAverageIndex(i, d_current_avg_index[i]); } } -FftDisplayPlot::average_sptr FftDisplayPlot::getNewAvgObject( - enum AverageType avg_type, uint data_width, uint history, bool history_en) +FftDisplayPlot::average_sptr FftDisplayPlot::getNewAvgObject(enum AverageType avg_type, uint data_width, uint history, + bool history_en) { - switch (avg_type) { - case SAMPLE: - return nullptr; - - case PEAK_HOLD: - return std::make_shared(data_width, - history); - case PEAK_HOLD_CONTINUOUS: - return std::make_shared( - data_width, history); - case MIN_HOLD: - return std::make_shared(data_width, history); - case MIN_HOLD_CONTINUOUS: - return std::make_shared(data_width, - history); - case LINEAR_RMS: - if (history_en) { - return std::make_shared(data_width, - history); + switch(avg_type) { + case SAMPLE: + return nullptr; + + case PEAK_HOLD: + return std::make_shared(data_width, history); + case PEAK_HOLD_CONTINUOUS: + return std::make_shared(data_width, history); + case MIN_HOLD: + return std::make_shared(data_width, history); + case MIN_HOLD_CONTINUOUS: + return std::make_shared(data_width, history); + case LINEAR_RMS: + if(history_en) { + return std::make_shared(data_width, history); } else { - return std::make_shared(data_width, - history); + return std::make_shared(data_width, history); } - case LINEAR_DB: - if (history_en) { - return std::make_shared(data_width, - history); + case LINEAR_DB: + if(history_en) { + return std::make_shared(data_width, history); } else { - return std::make_shared(data_width, - history); + return std::make_shared(data_width, history); } - case EXPONENTIAL_RMS: - return std::make_shared( - data_width, history); - case EXPONENTIAL_DB: - return std::make_shared( - data_width, history); - default: - return nullptr; + case EXPONENTIAL_RMS: + return std::make_shared(data_width, history); + case EXPONENTIAL_DB: + return std::make_shared(data_width, history); + default: + return nullptr; } } QString FftDisplayPlot::leftVerAxisUnit() const { return d_yAxisUnit; } -void FftDisplayPlot::setLeftVertAxisUnit(const QString& unit) +void FftDisplayPlot::setLeftVertAxisUnit(const QString &unit) { - if (d_yAxisUnit != unit) { - d_yAxisUnit = unit; + if(d_yAxisUnit != unit) { + d_yAxisUnit = unit; - auto scale_draw = dynamic_cast( - axisScaleDraw(QwtAxis::YLeft)); - if (scale_draw) { + auto scale_draw = dynamic_cast(axisScaleDraw(QwtAxis::YLeft)); + if(scale_draw) { scale_draw->setUnitType(unit); } } @@ -1054,26 +970,26 @@ QString FftDisplayPlot::btmHorAxisUnit() const { return d_xAxisUnit; } void FftDisplayPlot::setBtmHorAxisUnit(const QString &unit) { - if (d_xAxisUnit != unit) { + if(d_xAxisUnit != unit) { d_xAxisUnit = unit; - auto scale_draw = dynamic_cast(axisScaleDraw(QwtAxis::XBottom)); - if (scale_draw) + auto scale_draw = dynamic_cast(axisScaleDraw(QwtAxis::XBottom)); + if(scale_draw) scale_draw->setUnitType(unit); } } void FftDisplayPlot::findPeaks(int chn) { - QList>& markers = d_peaks[chn]; - QList>& f_sort_mrks = d_freq_asc_sorted_peaks[chn]; + QList> &markers = d_peaks[chn]; + QList> &f_sort_mrks = d_freq_asc_sorted_peaks[chn]; int marker_count = markers.size(); int maxX[marker_count + 1]; float maxY[marker_count + 1]; double *x = nullptr; double *y = nullptr; unsigned int num_points = 0; - if (chn < d_nplots) { + if(chn < d_nplots) { x = x_data; y = y_data[chn]; num_points = d_numPoints; @@ -1083,11 +999,11 @@ void FftDisplayPlot::findPeaks(int chn) num_points = d_plot_curve[chn]->data()->size(); } - if (!x || !y) { + if(!x || !y) { return; } - for (int i = 0; i <= marker_count; i++) { + for(int i = 0; i <= marker_count; i++) { maxX[i] = 0; maxY[i] = -200.0; } @@ -1097,28 +1013,25 @@ void FftDisplayPlot::findPeaks(int chn) auto start = 3; auto stop = num_points; - if(m_visiblePeakSearch) - { - auto coef = num_points/d_stop_frequency; - if (m_sweepStart * coef > 0) { + if(m_visiblePeakSearch) { + auto coef = num_points / d_stop_frequency; + if(m_sweepStart * coef > 0) { start = m_sweepStart * coef; } stop = m_sweepStop * coef; maxY[0] = y[start]; } - for (int i = start; i < stop; i++) { - for (int j = 0; j < marker_count; j++ ) { - if (i < 2) { + for(int i = start; i < stop; i++) { + for(int j = 0; j < marker_count; j++) { + if(i < 2) { continue; } - if ((y[i - 1] > maxY[j]) && - ((!((y[i - 2] > y[i - 1]) && - (y[i - 1] > y[i]))) && - (!((y[i - 2] < y[i - 1]) && - (y[i - 1] < y[i]))))) { + if((y[i - 1] > maxY[j]) && + ((!((y[i - 2] > y[i - 1]) && (y[i - 1] > y[i]))) && + (!((y[i - 2] < y[i - 1]) && (y[i - 1] < y[i]))))) { - for (int k = marker_count; k > j; k--) { + for(int k = marker_count; k > j; k--) { maxY[k] = maxY[k - 1]; maxX[k] = maxX[k - 1]; } @@ -1129,21 +1042,18 @@ void FftDisplayPlot::findPeaks(int chn) } } - for (int i = 0; i < marker_count; i++) { + for(int i = 0; i < marker_count; i++) { markers[i]->x = x[maxX[i]]; markers[i]->y = y[maxX[i]]; markers[i]->bin = maxX[i]; } - for (int i = 0; i < markers.size(); i++) { + for(int i = 0; i < markers.size(); i++) { f_sort_mrks[i] = markers[i]; } std::sort(f_sort_mrks.begin(), f_sort_mrks.end(), - [](const std::shared_ptr m1, - const std::shared_ptr m2) -> bool - { - return m1->x < m2->x; - }); + [](const std::shared_ptr m1, + const std::shared_ptr m2) -> bool { return m1->x < m2->x; }); updateMarkersUi(); } @@ -1153,15 +1063,15 @@ void FftDisplayPlot::updateMarkerUi(uint chIdx, uint mkIdx) auto marker = d_markers[chIdx][mkIdx]; // update marker ony if active - if (marker.data && marker.data->update_ui) { + if(marker.data && marker.data->update_ui) { marker.ui->setValue(marker.data->x, marker.data->y); } } void FftDisplayPlot::updateMarkersUi() { - for (int c = 0; c < d_nplots; c++) { - for (int i = 0; i < d_markers[c].size(); i++) { + for(int c = 0; c < d_nplots; c++) { + for(int i = 0; i < d_markers[c].size(); i++) { updateMarkerUi(c, i); } } @@ -1182,10 +1092,8 @@ void FftDisplayPlot::add_marker(int chn) // GUI marker auto gui_marker = std::make_shared(markerName); QColor marker_color = d_markerColors[chn % d_markerColors.size()]; - QwtSymbol *symbol = new QwtSymbol( - QwtSymbol::Diamond, QColor(237, 28, 36), - QPen(marker_color, 2, Qt::SolidLine), - QSize(18, 18)); + QwtSymbol *symbol = new QwtSymbol(QwtSymbol::Diamond, QColor(237, 28, 36), QPen(marker_color, 2, Qt::SolidLine), + QSize(18, 18)); symbol->setSize(18, 18); gui_marker->setSymbol(symbol); @@ -1212,28 +1120,26 @@ void FftDisplayPlot::add_marker(int chn) void FftDisplayPlot::remove_marker(int chn, int which) { - if (which < d_markers[chn].size()) { + if(which < d_markers[chn].size()) { d_markers[chn][which].ui->detach(); d_markers[chn].removeAt(which); } - } -void FftDisplayPlot::marker_set_pos_source(uint chIdx, uint mkIdx, - std::shared_ptr &source_sptr) +void FftDisplayPlot::marker_set_pos_source(uint chIdx, uint mkIdx, std::shared_ptr &source_sptr) { d_markers[chIdx][mkIdx].data = source_sptr; - if (d_emitNewMkrData) + if(d_emitNewMkrData) Q_EMIT newMarkerData(); } void FftDisplayPlot::calculate_fixed_markers(int chn) { - for (int i = 0; i < d_markers[chn].size(); i++) { + for(int i = 0; i < d_markers[chn].size(); i++) { double *ydata = nullptr, *xdata = nullptr; unsigned int index = -1; - if (chn < d_nplots) { + if(chn < d_nplots) { ydata = y_data[chn]; xdata = x_data; } else { @@ -1243,7 +1149,7 @@ void FftDisplayPlot::calculate_fixed_markers(int chn) // update active markers only auto marker = d_markers[chn][i]; - if (marker.data && marker.data->type == 0) { + if(marker.data && marker.data->type == 0) { marker.data->y = ydata[marker.data->bin]; marker.data->x = xdata[marker.data->bin]; } @@ -1252,7 +1158,7 @@ void FftDisplayPlot::calculate_fixed_markers(int chn) uint FftDisplayPlot::peakCount(uint chIdx) const { - if (chIdx >= d_peaks.size()) + if(chIdx >= d_peaks.size()) return 0; return d_peaks[chIdx].size(); @@ -1260,17 +1166,16 @@ uint FftDisplayPlot::peakCount(uint chIdx) const void FftDisplayPlot::setPeakCount(uint chIdx, uint count) { - if (chIdx >= d_peaks.size()) + if(chIdx >= d_peaks.size()) return; - if (d_peaks[chIdx].size() == count) + if(d_peaks[chIdx].size() == count) return; - d_peaks[chIdx].clear(); d_freq_asc_sorted_peaks[chIdx].clear(); - for (uint i = 0; i < count; i++) { + for(uint i = 0; i < count; i++) { auto data_marker_sp = std::make_shared(); data_marker_sp->type = 1; // Peak marker data_marker_sp->update_ui = true; @@ -1279,45 +1184,38 @@ void FftDisplayPlot::setPeakCount(uint chIdx, uint count) } } -uint FftDisplayPlot::markerCount(uint chIdx) const -{ - return d_markers[chIdx].size(); -} +uint FftDisplayPlot::markerCount(uint chIdx) const { return d_markers[chIdx].size(); } void FftDisplayPlot::setMarkerCount(uint chIdx, uint count) { - if (chIdx >= d_markers.size()) { + if(chIdx >= d_markers.size()) { qDebug() << "Invalid channel index!"; return; } - if (d_markers[chIdx].size() == count) { + if(d_markers[chIdx].size() == count) { return; } - while (d_markers[chIdx].size()) { + while(d_markers[chIdx].size()) { remove_marker(chIdx, 0); } - for (uint i = 0; i < count; i++) { + for(uint i = 0; i < count; i++) { add_marker(chIdx); } } -bool FftDisplayPlot::markerEnabled(uint chIdx, uint mkIdx) const -{ - return !!d_markers[chIdx][mkIdx].data; -} +bool FftDisplayPlot::markerEnabled(uint chIdx, uint mkIdx) const { return !!d_markers[chIdx][mkIdx].data; } - -bool FftDisplayPlot:: markerVisible(uint chIdx, uint mkIdx) const +bool FftDisplayPlot::markerVisible(uint chIdx, uint mkIdx) const { - if (chIdx >= d_markers.size()) { + if(chIdx >= d_markers.size()) { qDebug() << "Invalid channel index!"; return false; } - if (mkIdx >= d_markers[chIdx].size()) { + if(mkIdx >= d_markers[chIdx].size()) { qDebug() << "Invalid marker index"; return false; } @@ -1327,12 +1225,12 @@ bool FftDisplayPlot:: markerVisible(uint chIdx, uint mkIdx) const void FftDisplayPlot::setMarkerVisible(uint chIdx, uint mkIdx, bool en) { - if (chIdx >= d_markers.size()) { + if(chIdx >= d_markers.size()) { qDebug() << "Invalid channel index!"; return; } - if (mkIdx >= d_markers[chIdx].size()) { + if(mkIdx >= d_markers[chIdx].size()) { qDebug() << "Invalid marker index"; return; } @@ -1340,19 +1238,19 @@ void FftDisplayPlot::setMarkerVisible(uint chIdx, uint mkIdx, bool en) d_markers[chIdx][mkIdx].ui->setVisible(en); } -void FftDisplayPlot:: setMarkerEnabled(uint chIdx, uint mkIdx, bool en) +void FftDisplayPlot::setMarkerEnabled(uint chIdx, uint mkIdx, bool en) { - if (chIdx >= d_markers.size()) { + if(chIdx >= d_markers.size()) { qDebug() << "Invalid channel index!"; return; } - if (mkIdx >= d_markers[chIdx].size()) { + if(mkIdx >= d_markers[chIdx].size()) { qDebug() << "Invalid marker index"; return; } - if (en) { + if(en) { auto data_sp = std::make_shared(); data_sp->x = 0; data_sp->y = axisScaleDiv(QwtAxis::YLeft).lowerBound(); @@ -1372,21 +1270,21 @@ void FftDisplayPlot:: setMarkerEnabled(uint chIdx, uint mkIdx, bool en) d_markers[chIdx][mkIdx].ui->setVisible(en); int en_markers = 0; - for (int c = 0; c < d_nplots; c++) - for (int m = 0; m < d_markers[c].size(); m++) - if (!!d_markers[c][m].data) + for(int c = 0; c < d_nplots; c++) + for(int m = 0; m < d_markers[c].size(); m++) + if(!!d_markers[c][m].data) en_markers++; d_emitNewMkrData = (en_markers > 0); } double FftDisplayPlot::markerFrequency(uint chIdx, uint mkIdx) const { - if (chIdx >= d_markers.size()) { + if(chIdx >= d_markers.size()) { qDebug() << "Invalid channel index!"; return 0; } - if (mkIdx >= d_markers[chIdx].size()) { + if(mkIdx >= d_markers[chIdx].size()) { qDebug() << "Invalid marker index"; return 0; } @@ -1396,12 +1294,12 @@ double FftDisplayPlot::markerFrequency(uint chIdx, uint mkIdx) const double FftDisplayPlot::markerMagnitude(uint chIdx, uint mkIdx) const { - if (chIdx >= d_markers.size()) { + if(chIdx >= d_markers.size()) { qDebug() << "Invalid channel index!"; return 0; } - if (mkIdx >= d_markers[chIdx].size()) { + if(mkIdx >= d_markers[chIdx].size()) { qDebug() << "Invalid marker index"; return 0; } @@ -1411,25 +1309,25 @@ double FftDisplayPlot::markerMagnitude(uint chIdx, uint mkIdx) const void FftDisplayPlot::setMarkerAtFreq(uint chIdx, uint mkIdx, double freq) { - if (chIdx >= d_markers.size()) { + if(chIdx >= d_markers.size()) { qDebug() << "Invalid channel index!"; return; } - if (mkIdx >= d_markers[chIdx].size()) { + if(mkIdx >= d_markers[chIdx].size()) { qDebug() << "Invalid marker index"; return; } int64_t pos = posAtFrequency(freq, chIdx); - if ((pos < 0 || pos >= d_numPoints) && chIdx < d_nplots) { + if((pos < 0 || pos >= d_numPoints) && chIdx < d_nplots) { qDebug() << "Invalid frenquency!"; return; } unsigned int index = -1; double *ydata = nullptr, *xdata = nullptr; - if (chIdx < d_nplots) { + if(chIdx < d_nplots) { ydata = y_data[chIdx]; xdata = x_data; index = chIdx; @@ -1440,13 +1338,13 @@ void FftDisplayPlot::setMarkerAtFreq(uint chIdx, uint mkIdx, double freq) } double y; - if (ydata) { + if(ydata) { y = ydata[pos]; } else { y = axisScaleDiv(QwtAxis::YLeft).lowerBound(); } - if (d_markers[chIdx][mkIdx].data->type != 0) { + if(d_markers[chIdx][mkIdx].data->type != 0) { auto marker_data = std::make_shared(); marker_data->type = 0; // Fixed marker marker_data->x = xdata[pos]; @@ -1465,7 +1363,7 @@ void FftDisplayPlot::marker_to_max_peak(uint chIdx, uint mkIdx) { d_markers[chIdx][mkIdx].data = d_peaks[chIdx][0]; - if (d_emitNewMkrData) + if(d_emitNewMkrData) Q_EMIT newMarkerData(); } @@ -1476,14 +1374,14 @@ void FftDisplayPlot::marker_to_next_higher_freq_peak(uint chIdx, uint mkIdx) int pos = -1; // find the first peak with the freq higher that marker freq pos - for (int i = 0; i < peaks.size(); i++) { - if (peaks[i]->x > freq) { + for(int i = 0; i < peaks.size(); i++) { + if(peaks[i]->x > freq) { pos = i; break; } } - if (pos < 0) + if(pos < 0) return; marker_set_pos_source(chIdx, mkIdx, peaks[pos]); @@ -1496,14 +1394,14 @@ void FftDisplayPlot::marker_to_next_lower_freq_peak(uint chIdx, uint mkIdx) int pos = -1; // find the first peak with the freq lower that marker freq pos - for (int i = peaks.size() - 1; i >= 0; i--) { - if (peaks[i]->x < freq) { + for(int i = peaks.size() - 1; i >= 0; i--) { + if(peaks[i]->x < freq) { pos = i; break; } } - if (pos < 0) + if(pos < 0) return; marker_set_pos_source(chIdx, mkIdx, peaks[pos]); @@ -1516,14 +1414,14 @@ void FftDisplayPlot::marker_to_next_higher_mag_peak(uint chIdx, uint mkIdx) int pos = -1; // find the first peak with the magnitude higher than the current marker - for (int i = peaks.size() - 1; i >= 0; i--) { - if (peaks[i]->y > mag) { + for(int i = peaks.size() - 1; i >= 0; i--) { + if(peaks[i]->y > mag) { pos = i; break; } } - if (pos < 0) + if(pos < 0) return; marker_set_pos_source(chIdx, mkIdx, peaks[pos]); @@ -1538,10 +1436,7 @@ void FftDisplayPlot::setStartStop(double start, double stop) setXaxisMajorTicksPos(div.ticks(2)); } -void FftDisplayPlot::setVisiblePeakSearch(bool enabled) -{ - m_visiblePeakSearch = enabled; -} +void FftDisplayPlot::setVisiblePeakSearch(bool enabled) { m_visiblePeakSearch = enabled; } void FftDisplayPlot::marker_to_next_lower_mag_peak(uint chIdx, uint mkIdx) { @@ -1550,41 +1445,37 @@ void FftDisplayPlot::marker_to_next_lower_mag_peak(uint chIdx, uint mkIdx) int pos = -1; // find the first peak with the magnitude lower than the current marker - for (int i = 0; i < peaks.size(); i++) { - if (peaks[i]->y < mag) { + for(int i = 0; i < peaks.size(); i++) { + if(peaks[i]->y < mag) { pos = i; break; } } - if (pos < 0) + if(pos < 0) return; marker_set_pos_source(chIdx, mkIdx, peaks[pos]); } -int FftDisplayPlot::getMarkerPos(const QList& marker_list, - std::shared_ptr &marker) const +int FftDisplayPlot::getMarkerPos(const QList &marker_list, std::shared_ptr &marker) const { int pos = -1; auto it = std::find_if(marker_list.begin(), marker_list.end(), - [&](const struct marker &mrk) { - return mrk.ui == marker; - }); - if (it != marker_list.end()) { + [&](const struct marker &mrk) { return mrk.ui == marker; }); + if(it != marker_list.end()) { pos = it - marker_list.begin(); } return pos; } -void FftDisplayPlot::onMrkCtrlMarkerSelected(std::shared_ptr - &marker) +void FftDisplayPlot::onMrkCtrlMarkerSelected(std::shared_ptr &marker) { - for (uint i = 0; i < d_nplots; i++) { - for (uint j = 0; j < d_markers[i].size(); j++) { - if (d_markers[i][j].ui == marker) { + for(uint i = 0; i < d_nplots; i++) { + for(uint j = 0; j < d_markers[i].size(); j++) { + if(d_markers[i][j].ui == marker) { marker->setSelected(true); Q_EMIT markerSelected(i, j); } else { @@ -1599,25 +1490,25 @@ void FftDisplayPlot::onMrkCtrlMarkerPosChanged(std::shared_ptr & int markerPos = 0; uint chn = -1; - for (uint i = 0; i < d_nplots + n_ref_curves; i++) { + for(uint i = 0; i < d_nplots + n_ref_curves; i++) { markerPos = getMarkerPos(d_markers[i], marker); - if (markerPos >= 0) { + if(markerPos >= 0) { chn = i; break; } } - if (markerPos < 0) { + if(markerPos < 0) { qDebug() << "unknown marker in marker controller"; return; } int bin = posAtFrequency(marker->value().x(), chn); - if (bin < 0) { + if(bin < 0) { qDebug() << "bin should not be negative"; return; } - if (bin >= d_numPoints && chn < d_nplots) { + if(bin >= d_numPoints && chn < d_nplots) { bin = d_numPoints - 1; } @@ -1625,7 +1516,7 @@ void FftDisplayPlot::onMrkCtrlMarkerPosChanged(std::shared_ptr & unsigned int index = -1; double *ydata = nullptr, *xdata = nullptr; - if (chn < d_nplots) { + if(chn < d_nplots) { ydata = y_data[chn]; xdata = x_data; index = chn; @@ -1636,7 +1527,7 @@ void FftDisplayPlot::onMrkCtrlMarkerPosChanged(std::shared_ptr & } double y; - if (ydata) { + if(ydata) { y = ydata[bin]; } else { qDebug() << "problem"; @@ -1652,21 +1543,20 @@ void FftDisplayPlot::onMrkCtrlMarkerPosChanged(std::shared_ptr & marker_set_pos_source(chn, markerPos, marker_data); } -void FftDisplayPlot::onMrkCtrlMarkerReleased(std::shared_ptr - &marker) +void FftDisplayPlot::onMrkCtrlMarkerReleased(std::shared_ptr &marker) { int markerPos = -1; uint chn = -1; - for (uint i = 0; i < d_nplots + n_ref_curves; i++) { + for(uint i = 0; i < d_nplots + n_ref_curves; i++) { markerPos = getMarkerPos(d_markers[i], marker); - if (markerPos >= 0) { + if(markerPos >= 0) { chn = i; break; } } - if (markerPos < 0) { + if(markerPos < 0) { qDebug() << "unknown marker in marker controller"; return; } @@ -1678,8 +1568,8 @@ void FftDisplayPlot::onMrkCtrlMarkerReleased(std::shared_ptr void FftDisplayPlot::selectMarker(uint chIdx, uint mkIdx) { - for (uint i = 0; i < d_nplots; i++) { - for (uint j = 0; j < d_markers[i].size(); j++) { + for(uint i = 0; i < d_nplots; i++) { + for(uint j = 0; j < d_markers[i].size(); j++) { d_markers[i][j].ui->setSelected(false); } } @@ -1690,12 +1580,12 @@ void FftDisplayPlot::selectMarker(uint chIdx, uint mkIdx) int FftDisplayPlot::markerType(uint chIdx, uint mkIdx) const { - if (chIdx >= d_markers.size()) { + if(chIdx >= d_markers.size()) { qDebug() << "Invalid channel index!"; return -1; } - if (mkIdx >= d_markers[chIdx].size()) { + if(mkIdx >= d_markers[chIdx].size()) { qDebug() << "Invalid marker index"; return -1; } @@ -1703,20 +1593,11 @@ int FftDisplayPlot::markerType(uint chIdx, uint mkIdx) const return d_markers[chIdx][mkIdx].data->type; } -double FftDisplayPlot::channelScaleFactor(int chIdx) const -{ - return y_scale_factor[chIdx]; -} +double FftDisplayPlot::channelScaleFactor(int chIdx) const { return y_scale_factor[chIdx]; } -void FftDisplayPlot::setScaleFactor(int chIdx, double scale) -{ - y_scale_factor[chIdx] = scale; -} +void FftDisplayPlot::setScaleFactor(int chIdx, double scale) { y_scale_factor[chIdx] = scale; } -FftDisplayPlot::MagnitudeType FftDisplayPlot::magnitudeType() const -{ - return d_magType; -} +FftDisplayPlot::MagnitudeType FftDisplayPlot::magnitudeType() const { return d_magType; } void FftDisplayPlot::setMagnitudeType(enum MagnitudeType type) { @@ -1738,12 +1619,12 @@ void FftDisplayPlot::setNbOverlappingAverages(unsigned int nb_avg) void FftDisplayPlot::recalculateMagnitudes() { // Check if at least one acquisition has been made - for (unsigned int i = 0; i < d_nplots; i++) { - if (!y_data[i]) + for(unsigned int i = 0; i < d_nplots; i++) { + if(!y_data[i]) return; } - if (d_presetMagType != d_magType) { + if(d_presetMagType != d_magType) { d_magType = d_presetMagType; resetAverageHistory(); } @@ -1759,11 +1640,11 @@ void FftDisplayPlot::recalculateMagnitudes() */ void FftDisplayPlot::detectMarkers() { - for (int i = 0; i < d_nplots + n_ref_curves; i++) { + for(int i = 0; i < d_nplots + n_ref_curves; i++) { calculate_fixed_markers(i); findPeaks(i); - if (d_emitNewMkrData) + if(d_emitNewMkrData) Q_EMIT newMarkerData(); } } diff --git a/gui/src/HistogramDisplayPlot.cc b/gui/src/HistogramDisplayPlot.cc index d5291e502d..6dccd71d50 100644 --- a/gui/src/HistogramDisplayPlot.cc +++ b/gui/src/HistogramDisplayPlot.cc @@ -42,16 +42,19 @@ #ifndef HISTOGRAM_DISPLAY_PLOT_C #define HISTOGRAM_DISPLAY_PLOT_C -#include -#include +#include "HistogramDisplayPlot.h" + +#include + #include +#include +#include +#include +#include + #include #include #include -#include -#include -#include -#include "HistogramDisplayPlot.h" #ifdef _MSC_VER #define copysign _copysign @@ -62,99 +65,70 @@ using namespace scopy; class TimePrecisionClass { public: - TimePrecisionClass(const int timeprecision) - { - d_time_precision = timeprecision; - } - - virtual ~TimePrecisionClass() - { - } - - virtual unsigned int getTimePrecision() const - { - return d_time_precision; - } - - virtual void setTimePrecision(const unsigned int newprecision) - { - d_time_precision = newprecision; - } + TimePrecisionClass(const int timeprecision) { d_time_precision = timeprecision; } + + virtual ~TimePrecisionClass() {} + + virtual unsigned int getTimePrecision() const { return d_time_precision; } + + virtual void setTimePrecision(const unsigned int newprecision) { d_time_precision = newprecision; } + protected: - unsigned int d_time_precision; + unsigned int d_time_precision; }; - -class HistogramDisplayZoomer: public LimitedPlotZoomer, public TimePrecisionClass +class HistogramDisplayZoomer : public LimitedPlotZoomer, public TimePrecisionClass { public: #if QWT_VERSION < 0x060100 - HistogramDisplayZoomer(QwtPlotCanvas* canvas, const unsigned int timeprecision) -#else /* QWT_VERSION < 0x060100 */ - HistogramDisplayZoomer(QWidget* canvas, const unsigned int timeprecision, - QColor c) + HistogramDisplayZoomer(QwtPlotCanvas *canvas, const unsigned int timeprecision) +#else /* QWT_VERSION < 0x060100 */ + HistogramDisplayZoomer(QWidget *canvas, const unsigned int timeprecision, QColor c) #endif /* QWT_VERSION < 0x060100 */ - : LimitedPlotZoomer(canvas),TimePrecisionClass(timeprecision) - { - setTrackerMode(QwtPicker::AlwaysOff); + : LimitedPlotZoomer(canvas) + , TimePrecisionClass(timeprecision) + { + setTrackerMode(QwtPicker::AlwaysOff); #if QWT_VERSION < 0x060000 - setSelectionFlags(QwtPicker::RectSelection | QwtPicker::DragSelection); + setSelectionFlags(QwtPicker::RectSelection | QwtPicker::DragSelection); #endif - setMousePattern(QwtEventPattern::MouseSelect2, - Qt::RightButton, Qt::ControlModifier); - setMousePattern(QwtEventPattern::MouseSelect3, - Qt::RightButton); - - setRubberBandPen(QColor("#999999")); - setTrackerPen(c); + setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); + setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); - setEnabled(false); + setRubberBandPen(QColor("#999999")); + setTrackerPen(c); - } + setEnabled(false); + } - virtual ~HistogramDisplayZoomer() - { - } + virtual ~HistogramDisplayZoomer() {} - virtual void updateTrackerText() - { - updateDisplay(); - } + virtual void updateTrackerText() { updateDisplay(); } - void setUnitType(const std::string &type) - { - d_unit_type = type; - } + void setUnitType(const std::string &type) { d_unit_type = type; } protected: - using QwtPlotZoomer::trackerText; - virtual QwtText trackerText(const QPoint& p) const - { - QwtText t; - QPointF dp = QwtPlotZoomer::invTransform(p); - if((dp.y() > 0.0001) && (dp.y() < 10000)) { - t.setText(QString("%1 V, %2 pts"). - arg(dp.x(), 0, 'f', 2). - arg(dp.y(), 0, 'f', 0)); - } - else { - t.setText(QString("%1 V, %2 pts"). - arg(dp.x(), 0, 'f', 4). - arg(0)); - } - - t.setBackgroundBrush(QBrush(QColor(0, 0, 0 ,155))); - return t; - } + using QwtPlotZoomer::trackerText; + virtual QwtText trackerText(const QPoint &p) const + { + QwtText t; + QPointF dp = QwtPlotZoomer::invTransform(p); + if((dp.y() > 0.0001) && (dp.y() < 10000)) { + t.setText(QString("%1 V, %2 pts").arg(dp.x(), 0, 'f', 2).arg(dp.y(), 0, 'f', 0)); + } else { + t.setText(QString("%1 V, %2 pts").arg(dp.x(), 0, 'f', 4).arg(0)); + } + + t.setBackgroundBrush(QBrush(QColor(0, 0, 0, 155))); + return t; + } private: - std::string d_unit_type; + std::string d_unit_type; }; - - -Histogram::Histogram(const QString& title, const QColor& color) +Histogram::Histogram(const QString &title, const QColor &color) : QwtPlotHistogram(title) { setStyle(QwtPlotHistogram::Columns); @@ -162,23 +136,21 @@ Histogram::Histogram(const QString& title, const QColor& color) setColor(color); } -void -Histogram::setColor(const QColor& color) +void Histogram::setColor(const QColor &color) { QColor c = color; c.setAlpha(255 / 2); setBrush(QBrush(c)); } -void -Histogram::setValues(const double *xData, const double *yData, unsigned int nr_bins) +void Histogram::setValues(const double *xData, const double *yData, unsigned int nr_bins) { QVector samples(nr_bins - 1); - if (m_samples.size() != samples.size()) { + if(m_samples.size() != samples.size()) { m_samples.clear(); m_samples.resize(samples.size()); } - for (unsigned int i = 0; i < nr_bins - 1; ++i) { + for(unsigned int i = 0; i < nr_bins - 1; ++i) { QwtInterval interval(xData[i], xData[i + 1]); interval.setBorderFlags(QwtInterval::IncludeBorders); @@ -192,12 +164,12 @@ Histogram::setValues(const double *xData, const double *yData, unsigned int nr_b void Histogram::setOrientation(Qt::Orientation orientation) { - if (this->orientation() == orientation) { + if(this->orientation() == orientation) { return; } QwtPlotSeriesItem::setOrientation(orientation); - for (int i = 0; i < m_samples.size(); ++i) { + for(int i = 0; i < m_samples.size(); ++i) { m_samples[i].value = (-1) * m_samples[i].value; } setData(new QwtIntervalSeriesData(m_samples)); @@ -207,7 +179,7 @@ int Histogram::getMaxHeight() { double max_h = 0; int sign = orientation() == Qt::Horizontal ? -1 : 1; - for (int i = 0; i < m_samples.size(); ++i) { + for(int i = 0; i < m_samples.size(); ++i) { max_h = std::max(max_h, sign * m_samples[i].value); } return max_h; @@ -216,129 +188,122 @@ int Histogram::getMaxHeight() /*********************************************************************** * Main Time domain plotter widget **********************************************************************/ -HistogramDisplayPlot::HistogramDisplayPlot(int nplots, QWidget* parent) - : DisplayPlot(nplots, parent) -{ - d_bins = 100; - d_accum = false; - d_height = 0; - stop = false; - d_orientation = Qt::Horizontal; - d_minPos = 0; - d_maxPos = 0; - d_zoomed = false; - d_xmin = 1e20; - d_xmax = -1e20; - - setLeftVertAxesCount(2); - - // Initialize x-axis data array - d_xdata = new double[d_bins]; - memset(d_xdata, 0x0, d_bins*sizeof(double)); - - d_semilogx = false; - d_semilogy = false; - d_autoscale_state = false; - d_autoscalex_state = false; - - setAxesCount(QwtAxis::XBottom, 2); - horizAxes.resize(2); - d_pf = new MetricPrefixFormatter(); - d_pf->setTwoDecimalMode(true); - for (int i = 0; i < 2; ++i) { - horizAxes[i] = new PlotAxisConfiguration(QwtAxis::XBottom, i, this); - configureAxis(QwtAxis::XBottom, i); - setAxisVisible(QwtAxisId(QwtAxis::XBottom, i), - d_usingLeftAxisScales); - connect(axisWidget(horizAxes[i]->axis()), SIGNAL(scaleDivChanged()), - this, SLOT(_onXbottomAxisWidgetScaleDivChanged())); - QwtScaleWidget *scaleWidget = axisWidget(QwtAxisId(QwtAxis::XBottom, i)); - OscScaleDraw* osd = dynamic_cast(scaleWidget->scaleDraw()); - osd->setFormatter(d_pf); - osd->setUnitType("V"); - osd->setFloatPrecision(2); - osd->setColor(d_CurveColors[i]); - const int fmw = QFontMetrics(scaleWidget->font()).horizontalAdvance("-XX.XX XX"); - scaleWidget->setMinBorderDist(fmw / 2, fmw / 2); - } - for (int i = 0; i < 2; ++i) { - HistogramScaleDraw *hsd = new HistogramScaleDraw(); - hsd->setColor(d_CurveColors[i]); - setAxisScaleDraw(QwtAxisId(QwtAxis::YLeft, i), hsd); - } - - this->_updateXScales(100); - - // Setup dataPoints and plot vectors - // Automatically deleted when parent is deleted - for(int i = 0; i < d_nplots; i++) { - d_ydata.push_back(new double[d_bins]); - memset(d_ydata[i], 0, d_bins*sizeof(double)); - - d_histograms.push_back(new Histogram(QString("Data %1").arg(i), d_CurveColors[i])); - d_histograms[i]->setXAxis(QwtAxisId(QwtAxis::XBottom, i)); - d_histograms[i]->setYAxis(QwtAxisId(QwtAxis::YLeft, i)); - d_histograms[i]->setOrientation(Qt::Horizontal); - d_histograms[i]->attach(this); - - - d_plot_curve.push_back(new QwtPlotCurve(QString("Data %1").arg(i))); - // d_plot_curve[i]->attach(this); - d_plot_curve[i]->setPen(QPen(d_CurveColors[i])); - d_plot_curve[i]->setRenderHint(QwtPlotItem::RenderAntialiased); - - // Adjust color's transparency for the brush - d_CurveColors[i].setAlpha(127 / d_nplots); - d_plot_curve[i]->setBrush(QBrush(d_CurveColors[i])); - - d_CurveColors[i].setAlpha(255 / d_nplots); - QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, - QBrush(d_CurveColors[i]), - QPen(d_CurveColors[i]), QSize(7,7)); +HistogramDisplayPlot::HistogramDisplayPlot(int nplots, QWidget *parent) + : DisplayPlot(nplots, parent) +{ + d_bins = 100; + d_accum = false; + d_height = 0; + stop = false; + d_orientation = Qt::Horizontal; + d_minPos = 0; + d_maxPos = 0; + d_zoomed = false; + d_xmin = 1e20; + d_xmax = -1e20; + + setLeftVertAxesCount(2); + + // Initialize x-axis data array + d_xdata = new double[d_bins]; + memset(d_xdata, 0x0, d_bins * sizeof(double)); + + d_semilogx = false; + d_semilogy = false; + d_autoscale_state = false; + d_autoscalex_state = false; + + setAxesCount(QwtAxis::XBottom, 2); + horizAxes.resize(2); + d_pf = new MetricPrefixFormatter(); + d_pf->setTwoDecimalMode(true); + for(int i = 0; i < 2; ++i) { + horizAxes[i] = new PlotAxisConfiguration(QwtAxis::XBottom, i, this); + configureAxis(QwtAxis::XBottom, i); + setAxisVisible(QwtAxisId(QwtAxis::XBottom, i), d_usingLeftAxisScales); + connect(axisWidget(horizAxes[i]->axis()), SIGNAL(scaleDivChanged()), this, + SLOT(_onXbottomAxisWidgetScaleDivChanged())); + QwtScaleWidget *scaleWidget = axisWidget(QwtAxisId(QwtAxis::XBottom, i)); + OscScaleDraw *osd = dynamic_cast(scaleWidget->scaleDraw()); + osd->setFormatter(d_pf); + osd->setUnitType("V"); + osd->setFloatPrecision(2); + osd->setColor(d_CurveColors[i]); + const int fmw = QFontMetrics(scaleWidget->font()).horizontalAdvance("-XX.XX XX"); + scaleWidget->setMinBorderDist(fmw / 2, fmw / 2); + } + for(int i = 0; i < 2; ++i) { + HistogramScaleDraw *hsd = new HistogramScaleDraw(); + hsd->setColor(d_CurveColors[i]); + setAxisScaleDraw(QwtAxisId(QwtAxis::YLeft, i), hsd); + } + + this->_updateXScales(100); + + // Setup dataPoints and plot vectors + // Automatically deleted when parent is deleted + for(int i = 0; i < d_nplots; i++) { + d_ydata.push_back(new double[d_bins]); + memset(d_ydata[i], 0, d_bins * sizeof(double)); + + d_histograms.push_back(new Histogram(QString("Data %1").arg(i), d_CurveColors[i])); + d_histograms[i]->setXAxis(QwtAxisId(QwtAxis::XBottom, i)); + d_histograms[i]->setYAxis(QwtAxisId(QwtAxis::YLeft, i)); + d_histograms[i]->setOrientation(Qt::Horizontal); + d_histograms[i]->attach(this); + + d_plot_curve.push_back(new QwtPlotCurve(QString("Data %1").arg(i))); + // d_plot_curve[i]->attach(this); + d_plot_curve[i]->setPen(QPen(d_CurveColors[i])); + d_plot_curve[i]->setRenderHint(QwtPlotItem::RenderAntialiased); + + // Adjust color's transparency for the brush + d_CurveColors[i].setAlpha(127 / d_nplots); + d_plot_curve[i]->setBrush(QBrush(d_CurveColors[i])); + + d_CurveColors[i].setAlpha(255 / d_nplots); + QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(d_CurveColors[i]), QPen(d_CurveColors[i]), + QSize(7, 7)); #if QWT_VERSION < 0x060000 - d_plot_curve[i]->setRawData(d_xdata, d_ydata[i], d_bins); - d_plot_curve[i]->setSymbol(*symbol); + d_plot_curve[i]->setRawData(d_xdata, d_ydata[i], d_bins); + d_plot_curve[i]->setSymbol(*symbol); #else - d_plot_curve[i]->setRawSamples(d_xdata, d_ydata[i], d_bins); - d_plot_curve[i]->setSymbol(symbol); + d_plot_curve[i]->setRawSamples(d_xdata, d_ydata[i], d_bins); + d_plot_curve[i]->setSymbol(symbol); #endif - } - - for (unsigned int i = 0; i < d_histograms.size(); ++i) { - d_zoomer.push_back(new HistogramDisplayZoomer(canvas(), 0, - getLineColor(i))); - d_zoomer[i]->setAxes(QwtAxisId(QwtAxis::XBottom, i), - QwtAxisId(QwtAxis::YLeft, i)); + } - connect(d_zoomer[i], SIGNAL(zoomed(QRectF)), - this, SLOT(_onZoom(QRectF))); - } + for(unsigned int i = 0; i < d_histograms.size(); ++i) { + d_zoomer.push_back(new HistogramDisplayZoomer(canvas(), 0, getLineColor(i))); + d_zoomer[i]->setAxes(QwtAxisId(QwtAxis::XBottom, i), QwtAxisId(QwtAxis::YLeft, i)); + connect(d_zoomer[i], SIGNAL(zoomed(QRectF)), this, SLOT(_onZoom(QRectF))); + } - _resetXAxisPoints(-1, 1); + _resetXAxisPoints(-1, 1); - for (unsigned int i = 0; i < d_histograms.size(); ++i) { - setAxisScale(QwtAxisId(QwtAxis::XBottom, i), 0, 100); - setAxisScale(QwtAxisId(QwtAxis::YLeft, i), -10, 10); - } + for(unsigned int i = 0; i < d_histograms.size(); ++i) { + setAxisScale(QwtAxisId(QwtAxis::XBottom, i), 0, 100); + setAxisScale(QwtAxisId(QwtAxis::YLeft, i), -10, 10); + } - setAxisVisible(QwtAxisId(QwtAxis::YLeft, 0), false); - setAxisVisible(QwtAxisId(QwtAxis::YLeft, 1), false); - setAxisVisible(QwtAxisId(QwtAxis::XBottom, 0), false); - setAxisVisible(QwtAxisId(QwtAxis::XBottom, 1), false); + setAxisVisible(QwtAxisId(QwtAxis::YLeft, 0), false); + setAxisVisible(QwtAxisId(QwtAxis::YLeft, 1), false); + setAxisVisible(QwtAxisId(QwtAxis::XBottom, 0), false); + setAxisVisible(QwtAxisId(QwtAxis::XBottom, 1), false); - insertLegend(nullptr); + insertLegend(nullptr); - d_grid->detach(); - for(QwtPlotScaleItem* scale : qAsConst(scaleItems)){ - scale->detach(); - } + d_grid->detach(); + for(QwtPlotScaleItem *scale : qAsConst(scaleItems)) { + scale->detach(); + } } void HistogramDisplayPlot::_onZoom(const QRectF &rect) { - QwtPlotZoomer *zoomer = static_cast(sender()); + QwtPlotZoomer *zoomer = static_cast(sender()); d_zoomed = (rect != zoomer->zoomBase()); } @@ -346,18 +311,18 @@ void HistogramDisplayPlot::setOrientation(Qt::Orientation orientation) { d_orientation = orientation; - for (size_t i = 0; i < d_histograms.size(); ++i) { + for(size_t i = 0; i < d_histograms.size(); ++i) { d_histograms[i]->setOrientation(orientation); } - if (orientation == Qt::Vertical) { + if(orientation == Qt::Vertical) { d_grid->attach(this); - for(QwtPlotScaleItem* scale : qAsConst(scaleItems)){ + for(QwtPlotScaleItem *scale : qAsConst(scaleItems)) { scale->attach(this); } } else { d_grid->detach(); - for(QwtPlotScaleItem* scale : qAsConst(scaleItems)){ + for(QwtPlotScaleItem *scale : qAsConst(scaleItems)) { scale->detach(); } } @@ -367,8 +332,7 @@ void HistogramDisplayPlot::setOrientation(Qt::Orientation orientation) QwtInterval xInt2 = axisInterval(QwtAxisId(QwtAxis::XBottom, 1)); QwtInterval yInt2 = axisInterval(QwtAxisId(QwtAxis::YLeft, 1)); - - if (orientation == Qt::Vertical) { + if(orientation == Qt::Vertical) { setAxisScale(QwtAxisId(QwtAxis::XBottom, 0), yInt.minValue(), yInt.maxValue()); setAxisScale(QwtAxisId(QwtAxis::YLeft, 0), xInt.maxValue(), -xInt.minValue()); setAxisScale(QwtAxisId(QwtAxis::XBottom, 1), yInt2.minValue(), yInt2.maxValue()); @@ -391,15 +355,9 @@ void HistogramDisplayPlot::setOrientation(Qt::Orientation orientation) replot(); } -Qt::Orientation HistogramDisplayPlot::getOrientation() -{ - return d_orientation; -} +Qt::Orientation HistogramDisplayPlot::getOrientation() { return d_orientation; } -bool HistogramDisplayPlot::isZoomed() -{ - return d_zoomed; -} +bool HistogramDisplayPlot::isZoomed() { return d_zoomed; } HistogramDisplayPlot::~HistogramDisplayPlot() { @@ -412,17 +370,16 @@ HistogramDisplayPlot::~HistogramDisplayPlot() delete d_pf; delete[] d_xdata; - // d_zoomer and _panner deleted when parent deleted + // d_zoomer and _panner deleted when parent deleted } -void -HistogramDisplayPlot::enableChannel(unsigned int chIdx, bool enable) +void HistogramDisplayPlot::enableChannel(unsigned int chIdx, bool enable) { - if (chIdx < 0 || chIdx > 1) { + if(chIdx < 0 || chIdx > 1) { return; } - if (enable) { + if(enable) { d_histograms[chIdx]->attach(this); } else { d_histograms[chIdx]->detach(); @@ -432,26 +389,25 @@ HistogramDisplayPlot::enableChannel(unsigned int chIdx, bool enable) void HistogramDisplayPlot::setYaxisSpan(unsigned int chIdx, double bot, double top) { - if (chIdx < 0 || chIdx > 1) { + if(chIdx < 0 || chIdx > 1) { return; } - if (d_orientation == Qt::Vertical) { + if(d_orientation == Qt::Vertical) { setAxisScale(QwtAxisId(QwtAxis::XBottom, chIdx), bot, top); return; } setAxisScale(QwtAxisId(QwtAxis::YLeft, chIdx), bot, top); - } void HistogramDisplayPlot::setXaxisSpan(double start, double stop) { - if (d_orientation == Qt::Vertical) { + if(d_orientation == Qt::Vertical) { return; } - for (size_t i = 0; i < d_histograms.size(); ++i) { + for(size_t i = 0; i < d_histograms.size(); ++i) { setAxisScale(QwtAxisId(QwtAxis::XBottom, i), start, stop); } } @@ -462,217 +418,198 @@ void HistogramDisplayPlot::setDataInterval(int min, int max) d_maxPos = max; } -void -HistogramDisplayPlot::replot() -{ - BasicPlot::replot(); -} - -void -HistogramDisplayPlot::plotNewData(const std::vector dataPoints, - const int64_t numDataPoints, - const double timeInterval) -{ - if(!d_stop) { - if((numDataPoints > 0)) { - - _updateXScales(numDataPoints); - if (d_minPos < 0) { - d_minPos = 0; - } - if (d_maxPos > numDataPoints || d_maxPos == 0) { - d_maxPos = numDataPoints; - } - if (d_minPos > d_maxPos) { - d_minPos = 0; - d_maxPos = numDataPoints; - } - - // keep track of the min/max values for when autoscaleX is called. - double xminTemp = 1e20; - double xmaxTemp = -1e20; - for(int n = 0; n < d_nplots; n++) { - xminTemp = std::min(xminTemp, *std::min_element(dataPoints[n] + d_minPos, dataPoints[n]+d_maxPos)); - xmaxTemp = std::max(xmaxTemp, *std::max_element(dataPoints[n] + d_minPos, dataPoints[n]+d_maxPos)); - } - - const double EPS = 0.1; - if (std::abs(xminTemp - d_xmin) > EPS || - std::abs(xmaxTemp - d_xmax) > EPS) { - if (d_minPos == 0 && d_maxPos == numDataPoints) { - d_autoscalex_state = true; - } - } - d_xmin = xminTemp; - d_xmax = xmaxTemp; - - // If autoscalex has been clicked, clear the data for the new - // bin widths and reset the x-axis. - if(d_autoscalex_state) { - for(int n = 0; n < d_nplots; n++) - memset(d_ydata[n], 0, d_bins*sizeof(double)); - _resetXAxisPoints(d_xmin, d_xmax); - d_autoscalex_state = false; - } - - int index; - for(int n = 0; n < d_nplots; n++) { - if(!d_accum) - memset(d_ydata[n], 0, d_bins*sizeof(double)); - for(int64_t point = d_minPos; point < d_maxPos; point++) { - index = round(1e-20 + (dataPoints[n][point] - d_left)/d_width); - if((index >= 0) && (index < d_bins)) - d_ydata[n][index] += 1; - } - d_histograms[n]->setValues(d_xdata, d_ydata[n], d_bins); - } - - double height = 0; - double histogramHeights[d_nplots]; - for(int n = 0; n < d_nplots; n++) { - histogramHeights[n] = *std::max_element(d_ydata[n], d_ydata[n]+d_bins); - } - for (int n = 0; n < d_nplots - 1; n++) { - if (histogramHeights[n] != 0) { - height = histogramHeights[n]; - break; - } - } - for (int n = 0; n < d_nplots; n++) { - if (d_histograms[n]->plot()) { - height = std::min(height, histogramHeights[n]); - } - } - - d_height = height; - - if (d_orientation == Qt::Vertical) { - for (size_t i = 0; i < d_histograms.size(); ++i) { - double h = histogramHeights[i] + (0.2 * histogramHeights[i]); - if (h > numDataPoints) { - h = numDataPoints; - } - double pr = h * 0.15; - - if (abs(h - axisInterval(QwtAxisId(QwtAxis::YLeft, i)).maxValue()) > pr) { - setAxisScale(QwtAxisId(QwtAxis::YLeft, i), 0, h); - } - } - } - - if(d_autoscale_state) { - _autoScaleY(0, height); - } - - setXaxisSpan(-d_height, 0); - - replot(); - - } - } +void HistogramDisplayPlot::replot() { BasicPlot::replot(); } + +void HistogramDisplayPlot::plotNewData(const std::vector dataPoints, const int64_t numDataPoints, + const double timeInterval) +{ + if(!d_stop) { + if((numDataPoints > 0)) { + + _updateXScales(numDataPoints); + if(d_minPos < 0) { + d_minPos = 0; + } + if(d_maxPos > numDataPoints || d_maxPos == 0) { + d_maxPos = numDataPoints; + } + if(d_minPos > d_maxPos) { + d_minPos = 0; + d_maxPos = numDataPoints; + } + + // keep track of the min/max values for when autoscaleX is called. + double xminTemp = 1e20; + double xmaxTemp = -1e20; + for(int n = 0; n < d_nplots; n++) { + xminTemp = + std::min(xminTemp, + *std::min_element(dataPoints[n] + d_minPos, dataPoints[n] + d_maxPos)); + xmaxTemp = + std::max(xmaxTemp, + *std::max_element(dataPoints[n] + d_minPos, dataPoints[n] + d_maxPos)); + } + + const double EPS = 0.1; + if(std::abs(xminTemp - d_xmin) > EPS || std::abs(xmaxTemp - d_xmax) > EPS) { + if(d_minPos == 0 && d_maxPos == numDataPoints) { + d_autoscalex_state = true; + } + } + d_xmin = xminTemp; + d_xmax = xmaxTemp; + + // If autoscalex has been clicked, clear the data for the new + // bin widths and reset the x-axis. + if(d_autoscalex_state) { + for(int n = 0; n < d_nplots; n++) + memset(d_ydata[n], 0, d_bins * sizeof(double)); + _resetXAxisPoints(d_xmin, d_xmax); + d_autoscalex_state = false; + } + + int index; + for(int n = 0; n < d_nplots; n++) { + if(!d_accum) + memset(d_ydata[n], 0, d_bins * sizeof(double)); + for(int64_t point = d_minPos; point < d_maxPos; point++) { + index = round(1e-20 + (dataPoints[n][point] - d_left) / d_width); + if((index >= 0) && (index < d_bins)) + d_ydata[n][index] += 1; + } + d_histograms[n]->setValues(d_xdata, d_ydata[n], d_bins); + } + + double height = 0; + double histogramHeights[d_nplots]; + for(int n = 0; n < d_nplots; n++) { + histogramHeights[n] = *std::max_element(d_ydata[n], d_ydata[n] + d_bins); + } + for(int n = 0; n < d_nplots - 1; n++) { + if(histogramHeights[n] != 0) { + height = histogramHeights[n]; + break; + } + } + for(int n = 0; n < d_nplots; n++) { + if(d_histograms[n]->plot()) { + height = std::min(height, histogramHeights[n]); + } + } + + d_height = height; + + if(d_orientation == Qt::Vertical) { + for(size_t i = 0; i < d_histograms.size(); ++i) { + double h = histogramHeights[i] + (0.2 * histogramHeights[i]); + if(h > numDataPoints) { + h = numDataPoints; + } + double pr = h * 0.15; + + if(abs(h - axisInterval(QwtAxisId(QwtAxis::YLeft, i)).maxValue()) > pr) { + setAxisScale(QwtAxisId(QwtAxis::YLeft, i), 0, h); + } + } + } + + if(d_autoscale_state) { + _autoScaleY(0, height); + } + + setXaxisSpan(-d_height, 0); + + replot(); + } + } } -void -HistogramDisplayPlot::newData(const QEvent* updateEvent) +void HistogramDisplayPlot::newData(const QEvent *updateEvent) { - HistogramUpdateEvent *hevent = (HistogramUpdateEvent*)updateEvent; - const std::vector dataPoints = hevent->getDataPoints(); - const uint64_t numDataPoints = hevent->getNumDataPoints(); + HistogramUpdateEvent *hevent = (HistogramUpdateEvent *)updateEvent; + const std::vector dataPoints = hevent->getDataPoints(); + const uint64_t numDataPoints = hevent->getNumDataPoints(); - plotNewData(dataPoints, - numDataPoints, - 0); + plotNewData(dataPoints, numDataPoints, 0); } -void -HistogramDisplayPlot::customEvent(QEvent * e) +void HistogramDisplayPlot::customEvent(QEvent *e) { - if(e->type() == HistogramUpdateEvent::Type()) { - newData(e); - } + if(e->type() == HistogramUpdateEvent::Type()) { + newData(e); + } } -void -HistogramDisplayPlot::setXaxis(double min, double max) -{ - _resetXAxisPoints(min, max); -} +void HistogramDisplayPlot::setXaxis(double min, double max) { _resetXAxisPoints(min, max); } -void -HistogramDisplayPlot::_resetXAxisPoints(double left, double right) +void HistogramDisplayPlot::_resetXAxisPoints(double left, double right) { // Something's wrong with the data (NaN, Inf, or something else) - if((left == 0 && right == 0) || (left > right)) - { + if((left == 0 && right == 0) || (left > right)) { // assume some default values d_left = -0.01; d_right = 0.01; qDebug() << "Using default values for histogram"; - // throw std::runtime_error("HistogramDisplayPlot::_resetXAxisPoints left and/or right values are invalid"); - } - else - { - d_left = left *(1 - copysign(0.1, left)); - d_right = right*(1 + copysign(0.1, right)); + // throw std::runtime_error("HistogramDisplayPlot::_resetXAxisPoints left and/or right values are + // invalid"); + } else { + d_left = left * (1 - copysign(0.1, left)); + d_right = right * (1 + copysign(0.1, right)); } // when both left & right are 0 - d_width = (d_right - d_left)/(d_bins); - for(long loc = 0; loc < d_bins; loc++){ - d_xdata[loc] = d_left + loc*d_width; - } + d_width = (d_right - d_left) / (d_bins); + for(long loc = 0; loc < d_bins; loc++) { + d_xdata[loc] = d_left + loc * d_width; + } #if QWT_VERSION < 0x060100 - axisScaleDiv(QwtAxis::XBottom)->setInterval(d_left, d_right); -#else /* QWT_VERSION < 0x060100 */ - QwtScaleDiv scalediv(d_left, d_right); - setAxisScaleDiv(QwtAxis::XBottom, scalediv); + axisScaleDiv(QwtAxis::XBottom)->setInterval(d_left, d_right); +#else /* QWT_VERSION < 0x060100 */ + QwtScaleDiv scalediv(d_left, d_right); + setAxisScaleDiv(QwtAxis::XBottom, scalediv); #endif /* QWT_VERSION < 0x060100 */ - // Set up zoomer base for maximum unzoom x-axis - // and reset to maximum unzoom level - QRectF zbase = d_zoomer[0]->zoomBase(); - - if(d_semilogx) { - setAxisScale(QwtAxis::XBottom, 1e-1, d_right); - zbase.setLeft(1e-1); - } - else { - setAxisScale(QwtAxis::XBottom, d_left, d_right); - zbase.setLeft(d_left); - } - - zbase.setRight(d_right); -// d_zoomer[0]->zoom(zbase); -// d_zoomer[0]->setZoomBase(zbase); -// d_zoomer[0]->zoom(0); + // Set up zoomer base for maximum unzoom x-axis + // and reset to maximum unzoom level + QRectF zbase = d_zoomer[0]->zoomBase(); + + if(d_semilogx) { + setAxisScale(QwtAxis::XBottom, 1e-1, d_right); + zbase.setLeft(1e-1); + } else { + setAxisScale(QwtAxis::XBottom, d_left, d_right); + zbase.setLeft(d_left); + } + + zbase.setRight(d_right); + // d_zoomer[0]->zoom(zbase); + // d_zoomer[0]->setZoomBase(zbase); + // d_zoomer[0]->zoom(0); } -void -HistogramDisplayPlot::_autoScaleY(double bottom, double top) -{ - // Auto scale the y-axis with a margin of 20% (10 dB for log scale) - double b = bottom - fabs(bottom)*0.20; - double t = top + fabs(top)*0.20; - if(d_semilogy) { - if(bottom > 0) { - setYaxis(b-10, t+10); - } - else { - setYaxis(1e-3, t+10); - } - } - else { - setYaxis(b, t); - } +void HistogramDisplayPlot::_autoScaleY(double bottom, double top) +{ + // Auto scale the y-axis with a margin of 20% (10 dB for log scale) + double b = bottom - fabs(bottom) * 0.20; + double t = top + fabs(top) * 0.20; + if(d_semilogy) { + if(bottom > 0) { + setYaxis(b - 10, t + 10); + } else { + setYaxis(1e-3, t + 10); + } + } else { + setYaxis(b, t); + } } void HistogramDisplayPlot::_updateXScales(unsigned int totalSamples) { - for (size_t i = 0; i < d_histograms.size(); ++i) { - HistogramScaleDraw *hsd = dynamic_cast( - axisWidget(QwtAxisId(QwtAxis::YLeft, i))->scaleDraw()); - if (hsd) { + for(size_t i = 0; i < d_histograms.size(); ++i) { + HistogramScaleDraw *hsd = + dynamic_cast(axisWidget(QwtAxisId(QwtAxis::YLeft, i))->scaleDraw()); + if(hsd) { hsd->setTotalSamples(totalSamples); hsd->invalidateCache(); } @@ -681,46 +618,44 @@ void HistogramDisplayPlot::_updateXScales(unsigned int totalSamples) void HistogramDisplayPlot::_orientationChanged() { - if (d_orientation == Qt::Horizontal) { + if(d_orientation == Qt::Horizontal) { int min_h = d_histograms[0]->getMaxHeight(); - for (size_t i = 1; i < d_histograms.size(); ++i) { + for(size_t i = 1; i < d_histograms.size(); ++i) { min_h = std::min(min_h, d_histograms[i]->getMaxHeight()); } - for (size_t i = 0; i < d_histograms.size(); ++i) { + for(size_t i = 0; i < d_histograms.size(); ++i) { setAxisScale(QwtAxisId(QwtAxis::XBottom, i), -min_h, 0); } } else { - //big histogram - for (size_t i = 0; i < d_histograms.size(); ++i) { + // big histogram + for(size_t i = 0; i < d_histograms.size(); ++i) { int h = d_histograms[i]->getMaxHeight(); h += h * 0.2; setAxisScale(QwtAxisId(QwtAxis::YLeft, i), 0, h); } } - for (int i = 0; i < d_zoomer.size(); ++i) { - d_zoomer[i]->setEnabled(d_orientation == Qt::Horizontal - ? false : true); + for(int i = 0; i < d_zoomer.size(); ++i) { + d_zoomer[i]->setEnabled(d_orientation == Qt::Horizontal ? false : true); } } void HistogramDisplayPlot::_resetZoom() { - for (int i = 0; i < d_zoomer.size(); ++i) { - static_cast(d_zoomer[i])->resetZoom(); + for(int i = 0; i < d_zoomer.size(); ++i) { + static_cast(d_zoomer[i])->resetZoom(); } } void HistogramDisplayPlot::setSelectedChannel(unsigned int value) { - if (value >= d_histograms.size()) { + if(value >= d_histograms.size()) { return; } - for (int i = 0; i < d_zoomer.size(); ++i) { - d_zoomer[i]->setTrackerMode( - (i == value) ? QwtPicker::AlwaysOn : QwtPicker::AlwaysOff); + for(int i = 0; i < d_zoomer.size(); ++i) { + d_zoomer[i]->setTrackerMode((i == value) ? QwtPicker::AlwaysOn : QwtPicker::AlwaysOff); } d_selected_channel = value; @@ -728,183 +663,165 @@ void HistogramDisplayPlot::setSelectedChannel(unsigned int value) d_histograms[value]->detach(); d_histograms[value]->attach(this); - if (d_orientation == Qt::Horizontal) { + if(d_orientation == Qt::Horizontal) { return; } - for (size_t i = 0; i < d_histograms.size(); ++i) { + for(size_t i = 0; i < d_histograms.size(); ++i) { setAxisVisible(QwtAxisId(QwtAxis::YLeft, i), value == i); setAxisVisible(QwtAxisId(QwtAxis::XBottom, i), value == i); } } -void -HistogramDisplayPlot::setAutoScaleX() +void HistogramDisplayPlot::setAutoScaleX() { if(d_orientation == Qt::Horizontal) { d_autoscalex_state = true; } } -void -HistogramDisplayPlot::setAutoScale(bool state) -{ - d_autoscale_state = state; -} +void HistogramDisplayPlot::setAutoScale(bool state) { d_autoscale_state = state; } -void -HistogramDisplayPlot::setSemilogx(bool en) +void HistogramDisplayPlot::setSemilogx(bool en) { - d_semilogx = en; - if(!d_semilogx) { - setAxisScaleEngine(QwtAxis::XBottom, new QwtLinearScaleEngine); - } - else { + d_semilogx = en; + if(!d_semilogx) { + setAxisScaleEngine(QwtAxis::XBottom, new QwtLinearScaleEngine); + } else { #if QWT_VERSION < 0x060100 - setAxisScaleEngine(QwtAxis::XBottom, new QwtLog10ScaleEngine); -#else /* QWT_VERSION < 0x060100 */ - setAxisScaleEngine(QwtAxis::XBottom, new QwtLogScaleEngine); + setAxisScaleEngine(QwtAxis::XBottom, new QwtLog10ScaleEngine); +#else /* QWT_VERSION < 0x060100 */ + setAxisScaleEngine(QwtAxis::XBottom, new QwtLogScaleEngine); #endif /* QWT_VERSION < 0x060100 */ - } + } } -void -HistogramDisplayPlot::setSemilogy(bool en) +void HistogramDisplayPlot::setSemilogy(bool en) { - if(d_semilogy != en) { - d_semilogy = en; + if(d_semilogy != en) { + d_semilogy = en; #if QWT_VERSION < 0x060100 - double max = axisScaleDiv(QwtAxis::YLeft)->upperBound(); -#else /* QWT_VERSION < 0x060100 */ - double max = axisScaleDiv(QwtAxis::YLeft).upperBound(); + double max = axisScaleDiv(QwtAxis::YLeft)->upperBound(); +#else /* QWT_VERSION < 0x060100 */ + double max = axisScaleDiv(QwtAxis::YLeft).upperBound(); #endif /* QWT_VERSION < 0x060100 */ - if(!d_semilogy) { - setAxisScaleEngine(QwtAxis::YLeft, new QwtLinearScaleEngine); - setYaxis(-pow(10.0, max/10.0), pow(10.0, max/10.0)); - } - else { + if(!d_semilogy) { + setAxisScaleEngine(QwtAxis::YLeft, new QwtLinearScaleEngine); + setYaxis(-pow(10.0, max / 10.0), pow(10.0, max / 10.0)); + } else { #if QWT_VERSION < 0x060100 - setAxisScaleEngine(QwtAxis::YLeft, new QwtLog10ScaleEngine); -#else /* QWT_VERSION < 0x060100 */ - setAxisScaleEngine(QwtAxis::YLeft, new QwtLogScaleEngine); + setAxisScaleEngine(QwtAxis::YLeft, new QwtLog10ScaleEngine); +#else /* QWT_VERSION < 0x060100 */ + setAxisScaleEngine(QwtAxis::YLeft, new QwtLogScaleEngine); #endif /* QWT_VERSION < 0x060100 */ - setYaxis(1e-10, 10.0*log10(100*max)); - } - } + setYaxis(1e-10, 10.0 * log10(100 * max)); + } + } } -void -HistogramDisplayPlot::setAccumulate(bool state) -{ - d_accum = state; -} +void HistogramDisplayPlot::setAccumulate(bool state) { d_accum = state; } -void -HistogramDisplayPlot::setMarkerAlpha(int which, int alpha) +void HistogramDisplayPlot::setMarkerAlpha(int which, int alpha) { - if(which < d_nplots) { - // Get the pen color - QPen pen(d_plot_curve[which]->pen()); - QBrush brush(d_plot_curve[which]->brush()); - QColor color = brush.color(); + if(which < d_nplots) { + // Get the pen color + QPen pen(d_plot_curve[which]->pen()); + QBrush brush(d_plot_curve[which]->brush()); + QColor color = brush.color(); - // Set new alpha and update pen - color.setAlpha(alpha); - brush.setColor(color); - color.setAlpha(std::min(255, static_cast(alpha*1.5))); - pen.setColor(color); - d_plot_curve[which]->setBrush(brush); - d_plot_curve[which]->setPen(pen); + // Set new alpha and update pen + color.setAlpha(alpha); + brush.setColor(color); + color.setAlpha(std::min(255, static_cast(alpha * 1.5))); + pen.setColor(color); + d_plot_curve[which]->setBrush(brush); + d_plot_curve[which]->setPen(pen); - // And set the new color for the markers + // And set the new color for the markers #if QWT_VERSION < 0x060000 - QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); - setLineMarker(which, sym.style()); + QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); + setLineMarker(which, sym.style()); #else - QwtSymbol *sym = (QwtSymbol*)d_plot_curve[which]->symbol(); - if(sym) { - sym->setColor(color); - sym->setPen(pen); - d_plot_curve[which]->setSymbol(sym); - } + QwtSymbol *sym = (QwtSymbol *)d_plot_curve[which]->symbol(); + if(sym) { + sym->setColor(color); + sym->setPen(pen); + d_plot_curve[which]->setSymbol(sym); + } #endif - } + } } -int -HistogramDisplayPlot::getMarkerAlpha(int which) const +int HistogramDisplayPlot::getMarkerAlpha(int which) const { - if(which < d_nplots) { - return d_plot_curve[which]->brush().color().alpha(); - } - else { - return 0; - } + if(which < d_nplots) { + return d_plot_curve[which]->brush().color().alpha(); + } else { + return 0; + } } -void -HistogramDisplayPlot::setLineColor(int which, QColor color) +void HistogramDisplayPlot::setLineColor(int which, QColor color) { - if(which < d_nplots) { - // Adjust color's transparency for the brush - color.setAlpha(127 / d_nplots); + if(which < d_nplots) { + // Adjust color's transparency for the brush + color.setAlpha(127 / d_nplots); - QBrush brush(d_plot_curve[which]->brush()); - brush.setColor(color); - d_plot_curve[which]->setBrush(brush); + QBrush brush(d_plot_curve[which]->brush()); + brush.setColor(color); + d_plot_curve[which]->setBrush(brush); - // Adjust color's transparency darker for the pen and markers - color.setAlpha(255 / d_nplots); + // Adjust color's transparency darker for the pen and markers + color.setAlpha(255 / d_nplots); - QPen pen(d_plot_curve[which]->pen()); - pen.setColor(color); - d_plot_curve[which]->setPen(pen); + QPen pen(d_plot_curve[which]->pen()); + pen.setColor(color); + d_plot_curve[which]->setPen(pen); #if QWT_VERSION < 0x060000 - d_plot_curve[which]->setPen(pen); - QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); - setLineMarker(which, sym.style()); + d_plot_curve[which]->setPen(pen); + QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); + setLineMarker(which, sym.style()); #else - QwtSymbol *sym = (QwtSymbol*)d_plot_curve[which]->symbol(); - if(sym) { - sym->setColor(color); - sym->setPen(pen); - d_plot_curve[which]->setSymbol(sym); - } + QwtSymbol *sym = (QwtSymbol *)d_plot_curve[which]->symbol(); + if(sym) { + sym->setColor(color); + sym->setPen(pen); + d_plot_curve[which]->setSymbol(sym); + } #endif - } + } } -void -HistogramDisplayPlot::setNumBins(int bins) +void HistogramDisplayPlot::setNumBins(int bins) { - d_bins = bins; + d_bins = bins; - delete [] d_xdata; - d_xdata = new double[d_bins]; - _resetXAxisPoints(d_left, d_right); + delete[] d_xdata; + d_xdata = new double[d_bins]; + _resetXAxisPoints(d_left, d_right); - for(int i = 0; i < d_nplots; i++) { - delete [] d_ydata[i]; - d_ydata[i] = new double[d_bins]; - memset(d_ydata[i], 0, d_bins*sizeof(double)); + for(int i = 0; i < d_nplots; i++) { + delete[] d_ydata[i]; + d_ydata[i] = new double[d_bins]; + memset(d_ydata[i], 0, d_bins * sizeof(double)); #if QWT_VERSION < 0x060000 - d_plot_curve[i]->setRawData(d_xdata, d_ydata[i], d_bins); + d_plot_curve[i]->setRawData(d_xdata, d_ydata[i], d_bins); #else - d_plot_curve[i]->setRawSamples(d_ydata[i], d_xdata, d_bins); + d_plot_curve[i]->setRawSamples(d_ydata[i], d_xdata, d_bins); #endif - } + } } #endif /* HISTOGRAM_DISPLAY_PLOT_C */ -HistogramScaleDraw::HistogramScaleDraw() : - QwtScaleDraw(), - m_color(Qt::gray), - m_totalSamples(0) +HistogramScaleDraw::HistogramScaleDraw() + : QwtScaleDraw() + , m_color(Qt::gray) + , m_totalSamples(0) { enableComponent(QwtAbstractScaleDraw::Backbone, false); enableComponent(QwtAbstractScaleDraw::Ticks, false); @@ -916,7 +833,7 @@ QwtText HistogramScaleDraw::label(double value) const double displayValue = 0; - if (!m_totalSamples) { + if(!m_totalSamples) { QwtText text("--"); text.setColor(m_color); return text; @@ -925,19 +842,13 @@ QwtText HistogramScaleDraw::label(double value) const displayValue = value * 100 / m_totalSamples; QwtText text(QLocale().toString(displayValue, 'f', 2) + prefix); - if (m_color != Qt::gray) { + if(m_color != Qt::gray) { text.setColor(m_color); } return text; } -void HistogramScaleDraw::setColor(const QColor &color) -{ - m_color = color; -} +void HistogramScaleDraw::setColor(const QColor &color) { m_color = color; } -void HistogramScaleDraw::setTotalSamples(unsigned int totalSamples) -{ - m_totalSamples = totalSamples; -} +void HistogramScaleDraw::setTotalSamples(unsigned int totalSamples) { m_totalSamples = totalSamples; } diff --git a/gui/src/TimeDomainDisplayPlot.cc b/gui/src/TimeDomainDisplayPlot.cc index 72a50c38b6..9773dacbb4 100644 --- a/gui/src/TimeDomainDisplayPlot.cc +++ b/gui/src/TimeDomainDisplayPlot.cc @@ -42,86 +42,76 @@ #ifndef TIME_DOMAIN_DISPLAY_PLOT_C #define TIME_DOMAIN_DISPLAY_PLOT_C -#include -#include +#include "TimeDomainDisplayPlot.h" + +#include "osc_scale_engine.h" +#include "smoothcurvefitter.h" + #include +#include +#include +#include + #include #include #include -#include - -#include "TimeDomainDisplayPlot.h" -#include "osc_scale_engine.h" - -#include "smoothcurvefitter.h" using namespace scopy; -class TimeDomainDisplayZoomer: public OscPlotZoomer +class TimeDomainDisplayZoomer : public OscPlotZoomer { public: #if QWT_VERSION < 0x060100 - TimeDomainDisplayZoomer(QwtPlotCanvas* canvas) -#else /* QWT_VERSION < 0x060100 */ - TimeDomainDisplayZoomer(QWidget* canvas) + TimeDomainDisplayZoomer(QwtPlotCanvas *canvas) +#else /* QWT_VERSION < 0x060100 */ + TimeDomainDisplayZoomer(QWidget *canvas) #endif /* QWT_VERSION < 0x060100 */ - : OscPlotZoomer(canvas) - { - setTrackerMode(QwtPicker::AlwaysOn); - } + : OscPlotZoomer(canvas) + { + setTrackerMode(QwtPicker::AlwaysOn); + } - virtual ~TimeDomainDisplayZoomer() - { - } + virtual ~TimeDomainDisplayZoomer() {} - virtual void updateTrackerText() - { - updateDisplay(); - } + virtual void updateTrackerText() { updateDisplay(); } protected: - using QwtPlotZoomer::trackerText; - virtual QwtText trackerText( const QPoint& p ) const - { - QwtText t; - QPointF dp = QwtPlotZoomer::invTransform(p); - const TimeDomainDisplayPlot* plt = (const TimeDomainDisplayPlot *)plot(); - t.setText(plt->timeScaleValueFormat(dp.x(), 3) + "," + - plt->yAxisScaleValueFormat(dp.y(), 3)); - return t; - } + using QwtPlotZoomer::trackerText; + virtual QwtText trackerText(const QPoint &p) const + { + QwtText t; + QPointF dp = QwtPlotZoomer::invTransform(p); + const TimeDomainDisplayPlot *plt = (const TimeDomainDisplayPlot *)plot(); + t.setText(plt->timeScaleValueFormat(dp.x(), 3) + "," + plt->yAxisScaleValueFormat(dp.y(), 3)); + return t; + } }; +SinkManager::SinkManager() {} -SinkManager::SinkManager() -{ -} - -SinkManager::~SinkManager() -{ -} +SinkManager::~SinkManager() {} -bool SinkManager::addSink(const std::string& name, unsigned int numChannels, unsigned long long channelsDataLength) +bool SinkManager::addSink(const std::string &name, unsigned int numChannels, unsigned long long channelsDataLength) { bool can_add = true; - for (auto it = d_sinkList.begin(); it != d_sinkList.end(); ++it) - if ((*it).name() == name) { + for(auto it = d_sinkList.begin(); it != d_sinkList.end(); ++it) + if((*it).name() == name) { can_add = false; break; } - if (can_add) + if(can_add) d_sinkList.push_back(Sink(name, numChannels, channelsDataLength)); return can_add; } -bool SinkManager::removeSink(const std::string& name) +bool SinkManager::removeSink(const std::string &name) { bool found = false; - for (auto it = d_sinkList.begin(); it != d_sinkList.end(); ++it) - if ((*it).name() == name) { + for(auto it = d_sinkList.begin(); it != d_sinkList.end(); ++it) + if((*it).name() == name) { found = true; it = d_sinkList.erase(it); break; @@ -130,39 +120,37 @@ bool SinkManager::removeSink(const std::string& name) return found; } -unsigned int SinkManager::sinkListLength() -{ - return d_sinkList.size(); -} +unsigned int SinkManager::sinkListLength() { return d_sinkList.size(); } -Sink* SinkManager::sink(unsigned int index) +Sink *SinkManager::sink(unsigned int index) { - if (index < d_sinkList.size()) + if(index < d_sinkList.size()) return &d_sinkList[index]; return NULL; } -int SinkManager::indexOfSink(const std::string& name) +int SinkManager::indexOfSink(const std::string &name) { - int pos = find_if(d_sinkList.begin(), d_sinkList.end(), [&name](Sink& s) {return s.name() == name;}) - d_sinkList.begin(); + int pos = find_if(d_sinkList.begin(), d_sinkList.end(), [&name](Sink &s) { return s.name() == name; }) - + d_sinkList.begin(); - if (pos >= d_sinkList.size()) + if(pos >= d_sinkList.size()) pos = -1; return pos; } -int SinkManager::sinkFirstChannelPos(const std::string& name) +int SinkManager::sinkFirstChannelPos(const std::string &name) { size_t i, index = 0; - for (i = 0; i < d_sinkList.size(); ++i) { - if (d_sinkList[i].name() == name) + for(i = 0; i < d_sinkList.size(); ++i) { + if(d_sinkList[i].name() == name) break; index += d_sinkList[i].numChannels(); } - if (i == d_sinkList.size()) + if(i == d_sinkList.size()) index = -1; return index; @@ -171,112 +159,108 @@ int SinkManager::sinkFirstChannelPos(const std::string& name) /*********************************************************************** * Main Time domain plotter widget **********************************************************************/ -TimeDomainDisplayPlot::TimeDomainDisplayPlot(QWidget* parent, bool isdBgraph, unsigned int xNumDivs, unsigned int yNumDivs, - PrefixFormatter* pfXaxis, PrefixFormatter* pfYaxis, int qwtAxis) - : DisplayPlot(0, parent, isdBgraph, xNumDivs, yNumDivs, qwtAxis) +TimeDomainDisplayPlot::TimeDomainDisplayPlot(QWidget *parent, bool isdBgraph, unsigned int xNumDivs, + unsigned int yNumDivs, PrefixFormatter *pfXaxis, PrefixFormatter *pfYaxis, + int qwtAxis) + : DisplayPlot(0, parent, isdBgraph, xNumDivs, yNumDivs, qwtAxis) { - d_tag_text_color = Qt::black; - d_tag_background_color = Qt::white; - d_tag_background_style = Qt::NoBrush; + d_tag_text_color = Qt::black; + d_tag_background_color = Qt::white; + d_tag_background_style = Qt::NoBrush; - d_sample_rate = 1; - d_data_starting_point = 0.0; - d_curves_hidden = false; - d_nbPtsXAxis = 0; + d_sample_rate = 1; + d_data_starting_point = 0.0; + d_curves_hidden = false; + d_nbPtsXAxis = 0; - d_nb_ref_curves = 0; + d_nb_ref_curves = 0; - d_autoscale_state = false; + d_autoscale_state = false; - // Reconfigure the bottom horizontal axis that was created by the base class - configureAxis(QwtAxis::XBottom, 0, pfXaxis); - configureAxis(m_qwtYAxis, 0, pfYaxis); + // Reconfigure the bottom horizontal axis that was created by the base class + configureAxis(QwtAxis::XBottom, 0, pfXaxis); + configureAxis(m_qwtYAxis, 0, pfYaxis); - d_xAxisUnit = ""; - d_yAxisUnit = ""; + d_xAxisUnit = ""; + d_yAxisUnit = ""; - //d_zoomer = new TimeDomainDisplayZoomer(canvas()); + // d_zoomer = new TimeDomainDisplayZoomer(canvas()); - QFont font; - font.setPointSize(10); - font.setWeight(75); - //d_zoomer->setTrackerFont(font); + QFont font; + font.setPointSize(10); + font.setWeight(75); + // d_zoomer->setTrackerFont(font); #if QWT_VERSION < 0x060000 - //d_zoomer->setSelectionFlags(QwtPicker::RectSelection | QwtPicker::DragSelection); + // d_zoomer->setSelectionFlags(QwtPicker::RectSelection | QwtPicker::DragSelection); #endif - //d_zoomer->setMousePattern(QwtEventPattern::MouseSelect2, -// Qt::RightButton, Qt::ControlModifier); - //d_zoomer->setMousePattern(QwtEventPattern::MouseSelect3, + // d_zoomer->setMousePattern(QwtEventPattern::MouseSelect2, + // Qt::RightButton, Qt::ControlModifier); + // d_zoomer->setMousePattern(QwtEventPattern::MouseSelect3, // Qt::RightButton); - const QColor c("#999999"); - //d_zoomer->setRubberBandPen(c); - //d_zoomer->setTrackerPen(c); - - d_semilogx = false; - d_semilogy = false; - d_autoscale_shot = false; - d_plotGrTags = false; - - if (d_xAxisFormatter) { - d_xAxisFormatter->setTwoDecimalMode(true); - d_xAxisFormatter->setTrimZeroes(true); - } - - if (d_yAxisFormatter) { - d_yAxisFormatter->setTwoDecimalMode(true); - d_yAxisFormatter->setTrimZeroes(true); - } - - d_tag_markers.resize(d_nplots); - d_tag_markers_en = std::vector(d_nplots, true); - - d_trigger_lines[0] = new QwtPlotMarker(); - d_trigger_lines[0]->setLineStyle(QwtPlotMarker::HLine); - d_trigger_lines[0]->setLinePen(QPen(Qt::red, 0.6, Qt::DashLine)); - d_trigger_lines[0]->setRenderHint(QwtPlotItem::RenderAntialiased); - d_trigger_lines[0]->setXValue(0.0); - d_trigger_lines[0]->setYValue(0.0); - - d_trigger_lines[1] = new QwtPlotMarker(); - d_trigger_lines[1]->setLineStyle(QwtPlotMarker::VLine); - d_trigger_lines[1]->setLinePen(QPen(Qt::red, 0.6, Qt::DashLine)); - d_trigger_lines[1]->setRenderHint(QwtPlotItem::RenderAntialiased); - d_trigger_lines[1]->setXValue(0.0); - d_trigger_lines[1]->setYValue(0.0); - - for (int i = 0; i < 8; i++) { - d_zoomer.push_back(new TimeDomainDisplayZoomer(this->canvas())); - d_zoomer[i]->setEnabled(false); - } -} + const QColor c("#999999"); + // d_zoomer->setRubberBandPen(c); + // d_zoomer->setTrackerPen(c); + d_semilogx = false; + d_semilogy = false; + d_autoscale_shot = false; + d_plotGrTags = false; + + if(d_xAxisFormatter) { + d_xAxisFormatter->setTwoDecimalMode(true); + d_xAxisFormatter->setTrimZeroes(true); + } + + if(d_yAxisFormatter) { + d_yAxisFormatter->setTwoDecimalMode(true); + d_yAxisFormatter->setTrimZeroes(true); + } + + d_tag_markers.resize(d_nplots); + d_tag_markers_en = std::vector(d_nplots, true); + + d_trigger_lines[0] = new QwtPlotMarker(); + d_trigger_lines[0]->setLineStyle(QwtPlotMarker::HLine); + d_trigger_lines[0]->setLinePen(QPen(Qt::red, 0.6, Qt::DashLine)); + d_trigger_lines[0]->setRenderHint(QwtPlotItem::RenderAntialiased); + d_trigger_lines[0]->setXValue(0.0); + d_trigger_lines[0]->setYValue(0.0); + + d_trigger_lines[1] = new QwtPlotMarker(); + d_trigger_lines[1]->setLineStyle(QwtPlotMarker::VLine); + d_trigger_lines[1]->setLinePen(QPen(Qt::red, 0.6, Qt::DashLine)); + d_trigger_lines[1]->setRenderHint(QwtPlotItem::RenderAntialiased); + d_trigger_lines[1]->setXValue(0.0); + d_trigger_lines[1]->setYValue(0.0); + + for(int i = 0; i < 8; i++) { + d_zoomer.push_back(new TimeDomainDisplayZoomer(this->canvas())); + d_zoomer[i]->setEnabled(false); + } +} TimeDomainDisplayPlot::~TimeDomainDisplayPlot() { - while (d_sinkManager.sinkListLength()) { + while(d_sinkManager.sinkListLength()) { Sink *sink = d_sinkManager.sink(0); unregisterSink(sink->name()); } - //TODO: prob remove d_trigger_lines -> not used. + // TODO: prob remove d_trigger_lines -> not used. delete d_trigger_lines[0]; delete d_trigger_lines[1]; - for (int i = 0; i < d_ref_ydata.size(); ++i) { + for(int i = 0; i < d_ref_ydata.size(); ++i) { delete[] d_ref_ydata[i]; } - // d_zoomer and _panner deleted when parent deleted + // d_zoomer and _panner deleted when parent deleted } -void -TimeDomainDisplayPlot::replot() -{ - BasicPlot::replot(); -} +void TimeDomainDisplayPlot::replot() { BasicPlot::replot(); } /*void TimeDomainDisplayPlot::plotTags(const std::vector< std::vector > &tags) { // Detach and delete any tags that were plotted last time @@ -410,211 +394,189 @@ TimeDomainDisplayPlot::replot() }*/ -void -TimeDomainDisplayPlot::plotNewData(const std::string &sender, - const std::vector &dataPoints, - const int64_t numDataPoints, - const double timeInterval -// const std::vector< std::vector > &tags - ) -{ - int sinkIndex = d_sinkManager.indexOfSink(sender); - - if(!d_stop) { - if((numDataPoints > 0) && sinkIndex >= 0) { - Sink *sink = d_sinkManager.sink((unsigned int)sinkIndex); - int start = d_sinkManager.sinkFirstChannelPos(sender); - unsigned int sinkNumChannels = sink->numChannels(); - unsigned long long sinkNumPoints = sink->channelsDataLength(); - bool reset_x_axis_points = d_sink_reset_x_axis_pts[sinkIndex]; - - if(numDataPoints != sinkNumPoints){ - sinkNumPoints = numDataPoints; - sink->setChannelsDataLength(numDataPoints); - - delete[] d_xdata[sinkIndex]; - d_xdata[sinkIndex] = new double[numDataPoints]; - - int ref_offset = countReferenceWaveform(start); - for(int i = start; i < start + sinkNumChannels; i++) { - delete[] d_ydata[i]; - d_ydata[i] = new double[numDataPoints]; - - d_plot_curve[i + ref_offset]->setRawSamples(d_xdata[sinkIndex], d_ydata[i], numDataPoints); - } - - _resetXAxisPoints(d_xdata[sinkIndex], numDataPoints, d_sample_rate); - } else if (reset_x_axis_points) { - _resetXAxisPoints(d_xdata[sinkIndex], numDataPoints, d_sample_rate); - reset_x_axis_points = false; - } - - for(int i = 0; i < sinkNumChannels; i++) { - if(d_semilogy) { - for(int n = 0; n < numDataPoints; n++) - d_ydata[start + i][n] = fabs(dataPoints[i][n]); - } - else { - memcpy(d_ydata[start + i], dataPoints[i], numDataPoints*sizeof(double)); - } - } - - for (size_t i = 0; i < d_plot_curve.size(); i++) - d_plot_curve.at(i)->show(); - d_curves_hidden = false; +void TimeDomainDisplayPlot::plotNewData( + const std::string &sender, const std::vector &dataPoints, const int64_t numDataPoints, + const double timeInterval + // const std::vector< std::vector > &tags +) +{ + int sinkIndex = d_sinkManager.indexOfSink(sender); + + if(!d_stop) { + if((numDataPoints > 0) && sinkIndex >= 0) { + Sink *sink = d_sinkManager.sink((unsigned int)sinkIndex); + int start = d_sinkManager.sinkFirstChannelPos(sender); + unsigned int sinkNumChannels = sink->numChannels(); + unsigned long long sinkNumPoints = sink->channelsDataLength(); + bool reset_x_axis_points = d_sink_reset_x_axis_pts[sinkIndex]; + + if(numDataPoints != sinkNumPoints) { + sinkNumPoints = numDataPoints; + sink->setChannelsDataLength(numDataPoints); + + delete[] d_xdata[sinkIndex]; + d_xdata[sinkIndex] = new double[numDataPoints]; + + int ref_offset = countReferenceWaveform(start); + for(int i = start; i < start + sinkNumChannels; i++) { + delete[] d_ydata[i]; + d_ydata[i] = new double[numDataPoints]; + + d_plot_curve[i + ref_offset]->setRawSamples(d_xdata[sinkIndex], d_ydata[i], + numDataPoints); + } + + _resetXAxisPoints(d_xdata[sinkIndex], numDataPoints, d_sample_rate); + } else if(reset_x_axis_points) { + _resetXAxisPoints(d_xdata[sinkIndex], numDataPoints, d_sample_rate); + reset_x_axis_points = false; + } - if(d_plotGrTags) -// plotTags(tags); + for(int i = 0; i < sinkNumChannels; i++) { + if(d_semilogy) { + for(int n = 0; n < numDataPoints; n++) + d_ydata[start + i][n] = fabs(dataPoints[i][n]); + } else { + memcpy(d_ydata[start + i], dataPoints[i], numDataPoints * sizeof(double)); + } + } - if(d_autoscale_state) { - double bottom=1e20, top=-1e20; - for(int n = 0; n < d_nplots; n++) { - if(d_plot_curve[n]->plot()) { - for(int64_t point = 0; point < numDataPoints; point++) { - if(d_ydata[n][point] < bottom) { - bottom = d_ydata[n][point]; - } - if(d_ydata[n][point] > top) { - top = d_ydata[n][point]; - } - } - } - } - _autoScale(bottom, top); - if(d_autoscale_shot) { - d_autoscale_state = false; - d_autoscale_shot = false; + for(size_t i = 0; i < d_plot_curve.size(); i++) + d_plot_curve.at(i)->show(); + d_curves_hidden = false; + + if(d_plotGrTags) + // plotTags(tags); + + if(d_autoscale_state) { + double bottom = 1e20, top = -1e20; + for(int n = 0; n < d_nplots; n++) { + if(d_plot_curve[n]->plot()) { + for(int64_t point = 0; point < numDataPoints; point++) { + if(d_ydata[n][point] < bottom) { + bottom = d_ydata[n][point]; + } + if(d_ydata[n][point] > top) { + top = d_ydata[n][point]; + } + } + } + } + _autoScale(bottom, top); + if(d_autoscale_shot) { + d_autoscale_state = false; + d_autoscale_shot = false; + } + } + replot(); + + Q_EMIT newData(); + } } - } - replot(); - - Q_EMIT newData(); - - } - } } -void TimeDomainDisplayPlot::newData(const QEvent* updateEvent) +void TimeDomainDisplayPlot::newData(const QEvent *updateEvent) { - IdentifiableTimeUpdateEvent *tevent = (IdentifiableTimeUpdateEvent*)updateEvent; - const std::vector dataPoints = tevent->getTimeDomainPoints(); + IdentifiableTimeUpdateEvent *tevent = (IdentifiableTimeUpdateEvent *)updateEvent; + const std::vector dataPoints = tevent->getTimeDomainPoints(); const uint64_t numDataPoints = tevent->getNumTimeDomainDataPoints(); - const std::vector< std::vector > tags = tevent->getTags(); + const std::vector> tags = tevent->getTags(); const std::string sender = tevent->senderName(); - if ((d_nbPtsXAxis != 0) && (d_nbPtsXAxis <= numDataPoints) - && sender == "Osc Time") { + if((d_nbPtsXAxis != 0) && (d_nbPtsXAxis <= numDataPoints) && sender == "Osc Time") { Q_EMIT filledScreen(true, numDataPoints); } - this->plotNewData(sender, - dataPoints, - numDataPoints, - 0); + this->plotNewData(sender, dataPoints, numDataPoints, 0); } -void TimeDomainDisplayPlot::customEvent(QEvent * e) +void TimeDomainDisplayPlot::customEvent(QEvent *e) { - if(e->type() == TimeUpdateEvent::Type()) { - newData(e); - } + if(e->type() == TimeUpdateEvent::Type()) { + newData(e); + } } -void -TimeDomainDisplayPlot::legendEntryChecked(QwtPlotItem* plotItem, bool on) +void TimeDomainDisplayPlot::legendEntryChecked(QwtPlotItem *plotItem, bool on) { - // When line is turned on/off, immediately show/hide tag markers - for(int n = 0; n < d_nplots; n++) { - if(plotItem == d_plot_curve[n]) { - for(size_t i = 0; i < d_tag_markers[n].size(); i++) { - if(!(!on && d_tag_markers_en[n])) - d_tag_markers[n][i]->hide(); - else - d_tag_markers[n][i]->show(); - } - } - } - DisplayPlot::legendEntryChecked(plotItem, on); + // When line is turned on/off, immediately show/hide tag markers + for(int n = 0; n < d_nplots; n++) { + if(plotItem == d_plot_curve[n]) { + for(size_t i = 0; i < d_tag_markers[n].size(); i++) { + if(!(!on && d_tag_markers_en[n])) + d_tag_markers[n][i]->hide(); + else + d_tag_markers[n][i]->show(); + } + } + } + DisplayPlot::legendEntryChecked(plotItem, on); } -void -TimeDomainDisplayPlot::legendEntryChecked(const QVariant &plotItem, bool on, int index) +void TimeDomainDisplayPlot::legendEntryChecked(const QVariant &plotItem, bool on, int index) { #if QWT_VERSION < 0x060100 - std::runtime_error("TimeDomainDisplayPlot::legendEntryChecked with QVariant not enabled in this version of QWT.\n"); + std::runtime_error( + "TimeDomainDisplayPlot::legendEntryChecked with QVariant not enabled in this version of QWT.\n"); #else - QwtPlotItem *p = infoToItem(plotItem); - legendEntryChecked(p, on); + QwtPlotItem *p = infoToItem(plotItem); + legendEntryChecked(p, on); #endif /* QWT_VERSION < 0x060100 */ } -void -TimeDomainDisplayPlot::_resetXAxisPoints(double*& xAxis, unsigned long long numPoints, double sampleRate) +void TimeDomainDisplayPlot::_resetXAxisPoints(double *&xAxis, unsigned long long numPoints, double sampleRate) { - double delt = 1.0 / sampleRate; + double delt = 1.0 / sampleRate; - for (long loc = 0; loc < numPoints; loc++) - xAxis[loc] = (d_data_starting_point + loc) * delt; + for(long loc = 0; loc < numPoints; loc++) + xAxis[loc] = (d_data_starting_point + loc) * delt; + // Set up zoomer base for maximum unzoom x-axis + // and reset to maximum unzoom level + // QRectF zbase = d_zoomer->zoomBase(); - // Set up zoomer base for maximum unzoom x-axis - // and reset to maximum unzoom level -// QRectF zbase = d_zoomer->zoomBase(); - -// if(d_semilogx) { -// setAxisScale(QwtAxis::XBottom, 1e-1, d_numPoints*delt); -// zbase.setLeft(1e-1); -// } -// else { -// setAxisScale(QwtAxis::XBottom, 0, d_numPoints*delt); -// zbase.setLeft(0); -// } - -// zbase.setRight(d_numPoints*delt); -// d_zoomer->zoom(zbase); -// d_zoomer->setZoomBase(zbase); -// d_zoomer->zoom(0); + // if(d_semilogx) { + // setAxisScale(QwtAxis::XBottom, 1e-1, d_numPoints*delt); + // zbase.setLeft(1e-1); + // } + // else { + // setAxisScale(QwtAxis::XBottom, 0, d_numPoints*delt); + // zbase.setLeft(0); + // } + // zbase.setRight(d_numPoints*delt); + // d_zoomer->zoom(zbase); + // d_zoomer->setZoomBase(zbase); + // d_zoomer->zoom(0); } -void -TimeDomainDisplayPlot::_autoScale(double bottom, double top) +void TimeDomainDisplayPlot::_autoScale(double bottom, double top) { - // Auto scale the y-axis with a margin of 20% (10 dB for log scale) - double _bot = bottom - fabs(bottom-top)*0.125; - double _top = top + fabs(bottom-top)*0.125; - if(d_semilogy) { - if(bottom > 0) { - setYaxis(_bot-10, _top+10); - } - else { - setYaxis(1e-3, _top+10); - } - } - else { - if(_bot == 0 && _top == 0){ - setYaxis(-1e-3, 1e-3); - } - else{ - setYaxis(_bot, _top); - } - } + // Auto scale the y-axis with a margin of 20% (10 dB for log scale) + double _bot = bottom - fabs(bottom - top) * 0.125; + double _top = top + fabs(bottom - top) * 0.125; + if(d_semilogy) { + if(bottom > 0) { + setYaxis(_bot - 10, _top + 10); + } else { + setYaxis(1e-3, _top + 10); + } + } else { + if(_bot == 0 && _top == 0) { + setYaxis(-1e-3, 1e-3); + } else { + setYaxis(_bot, _top); + } + } - replot(); + replot(); } -bool TimeDomainDisplayPlot::getPlotGrTags() const -{ - return d_plotGrTags; -} +bool TimeDomainDisplayPlot::getPlotGrTags() const { return d_plotGrTags; } -void TimeDomainDisplayPlot::setPlotGrTags(bool val) -{ - d_plotGrTags = val; -} +void TimeDomainDisplayPlot::setPlotGrTags(bool val) { d_plotGrTags = val; } -void -TimeDomainDisplayPlot::addZoomer(unsigned int zoomerIdx) +void TimeDomainDisplayPlot::addZoomer(unsigned int zoomerIdx) { QFont font; font.setPointSize(10); @@ -625,10 +587,8 @@ TimeDomainDisplayPlot::addZoomer(unsigned int zoomerIdx) d_zoomer[zoomerIdx]->setSelectionFlags(QwtPicker::RectSelection | QwtPicker::DragSelection); #endif - d_zoomer[zoomerIdx]->setMousePattern(QwtEventPattern::MouseSelect2, - Qt::RightButton, Qt::ControlModifier); - d_zoomer[zoomerIdx]->setMousePattern(QwtEventPattern::MouseSelect3, - Qt::RightButton); + d_zoomer[zoomerIdx]->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); + d_zoomer[zoomerIdx]->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); d_zoomer[zoomerIdx]->setTrackerMode(QwtPicker::AlwaysOff); const QColor c("#999999"); d_zoomer[zoomerIdx]->setRubberBandPen(c); @@ -638,156 +598,135 @@ TimeDomainDisplayPlot::addZoomer(unsigned int zoomerIdx) d_zoomer[zoomerIdx]->setAxes(QwtAxisId(QwtAxis::XBottom, 0), QwtAxisId(m_qwtYAxis, zoomerIdx)); } -void -TimeDomainDisplayPlot::removeZoomer(unsigned int zoomerIdx) +void TimeDomainDisplayPlot::removeZoomer(unsigned int zoomerIdx) { - if (zoomerIdx == 0 || zoomerIdx == 1) { + if(zoomerIdx == 0 || zoomerIdx == 1) { d_zoomer[zoomerIdx]->setEnabled(false); return; } int toDisable = zoomerIdx; - while (d_zoomer[toDisable]->isEnabled() - && toDisable < d_zoomer.size() - 1) { + while(d_zoomer[toDisable]->isEnabled() && toDisable < d_zoomer.size() - 1) { toDisable++; } - if (toDisable == d_zoomer.size() - 1 && d_zoomer[toDisable]->isEnabled()) { + if(toDisable == d_zoomer.size() - 1 && d_zoomer[toDisable]->isEnabled()) { d_zoomer[toDisable]->setEnabled(false); } else { d_zoomer[toDisable - 1]->setEnabled(false); } - for (int i = 0; i < d_zoomer.size(); ++i) { - if (d_zoomer[i]->isEnabled()) { + for(int i = 0; i < d_zoomer.size(); ++i) { + if(d_zoomer[i]->isEnabled()) { d_zoomer[i]->setAxes(QwtAxisId(QwtAxis::XBottom, 0), QwtAxisId(m_qwtYAxis, i)); d_zoomer[i]->setTrackerPen(getLineColor(i)); } } } -void TimeDomainDisplayPlot::setXAxisNumPoints(unsigned int pts) -{ - d_nbPtsXAxis = pts; -} +void TimeDomainDisplayPlot::setXAxisNumPoints(unsigned int pts) { d_nbPtsXAxis = pts; } void TimeDomainDisplayPlot::setAutoScale(bool state) { - d_autoscale_state = state; - - if(d_autoscale_state) { - double bottom=1e20, top=-1e20; - for(int n = 0; n < d_nplots; n++) { - if(d_plot_curve[n]->plot()) { - for(int64_t point = 0; point < Curve(n)->data()->size(); point++) { - if(d_ydata[n][point] < bottom) { - bottom = d_ydata[n][point]; - } - if(d_ydata[n][point] > top) { - top = d_ydata[n][point]; - } + d_autoscale_state = state; + + if(d_autoscale_state) { + double bottom = 1e20, top = -1e20; + for(int n = 0; n < d_nplots; n++) { + if(d_plot_curve[n]->plot()) { + for(int64_t point = 0; point < Curve(n)->data()->size(); point++) { + if(d_ydata[n][point] < bottom) { + bottom = d_ydata[n][point]; + } + if(d_ydata[n][point] > top) { + top = d_ydata[n][point]; + } + } + } + } + _autoScale(bottom, top); + if(d_autoscale_shot) { + d_autoscale_state = false; + d_autoscale_shot = false; + } + } else { + setYaxis(-5, 5); + replot(); } - } - } - _autoScale(bottom, top); - if(d_autoscale_shot) { - d_autoscale_state = false; - d_autoscale_shot = false; - } - } - else{ - setYaxis(-5, 5); - replot(); - } } -void -TimeDomainDisplayPlot::setAutoScaleShot() +void TimeDomainDisplayPlot::setAutoScaleShot() { - d_autoscale_state = true; - d_autoscale_shot = true; + d_autoscale_state = true; + d_autoscale_shot = true; } - -void -TimeDomainDisplayPlot::setSampleRate(double sr, double units, - const std::string &strunits) +void TimeDomainDisplayPlot::setSampleRate(double sr, double units, const std::string &strunits) { - double newsr = sr/units; - if(newsr != d_sample_rate) { - d_sample_rate = sr/units; + double newsr = sr / units; + if(newsr != d_sample_rate) { + d_sample_rate = sr / units; - for (unsigned int i = 0; i < d_sinkManager.sinkListLength(); i++) - _resetXAxisPoints(d_xdata[i], d_sinkManager.sink(i)->channelsDataLength(), d_sample_rate); - } + for(unsigned int i = 0; i < d_sinkManager.sinkListLength(); i++) + _resetXAxisPoints(d_xdata[i], d_sinkManager.sink(i)->channelsDataLength(), d_sample_rate); + } } -double -TimeDomainDisplayPlot::sampleRate() const -{ - return d_sample_rate; -} +double TimeDomainDisplayPlot::sampleRate() const { return d_sample_rate; } void TimeDomainDisplayPlot::setYaxisUnit(QString unitType, int axisIdx) { - if (d_yAxisUnit != unitType) { + if(d_yAxisUnit != unitType) { d_yAxisUnit = unitType; } OscScaleDraw *scaleDraw = static_cast(this->axisScaleDraw(QwtAxisId(m_qwtYAxis, axisIdx))); - if (scaleDraw) + if(scaleDraw) scaleDraw->setUnitType(d_yAxisUnit); } -QString TimeDomainDisplayPlot::yAxisUnit(void) -{ - return d_yAxisUnit; -} +QString TimeDomainDisplayPlot::yAxisUnit(void) { return d_yAxisUnit; } QString TimeDomainDisplayPlot::yAxisUnit(int axisIdx) { - OscScaleDraw *scaleDraw = - static_cast(this->axisScaleDraw(QwtAxisId(m_qwtYAxis, axisIdx))); - if (scaleDraw) { + OscScaleDraw *scaleDraw = static_cast(this->axisScaleDraw(QwtAxisId(m_qwtYAxis, axisIdx))); + if(scaleDraw) { return scaleDraw->getUnitType(); } else { - return d_yAxisUnit; + return d_yAxisUnit; } - } void TimeDomainDisplayPlot::setXaxisUnit(QString unitType) { - if (d_xAxisUnit != unitType) { + if(d_xAxisUnit != unitType) { d_xAxisUnit = unitType; - OscScaleDraw* scaleDraw = static_cast(this->axisScaleDraw(QwtAxis::XBottom)); - if (scaleDraw) + OscScaleDraw *scaleDraw = static_cast(this->axisScaleDraw(QwtAxis::XBottom)); + if(scaleDraw) scaleDraw->setUnitType(d_xAxisUnit); } } QString TimeDomainDisplayPlot::xAxisUnit() { return d_xAxisUnit; } - void TimeDomainDisplayPlot::stemPlot(bool en) { - if(en) { - for(int i = 0; i < d_nplots; i++) { - d_plot_curve[i]->setStyle(QwtPlotCurve::Sticks); - setLineMarker(i, QwtSymbol::Ellipse); - } - } - else { - for(int i = 0; i < d_nplots; i++) { - d_plot_curve[i]->setStyle(QwtPlotCurve::Lines); - setLineMarker(i, QwtSymbol::NoSymbol); - } - } + if(en) { + for(int i = 0; i < d_nplots; i++) { + d_plot_curve[i]->setStyle(QwtPlotCurve::Sticks); + setLineMarker(i, QwtSymbol::Ellipse); + } + } else { + for(int i = 0; i < d_nplots; i++) { + d_plot_curve[i]->setStyle(QwtPlotCurve::Lines); + setLineMarker(i, QwtSymbol::NoSymbol); + } + } } void TimeDomainDisplayPlot::setPlotLineStyle(unsigned int chIdx, unsigned int style) { - if (chIdx < 0 || chIdx >= d_plot_curve.size()) { + if(chIdx < 0 || chIdx >= d_plot_curve.size()) { return; } @@ -796,24 +735,24 @@ void TimeDomainDisplayPlot::setPlotLineStyle(unsigned int chIdx, unsigned int st curve->setPaintAttribute(QwtPlotCurve::ClipPolygons, true); curve->setCurveAttribute(QwtPlotCurve::Fitted, false); - switch (style) { - case 0: + switch(style) { + case 0: curve->setStyle(QwtPlotCurve::CurveStyle::Lines); replot(); break; - case 1: + case 1: curve->setStyle(QwtPlotCurve::CurveStyle::Dots); replot(); break; - case 2: + case 2: curve->setStyle(QwtPlotCurve::CurveStyle::Steps); replot(); break; - case 3: + case 3: curve->setStyle(QwtPlotCurve::CurveStyle::Sticks); replot(); break; - case 4: + case 4: curve->setPaintAttribute(QwtPlotCurve::ClipPolygons, false); curve->setCurveAttribute(QwtPlotCurve::Fitted, true); curve->setStyle(QwtPlotCurve::CurveStyle::Lines); @@ -824,144 +763,114 @@ void TimeDomainDisplayPlot::setPlotLineStyle(unsigned int chIdx, unsigned int st int TimeDomainDisplayPlot::getPlotLineStyle(unsigned int chIdx) const { - if (chIdx < 0 || chIdx >= d_plot_curve.size()) { + if(chIdx < 0 || chIdx >= d_plot_curve.size()) { return -1; } auto style = d_plot_curve[chIdx]->style(); - switch (style) { - case QwtPlotCurve::CurveStyle::Lines: - if (d_plot_curve[chIdx]->testCurveAttribute(QwtPlotCurve::Fitted)) { + switch(style) { + case QwtPlotCurve::CurveStyle::Lines: + if(d_plot_curve[chIdx]->testCurveAttribute(QwtPlotCurve::Fitted)) { return 4; } else { return 0; } - case QwtPlotCurve::CurveStyle::Dots: + case QwtPlotCurve::CurveStyle::Dots: return 1; - case QwtPlotCurve::CurveStyle::Steps: + case QwtPlotCurve::CurveStyle::Steps: return 2; - case QwtPlotCurve::CurveStyle::Sticks: + case QwtPlotCurve::CurveStyle::Sticks: return 3; default: return -1; } } -void -TimeDomainDisplayPlot::setSemilogx(bool en) +void TimeDomainDisplayPlot::setSemilogx(bool en) { - d_semilogx = en; - if(!d_semilogx) { - setAxisScaleEngine(QwtAxis::XBottom, new QwtLinearScaleEngine); - } - else { + d_semilogx = en; + if(!d_semilogx) { + setAxisScaleEngine(QwtAxis::XBottom, new QwtLinearScaleEngine); + } else { #if QWT_VERSION < 0x060100 - setAxisScaleEngine(QwtAxis::XBottom, new QwtLog10ScaleEngine); -#else /* QWT_VERSION < 0x060100 */ - setAxisScaleEngine(QwtAxis::XBottom, new QwtLogScaleEngine); + setAxisScaleEngine(QwtAxis::XBottom, new QwtLog10ScaleEngine); +#else /* QWT_VERSION < 0x060100 */ + setAxisScaleEngine(QwtAxis::XBottom, new QwtLogScaleEngine); #endif /*QWT_VERSION < 0x060100 */ - } - for (unsigned int i = 0; i < d_sinkManager.sinkListLength(); i++) - _resetXAxisPoints(d_xdata[i], d_sinkManager.sink(i)->channelsDataLength(), d_sample_rate); + } + for(unsigned int i = 0; i < d_sinkManager.sinkListLength(); i++) + _resetXAxisPoints(d_xdata[i], d_sinkManager.sink(i)->channelsDataLength(), d_sample_rate); } -void -TimeDomainDisplayPlot::setSemilogy(bool en) +void TimeDomainDisplayPlot::setSemilogy(bool en) { - if(d_semilogy != en) { - d_semilogy = en; + if(d_semilogy != en) { + d_semilogy = en; #if QWT_VERSION < 0x060100 - double max = axisScaleDiv(QwtAxis::YLeft)->upperBound(); -#else /* QWT_VERSION < 0x060100 */ - double max = axisScaleDiv(QwtAxis::YLeft).upperBound(); + double max = axisScaleDiv(QwtAxis::YLeft)->upperBound(); +#else /* QWT_VERSION < 0x060100 */ + double max = axisScaleDiv(QwtAxis::YLeft).upperBound(); #endif /* QWT_VERSION < 0x060100 */ - if(!d_semilogy) { - setAxisScaleEngine(QwtAxis::YLeft, new QwtLinearScaleEngine); - setYaxis(-pow(10.0, max/10.0), pow(10.0, max/10.0)); - } - else { + if(!d_semilogy) { + setAxisScaleEngine(QwtAxis::YLeft, new QwtLinearScaleEngine); + setYaxis(-pow(10.0, max / 10.0), pow(10.0, max / 10.0)); + } else { #if QWT_VERSION < 0x060100 - setAxisScaleEngine(QwtAxis::YLeft, new QwtLog10ScaleEngine); -#else /* QWT_VERSION < 0x060100 */ - setAxisScaleEngine(QwtAxis::YLeft, new QwtLogScaleEngine); + setAxisScaleEngine(QwtAxis::YLeft, new QwtLog10ScaleEngine); +#else /* QWT_VERSION < 0x060100 */ + setAxisScaleEngine(QwtAxis::YLeft, new QwtLogScaleEngine); #endif /*QWT_VERSION < 0x060100 */ - setYaxis(1e-10, 10.0*log10(max)); - } - } + setYaxis(1e-10, 10.0 * log10(max)); + } + } } -void -TimeDomainDisplayPlot::enableTagMarker(int which, bool en) +void TimeDomainDisplayPlot::enableTagMarker(int which, bool en) { - if((size_t)which < d_tag_markers_en.size()) - d_tag_markers_en[which] = en; - else - throw std::runtime_error("TimeDomainDisplayPlot: enabled tag marker does not exist.\n"); + if((size_t)which < d_tag_markers_en.size()) + d_tag_markers_en[which] = en; + else + throw std::runtime_error("TimeDomainDisplayPlot: enabled tag marker does not exist.\n"); } -const QColor -TimeDomainDisplayPlot::getTagTextColor() -{ - return d_tag_text_color; -} +const QColor TimeDomainDisplayPlot::getTagTextColor() { return d_tag_text_color; } -const QColor -TimeDomainDisplayPlot::getTagBackgroundColor() -{ - return d_tag_background_color; -} +const QColor TimeDomainDisplayPlot::getTagBackgroundColor() { return d_tag_background_color; } -const Qt::BrushStyle -TimeDomainDisplayPlot::getTagBackgroundStyle() -{ - return d_tag_background_style; -} +const Qt::BrushStyle TimeDomainDisplayPlot::getTagBackgroundStyle() { return d_tag_background_style; } -void -TimeDomainDisplayPlot::setTagTextColor(QColor c) -{ - d_tag_text_color = c; -} +void TimeDomainDisplayPlot::setTagTextColor(QColor c) { d_tag_text_color = c; } -void -TimeDomainDisplayPlot::setTagBackgroundColor(QColor c) -{ - d_tag_background_color = c; -} +void TimeDomainDisplayPlot::setTagBackgroundColor(QColor c) { d_tag_background_color = c; } -void -TimeDomainDisplayPlot::setTagBackgroundStyle(Qt::BrushStyle b) -{ - d_tag_background_style = b; -} +void TimeDomainDisplayPlot::setTagBackgroundStyle(Qt::BrushStyle b) { d_tag_background_style = b; } void TimeDomainDisplayPlot::setZoomerEnabled(bool en) { - for (unsigned int i = 0; i < d_zoomer.size(); ++i) + for(unsigned int i = 0; i < d_zoomer.size(); ++i) d_zoomer[i]->setEnabled(en); } bool TimeDomainDisplayPlot::isZoomerEnabled() { - if (d_zoomer.isEmpty()) + if(d_zoomer.isEmpty()) return false; return d_zoomer[0]->isEnabled(); } void TimeDomainDisplayPlot::setZoomerVertAxis(int index) { - if (index < -1 || index >= axesCount(m_qwtYAxis)) + if(index < -1 || index >= axesCount(m_qwtYAxis)) return; - for (unsigned int i = 0; i < d_zoomer.size(); ++i) - if (d_zoomer[i]->isEnabled()) - d_zoomer[i]->setTrackerMode( - (i == index) ? QwtPicker::AlwaysOn : QwtPicker::AlwaysOff); + for(unsigned int i = 0; i < d_zoomer.size(); ++i) + if(d_zoomer[i]->isEnabled()) + d_zoomer[i]->setTrackerMode((i == index) ? QwtPicker::AlwaysOn : QwtPicker::AlwaysOff); } QString TimeDomainDisplayPlot::timeScaleValueFormat(double value, int precision) const @@ -989,70 +898,57 @@ QString TimeDomainDisplayPlot::yAxisScaleValueFormat(double value) return d_xAxisFormatter->format(value, d_yAxisUnit, scale->getFloatPrecison()); } -void -TimeDomainDisplayPlot::setYLabel(const std::string &label, - const std::string &unit, - int axisIdx) +void TimeDomainDisplayPlot::setYLabel(const std::string &label, const std::string &unit, int axisIdx) { - std::string l = label; - if(unit.length() > 0) - l += " (" + unit + ")"; - setAxisTitle(QwtAxisId(m_qwtYAxis, axisIdx), QString(l.c_str())); + std::string l = label; + if(unit.length() > 0) + l += " (" + unit + ")"; + setAxisTitle(QwtAxisId(m_qwtYAxis, axisIdx), QString(l.c_str())); } -void -TimeDomainDisplayPlot::attachTriggerLines(bool en) +void TimeDomainDisplayPlot::attachTriggerLines(bool en) { - if(en) { - d_trigger_lines[0]->attach(this); - d_trigger_lines[1]->attach(this); - } - else { - d_trigger_lines[0]->detach(); - d_trigger_lines[1]->detach(); - } + if(en) { + d_trigger_lines[0]->attach(this); + d_trigger_lines[1]->attach(this); + } else { + d_trigger_lines[0]->detach(); + d_trigger_lines[1]->detach(); + } } -void -TimeDomainDisplayPlot::setTriggerLines(double x, double y) +void TimeDomainDisplayPlot::setTriggerLines(double x, double y) { - d_trigger_lines[0]->setXValue(x); - d_trigger_lines[0]->setYValue(y); - d_trigger_lines[1]->setXValue(x); - d_trigger_lines[1]->setYValue(y); + d_trigger_lines[0]->setXValue(x); + d_trigger_lines[0]->setYValue(y); + d_trigger_lines[1]->setXValue(x); + d_trigger_lines[1]->setYValue(y); } QColor TimeDomainDisplayPlot::getChannelColor() { - for (QList::const_iterator it = d_CurveColors.cbegin(); - it != d_CurveColors.cend(); ++it) { + for(QList::const_iterator it = d_CurveColors.cbegin(); it != d_CurveColors.cend(); ++it) { bool used = false; - for (std::vector::const_iterator it2 = d_plot_curve.cbegin(); - !used && it2 != d_plot_curve.cend(); ++it2) + for(std::vector::const_iterator it2 = d_plot_curve.cbegin(); + !used && it2 != d_plot_curve.cend(); ++it2) used = (*it2)->pen().color() == (*it); - if (!used) + if(!used) return *it; } return Qt::black; } -bool TimeDomainDisplayPlot::isReferenceWaveform(QwtPlotCurve *curve) -{ - return d_ref_curves.values().contains(curve); -} - -bool TimeDomainDisplayPlot::isMathWaveform(QwtPlotCurve *curve) const -{ - return d_math_curves.values().contains(curve); -} +bool TimeDomainDisplayPlot::isReferenceWaveform(QwtPlotCurve *curve) { return d_ref_curves.values().contains(curve); } +bool TimeDomainDisplayPlot::isMathWaveform(QwtPlotCurve *curve) const { return d_math_curves.values().contains(curve); } int TimeDomainDisplayPlot::getCurveNextTo(int pos) { - while (isReferenceWaveform(Curve(pos))) pos++; + while(isReferenceWaveform(Curve(pos))) + pos++; return pos; } @@ -1064,10 +960,10 @@ int TimeDomainDisplayPlot::countReferenceWaveform(int position) QwtPlotCurve *curve = Curve(curveIdx); int count = 0; - for (size_t i = 0; i < d_plot_curve.size(); ++i) - if (d_plot_curve[i] == curve) { + for(size_t i = 0; i < d_plot_curve.size(); ++i) + if(d_plot_curve[i] == curve) { return count; - } else if (isReferenceWaveform(d_plot_curve[i])) { + } else if(isReferenceWaveform(d_plot_curve[i])) { count++; } return count; @@ -1084,8 +980,7 @@ void TimeDomainDisplayPlot::registerReferenceWaveform(QString name, QVectorsetPen(QPen(color)); curve->setRenderHint(QwtPlotItem::RenderAntialiased); - QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(color), - QPen(color), QSize(7,7)); + QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(color), QPen(color), QSize(7, 7)); curve->setSymbol(symbol); @@ -1094,7 +989,7 @@ void TimeDomainDisplayPlot::registerReferenceWaveform(QString name, QVectortitle().text() == name) { + for(i = 0; i < d_plot_curve.size(); i++) { + if(isReferenceWaveform(Curve(i))) { + if(Curve(i)->title().text() == name) { break; } else { pos++; @@ -1142,7 +1037,7 @@ void TimeDomainDisplayPlot::addDigitalPlotCurve(QwtPlotCurve *curve, bool visibl { d_logic_curves.push_back(curve); - if (visible) { + if(visible) { curve->attach(this); } @@ -1157,62 +1052,54 @@ void TimeDomainDisplayPlot::removeDigitalPlotCurve(QwtPlotCurve *curve) void TimeDomainDisplayPlot::enableDigitalPlotCurve(int curveId, bool enable) { - if (curveId < 0 || curveId > d_logic_curves.size() - 1) { + if(curveId < 0 || curveId > d_logic_curves.size() - 1) { return; } - if (enable) { + if(enable) { d_logic_curves[curveId]->attach(this); } else { d_logic_curves[curveId]->detach(); } } -int TimeDomainDisplayPlot::getNrDigitalPlotCurves() const -{ - return d_logic_curves.size(); -} +int TimeDomainDisplayPlot::getNrDigitalPlotCurves() const { return d_logic_curves.size(); } -QwtPlotCurve * TimeDomainDisplayPlot::getDigitalPlotCurve(int curveId) +QwtPlotCurve *TimeDomainDisplayPlot::getDigitalPlotCurve(int curveId) { - if (curveId < 0 || curveId > d_logic_curves.size() - 1) { + if(curveId < 0 || curveId > d_logic_curves.size() - 1) { return nullptr; } return d_logic_curves[curveId]; } -void TimeDomainDisplayPlot::addPreview(QVector > curvesToBePreviewed, double reftimebase, +void TimeDomainDisplayPlot::addPreview(QVector> curvesToBePreviewed, double reftimebase, double timebase, double timeposition) { d_preview_ydata.resize(curvesToBePreviewed[0].size()); - for (int i = 0; i < curvesToBePreviewed.size(); ++i) { - for (int j = 0; j < curvesToBePreviewed[i].size(); ++j) { + for(int i = 0; i < curvesToBePreviewed.size(); ++i) { + for(int j = 0; j < curvesToBePreviewed[i].size(); ++j) { d_preview_ydata[j].push_back(curvesToBePreviewed[i][j]); } } - - double mid_point_on_screen = (timebase * 8) - (( - timebase * 8) - timeposition); - double x_axis_step_size = (reftimebase / - (curvesToBePreviewed.size() / xAxisNumDiv())); + double mid_point_on_screen = (timebase * 8) - ((timebase * 8) - timeposition); + double x_axis_step_size = (reftimebase / (curvesToBePreviewed.size() / xAxisNumDiv())); QVector xData; - for (int i = -(curvesToBePreviewed.size() / 2); i < (curvesToBePreviewed.size() / 2); - ++i) { + for(int i = -(curvesToBePreviewed.size() / 2); i < (curvesToBePreviewed.size() / 2); ++i) { xData.push_back(mid_point_on_screen + ((double)i * x_axis_step_size)); } - for (int i = 0; i < curvesToBePreviewed[0].size(); ++i) { + for(int i = 0; i < curvesToBePreviewed[0].size(); ++i) { QwtPlotCurve *curve = new QwtPlotCurve(); curve->setSamples(xData, d_preview_ydata[i]); curve->setPen(QPen(Qt::gray)); curve->setRenderHint(QwtPlotItem::RenderAntialiased); - QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(Qt::gray), - QPen(Qt::gray), QSize(7,7)); + QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(Qt::gray), QPen(Qt::gray), QSize(7, 7)); curve->setSymbol(symbol); @@ -1221,12 +1108,11 @@ void TimeDomainDisplayPlot::addPreview(QVector > curvesToBePrevi d_preview_curves.push_back(curve); replot(); } - } void TimeDomainDisplayPlot::clearPreview() { - for (auto it = d_preview_curves.begin(); it != d_preview_curves.end(); ++it) { + for(auto it = d_preview_curves.begin(); it != d_preview_curves.end(); ++it) { (*it)->detach(); delete *it; } @@ -1235,35 +1121,30 @@ void TimeDomainDisplayPlot::clearPreview() void TimeDomainDisplayPlot::updatePreview(double reftimebase, double timebase, double timeposition) { - if (!d_preview_ydata.size()) { + if(!d_preview_ydata.size()) { return; } - double mid_point_on_screen = (timebase * 8) - (( - timebase * 8) - timeposition); - double x_axis_step_size = (reftimebase / - (d_preview_ydata[0].size() / xAxisNumDiv())); + double mid_point_on_screen = (timebase * 8) - ((timebase * 8) - timeposition); + double x_axis_step_size = (reftimebase / (d_preview_ydata[0].size() / xAxisNumDiv())); QVector xData; - for (int i = -(d_preview_ydata[0].size() / 2); i < (d_preview_ydata[0].size() / 2); - ++i) { + for(int i = -(d_preview_ydata[0].size() / 2); i < (d_preview_ydata[0].size() / 2); ++i) { xData.push_back(mid_point_on_screen + ((double)i * x_axis_step_size)); } - for (int i = 0; i < d_preview_curves.size(); ++i) { + for(int i = 0; i < d_preview_curves.size(); ++i) { d_preview_curves[i]->setSamples(xData, d_preview_ydata[i]); replot(); } - - } void TimeDomainDisplayPlot::configureAllYAxis() { int yAxisSize = vertAxes.size(); - for (int i = 0; i < yAxisSize; i++) { - if (d_xAxisFormatter) { + for(int i = 0; i < yAxisSize; i++) { + if(d_xAxisFormatter) { configureAxis(m_qwtYAxis, i, d_xAxisFormatter); } else { configureAxis(m_qwtYAxis, i, new MetricPrefixFormatter()); @@ -1276,20 +1157,19 @@ void TimeDomainDisplayPlot::realignReferenceWaveforms(double timebase, double ti QList curves = d_ref_curves.values(); - for (auto &curve : curves) { - double x_axis_step_size = curve->data()->sample(1).x() - - curve->data()->sample(0).x(); + for(auto &curve : curves) { + double x_axis_step_size = curve->data()->sample(1).x() - curve->data()->sample(0).x(); double mid_point_on_screen = (timebase * 8) - ((timebase * 8) - timeposition); int nr_of_samples_in_file = curve->data()->size(); QVector xData; QVector yData; - for (int i = -(nr_of_samples_in_file / 2); i < (nr_of_samples_in_file / 2); ++i) { + for(int i = -(nr_of_samples_in_file / 2); i < (nr_of_samples_in_file / 2); ++i) { xData.push_back(mid_point_on_screen + ((double)i * x_axis_step_size)); } - for (int i = 0; i < nr_of_samples_in_file; ++i) + for(int i = 0; i < nr_of_samples_in_file; ++i) yData.push_back(curve->data()->sample(i).y()); curve->setSamples(xData, yData); @@ -1297,28 +1177,27 @@ void TimeDomainDisplayPlot::realignReferenceWaveforms(double timebase, double ti } bool TimeDomainDisplayPlot::registerMathWaveform(const std::string &sinkUniqueNme, unsigned int numChannels, - unsigned long long channelsDataLength, bool curvesAttached) + unsigned long long channelsDataLength, bool curvesAttached) { bool ret = registerSink(sinkUniqueNme, numChannels, channelsDataLength, curvesAttached); - if (ret) { + if(ret) { d_math_curves.insert(QString::fromStdString(sinkUniqueNme), d_plot_curve.back()); } return ret; } - bool TimeDomainDisplayPlot::registerSink(std::string sinkUniqueNme, unsigned int numChannels, - unsigned long long channelsDataLength, bool curvesAttached) + unsigned long long channelsDataLength, bool curvesAttached) { bool ret; ret = d_sinkManager.addSink(sinkUniqueNme, numChannels, channelsDataLength); - if (ret) { + if(ret) { int numCurves = d_ydata.size(); int sinkIndex = d_sinkManager.indexOfSink(sinkUniqueNme); d_xdata.push_back(new double[channelsDataLength]); - for (size_t i = 0; i < numChannels; i++) { + for(size_t i = 0; i < numChannels; i++) { int n = i + numCurves; d_ydata.push_back(new double[channelsDataLength]); memset(d_ydata[n], 0x0, channelsDataLength * sizeof(double)); @@ -1331,10 +1210,9 @@ bool TimeDomainDisplayPlot::registerSink(std::string sinkUniqueNme, unsigned int d_plot_curve.push_back(curve); curve->setItemAttribute(QwtPlotItem::Legend, true); - QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(color), - QPen(color), QSize(7,7)); + QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(color), QPen(color), QSize(7, 7)); - if (sinkIndex >= 1) { + if(sinkIndex >= 1) { d_plot_curve.back()->setPaintAttribute(QwtPlotCurve::ClipPolygons, false); d_plot_curve.back()->setPaintAttribute(QwtPlotCurve::FilterPointsAggressive, true); } @@ -1344,7 +1222,7 @@ bool TimeDomainDisplayPlot::registerSink(std::string sinkUniqueNme, unsigned int d_plot_curve.back()->setCurveFitter(new SmoothCurveFitter()); - if (curvesAttached) + if(curvesAttached) d_plot_curve.back()->attach(this); Q_EMIT channelAdded(n + d_nb_ref_curves); @@ -1362,7 +1240,7 @@ bool TimeDomainDisplayPlot::registerSink(std::string sinkUniqueNme, unsigned int bool TimeDomainDisplayPlot::unregisterMathWaveform(const std::string &sinkName) { int ret = unregisterSink(sinkName); - if (ret) { + if(ret) { d_math_curves.remove(QString::fromStdString(sinkName)); } return ret; @@ -1373,7 +1251,7 @@ bool TimeDomainDisplayPlot::unregisterSink(std::string sinkName) bool ret = false; int sinkIndex = d_sinkManager.indexOfSink(sinkName); - if (sinkIndex >= 0) { + if(sinkIndex >= 0) { // Remove X axis associated with the channels of the sink delete[] d_xdata[sinkIndex]; @@ -1382,21 +1260,21 @@ bool TimeDomainDisplayPlot::unregisterSink(std::string sinkName) // Remove Y axes corresponding to each channel of the sink int offset = d_sinkManager.sinkFirstChannelPos(sinkName); int numChannels = d_sinkManager.sink(sinkIndex)->numChannels(); - for (int i = offset; i < offset + numChannels; i++) { + for(int i = offset; i < offset + numChannels; i++) { cleanUpJustBeforeChannelRemoval(offset); - delete [] d_ydata[i]; + delete[] d_ydata[i]; } d_ydata.erase(d_ydata.begin() + offset, d_ydata.begin() + offset + numChannels); /* Remove the QwtPlotCurve */ int ref_offset = countReferenceWaveform(offset); - for (int i = offset; i < offset + numChannels; i++) { + for(int i = offset; i < offset + numChannels; i++) { d_plot_curve[i + ref_offset]->detach(); delete d_plot_curve[i + ref_offset]; } d_plot_curve.erase(d_plot_curve.begin() + offset + ref_offset, - d_plot_curve.begin() + ref_offset + offset + numChannels); + d_plot_curve.begin() + ref_offset + offset + numChannels); // Finally remove the sink ret = d_sinkManager.removeSink(sinkName); @@ -1404,21 +1282,20 @@ bool TimeDomainDisplayPlot::unregisterSink(std::string sinkName) d_nplots -= numChannels; d_tag_markers.resize(d_nplots); - d_sink_reset_x_axis_pts.erase(d_sink_reset_x_axis_pts.begin() + - sinkIndex); + d_sink_reset_x_axis_pts.erase(d_sink_reset_x_axis_pts.begin() + sinkIndex); } return ret; } -void TimeDomainDisplayPlot::configureAxis(int axisPos, int axisIdx, PrefixFormatter* prefixFormatter) +void TimeDomainDisplayPlot::configureAxis(int axisPos, int axisIdx, PrefixFormatter *prefixFormatter) { QwtAxisId axis(axisPos, axisIdx); QString unit; unsigned int floatPrecision; unsigned int numDivs; - if (axisPos == m_qwtYAxis) { + if(axisPos == m_qwtYAxis) { d_xAxisFormatter = prefixFormatter; unit = d_yAxisUnit; floatPrecision = 2; @@ -1439,65 +1316,57 @@ void TimeDomainDisplayPlot::configureAxis(int axisPos, int axisIdx, PrefixFormat OscScaleDraw *scaleDraw = new OscScaleDraw(prefixFormatter, unit); scaleDraw->setFloatPrecision(floatPrecision); this->setAxisScaleDraw(axis, scaleDraw); - if (axisPos == QwtAxis::YLeft) { - //yLeft 0 has a different position than the rest, so we - //give it a bigger minimum extent in order to align it with - //the other yLeft axes. - if (axisIdx == 0) + if(axisPos == QwtAxis::YLeft) { + // yLeft 0 has a different position than the rest, so we + // give it a bigger minimum extent in order to align it with + // the other yLeft axes. + if(axisIdx == 0) scaleDraw->setMinimumExtent(94); else scaleDraw->setMinimumExtent(65); } } -void TimeDomainDisplayPlot::cleanUpJustBeforeChannelRemoval(int) -{ -} +void TimeDomainDisplayPlot::cleanUpJustBeforeChannelRemoval(int) {} void TimeDomainDisplayPlot::cancelZoom() { - for (unsigned int i = 0; i < d_zoomer.size(); ++i) { + for(unsigned int i = 0; i < d_zoomer.size(); ++i) { OscPlotZoomer *zoomer = static_cast(d_zoomer[i]); zoomer->resetZoom(); } } -long TimeDomainDisplayPlot::dataStartingPoint() const -{ - return d_data_starting_point; -} +long TimeDomainDisplayPlot::dataStartingPoint() const { return d_data_starting_point; } void TimeDomainDisplayPlot::resetXaxisOnNextReceivedData() { - for (size_t i = 0; i < d_sink_reset_x_axis_pts.size(); i++) + for(size_t i = 0; i < d_sink_reset_x_axis_pts.size(); i++) d_sink_reset_x_axis_pts[i] = true; } -void TimeDomainDisplayPlot::setDataStartingPoint(long pos) -{ - d_data_starting_point = pos; -} +void TimeDomainDisplayPlot::setDataStartingPoint(long pos) { d_data_starting_point = pos; } void TimeDomainDisplayPlot::setLineWidthF(int which, qreal widthF) { - if (which < d_plot_curve.size()) { - QPen pen(d_plot_curve[which]->pen()); - pen.setWidthF(widthF); - d_plot_curve[which]->setPen(pen); - } + if(which < d_plot_curve.size()) { + QPen pen(d_plot_curve[which]->pen()); + pen.setWidthF(widthF); + d_plot_curve[which]->setPen(pen); + } } qreal TimeDomainDisplayPlot::getLineWidthF(int which) const { - if (which < d_plot_curve.size()) - return d_plot_curve[which]->pen().widthF(); - else - return 0; + if(which < d_plot_curve.size()) + return d_plot_curve[which]->pen().widthF(); + else + return 0; } void TimeDomainDisplayPlot::hideCurvesUntilNewData() { - for (size_t i = 0; i < d_plot_curve.size(); i++) + for(size_t i = 0; i < d_plot_curve.size(); i++) d_plot_curve.at(i)->hide(); d_curves_hidden = true; } diff --git a/gui/src/WaterfallDisplayPlot.cc b/gui/src/WaterfallDisplayPlot.cc index afeee4ea7d..dbc759125f 100644 --- a/gui/src/WaterfallDisplayPlot.cc +++ b/gui/src/WaterfallDisplayPlot.cc @@ -31,16 +31,17 @@ #define WATERFALL_DISPLAY_PLOT_C #include "WaterfallDisplayPlot.h" + #include "osc_scale_engine.h" -#include "spectrumUpdateEvents.h" #include "qtgui_types.h" +#include "spectrumUpdateEvents.h" +#include #include #include +#include #include #include -#include -#include #if QWT_VERSION < 0x060100 #include @@ -62,14 +63,13 @@ using namespace scopy; /*********************************************************************** * Widget to provide mouse pointer coordinate text **********************************************************************/ -class WaterfallZoomer : public LimitedPlotZoomer, - public TimeScaleData +class WaterfallZoomer : public LimitedPlotZoomer, public TimeScaleData { public: #if QWT_VERSION < 0x060100 - WaterfallZoomer(QwtPlotCanvas* canvas, const unsigned int freqPrecision) + WaterfallZoomer(QwtPlotCanvas *canvas, const unsigned int freqPrecision) #else /* QWT_VERSION < 0x060100 */ - WaterfallZoomer(QWidget* canvas) + WaterfallZoomer(QWidget *canvas) #endif /* QWT_VERSION < 0x060100 */ : LimitedPlotZoomer(canvas) { @@ -80,20 +80,17 @@ class WaterfallZoomer : public LimitedPlotZoomer, virtual void updateTrackerText() { updateDisplay(); } - void setUnitType(const std::string& type) { d_unitType = type; } + void setUnitType(const std::string &type) { d_unitType = type; } void setCenterTime(double value) { centerTime = value; } protected: using QwtPlotZoomer::trackerText; - QwtText trackerText(QPoint const& p) const override + QwtText trackerText(QPoint const &p) const override { QwtDoublePoint dp = QwtPlotZoomer::invTransform(p); double secs = double(centerTime + dp.y() * getSecondsPerLine()); - QwtText t(QString("(%1 %2, %3 s)") - .arg(dp.x(), 0, 'f', 4) - .arg(d_unitType.c_str()) - .arg(secs, 0, 'f', 4)); + QwtText t(QString("(%1 %2, %3 s)").arg(dp.x(), 0, 'f', 4).arg(d_unitType.c_str()).arg(secs, 0, 'f', 4)); return t; } @@ -105,7 +102,7 @@ class WaterfallZoomer : public LimitedPlotZoomer, /********************************************************************* * Main waterfall plot widget *********************************************************************/ -WaterfallDisplayPlot::WaterfallDisplayPlot(int nplots, QWidget* parent) +WaterfallDisplayPlot::WaterfallDisplayPlot(int nplots, QWidget *parent) : DisplayPlot(nplots, parent) { d_zoomer.push_back(nullptr); // need this for proper init @@ -122,13 +119,12 @@ WaterfallDisplayPlot::WaterfallDisplayPlot(int nplots, QWidget* parent) d_formatter = static_cast(new MetricPrefixFormatter); resetAvgAcquisitionTime(); - for (unsigned int i = 0; i < d_nplots; ++i) { - d_data.push_back( - new WaterfallData(d_start_frequency, d_stop_frequency, d_numPoints, d_nrows)); + for(unsigned int i = 0; i < d_nplots; ++i) { + d_data.push_back(new WaterfallData(d_start_frequency, d_stop_frequency, d_numPoints, d_nrows)); #if QWT_VERSION < 0x060000 - d_spectrogram.push_back(new PlotWaterfall(d_data[i] waterfall_plot->setIntensityRange(bottom_value, top_value); - , "Spectrogram")); + d_spectrogram.push_back(new PlotWaterfall( + d_data[i] waterfall_plot->setIntensityRange(bottom_value, top_value);, "Spectrogram")); #else d_spectrogram.push_back(new QwtPlotSpectrogram("Spectrogram")); @@ -144,10 +140,8 @@ WaterfallDisplayPlot::WaterfallDisplayPlot(int nplots, QWidget* parent) d_spectrogram[i]->attach(this); - d_intensity_color_map_type.push_back( - INTENSITY_COLOR_MAP_TYPE_DEFAULT_DARK); - setIntensityColorMapType( - i, d_intensity_color_map_type[i], QColor("black"), QColor("white")); + d_intensity_color_map_type.push_back(INTENSITY_COLOR_MAP_TYPE_DEFAULT_DARK); + setIntensityColorMapType(i, d_intensity_color_map_type[i], QColor("black"), QColor("white")); setAlpha(i, 255); } @@ -161,8 +155,7 @@ WaterfallDisplayPlot::WaterfallDisplayPlot(int nplots, QWidget* parent) #if QWT_VERSION < 0x060000 d_zoomer[0]->setSelectionFlags(QwtPicker::RectSelection | QwtPicker::DragSelection); #endif - d_zoomer[0]->setMousePattern( - QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); + d_zoomer[0]->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); d_zoomer[0]->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); const QColor c("#999999"); @@ -223,7 +216,8 @@ WaterfallDisplayPlot::WaterfallDisplayPlot(int nplots, QWidget* parent) installEventFilter(this); } -WaterfallDisplayPlot::~WaterfallDisplayPlot() { +WaterfallDisplayPlot::~WaterfallDisplayPlot() +{ removeEventFilter(this); canvas()->removeEventFilter(d_cursorReadouts); canvas()->removeEventFilter(d_symbolCtrl); @@ -249,27 +243,29 @@ void WaterfallDisplayPlot::onHCursor1Moved(double value) { QString text; bool error = false; - if (d_trackMode) { - if (value == ERROR_VALUE) { + if(d_trackMode) { + if(value == ERROR_VALUE) { error = true; } } value *= d_displayScale; - value = getFlowDirection() == WaterfallFlowDirection::UP ? value * d_avg_acquisition_time: - value * d_avg_acquisition_time * -1 + d_center_plot_time; + value = getFlowDirection() == WaterfallFlowDirection::UP + ? value * d_avg_acquisition_time + : value * d_avg_acquisition_time * -1 + d_center_plot_time; text = d_formatter->format(value, d_yAxisUnit, 3); d_cursorReadouts->setVoltageCursor1Text(error ? "-" : text); d_cursorReadoutsText.t1 = error ? "-" : text; double valueCursor2; - if (d_trackMode) { + if(d_trackMode) { valueCursor2 = getHorizontalCursorIntersection(d_vBar2->plotCoord().x()); } else { valueCursor2 = d_hBar2->plotCoord().y(); } - valueCursor2 = getFlowDirection() == WaterfallFlowDirection::UP ? valueCursor2 * d_avg_acquisition_time: - valueCursor2 * d_avg_acquisition_time * -1 + d_center_plot_time; + valueCursor2 = getFlowDirection() == WaterfallFlowDirection::UP + ? valueCursor2 * d_avg_acquisition_time + : valueCursor2 * d_avg_acquisition_time * -1 + d_center_plot_time; double diff = value - (valueCursor2 * d_displayScale); text = d_formatter->format(diff, d_yAxisUnit, 3); @@ -283,28 +279,30 @@ void WaterfallDisplayPlot::onHCursor2Moved(double value) { QString text; bool error = false; - if (d_trackMode) { - if (value == ERROR_VALUE) { + if(d_trackMode) { + if(value == ERROR_VALUE) { error = true; } } value *= d_displayScale; - value = getFlowDirection() == WaterfallFlowDirection::UP ? value * d_avg_acquisition_time: - value * d_avg_acquisition_time * -1 + d_center_plot_time; + value = getFlowDirection() == WaterfallFlowDirection::UP + ? value * d_avg_acquisition_time + : value * d_avg_acquisition_time * -1 + d_center_plot_time; text = d_formatter->format(value, d_yAxisUnit, 3); d_cursorReadouts->setVoltageCursor2Text(error ? "-" : text); d_cursorReadoutsText.t2 = error ? "-" : text; double valueCursor1; - if (d_trackMode) { + if(d_trackMode) { valueCursor1 = getHorizontalCursorIntersection(d_vBar1->plotCoord().x()); } else { valueCursor1 = d_hBar1->plotCoord().y(); } - valueCursor1 = getFlowDirection() == WaterfallFlowDirection::UP ? valueCursor1 * d_avg_acquisition_time: - valueCursor1 * d_avg_acquisition_time * -1 + d_center_plot_time; + valueCursor1 = getFlowDirection() == WaterfallFlowDirection::UP + ? valueCursor1 * d_avg_acquisition_time + : valueCursor1 * d_avg_acquisition_time * -1 + d_center_plot_time; double diff = (valueCursor1 * d_displayScale) - value; text = d_formatter->format(diff, d_yAxisUnit, 3); @@ -326,7 +324,7 @@ void WaterfallDisplayPlot::onVCursor1Moved(double value) d_cursorReadouts->setTimeDeltaText(text); d_cursorReadoutsText.vDelta = text; - if (d_trackMode) { + if(d_trackMode) { onHCursor1Moved(getHorizontalCursorIntersection(d_vBar1->plotCoord().x())); } @@ -345,7 +343,7 @@ void WaterfallDisplayPlot::onVCursor2Moved(double value) d_cursorReadouts->setTimeDeltaText(text); d_cursorReadoutsText.vDelta = text; - if (d_trackMode) { + if(d_trackMode) { onHCursor2Moved(getHorizontalCursorIntersection(d_vBar2->plotCoord().x())); } @@ -360,11 +358,11 @@ void WaterfallDisplayPlot::updateCursorsData() bool WaterfallDisplayPlot::eventFilter(QObject *object, QEvent *event) { - if (object == canvas() && event->type() == QEvent::Resize) { + if(object == canvas() && event->type() == QEvent::Resize) { updateHandleAreaPadding(); - //force cursor handles to emit position changed - //when the plot canvas is being resized + // force cursor handles to emit position changed + // when the plot canvas is being resized d_hCursorHandle1->triggerMove(); d_hCursorHandle2->triggerMove(); d_vCursorHandle1->triggerMove(); @@ -378,7 +376,7 @@ void WaterfallDisplayPlot::updateHandleAreaPadding() d_leftHandlesArea->update(); d_bottomHandlesArea->setLeftPadding(d_leftHandlesArea->width()); - //update handle position to avoid cursors getting out of the plot bounds when changing the padding; + // update handle position to avoid cursors getting out of the plot bounds when changing the padding; d_hCursorHandle1->updatePosition(); d_hCursorHandle2->updatePosition(); d_vCursorHandle1->updatePosition(); @@ -407,9 +405,9 @@ void WaterfallDisplayPlot::enableXaxisLabels() void WaterfallDisplayPlot::resetAxis(bool resetData) { - for (unsigned int i = 0; i < d_nplots; ++i) { + for(unsigned int i = 0; i < d_nplots; ++i) { d_data[i]->resizeData(d_start_frequency, d_stop_frequency, d_numPoints, d_nrows); - if (resetData) { + if(resetData) { d_data[i]->reset(); } } @@ -426,22 +424,22 @@ void WaterfallDisplayPlot::resetAxis(bool resetData) void WaterfallDisplayPlot::setLeftVertAxisUnit(const QString &unit) { - if (d_yAxisUnit != unit) { + if(d_yAxisUnit != unit) { d_yAxisUnit = unit; - auto scale_draw = dynamic_cast(axisScaleDraw(QwtAxis::YLeft)); - if (scale_draw) + auto scale_draw = dynamic_cast(axisScaleDraw(QwtAxis::YLeft)); + if(scale_draw) scale_draw->setUnitType(unit); } } void WaterfallDisplayPlot::setBtmHorAxisUnit(const QString &unit) { - if (d_xAxisUnit != unit) { + if(d_xAxisUnit != unit) { d_xAxisUnit = unit; - auto scale_draw = dynamic_cast(axisScaleDraw(QwtAxis::XBottom)); - if (scale_draw) + auto scale_draw = dynamic_cast(axisScaleDraw(QwtAxis::XBottom)); + if(scale_draw) scale_draw->setUnitType(unit); } } @@ -453,55 +451,50 @@ QString WaterfallDisplayPlot::formatXValue(double value, int precision) const QString WaterfallDisplayPlot::formatYValue(double value, int precision) const { - value = getFlowDirection() == WaterfallFlowDirection::UP ? value * d_avg_acquisition_time: - value * d_avg_acquisition_time * -1 + d_center_plot_time; + value = getFlowDirection() == WaterfallFlowDirection::UP + ? value * d_avg_acquisition_time + : value * d_avg_acquisition_time * -1 + d_center_plot_time; return d_formatter->format(value, d_yAxisUnit, precision); } void WaterfallDisplayPlot::autoScale() -{ +{ qDebug() << d_min_val << d_max_val; setIntensityRange(d_min_val, d_max_val); } -void WaterfallDisplayPlot::setCenterFrequency(const double freq) -{ - d_center_frequency = freq; -} +void WaterfallDisplayPlot::setCenterFrequency(const double freq) { d_center_frequency = freq; } -void WaterfallDisplayPlot::setFrequencyRange(const double centerfreq, - const double bandwidth, - const double units, - const std::string& strunits) +void WaterfallDisplayPlot::setFrequencyRange(const double centerfreq, const double bandwidth, const double units, + const std::string &strunits) { double startFreq; double stopFreq = (centerfreq + bandwidth / 2.0f) / units; - if (d_half_freq) + if(d_half_freq) startFreq = centerfreq / units; else startFreq = (centerfreq - bandwidth / 2.0f) / units; - d_xaxis_multiplier = units; bool reset = false; - if ((startFreq != d_start_frequency) || (stopFreq != d_stop_frequency)) + if((startFreq != d_start_frequency) || (stopFreq != d_stop_frequency)) reset = true; - if (stopFreq > startFreq) { + if(stopFreq > startFreq) { d_start_frequency = startFreq; d_stop_frequency = stopFreq; d_center_frequency = centerfreq / units; - if ((axisScaleDraw(QwtAxis::XBottom) != NULL) && (d_zoomer[0] != NULL)) { + if((axisScaleDraw(QwtAxis::XBottom) != NULL) && (d_zoomer[0] != NULL)) { double display_units = ceil(log10(units) / 2.0); - if (reset) { + if(reset) { resetAxis(); } - ((WaterfallZoomer*)d_zoomer[0])->setUnitType(strunits); + ((WaterfallZoomer *)d_zoomer[0])->setUnitType(strunits); } } } @@ -509,10 +502,10 @@ void WaterfallDisplayPlot::setFrequencyRange(const double centerfreq, WaterfallFlowDirection WaterfallDisplayPlot::getFlowDirection() const { auto direction = WaterfallFlowDirection::UP; - for (unsigned int i = 0; i < d_nplots; ++i) { - if (i == 0) { + for(unsigned int i = 0; i < d_nplots; ++i) { + if(i == 0) { direction = d_data[i]->getFlowDirection(); - } else if (direction != d_data[i]->getFlowDirection()) { + } else if(direction != d_data[i]->getFlowDirection()) { d_data[i]->setFlowDirection(direction); } } @@ -520,23 +513,17 @@ WaterfallFlowDirection WaterfallDisplayPlot::getFlowDirection() const return direction; } -int WaterfallDisplayPlot::getEnabledChannelID() -{ - return enabledChannelID; -} +int WaterfallDisplayPlot::getEnabledChannelID() { return enabledChannelID; } void WaterfallDisplayPlot::setFlowDirection(WaterfallFlowDirection direction) { - for (unsigned int i = 0; i < d_nplots; ++i) { + for(unsigned int i = 0; i < d_nplots; ++i) { d_data[i]->setFlowDirection(direction); d_data[i]->reset(); } } -void WaterfallDisplayPlot::setResolutionBW(double value) -{ - d_resolution_bw = value; -} +void WaterfallDisplayPlot::setResolutionBW(double value) { d_resolution_bw = value; } double WaterfallDisplayPlot::getStartFrequency() const { return d_start_frequency; } @@ -544,16 +531,17 @@ double WaterfallDisplayPlot::getResolutionBW() const { return d_resolution_bw; } double WaterfallDisplayPlot::getStopFrequency() const { return d_stop_frequency; } -void WaterfallDisplayPlot::plotNewData(const std::vector &dataPoints, - const int64_t numDataPoints, +void WaterfallDisplayPlot::plotNewData(const std::vector &dataPoints, const int64_t numDataPoints, gr::high_res_timer_type acquisitionTime) { // Display first half of the plot if d_half_freq is true - int64_t _npoints_in = d_half_freq ? (getStopFrequency() - getStartFrequency()) / getResolutionBW() : numDataPoints; + int64_t _npoints_in = + d_half_freq ? (getStopFrequency() - getStartFrequency()) / getResolutionBW() : numDataPoints; int64_t _in_index = d_half_freq ? getStartFrequency() / getResolutionBW() : 0; // there was a fft resize meanwhile event was being sent - if (_npoints_in > numDataPoints - _in_index) return; + if(_npoints_in > numDataPoints - _in_index) + return; double current_time = gr::high_res_timer_now(); @@ -561,19 +549,20 @@ void WaterfallDisplayPlot::plotNewData(const std::vector &dataPoints, double seconds_per_line = (current_time - d_last_draw_time) / 1000000000.; // compute avg acquisition time - if (d_avg_acquisition_time == -1) { + if(d_avg_acquisition_time == -1) { // avg time was reset d_avg_acquisition_time = seconds_per_line; } else { - d_avg_acquisition_time = (d_avg_acquisition_time * (d_visible_line_count - 1) + seconds_per_line) / d_visible_line_count; + d_avg_acquisition_time = + (d_avg_acquisition_time * (d_visible_line_count - 1) + seconds_per_line) / d_visible_line_count; } d_last_draw_time = current_time; double time_per_line = d_avg_acquisition_time; double centerTime = 0; - if (getFlowDirection() == WaterfallFlowDirection::DOWN) { + if(getFlowDirection() == WaterfallFlowDirection::DOWN) { time_per_line *= -1; centerTime = -getNumRows() * time_per_line; } @@ -581,24 +570,24 @@ void WaterfallDisplayPlot::plotNewData(const std::vector &dataPoints, d_center_plot_time = centerTime; updateCursorsData(); - if (!d_stop && _npoints_in > 0) { + if(!d_stop && _npoints_in > 0) { d_leftHandlesArea->update(); d_bottomHandlesArea->update(); - ((WaterfallZoomer*)d_zoomer[0])->setSecondsPerLine(time_per_line); - ((WaterfallZoomer*)d_zoomer[0])->setCenterTime(centerTime); + ((WaterfallZoomer *)d_zoomer[0])->setSecondsPerLine(time_per_line); + ((WaterfallZoomer *)d_zoomer[0])->setCenterTime(centerTime); - if (_npoints_in != d_numPoints) { + if(_npoints_in != d_numPoints) { d_numPoints = _npoints_in; resetAxis(); - for (unsigned int i = 0; i < d_nplots; ++i) { + for(unsigned int i = 0; i < d_nplots; ++i) { d_spectrogram[i]->invalidateCache(); d_spectrogram[i]->itemChanged(); } } else { - for (int i = 0; i &dataPoints, replot(); d_visible_line_count = std::min(d_visible_line_count + 1, d_nrows); - } + } Q_EMIT newWaterfallData(); } void WaterfallDisplayPlot::useLogFreq(bool use_log_freq) { - if (use_log_freq && d_half_freq) { + if(use_log_freq && d_half_freq) { setPlotLogaritmic(true); setAxisScaleEngine(QwtAxis::XBottom, new QwtLogScaleEngine); replot(); @@ -638,13 +627,12 @@ void WaterfallDisplayPlot::useLogFreq(bool use_log_freq) replot(); } -void WaterfallDisplayPlot::setIntensityRange(double minIntensity, - double maxIntensity) +void WaterfallDisplayPlot::setIntensityRange(double minIntensity, double maxIntensity) { minIntensity += d_intensity_offset; maxIntensity += d_intensity_offset; - for (unsigned int i = 0; i < d_nplots; ++i) { + for(unsigned int i = 0; i < d_nplots; ++i) { #if QWT_VERSION < 0x060000 d_data[i]->setRange(QwtDoubleInterval(minIntensity, maxIntensity)); #else @@ -680,37 +668,30 @@ double WaterfallDisplayPlot::getMaxIntensity(unsigned int which) const return r.maxValue(); } -int WaterfallDisplayPlot::getColorMapTitleFontSize() const -{ - return d_color_bar_title_font_size; -} +int WaterfallDisplayPlot::getColorMapTitleFontSize() const { return d_color_bar_title_font_size; } -void WaterfallDisplayPlot::setColorMapTitleFontSize(int tfs) -{ - d_color_bar_title_font_size = tfs; -} +void WaterfallDisplayPlot::setColorMapTitleFontSize(int tfs) { d_color_bar_title_font_size = tfs; } void WaterfallDisplayPlot::replot() { d_leftHandlesArea->update(); d_bottomHandlesArea->update(); - FreqDisplayScaleDraw* freqScale = - (FreqDisplayScaleDraw*)axisScaleDraw(QwtAxis::XBottom); -// freqScale->initiateUpdate(); + FreqDisplayScaleDraw *freqScale = (FreqDisplayScaleDraw *)axisScaleDraw(QwtAxis::XBottom); + // freqScale->initiateUpdate(); // Update the time axis display - if (axisWidget(QwtAxis::YLeft) != NULL) { + if(axisWidget(QwtAxis::YLeft) != NULL) { axisWidget(QwtAxis::YLeft)->update(); } // Update the Frequency Offset Display - if (axisWidget(QwtAxis::XBottom) != NULL) { + if(axisWidget(QwtAxis::XBottom) != NULL) { axisWidget(QwtAxis::XBottom)->update(); } - if (d_zoomer[0] != NULL) { - ((WaterfallZoomer*)d_zoomer[0])->updateTrackerText(); + if(d_zoomer[0] != NULL) { + ((WaterfallZoomer *)d_zoomer[0])->updateTrackerText(); } BasicPlot::replot(); @@ -718,26 +699,22 @@ void WaterfallDisplayPlot::replot() void WaterfallDisplayPlot::clearData() { - for (unsigned int i = 0; i < d_nplots; ++i) { + for(unsigned int i = 0; i < d_nplots; ++i) { d_data[i]->reset(); } } - int WaterfallDisplayPlot::getIntensityColorMapType(unsigned int which) const { return d_intensity_color_map_type[which]; } -void WaterfallDisplayPlot::setIntensityColorMapType(const unsigned int which, - const int newType, - const QColor lowColor, +void WaterfallDisplayPlot::setIntensityColorMapType(const unsigned int which, const int newType, const QColor lowColor, const QColor highColor) { - if ((d_intensity_color_map_type[which] != newType) || - ((newType == INTENSITY_COLOR_MAP_TYPE_USER_DEFINED) && - (lowColor.isValid() && highColor.isValid()))) { - switch (newType) { + if((d_intensity_color_map_type[which] != newType) || + ((newType == INTENSITY_COLOR_MAP_TYPE_USER_DEFINED) && (lowColor.isValid() && highColor.isValid()))) { + switch(newType) { case INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR: { d_intensity_color_map_type[which] = newType; #if QWT_VERSION < 0x060000 @@ -806,8 +783,7 @@ void WaterfallDisplayPlot::setIntensityColorMapType(const unsigned int which, ColorMap_UserDefined colorMap(lowColor, highColor); d_spectrogram[which]->setColorMap(colorMap); #else - d_spectrogram[which]->setColorMap( - new ColorMap_UserDefined(lowColor, highColor)); + d_spectrogram[which]->setColorMap(new ColorMap_UserDefined(lowColor, highColor)); #endif break; } @@ -831,72 +807,49 @@ void WaterfallDisplayPlot::setIntensityColorMapType(const unsigned int which, void WaterfallDisplayPlot::setIntensityColorMapType1(int newType) { - setIntensityColorMapType(0, - newType, - d_user_defined_low_intensity_color, - d_user_defined_high_intensity_color); + setIntensityColorMapType(0, newType, d_user_defined_low_intensity_color, d_user_defined_high_intensity_color); } -int WaterfallDisplayPlot::getIntensityColorMapType1() const -{ - return getIntensityColorMapType(0); -} +int WaterfallDisplayPlot::getIntensityColorMapType1() const { return getIntensityColorMapType(0); } -void WaterfallDisplayPlot::setUserDefinedLowIntensityColor(QColor c) -{ - d_user_defined_low_intensity_color = c; -} +void WaterfallDisplayPlot::setUserDefinedLowIntensityColor(QColor c) { d_user_defined_low_intensity_color = c; } const QColor WaterfallDisplayPlot::getUserDefinedLowIntensityColor() const { return d_user_defined_low_intensity_color; } -void WaterfallDisplayPlot::setUserDefinedHighIntensityColor(QColor c) -{ - d_user_defined_high_intensity_color = c; -} +void WaterfallDisplayPlot::setUserDefinedHighIntensityColor(QColor c) { d_user_defined_high_intensity_color = c; } const QColor WaterfallDisplayPlot::getUserDefinedHighIntensityColor() const { return d_user_defined_high_intensity_color; } -int WaterfallDisplayPlot::getAlpha(unsigned int which) -{ - return d_spectrogram[which]->alpha(); -} +int WaterfallDisplayPlot::getAlpha(unsigned int which) { return d_spectrogram[which]->alpha(); } -void WaterfallDisplayPlot::setAlpha(unsigned int which, int alpha) -{ - d_spectrogram[which]->setAlpha(alpha); -} +void WaterfallDisplayPlot::setAlpha(unsigned int which, int alpha) { d_spectrogram[which]->setAlpha(alpha); } int WaterfallDisplayPlot::getNumRows() const { return d_nrows; } -void WaterfallDisplayPlot::enableChannel(int id) -{ - enabledChannelID = id; -} +void WaterfallDisplayPlot::enableChannel(int id) { enabledChannelID = id; } void WaterfallDisplayPlot::_updateIntensityRangeDisplay() { - QwtScaleWidget* rightAxis = axisWidget(QwtAxis::YRight); + QwtScaleWidget *rightAxis = axisWidget(QwtAxis::YRight); QwtText colorBarTitle("Intensity (dB)"); colorBarTitle.setFont(QFont("Arial", d_color_bar_title_font_size)); rightAxis->setTitle(colorBarTitle); rightAxis->setColorBarEnabled(true); - for (unsigned int i = 0; i < d_nplots; ++i) { + for(unsigned int i = 0; i < d_nplots; ++i) { #if QWT_VERSION < 0x060000 - rightAxis->setColorMap(d_spectrogram[i]->data()->range(), - d_spectrogram[i]->colorMap()); - setAxisScale(QwtAxis::YRight, - d_spectrogram[i]->data()->range().minValue(), + rightAxis->setColorMap(d_spectrogram[i]->data()->range(), d_spectrogram[i]->colorMap()); + setAxisScale(QwtAxis::YRight, d_spectrogram[i]->data()->range().minValue(), d_spectrogram[i]->data()->range().maxValue()); #else QwtInterval intv = d_spectrogram[i]->interval(Qt::ZAxis); - switch (d_intensity_color_map_type[i]) { + switch(d_intensity_color_map_type[i]) { case INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR: rightAxis->setColorMap(intv, new ColorMap_MultiColor()); break; @@ -916,10 +869,9 @@ void WaterfallDisplayPlot::_updateIntensityRangeDisplay() rightAxis->setColorMap(intv, new ColorMap_Cool()); break; case INTENSITY_COLOR_MAP_TYPE_USER_DEFINED: - rightAxis->setColorMap( - intv, - new ColorMap_UserDefined(d_user_defined_low_intensity_color, - d_user_defined_high_intensity_color)); + rightAxis->setColorMap(intv, + new ColorMap_UserDefined(d_user_defined_low_intensity_color, + d_user_defined_high_intensity_color)); break; case INTENSITY_COLOR_MAP_TYPE_DEFAULT_DARK: rightAxis->setColorMap(intv, new ColorMap_DefaultDark()); @@ -960,10 +912,7 @@ void WaterfallDisplayPlot::enableLegend(bool en) setAxisAutoScale(QwtAxis::YRight, en); } -void WaterfallDisplayPlot::setNumRows(int nrows) -{ - d_nrows = nrows; -} +void WaterfallDisplayPlot::setNumRows(int nrows) { d_nrows = nrows; } void WaterfallDisplayPlot::resetAvgAcquisitionTime() { @@ -987,14 +936,13 @@ void WaterfallDisplayPlot::updateZoomerBase() getZoomer()->setZoomBase(rect); getZoomer()->QwtPlotZoomer::zoom(rect); getZoomer()->blockSignals(false); - } void WaterfallDisplayPlot::customEvent(QEvent *e) { - if (e->type() == WaterfallUpdateEvent::Type()) { - WaterfallUpdateEvent* event = (WaterfallUpdateEvent*)e; - const std::vector dataPoints = event->getPoints(); + if(e->type() == WaterfallUpdateEvent::Type()) { + WaterfallUpdateEvent *event = (WaterfallUpdateEvent *)e; + const std::vector dataPoints = event->getPoints(); const uint64_t numDataPoints = event->getNumDataPoints(); const gr::high_res_timer_type dataTimestamp = event->getDataTimestamp(); @@ -1005,9 +953,8 @@ void WaterfallDisplayPlot::customEvent(QEvent *e) void WaterfallDisplayPlot::setPlotPosHalf(bool half) { d_half_freq = half; - if (half) + if(half) d_start_frequency = d_center_frequency; } - #endif /* WATERFALL_DISPLAY_PLOT_C */ diff --git a/gui/src/animationmanager.cpp b/gui/src/animationmanager.cpp index d2043ff123..df65d57d8e 100644 --- a/gui/src/animationmanager.cpp +++ b/gui/src/animationmanager.cpp @@ -36,15 +36,12 @@ void AnimationManager::toggleAnimations(bool on) void AnimationManager::registerAnimation(CustomAnimation *animation) { // register the animation for enable/disable signal - connect(this, &AnimationManager::toggle, - animation, &CustomAnimation::toggle); + connect(this, &AnimationManager::toggle, animation, &CustomAnimation::toggle); animation->toggle(m_animationsEnabled); - } -AnimationManager::AnimationManager(): - m_animationsEnabled(true) -{ -} +AnimationManager::AnimationManager() + : m_animationsEnabled(true) +{} #include "moc_animationmanager.cpp" diff --git a/gui/src/animationpushbutton.cpp b/gui/src/animationpushbutton.cpp index 42847c5521..c0dde8f477 100644 --- a/gui/src/animationpushbutton.cpp +++ b/gui/src/animationpushbutton.cpp @@ -1,4 +1,5 @@ #include "animationpushbutton.h" + #include Q_LOGGING_CATEGORY(CAT_GUI_ANIMATION_BTN, "AnimationPushButton") @@ -12,15 +13,15 @@ AnimationPushButton::AnimationPushButton(QWidget *parent) AnimationPushButton::~AnimationPushButton() { - if (m_animation) { + if(m_animation) { disconnect(m_animation, &QMovie::frameChanged, this, &AnimationPushButton::setBtnIcon); } } void AnimationPushButton::setAnimation(QMovie *animation) { - if (animation->isValid()) { - if (m_animation) { + if(animation->isValid()) { + if(m_animation) { disconnect(m_animation, &QMovie::frameChanged, this, &AnimationPushButton::setBtnIcon); } m_animation = animation; @@ -34,7 +35,7 @@ void AnimationPushButton::startAnimation() { m_currentText = this->text(); m_currentIcon = this->icon(); - if (m_animation->isValid() && (m_animation->state() == QMovie::NotRunning)) { + if(m_animation->isValid() && (m_animation->state() == QMovie::NotRunning)) { m_animation->start(); this->setText(""); this->setEnabled(false); @@ -43,7 +44,7 @@ void AnimationPushButton::startAnimation() void AnimationPushButton::stopAnimation() { - if (m_animation->isValid() && (m_animation->state() == QMovie::Running)) { + if(m_animation->isValid() && (m_animation->state() == QMovie::Running)) { m_animation->stop(); this->setIcon(m_currentIcon); this->setText(m_currentText); @@ -51,7 +52,6 @@ void AnimationPushButton::stopAnimation() } } -void AnimationPushButton::setBtnIcon() -{ - this->setIcon(m_animation->currentPixmap()); -} +void AnimationPushButton::setBtnIcon() { this->setIcon(m_animation->currentPixmap()); } + +#include "moc_animationpushbutton.cpp" diff --git a/gui/src/autoScaler.cpp b/gui/src/autoScaler.cpp index 88dd7304b5..8eef3bbb69 100644 --- a/gui/src/autoScaler.cpp +++ b/gui/src/autoScaler.cpp @@ -26,14 +26,15 @@ using namespace scopy; -AutoScaler::AutoScaler(QObject *parent, - const QVector &divs, unsigned int timeout_ms) : - QObject(parent), divs(divs), timer(this) +AutoScaler::AutoScaler(QObject *parent, const QVector &divs, unsigned int timeout_ms) + : QObject(parent) + , divs(divs) + , timer(this) { timer.setSingleShot(true); timer.setInterval(timeout_ms); - if (divs.empty()) + if(divs.empty()) throw std::runtime_error("AutoScaler called with empty divs vector"); changeScaleDiv(&this->divs.at(0)); @@ -41,27 +42,25 @@ AutoScaler::AutoScaler(QObject *parent, connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); } -AutoScaler::~AutoScaler() -{ -} +AutoScaler::~AutoScaler() {} void AutoScaler::setValue(double val) { - if (val < min) + if(val < min) min = val; - else if (val > max) + else if(val > max) max = val; - if (val < current_div->lowerBound()) { - for (auto it = divs.cbegin(); it != divs.cend(); ++it) { - if (it->lowerBound() <= val) { + if(val < current_div->lowerBound()) { + for(auto it = divs.cbegin(); it != divs.cend(); ++it) { + if(it->lowerBound() <= val) { changeScaleDiv(&*it); break; } } - } else if (val > current_div->upperBound()) { - for (auto it = divs.cbegin(); it != divs.cend(); ++it) { - if (it->upperBound() >= val) { + } else if(val > current_div->upperBound()) { + for(auto it = divs.cbegin(); it != divs.cend(); ++it) { + if(it->upperBound() >= val) { changeScaleDiv(&*it); break; } @@ -82,16 +81,13 @@ void AutoScaler::startTimer() timer.start(); } -void AutoScaler::stopTimer() -{ - timer.stop(); -} +void AutoScaler::stopTimer() { timer.stop(); } void AutoScaler::timeout() { - for (auto it = divs.cbegin(); it != divs.cend(); ++it) { - if (it->lowerBound() <= min && it->upperBound() >= max) { - if (&*it != current_div) + for(auto it = divs.cbegin(); it != divs.cend(); ++it) { + if(it->lowerBound() <= min && it->upperBound() >= max) { + if(&*it != current_div) changeScaleDiv(&*it); break; } @@ -105,12 +101,9 @@ void AutoScaler::setTimeout(int timeout_ms) timer.setInterval(timeout_ms); /* restart timer */ - if (timer.isActive()) + if(timer.isActive()) timer.start(); } -void AutoScaler::addScaleDivs(QwtScaleDiv div) -{ - divs.push_back(div); -} +void AutoScaler::addScaleDivs(QwtScaleDiv div) { divs.push_back(div); } #include "moc_autoScaler.cpp" diff --git a/gui/src/average.cpp b/gui/src/average.cpp index 8f751bc1f6..c41e4844d8 100644 --- a/gui/src/average.cpp +++ b/gui/src/average.cpp @@ -19,6 +19,7 @@ */ #include "average.h" + #include #include #include @@ -29,81 +30,59 @@ using namespace scopy; /* * class SpectrumAverage */ -SpectrumAverage::SpectrumAverage(unsigned int data_width, unsigned int history, - bool history_en): - m_data_width(data_width), m_history_size(history), - m_history_enabled(history_en) +SpectrumAverage::SpectrumAverage(unsigned int data_width, unsigned int history, bool history_en) + : m_data_width(data_width) + , m_history_size(history) + , m_history_enabled(history_en) { - if (data_width < 1) + if(data_width < 1) m_data_width = 1; - if (history < 1) + if(history < 1) m_history_size = 1; m_average = new double[m_data_width]; } -SpectrumAverage::~SpectrumAverage() -{ - delete[] m_average; -} +SpectrumAverage::~SpectrumAverage() { delete[] m_average; } -void SpectrumAverage::getAverage(double *out_data, - unsigned int num_samples) const +void SpectrumAverage::getAverage(double *out_data, unsigned int num_samples) const { unsigned int size = std::min(m_data_width, num_samples); std::memcpy(out_data, m_average, size * sizeof(double)); } -unsigned int SpectrumAverage::dataWidth() const -{ - return m_data_width; -} +unsigned int SpectrumAverage::dataWidth() const { return m_data_width; } -unsigned int SpectrumAverage::history() const -{ - return m_history_size; -} +unsigned int SpectrumAverage::history() const { return m_history_size; } -void SpectrumAverage::setHistory(unsigned int history) -{ - m_history_size = history; -} - -bool SpectrumAverage::historyEnabled() const -{ - return m_history_enabled; -} +void SpectrumAverage::setHistory(unsigned int history) { m_history_size = history; } +bool SpectrumAverage::historyEnabled() const { return m_history_enabled; } /* * class AverageHistoryOne */ -AverageHistoryOne::AverageHistoryOne(unsigned int data_width, unsigned history): - SpectrumAverage(data_width, history, false), m_anyDataPushed(false) -{ -} +AverageHistoryOne::AverageHistoryOne(unsigned int data_width, unsigned history) + : SpectrumAverage(data_width, history, false) + , m_anyDataPushed(false) +{} -void AverageHistoryOne::reset() -{ - m_anyDataPushed = false; -} +void AverageHistoryOne::reset() { m_anyDataPushed = false; } /* * class AverageHistoryN */ -AverageHistoryN::AverageHistoryN(unsigned int data_width, unsigned int history): - SpectrumAverage(data_width, history, true), m_insert_index(0), - m_inserted_count(0) +AverageHistoryN::AverageHistoryN(unsigned int data_width, unsigned int history) + : SpectrumAverage(data_width, history, true) + , m_insert_index(0) + , m_inserted_count(0) { alloc_history(m_data_width, m_history_size); } -AverageHistoryN::~AverageHistoryN() -{ - free_history(); -} +AverageHistoryN::~AverageHistoryN() { free_history(); } void AverageHistoryN::reset() { @@ -111,20 +90,18 @@ void AverageHistoryN::reset() m_insert_index = 0; } -void AverageHistoryN::alloc_history(unsigned int data_width, - unsigned int history_size) +void AverageHistoryN::alloc_history(unsigned int data_width, unsigned int history_size) { std::unique_lock lock(m_history_mutex); - m_history = new double*[history_size]; - for (unsigned int i = 0; i < history_size; i++) + m_history = new double *[history_size]; + for(unsigned int i = 0; i < history_size; i++) m_history[i] = new double[data_width]; - } void AverageHistoryN::free_history() { std::unique_lock lock(m_history_mutex); - for (unsigned int i = 0; i < m_history_size; i++) + for(unsigned int i = 0; i < m_history_size; i++) delete[] m_history[i]; delete[] m_history; } @@ -132,36 +109,33 @@ void AverageHistoryN::free_history() void AverageHistoryN::setHistory(unsigned int history) { double **tmp_history; - tmp_history = new double*[history]; + tmp_history = new double *[history]; - for (unsigned int i = 0; i < history; i++) { + for(unsigned int i = 0; i < history; i++) { tmp_history[i] = new double[m_data_width]; } - if (history > m_history_size) { - for (unsigned int i = 0; i < m_history_size; i++) { - std::memcpy(tmp_history[i], m_history[i], - m_data_width * sizeof(double)); + if(history > m_history_size) { + for(unsigned int i = 0; i < m_history_size; i++) { + std::memcpy(tmp_history[i], m_history[i], m_data_width * sizeof(double)); } } else { int start_index = (m_insert_index > history) ? (m_insert_index - history) : 0; int remaining_samples = std::min(m_inserted_count, history); int tmp_i = 0; - for (unsigned int i = start_index; i < m_insert_index; i++) { - std::memcpy(tmp_history[tmp_i], m_history[i], - m_data_width * sizeof(double)); + for(unsigned int i = start_index; i < m_insert_index; i++) { + std::memcpy(tmp_history[tmp_i], m_history[i], m_data_width * sizeof(double)); remaining_samples--; tmp_i++; } - for (unsigned int i = m_history_size - remaining_samples; i < m_history_size; i++) { - std::memcpy(tmp_history[tmp_i], m_history[i], - m_data_width * sizeof(double)); + for(unsigned int i = m_history_size - remaining_samples; i < m_history_size; i++) { + std::memcpy(tmp_history[tmp_i], m_history[i], m_data_width * sizeof(double)); tmp_i++; } - if (m_insert_index > history) { + if(m_insert_index > history) { m_insert_index = 0; } m_inserted_count = std::min(m_inserted_count, history); @@ -177,8 +151,7 @@ void AverageHistoryN::setHistory(unsigned int history) void AverageHistoryN::pushNewData(double *data) { std::unique_lock lock(m_history_mutex); - std::memcpy(m_history[m_insert_index], data, - m_data_width * sizeof(double)); + std::memcpy(m_history[m_insert_index], data, m_data_width * sizeof(double)); m_insert_index = (m_insert_index + 1) % m_history_size; m_inserted_count = std::min(m_inserted_count + 1, m_history_size); } @@ -186,15 +159,14 @@ void AverageHistoryN::pushNewData(double *data) /* * class PeakHoldContinuous */ -PeakHoldContinuous::PeakHoldContinuous(unsigned int data_width, - unsigned int history): AverageHistoryOne(data_width, history) -{ -} +PeakHoldContinuous::PeakHoldContinuous(unsigned int data_width, unsigned int history) + : AverageHistoryOne(data_width, history) +{} void PeakHoldContinuous::pushNewData(double *data) { - if (m_anyDataPushed) { - for (unsigned int i = 0; i < m_data_width; i++) + if(m_anyDataPushed) { + for(unsigned int i = 0; i < m_data_width; i++) m_average[i] = std::max(data[i], m_average[i]); } else { std::memcpy(m_average, data, m_data_width * sizeof(double)); @@ -205,15 +177,14 @@ void PeakHoldContinuous::pushNewData(double *data) /* * class MinHoldContinuous */ -MinHoldContinuous::MinHoldContinuous(unsigned int data_width, - unsigned int history): AverageHistoryOne(data_width, history) -{ -} +MinHoldContinuous::MinHoldContinuous(unsigned int data_width, unsigned int history) + : AverageHistoryOne(data_width, history) +{} void MinHoldContinuous::pushNewData(double *data) { - if (m_anyDataPushed) { - for (unsigned int i = 0; i < m_data_width; i++) + if(m_anyDataPushed) { + for(unsigned int i = 0; i < m_data_width; i++) m_average[i] = std::min(data[i], m_average[i]); } else { std::memcpy(m_average, data, m_data_width * sizeof(double)); @@ -224,19 +195,17 @@ void MinHoldContinuous::pushNewData(double *data) /* * class ExponentialRMS */ -ExponentialRMS::ExponentialRMS(unsigned int data_width, unsigned int history): - AverageHistoryOne(data_width, history) -{ -} +ExponentialRMS::ExponentialRMS(unsigned int data_width, unsigned int history) + : AverageHistoryOne(data_width, history) +{} void ExponentialRMS::pushNewData(double *data) { - if (m_anyDataPushed) { - for (unsigned int i = 0; i < m_data_width; i++) - m_average[i] = (data[i] * data[i] + (m_history_size - 1) - * m_average[i]) / m_history_size; + if(m_anyDataPushed) { + for(unsigned int i = 0; i < m_data_width; i++) + m_average[i] = (data[i] * data[i] + (m_history_size - 1) * m_average[i]) / m_history_size; } else { - for (unsigned int i = 0; i < m_data_width; i++) + for(unsigned int i = 0; i < m_data_width; i++) m_average[i] = data[i] * data[i]; m_anyDataPushed = true; } @@ -245,17 +214,15 @@ void ExponentialRMS::pushNewData(double *data) /* * class ExponentialAverage */ -ExponentialAverage::ExponentialAverage(unsigned int data_width, unsigned int history): - AverageHistoryOne(data_width, history) -{ -} +ExponentialAverage::ExponentialAverage(unsigned int data_width, unsigned int history) + : AverageHistoryOne(data_width, history) +{} void ExponentialAverage::pushNewData(double *data) { - if (m_anyDataPushed) { - for (unsigned int i = 0; i < m_data_width; i++) - m_average[i] = (data[i] + (m_history_size - 1) - * m_average[i]) / m_history_size; + if(m_anyDataPushed) { + for(unsigned int i = 0; i < m_data_width; i++) + m_average[i] = (data[i] + (m_history_size - 1) * m_average[i]) / m_history_size; } else { std::memcpy(m_average, data, m_data_width * sizeof(double)); m_anyDataPushed = true; @@ -265,28 +232,27 @@ void ExponentialAverage::pushNewData(double *data) /* * class PeakHold */ -PeakHold::PeakHold(unsigned int data_width, unsigned int history): - AverageHistoryN(data_width, history) -{ -} +PeakHold::PeakHold(unsigned int data_width, unsigned int history) + : AverageHistoryN(data_width, history) +{} void PeakHold::pushNewData(double *data) { double *peaks = m_average; - if (m_inserted_count == 0 || m_history_size == 1) { + if(m_inserted_count == 0 || m_history_size == 1) { std::memcpy(peaks, data, m_data_width * sizeof(double)); } else { - for (unsigned int i = 0; i < m_data_width; i++) { - if (data[i] > peaks[i]) + for(unsigned int i = 0; i < m_data_width; i++) { + if(data[i] > peaks[i]) peaks[i] = data[i]; - if (m_inserted_count != m_history_size) + if(m_inserted_count != m_history_size) continue; // If the value that we're about to drop (overwrite) is // currently the peak we need to find a new peak - if (m_history[m_insert_index][i] == peaks[i]) + if(m_history[m_insert_index][i] == peaks[i]) peaks[i] = getPeakFromHistoryColumn(i); } } @@ -297,14 +263,14 @@ void PeakHold::pushNewData(double *data) double PeakHold::getPeakFromHistoryColumn(unsigned int col) { - if (m_inserted_count < 2) + if(m_inserted_count < 2) return m_history[0][col]; unsigned int start = (m_insert_index != 0) ? 0 : 1; double peak = m_history[start][col]; - for (unsigned int i = start + 1; i < m_inserted_count; i++) { - if (i != m_insert_index && m_history[i][col] > peak) + for(unsigned int i = start + 1; i < m_inserted_count; i++) { + if(i != m_insert_index && m_history[i][col] > peak) peak = m_history[i][col]; } @@ -314,28 +280,27 @@ double PeakHold::getPeakFromHistoryColumn(unsigned int col) /* * class MinHold */ -MinHold::MinHold(unsigned int data_width, unsigned int history): - AverageHistoryN(data_width, history) -{ -} +MinHold::MinHold(unsigned int data_width, unsigned int history) + : AverageHistoryN(data_width, history) +{} void MinHold::pushNewData(double *data) { double *mins = m_average; - if (m_inserted_count == 0 || m_history_size == 1) { + if(m_inserted_count == 0 || m_history_size == 1) { std::memcpy(mins, data, m_data_width * sizeof(double)); } else { - for (unsigned int i = 0; i < m_data_width; i++) { - if (data[i] < mins[i]) + for(unsigned int i = 0; i < m_data_width; i++) { + if(data[i] < mins[i]) mins[i] = data[i]; - if (m_inserted_count != m_history_size) + if(m_inserted_count != m_history_size) continue; // If the value that we're about to drop (overwrite) is // currently the min we need to find a new min - if (m_history[m_insert_index][i] == mins[i]) + if(m_history[m_insert_index][i] == mins[i]) mins[i] = getMinFromHistoryColumn(i); } } @@ -346,14 +311,14 @@ void MinHold::pushNewData(double *data) double MinHold::getMinFromHistoryColumn(unsigned int col) { - if (m_inserted_count < 2) + if(m_inserted_count < 2) return m_history[0][col]; unsigned int start = (m_insert_index != 0) ? 0 : 1; double min = m_history[start][col]; - for (unsigned int i = start + 1; i < m_inserted_count; i++) { - if (i != m_insert_index && m_history[i][col] < min) + for(unsigned int i = start + 1; i < m_inserted_count; i++) { + if(i != m_insert_index && m_history[i][col] < min) min = m_history[i][col]; } @@ -363,28 +328,25 @@ double MinHold::getMinFromHistoryColumn(unsigned int col) /* * class LinearRMSOne */ -LinearRMSOne::LinearRMSOne(unsigned int data_width, unsigned int history): - AverageHistoryOne(data_width, history) +LinearRMSOne::LinearRMSOne(unsigned int data_width, unsigned int history) + : AverageHistoryOne(data_width, history) { m_sqr_sums = new double[m_data_width]; m_inserted_count = 0; } -LinearRMSOne::~LinearRMSOne() -{ - delete[] m_sqr_sums; -} +LinearRMSOne::~LinearRMSOne() { delete[] m_sqr_sums; } void LinearRMSOne::pushNewData(double *data) { - if (m_anyDataPushed) { - if (m_inserted_count < m_history_size) { - for (unsigned int i = 0; i < m_data_width; i++) { + if(m_anyDataPushed) { + if(m_inserted_count < m_history_size) { + for(unsigned int i = 0; i < m_data_width; i++) { m_sqr_sums[i] += (data[i] * data[i]); } m_inserted_count++; - } else if (m_inserted_count != 0) { - for (unsigned int i = 0; i < m_data_width; i++) { + } else if(m_inserted_count != 0) { + for(unsigned int i = 0; i < m_data_width; i++) { m_average[i] = m_sqr_sums[i] / m_inserted_count; m_sqr_sums[i] = 0; } @@ -394,35 +356,30 @@ void LinearRMSOne::pushNewData(double *data) std::memcpy(m_average, data, m_data_width * sizeof(double)); m_anyDataPushed = true; } - } - /* * class LinearAverageOne */ -LinearAverageOne::LinearAverageOne(unsigned int data_width, unsigned int history): - AverageHistoryOne(data_width, history) +LinearAverageOne::LinearAverageOne(unsigned int data_width, unsigned int history) + : AverageHistoryOne(data_width, history) { m_sums = new double[m_data_width]; m_inserted_count = 0; } -LinearAverageOne::~LinearAverageOne() -{ - delete[] m_sums; -} +LinearAverageOne::~LinearAverageOne() { delete[] m_sums; } void LinearAverageOne::pushNewData(double *data) { - if (m_anyDataPushed) { - if (m_inserted_count < m_history_size) { - for (unsigned int i = 0; i < m_data_width; i++) { + if(m_anyDataPushed) { + if(m_inserted_count < m_history_size) { + for(unsigned int i = 0; i < m_data_width; i++) { m_sums[i] += data[i]; } m_inserted_count++; - } else if (m_inserted_count != 0) { - for (unsigned int i = 0; i < m_data_width; i++) { + } else if(m_inserted_count != 0) { + for(unsigned int i = 0; i < m_data_width; i++) { m_average[i] = m_sums[i] / m_inserted_count; m_sums[i] = 0; } @@ -434,31 +391,26 @@ void LinearAverageOne::pushNewData(double *data) } } - /* * class LinearRMS */ -LinearRMS::LinearRMS(unsigned int data_width, unsigned int history): - AverageHistoryN(data_width, history) +LinearRMS::LinearRMS(unsigned int data_width, unsigned int history) + : AverageHistoryN(data_width, history) { m_sqr_sums = new double[data_width](); } -LinearRMS::~LinearRMS() -{ - delete[] m_sqr_sums; -} +LinearRMS::~LinearRMS() { delete[] m_sqr_sums; } void LinearRMS::pushNewData(double *data) { - if (m_inserted_count != m_history_size) { - for (unsigned int i = 0; i < m_data_width; i++) { + if(m_inserted_count != m_history_size) { + for(unsigned int i = 0; i < m_data_width; i++) { m_sqr_sums[i] += (data[i] * data[i]); } } else { - for (unsigned int i = 0; i < m_data_width; i++) { - m_sqr_sums[i] -= (m_history[m_insert_index][i] * - m_history[m_insert_index][i]); + for(unsigned int i = 0; i < m_data_width; i++) { + m_sqr_sums[i] -= (m_history[m_insert_index][i] * m_history[m_insert_index][i]); m_sqr_sums[i] += (data[i] * data[i]); } } @@ -471,7 +423,7 @@ void LinearRMS::getAverage(double *out_data, unsigned int num_samples) const { unsigned int num = std::min(m_data_width, num_samples); - for (unsigned int i = 0; i < num; i++) + for(unsigned int i = 0; i < num; i++) out_data[i] = sqrt(m_sqr_sums[i] / m_inserted_count); } @@ -484,25 +436,22 @@ void LinearRMS::reset() /* * class LinearAverage */ -LinearAverage::LinearAverage(unsigned int data_width, unsigned int history): - AverageHistoryN(data_width, history) +LinearAverage::LinearAverage(unsigned int data_width, unsigned int history) + : AverageHistoryN(data_width, history) { m_sums = new double[data_width](); } -LinearAverage::~LinearAverage() -{ - delete[] m_sums; -} +LinearAverage::~LinearAverage() { delete[] m_sums; } void LinearAverage::pushNewData(double *data) { - if (m_inserted_count != m_history_size) { - for (unsigned int i = 0; i < m_data_width; i++) { + if(m_inserted_count != m_history_size) { + for(unsigned int i = 0; i < m_data_width; i++) { m_sums[i] += data[i]; } } else { - for (unsigned int i = 0; i < m_data_width; i++) { + for(unsigned int i = 0; i < m_data_width; i++) { m_sums[i] -= m_history[m_insert_index][i]; m_sums[i] += data[i]; } @@ -516,7 +465,7 @@ void LinearAverage::getAverage(double *out_data, unsigned int num_samples) const { unsigned int num = std::min(m_data_width, num_samples); - for (unsigned int i = 0; i < num; i++) + for(unsigned int i = 0; i < num; i++) out_data[i] = m_sums[i] / m_inserted_count; } diff --git a/gui/src/basemenu.cpp b/gui/src/basemenu.cpp index a955b22dd0..0f77e7887b 100644 --- a/gui/src/basemenu.cpp +++ b/gui/src/basemenu.cpp @@ -19,17 +19,19 @@ */ #include "basemenu.h" -#include "ui_basemenu.h" + #include "utils.h" +#include "ui_basemenu.h" + #include using namespace scopy; -BaseMenu::BaseMenu(QWidget *parent) : - QWidget(parent), - d_ui(new Ui::BaseMenu), - d_items(0) +BaseMenu::BaseMenu(QWidget *parent) + : QWidget(parent) + , d_ui(new Ui::BaseMenu) + , d_items(0) { d_ui->setupUi(this); setAcceptDrops(true); @@ -38,22 +40,19 @@ BaseMenu::BaseMenu(QWidget *parent) : d_ui->bottomSeparator->setVisible(false); } -BaseMenu::~BaseMenu() -{ - delete d_ui; -} +BaseMenu::~BaseMenu() { delete d_ui; } void BaseMenu::insertMenuItem(BaseMenuItem *menuItem, int position) { menuItem->setOwner(this); - for (int i = 0; i < d_ui->mainLayout->count(); ++i) { - if (menuItem == d_ui->mainLayout->itemAt(i)->widget()) { + for(int i = 0; i < d_ui->mainLayout->count(); ++i) { + if(menuItem == d_ui->mainLayout->itemAt(i)->widget()) { return; } } - if(position == -1 ) + if(position == -1) position = d_ui->mainLayout->count() - 2; d_ui->mainLayout->insertWidget(position, menuItem); @@ -61,27 +60,25 @@ void BaseMenu::insertMenuItem(BaseMenuItem *menuItem, int position) menuItem->setVisible(true); - connect(menuItem, &BaseMenuItem::moveItem, - this, &BaseMenu::moveItem); + connect(menuItem, &BaseMenuItem::moveItem, this, &BaseMenu::moveItem); _updateItemsPosition(); - } void BaseMenu::insertMenuItem(QVector items, QVector positions) { - if (!positions.empty()) { + if(!positions.empty()) { int i = 0; - while (i < items.size() && positions.size()) { + while(i < items.size() && positions.size()) { insertMenuItem(items[i], positions[i]); i++; } - while (i < items.size()) { + while(i < items.size()) { insertMenuItem(items[i]); i++; } } else { - for (int i = 0; i < items.size(); ++i) { + for(int i = 0; i < items.size(); ++i) { insertMenuItem(items[i]); } } @@ -90,8 +87,7 @@ void BaseMenu::insertMenuItem(QVector items, QVector positi void BaseMenu::removeMenuItem(BaseMenuItem *menuItem) { d_ui->mainLayout->removeWidget(menuItem); - disconnect(menuItem, &BaseMenuItem::moveItem, - this, &BaseMenu::moveItem); + disconnect(menuItem, &BaseMenuItem::moveItem, this, &BaseMenu::moveItem); d_items = d_ui->mainLayout->count(); menuItem->setVisible(false); @@ -100,7 +96,7 @@ void BaseMenu::removeMenuItem(BaseMenuItem *menuItem) void BaseMenu::removeMenuItem(QVector items) { - for (auto const & item : items) { + for(auto const &item : items) { removeMenuItem(item); } } @@ -116,25 +112,19 @@ void BaseMenu::setMargins(int left, int top, int right, int bottom) d_ui->mainLayout->setContentsMargins(left, top, right, bottom); } -int BaseMenu::spacing() const -{ - return d_ui->mainLayout->spacing(); -} +int BaseMenu::spacing() const { return d_ui->mainLayout->spacing(); } -void BaseMenu::setSpacing(int spacing) -{ - d_ui->mainLayout->setSpacing(spacing); -} +void BaseMenu::setSpacing(int spacing) { d_ui->mainLayout->setSpacing(spacing); } void BaseMenu::dragEnterEvent(QDragEnterEvent *event) { - if (!event->source()) { + if(!event->source()) { event->ignore(); return; } - if (!d_ui->verticalSpacer->geometry().contains(event->pos()) - || !event->mimeData()->hasFormat(BaseMenuItem::menuItemMimeDataType)) { + if(!d_ui->verticalSpacer->geometry().contains(event->pos()) || + !event->mimeData()->hasFormat(BaseMenuItem::menuItemMimeDataType)) { event->ignore(); return; } @@ -142,20 +132,17 @@ void BaseMenu::dragEnterEvent(QDragEnterEvent *event) event->accept(); } -void BaseMenu::dragLeaveEvent(QDragLeaveEvent *event) -{ - d_ui->bottomSeparator->setVisible(false); -} +void BaseMenu::dragLeaveEvent(QDragLeaveEvent *event) { d_ui->bottomSeparator->setVisible(false); } void BaseMenu::dropEvent(QDropEvent *event) { d_ui->bottomSeparator->setVisible(false); - if (!event->source()) { + if(!event->source()) { return; } - if (event->mimeData()->hasFormat(BaseMenuItem::menuItemMimeDataType)) { + if(event->mimeData()->hasFormat(BaseMenuItem::menuItemMimeDataType)) { short from = (short)event->mimeData()->data(BaseMenuItem::menuItemMimeDataType)[1]; moveItem(from, d_items); } @@ -163,14 +150,15 @@ void BaseMenu::dropEvent(QDropEvent *event) void BaseMenu::_updateItemsPosition() { - for (auto& item : findChildren()) { + for(auto &item : findChildren()) { item->setPosition(positionOf(item)); } } void BaseMenu::moveItem(short from, short to) { - if (to > from) to--; + if(to > from) + to--; QWidget *widget = d_ui->mainLayout->itemAt(from)->widget(); d_ui->mainLayout->removeWidget(widget); d_ui->mainLayout->insertWidget(to, widget); diff --git a/gui/src/basemenuitem.cpp b/gui/src/basemenuitem.cpp index ff67777a1e..43fee572a7 100644 --- a/gui/src/basemenuitem.cpp +++ b/gui/src/basemenuitem.cpp @@ -19,12 +19,12 @@ */ #include "basemenuitem.h" -#include "ui_basemenuitem.h" #include "basemenu.h" - #include "utils.h" +#include "ui_basemenuitem.h" + #include #include #include @@ -33,20 +33,20 @@ using namespace scopy; const char *BaseMenuItem::menuItemMimeDataType = "menuItem"; -BaseMenuItem::BaseMenuItem(QWidget *parent) : - QWidget(parent), - d_ui(new Ui::BaseMenuItem), - d_menu(nullptr), - d_position(0), - d_dragStartPosition(QPoint()), - d_topDragBox(QRect()), - d_centerDragBox(QRect()), - d_botDragbox(QRect()), - d_dragWidget(nullptr), - d_allowDrag(false), - d_draggable(true) -{ - d_ui->setupUi(this); +BaseMenuItem::BaseMenuItem(QWidget *parent) + : QWidget(parent) + , d_ui(new Ui::BaseMenuItem) + , d_menu(nullptr) + , d_position(0) + , d_dragStartPosition(QPoint()) + , d_topDragBox(QRect()) + , d_centerDragBox(QRect()) + , d_botDragbox(QRect()) + , d_dragWidget(nullptr) + , d_allowDrag(false) + , d_draggable(true) +{ + d_ui->setupUi(this); // Retain widget size when not visible Util::retainWidgetSizeWhenHidden(this); @@ -67,24 +67,15 @@ BaseMenuItem::~BaseMenuItem() delete d_ui; } -void BaseMenuItem::setWidget(QWidget *widget) -{ - d_ui->contentsLayout->addWidget(widget); -} +void BaseMenuItem::setWidget(QWidget *widget) { d_ui->contentsLayout->addWidget(widget); } -int BaseMenuItem::position() const -{ - return d_position; -} +int BaseMenuItem::position() const { return d_position; } -void BaseMenuItem::setPosition(int position) -{ - d_position = position; -} +void BaseMenuItem::setPosition(int position) { d_position = position; } void BaseMenuItem::mousePressEvent(QMouseEvent *event) { - if (event->button() == Qt::LeftButton) { + if(event->button() == Qt::LeftButton) { d_dragStartPosition = event->pos(); } } @@ -93,16 +84,15 @@ void BaseMenuItem::mouseMoveEvent(QMouseEvent *event) { if(!d_draggable) return; - if (!(event->buttons() & Qt::LeftButton)) { + if(!(event->buttons() & Qt::LeftButton)) { return; } - if ((event->pos() - d_dragStartPosition).manhattanLength() - < QApplication::startDragDistance()) { + if((event->pos() - d_dragStartPosition).manhattanLength() < QApplication::startDragDistance()) { return; } - if (d_dragWidget && !d_allowDrag) { + if(d_dragWidget && !d_allowDrag) { return; } @@ -115,8 +105,7 @@ void BaseMenuItem::mouseMoveEvent(QMouseEvent *event) mimeData->setData(menuItemMimeDataType, itemData); QPixmap pix; - pix = grab().scaled(geometry().width(), - geometry().height()); + pix = grab().scaled(geometry().width(), geometry().height()); // Hide this item while it is being dragged setVisible(false); @@ -130,7 +119,7 @@ void BaseMenuItem::mouseMoveEvent(QMouseEvent *event) // Make it visible again when the drag operation finishes setVisible(true); - if (d_dragWidget) { + if(d_dragWidget) { d_allowDrag = false; } } @@ -142,10 +131,9 @@ void BaseMenuItem::dragLeaveEvent(QDragLeaveEvent *event) event->accept(); } - void BaseMenuItem::dragEnterEvent(QDragEnterEvent *event) { - if (!event->source()) { + if(!event->source()) { event->ignore(); return; } @@ -156,7 +144,7 @@ void BaseMenuItem::dragEnterEvent(QDragEnterEvent *event) d_topDragBox.setRect(0, 0, width, height / 2); d_botDragbox.setRect(0, height / 2, width, height / 2); - if (!event->mimeData()->hasFormat(menuItemMimeDataType)) { + if(!event->mimeData()->hasFormat(menuItemMimeDataType)) { event->ignore(); return; } @@ -165,11 +153,11 @@ void BaseMenuItem::dragEnterEvent(QDragEnterEvent *event) void BaseMenuItem::dragMoveEvent(QDragMoveEvent *event) { - if (event->answerRect().intersects(d_topDragBox)) { + if(event->answerRect().intersects(d_topDragBox)) { _enableBotSeparator(false); _enableTopSeparator(true); event->accept(); - } else if (event->answerRect().intersects(d_botDragbox)) { + } else if(event->answerRect().intersects(d_botDragbox)) { _enableBotSeparator(true); _enableTopSeparator(false); event->accept(); @@ -185,34 +173,28 @@ void BaseMenuItem::dropEvent(QDropEvent *event) _enableBotSeparator(false); _enableTopSeparator(false); - if (!event->source()) { + if(!event->source()) { return; } - if (event->source() == this && event->possibleActions() & Qt::MoveAction) { + if(event->source() == this && event->possibleActions() & Qt::MoveAction) { return; } bool dropAfter = d_botDragbox.contains(event->pos()); - if (event->mimeData()->hasFormat(menuItemMimeDataType)) { + if(event->mimeData()->hasFormat(menuItemMimeDataType)) { short from = (short)event->mimeData()->data(menuItemMimeDataType)[1]; short to = d_position; - if (dropAfter) to++; + if(dropAfter) + to++; Q_EMIT moveItem(from, to); } - } -void BaseMenuItem::enterEvent(QEvent *event) -{ - event->accept(); -} +void BaseMenuItem::enterEvent(QEvent *event) { event->accept(); } -void BaseMenuItem::leaveEvent(QEvent *event) -{ - event->accept(); -} +void BaseMenuItem::leaveEvent(QEvent *event) { event->accept(); } void BaseMenuItem::setDragWidget(QWidget *widget) { @@ -223,46 +205,28 @@ void BaseMenuItem::setDragWidget(QWidget *widget) bool BaseMenuItem::eventFilter(QObject *watched, QEvent *event) { - if (event->type() == QEvent::DragEnter){ + if(event->type() == QEvent::DragEnter) { QDragEnterEvent *enterEvent = static_cast(event); - if (!enterEvent->mimeData()->hasFormat(menuItemMimeDataType)) + if(!enterEvent->mimeData()->hasFormat(menuItemMimeDataType)) return true; } - if (watched == d_dragWidget && event->type() == QEvent::MouseButtonPress) { + if(watched == d_dragWidget && event->type() == QEvent::MouseButtonPress) { d_allowDrag = true; } return QWidget::eventFilter(watched, event); } -BaseMenu *BaseMenuItem::getOwner() const -{ - return d_menu; -} +BaseMenu *BaseMenuItem::getOwner() const { return d_menu; } -void BaseMenuItem::setOwner(BaseMenu *menu) -{ - d_menu = menu; -} +void BaseMenuItem::setOwner(BaseMenu *menu) { d_menu = menu; } -void BaseMenuItem::_enableBotSeparator(bool enable) -{ - d_ui->botSep->setVisible(enable); -} +void BaseMenuItem::_enableBotSeparator(bool enable) { d_ui->botSep->setVisible(enable); } -void BaseMenuItem::_enableTopSeparator(bool enable) -{ - d_ui->topSep->setVisible(enable); -} +void BaseMenuItem::_enableTopSeparator(bool enable) { d_ui->topSep->setVisible(enable); } -bool BaseMenuItem::draggable() const -{ - return d_draggable; -} +bool BaseMenuItem::draggable() const { return d_draggable; } -void BaseMenuItem::setDraggable(bool newDraggable) -{ - d_draggable = newDraggable; -} +void BaseMenuItem::setDraggable(bool newDraggable) { d_draggable = newDraggable; } #include "moc_basemenuitem.cpp" diff --git a/gui/src/buffer_previewer.cpp b/gui/src/buffer_previewer.cpp index 4df15ccde8..d71d482827 100644 --- a/gui/src/buffer_previewer.cpp +++ b/gui/src/buffer_previewer.cpp @@ -20,10 +20,10 @@ #include "buffer_previewer.hpp" -#include -#include #include #include +#include +#include using namespace scopy; @@ -31,117 +31,93 @@ using namespace scopy; * Class BufferPreviewer implementation */ -BufferPreviewer::BufferPreviewer(QWidget *parent): - BufferPreviewer(50, 0.0, parent) -{ -} - -BufferPreviewer::BufferPreviewer(int pixelsPerPeriod, double wavePhase, - QWidget *parent): - QFrame(parent), - m_waveformPos(0.0), - m_waveformWidth(1.0), - m_highlightPos(0.0), - m_highlightWidth(0.5), - m_cursorPos(0.0), - m_verticalSpacing(0), - m_pixelsPerPeriod(pixelsPerPeriod), - m_startingPhase(wavePhase), - m_fullWaveNumPoints(1), - m_fullWavePoints(new QPointF[m_fullWaveNumPoints]), - m_rightBtnClick(false), - m_gatingEnabled(false), - m_leftGateWidth(0), - m_rightGateWidth(0), - m_cursorVisible(true) -{ -} - -BufferPreviewer::~BufferPreviewer() -{ - delete[] m_fullWavePoints; -} - -double BufferPreviewer::waveformPos() const -{ - return m_waveformPos; -} +BufferPreviewer::BufferPreviewer(QWidget *parent) + : BufferPreviewer(50, 0.0, parent) +{} + +BufferPreviewer::BufferPreviewer(int pixelsPerPeriod, double wavePhase, QWidget *parent) + : QFrame(parent) + , m_waveformPos(0.0) + , m_waveformWidth(1.0) + , m_highlightPos(0.0) + , m_highlightWidth(0.5) + , m_cursorPos(0.0) + , m_verticalSpacing(0) + , m_pixelsPerPeriod(pixelsPerPeriod) + , m_startingPhase(wavePhase) + , m_fullWaveNumPoints(1) + , m_fullWavePoints(new QPointF[m_fullWaveNumPoints]) + , m_rightBtnClick(false) + , m_gatingEnabled(false) + , m_leftGateWidth(0) + , m_rightGateWidth(0) + , m_cursorVisible(true) +{} + +BufferPreviewer::~BufferPreviewer() { delete[] m_fullWavePoints; } + +double BufferPreviewer::waveformPos() const { return m_waveformPos; } void BufferPreviewer::setWaveformPos(double pos) { - if (pos < 0.0 || pos > 1.0 || pos == m_waveformPos) + if(pos < 0.0 || pos > 1.0 || pos == m_waveformPos) return; m_waveformPos = pos; update(); } -double BufferPreviewer::waveformWidth() const -{ - return m_waveformWidth; -} +double BufferPreviewer::waveformWidth() const { return m_waveformWidth; } void BufferPreviewer::setWaveformWidth(double width) { - if (width < 0.0 || width > 1.0 || width == m_waveformWidth) + if(width < 0.0 || width > 1.0 || width == m_waveformWidth) return; m_waveformWidth = width; update(); } -double BufferPreviewer::highlightPos() const -{ - return m_highlightPos; -} +double BufferPreviewer::highlightPos() const { return m_highlightPos; } void BufferPreviewer::setHighlightPos(double pos) { - if (pos < 0.0 || pos > 1.0 || pos == m_highlightPos) + if(pos < 0.0 || pos > 1.0 || pos == m_highlightPos) return; m_highlightPos = pos; update(); } -double BufferPreviewer::highlightWidth() const -{ - return m_highlightPos; -} +double BufferPreviewer::highlightWidth() const { return m_highlightPos; } void BufferPreviewer::setHighlightWidth(double width) { - if (width < 0.0 || width > 1.0 || width == m_highlightWidth) + if(width < 0.0 || width > 1.0 || width == m_highlightWidth) return; m_highlightWidth = width; update(); } -double BufferPreviewer::cursorPos() const -{ - return m_cursorPos; -} +double BufferPreviewer::cursorPos() const { return m_cursorPos; } void BufferPreviewer::setCursorPos(double pos) { - if (pos < 0.0 || pos > 1.0 || pos == m_cursorPos) + if(pos < 0.0 || pos > 1.0 || pos == m_cursorPos) return; m_cursorPos = pos; update(); } -int BufferPreviewer::verticalSpacing() const -{ - return m_verticalSpacing; -} +int BufferPreviewer::verticalSpacing() const { return m_verticalSpacing; } void BufferPreviewer::setVerticalSpacing(int spacing) { - if (spacing < 0) + if(spacing < 0) spacing = 0; - if (m_verticalSpacing != spacing) { + if(m_verticalSpacing != spacing) { m_verticalSpacing = spacing; buildFullWaveform(m_fullWavePoints, m_fullWaveNumPoints); @@ -149,15 +125,9 @@ void BufferPreviewer::setVerticalSpacing(int spacing) } } -int BufferPreviewer::pixelsPerPeriod() const -{ - return m_pixelsPerPeriod; -} +int BufferPreviewer::pixelsPerPeriod() const { return m_pixelsPerPeriod; } -double BufferPreviewer::wavePhase() const -{ - return m_startingPhase; -} +double BufferPreviewer::wavePhase() const { return m_startingPhase; } void BufferPreviewer::setGatingEnabled(bool enabled) { @@ -179,7 +149,7 @@ void BufferPreviewer::setRightGateWidth(double width) void BufferPreviewer::setCursorVisible(bool visible) { - if (m_cursorVisible != visible) { + if(m_cursorVisible != visible) { m_cursorVisible = visible; update(); } @@ -202,15 +172,14 @@ void BufferPreviewer::paintEvent(QPaintEvent *) int cursor_start = qRound(m_cursorPos * w); // Limit width of movable elements so they don't exceed the widget width - if (hlight_start + hlight_width > w) + if(hlight_start + hlight_width > w) hlight_width = w - hlight_start; - if (wave_start + wave_width > w) + if(wave_start + wave_width > w) wave_width = w - wave_start; // Get intersection between the visible wave and the highlight rectangle int hlightedWaveStartPos = qMax(hlight_start, wave_start); - int hlightedWaveEndPos = qMin((hlight_start + hlight_width), - (wave_start + wave_width)); + int hlightedWaveEndPos = qMin((hlight_start + hlight_width), (wave_start + wave_width)); int hlightedWaveWidth = hlightedWaveEndPos - hlightedWaveStartPos; /* Start drawing */ @@ -235,11 +204,10 @@ void BufferPreviewer::paintEvent(QPaintEvent *) p.setRenderHint(QPainter::Antialiasing, true); linePen.setColor(palette().color(QPalette::HighlightedText)); p.setPen(linePen); - p.drawPolyline(m_fullWavePoints + hlightedWaveStartPos , hlightedWaveWidth); + p.drawPolyline(m_fullWavePoints + hlightedWaveStartPos, hlightedWaveWidth); - //Draw two vertical lines at the start and end of the highlight; - if (hlight_start + hlight_width > wave_start - && wave_start + wave_width > hlight_start) { + // Draw two vertical lines at the start and end of the highlight; + if(hlight_start + hlight_width > wave_start && wave_start + wave_width > hlight_start) { int line_w = 2; p.setPen(rectPen); p.setBrush(palette().color(QPalette::HighlightedText)); @@ -247,8 +215,8 @@ void BufferPreviewer::paintEvent(QPaintEvent *) p.drawRect(hlight_start + hlight_width, 0, line_w, h); } - if (m_cursorVisible) { - //Draw Cursor + if(m_cursorVisible) { + // Draw Cursor p.setRenderHint(QPainter::Antialiasing, false); int cur_head_w = 8; int cur_head_h = 4; @@ -258,16 +226,17 @@ void BufferPreviewer::paintEvent(QPaintEvent *) p.drawRect((cursor_start - 1), cur_head_h, 2, h - cur_head_h); } - //Draw gatings if enabled - if(m_gatingEnabled){ + // Draw gatings if enabled + if(m_gatingEnabled) { int leftGateWidth = hlight_width * m_leftGateWidth + hlight_start; int rightGateWidth = hlight_width * m_rightGateWidth; - QBrush gateBrush(QColor(0,15,150,130)); - p.setRenderHint(QPainter::Antialiasing,true); - //draw left gate - p.fillRect(0, 0, leftGateWidth,h, gateBrush); - //draw right gate - p.fillRect(hlight_start+hlight_width-rightGateWidth, 0,rightGateWidth+(w-hlight_start+hlight_width),h, gateBrush); + QBrush gateBrush(QColor(0, 15, 150, 130)); + p.setRenderHint(QPainter::Antialiasing, true); + // draw left gate + p.fillRect(0, 0, leftGateWidth, h, gateBrush); + // draw right gate + p.fillRect(hlight_start + hlight_width - rightGateWidth, 0, + rightGateWidth + (w - hlight_start + hlight_width), h, gateBrush); } } @@ -279,15 +248,12 @@ void BufferPreviewer::resizeEvent(QResizeEvent *) buildFullWaveform(m_fullWavePoints, m_fullWaveNumPoints); } -void BufferPreviewer::mouseDoubleClickEvent(QMouseEvent *event) -{ - Q_EMIT bufferResetPosition(); -} +void BufferPreviewer::mouseDoubleClickEvent(QMouseEvent *event) { Q_EMIT bufferResetPosition(); } void BufferPreviewer::mousePressEvent(QMouseEvent *event) { - if (event->button() == Qt::RightButton) { - m_rightBtnClick = true; + if(event->button() == Qt::RightButton) { + m_rightBtnClick = true; } else { setCursor(Qt::ClosedHandCursor); m_offset = event->pos(); @@ -297,7 +263,7 @@ void BufferPreviewer::mousePressEvent(QMouseEvent *event) void BufferPreviewer::mouseMoveEvent(QMouseEvent *event) { - if (!m_rightBtnClick) { + if(!m_rightBtnClick) { int value = (event->pos() - m_offset).x(); Q_EMIT bufferMovedBy(value); } @@ -305,7 +271,7 @@ void BufferPreviewer::mouseMoveEvent(QMouseEvent *event) void BufferPreviewer::mouseReleaseEvent(QMouseEvent *event) { - if (m_rightBtnClick) { + if(m_rightBtnClick) { Q_EMIT bufferResetPosition(); m_rightBtnClick = false; } else { @@ -314,39 +280,29 @@ void BufferPreviewer::mouseReleaseEvent(QMouseEvent *event) } } -void BufferPreviewer::enterEvent(QEvent *event) -{ - setCursor(Qt::OpenHandCursor); -} +void BufferPreviewer::enterEvent(QEvent *event) { setCursor(Qt::OpenHandCursor); } -void BufferPreviewer::leaveEvent(QEvent *event) -{ - setCursor(Qt::ArrowCursor); -} +void BufferPreviewer::leaveEvent(QEvent *event) { setCursor(Qt::ArrowCursor); } /* * Class AnalogBufferPrevier implementation */ -AnalogBufferPreviewer::AnalogBufferPreviewer(QWidget *parent): - BufferPreviewer(parent) -{ -} +AnalogBufferPreviewer::AnalogBufferPreviewer(QWidget *parent) + : BufferPreviewer(parent) +{} -AnalogBufferPreviewer::AnalogBufferPreviewer(int pixelsPerPeriod, - double wavePhase, QWidget *parent): - BufferPreviewer(pixelsPerPeriod, wavePhase, parent) -{ -} +AnalogBufferPreviewer::AnalogBufferPreviewer(int pixelsPerPeriod, double wavePhase, QWidget *parent) + : BufferPreviewer(pixelsPerPeriod, wavePhase, parent) +{} void AnalogBufferPreviewer::buildFullWaveform(QPointF *wavePoints, int numPts) { int middle = contentsRect().height() / 2; int amplitude = middle - verticalSpacing() / 2; - for (int i = 0; i < numPts; i++) { - qreal y = middle + amplitude * qSin(2 * M_PI * i / - pixelsPerPeriod() + wavePhase()); + for(int i = 0; i < numPts; i++) { + qreal y = middle + amplitude * qSin(2 * M_PI * i / pixelsPerPeriod() + wavePhase()); wavePoints[i] = QPointF(i, y); } } @@ -355,39 +311,32 @@ void AnalogBufferPreviewer::buildFullWaveform(QPointF *wavePoints, int numPts) * Class DigitalBufferPreviewer implementation */ -DigitalBufferPreviewer::DigitalBufferPreviewer(QWidget *parent): - BufferPreviewer(parent), m_noOfSteps(0) -{ -} +DigitalBufferPreviewer::DigitalBufferPreviewer(QWidget *parent) + : BufferPreviewer(parent) + , m_noOfSteps(0) +{} -DigitalBufferPreviewer::DigitalBufferPreviewer(int pixelsPerPeriod, - QWidget *parent): - BufferPreviewer(pixelsPerPeriod, M_PI / 2, parent), m_noOfSteps(0) -{ -} +DigitalBufferPreviewer::DigitalBufferPreviewer(int pixelsPerPeriod, QWidget *parent) + : BufferPreviewer(pixelsPerPeriod, M_PI / 2, parent) + , m_noOfSteps(0) +{} -void DigitalBufferPreviewer::setNoOfSteps(double val) -{ - m_noOfSteps = val; -} +void DigitalBufferPreviewer::setNoOfSteps(double val) { m_noOfSteps = val; } -double DigitalBufferPreviewer::noOfSteps() -{ - return m_noOfSteps; -} +double DigitalBufferPreviewer::noOfSteps() { return m_noOfSteps; } void DigitalBufferPreviewer::buildFullWaveform(QPointF *wavePoints, int numPts) { - for (int i = 0; i < numPts; i++) { + for(int i = 0; i < numPts; i++) { qreal y; int pos = i % pixelsPerPeriod(); - if( pos < pixelsPerPeriod() / 2) { + if(pos < pixelsPerPeriod() / 2) { y = contentsRect().height() - verticalSpacing() / 2; - } - else { + } else { y = verticalSpacing() / 2; } wavePoints[i] = QPointF(i, y); } } +#include "moc_buffer_previewer.cpp" diff --git a/gui/src/channel_manager.cpp b/gui/src/channel_manager.cpp index 8814accb0b..e7e6f7b55b 100644 --- a/gui/src/channel_manager.cpp +++ b/gui/src/channel_manager.cpp @@ -1,19 +1,19 @@ +#include "channel_manager.hpp" + #include "dynamicWidget.h" #include -#include "channel_manager.hpp" - using namespace scopy; using namespace scopy::gui; -ChannelManager::ChannelManager(ChannelsPositionEnum position, QWidget* parent) +ChannelManager::ChannelManager(ChannelsPositionEnum position, QWidget *parent) : QWidget(parent) , m_scrollArea(new QScrollArea(parent)) , m_channelsWidget(new QWidget(m_scrollArea)) , m_hasAddBtn(false) , m_switchBtn(new QPushButton(m_scrollArea)) - , m_addChannelBtn(new CustomPushButton()) //check if parent removed + , m_addChannelBtn(new CustomPushButton()) // check if parent removed , m_position(position) , m_channelsList(QList()) , m_channelIdVisible(true) @@ -27,7 +27,7 @@ ChannelManager::ChannelManager(ChannelsPositionEnum position, QWidget* parent) header = new QWidget(); auto headerLayout = new QHBoxLayout(header); - header->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Maximum); + header->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); headerLayout->setMargin(10); headerLayout->setSpacing(10); @@ -37,12 +37,12 @@ ChannelManager::ChannelManager(ChannelsPositionEnum position, QWidget* parent) QStringList icons = QStringList() << ":/gui/icons/scopy-default/icons/menu.svg"; QIcon my_icon; - my_icon.addFile(icons[0],QSize(), QIcon::Normal); + my_icon.addFile(icons[0], QSize(), QIcon::Normal); toggleChannels = new QPushButton(this); toggleChannels->setStyleSheet("font-size: 12px; color: rgba(255, 255, 255, 70);"); toggleChannels->setIcon(my_icon); - toggleChannels->setIconSize(QSize(24,24)); + toggleChannels->setIconSize(QSize(24, 24)); toggleChannels->setFixedWidth(20); toggleChannels->setCheckable(true); toggleChannels->setChecked(false); @@ -54,7 +54,7 @@ ChannelManager::ChannelManager(ChannelsPositionEnum position, QWidget* parent) m_channelsWidget->layout()->setSpacing(0); m_channelsWidget->layout()->setMargin(0); - m_channelsWidget->layout()->setContentsMargins(QMargins(0,0,0,0)); + m_channelsWidget->layout()->setContentsMargins(QMargins(0, 0, 0, 0)); m_channelsWidget->layout()->setSizeConstraint(QLayout::SetMinAndMaxSize); m_channelsWidget->setStyleSheet("border: 0px;"); @@ -66,14 +66,14 @@ ChannelManager::ChannelManager(ChannelsPositionEnum position, QWidget* parent) ChannelManager::~ChannelManager() { delete m_channelsWidget; - if (m_addChannelBtn) { + if(m_addChannelBtn) { delete m_addChannelBtn; } delete m_switchBtn; delete m_parent; } -void ChannelManager::build(QWidget* parent) +void ChannelManager::build(QWidget *parent) { m_parent = parent; @@ -83,13 +83,12 @@ void ChannelManager::build(QWidget* parent) m_switchBtn->setFlat(true); m_switchBtn->setText("Switch"); connect(m_switchBtn, &QPushButton::toggled, [=]() { - if (m_position == ChannelsPositionEnum::VERTICAL) { + if(m_position == ChannelsPositionEnum::VERTICAL) { m_position = ChannelsPositionEnum::HORIZONTAL; - -// if (channelManagerToggled) { -// toggleChannels->click(); -// } + // if (channelManagerToggled) { + // toggleChannels->click(); + // } } else { m_position = ChannelsPositionEnum::VERTICAL; } @@ -102,24 +101,20 @@ void ChannelManager::build(QWidget* parent) void ChannelManager::updatePosition(ChannelsPositionEnum position) { - m_position = position == ChannelsPositionEnum::VERTICAL ? - ChannelsPositionEnum::HORIZONTAL : - ChannelsPositionEnum::VERTICAL; + m_position = position == ChannelsPositionEnum::VERTICAL ? ChannelsPositionEnum::HORIZONTAL + : ChannelsPositionEnum::VERTICAL; Q_EMIT m_switchBtn->toggled(true); } -int ChannelManager::getChannelID(ChannelWidget *ch) -{ - return m_channelsList.indexOf(ch); -} +int ChannelManager::getChannelID(ChannelWidget *ch) { return m_channelsList.indexOf(ch); } -ChannelWidget* ChannelManager::buildNewChannel(int chId, bool deletable, bool simplefied, QColor color, - const QString& fullName, const QString& shortName) +ChannelWidget *ChannelManager::buildNewChannel(int chId, bool deletable, bool simplefied, QColor color, + const QString &fullName, const QString &shortName) { - ChannelWidget* ch = new ChannelWidget(chId, deletable, simplefied, color); + ChannelWidget *ch = new ChannelWidget(chId, deletable, simplefied, color); m_channelsWidget->layout()->setMargin(0); m_channelsWidget->layout()->addWidget(ch); - if (m_channelIdVisible) { + if(m_channelIdVisible) { ch->setFullName(fullName + QString(" %1").arg(chId + 1)); ch->setShortName(shortName + QString(" %1").arg(chId + 1)); } else { @@ -134,10 +129,10 @@ ChannelWidget* ChannelManager::buildNewChannel(int chId, bool deletable, bool si connect(ch, &ChannelWidget::enabled, this, &ChannelManager::onChannelEnabled); connect(ch, &ChannelWidget::deleteClicked, this, &ChannelManager::onChannelDeleted); - if (m_position == ChannelsPositionEnum::VERTICAL) { + if(m_position == ChannelsPositionEnum::VERTICAL) { m_channelsWidget->setMinimumHeight(m_channelsList.size() * m_channelsList.first()->height()); m_channelsWidget->setMaximumHeight(m_channelsList.size() * m_channelsList.first()->height()); - if (m_maxChannelWidth < ch->sizeHint().width()) { + if(m_maxChannelWidth < ch->sizeHint().width()) { m_minChannelWidth = ch->minimumWidth(); m_maxChannelWidth = ch->sizeHint().width(); m_channelsWidget->setMinimumWidth(m_minChannelWidth); @@ -145,16 +140,15 @@ ChannelWidget* ChannelManager::buildNewChannel(int chId, bool deletable, bool si m_parent->setMinimumWidth(m_maxChannelWidth); m_parent->setMaximumWidth(m_maxChannelWidth); - } - else { - //RESIZE CHANNELS - for (auto c : qAsConst(m_channelsList)) { + } else { + // RESIZE CHANNELS + for(auto c : qAsConst(m_channelsList)) { c->setMinimumWidth(m_maxChannelWidth); } } } else { - if (m_maxChannelWidth < ch->sizeHint().width()) { + if(m_maxChannelWidth < ch->sizeHint().width()) { m_minChannelWidth = ch->minimumWidth(); m_maxChannelWidth = ch->sizeHint().width(); } @@ -173,45 +167,42 @@ ChannelWidget* ChannelManager::buildNewChannel(int chId, bool deletable, bool si return ch; } -void ChannelManager::removeChannel(ChannelWidget* ch) +void ChannelManager::removeChannel(ChannelWidget *ch) { m_channelsList.removeOne(ch); m_channelsWidget->layout()->removeWidget(ch); delete ch; } -CustomPushButton* ChannelManager::getAddChannelBtn() +CustomPushButton *ChannelManager::getAddChannelBtn() { - if (m_hasAddBtn) { + if(m_hasAddBtn) { return m_addChannelBtn; } else { return nullptr; } } -QList ChannelManager::getChannelsList() { return m_channelsList; } +QList ChannelManager::getChannelsList() { return m_channelsList; } -int ChannelManager::getChannelsCount() -{ - return m_channelsList.size(); -} +int ChannelManager::getChannelsCount() { return m_channelsList.size(); } -void ChannelManager::changeParent(QWidget* newParent) +void ChannelManager::changeParent(QWidget *newParent) { delete m_channelsWidget->layout(); int ch_width = 0, ch_height = 0; - if (m_channelsList.empty()) { + if(m_channelsList.empty()) { ch_width = header->width(); ch_height = header->height(); } else { - for (auto ch: m_channelsList) { + for(auto ch : m_channelsList) { ch_width = std::max(ch_width, ch->width()); ch_height = std::max(ch_height, ch->height()); } } - if (m_position == ChannelsPositionEnum::VERTICAL) { + if(m_position == ChannelsPositionEnum::VERTICAL) { m_channelsWidget->setLayout(new QVBoxLayout(m_channelsWidget)); m_channelsWidget->layout()->addWidget(header); @@ -227,15 +218,15 @@ void ChannelManager::changeParent(QWidget* newParent) m_channelsWidget->layout()->setSpacing(0); m_channelsWidget->layout()->setMargin(0); - m_channelsWidget->layout()->setContentsMargins(QMargins(0,0,0,0)); + m_channelsWidget->layout()->setContentsMargins(QMargins(0, 0, 0, 0)); m_channelsWidget->layout()->setSizeConstraint(QLayout::SetMinAndMaxSize); m_channelsWidget->setStyleSheet("border: 0px;"); - for (ChannelWidget* channel : qAsConst(m_channelsList)) { + for(ChannelWidget *channel : qAsConst(m_channelsList)) { m_channelsWidget->layout()->addWidget(channel); } - if (m_position == ChannelsPositionEnum::VERTICAL) { + if(m_position == ChannelsPositionEnum::VERTICAL) { m_channelsWidget->setMinimumHeight(m_channelsList.size() * ch_height); m_channelsWidget->setMaximumHeight(m_channelsList.size() * ch_height); @@ -252,36 +243,35 @@ void ChannelManager::changeParent(QWidget* newParent) m_parent = newParent; m_parent->layout()->addWidget(m_switchBtn); m_parent->layout()->addWidget(m_scrollArea); - if (m_hasAddBtn) { + if(m_hasAddBtn) { m_parent->layout()->addWidget(m_addChannelBtn); } - m_parent->layout()->setAlignment(m_addChannelBtn,Qt::AlignHCenter); + m_parent->layout()->setAlignment(m_addChannelBtn, Qt::AlignHCenter); m_parent->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_channelsWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - if (m_position == ChannelsPositionEnum::VERTICAL) { + if(m_position == ChannelsPositionEnum::VERTICAL) { m_parent->setMaximumHeight(INT_MAX); m_parent->setMaximumWidth(m_maxChannelWidth); -// m_parent->setMinimumWidth(m_maxChannelWidth); + // m_parent->setMinimumWidth(m_maxChannelWidth); } else { m_parent->setMinimumHeight(ch_height + 8); m_parent->setMaximumHeight(ch_height + 8); m_parent->setMaximumWidth(INT_MAX); -// m_parent->setMinimumWidth(ch_width); + // m_parent->setMinimumWidth(ch_width); } - } -QList ChannelManager::getEnabledChannels() +QList ChannelManager::getEnabledChannels() { - QList lst; + QList lst; - for (auto widget : m_channelsWidget->children()) { - ChannelWidget* channel = qobject_cast(widget); - if (channel->enableButton()->isChecked()) { + for(auto widget : m_channelsWidget->children()) { + ChannelWidget *channel = qobject_cast(widget); + if(channel->enableButton()->isChecked()) { lst.append(channel); } } @@ -289,12 +279,9 @@ QList ChannelManager::getEnabledChannels() return lst; } -void ChannelManager::enableSwitchButton(bool en) -{ - m_switchBtn->setVisible(en); -} +void ChannelManager::enableSwitchButton(bool en) { m_switchBtn->setVisible(en); } -void ChannelManager::insertAddBtn(QWidget* menu, bool dockable) +void ChannelManager::insertAddBtn(QWidget *menu, bool dockable) { m_hasAddBtn = true; @@ -307,35 +294,32 @@ void ChannelManager::insertAddBtn(QWidget* menu, bool dockable) m_addChannelBtn->setMaximumSize(25, 25); m_parent->layout()->addWidget(m_addChannelBtn); - m_parent->layout()->setAlignment(m_addChannelBtn,Qt::AlignHCenter); + m_parent->layout()->setAlignment(m_addChannelBtn, Qt::AlignHCenter); Q_EMIT(configureAddBtn(menu, dockable)); } -void ChannelManager::setChannelAlignment(ChannelWidget* ch, Qt::Alignment alignment) +void ChannelManager::setChannelAlignment(ChannelWidget *ch, Qt::Alignment alignment) { - m_channelsWidget->layout()->setAlignment(ch,alignment); + m_channelsWidget->layout()->setAlignment(ch, alignment); } -void ChannelManager::setChannelIdVisible(bool visible) -{ - m_channelIdVisible = visible; -} +void ChannelManager::setChannelIdVisible(bool visible) { m_channelIdVisible = visible; } void ChannelManager::toggleChannelManager(bool toggled) { Q_EMIT channelManagerToggle(toggled); - for (auto ch : qAsConst(m_channelsList)) { + for(auto ch : qAsConst(m_channelsList)) { ch->toggleChannel(!toggled); - if (ch->isMainChannel() ||ch-> isPhysicalChannel()) { + if(ch->isMainChannel() || ch->isPhysicalChannel()) { ch->setMenuButtonVisibility(toggled); } } toolStatus->setVisible(toggled); auto currentWidth = 0; - if (!toggled) { + if(!toggled) { currentWidth = m_minChannelWidth; } else { currentWidth = m_maxChannelWidth; @@ -344,21 +328,18 @@ void ChannelManager::toggleChannelManager(bool toggled) m_channelsWidget->setMinimumWidth(currentWidth); m_channelsWidget->setMaximumWidth(currentWidth); - //RESIZE CHANNELS - for (auto c : qAsConst(m_channelsList)) { + // RESIZE CHANNELS + for(auto c : qAsConst(m_channelsList)) { c->setMinimumWidth(currentWidth); } } -int ChannelManager::getSelectedChannel() -{ - return m_selectedChannel; -} +int ChannelManager::getSelectedChannel() { return m_selectedChannel; } void ChannelManager::onChannelSelected(bool toggled) { - ChannelWidget* ch = dynamic_cast(sender()); - if (ch != nullptr) { + ChannelWidget *ch = dynamic_cast(sender()); + if(ch != nullptr) { int id = m_channelsList.indexOf(ch); m_selectedChannel = id; Q_EMIT selectedChannel(id, toggled); @@ -367,8 +348,8 @@ void ChannelManager::onChannelSelected(bool toggled) void ChannelManager::onChannelEnabled(bool enabled) { - ChannelWidget* ch = dynamic_cast(sender()); - if (ch != nullptr) { + ChannelWidget *ch = dynamic_cast(sender()); + if(ch != nullptr) { int id = m_channelsList.indexOf(ch); Q_EMIT enabledChannel(id, enabled); @@ -377,17 +358,14 @@ void ChannelManager::onChannelEnabled(bool enabled) void ChannelManager::onChannelDeleted() { - ChannelWidget* ch = dynamic_cast(sender()); - if (ch != nullptr) { + ChannelWidget *ch = dynamic_cast(sender()); + if(ch != nullptr) { Q_EMIT deletedChannel(ch->shortName()); } } -const ChannelWidget* ChannelManager::getChannelAt(int id) -{ - return m_channelsList.at(id); -} +const ChannelWidget *ChannelManager::getChannelAt(int id) { return m_channelsList.at(id); } const QString &ChannelManager::getToolStatus() const { @@ -395,9 +373,6 @@ const QString &ChannelManager::getToolStatus() const return text; } -void ChannelManager::setToolStatus(const QString &newToolStatus) -{ - toolStatus->setText(newToolStatus); -} - +void ChannelManager::setToolStatus(const QString &newToolStatus) { toolStatus->setText(newToolStatus); } +#include "moc_channel_manager.cpp" diff --git a/gui/src/channel_widget.cpp b/gui/src/channel_widget.cpp index 061b787816..929a4a6923 100644 --- a/gui/src/channel_widget.cpp +++ b/gui/src/channel_widget.cpp @@ -18,10 +18,13 @@ * along with this program. If not, see . */ #include "channel_widget.hpp" -#include "ui_channel.h" + #include "dynamicWidget.h" +#include "ui_channel.h" + #include + #include using namespace scopy; @@ -34,24 +37,24 @@ using namespace scopy; * thin line which is visible only when the channel is selected, thus increasing * the visibility of the selected state of the channel. */ -ChannelWidget::ChannelWidget(int id, bool deletable, bool simplified, - QColor color, QWidget *parent) : - QWidget(parent), - m_ui(new Ui::Channel), - m_id(id), - m_deletable(deletable), - m_simplified(simplified), - m_color(color), - m_math(false), - m_function(""), - m_ref(false), - m_isMainChannel(false), - m_isPhysicalChannel(false) +ChannelWidget::ChannelWidget(int id, bool deletable, bool simplified, QColor color, QWidget *parent) + : QWidget(parent) + , m_ui(new Ui::Channel) + , m_id(id) + , m_deletable(deletable) + , m_simplified(simplified) + , m_color(color) + , m_math(false) + , m_function("") + , m_ref(false) + , m_isMainChannel(false) + , m_isPhysicalChannel(false) { init(); nameButton()->installEventFilter(this); - m_channelWSpacer = new QSpacerItem(1,1,QSizePolicy::Expanding,QSizePolicy::Fixed); - setStyleSheet("scopy--ChannelWidget QPushButton#btn:hover:!pressed:!checked { border-image: url(:/gui/icons/setup_btn_hover.svg) }"); + m_channelWSpacer = new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Fixed); + setStyleSheet("scopy--ChannelWidget QPushButton#btn:hover:!pressed:!checked { border-image: " + "url(:/gui/icons/setup_btn_hover.svg) }"); } ChannelWidget::~ChannelWidget() @@ -74,58 +77,36 @@ void ChannelWidget::init() m_ui->delBtn->setVisible(m_deletable); setColor(m_color); - if (m_simplified) { + if(m_simplified) { m_ui->name->hide(); m_ui->line->hide(); QString stylesheet = styleSheet(); stylesheet += QString("QCheckBox#box { spacing: 12px; }"); setStyleSheet(stylesheet); } else { - connect(m_ui->name, &QPushButton::toggled, - [=] (bool checked) { - setDynamicProperty(m_ui->widget, "selected", - checked); - setDynamicProperty(m_ui->line, "selected", - checked); - } - ); + connect(m_ui->name, &QPushButton::toggled, [=](bool checked) { + setDynamicProperty(m_ui->widget, "selected", checked); + setDynamicProperty(m_ui->line, "selected", checked); + }); } m_ui->horizontalLayout->setAlignment(Qt::AlignLeft); - m_ui->horizontalLayout->setAlignment(m_ui->btn,Qt::AlignRight); - Util::setWidgetNrOfChars(m_ui->name,6,15); -// m_ui->verticalSpacer->changeSize(0, 0, QSizePolicy::Fixed, -// QSizePolicy::Fixed); + m_ui->horizontalLayout->setAlignment(m_ui->btn, Qt::AlignRight); + Util::setWidgetNrOfChars(m_ui->name, 6, 15); + // m_ui->verticalSpacer->changeSize(0, 0, QSizePolicy::Fixed, + // QSizePolicy::Fixed); } -QAbstractButton* ChannelWidget::enableButton() const -{ - return m_ui->box; -} +QAbstractButton *ChannelWidget::enableButton() const { return m_ui->box; } -QAbstractButton* ChannelWidget::nameButton() const -{ - return m_ui->name; -} +QAbstractButton *ChannelWidget::nameButton() const { return m_ui->name; } -QAbstractButton* ChannelWidget::menuButton() const -{ - return m_ui->btn; -} +QAbstractButton *ChannelWidget::menuButton() const { return m_ui->btn; } -QAbstractButton* ChannelWidget::deleteButton() const -{ - return m_ui->delBtn; -} +QAbstractButton *ChannelWidget::deleteButton() const { return m_ui->delBtn; } -QAbstractButton* ChannelWidget::toggleChannelsButton() const -{ - return m_ui->toggleChannels; -} +QAbstractButton *ChannelWidget::toggleChannelsButton() const { return m_ui->toggleChannels; } -int ChannelWidget::id() const -{ - return m_id; -} +int ChannelWidget::id() const { return m_id; } void ChannelWidget::setId(int id) { @@ -137,57 +118,37 @@ void ChannelWidget::setId(int id) m_id = id; } -QColor ChannelWidget::color() const -{ - return m_color; -} +QColor ChannelWidget::color() const { return m_color; } void ChannelWidget::setColor(QColor color) { - QString boxStyleSheet = QString( - "QCheckBox#box::indicator {" - "border: 2px solid %1;" - "}" - "QCheckBox#box::indicator:checked {" - "background-color: %1;" - "}" - ).arg(color.name()); + QString boxStyleSheet = QString("QCheckBox#box::indicator {" + "border: 2px solid %1;" + "}" + "QCheckBox#box::indicator:checked {" + "background-color: %1;" + "}") + .arg(color.name()); m_ui->box->setStyleSheet(boxStyleSheet); - QString lineStyleSheet = QString( - "QFrame#line[selected=true] {" - "border: 2px solid %1;" - "}" - ).arg(color.name()); + QString lineStyleSheet = QString("QFrame#line[selected=true] {" + "border: 2px solid %1;" + "}") + .arg(color.name()); m_ui->line->setStyleSheet(lineStyleSheet); m_color = color; } -QString ChannelWidget::fullName() const -{ - return m_fullName; -} +QString ChannelWidget::fullName() const { return m_fullName; } -void ChannelWidget::setFullName(const QString& name) -{ - m_fullName = name; -} +void ChannelWidget::setFullName(const QString &name) { m_fullName = name; } -QString ChannelWidget::shortName() const -{ - return m_shortName; -} +QString ChannelWidget::shortName() const { return m_shortName; } -void ChannelWidget::setShortName(const QString &name) -{ - m_shortName = name; -} +void ChannelWidget::setShortName(const QString &name) { m_shortName = name; } -QString ChannelWidget::function() const -{ - return m_function; -} +QString ChannelWidget::function() const { return m_function; } void ChannelWidget::setFunction(const QString &function) { @@ -195,40 +156,27 @@ void ChannelWidget::setFunction(const QString &function) setProperty("function", QVariant(function)); } -bool ChannelWidget::isMathChannel() const -{ - return m_math; -} +bool ChannelWidget::isMathChannel() const { return m_math; } -void ChannelWidget::setMathChannel(const bool &math) -{ - m_math = math; -} +void ChannelWidget::setMathChannel(const bool &math) { m_math = math; } -bool ChannelWidget::isReferenceChannel() const -{ - return m_ref; -} +bool ChannelWidget::isReferenceChannel() const { return m_ref; } -void ChannelWidget::setReferenceChannel(const bool &ref) -{ - m_ref = ref; -} +void ChannelWidget::setReferenceChannel(const bool &ref) { m_ref = ref; } void ChannelWidget::setMenuFloating(bool floating) { m_floatingMenu = floating; } bool ChannelWidget::eventFilter(QObject *object, QEvent *event) { - if (event->type() == QEvent::MouseButtonPress) { - if (!m_ui->box->isChecked()) { + if(event->type() == QEvent::MouseButtonPress) { + if(!m_ui->box->isChecked()) { m_ui->box->setChecked(true); m_ui->name->setChecked(true); - } else if (!m_ui->btn->isChecked() && - m_ui->name->isChecked()){ + } else if(!m_ui->btn->isChecked() && m_ui->name->isChecked()) { m_ui->btn->setChecked(true); } - } else if (event->type() == QEvent::MouseButtonDblClick) { - if (!m_ui->box->isChecked()) { + } else if(event->type() == QEvent::MouseButtonDblClick) { + if(!m_ui->box->isChecked()) { m_ui->box->setChecked(true); m_ui->name->setChecked(true); } @@ -240,37 +188,36 @@ bool ChannelWidget::eventFilter(QObject *object, QEvent *event) void ChannelWidget::mouseDoubleClickEvent(QMouseEvent *event) { - if (!m_ui->box->isChecked()) { + if(!m_ui->box->isChecked()) { m_ui->box->setChecked(true); m_ui->name->setChecked(true); } m_ui->btn->setChecked(true); - } void ChannelWidget::on_box_toggled(bool checked) { - if (checked) { - if (!m_simplified) + if(checked) { + if(!m_simplified) m_ui->name->setEnabled(true); m_ui->btn->setEnabled(true); // When enabling ChannelWidget select it as well - if (!m_simplified) + if(!m_simplified) m_ui->name->setChecked(true); } else { // Unselect the ChannelWidget when it's about to be disabled - if (!m_simplified) { + if(!m_simplified) { QButtonGroup *group = m_ui->name->group(); bool exclusive; - if (group) { + if(group) { exclusive = group->exclusive(); - if (m_ui->name->isChecked()) { + if(m_ui->name->isChecked()) { group->setExclusive(false); } } m_ui->name->setChecked(false); - if (group) { + if(group) { group->setExclusive(exclusive); } } @@ -278,7 +225,7 @@ void ChannelWidget::on_box_toggled(bool checked) // Uncheck the menu button when disabling the ChannelWidget m_ui->btn->setChecked(false); - if (!m_simplified) + if(!m_simplified) m_ui->name->setEnabled(false); m_ui->btn->setEnabled(false); @@ -287,15 +234,9 @@ void ChannelWidget::on_box_toggled(bool checked) Q_EMIT enabled(checked); } -void ChannelWidget::on_name_toggled(bool checked) -{ - Q_EMIT selected(checked); -} +void ChannelWidget::on_name_toggled(bool checked) { Q_EMIT selected(checked); } -void ChannelWidget::on_btn_toggled(bool checked) -{ - Q_EMIT menuToggled(checked); -} +void ChannelWidget::on_btn_toggled(bool checked) { Q_EMIT menuToggled(checked); } void ChannelWidget::on_delBtn_clicked() { @@ -306,33 +247,21 @@ void ChannelWidget::on_delBtn_clicked() Q_EMIT deleteClicked(); } -bool ChannelWidget::isMainChannel() const -{ - return m_isMainChannel; -} +bool ChannelWidget::isMainChannel() const { return m_isMainChannel; } -bool ChannelWidget::isPhysicalChannel() const -{ - return m_isPhysicalChannel; -} +bool ChannelWidget::isPhysicalChannel() const { return m_isPhysicalChannel; } void ChannelWidget::setButtonNoGroup(QAbstractButton *btn) { QButtonGroup *group = btn->group(); - if (group) { + if(group) { group->removeButton(btn); } } -void ChannelWidget::setMenuButtonVisibility(bool visible) -{ - m_ui->btn->setVisible(visible); -} +void ChannelWidget::setMenuButtonVisibility(bool visible) { m_ui->btn->setVisible(visible); } -void ChannelWidget::setBottomLineVIsibility(bool visible) -{ - m_ui->line->setVisible(visible); -} +void ChannelWidget::setBottomLineVIsibility(bool visible) { m_ui->line->setVisible(visible); } void ChannelWidget::toggleChannel(bool toggled) { @@ -342,17 +271,15 @@ void ChannelWidget::toggleChannel(bool toggled) void ChannelWidget::setIsMainChannel(bool mainChannel) { - if (mainChannel) { + if(mainChannel) { m_isMainChannel = true; m_ui->box->hide(); m_ui->toggleChannels->show(); - connect(m_ui->toggleChannels, &QPushButton::toggled, this, [=](bool toggled){ - Q_EMIT enabled(toggled); - }); + connect(m_ui->toggleChannels, &QPushButton::toggled, this, + [=](bool toggled) { Q_EMIT enabled(toggled); }); } } -void ChannelWidget::setIsPhysicalChannel(bool physChannel) -{ - m_isPhysicalChannel = physChannel; -} +void ChannelWidget::setIsPhysicalChannel(bool physChannel) { m_isPhysicalChannel = physChannel; } + +#include "moc_channel_widget.cpp" diff --git a/gui/src/checkbox_delegate.cpp b/gui/src/checkbox_delegate.cpp index a3a21517b5..6492eb0d0b 100644 --- a/gui/src/checkbox_delegate.cpp +++ b/gui/src/checkbox_delegate.cpp @@ -25,39 +25,34 @@ using namespace scopy; -CheckboxDelegate::CheckboxDelegate(QObject *parent): - QStyledItemDelegate(parent) -{ -} +CheckboxDelegate::CheckboxDelegate(QObject *parent) + : QStyledItemDelegate(parent) +{} -QWidget *CheckboxDelegate::createEditor(QWidget *parent, - const QStyleOptionViewItem &, const QModelIndex &) const +QWidget *CheckboxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &) const { QCheckBox *editor = new QCheckBox(parent); editor->setAutoFillBackground(true); - connect(editor, SIGNAL(toggled(bool)), - this, SLOT(commitDataToModel())); + connect(editor, SIGNAL(toggled(bool)), this, SLOT(commitDataToModel())); return editor; } -void CheckboxDelegate::setEditorData(QWidget *editor, - const QModelIndex &index) const +void CheckboxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { bool state = index.model()->data(index, Qt::EditRole).toBool(); - QCheckBox *checkBox = static_cast(editor); + QCheckBox *checkBox = static_cast(editor); checkBox->setChecked(state); } -void CheckboxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const +void CheckboxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { - QCheckBox *checkBox = static_cast(editor); + QCheckBox *checkBox = static_cast(editor); int val; - if (checkBox->isChecked()) + if(checkBox->isChecked()) val = 1; else val = 0; @@ -71,3 +66,5 @@ void CheckboxDelegate::commitDataToModel() Q_EMIT commitData(editor); } + +#include "moc_checkbox_delegate.cpp" diff --git a/gui/src/completion_circle.cpp b/gui/src/completion_circle.cpp index e919001469..4ebfb23df0 100644 --- a/gui/src/completion_circle.cpp +++ b/gui/src/completion_circle.cpp @@ -20,20 +20,26 @@ #include "completion_circle.h" +#include #include #include #include -#include - using namespace scopy; -CompletionCircle::CompletionCircle(QWidget *parent, bool invert_circle) : - QDial(parent), - m_double_value(0.5), m_double_minimum(1.0), m_double_maximum(0.0), m_origin(90), - m_xc(0), m_yc(0), m_radius(23), - m_pressed(false), m_log_scale(false), invert_circle(invert_circle), - m_toggleable(true) +CompletionCircle::CompletionCircle(QWidget *parent, bool invert_circle) + : QDial(parent) + , m_double_value(0.5) + , m_double_minimum(1.0) + , m_double_maximum(0.0) + , m_origin(90) + , m_xc(0) + , m_yc(0) + , m_radius(23) + , m_pressed(false) + , m_log_scale(false) + , invert_circle(invert_circle) + , m_toggleable(true) { setWrapping(true); setMinimumSize(50, 50); @@ -56,7 +62,7 @@ void CompletionCircle::paintEvent(QPaintEvent *) m_xc = xc; m_yc = yc; - if (!m_log_scale) { + if(!m_log_scale) { min = minimumDouble(); max = maximumDouble(); val = valueDouble(); @@ -68,7 +74,7 @@ void CompletionCircle::paintEvent(QPaintEvent *) completeRatio = qAbs((val - min) / (max - min)); - if (invert_circle) { + if(invert_circle) { completeRatio = 1.0 - completeRatio; } @@ -83,7 +89,7 @@ void CompletionCircle::paintEvent(QPaintEvent *) QPen rail_pen(qss_color); rail_pen.setWidth(3); p.setPen(rail_pen); - QRectF rect(xc - r, yc - r, 2* r, 2 * r); + QRectF rect(xc - r, yc - r, 2 * r, 2 * r); p.drawArc(rect, m_origin * 16, angle * 16); // Background circle @@ -93,10 +99,10 @@ void CompletionCircle::paintEvent(QPaintEvent *) p.drawArc(rect, (m_origin + angle) * 16, (360 - angle) * 16); // The center dot - if (m_toggleable) { + if(m_toggleable) { QColor centerDotColor(Qt::black); - if (m_pressed) { + if(m_pressed) { centerDotColor = QColor(255, 114, 0); } @@ -125,9 +131,9 @@ void CompletionCircle::paintEvent(QPaintEvent *) void CompletionCircle::mousePressEvent(QMouseEvent *e) { - if (e->button() == Qt::LeftButton) { - if (pointInsideCircle(e->pos(), m_xc, m_yc, m_radius - 2)) { - if (m_toggleable) { + if(e->button() == Qt::LeftButton) { + if(pointInsideCircle(e->pos(), m_xc, m_yc, m_radius - 2)) { + if(m_toggleable) { m_pressed = !m_pressed; repaint(); Q_EMIT toggled(m_pressed); @@ -136,23 +142,15 @@ void CompletionCircle::mousePressEvent(QMouseEvent *e) } } -void CompletionCircle::mouseReleaseEvent(QMouseEvent *) -{ -} +void CompletionCircle::mouseReleaseEvent(QMouseEvent *) {} -void CompletionCircle::mouseMoveEvent(QMouseEvent *) -{ -} +void CompletionCircle::mouseMoveEvent(QMouseEvent *) {} -void CompletionCircle::keyPressEvent(QKeyEvent *) -{ -} +void CompletionCircle::keyPressEvent(QKeyEvent *) {} -void CompletionCircle::wheelEvent(QWheelEvent *) -{ -} +void CompletionCircle::wheelEvent(QWheelEvent *) {} -bool CompletionCircle::pointInsideCircle(const QPoint& p, int xc, int yc, int r) +bool CompletionCircle::pointInsideCircle(const QPoint &p, int xc, int yc, int r) { int x = p.x(); int y = p.y(); @@ -160,92 +158,65 @@ bool CompletionCircle::pointInsideCircle(const QPoint& p, int xc, int yc, int r) return ((x - xc) * (x - xc) + (y - yc) * (y - yc) < r * r); } -double CompletionCircle::valueDouble() -{ - return m_double_value; -} +double CompletionCircle::valueDouble() { return m_double_value; } void CompletionCircle::setValueDouble(double value) { - if (value < m_double_minimum) { + if(value < m_double_minimum) { value = m_double_minimum; - } else if (value > m_double_maximum) { + } else if(value > m_double_maximum) { value = m_double_maximum; } - if (m_double_value != value) { + if(m_double_value != value) { m_double_value = value; sliderChange(SliderValueChange); } } -bool CompletionCircle::toggledState() -{ - return m_pressed; -} +bool CompletionCircle::toggledState() { return m_pressed; } void CompletionCircle::setToggled(bool on) { - if (m_pressed != on) { + if(m_pressed != on) { m_pressed = on; Q_EMIT toggled(on); } } -double CompletionCircle::minimumDouble() -{ - return m_double_minimum; -} +double CompletionCircle::minimumDouble() { return m_double_minimum; } -void CompletionCircle::setOrigin(double value) -{ - m_origin = value; -} +void CompletionCircle::setOrigin(double value) { m_origin = value; } void CompletionCircle::setMinimumDouble(double value) { m_double_minimum = value; - if (m_double_value < m_double_minimum) { + if(m_double_value < m_double_minimum) { setValueDouble(value); } repaint(); } -double CompletionCircle::maximumDouble() -{ - return m_double_maximum; -} +double CompletionCircle::maximumDouble() { return m_double_maximum; } void CompletionCircle::setMaximumDouble(double value) { m_double_maximum = value; - if (m_double_value > m_double_maximum) { + if(m_double_value > m_double_maximum) { setValueDouble(value); } repaint(); } -void CompletionCircle::setToggleable(bool tog) -{ - m_toggleable = tog; -} +void CompletionCircle::setToggleable(bool tog) { m_toggleable = tog; } -bool CompletionCircle::isLogScale() -{ - return m_log_scale; -} +bool CompletionCircle::isLogScale() { return m_log_scale; } -bool CompletionCircle::toggleable() -{ - return m_toggleable; -} -void CompletionCircle::setIsLogScale(bool state) -{ - m_log_scale = state; -} +bool CompletionCircle::toggleable() { return m_toggleable; } +void CompletionCircle::setIsLogScale(bool state) { m_log_scale = state; } #include "moc_completion_circle.cpp" diff --git a/gui/src/cursor.cpp b/gui/src/cursor.cpp index 257679db14..46f40bef97 100644 --- a/gui/src/cursor.cpp +++ b/gui/src/cursor.cpp @@ -1,37 +1,25 @@ #include "cursor.h" + #include "plot_line_handle.h" using namespace scopy; - Cursor::Cursor(PlotWidget *p, PlotAxis *ax, QPen pen) - : QObject(p), - m_plotWidget(p), - m_axis(ax), - m_plot(p->plot()), - m_pen(pen), - m_canLeavePlot(false) -{ + : QObject(p) + , m_plotWidget(p) + , m_axis(ax) + , m_plot(p->plot()) + , m_pen(pen) + , m_canLeavePlot(false) +{} -} +Cursor::~Cursor() {} -Cursor::~Cursor() -{ +void Cursor::setCanLeavePlot(bool leave) { m_canLeavePlot = leave; } -} +PlotLineHandle *Cursor::cursorHandle() const { return m_cursorHandle; } -void Cursor::setCanLeavePlot(bool leave) -{ - m_canLeavePlot = leave; -} - -PlotLineHandle *Cursor::cursorHandle() const { - return m_cursorHandle; -} - -void Cursor::setAxis(PlotAxis *ax) { - m_axis = ax; -} +void Cursor::setAxis(PlotAxis *ax) { m_axis = ax; } void Cursor::setVisible(bool visible) { @@ -39,7 +27,6 @@ void Cursor::setVisible(bool visible) m_cursorBar->setVisible(visible); } -bool Cursor::isVisible() -{ - return m_cursorHandle->isVisible() || m_cursorBar->isVisible(); -} +bool Cursor::isVisible() { return m_cursorHandle->isVisible() || m_cursorBar->isVisible(); } + +#include "moc_cursor.cpp" diff --git a/gui/src/cursor_readouts.cpp b/gui/src/cursor_readouts.cpp index fa7302ff82..e89eea322d 100644 --- a/gui/src/cursor_readouts.cpp +++ b/gui/src/cursor_readouts.cpp @@ -19,28 +19,29 @@ */ #include "cursor_readouts.h" + #include "ui_cursor_readouts.h" -#include -#include -#include #include +#include +#include +#include #include #include #include using namespace scopy; -CursorReadouts::CursorReadouts(QwtPlot *plot): - QWidget(plot), - ui(new Ui::CursorReadouts), - d_voltage_rd_visible(true), - d_time_rd_visible(true), - freq_delta_visible(true), - d_topLeft(QPoint(0, 0)), - currentPosition(CustomPlotPositionButton::topLeft), - hAxis(QwtAxis::XBottom), - vAxis(QwtAxis::YLeft) +CursorReadouts::CursorReadouts(QwtPlot *plot) + : QWidget(plot) + , ui(new Ui::CursorReadouts) + , d_voltage_rd_visible(true) + , d_time_rd_visible(true) + , freq_delta_visible(true) + , d_topLeft(QPoint(0, 0)) + , currentPosition(CustomPlotPositionButton::topLeft) + , hAxis(QwtAxis::XBottom) + , vAxis(QwtAxis::YLeft) { ui->setupUi(this); ui->TimeCursors->setParent(plot->canvas()); @@ -70,25 +71,29 @@ void CursorReadouts::setTransparency(int value) double percent = (100 - value) / 100.0; QString color = ""; - if (QIcon::themeName() == "scopy-default") { - color +="rgba(20, 20, 22, "; + if(QIcon::themeName() == "scopy-default") { + color += "rgba(20, 20, 22, "; } else { - color +="rgba(197, 197, 197, "; + color += "rgba(197, 197, 197, "; } color += QString::number(percent); ui->TimeCursors->setStyleSheet("QWidget {" - "background-color: " + color + ");" - "}"); + "background-color: " + + color + + ");" + "}"); ui->VoltageCursors->setStyleSheet("QWidget {" - "background-color: " + color + ");" - "}"); + "background-color: " + + color + + ");" + "}"); } void CursorReadouts::moveToPosition(CustomPlotPositionButton::ReadoutsPosition position) { - switch (position) { + switch(position) { case CustomPlotPositionButton::topLeft: moveTopLeft(); @@ -110,10 +115,7 @@ void CursorReadouts::moveToPosition(CustomPlotPositionButton::ReadoutsPosition p currentPosition = position; } -CustomPlotPositionButton::ReadoutsPosition CursorReadouts::getCurrentPosition() -{ - return currentPosition; -} +CustomPlotPositionButton::ReadoutsPosition CursorReadouts::getCurrentPosition() { return currentPosition; } void CursorReadouts::showEvent(QShowEvent *event) { @@ -122,195 +124,116 @@ void CursorReadouts::showEvent(QShowEvent *event) QWidget::showEvent(event); } -QwtPlot *CursorReadouts::plot() -{ - return static_cast(parent()); -} +QwtPlot *CursorReadouts::plot() { return static_cast(parent()); } -const QwtPlot *CursorReadouts::plot() const -{ - return static_cast(parent()); -} +const QwtPlot *CursorReadouts::plot() const { return static_cast(parent()); } void CursorReadouts::setVoltageReadoutVisible(bool on) { - if (d_voltage_rd_visible != on) { + if(d_voltage_rd_visible != on) { d_voltage_rd_visible = on; ui->VoltageCursors->setVisible(on); updateSizeAndPosition(); } } -bool CursorReadouts::isVoltageReadoutVisible() -{ - return d_voltage_rd_visible; -} +bool CursorReadouts::isVoltageReadoutVisible() { return d_voltage_rd_visible; } void CursorReadouts::setTimeReadoutVisible(bool on) { - if (d_time_rd_visible != on) { + if(d_time_rd_visible != on) { d_time_rd_visible = on; ui->TimeCursors->setVisible(on); updateSizeAndPosition(); } } -bool CursorReadouts::isTimeReadoutVisible() -{ - return d_time_rd_visible; -} +bool CursorReadouts::isTimeReadoutVisible() { return d_time_rd_visible; } -void CursorReadouts::setTopLeftStartingPoint(QPoint point) -{ - d_topLeft = point; -} +void CursorReadouts::setTopLeftStartingPoint(QPoint point) { d_topLeft = point; } -QPoint CursorReadouts::topLeftStartingPoint() -{ - return d_topLeft; -} +QPoint CursorReadouts::topLeftStartingPoint() { return d_topLeft; } -void CursorReadouts::setTimeCursor1Text(const QString &text) -{ - ui->cursorT1->setText(text); -} +void CursorReadouts::setTimeCursor1Text(const QString &text) { ui->cursorT1->setText(text); } -QString CursorReadouts::timeCursor1Text() -{ - return ui->cursorT1->text(); -} +QString CursorReadouts::timeCursor1Text() { return ui->cursorT1->text(); } -void CursorReadouts::setTimeCursor2Text(const QString &text) -{ - ui->cursorT2->setText(text); -} +void CursorReadouts::setTimeCursor2Text(const QString &text) { ui->cursorT2->setText(text); } -QString CursorReadouts::timeCursor2Text() -{ - return ui->cursorT2->text(); -} +QString CursorReadouts::timeCursor2Text() { return ui->cursorT2->text(); } -void CursorReadouts::setTimeDeltaText(const QString &text) -{ - ui->timeDelta->setText(text); -} +void CursorReadouts::setTimeDeltaText(const QString &text) { ui->timeDelta->setText(text); } -QString CursorReadouts::timeDeltaText() -{ - return ui->timeDelta->text(); -} +QString CursorReadouts::timeDeltaText() { return ui->timeDelta->text(); } -void CursorReadouts::setFreqDeltaText(const QString &text) -{ - ui->frequencyDelta->setText(text); -} +void CursorReadouts::setFreqDeltaText(const QString &text) { ui->frequencyDelta->setText(text); } -QString CursorReadouts::freqDeltaText() -{ - return ui->frequencyDelta->text(); -} +QString CursorReadouts::freqDeltaText() { return ui->frequencyDelta->text(); } -void CursorReadouts::setVoltageCursor1Text(const QString &text) -{ - ui->cursorV1->setText(text); -} +void CursorReadouts::setVoltageCursor1Text(const QString &text) { ui->cursorV1->setText(text); } -QString CursorReadouts::voltageCursor1Text() -{ - return ui->cursorV1->text(); -} +QString CursorReadouts::voltageCursor1Text() { return ui->cursorV1->text(); } -void CursorReadouts::setVoltageCursor2Text(const QString &text) -{ - ui->cursorV2->setText(text); -} +void CursorReadouts::setVoltageCursor2Text(const QString &text) { ui->cursorV2->setText(text); } -QString CursorReadouts::voltageCursor2Text() -{ - return ui->cursorV2->text(); -} +QString CursorReadouts::voltageCursor2Text() { return ui->cursorV2->text(); } + +void CursorReadouts::setVoltageDeltaText(const QString &text) { ui->voltageDelta->setText(text); } -void CursorReadouts::setVoltageDeltaText(const QString &text) +QString CursorReadouts::voltageDeltaText() { return ui->voltageDelta->text(); } + +void CursorReadouts::setTimeDeltaVisible(bool visible) { - ui->voltageDelta->setText(text); + ui->timeDeltaLabel->setVisible(visible); + ui->timeDelta->setVisible(visible); } -QString CursorReadouts::voltageDeltaText() +void CursorReadouts::setFrequencyDeltaVisible(bool visible) { - return ui->voltageDelta->text(); + ui->frequencyDeltaLabel->setVisible(visible); + ui->frequencyDelta->setVisible(visible); + freq_delta_visible = visible; } -void CursorReadouts::setTimeDeltaVisible(bool visible){ - ui->timeDeltaLabel->setVisible(visible); - ui->timeDelta->setVisible(visible); -} +void CursorReadouts::setTimeCursor1LabelText(const QString &text) { ui->cursorT1label->setText(text); } -void CursorReadouts::setFrequencyDeltaVisible(bool visible){ - ui->frequencyDeltaLabel->setVisible(visible); - ui->frequencyDelta->setVisible(visible); - freq_delta_visible = visible; -} +QString CursorReadouts::timeCursor1LabelText() { return ui->cursorT1label->text(); } -void CursorReadouts::setTimeCursor1LabelText(const QString &text){ - ui->cursorT1label->setText(text); -} +void CursorReadouts::setTimeCursor2LabelText(const QString &text) { ui->cursorT2label->setText(text); } -QString CursorReadouts::timeCursor1LabelText(){ - return ui->cursorT1label->text(); -} +QString CursorReadouts::timeCursor2LabelText() { return ui->cursorT2label->text(); } -void CursorReadouts::setTimeCursor2LabelText(const QString &text){ - ui->cursorT2label->setText(text); -} +void CursorReadouts::setTimeDeltaLabelText(const QString &text) { ui->timeDeltaLabel->setText(text); } -QString CursorReadouts::timeCursor2LabelText(){ - return ui->cursorT2label->text(); -} +void CursorReadouts::setVoltageCursor1LabelText(const QString &text) { ui->cursorV1label->setText(text); } -void CursorReadouts::setTimeDeltaLabelText(const QString &text){ - ui->timeDeltaLabel->setText(text); -} +QString CursorReadouts::voltageCursor1LabelText() { return ui->cursorV2label->text(); } -void CursorReadouts::setVoltageCursor1LabelText(const QString &text){ - ui->cursorV1label->setText(text); -} +void CursorReadouts::setVoltageCursor2LabelText(const QString &text) { ui->cursorV2label->setText(text); } -QString CursorReadouts::voltageCursor1LabelText(){ - return ui->cursorV2label->text(); -} +QString CursorReadouts::voltageCursor2LabelText() { return ui->cursorV2label->text(); } -void CursorReadouts::setVoltageCursor2LabelText(const QString &text){ - ui->cursorV2label->setText(text); -} +void CursorReadouts::setDeltaVoltageLabelText(const QString &text) { ui->deltaVlabel->setText(text); } -QString CursorReadouts::voltageCursor2LabelText(){ - return ui->cursorV2label->text(); -} - -void CursorReadouts::setDeltaVoltageLabelText(const QString &text){ - ui->deltaVlabel->setText(text); -} - -QString CursorReadouts::deltaVoltageLabelText(){ - return ui->deltaVlabel->text(); -} +QString CursorReadouts::deltaVoltageLabelText() { return ui->deltaVlabel->text(); } -void CursorReadouts::setAxis(QwtAxisId hAxis,QwtAxisId vAxis){ - this->hAxis = hAxis; - this->vAxis = vAxis; +void CursorReadouts::setAxis(QwtAxisId hAxis, QwtAxisId vAxis) +{ + this->hAxis = hAxis; + this->vAxis = vAxis; } bool CursorReadouts::eventFilter(QObject *object, QEvent *event) { - if (object == plot()->canvas()) { + if(object == plot()->canvas()) { switch(event->type()) { - case QEvent::Resize: { - updateSizeAndPosition(true); - break; - } - default: - break; - } + case QEvent::Resize: { + updateSizeAndPosition(true); + break; + } + default: + break; + } return false; } @@ -320,15 +243,15 @@ bool CursorReadouts::eventFilter(QObject *object, QEvent *event) QPoint CursorReadouts::plotPointToPixelPoint(const QPointF &point) const { - const QwtScaleMap xMap = plot()->canvasMap(hAxis); - const QwtScaleMap yMap = plot()->canvasMap(vAxis); + const QwtScaleMap xMap = plot()->canvasMap(hAxis); + const QwtScaleMap yMap = plot()->canvasMap(vAxis); return QwtScaleMap::transform(xMap, yMap, point).toPoint(); } void CursorReadouts::updateSizeAndPosition(bool resize) { - switch (currentPosition) { + switch(currentPosition) { case CustomPlotPositionButton::topLeft: moveTopLeft(resize); @@ -350,26 +273,34 @@ void CursorReadouts::updateSizeAndPosition(bool resize) void CursorReadouts::moveTopLeft(bool resize) { - if (!isVisible()) + if(!isVisible()) return; d_topLeft = QPoint(8, 8); - QRect timeRect, voltageRect; + QRect timeRect, voltageRect; - if (!d_time_rd_visible && d_voltage_rd_visible) { - voltageRect = QRect(d_topLeft, QPoint(d_topLeft.x()+ui->VoltageCursors->width(),d_topLeft.y()+ui->VoltageCursors->height())); - timeRect = QRect(0,0,0,0); - } else { - timeRect = QRect(d_topLeft, QPoint(ui->TimeCursors->width()+d_topLeft.x(),ui->TimeCursors->height()+d_topLeft.y())); - voltageRect = QRect(QPoint(d_topLeft.x()+timeRect.width(),d_topLeft.y()), QPoint(d_topLeft.x()+timeRect.width()+ui->VoltageCursors->width(),ui->VoltageCursors->height()+d_topLeft.y())); - } + if(!d_time_rd_visible && d_voltage_rd_visible) { + voltageRect = QRect(d_topLeft, + QPoint(d_topLeft.x() + ui->VoltageCursors->width(), + d_topLeft.y() + ui->VoltageCursors->height())); + timeRect = QRect(0, 0, 0, 0); + } else { + timeRect = QRect( + d_topLeft, + QPoint(ui->TimeCursors->width() + d_topLeft.x(), ui->TimeCursors->height() + d_topLeft.y())); + voltageRect = QRect(QPoint(d_topLeft.x() + timeRect.width(), d_topLeft.y()), + QPoint(d_topLeft.x() + timeRect.width() + ui->VoltageCursors->width(), + ui->VoltageCursors->height() + d_topLeft.y())); + } int diff = voltageRect.x() - lastVoltageRect.x(); - if (diff < 10 && diff > -10) diff = voltageRect.y() - lastVoltageRect.y(); + if(diff < 10 && diff > -10) + diff = voltageRect.y() - lastVoltageRect.y(); int duration = diff < 0 ? -diff : diff; duration = duration > 200 ? 200 : duration; - if (resize) duration = 0; + if(resize) + duration = 0; anim->setDuration(duration), anim2->setDuration(duration); QRect start = lastVoltageRect; @@ -387,29 +318,32 @@ void CursorReadouts::moveTopLeft(bool resize) void CursorReadouts::moveTopRight(bool resize) { - if (!isVisible()) + if(!isVisible()) return; d_topLeft.setY(8); - d_topLeft.setX(plot()->canvas()->width()-8); - + d_topLeft.setX(plot()->canvas()->width() - 8); QRect timeRect, voltageRect; - if (d_time_rd_visible && !d_voltage_rd_visible) { - voltageRect = QRect(0,0,0,0); - timeRect = QRect(d_topLeft.x() - ui->TimeCursors->width(),d_topLeft.y(),d_topLeft.x(),d_topLeft.y()+ui->TimeCursors->height()); + if(d_time_rd_visible && !d_voltage_rd_visible) { + voltageRect = QRect(0, 0, 0, 0); + timeRect = QRect(d_topLeft.x() - ui->TimeCursors->width(), d_topLeft.y(), d_topLeft.x(), + d_topLeft.y() + ui->TimeCursors->height()); } else { - voltageRect = QRect(d_topLeft.x() - ui->VoltageCursors->width(),d_topLeft.y(),d_topLeft.x(),d_topLeft.y()+ui->VoltageCursors->height()); - timeRect = QRect(voltageRect.x()-ui->TimeCursors->width(),d_topLeft.y(),voltageRect.x(),d_topLeft.y()+ui->VoltageCursors->height()); - + voltageRect = QRect(d_topLeft.x() - ui->VoltageCursors->width(), d_topLeft.y(), d_topLeft.x(), + d_topLeft.y() + ui->VoltageCursors->height()); + timeRect = QRect(voltageRect.x() - ui->TimeCursors->width(), d_topLeft.y(), voltageRect.x(), + d_topLeft.y() + ui->VoltageCursors->height()); } int diff = timeRect.x() - lastTimeRect.x(); - if (diff < 10 && diff > -10) diff = timeRect.y() - lastTimeRect.y(); + if(diff < 10 && diff > -10) + diff = timeRect.y() - lastTimeRect.y(); int duration = diff < 0 ? -diff : diff; duration = duration > 200 ? 200 : duration; - if (resize) duration = 0; + if(resize) + duration = 0; anim->setDuration(duration), anim2->setDuration(duration); QRect start = lastVoltageRect; @@ -427,37 +361,43 @@ void CursorReadouts::moveTopRight(bool resize) void CursorReadouts::moveBottomLeft(bool resize) { - if (!isVisible()) + if(!isVisible()) return; QRect timeRect, voltageRect; - int value = plot()->canvas()->height()-8; + int value = plot()->canvas()->height() - 8; d_topLeft.setY(value); d_topLeft.setX(8); - if(freq_delta_visible) - { - if (!d_time_rd_visible && d_voltage_rd_visible) { - voltageRect = QRect(QPoint(d_topLeft.x(),d_topLeft.y()-ui->VoltageCursors->height()-20), QPoint(d_topLeft.x()+ui->VoltageCursors->width(),d_topLeft.y())); - timeRect = QRect(0,0,0,0); + if(freq_delta_visible) { + if(!d_time_rd_visible && d_voltage_rd_visible) { + voltageRect = QRect(QPoint(d_topLeft.x(), d_topLeft.y() - ui->VoltageCursors->height() - 20), + QPoint(d_topLeft.x() + ui->VoltageCursors->width(), d_topLeft.y())); + timeRect = QRect(0, 0, 0, 0); } else { - timeRect = QRect(QPoint(d_topLeft.x(),d_topLeft.y()-ui->TimeCursors->height()-20), QPoint(ui->TimeCursors->width()+d_topLeft.x(),d_topLeft.y())); - voltageRect = QRect(QPoint(d_topLeft.x()+timeRect.width(),d_topLeft.y()-ui->VoltageCursors->height()-20), QPoint(d_topLeft.x()+timeRect.width()+ui->VoltageCursors->width(),d_topLeft.y())); + timeRect = QRect(QPoint(d_topLeft.x(), d_topLeft.y() - ui->TimeCursors->height() - 20), + QPoint(ui->TimeCursors->width() + d_topLeft.x(), d_topLeft.y())); + voltageRect = QRect( + QPoint(d_topLeft.x() + timeRect.width(), + d_topLeft.y() - ui->VoltageCursors->height() - 20), + QPoint(d_topLeft.x() + timeRect.width() + ui->VoltageCursors->width(), d_topLeft.y())); } + } else { + timeRect = QRect(QPoint(d_topLeft.x(), d_topLeft.y() - ui->TimeCursors->height() + 5), + QPoint(ui->TimeCursors->width() + d_topLeft.x(), d_topLeft.y())); + voltageRect = QRect( + QPoint(d_topLeft.x() + timeRect.width(), d_topLeft.y() - ui->VoltageCursors->height() + 5), + QPoint(d_topLeft.x() + timeRect.width() + ui->VoltageCursors->width(), d_topLeft.y())); } - else - { - timeRect = QRect(QPoint(d_topLeft.x(),d_topLeft.y()-ui->TimeCursors->height()+5), QPoint(ui->TimeCursors->width()+d_topLeft.x(),d_topLeft.y())); - voltageRect = QRect(QPoint(d_topLeft.x()+timeRect.width(),d_topLeft.y()-ui->VoltageCursors->height()+5), QPoint(d_topLeft.x()+timeRect.width()+ui->VoltageCursors->width(),d_topLeft.y())); - } - int diff = voltageRect.x() - lastVoltageRect.x(); - if (diff < 10 && diff > -10) diff = voltageRect.y() - lastVoltageRect.y(); + if(diff < 10 && diff > -10) + diff = voltageRect.y() - lastVoltageRect.y(); int duration = diff < 0 ? -diff : diff; duration = duration > 200 ? 200 : duration; - if (resize) duration = 0; + if(resize) + duration = 0; anim->setDuration(duration), anim2->setDuration(duration); QRect start = lastVoltageRect; @@ -475,35 +415,40 @@ void CursorReadouts::moveBottomLeft(bool resize) void CursorReadouts::moveBottomRight(bool resize) { - if (!isVisible()) + if(!isVisible()) return; QRect timeRect, voltageRect; - d_topLeft.setY(plot()->canvas()->height()-8); - d_topLeft.setX(plot()->canvas()->width()-8); + d_topLeft.setY(plot()->canvas()->height() - 8); + d_topLeft.setX(plot()->canvas()->width() - 8); - if(freq_delta_visible) - { - if (d_time_rd_visible && !d_voltage_rd_visible) { - voltageRect = QRect(0,0,0,0); - timeRect = QRect(d_topLeft.x() - ui->TimeCursors->width(),d_topLeft.y()-ui->TimeCursors->height()-20,d_topLeft.x(),d_topLeft.y()); + if(freq_delta_visible) { + if(d_time_rd_visible && !d_voltage_rd_visible) { + voltageRect = QRect(0, 0, 0, 0); + timeRect = QRect(d_topLeft.x() - ui->TimeCursors->width(), + d_topLeft.y() - ui->TimeCursors->height() - 20, d_topLeft.x(), d_topLeft.y()); } else { - voltageRect = QRect(d_topLeft.x() - ui->VoltageCursors->width(),d_topLeft.y()-ui->VoltageCursors->height()-20,d_topLeft.x(),d_topLeft.y()); - timeRect = QRect(voltageRect.x()-ui->TimeCursors->width(),voltageRect.y(),voltageRect.x(),voltageRect.y()+ui->TimeCursors->height()); + voltageRect = + QRect(d_topLeft.x() - ui->VoltageCursors->width(), + d_topLeft.y() - ui->VoltageCursors->height() - 20, d_topLeft.x(), d_topLeft.y()); + timeRect = QRect(voltageRect.x() - ui->TimeCursors->width(), voltageRect.y(), voltageRect.x(), + voltageRect.y() + ui->TimeCursors->height()); } - } - else - { - voltageRect = QRect(d_topLeft.x() - ui->VoltageCursors->width(),d_topLeft.y()-ui->VoltageCursors->height()+5,d_topLeft.x(),d_topLeft.y()); - timeRect = QRect(voltageRect.x()-ui->TimeCursors->width(),voltageRect.y(),voltageRect.x(),voltageRect.y()+ui->TimeCursors->height()+5); + } else { + voltageRect = QRect(d_topLeft.x() - ui->VoltageCursors->width(), + d_topLeft.y() - ui->VoltageCursors->height() + 5, d_topLeft.x(), d_topLeft.y()); + timeRect = QRect(voltageRect.x() - ui->TimeCursors->width(), voltageRect.y(), voltageRect.x(), + voltageRect.y() + ui->TimeCursors->height() + 5); } int diff = timeRect.x() - lastTimeRect.x(); - if (diff < 10 && diff > -10) diff = timeRect.y() - lastTimeRect.y(); + if(diff < 10 && diff > -10) + diff = timeRect.y() - lastTimeRect.y(); int duration = diff < 0 ? -diff : diff; duration = duration > 200 ? 200 : duration; - if (resize) duration = 0; + if(resize) + duration = 0; anim->setDuration(duration), anim2->setDuration(duration); QRect start = lastVoltageRect; diff --git a/gui/src/cursorcontroller.cpp b/gui/src/cursorcontroller.cpp index 5f2b506afa..1d8b3fa749 100644 --- a/gui/src/cursorcontroller.cpp +++ b/gui/src/cursorcontroller.cpp @@ -145,10 +145,7 @@ void CursorController::setVisible(bool visible) cursorsSetVisible(visible); } -void CursorController::readoutsSetVisible(bool visible) -{ - hoverReadouts->setVisible(visible && (horizEn || vertEn)); -} +void CursorController::readoutsSetVisible(bool visible) { hoverReadouts->setVisible(visible && (horizEn || vertEn)); } void CursorController::cursorsSetVisible(bool visible) { @@ -156,12 +153,8 @@ void CursorController::cursorsSetVisible(bool visible) plotCursors->vertSetVisible(visible && vertEn); } -CursorSettings *CursorController::getCursorSettings() -{ - return cursorSettings; -} +CursorSettings *CursorController::getCursorSettings() { return cursorSettings; } -PlotCursors *CursorController::getPlotCursors() -{ - return plotCursors; -} +PlotCursors *CursorController::getPlotCursors() { return plotCursors; } + +#include "moc_cursorcontroller.cpp" diff --git a/gui/src/customPushButton.cpp b/gui/src/customPushButton.cpp index 1f1c2e5d45..f3a8dfce32 100644 --- a/gui/src/customPushButton.cpp +++ b/gui/src/customPushButton.cpp @@ -24,43 +24,40 @@ using namespace scopy; -CustomPushButton::CustomPushButton(QWidget *parent) : QPushButton(parent) -{ -} +CustomPushButton::CustomPushButton(QWidget *parent) + : QPushButton(parent) +{} -CustomPushButton::~CustomPushButton() -{ -} +CustomPushButton::~CustomPushButton() {} void CustomPushButton::mouseReleaseEvent(QMouseEvent *event) { QButtonGroup *btnGroup = group(); - if (btnGroup) { + if(btnGroup) { if(btnGroup->checkedId() == group()->id(this) && isDown()) btnGroup->setExclusive(false); } QPushButton::mouseReleaseEvent(event); - if (btnGroup) { + if(btnGroup) { btnGroup->setExclusive(true); } - } void CustomPushButton::setChecked(bool checked) { QButtonGroup *btnGroup = group(); - if (btnGroup) { + if(btnGroup) { if(btnGroup->checkedId() == group()->id(this) && !checked) btnGroup->setExclusive(false); } QPushButton::setChecked(checked); - if (btnGroup) { + if(btnGroup) { btnGroup->setExclusive(true); } } diff --git a/gui/src/customScale.cpp b/gui/src/customScale.cpp index bb49acd2fe..988d325a7f 100644 --- a/gui/src/customScale.cpp +++ b/gui/src/customScale.cpp @@ -21,14 +21,15 @@ #include "customScale.hpp" #include + #include using namespace scopy; -CustomScale::CustomScale(QWidget *parent) : - QwtThermo(parent), - m_currentScale(0), - autoScale(true) +CustomScale::CustomScale(QWidget *parent) + : QwtThermo(parent) + , m_currentScale(0) + , autoScale(true) { QVector divs; @@ -36,54 +37,35 @@ CustomScale::CustomScale(QWidget *parent) : scaler = new AutoScaler(this, divs); - connect(scaler, SIGNAL(updateScale(const QwtScaleDiv)), - this, SLOT(updateScale(const QwtScaleDiv))); + connect(scaler, SIGNAL(updateScale(const QwtScaleDiv)), this, SLOT(updateScale(const QwtScaleDiv))); } -CustomScale::~CustomScale() -{ - delete scaler; -} +CustomScale::~CustomScale() { delete scaler; } void CustomScale::addScale(double x1, double x2, int maxMajorSteps, int maxMinorSteps, double stepSize) { - scaler->addScaleDivs(scaleEngine()->divideScale(x1, x2, maxMajorSteps, maxMinorSteps,stepSize)); + scaler->addScaleDivs(scaleEngine()->divideScale(x1, x2, maxMajorSteps, maxMinorSteps, stepSize)); } -void CustomScale::updateScale(const QwtScaleDiv div) -{ - setScale(div); -} +void CustomScale::updateScale(const QwtScaleDiv div) { setScale(div); } -bool CustomScale::getAutoScaler() const -{ - return autoScale; -} +bool CustomScale::getAutoScaler() const { return autoScale; } -void CustomScale::setAutoScaler(bool newAutoScaler) -{ - autoScale = newAutoScaler; -} +void CustomScale::setAutoScaler(bool newAutoScaler) { autoScale = newAutoScaler; } -void CustomScale::start() -{ - scaler->startTimer(); -} +void CustomScale::start() { scaler->startTimer(); } -void CustomScale::stop() -{ - scaler->stopTimer(); -} +void CustomScale::stop() { scaler->stopTimer(); } int numDigits(double num) { - if (int(num) == 0) { + if(int(num) == 0) { return -1; } int digits = 0; - while ((int)num) { + while((int)num) { num /= 10; digits++; } @@ -93,15 +75,15 @@ int numDigits(double num) void CustomScale::setValue(double value) { - if (autoScale) { + if(autoScale) { // update scale int n = numDigits(value); - double scale = pow(10 , n); - if (scale < value) { + double scale = pow(10, n); + if(scale < value) { scale *= 10; } - if (scale != m_currentScale) { - updateScale(scaleEngine()->divideScale((-1*scale),scale,5,10)); + if(scale != m_currentScale) { + updateScale(scaleEngine()->divideScale((-1 * scale), scale, 5, 10)); m_currentScale = scale; } } diff --git a/gui/src/customSwitch.cpp b/gui/src/customSwitch.cpp index 05611b9a44..8bd044e63e 100644 --- a/gui/src/customSwitch.cpp +++ b/gui/src/customSwitch.cpp @@ -21,14 +21,18 @@ #include "customSwitch.h" #include -#include #include +#include using namespace scopy; -CustomSwitch::CustomSwitch(QWidget *parent) : QPushButton(parent), - on(this), off(this), handle(this), anim(&handle, "geometry"), - polarity(false) +CustomSwitch::CustomSwitch(QWidget *parent) + : QPushButton(parent) + , on(this) + , off(this) + , handle(this) + , anim(&handle, "geometry") + , polarity(false) { on.setObjectName("on"); off.setObjectName("off"); @@ -59,20 +63,19 @@ void CustomSwitch::updateOnOffLabels() bool CustomSwitch::event(QEvent *e) { - if (e->type() == QEvent::DynamicPropertyChange) - { - QDynamicPropertyChangeEvent *const propEvent = static_cast(e); + if(e->type() == QEvent::DynamicPropertyChange) { + QDynamicPropertyChangeEvent *const propEvent = static_cast(e); QString propName = propEvent->propertyName(); - if(propName=="leftText" && property("leftText").isValid()) + if(propName == "leftText" && property("leftText").isValid()) on.setText(property("leftText").toString()); - if(propName=="rightText" && property("rightText").isValid()) + if(propName == "rightText" && property("rightText").isValid()) off.setText(property("rightText").toString()); - if(propName=="polarity" && property("polarity").isValid()) + if(propName == "polarity" && property("polarity").isValid()) polarity = property("polarity").toBool(); - if(propName=="duration" && property("duration").isValid()) + if(propName == "duration" && property("duration").isValid()) setDuration(property("duration").toInt()); - if(propName=="bigBtn" && property("bigBtn").isValid()) { - if (property("bigBtn").toBool()) { + if(propName == "bigBtn" && property("bigBtn").isValid()) { + if(property("bigBtn").toBool()) { QFile file(":/gui/stylesheets/bigCustomSwitch.qss"); file.open(QFile::ReadOnly); QString styleSheet = QString::fromLatin1(file.readAll()); @@ -83,9 +86,7 @@ bool CustomSwitch::event(QEvent *e) return QPushButton::event(e); } -CustomSwitch::~CustomSwitch() -{ -} +CustomSwitch::~CustomSwitch() {} void CustomSwitch::setDuration(int ms) { @@ -95,16 +96,15 @@ void CustomSwitch::setDuration(int ms) void CustomSwitch::toggleAnim(bool enabled) { - if (!isVisible()) + if(!isVisible()) return; QRect on_rect(0, handle.y(), handle.width(), handle.height()); - QRect off_rect(width() - handle.width(), handle.y(), - handle.width(), handle.height()); + QRect off_rect(width() - handle.width(), handle.y(), handle.width(), handle.height()); anim.stop(); - if (enabled ^ polarity) { + if(enabled ^ polarity) { anim.setStartValue(off_rect); anim.setEndValue(on_rect); } else { @@ -119,39 +119,23 @@ void CustomSwitch::toggleAnim(bool enabled) void CustomSwitch::showEvent(QShowEvent *event) { updateOnOffLabels(); - if (isChecked() ^ polarity) { - handle.setGeometry(QRect(0, handle.y(), handle.width(), - handle.height())); - } - else { - handle.setGeometry(QRect(width() - handle.width(), handle.y(), - handle.width(), handle.height())); + if(isChecked() ^ polarity) { + handle.setGeometry(QRect(0, handle.y(), handle.width(), handle.height())); + } else { + handle.setGeometry(QRect(width() - handle.width(), handle.y(), handle.width(), handle.height())); } - } -const QLabel &CustomSwitch::getOn() const { - return on; -} +const QLabel &CustomSwitch::getOn() const { return on; } -void CustomSwitch::setOnText(const QString &on_) { - this->on.setText(on_); -} +void CustomSwitch::setOnText(const QString &on_) { this->on.setText(on_); } -const QLabel &CustomSwitch::getOff() const { - return off; -} +const QLabel &CustomSwitch::getOff() const { return off; } -void CustomSwitch::setOffText(const QString &off_) { - this->off.setText(off_); -} +void CustomSwitch::setOffText(const QString &off_) { this->off.setText(off_); } -void CustomSwitch::setOn(const QPixmap &pixmap) { - this->on.setPixmap(pixmap); -} +void CustomSwitch::setOn(const QPixmap &pixmap) { this->on.setPixmap(pixmap); } -void CustomSwitch::setOff(const QPixmap &pixmap) { - this->off.setPixmap(pixmap); -} +void CustomSwitch::setOff(const QPixmap &pixmap) { this->off.setPixmap(pixmap); } #include "moc_customSwitch.cpp" diff --git a/gui/src/custom_menu_button.cpp b/gui/src/custom_menu_button.cpp index c80a421986..19ce42534f 100644 --- a/gui/src/custom_menu_button.cpp +++ b/gui/src/custom_menu_button.cpp @@ -1,23 +1,23 @@ -#include "ui_custom_menu_button.h" - #include "custom_menu_button.hpp" +#include "ui_custom_menu_button.h" + using namespace scopy::gui; -CustomMenuButton::CustomMenuButton(QString labelText, bool checkboxVisible, bool checkBoxChecked, QWidget* parent) +CustomMenuButton::CustomMenuButton(QString labelText, bool checkboxVisible, bool checkBoxChecked, QWidget *parent) : CustomMenuButton(parent) { m_ui->lblCustomMenuButton->setText(labelText); m_ui->checkBoxCustomMenuButton->setVisible(checkboxVisible); - if (checkboxVisible) { + if(checkboxVisible) { checkBoxToggled(checkBoxChecked); m_ui->checkBoxCustomMenuButton->setChecked(checkBoxChecked); } } -CustomMenuButton::CustomMenuButton(QWidget* parent) +CustomMenuButton::CustomMenuButton(QWidget *parent) : QWidget(parent) , m_ui(new Ui::CustomMenuButton) , m_floatingMenu(false) @@ -28,13 +28,13 @@ CustomMenuButton::CustomMenuButton(QWidget* parent) CustomMenuButton::~CustomMenuButton() { delete m_ui; } -void CustomMenuButton::setLabel(const QString& text) { m_ui->lblCustomMenuButton->setText(text); } +void CustomMenuButton::setLabel(const QString &text) { m_ui->lblCustomMenuButton->setText(text); } void CustomMenuButton::setCheckboxVisible(bool visible) { m_ui->checkBoxCustomMenuButton->setVisible(visible); } -CustomPushButton* CustomMenuButton::getBtn() { return m_ui->btnCustomMenuButton; } +CustomPushButton *CustomMenuButton::getBtn() { return m_ui->btnCustomMenuButton; } -QCheckBox* CustomMenuButton::getCheckBox() { return m_ui->checkBoxCustomMenuButton; } +QCheckBox *CustomMenuButton::getCheckBox() { return m_ui->checkBoxCustomMenuButton; } bool CustomMenuButton::getCheckBoxState() { return getCheckBox()->isChecked(); } @@ -44,11 +44,13 @@ void CustomMenuButton::setMenuFloating(bool floating) { m_floatingMenu = floatin void CustomMenuButton::checkBoxToggled(bool toggled) { - if (!toggled) { + if(!toggled) { m_ui->btnCustomMenuButton->setChecked(false); } - if (!m_floatingMenu) { + if(!m_floatingMenu) { m_ui->btnCustomMenuButton->setEnabled(toggled); } } + +#include "moc_custom_menu_button.cpp" diff --git a/gui/src/customanimation.cpp b/gui/src/customanimation.cpp index ed640417c4..c1bbdc1a5f 100644 --- a/gui/src/customanimation.cpp +++ b/gui/src/customanimation.cpp @@ -19,35 +19,33 @@ */ #include "customanimation.h" + #include using namespace scopy; -CustomAnimation::CustomAnimation(QObject *target): - QPropertyAnimation(target), - m_enabled(true), - m_duration(0) +CustomAnimation::CustomAnimation(QObject *target) + : QPropertyAnimation(target) + , m_enabled(true) + , m_duration(0) { AnimationManager::getInstance().registerAnimation(this); } -CustomAnimation::CustomAnimation(QObject *target, const QByteArray &propertyName, - QObject *parent): - QPropertyAnimation(target, propertyName, parent), - m_enabled(true), - m_duration(0) +CustomAnimation::CustomAnimation(QObject *target, const QByteArray &propertyName, QObject *parent) + : QPropertyAnimation(target, propertyName, parent) + , m_enabled(true) + , m_duration(0) { AnimationManager::getInstance().registerAnimation(this); } -CustomAnimation::~CustomAnimation() -{ -} +CustomAnimation::~CustomAnimation() {} void CustomAnimation::setDuration(int msec) { m_duration = msec; - if (m_enabled) { + if(m_enabled) { QPropertyAnimation::setDuration(msec); } } diff --git a/gui/src/customplotpositionbutton.cpp b/gui/src/customplotpositionbutton.cpp index 0ad5119332..7032cbf20b 100644 --- a/gui/src/customplotpositionbutton.cpp +++ b/gui/src/customplotpositionbutton.cpp @@ -18,45 +18,47 @@ * along with this program. If not, see . */ #include "customplotpositionbutton.h" -#include "ui_customplotpositionbutton.h" + #include "dynamicWidget.h" +#include "ui_customplotpositionbutton.h" + using namespace scopy; -CustomPlotPositionButton::CustomPlotPositionButton(QWidget *parent) : - QWidget(parent), - ui(new Ui::CustomPlotPositionButton) +CustomPlotPositionButton::CustomPlotPositionButton(QWidget *parent) + : QWidget(parent) + , ui(new Ui::CustomPlotPositionButton) { ui->setupUi(this); - setAttribute(Qt::WA_StyledBackground,true); + setAttribute(Qt::WA_StyledBackground, true); - setDynamicProperty(ui->leftTop, "selected" , true); - setDynamicProperty(ui->rightTop, "selected" , false); - setDynamicProperty(ui->rightBot, "selected" , false); - setDynamicProperty(ui->leftBot, "selected" , false); + setDynamicProperty(ui->leftTop, "selected", true); + setDynamicProperty(ui->rightTop, "selected", false); + setDynamicProperty(ui->rightBot, "selected", false); + setDynamicProperty(ui->leftBot, "selected", false); ui->leftTop->setChecked(true); btns = new QButtonGroup(this); - connect(ui->leftTop, &QPushButton::toggled, [=](bool on){ - setDynamicProperty(ui->leftTop, "selected" , on); - if (on) + connect(ui->leftTop, &QPushButton::toggled, [=](bool on) { + setDynamicProperty(ui->leftTop, "selected", on); + if(on) Q_EMIT positionChanged(topLeft); }); - connect(ui->rightTop, &QPushButton::toggled, [=](bool on){ - setDynamicProperty(ui->rightTop, "selected" , on); - if (on) + connect(ui->rightTop, &QPushButton::toggled, [=](bool on) { + setDynamicProperty(ui->rightTop, "selected", on); + if(on) Q_EMIT positionChanged(topRight); }); - connect(ui->rightBot, &QPushButton::toggled, [=](bool on){ - setDynamicProperty(ui->rightBot, "selected" , on); - if (on) + connect(ui->rightBot, &QPushButton::toggled, [=](bool on) { + setDynamicProperty(ui->rightBot, "selected", on); + if(on) Q_EMIT positionChanged(bottomRight); }); - connect(ui->leftBot, &QPushButton::toggled, [=](bool on){ - setDynamicProperty(ui->leftBot, "selected" , on); - if (on) + connect(ui->leftBot, &QPushButton::toggled, [=](bool on) { + setDynamicProperty(ui->leftBot, "selected", on); + if(on) Q_EMIT positionChanged(bottomLeft); }); @@ -66,14 +68,11 @@ CustomPlotPositionButton::CustomPlotPositionButton(QWidget *parent) : btns->addButton(ui->rightTop); } -CustomPlotPositionButton::~CustomPlotPositionButton() -{ - delete ui; -} +CustomPlotPositionButton::~CustomPlotPositionButton() { delete ui; } void CustomPlotPositionButton::setPosition(ReadoutsPosition position) { - switch (position) { + switch(position) { case topLeft: default: ui->leftTop->setChecked(true); diff --git a/gui/src/customqwtscaledraw.cpp b/gui/src/customqwtscaledraw.cpp index 86510e36c5..065286b729 100644 --- a/gui/src/customqwtscaledraw.cpp +++ b/gui/src/customqwtscaledraw.cpp @@ -2,19 +2,15 @@ using namespace scopy; -CustomQwtScaleDraw::CustomQwtScaleDraw() -{} +CustomQwtScaleDraw::CustomQwtScaleDraw() {} -CustomQwtScaleDraw::~CustomQwtScaleDraw() -{} +CustomQwtScaleDraw::~CustomQwtScaleDraw() {} QwtText CustomQwtScaleDraw::label(double value) const { MetricPrefixFormatter m_prefixFormater; - return QwtText(QString::number(m_prefixFormater.getFormatedValue(value)) + " " + m_prefixFormater.getFormatedMeasureUnit(value) + m_unitOfMeasure); + return QwtText(QString::number(m_prefixFormater.getFormatedValue(value)) + " " + + m_prefixFormater.getFormatedMeasureUnit(value) + m_unitOfMeasure); } -void CustomQwtScaleDraw::setUnitOfMeasure(QString unitOfMeasure) -{ - m_unitOfMeasure = unitOfMeasure; -} +void CustomQwtScaleDraw::setUnitOfMeasure(QString unitOfMeasure) { m_unitOfMeasure = unitOfMeasure; } diff --git a/gui/src/db_click_buttons.cpp b/gui/src/db_click_buttons.cpp index 4361eafae0..3c9c805a9d 100644 --- a/gui/src/db_click_buttons.cpp +++ b/gui/src/db_click_buttons.cpp @@ -18,9 +18,11 @@ * along with this program. If not, see . */ #include "db_click_buttons.hpp" -#include "ui_db_click_buttons.h" + #include "dynamicWidget.h" +#include "ui_db_click_buttons.h" + #include using namespace scopy; @@ -32,45 +34,40 @@ using namespace scopy; * button has been selected it can be toggled. */ -DbClickButtons::DbClickButtons(QWidget *parent, int maxRowBtnCount) : - QWidget(parent), - ui(new Ui::DbClickButtons), - btn_states(), - selected_btn(-1), - max_row_btn_cnt(maxRowBtnCount > 0 ? maxRowBtnCount : 1) +DbClickButtons::DbClickButtons(QWidget *parent, int maxRowBtnCount) + : QWidget(parent) + , ui(new Ui::DbClickButtons) + , btn_states() + , selected_btn(-1) + , max_row_btn_cnt(maxRowBtnCount > 0 ? maxRowBtnCount : 1) { ui->setupUi(this); - color_codes << "#F44336" << "#2096F3" << "#8BC34A" << "#FF5721" << - "#607D8B"; + color_codes << "#F44336" + << "#2096F3" + << "#8BC34A" + << "#FF5721" + << "#607D8B"; btn_list = findChildren(); int n = 0; - for (const auto& i : qAsConst(btn_list)) { + for(const auto &i : qAsConst(btn_list)) { btn_states.push_back(false); i->setProperty("id", QVariant(n++)); - connect(i, SIGNAL(clicked()), - this, SLOT(onButtonClicked())); - + connect(i, SIGNAL(clicked()), this, SLOT(onButtonClicked())); } } -DbClickButtons::~DbClickButtons() -{ - delete ui; -} +DbClickButtons::~DbClickButtons() { delete ui; } -int DbClickButtons::selectedButton() const -{ - return selected_btn; -} +int DbClickButtons::selectedButton() const { return selected_btn; } void DbClickButtons::setSelectedButton(int btnId) { - for (int i = 0; i < btn_list.size(); i++) { + for(int i = 0; i < btn_list.size(); i++) { bool selected; - if (i == btnId) { + if(i == btnId) { selected = true; } else { selected = false; @@ -79,17 +76,14 @@ void DbClickButtons::setSelectedButton(int btnId) setDynamicProperty(btn_list[i], "is_selected", selected); btn_list[i]->update(); - if (selected) { + if(selected) { selected_btn = btnId; Q_EMIT buttonSelected(btnId); } } } -bool DbClickButtons::buttonChecked(int btnId) const -{ - return btn_states[btnId]; -} +bool DbClickButtons::buttonChecked(int btnId) const { return btn_states[btnId]; } void DbClickButtons::setButtonChecked(int btnId, bool checked) { @@ -100,22 +94,19 @@ void DbClickButtons::setButtonChecked(int btnId, bool checked) Q_EMIT buttonToggled(btnId, checked); } -int DbClickButtons::buttonCount() const -{ - return btn_list.size(); -} +int DbClickButtons::buttonCount() const { return btn_list.size(); } void DbClickButtons::setButtonCount(int count) { - if (count != btn_list.size()) { - for (int i = 0; i < btn_list.size(); i++) { + if(count != btn_list.size()) { + for(int i = 0; i < btn_list.size(); i++) { delete btn_list[i]; } selected_btn = -1; btn_list.clear(); QGridLayout *gLayout = static_cast(layout()); - for (int i = 0; i < count; i++) { + for(int i = 0; i < count; i++) { QPushButton *btn = new QPushButton(this); btn->setText(QString::number(i)); btn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); @@ -123,15 +114,15 @@ void DbClickButtons::setButtonCount(int count) btn->setProperty("is_checked", QVariant(false)); btn->setProperty("is_selected", QVariant(false)); QString color = color_codes[i % color_codes.size()]; - QString stylesheet = QString ("QPushButton" - "{\n border: 2px solid %1;\n}\n" - "\nQPushButton[is_checked=true] {\n " - "background-color: %1;\n}\n" - "\nQPushButton[is_selected=true] {\n " - "border: 4px solid white;\n}\n").arg(color); + QString stylesheet = QString("QPushButton" + "{\n border: 2px solid %1;\n}\n" + "\nQPushButton[is_checked=true] {\n " + "background-color: %1;\n}\n" + "\nQPushButton[is_selected=true] {\n " + "border: 4px solid white;\n}\n") + .arg(color); btn->setStyleSheet(stylesheet); - connect(btn, SIGNAL(clicked()), - this, SLOT(onButtonClicked())); + connect(btn, SIGNAL(clicked()), this, SLOT(onButtonClicked())); int row = i / max_row_btn_cnt; int col = i % max_row_btn_cnt; @@ -147,16 +138,15 @@ void DbClickButtons::onButtonClicked() QPushButton *btn = static_cast(QObject::sender()); int btnId = btn->property("id").toInt(); - if (selected_btn < 0) { + if(selected_btn < 0) { setSelectedButton(btnId); - } else if (btn == btn_list[selected_btn]) { - toggleButton(btnId); + } else if(btn == btn_list[selected_btn]) { + toggleButton(btnId); } else { setSelectedButton(btnId); } } -void DbClickButtons::toggleButton(int btnId) -{ - setButtonChecked(btnId, !btn_states[btnId]); -} +void DbClickButtons::toggleButton(int btnId) { setButtonChecked(btnId, !btn_states[btnId]); } + +#include "moc_db_click_buttons.cpp" diff --git a/gui/src/dbgraph.cpp b/gui/src/dbgraph.cpp index 1df6352da2..1978ac12c6 100644 --- a/gui/src/dbgraph.cpp +++ b/gui/src/dbgraph.cpp @@ -19,13 +19,14 @@ */ #include "dbgraph.hpp" + #include "DisplayPlot.h" #include "osc_scale_engine.h" -#include "x_axis_scale_zoomer.h" #include "plotpickerwrapper.h" +#include "x_axis_scale_zoomer.h" -#include #include +#include using namespace scopy; @@ -49,8 +50,7 @@ void dBgraph::setupVerticalBars() d_plotBar->setPen(plotLinePen); d_plotBar->setMobileAxis(QwtAxis::XTop); - connect(d_frequencyBar, &VertBar::pixelPositionChanged, - this, &dBgraph::frequencyBarPositionChanged); + connect(d_frequencyBar, &VertBar::pixelPositionChanged, this, &dBgraph::frequencyBarPositionChanged); d_vBar1->setMobileAxis(QwtAxis::XTop); d_vBar2->setMobileAxis(QwtAxis::XTop); @@ -73,17 +73,17 @@ void dBgraph::setupReadouts() } dBgraph::dBgraph(QWidget *parent, bool isdBgraph) - : DisplayPlot(0, parent, isdBgraph), - curve("data"), - reference("reference"), - xmin(10), - xmax(10), - ymin(10), - ymax(10), - d_plotPosition(0), - numSamples(0), - delta_label(false), - d_plotBarEnabled(true) + : DisplayPlot(0, parent, isdBgraph) + , curve("data") + , reference("reference") + , xmin(10) + , xmax(10) + , ymin(10) + , ymax(10) + , d_plotPosition(0) + , numSamples(0) + , delta_label(false) + , d_plotBarEnabled(true) { setAxisVisible(QwtAxis::XBottom, false); setAxisVisible(QwtAxis::XTop, true); @@ -92,7 +92,7 @@ dBgraph::dBgraph(QWidget *parent, bool isdBgraph) setAxisAutoScale(QwtAxis::XTop, false); QColor plotColor; - if (QIcon::themeName() == "scopy-default") { + if(QIcon::themeName() == "scopy-default") { plotColor = QColor("#6E6E6F"); } else { plotColor = QColor("#D3D3D3"); @@ -123,8 +123,7 @@ dBgraph::dBgraph(QWidget *parent, bool isdBgraph) OscScaleEngine *scaleLeft = new OscScaleEngine; setYaxisNumDiv(7); scaleLeft->setMajorTicksCount(7); - this->setAxisScaleEngine(QwtAxis::YLeft, - static_cast(scaleLeft)); + this->setAxisScaleEngine(QwtAxis::YLeft, static_cast(scaleLeft)); /* draw_x / draw_y: Outmost X / Y scales. Only draw the labels */ draw_x = new OscScaleDraw(d_formatter, "Hz"); @@ -148,29 +147,25 @@ dBgraph::dBgraph(QWidget *parent, bool isdBgraph) d_rightHandlesArea->setMinimumWidth(40); d_rightHandlesArea->setMinimumHeight(this->minimumHeight()); - d_topHandlesArea->setMinimumHeight(20); d_topHandlesArea->setLargestChildWidth(60); useLogFreq(false); /* Create 4 scales within the plot itself. Only draw the ticks */ - for (unsigned int i = 0; i < 4; i++) { - EdgelessPlotScaleItem *scaleItem = new EdgelessPlotScaleItem( - static_cast(i)); + for(unsigned int i = 0; i < 4; i++) { + EdgelessPlotScaleItem *scaleItem = new EdgelessPlotScaleItem(static_cast(i)); /* Top/bottom scales must be sync'd to xTop; left/right scales - * must be sync'd to yLeft */ - if (i < 2) { + * must be sync'd to yLeft */ + if(i < 2) { scaleItem->setXAxis(QwtAxis::XTop); } else { scaleItem->setYAxis(QwtAxis::YLeft); } - scaleItem->scaleDraw()->enableComponent( - QwtAbstractScaleDraw::Backbone, false); - scaleItem->scaleDraw()->enableComponent( - QwtAbstractScaleDraw::Labels, false); + scaleItem->scaleDraw()->enableComponent(QwtAbstractScaleDraw::Backbone, false); + scaleItem->scaleDraw()->enableComponent(QwtAbstractScaleDraw::Labels, false); QPalette palette = scaleItem->palette(); palette.setBrush(QPalette::WindowText, QColor(plotColor)); @@ -181,10 +176,8 @@ dBgraph::dBgraph(QWidget *parent, bool isdBgraph) } zoomer = new XAxisScaleZoomer(canvas()); - zoomer->setMousePattern(QwtEventPattern::MouseSelect3, - Qt::RightButton); - zoomer->setMousePattern(QwtEventPattern::MouseSelect2, - Qt::RightButton, Qt::ControlModifier); + zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); + zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); installEventFilter(this); @@ -217,7 +210,7 @@ dBgraph::~dBgraph() void dBgraph::replot() { - if (!d_leftHandlesArea || !d_topHandlesArea) { + if(!d_leftHandlesArea || !d_topHandlesArea) { return; } @@ -232,7 +225,6 @@ void dBgraph::enableXaxisLabels() d_topHandlesArea->installExtension(std::unique_ptr(new XTopRuller(this))); } - void dBgraph::enableYaxisLabels() { d_leftHandlesArea->installExtension(std::unique_ptr(new YLeftRuller(this))); @@ -240,7 +232,7 @@ void dBgraph::enableYaxisLabels() void dBgraph::parametersOverrange(bool enable) { - if (enable) { + if(enable) { d_plotBar->setPen(QPen(QColor(250, 0, 0, 50), 5, Qt::SolidLine)); } else { d_plotBar->setPen(QPen(QColor(211, 211, 211, 50), 5, Qt::SolidLine)); @@ -253,7 +245,7 @@ void dBgraph::setAxesScales(double xmin, double xmax, double ymin, double ymax) setAxisScale(QwtAxis::YLeft, ymin, ymax); } -void dBgraph::setAxesTitles(const QString& x, const QString& y) +void dBgraph::setAxesTitles(const QString &x, const QString &y) { QwtText xTitle(x); QwtText yTitle(y); @@ -269,13 +261,13 @@ void dBgraph::setAxesTitles(const QString& x, const QString& y) void dBgraph::plot(double x, double y) { - if (!d_plotBar->isVisible() && !xdata.size()) { - if (d_plotBarEnabled) { + if(!d_plotBar->isVisible() && !xdata.size()) { + if(d_plotBarEnabled) { d_plotBar->setVisible(true); } } - if (xdata.size() == numSamples) { + if(xdata.size() == numSamples) { xdata[d_plotPosition] = x; ydata[d_plotPosition] = y; @@ -283,7 +275,7 @@ void dBgraph::plot(double x, double y) d_plotPosition++; // Return to first point when reaching the end - if (d_plotPosition == numSamples) { + if(d_plotPosition == numSamples) { d_plotPosition = 0; } } else { @@ -295,7 +287,7 @@ void dBgraph::plot(double x, double y) curve.setRawSamples(xdata.data(), ydata.data(), xdata.size()); - if (d_cursorsEnabled) { + if(d_cursorsEnabled) { onVCursor1Moved(d_vBar1->plotCoord().x()); onVCursor2Moved(d_vBar2->plotCoord().x()); } @@ -304,41 +296,29 @@ void dBgraph::plot(double x, double y) bool dBgraph::eventFilter(QObject *object, QEvent *event) { - if (object == canvas() && event->type() == QEvent::Resize) - { + if(object == canvas() && event->type() == QEvent::Resize) { d_leftHandlesArea->repaint(); d_bottomHandlesArea->setLeftPadding(d_leftHandlesArea->width() + 10); d_bottomHandlesArea->setRightPadding(d_rightHandlesArea->width() + 24); - } return QObject::eventFilter(object, event); } -int dBgraph::getNumSamples() const -{ - return numSamples; -} +int dBgraph::getNumSamples() const { return numSamples; } QString dBgraph::getScaleValueFormat(double value, QwtAxisId scale) const { - auto *scaleDraw = static_cast( - axisScaleDraw(scale)); + auto *scaleDraw = static_cast(axisScaleDraw(scale)); - return d_formatter->format(value, - scaleDraw->getUnitType(), - scaleDraw->getFloatPrecison()); + return d_formatter->format(value, scaleDraw->getUnitType(), scaleDraw->getFloatPrecison()); } -QString dBgraph::getScaleValueFormat(double value, QwtAxisId scale, - int precision) const +QString dBgraph::getScaleValueFormat(double value, QwtAxisId scale, int precision) const { - auto *scaleDraw = static_cast( - axisScaleDraw(scale)); + auto *scaleDraw = static_cast(axisScaleDraw(scale)); - return d_formatter->format(value, - scaleDraw->getUnitType(), - precision); + return d_formatter->format(value, scaleDraw->getUnitType(), precision); } void dBgraph::setShowZero(bool en) @@ -347,24 +327,20 @@ void dBgraph::setShowZero(bool en) scaleLeft->setMajorTicksCount(7); scaleLeft->showZero(en); - this->setAxisScaleEngine(QwtAxis::YLeft, - static_cast(scaleLeft)); + this->setAxisScaleEngine(QwtAxis::YLeft, static_cast(scaleLeft)); replot(); } -const QwtScaleWidget *dBgraph::getAxisWidget(QwtAxisId id) -{ - return axisWidget(id); -} +const QwtScaleWidget *dBgraph::getAxisWidget(QwtAxisId id) { return axisWidget(id); } void dBgraph::setNumSamples(int num) { - if (numSamples == num) { + if(numSamples == num) { return; } - numSamples = (unsigned int) num; + numSamples = (unsigned int)num; reset(); @@ -378,41 +354,29 @@ void dBgraph::reset() d_plotPosition = 0; } -void dBgraph::setColor(const QColor& color) +void dBgraph::setColor(const QColor &color) { this->color = color; - curve.setPen(QPen(color,thickness)); + curve.setPen(QPen(color, thickness)); } -const QColor& dBgraph::getColor() const -{ - return this->color; -} +const QColor &dBgraph::getColor() const { return this->color; } void dBgraph::setThickness(int index) { double thickness = 0.5 * (index + 1); this->thickness = thickness; - curve.setPen(QPen(color,thickness)); + curve.setPen(QPen(color, thickness)); replot(); } -double dBgraph::getThickness() -{ - return this->thickness; -} +double dBgraph::getThickness() { return this->thickness; } -QString dBgraph::xTitle() const -{ - return axisTitle(QwtAxis::XTop).text(); -} +QString dBgraph::xTitle() const { return axisTitle(QwtAxis::XTop).text(); } -QString dBgraph::yTitle() const -{ - return axisTitle(QwtAxis::YLeft).text(); -} +QString dBgraph::yTitle() const { return axisTitle(QwtAxis::YLeft).text(); } -void dBgraph::setXTitle(const QString& title) +void dBgraph::setXTitle(const QString &title) { QwtText xTitle(title); QFont font = axisTitle(QwtAxis::XTop).font(); @@ -422,7 +386,7 @@ void dBgraph::setXTitle(const QString& title) setAxisTitle(QwtAxis::XTop, xTitle); } -void dBgraph::setYTitle(const QString& title) +void dBgraph::setYTitle(const QString &title) { QwtText yTitle(title); QFont font = axisTitle(QwtAxis::XTop).font(); @@ -430,9 +394,9 @@ void dBgraph::setYTitle(const QString& title) yTitle.setFont(font); setAxisTitle(QwtAxis::YLeft, yTitle); - d_cursorReadouts->setVoltageCursor1LabelText(title.mid(0,3)+"1 = "); - d_cursorReadouts->setVoltageCursor2LabelText(title.mid(0,3)+"2 = "); - d_cursorReadouts->setDeltaVoltageLabelText("Δ"+title.mid(0,3)+" = "); + d_cursorReadouts->setVoltageCursor1LabelText(title.mid(0, 3) + "1 = "); + d_cursorReadouts->setVoltageCursor2LabelText(title.mid(0, 3) + "2 = "); + d_cursorReadouts->setDeltaVoltageLabelText("Δ" + title.mid(0, 3) + " = "); } void dBgraph::setXMin(double val) @@ -489,27 +453,23 @@ void dBgraph::setYMax(double val) QString dBgraph::xUnit() const { - return draw_x->getUnitType();; + return draw_x->getUnitType(); + ; } QString dBgraph::yUnit() const { - return draw_y->getUnitType();; + return draw_y->getUnitType(); + ; } -void dBgraph::setXUnit(const QString& unit) -{ - draw_x->setUnitType(unit); -} +void dBgraph::setXUnit(const QString &unit) { draw_x->setUnitType(unit); } -void dBgraph::setYUnit(const QString& unit) -{ - draw_y->setUnitType(unit); -} +void dBgraph::setYUnit(const QString &unit) { draw_y->setUnitType(unit); } void dBgraph::useLogFreq(bool use_log_freq) { - if (use_log_freq) { + if(use_log_freq) { setPlotLogaritmic(true); this->setAxisScaleEngine(QwtAxis::XTop, new QwtLogScaleEngine); replot(); @@ -526,7 +486,7 @@ void dBgraph::useLogFreq(bool use_log_freq) this->log_freq = use_log_freq; - if (d_cursorsEnabled && isVisible()) { + if(d_cursorsEnabled && isVisible()) { onVCursor1Moved(d_vBar1->plotCoord().x()); onVCursor2Moved(d_vBar2->plotCoord().x()); } @@ -543,10 +503,10 @@ void dBgraph::useLogFreq(bool use_log_freq) void dBgraph::useDeltaLabel(bool use_delta) { - if (delta_label != use_delta) { + if(delta_label != use_delta) { delta_label = use_delta; - if (!log_freq) { + if(!log_freq) { auto sw = axisWidget(QwtAxis::XTop); auto *sd = dynamic_cast(sw->scaleDraw()); sd->enableDeltaLabel(use_delta); @@ -557,7 +517,7 @@ void dBgraph::useDeltaLabel(bool use_delta) void dBgraph::sweepDone() { - if (d_plotBarEnabled) { + if(d_plotBarEnabled) { d_plotBar->setVisible(false); } } @@ -590,7 +550,7 @@ void dBgraph::removeReferenceWaveform() bool dBgraph::addReferenceWaveformFromPlot() { - if (xdata.size() == 0 || ydata.size() == 0) { + if(xdata.size() == 0 || ydata.size() == 0) { return false; } @@ -599,14 +559,11 @@ bool dBgraph::addReferenceWaveformFromPlot() return true; } -QString dBgraph::formatXValue(double value, int precision) const -{ - return d_formatter->format(value, "Hz", precision); -} +QString dBgraph::formatXValue(double value, int precision) const { return d_formatter->format(value, "Hz", precision); } QString dBgraph::formatYValue(double value, int precision) const { - return d_formatter->format(value, draw_y->getUnitType(), precision); + return d_formatter->format(value, draw_y->getUnitType(), precision); } void dBgraph::onVCursor1Moved(double value) @@ -621,18 +578,17 @@ void dBgraph::onVCursor1Moved(double value) double d1 = d_cursorReadouts->voltageCursor1Text().split(" ")[0].toDouble(); double d2 = d_cursorReadouts->voltageCursor2Text().split(" ")[0].toDouble(); - if (text == "-") { + if(text == "-") { markerIntersection1->detach(); } else { - if (d_cursorsEnabled) { + if(d_cursorsEnabled) { markerIntersection1->attach(this); markerIntersection1->setValue(value, d1); } } replot(); - d_cursorReadouts->setVoltageDeltaText(QString::number(d2-d1)+" "+ - draw_y->getUnitType()); + d_cursorReadouts->setVoltageDeltaText(QString::number(d2 - d1) + " " + draw_y->getUnitType()); } void dBgraph::onVCursor2Moved(double value) @@ -647,41 +603,40 @@ void dBgraph::onVCursor2Moved(double value) double d1 = d_cursorReadouts->voltageCursor1Text().split(" ")[0].toDouble(); double d2 = d_cursorReadouts->voltageCursor2Text().split(" ")[0].toDouble(); - if (text == "-") { + if(text == "-") { markerIntersection2->detach(); } else { - if (d_cursorsEnabled) { + if(d_cursorsEnabled) { markerIntersection2->attach(this); markerIntersection2->setValue(value, d2); } } replot(); - d_cursorReadouts->setVoltageDeltaText(QString::number(d2-d1)+" "+ - draw_y->getUnitType()); + d_cursorReadouts->setVoltageDeltaText(QString::number(d2 - d1) + " " + draw_y->getUnitType()); } QString dBgraph::cursorIntersection(qreal freq) { - if (xdata.size() == 0 || xdata.data()[xdata.size()-1] < freq) { - return QString("-");//for the case when there is no plot + if(xdata.size() == 0 || xdata.data()[xdata.size() - 1] < freq) { + return QString("-"); // for the case when there is no plot } else { - double leftFreq,rightFreq,leftCustom,rightCustom; + double leftFreq, rightFreq, leftCustom, rightCustom; int rightIndex = -1; int leftIndex = -1; - for (int i=1; igetUnitType(); + return QString::number(val, 'f', 2) + " " + draw_y->getUnitType(); } } @@ -704,7 +658,7 @@ QVector dBgraph::getXAxisData() { QVector data; - for (size_t i = 0; i < curve.data()->size(); ++i) { + for(size_t i = 0; i < curve.data()->size(); ++i) { data.push_back(curve.data()->sample(i).x()); } @@ -715,7 +669,7 @@ QVector dBgraph::getYAxisData() { QVector data; - for (size_t i = 0; i < curve.data()->size(); ++i) { + for(size_t i = 0; i < curve.data()->size(); ++i) { data.push_back(curve.data()->sample(i).y()); } @@ -730,18 +684,18 @@ void dBgraph::enableFrequencyBar(bool enable) void dBgraph::setYAxisInterval(double min, double max, double correction) { - for (size_t i = 0; i < ydata.size(); ++i) { + for(size_t i = 0; i < ydata.size(); ++i) { double value = ydata[i]; bool modified = false; - if (value > max) { + if(value > max) { value = value - correction; modified = true; - } else if (value < min) { + } else if(value < min) { value = value + correction; modified = true; } - if (modified) { + if(modified) { ydata[i] = value; curve.setRawSamples(xdata.data(), ydata.data(), xdata.size()); replot(); @@ -762,26 +716,20 @@ void dBgraph::scaleDivChanged() void dBgraph::mousePressEvent(QMouseEvent *event) { - if (event->button() == Qt::RightButton) { + if(event->button() == Qt::RightButton) { Q_EMIT resetZoom(); #ifdef __ANDROID__ - } else if (event->type() == QEvent::MouseButtonDblClick) { + } else if(event->type() == QEvent::MouseButtonDblClick) { zoomer->popZoom(); Q_EMIT zoomOut(); #endif } } -void dBgraph::onResetZoom() -{ - zoomer->resetZoom(); -} +void dBgraph::onResetZoom() { zoomer->resetZoom(); } #ifdef __ANDROID__ -void dBgraph::onZoomOut() -{ - zoomer->popZoom(); -} +void dBgraph::onZoomOut() { zoomer->popZoom(); } #endif void dBgraph::showEvent(QShowEvent *event) @@ -793,7 +741,6 @@ void dBgraph::showEvent(QShowEvent *event) sw->repaint(); } -void dBgraph::setPlotBarEnabled(bool enabled) -{ - d_plotBarEnabled = enabled; -} +void dBgraph::setPlotBarEnabled(bool enabled) { d_plotBarEnabled = enabled; } + +#include "moc_dbgraph.cpp" diff --git a/gui/src/dropdown_switch_list.cpp b/gui/src/dropdown_switch_list.cpp index 72c6706733..43accbadb0 100644 --- a/gui/src/dropdown_switch_list.cpp +++ b/gui/src/dropdown_switch_list.cpp @@ -19,14 +19,15 @@ */ #include "dropdown_switch_list.h" + #include "checkbox_delegate.h" +#include +#include #include -#include #include +#include #include -#include -#include using namespace scopy; @@ -36,18 +37,18 @@ using namespace scopy; * QCheckBox widgets on its right side. As opposed to a QCombobox the * items of this widget cannot be selected. */ -DropdownSwitchList::DropdownSwitchList(int switchColCount, QWidget *parent): - QComboBox(parent), - m_title("Title"), - m_rows(0), - m_columns(1 + switchColCount), - m_model(NULL), - m_treeView(NULL), - m_popVisible(false), - m_mouseInside(false), - m_mousePressed(false) -{ - if (m_columns < 2) +DropdownSwitchList::DropdownSwitchList(int switchColCount, QWidget *parent) + : QComboBox(parent) + , m_title("Title") + , m_rows(0) + , m_columns(1 + switchColCount) + , m_model(NULL) + , m_treeView(NULL) + , m_popVisible(false) + , m_mouseInside(false) + , m_mousePressed(false) +{ + if(m_columns < 2) m_columns = 2; // Title of the dropdown @@ -58,8 +59,7 @@ DropdownSwitchList::DropdownSwitchList(int switchColCount, QWidget *parent): this->setTitle(m_title); // Force combobox to point to no item - connect(this, SIGNAL(currentIndexChanged(int)), - SLOT(resetIndex(int))); + connect(this, SIGNAL(currentIndexChanged(int)), SLOT(resetIndex(int))); // Data m_model = new QStandardItemModel(0, m_columns, this); @@ -71,13 +71,13 @@ DropdownSwitchList::DropdownSwitchList(int switchColCount, QWidget *parent): this->setView(m_treeView); // Column titles - for (int col = 0; col < m_columns; col++) + for(int col = 0; col < m_columns; col++) m_colTitles.push_back(QString("Title %1").arg(col)); m_model->setHorizontalHeaderLabels(m_colTitles); // Use checkboxes instead of the default editor (spinbuttons) CheckboxDelegate *delegate = new CheckboxDelegate(m_treeView); - for (int col = 1; col < m_columns; col++) + for(int col = 1; col < m_columns; col++) m_treeView->setItemDelegateForColumn(col, delegate); // View size and alignment settings @@ -91,12 +91,9 @@ DropdownSwitchList::DropdownSwitchList(int switchColCount, QWidget *parent): m_treeView->header()->setDefaultAlignment(Qt::AlignCenter); } -QString DropdownSwitchList::title() const -{ - return m_title; -} +QString DropdownSwitchList::title() const { return m_title; } -void DropdownSwitchList::setTitle(const QString& title) +void DropdownSwitchList::setTitle(const QString &title) { m_title = title; lineEdit()->setPlaceholderText(title); @@ -104,33 +101,29 @@ void DropdownSwitchList::setTitle(const QString& title) QString DropdownSwitchList::columnTitle(int col) const { - if (col < m_columns) + if(col < m_columns) return m_colTitles[col]; else return ""; } -void DropdownSwitchList::setColumnTitle(int col, const QString& title) +void DropdownSwitchList::setColumnTitle(int col, const QString &title) { - if (col >= 0 && col < m_columns) { + if(col >= 0 && col < m_columns) { m_colTitles[col] = title; m_model->setHorizontalHeaderLabels(m_colTitles); } } -int DropdownSwitchList::switchColumnCount() const -{ - return m_columns - 1; -} +int DropdownSwitchList::switchColumnCount() const { return m_columns - 1; } -void DropdownSwitchList::addDropdownElement(const QIcon& icon, - const QString& name) +void DropdownSwitchList::addDropdownElement(const QIcon &icon, const QString &name) { QStandardItem *item = new QStandardItem(icon, name); m_model->setItem(m_rows, 0, item); item->setFlags(item->flags() & ~Qt::ItemIsEditable); item->setFlags(item->flags() & ~Qt::ItemIsSelectable); - for (int col = 1; col < m_columns; col++) { + for(int col = 1; col < m_columns; col++) { QModelIndex index = m_model->index(m_rows, col, QModelIndex()); m_model->setData(index, QVariant(1)); QStandardItem *item = m_model->item(m_rows, col); @@ -142,8 +135,7 @@ void DropdownSwitchList::addDropdownElement(const QIcon& icon, m_rows++; } -void DropdownSwitchList::addDropdownElement(const QIcon& icon, - const QString& name, const QVariant& user_data) +void DropdownSwitchList::addDropdownElement(const QIcon &icon, const QString &name, const QVariant &user_data) { addDropdownElement(icon, name); QModelIndex index = m_model->index(m_rows - 1, 0, QModelIndex()); @@ -170,20 +162,20 @@ void DropdownSwitchList::hidePopup() void DropdownSwitchList::mousePressEvent(QMouseEvent *event) { - if (m_mouseInside) { + if(m_mouseInside) { m_mousePressed = true; } } void DropdownSwitchList::mouseReleaseEvent(QMouseEvent *event) { - if (!rect().contains(event->localPos().toPoint())) { + if(!rect().contains(event->localPos().toPoint())) { return; } - if (m_mousePressed) { + if(m_mousePressed) { m_mousePressed = false; - if (m_popVisible) { + if(m_popVisible) { hidePopup(); } else { showPopup(); @@ -191,17 +183,10 @@ void DropdownSwitchList::mouseReleaseEvent(QMouseEvent *event) } } -void DropdownSwitchList::enterEvent(QEvent *event) -{ - m_mouseInside = true; -} +void DropdownSwitchList::enterEvent(QEvent *event) { m_mouseInside = true; } -void DropdownSwitchList::leaveEvent(QEvent *event) -{ - m_mouseInside = false; -} +void DropdownSwitchList::leaveEvent(QEvent *event) { m_mouseInside = false; } -void DropdownSwitchList::resetIndex(int) -{ - setCurrentIndex(-1); -} +void DropdownSwitchList::resetIndex(int) { setCurrentIndex(-1); } + +#include "moc_dropdown_switch_list.cpp" diff --git a/gui/src/dynamicWidget.cpp b/gui/src/dynamicWidget.cpp index 2a6feb510f..13a08bbc69 100644 --- a/gui/src/dynamicWidget.cpp +++ b/gui/src/dynamicWidget.cpp @@ -24,19 +24,17 @@ #include #include -void scopy::setDynamicProperty(QWidget *widget, - const char *property, bool set) +void scopy::setDynamicProperty(QWidget *widget, const char *property, bool set) { widget->setProperty(property, QVariant(set)); widget->style()->unpolish(widget); widget->style()->polish(widget); } -bool scopy::getDynamicProperty(QWidget *widget, - const char *property) +bool scopy::getDynamicProperty(QWidget *widget, const char *property) { QVariant val = widget->property(property); - if (val.canConvert()) { + if(val.canConvert()) { return val.toBool(); } return false; diff --git a/gui/src/extendingplotzoomer.cpp b/gui/src/extendingplotzoomer.cpp index f6b615443a..5c04af2f72 100644 --- a/gui/src/extendingplotzoomer.cpp +++ b/gui/src/extendingplotzoomer.cpp @@ -18,18 +18,19 @@ * along with this program. If not, see . */ #include "extendingplotzoomer.h" + #include "oscilloscope_plot.hpp" + #include using namespace scopy; - -ExtendingPlotZoomer::ExtendingPlotZoomer(QwtAxisId xAxis, QwtAxisId yAxis,QWidget *parent, bool doReplot): - LimitedPlotZoomer(xAxis, yAxis,parent, doReplot), - widthPass(false), - heightPass(false), - extendWidth(false), - extendHeight(false) +ExtendingPlotZoomer::ExtendingPlotZoomer(QwtAxisId xAxis, QwtAxisId yAxis, QWidget *parent, bool doReplot) + : LimitedPlotZoomer(xAxis, yAxis, parent, doReplot) + , widthPass(false) + , heightPass(false) + , extendWidth(false) + , extendHeight(false) { extendMarkers.push_back(new QwtPlotShapeItem()); extendMarkers.push_back(new QwtPlotShapeItem()); @@ -40,12 +41,12 @@ ExtendingPlotZoomer::ExtendingPlotZoomer(QwtAxisId xAxis, QwtAxisId yAxis,QWidge cornerMarkers.push_back(new QwtPlotShapeItem()); } -ExtendingPlotZoomer::ExtendingPlotZoomer(QWidget *parent, bool doReplot): - LimitedPlotZoomer(parent, doReplot), - widthPass(false), - heightPass(false), - extendWidth(false), - extendHeight(false) +ExtendingPlotZoomer::ExtendingPlotZoomer(QWidget *parent, bool doReplot) + : LimitedPlotZoomer(parent, doReplot) + , widthPass(false) + , heightPass(false) + , extendWidth(false) + , extendHeight(false) { extendMarkers.push_back(new QwtPlotShapeItem()); extendMarkers.push_back(new QwtPlotShapeItem()); @@ -58,11 +59,11 @@ ExtendingPlotZoomer::ExtendingPlotZoomer(QWidget *parent, bool doReplot): ExtendingPlotZoomer::~ExtendingPlotZoomer() { - for (auto it = extendMarkers.begin(); it != extendMarkers.end(); ++it) { + for(auto it = extendMarkers.begin(); it != extendMarkers.end(); ++it) { delete *it; } - for (auto it = cornerMarkers.begin(); it != cornerMarkers.end(); ++it) { + for(auto it = cornerMarkers.begin(); it != cornerMarkers.end(); ++it) { delete *it; } } @@ -86,10 +87,10 @@ void ExtendingPlotZoomer::zoom(const QRectF &rect) QPolygon ExtendingPlotZoomer::adjustedPoints(const QPolygon &points) const { QPolygon adjusted; - if (points.size() < 2) + if(points.size() < 2) return points; - if (points[0] == points[1]) { + if(points[0] == points[1]) { cornerMarkers[0]->detach(); cornerMarkers[1]->detach(); cornerMarkers[2]->detach(); @@ -100,37 +101,37 @@ QPolygon ExtendingPlotZoomer::adjustedPoints(const QPolygon &points) const const int width = qAbs(points[1].x() - points[0].x()); const int height = qAbs(points[1].y() - points[0].y()); - if ((width > 50) && !widthPass) { + if((width > 50) && !widthPass) { widthPass = true; } - if ((height > 50) && !heightPass) { + if((height > 50) && !heightPass) { heightPass = true; } - //Handle width extension - if (width < 40 && widthPass && !extendWidth && !extendHeight) { + // Handle width extension + if(width < 40 && widthPass && !extendWidth && !extendHeight) { extendWidth = true; } - if (width > 40 && widthPass && extendWidth && !extendHeight) { + if(width > 40 && widthPass && extendWidth && !extendHeight) { extendWidth = false; } - //Handle height extension - if (height < 40 && heightPass && !extendHeight && !extendWidth) { + // Handle height extension + if(height < 40 && heightPass && !extendHeight && !extendWidth) { extendHeight = true; } - if (height > 40 && heightPass && extendHeight && !extendWidth) { + if(height > 40 && heightPass && extendHeight && !extendWidth) { extendHeight = false; } - if (extendWidth && !extendHeight) { + if(extendWidth && !extendHeight) { QPoint topLeft(0, points[0].y()); QPoint bottomRight(canvas()->width() - 1, points[1].y()); adjusted += topLeft; adjusted += bottomRight; - if (yAxis() == QwtAxisId(QwtAxis::YLeft, 0)) { + if(yAxis() == QwtAxisId(QwtAxis::YLeft, 0)) { cornerMarkers[0]->detach(); cornerMarkers[1]->detach(); cornerMarkers[2]->detach(); @@ -146,8 +147,7 @@ QPolygon ExtendingPlotZoomer::adjustedPoints(const QPolygon &points) const extendMarkers[0]->setShape(path1); extendMarkers[0]->setPen(Qt::white, 3, Qt::SolidLine); extendMarkers[0]->setZ(1000); - extendMarkers[0]->attach((QwtPlot*)plot()); - + extendMarkers[0]->attach((QwtPlot *)plot()); QPointF x12 = invTransform(QPoint(points[0].x() - 40, points[0].y())); QPointF x22 = invTransform(QPoint(points[0].x() + 40, points[0].y())); @@ -159,22 +159,21 @@ QPolygon ExtendingPlotZoomer::adjustedPoints(const QPolygon &points) const extendMarkers[1]->setShape(path2); extendMarkers[1]->setPen(Qt::white, 3, Qt::SolidLine); extendMarkers[1]->setZ(1000); - extendMarkers[1]->attach((QwtPlot*)plot()); + extendMarkers[1]->attach((QwtPlot *)plot()); - - static_cast((QwtPlot*)plot())->replot(); + static_cast((QwtPlot *)plot())->replot(); } return adjusted; } - if (extendHeight && !extendWidth) { + if(extendHeight && !extendWidth) { QPoint topLeft(points[0].x(), 0); QPoint bottomRight(points[1].x(), canvas()->height() - 1); adjusted += topLeft; adjusted += bottomRight; - if (yAxis() == QwtAxisId(QwtAxis::YLeft, 0)) { + if(yAxis() == QwtAxisId(QwtAxis::YLeft, 0)) { cornerMarkers[0]->detach(); cornerMarkers[1]->detach(); cornerMarkers[2]->detach(); @@ -190,8 +189,7 @@ QPolygon ExtendingPlotZoomer::adjustedPoints(const QPolygon &points) const extendMarkers[0]->setShape(path1); extendMarkers[0]->setPen(Qt::white, 3, Qt::SolidLine); extendMarkers[0]->setZ(1000); - extendMarkers[0]->attach((QwtPlot*)plot()); - + extendMarkers[0]->attach((QwtPlot *)plot()); QPointF x12 = invTransform(QPoint(points[1].x(), points[0].y() - 40)); QPointF x22 = invTransform(QPoint(points[1].x(), points[0].y() + 40)); @@ -203,28 +201,26 @@ QPolygon ExtendingPlotZoomer::adjustedPoints(const QPolygon &points) const extendMarkers[1]->setShape(path2); extendMarkers[1]->setPen(Qt::white, 3, Qt::SolidLine); extendMarkers[1]->setZ(1000); - extendMarkers[1]->attach((QwtPlot*)plot()); + extendMarkers[1]->attach((QwtPlot *)plot()); - - static_cast((QwtPlot*)plot())->replot(); + static_cast((QwtPlot *)plot())->replot(); } return adjusted; } - - if (yAxis() == QwtAxisId(QwtAxis::YLeft, 0)) { + if(yAxis() == QwtAxisId(QwtAxis::YLeft, 0)) { extendMarkers[0]->detach(); extendMarkers[1]->detach(); QPainterPath path1, path2, path3, path4; - if (points[0].x() < points[1].x()) { + if(points[0].x() < points[1].x()) { QPointF origin1 = invTransform(points[0]); QPointF bottom1; - if (points[0].y() < points[1].y()) + if(points[0].y() < points[1].y()) bottom1 = invTransform(QPoint(points[0].x(), points[0].y() + 20)); else bottom1 = invTransform(QPoint(points[0].x(), points[0].y() - 20)); @@ -236,7 +232,7 @@ QPolygon ExtendingPlotZoomer::adjustedPoints(const QPolygon &points) const QPointF origin2 = invTransform(QPoint(points[1].x(), points[0].y())); QPointF bottom2; - if (points[0].y() < points[1].y()) + if(points[0].y() < points[1].y()) bottom2 = invTransform(QPoint(points[1].x(), points[0].y() + 20)); else bottom2 = invTransform(QPoint(points[1].x(), points[0].y() - 20)); @@ -248,7 +244,7 @@ QPolygon ExtendingPlotZoomer::adjustedPoints(const QPolygon &points) const QPointF origin3 = invTransform(QPoint(points[1].x(), points[1].y())); QPointF bottom3; - if (points[0].y() < points[1].y()) + if(points[0].y() < points[1].y()) bottom3 = invTransform(QPoint(points[1].x(), points[1].y() - 20)); else bottom3 = invTransform(QPoint(points[1].x(), points[1].y() + 20)); @@ -260,7 +256,7 @@ QPolygon ExtendingPlotZoomer::adjustedPoints(const QPolygon &points) const QPointF origin4 = invTransform(QPoint(points[0].x(), points[1].y())); QPointF bottom4; - if (points[0].y() < points[1].y()) + if(points[0].y() < points[1].y()) bottom4 = invTransform(QPoint(points[0].x(), points[1].y() - 20)); else bottom4 = invTransform(QPoint(points[0].x(), points[1].y() + 20)); @@ -274,7 +270,7 @@ QPolygon ExtendingPlotZoomer::adjustedPoints(const QPolygon &points) const QPointF origin1 = invTransform(points[0]); QPointF bottom1; - if (points[0].y() < points[1].y()) + if(points[0].y() < points[1].y()) bottom1 = invTransform(QPoint(points[0].x(), points[0].y() + 20)); else bottom1 = invTransform(QPoint(points[0].x(), points[0].y() - 20)); @@ -286,7 +282,7 @@ QPolygon ExtendingPlotZoomer::adjustedPoints(const QPolygon &points) const QPointF origin2 = invTransform(QPoint(points[1].x(), points[0].y())); QPointF bottom2; - if (points[0].y() < points[1].y()) + if(points[0].y() < points[1].y()) bottom2 = invTransform(QPoint(points[1].x(), points[0].y() + 20)); else bottom2 = invTransform(QPoint(points[1].x(), points[0].y() - 20)); @@ -298,7 +294,7 @@ QPolygon ExtendingPlotZoomer::adjustedPoints(const QPolygon &points) const QPointF origin3 = invTransform(QPoint(points[1].x(), points[1].y())); QPointF bottom3; - if (points[0].y() < points[1].y()) + if(points[0].y() < points[1].y()) bottom3 = invTransform(QPoint(points[1].x(), points[1].y() - 20)); else bottom3 = invTransform(QPoint(points[1].x(), points[1].y() + 20)); @@ -310,7 +306,7 @@ QPolygon ExtendingPlotZoomer::adjustedPoints(const QPolygon &points) const QPointF origin4 = invTransform(QPoint(points[0].x(), points[1].y())); QPointF bottom4; - if (points[0].y() < points[1].y()) + if(points[0].y() < points[1].y()) bottom4 = invTransform(QPoint(points[0].x(), points[1].y() - 20)); else bottom4 = invTransform(QPoint(points[0].x(), points[1].y() + 20)); @@ -324,24 +320,24 @@ QPolygon ExtendingPlotZoomer::adjustedPoints(const QPolygon &points) const cornerMarkers[0]->setShape(path1); cornerMarkers[0]->setPen(Qt::white, 3, Qt::SolidLine); cornerMarkers[0]->setZ(1000); - cornerMarkers[0]->attach((QwtPlot*)plot()); + cornerMarkers[0]->attach((QwtPlot *)plot()); cornerMarkers[1]->setShape(path2); cornerMarkers[1]->setPen(Qt::white, 3, Qt::SolidLine); cornerMarkers[1]->setZ(1000); - cornerMarkers[1]->attach((QwtPlot*)plot()); + cornerMarkers[1]->attach((QwtPlot *)plot()); cornerMarkers[2]->setShape(path3); cornerMarkers[2]->setPen(Qt::white, 3, Qt::SolidLine); cornerMarkers[2]->setZ(1000); - cornerMarkers[2]->attach((QwtPlot*)plot()); + cornerMarkers[2]->attach((QwtPlot *)plot()); cornerMarkers[3]->setShape(path4); cornerMarkers[3]->setPen(Qt::white, 3, Qt::SolidLine); cornerMarkers[3]->setZ(1000); - cornerMarkers[3]->attach((QwtPlot*)plot()); + cornerMarkers[3]->attach((QwtPlot *)plot()); - static_cast((QwtPlot*)plot())->replot(); + static_cast((QwtPlot *)plot())->replot(); } return points; } diff --git a/gui/src/filemanager.cpp b/gui/src/filemanager.cpp index 198d718fc6..48a305e3fd 100644 --- a/gui/src/filemanager.cpp +++ b/gui/src/filemanager.cpp @@ -20,33 +20,28 @@ #include "filemanager.h" +#include #include #include -#include + #include using namespace scopy; -FileManager::FileManager(QString toolName) : - hasHeader(false), - sampleRate(0), - nrOfSamples(0), - toolName(toolName) -{ - -} - -FileManager::~FileManager() -{ +FileManager::FileManager(QString toolName) + : hasHeader(false) + , sampleRate(0) + , nrOfSamples(0) + , toolName(toolName) +{} -} +FileManager::~FileManager() {} -void FileManager::open(QString fileName, - FileManager::FilePurpose filepurpose) +void FileManager::open(QString fileName, FileManager::FilePurpose filepurpose) { - //read the data from the file if filepurpose is Import - //throws exception if the file is corrupted, has a header but not the scopy one - //columns with different sizes etc.. + // read the data from the file if filepurpose is Import + // throws exception if the file is corrupted, has a header but not the scopy one + // columns with different sizes etc.. QVector> raw_data; bool srOk = true; @@ -54,90 +49,90 @@ void FileManager::open(QString fileName, openedFor = filepurpose; - if (fileName.endsWith(".csv")) { + if(fileName.endsWith(".csv")) { separator = ","; fileType = CSV; - } else if (fileName.endsWith(".txt")) { + } else if(fileName.endsWith(".txt")) { separator = "\t"; fileType = TXT; - //find sep to read txt files + // find sep to read txt files } - //clear previous data if the manager was used for other exports + // clear previous data if the manager was used for other exports data.clear(); decoder_data.clear(); columnNames.clear(); this->filename = fileName; - if (filepurpose == IMPORT) { + if(filepurpose == IMPORT) { - if (fileName.isEmpty()) { + if(fileName.isEmpty()) { throw FileManagerException("No file selected"); } QFile file(fileName); - if (!file.open(QIODevice::ReadOnly)) { + if(!file.open(QIODevice::ReadOnly)) { throw FileManagerException("Can't open selected file"); } QTextStream in(&file); - for (int i = 0; i < data.size(); ++i) + for(int i = 0; i < data.size(); ++i) data[i].clear(); - while (!in.atEnd()) { + while(!in.atEnd()) { QVector line_data; QString line = in.readLine(); QStringList list = line.split(separator, Qt::SkipEmptyParts); - for (const QString &list_item : qAsConst(list)) { + for(const QString &list_item : qAsConst(list)) { line_data.push_back(list_item); } - if (line_data.size() > 0) { + if(line_data.size() > 0) { raw_data.push_back(line_data); } } - //check if it has a header or not + // check if it has a header or not /* - * Header format - * - * ;Scopy version abcdefg - * ;Exported on Wed Apr 4 13:49:01 2018 - * ;Device M2K - * ;Nr of samples 1234 - * ;Sample rate 1234 or 0 if it does not have samp. rate - * ;Tool: Oscilloscope/ Spectrum ... - * ;Additional Information - */ + * Header format + * + * ;Scopy version abcdefg + * ;Exported on Wed Apr 4 13:49:01 2018 + * ;Device M2K + * ;Nr of samples 1234 + * ;Sample rate 1234 or 0 if it does not have samp. rate + * ;Tool: Oscilloscope/ Spectrum ... + * ;Additional Information + */ hasHeader = ScopyFileHeader::hasValidHeader(raw_data); - if (hasHeader) { + if(hasHeader) { format = SCOPY; - //first column in data is the time!!! when retrieving channel data start from data[1] - for (int i = 1; i < raw_data[6].size(); ++i) { + // first column in data is the time!!! when retrieving channel data start from data[1] + for(int i = 1; i < raw_data[6].size(); ++i) { additionalInformation.push_back(raw_data[6][i]); } sampleRate = raw_data[4][1].toDouble(&srOk); - if (!srOk) { + if(!srOk) { throw FileManagerException("File is corrupted!"); } - //should be 0 if read from network/spectrum analyzer exported file + // should be 0 if read from network/spectrum analyzer exported file - for (int j = 1; j < raw_data[7].size(); ++j) + for(int j = 1; j < raw_data[7].size(); ++j) columnNames.push_back(raw_data[7][j]); data.resize(raw_data.size() - 8); - for (int i = 0; i < data.size(); ++i) { + for(int i = 0; i < data.size(); ++i) { data[i].resize(raw_data[i + 8].size() - 1); } - for (int i = 8; i < raw_data.size(); ++i) { - for (int j = 1; j < raw_data[i].size(); ++j) { + for(int i = 8; i < raw_data.size(); ++i) { + for(int j = 1; j < raw_data[i].size(); ++j) { data[i - 8][j - 1] = raw_data[i][j].toDouble(&dataOk); - if (!dataOk) { + if(!dataOk) { throw FileManagerException("File is corrupted!"); } } @@ -147,14 +142,14 @@ void FileManager::open(QString fileName, format = RAW; data.resize(raw_data.size()); - for (int i = 0; i < data.size(); ++i) { + for(int i = 0; i < data.size(); ++i) { data[i].resize(raw_data[i].size()); } - for (int i = 0; i < raw_data.size(); ++i) { - for (int j = 0; j < raw_data[i].size(); ++j) { + for(int i = 0; i < raw_data.size(); ++i) { + for(int j = 0; j < raw_data[i].size(); ++j) { data[i][j] = raw_data[i][j].toDouble(&dataOk); - if (!dataOk) { + if(!dataOk) { throw FileManagerException("File is corrupted!"); } } @@ -169,68 +164,65 @@ void FileManager::save(QVector data, QString name) { this->columnNames.push_back(name); - if (this->data.size() == 0) { + if(this->data.size() == 0) { this->data.resize(data.size()); } - for (int i = 0; i < data.size(); ++i) { + for(int i = 0; i < data.size(); ++i) { this->data[i].push_back(data[i]); } } void FileManager::save(QVector> data, QVector> decoder_data, QStringList columnNames) { - for (auto &column : data) { + for(auto &column : data) { this->data.push_back(column); } this->decoder_data.clear(); - for (auto &column : decoder_data) { + for(auto &column : decoder_data) { this->decoder_data.push_back(column); } - for (auto &column_name : columnNames) { + for(auto &column_name : columnNames) { this->columnNames.push_back(column_name); } } -void FileManager::save(QVector > data, QStringList columnNames) +void FileManager::save(QVector> data, QStringList columnNames) { - for (auto &column : data) { + for(auto &column : data) { this->data.push_back(column); } - for (auto &column_name : columnNames) { + for(auto &column_name : columnNames) { this->columnNames.push_back(column_name); } } QVector FileManager::read(int index) { - if (index < 0 || index + 1 >= data.size()) { + if(index < 0 || index + 1 >= data.size()) { return QVector(); } - if (hasHeader) { + if(hasHeader) { index++; } QVector channel_data; - for (int i = 0; i < nrOfSamples; ++i) { + for(int i = 0; i < nrOfSamples; ++i) { channel_data.push_back(data[i][index]); } return channel_data; } -QVector> FileManager::read() -{ - return data; -} +QVector> FileManager::read() { return data; } void FileManager::setColumnName(int index, QString name) { - if (index < 0 || index >= data.size()) { + if(index < 0 || index >= data.size()) { return; } @@ -239,39 +231,30 @@ void FileManager::setColumnName(int index, QString name) QString FileManager::getColumnName(int index) { - if (index < 0 || index >= columnNames.size()) { + if(index < 0 || index >= columnNames.size()) { return ""; } - if (hasHeader) { + if(hasHeader) { index++; } return columnNames[index]; } -double FileManager::getSampleRate() const -{ - return sampleRate; -} +double FileManager::getSampleRate() const { return sampleRate; } -void FileManager::setSampleRate(double sampleRate) -{ - this->sampleRate = sampleRate; -} +void FileManager::setSampleRate(double sampleRate) { this->sampleRate = sampleRate; } -double FileManager::getNrOfSamples() const -{ - return nrOfSamples; -} +double FileManager::getNrOfSamples() const { return nrOfSamples; } int FileManager::getNrOfChannels() const { - if (data.size() == 0) { + if(data.size() == 0) { return 0; } - if (hasHeader) { + if(hasHeader) { return data[0].size() - 1; } else { return data[0].size(); @@ -281,7 +264,7 @@ int FileManager::getNrOfChannels() const void FileManager::performWrite(bool withScopyHeader) { QString additionalInfo = ""; - if (openedFor == IMPORT) { + if(openedFor == IMPORT) { qDebug() << "Can't write when opened for import!"; return; } @@ -292,23 +275,24 @@ void FileManager::performWrite(bool withScopyHeader) additionalInfo = (additionalInformation.size() != 0) ? additionalInformation[0] : ""; - if (withScopyHeader) { + if(withScopyHeader) { QStringList header = ScopyFileHeader::getHeader(); - //prepare header - //exportStream << header[0] << separator << QString(SCOPY_VERSION_GIT) << "\n"; + // prepare header + // exportStream << header[0] << separator << QString(SCOPY_VERSION_GIT) << "\n"; exportStream << header[1] << separator << QDate::currentDate().toString("dddd MMMM dd/MM/yyyy") << "\n"; - exportStream << header[2] << separator << "M2K" << "\n"; + exportStream << header[2] << separator << "M2K" + << "\n"; exportStream << header[3] << separator << data.size() << "\n"; exportStream << header[4] << separator << sampleRate << "\n"; exportStream << header[5] << separator << toolName << "\n"; exportStream << header[6] << separator << additionalInfo << "\n"; } - //column names row + // column names row exportStream << "Sample" << separator; - bool skipFirstSeparator=true; - for (const QString &columnName : qAsConst(columnNames)) { + bool skipFirstSeparator = true; + for(const QString &columnName : qAsConst(columnNames)) { if(!skipFirstSeparator) exportStream << separator; exportStream << columnName; @@ -316,25 +300,26 @@ void FileManager::performWrite(bool withScopyHeader) } exportStream << "\n"; - for (int i = 0; i < data.size(); ++i) { + for(int i = 0; i < data.size(); ++i) { skipFirstSeparator = true; exportStream << QString::number(i) << separator; - for (int j = 0; j < data[i].size(); ++j) { + for(int j = 0; j < data[i].size(); ++j) { if(!skipFirstSeparator) exportStream << separator; exportStream << data[i][j]; skipFirstSeparator = false; } - if (!decoder_data.isEmpty()) { - for (int j = 0; j < decoder_data[i].size(); ++j) { + if(!decoder_data.isEmpty()) { + for(int j = 0; j < decoder_data[i].size(); ++j) { if(!skipFirstSeparator) exportStream << separator; - if (!decoder_data[i][j].isEmpty()) { + if(!decoder_data[i][j].isEmpty()) { exportStream << "\"" << decoder_data[i][j] << "\""; } skipFirstSeparator = false; - }} + } + } exportStream << "\n"; } @@ -344,7 +329,7 @@ void FileManager::performWrite(bool withScopyHeader) void FileManager::performDecoderWrite(bool skip_empty_lines) { // write decoder data - if (openedFor == IMPORT) { + if(openedFor == IMPORT) { qDebug() << "Can't write when opened for import!"; return; } @@ -353,45 +338,45 @@ void FileManager::performDecoderWrite(bool skip_empty_lines) exportFile.open(QIODevice::WriteOnly); QTextStream exportStream(&exportFile); - //column names row - bool skipFirstSeparator=true; + // column names row + bool skipFirstSeparator = true; - for (const auto &column : qAsConst(columnNames)) { - if (!skipFirstSeparator) { + for(const auto &column : qAsConst(columnNames)) { + if(!skipFirstSeparator) { exportStream << separator; } skipFirstSeparator = false; exportStream << column; } - if (!columnNames.empty()) { + if(!columnNames.empty()) { exportStream << "\n"; } QString line; bool empty_line; - if (!decoder_data.isEmpty()) { - for (int i = 0; i < decoder_data.size(); ++i) { + if(!decoder_data.isEmpty()) { + for(int i = 0; i < decoder_data.size(); ++i) { skipFirstSeparator = true; line = QString(); empty_line = true; - for (int j = 0; j < decoder_data[i].size(); ++j) { - if (!skipFirstSeparator) + for(int j = 0; j < decoder_data[i].size(); ++j) { + if(!skipFirstSeparator) line += separator; - if (!decoder_data[i][j].isEmpty()) { + if(!decoder_data[i][j].isEmpty()) { line += decoder_data[i][j].replace(separator, " "); } skipFirstSeparator = false; - - if (j != 0 && decoder_data[i][j] != "") { + if(j != 0 && decoder_data[i][j] != "") { empty_line = false; } } line += '\n'; - if (skip_empty_lines && empty_line) continue; + if(skip_empty_lines && empty_line) + continue; exportStream << line; } } @@ -399,46 +384,35 @@ void FileManager::performDecoderWrite(bool skip_empty_lines) exportFile.close(); } -QStringList FileManager::getAdditionalInformation() const -{ - return additionalInformation; -} +QStringList FileManager::getAdditionalInformation() const { return additionalInformation; } -void FileManager::setAdditionalInformation(const QString &value) -{ +void FileManager::setAdditionalInformation(const QString &value) { additionalInformation.push_back(value); } - additionalInformation.push_back(value); -} +FileManager::FileFormat FileManager::getFormat() const { return format; } -FileManager::FileFormat FileManager::getFormat() const -{ - return format; -} +void FileManager::setFormat(const FileManager::FileFormat &value) { format = value; } -void FileManager::setFormat(const FileManager::FileFormat &value) -{ - format = value; -} - -void FileManager::writeToFile(bool overwrite,QMap> data) +void FileManager::writeToFile(bool overwrite, QMap> data) { QFile file(filename); QTextStream exportStream(&file); - if (!file.isOpen()) { - if (overwrite) { + if(!file.isOpen()) { + if(overwrite) { file.open(QIODevice::WriteOnly); QStringList header = ScopyFileHeader::getHeader(); - //prepare header - exportStream << header[0] << separator << "git"/*QString(SCOPY_VERSION_GIT)*/ << "\n"; - exportStream << header[1] << separator << QDate::currentDate().toString("dddd MMMM dd/MM/yyyy") << "\n"; - exportStream << header[2] << separator << "M2K" << "\n"; + // prepare header + exportStream << header[0] << separator << "git" /*QString(SCOPY_VERSION_GIT)*/ << "\n"; + exportStream << header[1] << separator << QDate::currentDate().toString("dddd MMMM dd/MM/yyyy") + << "\n"; + exportStream << header[2] << separator << "M2K" + << "\n"; exportStream << header[5] << separator << toolName << "\n"; - //add columns + // add columns QString columns = ""; - for (const auto &ch : data.keys()) { - columns+= ch + separator; + for(const auto &ch : data.keys()) { + columns += ch + separator; } exportStream << columns << "\n"; @@ -446,9 +420,9 @@ void FileManager::writeToFile(bool overwrite,QMap> data file.open(QIODevice::Append); QString dataToWrite = ""; - for (const auto &ch : data.keys()) { - if (!data[ch].empty()) { - for (const auto &d : data[ch]) { + for(const auto &ch : data.keys()) { + if(!data[ch].empty()) { + for(const auto &d : data[ch]) { dataToWrite += d + " "; } dataToWrite += separator; @@ -456,15 +430,15 @@ void FileManager::writeToFile(bool overwrite,QMap> data dataToWrite += ","; } } - exportStream << dataToWrite << "" << "\n"; - + exportStream << dataToWrite << "" + << "\n"; } } else { qDebug() << "File already opened!"; return; } - if (file.isOpen()) { + if(file.isOpen()) { file.close(); } } @@ -474,12 +448,12 @@ bool ScopyFileHeader::hasValidHeader(QVector> data) QStringList header_elements = getHeader(); - if (data.size() < header_elements.size()) { + if(data.size() < header_elements.size()) { return false; } - for (int i = 0; i < header_elements.size(); ++i) { - if (data[i][0] != header_elements[i]) { + for(int i = 0; i < header_elements.size(); ++i) { + if(data[i][0] != header_elements[i]) { return false; } } diff --git a/gui/src/flexgridlayout.cpp b/gui/src/flexgridlayout.cpp index 4d2e6a3346..a381fd6744 100644 --- a/gui/src/flexgridlayout.cpp +++ b/gui/src/flexgridlayout.cpp @@ -1,17 +1,19 @@ #include "flexgridlayout.hpp" + #include "QScrollArea" -#include + #include +#include using namespace scopy; -FlexGridLayout::FlexGridLayout(int maxCols, QWidget *parent) : - QWidget(parent), - m_maxCols(maxCols-1), - currentNumberOfCols(m_maxCols), - col(0), - row(0), - updatePending(false) +FlexGridLayout::FlexGridLayout(int maxCols, QWidget *parent) + : QWidget(parent) + , m_maxCols(maxCols - 1) + , currentNumberOfCols(m_maxCols) + , col(0) + , row(0) + , updatePending(false) { m_gridLayout = new QGridLayout(this); m_gridLayout->setHorizontalSpacing(0); @@ -21,73 +23,74 @@ FlexGridLayout::FlexGridLayout(int maxCols, QWidget *parent) : m_gridLayout->setMargin(0); setLayout(m_gridLayout); - m_hspacer = new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Fixed); - m_vspacer = new QSpacerItem(1,1, QSizePolicy::Fixed, QSizePolicy::Expanding); + m_hspacer = new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Fixed); + m_vspacer = new QSpacerItem(1, 1, QSizePolicy::Fixed, QSizePolicy::Expanding); - m_gridLayout->addItem(m_hspacer,0, m_maxCols + 1); - m_gridLayout->addItem(m_vspacer,10, 0); + m_gridLayout->addItem(m_hspacer, 0, m_maxCols + 1); + m_gridLayout->addItem(m_vspacer, 10, 0); - QObject::connect(this, &FlexGridLayout::reqestLayoutUpdate, this, &FlexGridLayout::updateLayout, Qt::DirectConnection); + QObject::connect(this, &FlexGridLayout::reqestLayoutUpdate, this, &FlexGridLayout::updateLayout, + Qt::DirectConnection); } // adds widget to internal widget list and return the index of the added widget int FlexGridLayout::addQWidgetToList(QWidget *widget) { m_widgetList.push_back(widget); - return m_widgetList.size() -1; + return m_widgetList.size() - 1; } // adds a widget at index to the layout and it's index to the active widget list void FlexGridLayout::addWidget(int index) { - m_gridLayout->addWidget(m_widgetList.at(index),row,col); + m_gridLayout->addWidget(m_widgetList.at(index), row, col); m_widgetList.at(index)->show(); m_activeWidgetList.push_back(index); - //logic for resizable n columns grid layout - if (col == currentNumberOfCols) { + // logic for resizable n columns grid layout + if(col == currentNumberOfCols) { col = 0; row++; } else { - col ++; + col++; } } // remove widget at index from layout void FlexGridLayout::removeWidget(int index) { - //get index, row and column of item that will be removed + // get index, row and column of item that will be removed int indexOfGrid = m_gridLayout->indexOf(m_widgetList.at(index)); - int r = 0, c=0, rs = 0, cs =0; - m_gridLayout->getItemPosition(indexOfGrid,&r,&c,&rs,&cs); + int r = 0, c = 0, rs = 0, cs = 0; + m_gridLayout->getItemPosition(indexOfGrid, &r, &c, &rs, &cs); - //remove the widget from the layout and hide it (use hide instead of delete since widget can be added again) + // remove the widget from the layout and hide it (use hide instead of delete since widget can be added again) m_gridLayout->removeWidget(m_widgetList.at(index)); m_widgetList.at(index)->hide(); int i = 0; - for (int idx = 0; idx < m_activeWidgetList.size(); idx++) { - if (m_activeWidgetList.at(idx) == index) { + for(int idx = 0; idx < m_activeWidgetList.size(); idx++) { + if(m_activeWidgetList.at(idx) == index) { i = idx; m_activeWidgetList.remove(idx); break; } } - //shift all remaing active widgets to fill the empty space - while (i < m_activeWidgetList.size()) { - repositionWidgets(m_activeWidgetList.at(i),r,c); + // shift all remaing active widgets to fill the empty space + while(i < m_activeWidgetList.size()) { + repositionWidgets(m_activeWidgetList.at(i), r, c); i++; - if (c == currentNumberOfCols) { + if(c == currentNumberOfCols) { c = 0; r++; } else { - c ++; + c++; } } - //logic for n columns grid layout - if (col != 0) { + // logic for n columns grid layout + if(col != 0) { col--; } else { row--; @@ -99,31 +102,28 @@ void FlexGridLayout::removeWidget(int index) // moving the widget will replace the current widget at that position void FlexGridLayout::repositionWidgets(int index, int row, int col) { - m_gridLayout->addWidget(m_widgetList.at(index),row,col); + m_gridLayout->addWidget(m_widgetList.at(index), row, col); } // returns widget at index -QWidget* FlexGridLayout::getWidget(int index) -{ - return m_widgetList.at(index); -} +QWidget *FlexGridLayout::getWidget(int index) { return m_widgetList.at(index); } // check if widget is active on layout bool FlexGridLayout::isWidgetActive(int index) { - for (int i = 0 ; i < m_activeWidgetList.size(); i++) { - if (m_activeWidgetList.at(i) == index) { + for(int i = 0; i < m_activeWidgetList.size(); i++) { + if(m_activeWidgetList.at(i) == index) { return true; } } return false; } -//toggle all widgets +// toggle all widgets void FlexGridLayout::toggleAll(bool toggled) { - for (int i=0; i< m_widgetList.size(); i++) { - if (toggled) { + for(int i = 0; i < m_widgetList.size(); i++) { + if(toggled) { addWidget(i); } else { removeWidget(i); @@ -131,52 +131,35 @@ void FlexGridLayout::toggleAll(bool toggled) } } -//set the maximum number of columns -void FlexGridLayout::setMaxColumnNumber(int maxColumns) -{ - m_maxCols = maxColumns - 1; -} +// set the maximum number of columns +void FlexGridLayout::setMaxColumnNumber(int maxColumns) { m_maxCols = maxColumns - 1; } -//returns the maximum number of columns -int FlexGridLayout::getMaxColumnNumber() -{ - return m_maxCols; -} +// returns the maximum number of columns +int FlexGridLayout::getMaxColumnNumber() { return m_maxCols; } -//returns the number of rows that contain the maximum number of cols/elements that could fit on a row -int FlexGridLayout::fullRows() const -{ - return row; -} +// returns the number of rows that contain the maximum number of cols/elements that could fit on a row +int FlexGridLayout::fullRows() const { return row; } -//returns the number of rows, including the last row that might not be full -int FlexGridLayout::rows() const -{ - return row + (col != 0); -} +// returns the number of rows, including the last row that might not be full +int FlexGridLayout::rows() const { return row + (col != 0); } -//returns the maximum number of cols/elements that are currently on a row +// returns the maximum number of cols/elements that are currently on a row int FlexGridLayout::columns() const { - if (row == 0) return 0; - return ((int) (m_widgetList.size() - col)) / row; + if(row == 0) + return 0; + return ((int)(m_widgetList.size() - col)) / row; } -//returns the number of cols/elements that are on the last row -int FlexGridLayout::columnsOnLastRow() const -{ - return col; -} +// returns the number of cols/elements that are on the last row +int FlexGridLayout::columnsOnLastRow() const { return col; } // returns the number of widgets in the grid -int FlexGridLayout::count() const -{ - return this->m_widgetList.size(); -} +int FlexGridLayout::count() const { return this->m_widgetList.size(); } void FlexGridLayout::resizeEvent(QResizeEvent *event) { - if (!updatePending) { + if(!updatePending) { updatePending = true; Q_EMIT reqestLayoutUpdate(); } @@ -184,7 +167,7 @@ void FlexGridLayout::resizeEvent(QResizeEvent *event) void FlexGridLayout::itemSizeChanged() { - if (!updatePending) { + if(!updatePending) { updatePending = true; Q_EMIT reqestLayoutUpdate(); } @@ -192,8 +175,8 @@ void FlexGridLayout::itemSizeChanged() void FlexGridLayout::updateLayout() { - if (availableWidth != this->width()) { - if (m_activeWidgetList.size() > 0) { + if(availableWidth != this->width()) { + if(m_activeWidgetList.size() > 0) { computeCols(m_widgetList.at(m_activeWidgetList.at(0))->minimumSizeHint().width()); } } else { @@ -204,14 +187,14 @@ void FlexGridLayout::updateLayout() void FlexGridLayout::recomputeColCount() { - if (m_activeWidgetList.size() > 0) { + if(m_activeWidgetList.size() > 0) { auto maxWidth = m_widgetList.at(m_activeWidgetList.at(0))->minimumSizeHint().width(); - for (int i = 1; i < m_activeWidgetList.size(); i++ ) { - if (m_widgetList.at(m_activeWidgetList.at(i))->minimumSizeHint().width()> maxWidth){ + for(int i = 1; i < m_activeWidgetList.size(); i++) { + if(m_widgetList.at(m_activeWidgetList.at(i))->minimumSizeHint().width() > maxWidth) { maxWidth = m_widgetList.at(m_activeWidgetList.at(i))->minimumSizeHint().width(); } } - if (colWidth != maxWidth) { + if(colWidth != maxWidth) { computeCols(maxWidth); } } else { @@ -224,24 +207,24 @@ void FlexGridLayout::computeCols(double width) // width of the first active widg int colCount = currentNumberOfCols; availableWidth = this->width(); - if (width != 0) { - colCount = (availableWidth / width) - 1; //index starts at 0 - int width_extra = availableWidth - (colCount+1) * width; - colWidth = width + (width_extra/(colCount+1)); + if(width != 0) { + colCount = (availableWidth / width) - 1; // index starts at 0 + int width_extra = availableWidth - (colCount + 1) * width; + colWidth = width + (width_extra / (colCount + 1)); } else { - if (m_widgetList.size() > 0) { - if (m_widgetList.at(0)->width() > 0) { + if(m_widgetList.size() > 0) { + if(m_widgetList.at(0)->width() > 0) { colCount = (availableWidth / m_widgetList.at(0)->width()) - 1; colWidth = m_widgetList.at(0)->width(); } } } - if (colCount != currentNumberOfCols) { + if(colCount != currentNumberOfCols) { currentNumberOfCols = colCount; - if (m_activeWidgetList.size() > 1) { + if(m_activeWidgetList.size() > 1) { redrawWidgets(); } } @@ -252,17 +235,17 @@ void FlexGridLayout::redrawWidgets() { row = 0; col = 0; - if (!m_activeWidgetList.empty()) { - for (int i = 0; i < m_activeWidgetList.size(); i++) { + if(!m_activeWidgetList.empty()) { + for(int i = 0; i < m_activeWidgetList.size(); i++) { m_gridLayout->removeWidget(m_widgetList.at(m_activeWidgetList.at(i))); m_widgetList.at(m_activeWidgetList.at(i))->hide(); - m_gridLayout->addWidget(m_widgetList.at(m_activeWidgetList.at(i)),row,col); + m_gridLayout->addWidget(m_widgetList.at(m_activeWidgetList.at(i)), row, col); m_widgetList.at(m_activeWidgetList.at(i))->show(); - //logic for resizable n columns grid layout - if (col == currentNumberOfCols) { + // logic for resizable n columns grid layout + if(col == currentNumberOfCols) { col = 0; row++; } else { @@ -274,12 +257,14 @@ void FlexGridLayout::redrawWidgets() FlexGridLayout::~FlexGridLayout() { - for (auto widget: m_widgetList) { + for(auto widget : m_widgetList) { delete widget; } - if (m_gridLayout) { + if(m_gridLayout) { m_gridLayout->removeItem(m_vspacer); m_gridLayout->removeItem(m_hspacer); delete m_gridLayout; } } + +#include "moc_flexgridlayout.cpp" diff --git a/gui/src/generic_menu.cpp b/gui/src/generic_menu.cpp index c2a3aa8a65..ed4812b28a 100644 --- a/gui/src/generic_menu.cpp +++ b/gui/src/generic_menu.cpp @@ -1,9 +1,10 @@ -#include #include "generic_menu.hpp" +#include + using namespace scopy::gui; -GenericMenu::GenericMenu(QWidget* parent) +GenericMenu::GenericMenu(QWidget *parent) : QWidget(parent) , m_menuHeader(new MenuHeader(parent)) , m_menu(new BaseMenu(parent)) @@ -12,15 +13,15 @@ GenericMenu::GenericMenu(QWidget* parent) GenericMenu::~GenericMenu() { -// delete m_menuHeader; -// delete m_menu; + // delete m_menuHeader; + // delete m_menu; } void GenericMenu::initInteractiveMenu() { this->setStyleSheet(".QWidget { background-color: none; }"); - QVBoxLayout* layout = new QVBoxLayout(this); + QVBoxLayout *layout = new QVBoxLayout(this); layout->setSpacing(10); layout->setContentsMargins(18, 20, 18, 9); @@ -30,16 +31,16 @@ void GenericMenu::initInteractiveMenu() this->setLayout(layout); } -void GenericMenu::setMenuHeader(const QString& title, const QColor* lineColor, bool hasEnableBtn) +void GenericMenu::setMenuHeader(const QString &title, const QColor *lineColor, bool hasEnableBtn) { m_menuHeader->setLabel(title); m_menuHeader->setLineColor(lineColor); m_menuHeader->setEnabledBtnState(hasEnableBtn); } -void GenericMenu::insertSection(SubsectionSeparator* section) +void GenericMenu::insertSection(SubsectionSeparator *section) { - BaseMenuItem* item = new BaseMenuItem(m_menu); + BaseMenuItem *item = new BaseMenuItem(m_menu); item->setWidget(section); m_menu->insertMenuItem(item, m_lastOpenPosition); @@ -62,17 +63,10 @@ void GenericMenu::setMenuWidget(QWidget *widget) this->layout()->addWidget(widget); } -void GenericMenu::hideEvent(QHideEvent *) -{ - Q_EMIT menuVisibilityChanged(false); -} +void GenericMenu::hideEvent(QHideEvent *) { Q_EMIT menuVisibilityChanged(false); } -void GenericMenu::showEvent(QShowEvent *) -{ - Q_EMIT menuVisibilityChanged(true); -} +void GenericMenu::showEvent(QShowEvent *) { Q_EMIT menuVisibilityChanged(true); } -void GenericMenu::addNewHeaderWidget(QWidget *widget) -{ - m_menuHeader->addNewHeaderWidget(widget); -} +void GenericMenu::addNewHeaderWidget(QWidget *widget) { m_menuHeader->addNewHeaderWidget(widget); } + +#include "moc_generic_menu.cpp" diff --git a/gui/src/genericlogicplotcurve.cpp b/gui/src/genericlogicplotcurve.cpp index dc0a8af792..80a9ef72ed 100644 --- a/gui/src/genericlogicplotcurve.cpp +++ b/gui/src/genericlogicplotcurve.cpp @@ -18,95 +18,59 @@ * along with this program. If not, see . */ - #include "genericlogicplotcurve.h" + #include #include +GenericLogicPlotCurve::GenericLogicPlotCurve(const QString &name, const QString &id, LogicPlotCurveType type, + double pixelOffset, double traceHeight, double sampleRate, + double timeTriggerOffset, uint64_t bufferSize) + : QObject() + , QwtPlotCurve() + , m_name(name) + , m_id(id) + , m_traceColor("dodgerblue") + , m_pixelOffset(pixelOffset) + , m_traceHeight(traceHeight) + , m_sampleRate(sampleRate) + , m_timeTriggerOffset(timeTriggerOffset) + , m_bufferSize(bufferSize) + , m_type(type) +{} -GenericLogicPlotCurve::GenericLogicPlotCurve(const QString &name, const QString &id, LogicPlotCurveType type, double pixelOffset, - double traceHeight, double sampleRate, - double timeTriggerOffset, uint64_t bufferSize): - QObject(), - QwtPlotCurve(), - m_name(name), - m_id(id), - m_traceColor("dodgerblue"), - m_pixelOffset(pixelOffset), - m_traceHeight(traceHeight), - m_sampleRate(sampleRate), - m_timeTriggerOffset(timeTriggerOffset), - m_bufferSize(bufferSize), - m_type(type) -{ -} - -QString GenericLogicPlotCurve::getName() const -{ - return m_name; -} +QString GenericLogicPlotCurve::getName() const { return m_name; } -QString GenericLogicPlotCurve::getId() const -{ - return m_id; -} +QString GenericLogicPlotCurve::getId() const { return m_id; } -QColor GenericLogicPlotCurve::getTraceColor() const -{ - return m_traceColor; -} +QColor GenericLogicPlotCurve::getTraceColor() const { return m_traceColor; } +double GenericLogicPlotCurve::getPixelOffset() const { return m_pixelOffset; } -double GenericLogicPlotCurve::getPixelOffset() const -{ - return m_pixelOffset; -} +double GenericLogicPlotCurve::getTraceHeight() const { return m_traceHeight; } -double GenericLogicPlotCurve::getTraceHeight() const -{ - return m_traceHeight; -} - -double GenericLogicPlotCurve::getSampleRate() const -{ - return m_sampleRate; -} +double GenericLogicPlotCurve::getSampleRate() const { return m_sampleRate; } double GenericLogicPlotCurve::getTotalTime() const { - if (m_bufferSize == 0) return 0; + if(m_bufferSize == 0) + return 0; return static_cast(m_bufferSize) / m_sampleRate; } +double GenericLogicPlotCurve::getTimeTriggerOffset() const { return m_timeTriggerOffset; } -double GenericLogicPlotCurve::getTimeTriggerOffset() const -{ - return m_timeTriggerOffset; -} +uint64_t GenericLogicPlotCurve::getBufferSize() const { return m_bufferSize; } -uint64_t GenericLogicPlotCurve::getBufferSize() const -{ - return m_bufferSize; -} +int GenericLogicPlotCurve::getVisibleRows() const { return 1; } -int GenericLogicPlotCurve::getVisibleRows() const -{ - return 1; -} +double GenericLogicPlotCurve::getHeightOffset() const { return 0; } -double GenericLogicPlotCurve::getHeightOffset() const -{ - return 0; -} - -LogicPlotCurveType GenericLogicPlotCurve::getType() const -{ - return m_type; -} +LogicPlotCurveType GenericLogicPlotCurve::getType() const { return m_type; } void GenericLogicPlotCurve::setName(const QString &name) { - if (m_name != name) { + if(m_name != name) { m_name = name; Q_EMIT nameChanged(name); } @@ -114,14 +78,14 @@ void GenericLogicPlotCurve::setName(const QString &name) void GenericLogicPlotCurve::setId(const QString &id) { - if (m_id != id) { + if(m_id != id) { m_id = id; } } void GenericLogicPlotCurve::setPixelOffset(double pixelOffset) { - if (m_pixelOffset != pixelOffset) { + if(m_pixelOffset != pixelOffset) { m_pixelOffset = pixelOffset; setBaseline(m_pixelOffset + m_traceHeight); @@ -132,35 +96,32 @@ void GenericLogicPlotCurve::setPixelOffset(double pixelOffset) void GenericLogicPlotCurve::setTraceHeight(double traceHeight) { - if (m_traceHeight != traceHeight) { + if(m_traceHeight != traceHeight) { m_traceHeight = traceHeight; setBaseline(m_pixelOffset + m_traceHeight); } } -void GenericLogicPlotCurve::setTraceColor(const QColor traceColor) -{ - m_traceColor = traceColor; -} +void GenericLogicPlotCurve::setTraceColor(const QColor traceColor) { m_traceColor = traceColor; } void GenericLogicPlotCurve::setSampleRate(double sampleRate) { - if (m_sampleRate != sampleRate) { + if(m_sampleRate != sampleRate) { m_sampleRate = sampleRate; } } void GenericLogicPlotCurve::setTimeTriggerOffset(double timeTriggerOffset) { - if (m_timeTriggerOffset != timeTriggerOffset) { + if(m_timeTriggerOffset != timeTriggerOffset) { m_timeTriggerOffset = timeTriggerOffset; } } void GenericLogicPlotCurve::setBufferSize(uint64_t bufferSize) { - if (m_bufferSize != bufferSize) { + if(m_bufferSize != bufferSize) { m_bufferSize = bufferSize; } } @@ -173,11 +134,11 @@ uint64_t GenericLogicPlotCurve::fromTimeToSample(double time) const const double smin = 0; const double smax = m_bufferSize; - if (time > tmax) { + if(time > tmax) { time = tmax; } - if (time < tmin) { + if(time < tmin) { time = tmin; } @@ -192,21 +153,22 @@ double GenericLogicPlotCurve::fromSampleToTime(uint64_t sample) const const double smin = 0; const double smax = m_bufferSize; - if (sample > smax) { + if(sample > smax) { sample = smax; } return (sample - smin) / (smax - smin) * (tmax - tmin) + tmin; } -QPointF GenericLogicPlotCurve::screenPosToCurvePoint(const QPoint& pos) const +QPointF GenericLogicPlotCurve::screenPosToCurvePoint(const QPoint &pos) const { - const auto plt = plot(); - if (plt == nullptr) return QPointF(); - // TODO: Is there another way to do this? - const auto xmap = plt->canvasMap(xAxis().pos); - const auto ymap = plt->canvasMap(yAxis().pos); - return QPointF(xmap.invTransform(pos.x()), ymap.invTransform(pos.y())); + const auto plt = plot(); + if(plt == nullptr) + return QPointF(); + // TODO: Is there another way to do this? + const auto xmap = plt->canvasMap(xAxis().pos); + const auto ymap = plt->canvasMap(yAxis().pos); + return QPointF(xmap.invTransform(pos.x()), ymap.invTransform(pos.y())); } #include "moc_genericlogicplotcurve.cpp" diff --git a/gui/src/graticule.cpp b/gui/src/graticule.cpp index 00c48886f0..d24d25b00b 100644 --- a/gui/src/graticule.cpp +++ b/gui/src/graticule.cpp @@ -22,14 +22,14 @@ using namespace scopy; -Graticule::Graticule(QwtPlot *plot): - enabled(false), - plot(plot) +Graticule::Graticule(QwtPlot *plot) + : enabled(false) + , plot(plot) { - vertScale = new GraticulePlotScaleItem(QwtScaleDraw::LeftScale,-1); - horizScale = new GraticulePlotScaleItem(QwtScaleDraw::BottomScale,-1); - vertScale2 = new GraticulePlotScaleItem(QwtScaleDraw::RightScale,-1); - horizScale2 = new GraticulePlotScaleItem(QwtScaleDraw::TopScale,-1); + vertScale = new GraticulePlotScaleItem(QwtScaleDraw::LeftScale, -1); + horizScale = new GraticulePlotScaleItem(QwtScaleDraw::BottomScale, -1); + vertScale2 = new GraticulePlotScaleItem(QwtScaleDraw::RightScale, -1); + horizScale2 = new GraticulePlotScaleItem(QwtScaleDraw::TopScale, -1); QPalette palette = vertScale->palette(); palette.setBrush(QPalette::WindowText, QColor(0x6E6E6F)); @@ -41,30 +41,30 @@ Graticule::Graticule(QwtPlot *plot): vertScale->scaleDraw()->enableComponent(QwtAbstractScaleDraw::Backbone, false); vertScale->scaleDraw()->enableComponent(QwtAbstractScaleDraw::Labels, false); - vertScale->scaleDraw()->setTickLength(QwtScaleDiv::MinorTick,minTick*3/4); - vertScale->scaleDraw()->setTickLength(QwtScaleDiv::MediumTick,medTick*3/4); - vertScale->scaleDraw()->setTickLength(QwtScaleDiv::MajorTick,majTick*3/4); + vertScale->scaleDraw()->setTickLength(QwtScaleDiv::MinorTick, minTick * 3 / 4); + vertScale->scaleDraw()->setTickLength(QwtScaleDiv::MediumTick, medTick * 3 / 4); + vertScale->scaleDraw()->setTickLength(QwtScaleDiv::MajorTick, majTick * 3 / 4); vertScale->setPalette(palette); horizScale->scaleDraw()->enableComponent(QwtAbstractScaleDraw::Backbone, false); horizScale->scaleDraw()->enableComponent(QwtAbstractScaleDraw::Labels, false); - horizScale->scaleDraw()->setTickLength(QwtScaleDiv::MinorTick,minTick*3/4); - horizScale->scaleDraw()->setTickLength(QwtScaleDiv::MediumTick,medTick*3/4); - horizScale->scaleDraw()->setTickLength(QwtScaleDiv::MajorTick,majTick*3/4); + horizScale->scaleDraw()->setTickLength(QwtScaleDiv::MinorTick, minTick * 3 / 4); + horizScale->scaleDraw()->setTickLength(QwtScaleDiv::MediumTick, medTick * 3 / 4); + horizScale->scaleDraw()->setTickLength(QwtScaleDiv::MajorTick, majTick * 3 / 4); horizScale->setPalette(palette); vertScale2->scaleDraw()->enableComponent(QwtAbstractScaleDraw::Backbone, false); vertScale2->scaleDraw()->enableComponent(QwtAbstractScaleDraw::Labels, false); - vertScale2->scaleDraw()->setTickLength(QwtScaleDiv::MinorTick,minTick*3/4); - vertScale2->scaleDraw()->setTickLength(QwtScaleDiv::MediumTick,medTick*3/4); - vertScale2->scaleDraw()->setTickLength(QwtScaleDiv::MajorTick,majTick*3/4); + vertScale2->scaleDraw()->setTickLength(QwtScaleDiv::MinorTick, minTick * 3 / 4); + vertScale2->scaleDraw()->setTickLength(QwtScaleDiv::MediumTick, medTick * 3 / 4); + vertScale2->scaleDraw()->setTickLength(QwtScaleDiv::MajorTick, majTick * 3 / 4); vertScale2->setPalette(palette); horizScale2->scaleDraw()->enableComponent(QwtAbstractScaleDraw::Backbone, false); horizScale2->scaleDraw()->enableComponent(QwtAbstractScaleDraw::Labels, false); - horizScale2->scaleDraw()->setTickLength(QwtScaleDiv::MinorTick,minTick*3/4); - horizScale2->scaleDraw()->setTickLength(QwtScaleDiv::MediumTick,medTick*3/4); - horizScale2->scaleDraw()->setTickLength(QwtScaleDiv::MajorTick,majTick*3/4); + horizScale2->scaleDraw()->setTickLength(QwtScaleDiv::MinorTick, minTick * 3 / 4); + horizScale2->scaleDraw()->setTickLength(QwtScaleDiv::MediumTick, medTick * 3 / 4); + horizScale2->scaleDraw()->setTickLength(QwtScaleDiv::MajorTick, majTick * 3 / 4); horizScale2->setPalette(palette); } @@ -76,16 +76,16 @@ Graticule::~Graticule() delete horizScale2; } -void Graticule::toggleGraticule(){ +void Graticule::toggleGraticule() +{ enabled = !enabled; - if(enabled){ + if(enabled) { vertScale->attach(plot); vertScale2->attach(plot); horizScale->attach(plot); horizScale2->attach(plot); - } - else{ + } else { vertScale->detach(); vertScale2->detach(); horizScale->detach(); @@ -93,17 +93,17 @@ void Graticule::toggleGraticule(){ } } -void Graticule::enableGraticule(bool enable){ - if(enable != enabled){ +void Graticule::enableGraticule(bool enable) +{ + if(enable != enabled) { enabled = enable; - if(enabled){ + if(enabled) { vertScale->attach(plot); vertScale2->attach(plot); horizScale->attach(plot); horizScale2->attach(plot); - } - else{ + } else { vertScale->detach(); vertScale2->detach(); horizScale->detach(); @@ -112,20 +112,19 @@ void Graticule::enableGraticule(bool enable){ } } -void Graticule::onCanvasSizeChanged(){ - vertScale->setBorderDistance(plot->canvas()->width()/2); - horizScale->setBorderDistance(plot->canvas()->height()/2); - vertScale2->setBorderDistance(plot->canvas()->width()/2); - horizScale2->setBorderDistance(plot->canvas()->height()/2); -} - -GraticulePlotScaleItem::GraticulePlotScaleItem( - QwtScaleDraw::Alignment alignment, const double pos ): - QwtPlotScaleItem(alignment, pos) +void Graticule::onCanvasSizeChanged() { + vertScale->setBorderDistance(plot->canvas()->width() / 2); + horizScale->setBorderDistance(plot->canvas()->height() / 2); + vertScale2->setBorderDistance(plot->canvas()->width() / 2); + horizScale2->setBorderDistance(plot->canvas()->height() / 2); } -static QwtScaleDiv getGraticuleScaleDiv(const QwtScaleDiv& from_scaleDiv) +GraticulePlotScaleItem::GraticulePlotScaleItem(QwtScaleDraw::Alignment alignment, const double pos) + : QwtPlotScaleItem(alignment, pos) +{} + +static QwtScaleDiv getGraticuleScaleDiv(const QwtScaleDiv &from_scaleDiv) { double lowerBound; double upperBound; @@ -139,7 +138,7 @@ static QwtScaleDiv getGraticuleScaleDiv(const QwtScaleDiv& from_scaleDiv) mediumTicks = from_scaleDiv.ticks(QwtScaleDiv::MediumTick); majorTicks = from_scaleDiv.ticks(QwtScaleDiv::MajorTick); - if (majorTicks.size() >= 2) { + if(majorTicks.size() >= 2) { majorTicks.erase(majorTicks.begin()); majorTicks.erase(majorTicks.end() - 1); } @@ -147,11 +146,9 @@ static QwtScaleDiv getGraticuleScaleDiv(const QwtScaleDiv& from_scaleDiv) return QwtScaleDiv(lowerBound, upperBound, minorTicks, mediumTicks, majorTicks); } -void GraticulePlotScaleItem::updateScaleDiv( const QwtScaleDiv& xScaleDiv, - const QwtScaleDiv& yScaleDiv ) +void GraticulePlotScaleItem::updateScaleDiv(const QwtScaleDiv &xScaleDiv, const QwtScaleDiv &yScaleDiv) { - QwtPlotScaleItem::updateScaleDiv(getGraticuleScaleDiv(xScaleDiv), - getGraticuleScaleDiv(yScaleDiv)); + QwtPlotScaleItem::updateScaleDiv(getGraticuleScaleDiv(xScaleDiv), getGraticuleScaleDiv(yScaleDiv)); } #include "moc_graticule.cpp" diff --git a/gui/src/handles_area.cpp b/gui/src/handles_area.cpp index da4ed3ce45..3248bb3c18 100644 --- a/gui/src/handles_area.cpp +++ b/gui/src/handles_area.cpp @@ -19,20 +19,21 @@ */ #include "handles_area.hpp" -#include "plot_line_handle.h" -#include -#include #include "handlesareaextension.h" +#include "plot_line_handle.h" + +#include +#include /* * Class HandlesArea implementation */ -HandlesArea::HandlesArea(QWidget *parent): - QWidget(parent), - canvas(parent), - selectedItem(NULL) +HandlesArea::HandlesArea(QWidget *parent) + : QWidget(parent) + , canvas(parent) + , selectedItem(NULL) { this->setStyleSheet("QWidget {background-color: transparent}"); } @@ -44,10 +45,9 @@ void HandlesArea::installExtension(std::unique_ptr extensi void HandlesArea::mousePressEvent(QMouseEvent *event) { - PlotLineHandle *child = static_cast - (childAt(event->pos())); + PlotLineHandle *child = static_cast(childAt(event->pos())); - if (child) { + if(child) { child->raise(); selectedItem = child; hotspot = event->pos() - child->pos(); @@ -58,7 +58,7 @@ void HandlesArea::mousePressEvent(QMouseEvent *event) void HandlesArea::mouseReleaseEvent(QMouseEvent *) { - if (selectedItem) { + if(selectedItem) { selectedItem->setGrabbed(false); selectedItem = NULL; } @@ -66,7 +66,7 @@ void HandlesArea::mouseReleaseEvent(QMouseEvent *) void HandlesArea::mouseMoveEvent(QMouseEvent *event) { - if (selectedItem) { + if(selectedItem) { int x = event->pos().x() - hotspot.x(); int y = event->pos().y() - hotspot.y(); @@ -85,8 +85,8 @@ void HandlesArea::paintEvent(QPaintEvent *event) { QPainter p(this); - for (std::unique_ptr &extension : m_extensions) { - if (extension->draw(&p, this)) { + for(std::unique_ptr &extension : m_extensions) { + if(extension->draw(&p, this)) { break; } } @@ -98,55 +98,45 @@ void HandlesArea::paintEvent(QPaintEvent *event) * Class VertHandlesArea implementation */ -VertHandlesArea::VertHandlesArea(QWidget *parent): - HandlesArea(parent) +VertHandlesArea::VertHandlesArea(QWidget *parent) + : HandlesArea(parent) { largest_child_height = 0; top_padding = 50; bottom_padding = 50; } -int VertHandlesArea::topPadding() -{ - return top_padding; -} +int VertHandlesArea::topPadding() { return top_padding; } void VertHandlesArea::setTopPadding(int new_padding) { - if (top_padding != new_padding) { + if(top_padding != new_padding) { top_padding = new_padding; } } -int VertHandlesArea::bottomPadding() -{ - return bottom_padding; -} +int VertHandlesArea::bottomPadding() { return bottom_padding; } void VertHandlesArea::setLargestChildHeight(int height) { - if (largest_child_height != height) { + if(largest_child_height != height) { largest_child_height = height; resizeMask(this->size()); } } -int VertHandlesArea::largestChildHeight() -{ - return largest_child_height; -} +int VertHandlesArea::largestChildHeight() { return largest_child_height; } void VertHandlesArea::setBottomPadding(int new_padding) { - if (bottom_padding != new_padding) { + if(bottom_padding != new_padding) { bottom_padding = new_padding; } } void VertHandlesArea::resizeMask(QSize size) { - QRegion activeRegion(0, largest_child_height / 2, size.width(), - size.height() - largest_child_height); + QRegion activeRegion(0, largest_child_height / 2, size.width(), size.height() - largest_child_height); setMask(activeRegion); } @@ -154,80 +144,68 @@ void VertHandlesArea::resizeMask(QSize size) * Class HorizHandlesArea implementation */ -HorizHandlesArea::HorizHandlesArea(QWidget *parent): - HandlesArea(parent) +HorizHandlesArea::HorizHandlesArea(QWidget *parent) + : HandlesArea(parent) { largest_child_width = 0; left_padding = 50; right_padding = 50; } -int HorizHandlesArea::leftPadding() -{ - return left_padding; -} +int HorizHandlesArea::leftPadding() { return left_padding; } void HorizHandlesArea::setLeftPadding(int new_padding) { - if (left_padding != new_padding) { + if(left_padding != new_padding) { left_padding = new_padding; } } -int HorizHandlesArea::rightPadding() -{ - return right_padding; -} +int HorizHandlesArea::rightPadding() { return right_padding; } void HorizHandlesArea::setRightPadding(int new_padding) { - if (right_padding != new_padding) { + if(right_padding != new_padding) { right_padding = new_padding; } } void HorizHandlesArea::setLargestChildWidth(int width) { - if (largest_child_width != width) { + if(largest_child_width != width) { largest_child_width = width; resizeMask(this->size()); } } -int HorizHandlesArea::largestChildWidth() -{ - return largest_child_width; -} +int HorizHandlesArea::largestChildWidth() { return largest_child_width; } void HorizHandlesArea::resizeMask(QSize size) { - QRegion activeRegion(largest_child_width / 2, 0, size.width() - - largest_child_width, size.height()); + QRegion activeRegion(largest_child_width / 2, 0, size.width() - largest_child_width, size.height()); setMask(activeRegion); } - /* * Class GateHandlesArea implementation */ -GateHandlesArea::GateHandlesArea(QWidget *parent): - HorizHandlesArea(parent) +GateHandlesArea::GateHandlesArea(QWidget *parent) + : HorizHandlesArea(parent) {} void GateHandlesArea::mousePressEvent(QMouseEvent *event) { - PlotLineHandle *child = static_cast - (childAt(event->pos())); - if (child) { + PlotLineHandle *child = static_cast(childAt(event->pos())); + if(child) { child->raise(); selectedItem = child; - PlotGateHandle *handle = static_cast(child); + PlotGateHandle *handle = static_cast(child); if(handle->reachedLimit()) /*if the handle reached the limit update the hotspot so we can still change the bar position */ - hotspot = event->pos() - QPoint(handle->getCurrentPos(),handle->y()); - else{ + hotspot = event->pos() - QPoint(handle->getCurrentPos(), handle->y()); + else { hotspot = event->pos() - child->pos(); } child->setGrabbed(true); diff --git a/gui/src/handlesareaextension.cpp b/gui/src/handlesareaextension.cpp index b32e98a7b3..dc110886cf 100644 --- a/gui/src/handlesareaextension.cpp +++ b/gui/src/handlesareaextension.cpp @@ -1,29 +1,30 @@ #include "handlesareaextension.h" -#include +#include "DisplayPlot.h" +#include "handles_area.hpp" +#include #include -#include "handles_area.hpp" -#include "DisplayPlot.h" - using namespace scopy; -HandlesAreaExtension::HandlesAreaExtension(QwtPlot* plot) - : m_plot(plot) {} +HandlesAreaExtension::HandlesAreaExtension(QwtPlot *plot) + : m_plot(plot) +{} XBottomRuller::XBottomRuller(QwtPlot *plot) - : HandlesAreaExtension(plot) {} + : HandlesAreaExtension(plot) +{} bool XBottomRuller::draw(QPainter *painter, QWidget *owner) { - HorizHandlesArea *area = qobject_cast(owner); - if (!area) { + HorizHandlesArea *area = qobject_cast(owner); + if(!area) { return false; } - const DisplayPlot *plot = qobject_cast(m_plot); - if (!plot) { + const DisplayPlot *plot = qobject_cast(m_plot); + if(!plot) { return false; } @@ -33,12 +34,11 @@ bool XBottomRuller::draw(QPainter *painter, QWidget *owner) QVector labelRectangles; QStringList labelTexts; - if(plot->isLogaritmicPlot()) - { + if(plot->isLogaritmicPlot()) { QList majorTicks = plot->getXaxisMajorTicksPos(); double pointVal, currentValue; - for (int i = 0; i < majorTicks.size(); ++i) { + for(int i = 0; i < majorTicks.size(); ++i) { currentValue = majorTicks.at(i); pointVal = plot->transform(QwtAxis::XBottom, currentValue) + leftP; @@ -55,18 +55,18 @@ bool XBottomRuller::draw(QPainter *painter, QWidget *owner) // adjust labels to fit visible area of the handle area // mainly the first and last label - if (labelRectangles.first().topLeft().x() < owner->mask().boundingRect().bottomLeft().x()) { - int offset = owner->mask().boundingRect().bottomLeft().x() - labelRectangles.first().topLeft().x(); + if(labelRectangles.first().topLeft().x() < owner->mask().boundingRect().bottomLeft().x()) { + int offset = + owner->mask().boundingRect().bottomLeft().x() - labelRectangles.first().topLeft().x(); labelRectangles.first().adjust(offset, 0, offset, 0); } - if (labelRectangles.last().bottomRight().x() > owner->mask().boundingRect().bottomRight().x()) { - int offset = labelRectangles.last().bottomRight().x() - owner->mask().boundingRect().bottomRight().x(); + if(labelRectangles.last().bottomRight().x() > owner->mask().boundingRect().bottomRight().x()) { + int offset = labelRectangles.last().bottomRight().x() - + owner->mask().boundingRect().bottomRight().x(); labelRectangles.last().adjust(-offset, 0, -offset, 0); } - } - else - { + } else { // Some extensions might alter the state of the painter // such as its brush or pen. Consider saving its state // then restore it when done using it so other extensions @@ -82,7 +82,7 @@ bool XBottomRuller::draw(QPainter *painter, QWidget *owner) double midPoint = leftP; double currentValue = interval.minValue(); - for (int i = 0; i < labels; ++i) { + for(int i = 0; i < labels; ++i) { const QString text = plot->formatXValue(currentValue, 2); @@ -99,8 +99,8 @@ bool XBottomRuller::draw(QPainter *painter, QWidget *owner) } bool allLabelsTheSame = true; - for (int i = 1; i < labelTexts.size(); ++i) { - if (labelTexts[i] != labelTexts[i - 1]) { + for(int i = 1; i < labelTexts.size(); ++i) { + if(labelTexts[i] != labelTexts[i - 1]) { allLabelsTheSame = false; break; } @@ -110,20 +110,23 @@ bool XBottomRuller::draw(QPainter *painter, QWidget *owner) const int nrMajorTicks = plot->axisScaleDiv(QwtAxis::XBottom).ticks(QwtScaleDiv::MajorTick).size(); const int midLabelTick = nrMajorTicks / 2; - if (allLabelsTheSame) { + if(allLabelsTheSame) { // draw delta as middle label labelRectangles.clear(); labelTexts.clear(); midPoint = leftP; currentValue = interval.minValue(); - for (int i = 0; i < labels; ++i) { + for(int i = 0; i < labels; ++i) { QString text; - if (i == midLabelTick) { + if(i == midLabelTick) { text = plot->formatXValue(currentValue, 6); } else { - text = plot->formatXValue(currentValue - (interval.minValue() + midLabelTick * valueBetween2Labels), 2); + text = plot->formatXValue( + currentValue - + (interval.minValue() + midLabelTick * valueBetween2Labels), + 2); - if (i > midLabelTick) { + if(i > midLabelTick) { text = "+" + text; } } @@ -139,18 +142,19 @@ bool XBottomRuller::draw(QPainter *painter, QWidget *owner) midPoint += distBetween2Labels; currentValue += valueBetween2Labels; } - } // adjust labels to fit visible area of the handle area // mainly the first and last label - if (labelRectangles.first().topLeft().x() < owner->mask().boundingRect().bottomLeft().x()) { - int offset = owner->mask().boundingRect().bottomLeft().x() - labelRectangles.first().topLeft().x(); + if(labelRectangles.first().topLeft().x() < owner->mask().boundingRect().bottomLeft().x()) { + int offset = + owner->mask().boundingRect().bottomLeft().x() - labelRectangles.first().topLeft().x(); labelRectangles.first().adjust(offset, 0, offset, 0); } - if (labelRectangles.last().bottomRight().x() > owner->mask().boundingRect().bottomRight().x()) { - int offset = labelRectangles.last().bottomRight().x() - owner->mask().boundingRect().bottomRight().x(); + if(labelRectangles.last().bottomRight().x() > owner->mask().boundingRect().bottomRight().x()) { + int offset = labelRectangles.last().bottomRight().x() - + owner->mask().boundingRect().bottomRight().x(); labelRectangles.last().adjust(-offset, 0, -offset, 0); } @@ -163,34 +167,34 @@ bool XBottomRuller::draw(QPainter *painter, QWidget *owner) // find overlaping int i = 0; - for (; i < labelRectangles.size() - 1; ++i) { - if (labelRectangles[i].intersects(labelRectangles[i + 1])) { + for(; i < labelRectangles.size() - 1; ++i) { + if(labelRectangles[i].intersects(labelRectangles[i + 1])) { overlaping = true; break; } } // done - if (!overlaping) { + if(!overlaping) { break; } - if (allLabelsTheSame) { + if(allLabelsTheSame) { int center = midLabelTick; - for (int i = center - 1; i >= 0; i -= 2) { + for(int i = center - 1; i >= 0; i -= 2) { // Remove the tick and make sure to update the center // label position labelRectangles.removeAt(i); labelTexts.removeAt(i); --center; } - for (int j = center + 1; j < labelRectangles.size(); j += 1) { + for(int j = center + 1; j < labelRectangles.size(); j += 1) { labelRectangles.removeAt(j); labelTexts.removeAt(j); } } else { // remove overlaping - if (i + 1 == labelRectangles.size() - 1) { + if(i + 1 == labelRectangles.size() - 1) { labelRectangles.removeAt(i); labelTexts.removeAt(i); } else { @@ -199,10 +203,9 @@ bool XBottomRuller::draw(QPainter *painter, QWidget *owner) } } } while(overlaping); - } // draw the labels - for (int i = 0; i < labelRectangles.size(); ++i) { + for(int i = 0; i < labelRectangles.size(); ++i) { painter->drawText(labelRectangles[i], labelTexts[i]); } @@ -210,17 +213,18 @@ bool XBottomRuller::draw(QPainter *painter, QWidget *owner) } XTopRuller::XTopRuller(QwtPlot *plot) - : HandlesAreaExtension(plot) {} + : HandlesAreaExtension(plot) +{} bool XTopRuller::draw(QPainter *painter, QWidget *owner) { - HorizHandlesArea *area = qobject_cast(owner); - if (!area) { + HorizHandlesArea *area = qobject_cast(owner); + if(!area) { return false; } - const DisplayPlot *plot = qobject_cast(m_plot); - if (!plot) { + const DisplayPlot *plot = qobject_cast(m_plot); + if(!plot) { return false; } @@ -230,12 +234,11 @@ bool XTopRuller::draw(QPainter *painter, QWidget *owner) QVector labelRectangles; QStringList labelTexts; - if(plot->isLogaritmicPlot()) - { + if(plot->isLogaritmicPlot()) { QList majorTicks = plot->getXaxisMajorTicksPos(); double pointVal, currentValue; - for (int i = 0; i < majorTicks.size(); ++i) { + for(int i = 0; i < majorTicks.size(); ++i) { currentValue = majorTicks.at(i); pointVal = plot->transform(QwtAxis::XTop, currentValue) + leftP; @@ -252,26 +255,24 @@ bool XTopRuller::draw(QPainter *painter, QWidget *owner) // adjust labels to fit visible area of the handle area // mainly the first and last label - if (labelRectangles.first().topLeft().x() < owner->mask().boundingRect().bottomLeft().x()) { - int offset = owner->mask().boundingRect().bottomLeft().x() - labelRectangles.first().topLeft().x(); + if(labelRectangles.first().topLeft().x() < owner->mask().boundingRect().bottomLeft().x()) { + int offset = + owner->mask().boundingRect().bottomLeft().x() - labelRectangles.first().topLeft().x(); labelRectangles.first().adjust(offset, 0, offset, 0); } - if (labelRectangles.last().bottomRight().x() > owner->mask().boundingRect().bottomRight().x()) { - int offset = labelRectangles.last().bottomRight().x() - owner->mask().boundingRect().bottomRight().x(); + if(labelRectangles.last().bottomRight().x() > owner->mask().boundingRect().bottomRight().x()) { + int offset = labelRectangles.last().bottomRight().x() - + owner->mask().boundingRect().bottomRight().x(); labelRectangles.last().adjust(-offset, 0, -offset, 0); } - - } - else - { + } else { // Some extensions might alter the state of the painter // such as its brush or pen. Consider saving its state // then restore it when done using it so other extensions // won't be affected - const QwtInterval interval = plot->axisInterval(QwtAxis::XTop); const int labels = plot->xAxisNumDiv() + 1; @@ -282,7 +283,7 @@ bool XTopRuller::draw(QPainter *painter, QWidget *owner) double midPoint = leftP; double currentValue = interval.minValue(); - for (int i = 0; i < labels; ++i) { + for(int i = 0; i < labels; ++i) { const QString text = plot->formatXValue(currentValue, 2); const QSizeF textSize = QwtText(text).textSize(painter->font()); @@ -298,8 +299,8 @@ bool XTopRuller::draw(QPainter *painter, QWidget *owner) } bool allLabelsTheSame = true; - for (int i = 1; i < labelTexts.size(); ++i) { - if (labelTexts[i] != labelTexts[i - 1]) { + for(int i = 1; i < labelTexts.size(); ++i) { + if(labelTexts[i] != labelTexts[i - 1]) { allLabelsTheSame = false; break; } @@ -309,19 +310,22 @@ bool XTopRuller::draw(QPainter *painter, QWidget *owner) const int nrMajorTicks = plot->axisScaleDiv(QwtAxis::XTop).ticks(QwtScaleDiv::MajorTick).size(); const int midLabelTick = nrMajorTicks / 2; - if (allLabelsTheSame) { + if(allLabelsTheSame) { // draw delta as middle label labelRectangles.clear(); labelTexts.clear(); midPoint = leftP; currentValue = interval.minValue(); - for (int i = 0; i < labels; ++i) { + for(int i = 0; i < labels; ++i) { QString text; - if (i == midLabelTick) { + if(i == midLabelTick) { text = plot->formatXValue(currentValue, 2); } else { - text= plot->formatXValue(currentValue - (interval.minValue() + midLabelTick * valueBetween2Labels), 2); - if (i > midLabelTick) { + text = plot->formatXValue( + currentValue - + (interval.minValue() + midLabelTick * valueBetween2Labels), + 2); + if(i > midLabelTick) { text = "+" + text; } } @@ -337,18 +341,19 @@ bool XTopRuller::draw(QPainter *painter, QWidget *owner) midPoint += distBetween2Labels; currentValue += valueBetween2Labels; } - } // adjust labels to fit visible area of the handle area // mainly the first and last label - if (labelRectangles.first().topLeft().x() < owner->mask().boundingRect().bottomLeft().x()) { - int offset = owner->mask().boundingRect().bottomLeft().x() - labelRectangles.first().topLeft().x(); + if(labelRectangles.first().topLeft().x() < owner->mask().boundingRect().bottomLeft().x()) { + int offset = + owner->mask().boundingRect().bottomLeft().x() - labelRectangles.first().topLeft().x(); labelRectangles.first().adjust(offset, 0, offset, 0); } - if (labelRectangles.last().bottomRight().x() > owner->mask().boundingRect().bottomRight().x()) { - int offset = labelRectangles.last().bottomRight().x() - owner->mask().boundingRect().bottomRight().x(); + if(labelRectangles.last().bottomRight().x() > owner->mask().boundingRect().bottomRight().x()) { + int offset = labelRectangles.last().bottomRight().x() - + owner->mask().boundingRect().bottomRight().x(); labelRectangles.last().adjust(-offset, 0, -offset, 0); } @@ -361,34 +366,34 @@ bool XTopRuller::draw(QPainter *painter, QWidget *owner) // find overlaping int i = 0; - for (; i < labelRectangles.size() - 1; ++i) { - if (labelRectangles[i].intersects(labelRectangles[i + 1])) { + for(; i < labelRectangles.size() - 1; ++i) { + if(labelRectangles[i].intersects(labelRectangles[i + 1])) { overlaping = true; break; } } // done - if (!overlaping) { + if(!overlaping) { break; } - if (allLabelsTheSame) { + if(allLabelsTheSame) { int center = midLabelTick; - for (int i = center - 1; i >= 0; i -= 2) { + for(int i = center - 1; i >= 0; i -= 2) { // Remove the tick and make sure to update the center // label position labelRectangles.removeAt(i); labelTexts.removeAt(i); --center; } - for (int j = center + 1; j < labelRectangles.size(); j += 1) { + for(int j = center + 1; j < labelRectangles.size(); j += 1) { labelRectangles.removeAt(j); labelTexts.removeAt(j); } } else { // remove overlaping - if (i + 1 == labelRectangles.size() - 1) { + if(i + 1 == labelRectangles.size() - 1) { labelRectangles.removeAt(i); labelTexts.removeAt(i); } else { @@ -400,7 +405,7 @@ bool XTopRuller::draw(QPainter *painter, QWidget *owner) } // draw the labels - for (int i = 0; i < labelRectangles.size(); ++i) { + for(int i = 0; i < labelRectangles.size(); ++i) { painter->drawText(labelRectangles[i], labelTexts[i]); } @@ -408,12 +413,13 @@ bool XTopRuller::draw(QPainter *painter, QWidget *owner) } YLeftRuller::YLeftRuller(QwtPlot *plot) - : HandlesAreaExtension(plot) {} + : HandlesAreaExtension(plot) +{} bool YLeftRuller::draw(QPainter *painter, QWidget *owner) { - VertHandlesArea *area = qobject_cast(owner); - if (!area) { + VertHandlesArea *area = qobject_cast(owner); + if(!area) { return false; } @@ -421,24 +427,22 @@ bool YLeftRuller::draw(QPainter *painter, QWidget *owner) if(area->width() != width_text) area->setMinimumWidth(width_text); - const DisplayPlot *plot = qobject_cast(m_plot); - if (!plot) { + const DisplayPlot *plot = qobject_cast(m_plot); + if(!plot) { return false; } - const double topP = area->topPadding(); const double bottomP = area->bottomPadding(); QVector labelRectangles; QStringList labelTexts; - if(plot->isLogaritmicYPlot()) - { + if(plot->isLogaritmicYPlot()) { QList majorTicks = plot->getYaxisMajorTicksPos(); double pointVal, currentValue; - for (int i = 0; i < majorTicks.size(); ++i) { + for(int i = 0; i < majorTicks.size(); ++i) { currentValue = majorTicks.at(i); pointVal = plot->transform(QwtAxis::YLeft, currentValue) + topP; @@ -455,21 +459,20 @@ bool YLeftRuller::draw(QPainter *painter, QWidget *owner) // adjust labels to fit visible area of the handle area // mainly the first and last label - if(!labelRectangles.empty()) - { - if (labelRectangles.first().topRight().y() < owner->mask().boundingRect().topLeft().y()) { - int offset = owner->mask().boundingRect().topLeft().y() - labelRectangles.first().topRight().y(); + if(!labelRectangles.empty()) { + if(labelRectangles.first().topRight().y() < owner->mask().boundingRect().topLeft().y()) { + int offset = owner->mask().boundingRect().topLeft().y() - + labelRectangles.first().topRight().y(); labelRectangles.first().adjust(0, offset, 0, offset); } - if (labelRectangles.last().bottomRight().y() > owner->mask().boundingRect().bottomLeft().y()) { - int offset = labelRectangles.last().bottomRight().y() - owner->mask().boundingRect().bottomLeft().y(); + if(labelRectangles.last().bottomRight().y() > owner->mask().boundingRect().bottomLeft().y()) { + int offset = labelRectangles.last().bottomRight().y() - + owner->mask().boundingRect().bottomLeft().y(); labelRectangles.last().adjust(0, -offset, 0, -offset); } } - } - else - { + } else { const QwtInterval interval = plot->axisInterval(QwtAxis::YLeft); @@ -484,7 +487,7 @@ bool YLeftRuller::draw(QPainter *painter, QWidget *owner) QList majorTicks = plot->axisScaleDiv(QwtAxis::YLeft).ticks(QwtScaleDiv::MajorTick); double pointVal, currentValue; - for (int i = 0; i < majorTicks.size(); ++i) { + for(int i = 0; i < majorTicks.size(); ++i) { // this is the same way ticks are parsed in logarithmic mode too // this whole function may need refactoring soon ... @@ -503,8 +506,8 @@ bool YLeftRuller::draw(QPainter *painter, QWidget *owner) } bool allLabelsTheSame = true; - for (int i = 1; i < labelTexts.size(); ++i) { - if (labelTexts[i] != labelTexts[i - 1]) { + for(int i = 1; i < labelTexts.size(); ++i) { + if(labelTexts[i] != labelTexts[i - 1]) { allLabelsTheSame = false; break; } @@ -514,19 +517,22 @@ bool YLeftRuller::draw(QPainter *painter, QWidget *owner) const int nrMajorTicks = plot->axisScaleDiv(QwtAxis::YLeft).ticks(QwtScaleDiv::MajorTick).size(); const int midLabelTick = nrMajorTicks / 2; - if (allLabelsTheSame) { + if(allLabelsTheSame) { // draw delta as middle label labelRectangles.clear(); labelTexts.clear(); midPoint = topP; currentValue = interval.maxValue(); - for (int i = 0; i < labels; ++i) { + for(int i = 0; i < labels; ++i) { QString text; - if (i == midLabelTick) { + if(i == midLabelTick) { text = plot->formatYValue(currentValue, 2); } else { - text = plot->formatYValue(currentValue - (interval.maxValue() + midLabelTick * valueBetween2Labels), 2); - if (i > midLabelTick) { + text = plot->formatYValue( + currentValue - + (interval.maxValue() + midLabelTick * valueBetween2Labels), + 2); + if(i > midLabelTick) { text = "+" + text; } } @@ -546,13 +552,15 @@ bool YLeftRuller::draw(QPainter *painter, QWidget *owner) // adjust labels to fit visible area of the handle area // mainly the first and last label - if (labelRectangles.first().topRight().y() < owner->mask().boundingRect().topLeft().y()) { - int offset = owner->mask().boundingRect().topLeft().y() - labelRectangles.first().topRight().y(); + if(labelRectangles.first().topRight().y() < owner->mask().boundingRect().topLeft().y()) { + int offset = + owner->mask().boundingRect().topLeft().y() - labelRectangles.first().topRight().y(); labelRectangles.first().adjust(0, offset, 0, offset); } - if (labelRectangles.last().bottomRight().y() > owner->mask().boundingRect().bottomLeft().y()) { - int offset = labelRectangles.last().bottomRight().y() - owner->mask().boundingRect().bottomLeft().y(); + if(labelRectangles.last().bottomRight().y() > owner->mask().boundingRect().bottomLeft().y()) { + int offset = labelRectangles.last().bottomRight().y() - + owner->mask().boundingRect().bottomLeft().y(); labelRectangles.last().adjust(0, -offset, 0, -offset); } @@ -565,34 +573,34 @@ bool YLeftRuller::draw(QPainter *painter, QWidget *owner) // find overlaping int i = 0; - for (; i < labelRectangles.size() - 1; ++i) { - if (labelRectangles[i].intersects(labelRectangles[i + 1])) { + for(; i < labelRectangles.size() - 1; ++i) { + if(labelRectangles[i].intersects(labelRectangles[i + 1])) { overlaping = true; break; } } // done - if (!overlaping) { + if(!overlaping) { break; } - if (allLabelsTheSame) { + if(allLabelsTheSame) { int center = midLabelTick; - for (int i = center - 1; i >= 0; i -= 2) { + for(int i = center - 1; i >= 0; i -= 2) { // Remove the tick and make sure to update the center // label position labelRectangles.removeAt(i); labelTexts.removeAt(i); --center; } - for (int j = center + 1; j < labelRectangles.size(); j += 1) { + for(int j = center + 1; j < labelRectangles.size(); j += 1) { labelRectangles.removeAt(j); labelTexts.removeAt(j); } - }else { + } else { // remove overlaping - if (i + 1 == labelRectangles.size() - 1) { + if(i + 1 == labelRectangles.size() - 1) { labelRectangles.removeAt(i); labelTexts.removeAt(i); } else { @@ -600,11 +608,11 @@ bool YLeftRuller::draw(QPainter *painter, QWidget *owner) labelTexts.removeAt(i + 1); } } - }while(overlaping); + } while(overlaping); } // draw the labels - for (int i = 0; i < labelRectangles.size(); ++i) { + for(int i = 0; i < labelRectangles.size(); ++i) { painter->drawText(labelRectangles[i], labelTexts[i]); } diff --git a/gui/src/hcursor.cpp b/gui/src/hcursor.cpp index 5a9be2cefa..8bae3748b8 100644 --- a/gui/src/hcursor.cpp +++ b/gui/src/hcursor.cpp @@ -2,13 +2,12 @@ using namespace scopy; - -HCursor::HCursor(PlotWidget *p, PlotAxis *ax,bool bottom, QPen pen) : - Cursor(p, ax, pen) +HCursor::HCursor(PlotWidget *p, PlotAxis *ax, bool bottom, QPen pen) + : Cursor(p, ax, pen) { m_symbolCtrl = p->symbolCtrl(); m_cursorBar = new VertBar(p->plot()); - auto hCursorBar = static_cast(m_cursorBar); + auto hCursorBar = static_cast(m_cursorBar); m_symbolCtrl->attachSymbol(m_cursorBar); m_cursorBar->setCanLeavePlot(m_canLeavePlot); @@ -16,41 +15,33 @@ HCursor::HCursor(PlotWidget *p, PlotAxis *ax,bool bottom, QPen pen) : m_cursorBar->setMobileAxis(m_axis->axisId()); m_cursorBar->setPen(pen); - m_cursorHandle = new PlotLineHandleH( - QPixmap(":/gui/icons/h_cursor_handle.svg"), - (bottom) ? p->bottomHandlesArea() : p->topHandlesArea(), !bottom); + m_cursorHandle = new PlotLineHandleH(QPixmap(":/gui/icons/h_cursor_handle.svg"), + (bottom) ? p->bottomHandlesArea() : p->topHandlesArea(), !bottom); - auto m_hCursorHandle = static_cast(m_cursorHandle); + auto m_hCursorHandle = static_cast(m_cursorHandle); m_hCursorHandle->setPen(pen); m_hCursorHandle->setVisible(true); /* When bar position changes due to plot resizes update the handle */ - connect(p->rightHandlesArea(), &HandlesArea::sizeChanged, m_cursorHandle, [=](){ - m_hCursorHandle->updatePosition(); - }); + connect(p->rightHandlesArea(), &HandlesArea::sizeChanged, m_cursorHandle, + [=]() { m_hCursorHandle->updatePosition(); }); connect(hCursorBar, &VertBar::pixelPositionChanged, this, - [=](int pos) { - m_hCursorHandle->setPositionSilenty(pos); - }); - - connect(m_cursorHandle, &PlotLineHandleH::positionChanged, this, - [=](int pos) { - double new_pos = computePosition(pos); - if (!m_canLeavePlot) { - new_pos = std::max(std::min(m_axis->max(), new_pos), m_axis->min()); - } - hCursorBar->setPosition(new_pos); - Q_EMIT positionChanged(new_pos); - }); + [=](int pos) { m_hCursorHandle->setPositionSilenty(pos); }); + + connect(m_cursorHandle, &PlotLineHandleH::positionChanged, this, [=](int pos) { + double new_pos = computePosition(pos); + if(!m_canLeavePlot) { + new_pos = std::max(std::min(m_axis->max(), new_pos), m_axis->min()); + } + hCursorBar->setPosition(new_pos); + Q_EMIT positionChanged(new_pos); + }); connect(this, &HCursor::update, m_hCursorHandle, &PlotLineHandleH::triggerMove); } -HCursor::~HCursor() -{ - -} +HCursor::~HCursor() {} void HCursor::setCanLeavePlot(bool leave) { @@ -58,22 +49,22 @@ void HCursor::setCanLeavePlot(bool leave) m_cursorBar->setCanLeavePlot(m_canLeavePlot); } -double HCursor::getPosition() -{ - return static_cast(m_cursorBar)->getPosition(); -} +double HCursor::getPosition() { return static_cast(m_cursorBar)->getPosition(); } void HCursor::setPosition(double pos) { // cursors cannot be outside of the axis - if (!m_canLeavePlot) { + if(!m_canLeavePlot) { pos = std::max(std::min(m_axis->max(), pos), m_axis->min()); } - static_cast(m_cursorBar)->setPosition(pos); + static_cast(m_cursorBar)->setPosition(pos); } -double HCursor::computePosition(int pos) { +double HCursor::computePosition(int pos) +{ QwtScaleMap xMap = m_plot->canvasMap(m_axis->axisId()); double offset = xMap.invTransform(pos); return offset; } + +#include "moc_hcursor.cpp" diff --git a/gui/src/homepage_controls.cpp b/gui/src/homepage_controls.cpp index 71dfeb3327..1b7b0ed25a 100644 --- a/gui/src/homepage_controls.cpp +++ b/gui/src/homepage_controls.cpp @@ -19,13 +19,14 @@ */ #include "homepage_controls.h" + #include using namespace scopy; -HomepageControls::HomepageControls(QWidget *parent) : - HoverWidget(), - controls(new PageNavigationWidget(false, false, this)) +HomepageControls::HomepageControls(QWidget *parent) + : HoverWidget() + , controls(new PageNavigationWidget(false, false, this)) { setContent(controls); setAnchor(parent); @@ -37,32 +38,17 @@ HomepageControls::HomepageControls(QWidget *parent) : connectSignals(); } -HomepageControls::~HomepageControls() -{ - -} +HomepageControls::~HomepageControls() {} void HomepageControls::connectSignals() { - connect(controls->getBackwardBtn(), &QPushButton::clicked, this, [=](){ - Q_EMIT goLeft(); - }); - connect(controls->getForwardBtn(), &QPushButton::clicked, this, [=](){ - Q_EMIT goRight(); - }); - connect(controls->getOpenBtn(), &QPushButton::clicked, this, [=](){ - Q_EMIT openFile(); - }); + connect(controls->getBackwardBtn(), &QPushButton::clicked, this, [=]() { Q_EMIT goLeft(); }); + connect(controls->getForwardBtn(), &QPushButton::clicked, this, [=]() { Q_EMIT goRight(); }); + connect(controls->getOpenBtn(), &QPushButton::clicked, this, [=]() { Q_EMIT openFile(); }); } -void HomepageControls::enableLeft(bool en) -{ - controls->getBackwardBtn()->setEnabled(en); -} +void HomepageControls::enableLeft(bool en) { controls->getBackwardBtn()->setEnabled(en); } -void HomepageControls::enableRight(bool en) -{ - controls->getForwardBtn()->setEnabled(en); -} +void HomepageControls::enableRight(bool en) { controls->getForwardBtn()->setEnabled(en); } #include "moc_homepage_controls.cpp" diff --git a/gui/src/infopage.cpp b/gui/src/infopage.cpp index fd0bdb63fc..54b9b3806c 100644 --- a/gui/src/infopage.cpp +++ b/gui/src/infopage.cpp @@ -1,13 +1,14 @@ #include "infopage.h" + #include "QFile" #include "qjsondocument.h" #include "qjsonobject.h" using namespace scopy; -InfoPage::InfoPage(QWidget *parent) : - QWidget(parent) - , m_advancedMode(false) +InfoPage::InfoPage(QWidget *parent) + : QWidget(parent) + , m_advancedMode(false) { getKeyMap(); lay = new QVBoxLayout(this); @@ -16,33 +17,32 @@ InfoPage::InfoPage(QWidget *parent) : InfoPage::~InfoPage() { - if (!map.empty()) { + if(!map.empty()) { map.clear(); } - if (!wmap.empty()) { + if(!wmap.empty()) { qDeleteAll(wmap); wmap.clear(); } - if (!keyMap.empty()) { + if(!keyMap.empty()) { keyMap.clear(); } } void InfoPage::update(QString key, QString value) { - if (!m_advancedMode) { - if (keyMap.contains(key)) { + if(!m_advancedMode) { + if(keyMap.contains(key)) { key = keyMap[key]; } else { return; } - } if(!map.contains(key)) { - map.insert(key,value); - InfoPageKeyValueWidget *w = new InfoPageKeyValueWidget(key,value, this); - w->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); - wmap.insert(key,w); + map.insert(key, value); + InfoPageKeyValueWidget *w = new InfoPageKeyValueWidget(key, value, this); + w->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + wmap.insert(key, w); lay->addWidget(w); } else { @@ -53,10 +53,10 @@ void InfoPage::update(QString key, QString value) void InfoPage::clear() { - if (!map.empty()) { + if(!map.empty()) { map.clear(); } - if (!wmap.empty()) { + if(!wmap.empty()) { qDeleteAll(wmap); wmap.clear(); } @@ -71,10 +71,10 @@ void InfoPage::getKeyMap() val = file.readAll(); file.close(); - if (fileIsOpen) { + if(fileIsOpen) { QJsonDocument d = QJsonDocument::fromJson(val.toUtf8()); QJsonObject json = d.object(); - foreach(const QString& key, json.keys()) { + foreach(const QString &key, json.keys()) { QJsonValue value = json.value(key); keyMap[key] = value["value"].toString(); } @@ -83,10 +83,6 @@ void InfoPage::getKeyMap() } } -void InfoPage::setAdvancedMode(bool newAdvancedMode) -{ - m_advancedMode = newAdvancedMode; -} - +void InfoPage::setAdvancedMode(bool newAdvancedMode) { m_advancedMode = newAdvancedMode; } #include "moc_infopage.cpp" diff --git a/gui/src/infopagekeyvaluewidget.cpp b/gui/src/infopagekeyvaluewidget.cpp index d046867241..ba72b69e84 100644 --- a/gui/src/infopagekeyvaluewidget.cpp +++ b/gui/src/infopagekeyvaluewidget.cpp @@ -1,12 +1,14 @@ #include "infopagekeyvaluewidget.h" using namespace scopy; -InfoPageKeyValueWidget::InfoPageKeyValueWidget(QString key, QString value, QWidget *parent) : +InfoPageKeyValueWidget::InfoPageKeyValueWidget(QString key, QString value, QWidget *parent) + : - QWidget(parent) { + QWidget(parent) +{ QHBoxLayout *lay = new QHBoxLayout(this); - lay->setContentsMargins(0,0,0,0); + lay->setContentsMargins(0, 0, 0, 0); lay->setMargin(0); lay->setSpacing(0); @@ -18,6 +20,4 @@ InfoPageKeyValueWidget::InfoPageKeyValueWidget(QString key, QString value, QWidg lay->setStretch(1, 3); } -void InfoPageKeyValueWidget::updateValue(QString value) { - valueWidget->setText(value); -} +void InfoPageKeyValueWidget::updateValue(QString value) { valueWidget->setText(value); } diff --git a/gui/src/instrumentnotes.cpp b/gui/src/instrumentnotes.cpp index 1486de6a42..27985cd78f 100644 --- a/gui/src/instrumentnotes.cpp +++ b/gui/src/instrumentnotes.cpp @@ -1,29 +1,20 @@ #include "instrumentnotes.h" + #include "ui_instrumentnotes.h" namespace scopy { -InstrumentNotes::InstrumentNotes(QWidget *parent) : - QWidget(parent), - ui(new Ui::InstrumentNotes) +InstrumentNotes::InstrumentNotes(QWidget *parent) + : QWidget(parent) + , ui(new Ui::InstrumentNotes) { ui->setupUi(this); } -InstrumentNotes::~InstrumentNotes() -{ - delete ui; -} +InstrumentNotes::~InstrumentNotes() { delete ui; } +QString InstrumentNotes::getNotes() { return ui->textEdit->toPlainText(); } +void InstrumentNotes::setNotes(QString str) { ui->textEdit->setPlainText(str); } -QString InstrumentNotes::getNotes() -{ - return ui->textEdit->toPlainText(); -} -void InstrumentNotes::setNotes(QString str) -{ - ui->textEdit->setPlainText(str); -} - -} +} // namespace scopy #include "moc_instrumentnotes.cpp" diff --git a/gui/src/lcdNumber.cpp b/gui/src/lcdNumber.cpp index 15590ebb9f..5e215b1b5e 100644 --- a/gui/src/lcdNumber.cpp +++ b/gui/src/lcdNumber.cpp @@ -26,22 +26,16 @@ using namespace scopy; -LcdNumber::LcdNumber(QWidget *parent, unsigned precision) : - QLCDNumber(parent), precision(precision) +LcdNumber::LcdNumber(QWidget *parent, unsigned precision) + : QLCDNumber(parent) + , precision(precision) { display(0.0); } -void LcdNumber::setPrecision(unsigned precision) -{ - this->precision = precision; - -} +void LcdNumber::setPrecision(unsigned precision) { this->precision = precision; } -unsigned LcdNumber::getPrecision() -{ - return precision; -} +unsigned LcdNumber::getPrecision() { return precision; } void LcdNumber::display(double num) { diff --git a/gui/src/limitedplotzoomer.cpp b/gui/src/limitedplotzoomer.cpp index c9712446f6..774aa2be42 100644 --- a/gui/src/limitedplotzoomer.cpp +++ b/gui/src/limitedplotzoomer.cpp @@ -18,23 +18,26 @@ * along with this program. If not, see . */ #include "limitedplotzoomer.h" -#include + #include +#include using namespace scopy; -LimitedPlotZoomer::LimitedPlotZoomer(QwtAxisId xAxis, QwtAxisId yAxis,QWidget *parent, bool doReplot): - QwtPlotZoomer(xAxis, yAxis,parent, doReplot), - m_boundVertical(false), m_updateBaseNextZoom(true) +LimitedPlotZoomer::LimitedPlotZoomer(QwtAxisId xAxis, QwtAxisId yAxis, QWidget *parent, bool doReplot) + : QwtPlotZoomer(xAxis, yAxis, parent, doReplot) + , m_boundVertical(false) + , m_updateBaseNextZoom(true) { setMaxStackDepth(5); } -LimitedPlotZoomer::LimitedPlotZoomer(QWidget *parent, bool doReplot): - QwtPlotZoomer(parent, doReplot), - m_boundVertical(false), m_updateBaseNextZoom(true) +LimitedPlotZoomer::LimitedPlotZoomer(QWidget *parent, bool doReplot) + : QwtPlotZoomer(parent, doReplot) + , m_boundVertical(false) + , m_updateBaseNextZoom(true) { - setMaxStackDepth(5); + setMaxStackDepth(5); } void LimitedPlotZoomer::resetZoom() @@ -43,15 +46,9 @@ void LimitedPlotZoomer::resetZoom() m_updateBaseNextZoom = true; } -void LimitedPlotZoomer::popZoom() -{ - QwtPlotZoomer::zoom(-1); -} +void LimitedPlotZoomer::popZoom() { QwtPlotZoomer::zoom(-1); } -void LimitedPlotZoomer::setBoundVertical(bool bound) -{ - m_boundVertical = bound; -} +void LimitedPlotZoomer::setBoundVertical(bool bound) { m_boundVertical = bound; } void LimitedPlotZoomer::zoom(const QRectF &rect) { @@ -62,7 +59,7 @@ void LimitedPlotZoomer::zoom(const QRectF &rect) } QRectF boundedRect = rect & zoomBase(); - if (m_boundVertical) { + if(m_boundVertical) { QRectF baseRect = zoomBase(); boundedRect.setTop(baseRect.top()); boundedRect.setBottom(baseRect.bottom()); diff --git a/gui/src/linked_button.cpp b/gui/src/linked_button.cpp index 3c413644bb..0096d88d33 100644 --- a/gui/src/linked_button.cpp +++ b/gui/src/linked_button.cpp @@ -1,16 +1,17 @@ #include "linked_button.hpp" + #include "dynamicWidget.h" #include -#include #include +#include using namespace scopy; -LinkedButton::LinkedButton(QWidget* parent) +LinkedButton::LinkedButton(QWidget *parent) : QPushButton(parent) { - setDynamicProperty(this,"info_button", true); + setDynamicProperty(this, "info_button", true); this->setIcon(QIcon::fromTheme(":/gui/icons/scopy-default/icons/info")); this->setIconSize(QSize(32, 32)); @@ -20,12 +21,8 @@ LinkedButton::LinkedButton(QWidget* parent) connect(this, SIGNAL(clicked()), this, SLOT(openUrl())); } -void LinkedButton::openUrl() { - QDesktopServices::openUrl(QUrl(this->url)); -} +void LinkedButton::openUrl() { QDesktopServices::openUrl(QUrl(this->url)); } -void LinkedButton::setUrl(QString url) { - this->url = url; -} +void LinkedButton::setUrl(QString url) { this->url = url; } #include "moc_linked_button.cpp" diff --git a/gui/src/logicdatacurve.cpp b/gui/src/logicdatacurve.cpp index 9aaca910e0..24d313ddc6 100644 --- a/gui/src/logicdatacurve.cpp +++ b/gui/src/logicdatacurve.cpp @@ -18,78 +18,71 @@ * along with this program. If not, see . */ - #include "logicdatacurve.h" #include - -#include +#include #include +#include #include -#include -#include #include - -#include +#include static const QColor EdgeColor(0x80, 0x80, 0x80); static const QColor HighColor(0x00, 0xC0, 0x00); static const QColor LowColor(0xC0, 0x00, 0x00); static const QColor SamplingPointColor(0x77, 0x77, 0x77); -LogicDataCurve::LogicDataCurve(uint16_t *data, uint8_t bit) : - GenericLogicPlotCurve(QString(QString::number(bit)), QString(QString::number(bit))), - m_startSample(0), - m_endSample(0), - m_bit(bit), - m_displaySampling(false) +LogicDataCurve::LogicDataCurve(uint16_t *data, uint8_t bit) + : GenericLogicPlotCurve(QString(QString::number(bit)), QString(QString::number(bit))) + , m_startSample(0) + , m_endSample(0) + , m_bit(bit) + , m_displaySampling(false) { - // If there are no set samples, QwtPlot::replot() won't call our - // draw() method. Trick the plot into thinking that we have data - // set on our curve. + // If there are no set samples, QwtPlot::replot() won't call our + // draw() method. Trick the plot into thinking that we have data + // set on our curve. - // TODO: maybe custom plot with reimplemented replot() ? + // TODO: maybe custom plot with reimplemented replot() ? - setSamples(QVector({0.0}), QVector({0.0})); - setBrush(QBrush(Qt::black)); + setSamples(QVector({0.0}), QVector({0.0})); + setBrush(QBrush(Qt::black)); } -void LogicDataCurve::setData(uint16_t *data) -{ - m_data = data; -} +void LogicDataCurve::setData(uint16_t *data) { m_data = data; } void LogicDataCurve::dataAvailable(uint64_t from, uint64_t to, uint16_t *data) { std::unique_lock lock(m_dataAvailableMutex); - if (from == 0) { - reset(); - } + if(from == 0) { + reset(); + } - m_data = data; + m_data = data; - // Take into account the last pushed edge from the previous chunk of - // available data - uint64_t currentSample = from; - if (from > 0) { - currentSample--; - } + // Take into account the last pushed edge from the previous chunk of + // available data + uint64_t currentSample = from; + if(from > 0) { + currentSample--; + } - if (from == to) { - return; - } + if(from == to) { + return; + } - for (; currentSample < to - 1; ++currentSample) { - bool transition = (m_data[currentSample] & (1 << m_bit)) ^ (m_data[currentSample + 1] & (1 << m_bit)); - bool high = (m_data[currentSample] & (1 << m_bit)) > (m_data[currentSample + 1] & (1 << m_bit)); - if (transition) { - m_edges.emplace_back(currentSample, high); - } - } + for(; currentSample < to - 1; ++currentSample) { + bool transition = (m_data[currentSample] & (1 << m_bit)) ^ (m_data[currentSample + 1] & (1 << m_bit)); + bool high = (m_data[currentSample] & (1 << m_bit)) > (m_data[currentSample + 1] & (1 << m_bit)); + if(transition) { + m_edges.emplace_back(currentSample, high); + } + } - m_endSample = to; + m_endSample = to; } void LogicDataCurve::reset() @@ -99,133 +92,123 @@ void LogicDataCurve::reset() m_endSample = 0; } -uint8_t LogicDataCurve::getBitId() const -{ - return m_bit; -} +uint8_t LogicDataCurve::getBitId() const { return m_bit; } -void LogicDataCurve::setDisplaySampling(bool display) -{ - m_displaySampling = display; -} +void LogicDataCurve::setDisplaySampling(bool display) { m_displaySampling = display; } -void LogicDataCurve::drawLines(QPainter *painter, const QwtScaleMap &xMap, - const QwtScaleMap &yMap, const QRectF &canvasRect, - int from, int to) const +void LogicDataCurve::drawLines(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, + const QRectF &canvasRect, int from, int to) const { std::unique_lock lock(m_dataAvailableMutex); QwtPointMapper mapper; - mapper.setFlag( QwtPointMapper::RoundPoints, QwtPainter::roundingAlignment( painter ) ); + mapper.setFlag(QwtPointMapper::RoundPoints, QwtPainter::roundingAlignment(painter)); mapper.setBoundingRect(canvasRect); QVector displayedData; const double heightInPoints = yMap.invTransform(0) - yMap.invTransform(m_traceHeight); - if (!m_edges.size()) { - if (m_startSample != m_endSample) { - const bool logicLevel = (m_data[m_startSample] & (1 << m_bit)) >> m_bit; - displayedData += QPointF(fromSampleToTime(m_startSample), logicLevel * heightInPoints + m_pixelOffset); - displayedData += QPointF(fromSampleToTime(m_endSample), logicLevel * heightInPoints + m_pixelOffset); - - painter->save(); - painter->setPen(m_traceColor); + if(!m_edges.size()) { + if(m_startSample != m_endSample) { + const bool logicLevel = (m_data[m_startSample] & (1 << m_bit)) >> m_bit; + displayedData += + QPointF(fromSampleToTime(m_startSample), logicLevel * heightInPoints + m_pixelOffset); + displayedData += + QPointF(fromSampleToTime(m_endSample), logicLevel * heightInPoints + m_pixelOffset); - QwtPointSeriesData *d = new QwtPointSeriesData(displayedData); - QPolygonF polyline = mapper.toPolygonF(xMap, yMap, d, 0, displayedData.size() - 1); - QwtPainter::drawPolyline(painter, polyline); + painter->save(); + painter->setPen(m_traceColor); - painter->restore(); + QwtPointSeriesData *d = new QwtPointSeriesData(displayedData); + QPolygonF polyline = mapper.toPolygonF(xMap, yMap, d, 0, displayedData.size() - 1); + QwtPainter::drawPolyline(painter, polyline); - delete d; + painter->restore(); - } - return; - } - - std::vector> edges; - getSubsampledEdges(edges, xMap); - - - if (!edges.size()) { - return; - } + delete d; + } + return; + } - if (edges.front().first > 0) { - displayedData += QPointF(fromSampleToTime(0), edges.front().second * heightInPoints + m_pixelOffset); - } + std::vector> edges; + getSubsampledEdges(edges, xMap); - for (const auto & edge : edges) { - double y1 = edge.second * heightInPoints + m_pixelOffset; - double y2 = !edge.second * heightInPoints + m_pixelOffset; + if(!edges.size()) { + return; + } - double t1 = fromSampleToTime(edge.first); - double t2 = fromSampleToTime(edge.first + 1); + if(edges.front().first > 0) { + displayedData += QPointF(fromSampleToTime(0), edges.front().second * heightInPoints + m_pixelOffset); + } - displayedData += QPointF(t1, y1); - displayedData += QPointF(t2, y1); - displayedData += QPointF(t2, y2); - } + for(const auto &edge : edges) { + double y1 = edge.second * heightInPoints + m_pixelOffset; + double y2 = !edge.second * heightInPoints + m_pixelOffset; - if (edges.back().first + 1 < m_endSample) { - displayedData += QPointF(plot()->axisInterval(QwtAxis::XBottom).maxValue(), displayedData.back().y()); - } + double t1 = fromSampleToTime(edge.first); + double t2 = fromSampleToTime(edge.first + 1); - painter->save(); - painter->setPen(m_traceColor); + displayedData += QPointF(t1, y1); + displayedData += QPointF(t2, y1); + displayedData += QPointF(t2, y2); + } - QwtPointSeriesData *d = new QwtPointSeriesData(displayedData); - QPolygonF polyline = mapper.toPolygonF(xMap, yMap, d, 0, displayedData.size() - 1); - QwtPainter::drawPolyline(painter, polyline); + if(edges.back().first + 1 < m_endSample) { + displayedData += QPointF(plot()->axisInterval(QwtAxis::XBottom).maxValue(), displayedData.back().y()); + } - painter->restore(); + painter->save(); + painter->setPen(m_traceColor); - delete d; + QwtPointSeriesData *d = new QwtPointSeriesData(displayedData); + QPolygonF polyline = mapper.toPolygonF(xMap, yMap, d, 0, displayedData.size() - 1); + QwtPainter::drawPolyline(painter, polyline); - // Draw sampling points - // Optimize for each segment we can draw the points connecting it - // knowing from segment.second if it is "1" or "0" - double dist = xMap.transform(fromSampleToTime(1)) - xMap.transform(fromSampleToTime(0)); + painter->restore(); + delete d; - if (dist <= 4.0 || !m_displaySampling) { - return; - } + // Draw sampling points + // Optimize for each segment we can draw the points connecting it + // knowing from segment.second if it is "1" or "0" + double dist = xMap.transform(fromSampleToTime(1)) - xMap.transform(fromSampleToTime(0)); - QwtInterval interval = plot()->axisInterval(QwtAxis::XBottom); + if(dist <= 4.0 || !m_displaySampling) { + return; + } - int start = fromTimeToSample(interval.minValue()); - int end = fromTimeToSample(interval.maxValue()); + QwtInterval interval = plot()->axisInterval(QwtAxis::XBottom); - start = start < 0 ? 0 : start; - end = end > (m_endSample - 1) ? (m_endSample - 1) : end; + int start = fromTimeToSample(interval.minValue()); + int end = fromTimeToSample(interval.maxValue()); - QVector points; - for (; start <= end; ++start) { - double y = ((m_data[start] & (1 << m_bit)) >> m_bit) * heightInPoints + m_pixelOffset; - points += QPointF(fromSampleToTime(start), y); - } + start = start < 0 ? 0 : start; + end = end > (m_endSample - 1) ? (m_endSample - 1) : end; - QwtPointSeriesData *d2 = new QwtPointSeriesData(points); - QPolygonF points_poly = mapper.toPointsF(xMap, yMap, d2, 0, points.size() - 1); + QVector points; + for(; start <= end; ++start) { + double y = ((m_data[start] & (1 << m_bit)) >> m_bit) * heightInPoints + m_pixelOffset; + points += QPointF(fromSampleToTime(start), y); + } - delete d2; + QwtPointSeriesData *d2 = new QwtPointSeriesData(points); + QPolygonF points_poly = mapper.toPointsF(xMap, yMap, d2, 0, points.size() - 1); - painter->save(); + delete d2; - painter->setPen(QPen(QBrush(SamplingPointColor), 3)); - QwtPainter::drawPoints( painter, points_poly ); + painter->save(); - painter->restore(); + painter->setPen(QPen(QBrush(SamplingPointColor), 3)); + QwtPainter::drawPoints(painter, points_poly); -// qDebug() << "Drawing of points took: " << tt.elapsed(); + painter->restore(); + // qDebug() << "Drawing of points took: " << tt.elapsed(); } -void LogicDataCurve::getSubsampledEdges(std::vector> &edges, const QwtScaleMap &xMap) const { - - +void LogicDataCurve::getSubsampledEdges(std::vector> &edges, const QwtScaleMap &xMap) const +{ double dist = xMap.transform(fromSampleToTime(1)) - xMap.transform(fromSampleToTime(0)); @@ -233,27 +216,27 @@ void LogicDataCurve::getSubsampledEdges(std::vector> & uint64_t firstEdge = edgeAtX(fromTimeToSample(interval.minValue()), m_edges); uint64_t lastEdge = edgeAtX(fromTimeToSample(interval.maxValue()), m_edges); - if (firstEdge > 0) { + if(firstEdge > 0) { firstEdge--; } - if (lastEdge < m_edges.size() - 1) { + if(lastEdge < m_edges.size() - 1) { lastEdge++; } - if (m_edges.size() == 1) { // corner case + if(m_edges.size() == 1) { // corner case edges.emplace_back(m_edges.front()); return; } // If plot is zoomed in / not so many edges close together // draw them all - if (dist > 0.10) { - if (lastEdge == m_edges.size() - 1) { + if(dist > 0.10) { + if(lastEdge == m_edges.size() - 1) { lastEdge = m_edges.size(); } - for (; firstEdge < lastEdge; ++firstEdge) { + for(; firstEdge < lastEdge; ++firstEdge) { edges.emplace_back(m_edges[firstEdge]); } } else { @@ -263,27 +246,28 @@ void LogicDataCurve::getSubsampledEdges(std::vector> & // always add the first edge edges.emplace_back(m_edges[firstEdge]); - for (; firstEdge < lastEdge; ) { + for(; firstEdge < lastEdge;) { // Find the next edge that is at least "pointsPerPixel" away // from the current one - auto next = std::upper_bound(m_edges.begin(), m_edges.end(), + auto next = std::upper_bound( + m_edges.begin(), m_edges.end(), std::make_pair(edges.back().first + pointsPerPixel - 1, false), - [=](const std::pair &lhs, const std::pair &rhs) -> bool { - return lhs.first < rhs.first; - }); + [=](const std::pair &lhs, + const std::pair &rhs) -> bool { return lhs.first < rhs.first; }); bool didReachEnd = false; - if (next == m_edges.end()) { + if(next == m_edges.end()) { next = m_edges.end() - 1; didReachEnd = true; } - if (next->second == edges.back().second) { + if(next->second == edges.back().second) { std::advance(next, -1); - if (didReachEnd) { - // If the end is reached (next == last edge) and it has the same transition as the last - // edge in the "edges" vector we have to add "next - 1" and "next" to the "edges" array - // in order to have valid transition, and also plot the last edge. + if(didReachEnd) { + // If the end is reached (next == last edge) and it has the same transition as + // the last edge in the "edges" vector we have to add "next - 1" and "next" to + // the "edges" array in order to have valid transition, and also plot the last + // edge. edges.emplace_back(*next); std::advance(next, 1); edges.emplace_back(*next); @@ -298,30 +282,31 @@ void LogicDataCurve::getSubsampledEdges(std::vector> & } } -uint64_t LogicDataCurve::edgeAtX(int x, const std::vector> &edges) const { - // returns position of edge close to x value - // O(log N) +uint64_t LogicDataCurve::edgeAtX(int x, const std::vector> &edges) const +{ + // returns position of edge close to x value + // O(log N) - int64_t start = 0; - int64_t end = edges.size() - 1; + int64_t start = 0; + int64_t end = edges.size() - 1; - int64_t mid = 0; + int64_t mid = 0; - while (end >= start) { - mid = start + (end - start) / 2; + while(end >= start) { + mid = start + (end - start) / 2; - if (mid >= m_edges.size()) { -// qDebug() << "mid: " << mid << " m_edges.size():" << m_edges.size(); - } + if(mid >= m_edges.size()) { + // qDebug() << "mid: " << mid << " m_edges.size():" << m_edges.size(); + } - if (edges[mid].first < x) { - start = mid + 1; - } else if (edges[mid].first > x) { - end = mid - 1; - } else { - return mid; - } - } + if(edges[mid].first < x) { + start = mid + 1; + } else if(edges[mid].first > x) { + end = mid - 1; + } else { + return mid; + } + } - return mid; + return mid; } diff --git a/gui/src/m2kmeasure.cpp b/gui/src/m2kmeasure.cpp index acea0cc472..b4e1f9e889 100644 --- a/gui/src/m2kmeasure.cpp +++ b/gui/src/m2kmeasure.cpp @@ -19,351 +19,329 @@ */ #include "m2kmeasure.h" -#include -#include -#include + #include #include -#include +#include + +#include #include +#include using namespace scopy; namespace scopy { - class CrossPoint +class CrossPoint +{ +public: + CrossPoint(float value, size_t bufIndex, bool onRising, QString name) + : m_value(value) + , m_bufIdx(bufIndex) + , m_onRising(onRising) + , m_name(name) + + {} + +public: + float m_value; + size_t m_bufIdx; + bool m_onRising; + QString m_name; +}; + +class HystLevelCross +{ +public: + enum crossEvents { - public: - CrossPoint(float value, size_t bufIndex, bool onRising, QString name): - m_value(value), - m_bufIdx(bufIndex), - m_onRising(onRising), - m_name(name) + NO_CROSS = 0, + POS_CROSS_LOW, + POS_CROSS_HIGH, + POS_CROSS_FULL, + NEG_CROSS_LOW, + NEG_CROSS_HIGH, + NEG_CROSS_FULL, + }; + HystLevelCross() + : m_low_trhold_crossed(false) + , m_high_trhold_crossed(false) + , m_is_between_trholds(false) + {} - { - } + bool isBetweenThresholds() { return m_is_between_trholds; } - public: - float m_value; - size_t m_bufIdx; - bool m_onRising; - QString m_name; - }; + virtual inline bool updateState(enum crossEvents crsEvent) = 0; - class HystLevelCross + static inline enum crossEvents get_crossing_type(double samp, double prevSamp, double low_trhold, + double high_trhold) { - public: - enum crossEvents { - NO_CROSS = 0, - POS_CROSS_LOW, - POS_CROSS_HIGH, - POS_CROSS_FULL, - NEG_CROSS_LOW, - NEG_CROSS_HIGH, - NEG_CROSS_FULL, - }; - - HystLevelCross() : - m_low_trhold_crossed(false), - m_high_trhold_crossed(false), - m_is_between_trholds(false) - { - } - - bool isBetweenThresholds() - { - return m_is_between_trholds; + enum crossEvents cross_type = NO_CROSS; + + if(samp > prevSamp) { + if((prevSamp <= low_trhold) && (samp >= low_trhold)) + cross_type = POS_CROSS_LOW; + if((prevSamp <= high_trhold) && (samp >= high_trhold)) { + if(cross_type == POS_CROSS_LOW) + cross_type = POS_CROSS_FULL; + else + cross_type = POS_CROSS_HIGH; + } + } else if(samp < prevSamp) { + if((prevSamp >= low_trhold) && (samp <= low_trhold)) + cross_type = NEG_CROSS_LOW; + if((prevSamp >= high_trhold) && (samp <= high_trhold)) { + if(cross_type == NEG_CROSS_LOW) + cross_type = NEG_CROSS_FULL; + else + cross_type = NEG_CROSS_HIGH; + } } - virtual inline bool updateState(enum crossEvents crsEvent) = 0; - - static inline enum crossEvents - get_crossing_type(double samp, double prevSamp, - double low_trhold, double high_trhold) - { - enum crossEvents cross_type = NO_CROSS; - - if (samp > prevSamp) { - if ((prevSamp <= low_trhold) && (samp >= low_trhold)) - cross_type = POS_CROSS_LOW; - if ((prevSamp <= high_trhold) && (samp >= high_trhold)) { - if (cross_type == POS_CROSS_LOW) - cross_type = POS_CROSS_FULL; - else - cross_type = POS_CROSS_HIGH; - } - } else if (samp < prevSamp) { - if ((prevSamp >= low_trhold) && (samp <= low_trhold)) - cross_type = NEG_CROSS_LOW; - if ((prevSamp >= high_trhold) && (samp <= high_trhold)) { - if (cross_type == NEG_CROSS_LOW) - cross_type = NEG_CROSS_FULL; - else - cross_type = NEG_CROSS_HIGH; - } - } + return cross_type; + } - return cross_type; - } + void resetState() + { + m_low_trhold_crossed = false; + m_high_trhold_crossed = false; + m_is_between_trholds = false; + } - void resetState() - { - m_low_trhold_crossed = false; - m_high_trhold_crossed = false; - m_is_between_trholds = false; - } +protected: + bool m_low_trhold_crossed; + bool m_high_trhold_crossed; + bool m_is_between_trholds; +}; - protected: - bool m_low_trhold_crossed; - bool m_high_trhold_crossed; - bool m_is_between_trholds; - }; +class HystLevelPosCross : public HystLevelCross +{ +public: + HystLevelPosCross() + : HystLevelCross() + {} - class HystLevelPosCross: public HystLevelCross + inline bool updateState(enum crossEvents crsEvent) { - public: - HystLevelPosCross() : - HystLevelCross() - { - } - - inline bool updateState(enum crossEvents crsEvent) - { - bool level_crossed = false; + bool level_crossed = false; - switch (crsEvent) { - case POS_CROSS_LOW: - m_is_between_trholds = true; - break; - case POS_CROSS_HIGH: - if (m_is_between_trholds) { - level_crossed = true; - m_is_between_trholds = false; - } - break; - case POS_CROSS_FULL: + switch(crsEvent) { + case POS_CROSS_LOW: + m_is_between_trholds = true; + break; + case POS_CROSS_HIGH: + if(m_is_between_trholds) { level_crossed = true; - break; - case NEG_CROSS_LOW: m_is_between_trholds = false; - default: - break; } - - return level_crossed; + break; + case POS_CROSS_FULL: + level_crossed = true; + break; + case NEG_CROSS_LOW: + m_is_between_trholds = false; + default: + break; } - }; - class HystLevelNegCross: public HystLevelCross - { - public: - HystLevelNegCross() : - HystLevelCross() - { - } + return level_crossed; + } +}; - inline bool updateState(enum crossEvents crsEvent) - { - bool level_crossed = false; +class HystLevelNegCross : public HystLevelCross +{ +public: + HystLevelNegCross() + : HystLevelCross() + {} - switch (crsEvent) { - case NEG_CROSS_HIGH: - m_is_between_trholds = true; - break; - case NEG_CROSS_LOW: - if (m_is_between_trholds) { - level_crossed = true; - m_is_between_trholds = false; - } - break; - case NEG_CROSS_FULL: + inline bool updateState(enum crossEvents crsEvent) + { + bool level_crossed = false; + + switch(crsEvent) { + case NEG_CROSS_HIGH: + m_is_between_trholds = true; + break; + case NEG_CROSS_LOW: + if(m_is_between_trholds) { level_crossed = true; - break; - case POS_CROSS_HIGH: m_is_between_trholds = false; - default: - break; } - - return level_crossed; + break; + case NEG_CROSS_FULL: + level_crossed = true; + break; + case POS_CROSS_HIGH: + m_is_between_trholds = false; + default: + break; } - }; - class M2kCrossingDetection + return level_crossed; + } +}; + +class M2kCrossingDetection +{ +public: + M2kCrossingDetection(double level, double hysteresis_span, const QString &name) + : m_posCrossFound(false) + , m_negCrossFound(false) + , m_crossed(false) + , m_posCrossPoint(0) + , m_negCrossPoint(0) + , m_level(level) + , m_hysteresis_span(hysteresis_span) + , m_low_level(level - hysteresis_span / 2) + , m_high_level(level + hysteresis_span / 2) + , m_name(name) + , m_externList(NULL) + {} + + double level() { return m_level; } + + void setLevel(double level) { - public: - M2kCrossingDetection(double level, double hysteresis_span, - const QString &name): - m_posCrossFound(false), - m_negCrossFound(false), - m_crossed(false), - m_posCrossPoint(0), - m_negCrossPoint(0), - m_level(level), - m_hysteresis_span(hysteresis_span), - m_low_level(level - hysteresis_span / 2), - m_high_level(level + hysteresis_span / 2), - m_name(name), - m_externList(NULL) - { + if(m_level != level) { + m_level = level; + m_low_level = level - m_hysteresis_span / 2; + m_high_level = level + m_hysteresis_span / 2; } + } - double level() - { - return m_level; - } + double hysteresisSpan() { return m_hysteresis_span; } - void setLevel(double level) - { - if (m_level != level) { - m_level = level; - m_low_level = level - m_hysteresis_span / 2; - m_high_level = level + m_hysteresis_span / 2; - } - } - - double hysteresisSpan() - { - return m_hysteresis_span; + void setHysteresisSpan(double span) + { + if(m_hysteresis_span != span) { + m_hysteresis_span = span; + m_low_level = m_level - span / 2; + m_high_level = m_level + span / 2; } + } - void setHysteresisSpan(double span) - { - if (m_hysteresis_span != span) { - m_hysteresis_span = span; - m_low_level = m_level - span / 2; - m_high_level = m_level + span / 2; - } - } + void setExternalList(QList *externList) { m_externList = externList; } - void setExternalList(QList *externList) - { - m_externList = externList; - } + QList detectedCrossings() { return m_detectedCrossings; } - QList detectedCrossings() - { - return m_detectedCrossings; + inline void store_closest_val_to_cross_lvl(double *data, size_t i, size_t &point) + { + double diff1 = qAbs(data[i - 1] - m_level); + double diff2 = qAbs(data[i] - m_level); + double diff; + size_t idx; + + if(diff1 < diff2) { + idx = i - 1; + diff = diff1; + } else { + idx = i; + diff = diff2; } - inline void store_closest_val_to_cross_lvl(double *data, size_t i, size_t &point) - { - double diff1 = qAbs(data[i - 1] - m_level); - double diff2 = qAbs(data[i] - m_level); - double diff; - size_t idx; - - if (diff1 < diff2) { - idx = i - 1; - diff = diff1; - } else { - idx = i; - diff = diff2; - } - - double old_diff = qAbs(data[point] - m_level); - if (diff < old_diff) - point = idx; - } + double old_diff = qAbs(data[point] - m_level); + if(diff < old_diff) + point = idx; + } - inline void store_first_closest_val_to_cross_lvl(double *data, size_t i, size_t &point) - { - double diff1 = qAbs(data[i - 1] - m_level); - double diff2 = qAbs(data[i] - m_level); + inline void store_first_closest_val_to_cross_lvl(double *data, size_t i, size_t &point) + { + double diff1 = qAbs(data[i - 1] - m_level); + double diff2 = qAbs(data[i] - m_level); - if (diff1 < diff2) - point = i - 1; - else - point = i; - } + if(diff1 < diff2) + point = i - 1; + else + point = i; + } - inline void crossDetectStep(double *data, size_t i) - { - auto cross_type = HystLevelCross::get_crossing_type(data[i], - data[i - 1], m_low_level, m_high_level); - - if (m_posCross.isBetweenThresholds()) - store_closest_val_to_cross_lvl(data, i, m_posCrossPoint); - if (m_negCross.isBetweenThresholds()) - store_closest_val_to_cross_lvl(data, i, m_negCrossPoint); - - if (cross_type != HystLevelCross::NO_CROSS) { - if (!m_posCrossFound) { - bool old_between_thresh = m_posCross.isBetweenThresholds(); - m_crossed = m_posCross.updateState(cross_type); - if (!old_between_thresh && m_posCross.isBetweenThresholds()) - store_first_closest_val_to_cross_lvl(data, i, m_posCrossPoint); - - if (m_crossed) { - m_posCrossFound = true; - m_negCrossFound = false; - m_negCross.resetState(); - if (cross_type == HystLevelCross::POS_CROSS_FULL) - m_posCrossPoint = i; - m_detectedCrossings.push_back( - CrossPoint(data[m_posCrossPoint], m_posCrossPoint, - true, m_name + "R")); - if (m_externList) - m_externList->push_back(m_detectedCrossings.last()); - } + inline void crossDetectStep(double *data, size_t i) + { + auto cross_type = HystLevelCross::get_crossing_type(data[i], data[i - 1], m_low_level, m_high_level); + + if(m_posCross.isBetweenThresholds()) + store_closest_val_to_cross_lvl(data, i, m_posCrossPoint); + if(m_negCross.isBetweenThresholds()) + store_closest_val_to_cross_lvl(data, i, m_negCrossPoint); + + if(cross_type != HystLevelCross::NO_CROSS) { + if(!m_posCrossFound) { + bool old_between_thresh = m_posCross.isBetweenThresholds(); + m_crossed = m_posCross.updateState(cross_type); + if(!old_between_thresh && m_posCross.isBetweenThresholds()) + store_first_closest_val_to_cross_lvl(data, i, m_posCrossPoint); + + if(m_crossed) { + m_posCrossFound = true; + m_negCrossFound = false; + m_negCross.resetState(); + if(cross_type == HystLevelCross::POS_CROSS_FULL) + m_posCrossPoint = i; + m_detectedCrossings.push_back( + CrossPoint(data[m_posCrossPoint], m_posCrossPoint, true, m_name + "R")); + if(m_externList) + m_externList->push_back(m_detectedCrossings.last()); } - if (!m_negCrossFound) { - bool old_between_thresh = m_negCross.isBetweenThresholds(); - m_crossed = m_negCross.updateState(cross_type); - if (!old_between_thresh && m_negCross.isBetweenThresholds()) - store_first_closest_val_to_cross_lvl(data, i, m_negCrossPoint); - if (m_crossed) { - m_negCrossFound = true; - m_posCrossFound = false; - m_posCross.resetState(); - if (cross_type == HystLevelCross::NEG_CROSS_FULL) - m_negCrossPoint = i - 1; - m_detectedCrossings.push_back( - CrossPoint(data[m_negCrossPoint], m_negCrossPoint, - false, m_name + "F")); - if (m_externList) - m_externList->push_back(m_detectedCrossings.last()); - } + } + if(!m_negCrossFound) { + bool old_between_thresh = m_negCross.isBetweenThresholds(); + m_crossed = m_negCross.updateState(cross_type); + if(!old_between_thresh && m_negCross.isBetweenThresholds()) + store_first_closest_val_to_cross_lvl(data, i, m_negCrossPoint); + if(m_crossed) { + m_negCrossFound = true; + m_posCrossFound = false; + m_posCross.resetState(); + if(cross_type == HystLevelCross::NEG_CROSS_FULL) + m_negCrossPoint = i - 1; + m_detectedCrossings.push_back(CrossPoint(data[m_negCrossPoint], m_negCrossPoint, + false, m_name + "F")); + if(m_externList) + m_externList->push_back(m_detectedCrossings.last()); } } } + } - private: - HystLevelPosCross m_posCross; - HystLevelNegCross m_negCross; +private: + HystLevelPosCross m_posCross; + HystLevelNegCross m_negCross; - bool m_posCrossFound; - bool m_negCrossFound; - bool m_crossed; + bool m_posCrossFound; + bool m_negCrossFound; + bool m_crossed; - double m_level; - double m_hysteresis_span; - double m_low_level; - double m_high_level; + double m_level; + double m_hysteresis_span; + double m_low_level; + double m_high_level; - size_t m_posCrossPoint; - size_t m_negCrossPoint; + size_t m_posCrossPoint; + size_t m_negCrossPoint; - QList m_detectedCrossings; - QList *m_externList; + QList m_detectedCrossings; + QList *m_externList; - QString m_name; - }; + QString m_name; +}; - class SpectralDetection { - public: - SpectralDetection(double *data, ssize_t data_length, int harmonics_number): - m_data(data), - m_data_length(data_length), - m_harmonics_number(harmonics_number) - { - } - - void calculateSpectralDetectionParameters(double &spur, double &harm_dist, double &noise, - double &average_noise, double &signal) { - struct harmonic_tuple { - double harm_value; - int harm_bin; +class SpectralDetection +{ +public: + SpectralDetection(double *data, ssize_t data_length, int harmonics_number) + : m_data(data) + , m_data_length(data_length) + , m_harmonics_number(harmonics_number) + {} + + void calculateSpectralDetectionParameters(double &spur, double &harm_dist, double &noise, double &average_noise, + double &signal) + { + struct harmonic_tuple + { + double harm_value; + int harm_bin; }; findHarmonics(m_harmonics_number); @@ -372,7 +350,7 @@ namespace scopy { findSpur(spur, spur_bw, false, m_harmonic_bins[0]); if(m_mask.empty()) - m_mask = calculateAutoMask(); + m_mask = calculateAutoMask(); int noise_bins; maskedSumOfSquares(noise_bins, noise, m_mask); @@ -380,33 +358,31 @@ namespace scopy { noise = average_noise * (m_data_length - 1); std::map harmonic; - for(int i = 0; i < m_harmonics_number; i++) - { - struct harmonic_tuple harm; - harm.harm_bin = m_harmonic_bins[i]; - harm.harm_value = m_harmonics[i]; - harm.harm_value -= average_noise * m_harmonic_bw[i]; - harmonic[i+1] = harm; + for(int i = 0; i < m_harmonics_number; i++) { + struct harmonic_tuple harm; + harm.harm_bin = m_harmonic_bins[i]; + harm.harm_value = m_harmonics[i]; + harm.harm_value -= average_noise * m_harmonic_bw[i]; + harmonic[i + 1] = harm; } spur -= average_noise * spur_bw; signal = harmonic[1].harm_value; - harm_dist = harmonic[2].harm_value + harmonic[3].harm_value + - harmonic[4].harm_value + harmonic[5].harm_value; - - } - - private: + harm_dist = harmonic[2].harm_value + harmonic[3].harm_value + harmonic[4].harm_value + + harmonic[5].harm_value; + } - std::vector calculateAutoMask() { +private: + std::vector calculateAutoMask() + { const int BANDWIDTH_DIVIDER = 80; const int NUM_INITAL_NOISE_HARMS = 5; int bw = int(m_data_length / BANDWIDTH_DIVIDER); std::vector mask; mask.resize(m_data_length, 1); - for (int i = 0; i < NUM_INITAL_NOISE_HARMS; i++) + for(int i = 0; i < NUM_INITAL_NOISE_HARMS; i++) clearMask(mask, m_harmonic_bins[i] - bw, m_harmonic_bins[i] + bw); mask[0] = 0; @@ -415,154 +391,135 @@ namespace scopy { maskedSum(noise_bins, noise_est, mask); noise_est /= noise_bins; - std::fill(mask.begin(), mask.end(), 1); - //clear mask la dc. - clearMask(mask, 0, 1); - int j; - int low, high; - - double sum; - - for(size_t i = 0; i < m_harmonic_bins.size(); i++) - { - int h = m_harmonic_bins.at(i); - if(mask[h] == 0) - continue; - j = 1; - sum = 0.0F; - for(int s = h-j; s < h-j+3; s++) - { - sum += m_data[s]; - } - sum /= 3; - while ( h - j > 0 && mask[h-j] == 1 && - sum > noise_est ) { - j++; - sum = 0.0F; - for(int s = h-j; s < h-j+3; s++) - { - sum += m_data[s]; - } - sum /= 3; - } - low = h - j + 1; - - j = 1; - sum = 0.0F; - for(int s = h+j-2; s < h+j+1; s++) - { - sum += m_data[s]; - } - sum /= 3; - while ( h + j < m_data_length && mask[h+j] == 1 && - sum > noise_est ) { - j++; - sum = 0.0F; - for(int s = h+j-2; s < h+j+1; s++) - { - sum += m_data[s]; - } - sum /= 3; - } - high = h + j - 1; - clearMask(mask, low, high); - } + std::fill(mask.begin(), mask.end(), 1); + // clear mask la dc. + clearMask(mask, 0, 1); + int j; + int low, high; + + double sum; + + for(size_t i = 0; i < m_harmonic_bins.size(); i++) { + int h = m_harmonic_bins.at(i); + if(mask[h] == 0) + continue; + j = 1; + sum = 0.0F; + for(int s = h - j; s < h - j + 3; s++) { + sum += m_data[s]; + } + sum /= 3; + while(h - j > 0 && mask[h - j] == 1 && sum > noise_est) { + j++; + sum = 0.0F; + for(int s = h - j; s < h - j + 3; s++) { + sum += m_data[s]; + } + sum /= 3; + } + low = h - j + 1; + + j = 1; + sum = 0.0F; + for(int s = h + j - 2; s < h + j + 1; s++) { + sum += m_data[s]; + } + sum /= 3; + while(h + j < m_data_length && mask[h + j] == 1 && sum > noise_est) { + j++; + sum = 0.0F; + for(int s = h + j - 2; s < h + j + 1; s++) { + sum += m_data[s]; + } + sum /= 3; + } + high = h + j - 1; + clearMask(mask, low, high); + } return mask; - } + } - void setMask(std::vector &mask, int start, int end, int value) - { + void setMask(std::vector &mask, int start, int end, int value) + { int nyq = mask.size(); int n = 2 * (nyq - 1); std::vector indices; - for(int i = start; i <= end; i++) - { - int index_value = (i + n) % n; - if (index_value > nyq) - index_value = n - index_value; - indices.push_back(index_value); + for(int i = start; i <= end; i++) { + int index_value = (i + n) % n; + if(index_value > nyq) + index_value = n - index_value; + indices.push_back(index_value); } - for(std::vector::iterator it = indices.begin(); it != indices.end(); ++it) - { - mask.at(*it) = value; + for(std::vector::iterator it = indices.begin(); it != indices.end(); ++it) { + mask.at(*it) = value; } - } + } - void clearMask(std::vector &mask, int start, int end) - { - setMask(mask, start, end, 0); - } + void clearMask(std::vector &mask, int start, int end) { setMask(mask, start, end, 0); } - void maskedSubset(std::vector &indices, std::vector &new_mask, std::vector mask, int start, int end) - { + void maskedSubset(std::vector &indices, std::vector &new_mask, std::vector mask, int start, + int end) + { int nyq = mask.size(); int n = 2 * (nyq - 1); std::vector mapped_subset; - for(int i = start; i < end; i++) - { - int index_value = (i + n) % n; - if (index_value > nyq) - index_value = n - index_value; - mapped_subset.push_back(index_value); + for(int i = start; i < end; i++) { + int index_value = (i + n) % n; + if(index_value > nyq) + index_value = n - index_value; + mapped_subset.push_back(index_value); } - for(size_t i = 0; i < mapped_subset.size(); i++) - { - if(mask.at(mapped_subset.at(i)) == 1) - { - indices.push_back(mapped_subset.at(i)); - new_mask.push_back(mask.at(mapped_subset.at(i))); - } - + for(size_t i = 0; i < mapped_subset.size(); i++) { + if(mask.at(mapped_subset.at(i)) == 1) { + indices.push_back(mapped_subset.at(i)); + new_mask.push_back(mask.at(mapped_subset.at(i))); + } } - } - - void maskedSumOfSquares(int &index, double &value, std::vector mask, int start = 0, int end = 0) - { - if(end == 0 || end >= m_data_length) - end = m_data_length - 1; - - std::vector indices; - std::vector new_mask; - maskedSubset(indices, new_mask, mask, start, end); - double sum = 0; + } + void maskedSumOfSquares(int &index, double &value, std::vector mask, int start = 0, int end = 0) + { + if(end == 0 || end >= m_data_length) + end = m_data_length - 1; - for(std::vector::iterator it = indices.begin(); it != indices.end(); ++it) - { - sum = sum + (m_data[*it] * m_data[*it]); - } + std::vector indices; + std::vector new_mask; + maskedSubset(indices, new_mask, mask, start, end); + double sum = 0; - index = indices.size(); - value = sum; - } + for(std::vector::iterator it = indices.begin(); it != indices.end(); ++it) { + sum = sum + (m_data[*it] * m_data[*it]); + } - void maskedSum(int &index, double &value, std::vector mask, int start = 0, int end = 0) - { - if(end == 0 || end >= m_data_length) - end = m_data_length - 1; + index = indices.size(); + value = sum; + } - std::vector indices; - std::vector new_mask; - maskedSubset(indices, new_mask, mask, start, end); - double sum = 0; + void maskedSum(int &index, double &value, std::vector mask, int start = 0, int end = 0) + { + if(end == 0 || end >= m_data_length) + end = m_data_length - 1; + std::vector indices; + std::vector new_mask; + maskedSubset(indices, new_mask, mask, start, end); + double sum = 0; - for(std::vector::iterator it = indices.begin(); it != indices.end(); ++it) - { - sum = sum + (m_data[*it]); - } + for(std::vector::iterator it = indices.begin(); it != indices.end(); ++it) { + sum = sum + (m_data[*it]); + } - index = indices.size(); - value = sum; - } + index = indices.size(); + value = sum; + } - void maskedMax(int &index, double &value, std::vector mask, int start = 0, int end = 0) - { + void maskedMax(int &index, double &value, std::vector mask, int start = 0, int end = 0) + { if(end == 0) - end = m_data_length - 1; + end = m_data_length - 1; double *data_at_index = new double[end](); double data_at_index_size; @@ -570,36 +527,33 @@ namespace scopy { std::vector new_mask; maskedSubset(indices, new_mask, mask, start, end); - for(size_t i=0; i value) - { - index = i; - value = data[i]; - } + for(int i = 0; i < size; i++) { + if(data[i] > value) { + index = i; + value = data[i]; + } } - } + } - void findHarmonics(int max_harmonics) - { + void findHarmonics(int max_harmonics) + { m_harmonic_bins.resize(max_harmonics); m_harmonic_bw.resize(max_harmonics); m_harmonics.resize(max_harmonics); @@ -608,74 +562,66 @@ namespace scopy { std::fill(m_harmonic_bw.begin(), m_harmonic_bw.end(), 0); std::fill(m_harmonics.begin(), m_harmonics.end(), 0.0); - //find the fundamental bin (max value) from the data + // find the fundamental bin (max value) from the data int fund_bin = 0; double max = 0; getMax(m_data, m_data_length, fund_bin, max); m_harmonic_bins.at(0) = fund_bin; - for(int h = 1; h < max_harmonics + 1; h++) - { - std::vector mask; - mask.resize(m_data_length, 0); - - int nominal_bin = h * fund_bin; - int h_2 = static_cast(h / 2); - if(h > 1) - { - setMask(mask, nominal_bin - h_2, nominal_bin + h_2, 1); - for(int i = 0; i < h - 1; i++) - { - clearMask(mask, m_harmonic_bins.at(i), m_harmonic_bins.at(i)); - } - int index; - double value; - maskedMax(index, value, mask); - m_harmonic_bins.at(h-1) = index; - } - clearMask(mask, nominal_bin - h_2, nominal_bin + h_2); - setMask(mask, m_harmonic_bins.at(h-1) - BW, m_harmonic_bins.at(h-1) + BW, 1); - for(int i = 0; i < h - 1; i++) - { - clearMask(mask, m_harmonic_bins.at(i) - BW, m_harmonic_bins.at(i) + BW); - } - double val_harm; - int val_hbws; - maskedSumOfSquares(val_hbws, val_harm, mask); - m_harmonics[h-1] = val_harm; - m_harmonic_bw[h-1] = val_hbws; + for(int h = 1; h < max_harmonics + 1; h++) { + std::vector mask; + mask.resize(m_data_length, 0); + int nominal_bin = h * fund_bin; + int h_2 = static_cast(h / 2); + if(h > 1) { + setMask(mask, nominal_bin - h_2, nominal_bin + h_2, 1); + for(int i = 0; i < h - 1; i++) { + clearMask(mask, m_harmonic_bins.at(i), m_harmonic_bins.at(i)); + } + int index; + double value; + maskedMax(index, value, mask); + m_harmonic_bins.at(h - 1) = index; + } + clearMask(mask, nominal_bin - h_2, nominal_bin + h_2); + setMask(mask, m_harmonic_bins.at(h - 1) - BW, m_harmonic_bins.at(h - 1) + BW, 1); + for(int i = 0; i < h - 1; i++) { + clearMask(mask, m_harmonic_bins.at(i) - BW, m_harmonic_bins.at(i) + BW); + } + double val_harm; + int val_hbws; + maskedSumOfSquares(val_hbws, val_harm, mask); + m_harmonics[h - 1] = val_harm; + m_harmonic_bw[h - 1] = val_hbws; } + } - } - - void findSpur(double &spur, int& spur_bw, bool find_in_harmonics, int fund_bin) { + void findSpur(double &spur, int &spur_bw, bool find_in_harmonics, int fund_bin) + { if(find_in_harmonics == true) { - int index = std::max_element(m_harmonics.begin() + 1, m_harmonics.end()) - m_harmonics.begin(); - spur = *std::max_element(m_harmonics.begin() + 1, m_harmonics.end()); - spur_bw = m_harmonic_bw[index + 1]; - } - else - { - findSpurInData(spur, spur_bw, fund_bin); + int index = std::max_element(m_harmonics.begin() + 1, m_harmonics.end()) - m_harmonics.begin(); + spur = *std::max_element(m_harmonics.begin() + 1, m_harmonics.end()); + spur_bw = m_harmonic_bw[index + 1]; + } else { + findSpurInData(spur, spur_bw, fund_bin); } - } + } - void findSpurInData(double &spur, int& spur_bw, int fund_bin) { + void findSpurInData(double &spur, int &spur_bw, int fund_bin) + { std::vector mask; mask.resize(m_data_length, 1); - //clear mask la dc. + // clear mask la dc. clearMask(mask, 0, 1); clearMask(mask, fund_bin - BW, fund_bin + BW); int index = 0; - for(size_t i = 0; i < mask.size(); i++) - { - if(mask.at(i) == 1) - { - index = i; - break; - } + for(size_t i = 0; i < mask.size(); i++) { + if(mask.at(i) == 1) { + index = i; + break; + } } double max_value; int max_index; @@ -684,134 +630,127 @@ namespace scopy { int masked_index = 0; double value; - while(index < m_data_length) - { - if(mask.at(index) == 1) - { - maskedSumOfSquares(masked_index, value, mask, index - BW, index + BW); - if(value > max_value) - { - max_value = value; - max_index = index; + while(index < m_data_length) { + if(mask.at(index) == 1) { + maskedSumOfSquares(masked_index, value, mask, index - BW, index + BW); + if(value > max_value) { + max_value = value; + max_index = index; + } } - } - index++; + index++; } int spur_bin; double spur_value; maskedMax(spur_bin, spur_value, mask, max_index - BW, max_index + BW); maskedSumOfSquares(spur_bw, spur, mask, spur_bin - BW, spur_bin + BW); - } - - private: - double *m_data; - ssize_t m_data_length; + } - const int BW = 3; - std::vector m_harmonic_bins; - std::vector m_harmonic_bw; - std::vector m_harmonics; - int m_harmonics_number; - std::vector m_mask; +private: + double *m_data; + ssize_t m_data_length; - }; -} + const int BW = 3; + std::vector m_harmonic_bins; + std::vector m_harmonic_bw; + std::vector m_harmonics; + int m_harmonics_number; + std::vector m_mask; +}; +} // namespace scopy M2kMeasure::M2kMeasure(int channel, double *buffer, size_t length, - const std::function &conversion_fct, bool isTimeDomain): - m_channel(channel), - m_buffer(buffer), - m_buf_length(length), - m_sample_rate(1.0), - m_adc_bit_count(0), - m_cross_level(0), - m_hysteresis_span(0), - m_histogram(nullptr), - m_cross_detect(nullptr), - m_gatingEnabled(false), - m_conversion_function(conversion_fct), - m_isTimeDomain(isTimeDomain), - m_harmonics_number(5) + const std::function &conversion_fct, bool isTimeDomain) + : m_channel(channel) + , m_buffer(buffer) + , m_buf_length(length) + , m_sample_rate(1.0) + , m_adc_bit_count(0) + , m_cross_level(0) + , m_hysteresis_span(0) + , m_histogram(nullptr) + , m_cross_detect(nullptr) + , m_gatingEnabled(false) + , m_conversion_function(conversion_fct) + , m_isTimeDomain(isTimeDomain) + , m_harmonics_number(5) { if(m_isTimeDomain) { // Create a set of measurements - m_measurements.push_back(std::make_shared(QObject::tr("Period"), - M2kMeasurementData::HORIZONTAL, "s", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("Frequency"), - M2kMeasurementData::HORIZONTAL, "Hz", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("Min"), - M2kMeasurementData::VERTICAL, "V", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("Max"), - M2kMeasurementData::VERTICAL, "V", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("Peak-peak"), - M2kMeasurementData::VERTICAL, "V", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("Mean"), - M2kMeasurementData::VERTICAL, "V", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("Cycle Mean"), - M2kMeasurementData::VERTICAL, "V", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("RMS"), - M2kMeasurementData::VERTICAL, "V", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("Cycle RMS"), - M2kMeasurementData::VERTICAL, "V", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("AC RMS"), - M2kMeasurementData::VERTICAL, "V", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("Area"), - M2kMeasurementData::VERTICAL, "Vs", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("Cycle Area"), - M2kMeasurementData::VERTICAL, "Vs", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("Low"), - M2kMeasurementData::VERTICAL, "V", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("High"), - M2kMeasurementData::VERTICAL, "V", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("Amplitude"), - M2kMeasurementData::VERTICAL, "V", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("Middle"), - M2kMeasurementData::VERTICAL, "V", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("+Over"), - M2kMeasurementData::VERTICAL, "%", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("-Over"), - M2kMeasurementData::VERTICAL, "%", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("Rise"), - M2kMeasurementData::HORIZONTAL, "s", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("Fall"), - M2kMeasurementData::HORIZONTAL, "s", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("+Width"), - M2kMeasurementData::HORIZONTAL, "s", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("-Width"), - M2kMeasurementData::HORIZONTAL, "s", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("+Duty"), - M2kMeasurementData::HORIZONTAL, "%", channel)); - m_measurements.push_back(std::make_shared(QObject::tr("-Duty"), - M2kMeasurementData::HORIZONTAL, "%", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("Period"), M2kMeasurementData::HORIZONTAL, "s", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("Frequency"), M2kMeasurementData::HORIZONTAL, "Hz", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("Min"), M2kMeasurementData::VERTICAL, "V", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("Max"), M2kMeasurementData::VERTICAL, "V", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("Peak-peak"), M2kMeasurementData::VERTICAL, "V", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("Mean"), M2kMeasurementData::VERTICAL, "V", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("Cycle Mean"), M2kMeasurementData::VERTICAL, "V", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("RMS"), M2kMeasurementData::VERTICAL, "V", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("Cycle RMS"), M2kMeasurementData::VERTICAL, "V", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("AC RMS"), M2kMeasurementData::VERTICAL, "V", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("Area"), M2kMeasurementData::VERTICAL, "Vs", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("Cycle Area"), M2kMeasurementData::VERTICAL, "Vs", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("Low"), M2kMeasurementData::VERTICAL, "V", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("High"), M2kMeasurementData::VERTICAL, "V", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("Amplitude"), M2kMeasurementData::VERTICAL, "V", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("Middle"), M2kMeasurementData::VERTICAL, "V", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("+Over"), M2kMeasurementData::VERTICAL, "%", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("-Over"), M2kMeasurementData::VERTICAL, "%", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("Rise"), M2kMeasurementData::HORIZONTAL, "s", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("Fall"), M2kMeasurementData::HORIZONTAL, "s", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("+Width"), M2kMeasurementData::HORIZONTAL, "s", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("-Width"), M2kMeasurementData::HORIZONTAL, "s", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("+Duty"), M2kMeasurementData::HORIZONTAL, "%", channel)); + m_measurements.push_back(std::make_shared( + QObject::tr("-Duty"), M2kMeasurementData::HORIZONTAL, "%", channel)); } else { - //Spectral Measurements - m_measurements.push_back(std::make_shared("Noise_Floor", - M2kMeasurementData::HORIZONTAL_F, "dB", channel)); - m_measurements.push_back(std::make_shared("SINAD", - M2kMeasurementData::HORIZONTAL_F, "dB", channel)); - m_measurements.push_back(std::make_shared("SNR", - M2kMeasurementData::HORIZONTAL_F, "dB", channel)); - m_measurements.push_back(std::make_shared("THD", - M2kMeasurementData::HORIZONTAL_F, "dB", channel)); - m_measurements.push_back(std::make_shared("THDN", - M2kMeasurementData::HORIZONTAL_F, "dB", channel)); - m_measurements.push_back(std::make_shared("SFDR", - M2kMeasurementData::VERTICAL_F, "dBc", channel)); + // Spectral Measurements + m_measurements.push_back(std::make_shared( + "Noise_Floor", M2kMeasurementData::HORIZONTAL_F, "dB", channel)); + m_measurements.push_back( + std::make_shared("SINAD", M2kMeasurementData::HORIZONTAL_F, "dB", channel)); + m_measurements.push_back( + std::make_shared("SNR", M2kMeasurementData::HORIZONTAL_F, "dB", channel)); + m_measurements.push_back( + std::make_shared("THD", M2kMeasurementData::HORIZONTAL_F, "dB", channel)); + m_measurements.push_back( + std::make_shared("THDN", M2kMeasurementData::HORIZONTAL_F, "dB", channel)); + m_measurements.push_back( + std::make_shared("SFDR", M2kMeasurementData::VERTICAL_F, "dBc", channel)); } - } void M2kMeasure::setConversionFunction(const std::function &fp) { m_conversion_function = fp; - } -bool M2kMeasure::highLowFromHistogram(double &low, double &high, - double min, double max) +bool M2kMeasure::highLowFromHistogram(double &low, double &high, double min, double max) { bool success = false; int *hist = m_histogram; @@ -820,7 +759,7 @@ bool M2kMeasure::highLowFromHistogram(double &low, double &high, int minRaw = min; int maxRaw = max; - if (m_conversion_function) { + if(m_conversion_function) { minRaw = m_conversion_function(m_channel, min, false); maxRaw = m_conversion_function(m_channel, max, false); } @@ -828,7 +767,7 @@ bool M2kMeasure::highLowFromHistogram(double &low, double &high, minRaw += hlf_scale; maxRaw += hlf_scale; - int middleRaw = minRaw + (maxRaw - minRaw) / 2; + int middleRaw = minRaw + (maxRaw - minRaw) / 2; auto lowIt = std::max_element(hist + minRaw, hist + middleRaw + 1); int lowRaw = std::distance(hist, lowIt); @@ -840,12 +779,11 @@ bool M2kMeasure::highLowFromHistogram(double &low, double &high, clearly identified (weight of a level should be 5 times greater than a peak weight - there probably is a better method) */ - if (hist[lowRaw] / 5.0 >= hist[minRaw] && - hist[highRaw] / 5.0 >= hist[maxRaw]) { + if(hist[lowRaw] / 5.0 >= hist[minRaw] && hist[highRaw] / 5.0 >= hist[maxRaw]) { int lowTmp = lowRaw - hlf_scale; int highTmp = highRaw - hlf_scale; - if (m_conversion_function) { + if(m_conversion_function) { low = m_conversion_function(m_channel, lowTmp, true); high = m_conversion_function(m_channel, highTmp, true); } @@ -857,7 +795,7 @@ bool M2kMeasure::highLowFromHistogram(double &low, double &high, void M2kMeasure::clearMeasurements() { - for (int i = 0; i < m_measurements.size(); i++) + for(int i = 0; i < m_measurements.size(); i++) m_measurements[i]->setMeasured(false); } @@ -871,7 +809,7 @@ void M2kMeasure::measure() { clearMeasurements(); - if (!m_buffer || m_buf_length == 0) + if(!m_buffer || m_buf_length == 0) return; if(m_isTimeDomain) { @@ -921,17 +859,17 @@ void M2kMeasure::measureTimeDomain() int startIndex; int endIndex; - if (qIsNaN(data[0])) { + if(qIsNaN(data[0])) { return; } - //if gating is enabled measure only on data between the gates - if(m_gatingEnabled){ - //make sure that start/end indexes are valid - if(m_startIndex < 0 || m_startIndex > m_buf_length){ + // if gating is enabled measure only on data between the gates + if(m_gatingEnabled) { + // make sure that start/end indexes are valid + if(m_startIndex < 0 || m_startIndex > m_buf_length) { m_startIndex = 0; } - if(m_endIndex < 0 || m_endIndex > m_buf_length ){ + if(m_endIndex < 0 || m_endIndex > m_buf_length) { m_endIndex = m_buf_length; } @@ -939,12 +877,11 @@ void M2kMeasure::measureTimeDomain() min = data[m_startIndex]; sum = data[m_startIndex]; sqr_sum = data[m_startIndex] * data[m_startIndex]; - startIndex = m_startIndex+1; + startIndex = m_startIndex + 1; endIndex = m_endIndex; count = (m_endIndex - m_startIndex) ?: 1; - } - else{ + } else { max = data[0]; min = data[0]; sum = data[0]; @@ -953,14 +890,13 @@ void M2kMeasure::measureTimeDomain() endIndex = data_length; } - m_cross_detect = new M2kCrossingDetection(m_cross_level, m_hysteresis_span, - "P"); - if (using_histogram_method) + m_cross_detect = new M2kCrossingDetection(m_cross_level, m_hysteresis_span, "P"); + if(using_histogram_method) m_histogram = new int[adc_span]{}; - for (ssize_t i = startIndex; i < endIndex; i++) { + for(ssize_t i = startIndex; i < endIndex; i++) { - if (qIsNaN(data[i])) { + if(qIsNaN(data[i])) { count--; continue; } @@ -968,12 +904,12 @@ void M2kMeasure::measureTimeDomain() m_cross_detect->crossDetectStep(data, i); // Min - if (data[i] < min) { + if(data[i] < min) { min = data[i]; } // Max - if (data[i] > max) { + if(data[i] > max) { max = data[i]; } @@ -984,15 +920,15 @@ void M2kMeasure::measureTimeDomain() sqr_sum += data[i] * data[i]; // Build histogram - if (using_histogram_method) { + if(using_histogram_method) { double rawTmp = data[i]; int raw = 0; - if (m_conversion_function) { + if(m_conversion_function) { raw = (int)m_conversion_function(m_channel, rawTmp, false); } raw += hlf_scale; - if (raw >= 0 && raw < adc_span) + if(raw >= 0 && raw < adc_span) m_histogram[raw] += 1; } } @@ -1013,15 +949,14 @@ void M2kMeasure::measureTimeDomain() m_measurements[RMS]->setValue(rms); // AC RMS - rms_ac = sqrt((sqr_sum - 2 * mean * sum + - count * mean * mean) / count); + rms_ac = sqrt((sqr_sum - 2 * mean * sum + count * mean * mean) / count); m_measurements[AC_RMS]->setValue(rms_ac); low = min; high = max; // Try to use Histogram method - if (using_histogram_method) + if(using_histogram_method) highLowFromHistogram(low, high, min, max); // Low, High, Middle, Amplitude, Overshoot positive/negative @@ -1040,7 +975,7 @@ void M2kMeasure::measureTimeDomain() overshoot_n = (low - min) / amplitude * 100; m_measurements[N_OVER]->setValue(overshoot_n); - if (m_histogram != NULL) { + if(m_histogram != NULL) { delete[] m_histogram; m_histogram = NULL; } @@ -1048,28 +983,25 @@ void M2kMeasure::measureTimeDomain() // Find Period / Frequency QList periodPoints = m_cross_detect->detectedCrossings(); int n = periodPoints.size(); - if (n > 2) { + if(n > 2) { double sample_period; double first_hlf_cycl = 0; double secnd_hlf_cycl = 0; int j = 0; int k = 0; - for (int i = 0; i < n - 1; i++) { - size_t diff = periodPoints[i + 1].m_bufIdx - - periodPoints[i].m_bufIdx; - if (i % 2) { + for(int i = 0; i < n - 1; i++) { + size_t diff = periodPoints[i + 1].m_bufIdx - periodPoints[i].m_bufIdx; + if(i % 2) { secnd_hlf_cycl += diff; j++; - } - else { + } else { first_hlf_cycl += diff; k++; - } + } } - sample_period = first_hlf_cycl / (n / 2) + - secnd_hlf_cycl / ((n + 1) / 2 - 1); + sample_period = first_hlf_cycl / (n / 2) + secnd_hlf_cycl / ((n + 1) / 2 - 1); period = sample_period * (1 / m_sample_rate); m_measurements[PERIOD]->setValue(period); @@ -1097,40 +1029,39 @@ void M2kMeasure::measureTimeDomain() double period_sum = data[period_start]; double period_sqr_sum = data[period_start] * data[period_start]; - for (size_t i = period_start + 1; i <= period_start + 2 * length; i++) { - size_t idx = period_start + (i % length); + for(size_t i = period_start + 1; i <= period_start + 2 * length; i++) { + size_t idx = period_start + (i % length); cdLow.crossDetectStep(data, idx); cdMid.crossDetectStep(data, idx); cdHigh.crossDetectStep(data, idx); } - for (size_t i = period_start + 1; i <= period_end; i++) { + for(size_t i = period_start + 1; i <= period_end; i++) { period_sum += data[i]; period_sqr_sum += data[i] * data[i]; } - for (int i = 1; i < crossSequence.size(); i++) { + for(int i = 1; i < crossSequence.size(); i++) { CrossPoint &p0 = crossSequence[i - 1]; CrossPoint &p1 = crossSequence[i]; - if ((p1.m_bufIdx == p0.m_bufIdx) && (p1.m_onRising == p0.m_onRising)) { - if ((p0.m_name == "MR" && p1.m_name == "LR") || - (p0.m_name == "HR" && p1.m_name == "MR")) + if((p1.m_bufIdx == p0.m_bufIdx) && (p1.m_onRising == p0.m_onRising)) { + if((p0.m_name == "MR" && p1.m_name == "LR") || (p0.m_name == "HR" && p1.m_name == "MR")) crossSequence.swapItemsAt(i, i - 1); - else if ((p0.m_name == "MF" && p1.m_name == "HF") || - (p0.m_name == "LF" && p1.m_name == "MF")) + else if((p0.m_name == "MF" && p1.m_name == "HF") || + (p0.m_name == "LF" && p1.m_name == "MF")) crossSequence.swapItemsAt(i, i - 1); } } QString sequence = ""; - for (int i = 0; i < crossSequence.size(); i++) + for(int i = 0; i < crossSequence.size(); i++) sequence += crossSequence[i].m_name; QString periodSequence = "LRMRHRHFMFLF"; int pos = sequence.indexOf(periodSequence); - if (pos < 0) { + if(pos < 0) { qDebug() << "Unable to find 2 transitions for each of the 10%, 50%, 90% levels"; } else { pos /= 2; @@ -1141,42 +1072,39 @@ void M2kMeasure::measureTimeDomain() CrossPoint &midFalling = crossSequence[pos + 4]; CrossPoint &lowFalling = crossSequence[pos + 5]; - //Cycle Mean + // Cycle Mean cycle_mean = period_sum / length; m_measurements[CYCLE_MEAN]->setValue(cycle_mean); - //Cycle RMS + // Cycle RMS cycle_rms = sqrt(period_sqr_sum / length); m_measurements[CYCLE_RMS]->setValue(cycle_rms); - //Area + // Area area = sum * (1 / m_sample_rate); m_measurements[AREA]->setValue(area); - //Cycle Area + // Cycle Area cycle_area = period_sum * (1 / m_sample_rate); m_measurements[CYCLE_AREA]->setValue(cycle_area); // Rise Time - long long rise = (long long)(highRising.m_bufIdx - - lowRising.m_bufIdx); - if (rise < 0) + long long rise = (long long)(highRising.m_bufIdx - lowRising.m_bufIdx); + if(rise < 0) rise += length; rise_time = rise / m_sample_rate; m_measurements[RISE]->setValue(rise_time); // Fall Time - long long fall = (long long)(lowFalling.m_bufIdx - - highFalling.m_bufIdx); - if (fall < 0) + long long fall = (long long)(lowFalling.m_bufIdx - highFalling.m_bufIdx); + if(fall < 0) fall += length; fall_time = fall / m_sample_rate; m_measurements[FALL]->setValue(fall_time); // Positive Width - long long posWidth = (long long)(midFalling.m_bufIdx - - midRising.m_bufIdx); - if (posWidth < 0) + long long posWidth = (long long)(midFalling.m_bufIdx - midRising.m_bufIdx); + if(posWidth < 0) posWidth += length; width_p = posWidth / m_sample_rate; m_measurements[P_WIDTH]->setValue(width_p); @@ -1197,149 +1125,102 @@ void M2kMeasure::measureTimeDomain() delete m_cross_detect; m_cross_detect = NULL; - } -void M2kMeasure::measureSpectral() { +void M2kMeasure::measureSpectral() +{ - //TODO - reconsider computation of measurements - double spur, harm_dist, noise, average_noise = 0, signal; + // TODO - reconsider computation of measurements + double spur, harm_dist, noise, average_noise = 0, signal; - SpectralDetection detection(m_buffer, m_buf_length, m_harmonics_number); + SpectralDetection detection(m_buffer, m_buf_length, m_harmonics_number); - detection.calculateSpectralDetectionParameters(spur, harm_dist, noise, average_noise, signal); + detection.calculateSpectralDetectionParameters(spur, harm_dist, noise, average_noise, signal); - double noise_floor, snr, thd, thdn, sinad, sfdr; - noise_floor = 10 * log10(average_noise / signal); - m_measurements[NOISE_FLOOR]->setValue(noise_floor); + double noise_floor, snr, thd, thdn, sinad, sfdr; + noise_floor = 10 * log10(average_noise / signal); + m_measurements[NOISE_FLOOR]->setValue(noise_floor); - snr = 10 * log10(signal / noise); - m_measurements[SNR]->setValue(snr); + snr = 10 * log10(signal / noise); + m_measurements[SNR]->setValue(snr); - thd = harm_dist > 0 ? 10 * log10(harm_dist / signal) : 0; - m_measurements[THD]->setValue(thd); + thd = harm_dist > 0 ? 10 * log10(harm_dist / signal) : 0; + m_measurements[THD]->setValue(thd); - sinad = 10 * log10(signal / (harm_dist + noise)); - m_measurements[SINAD]->setValue(sinad); + sinad = 10 * log10(signal / (harm_dist + noise)); + m_measurements[SINAD]->setValue(sinad); - thdn = harm_dist > 0 ? 10 * log10((harm_dist + noise) / signal) : 0; - m_measurements[THDN]->setValue(thdn); + thdn = harm_dist > 0 ? 10 * log10((harm_dist + noise) / signal) : 0; + m_measurements[THDN]->setValue(thdn); - sfdr = spur > 0 ? 10 * log10(signal / spur) : 0; - m_measurements[SFDR]->setValue(sfdr); + sfdr = spur > 0 ? 10 * log10(signal / spur) : 0; + m_measurements[SFDR]->setValue(sfdr); } +double M2kMeasure::sampleRate() { return m_sample_rate; } -double M2kMeasure::sampleRate() -{ - return m_sample_rate; -} +void M2kMeasure::setSampleRate(double value) { m_sample_rate = value; } -void M2kMeasure::setSampleRate(double value) -{ - m_sample_rate = value; -} +unsigned int M2kMeasure::adcBitCount() { return m_adc_bit_count; } -unsigned int M2kMeasure::adcBitCount() -{ - return m_adc_bit_count; -} +void M2kMeasure::setAdcBitCount(unsigned int val) { m_adc_bit_count = val; } -void M2kMeasure::setAdcBitCount(unsigned int val) -{ - m_adc_bit_count = val; -} +double M2kMeasure::crossLevel() { return m_cross_level; } -double M2kMeasure::crossLevel() -{ - return m_cross_level; -} +void M2kMeasure::setCrossLevel(double value) { m_cross_level = value; } -void M2kMeasure::setCrossLevel(double value) -{ - m_cross_level = value; -} +double M2kMeasure::hysteresisSpan() { return m_hysteresis_span; } -double M2kMeasure::hysteresisSpan() -{ - return m_hysteresis_span; -} +void M2kMeasure::setHysteresisSpan(double value) { m_hysteresis_span = value; } -void M2kMeasure::setHysteresisSpan(double value) -{ - m_hysteresis_span = value; -} - -int M2kMeasure::channel() const -{ - return m_channel; -} +int M2kMeasure::channel() const { return m_channel; } void M2kMeasure::setChannel(int channel) { - if (m_channel != channel) { - for (int i = 0; i < m_measurements.size(); i++) { + if(m_channel != channel) { + for(int i = 0; i < m_measurements.size(); i++) { m_measurements[i]->setChannel(channel); } m_channel = channel; } } -void M2kMeasure::setStartIndex(int index) -{ - m_startIndex = index; -} +void M2kMeasure::setStartIndex(int index) { m_startIndex = index; } -void M2kMeasure::setEndIndex(int index) -{ - m_endIndex = index; -} +void M2kMeasure::setEndIndex(int index) { m_endIndex = index; } -void M2kMeasure::setGatingEnabled(bool enable){ - m_gatingEnabled = enable; -} +void M2kMeasure::setGatingEnabled(bool enable) { m_gatingEnabled = enable; } std::vector M2kMeasure::LoadMaskfromFile(std::string file_name) { - std::vector mask; - std::ifstream mask_file(file_name.c_str()); - if(!mask_file.is_open()) throw std::runtime_error("Could not open freq file"); + std::vector mask; + std::ifstream mask_file(file_name.c_str()); + if(!mask_file.is_open()) + throw std::runtime_error("Could not open freq file"); - std::string line = ""; - while(std::getline(mask_file, line)) { + std::string line = ""; + while(std::getline(mask_file, line)) { - int val = std::atoi(line.c_str()); - mask.push_back(val); - } - return mask; + int val = std::atoi(line.c_str()); + mask.push_back(val); + } + return mask; } -void M2kMeasure::setHarmonicNumber(int harmonics_number) -{ - m_harmonics_number = harmonics_number; -} +void M2kMeasure::setHarmonicNumber(int harmonics_number) { m_harmonics_number = harmonics_number; } -void M2kMeasure::setMask(std::vector mask) -{ - std::vector m_mask = mask; -} +void M2kMeasure::setMask(std::vector mask) { std::vector m_mask = mask; } -QList> M2kMeasure::measurments() -{ - return m_measurements; -} +QList> M2kMeasure::measurments() { return m_measurements; } -std::shared_ptr M2kMeasure::measurement(int id) -{ - return m_measurements[id]; -} +std::shared_ptr M2kMeasure::measurement(int id) { return m_measurements[id]; } int M2kMeasure::activeMeasurementsCount() const { int count = 0; - for (int i = 0; i < m_measurements.size(); i++) - if (m_measurements[i]->enabled()) + for(int i = 0; i < m_measurements.size(); i++) + if(m_measurements[i]->enabled()) count++; return count; @@ -1349,40 +1230,33 @@ int M2kMeasure::activeMeasurementsCount() const * Class MeasurementData implementation */ -M2kMeasurementData::M2kMeasurementData(const QString& name, axisType axis, - const QString& unit, int channel): - m_name(name), - m_value(0), - m_measured(false), - m_enabled(false), - m_unit(unit), - m_unitType(DIMENSIONLESS), - m_channel(channel), - m_axis(axis) +M2kMeasurementData::M2kMeasurementData(const QString &name, axisType axis, const QString &unit, int channel) + : m_name(name) + , m_value(0) + , m_measured(false) + , m_enabled(false) + , m_unit(unit) + , m_unitType(DIMENSIONLESS) + , m_channel(channel) + , m_axis(axis) { - if (unit.isEmpty()) + if(unit.isEmpty()) m_unitType = DIMENSIONLESS; - else if (unit == "%") + else if(unit == "%") m_unitType = PERCENTAGE; - else if (unit.toLower() == "s" || unit.toLower() == "seconds") + else if(unit.toLower() == "s" || unit.toLower() == "seconds") m_unitType = TIME; - else if ((unit.toLower() == "db" || unit.toLower() == "decibels")) + else if((unit.toLower() == "db" || unit.toLower() == "decibels")) m_unitType = DECIBELS; - else if ((unit.toLower() == "dbc" || unit.toLower() == "decibels_to_carrier")) + else if((unit.toLower() == "dbc" || unit.toLower() == "decibels_to_carrier")) m_unitType = DECIBELS_TO_CARRIER; else m_unitType = METRIC; } -QString M2kMeasurementData::name() const -{ - return m_name; -} +QString M2kMeasurementData::name() const { return m_name; } -double M2kMeasurementData::value() const -{ - return m_value; -} +double M2kMeasurementData::value() const { return m_value; } void M2kMeasurementData::setValue(double value) { @@ -1390,75 +1264,47 @@ void M2kMeasurementData::setValue(double value) m_measured = true; } -bool M2kMeasurementData::measured() const -{ - return m_measured; -} +bool M2kMeasurementData::measured() const { return m_measured; } -void M2kMeasurementData::setMeasured(bool state) -{ - m_measured = state; -} +void M2kMeasurementData::setMeasured(bool state) { m_measured = state; } -bool M2kMeasurementData::enabled() const -{ - return m_enabled; -} +bool M2kMeasurementData::enabled() const { return m_enabled; } -void M2kMeasurementData::setEnabled(bool en) -{ - m_enabled = en; -} +void M2kMeasurementData::setEnabled(bool en) { m_enabled = en; } -QString M2kMeasurementData::unit() const -{ - return m_unit; -} +QString M2kMeasurementData::unit() const { return m_unit; } -M2kMeasurementData::unitTypes M2kMeasurementData::unitType() const -{ - return m_unitType; -} +M2kMeasurementData::unitTypes M2kMeasurementData::unitType() const { return m_unitType; } -int M2kMeasurementData::channel() const -{ - return m_channel; -} +int M2kMeasurementData::channel() const { return m_channel; } -void M2kMeasurementData::setChannel(int channel) -{ - m_channel = channel; -} +void M2kMeasurementData::setChannel(int channel) { m_channel = channel; } -M2kMeasurementData::axisType M2kMeasurementData::axis() const -{ - return m_axis; -} +M2kMeasurementData::axisType M2kMeasurementData::axis() const { return m_axis; } /* * Class Statistic implementation */ -M2kStatistic::M2kStatistic(): - m_sum(0), - m_min(0), - m_max(0), - m_dataCount(0), - m_average(0) -{ -} +M2kStatistic::M2kStatistic() + : m_sum(0) + , m_min(0) + , m_max(0) + , m_dataCount(0) + , m_average(0) +{} void M2kStatistic::pushNewData(double data) { m_sum += data; - if (!m_dataCount) { + if(!m_dataCount) { m_min = data; m_max = data; } else { - if (data < m_min) + if(data < m_min) m_min = data; - else if (data > m_max) + else if(data > m_max) m_max = data; } @@ -1475,22 +1321,10 @@ void M2kStatistic::clear() m_average = 0; } -double M2kStatistic::average() const -{ - return m_average; -} +double M2kStatistic::average() const { return m_average; } -double M2kStatistic::min() const -{ - return m_min; -} +double M2kStatistic::min() const { return m_min; } -double M2kStatistic::max() const -{ - return m_max; -} +double M2kStatistic::max() const { return m_max; } -double M2kStatistic::numPushedData() const -{ - return m_dataCount; -} +double M2kStatistic::numPushedData() const { return m_dataCount; } diff --git a/gui/src/m2kmeasurement_gui.cpp b/gui/src/m2kmeasurement_gui.cpp index 5656eb90b6..e0f56cc5cb 100644 --- a/gui/src/m2kmeasurement_gui.cpp +++ b/gui/src/m2kmeasurement_gui.cpp @@ -18,6 +18,7 @@ * along with this program. If not, see . */ #include "m2kmeasurement_gui.h" + #include "m2kmeasure.h" #include @@ -27,35 +28,26 @@ using namespace scopy; /* * Class MeasurementGui implementation */ -M2kMeasurementGui::M2kMeasurementGui(): - m_name(""), - m_value(""), - m_nameLabel(NULL), - m_valueLabel(NULL), - m_minValLableWidth(0) -{ -} +M2kMeasurementGui::M2kMeasurementGui() + : m_name("") + , m_value("") + , m_nameLabel(NULL) + , m_valueLabel(NULL) + , m_minValLableWidth(0) +{} -M2kMeasurementGui::~M2kMeasurementGui() -{ -} +M2kMeasurementGui::~M2kMeasurementGui() {} -QString M2kMeasurementGui::name() const -{ - return m_name; -} +QString M2kMeasurementGui::name() const { return m_name; } -QString M2kMeasurementGui::value() const -{ - return m_value; -} +QString M2kMeasurementGui::value() const { return m_value; } -void M2kMeasurementGui::setLabelsColor(const QColor& color) +void M2kMeasurementGui::setLabelsColor(const QColor &color) { QString stylesheet = QString("color: %1;").arg(color.name()); - if (m_nameLabel) + if(m_nameLabel) m_nameLabel->setStyleSheet(stylesheet); - if (m_valueLabel) + if(m_valueLabel) m_valueLabel->setStyleSheet(stylesheet); } @@ -65,15 +57,13 @@ void M2kMeasurementGui::init(QLabel *name, QLabel *value) m_valueLabel = value; } - /* * Class MetricMeasurementGui implementation */ -M2kMetricMeasurementGui::M2kMetricMeasurementGui(): - M2kMeasurementGui() -{ -} +M2kMetricMeasurementGui::M2kMetricMeasurementGui() + : M2kMeasurementGui() +{} void M2kMetricMeasurementGui::init(QLabel *name, QLabel *value) { @@ -87,17 +77,16 @@ void M2kMetricMeasurementGui::init(QLabel *name, QLabel *value) M2kMeasurementGui::init(name, value); } -void M2kMetricMeasurementGui::update(const M2kMeasurementData& data, double displayScale) +void M2kMetricMeasurementGui::update(const M2kMeasurementData &data, double displayScale) { m_name = data.name() + ":"; - if (data.measured() && data.enabled()) { + if(data.measured() && data.enabled()) { double value = data.value(); - if (data.axis() == M2kMeasurementData::VERTICAL) { + if(data.axis() == M2kMeasurementData::VERTICAL) { value *= displayScale; } m_value = m_formatter.format(value, data.unit(), 3); - } - else + } else m_value = "--"; m_nameLabel->setText(m_name); @@ -108,10 +97,9 @@ void M2kMetricMeasurementGui::update(const M2kMeasurementData& data, double disp * Class TimeMeasurementGui implementation */ -M2kTimeMeasurementGui::M2kTimeMeasurementGui(): - M2kMeasurementGui() -{ -} +M2kTimeMeasurementGui::M2kTimeMeasurementGui() + : M2kMeasurementGui() +{} void M2kTimeMeasurementGui::init(QLabel *name, QLabel *value) { @@ -125,13 +113,13 @@ void M2kTimeMeasurementGui::init(QLabel *name, QLabel *value) M2kMeasurementGui::init(name, value); } -void M2kTimeMeasurementGui::update(const M2kMeasurementData& data, double displayScale) +void M2kTimeMeasurementGui::update(const M2kMeasurementData &data, double displayScale) { m_name = data.name() + ":"; - if (data.measured() && data.enabled()) { + if(data.measured() && data.enabled()) { double value = data.value(); - if (data.axis() == M2kMeasurementData::VERTICAL) { + if(data.axis() == M2kMeasurementData::VERTICAL) { value *= displayScale; } m_value = m_formatter.format(value, "", 3); @@ -146,10 +134,9 @@ void M2kTimeMeasurementGui::update(const M2kMeasurementData& data, double displa * Class PercentageMeasurementGui implementation */ -M2kPercentageMeasurementGui::M2kPercentageMeasurementGui(): - M2kMeasurementGui() -{ -} +M2kPercentageMeasurementGui::M2kPercentageMeasurementGui() + : M2kMeasurementGui() +{} void M2kPercentageMeasurementGui::init(QLabel *name, QLabel *value) { @@ -163,13 +150,13 @@ void M2kPercentageMeasurementGui::init(QLabel *name, QLabel *value) M2kMeasurementGui::init(name, value); } -void M2kPercentageMeasurementGui::update(const M2kMeasurementData& data, double displayScale) +void M2kPercentageMeasurementGui::update(const M2kMeasurementData &data, double displayScale) { m_name = data.name() + ":"; - if (data.measured() && data.enabled()) { + if(data.measured() && data.enabled()) { double value = data.value(); - if (data.axis() == M2kMeasurementData::VERTICAL) { + if(data.axis() == M2kMeasurementData::VERTICAL) { value *= displayScale; } m_value.setNum(value, 'f', 2); @@ -186,98 +173,95 @@ void M2kPercentageMeasurementGui::update(const M2kMeasurementData& data, double * Class DecibelsMeasurementGui implementation */ - M2kDecibelsMeasurementGui::M2kDecibelsMeasurementGui(): - M2kMeasurementGui() -{ -} +M2kDecibelsMeasurementGui::M2kDecibelsMeasurementGui() + : M2kMeasurementGui() +{} void M2kDecibelsMeasurementGui::init(QLabel *name, QLabel *value) { - // Get the necessary label width so that the label will never resize - QLabel *label = new QLabel(value); - label->setText("-999.999 dB"); - m_minValLableWidth = label->minimumSizeHint().width(); - value->setMinimumWidth(m_minValLableWidth); - delete label; + // Get the necessary label width so that the label will never resize + QLabel *label = new QLabel(value); + label->setText("-999.999 dB"); + m_minValLableWidth = label->minimumSizeHint().width(); + value->setMinimumWidth(m_minValLableWidth); + delete label; M2kMeasurementGui::init(name, value); } -void M2kDecibelsMeasurementGui::update(const M2kMeasurementData& data, double displayScale) +void M2kDecibelsMeasurementGui::update(const M2kMeasurementData &data, double displayScale) { - m_name = data.name() + ":"; + m_name = data.name() + ":"; - if (data.measured() && data.enabled()) { - double value = data.value(); - if (data.axis() == M2kMeasurementData::VERTICAL_F) { - value *= displayScale; + if(data.measured() && data.enabled()) { + double value = data.value(); + if(data.axis() == M2kMeasurementData::VERTICAL_F) { + value *= displayScale; + } + m_value.setNum(value, 'f', 3); + m_value += "dB"; + } else { + m_value = "--"; } - m_value.setNum(value, 'f', 3); - m_value += "dB"; - } else { - m_value = "--"; - } - - m_nameLabel->setText(m_name); - m_valueLabel->setText(m_value); + + m_nameLabel->setText(m_name); + m_valueLabel->setText(m_value); } /* * Class DecibelstoCarrierMeasurementGui implementation */ -M2kDecibelstoCarrierMeasurementGui::M2kDecibelstoCarrierMeasurementGui(): - M2kMeasurementGui() -{ -} +M2kDecibelstoCarrierMeasurementGui::M2kDecibelstoCarrierMeasurementGui() + : M2kMeasurementGui() +{} void M2kDecibelstoCarrierMeasurementGui::init(QLabel *name, QLabel *value) { - // Get the necessary label width so that the label will never resize - QLabel *label = new QLabel(value); - label->setText("-999.999 dB"); - m_minValLableWidth = label->minimumSizeHint().width(); - value->setMinimumWidth(m_minValLableWidth); - delete label; + // Get the necessary label width so that the label will never resize + QLabel *label = new QLabel(value); + label->setText("-999.999 dB"); + m_minValLableWidth = label->minimumSizeHint().width(); + value->setMinimumWidth(m_minValLableWidth); + delete label; M2kMeasurementGui::init(name, value); } -void M2kDecibelstoCarrierMeasurementGui::update(const M2kMeasurementData& data, double displayScale) +void M2kDecibelstoCarrierMeasurementGui::update(const M2kMeasurementData &data, double displayScale) { - m_name = data.name() + ":"; + m_name = data.name() + ":"; - if (data.measured() && data.enabled()) { - double value = data.value(); - if (data.axis() == M2kMeasurementData::VERTICAL_F) { - value *= displayScale; + if(data.measured() && data.enabled()) { + double value = data.value(); + if(data.axis() == M2kMeasurementData::VERTICAL_F) { + value *= displayScale; + } + m_value.setNum(value, 'f', 3); + m_value += "dB"; + } else { + m_value = "--"; } - m_value.setNum(value, 'f', 3); - m_value += "dB"; - } else { - m_value = "--"; - } - - m_nameLabel->setText(m_name); - m_valueLabel->setText(m_value); + + m_nameLabel->setText(m_name); + m_valueLabel->setText(m_value); } /* * Class DimensionlessMeasurementGui implementation */ -M2kDimensionlessMeasurementGui::M2kDimensionlessMeasurementGui(): - M2kMeasurementGui() -{ -} +M2kDimensionlessMeasurementGui::M2kDimensionlessMeasurementGui() + : M2kMeasurementGui() +{} -void M2kDimensionlessMeasurementGui::update(const M2kMeasurementData& data, double displayScale) +void M2kDimensionlessMeasurementGui::update(const M2kMeasurementData &data, double displayScale) { m_name = data.name() + ":"; - if (data.measured() && data.enabled()) { + if(data.measured() && data.enabled()) { double value = data.value(); - if (data.axis() == M2kMeasurementData::VERTICAL) { + if(data.axis() == M2kMeasurementData::VERTICAL) { value *= displayScale; } m_value.setNum(value, 'f', 3); diff --git a/gui/src/mapstackedwidget.cpp b/gui/src/mapstackedwidget.cpp index 7e4cabeb5a..d6340fc273 100644 --- a/gui/src/mapstackedwidget.cpp +++ b/gui/src/mapstackedwidget.cpp @@ -1,4 +1,5 @@ #include "mapstackedwidget.h" + #include #include @@ -6,19 +7,15 @@ Q_LOGGING_CATEGORY(CAT_MAPSTACKWIDGET, "MapStackedWidget") using namespace scopy; -MapStackedWidget::MapStackedWidget(QWidget *parent) : - QStackedWidget(parent) -{ +MapStackedWidget::MapStackedWidget(QWidget *parent) + : QStackedWidget(parent) +{} -} +MapStackedWidget::~MapStackedWidget() {} -MapStackedWidget::~MapStackedWidget() +QString MapStackedWidget::getKey(QWidget *w) { - -} - -QString MapStackedWidget::getKey(QWidget *w) { - QString key = map.key(w,nullptr); + QString key = map.key(w, nullptr); return key; } @@ -26,27 +23,25 @@ void MapStackedWidget::add(QString key, QWidget *w) { map[key] = w; addWidget(w); - qDebug(CAT_MAPSTACKWIDGET) << key <<"added to stack"; + qDebug(CAT_MAPSTACKWIDGET) << key << "added to stack"; } bool MapStackedWidget::remove(QString key) { QWidget *w = map.take(key); - if(w) { -// if(indexOf(w) == currentIndex()) -// setCurrentIndex(0); + if(w) { + // if(indexOf(w) == currentIndex()) + // setCurrentIndex(0); removeWidget(w); } else { - qWarning(CAT_MAPSTACKWIDGET)<. */ #include "marker_controller.h" + #include "spectrum_marker.hpp" -#include +#include #include +#include #include -#include using namespace scopy; @@ -35,33 +36,25 @@ using namespace scopy; * It doesn't own the markers but shares them. It operates on a list of markers * that is modified using the registerMarker() and unRegisterMarker(). */ -MarkerController::MarkerController(QwtPlot *plot): - QObject(static_cast(plot)), - d_picker(new QwtPlotPicker(plot->canvas())), - d_picked_mrk(nullptr), - d_item_moving(nullptr), - d_mrks_default_z(0.0) +MarkerController::MarkerController(QwtPlot *plot) + : QObject(static_cast(plot)) + , d_picker(new QwtPlotPicker(plot->canvas())) + , d_picked_mrk(nullptr) + , d_item_moving(nullptr) + , d_mrks_default_z(0.0) { d_picker->setStateMachine(new QwtPickerDragPointMachine); - connect(d_picker, SIGNAL(selected(QPointF)), - this, SLOT(onPickerSelected(QPointF))); - connect(d_picker, SIGNAL(moved(QPoint)), - this, SLOT(onPickerMoved(QPoint))); + connect(d_picker, SIGNAL(selected(QPointF)), this, SLOT(onPickerSelected(QPointF))); + connect(d_picker, SIGNAL(moved(QPoint)), this, SLOT(onPickerMoved(QPoint))); } -bool MarkerController::enabled() const -{ - return d_picker->isEnabled(); -} +bool MarkerController::enabled() const { return d_picker->isEnabled(); } -void MarkerController::setEnabled(bool en) -{ - d_picker->setEnabled(en); -} +void MarkerController::setEnabled(bool en) { d_picker->setEnabled(en); } void MarkerController::onPickerSelected(QPointF pf) { - if (d_item_moving) { + if(d_item_moving) { d_item_moving = false; Q_EMIT markerReleased(d_picked_mrk); d_picked_mrk = nullptr; @@ -71,15 +64,12 @@ void MarkerController::onPickerSelected(QPointF pf) auto mrks = d_mrks_overlap_order; d_selected_mkr = nullptr; - for (int i = 0; i < mrks.size(); i++) { + for(int i = 0; i < mrks.size(); i++) { QPoint p = mrks[i]->plotValueToPixels(pf); QRect rect = mrks[i]->boundingRectPixels(); - if (p.x() >= rect.topLeft().x() && - p.x() <= rect.bottomRight().x() && - p.y() >= rect.topLeft().y() && - p.y() <= rect.bottomRight().y() && - !d_selected_mkr) { + if(p.x() >= rect.topLeft().x() && p.x() <= rect.bottomRight().x() && p.y() >= rect.topLeft().y() && + p.y() <= rect.bottomRight().y() && !d_selected_mkr) { markerBringToFront(mrks[i]); @@ -93,16 +83,13 @@ void MarkerController::onPickerSelected(QPointF pf) void MarkerController::onPickerMoved(QPoint p) { - if (!d_picked_mrk) { + if(!d_picked_mrk) { auto mrks = d_mrks_overlap_order; - for (int i = 0; i < mrks.size(); i++) { + for(int i = 0; i < mrks.size(); i++) { QRect rect = mrks[i]->boundingRectPixels(); - if (p.x() >= rect.topLeft().x() && - p.x() <= rect.bottomRight().x() && - p.y() >= rect.topLeft().y() && - p.y() <= rect.bottomRight().y() && - !d_picked_mrk) { + if(p.x() >= rect.topLeft().x() && p.x() <= rect.bottomRight().x() && + p.y() >= rect.topLeft().y() && p.y() <= rect.bottomRight().y() && !d_picked_mrk) { markerBringToFront(mrks[i]); @@ -115,22 +102,20 @@ void MarkerController::onPickerMoved(QPoint p) } } - if (d_picked_mrk) { + if(d_picked_mrk) { QPointF val = d_picked_mrk->plotPixelsToValue(p); - QwtInterval xItv = plot()->axisScaleDiv( - QwtAxis::XBottom).interval(); - QwtInterval yItv = plot()->axisScaleDiv( - QwtAxis::YLeft).interval(); + QwtInterval xItv = plot()->axisScaleDiv(QwtAxis::XBottom).interval(); + QwtInterval yItv = plot()->axisScaleDiv(QwtAxis::YLeft).interval(); // Make sure the marker does not leave the plot canvas - if (val.x() < xItv.minValue()) { + if(val.x() < xItv.minValue()) { val.setX(xItv.minValue()); - } else if (val.x() > xItv.maxValue()) { + } else if(val.x() > xItv.maxValue()) { val.setX(xItv.maxValue()); } - if (val.y() < yItv.minValue()) { + if(val.y() < yItv.minValue()) { val.setY(yItv.minValue()); - } else if (val.y() > yItv.maxValue()) { + } else if(val.y() > yItv.maxValue()) { val.setY(yItv.maxValue()); } @@ -146,7 +131,7 @@ void MarkerController::registerMarker(marker_sptr marker) d_markers.push_back(marker); d_mrks_overlap_order.push_front(marker); - if (d_markers.size() == 1) { + if(d_markers.size() == 1) { d_mrks_default_z = marker->z(); } } @@ -156,15 +141,12 @@ void MarkerController::unRegisterMarker(marker_sptr marker) d_markers.removeOne(marker); d_mrks_overlap_order.removeOne(marker); - if (marker == d_selected_mkr) { + if(marker == d_selected_mkr) { d_selected_mkr = nullptr; } } -MarkerController::marker_sptr MarkerController::selectedMarker() const -{ - return d_selected_mkr; -} +MarkerController::marker_sptr MarkerController::selectedMarker() const { return d_selected_mkr; } void MarkerController::markerBringToFront(marker_sptr marker) { @@ -175,19 +157,13 @@ void MarkerController::markerBringToFront(marker_sptr marker) marker->setZ(d_mrks_default_z); } -QwtPlot *MarkerController::plot() -{ - return static_cast(parent()); -} +QwtPlot *MarkerController::plot() { return static_cast(parent()); } -const QwtPlot *MarkerController::plot() const -{ - return static_cast(parent()); -} +const QwtPlot *MarkerController::plot() const { return static_cast(parent()); } void MarkerController::selectMarker(marker_sptr marker) { - if (marker->isVisible()) { + if(marker->isVisible()) { d_selected_mkr = marker; Q_EMIT markerSelected(marker); } diff --git a/gui/src/marker_table.cpp b/gui/src/marker_table.cpp index 79fe3ad615..a82e05c68d 100644 --- a/gui/src/marker_table.cpp +++ b/gui/src/marker_table.cpp @@ -18,9 +18,11 @@ * along with this program. If not, see . */ #include "marker_table.hpp" -#include "ui_marker_table.h" + #include "plot_utils.hpp" +#include "ui_marker_table.h" + #include #include @@ -32,9 +34,9 @@ using namespace scopy; class FrequencyDelegate : public QStyledItemDelegate { public: - FrequencyDelegate(QObject *parent = 0): QStyledItemDelegate(parent) - { - } + FrequencyDelegate(QObject *parent = 0) + : QStyledItemDelegate(parent) + {} virtual QString displayText(const QVariant &value, const QLocale &locale) const { @@ -43,6 +45,7 @@ class FrequencyDelegate : public QStyledItemDelegate double freq = value.toDouble(); return formatter.format(freq, "Hz", 3); } + private: scopy::MetricPrefixFormatter formatter; }; @@ -53,9 +56,9 @@ class FrequencyDelegate : public QStyledItemDelegate class ChannelDelegate : public QStyledItemDelegate { public: - ChannelDelegate(QObject *parent = 0): QStyledItemDelegate(parent) - { - } + ChannelDelegate(QObject *parent = 0) + : QStyledItemDelegate(parent) + {} virtual QString displayText(const QVariant &value, const QLocale &locale) const { @@ -70,9 +73,9 @@ class ChannelDelegate : public QStyledItemDelegate * Class MarkerTable */ -MarkerTable::MarkerTable(QWidget *parent) : -QWidget(parent), -ui(new Ui::MarkerTable) +MarkerTable::MarkerTable(QWidget *parent) + : QWidget(parent) + , ui(new Ui::MarkerTable) { ui->setupUi(this); @@ -89,8 +92,7 @@ ui(new Ui::MarkerTable) ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); ui->tableView->horizontalHeader()->setStretchLastSection(true); - ui->tableView->horizontalHeader()->setSectionResizeMode( - QHeaderView::ResizeToContents); + ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); ui->tableView->horizontalHeader()->setHighlightSections(false); ui->tableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); ui->tableView->verticalHeader()->hide(); @@ -106,20 +108,17 @@ ui(new Ui::MarkerTable) ui->tableView->setItemDelegateForColumn(COL_CH, chnDelegate); } -MarkerTable::~MarkerTable() -{ - delete ui; -} +MarkerTable::~MarkerTable() { delete ui; } int MarkerTable::rowOfMarker(int mkIdx, int chIdx) const { int markerRow = -1; - for (int r = 0; r < model->rowCount(); r++) { + for(int r = 0; r < model->rowCount(); r++) { int id = model->item(r, COL_ID)->data(Qt::DisplayRole).toInt(); int ch = model->item(r, COL_CH)->data(Qt::DisplayRole).toInt(); - if (id == mkIdx && ch == chIdx) { + if(id == mkIdx && ch == chIdx) { markerRow = r; break; } @@ -128,8 +127,8 @@ int MarkerTable::rowOfMarker(int mkIdx, int chIdx) const return markerRow; } -void MarkerTable::addMarker(int mkIdx, int chIdx, const QString& name, - double frequency, double magnitude, const QString& type) +void MarkerTable::addMarker(int mkIdx, int chIdx, const QString &name, double frequency, double magnitude, + const QString &type) { model->insertRow(0); model->setData(model->index(0, COL_ID), mkIdx); @@ -144,19 +143,18 @@ void MarkerTable::removeMarker(int mkIdx, int chIdx) { int row = rowOfMarker(mkIdx, chIdx); - if (row < 0) { + if(row < 0) { return; } model->removeRow(row); } -void MarkerTable::updateMarker(int mkIdx, int chIdx, double frequency, - double magnitude, const QString &type) +void MarkerTable::updateMarker(int mkIdx, int chIdx, double frequency, double magnitude, const QString &type) { int row = rowOfMarker(mkIdx, chIdx); - if (row < 0) { + if(row < 0) { return; } @@ -167,8 +165,10 @@ void MarkerTable::updateMarker(int mkIdx, int chIdx, double frequency, bool MarkerTable::isMarker(int mkIdx, int chIdx) { - if (rowOfMarker(mkIdx, chIdx) > 0) { + if(rowOfMarker(mkIdx, chIdx) > 0) { return true; } return false; } + +#include "moc_marker_table.cpp" diff --git a/gui/src/menu_anim.cpp b/gui/src/menu_anim.cpp index a9a7b357ee..4d3332c61c 100644 --- a/gui/src/menu_anim.cpp +++ b/gui/src/menu_anim.cpp @@ -25,44 +25,32 @@ using namespace scopy; -MenuVAnim::MenuVAnim(QWidget *parent) : MenuAnim("minimumHeight", "maximumHeight", parent) -{ -} +MenuVAnim::MenuVAnim(QWidget *parent) + : MenuAnim("minimumHeight", "maximumHeight", parent) +{} -int MenuVAnim::getImplicitMin() -{ - return 0; -} +int MenuVAnim::getImplicitMin() { return 0; } -int MenuVAnim::getImplicitMax() -{ - return sizeHint().height(); -} +int MenuVAnim::getImplicitMax() { return sizeHint().height(); } -MenuHAnim::MenuHAnim(QWidget *parent) : MenuAnim("minimumWidth", "maximumWidth", parent) -{ +MenuHAnim::MenuHAnim(QWidget *parent) + : MenuAnim("minimumWidth", "maximumWidth", parent) +{} -} +int MenuHAnim::getImplicitMin() { return 0; } -int MenuHAnim::getImplicitMin() -{ - return 0; -} +int MenuHAnim::getImplicitMax() { return sizeHint().width(); } -int MenuHAnim::getImplicitMax() -{ - return sizeHint().width(); -} - -MenuAnim::MenuAnim(QByteArray minAnimationProperty, QByteArray maxAnimationProperty, QWidget *parent) : QWidget(parent), - open_anim_max(this, maxAnimationProperty), - open_anim_min(this, minAnimationProperty), - close_anim_max(this, maxAnimationProperty), - close_anim_min(this, minAnimationProperty), - min_val(-1), - max_val(-1), - animInProg(false), - animationDuration(200) +MenuAnim::MenuAnim(QByteArray minAnimationProperty, QByteArray maxAnimationProperty, QWidget *parent) + : QWidget(parent) + , open_anim_max(this, maxAnimationProperty) + , open_anim_min(this, minAnimationProperty) + , close_anim_max(this, maxAnimationProperty) + , close_anim_min(this, minAnimationProperty) + , min_val(-1) + , max_val(-1) + , animInProg(false) + , animationDuration(200) { setAttribute(Qt::WA_StyledBackground, true); open_anim_max.setDuration(animationDuration); @@ -77,10 +65,8 @@ MenuAnim::MenuAnim(QByteArray minAnimationProperty, QByteArray maxAnimationPrope close_anim_min.setDuration(animationDuration); close_anim_min.setEasingCurve(QEasingCurve::InOutExpo); - connect(&open_anim_max, SIGNAL(finished()), - this, SLOT(openAnimFinished())); - connect(&close_anim_max, SIGNAL(finished()), - this, SLOT(closeAnimFinished())); + connect(&open_anim_max, SIGNAL(finished()), this, SLOT(openAnimFinished())); + connect(&close_anim_max, SIGNAL(finished()), this, SLOT(closeAnimFinished())); } void MenuAnim::toggleMenu(bool open) @@ -92,7 +78,7 @@ void MenuAnim::toggleMenu(bool open) int min = min_val < 0 ? getImplicitMin() : min_val; int max = max_val < 0 ? getImplicitMax() : max_val; - if (open) { + if(open) { start = min; stop = max; @@ -123,10 +109,7 @@ void MenuAnim::toggleMenu(bool open) } } -bool MenuAnim::animInProgress() const -{ - return animInProg; -} +bool MenuAnim::animInProgress() const { return animInProg; } void MenuAnim::closeAnimFinished() { @@ -140,10 +123,7 @@ void MenuAnim::openAnimFinished() Q_EMIT finished(true); } -int MenuAnim::getAnimationDuration() const -{ - return animationDuration; -} +int MenuAnim::getAnimationDuration() const { return animationDuration; } void MenuAnim::setAnimationDuration(int newAnimationDuration) { @@ -154,13 +134,7 @@ void MenuAnim::setAnimationDuration(int newAnimationDuration) close_anim_min.setDuration(animationDuration); } -void MenuAnim::setAnimMin(int min) -{ - min_val = min; -} -void MenuAnim::setAnimMax(int max) -{ - max_val = max; -} +void MenuAnim::setAnimMin(int min) { min_val = min; } +void MenuAnim::setAnimMax(int max) { max_val = max; } #include "moc_menu_anim.cpp" diff --git a/gui/src/menu_header.cpp b/gui/src/menu_header.cpp index 6e1ef43be4..0344cc094f 100644 --- a/gui/src/menu_header.cpp +++ b/gui/src/menu_header.cpp @@ -1,13 +1,13 @@ +#include "menu_header.hpp" + #include "ui_menu_header.h" #include #include -#include "menu_header.hpp" - using namespace scopy::gui; -MenuHeader::MenuHeader(QWidget* parent) +MenuHeader::MenuHeader(QWidget *parent) : QWidget(parent) , m_ui(new Ui::MenuHeader) { @@ -15,7 +15,7 @@ MenuHeader::MenuHeader(QWidget* parent) this->setEnableBtnVisible(false); } -MenuHeader::MenuHeader(const QString& label, const QColor* color, bool enableBtnVisible, QWidget* parent) +MenuHeader::MenuHeader(const QString &label, const QColor *color, bool enableBtnVisible, QWidget *parent) : MenuHeader(parent) { this->setLabel(label); @@ -27,19 +27,21 @@ MenuHeader::~MenuHeader() { delete m_ui; } void MenuHeader::setEnabledBtnState(bool state) { m_ui->btnEnabled->setChecked(state); } -void MenuHeader::setLabel(const QString& text) { m_ui->lblTitle->setText(text); } +void MenuHeader::setLabel(const QString &text) { m_ui->lblTitle->setText(text); } -void MenuHeader::setLineColor(const QColor* color) +void MenuHeader::setLineColor(const QColor *color) { m_ui->lineSeparator->setStyleSheet("border: 2px solid " + color->name()); } void MenuHeader::setEnableBtnVisible(bool visible) { m_ui->btnEnabled->setVisible(visible); } -QPushButton* MenuHeader::getEnableBtn() { return m_ui->btnEnabled; } +QPushButton *MenuHeader::getEnableBtn() { return m_ui->btnEnabled; } void MenuHeader::addNewHeaderWidget(QWidget *widget) { m_ui->stackedWidget->addWidget(widget); m_ui->stackedWidget->setCurrentWidget(widget); } + +#include "moc_menu_header.cpp" diff --git a/gui/src/mousewheelwidgetguard.cpp b/gui/src/mousewheelwidgetguard.cpp index 2bdfef28fa..c18f40c3a8 100644 --- a/gui/src/mousewheelwidgetguard.cpp +++ b/gui/src/mousewheelwidgetguard.cpp @@ -19,25 +19,24 @@ */ #include "mousewheelwidgetguard.h" -#include -#include + #include -#include #include +#include #include +#include +#include using namespace scopy; -MouseWheelWidgetGuard::MouseWheelWidgetGuard(QObject *parent): - QObject(parent) -{ -} +MouseWheelWidgetGuard::MouseWheelWidgetGuard(QObject *parent) + : QObject(parent) +{} bool MouseWheelWidgetGuard::eventFilter(QObject *o, QEvent *e) { - const QWidget* widget = dynamic_cast(o); - if( e->type() == QEvent::Wheel && widget && !widget->hasFocus()) - { + const QWidget *widget = dynamic_cast(o); + if(e->type() == QEvent::Wheel && widget && !widget->hasFocus()) { e->ignore(); return true; } @@ -49,29 +48,25 @@ void MouseWheelWidgetGuard::installEventRecursively(QWidget *parentWidget) if(parentWidget->children().count() == 0) { return; } - QList comboBoxes = parentWidget-> - findChildren(); + QList comboBoxes = parentWidget->findChildren(); for(auto ch : qAsConst(comboBoxes)) { ch->installEventFilter(new MouseWheelWidgetGuard(ch)); ch->setFocusPolicy(Qt::StrongFocus); } - QList doubleSpinBoxes = parentWidget-> - findChildren(); + QList doubleSpinBoxes = parentWidget->findChildren(); for(auto ch : qAsConst(doubleSpinBoxes)) { ch->installEventFilter(new MouseWheelWidgetGuard(ch)); ch->setFocusPolicy(Qt::StrongFocus); } - QList spinBoxes = parentWidget-> - findChildren(); + QList spinBoxes = parentWidget->findChildren(); for(auto ch : qAsConst(spinBoxes)) { ch->installEventFilter(new MouseWheelWidgetGuard(ch)); ch->setFocusPolicy(Qt::StrongFocus); } - QList lineEdits = parentWidget-> - findChildren(); + QList lineEdits = parentWidget->findChildren(); for(auto ch : qAsConst(lineEdits)) { ch->installEventFilter(new MouseWheelWidgetGuard(ch)); ch->setFocusPolicy(Qt::StrongFocus); diff --git a/gui/src/movingaverage.cpp b/gui/src/movingaverage.cpp index ed0be4f4f8..790099d6ad 100644 --- a/gui/src/movingaverage.cpp +++ b/gui/src/movingaverage.cpp @@ -1,36 +1,26 @@ #include "movingaverage.h" -MovingAverage::MovingAverage() -{ - sum = 0; -} +MovingAverage::MovingAverage() { sum = 0; } -int MovingAverage::getCapacity() const -{ - return capacity; -} +int MovingAverage::getCapacity() const { return capacity; } -void MovingAverage::setCapacity(int newCapacity) -{ - capacity = newCapacity; -} +void MovingAverage::setCapacity(int newCapacity) { capacity = newCapacity; } -const QVector &MovingAverage::getHistory() const -{ - return history; -} +const QVector &MovingAverage::getHistory() const { return history; } -double MovingAverage::pushValueReturnAverage(double newVal){ - sum+=newVal; +double MovingAverage::pushValueReturnAverage(double newVal) +{ + sum += newVal; if(history.count() == capacity && capacity > 0) { - sum-=history.front(); + sum -= history.front(); history.pop_front(); } history.push_back(newVal); - return (sum/(double)history.count()); + return (sum / (double)history.count()); } -void MovingAverage::clearHistory() { +void MovingAverage::clearHistory() +{ history.clear(); sum = 0; } diff --git a/gui/src/nyquistGraph.cpp b/gui/src/nyquistGraph.cpp index ffadfb0db2..ee0840c771 100644 --- a/gui/src/nyquistGraph.cpp +++ b/gui/src/nyquistGraph.cpp @@ -20,79 +20,76 @@ #include "nyquistGraph.hpp" +#include +#include #include #include #include #include -#include - -#include - #include #include -#include -#include - #include #include +#include +#include namespace scopy { - class NyquistSamplesArray : public QwtArraySeriesData - { - public: - NyquistSamplesArray() : QwtArraySeriesData() {} - - void addSample(const QwtPointPolar& point) { - m_samples.push_back(point); - } - void clear() { m_samples.clear(); } - void reserve(unsigned int nb) { m_samples.reserve(nb); } - QRectF boundingRect() const; - - QwtPointPolar sample(size_t index) const { - return m_samples.at(index); - } - }; -} +class NyquistSamplesArray : public QwtArraySeriesData +{ +public: + NyquistSamplesArray() + : QwtArraySeriesData() + {} + + void addSample(const QwtPointPolar &point) { m_samples.push_back(point); } + void clear() { m_samples.clear(); } + void reserve(unsigned int nb) { m_samples.reserve(nb); } + QRectF boundingRect() const; + QwtPointPolar sample(size_t index) const { return m_samples.at(index); } +}; +} // namespace scopy using namespace scopy; -const QwtInterval radialInterval( 0.0, 10.0 ); -const QwtInterval azimuthInterval( 0.0, 360.0 ); +const QwtInterval radialInterval(0.0, 10.0); +const QwtInterval azimuthInterval(0.0, 360.0); QRectF NyquistSamplesArray::boundingRect() const { double xmin = 0.0, xmax = 0.0, ymin = 0.0, ymax = 0.0; - for (auto it = m_samples.begin(); - it != m_samples.end(); ++it) { + for(auto it = m_samples.begin(); it != m_samples.end(); ++it) { double point_x = it->radius() * cos(it->azimuth()); double point_y = it->radius() * sin(it->azimuth()); - if (point_x < xmin) + if(point_x < xmin) xmin = point_x; - else if (point_x > xmax) + else if(point_x > xmax) xmax = point_x; - if (point_y < ymin) + if(point_y < ymin) ymin = point_y; - else if (point_y > ymax) + else if(point_y > ymax) ymax = point_y; } return QRectF(QPointF(xmin, ymin), QPointF(xmax, ymax)); } -NyquistGraph::NyquistGraph(QWidget *parent) : QwtPolarPlot(parent), - mag_min(0.0), mag_max(0.0), samples(new NyquistSamplesArray), - grid(new QwtPolarGrid), numSamples(0),m_thickness(1) +NyquistGraph::NyquistGraph(QWidget *parent) + : QwtPolarPlot(parent) + , mag_min(0.0) + , mag_max(0.0) + , samples(new NyquistSamplesArray) + , grid(new QwtPolarGrid) + , numSamples(0) + , m_thickness(1) { setAutoReplot(false); setScale(QwtPolar::Azimuth, 0.0, 360.0, 45.0); grid->setPen(QPen(Qt::white)); - for (unsigned int i = 0; i < QwtPolar::ScaleCount; i++) - { + for(unsigned int i = 0; i < QwtPolar::ScaleCount; i++) { grid->showGrid(i); grid->showMinorGrid(i); @@ -119,22 +116,20 @@ NyquistGraph::NyquistGraph(QWidget *parent) : QwtPolarPlot(parent), curve.attach(this); } -NyquistGraph::~NyquistGraph() -{ -} +NyquistGraph::~NyquistGraph() {} void NyquistGraph::enableZooming(QPushButton *btnZoomIn, QPushButton *btnZoomOut) { - connect(btnZoomIn, &QPushButton::clicked, [=](){ + connect(btnZoomIn, &QPushButton::clicked, [=]() { zoomer->zoomIn(); - if (zoomer->isZoomed()) + if(zoomer->isZoomed()) QApplication::setOverrideCursor(Qt::OpenHandCursor); else QApplication::setOverrideCursor(Qt::CrossCursor); }); - connect(btnZoomOut, &QPushButton::clicked, [=](){ + connect(btnZoomOut, &QPushButton::clicked, [=]() { zoomer->zoomOut(); - if (zoomer->isZoomed()) + if(zoomer->isZoomed()) QApplication::setOverrideCursor(Qt::OpenHandCursor); else QApplication::setOverrideCursor(Qt::CrossCursor); @@ -145,58 +140,43 @@ void NyquistGraph::enableZooming(QPushButton *btnZoomIn, QPushButton *btnZoomOut zoomer->setWheelFactor(1); } -const QColor NyquistGraph::getColor() const -{ - return curve.pen().color(); -} +const QColor NyquistGraph::getColor() const { return curve.pen().color(); } -const QColor& NyquistGraph::getBgColor() const -{ - return plotBackground().color(); -} +const QColor &NyquistGraph::getBgColor() const { return plotBackground().color(); } -void NyquistGraph::setColor(const QColor& color) +void NyquistGraph::setColor(const QColor &color) { QPen pen(color); pen.setWidthF(m_thickness); curve.setPen(pen); } -void NyquistGraph::setBgColor(const QColor& color) -{ - setPlotBackground(QBrush(color)); -} +void NyquistGraph::setBgColor(const QColor &color) { setPlotBackground(QBrush(color)); } void NyquistGraph::plot(double azimuth, double radius) { - if (curve.dataSize() == numSamples + 1) + if(curve.dataSize() == numSamples + 1) return; samples->addSample(QwtPointPolar(azimuth, radius)); replot(); } -int NyquistGraph::getNumSamples() const -{ - return numSamples; -} +int NyquistGraph::getNumSamples() const { return numSamples; } void NyquistGraph::setNumSamples(int num) { - if (numSamples == num) { + if(numSamples == num) { return; } - numSamples = (unsigned int) num; + numSamples = (unsigned int)num; samples->reserve(numSamples + 1); replot(); } -void NyquistGraph::reset() -{ - samples->clear(); -} +void NyquistGraph::reset() { samples->clear(); } void NyquistGraph::setThickness(int index) { @@ -209,10 +189,7 @@ void NyquistGraph::setThickness(int index) replot(); } -double NyquistGraph::getThickness() const -{ - return m_thickness; -} +double NyquistGraph::getThickness() const { return m_thickness; } void NyquistGraph::setMin(double min) { @@ -228,22 +205,13 @@ void NyquistGraph::setMax(double max) replot(); } -QFont NyquistGraph::getFontAzimuth() const -{ - return grid->axisFont(QwtPolar::AxisAzimuth); -} +QFont NyquistGraph::getFontAzimuth() const { return grid->axisFont(QwtPolar::AxisAzimuth); } -QFont NyquistGraph::getFontRadius() const -{ - return grid->axisFont(QwtPolar::AxisRight); -} +QFont NyquistGraph::getFontRadius() const { return grid->axisFont(QwtPolar::AxisRight); } -void NyquistGraph::setFontAzimuth(const QFont& font) -{ - grid->setAxisFont(QwtPolar::AxisAzimuth, font); -} +void NyquistGraph::setFontAzimuth(const QFont &font) { grid->setAxisFont(QwtPolar::AxisAzimuth, font); } -void NyquistGraph::setFontRadius(const QFont& font) +void NyquistGraph::setFontRadius(const QFont &font) { grid->setAxisFont(QwtPolar::AxisRight, font); grid->setAxisFont(QwtPolar::AxisTop, font); @@ -251,7 +219,7 @@ void NyquistGraph::setFontRadius(const QFont& font) void NyquistGraph::mousePressEvent(QMouseEvent *event) { - if (event->button() == Qt::RightButton) { + if(event->button() == Qt::RightButton) { zoomer->cancelZoom(); QApplication::setOverrideCursor(Qt::CrossCursor); QwtPolarPlot::mousePressEvent(event); @@ -259,7 +227,7 @@ void NyquistGraph::mousePressEvent(QMouseEvent *event) } #ifdef __ANDROID__ - if (event->type() == QEvent::MouseButtonDblClick) { + if(event->type() == QEvent::MouseButtonDblClick) { zoomer->cancelZoom(); QApplication::setOverrideCursor(Qt::CrossCursor); QwtPolarPlot::mousePressEvent(event); @@ -267,7 +235,7 @@ void NyquistGraph::mousePressEvent(QMouseEvent *event) } #endif - if (zoomer->isZoomed()) + if(zoomer->isZoomed()) QApplication::setOverrideCursor(Qt::ClosedHandCursor); QwtPolarPlot::mousePressEvent(event); @@ -275,14 +243,14 @@ void NyquistGraph::mousePressEvent(QMouseEvent *event) void NyquistGraph::mouseReleaseEvent(QMouseEvent *event) { - if (zoomer->isZoomed()) + if(zoomer->isZoomed()) QApplication::setOverrideCursor(Qt::OpenHandCursor); QwtPolarPlot::mouseReleaseEvent(event); } void NyquistGraph::enterEvent(QEvent *event) { - if (zoomer->isZoomed()) + if(zoomer->isZoomed()) QApplication::setOverrideCursor(Qt::OpenHandCursor); else QApplication::setOverrideCursor(Qt::CrossCursor); @@ -294,3 +262,5 @@ void NyquistGraph::leaveEvent(QEvent *event) QApplication::setOverrideCursor(Qt::ArrowCursor); QwtPolarPlot::leaveEvent(event); } + +#include "moc_nyquistGraph.cpp" diff --git a/gui/src/nyquistplotzoomer.cpp b/gui/src/nyquistplotzoomer.cpp index f7eb99ac14..45954b3eae 100644 --- a/gui/src/nyquistplotzoomer.cpp +++ b/gui/src/nyquistplotzoomer.cpp @@ -19,14 +19,12 @@ */ #include "nyquistplotzoomer.h" - using namespace scopy; -NyquistPlotZoomer::NyquistPlotZoomer(QwtPolarCanvas* parent): - QwtPolarMagnifier(parent), zoom_count(0) -{ - -} +NyquistPlotZoomer::NyquistPlotZoomer(QwtPolarCanvas *parent) + : QwtPolarMagnifier(parent) + , zoom_count(0) +{} void NyquistPlotZoomer::zoomIn() { @@ -37,14 +35,11 @@ void NyquistPlotZoomer::zoomIn() void NyquistPlotZoomer::zoomOut() { QwtPolarMagnifier::rescale(1.25); - if (zoom_count > 0) + if(zoom_count > 0) --zoom_count; } -bool NyquistPlotZoomer::isZoomed() -{ - return (zoom_count != 0); -} +bool NyquistPlotZoomer::isZoomed() { return (zoom_count != 0); } void NyquistPlotZoomer::cancelZoom() { diff --git a/gui/src/osc_adjuster.cpp b/gui/src/osc_adjuster.cpp index e9faca74f6..ae22e13406 100644 --- a/gui/src/osc_adjuster.cpp +++ b/gui/src/osc_adjuster.cpp @@ -19,60 +19,41 @@ */ #include "osc_adjuster.hpp" -#include -#include +#include +#include -OscAdjuster::OscAdjuster(QWidget *parent, QwtAxisId axisId) : - QObject(parent), - d_isEnabled(false), - d_mousePressed(false), - d_mouseFactor(0.95), - d_mouseButton( Qt::LeftButton ), - d_axisId(axisId) +OscAdjuster::OscAdjuster(QWidget *parent, QwtAxisId axisId) + : QObject(parent) + , d_isEnabled(false) + , d_mousePressed(false) + , d_mouseFactor(0.95) + , d_mouseButton(Qt::LeftButton) + , d_axisId(axisId) { setEnabled(true); } -OscAdjuster::~OscAdjuster() -{ -} +OscAdjuster::~OscAdjuster() {} -QWidget* OscAdjuster::parentWidget() -{ - return qobject_cast(parent()); -} +QWidget *OscAdjuster::parentWidget() { return qobject_cast(parent()); } -const QWidget* OscAdjuster::parentWidget() const -{ - return qobject_cast(parent()); -} +const QWidget *OscAdjuster::parentWidget() const { return qobject_cast(parent()); } -QwtAxisId OscAdjuster::axisId() -{ - return d_axisId; -} +QwtAxisId OscAdjuster::axisId() { return d_axisId; } -void OscAdjuster::setMouseFactor(double factor) -{ - d_mouseFactor = factor; -} +void OscAdjuster::setMouseFactor(double factor) { d_mouseFactor = factor; } -double OscAdjuster::mouseFactor() const -{ - return d_mouseFactor; -} +double OscAdjuster::mouseFactor() const { return d_mouseFactor; } void OscAdjuster::setEnabled(bool on) { - if (d_isEnabled != on) - { + if(d_isEnabled != on) { d_isEnabled = on; QObject *o = parent(); - if (o) - { - if (d_isEnabled) + if(o) { + if(d_isEnabled) o->installEventFilter(this); else o->removeEventFilter(this); @@ -80,48 +61,33 @@ void OscAdjuster::setEnabled(bool on) } } -bool OscAdjuster::isEnabled() const -{ - return d_isEnabled; -} +bool OscAdjuster::isEnabled() const { return d_isEnabled; } -void OscAdjuster::setMouseButton(Qt::MouseButton button) -{ - d_mouseButton = button; -} +void OscAdjuster::setMouseButton(Qt::MouseButton button) { d_mouseButton = button; } -void OscAdjuster::getMouseButton(Qt::MouseButton &button) const -{ - button = d_mouseButton; -} +void OscAdjuster::getMouseButton(Qt::MouseButton &button) const { button = d_mouseButton; } bool OscAdjuster::eventFilter(QObject *object, QEvent *event) { - if (object && object == parent()) - { - switch (event->type()) - { - case QEvent::MouseButtonPress: - { - widgetMousePressEvent(static_cast(event)); - break; - } - case QEvent::MouseMove: - { - widgetMouseMoveEvent(static_cast(event)); - break; - } - case QEvent::MouseButtonRelease: - { - widgetMouseReleaseEvent(static_cast(event)); - break; - } - case QEvent::Wheel: - { - widgetMouseWheelEvent(static_cast(event)); - break; - } - default:; + if(object && object == parent()) { + switch(event->type()) { + case QEvent::MouseButtonPress: { + widgetMousePressEvent(static_cast(event)); + break; + } + case QEvent::MouseMove: { + widgetMouseMoveEvent(static_cast(event)); + break; + } + case QEvent::MouseButtonRelease: { + widgetMouseReleaseEvent(static_cast(event)); + break; + } + case QEvent::Wheel: { + widgetMouseWheelEvent(static_cast(event)); + break; + } + default:; } } return QObject::eventFilter(object, event); @@ -129,11 +95,10 @@ bool OscAdjuster::eventFilter(QObject *object, QEvent *event) void OscAdjuster::widgetMousePressEvent(QMouseEvent *mouseEvent) { - if (parentWidget() == NULL) + if(parentWidget() == NULL) return; - if (mouseEvent->button() != d_mouseButton) - { + if(mouseEvent->button() != d_mouseButton) { return; } @@ -148,8 +113,7 @@ void OscAdjuster::widgetMouseReleaseEvent(QMouseEvent *mouseEvent) { Q_UNUSED(mouseEvent); - if (d_mousePressed && parentWidget()) - { + if(d_mousePressed && parentWidget()) { d_mousePressed = false; parentWidget()->setMouseTracking(d_hasMouseTracking); } @@ -161,8 +125,8 @@ void OscAdjuster::widgetMouseWheelEvent(QWheelEvent *wheelEvent) // Only y value changes if a mouse with wheel is used. // TO DO: Check if this works for touch screens and fix if necessary - if (y != 0) { - if (y > 0) + if(y != 0) { + if(y > 0) Q_EMIT wheelUp(y); else Q_EMIT wheelDown(y); diff --git a/gui/src/osc_custom_scroll.cpp b/gui/src/osc_custom_scroll.cpp index b284adc732..b96aefd383 100644 --- a/gui/src/osc_custom_scroll.cpp +++ b/gui/src/osc_custom_scroll.cpp @@ -20,17 +20,17 @@ #include "osc_custom_scroll.h" #include -#include #include -#include +#include #include +#include using namespace scopy; -OscCustomScrollArea::OscCustomScrollArea(QWidget *parent): - QScrollArea(parent), - inside(false), - disableCursor(true) +OscCustomScrollArea::OscCustomScrollArea(QWidget *parent) + : QScrollArea(parent) + , inside(false) + , disableCursor(true) { QScroller::grabGesture(this->viewport(), QScroller::LeftMouseButtonGesture); @@ -38,27 +38,28 @@ OscCustomScrollArea::OscCustomScrollArea(QWidget *parent): QScrollerProperties properties = QScroller::scroller(this->viewport())->scrollerProperties(); - QVariant overshootPolicy = QVariant::fromValue(QScrollerProperties::OvershootWhenScrollable); + QVariant overshootPolicy = + QVariant::fromValue(QScrollerProperties::OvershootWhenScrollable); properties.setScrollMetric(QScrollerProperties::HorizontalOvershootPolicy, overshootPolicy); QScroller::scroller(this->viewport())->setScrollerProperties(properties); - connect(scroll, &QScroller::stateChanged, [=](QScroller::State newstate){ - if (disableCursor) - return; - switch (newstate) { - case QScroller::Inactive : - if (inside) + connect(scroll, &QScroller::stateChanged, [=](QScroller::State newstate) { + if(disableCursor) + return; + switch(newstate) { + case QScroller::Inactive: + if(inside) setCursor(Qt::OpenHandCursor); break; - case QScroller::Pressed : + case QScroller::Pressed: setCursor(Qt::ClosedHandCursor); break; - case QScroller::Dragging : + case QScroller::Dragging: setCursor(Qt::ClosedHandCursor); break; - case QScroller::Scrolling : - if (inside) + case QScroller::Scrolling: + if(inside) setCursor(Qt::OpenHandCursor); break; default: @@ -67,32 +68,28 @@ OscCustomScrollArea::OscCustomScrollArea(QWidget *parent): } }); - connect(horizontalScrollBar(), &QScrollBar::rangeChanged, [=](int v1, int v2){ - if (v2 - v1 == 0) + connect(horizontalScrollBar(), &QScrollBar::rangeChanged, [=](int v1, int v2) { + if(v2 - v1 == 0) disableCursor = true; else disableCursor = false; }); } -OscCustomScrollArea::~OscCustomScrollArea() -{ - QScroller::ungrabGesture(this->viewport()); -} +OscCustomScrollArea::~OscCustomScrollArea() { QScroller::ungrabGesture(this->viewport()); } void OscCustomScrollArea::enterEvent(QEvent *event) { - if (!disableCursor) + if(!disableCursor) setCursor(Qt::OpenHandCursor); inside = true; } void OscCustomScrollArea::leaveEvent(QEvent *event) { - if (!disableCursor) + if(!disableCursor) setCursor(Qt::ArrowCursor); inside = false; } - - +#include "moc_osc_custom_scroll.cpp" diff --git a/gui/src/osc_export_settings.cpp b/gui/src/osc_export_settings.cpp index 512ff772e7..82bcd467fc 100644 --- a/gui/src/osc_export_settings.cpp +++ b/gui/src/osc_export_settings.cpp @@ -18,19 +18,20 @@ * along with this program. If not, see . */ #include "osc_export_settings.h" + #include "ui_osc_export_settings.h" -#include -#include #include +#include +#include using namespace scopy; -ExportSettings::ExportSettings(QWidget *parent) : - QWidget(parent), - ui(new Ui::ExportSettings), - exportChannels(nullptr), - nr_channels(0) +ExportSettings::ExportSettings(QWidget *parent) + : QWidget(parent) + , ui(new Ui::ExportSettings) + , exportChannels(nullptr) + , nr_channels(0) { ui->setupUi(this); @@ -45,27 +46,20 @@ ExportSettings::ExportSettings(QWidget *parent) : treeView->header()->resizeSection(0, 80); treeView->setContentsMargins(2, 2, 2, 2); - connect(exportChannels->model(), - SIGNAL(itemChanged(QStandardItem*)), - SLOT(onExportChannelChanged(QStandardItem*))); + connect(exportChannels->model(), SIGNAL(itemChanged(QStandardItem *)), + SLOT(onExportChannelChanged(QStandardItem *))); ui->dropDownLayout->addWidget(exportChannels); } -ExportSettings::~ExportSettings() -{ - delete ui; -} +ExportSettings::~ExportSettings() { delete ui; } void ExportSettings::addChannel(int id, QString name) { - exportChannels->addDropdownElement(QIcon(""), name, - QVariant(id)); + exportChannels->addDropdownElement(QIcon(""), name, QVariant(id)); nr_channels++; - QStandardItemModel *model = - static_cast(exportChannels->model()); - model->item(id, 1)->setData(QVariant((int) true), - Qt::EditRole); + QStandardItemModel *model = static_cast(exportChannels->model()); + model->item(id, 1)->setData(QVariant((int)true), Qt::EditRole); } void ExportSettings::removeChannel(int id) @@ -76,7 +70,7 @@ void ExportSettings::removeChannel(int id) void ExportSettings::clear() { - for (int i = 0; i < nr_channels; ++i) + for(int i = 0; i < nr_channels; ++i) exportChannels->removeItem(i); nr_channels = 0; } @@ -85,8 +79,8 @@ void ExportSettings::onExportChannelChanged(QStandardItem *item) { bool en = item->data(Qt::EditRole).toBool(); - if (ui->btnExportAll->isChecked()){ - if (!en){ + if(ui->btnExportAll->isChecked()) { + if(!en) { ui->btnExportAll->setChecked(false); oldSettings.clear(); } @@ -97,11 +91,10 @@ void ExportSettings::onExportChannelChanged(QStandardItem *item) void ExportSettings::checkIfAllActivated() { - QStandardItemModel *model = - static_cast(exportChannels->model()); + QStandardItemModel *model = static_cast(exportChannels->model()); bool ok = true; - for (int i = 0; i < nr_channels; i++) { - if (!model->item(i, 1)->data(Qt::EditRole).toBool()){ + for(int i = 0; i < nr_channels; i++) { + if(!model->item(i, 1)->data(Qt::EditRole).toBool()) { ok = false; break; } @@ -109,22 +102,15 @@ void ExportSettings::checkIfAllActivated() ui->btnExportAll->setChecked(ok); } -QPushButton* ExportSettings::getExportButton() -{ - return ui->btnExport; -} +QPushButton *ExportSettings::getExportButton() { return ui->btnExport; } -QPushButton* ExportSettings::getExportAllButton() -{ - return ui->btnExportAll; -} +QPushButton *ExportSettings::getExportAllButton() { return ui->btnExportAll; } QMap ExportSettings::getExportConfig() { - QStandardItemModel *model = - static_cast(exportChannels->model()); + QStandardItemModel *model = static_cast(exportChannels->model()); QMap result; - for (int i = 0; i < nr_channels; i++) { + for(int i = 0; i < nr_channels; i++) { result[i] = model->item(i, 1)->data(Qt::EditRole).toBool(); } return result; @@ -132,49 +118,38 @@ QMap ExportSettings::getExportConfig() void ExportSettings::setExportConfig(QMap config) { - QStandardItemModel *model = - static_cast(exportChannels->model()); + QStandardItemModel *model = static_cast(exportChannels->model()); auto keys = config.keys(); - for (int key : qAsConst(keys)) { - model->item(key, 1)->setData(QVariant((int) config[key]), - Qt::EditRole); + for(int key : qAsConst(keys)) { + model->item(key, 1)->setData(QVariant((int)config[key]), Qt::EditRole); } } void ExportSettings::on_btnExportAll_clicked() { - QStandardItemModel *model = - static_cast(exportChannels->model()); - if (ui->btnExportAll->isChecked()){ + QStandardItemModel *model = static_cast(exportChannels->model()); + if(ui->btnExportAll->isChecked()) { oldSettings = getExportConfig(); - for (int i = 0; i < model->rowCount(); i++) { - model->item(i, 1)->setData(QVariant((int) true), - Qt::EditRole); + for(int i = 0; i < model->rowCount(); i++) { + model->item(i, 1)->setData(QVariant((int)true), Qt::EditRole); } } else { - if (!oldSettings.empty()) - for (int i = 0; i < model->rowCount(); i++) { - model->item(i, 1)->setData(QVariant((int) oldSettings[i]), - Qt::EditRole); - } else { - for (int i = 0; i < model->rowCount(); i++) { - model->item(i, 1)->setData(QVariant((int) false), - Qt::EditRole); + if(!oldSettings.empty()) + for(int i = 0; i < model->rowCount(); i++) { + model->item(i, 1)->setData(QVariant((int)oldSettings[i]), Qt::EditRole); + } + else { + for(int i = 0; i < model->rowCount(); i++) { + model->item(i, 1)->setData(QVariant((int)false), Qt::EditRole); } } } } -void ExportSettings::enableExportButton(bool on) -{ - ui->btnExport->setEnabled(on); -} +void ExportSettings::enableExportButton(bool on) { ui->btnExport->setEnabled(on); } -void ExportSettings::disableUIMargins() -{ - ui->verticalLayout_3->setMargin(0); -} +void ExportSettings::disableUIMargins() { ui->verticalLayout_3->setMargin(0); } void ExportSettings::setTitleLabelVisible(bool enabled) { @@ -182,9 +157,6 @@ void ExportSettings::setTitleLabelVisible(bool enabled) ui->line->setVisible(enabled); } -void ExportSettings::setExportAllButtonLabel(const QString& text) -{ - ui->label_3->setText(text); -} - +void ExportSettings::setExportAllButtonLabel(const QString &text) { ui->label_3->setText(text); } +#include "moc_osc_export_settings.cpp" diff --git a/gui/src/osc_import_settings.cpp b/gui/src/osc_import_settings.cpp index 47781134cb..98729ae49e 100644 --- a/gui/src/osc_import_settings.cpp +++ b/gui/src/osc_import_settings.cpp @@ -22,15 +22,15 @@ using namespace scopy; -ImportSettings::ImportSettings(QWidget *parent) : - ExportSettings(parent) +ImportSettings::ImportSettings(QWidget *parent) + : ExportSettings(parent) { - getExportButton()->setVisible(false); + getExportButton()->setVisible(false); exportChannels->setColumnTitle(1, tr("Import")); - setTitleLabelVisible(false); + setTitleLabelVisible(false); setExportAllButtonLabel(tr("Import all")); } -ImportSettings::~ImportSettings() -{ -} +ImportSettings::~ImportSettings() {} + +#include "moc_osc_import_settings.cpp" diff --git a/gui/src/osc_scale_engine.cpp b/gui/src/osc_scale_engine.cpp index f81d52e29c..44f9683074 100644 --- a/gui/src/osc_scale_engine.cpp +++ b/gui/src/osc_scale_engine.cpp @@ -19,55 +19,40 @@ */ #include "osc_scale_engine.h" + #include "qwt_math.h" -#include + #include +#include + #include -static inline long double qwtIntervalWidthL( const QwtInterval &interval ) +static inline long double qwtIntervalWidthL(const QwtInterval &interval) { - if ( !interval.isValid() ) - return 0.0; + if(!interval.isValid()) + return 0.0; - return static_cast( interval.maxValue() ) - - static_cast( interval.minValue() ); + return static_cast(interval.maxValue()) - static_cast(interval.minValue()); } -OscScaleEngine::OscScaleEngine(): - QwtLinearScaleEngine(10), - m_majorTicks(11), - m_minorTicks(9), - m_showZero(false) -{ -} +OscScaleEngine::OscScaleEngine() + : QwtLinearScaleEngine(10) + , m_majorTicks(11) + , m_minorTicks(9) + , m_showZero(false) +{} -OscScaleEngine::~OscScaleEngine() -{ -} +OscScaleEngine::~OscScaleEngine() {} -void OscScaleEngine::setMajorTicksCount(uint majorTicks) -{ - m_majorTicks = majorTicks; -} +void OscScaleEngine::setMajorTicksCount(uint majorTicks) { m_majorTicks = majorTicks; } -uint OscScaleEngine::majorTicksCount() -{ - return m_majorTicks; -} +uint OscScaleEngine::majorTicksCount() { return m_majorTicks; } -void OscScaleEngine::setMinorTicksCount(uint minorTicks) -{ - m_minorTicks = minorTicks; -} +void OscScaleEngine::setMinorTicksCount(uint minorTicks) { m_minorTicks = minorTicks; } -uint OscScaleEngine::minorTicksCount() -{ - return m_minorTicks; -} -void OscScaleEngine::showZero(bool en){ - m_showZero = en; -} -void OscScaleEngine::autoScale( int maxSteps, double &x1, double &x2, double &stepSize ) const +uint OscScaleEngine::minorTicksCount() { return m_minorTicks; } +void OscScaleEngine::showZero(bool en) { m_showZero = en; } +void OscScaleEngine::autoScale(int maxSteps, double &x1, double &x2, double &stepSize) const { // No implementation is needed for now Q_UNUSED(maxSteps) @@ -76,19 +61,19 @@ void OscScaleEngine::autoScale( int maxSteps, double &x1, double &x2, double &st Q_UNUSED(stepSize) } -QwtScaleDiv OscScaleEngine::divideScale(double x1, double x2, int maxMajorSteps, int maxMinorSteps, double stepSize) const +QwtScaleDiv OscScaleEngine::divideScale(double x1, double x2, int maxMajorSteps, int maxMinorSteps, + double stepSize) const { Q_UNUSED(maxMajorSteps); - QwtInterval interval = QwtInterval( x1, x2 ).normalized(); + QwtInterval interval = QwtInterval(x1, x2).normalized(); - if ( qwtIntervalWidthL( interval ) > std::numeric_limits::max() ) - { + if(qwtIntervalWidthL(interval) > std::numeric_limits::max()) { qWarning() << "QwtLinearScaleEngine::divideScale: overflow"; return QwtScaleDiv(); } - if ( interval.width() <= 0 ) + if(interval.width() <= 0) return QwtScaleDiv(); stepSize = interval.width() / (double)(m_majorTicks - 1); @@ -96,43 +81,41 @@ QwtScaleDiv OscScaleEngine::divideScale(double x1, double x2, int maxMajorSteps, QwtScaleDiv scaleDiv; QList ticks[QwtScaleDiv::NTickTypes]; - buildTicks( interval, stepSize, maxMinorSteps, ticks ); + buildTicks(interval, stepSize, maxMinorSteps, ticks); - scaleDiv = QwtScaleDiv( interval, ticks ); + scaleDiv = QwtScaleDiv(interval, ticks); - if ( x1 > x2 ) + if(x1 > x2) scaleDiv.invert(); return scaleDiv; } -void OscScaleEngine::buildTicks(const QwtInterval &interval, double stepSize, int maxMinorSteps, QList ticks[QwtScaleDiv::NTickTypes]) const +void OscScaleEngine::buildTicks(const QwtInterval &interval, double stepSize, int maxMinorSteps, + QList ticks[QwtScaleDiv::NTickTypes]) const { - ticks[QwtScaleDiv::MajorTick] = - buildMajorTicks( interval, stepSize ); + ticks[QwtScaleDiv::MajorTick] = buildMajorTicks(interval, stepSize); - if ( maxMinorSteps > 0 ) - { - buildMinorTicks( ticks[QwtScaleDiv::MajorTick], maxMinorSteps, stepSize, - ticks[QwtScaleDiv::MinorTick], ticks[QwtScaleDiv::MediumTick] ); + if(maxMinorSteps > 0) { + buildMinorTicks(ticks[QwtScaleDiv::MajorTick], maxMinorSteps, stepSize, ticks[QwtScaleDiv::MinorTick], + ticks[QwtScaleDiv::MediumTick]); } - for ( int i = 0; i < QwtScaleDiv::NTickTypes; i++ ) - { - ticks[i] = strip( ticks[i], interval ); + for(int i = 0; i < QwtScaleDiv::NTickTypes; i++) { + ticks[i] = strip(ticks[i], interval); // ticks very close to 0.0 are // explicitely set to 0.0 - for ( int j = 0; j < ticks[i].count(); j++ ) - { - if ( qwtFuzzyCompare( ticks[i][j], 0.0, stepSize ) == 0 ) + for(int j = 0; j < ticks[i].count(); j++) { + if(qwtFuzzyCompare(ticks[i][j], 0.0, stepSize) == 0) ticks[i][j] = 0.0; } } } -void OscScaleEngine::buildMinorTicks( const QList& majorTicks, int maxMinorSteps, double stepSize, QList &minorTicks, QList &mediumTicks ) const +void OscScaleEngine::buildMinorTicks(const QList &majorTicks, int maxMinorSteps, double stepSize, + QList &minorTicks, QList &mediumTicks) const { Q_UNUSED(maxMinorSteps) @@ -143,37 +126,35 @@ void OscScaleEngine::buildMinorTicks( const QList& majorTicks, int maxMi const int numTicks = m_minorTicks; int medIndex = -1; - if ( numTicks % 2 ) + if(numTicks % 2) medIndex = numTicks / 2; // calculate minor ticks - int majorTicksCnt = majorTicks.count(); + int majorTicksCnt = majorTicks.count(); - if(m_showZero){ - majorTicksCnt--; - } + if(m_showZero) { + majorTicksCnt--; + } - for ( int i = 0; i < majorTicksCnt; i++ ) - { - double val = majorTicks[i]; + for(int i = 0; i < majorTicksCnt; i++) { + double val = majorTicks[i]; - if(m_showZero){ - double upper = majorTicks[i+1]; - double diff = upper-val; + if(m_showZero) { + double upper = majorTicks[i + 1]; + double diff = upper - val; - minStep = diff / numTicks; - } + minStep = diff / numTicks; + } - for ( int k = 0; k < numTicks; k++ ) - { + for(int k = 0; k < numTicks; k++) { val += minStep; double alignedValue = val; - if ( qwtFuzzyCompare( val, 0.0, stepSize ) == 0 ) + if(qwtFuzzyCompare(val, 0.0, stepSize) == 0) alignedValue = 0.0; - if ( k == medIndex ) + if(k == medIndex) mediumTicks += alignedValue; else minorTicks += alignedValue; @@ -183,48 +164,46 @@ void OscScaleEngine::buildMinorTicks( const QList& majorTicks, int maxMi QList OscScaleEngine::buildMajorTicks(const QwtInterval &interval, double stepSize) const { - if(m_showZero && interval.minValue() < 0 && interval.maxValue() > 0){ - QList majorTicks; - - double range = interval.maxValue()-interval.minValue(); - double upperRange = interval.maxValue() / range; - double lowerRange = fabs(interval.minValue()) / range; - - int underTicks = round(lowerRange * (m_majorTicks -1)); - int overTicks = round(upperRange * (m_majorTicks - 1)); - - if(overTicks == 0){ - overTicks++; - underTicks--; - } - if(underTicks == 0) - { - underTicks++; - overTicks--; - } - if(overTicks + underTicks == m_majorTicks){ - if(underTicks > overTicks) - underTicks--; - else - overTicks--; - } - - double overStep = interval.maxValue() / overTicks; - double underStep = fabs(interval.minValue()) / underTicks; - - double val = interval.maxValue(); - for(int i=0;i 0) { + QList majorTicks; + + double range = interval.maxValue() - interval.minValue(); + double upperRange = interval.maxValue() / range; + double lowerRange = fabs(interval.minValue()) / range; + + int underTicks = round(lowerRange * (m_majorTicks - 1)); + int overTicks = round(upperRange * (m_majorTicks - 1)); + + if(overTicks == 0) { + overTicks++; + underTicks--; + } + if(underTicks == 0) { + underTicks++; + overTicks--; + } + if(overTicks + underTicks == m_majorTicks) { + if(underTicks > overTicks) + underTicks--; + else + overTicks--; + } + + double overStep = interval.maxValue() / overTicks; + double underStep = fabs(interval.minValue()) / underTicks; + + double val = interval.maxValue(); + for(int i = 0; i < overTicks; i++) { + majorTicks.append(val); + val -= overStep; + } + for(int i = 0; i < underTicks + 1; i++) { + majorTicks.append(val); + val -= underStep; + } + + return majorTicks; + } + return QwtLinearScaleEngine::buildMajorTicks(interval, stepSize); } diff --git a/gui/src/osc_scale_zoomer.cpp b/gui/src/osc_scale_zoomer.cpp index b9f2a7074f..eb9cc8496a 100644 --- a/gui/src/osc_scale_zoomer.cpp +++ b/gui/src/osc_scale_zoomer.cpp @@ -18,15 +18,16 @@ * along with this program. If not, see . */ -#include "DisplayPlot.h" #include "osc_scale_zoomer.h" +#include "DisplayPlot.h" + #include using namespace scopy; -OscScaleZoomer::OscScaleZoomer(QWidget *parent) : - LimitedPlotZoomer(parent) +OscScaleZoomer::OscScaleZoomer(QWidget *parent) + : LimitedPlotZoomer(parent) { setTrackerMode(QwtPicker::AlwaysOn); @@ -42,16 +43,12 @@ OscScaleZoomer::OscScaleZoomer(QWidget *parent) : setZoomBase(); } -OscScaleZoomer::~OscScaleZoomer() -{ -} +OscScaleZoomer::~OscScaleZoomer() {} -QwtText OscScaleZoomer::trackerText(const QPoint& pos) const +QwtText OscScaleZoomer::trackerText(const QPoint &pos) const { - const OscScaleDraw *draw_x = static_cast( - plot()->axisScaleDraw(QwtAxis::XTop)); - const OscScaleDraw *draw_y = static_cast( - plot()->axisScaleDraw(QwtAxis::YLeft)); + const OscScaleDraw *draw_x = static_cast(plot()->axisScaleDraw(QwtAxis::XTop)); + const OscScaleDraw *draw_y = static_cast(plot()->axisScaleDraw(QwtAxis::YLeft)); QPointF dp = QwtPlotZoomer::invTransform(pos); QString text; @@ -62,17 +59,11 @@ QwtText OscScaleZoomer::trackerText(const QPoint& pos) const return QwtText(text); } -void OscScaleZoomer::cancel() -{ - reset(); -} +void OscScaleZoomer::cancel() { reset(); } -QColor OscScaleZoomer::getColor() const -{ - return trackerPen().color(); -} +QColor OscScaleZoomer::getColor() const { return trackerPen().color(); } -void OscScaleZoomer::setColor(const QColor& color) +void OscScaleZoomer::setColor(const QColor &color) { QPen pen(color); setRubberBandPen(pen); diff --git a/gui/src/oscilloscope_plot.cpp b/gui/src/oscilloscope_plot.cpp index 0cf36dbb2b..9d739966bc 100644 --- a/gui/src/oscilloscope_plot.cpp +++ b/gui/src/oscilloscope_plot.cpp @@ -19,18 +19,18 @@ */ #include "oscilloscope_plot.hpp" -#include "symbol_controller.h" -#include "handles_area.hpp" -#include "plot_line_handle.h" +#include "handles_area.hpp" #include "logicdatacurve.h" +#include "plot_line_handle.h" #include "scopy-gui_config.h" +#include "symbol_controller.h" +#include #include #include -#include -#include #include +#include #include @@ -41,43 +41,41 @@ using namespace scopy; /* * OscilloscopePlot class */ -OscilloscopePlot::OscilloscopePlot(QWidget *parent, bool isdBgraph, unsigned int xNumDivs, unsigned int yNumDivs - ,PrefixFormatter* pfXaxis, PrefixFormatter* pfYaxis, int qwtAxis): - TimeDomainDisplayPlot(parent, isdBgraph, xNumDivs, yNumDivs, pfXaxis, pfYaxis, qwtAxis) +OscilloscopePlot::OscilloscopePlot(QWidget *parent, bool isdBgraph, unsigned int xNumDivs, unsigned int yNumDivs, + PrefixFormatter *pfXaxis, PrefixFormatter *pfYaxis, int qwtAxis) + : TimeDomainDisplayPlot(parent, isdBgraph, xNumDivs, yNumDivs, pfXaxis, pfYaxis, qwtAxis) { -// setYaxisUnit("V"); + // setYaxisUnit("V"); setMinXaxisDivision(100E-9); // A minimum division of 100 nano second - setMaxXaxisDivision(1E-3); // A maximum division of 1 milli second - until adding decimation - setMinYaxisDivision(1E-6); // A minimum division of 1 micro Volts - setMaxYaxisDivision(10.0); // A maximum division of 10 Volts + setMaxXaxisDivision(1E-3); // A maximum division of 1 milli second - until adding decimation + setMinYaxisDivision(1E-6); // A minimum division of 1 micro Volts + setMaxYaxisDivision(10.0); // A maximum division of 10 Volts } -OscilloscopePlot::~OscilloscopePlot() -{ -} +OscilloscopePlot::~OscilloscopePlot() {} /* * CapturePlot class */ -CapturePlot::CapturePlot(QWidget *parent, bool isdBgraph, unsigned int xNumDivs, unsigned int yNumDivs - ,PrefixFormatter* pfXaxis, PrefixFormatter* pfYaxis, int qwtAxis): - OscilloscopePlot(parent, isdBgraph, xNumDivs, yNumDivs, pfXaxis, pfYaxis, qwtAxis), - d_triggerAEnabled(false), - d_triggerBEnabled(false), - d_measurementsEnabled(false), - d_bufferSizeLabelVal(0), - d_sampleRateLabelVal(1.0), - d_labelsEnabled(false), - d_timeTriggerMinValue(-1), - d_timeTriggerMaxValue(1), - d_bonusWidth(0), - d_gatingEnabled(false), - m_conversion_function(nullptr), - d_startedGrouping(false), - d_xAxisInterval{0.0, 0.0}, - d_currentHandleInitPx(30), - d_maxBufferError(nullptr) +CapturePlot::CapturePlot(QWidget *parent, bool isdBgraph, unsigned int xNumDivs, unsigned int yNumDivs, + PrefixFormatter *pfXaxis, PrefixFormatter *pfYaxis, int qwtAxis) + : OscilloscopePlot(parent, isdBgraph, xNumDivs, yNumDivs, pfXaxis, pfYaxis, qwtAxis) + , d_triggerAEnabled(false) + , d_triggerBEnabled(false) + , d_measurementsEnabled(false) + , d_bufferSizeLabelVal(0) + , d_sampleRateLabelVal(1.0) + , d_labelsEnabled(false) + , d_timeTriggerMinValue(-1) + , d_timeTriggerMaxValue(1) + , d_bonusWidth(0) + , d_gatingEnabled(false) + , m_conversion_function(nullptr) + , d_startedGrouping(false) + , d_xAxisInterval{0.0, 0.0} + , d_currentHandleInitPx(30) + , d_maxBufferError(nullptr) { setMinimumHeight(200); setMinimumWidth(200); @@ -100,8 +98,7 @@ CapturePlot::CapturePlot(QWidget *parent, bool isdBgraph, unsigned int xNumDivs d_topWidget->setStyleSheet("QWidget {background-color: transparent}"); d_topWidget->setMinimumHeight(50); - d_topWidget->setSizePolicy(QSizePolicy::Fixed, - QSizePolicy::Fixed); + d_topWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); d_topGateHandlesArea->setMinimumHeight(20); d_topGateHandlesArea->setLargestChildWidth(80); @@ -113,9 +110,9 @@ CapturePlot::CapturePlot(QWidget *parent, bool isdBgraph, unsigned int xNumDivs // Time Base d_timeBaseLabel = new QLabel(this); d_timeBaseLabel->setStyleSheet("QLabel {" - "color: #4a64ff;" - "font-weight: bold;" - "}"); + "color: #4a64ff;" + "font-weight: bold;" + "}"); // Call to minimumSizeHint() is required. Otherwise font properties from // stylesheet will be ignored when calculating width using FontMetrics @@ -135,28 +132,23 @@ CapturePlot::CapturePlot(QWidget *parent, bool isdBgraph, unsigned int xNumDivs d_maxBufferError = new QLabel(this); d_maxBufferError->setStyleSheet("QLabel {" - "color: #ff0000;" - "}"); + "color: #ff0000;" + "}"); d_maxBufferError->setWordWrap(true); // Top area layout QWidget *oldStatusWidget = new QWidget(); QHBoxLayout *topWidgetLayout = new QHBoxLayout(oldStatusWidget); - topWidgetLayout->setContentsMargins(d_leftHandlesArea->minimumWidth(), - 0, d_rightHandlesArea->minimumWidth(), 5); + topWidgetLayout->setContentsMargins(d_leftHandlesArea->minimumWidth(), 0, d_rightHandlesArea->minimumWidth(), + 5); topWidgetLayout->setSpacing(10); - topWidgetLayout->insertWidget(0, d_timeBaseLabel, 0, Qt::AlignLeft | - Qt::AlignBottom); - topWidgetLayout->insertWidget(1, d_sampleRateLabel, 0, Qt::AlignLeft | - Qt::AlignBottom); - topWidgetLayout->insertWidget(2, d_maxBufferError, 0, Qt::AlignRight | - Qt::AlignBottom); - topWidgetLayout->insertWidget(3, d_triggerStateLabel, 0, Qt::AlignRight | - Qt::AlignBottom); - - QSpacerItem *spacerItem = new QSpacerItem(0, 0, QSizePolicy::Expanding, - QSizePolicy::Fixed); + topWidgetLayout->insertWidget(0, d_timeBaseLabel, 0, Qt::AlignLeft | Qt::AlignBottom); + topWidgetLayout->insertWidget(1, d_sampleRateLabel, 0, Qt::AlignLeft | Qt::AlignBottom); + topWidgetLayout->insertWidget(2, d_maxBufferError, 0, Qt::AlignRight | Qt::AlignBottom); + topWidgetLayout->insertWidget(3, d_triggerStateLabel, 0, Qt::AlignRight | Qt::AlignBottom); + + QSpacerItem *spacerItem = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed); topWidgetLayout->insertSpacerItem(2, spacerItem); oldStatusWidget->setLayout(topWidgetLayout); @@ -164,8 +156,8 @@ CapturePlot::CapturePlot(QWidget *parent, bool isdBgraph, unsigned int xNumDivs d_topWidget->addWidget(m_statusWidget); QHBoxLayout *stackWidgetLayout = new QHBoxLayout(d_topWidget); - stackWidgetLayout->setContentsMargins(d_leftHandlesArea->minimumWidth(), - 0, d_rightHandlesArea->minimumWidth(), 5); + stackWidgetLayout->setContentsMargins(d_leftHandlesArea->minimumWidth(), 0, d_rightHandlesArea->minimumWidth(), + 5); d_topWidget->setLayout(stackWidgetLayout); /* Time trigger widget */ @@ -175,47 +167,39 @@ CapturePlot::CapturePlot(QWidget *parent, bool isdBgraph, unsigned int xNumDivs d_timeTriggerBar->setCanLeavePlot(true); d_timeTriggerHandle = new FreePlotLineHandleH( - QPixmap(":/gui/icons/time_trigger_handle.svg"), - QPixmap(":/gui/icons/time_trigger_left.svg"), - QPixmap(":/gui/icons/time_trigger_right.svg"), - d_bottomHandlesArea); + QPixmap(":/gui/icons/time_trigger_handle.svg"), QPixmap(":/gui/icons/time_trigger_left.svg"), + QPixmap(":/gui/icons/time_trigger_right.svg"), d_bottomHandlesArea); d_timeTriggerHandle->setPen(d_timeTriggerActiveLinePen); - connect(d_timeTriggerHandle, SIGNAL(grabbedChanged(bool)), - SLOT(onTimeTriggerHandleGrabbed(bool))); + connect(d_timeTriggerHandle, SIGNAL(grabbedChanged(bool)), SLOT(onTimeTriggerHandleGrabbed(bool))); - connect(d_timeTriggerHandle, SIGNAL(positionChanged(int)), - SLOT(onTimeTriggerHandlePosChanged(int))); + connect(d_timeTriggerHandle, SIGNAL(positionChanged(int)), SLOT(onTimeTriggerHandlePosChanged(int))); /* When bar position changes due to plot resizes update the handle */ - connect(d_timeTriggerBar, &VertBar::pixelPositionChanged, - [=](int pos) { + connect(d_timeTriggerBar, &VertBar::pixelPositionChanged, [=](int pos) { updateHandleAreaPadding(d_labelsEnabled); d_timeTriggerHandle->setPositionSilenty(pos); }); - connect(d_timeTriggerHandle, &FreePlotLineHandleH::positionChanged, - d_timeTriggerBar, &VertBar::setPixelPosition); + connect(d_timeTriggerHandle, &FreePlotLineHandleH::positionChanged, d_timeTriggerBar, + &VertBar::setPixelPosition); - connect(d_timeTriggerHandle, &RoundedHandleV::mouseReleased, - [=]() { - double pos = d_timeTriggerHandle->position(); + connect(d_timeTriggerHandle, &RoundedHandleV::mouseReleased, [=]() { + double pos = d_timeTriggerHandle->position(); - QwtScaleMap xMap = this->canvasMap(QwtAxisId(QwtAxis::XBottom, 0)); - double min = -(xAxisNumDiv() / 2.0) * HorizUnitsPerDiv(); - double max = (xAxisNumDiv() / 2.0) * HorizUnitsPerDiv(); + QwtScaleMap xMap = this->canvasMap(QwtAxisId(QwtAxis::XBottom, 0)); + double min = -(xAxisNumDiv() / 2.0) * HorizUnitsPerDiv(); + double max = (xAxisNumDiv() / 2.0) * HorizUnitsPerDiv(); - xMap.setScaleInterval(min, max); - double time = xMap.invTransform(pos); + xMap.setScaleInterval(min, max); + double time = xMap.invTransform(pos); - if (time < d_timeTriggerMinValue) { - d_timeTriggerBar->setPixelPosition( - xMap.transform(d_timeTriggerMinValue)); - } - if (time > d_timeTriggerMaxValue) { - d_timeTriggerBar->setPixelPosition( - xMap.transform(d_timeTriggerMaxValue)); - } + if(time < d_timeTriggerMinValue) { + d_timeTriggerBar->setPixelPosition(xMap.transform(d_timeTriggerMinValue)); + } + if(time > d_timeTriggerMaxValue) { + d_timeTriggerBar->setPixelPosition(xMap.transform(d_timeTriggerMaxValue)); + } }); /* Level triggers widgets */ @@ -226,26 +210,20 @@ CapturePlot::CapturePlot(QWidget *parent, bool isdBgraph, unsigned int xNumDivs d_levelTriggerABar->setCanLeavePlot(true); d_levelTriggerAHandle = new FreePlotLineHandleV( - QPixmap(":/gui/icons/level_trigger_handle.svg"), - QPixmap(":/gui/icons/level_trigger_up.svg"), - QPixmap(":/gui/icons/level_trigger_down.svg"), - d_rightHandlesArea); + QPixmap(":/gui/icons/level_trigger_handle.svg"), QPixmap(":/gui/icons/level_trigger_up.svg"), + QPixmap(":/gui/icons/level_trigger_down.svg"), d_rightHandlesArea); d_levelTriggerAHandle->setPen(d_timeTriggerActiveLinePen); d_levelTriggerABar->setVisible(false); d_levelTriggerAHandle->setVisible(false); /* When a handle position changes the bar follows */ - connect(d_levelTriggerAHandle, SIGNAL(positionChanged(int)), - d_levelTriggerABar, SLOT(setPixelPosition(int))); + connect(d_levelTriggerAHandle, SIGNAL(positionChanged(int)), d_levelTriggerABar, SLOT(setPixelPosition(int))); /* When bar position changes due to plot resizes update the handle */ connect(d_levelTriggerABar, &HorizBar::pixelPositionChanged, - [=](int pos) { - d_levelTriggerAHandle->setPositionSilenty(pos); - }); + [=](int pos) { d_levelTriggerAHandle->setPositionSilenty(pos); }); /* When handle is grabbed change bar drawing style */ - connect(d_levelTriggerAHandle, SIGNAL(grabbedChanged(bool)), - SLOT(onTriggerAHandleGrabbed(bool))); + connect(d_levelTriggerAHandle, SIGNAL(grabbedChanged(bool)), SLOT(onTriggerAHandleGrabbed(bool))); // Trigger B d_levelTriggerBBar = new HorizBar(this); @@ -254,40 +232,30 @@ CapturePlot::CapturePlot(QWidget *parent, bool isdBgraph, unsigned int xNumDivs d_levelTriggerBBar->setCanLeavePlot(true); d_levelTriggerBHandle = new FreePlotLineHandleV( - QPixmap(":/gui/icons/level_trigger_handle.svg"), - QPixmap(":/gui/icons/level_trigger_up.svg"), - QPixmap(":/gui/icons/level_trigger_down.svg"), - d_rightHandlesArea); + QPixmap(":/gui/icons/level_trigger_handle.svg"), QPixmap(":/gui/icons/level_trigger_up.svg"), + QPixmap(":/gui/icons/level_trigger_down.svg"), d_rightHandlesArea); d_levelTriggerBHandle->setPen(d_trigBactiveLinePen); d_levelTriggerBBar->setVisible(false); d_levelTriggerBHandle->setVisible(false); /* When a handle position changes the bar follows */ - connect(d_levelTriggerBHandle, SIGNAL(positionChanged(int)), - d_levelTriggerBBar, SLOT(setPixelPosition(int))); + connect(d_levelTriggerBHandle, SIGNAL(positionChanged(int)), d_levelTriggerBBar, SLOT(setPixelPosition(int))); /* When bar position changes due to plot resizes update the handle */ connect(d_levelTriggerBBar, &HorizBar::pixelPositionChanged, - [=](int pos) { - d_levelTriggerBHandle->setPositionSilenty(pos); - }); + [=](int pos) { d_levelTriggerBHandle->setPositionSilenty(pos); }); /* When handle is grabbed change bar drawing style */ - connect(d_levelTriggerBHandle, SIGNAL(grabbedChanged(bool)), - SLOT(onTriggerBHandleGrabbed(bool))); + connect(d_levelTriggerBHandle, SIGNAL(grabbedChanged(bool)), SLOT(onTriggerBHandleGrabbed(bool))); /* Measurement gate cursors */ - d_hGatingHandle1 = new PlotGateHandle( - QPixmap(":/gui/icons/gate_handle.svg"), - d_topGateHandlesArea); + d_hGatingHandle1 = new PlotGateHandle(QPixmap(":/gui/icons/gate_handle.svg"), d_topGateHandlesArea); - d_hGatingHandle2 = new PlotGateHandle( - QPixmap(":/gui/icons/gate_handle.svg"), - d_topGateHandlesArea); + d_hGatingHandle2 = new PlotGateHandle(QPixmap(":/gui/icons/gate_handle.svg"), d_topGateHandlesArea); d_hGatingHandle1->setCenterLeft(false); - d_gateBar1 = new VertBar(this,true); - d_gateBar2 = new VertBar(this,true); + d_gateBar1 = new VertBar(this, true); + d_gateBar2 = new VertBar(this, true); d_gateBar1->setVisible(false); d_gateBar2->setVisible(false); @@ -296,7 +264,7 @@ CapturePlot::CapturePlot(QWidget *parent, bool isdBgraph, unsigned int xNumDivs d_symbolCtrl->attachSymbol(d_gateBar2); /* gate bars */ - QPen gatePen = QPen(QColor(255,255,255),1,Qt::SolidLine); + QPen gatePen = QPen(QColor(255, 255, 255), 1, Qt::SolidLine); d_gateBar1->setPen(gatePen); d_gateBar2->setPen(gatePen); @@ -309,27 +277,25 @@ CapturePlot::CapturePlot(QWidget *parent, bool isdBgraph, unsigned int xNumDivs d_cursorMetricFormatter.setTwoDecimalMode(false); d_cursorTimeFormatter.setTwoDecimalMode(false); - connect(d_hGatingHandle1, &PlotLineHandleH::positionChanged,[=](int value){ + connect(d_hGatingHandle1, &PlotLineHandleH::positionChanged, [=](int value) { d_hGatingHandle2->setOtherCursorPosition(d_hGatingHandle1->position()); /* make sure that the gate handles don't cross each other */ - if(d_hGatingHandle1->position() <= d_hGatingHandle2->position()){ + if(d_hGatingHandle1->position() <= d_hGatingHandle2->position()) { d_gateBar1->setPixelPosition(value); - } - else{ + } else { d_gateBar1->setPixelPosition(d_hGatingHandle2->position()); d_hGatingHandle1->setPosition(d_hGatingHandle2->position()); } }); - connect(d_hGatingHandle2, &PlotLineHandleH::positionChanged,[=](int value){ + connect(d_hGatingHandle2, &PlotLineHandleH::positionChanged, [=](int value) { d_hGatingHandle1->setOtherCursorPosition(d_hGatingHandle2->position()); /* make sure that the gate handles don't cross each other */ - if(d_hGatingHandle2->position() >= d_hGatingHandle1->position()){ + if(d_hGatingHandle2->position() >= d_hGatingHandle1->position()) { d_gateBar2->setPixelPosition(value); - } - else{ + } else { d_gateBar2->setPixelPosition(d_hGatingHandle1->position()); d_hGatingHandle2->setPosition(d_hGatingHandle1->position()); } @@ -343,52 +309,41 @@ CapturePlot::CapturePlot(QWidget *parent, bool isdBgraph, unsigned int xNumDivs d_hGatingHandle1->setOtherCursorPosition(d_hGatingHandle2->position()); d_hGatingHandle2->setOtherCursorPosition(d_hGatingHandle1->position()); - connect(d_timeTriggerHandle, &FreePlotLineHandleH::reset, [=](){ - Q_EMIT timeTriggerValueChanged(0); - }); - connect(d_levelTriggerAHandle, &FreePlotLineHandleV::reset, [=](){ - d_levelTriggerABar->setPlotCoord( - QPointF(d_levelTriggerABar->plotCoord().x(), 0)); - }); + connect(d_timeTriggerHandle, &FreePlotLineHandleH::reset, [=]() { Q_EMIT timeTriggerValueChanged(0); }); + connect(d_levelTriggerAHandle, &FreePlotLineHandleV::reset, + [=]() { d_levelTriggerABar->setPlotCoord(QPointF(d_levelTriggerABar->plotCoord().x(), 0)); }); - connect(d_gateBar1,SIGNAL(pixelPositionChanged(int)), - SLOT(onGateBar1PixelPosChanged(int))); - connect(d_gateBar2,SIGNAL(pixelPositionChanged(int)), - SLOT(onGateBar2PixelPosChanged(int))); + connect(d_gateBar1, SIGNAL(pixelPositionChanged(int)), SLOT(onGateBar1PixelPosChanged(int))); + connect(d_gateBar2, SIGNAL(pixelPositionChanged(int)), SLOT(onGateBar2PixelPosChanged(int))); - connect(d_gateBar1,SIGNAL(positionChanged(double)), - SLOT(onGateBar1Moved(double))); - connect(d_gateBar2,SIGNAL(positionChanged(double)), - SLOT(onGateBar2Moved(double))); + connect(d_gateBar1, SIGNAL(positionChanged(double)), SLOT(onGateBar1Moved(double))); + connect(d_gateBar2, SIGNAL(positionChanged(double)), SLOT(onGateBar2Moved(double))); /* Apply measurements for every new batch of data */ - connect(this, SIGNAL(newData()), - SLOT(onNewDataReceived())); + connect(this, SIGNAL(newData()), SLOT(onNewDataReceived())); /* Add offset widgets for each new channel */ - connect(this, SIGNAL(channelAdded(int)), - SLOT(onChannelAdded(int))); + connect(this, SIGNAL(channelAdded(int)), SLOT(onChannelAdded(int))); - connect(this, &TimeDomainDisplayPlot::digitalPlotCurveAdded, - this, &CapturePlot::onDigitalChannelAdded); + connect(this, &TimeDomainDisplayPlot::digitalPlotCurveAdded, this, &CapturePlot::onDigitalChannelAdded); installEventFilter(this); QwtScaleWidget *scaleWidget = axisWidget(QwtAxis::XBottom); - const int fmw = QFontMetrics( scaleWidget->font()).horizontalAdvance("-XXX.XXX XX"); - //WIP: elimination of unnecessary spaces - scaleWidget->setMinBorderDist(0, 0);//fmw / 2 + 30, fmw / 2 + 30); + const int fmw = QFontMetrics(scaleWidget->font()).horizontalAdvance("-XXX.XXX XX"); + // WIP: elimination of unnecessary spaces + scaleWidget->setMinBorderDist(0, 0); // fmw / 2 + 30, fmw / 2 + 30); displayGraticule = false; graticule = new Graticule(this); - connect(this, SIGNAL(canvasSizeChanged()),graticule,SLOT(onCanvasSizeChanged())); + connect(this, SIGNAL(canvasSizeChanged()), graticule, SLOT(onCanvasSizeChanged())); - QBrush gateBrush = QBrush(QColor(0,30,150,90)); + QBrush gateBrush = QBrush(QColor(0, 30, 150, 90)); gateBrush.setStyle(Qt::SolidPattern); /* configure the measurement gates */ leftGate = new QwtPlotShapeItem(); - leftGate->setAxes(QwtAxis::XBottom,QwtAxis::YRight); + leftGate->setAxes(QwtAxis::XBottom, QwtAxis::YRight); leftGateRect.setTop(axisScaleDiv(QwtAxis::YRight).upperBound()); leftGateRect.setBottom(axisScaleDiv(QwtAxis::YRight).lowerBound()); leftGateRect.setLeft(axisScaleDiv(QwtAxis::XBottom).lowerBound()); @@ -397,14 +352,13 @@ CapturePlot::CapturePlot(QWidget *parent, bool isdBgraph, unsigned int xNumDivs leftGate->setBrush(gateBrush); rightGate = new QwtPlotShapeItem(); - rightGate->setAxes(QwtAxis::XBottom,QwtAxis::YRight); + rightGate->setAxes(QwtAxis::XBottom, QwtAxis::YRight); rightGateRect.setTop(axisScaleDiv(QwtAxis::YRight).upperBound()); rightGateRect.setBottom(axisScaleDiv(QwtAxis::YRight).lowerBound()); rightGateRect.setLeft(d_gateBar2->plotCoord().x()); rightGateRect.setRight(axisScaleDiv(QwtAxis::XBottom).upperBound()); rightGate->setRect(rightGateRect); rightGate->setBrush(gateBrush); - } CapturePlot::~CapturePlot() @@ -412,7 +366,7 @@ CapturePlot::~CapturePlot() canvas()->removeEventFilter(d_cursorReadouts); removeEventFilter(this); canvas()->removeEventFilter(d_symbolCtrl); - for (auto it = d_measureObjs.begin(); it != d_measureObjs.end(); ++it) { + for(auto it = d_measureObjs.begin(); it != d_measureObjs.end(); ++it) { delete *it; } delete graticule; @@ -430,23 +384,19 @@ QString CapturePlot::formatYValue(double value, int precision) const return d_cursorMetricFormatter.format(value, "", precision); } -CursorReadouts * CapturePlot::getCursorReadouts() const -{ - return d_cursorReadouts; -} +CursorReadouts *CapturePlot::getCursorReadouts() const { return d_cursorReadouts; } void CapturePlot::replot() { TimeDomainDisplayPlot::replot(); - if (!d_bottomHandlesArea) { + if(!d_bottomHandlesArea) { return; } const QwtInterval interval = axisInterval(QwtAxis::XBottom); - if (interval.minValue() != d_xAxisInterval.first - || interval.maxValue() != d_xAxisInterval.second) { + if(interval.minValue() != d_xAxisInterval.first || interval.maxValue() != d_xAxisInterval.second) { d_bottomHandlesArea->repaint(); @@ -455,20 +405,11 @@ void CapturePlot::replot() } } -QList* CapturePlot::getMeasurements() -{ - return &d_measureObjs; -} +QList *CapturePlot::getMeasurements() { return &d_measureObjs; } -HorizBar *CapturePlot::levelTriggerA() -{ - return d_levelTriggerABar; -} +HorizBar *CapturePlot::levelTriggerA() { return d_levelTriggerABar; } -HorizBar *CapturePlot::levelTriggerB() -{ - return d_levelTriggerBBar; -} +HorizBar *CapturePlot::levelTriggerB() { return d_levelTriggerBBar; } void CapturePlot::enableTimeTrigger(bool enable) { @@ -484,14 +425,9 @@ void CapturePlot::setAllAxes(int ch_id) DisplayPlot::setCursorAxes(fixed_axis, mobile_axis); } -VertBar *CapturePlot::getMeasurementGateBar1() -{ - return d_gateBar1; -} +VertBar *CapturePlot::getMeasurementGateBar1() { return d_gateBar1; } -VertBar *CapturePlot::getMeasurementGateBar2() { - return d_gateBar2; -} +VertBar *CapturePlot::getMeasurementGateBar2() { return d_gateBar2; } void CapturePlot::onVCursor1Moved(double value) { @@ -505,13 +441,13 @@ void CapturePlot::onVCursor1Moved(double value) d_cursorReadouts->setTimeDeltaText(text); d_cursorReadoutsText.tDelta = text; - if (diff !=0 ) + if(diff != 0) text = d_cursorMetricFormatter.format(1 / diff, "Hz", 3); else text = "Infinity"; d_cursorReadouts->setFreqDeltaText(text); d_cursorReadoutsText.freq = text; - if (d_trackMode) { + if(d_trackMode) { onHCursor1Moved(getHorizontalCursorIntersection(d_vBar1->plotCoord().x())); } @@ -531,13 +467,13 @@ void CapturePlot::onVCursor2Moved(double value) d_cursorReadouts->setTimeDeltaText(text); d_cursorReadoutsText.tDelta = text; - if (diff !=0 ) + if(diff != 0) text = d_cursorMetricFormatter.format(1 / diff, "Hz", 3); else text = "Infinity"; d_cursorReadouts->setFreqDeltaText(text); d_cursorReadoutsText.freq = text; - if (d_trackMode) { + if(d_trackMode) { onHCursor2Moved(getHorizontalCursorIntersection(d_vBar2->plotCoord().x())); } @@ -547,33 +483,30 @@ void CapturePlot::onVCursor2Moved(double value) void CapturePlot::setStatusWidget(QWidget *newStatusWidget) { - if (!m_statusWidget->layout()) { + if(!m_statusWidget->layout()) { QHBoxLayout *statusWidgetLayout = new QHBoxLayout(m_statusWidget); statusWidgetLayout->setSpacing(0); - statusWidgetLayout->setContentsMargins(d_leftHandlesArea->minimumWidth(), - 0, d_rightHandlesArea->minimumWidth(), 5); - statusWidgetLayout->insertWidget(0, newStatusWidget, 0, Qt::AlignLeft | - Qt::AlignBottom); + statusWidgetLayout->setContentsMargins(d_leftHandlesArea->minimumWidth(), 0, + d_rightHandlesArea->minimumWidth(), 5); + statusWidgetLayout->insertWidget(0, newStatusWidget, 0, Qt::AlignLeft | Qt::AlignBottom); d_topWidget->setCurrentIndex(1); } } -QList CapturePlot::getOffsetHandles() const -{ - return d_offsetHandles; -} +QList CapturePlot::getOffsetHandles() const { return d_offsetHandles; } void CapturePlot::onHCursor1Moved(double value) { QString text; bool error = false; - if (d_trackMode) { - if (value == ERROR_VALUE) { + if(d_trackMode) { + if(value == ERROR_VALUE) { error = true; } - if (dynamic_cast(sender()) != nullptr) return; + if(dynamic_cast(sender()) != nullptr) + return; } value *= d_displayScale; @@ -582,13 +515,13 @@ void CapturePlot::onHCursor1Moved(double value) d_cursorReadoutsText.v1 = error ? "-" : text; double valueCursor2; - if (d_trackMode) { + if(d_trackMode) { valueCursor2 = getHorizontalCursorIntersection(d_vBar2->plotCoord().x()); } else { valueCursor2 = d_hBar2->plotCoord().y(); } - double diff = value - (valueCursor2 * d_displayScale) ; + double diff = value - (valueCursor2 * d_displayScale); text = d_cursorMetricFormatter.format(diff, "V", 3); d_cursorReadouts->setVoltageDeltaText(error ? "-" : text); d_cursorReadoutsText.vDelta = error ? "-" : text; @@ -602,12 +535,13 @@ void CapturePlot::onHCursor2Moved(double value) QString text; bool error = false; - if (d_trackMode) { - if (value == ERROR_VALUE) { + if(d_trackMode) { + if(value == ERROR_VALUE) { error = true; } - if (dynamic_cast(sender()) != nullptr) return; + if(dynamic_cast(sender()) != nullptr) + return; } value *= d_displayScale; @@ -616,7 +550,7 @@ void CapturePlot::onHCursor2Moved(double value) d_cursorReadoutsText.v2 = error ? "-" : text; double valueCursor1; - if (d_trackMode) { + if(d_trackMode) { valueCursor1 = getHorizontalCursorIntersection(d_vBar1->plotCoord().x()); } else { valueCursor1 = d_hBar1->plotCoord().y(); @@ -646,11 +580,11 @@ void CapturePlot::onGateBar2PixelPosChanged(int pos) void CapturePlot::onGateBar1Moved(double value) { - if (d_selected_channel < 0) { + if(d_selected_channel < 0) { return; } - //update gate handle + // update gate handle leftGateRect.setTop(axisScaleDiv(QwtAxis::YRight).upperBound()); leftGateRect.setBottom(axisScaleDiv(QwtAxis::YRight).lowerBound()); leftGateRect.setLeft(axisScaleDiv(QwtAxis::XBottom).lowerBound()); @@ -662,25 +596,26 @@ void CapturePlot::onGateBar1Moved(double value) double maxTime = 0; double minTime = 0; - if (n == 0) { + if(n == 0) { maxTime = axisScaleDiv(QwtAxis::XBottom).upperBound(); minTime = axisScaleDiv(QwtAxis::XBottom).lowerBound(); } else { - maxTime = Curve(d_selected_channel)->data()->sample(n-1).x(); + maxTime = Curve(d_selected_channel)->data()->sample(n - 1).x(); minTime = Curve(d_selected_channel)->data()->sample(0).x(); } - //data index to start measurement - int currentIndex = (value - minTime) / (maxTime-minTime) * n; + // data index to start measurement + int currentIndex = (value - minTime) / (maxTime - minTime) * n; - for (int i = 0; i < d_measureObjs.size(); i++) { + for(int i = 0; i < d_measureObjs.size(); i++) { M2kMeasure *measure = d_measureObjs[i]; measure->setStartIndex(currentIndex); } value_gateLeft = value; - //find the percentage of the gate in relation with plot width - double width = (value - axisScaleDiv(QwtAxis::XBottom).lowerBound()) / (axisScaleDiv(QwtAxis::XBottom).upperBound() - axisScaleDiv(QwtAxis::XBottom).lowerBound()); + // find the percentage of the gate in relation with plot width + double width = (value - axisScaleDiv(QwtAxis::XBottom).lowerBound()) / + (axisScaleDiv(QwtAxis::XBottom).upperBound() - axisScaleDiv(QwtAxis::XBottom).lowerBound()); Q_EMIT leftGateChanged(width); d_hGatingHandle1->setTimeValue(d_gateBar1->plotCoord().x()); @@ -690,11 +625,11 @@ void CapturePlot::onGateBar1Moved(double value) void CapturePlot::onGateBar2Moved(double value) { - if (d_selected_channel < 0) { + if(d_selected_channel < 0) { return; } - //update gate handle + // update gate handle rightGateRect.setTop(axisScaleDiv(QwtAxis::YRight).upperBound()); rightGateRect.setBottom(axisScaleDiv(QwtAxis::YRight).lowerBound()); rightGateRect.setLeft(value); @@ -706,96 +641,76 @@ void CapturePlot::onGateBar2Moved(double value) double maxTime = 0; double minTime = 0; - if (n == 0) { + if(n == 0) { maxTime = axisScaleDiv(QwtAxis::XBottom).upperBound(); minTime = axisScaleDiv(QwtAxis::XBottom).lowerBound(); } else { - maxTime = Curve(d_selected_channel)->data()->sample(n-1).x(); + maxTime = Curve(d_selected_channel)->data()->sample(n - 1).x(); minTime = Curve(d_selected_channel)->data()->sample(0).x(); } - //data index to end measurement - int currentIndex = (value - minTime) / (maxTime-minTime) * n; + // data index to end measurement + int currentIndex = (value - minTime) / (maxTime - minTime) * n; - for (int i = 0; i < d_measureObjs.size(); i++) { + for(int i = 0; i < d_measureObjs.size(); i++) { M2kMeasure *measure = d_measureObjs[i]; measure->setEndIndex(currentIndex); } value_gateRight = value; - //find the percentage of the gate in relation with plot width - double width = (axisScaleDiv(QwtAxis::XBottom).upperBound() - value) / (axisScaleDiv(QwtAxis::XBottom).upperBound() - axisScaleDiv(QwtAxis::XBottom).lowerBound()); + // find the percentage of the gate in relation with plot width + double width = (axisScaleDiv(QwtAxis::XBottom).upperBound() - value) / + (axisScaleDiv(QwtAxis::XBottom).upperBound() - axisScaleDiv(QwtAxis::XBottom).lowerBound()); Q_EMIT rightGateChanged(width); d_hGatingHandle2->setTimeValue(d_gateBar2->plotCoord().x()); replot(); } -QWidget * CapturePlot::topArea() -{ - return d_topWidget; -} +QWidget *CapturePlot::topArea() { return d_topWidget; } -QWidget * CapturePlot::topHandlesArea() +QWidget *CapturePlot::topHandlesArea() { - /* handle area for gate cursors */ - return d_topGateHandlesArea; + /* handle area for gate cursors */ + return d_topGateHandlesArea; } -void CapturePlot::setBonusWidthForHistogram(int width) -{ - d_bonusWidth = width; -} +void CapturePlot::setBonusWidthForHistogram(int width) { d_bonusWidth = width; } void CapturePlot::setTriggerAEnabled(bool en) { - if (d_triggerAEnabled != en) { + if(d_triggerAEnabled != en) { d_triggerAEnabled = en; d_levelTriggerABar->setVisible(en); d_levelTriggerAHandle->setVisible(en); } } -bool CapturePlot::triggerAEnabled() -{ - return d_triggerAEnabled; -} +bool CapturePlot::triggerAEnabled() { return d_triggerAEnabled; } void CapturePlot::setTriggerBEnabled(bool en) { - if (d_triggerBEnabled != en) { + if(d_triggerBEnabled != en) { d_triggerBEnabled = en; d_levelTriggerBBar->setVisible(en); d_levelTriggerBHandle->setVisible(en); } } -bool CapturePlot::triggerBEnabled() -{ - return d_triggerBEnabled; -} +bool CapturePlot::triggerBEnabled() { return d_triggerBEnabled; } void CapturePlot::setSelectedChannel(int id) { - if (d_selected_channel != id) { + if(d_selected_channel != id) { d_selected_channel = id; } } -int CapturePlot::selectedChannel() -{ - return d_selected_channel; -} +int CapturePlot::selectedChannel() { return d_selected_channel; } -void CapturePlot::setMeasuremensEnabled(bool en) -{ - d_measurementsEnabled = en; -} +void CapturePlot::setMeasuremensEnabled(bool en) { d_measurementsEnabled = en; } -bool CapturePlot::measurementsEnabled() -{ - return d_measurementsEnabled; -} +bool CapturePlot::measurementsEnabled() { return d_measurementsEnabled; } void CapturePlot::onTimeTriggerHandlePosChanged(int pos) { @@ -808,8 +723,9 @@ void CapturePlot::onTimeTriggerHandlePosChanged(int pos) Q_EMIT timeTriggerValueChanged(-time); } -void CapturePlot::onTimeTriggerHandleGrabbed(bool grabbed) { - if (grabbed) +void CapturePlot::onTimeTriggerHandleGrabbed(bool grabbed) +{ + if(grabbed) d_timeTriggerBar->setPen(d_timeTriggerActiveLinePen); else d_timeTriggerBar->setPen(d_timeTriggerInactiveLinePen); @@ -818,7 +734,7 @@ void CapturePlot::onTimeTriggerHandleGrabbed(bool grabbed) { void CapturePlot::onTriggerAHandleGrabbed(bool grabbed) { - if (grabbed) + if(grabbed) d_levelTriggerABar->setPen(d_timeTriggerActiveLinePen); else d_levelTriggerABar->setPen(d_timeTriggerInactiveLinePen); @@ -827,7 +743,7 @@ void CapturePlot::onTriggerAHandleGrabbed(bool grabbed) void CapturePlot::onTriggerBHandleGrabbed(bool grabbed) { - if (grabbed) + if(grabbed) d_levelTriggerBBar->setPen(d_trigBactiveLinePen); else d_levelTriggerBBar->setPen(d_trigBinactiveLinePen); @@ -842,7 +758,7 @@ void CapturePlot::showEvent(QShowEvent *event) d_hCursorHandle2->triggerMove(); } -void CapturePlot::printWithNoBackground(const QString& toolName, bool editScaleDraw) +void CapturePlot::printWithNoBackground(const QString &toolName, bool editScaleDraw) { QwtPlotMarker detailsMarker; detailsMarker.setAxes(QwtAxis::XBottom, m_qwtYAxis); @@ -857,10 +773,10 @@ void CapturePlot::printWithNoBackground(const QString& toolName, bool editScaleD text.setColor(QColor(0, 0, 0)); detailsMarker.setLabel(text); - QVector markers; + QVector markers; - for(int i = 0; i < plot_logic_curves.size(); i++){ - if(plot_logic_curves.at(i)->plot() != NULL){ + for(int i = 0; i < plot_logic_curves.size(); i++) { + if(plot_logic_curves.at(i)->plot() != NULL) { double yCoord = plot_logic_curves.at(i)->getPixelOffset(); double xCoord = axisInterval(QwtAxis::XBottom).minValue(); @@ -878,24 +794,21 @@ void CapturePlot::printWithNoBackground(const QString& toolName, bool editScaleD replot(); DisplayPlot::printWithNoBackground(toolName, editScaleDraw); - for(auto marker: markers){ + for(auto marker : markers) { marker->detach(); delete marker; } } -int CapturePlot::getAnalogChannels() const -{ - return d_ydata.size() + d_ref_ydata.size(); -} +int CapturePlot::getAnalogChannels() const { return d_ydata.size() + d_ref_ydata.size(); } -M2kMeasure* CapturePlot::measureOfChannel(int chnIdx) const +M2kMeasure *CapturePlot::measureOfChannel(int chnIdx) const { M2kMeasure *measure = nullptr; auto it = std::find_if(d_measureObjs.begin(), d_measureObjs.end(), - [&](M2kMeasure *m) { return m->channel() == chnIdx; }); - if (it != d_measureObjs.end()) + [&](M2kMeasure *m) { return m->channel() == chnIdx; }); + if(it != d_measureObjs.end()) measure = *it; return measure; @@ -903,8 +816,8 @@ M2kMeasure* CapturePlot::measureOfChannel(int chnIdx) const void CapturePlot::bringCurveToFront(unsigned int curveIdx) { - for (auto &item : d_offsetHandles) { - if (item->pen().color() == getLineColor(curveIdx)) + for(auto &item : d_offsetHandles) { + if(item->pen().color() == getLineColor(curveIdx)) item->raise(); } @@ -925,11 +838,10 @@ void CapturePlot::enableXaxisLabels() void CapturePlot::enableAxisLabels(bool enabled) { setAxisVisible(QwtAxis::XBottom, enabled); - if (!enabled) { + if(!enabled) { int nrAxes = axesCount(m_qwtYAxis); - for (int i = 0; i < nrAxes; ++i) { - setAxisVisible(QwtAxisId(m_qwtYAxis, i), - enabled); + for(int i = 0; i < nrAxes; ++i) { + setAxisVisible(QwtAxisId(m_qwtYAxis, i), enabled); } } } @@ -947,22 +859,19 @@ void CapturePlot::setTimeTriggerInterval(double min, double max) d_timeTriggerMaxValue = max; } -bool CapturePlot::labelsEnabled() -{ - return d_labelsEnabled; -} +bool CapturePlot::labelsEnabled() { return d_labelsEnabled; } -void CapturePlot::setGraticuleEnabled(bool enabled){ +void CapturePlot::setGraticuleEnabled(bool enabled) +{ displayGraticule = enabled; - if(!displayGraticule){ - for(QwtPlotScaleItem* scale : qAsConst(scaleItems)){ + if(!displayGraticule) { + for(QwtPlotScaleItem *scale : qAsConst(scaleItems)) { scale->attach(this); } graticule->enableGraticule(displayGraticule); - } - else{ - for(QwtPlotScaleItem* scale : qAsConst(scaleItems)){ + } else { + for(QwtPlotScaleItem *scale : qAsConst(scaleItems)) { scale->detach(); } graticule->enableGraticule(displayGraticule); @@ -971,8 +880,9 @@ void CapturePlot::setGraticuleEnabled(bool enabled){ replot(); } -void CapturePlot::setGatingEnabled(bool enabled){ - if(d_gatingEnabled != enabled){ +void CapturePlot::setGatingEnabled(bool enabled) +{ + if(d_gatingEnabled != enabled) { d_gatingEnabled = enabled; d_gateBar1->setVisible(enabled); d_gateBar2->setVisible(enabled); @@ -980,20 +890,19 @@ void CapturePlot::setGatingEnabled(bool enabled){ d_hGatingHandle2->setVisible(enabled); updateHandleAreaPadding(d_labelsEnabled); - if(enabled){ + if(enabled) { leftGate->attach(this); rightGate->attach(this); d_topGateHandlesArea->show(); - //update handle + // update handle onGateBar1Moved(leftGateRect.right()); onGateBar2Moved(rightGateRect.left()); - } - else{ + } else { leftGate->detach(); rightGate->detach(); d_topGateHandlesArea->hide(); } - for (int i = 0; i < d_measureObjs.size(); i++) { + for(int i = 0; i < d_measureObjs.size(); i++) { M2kMeasure *measure = d_measureObjs[i]; measure->setGatingEnabled(enabled); } @@ -1009,30 +918,29 @@ void CapturePlot::setActiveVertAxis(unsigned int axisIdx, bool selected) { DisplayPlot::setActiveVertAxis(axisIdx, selected); updateHandleAreaPadding(d_labelsEnabled); - if (d_labelsEnabled) { + if(d_labelsEnabled) { setAxisVisible(QwtAxis::XBottom, true); } } void CapturePlot::showYAxisWidget(unsigned int axisIdx, bool en) { - if (!d_labelsEnabled) + if(!d_labelsEnabled) return; - setAxisVisible(QwtAxisId(m_qwtYAxis, axisIdx), - en); + setAxisVisible(QwtAxisId(m_qwtYAxis, axisIdx), en); int nrAxes = axesCount(m_qwtYAxis); bool allAxisDisabled = true; - for (int i = 0; i < nrAxes; ++i) - if (isAxisVisible(QwtAxisId(m_qwtYAxis, i))) + for(int i = 0; i < nrAxes; ++i) + if(isAxisVisible(QwtAxisId(m_qwtYAxis, i))) allAxisDisabled = false; - if (allAxisDisabled) { + if(allAxisDisabled) { setAxisVisible(QwtAxis::XBottom, false); updateHandleAreaPadding(false); } - if (en) { + if(en) { setAxisVisible(QwtAxis::XBottom, true); } } @@ -1041,43 +949,43 @@ void CapturePlot::updateHandleAreaPadding(bool enabled) { double xAxisBonusWidth = 0.0; - if (isAxisVisible(QwtAxis::XBottom)) { - if (!isAxisVisible(QwtAxis::YLeft)) { + if(isAxisVisible(QwtAxis::XBottom)) { + if(!isAxisVisible(QwtAxis::YLeft)) { xAxisBonusWidth = 65.0; } } - if (enabled) { + if(enabled) { d_bottomHandlesArea->setLeftPadding(50 + axisWidget(QwtAxisId(m_qwtYAxis, d_activeVertAxis))->width()); d_topGateHandlesArea->setLeftPadding(90 + axisWidget(QwtAxisId(m_qwtYAxis, d_activeVertAxis))->width()); QwtScaleWidget *scaleWidget = axisWidget(QwtAxis::XBottom); const int fmw = QFontMetrics(scaleWidget->font()).horizontalAdvance("-XX.XX XX"); const int fmh = QFontMetrics(scaleWidget->font()).height(); - d_bottomHandlesArea->setRightPadding(50 + fmw/2 + d_bonusWidth); - d_topGateHandlesArea->setRightPadding(50 + fmw/2 + d_bonusWidth); + d_bottomHandlesArea->setRightPadding(50 + fmw / 2 + d_bonusWidth); + d_topGateHandlesArea->setRightPadding(50 + fmw / 2 + d_bonusWidth); d_rightHandlesArea->setTopPadding(50 + 6); d_rightHandlesArea->setBottomPadding(50 + fmh); QMargins margins = d_topWidget->layout()->contentsMargins(); - margins.setLeft(d_leftHandlesArea->minimumWidth()+100); + margins.setLeft(d_leftHandlesArea->minimumWidth() + 100); d_topWidget->layout()->setContentsMargins(margins); } else { if(d_topGateHandlesArea->leftPadding() != 90) d_topGateHandlesArea->setLeftPadding(90); if(d_topGateHandlesArea->rightPadding() != 90) d_topGateHandlesArea->setRightPadding(90); - if (d_bottomHandlesArea->leftPadding() != 50 + xAxisBonusWidth) + if(d_bottomHandlesArea->leftPadding() != 50 + xAxisBonusWidth) d_bottomHandlesArea->setLeftPadding(50 + xAxisBonusWidth); - if (d_bottomHandlesArea->rightPadding() != 50 + d_bonusWidth + xAxisBonusWidth) + if(d_bottomHandlesArea->rightPadding() != 50 + d_bonusWidth + xAxisBonusWidth) d_bottomHandlesArea->setRightPadding(50 + d_bonusWidth + xAxisBonusWidth); - if (d_rightHandlesArea->topPadding() != 50) + if(d_rightHandlesArea->topPadding() != 50) d_rightHandlesArea->setTopPadding(50); - if (d_rightHandlesArea->bottomPadding() != 50) + if(d_rightHandlesArea->bottomPadding() != 50) d_rightHandlesArea->setBottomPadding(50); int topPadding = d_gatingEnabled ? d_topGateHandlesArea->height() : 0; topPadding += (d_topWidget->height() - 50); d_leftHandlesArea->setTopPadding(50 + topPadding); - if (d_gatingEnabled) { + if(d_gatingEnabled) { d_rightHandlesArea->setTopPadding(50 + topPadding); } QMargins margins = d_topWidget->layout()->contentsMargins(); @@ -1085,7 +993,7 @@ void CapturePlot::updateHandleAreaPadding(bool enabled) d_topWidget->layout()->setContentsMargins(margins); } - //update handle position to avoid cursors getting out of the plot bounds when changing the padding; + // update handle position to avoid cursors getting out of the plot bounds when changing the padding; d_hCursorHandle1->updatePosition(); d_hCursorHandle2->updatePosition(); @@ -1093,7 +1001,8 @@ void CapturePlot::updateHandleAreaPadding(bool enabled) d_vCursorHandle2->updatePosition(); } -void CapturePlot::updateGateMargins(){ +void CapturePlot::updateGateMargins() +{ /* update the size of the gates */ leftGateRect.setTop(axisScaleDiv(QwtAxis::YRight).upperBound()); leftGateRect.setBottom(axisScaleDiv(QwtAxis::YRight).lowerBound()); @@ -1108,53 +1017,55 @@ void CapturePlot::updateGateMargins(){ bool CapturePlot::eventFilter(QObject *object, QEvent *event) { - if (object == canvas()) { - switch (event->type()) { - case QEvent::MouseMove: { - Q_EMIT mouseMove(static_cast< QMouseEvent* >( event )); - break; - } - case QEvent::MouseButtonPress: { - Q_EMIT mouseButtonPress(static_cast< QMouseEvent* >( event )); - break; - } - case QEvent::MouseButtonRelease: { - Q_EMIT mouseButtonRelease(static_cast< QMouseEvent* >( event )); - break; - } - case QEvent::Resize: { - updateHandleAreaPadding(d_labelsEnabled); + if(object == canvas()) { + switch(event->type()) { + case QEvent::MouseMove: { + Q_EMIT mouseMove(static_cast(event)); + break; + } + case QEvent::MouseButtonPress: { + Q_EMIT mouseButtonPress(static_cast(event)); + break; + } + case QEvent::MouseButtonRelease: { + Q_EMIT mouseButtonRelease(static_cast(event)); + break; + } + case QEvent::Resize: { + updateHandleAreaPadding(d_labelsEnabled); - //force cursor handles to emit position changed - //when the plot canvas is being resized - d_hCursorHandle1->triggerMove(); - d_hCursorHandle2->triggerMove(); - d_vCursorHandle1->triggerMove(); - d_vCursorHandle2->triggerMove(); + // force cursor handles to emit position changed + // when the plot canvas is being resized + d_hCursorHandle1->triggerMove(); + d_hCursorHandle2->triggerMove(); + d_vCursorHandle1->triggerMove(); + d_vCursorHandle2->triggerMove(); - /* update the size of the gates when the plot canvas is resized */ - updateGateMargins(); + /* update the size of the gates when the plot canvas is resized */ + updateGateMargins(); - Q_EMIT canvasSizeChanged(); - break; - } - default: - break; - } - } - return QObject::eventFilter(object, event); + Q_EMIT canvasSizeChanged(); + break; + } + default: + break; + } + } + return QObject::eventFilter(object, event); } -QString CapturePlot::getChannelName(int chIdx) const { - if (chIdx >= d_offsetHandles.size() || chIdx < 0) { +QString CapturePlot::getChannelName(int chIdx) const +{ + if(chIdx >= d_offsetHandles.size() || chIdx < 0) { return ""; } return d_offsetHandles.at(chIdx)->getName(); } -void CapturePlot::setChannelName(const QString &name, int chIdx) { - if (chIdx >= d_offsetHandles.size() || chIdx < 0) { +void CapturePlot::setChannelName(const QString &name, int chIdx) +{ + if(chIdx >= d_offsetHandles.size() || chIdx < 0) { return; } @@ -1163,8 +1074,8 @@ void CapturePlot::setChannelName(const QString &name, int chIdx) { void CapturePlot::removeDigitalPlotCurve(QwtPlotCurve *curve) { - for (int i = 0; i < d_offsetHandles.size(); ++i) { - if (curve == getDigitalPlotCurve(i)) { + for(int i = 0; i < d_offsetHandles.size(); ++i) { + if(curve == getDigitalPlotCurve(i)) { removeOffsetWidgets(d_ydata.size() + d_ref_ydata.size() + i); removeLeftVertAxis(d_ydata.size() + d_ref_ydata.size() + i); break; @@ -1176,10 +1087,7 @@ void CapturePlot::removeDigitalPlotCurve(QwtPlotCurve *curve) replot(); } -void CapturePlot::setOffsetHandleVisible(int chIdx, bool visible) -{ - d_offsetHandles.at(chIdx)->setVisible(visible); -} +void CapturePlot::setOffsetHandleVisible(int chIdx, bool visible) { d_offsetHandles.at(chIdx)->setVisible(visible); } void CapturePlot::addToGroup(int currentGroup, int toAdd) { @@ -1199,7 +1107,7 @@ void CapturePlot::addToGroup(int currentGroup, int toAdd) void CapturePlot::onDigitalChannelAdded(int chnIdx) { setLeftVertAxesCount(d_ydata.size() + d_ref_ydata.size() + chnIdx + 1); - setAxisScale( QwtAxisId(QwtAxis::YLeft, d_ydata.size() + d_ref_ydata.size() + chnIdx), -5, 5); + setAxisScale(QwtAxisId(QwtAxis::YLeft, d_ydata.size() + d_ref_ydata.size() + chnIdx), -5, 5); replot(); QColor chnColor; @@ -1224,34 +1132,30 @@ void CapturePlot::onDigitalChannelAdded(int chnIdx) d_offsetBars.push_back(chOffsetBar); RoundedHandleV *chOffsetHdl = new RoundedHandleV( - QPixmap(":/gui/icons/handle_right_arrow.svg"), - QPixmap(":/gui/icons/handle_up_arrow.svg"), - QPixmap(":/gui/icons/handle_down_arrow.svg"), - d_leftHandlesArea, true, logicCurve->getName(), true); // TODO: add name + QPixmap(":/gui/icons/handle_right_arrow.svg"), QPixmap(":/gui/icons/handle_up_arrow.svg"), + QPixmap(":/gui/icons/handle_down_arrow.svg"), d_leftHandlesArea, true, logicCurve->getName(), + true); // TODO: add name chOffsetHdl->setRoundRectColor(chnColor); chOffsetHdl->setPen(QPen(chnColor, 2, Qt::SolidLine)); chOffsetHdl->setVisible(true); d_offsetHandles.push_back(chOffsetHdl); connect(logicCurve, &GenericLogicPlotCurve::nameChanged, - [=](const QString &name) { - chOffsetHdl->setName(name); - }); + [=](const QString &name) { chOffsetHdl->setName(name); }); - connect(logicCurve, &GenericLogicPlotCurve::pixelOffsetChanged, [=](double offset) { - chOffsetBar->setPosition(offset); - }); + connect(logicCurve, &GenericLogicPlotCurve::pixelOffsetChanged, + [=](double offset) { chOffsetBar->setPosition(offset); }); - connect(chOffsetHdl, &RoundedHandleV::selected, [=](bool selected){ + connect(chOffsetHdl, &RoundedHandleV::selected, [=](bool selected) { Q_EMIT channelSelected(d_offsetHandles.indexOf(chOffsetHdl), selected); - if (!selected && !d_startedGrouping) { - return ; + if(!selected && !d_startedGrouping) { + return; } - if (d_startedGrouping) { + if(d_startedGrouping) { chOffsetHdl->setSelected(selected); - if (selected) { + if(selected) { d_groupHandles.back().push_back(chOffsetHdl); } else { d_groupHandles.back().removeOne(chOffsetHdl); @@ -1259,8 +1163,8 @@ void CapturePlot::onDigitalChannelAdded(int chnIdx) return; } - for (auto &hdl : d_offsetHandles) { - if (hdl == chOffsetHdl) { + for(auto &hdl : d_offsetHandles) { + if(hdl == chOffsetHdl) { continue; } @@ -1269,57 +1173,50 @@ void CapturePlot::onDigitalChannelAdded(int chnIdx) }); /* When bar position changes due to plot resizes update the handle */ - connect(d_leftHandlesArea, &HandlesArea::sizeChanged, chOffsetHdl, [=](){ - chOffsetHdl->updatePosition(); - }); + connect(d_leftHandlesArea, &HandlesArea::sizeChanged, chOffsetHdl, [=]() { chOffsetHdl->updatePosition(); }); - connect(chOffsetBar, &HorizBar::pixelPositionChanged, - [=](int pos) { - chOffsetHdl->setPositionSilenty(pos); - }); - - connect(chOffsetHdl, &RoundedHandleV::positionChanged, - [=](int pos) { - int chn_id = d_offsetHandles.indexOf(chOffsetHdl); - if (chn_id < 0) - return; + connect(chOffsetBar, &HorizBar::pixelPositionChanged, [=](int pos) { chOffsetHdl->setPositionSilenty(pos); }); -// qDebug() << pos; + connect(chOffsetHdl, &RoundedHandleV::positionChanged, [=](int pos) { + int chn_id = d_offsetHandles.indexOf(chOffsetHdl); + if(chn_id < 0) + return; - QwtScaleMap yMap = this->canvasMap(QwtAxisId(m_qwtYAxis, chn_id)); + // qDebug() << pos; - auto y = axisInterval(QwtAxisId(m_qwtYAxis, chn_id)); + QwtScaleMap yMap = this->canvasMap(QwtAxisId(m_qwtYAxis, chn_id)); -// double min = -(yAxisNumDiv() / 2.0) * VertUnitsPerDiv(0); -// double max = (yAxisNumDiv() / 2.0) * VertUnitsPerDiv(0); + auto y = axisInterval(QwtAxisId(m_qwtYAxis, chn_id)); - double min = y.minValue(); - double max = y.maxValue(); + // double min = -(yAxisNumDiv() / 2.0) * VertUnitsPerDiv(0); + // double max = (yAxisNumDiv() / 2.0) * VertUnitsPerDiv(0); -// qDebug() << min << " " << max; + double min = y.minValue(); + double max = y.maxValue(); - yMap.setScaleInterval(min, max); - double offset = yMap.invTransform(pos); + // qDebug() << min << " " << max; - QwtPlotCurve *curve = getDigitalPlotCurve(chnIdx); - GenericLogicPlotCurve *logicCurve = dynamic_cast(curve); + yMap.setScaleInterval(min, max); + double offset = yMap.invTransform(pos); - if (logicCurve) { -// double plotOffset = VertOffset(0); - double pixelOffset = offset /*- logicCurve->getTraceHeight() / 2.0*/; - logicCurve->setPixelOffset(pixelOffset /*+ plotOffset*/); - QSignalBlocker blocker(chOffsetBar); - chOffsetBar->setPosition(pixelOffset /*+ plotOffset*/); - } + QwtPlotCurve *curve = getDigitalPlotCurve(chnIdx); + GenericLogicPlotCurve *logicCurve = dynamic_cast(curve); + if(logicCurve) { + // double plotOffset = VertOffset(0); + double pixelOffset = offset /*- logicCurve->getTraceHeight() / 2.0*/; + logicCurve->setPixelOffset(pixelOffset /*+ plotOffset*/); + QSignalBlocker blocker(chOffsetBar); + chOffsetBar->setPosition(pixelOffset /*+ plotOffset*/); + } - replot(); + replot(); -// Q_EMIT channelOffsetChanged(-offset); - }); + // Q_EMIT channelOffsetChanged(-offset); + }); - chOffsetHdl->setPosition(d_currentHandleInitPx); - d_currentHandleInitPx += 20; + chOffsetHdl->setPosition(d_currentHandleInitPx); + d_currentHandleInitPx += 20; } void CapturePlot::setChannelSelectable(int chnIdx, bool selectable) @@ -1329,7 +1226,7 @@ void CapturePlot::setChannelSelectable(int chnIdx, bool selectable) void CapturePlot::beginGroupSelection() { - if (d_startedGrouping) { + if(d_startedGrouping) { qDebug() << "\"beginGroupSelection\" already called. Consider terminating current group" "creation using \"endGroupSelection\"!"; } @@ -1337,8 +1234,8 @@ void CapturePlot::beginGroupSelection() d_startedGrouping = true; d_groupHandles.push_back(QList()); - for (auto &hdl : d_offsetHandles) { - if (hdl->isSelected()) { + for(auto &hdl : d_offsetHandles) { + if(hdl->isSelected()) { d_groupHandles.back().push_back(hdl); } } @@ -1346,45 +1243,43 @@ void CapturePlot::beginGroupSelection() bool CapturePlot::endGroupSelection(bool moveAnnotationCurvesLast) { - if (!d_startedGrouping) { + if(!d_startedGrouping) { qDebug() << "\"endGroupSelection\" call not paired with \"beginGroupSelection\"!"; return false; } d_startedGrouping = false; - if (d_groupHandles.back().size() < 2) { + if(d_groupHandles.back().size() < 2) { d_groupHandles.pop_back(); return false; } - for (auto & grp : d_groupHandles) { - for (RoundedHandleV *hdl : grp) { - disconnect(hdl, &RoundedHandleV::positionChanged, - this, &CapturePlot::handleInGroupChangedPosition); + for(auto &grp : d_groupHandles) { + for(RoundedHandleV *hdl : grp) { + disconnect(hdl, &RoundedHandleV::positionChanged, this, + &CapturePlot::handleInGroupChangedPosition); } } // merge new group if selected channels already have a group QList group = d_groupHandles.takeLast(); QList updatedGroup; - for (RoundedHandleV *hdl : qAsConst(group)) { - auto hdlGroup = std::find_if(d_groupHandles.begin(), d_groupHandles.end(), - [&hdl](const QList &group){ - return group.contains(hdl); - }); + for(RoundedHandleV *hdl : qAsConst(group)) { + auto hdlGroup = + std::find_if(d_groupHandles.begin(), d_groupHandles.end(), + [&hdl](const QList &group) { return group.contains(hdl); }); - if (hdlGroup == d_groupHandles.end()) { - if (!updatedGroup.contains(hdl)) { + if(hdlGroup == d_groupHandles.end()) { + if(!updatedGroup.contains(hdl)) { updatedGroup.push_back(hdl); } continue; } - auto hdlGroupContainer = *hdlGroup; - for (const auto &grpHdl : qAsConst(hdlGroupContainer)) { - if (!updatedGroup.contains(grpHdl)) { + for(const auto &grpHdl : qAsConst(hdlGroupContainer)) { + if(!updatedGroup.contains(grpHdl)) { updatedGroup.push_back(grpHdl); } } @@ -1393,8 +1288,8 @@ bool CapturePlot::endGroupSelection(bool moveAnnotationCurvesLast) } group = updatedGroup; // - if (moveAnnotationCurvesLast) { - std::sort(group.begin(), group.end(), [=](RoundedHandleV *a, RoundedHandleV *b){ + if(moveAnnotationCurvesLast) { + std::sort(group.begin(), group.end(), [=](RoundedHandleV *a, RoundedHandleV *b) { return d_offsetHandles.indexOf(a) < d_offsetHandles.indexOf(b); }); } @@ -1405,39 +1300,37 @@ bool CapturePlot::endGroupSelection(bool moveAnnotationCurvesLast) const int chIdx = d_offsetHandles.indexOf(handle); QwtPlotCurve *curve = getDigitalPlotCurve(chIdx); GenericLogicPlotCurve *logicCurve = dynamic_cast(curve); -//#ifdef SCOPY_HAVE_SIGROK_GUI -// AnnotationCurve *annCurve = dynamic_cast(logicCurve); -// if (annCurve) { -// bonusHeight = annCurve->getTraceHeight() * annCurve->getVisibleRows(); -// return static_cast(handle->size().height()); -// } -//#endif + //#ifdef SCOPY_HAVE_SIGROK_GUI + // AnnotationCurve *annCurve = dynamic_cast(logicCurve); + // if (annCurve) { + // bonusHeight = annCurve->getTraceHeight() * annCurve->getVisibleRows(); + // return static_cast(handle->size().height()); + // } + //#endif bonusHeight = logicCurve->getHeightOffset(); return logicCurve->getTraceHeight(); }; const bool newGroup = (d_groupHandles.size() != d_groupMarkers.size()); - - if (newGroup) { + if(newGroup) { // Move channels on top side of the plot int currentPos = 5; double bonusHeight = 0.0; currentPos += getTraceHeightInPixelsForHandle(group.first(), bonusHeight); group.first()->setPosition(currentPos); - for (int i = 1; i < group.size(); ++i) { + for(int i = 1; i < group.size(); ++i) { currentPos += bonusHeight; currentPos += getTraceHeightInPixelsForHandle(group[i], bonusHeight); group[i]->setPosition(currentPos); currentPos += 5; - } } - for (auto & grp : d_groupHandles) { - for (RoundedHandleV *hdl : grp) { - connect(hdl, &RoundedHandleV::positionChanged, - this, &CapturePlot::handleInGroupChangedPosition); + for(auto &grp : d_groupHandles) { + for(RoundedHandleV *hdl : grp) { + connect(hdl, &RoundedHandleV::positionChanged, this, + &CapturePlot::handleInGroupChangedPosition); hdl->setSelected(false); } } @@ -1445,14 +1338,14 @@ bool CapturePlot::endGroupSelection(bool moveAnnotationCurvesLast) group.first()->setSelected(true); group.first()->selected(true); - for (QwtPlotZoneItem *groupMarker : qAsConst(d_groupMarkers)) { + for(QwtPlotZoneItem *groupMarker : qAsConst(d_groupMarkers)) { groupMarker->detach(); delete groupMarker; } d_groupMarkers.clear(); - for (const auto &group : qAsConst(d_groupHandles)) { + for(const auto &group : qAsConst(d_groupHandles)) { // Add group marker QwtScaleMap yMap = this->canvasMap(QwtAxisId(QwtAxis::YLeft, 0)); const QwtInterval y = axisInterval(QwtAxisId(QwtAxis::YLeft, 0)); @@ -1461,7 +1354,7 @@ bool CapturePlot::endGroupSelection(bool moveAnnotationCurvesLast) yMap.setScaleInterval(min, max); double bonusHeight = 0.0; double y1 = yMap.invTransform(group.front()->position() - - getTraceHeightInPixelsForHandle(group.front(), bonusHeight) - 5); + getTraceHeightInPixelsForHandle(group.front(), bonusHeight) - 5); getTraceHeightInPixelsForHandle(group.back(), bonusHeight); double y2 = yMap.invTransform(group.back()->position() + 5 + bonusHeight); @@ -1475,8 +1368,8 @@ bool CapturePlot::endGroupSelection(bool moveAnnotationCurvesLast) groupMarker->attach(this); } - if (!newGroup) { - for (const auto &group : qAsConst(d_groupHandles)) { + if(!newGroup) { + for(const auto &group : qAsConst(d_groupHandles)) { group.first()->triggerMove(); } } @@ -1488,41 +1381,40 @@ QVector CapturePlot::getGroupOfChannel(int chnIdx) { QVector groupIdxList; - if (chnIdx < 0 || chnIdx >= d_offsetHandles.size()) { + if(chnIdx < 0 || chnIdx >= d_offsetHandles.size()) { return groupIdxList; // empty } - auto hdlGroup = std::find_if(d_groupHandles.begin(), d_groupHandles.end(), - [=](const QList &group){ - return group.contains(d_offsetHandles[chnIdx]); - }); + auto hdlGroup = + std::find_if(d_groupHandles.begin(), d_groupHandles.end(), [=](const QList &group) { + return group.contains(d_offsetHandles[chnIdx]); + }); // if no group return - if (hdlGroup == d_groupHandles.end()) { + if(hdlGroup == d_groupHandles.end()) { return groupIdxList; } auto hdlGroupContainer = *hdlGroup; - for (const auto &hdl : qAsConst(hdlGroupContainer)) { + for(const auto &hdl : qAsConst(hdlGroupContainer)) { groupIdxList.push_back(d_offsetHandles.indexOf(hdl)); } return groupIdxList; - } -QVector > CapturePlot::getAllGroups() +QVector> CapturePlot::getAllGroups() { QVector> allGroups; - for (int i = 0; i < d_groupHandles.size(); ++i) { + for(int i = 0; i < d_groupHandles.size(); ++i) { QVector group; - for (int j = 0; j < d_groupHandles[i].size(); ++j) { + for(int j = 0; j < d_groupHandles[i].size(); ++j) { int ch = d_offsetHandles.indexOf(d_groupHandles[i][j]); - if (ch != -1) { + if(ch != -1) { group.append(ch); } } - if (!group.empty()) { + if(!group.empty()) { allGroups.append(group); } } @@ -1532,27 +1424,27 @@ QVector > CapturePlot::getAllGroups() void CapturePlot::removeFromGroup(int chnIdx, int removedChnIdx, bool &didGroupVanish) { - auto hdlGroup = std::find_if(d_groupHandles.begin(), d_groupHandles.end(), - [=](const QList &group){ - return group.contains(d_offsetHandles[chnIdx]); - }); + auto hdlGroup = + std::find_if(d_groupHandles.begin(), d_groupHandles.end(), [=](const QList &group) { + return group.contains(d_offsetHandles[chnIdx]); + }); - if (hdlGroup == d_groupHandles.end()) { + if(hdlGroup == d_groupHandles.end()) { return; } const int positionOfFirstHandleInGroup = hdlGroup->at(0)->position(); const int positionOfLastHandleInGroup = hdlGroup->back()->position(); - disconnect(hdlGroup->at(removedChnIdx), &RoundedHandleV::positionChanged, - this, &CapturePlot::handleInGroupChangedPosition); + disconnect(hdlGroup->at(removedChnIdx), &RoundedHandleV::positionChanged, this, + &CapturePlot::handleInGroupChangedPosition); auto removedObj = hdlGroup->takeAt(removedChnIdx); - if (hdlGroup->size() < 2) { + if(hdlGroup->size() < 2) { didGroupVanish = true; - disconnect(hdlGroup->first(), &RoundedHandleV::positionChanged, - this, &CapturePlot::handleInGroupChangedPosition); + disconnect(hdlGroup->first(), &RoundedHandleV::positionChanged, this, + &CapturePlot::handleInGroupChangedPosition); const int indexOfCurrentGroup = d_groupHandles.indexOf(*hdlGroup); d_groupHandles.removeOne(*hdlGroup); auto marker = d_groupMarkers.takeAt(indexOfCurrentGroup); @@ -1573,12 +1465,12 @@ void CapturePlot::removeFromGroup(int chnIdx, int removedChnIdx, bool &didGroupV void CapturePlot::positionInGroupChanged(int chnIdx, int from, int to) { - auto hdlGroup = std::find_if(d_groupHandles.begin(), d_groupHandles.end(), - [=](const QList &group){ - return group.contains(d_offsetHandles[chnIdx]); - }); + auto hdlGroup = + std::find_if(d_groupHandles.begin(), d_groupHandles.end(), [=](const QList &group) { + return group.contains(d_offsetHandles[chnIdx]); + }); - if (hdlGroup == d_groupHandles.end()) { + if(hdlGroup == d_groupHandles.end()) { return; } @@ -1591,22 +1483,22 @@ void CapturePlot::positionInGroupChanged(int chnIdx, int from, int to) hdlGroup->at(0)->triggerMove(); } -void CapturePlot::setGroups(const QVector > &groups) +void CapturePlot::setGroups(const QVector> &groups) { auto selectedHandleIt = std::find_if(d_offsetHandles.begin(), d_offsetHandles.end(), - [](RoundedHandleV *handle){ - return handle->isSelected(); - }); + [](RoundedHandleV *handle) { return handle->isSelected(); }); - if (selectedHandleIt != d_offsetHandles.end()) { + if(selectedHandleIt != d_offsetHandles.end()) { (*selectedHandleIt)->setSelected(false); (*selectedHandleIt)->selected(false); } - for (const auto &grp : groups) { - if (grp.size() < 2) { continue; } + for(const auto &grp : groups) { + if(grp.size() < 2) { + continue; + } beginGroupSelection(); - for (const auto &hdl : grp) { + for(const auto &hdl : grp) { d_groupHandles.back().push_back(d_offsetHandles.at(hdl)); } endGroupSelection(); @@ -1616,7 +1508,7 @@ void CapturePlot::setGroups(const QVector > &groups) d_groupHandles.back().front()->setPosition(d_groupHandles.back().front()->position()); } - if (selectedHandleIt != d_offsetHandles.end()) { + if(selectedHandleIt != d_offsetHandles.end()) { (*selectedHandleIt)->setSelected(true); (*selectedHandleIt)->selected(true); } @@ -1629,18 +1521,16 @@ void CapturePlot::handleInGroupChangedPosition(int position) RoundedHandleV *hdl = dynamic_cast(QObject::sender()); // is the sender a RoundedHandleV? - if (!hdl) { + if(!hdl) { qDebug() << "Invalid sender!"; } // find the group of this handle auto hdlGroup = std::find_if(d_groupHandles.begin(), d_groupHandles.end(), - [&hdl](const QList &group){ - return group.contains(hdl); - }); + [&hdl](const QList &group) { return group.contains(hdl); }); // if no group return - if (hdlGroup == d_groupHandles.end()) { + if(hdlGroup == d_groupHandles.end()) { return; } @@ -1652,13 +1542,13 @@ void CapturePlot::handleInGroupChangedPosition(int position) const int chIdx = d_offsetHandles.indexOf(handle); QwtPlotCurve *curve = getDigitalPlotCurve(chIdx); GenericLogicPlotCurve *logicCurve = dynamic_cast(curve); -//#ifdef SCOPY_HAVE_SIGROK_GUI -// AnnotationCurve *annCurve = dynamic_cast(logicCurve); -// if (annCurve) { -// bonusHeight = annCurve->getTraceHeight() * annCurve->getVisibleRows(); -// return static_cast(handle->size().height()); -// } -//#endif + //#ifdef SCOPY_HAVE_SIGROK_GUI + // AnnotationCurve *annCurve = dynamic_cast(logicCurve); + // if (annCurve) { + // bonusHeight = annCurve->getTraceHeight() * annCurve->getVisibleRows(); + // return static_cast(handle->size().height()); + // } + //#endif bonusHeight = logicCurve->getHeightOffset(); return logicCurve->getTraceHeight(); }; @@ -1667,42 +1557,42 @@ void CapturePlot::handleInGroupChangedPosition(int position) double bonusHeight = 0.0; int currentPos = position - 5; currentPos -= getTraceHeightInPixelsForHandle(hdl, bonusHeight); - for (int i = index - 1; i >= 0; --i) { - if (!hdlGroup->at(i)->isVisible()) { + for(int i = index - 1; i >= 0; --i) { + if(!hdlGroup->at(i)->isVisible()) { continue; } - disconnect(hdlGroup->at(i), &RoundedHandleV::positionChanged, - this, &CapturePlot::handleInGroupChangedPosition); + disconnect(hdlGroup->at(i), &RoundedHandleV::positionChanged, this, + &CapturePlot::handleInGroupChangedPosition); hdlGroup->at(i)->setPosition(currentPos); int temp = getTraceHeightInPixelsForHandle(hdlGroup->at(i), bonusHeight); - if (bonusHeight != 0.0) { + if(bonusHeight != 0.0) { hdlGroup->at(i)->setPosition(currentPos - bonusHeight); currentPos -= bonusHeight; bonusHeight = 0.0; } currentPos -= temp; currentPos -= 5; - connect(hdlGroup->at(i), &RoundedHandleV::positionChanged, - this, &CapturePlot::handleInGroupChangedPosition); + connect(hdlGroup->at(i), &RoundedHandleV::positionChanged, this, + &CapturePlot::handleInGroupChangedPosition); } // update position of handles below the moved one currentPos = position + 5; getTraceHeightInPixelsForHandle(hdl, bonusHeight); - for (int i = index + 1; i < hdlGroup->size(); ++i) { - if (!hdlGroup->at(i)->isVisible()) { + for(int i = index + 1; i < hdlGroup->size(); ++i) { + if(!hdlGroup->at(i)->isVisible()) { continue; } - if (bonusHeight != 0.0) { + if(bonusHeight != 0.0) { currentPos += bonusHeight; bonusHeight = 0.0; } currentPos += getTraceHeightInPixelsForHandle(hdlGroup->at(i), bonusHeight); - disconnect(hdlGroup->at(i), &RoundedHandleV::positionChanged, - this, &CapturePlot::handleInGroupChangedPosition); + disconnect(hdlGroup->at(i), &RoundedHandleV::positionChanged, this, + &CapturePlot::handleInGroupChangedPosition); hdlGroup->at(i)->setPosition(currentPos); - connect(hdlGroup->at(i), &RoundedHandleV::positionChanged, - this, &CapturePlot::handleInGroupChangedPosition); + connect(hdlGroup->at(i), &RoundedHandleV::positionChanged, this, + &CapturePlot::handleInGroupChangedPosition); currentPos += 5; } @@ -1714,22 +1604,22 @@ void CapturePlot::handleInGroupChangedPosition(int position) yMap.setScaleInterval(min, max); RoundedHandleV *bottomHandle = nullptr, *topHandle = nullptr; - for (int i = 0; i < hdlGroup->size(); ++i) { - if (hdlGroup->at(i)->isVisible()) { + for(int i = 0; i < hdlGroup->size(); ++i) { + if(hdlGroup->at(i)->isVisible()) { topHandle = hdlGroup->at(i); break; } } - for (int i = hdlGroup->size() - 1; i >= 0; --i) { - if (hdlGroup->at(i)->isVisible()) { + for(int i = hdlGroup->size() - 1; i >= 0; --i) { + if(hdlGroup->at(i)->isVisible()) { bottomHandle = hdlGroup->at(i); break; } } - if (bottomHandle && topHandle) { + if(bottomHandle && topHandle) { double y1 = yMap.invTransform(topHandle->position() - - getTraceHeightInPixelsForHandle(topHandle, bonusHeight) - 5); + getTraceHeightInPixelsForHandle(topHandle, bonusHeight) - 5); getTraceHeightInPixelsForHandle(bottomHandle, bonusHeight); double y2 = yMap.invTransform(bottomHandle->position() + 5 + bonusHeight); @@ -1745,12 +1635,13 @@ void scopy::CapturePlot::pushBackNewOffsetWidgets(RoundedHandleV *chOffsetHdl, H d_offsetBars.insert(indexOfNewChannel, chOffsetBar); d_offsetHandles.insert(indexOfNewChannel, chOffsetHdl); - for (int i = 0; i < d_offsetBars.size(); ++i) { + for(int i = 0; i < d_offsetBars.size(); ++i) { d_offsetBars[i]->setMobileAxis(QwtAxisId(m_qwtYAxis, i)); } - for (int i = 0; i < d_logic_curves.size(); ++i) { - d_logic_curves[i]->setAxes(QwtAxis::XBottom, QwtAxisId(QwtAxis::YLeft, d_ydata.size() + d_ref_ydata.size() + i)); + for(int i = 0; i < d_logic_curves.size(); ++i) { + d_logic_curves[i]->setAxes(QwtAxis::XBottom, + QwtAxisId(QwtAxis::YLeft, d_ydata.size() + d_ref_ydata.size() + i)); } } @@ -1767,70 +1658,60 @@ void CapturePlot::onChannelAdded(int chnIdx) chOffsetBar->setMobileAxis(QwtAxisId(m_qwtYAxis, chnIdx)); RoundedHandleV *chOffsetHdl = new RoundedHandleV( - QPixmap(":/gui/icons/handle_right_arrow.svg"), - QPixmap(":/gui/icons/handle_up_arrow.svg"), - QPixmap(":/gui/icons/handle_down_arrow.svg"), - d_leftHandlesArea, true); + QPixmap(":/gui/icons/handle_right_arrow.svg"), QPixmap(":/gui/icons/handle_up_arrow.svg"), + QPixmap(":/gui/icons/handle_down_arrow.svg"), d_leftHandlesArea, true); chOffsetHdl->setRoundRectColor(chnColor); chOffsetHdl->setPen(QPen(chnColor, 2, Qt::SolidLine)); chOffsetHdl->setVisible(true); pushBackNewOffsetWidgets(chOffsetHdl, chOffsetBar); - connect(chOffsetHdl, &RoundedHandleV::positionChanged, - [=](int pos) { - int chn_id = d_offsetHandles.indexOf(chOffsetHdl); - if (chn_id < 0) - return; + connect(chOffsetHdl, &RoundedHandleV::positionChanged, [=](int pos) { + int chn_id = d_offsetHandles.indexOf(chOffsetHdl); + if(chn_id < 0) + return; - QwtScaleMap yMap = this->canvasMap(QwtAxisId(m_qwtYAxis, chn_id)); - double min = -(yAxisNumDiv() / 2.0) * VertUnitsPerDiv(chn_id); - double max = (yAxisNumDiv() / 2.0) * VertUnitsPerDiv(chn_id); + QwtScaleMap yMap = this->canvasMap(QwtAxisId(m_qwtYAxis, chn_id)); + double min = -(yAxisNumDiv() / 2.0) * VertUnitsPerDiv(chn_id); + double max = (yAxisNumDiv() / 2.0) * VertUnitsPerDiv(chn_id); - yMap.setScaleInterval(min, max); - double offset = yMap.invTransform(pos); - this->setVertOffset(-offset, chn_id); - this->replot(); + yMap.setScaleInterval(min, max); + double offset = yMap.invTransform(pos); + this->setVertOffset(-offset, chn_id); + this->replot(); - Q_EMIT channelOffsetChanged(chn_id, -offset); - }); + Q_EMIT channelOffsetChanged(chn_id, -offset); + }); /* When bar position changes due to plot resizes update the handle */ - connect(d_leftHandlesArea, &HandlesArea::sizeChanged, chOffsetHdl, [=](){ - chOffsetHdl->updatePosition(); - }); + connect(d_leftHandlesArea, &HandlesArea::sizeChanged, chOffsetHdl, [=]() { chOffsetHdl->updatePosition(); }); - connect(chOffsetBar, &HorizBar::pixelPositionChanged, - [=](int pos) { - chOffsetHdl->setPositionSilenty(pos); - }); + connect(chOffsetBar, &HorizBar::pixelPositionChanged, [=](int pos) { chOffsetHdl->setPositionSilenty(pos); }); - connect(chOffsetHdl, &RoundedHandleV::mouseReleased, - [=](){ - int chn_id = d_offsetHandles.indexOf(chOffsetHdl); - int offset = this->VertOffset(chn_id); - if (offset > d_maxOffsetValue){ - offset = d_maxOffsetValue; - this->setVertOffset(offset, chn_id); - this->replot(); + connect(chOffsetHdl, &RoundedHandleV::mouseReleased, [=]() { + int chn_id = d_offsetHandles.indexOf(chOffsetHdl); + int offset = this->VertOffset(chn_id); + if(offset > d_maxOffsetValue) { + offset = d_maxOffsetValue; + this->setVertOffset(offset, chn_id); + this->replot(); - Q_EMIT channelOffsetChanged(chn_id, offset); - } - if (offset < d_minOffsetValue){ - offset = d_minOffsetValue; - this->setVertOffset(offset, chn_id); - this->replot(); + Q_EMIT channelOffsetChanged(chn_id, offset); + } + if(offset < d_minOffsetValue) { + offset = d_minOffsetValue; + this->setVertOffset(offset, chn_id); + this->replot(); - Q_EMIT channelOffsetChanged(chn_id, offset); - } + Q_EMIT channelOffsetChanged(chn_id, offset); + } }); - connect(chOffsetHdl, &RoundedHandleV::grabbedChanged, [=](bool selected){ - if (selected) { + connect(chOffsetHdl, &RoundedHandleV::grabbedChanged, [=](bool selected) { + if(selected) { Q_EMIT channelSelected(d_offsetHandles.indexOf(chOffsetHdl), selected); - } }); - connect(chOffsetHdl, &RoundedHandleV::reset, [=](){ + connect(chOffsetHdl, &RoundedHandleV::reset, [=]() { int chn_id = d_offsetHandles.indexOf(chOffsetHdl); this->setVertOffset(0, chn_id); this->replot(); @@ -1842,14 +1723,13 @@ void CapturePlot::onChannelAdded(int chnIdx) M2kMeasure *measure = nullptr; - if (isReferenceWaveform(Curve(chnIdx))) { + if(isReferenceWaveform(Curve(chnIdx))) { int idx = chnIdx - d_ydata.size(); - measure = new M2kMeasure(chnIdx, d_ref_ydata[idx], - Curve(chnIdx)->data()->size(), nullptr); + measure = new M2kMeasure(chnIdx, d_ref_ydata[idx], Curve(chnIdx)->data()->size(), nullptr); } else { int count = countReferenceWaveform(chnIdx); - measure = new M2kMeasure(chnIdx, d_ydata[chnIdx - count], - Curve(chnIdx)->data()->size(), m_conversion_function); + measure = new M2kMeasure(chnIdx, d_ydata[chnIdx - count], Curve(chnIdx)->data()->size(), + m_conversion_function); } measure->setAdcBitCount(12); @@ -1858,7 +1738,7 @@ void CapturePlot::onChannelAdded(int chnIdx) void CapturePlot::computeMeasurementsForChannel(unsigned int chnIdx, unsigned int sampleRate) { - if (chnIdx >= d_measureObjs.size()) { + if(chnIdx >= d_measureObjs.size()) { return; } @@ -1872,7 +1752,7 @@ void CapturePlot::computeMeasurementsForChannel(unsigned int chnIdx, unsigned in void CapturePlot::setConversionFunction(const std::function &fp) { m_conversion_function = fp; - for (int i = 0; i < d_measureObjs.size(); i++) { + for(int i = 0; i < d_measureObjs.size(); i++) { M2kMeasure *measure = d_measureObjs[i]; measure->setConversionFunction(fp); } @@ -1881,11 +1761,10 @@ void CapturePlot::setConversionFunction(const std::functionsetChannel( - d_measureObjs[i]->channel() - 1); + for(int i = pos + 1; i < d_measureObjs.size(); i++) { + d_measureObjs[i]->setChannel(d_measureObjs[i]->channel() - 1); } d_measureObjs.removeOne(measure); delete measure; @@ -1894,35 +1773,35 @@ void CapturePlot::cleanUpJustBeforeChannelRemoval(int chnIdx) void CapturePlot::setOffsetWidgetVisible(int chnIdx, bool visible) { - if (chnIdx < 0 || chnIdx >= d_offsetHandles.size()) + if(chnIdx < 0 || chnIdx >= d_offsetHandles.size()) return; d_offsetHandles[chnIdx]->setVisible(visible); // find the group of this handle - auto hdlGroup = std::find_if(d_groupHandles.begin(), d_groupHandles.end(), - [=](const QList &group){ - return group.contains(d_offsetHandles[chnIdx]); - }); + auto hdlGroup = + std::find_if(d_groupHandles.begin(), d_groupHandles.end(), [=](const QList &group) { + return group.contains(d_offsetHandles[chnIdx]); + }); // if no group return - if (hdlGroup == d_groupHandles.end()) { - //qDebug() << "This handle is not in a group!"; + if(hdlGroup == d_groupHandles.end()) { + // qDebug() << "This handle is not in a group!"; return; } int count = 0; auto hdlGroupContainer = *hdlGroup; - for (const auto &handle : qAsConst(hdlGroupContainer)) { - if (handle->isVisible()) { + for(const auto &handle : qAsConst(hdlGroupContainer)) { + if(handle->isVisible()) { count++; } } const bool detach = (count < 2); const int groupIdx = d_groupHandles.indexOf(*hdlGroup); - if (detach) { + if(detach) { d_groupMarkers[groupIdx]->detach(); } else { d_groupMarkers[groupIdx]->attach(this); @@ -1931,7 +1810,7 @@ void CapturePlot::setOffsetWidgetVisible(int chnIdx, bool visible) void CapturePlot::removeOffsetWidgets(int chnIdx) { - if (chnIdx < 0 || chnIdx >= d_offsetHandles.size()) + if(chnIdx < 0 || chnIdx >= d_offsetHandles.size()) return; HorizBar *bar = d_offsetBars.takeAt(chnIdx); @@ -1943,9 +1822,9 @@ void CapturePlot::removeOffsetWidgets(int chnIdx) void CapturePlot::measure() { - for (int i = 0; i < d_measureObjs.size(); i++) { + for(int i = 0; i < d_measureObjs.size(); i++) { M2kMeasure *measure = d_measureObjs[i]; - if (measure->activeMeasurementsCount() > 0) { + if(measure->activeMeasurementsCount() > 0) { measure->setSampleRate(this->sampleRate()); measure->measure(); } @@ -1957,7 +1836,7 @@ int CapturePlot::activeMeasurementsCount(int chnIdx) int count = -1; M2kMeasure *measure = measureOfChannel(chnIdx); - if (measure) + if(measure) count = measure->activeMeasurementsCount(); return count; @@ -1967,20 +1846,18 @@ void CapturePlot::onNewDataReceived() { int ref_idx = 0; if(d_measurementsEnabled) { - for (int i = 0; i < d_measureObjs.size(); i++) { + for(int i = 0; i < d_measureObjs.size(); i++) { M2kMeasure *measure = d_measureObjs[i]; int chn = measure->channel(); - if (isReferenceWaveform(Curve(chn))) { - measure->setDataSource(d_ref_ydata[ref_idx], - Curve(chn)->data()->size()); + if(isReferenceWaveform(Curve(chn))) { + measure->setDataSource(d_ref_ydata[ref_idx], Curve(chn)->data()->size()); ref_idx++; } else { int count = countReferenceWaveform(chn); - measure->setDataSource(d_ydata[chn - count], - Curve(chn)->data()->size()); + measure->setDataSource(d_ydata[chn - count], Curve(chn)->data()->size()); } - if (isMathWaveform(Curve(chn))) { + if(isMathWaveform(Curve(chn))) { measure->setAdcBitCount(0); } @@ -1996,7 +1873,7 @@ QList> CapturePlot::measurements(int chnIdx) { M2kMeasure *measure = measureOfChannel(chnIdx); - if (measure) + if(measure) return measure->measurments(); else return QList>(); @@ -2005,7 +1882,7 @@ QList> CapturePlot::measurements(int chnIdx) std::shared_ptr CapturePlot::measurement(int id, int chnIdx) { M2kMeasure *measure = measureOfChannel(chnIdx); - if (measure) + if(measure) return measure->measurement(id); else return std::shared_ptr(); @@ -2013,9 +1890,9 @@ std::shared_ptr CapturePlot::measurement(int id, int chnIdx) OscPlotZoomer *CapturePlot::getZoomer() { - if (d_zoomer.isEmpty()) + if(d_zoomer.isEmpty()) return nullptr; - return static_cast(d_zoomer[0]); + return static_cast(d_zoomer[0]); } void CapturePlot::setOffsetInterval(double minValue, double maxValue) @@ -2024,34 +1901,28 @@ void CapturePlot::setOffsetInterval(double minValue, double maxValue) d_maxOffsetValue = maxValue; } -double CapturePlot::getMaxOffsetValue() -{ - return d_maxOffsetValue; -} +double CapturePlot::getMaxOffsetValue() { return d_maxOffsetValue; } -double CapturePlot::getMinOffsetValue() -{ - return d_minOffsetValue; -} +double CapturePlot::getMinOffsetValue() { return d_minOffsetValue; } void CapturePlot::setPeriodDetectLevel(int chnIdx, double lvl) { M2kMeasure *measure = measureOfChannel(chnIdx); - if (measure) + if(measure) measure->setCrossLevel(lvl); } void CapturePlot::setPeriodDetectHyst(int chnIdx, double hyst) { M2kMeasure *measure = measureOfChannel(chnIdx); - if (measure) + if(measure) measure->setHysteresisSpan(hyst); } void CapturePlot::setTimeBaseLabelValue(double value) { QString text = d_cursorTimeFormatter.format(value, "", 3); - if (d_timeBaseLabel->text().contains(tr("Zoom: "))) { + if(d_timeBaseLabel->text().contains(tr("Zoom: "))) { d_timeBaseLabel->setText(tr("Zoom: ") + text + tr("/div")); } else { d_timeBaseLabel->setText(text + tr("/div")); @@ -2060,12 +1931,12 @@ void CapturePlot::setTimeBaseLabelValue(double value) void CapturePlot::setTimeBaseZoomed(bool zoomed) { - if (zoomed) { - if (!d_timeBaseLabel->text().contains(tr("Zoom: "))) + if(zoomed) { + if(!d_timeBaseLabel->text().contains(tr("Zoom: "))) d_timeBaseLabel->setText(tr("Zoom: ") + d_timeBaseLabel->text()); } else { QString text = d_timeBaseLabel->text(); - if (text.contains(tr("Zoom: "))) { + if(text.contains(tr("Zoom: "))) { text = text.remove(tr("Zoom: ")); d_timeBaseLabel->setText(text); } @@ -2088,7 +1959,7 @@ void CapturePlot::setTriggerState(int triggerState) { d_triggerStateLabel->hide(); - switch (triggerState) { + switch(triggerState) { case Waiting: d_triggerStateLabel->setText(tr("Waiting")); break; @@ -2110,7 +1981,7 @@ void CapturePlot::setTriggerState(int triggerState) void CapturePlot::setMaxBufferSizeErrorLabel(bool reached, const QString &customWarning) { QString errorMessage = "Maximum buffer size reached"; - if (customWarning.length()) { + if(customWarning.length()) { errorMessage = customWarning; } d_maxBufferError->setText(reached ? errorMessage : ""); @@ -2130,11 +2001,11 @@ void CapturePlot::removeLeftVertAxis(unsigned int axis) { const unsigned int numAxis = vertAxes.size(); - if (axis >= numAxis) + if(axis >= numAxis) return; // Update the mobile axis ID of all symbols - for (size_t i = axis; i < numAxis - 1; i++) { + for(size_t i = axis; i < numAxis - 1; i++) { QwtAxisId axisId = d_offsetBars.at(i)->mobileAxis(); --axisId.id; d_offsetBars.at(i)->setMobileAxis(axisId); @@ -2143,27 +2014,27 @@ void CapturePlot::removeLeftVertAxis(unsigned int axis) DisplayPlot::removeLeftVertAxis(axis); } -GenericLogicPlotCurve* CapturePlot::curveAt( const QPoint& pos ) const +GenericLogicPlotCurve *CapturePlot::curveAt(const QPoint &pos) const { - using namespace QwtAxis; + using namespace QwtAxis; - double coords[ AxisPositions ]; + double coords[AxisPositions]; - coords[ XBottom ] = canvasMap( XBottom ).invTransform( pos.x() ); - coords[ XTop ] = canvasMap( XTop ).invTransform( pos.x() ); - coords[ YLeft ] = canvasMap( YLeft ).invTransform( pos.y() ); - coords[ YRight ] = canvasMap( YRight ).invTransform( pos.y() ); + coords[XBottom] = canvasMap(XBottom).invTransform(pos.x()); + coords[XTop] = canvasMap(XTop).invTransform(pos.x()); + coords[YLeft] = canvasMap(YLeft).invTransform(pos.y()); + coords[YRight] = canvasMap(YRight).invTransform(pos.y()); - for (const auto &curve: plot_logic_curves) { - if (curve->isVisible()) { - const QPointF p( coords[ curve->xAxis().pos ], coords[ curve->yAxis().pos ] ); - if ( curve->testHit( p )) { - return curve; - } - } - } - return nullptr; + for(const auto &curve : plot_logic_curves) { + if(curve->isVisible()) { + const QPointF p(coords[curve->xAxis().pos], coords[curve->yAxis().pos]); + if(curve->testHit(p)) { + return curve; + } + } + } + return nullptr; } #include "moc_oscilloscope_plot.cpp" diff --git a/gui/src/plot_line_handle.cpp b/gui/src/plot_line_handle.cpp index d34418a79a..8feb925148 100644 --- a/gui/src/plot_line_handle.cpp +++ b/gui/src/plot_line_handle.cpp @@ -19,28 +19,26 @@ */ #include "plot_line_handle.h" -#include "handles_area.hpp" -#include -#include -#include +#include "handles_area.hpp" #include - #include +#include +#include +#include -PlotLineHandle::PlotLineHandle(const QPixmap &handleIcon, QWidget *parent): - QWidget(parent), - m_enable_silent_move(false), - m_innerSpacing(0), - m_outerSpacing(0), - m_image(handleIcon), - m_grabbed(false), - m_current_pos(0), - m_width(20), - m_height(20) -{ -} +PlotLineHandle::PlotLineHandle(const QPixmap &handleIcon, QWidget *parent) + : QWidget(parent) + , m_enable_silent_move(false) + , m_innerSpacing(0) + , m_outerSpacing(0) + , m_image(handleIcon) + , m_grabbed(false) + , m_current_pos(0) + , m_width(20) + , m_height(20) +{} void PlotLineHandle::moveSilently(QPoint pos) { @@ -48,20 +46,11 @@ void PlotLineHandle::moveSilently(QPoint pos) moveWithinParent(pos.x(), pos.y()); } -int PlotLineHandle::position() -{ - return m_current_pos; -} +int PlotLineHandle::position() { return m_current_pos; } -void PlotLineHandle::setPen(const QPen& pen) -{ - m_pen = pen; -} +void PlotLineHandle::setPen(const QPen &pen) { m_pen = pen; } -const QPen& PlotLineHandle::pen() -{ - return m_pen; -} +const QPen &PlotLineHandle::pen() { return m_pen; } void PlotLineHandle::enterEvent(QEvent *event) { @@ -88,17 +77,17 @@ void PlotLineHandle::mouseReleaseEvent(QMouseEvent *event) void PlotLineHandle::setGrabbed(bool grabbed) { - if (m_grabbed != grabbed) { + if(m_grabbed != grabbed) { m_grabbed = grabbed; Q_EMIT grabbedChanged(grabbed); } } -PlotGateHandle::PlotGateHandle(const QPixmap &handleIcon, QWidget *parent): - PlotLineHandle(handleIcon, parent), - m_alignLeft(true), - m_reachLimit(false), - m_timeValue(0) +PlotGateHandle::PlotGateHandle(const QPixmap &handleIcon, QWidget *parent) + : PlotLineHandle(handleIcon, parent) + , m_alignLeft(true) + , m_reachLimit(false) + , m_timeValue(0) { m_width = m_image.width(); m_height = m_image.height(); @@ -106,27 +95,21 @@ PlotGateHandle::PlotGateHandle(const QPixmap &handleIcon, QWidget *parent): setMaximumSize(m_width, m_height); } -void PlotGateHandle::triggerMove() -{ - Q_EMIT positionChanged(m_current_pos); -} +void PlotGateHandle::triggerMove() { Q_EMIT positionChanged(m_current_pos); } void PlotGateHandle::setPosition(int pos) { - if (m_current_pos != pos) + if(m_current_pos != pos) moveWithinParent(centerPosToOrigin(pos), 0); } void PlotGateHandle::setPositionSilenty(int pos) { - if (m_current_pos != pos) + if(m_current_pos != pos) moveSilently(QPoint(centerPosToOrigin(pos), 0)); } -void PlotGateHandle::updatePosition() -{ - moveSilently(QPoint(0, centerPosToOrigin(m_current_pos))); -} +void PlotGateHandle::updatePosition() { moveSilently(QPoint(0, centerPosToOrigin(m_current_pos))); } void PlotGateHandle::moveWithinParent(int x, int y) { @@ -138,15 +121,13 @@ void PlotGateHandle::moveWithinParent(int x, int y) int upper_limit = area->width() - area->rightPadding() - width() / 2 - 1; int initialX = x; - if (x < lower_limit && !m_alignLeft){ + if(x < lower_limit && !m_alignLeft) { x = lower_limit; - m_reachLimit = true;//handle hit the margin - } - else if (x > upper_limit && m_alignLeft){ + m_reachLimit = true; // handle hit the margin + } else if(x > upper_limit && m_alignLeft) { x = upper_limit; - m_reachLimit = true;//handle hit the margin - } - else{ + m_reachLimit = true; // handle hit the margin + } else { m_reachLimit = false; } @@ -155,56 +136,47 @@ void PlotGateHandle::moveWithinParent(int x, int y) int oldCurrentPos = m_current_pos; - if(m_reachLimit){ + if(m_reachLimit) { m_position = initialX; - } - else{ + } else { m_current_pos = centerPos; } - if (centerPos != oldCenterPos) { - if(!m_reachLimit){ - if(x < m_otherCursorPos + width() && !m_alignLeft){ + if(centerPos != oldCenterPos) { + if(!m_reachLimit) { + if(x < m_otherCursorPos + width() && !m_alignLeft) { /*move the handle only if it doens't hit the other handle */ move(x, this->y()); - } - else if(x > m_otherCursorPos && m_alignLeft){ + } else if(x > m_otherCursorPos && m_alignLeft) { /*move the handle only if it doens't hit the other handle */ - move(x,this->y()); - } - else{/* remember bar position */ + move(x, this->y()); + } else { /* remember bar position */ centerPos = oldCurrentPos; m_current_pos = centerPos; } - } - else{ - if(m_alignLeft){//make sure that the handle doesn't go outside of the plot margins - move(upper_limit,this->y()); - } - else{ - move(lower_limit,this->y()); + } else { + if(m_alignLeft) { // make sure that the handle doesn't go outside of the plot margins + move(upper_limit, this->y()); + } else { + move(lower_limit, this->y()); } } - if (!m_enable_silent_move) + if(!m_enable_silent_move) Q_EMIT positionChanged(centerPos); - } - else{ - if(m_reachLimit){//update only the bar position if the handle reached a margin + } else { + if(m_reachLimit) { // update only the bar position if the handle reached a margin Q_EMIT positionChanged(originPosToCenter(m_position)); } } m_enable_silent_move = false; } -void PlotGateHandle::setInnerSpacing(int value) -{ - m_innerSpacing = value; -} +void PlotGateHandle::setInnerSpacing(int value) { m_innerSpacing = value; } int PlotGateHandle::position() { - if(m_reachLimit)//if the handle reached the limit return the position of the bar + if(m_reachLimit) // if the handle reached the limit return the position of the bar return originPosToCenter(m_position); return m_current_pos; } @@ -216,23 +188,20 @@ void PlotGateHandle::setTimeValue(double val) } void PlotGateHandle::setCenterLeft(bool val) -{/* align the bar to the left or the right part of the handle*/ +{ /* align the bar to the left or the right part of the handle*/ m_alignLeft = val; } -int PlotGateHandle::getCurrentPos() -{ - return m_position; -} +int PlotGateHandle::getCurrentPos() { return m_position; } bool PlotGateHandle::reachedLimit() { - return m_reachLimit;//cursor handle reached the plot margin + return m_reachLimit; // cursor handle reached the plot margin } void PlotGateHandle::setOtherCursorPosition(int position) { - m_otherCursorPos = position;//position of the other handle cursor + m_otherCursorPos = position; // position of the other handle cursor } void PlotGateHandle::paintEvent(QPaintEvent *event) @@ -244,13 +213,13 @@ void PlotGateHandle::paintEvent(QPaintEvent *event) p.drawPixmap(imageTopLeft, m_image); p.setPen(QPen(QColor(Qt::black))); - QString handleText = d_timeFormatter.format(m_timeValue,"",2); + QString handleText = d_timeFormatter.format(m_timeValue, "", 2); QFontMetrics fm = p.fontMetrics(); int textWidth = fm.horizontalAdvance(handleText); int textHeight = fm.height(); - p.drawText(QPoint((width()-textWidth)/2,height()-textHeight/2),handleText); + p.drawText(QPoint((width() - textWidth) / 2, height() - textHeight / 2), handleText); } int PlotGateHandle::originPosToCenter(int origin) @@ -269,11 +238,9 @@ int PlotGateHandle::centerPosToOrigin(int center) return (center - offset); } - -PlotLineHandleH::PlotLineHandleH(const QPixmap &handleIcon, QWidget *parent, - bool facingBottom): - PlotLineHandle(handleIcon, parent), - m_facingBottom(facingBottom) +PlotLineHandleH::PlotLineHandleH(const QPixmap &handleIcon, QWidget *parent, bool facingBottom) + : PlotLineHandle(handleIcon, parent) + , m_facingBottom(facingBottom) { m_innerSpacing = m_image.width() / 2; m_width = m_image.width(); @@ -282,32 +249,23 @@ PlotLineHandleH::PlotLineHandleH(const QPixmap &handleIcon, QWidget *parent, setMaximumSize(m_width, m_height); } -void PlotLineHandleH::triggerMove() -{ - Q_EMIT positionChanged(m_current_pos); -} +void PlotLineHandleH::triggerMove() { Q_EMIT positionChanged(m_current_pos); } void PlotLineHandleH::setPosition(int pos) { - if (m_current_pos != pos) + if(m_current_pos != pos) moveWithinParent(centerPosToOrigin(pos), 0); } void PlotLineHandleH::setPositionSilenty(int pos) { - if (m_current_pos != pos) + if(m_current_pos != pos) moveSilently(QPoint(centerPosToOrigin(pos), 0)); } -void PlotLineHandleH::updatePosition() -{ - moveSilently(QPoint(centerPosToOrigin(m_current_pos), 0)); -} +void PlotLineHandleH::updatePosition() { moveSilently(QPoint(centerPosToOrigin(m_current_pos), 0)); } -void PlotLineHandleH::setInnerSpacing(int value) -{ - m_innerSpacing = value; -} +void PlotLineHandleH::setInnerSpacing(int value) { m_innerSpacing = value; } void PlotLineHandleH::moveWithinParent(int x, int y) { @@ -318,18 +276,18 @@ void PlotLineHandleH::moveWithinParent(int x, int y) int lower_limit = 0 + area->leftPadding() - width() / 2; int upper_limit = area->width() - area->rightPadding() - width() / 2 - 1; - if (x < lower_limit) + if(x < lower_limit) x = lower_limit; - else if (x > upper_limit) + else if(x > upper_limit) x = upper_limit; int centerPos = originPosToCenter(x); int oldCenterPos = originPosToCenter(this->x()); - if (centerPos != oldCenterPos) { + if(centerPos != oldCenterPos) { move(x, this->y()); - if (!m_enable_silent_move) + if(!m_enable_silent_move) Q_EMIT positionChanged(centerPos); } m_enable_silent_move = false; @@ -344,9 +302,8 @@ void PlotLineHandleH::paintEvent(QPaintEvent *) p.setPen(m_pen); - if (m_facingBottom) { - lineStart = QPoint(m_image.width() / 2, - m_image.height()); + if(m_facingBottom) { + lineStart = QPoint(m_image.width() / 2, m_image.height()); imageTopLeft = QPoint(0, 0); } else { lineStart = QPoint(m_image.width() / 2, 0); @@ -382,39 +339,32 @@ void PlotLineHandleH::mouseDoubleClickEvent(QMouseEvent *event) Q_EMIT reset(); } -PlotLineHandleV::PlotLineHandleV(const QPixmap &handleIcon, QWidget *parent, - bool facingRight): - PlotLineHandle(handleIcon, parent), - m_facingRight(facingRight) +PlotLineHandleV::PlotLineHandleV(const QPixmap &handleIcon, QWidget *parent, bool facingRight) + : PlotLineHandle(handleIcon, parent) + , m_facingRight(facingRight) { m_innerSpacing = m_image.height() / 2; - m_width = m_innerSpacing + m_image.width() + m_outerSpacing; + m_width = m_innerSpacing + m_image.width() + m_outerSpacing; m_height = m_image.height(); setMinimumSize(m_width, m_height); setMaximumSize(m_width, m_height); } -void PlotLineHandleV::triggerMove() -{ - Q_EMIT positionChanged(m_current_pos); -} +void PlotLineHandleV::triggerMove() { Q_EMIT positionChanged(m_current_pos); } void PlotLineHandleV::setPosition(int pos) { - if (m_current_pos != pos) + if(m_current_pos != pos) moveWithinParent(0, centerPosToOrigin(pos)); } void PlotLineHandleV::setPositionSilenty(int pos) { - if (m_current_pos != pos) + if(m_current_pos != pos) moveSilently(QPoint(0, centerPosToOrigin(pos))); } -void PlotLineHandleV::updatePosition() -{ - moveSilently(QPoint(0, centerPosToOrigin(m_current_pos))); -} +void PlotLineHandleV::updatePosition() { moveSilently(QPoint(0, centerPosToOrigin(m_current_pos))); } void PlotLineHandleV::moveWithinParent(int x, int y) { @@ -425,17 +375,17 @@ void PlotLineHandleV::moveWithinParent(int x, int y) int lower_limit = 0 + area->topPadding() - height() / 2; int upper_limit = area->height() - area->bottomPadding() - height() / 2 - 1; - if (y < lower_limit) + if(y < lower_limit) y = lower_limit; - else if (y > upper_limit) + else if(y > upper_limit) y = upper_limit; int centerPos = originPosToCenter(y); int oldCenterPos = originPosToCenter(this->y()); - if (centerPos != oldCenterPos) { + if(centerPos != oldCenterPos) { move(this->x(), y); - if (!m_enable_silent_move) + if(!m_enable_silent_move) Q_EMIT positionChanged(centerPos); } m_enable_silent_move = false; @@ -450,7 +400,7 @@ void PlotLineHandleV::paintEvent(QPaintEvent *) p.setPen(m_pen); - if (m_facingRight) { + if(m_facingRight) { lineStart = QPoint(m_image.width(), m_image.height() / 2); imageTopLeft = QPoint(0, 0); } else { @@ -487,18 +437,14 @@ void PlotLineHandleV::mouseDoubleClickEvent(QMouseEvent *event) Q_EMIT reset(); } - -FreePlotLineHandleH::FreePlotLineHandleH(const QPixmap &handleIcon, - const QPixmap &beyondLeftIcon, - const QPixmap &beyondRightIcon, - QWidget *parent, bool facingRight): - PlotLineHandleH(handleIcon, parent, facingRight), - m_beyondLeftImage(beyondLeftIcon), - m_beyondRightImage(beyondRightIcon), - m_isBeyondLeft(false), - m_isBeyondRight(false) -{ -} +FreePlotLineHandleH::FreePlotLineHandleH(const QPixmap &handleIcon, const QPixmap &beyondLeftIcon, + const QPixmap &beyondRightIcon, QWidget *parent, bool facingRight) + : PlotLineHandleH(handleIcon, parent, facingRight) + , m_beyondLeftImage(beyondLeftIcon) + , m_beyondRightImage(beyondRightIcon) + , m_isBeyondLeft(false) + , m_isBeyondRight(false) +{} void FreePlotLineHandleH::moveWithinParent(int x, int y) { @@ -512,19 +458,19 @@ void FreePlotLineHandleH::moveWithinParent(int x, int y) int centerPos = originPosToCenter(x); int oldCenterPos = m_current_pos; - if (centerPos != oldCenterPos) { + if(centerPos != oldCenterPos) { m_isBeyondLeft = false; m_isBeyondRight = false; - if (x < lower_limit) { + if(x < lower_limit) { x = lower_limit; m_isBeyondLeft = true; - } else if (x > upper_limit) { + } else if(x > upper_limit) { x = upper_limit; m_isBeyondRight = true; } move(x, this->y()); - if (!m_enable_silent_move) { + if(!m_enable_silent_move) { Q_EMIT positionChanged(centerPos); this->update(); } @@ -541,18 +487,17 @@ void FreePlotLineHandleH::paintEvent(QPaintEvent *) p.setPen(m_pen); - if (m_facingBottom) { - lineStart = QPoint(m_image.width() / 2, - m_image.height()); + if(m_facingBottom) { + lineStart = QPoint(m_image.width() / 2, m_image.height()); imageTopLeft = QPoint(0, 0); } else { lineStart = QPoint(m_image.width() / 2, 0); imageTopLeft = QPoint(0, m_innerSpacing); } - if (m_isBeyondLeft) { + if(m_isBeyondLeft) { p.drawPixmap(imageTopLeft, m_beyondLeftImage); - } else if (m_isBeyondRight) { + } else if(m_isBeyondRight) { p.drawPixmap(imageTopLeft, m_beyondRightImage); } else { p.drawLine(lineStart, lineStart + QPoint(0, m_innerSpacing)); @@ -560,19 +505,16 @@ void FreePlotLineHandleH::paintEvent(QPaintEvent *) } } -FreePlotLineHandleV::FreePlotLineHandleV(const QPixmap &handleIcon, - const QPixmap &beyondTopIcon, - const QPixmap &beyondBottomIcon, - QWidget *parent, bool facingRight, - const QString &name): - PlotLineHandleV(handleIcon, parent, facingRight), - m_beyondTopImage(beyondTopIcon), - m_beyondBottomImage(beyondBottomIcon), - m_isBeyondTop(false), - m_isBeyondBottom(false), - m_name(name) -{ -} +FreePlotLineHandleV::FreePlotLineHandleV(const QPixmap &handleIcon, const QPixmap &beyondTopIcon, + const QPixmap &beyondBottomIcon, QWidget *parent, bool facingRight, + const QString &name) + : PlotLineHandleV(handleIcon, parent, facingRight) + , m_beyondTopImage(beyondTopIcon) + , m_beyondBottomImage(beyondBottomIcon) + , m_isBeyondTop(false) + , m_isBeyondBottom(false) + , m_name(name) +{} void FreePlotLineHandleV::moveWithinParent(int x, int y) { @@ -586,19 +528,19 @@ void FreePlotLineHandleV::moveWithinParent(int x, int y) int centerPos = originPosToCenter(y); int oldCenterPos = m_current_pos; - if (centerPos != oldCenterPos || !m_isBeyondTop || !m_isBeyondBottom) { + if(centerPos != oldCenterPos || !m_isBeyondTop || !m_isBeyondBottom) { m_isBeyondTop = false; m_isBeyondBottom = false; - if (y < lower_limit) { + if(y < lower_limit) { y = lower_limit; m_isBeyondTop = true; - } else if (y > upper_limit) { + } else if(y > upper_limit) { y = upper_limit; m_isBeyondBottom = true; } move(this->x(), y); - if (!m_enable_silent_move) { + if(!m_enable_silent_move) { Q_EMIT positionChanged(centerPos); this->update(); } @@ -609,16 +551,13 @@ void FreePlotLineHandleV::moveWithinParent(int x, int y) void FreePlotLineHandleV::setName(const QString &name) { - if (m_name != name) { + if(m_name != name) { m_name = name; update(); } } -QString FreePlotLineHandleV::getName() const -{ - return m_name; -} +QString FreePlotLineHandleV::getName() const { return m_name; } void FreePlotLineHandleV::paintEvent(QPaintEvent *) { @@ -628,7 +567,7 @@ void FreePlotLineHandleV::paintEvent(QPaintEvent *) p.setPen(m_pen); - if (m_facingRight) { + if(m_facingRight) { lineStart = QPoint(m_image.width(), m_image.height() / 2); imageTopLeft = QPoint(0, 0); } else { @@ -636,24 +575,23 @@ void FreePlotLineHandleV::paintEvent(QPaintEvent *) imageTopLeft = QPoint(m_innerSpacing, 0); } - if (m_isBeyondTop) { + if(m_isBeyondTop) { p.drawPixmap(imageTopLeft, m_beyondTopImage); - } else if (m_isBeyondBottom) { + } else if(m_isBeyondBottom) { p.drawPixmap(imageTopLeft, m_beyondBottomImage); } else { p.drawLine(lineStart, lineStart + QPoint(m_innerSpacing, 0)); - if (!m_name.isEmpty()) { + if(!m_name.isEmpty()) { int fontSize = 10; const QString fontFamily = QApplication::font().family(); - while (QFontMetrics(QFont(fontFamily, fontSize)).horizontalAdvance(m_name) - > m_image.width()) { + while(QFontMetrics(QFont(fontFamily, fontSize)).horizontalAdvance(m_name) > m_image.width()) { fontSize--; } - if (fontSize < 7) { + if(fontSize < 7) { // Set tool tip if size is to small as text // won't be visible setToolTip(m_name); @@ -678,16 +616,12 @@ void FreePlotLineHandleV::paintEvent(QPaintEvent *) } } -RoundedHandleV::RoundedHandleV(const QPixmap &handleIcon, - const QPixmap &beyondTopIcon, - const QPixmap &beyondBottomIcon, - QWidget *parent, bool facingRight, - const QString &name, bool selectable): - FreePlotLineHandleV(handleIcon, beyondTopIcon, beyondBottomIcon, - parent, facingRight, name) +RoundedHandleV::RoundedHandleV(const QPixmap &handleIcon, const QPixmap &beyondTopIcon, const QPixmap &beyondBottomIcon, + QWidget *parent, bool facingRight, const QString &name, bool selectable) + : FreePlotLineHandleV(handleIcon, beyondTopIcon, beyondBottomIcon, parent, facingRight, name) { m_innerSpacing = m_image.height(); - m_width = m_innerSpacing + m_image.width() + m_outerSpacing; + m_width = m_innerSpacing + m_image.width() + m_outerSpacing; m_height = m_image.height(); setMinimumSize(m_width, m_height); setMaximumSize(m_width, m_height); @@ -695,14 +629,11 @@ RoundedHandleV::RoundedHandleV(const QPixmap &handleIcon, m_selectable = selectable; } -QColor RoundedHandleV::roundRectColor() -{ - return m_roundRectColor; -} +QColor RoundedHandleV::roundRectColor() { return m_roundRectColor; } void RoundedHandleV::setRoundRectColor(const QColor &newColor) { - if (m_roundRectColor != newColor) { + if(m_roundRectColor != newColor) { m_roundRectColor = newColor; this->update(); } @@ -710,20 +641,17 @@ void RoundedHandleV::setRoundRectColor(const QColor &newColor) void RoundedHandleV::setSelected(bool selected) { - if (m_selected != selected) { + if(m_selected != selected) { m_selected = selected; update(); } } -bool RoundedHandleV::isSelected() const -{ - return m_selected; -} +bool RoundedHandleV::isSelected() const { return m_selected; } void RoundedHandleV::setSelectable(bool selectable) { - if (m_selectable != selectable) { + if(m_selectable != selectable) { m_selectable = selectable; update(); } @@ -740,8 +668,8 @@ void RoundedHandleV::paintEvent(QPaintEvent *pv) } QRect rect(x, 0, m_image.width() - 1, m_image.height() - 1); - if (m_selected && m_selectable) { - if (QIcon::themeName() == "scopy-default") { + if(m_selected && m_selectable) { + if(QIcon::themeName() == "scopy-default") { p.setPen(QPen(Qt::white, 2, Qt::SolidLine)); } else { p.setPen(QPen(Qt::black, 2, Qt::SolidLine)); @@ -759,7 +687,7 @@ void RoundedHandleV::paintEvent(QPaintEvent *pv) void RoundedHandleV::mouseDoubleClickEvent(QMouseEvent *event) { - if (!m_selectable) { + if(!m_selectable) { FreePlotLineHandleV::mouseDoubleClickEvent(event); return; } diff --git a/gui/src/plot_utils.cpp b/gui/src/plot_utils.cpp index 1c2bb4cec0..a02f9379fb 100644 --- a/gui/src/plot_utils.cpp +++ b/gui/src/plot_utils.cpp @@ -19,6 +19,7 @@ */ #include "plot_utils.hpp" + #include #include @@ -30,36 +31,29 @@ using namespace std; * PrefixFormatter class implementation */ -PrefixFormatter::PrefixFormatter(const vector> &prefixes, QObject *parent ): - QObject(parent), - m_prefixes(prefixes), - m_twoDecimalMode(false) +PrefixFormatter::PrefixFormatter(const vector> &prefixes, QObject *parent) + : QObject(parent) + , m_prefixes(prefixes) + , m_twoDecimalMode(false) { - m_defaultPrefixIndex = find_if( m_prefixes.begin(), m_prefixes.end(), - [](const pair& element) {return element.second == 1E0;} ) - m_prefixes.begin(); + m_defaultPrefixIndex = find_if(m_prefixes.begin(), m_prefixes.end(), + [](const pair &element) { return element.second == 1E0; }) - + m_prefixes.begin(); } -PrefixFormatter::~PrefixFormatter() -{ -} +PrefixFormatter::~PrefixFormatter() {} -void PrefixFormatter::setTwoDecimalMode(bool enable) -{ - m_twoDecimalMode = enable; -} +void PrefixFormatter::setTwoDecimalMode(bool enable) { m_twoDecimalMode = enable; } -bool PrefixFormatter::getTwoDecimalMode() -{ - return m_twoDecimalMode; -} +bool PrefixFormatter::getTwoDecimalMode() { return m_twoDecimalMode; } QString PrefixFormatter::buildString(double value, QString prefix, QString unitType, int precision) const { - if (m_trimZeroes) { - for (auto i = 0; i < precision; i++) { - const double singlePrecision = value * pow(10,i); - if (singlePrecision == round(singlePrecision)) { + if(m_trimZeroes) { + for(auto i = 0; i < precision; i++) { + const double singlePrecision = value * pow(10, i); + if(singlePrecision == round(singlePrecision)) { precision = i; break; } @@ -74,11 +68,11 @@ int PrefixFormatter::findPrefixIndex(double value) const int index = m_defaultPrefixIndex; value = fabs(value); - for (auto it = m_prefixes.rbegin(); it != m_prefixes.rend(); ++it) { - if (value >= (*it).second) { + for(auto it = m_prefixes.rbegin(); it != m_prefixes.rend(); ++it) { + if(value >= (*it).second) { index = m_prefixes.rend() - it - 1; - if (m_twoDecimalMode) - if (value / (*it).second >= 100 && it != m_prefixes.rbegin()) + if(m_twoDecimalMode) + if(value / (*it).second >= 100 && it != m_prefixes.rbegin()) index++; break; } @@ -87,15 +81,9 @@ int PrefixFormatter::findPrefixIndex(double value) const return index; } -bool PrefixFormatter::getTrimZeroes() const -{ - return m_trimZeroes; -} +bool PrefixFormatter::getTrimZeroes() const { return m_trimZeroes; } -void PrefixFormatter::setTrimZeroes(bool trimZeroes) -{ - m_trimZeroes = trimZeroes; -} +void PrefixFormatter::setTrimZeroes(bool trimZeroes) { m_trimZeroes = trimZeroes; } QString PrefixFormatter::format(double value, QString unitType = "", int precision = 0) const { @@ -104,7 +92,7 @@ QString PrefixFormatter::format(double value, QString unitType = "", int precisi return buildString(value / m_prefixes[index].second, m_prefixes[index].first, unitType, precision); } -void PrefixFormatter::getFormatAttributes(double value, QString& prefix, double& scale) const +void PrefixFormatter::getFormatAttributes(double value, QString &prefix, double &scale) const { int index = findPrefixIndex(value); @@ -122,84 +110,70 @@ double PrefixFormatter::getFormatedValue(double value) { int index = findPrefixIndex(value); - return value/m_prefixes[index].second; + return value / m_prefixes[index].second; } /* * MetricPrefixFormatter class implementation */ -MetricPrefixFormatter::MetricPrefixFormatter(QObject *parent): - PrefixFormatter({ - {"p", 1E-12}, - {"n", 1E-9}, - {"μ", 1E-6}, - {"m", 1E-3}, - {"", 1E0}, - {"k", 1E3}, - {"M", 1E6}, - {"G", 1E9}, - {"T", 1E12} }, - parent - ) -{ -} +MetricPrefixFormatter::MetricPrefixFormatter(QObject *parent) + : PrefixFormatter({{"p", 1E-12}, + {"n", 1E-9}, + {"μ", 1E-6}, + {"m", 1E-3}, + {"", 1E0}, + {"k", 1E3}, + {"M", 1E6}, + {"G", 1E9}, + {"T", 1E12}}, + parent) +{} /* * TimePrefixFormatter class implementation */ -TimePrefixFormatter::TimePrefixFormatter(QObject *parent): - PrefixFormatter({ - {"ps", 1E-12}, - {"ns", 1E-9}, - {"μs", 1E-6}, - {"ms", 1E-3}, - {"s", 1E0}, - {"min", 60}, - {"hr", 60 * 60}, - {"days", 24 * 60 * 60} }, - parent - ) -{ -} - +TimePrefixFormatter::TimePrefixFormatter(QObject *parent) + : PrefixFormatter({{"ps", 1E-12}, + {"ns", 1E-9}, + {"μs", 1E-6}, + {"ms", 1E-3}, + {"s", 1E0}, + {"min", 60}, + {"hr", 60 * 60}, + {"days", 24 * 60 * 60}}, + parent) +{} /* * NumberSeries class implementation */ -NumberSeries::NumberSeries(double lower, double upper, unsigned int powerStep, - const std::vector& steps): - m_lowerLimit(qAbs(lower)), - m_upperLimit(qAbs(upper)), - m_powerStep(powerStep), - m_templateSteps(steps) +NumberSeries::NumberSeries(double lower, double upper, unsigned int powerStep, const std::vector &steps) + : m_lowerLimit(qAbs(lower)) + , m_upperLimit(qAbs(upper)) + , m_powerStep(powerStep) + , m_templateSteps(steps) { // Avoid infinite loop - if (powerStep < 2) + if(powerStep < 2) m_powerStep = 2; - if (lower == 0) + if(lower == 0) m_lowerLimit = m_upperLimit; - if (lower > upper) + if(lower > upper) qSwap(lower, upper); buildNumberSeries(); } -NumberSeries::~NumberSeries() -{ +NumberSeries::~NumberSeries() {} -} - -const std::vector& NumberSeries::getNumbers() -{ - return m_numbers; -} +const std::vector &NumberSeries::getNumbers() { return m_numbers; } double NumberSeries::getNumberBefore(double value) { auto numberIt = std::lower_bound(m_numbers.begin(), m_numbers.end(), value); - if (numberIt != m_numbers.begin()) + if(numberIt != m_numbers.begin()) numberIt--; return (*numberIt); @@ -209,7 +183,7 @@ double NumberSeries::getNumberAfter(double value) { auto numberIt = std::upper_bound(m_numbers.begin(), m_numbers.end(), value); - if (numberIt == m_numbers.end()) + if(numberIt == m_numbers.end()) numberIt--; return (*numberIt); @@ -217,50 +191,43 @@ double NumberSeries::getNumberAfter(double value) void NumberSeries::setLower(double value) { - if ((value != m_lowerLimit) && (value != 0)) { + if((value != m_lowerLimit) && (value != 0)) { m_lowerLimit = qAbs(value); buildNumberSeries(); } } -double NumberSeries::lower() -{ - return m_lowerLimit; -} +double NumberSeries::lower() { return m_lowerLimit; } void NumberSeries::setUpper(double value) { - if (value != m_upperLimit) { + if(value != m_upperLimit) { m_upperLimit = qAbs(value); buildNumberSeries(); } } -double NumberSeries::upper() -{ - return m_upperLimit; -} +double NumberSeries::upper() { return m_upperLimit; } void NumberSeries::setPowerStep(unsigned int value) { - if (value != m_powerStep) { + if(value != m_powerStep) { m_powerStep = value; buildNumberSeries(); } } -unsigned int NumberSeries::stepPower() -{ - return m_powerStep; -} +unsigned int NumberSeries::stepPower() { return m_powerStep; } void NumberSeries::buildNumberSeries() { m_numbers.clear(); - for (double i = m_lowerLimit; i <= m_upperLimit; i *= m_powerStep) - for (size_t step = 0; step < m_templateSteps.size(); step++) { + for(double i = m_lowerLimit; i <= m_upperLimit; i *= m_powerStep) + for(size_t step = 0; step < m_templateSteps.size(); step++) { double number = i * m_templateSteps[step]; - if (number > m_upperLimit) + if(number > m_upperLimit) break; m_numbers.push_back(i * m_templateSteps[step]); } } + +#include "moc_plot_utils.cpp" diff --git a/gui/src/plotaxis.cpp b/gui/src/plotaxis.cpp index 3b17cb6d59..d69613e63e 100644 --- a/gui/src/plotaxis.cpp +++ b/gui/src/plotaxis.cpp @@ -1,10 +1,15 @@ #include "plotaxis.h" -#include + #include +#include using namespace scopy; -PlotAxis::PlotAxis(int position, PlotWidget *p, QPen pen,QObject *parent) : - QObject(parent), m_plotWidget(p), m_plot(p->plot()), m_position(position), m_axisId(QwtAxisId(position)) +PlotAxis::PlotAxis(int position, PlotWidget *p, QPen pen, QObject *parent) + : QObject(parent) + , m_plotWidget(p) + , m_plot(p->plot()) + , m_position(position) + , m_axisId(QwtAxisId(position)) { m_min = -1; m_max = 1; @@ -20,17 +25,16 @@ PlotAxis::PlotAxis(int position, PlotWidget *p, QPen pen,QObject *parent) : // move this outside (?) if(isHorizontal()) { auto prefixFormatter = new MetricPrefixFormatter(); - m_scaleDraw = new OscScaleDraw(prefixFormatter,"s"); - } - else { + m_scaleDraw = new OscScaleDraw(prefixFormatter, "s"); + } else { auto prefixFormatter = new MetricPrefixFormatter(); prefixFormatter->setTrimZeroes(true); prefixFormatter->setTwoDecimalMode(true); - m_scaleDraw = new OscScaleDraw(prefixFormatter,""); + m_scaleDraw = new OscScaleDraw(prefixFormatter, ""); } m_scaleDraw->setColor(pen.color()); - m_plot->setAxisScaleDraw(m_axisId,m_scaleDraw); + m_plot->setAxisScaleDraw(m_axisId, m_scaleDraw); m_scaleEngine = new OscScaleEngine(); m_scaleEngine->setMajorTicksCount(m_divs); @@ -48,31 +52,30 @@ PlotAxis::PlotAxis(int position, PlotWidget *p, QPen pen,QObject *parent) : connect(this, &PlotAxis::maxChanged, this, &PlotAxis::updateAxisScale); } -void PlotAxis::setupZoomer() { +void PlotAxis::setupZoomer() +{ // zoomer // OscPlotZoomer - need constructor - -// m_zoomer = new QwtPlotZoomer(m_plotWidget->xAxis()->axisId(), m_axisId, m_plot->canvas(), false); + // m_zoomer = new QwtPlotZoomer(m_plotWidget->xAxis()->axisId(), m_axisId, m_plot->canvas(), false); -// m_zoomer->setMousePattern(QwtEventPattern::MouseSelect2, -// Qt::RightButton, Qt::ControlModifier); -// m_zoomer->setMousePattern(QwtEventPattern::MouseSelect3, -// Qt::RightButton); - -// m_zoomer->setZoomBase(false); -// m_zoomer->setEnabled(true); - -// connect(m_zoomer,&QwtPlotZoomer::zoomed,this, [=](const QRectF &rect ) { -// qInfo()<< rect<< m_zoomer->zoomRectIndex() << "ZoomOut"; -// m_scaleDraw->invalidateCache(); -// }); - zoom out doesn't work correctly + // m_zoomer->setMousePattern(QwtEventPattern::MouseSelect2, + // Qt::RightButton, Qt::ControlModifier); + // m_zoomer->setMousePattern(QwtEventPattern::MouseSelect3, + // Qt::RightButton); + // m_zoomer->setZoomBase(false); + // m_zoomer->setEnabled(true); + // connect(m_zoomer,&QwtPlotZoomer::zoomed,this, [=](const QRectF &rect ) { + // qInfo()<< rect<< m_zoomer->zoomRectIndex() << "ZoomOut"; + // m_scaleDraw->invalidateCache(); + // }); - zoom out doesn't work correctly } -void PlotAxis::setupAxisScale() { - QwtScaleDraw::Alignment scale = - static_cast(m_position); +void PlotAxis::setupAxisScale() +{ + QwtScaleDraw::Alignment scale = static_cast(m_position); auto scaleItem = new EdgelessPlotScaleItem(scale); scaleItem->scaleDraw()->setAlignment(scale); @@ -89,51 +92,38 @@ void PlotAxis::setupAxisScale() { scaleItem->setZ(200); } -int PlotAxis::position() -{ - return m_position; -} +int PlotAxis::position() { return m_position; } -bool PlotAxis::isHorizontal() -{ - return (m_position == QwtAxis::XBottom || m_position == QwtAxis::XTop); -} +bool PlotAxis::isHorizontal() { return (m_position == QwtAxis::XBottom || m_position == QwtAxis::XTop); } -bool PlotAxis::isVertical() -{ - return (m_position == QwtAxis::YLeft || m_position == QwtAxis::YRight); -} +bool PlotAxis::isVertical() { return (m_position == QwtAxis::YLeft || m_position == QwtAxis::YRight); } -double PlotAxis::divs() const -{ - return (m_divs-1); -} +double PlotAxis::divs() const { return (m_divs - 1); } -void PlotAxis::setDivs(double divs) { +void PlotAxis::setDivs(double divs) +{ m_divs = divs; updateAxisScale(); - } -void PlotAxis::setInterval(double min, double max) { +void PlotAxis::setInterval(double min, double max) +{ setMin(min); setMax(max); -// updateAxisScale(); + // updateAxisScale(); } -void PlotAxis::setVisible(bool val) -{ - m_plot->setAxisVisible(m_axisId, val); -} +void PlotAxis::setVisible(bool val) { m_plot->setAxisVisible(m_axisId, val); } -void PlotAxis::updateAxisScale() { - m_plot->setAxisScale(m_axisId, m_min, m_max, (m_max - m_min)/m_divs); // set Divs, limits +void PlotAxis::updateAxisScale() +{ + m_plot->setAxisScale(m_axisId, m_min, m_max, (m_max - m_min) / m_divs); // set Divs, limits m_plot->replot(); } void PlotAxis::setMin(double newMin) { - if (qFuzzyCompare(m_min, newMin)) + if(qFuzzyCompare(m_min, newMin)) return; m_min = newMin; emit minChanged(); @@ -141,38 +131,22 @@ void PlotAxis::setMin(double newMin) void PlotAxis::setMax(double newMax) { - if (qFuzzyCompare(m_max, newMax)) + if(qFuzzyCompare(m_max, newMax)) return; m_max = newMax; emit maxChanged(); } -OscScaleDraw *PlotAxis::scaleDraw() const -{ - return m_scaleDraw; -} +OscScaleDraw *PlotAxis::scaleDraw() const { return m_scaleDraw; } -OscScaleEngine *PlotAxis::scaleEngine() const -{ - return m_scaleEngine; -} +OscScaleEngine *PlotAxis::scaleEngine() const { return m_scaleEngine; } -QwtPlotZoomer *PlotAxis::zoomer() const -{ - return m_zoomer; -} +QwtPlotZoomer *PlotAxis::zoomer() const { return m_zoomer; } -double PlotAxis::max() const -{ - return m_max; -} +double PlotAxis::max() const { return m_max; } -double PlotAxis::min() const -{ - return m_min; -} +double PlotAxis::min() const { return m_min; } -const QwtAxisId &PlotAxis::axisId() const -{ - return m_axisId; -} +const QwtAxisId &PlotAxis::axisId() const { return m_axisId; } + +#include "moc_plotaxis.cpp" diff --git a/gui/src/plotaxishandle.cpp b/gui/src/plotaxishandle.cpp index 15ef003439..8741c17453 100644 --- a/gui/src/plotaxishandle.cpp +++ b/gui/src/plotaxishandle.cpp @@ -1,15 +1,17 @@ #include "plotaxishandle.h" + #include "plotaxis.h" #include "symbol.h" #include "symbol_controller.h" + #include using namespace scopy; -PlotAxisHandle::PlotAxisHandle(QPen pen, PlotAxis* ax, PlotWidget *p, int position, QObject *parent) - : QObject(parent), - m_plotWidget(p), - m_axis(ax), - m_pen(pen) +PlotAxisHandle::PlotAxisHandle(QPen pen, PlotAxis *ax, PlotWidget *p, int position, QObject *parent) + : QObject(parent) + , m_plotWidget(p) + , m_axis(ax) + , m_pen(pen) { VertHandlesArea *area; bool left = false; @@ -20,7 +22,7 @@ PlotAxisHandle::PlotAxisHandle(QPen pen, PlotAxis* ax, PlotWidget *p, int positi area = p->rightHandlesArea(); } - //QColor chnColor = color; + // QColor chnColor = color; m_symbolCtrl = p->symbolCtrl(); /* Channel offset widget */ m_chOffsetBar = new HorizBar(p->plot()); @@ -32,49 +34,33 @@ PlotAxisHandle::PlotAxisHandle(QPen pen, PlotAxis* ax, PlotWidget *p, int positi m_chOffsetBar->setPen(pen); m_handle = new RoundedHandleV( - (left) ? QPixmap(":/gui/icons/handle_right_arrow.svg") - : QPixmap(":/gui/icons/handle_left_arrow.svg"), - QPixmap(":/gui/icons/handle_up_arrow.svg"), - QPixmap(":/gui/icons/handle_down_arrow.svg"), - area, left); + (left) ? QPixmap(":/gui/icons/handle_right_arrow.svg") : QPixmap(":/gui/icons/handle_left_arrow.svg"), + QPixmap(":/gui/icons/handle_up_arrow.svg"), QPixmap(":/gui/icons/handle_down_arrow.svg"), area, left); m_handle->setRoundRectColor(m_pen.color()); m_handle->setPen(pen); m_handle->setVisible(true); /* When bar position changes due to plot resizes update the handle */ - connect(area, &HandlesArea::sizeChanged, m_handle, [=](){ - m_handle->updatePosition(); - }); + connect(area, &HandlesArea::sizeChanged, m_handle, [=]() { m_handle->updatePosition(); }); connect(m_chOffsetBar, &HorizBar::pixelPositionChanged, this, - [=](int pos) { - m_handle->setPositionSilenty(pos); - }); - - connect(m_handle, &RoundedHandleV::positionChanged, this, - [=](int pos) { - QwtScaleMap yMap = p->plot()->canvasMap(ax->axisId()); - double offset = yMap.invTransform(pos); - double min = ax->min() - offset; - double max = ax->max() - offset; - ax->setInterval(min, max); - p->replot(); - } - ); + [=](int pos) { m_handle->setPositionSilenty(pos); }); + connect(m_handle, &RoundedHandleV::positionChanged, this, [=](int pos) { + QwtScaleMap yMap = p->plot()->canvasMap(ax->axisId()); + double offset = yMap.invTransform(pos); + double min = ax->min() - offset; + double max = ax->max() - offset; + ax->setInterval(min, max); + p->replot(); + }); } -PlotAxisHandle::~PlotAxisHandle() -{ -} +PlotAxisHandle::~PlotAxisHandle() {} -RoundedHandleV *PlotAxisHandle::handle() const -{ - return m_handle; -} +RoundedHandleV *PlotAxisHandle::handle() const { return m_handle; } -PlotAxis *PlotAxisHandle::axis() const -{ - return m_axis; -} +PlotAxis *PlotAxisHandle::axis() const { return m_axis; } + +#include "moc_plotaxishandle.cpp" diff --git a/gui/src/plotchannel.cpp b/gui/src/plotchannel.cpp index b1a5d5983c..5a3877e081 100644 --- a/gui/src/plotchannel.cpp +++ b/gui/src/plotchannel.cpp @@ -1,43 +1,38 @@ #include "plotchannel.h" -#include -#include "plotwidget.h" + #include "plotaxis.h" +#include "plotwidget.h" + +#include using namespace scopy; PlotChannel::PlotChannel(QString name, QPen pen, PlotWidget *plot, PlotAxis *xAxis, PlotAxis *yAxis, QObject *parent) - : QObject(parent), - m_plotWidget(plot), - m_plot(m_plotWidget->plot()), - m_xAxis(xAxis), - m_yAxis(yAxis), - m_handle(nullptr), - m_pen(pen) + : QObject(parent) + , m_plotWidget(plot) + , m_plot(m_plotWidget->plot()) + , m_xAxis(xAxis) + , m_yAxis(yAxis) + , m_handle(nullptr) + , m_pen(pen) { m_curve = new QwtPlotCurve(name); m_curve->setAxes(m_xAxis->axisId(), m_yAxis->axisId()); - m_curve->setStyle( QwtPlotCurve::Lines ); + m_curve->setStyle(QwtPlotCurve::Lines); m_curve->setPen(m_pen); - m_curve->setRenderHint( QwtPlotItem::RenderAntialiased, true ); - m_curve->setPaintAttribute( QwtPlotCurve::ClipPolygons, false ); + m_curve->setRenderHint(QwtPlotItem::RenderAntialiased, true); + m_curve->setPaintAttribute(QwtPlotCurve::ClipPolygons, false); m_curve->setItemAttribute(QwtPlotItem::Legend, true); - symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(m_pen.color()), - QPen(m_pen.color()), QSize(7,7)); + symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(m_pen.color()), QPen(m_pen.color()), QSize(7, 7)); m_curve->setSymbol(symbol); // curvefitter (?) - } -PlotChannel::~PlotChannel() -{ -} +PlotChannel::~PlotChannel() {} -QwtPlotCurve *PlotChannel::curve() const -{ - return m_curve; -} +QwtPlotCurve *PlotChannel::curve() const { return m_curve; } void PlotChannel::setEnabled(bool b) { @@ -47,15 +42,9 @@ void PlotChannel::setEnabled(bool b) m_curve->detach(); } -void PlotChannel::enable() -{ - setEnabled(true); -} +void PlotChannel::enable() { setEnabled(true); } -void PlotChannel::disable() -{ - setEnabled(false); -} +void PlotChannel::disable() { setEnabled(false); } void PlotChannel::setThickness(int thickness) { @@ -96,19 +85,17 @@ void PlotChannel::setStyle(int style) m_plot->replot(); } -QList PlotChannel::markers() -{ - return m_markers; -} +QList PlotChannel::markers() { return m_markers; } -QwtPlotMarker *PlotChannel::buildMarker(QString str, QwtSymbol::Style shape, double x, double y) { +QwtPlotMarker *PlotChannel::buildMarker(QString str, QwtSymbol::Style shape, double x, double y) +{ QwtPlotMarker *m = new QwtPlotMarker(); QBrush brush; brush.setColor(m_pen.color()); brush.setStyle(Qt::SolidPattern); - m->setSymbol(new QwtSymbol(shape, brush, m_pen, QSize(12,12))); + m->setSymbol(new QwtSymbol(shape, brush, m_pen, QSize(12, 12))); m->setLinePen(m_pen); QwtText txt(str); txt.setColor(m_pen.color()); @@ -122,11 +109,10 @@ QwtPlotMarker *PlotChannel::buildMarker(QString str, QwtSymbol::Style shape, dou return m; } -void PlotChannel::addMarker(QwtPlotMarker *m){ - m_markers.append(m); -} +void PlotChannel::addMarker(QwtPlotMarker *m) { m_markers.append(m); } -void PlotChannel::clearMarkers() { +void PlotChannel::clearMarkers() +{ for(auto *m : m_markers) { m->detach(); delete m; @@ -134,22 +120,16 @@ void PlotChannel::clearMarkers() { m_markers.clear(); } -void PlotChannel::removeMarker(QwtPlotMarker *m) { +void PlotChannel::removeMarker(QwtPlotMarker *m) +{ m->detach(); m_markers.removeAll(m); delete(m); - } -PlotAxisHandle *PlotChannel::handle() const -{ - return m_handle; -} +PlotAxisHandle *PlotChannel::handle() const { return m_handle; } -void PlotChannel::setHandle(PlotAxisHandle *newHandle) -{ - m_handle = newHandle; -} +void PlotChannel::setHandle(PlotAxisHandle *newHandle) { m_handle = newHandle; } void PlotChannel::raise() { @@ -160,24 +140,12 @@ void PlotChannel::raise() } } -void PlotChannel::attach() -{ - m_curve->attach(m_plot); -} - -void PlotChannel::detach() -{ - m_curve->detach(); -} +void PlotChannel::attach() { m_curve->attach(m_plot); } -PlotAxis *PlotChannel::yAxis() const -{ - return m_yAxis; -} +void PlotChannel::detach() { m_curve->detach(); } -PlotAxis *PlotChannel::xAxis() const -{ - return m_xAxis; -} +PlotAxis *PlotChannel::yAxis() const { return m_yAxis; } +PlotAxis *PlotChannel::xAxis() const { return m_xAxis; } +#include "moc_plotchannel.cpp" diff --git a/gui/src/plotcursors.cpp b/gui/src/plotcursors.cpp index 2d300fbe0a..71ed53042c 100644 --- a/gui/src/plotcursors.cpp +++ b/gui/src/plotcursors.cpp @@ -2,17 +2,15 @@ using namespace scopy; -PlotCursors::PlotCursors(PlotWidget* plot): - m_plot(plot), m_tracking(false) +PlotCursors::PlotCursors(PlotWidget *plot) + : m_plot(plot) + , m_tracking(false) { initUI(); connectSignals(); } -PlotCursors::~PlotCursors() -{ - -} +PlotCursors::~PlotCursors() {} void PlotCursors::initUI() { @@ -23,32 +21,28 @@ void PlotCursors::initUI() plotMarker1 = new QwtPlotMarker(); plotMarker2 = new QwtPlotMarker(); - plotMarker1->setSymbol(new QwtSymbol( - QwtSymbol::Ellipse, QColor(237, 28, 36), - QPen(QColor(255, 255 ,255, 140), 2, Qt::SolidLine), - QSize(5, 5))); - plotMarker2->setSymbol(new QwtSymbol( - QwtSymbol::Ellipse, QColor(237, 28, 36), - QPen(QColor(255, 255 ,255, 140), 2, Qt::SolidLine), - QSize(5, 5))); + plotMarker1->setSymbol(new QwtSymbol(QwtSymbol::Ellipse, QColor(237, 28, 36), + QPen(QColor(255, 255, 255, 140), 2, Qt::SolidLine), QSize(5, 5))); + plotMarker2->setSymbol(new QwtSymbol(QwtSymbol::Ellipse, QColor(237, 28, 36), + QPen(QColor(255, 255, 255, 140), 2, Qt::SolidLine), QSize(5, 5))); } void PlotCursors::connectSignals() { - connect(this, &PlotCursors::update, this, [=](){ + connect(this, &PlotCursors::update, this, [=]() { Q_EMIT m_vCursors.first->update(); Q_EMIT m_vCursors.second->update(); Q_EMIT m_hCursors.first->update(); Q_EMIT m_hCursors.second->update(); }); - connect(m_hCursors.first, &Cursor::positionChanged, this, [=](){ - if (m_tracking) { + connect(m_hCursors.first, &Cursor::positionChanged, this, [=]() { + if(m_tracking) { displayIntersection(); } }); - connect(m_hCursors.second, &Cursor::positionChanged, this, [=](){ - if (m_tracking) { + connect(m_hCursors.second, &Cursor::positionChanged, this, [=]() { + if(m_tracking) { displayIntersection(); } }); @@ -56,13 +50,13 @@ void PlotCursors::connectSignals() void PlotCursors::updateTracking() { - if (m_tracking && m_hCursors.first->isVisible()) { + if(m_tracking && m_hCursors.first->isVisible()) { plotMarker1->attach(m_plot->plot()); } else { plotMarker1->detach(); } - if (m_tracking && m_hCursors.second->isVisible()) { + if(m_tracking && m_hCursors.second->isVisible()) { plotMarker2->attach(m_plot->plot()); } else { plotMarker2->detach(); @@ -79,39 +73,30 @@ void PlotCursors::setCanLeavePlot(bool leave) getH2Cursor()->setCanLeavePlot(leave); } -VCursor *PlotCursors::getV1Cursor() -{ - return m_vCursors.first; -} +VCursor *PlotCursors::getV1Cursor() { return m_vCursors.first; } -VCursor *PlotCursors::getV2Cursor() -{ - return m_vCursors.second; -} +VCursor *PlotCursors::getV2Cursor() { return m_vCursors.second; } -HCursor *PlotCursors::getH1Cursor() -{ - return m_hCursors.first; -} +HCursor *PlotCursors::getH1Cursor() { return m_hCursors.first; } -HCursor *PlotCursors::getH2Cursor() -{ - return m_hCursors.second; -} +HCursor *PlotCursors::getH2Cursor() { return m_hCursors.second; } -void PlotCursors::setVisible(bool visible) { +void PlotCursors::setVisible(bool visible) +{ horizSetVisible(visible); vertSetVisible(visible); } -void PlotCursors::horizSetVisible(bool visible) { +void PlotCursors::horizSetVisible(bool visible) +{ m_hCursors.first->setVisible(visible); m_hCursors.second->setVisible(visible); updateTracking(); Q_EMIT update(); } -void PlotCursors::vertSetVisible(bool visible) { +void PlotCursors::vertSetVisible(bool visible) +{ m_vCursors.first->setVisible(visible && !m_tracking); m_vCursors.second->setVisible(visible && !m_tracking); updateTracking(); @@ -153,7 +138,7 @@ double PlotCursors::getHorizIntersectionAt(double pos) QwtSeriesData *curve_data = tmp->curve()->data(); int n = curve_data->size(); - if (n == 0) { + if(n == 0) { return -1; } else { double leftTime, rightTime, leftCustom, rightCustom; @@ -162,32 +147,32 @@ double PlotCursors::getHorizIntersectionAt(double pos) int left = 0; int right = n - 1; - if (curve_data->sample(right).x() < pos || curve_data->sample(left).x() > pos) { + if(curve_data->sample(right).x() < pos || curve_data->sample(left).x() > pos) { return -1; } - while (left <= right) { + while(left <= right) { int mid = (left + right) / 2; double xData = curve_data->sample(mid).x(); - if (xData == pos) { - if (mid > 0) { + if(xData == pos) { + if(mid > 0) { leftIndex = mid - 1; rightIndex = mid; } break; - } else if (xData < pos) { + } else if(xData < pos) { left = mid + 1; } else { right = mid - 1; } } - if ((leftIndex == -1 || rightIndex == -1) && left > 0) { + if((leftIndex == -1 || rightIndex == -1) && left > 0) { leftIndex = left - 1; rightIndex = left; } - if (leftIndex == -1 || rightIndex == -1) { + if(leftIndex == -1 || rightIndex == -1) { return -1; } @@ -197,10 +182,10 @@ double PlotCursors::getHorizIntersectionAt(double pos) leftCustom = curve_data->sample(leftIndex).y(); rightCustom = curve_data->sample(rightIndex).y(); - double value = (rightCustom - leftCustom) / (rightTime - leftTime) * - (pos - leftTime) + leftCustom; + double value = (rightCustom - leftCustom) / (rightTime - leftTime) * (pos - leftTime) + leftCustom; return value; } } +#include "moc_plotcursors.cpp" diff --git a/gui/src/plotpickerwrapper.cpp b/gui/src/plotpickerwrapper.cpp index 8816793152..6352a93418 100644 --- a/gui/src/plotpickerwrapper.cpp +++ b/gui/src/plotpickerwrapper.cpp @@ -20,13 +20,8 @@ #include "plotpickerwrapper.h" -PlotPickerWrapper::PlotPickerWrapper(QwtAxisId xAxis, QwtAxisId yAxis, - QWidget *canvas): - QwtPlotPicker(xAxis,yAxis,canvas) -{ -} +PlotPickerWrapper::PlotPickerWrapper(QwtAxisId xAxis, QwtAxisId yAxis, QWidget *canvas) + : QwtPlotPicker(xAxis, yAxis, canvas) +{} -QPointF PlotPickerWrapper::pointCoordinates(const QPoint& pos) const -{ - return invTransform(pos); -} +QPointF PlotPickerWrapper::pointCoordinates(const QPoint &pos) const { return invTransform(pos); } diff --git a/gui/src/plotwidget.cpp b/gui/src/plotwidget.cpp index f9d2ec3fc5..5ecc24bbc4 100644 --- a/gui/src/plotwidget.cpp +++ b/gui/src/plotwidget.cpp @@ -1,25 +1,28 @@ #include "plotwidget.h" -#include +#include "DisplayPlot.h" +#include "plotaxis.h" + +#include +#include +#include +#include #include #include #include +#include #include + +#include #include -#include #include -#include -#include "plotaxis.h" #include -#include -#include -#include -#include "DisplayPlot.h" using namespace scopy; - -PlotWidget::PlotWidget(QWidget *parent) : QWidget(parent) { +PlotWidget::PlotWidget(QWidget *parent) + : QWidget(parent) +{ m_selectedChannel = nullptr; setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); @@ -38,12 +41,12 @@ PlotWidget::PlotWidget(QWidget *parent) : QWidget(parent) { m_yPosition = Preferences::get("adc_plot_yaxis_label_position").toInt(); // default Axis - new PlotAxis(QwtAxis::XBottom,this,pen,this); - new PlotAxis(QwtAxis::YLeft,this,pen,this); + new PlotAxis(QwtAxis::XBottom, this, pen, this); + new PlotAxis(QwtAxis::YLeft, this, pen, this); hideDefaultAxis(); - m_xAxis = new PlotAxis(m_xPosition,this,pen,this); - m_yAxis = new PlotAxis(m_yPosition,this,pen,this); + m_xAxis = new PlotAxis(m_xPosition, this, pen, this); + m_yAxis = new PlotAxis(m_yPosition, this, pen, this); setupAxisScales(); setAxisScalesVisible(true); @@ -62,17 +65,16 @@ PlotWidget::PlotWidget(QWidget *parent) : QWidget(parent) { // d_origin->attach( m_plot ); graticule = new Graticule(m_plot); - connect(this, SIGNAL(canvasSizeChanged()),graticule,SLOT(onCanvasSizeChanged())); + connect(this, SIGNAL(canvasSizeChanged()), graticule, SLOT(onCanvasSizeChanged())); setDisplayGraticule(false); m_plot->plotLayout()->setAlignCanvasToScales(false); m_plot->plotLayout()->setCanvasMargin(0); m_plot->plotLayout()->setSpacing(0); setupZoomer(); - - } -void PlotWidget::setupHandlesArea() { +void PlotWidget::setupHandlesArea() +{ m_symbolCtrl = new SymbolController(m_plot); /* Adjacent areas */ @@ -101,29 +103,24 @@ void PlotWidget::setupHandlesArea() { m_topHandlesArea->setRightPadding(0); /// Why ? m_topHandlesArea->setVisible(false); - -// m_layout->addWidget(m_bufferPreviewer,0,1); - m_layout->addWidget(m_bottomHandlesArea,3,1); - m_layout->addWidget(m_rightHandlesArea,2,2); - m_layout->addWidget(m_leftHandlesArea,2,0); - m_layout->addWidget(m_topHandlesArea,1,1); - m_layout->addWidget(m_plot,2,1); + // m_layout->addWidget(m_bufferPreviewer,0,1); + m_layout->addWidget(m_bottomHandlesArea, 3, 1); + m_layout->addWidget(m_rightHandlesArea, 2, 2); + m_layout->addWidget(m_leftHandlesArea, 2, 0); + m_layout->addWidget(m_topHandlesArea, 1, 1); + m_layout->addWidget(m_plot, 2, 1); } -void PlotWidget::addPlotInfoSlot(QWidget *w) { - m_layout->addWidget(w,0,1); -} +void PlotWidget::addPlotInfoSlot(QWidget *w) { m_layout->addWidget(w, 0, 1); } -void PlotWidget::setupZoomer() { +void PlotWidget::setupZoomer() +{ // zoomer // OscPlotZoomer - need constructor - m_zoomer = new ExtendingPlotZoomer(xAxis()->axisId(), yAxis()->axisId(), m_plot->canvas(), false); - - m_zoomer->setMousePattern(QwtEventPattern::MouseSelect2, - Qt::RightButton, Qt::ControlModifier); - m_zoomer->setMousePattern(QwtEventPattern::MouseSelect3, - Qt::RightButton); + m_zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); + m_zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); m_zoomer->setTrackerMode(QwtPicker::ActiveOnly); const QColor c("#999999"); m_zoomer->setRubberBandPen(c); @@ -139,12 +136,9 @@ void PlotWidget::setupZoomer() { QwtPlotZoomer *zoomer = m_plotAxis[i][j]->zoomer(); if(zoomer != nullptr) { if(zoomer->zoomRectIndex() < m_zoomer->zoomRectIndex()) { - qInfo()<zoomRectIndex() << m_zoomer->zoomRectIndex() << i << j<< "ZoomIn"; - zoomer->zoom(rect); - } else { - qInfo()<zoomRectIndex() << m_zoomer->zoomRectIndex() << i<zoom(0); - zoomer->setZoomBase(); + qInfo()<zoomRectIndex() << m_zoomer->zoomRectIndex() << i << + j<< "ZoomIn"; zoomer->zoom(rect); } else { qInfo()<zoomRectIndex() << m_zoomer->zoomRectIndex() << + i<zoom(0); zoomer->setZoomBase(); } } } @@ -153,15 +147,12 @@ void PlotWidget::setupZoomer() { });*/ } +PlotWidget::~PlotWidget() {} -PlotWidget::~PlotWidget() { - -} - -void PlotWidget::setupAxisScales() { - for (unsigned int i = 0; i < 4; i++) { - QwtScaleDraw::Alignment scale = - static_cast(i); +void PlotWidget::setupAxisScales() +{ + for(unsigned int i = 0; i < 4; i++) { + QwtScaleDraw::Alignment scale = static_cast(i); auto scaleItem = new EdgelessPlotScaleItem(scale); scaleItem->scaleDraw()->setAlignment(scale); @@ -184,24 +175,24 @@ void PlotWidget::setupOpenGLCanvas() { bool useOpenGLCanvas = Preferences::GetInstance()->get("general_use_opengl").toBool(); if(useOpenGLCanvas) { - QwtPlotOpenGLCanvas* plotCanvas = qobject_cast< QwtPlotOpenGLCanvas* >( m_plot->canvas() ); - if ( plotCanvas == NULL ) - { + QwtPlotOpenGLCanvas *plotCanvas = qobject_cast(m_plot->canvas()); + if(plotCanvas == NULL) { plotCanvas = new QwtPlotOpenGLCanvas(m_plot); - plotCanvas->setPaintAttribute(QwtPlotAbstractGLCanvas::BackingStore ); - m_plot->setCanvas( plotCanvas ); + plotCanvas->setPaintAttribute(QwtPlotAbstractGLCanvas::BackingStore); + m_plot->setCanvas(plotCanvas); } else { ; } } else { - QwtPlotCanvas *plotCanvas = qobject_cast( m_plot->canvas() ); + QwtPlotCanvas *plotCanvas = qobject_cast(m_plot->canvas()); plotCanvas->setPaintAttribute(QwtPlotCanvas::BackingStore, true); } } -void PlotWidget::setAxisScalesVisible(bool visible) { - for(QwtPlotScaleItem* scale : qAsConst(m_scaleItems)){ - if(visible){ +void PlotWidget::setAxisScalesVisible(bool visible) +{ + for(QwtPlotScaleItem *scale : qAsConst(m_scaleItems)) { + if(visible) { scale->attach(m_plot); } else { scale->detach(); @@ -217,30 +208,15 @@ void PlotWidget::addPlotChannel(PlotChannel *ch) } } -void PlotWidget::removePlotChannel(PlotChannel *ch) -{ - m_plotChannels.removeAll(ch); -} - -void PlotWidget::addPlotAxisHandle(PlotAxisHandle *ax) { - - m_plotAxisHandles[ax->axis()->position()].append(ax); -} +void PlotWidget::removePlotChannel(PlotChannel *ch) { m_plotChannels.removeAll(ch); } -void PlotWidget::removePlotAxisHandle(PlotAxisHandle *ax) { - m_plotAxisHandles[ax->axis()->position()].removeAll(ax); -} +void PlotWidget::addPlotAxisHandle(PlotAxisHandle *ax) { m_plotAxisHandles[ax->axis()->position()].append(ax); } +void PlotWidget::removePlotAxisHandle(PlotAxisHandle *ax) { m_plotAxisHandles[ax->axis()->position()].removeAll(ax); } -void PlotWidget::addPlotAxis(PlotAxis *ax) -{ - m_plotAxis[ax->position()].append(ax); -} +void PlotWidget::addPlotAxis(PlotAxis *ax) { m_plotAxis[ax->position()].append(ax); } -bool PlotWidget::getDisplayGraticule() const -{ - return displayGraticule; -} +bool PlotWidget::getDisplayGraticule() const { return displayGraticule; } void PlotWidget::setDisplayGraticule(bool newDisplayGraticule) { @@ -252,32 +228,32 @@ void PlotWidget::setDisplayGraticule(bool newDisplayGraticule) bool PlotWidget::eventFilter(QObject *object, QEvent *event) { - if (object == m_plot->canvas()) { - switch (event->type()) { + if(object == m_plot->canvas()) { + switch(event->type()) { case QEvent::MouseMove: { - Q_EMIT mouseMove(static_cast< QMouseEvent* >( event )); + Q_EMIT mouseMove(static_cast(event)); break; } case QEvent::MouseButtonPress: { - Q_EMIT mouseButtonPress(static_cast< QMouseEvent* >( event )); + Q_EMIT mouseButtonPress(static_cast(event)); break; } case QEvent::MouseButtonRelease: { - Q_EMIT mouseButtonRelease(static_cast< QMouseEvent* >( event )); + Q_EMIT mouseButtonRelease(static_cast(event)); break; } case QEvent::Resize: { -// updateHandleAreaPadding(d_labelsEnabled); + // updateHandleAreaPadding(d_labelsEnabled); - //force cursor handles to emit position changed - //when the plot canvas is being resized -// d_hCursorHandle1->triggerMove(); -// d_hCursorHandle2->triggerMove(); -// d_vCursorHandle1->triggerMove(); -// d_vCursorHandle2->triggerMove(); + // force cursor handles to emit position changed + // when the plot canvas is being resized + // d_hCursorHandle1->triggerMove(); + // d_hCursorHandle2->triggerMove(); + // d_vCursorHandle1->triggerMove(); + // d_vCursorHandle2->triggerMove(); /* update the size of the gates when the plot canvas is resized */ -// updateGateMargins(); + // updateGateMargins(); Q_EMIT canvasSizeChanged(); break; @@ -289,30 +265,18 @@ bool PlotWidget::eventFilter(QObject *object, QEvent *event) return QObject::eventFilter(object, event); } -QList &PlotWidget::plotAxis(int position) { - return m_plotAxis[position]; -} +QList &PlotWidget::plotAxis(int position) { return m_plotAxis[position]; } -PlotAxis *PlotWidget::xAxis() { - return m_xAxis; -} +PlotAxis *PlotWidget::xAxis() { return m_xAxis; } -PlotAxis *PlotWidget::yAxis() { - return m_yAxis; -} +PlotAxis *PlotWidget::yAxis() { return m_yAxis; } +QwtPlot *PlotWidget::plot() const { return m_plot; } -QwtPlot *PlotWidget::plot() const -{ - return m_plot; -} +void PlotWidget::replot() { m_plot->replot(); } -void PlotWidget::replot() +void PlotWidget::hideAxisLabels() { - m_plot->replot(); -} - -void PlotWidget::hideAxisLabels() { m_yAxis->setVisible(false); if(m_selectedChannel != nullptr) { m_selectedChannel->yAxis()->setVisible(false); @@ -321,40 +285,30 @@ void PlotWidget::hideAxisLabels() { void PlotWidget::hideDefaultAxis() { - m_plot->setAxisVisible(QwtAxisId(QwtAxis::XBottom,0), false); - m_plot->setAxisVisible(QwtAxisId(QwtAxis::XTop,0), false); - m_plot->setAxisVisible(QwtAxisId(QwtAxis::YLeft,0), false); - m_plot->setAxisVisible(QwtAxisId(QwtAxis::YRight,0), false); + m_plot->setAxisVisible(QwtAxisId(QwtAxis::XBottom, 0), false); + m_plot->setAxisVisible(QwtAxisId(QwtAxis::XTop, 0), false); + m_plot->setAxisVisible(QwtAxisId(QwtAxis::YLeft, 0), false); + m_plot->setAxisVisible(QwtAxisId(QwtAxis::YRight, 0), false); } -bool PlotWidget::showYAxisLabels() const -{ - return m_showYAxisLabels; -} +bool PlotWidget::showYAxisLabels() const { return m_showYAxisLabels; } -void PlotWidget::setShowYAxisLabels(bool newShowYAxisLabels) -{ - m_showYAxisLabels = newShowYAxisLabels; -} +void PlotWidget::setShowYAxisLabels(bool newShowYAxisLabels) { m_showYAxisLabels = newShowYAxisLabels; } -bool PlotWidget::showXAxisLabels() const -{ - return m_showXAxisLabels; -} +bool PlotWidget::showXAxisLabels() const { return m_showXAxisLabels; } -void PlotWidget::setShowXAxisLabels(bool newShowXAxisLabels) -{ - m_showXAxisLabels = newShowXAxisLabels; -} +void PlotWidget::setShowXAxisLabels(bool newShowXAxisLabels) { m_showXAxisLabels = newShowXAxisLabels; } -void PlotWidget::showAxisLabels() { +void PlotWidget::showAxisLabels() +{ if(m_selectedChannel != nullptr) { m_selectedChannel->xAxis()->setVisible(m_showXAxisLabels); m_selectedChannel->yAxis()->setVisible(m_showYAxisLabels); } } -void PlotWidget::selectChannel(PlotChannel *ch) { +void PlotWidget::selectChannel(PlotChannel *ch) +{ hideAxisLabels(); m_selectedChannel = ch; showAxisLabels(); @@ -364,33 +318,16 @@ void PlotWidget::selectChannel(PlotChannel *ch) { } } -PlotChannel *PlotWidget::selectedChannel() const -{ - return m_selectedChannel; -} +PlotChannel *PlotWidget::selectedChannel() const { return m_selectedChannel; } -VertHandlesArea *PlotWidget::leftHandlesArea() const -{ - return m_leftHandlesArea; -} +VertHandlesArea *PlotWidget::leftHandlesArea() const { return m_leftHandlesArea; } -VertHandlesArea *PlotWidget::rightHandlesArea() const -{ - return m_rightHandlesArea; -} +VertHandlesArea *PlotWidget::rightHandlesArea() const { return m_rightHandlesArea; } -HorizHandlesArea *PlotWidget::topHandlesArea() const -{ - return m_topHandlesArea; -} +HorizHandlesArea *PlotWidget::topHandlesArea() const { return m_topHandlesArea; } -HorizHandlesArea *PlotWidget::bottomHandlesArea() const -{ - return m_bottomHandlesArea; -} +HorizHandlesArea *PlotWidget::bottomHandlesArea() const { return m_bottomHandlesArea; } -SymbolController *PlotWidget::symbolCtrl() const -{ - return m_symbolCtrl; -} +SymbolController *PlotWidget::symbolCtrl() const { return m_symbolCtrl; } +#include "moc_plotwidget.cpp" diff --git a/gui/src/printableplot.cpp b/gui/src/printableplot.cpp index 71bf1dde40..72a1e8a92d 100644 --- a/gui/src/printableplot.cpp +++ b/gui/src/printableplot.cpp @@ -19,16 +19,17 @@ */ #include "printableplot.h" + #include #include #include using namespace scopy; -PrintablePlot::PrintablePlot(QWidget *parent) : - BasicPlot(parent), - d_plotRenderer(new QwtPlotRenderer(this)), - d_useNativeDialog(true) +PrintablePlot::PrintablePlot(QWidget *parent) + : BasicPlot(parent) + , d_plotRenderer(new QwtPlotRenderer(this)) + , d_useNativeDialog(true) { dropBackground(true); } @@ -39,12 +40,9 @@ void PrintablePlot::dropBackground(bool drop) d_plotRenderer.setDiscardFlag(QwtPlotRenderer::DiscardCanvasBackground, drop); } -void PrintablePlot::setUseNativeDialog(bool nativeDialog) -{ - d_useNativeDialog = nativeDialog; -} +void PrintablePlot::setUseNativeDialog(bool nativeDialog) { d_useNativeDialog = nativeDialog; } -void PrintablePlot::printPlot(const QString& toolName) +void PrintablePlot::printPlot(const QString &toolName) { legendDisplay = new QwtLegend(this); legendDisplay->setDefaultItemMode(QwtLegendData::ReadOnly); @@ -61,34 +59,30 @@ void PrintablePlot::printPlot(const QString& toolName) // native or qt based. So we reconstruct the file formats used by it and use our own // call of QFileDialog::getSaveFileName(...) where we take into account the d_useNativeDialog // boolean - const QList imageFormats = - QImageWriter::supportedImageFormats(); + const QList imageFormats = QImageWriter::supportedImageFormats(); QStringList filter; - filter += QString( "PDF " ) + tr( "Documents" ) + " (*.pdf)"; - filter += QString( "SVG " ) + tr( "Documents" ) + " (*.svg)"; - filter += QString( "Postscript " ) + tr( "Documents" ) + " (*.ps)"; - - if ( imageFormats.size() > 0 ) { - for ( int i = 0; i < imageFormats.size(); i++ ) { - filter += (imageFormats[i].toUpper() + " " - + tr("Image") + " (*." + imageFormats[i] + ")"); - } + filter += QString("PDF ") + tr("Documents") + " (*.pdf)"; + filter += QString("SVG ") + tr("Documents") + " (*.svg)"; + filter += QString("Postscript ") + tr("Documents") + " (*.ps)"; + if(imageFormats.size() > 0) { + for(int i = 0; i < imageFormats.size(); i++) { + filter += (imageFormats[i].toUpper() + " " + tr("Image") + " (*." + imageFormats[i] + ")"); + } } - QString selectedFilter = QString( "PDF " ) + tr( "Documents" ) + " (*.pdf)"; + QString selectedFilter = QString("PDF ") + tr("Documents") + " (*.pdf)"; fileName = QFileDialog::getSaveFileName( - nullptr, tr( "Export File Name" ), fileName, - filter.join( ";;" ), &selectedFilter, - (d_useNativeDialog ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); + nullptr, tr("Export File Name"), fileName, filter.join(";;"), &selectedFilter, + (d_useNativeDialog ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); - if (fileName.split(".").size() <= 1) { + if(fileName.split(".").size() <= 1) { // file name w/o extension. Let's append it QString ext = selectedFilter.split(".")[1].split(")")[0]; fileName += "." + ext; } - d_plotRenderer.renderDocument(this, fileName, QSizeF( 300, 200 )); + d_plotRenderer.renderDocument(this, fileName, QSizeF(300, 200)); insertLegend(nullptr); } diff --git a/gui/src/qwt_utils.cpp b/gui/src/qwt_utils.cpp index dabb26a9d8..51574a4b27 100644 --- a/gui/src/qwt_utils.cpp +++ b/gui/src/qwt_utils.cpp @@ -1,22 +1,21 @@ #include "qwt_utils.h" -#include -#include -#include + #include #include +#include +#include +#include + QwtPickerDblClickPointMachine::QwtPickerDblClickPointMachine() #if QWT_VERSION < 0x060000 - : QwtPickerMachine () + : QwtPickerMachine() #else - : QwtPickerMachine (PointSelection) + : QwtPickerMachine(PointSelection) #endif -{ -} +{} -QwtPickerDblClickPointMachine::~QwtPickerDblClickPointMachine() -{ -} +QwtPickerDblClickPointMachine::~QwtPickerDblClickPointMachine() {} #if QWT_VERSION < 0x060000 #define CMDLIST_TYPE QwtPickerMachine::CommandList @@ -24,43 +23,35 @@ QwtPickerDblClickPointMachine::~QwtPickerDblClickPointMachine() #define CMDLIST_TYPE QList #endif CMDLIST_TYPE -QwtPickerDblClickPointMachine::transition(const QwtEventPattern &eventPattern, - const QEvent *e) +QwtPickerDblClickPointMachine::transition(const QwtEventPattern &eventPattern, const QEvent *e) { - CMDLIST_TYPE cmdList; - switch(e->type()) { - case QEvent::MouseButtonDblClick: - if ( eventPattern.mouseMatch(QwtEventPattern::MouseSelect1, - (const QMouseEvent *)e) ) { - cmdList += QwtPickerMachine::Begin; - cmdList += QwtPickerMachine::Append; - cmdList += QwtPickerMachine::End; - } - break; - default: - break; - } - return cmdList; + CMDLIST_TYPE cmdList; + switch(e->type()) { + case QEvent::MouseButtonDblClick: + if(eventPattern.mouseMatch(QwtEventPattern::MouseSelect1, (const QMouseEvent *)e)) { + cmdList += QwtPickerMachine::Begin; + cmdList += QwtPickerMachine::Append; + cmdList += QwtPickerMachine::End; + } + break; + default: + break; + } + return cmdList; } #if QWT_VERSION < 0x060100 -QwtDblClickPlotPicker::QwtDblClickPlotPicker(QwtPlotCanvas* canvas) -#else /* QWT_VERSION < 0x060100 */ -QwtDblClickPlotPicker::QwtDblClickPlotPicker(QWidget* canvas) +QwtDblClickPlotPicker::QwtDblClickPlotPicker(QwtPlotCanvas *canvas) +#else /* QWT_VERSION < 0x060100 */ +QwtDblClickPlotPicker::QwtDblClickPlotPicker(QWidget *canvas) #endif /* QWT_VERSION < 0x060100 */ - : QwtPlotPicker(canvas) + : QwtPlotPicker(canvas) { #if QWT_VERSION < 0x060000 - setSelectionFlags(QwtPicker::PointSelection); + setSelectionFlags(QwtPicker::PointSelection); #endif } -QwtDblClickPlotPicker::~QwtDblClickPlotPicker() -{ -} +QwtDblClickPlotPicker::~QwtDblClickPlotPicker() {} -QwtPickerMachine* -QwtDblClickPlotPicker::stateMachine(int n) const -{ - return new QwtPickerDblClickPointMachine; -} +QwtPickerMachine *QwtDblClickPlotPicker::stateMachine(int n) const { return new QwtPickerDblClickPointMachine; } diff --git a/gui/src/runsinglewidget.cpp b/gui/src/runsinglewidget.cpp index 3c6b5e0e04..252a631f52 100644 --- a/gui/src/runsinglewidget.cpp +++ b/gui/src/runsinglewidget.cpp @@ -19,33 +19,28 @@ */ #include "runsinglewidget.h" -#include "ui_runsinglewidget.h" -#include "utils.h" -#include "dynamicWidget.h" #include "customPushButton.h" +#include "dynamicWidget.h" +#include "utils.h" + +#include "ui_runsinglewidget.h" using namespace scopy; -RunSingleWidget::RunSingleWidget(QWidget *parent) : - QWidget(parent), - d_ui(new Ui::RunSingleWidget), - d_singleButtonEnabled(true), - d_runButtonEnabled(true) +RunSingleWidget::RunSingleWidget(QWidget *parent) + : QWidget(parent) + , d_ui(new Ui::RunSingleWidget) + , d_singleButtonEnabled(true) + , d_runButtonEnabled(true) { d_ui->setupUi(this); - connect(d_ui->runButton, &QPushButton::toggled, - this, &RunSingleWidget::_toggle); - connect(d_ui->singleButton, &QPushButton::toggled, - this, &RunSingleWidget::_toggle); - + connect(d_ui->runButton, &QPushButton::toggled, this, &RunSingleWidget::_toggle); + connect(d_ui->singleButton, &QPushButton::toggled, this, &RunSingleWidget::_toggle); } -RunSingleWidget::~RunSingleWidget() -{ - delete d_ui; -} +RunSingleWidget::~RunSingleWidget() { delete d_ui; } void RunSingleWidget::enableSingleButton(bool enable) { @@ -57,10 +52,7 @@ void RunSingleWidget::enableSingleButton(bool enable) } } -bool RunSingleWidget::singleButtonEnabled() const -{ - return d_singleButtonEnabled; -} +bool RunSingleWidget::singleButtonEnabled() const { return d_singleButtonEnabled; } void RunSingleWidget::enableRunButton(bool enable) { @@ -69,28 +61,19 @@ void RunSingleWidget::enableRunButton(bool enable) d_runButtonEnabled = enable; } -bool RunSingleWidget::runButtonEnabled() const -{ - return d_runButtonEnabled; -} +bool RunSingleWidget::runButtonEnabled() const { return d_runButtonEnabled; } -bool RunSingleWidget::singleButtonChecked() const -{ - return d_ui->singleButton->isChecked(); -} +bool RunSingleWidget::singleButtonChecked() const { return d_ui->singleButton->isChecked(); } -bool RunSingleWidget::runButtonChecked() const -{ - return d_ui->runButton->isChecked(); -} +bool RunSingleWidget::runButtonChecked() const { return d_ui->runButton->isChecked(); } -QPushButton* RunSingleWidget::getRunButton() { return d_ui->runButton; } +QPushButton *RunSingleWidget::getRunButton() { return d_ui->runButton; } -QPushButton* RunSingleWidget::getSingleButton() { return d_ui->singleButton; } +QPushButton *RunSingleWidget::getSingleButton() { return d_ui->singleButton; } void RunSingleWidget::toggle(bool checked) { - if (!checked) { + if(!checked) { QSignalBlocker blockerRunButton(d_ui->runButton); QSignalBlocker blockerSingleButton(d_ui->singleButton); d_ui->runButton->setChecked(false); @@ -100,12 +83,12 @@ void RunSingleWidget::toggle(bool checked) d_ui->runButton->setText(tr("Run")); d_ui->singleButton->setText(tr("Single")); - } else if (!d_ui->singleButton->isChecked()) { + } else if(!d_ui->singleButton->isChecked()) { QSignalBlocker blockerRunButton(d_ui->runButton); - if (runButtonEnabled()) { + if(runButtonEnabled()) { d_ui->runButton->setChecked(true); d_ui->runButton->setText(tr("Stop")); - } else if (singleButtonEnabled()) { + } else if(singleButtonEnabled()) { d_ui->singleButton->setChecked(true); d_ui->singleButton->setText(tr("Stop")); } @@ -116,28 +99,25 @@ void RunSingleWidget::toggle(bool checked) Q_EMIT toggled(checked); } -void RunSingleWidget::single() -{ - d_ui->singleButton->setChecked(true); -} +void RunSingleWidget::single() { d_ui->singleButton->setChecked(true); } void RunSingleWidget::_toggle(bool checked) { QPushButton *btn = dynamic_cast(QObject::sender()); setDynamicProperty(btn, "running", checked); - if (btn == d_ui->singleButton) { + if(btn == d_ui->singleButton) { btn->setText(checked ? tr("Stop") : tr("Single")); - } else if (btn == d_ui->runButton) { + } else if(btn == d_ui->runButton) { btn->setText(checked ? tr("Stop") : tr("Run")); } - if (btn == d_ui->singleButton && d_ui->runButton->isChecked()) { + if(btn == d_ui->singleButton && d_ui->runButton->isChecked()) { QSignalBlocker blocker(d_ui->runButton); d_ui->runButton->setChecked(false); setDynamicProperty(d_ui->runButton, "running", false); d_ui->runButton->setText(tr("Run")); - } else if (btn == d_ui->runButton && d_ui->singleButton->isChecked()) { + } else if(btn == d_ui->runButton && d_ui->singleButton->isChecked()) { QSignalBlocker blocker(d_ui->singleButton); d_ui->singleButton->setChecked(false); setDynamicProperty(d_ui->singleButton, "running", false); diff --git a/gui/src/settings_pair_widget.cpp b/gui/src/settings_pair_widget.cpp index 14c96a368d..7689e00912 100644 --- a/gui/src/settings_pair_widget.cpp +++ b/gui/src/settings_pair_widget.cpp @@ -1,10 +1,10 @@ -#include "ui_settings_pair_widget.h" - #include "settings_pair_widget.hpp" +#include "ui_settings_pair_widget.h" + using namespace scopy::gui; -SettingsPairWidget::SettingsPairWidget(QWidget* parent) +SettingsPairWidget::SettingsPairWidget(QWidget *parent) : QWidget(parent) , m_ui(new Ui::SettingsPairWidget) { @@ -13,6 +13,8 @@ SettingsPairWidget::SettingsPairWidget(QWidget* parent) SettingsPairWidget::~SettingsPairWidget() { delete m_ui; } -CustomPushButton* SettingsPairWidget::getGeneralSettingsBtn() { return m_ui->btnGenSettings; } +CustomPushButton *SettingsPairWidget::getGeneralSettingsBtn() { return m_ui->btnGenSettings; } + +QPushButton *SettingsPairWidget::getSettingsBtn() { return m_ui->btnSettings; } -QPushButton* SettingsPairWidget::getSettingsBtn() { return m_ui->btnSettings; } +#include "moc_settings_pair_widget.cpp" diff --git a/gui/src/sismograph.cpp b/gui/src/sismograph.cpp index cd78d449cf..af3fec4efb 100644 --- a/gui/src/sismograph.cpp +++ b/gui/src/sismograph.cpp @@ -20,22 +20,26 @@ #include "sismograph.hpp" +#include "plot_utils.hpp" + #include #include #include -#include "plot_utils.hpp" + #include #include using namespace scopy; -Sismograph::Sismograph(QWidget *parent) : QwtPlot(parent) - , curve("data"), sampleRate(10) - , m_currentScale(-Q_INFINITY) - , m_currentMaxValue(-Q_INFINITY) - , interval(10) - , autoscale(true) - , plotDirection(LEFT_TO_RIGHT) +Sismograph::Sismograph(QWidget *parent) + : QwtPlot(parent) + , curve("data") + , sampleRate(10) + , m_currentScale(-Q_INFINITY) + , m_currentMaxValue(-Q_INFINITY) + , interval(10) + , autoscale(true) + , plotDirection(LEFT_TO_RIGHT) { setAxisVisible(QwtAxis::XBottom, true); setAxisVisible(QwtAxis::YLeft, true); @@ -55,8 +59,8 @@ Sismograph::Sismograph(QWidget *parent) : QwtPlot(parent) divs.push_back(engine->divideScale(-0.1, +0.1, 5, 5)); scaler = new AutoScaler(this, divs); - connect(scaler, &AutoScaler::updateScale, this, [=](QwtScaleDiv div){ - if (autoscale) { + connect(scaler, &AutoScaler::updateScale, this, [=](QwtScaleDiv div) { + if(autoscale) { updateScale(); } else { updateScale(div); @@ -66,40 +70,38 @@ Sismograph::Sismograph(QWidget *parent) : QwtPlot(parent) plotLayout()->setAlignCanvasToScales(true); scaleLabel = new CustomQwtScaleDraw(); scaleLabel->setUnitOfMeasure(m_unitOfMeasureSymbol); - this->setAxisScaleDraw(QwtAxis::YLeft,scaleLabel); + this->setAxisScaleDraw(QwtAxis::YLeft, scaleLabel); curve.attach(this); curve.setXAxis(QwtAxis::YLeft); } -Sismograph::~Sismograph() -{ - delete scaler; -} +Sismograph::~Sismograph() { delete scaler; } void Sismograph::plot(double sample) { - if (plotDirection) { + if(plotDirection) { xdata.push_front(sample); } else { xdata.push_back(sample); } - if (xdata.size() == numSamples + 2) { // should have been +1, but there are n+1 samples, it includes indexes n and 0 - if (plotDirection) { + if(xdata.size() == + numSamples + 2) { // should have been +1, but there are n+1 samples, it includes indexes n and 0 + if(plotDirection) { xdata.pop_back(); } else { xdata.pop_front(); } } - if (sample > m_currentMaxValue && autoscale) { // check and update the Y scale + if(sample > m_currentMaxValue && autoscale) { // check and update the Y scale updateScale(); } scaler->setValue(sample); // depends on what is the main axis of the curve - if (plotDirection) { + if(plotDirection) { curve.setRawSamples(ydata.data(), xdata.data(), xdata.size()); } else { curve.setRawSamples(ydata.data() + (ydata.size() - xdata.size()), xdata.data(), xdata.size()); @@ -110,28 +112,22 @@ void Sismograph::plot(double sample) double Sismograph::findMaxInFifo() { double max = -Q_INFINITY; - for (int i = 0 ; i < xdata.size(); i++) { - if (abs(xdata.at(i)) > max) { + for(int i = 0; i < xdata.size(); i++) { + if(abs(xdata.at(i)) > max) { max = abs(xdata.at(i)); } } return max; } -bool Sismograph::getAutoscale() const -{ - return autoscale; -} +bool Sismograph::getAutoscale() const { return autoscale; } -void Sismograph::setAutoscale(bool newAutoscale) -{ - autoscale = newAutoscale; -} +void Sismograph::setAutoscale(bool newAutoscale) { autoscale = newAutoscale; } void Sismograph::addScale(double x1, double x2, int maxMajorSteps, int maxMinorSteps, double stepSize) { QwtScaleEngine *scaleEngine = axisScaleEngine(QwtAxis::YLeft); - scaler->addScaleDivs(scaleEngine->divideScale(x1, x2, maxMajorSteps, maxMinorSteps,stepSize)); + scaler->addScaleDivs(scaleEngine->divideScale(x1, x2, maxMajorSteps, maxMinorSteps, stepSize)); } void Sismograph::updateScale() @@ -140,22 +136,22 @@ void Sismograph::updateScale() /// compute scale int digits = 0; double num = sample; - if (num != 0) { - if (int(num) == 0) { - while ((int)num*10 == 0) { + if(num != 0) { + if(int(num) == 0) { + while((int)num * 10 == 0) { num *= 10; digits++; } digits = -1 * (digits - 1); } else { - while ((int)num) { + while((int)num) { num /= 10; digits++; } } } - double scale = pow(10 , digits); + double scale = pow(10, digits); ////update scale MetricPrefixFormatter m_prefixFormatter; @@ -164,27 +160,24 @@ void Sismograph::updateScale() scaleLabel->setUnitOfMeasure(m_unitOfMeasureSymbol); QwtScaleEngine *scaleEngine = axisScaleEngine(QwtAxis::YLeft); - updateScale(scaleEngine->divideScale((-1*scale),scale,5,10)); + updateScale(scaleEngine->divideScale((-1 * scale), scale, 5, 10)); m_currentScale = scale; } -int Sismograph::getNumSamples() const -{ - return numSamples; -} +int Sismograph::getNumSamples() const { return numSamples; } void Sismograph::setNumSamples(int num) { - numSamples = (unsigned int) num; + numSamples = (unsigned int)num; reset(); ydata.resize(numSamples + 1); xdata.reserve(numSamples + 1); - setAxisScale(QwtAxis::XBottom, 0.0, (double) numSamples / sampleRate); + setAxisScale(QwtAxis::XBottom, 0.0, (double)numSamples / sampleRate); replot(); - scaler->setTimeout((double) numSamples * 1000.0 / sampleRate); + scaler->setTimeout((double)numSamples * 1000.0 / sampleRate); - for (unsigned int i = 0; i <= numSamples; i++) + for(unsigned int i = 0; i <= numSamples; i++) ydata[i] = (double)(numSamples - i) / sampleRate; } @@ -194,7 +187,7 @@ void Sismograph::updateYScale(double max, double min) ydata.resize(numSamples + 1); xdata.reserve(numSamples + 1); setSampleRate(sampleRate); - setAxisScale(QwtAxis::XBottom, min,max); + setAxisScale(QwtAxis::XBottom, min, max); replot(); } @@ -204,10 +197,7 @@ void Sismograph::setHistoryDuration(double time) setNumSamples(interval * sampleRate); } -double Sismograph::getSampleRate() const -{ - return sampleRate; -} +double Sismograph::getSampleRate() const { return sampleRate; } void Sismograph::setSampleRate(double rate) { @@ -217,14 +207,14 @@ void Sismograph::setSampleRate(double rate) void Sismograph::reset() { - xdata.clear(); // clear curve data + xdata.clear(); // clear curve data curve.setRawSamples(ydata.data(), xdata.data(), xdata.size()); // set the cleared data - this->replot(); // update the plot with the empty data + this->replot(); // update the plot with the empty data scaler->startTimer(); } -void Sismograph::setColor(const QColor& color) +void Sismograph::setColor(const QColor &color) { QPen pen(curve.pen()); pen.setColor(color); @@ -235,14 +225,14 @@ void Sismograph::setColor(const QColor& color) void Sismograph::updateScale(const QwtScaleDiv div) { setAxisScale(QwtAxis::YLeft, div.lowerBound(), div.upperBound()); - setAxisScaleDraw(QwtAxis::YLeft,scaleLabel); + setAxisScaleDraw(QwtAxis::YLeft, scaleLabel); } void Sismograph::setLineWidth(qreal width) { - QPen pen(curve.pen()); - pen.setWidthF(width); - curve.setPen(QPen(pen)); + QPen pen(curve.pen()); + pen.setWidthF(width); + curve.setPen(QPen(pen)); } void Sismograph::setLineStyle(Qt::PenStyle lineStyle) @@ -253,23 +243,16 @@ void Sismograph::setLineStyle(Qt::PenStyle lineStyle) replot(); } -void Sismograph::setUnitOfMeasure(QString unitOfMeasureName,QString unitOfMeasureSymbol) +void Sismograph::setUnitOfMeasure(QString unitOfMeasureName, QString unitOfMeasureSymbol) { m_unitOfMeasureName = unitOfMeasureName; m_unitOfMeasureSymbol = unitOfMeasureSymbol; } -void Sismograph::setPlotAxisXTitle(const QString& title) -{ - setAxisTitle(QwtAxis::YLeft, title); -} +void Sismograph::setPlotAxisXTitle(const QString &title) { setAxisTitle(QwtAxis::YLeft, title); } -Sismograph::PlotDirection Sismograph::getPlotDirection() const { - return plotDirection; -} +Sismograph::PlotDirection Sismograph::getPlotDirection() const { return plotDirection; } -void Sismograph::setPlotDirection(Sismograph::PlotDirection direction) { - this->plotDirection = direction; -} +void Sismograph::setPlotDirection(Sismograph::PlotDirection direction) { this->plotDirection = direction; } #include "moc_sismograph.cpp" diff --git a/gui/src/smallOnOffSwitch.cpp b/gui/src/smallOnOffSwitch.cpp index 52995cb7ed..6bee53077c 100644 --- a/gui/src/smallOnOffSwitch.cpp +++ b/gui/src/smallOnOffSwitch.cpp @@ -19,19 +19,27 @@ */ #include "smallOnOffSwitch.h" + #include "dynamicWidget.h" #include +#include #include #include -#include using namespace scopy; -SmallOnOffSwitch::SmallOnOffSwitch(QWidget *parent) : QPushButton(parent), - color_start("grey"), color_end("blue"), on(this), off(this), - handle(this), anim(&handle, "geometry"), color_anim(this, "color"), - show_icon(false),bothValid(false) +SmallOnOffSwitch::SmallOnOffSwitch(QWidget *parent) + : QPushButton(parent) + , color_start("grey") + , color_end("blue") + , on(this) + , off(this) + , handle(this) + , anim(&handle, "geometry") + , color_anim(this, "color") + , show_icon(false) + , bothValid(false) { handle.setObjectName("handle"); on.setObjectName("on"); @@ -51,9 +59,7 @@ SmallOnOffSwitch::SmallOnOffSwitch(QWidget *parent) : QPushButton(parent), connect(this, SIGNAL(toggled(bool)), SLOT(toggleAnim(bool))); } -SmallOnOffSwitch::~SmallOnOffSwitch() -{ -} +SmallOnOffSwitch::~SmallOnOffSwitch() {} void SmallOnOffSwitch::setDuration(int ms) { @@ -62,26 +68,24 @@ void SmallOnOffSwitch::setDuration(int ms) color_anim.setDuration(ms); } -void SmallOnOffSwitch::setHandleColor(const QColor& color) +void SmallOnOffSwitch::setHandleColor(const QColor &color) { - QString ss(stylesheet + QString("QWidget#handle { background-color: %1; }") - .arg(color.name())); + QString ss(stylesheet + QString("QWidget#handle { background-color: %1; }").arg(color.name())); this->setStyleSheet(ss); } void SmallOnOffSwitch::toggleAnim(bool enabled) { - if (!isVisible()) + if(!isVisible()) return; QRect off_rect(0, handle.y(), handle.width(), handle.height()); - QRect on_rect(width() - handle.width(), handle.y(), - handle.width(), handle.height()); + QRect on_rect(width() - handle.width(), handle.y(), handle.width(), handle.height()); anim.stop(); color_anim.stop(); - if (!enabled) { + if(!enabled) { anim.setStartValue(off_rect); anim.setEndValue(on_rect); color_anim.setStartValue(color_start); @@ -104,78 +108,70 @@ void SmallOnOffSwitch::toggleAnim(bool enabled) color_anim.start(); } -bool SmallOnOffSwitch::event(QEvent* e) +bool SmallOnOffSwitch::event(QEvent *e) { - if (e->type() == QEvent::DynamicPropertyChange) - { - QDynamicPropertyChangeEvent *const propEvent = static_cast(e); + if(e->type() == QEvent::DynamicPropertyChange) { + QDynamicPropertyChangeEvent *const propEvent = static_cast(e); QString propName = propEvent->propertyName(); - if(propName=="leftText" && property("leftText").isValid()) + if(propName == "leftText" && property("leftText").isValid()) on.setText(property("leftText").toString()); - if(propName=="rightText" && property("rightText").isValid()) + if(propName == "rightText" && property("rightText").isValid()) off.setText(property("rightText").toString()); - if(propName=="bothValid" && property("bothValid").isValid()) + if(propName == "bothValid" && property("bothValid").isValid()) bothValid = property("bothValid").toBool(); - if(propName=="duration" && property("duration").isValid()) + if(propName == "duration" && property("duration").isValid()) setDuration(property("duration").toInt()); - - } return QPushButton::event(e); } void SmallOnOffSwitch::paintEvent(QPaintEvent *e) { - QPushButton::paintEvent(e); - show_icon = getDynamicProperty(this, "use_icon"); - - if (!show_icon) { - return; - } - - QIcon locked = QIcon::fromTheme("locked"); - QIcon unlocked = QIcon::fromTheme("unlocked"); - QPixmap pixmap; - - QStylePainter p(this); - int w, h; - int left = 4, top = 4; - - if (isChecked()) { - w = 8; h = 12; - pixmap = locked.pixmap(w, h); - p.drawPixmap(left + handle.x() + handle.width(), - handle.y() + top, w, h, pixmap); - } else { - w = 10; h = 12; - pixmap = unlocked.pixmap(w, h); - p.drawPixmap(left, handle.y() + top, w, h, pixmap); - } + QPushButton::paintEvent(e); + show_icon = getDynamicProperty(this, "use_icon"); + + if(!show_icon) { + return; + } + + QIcon locked = QIcon::fromTheme("locked"); + QIcon unlocked = QIcon::fromTheme("unlocked"); + QPixmap pixmap; + + QStylePainter p(this); + int w, h; + int left = 4, top = 4; + + if(isChecked()) { + w = 8; + h = 12; + pixmap = locked.pixmap(w, h); + p.drawPixmap(left + handle.x() + handle.width(), handle.y() + top, w, h, pixmap); + } else { + w = 10; + h = 12; + pixmap = unlocked.pixmap(w, h); + p.drawPixmap(left, handle.y() + top, w, h, pixmap); + } } void SmallOnOffSwitch::showEvent(QShowEvent *event) { - if (!isChecked()) { - handle.setGeometry(QRect(width() - handle.width(), handle.y(), - handle.width(), handle.height())); - if(bothValid) - { + if(!isChecked()) { + handle.setGeometry(QRect(width() - handle.width(), handle.y(), handle.width(), handle.height())); + if(bothValid) { setHandleColor(color_start); - } - else - { + } else { setHandleColor(color_end); } } else { setHandleColor(color_start); handle.setGeometry(0, handle.y(), handle.width(), handle.height()); } - } void SmallOnOffSwitch::updateOnOffLabels() { - if(!bothValid) - { + if(!bothValid) { on.setEnabled(isChecked()); off.setEnabled(!isChecked()); } diff --git a/gui/src/smoothcurvefitter.cpp b/gui/src/smoothcurvefitter.cpp index 1cde9765eb..5610754b52 100644 --- a/gui/src/smoothcurvefitter.cpp +++ b/gui/src/smoothcurvefitter.cpp @@ -20,26 +20,20 @@ #include "smoothcurvefitter.h" -#include #include +#include #include #include using namespace scopy; -SmoothCurveFitter::SmoothCurveFitter(): - QwtCurveFitter(QwtCurveFitter::Path), - d_spline(new QwtSplineCubic()) +SmoothCurveFitter::SmoothCurveFitter() + : QwtCurveFitter(QwtCurveFitter::Path) + , d_spline(new QwtSplineCubic()) { d_spline->setParametrization(QwtSplineParametrization::ParameterUniform); } -QPolygonF SmoothCurveFitter::fitCurve(const QPolygonF &points) const -{ - return d_spline->polygon(points, 0.5); -} +QPolygonF SmoothCurveFitter::fitCurve(const QPolygonF &points) const { return d_spline->polygon(points, 0.5); } -QPainterPath SmoothCurveFitter::fitCurvePath(const QPolygonF &points) const -{ - return d_spline->painterPath(points); -} +QPainterPath SmoothCurveFitter::fitCurvePath(const QPolygonF &points) const { return d_spline->painterPath(points); } diff --git a/gui/src/spectrumUpdateEvents.cc b/gui/src/spectrumUpdateEvents.cc index 442b2cd882..b5a8127058 100644 --- a/gui/src/spectrumUpdateEvents.cc +++ b/gui/src/spectrumUpdateEvents.cc @@ -23,537 +23,348 @@ #include "spectrumUpdateEvents.h" -SpectrumUpdateEvent::SpectrumUpdateEvent(const float* fftPoints, - const uint64_t numFFTDataPoints, - const double* realTimeDomainPoints, - const double* imagTimeDomainPoints, +SpectrumUpdateEvent::SpectrumUpdateEvent(const float *fftPoints, const uint64_t numFFTDataPoints, + const double *realTimeDomainPoints, const double *imagTimeDomainPoints, const uint64_t numTimeDomainDataPoints, - const gr::high_res_timer_type dataTimestamp, - const bool repeatDataFlag, + const gr::high_res_timer_type dataTimestamp, const bool repeatDataFlag, const bool lastOfMultipleUpdateFlag, - const gr::high_res_timer_type generatedTimestamp, - const int droppedFFTFrames) - : QEvent(QEvent::Type(SpectrumUpdateEventType)) + const gr::high_res_timer_type generatedTimestamp, const int droppedFFTFrames) + : QEvent(QEvent::Type(SpectrumUpdateEventType)) { - if(numFFTDataPoints < 1) { - _numFFTDataPoints = 1; - } - else { - _numFFTDataPoints = numFFTDataPoints; - } - - if(numTimeDomainDataPoints < 1) { - _numTimeDomainDataPoints = 1; - } - else { - _numTimeDomainDataPoints = numTimeDomainDataPoints; - } - - _fftPoints = new float[_numFFTDataPoints]; - _fftPoints[0] = 0; - memcpy(_fftPoints, fftPoints, numFFTDataPoints*sizeof(float)); - - _realDataTimeDomainPoints = new double[_numTimeDomainDataPoints]; - memset(_realDataTimeDomainPoints, 0x0, _numTimeDomainDataPoints*sizeof(double)); - if(numTimeDomainDataPoints > 0) { - memcpy(_realDataTimeDomainPoints, realTimeDomainPoints, - numTimeDomainDataPoints*sizeof(double)); - } - - _imagDataTimeDomainPoints = new double[_numTimeDomainDataPoints]; - memset(_imagDataTimeDomainPoints, 0x0, _numTimeDomainDataPoints*sizeof(double)); - if(numTimeDomainDataPoints > 0) { - memcpy(_imagDataTimeDomainPoints, imagTimeDomainPoints, - numTimeDomainDataPoints*sizeof(double)); - } - _dataTimestamp = dataTimestamp; - _repeatDataFlag = repeatDataFlag; - _lastOfMultipleUpdateFlag = lastOfMultipleUpdateFlag; - _eventGeneratedTimestamp = generatedTimestamp; - _droppedFFTFrames = droppedFFTFrames; + if(numFFTDataPoints < 1) { + _numFFTDataPoints = 1; + } else { + _numFFTDataPoints = numFFTDataPoints; + } + + if(numTimeDomainDataPoints < 1) { + _numTimeDomainDataPoints = 1; + } else { + _numTimeDomainDataPoints = numTimeDomainDataPoints; + } + + _fftPoints = new float[_numFFTDataPoints]; + _fftPoints[0] = 0; + memcpy(_fftPoints, fftPoints, numFFTDataPoints * sizeof(float)); + + _realDataTimeDomainPoints = new double[_numTimeDomainDataPoints]; + memset(_realDataTimeDomainPoints, 0x0, _numTimeDomainDataPoints * sizeof(double)); + if(numTimeDomainDataPoints > 0) { + memcpy(_realDataTimeDomainPoints, realTimeDomainPoints, numTimeDomainDataPoints * sizeof(double)); + } + + _imagDataTimeDomainPoints = new double[_numTimeDomainDataPoints]; + memset(_imagDataTimeDomainPoints, 0x0, _numTimeDomainDataPoints * sizeof(double)); + if(numTimeDomainDataPoints > 0) { + memcpy(_imagDataTimeDomainPoints, imagTimeDomainPoints, numTimeDomainDataPoints * sizeof(double)); + } + _dataTimestamp = dataTimestamp; + _repeatDataFlag = repeatDataFlag; + _lastOfMultipleUpdateFlag = lastOfMultipleUpdateFlag; + _eventGeneratedTimestamp = generatedTimestamp; + _droppedFFTFrames = droppedFFTFrames; } SpectrumUpdateEvent::~SpectrumUpdateEvent() { - delete[] _fftPoints; - delete[] _realDataTimeDomainPoints; - delete[] _imagDataTimeDomainPoints; + delete[] _fftPoints; + delete[] _realDataTimeDomainPoints; + delete[] _imagDataTimeDomainPoints; } -const float* -SpectrumUpdateEvent::getFFTPoints() const -{ - return _fftPoints; -} +const float *SpectrumUpdateEvent::getFFTPoints() const { return _fftPoints; } -const double* -SpectrumUpdateEvent::getRealTimeDomainPoints() const -{ - return _realDataTimeDomainPoints; -} +const double *SpectrumUpdateEvent::getRealTimeDomainPoints() const { return _realDataTimeDomainPoints; } -const double* -SpectrumUpdateEvent::getImagTimeDomainPoints() const -{ - return _imagDataTimeDomainPoints; -} +const double *SpectrumUpdateEvent::getImagTimeDomainPoints() const { return _imagDataTimeDomainPoints; } -uint64_t -SpectrumUpdateEvent::getNumFFTDataPoints() const -{ - return _numFFTDataPoints; -} +uint64_t SpectrumUpdateEvent::getNumFFTDataPoints() const { return _numFFTDataPoints; } -uint64_t -SpectrumUpdateEvent::getNumTimeDomainDataPoints() const -{ - return _numTimeDomainDataPoints; -} +uint64_t SpectrumUpdateEvent::getNumTimeDomainDataPoints() const { return _numTimeDomainDataPoints; } -gr::high_res_timer_type -SpectrumUpdateEvent::getDataTimestamp() const -{ - return _dataTimestamp; -} +gr::high_res_timer_type SpectrumUpdateEvent::getDataTimestamp() const { return _dataTimestamp; } -bool -SpectrumUpdateEvent::getRepeatDataFlag() const -{ - return _repeatDataFlag; -} +bool SpectrumUpdateEvent::getRepeatDataFlag() const { return _repeatDataFlag; } -bool -SpectrumUpdateEvent::getLastOfMultipleUpdateFlag() const -{ - return _lastOfMultipleUpdateFlag; -} +bool SpectrumUpdateEvent::getLastOfMultipleUpdateFlag() const { return _lastOfMultipleUpdateFlag; } -gr::high_res_timer_type -SpectrumUpdateEvent::getEventGeneratedTimestamp() const -{ - return _eventGeneratedTimestamp; -} +gr::high_res_timer_type SpectrumUpdateEvent::getEventGeneratedTimestamp() const { return _eventGeneratedTimestamp; } -int -SpectrumUpdateEvent::getDroppedFFTFrames() const -{ - return _droppedFFTFrames; -} +int SpectrumUpdateEvent::getDroppedFFTFrames() const { return _droppedFFTFrames; } -SpectrumWindowCaptionEvent::SpectrumWindowCaptionEvent(const QString& newLbl) - : QEvent(QEvent::Type(SpectrumWindowCaptionEventType)) +SpectrumWindowCaptionEvent::SpectrumWindowCaptionEvent(const QString &newLbl) + : QEvent(QEvent::Type(SpectrumWindowCaptionEventType)) { - _labelString = newLbl; + _labelString = newLbl; } -SpectrumWindowCaptionEvent::~SpectrumWindowCaptionEvent() -{ -} +SpectrumWindowCaptionEvent::~SpectrumWindowCaptionEvent() {} -QString -SpectrumWindowCaptionEvent::getLabel() -{ - return _labelString; -} +QString SpectrumWindowCaptionEvent::getLabel() { return _labelString; } SpectrumWindowResetEvent::SpectrumWindowResetEvent() - : QEvent(QEvent::Type(SpectrumWindowResetEventType)) -{ -} + : QEvent(QEvent::Type(SpectrumWindowResetEventType)) +{} -SpectrumWindowResetEvent::~SpectrumWindowResetEvent() -{ -} +SpectrumWindowResetEvent::~SpectrumWindowResetEvent() {} -SpectrumFrequencyRangeEvent::SpectrumFrequencyRangeEvent(const double centerFreq, - const double startFreq, +SpectrumFrequencyRangeEvent::SpectrumFrequencyRangeEvent(const double centerFreq, const double startFreq, const double stopFreq) - : QEvent(QEvent::Type(SpectrumFrequencyRangeEventType)) -{ - _centerFrequency = centerFreq; - _startFrequency = startFreq; - _stopFrequency = stopFreq; -} - -SpectrumFrequencyRangeEvent::~SpectrumFrequencyRangeEvent() + : QEvent(QEvent::Type(SpectrumFrequencyRangeEventType)) { + _centerFrequency = centerFreq; + _startFrequency = startFreq; + _stopFrequency = stopFreq; } -double -SpectrumFrequencyRangeEvent::GetCenterFrequency() const -{ - return _centerFrequency; -} +SpectrumFrequencyRangeEvent::~SpectrumFrequencyRangeEvent() {} -double -SpectrumFrequencyRangeEvent::GetStartFrequency() const -{ - return _startFrequency; -} +double SpectrumFrequencyRangeEvent::GetCenterFrequency() const { return _centerFrequency; } -double -SpectrumFrequencyRangeEvent::GetStopFrequency() const -{ - return _stopFrequency; -} +double SpectrumFrequencyRangeEvent::GetStartFrequency() const { return _startFrequency; } +double SpectrumFrequencyRangeEvent::GetStopFrequency() const { return _stopFrequency; } /***************************************************************************/ - -TimeUpdateEvent::TimeUpdateEvent(const std::vector &timeDomainPoints, - const uint64_t numTimeDomainDataPoints, - const std::vector< std::vector > &tags) - : QEvent(QEvent::Type(SpectrumUpdateEventType)) +TimeUpdateEvent::TimeUpdateEvent(const std::vector &timeDomainPoints, const uint64_t numTimeDomainDataPoints, + const std::vector> &tags) + : QEvent(QEvent::Type(SpectrumUpdateEventType)) { - if(numTimeDomainDataPoints < 1) { - _numTimeDomainDataPoints = 1; - } - else { - _numTimeDomainDataPoints = numTimeDomainDataPoints; - } - - _nplots = timeDomainPoints.size(); - for(size_t i = 0; i < _nplots; i++) { - _dataTimeDomainPoints.push_back(new double[_numTimeDomainDataPoints]); - if(numTimeDomainDataPoints > 0) { - memcpy(_dataTimeDomainPoints[i], timeDomainPoints[i], - _numTimeDomainDataPoints*sizeof(double)); - } - } - - _tags = tags; -} + if(numTimeDomainDataPoints < 1) { + _numTimeDomainDataPoints = 1; + } else { + _numTimeDomainDataPoints = numTimeDomainDataPoints; + } -TimeUpdateEvent::~TimeUpdateEvent() -{ - for(size_t i = 0; i < _nplots; i++) { - delete[] _dataTimeDomainPoints[i]; - } -} + _nplots = timeDomainPoints.size(); + for(size_t i = 0; i < _nplots; i++) { + _dataTimeDomainPoints.push_back(new double[_numTimeDomainDataPoints]); + if(numTimeDomainDataPoints > 0) { + memcpy(_dataTimeDomainPoints[i], timeDomainPoints[i], + _numTimeDomainDataPoints * sizeof(double)); + } + } -const std::vector -TimeUpdateEvent::getTimeDomainPoints() const -{ - return _dataTimeDomainPoints; + _tags = tags; } -uint64_t -TimeUpdateEvent::getNumTimeDomainDataPoints() const +TimeUpdateEvent::~TimeUpdateEvent() { - return _numTimeDomainDataPoints; + for(size_t i = 0; i < _nplots; i++) { + delete[] _dataTimeDomainPoints[i]; + } } -const std::vector< std::vector > -TimeUpdateEvent::getTags() const -{ - return _tags; -} +const std::vector TimeUpdateEvent::getTimeDomainPoints() const { return _dataTimeDomainPoints; } -/***************************************************************************/ +uint64_t TimeUpdateEvent::getNumTimeDomainDataPoints() const { return _numTimeDomainDataPoints; } +const std::vector> TimeUpdateEvent::getTags() const { return _tags; } -IdentifiableTimeUpdateEvent::IdentifiableTimeUpdateEvent(const std::vector &timeDomainPoints, - const uint64_t numTimeDomainDataPoints, - const std::vector< std::vector > &tags, - const std::string &senderName) - : TimeUpdateEvent(timeDomainPoints, numTimeDomainDataPoints, tags), - _senderName(senderName) -{ -} +/***************************************************************************/ - IdentifiableTimeUpdateEvent::~IdentifiableTimeUpdateEvent() - { - } +IdentifiableTimeUpdateEvent::IdentifiableTimeUpdateEvent(const std::vector &timeDomainPoints, + const uint64_t numTimeDomainDataPoints, + const std::vector> &tags, + const std::string &senderName) + : TimeUpdateEvent(timeDomainPoints, numTimeDomainDataPoints, tags) + , _senderName(senderName) +{} - std::string IdentifiableTimeUpdateEvent::senderName() - { - return _senderName; - } +IdentifiableTimeUpdateEvent::~IdentifiableTimeUpdateEvent() {} +std::string IdentifiableTimeUpdateEvent::senderName() { return _senderName; } /***************************************************************************/ - -FreqUpdateEvent::FreqUpdateEvent(const std::vector &dataPoints, - const uint64_t numDataPoints) - : QEvent(QEvent::Type(SpectrumUpdateEventType)) -{ - if(numDataPoints < 1) { - _numDataPoints = 1; - } - else { - _numDataPoints = numDataPoints; - } - - _nplots = dataPoints.size(); - for(size_t i = 0; i < _nplots; i++) { - _dataPoints.push_back(new double[_numDataPoints]); - if(numDataPoints > 0) { - memcpy(_dataPoints[i], dataPoints[i], - _numDataPoints*sizeof(double)); - } - } -} - -FreqUpdateEvent::~FreqUpdateEvent() +FreqUpdateEvent::FreqUpdateEvent(const std::vector &dataPoints, const uint64_t numDataPoints) + : QEvent(QEvent::Type(SpectrumUpdateEventType)) { - for(size_t i = 0; i < _nplots; i++) { - delete[] _dataPoints[i]; - } -} + if(numDataPoints < 1) { + _numDataPoints = 1; + } else { + _numDataPoints = numDataPoints; + } -const std::vector -FreqUpdateEvent::getPoints() const -{ - return _dataPoints; + _nplots = dataPoints.size(); + for(size_t i = 0; i < _nplots; i++) { + _dataPoints.push_back(new double[_numDataPoints]); + if(numDataPoints > 0) { + memcpy(_dataPoints[i], dataPoints[i], _numDataPoints * sizeof(double)); + } + } } -uint64_t -FreqUpdateEvent::getNumDataPoints() const +FreqUpdateEvent::~FreqUpdateEvent() { - return _numDataPoints; + for(size_t i = 0; i < _nplots; i++) { + delete[] _dataPoints[i]; + } } +const std::vector FreqUpdateEvent::getPoints() const { return _dataPoints; } +uint64_t FreqUpdateEvent::getNumDataPoints() const { return _numDataPoints; } -SetFreqEvent::SetFreqEvent(const double centerFreq, - const double bandwidth) - : QEvent(QEvent::Type(SpectrumFrequencyRangeEventType)) +SetFreqEvent::SetFreqEvent(const double centerFreq, const double bandwidth) + : QEvent(QEvent::Type(SpectrumFrequencyRangeEventType)) { - _centerFrequency = centerFreq; - _bandwidth = bandwidth; + _centerFrequency = centerFreq; + _bandwidth = bandwidth; } -SetFreqEvent::~SetFreqEvent() -{ -} +SetFreqEvent::~SetFreqEvent() {} -double -SetFreqEvent::getCenterFrequency() const -{ - return _centerFrequency; -} - -double -SetFreqEvent::getBandwidth() const -{ - return _bandwidth; -} +double SetFreqEvent::getCenterFrequency() const { return _centerFrequency; } +double SetFreqEvent::getBandwidth() const { return _bandwidth; } /***************************************************************************/ - -ConstUpdateEvent::ConstUpdateEvent(const std::vector &realDataPoints, - const std::vector &imagDataPoints, - const uint64_t numDataPoints) - : QEvent(QEvent::Type(SpectrumUpdateEventType)) +ConstUpdateEvent::ConstUpdateEvent(const std::vector &realDataPoints, + const std::vector &imagDataPoints, const uint64_t numDataPoints) + : QEvent(QEvent::Type(SpectrumUpdateEventType)) { - if(numDataPoints < 1) { - _numDataPoints = 1; - } - else { - _numDataPoints = numDataPoints; - } - - _nplots = realDataPoints.size(); - for(size_t i = 0; i < _nplots; i++) { - _realDataPoints.push_back(new double[_numDataPoints]); - _imagDataPoints.push_back(new double[_numDataPoints]); - if(numDataPoints > 0) { - memcpy(_realDataPoints[i], realDataPoints[i], - _numDataPoints*sizeof(double)); - memcpy(_imagDataPoints[i], imagDataPoints[i], - _numDataPoints*sizeof(double)); - } - } -} + if(numDataPoints < 1) { + _numDataPoints = 1; + } else { + _numDataPoints = numDataPoints; + } -ConstUpdateEvent::~ConstUpdateEvent() -{ - for(size_t i = 0; i < _nplots; i++) { - delete[] _realDataPoints[i]; - delete[] _imagDataPoints[i]; - } + _nplots = realDataPoints.size(); + for(size_t i = 0; i < _nplots; i++) { + _realDataPoints.push_back(new double[_numDataPoints]); + _imagDataPoints.push_back(new double[_numDataPoints]); + if(numDataPoints > 0) { + memcpy(_realDataPoints[i], realDataPoints[i], _numDataPoints * sizeof(double)); + memcpy(_imagDataPoints[i], imagDataPoints[i], _numDataPoints * sizeof(double)); + } + } } -const std::vector -ConstUpdateEvent::getRealPoints() const +ConstUpdateEvent::~ConstUpdateEvent() { - return _realDataPoints; + for(size_t i = 0; i < _nplots; i++) { + delete[] _realDataPoints[i]; + delete[] _imagDataPoints[i]; + } } -const std::vector -ConstUpdateEvent::getImagPoints() const -{ - return _imagDataPoints; -} +const std::vector ConstUpdateEvent::getRealPoints() const { return _realDataPoints; } -uint64_t -ConstUpdateEvent::getNumDataPoints() const -{ - return _numDataPoints; -} +const std::vector ConstUpdateEvent::getImagPoints() const { return _imagDataPoints; } +uint64_t ConstUpdateEvent::getNumDataPoints() const { return _numDataPoints; } /***************************************************************************/ - -WaterfallUpdateEvent::WaterfallUpdateEvent(const std::vector &dataPoints, - const uint64_t numDataPoints, +WaterfallUpdateEvent::WaterfallUpdateEvent(const std::vector &dataPoints, const uint64_t numDataPoints, const gr::high_res_timer_type dataTimestamp) - : QEvent(QEvent::Type(SpectrumUpdateEventType)) + : QEvent(QEvent::Type(SpectrumUpdateEventType)) { -if (numDataPoints < 1) { - _numDataPoints = 1; - } else { - _numDataPoints = numDataPoints; - } - - _nplots = dataPoints.size(); - for (size_t i = 0; i < _nplots; i++) { - _dataPoints.push_back(new double[_numDataPoints]); - if (numDataPoints > 0) { - memcpy(_dataPoints[i], dataPoints[i], _numDataPoints * sizeof(double)); + if(numDataPoints < 1) { + _numDataPoints = 1; + } else { + _numDataPoints = numDataPoints; + } + + _nplots = dataPoints.size(); + for(size_t i = 0; i < _nplots; i++) { + _dataPoints.push_back(new double[_numDataPoints]); + if(numDataPoints > 0) { + memcpy(_dataPoints[i], dataPoints[i], _numDataPoints * sizeof(double)); + } } - } - _dataTimestamp = dataTimestamp; + _dataTimestamp = dataTimestamp; } WaterfallUpdateEvent::~WaterfallUpdateEvent() { - for(size_t i = 0; i < _nplots; i++) { - delete[] _dataPoints[i]; - } + for(size_t i = 0; i < _nplots; i++) { + delete[] _dataPoints[i]; + } } -const std::vector -WaterfallUpdateEvent::getPoints() const -{ - return _dataPoints; -} +const std::vector WaterfallUpdateEvent::getPoints() const { return _dataPoints; } -uint64_t -WaterfallUpdateEvent::getNumDataPoints() const -{ - return _numDataPoints; -} - -gr::high_res_timer_type -WaterfallUpdateEvent::getDataTimestamp() const -{ - return _dataTimestamp; -} +uint64_t WaterfallUpdateEvent::getNumDataPoints() const { return _numDataPoints; } +gr::high_res_timer_type WaterfallUpdateEvent::getDataTimestamp() const { return _dataTimestamp; } /***************************************************************************/ - -TimeRasterUpdateEvent::TimeRasterUpdateEvent(const std::vector &dataPoints, - const uint64_t numDataPoints) - : QEvent(QEvent::Type(SpectrumUpdateEventType)) +TimeRasterUpdateEvent::TimeRasterUpdateEvent(const std::vector &dataPoints, const uint64_t numDataPoints) + : QEvent(QEvent::Type(SpectrumUpdateEventType)) { - if(numDataPoints < 1) { - _numDataPoints = 1; - } - else { - _numDataPoints = numDataPoints; - } - - _nplots = dataPoints.size(); - for(size_t i = 0; i < _nplots; i++) { - _dataPoints.push_back(new double[_numDataPoints]); - if(numDataPoints > 0) { - memcpy(_dataPoints[i], dataPoints[i], - _numDataPoints*sizeof(double)); - } - } + if(numDataPoints < 1) { + _numDataPoints = 1; + } else { + _numDataPoints = numDataPoints; + } + + _nplots = dataPoints.size(); + for(size_t i = 0; i < _nplots; i++) { + _dataPoints.push_back(new double[_numDataPoints]); + if(numDataPoints > 0) { + memcpy(_dataPoints[i], dataPoints[i], _numDataPoints * sizeof(double)); + } + } } TimeRasterUpdateEvent::~TimeRasterUpdateEvent() { - for(size_t i = 0; i < _nplots; i++) { - delete[] _dataPoints[i]; - } + for(size_t i = 0; i < _nplots; i++) { + delete[] _dataPoints[i]; + } } -const std::vector -TimeRasterUpdateEvent::getPoints() const -{ - return _dataPoints; -} +const std::vector TimeRasterUpdateEvent::getPoints() const { return _dataPoints; } -uint64_t -TimeRasterUpdateEvent::getNumDataPoints() const -{ - return _numDataPoints; -} +uint64_t TimeRasterUpdateEvent::getNumDataPoints() const { return _numDataPoints; } /***************************************************************************/ - -HistogramUpdateEvent::HistogramUpdateEvent(const std::vector &points, - const uint64_t npoints) - : QEvent(QEvent::Type(SpectrumUpdateEventType)) -{ - if(npoints < 1) { - _npoints = 1; - } - else { - _npoints = npoints; - } - - _nplots = points.size(); - for(size_t i = 0; i < _nplots; i++) { - _points.push_back(new double[_npoints]); - if(npoints > 0) { - memcpy(_points[i], points[i], _npoints*sizeof(double)); - } - } -} - -HistogramUpdateEvent::~HistogramUpdateEvent() +HistogramUpdateEvent::HistogramUpdateEvent(const std::vector &points, const uint64_t npoints) + : QEvent(QEvent::Type(SpectrumUpdateEventType)) { - for(size_t i = 0; i < _nplots; i++) { - delete[] _points[i]; - } -} + if(npoints < 1) { + _npoints = 1; + } else { + _npoints = npoints; + } -const std::vector -HistogramUpdateEvent::getDataPoints() const -{ - return _points; + _nplots = points.size(); + for(size_t i = 0; i < _nplots; i++) { + _points.push_back(new double[_npoints]); + if(npoints > 0) { + memcpy(_points[i], points[i], _npoints * sizeof(double)); + } + } } -uint64_t -HistogramUpdateEvent::getNumDataPoints() const +HistogramUpdateEvent::~HistogramUpdateEvent() { - return _npoints; + for(size_t i = 0; i < _nplots; i++) { + delete[] _points[i]; + } } +const std::vector HistogramUpdateEvent::getDataPoints() const { return _points; } +uint64_t HistogramUpdateEvent::getNumDataPoints() const { return _npoints; } /***************************************************************************/ - NumberUpdateEvent::NumberUpdateEvent(const std::vector &samples) - : QEvent(QEvent::Type(SpectrumUpdateEventType)), - _samples(samples), - _nplots(samples.size()) -{ -} - -NumberUpdateEvent::~NumberUpdateEvent() -{ -} + : QEvent(QEvent::Type(SpectrumUpdateEventType)) + , _samples(samples) + , _nplots(samples.size()) +{} -const std::vector -NumberUpdateEvent::getSamples() const -{ - return _samples; -} +NumberUpdateEvent::~NumberUpdateEvent() {} +const std::vector NumberUpdateEvent::getSamples() const { return _samples; } #endif /* SPECTRUM_UPDATE_EVENTS_C */ diff --git a/gui/src/spectrum_marker.cpp b/gui/src/spectrum_marker.cpp index 2af2d7601f..3ab9981edc 100644 --- a/gui/src/spectrum_marker.cpp +++ b/gui/src/spectrum_marker.cpp @@ -21,89 +21,75 @@ #include "spectrum_marker.hpp" #include -#include #include +#include using namespace scopy; -SpectrumMarker::SpectrumMarker(const QString &title, bool movable) : - QwtPlotMarker(title), m_xAxis(QwtAxis::XBottom), - m_yAxis(QwtAxis::YLeft), m_movable(movable), m_selected(false) -{ -} +SpectrumMarker::SpectrumMarker(const QString &title, bool movable) + : QwtPlotMarker(title) + , m_xAxis(QwtAxis::XBottom) + , m_yAxis(QwtAxis::YLeft) + , m_movable(movable) + , m_selected(false) +{} -SpectrumMarker::SpectrumMarker(const QString &title, QwtAxisId xAxis, - QwtAxisId yAxis, bool movable) : - QwtPlotMarker(title), m_xAxis(xAxis), m_yAxis(yAxis), m_movable(movable), m_selected(false) -{ -} +SpectrumMarker::SpectrumMarker(const QString &title, QwtAxisId xAxis, QwtAxisId yAxis, bool movable) + : QwtPlotMarker(title) + , m_xAxis(xAxis) + , m_yAxis(yAxis) + , m_movable(movable) + , m_selected(false) +{} -SpectrumMarker::~SpectrumMarker() -{ -} +SpectrumMarker::~SpectrumMarker() {} -QColor SpectrumMarker::defaultColor() const -{ - return m_default_color; -} +QColor SpectrumMarker::defaultColor() const { return m_default_color; } -void SpectrumMarker::setDefaultColor(const QColor& color) -{ - m_default_color = color; -} +void SpectrumMarker::setDefaultColor(const QColor &color) { m_default_color = color; } -bool SpectrumMarker::selected() const -{ - return m_selected; -} +bool SpectrumMarker::selected() const { return m_selected; } void SpectrumMarker::setSelected(bool on) { - if (m_selected != on) { + if(m_selected != on) { m_selected = on; QBrush brush = symbol()->brush(); - if (on) { + if(on) { brush.setColor(defaultColor()); } else { brush.setColor(symbol()->pen().color()); } - QwtSymbol *new_sym = new QwtSymbol(symbol()->style(), - brush, symbol()->pen(), symbol()->size()); + QwtSymbol *new_sym = new QwtSymbol(symbol()->style(), brush, symbol()->pen(), symbol()->size()); setSymbol(new_sym); } } -bool SpectrumMarker::movable() const -{ - return m_movable; -} +bool SpectrumMarker::movable() const { return m_movable; } -void SpectrumMarker::setMovable(bool on) -{ - m_movable = on; -} +void SpectrumMarker::setMovable(bool on) { m_movable = on; } -QPoint SpectrumMarker::plotValueToPixels(const QPointF& point) const +QPoint SpectrumMarker::plotValueToPixels(const QPointF &point) const { QPoint pixelPoint(0, 0); - if (plot()) { + if(plot()) { const QwtScaleMap xMap = plot()->canvasMap(m_xAxis); const QwtScaleMap yMap = plot()->canvasMap(m_yAxis); QPointF p = QwtScaleMap::transform(xMap, yMap, point); - pixelPoint = QPoint(p.x(),p.y()); + pixelPoint = QPoint(p.x(), p.y()); } return pixelPoint; } -QPointF SpectrumMarker::plotPixelsToValue(const QPoint& point) const +QPointF SpectrumMarker::plotPixelsToValue(const QPoint &point) const { QPointF valuePoint(0.0, 0.0); - if (plot()) { + if(plot()) { const QwtScaleMap xMap = plot()->canvasMap(m_xAxis); const QwtScaleMap yMap = plot()->canvasMap(m_yAxis); @@ -118,6 +104,5 @@ QRect SpectrumMarker::boundingRectPixels() const QPoint markerPixPos = plotValueToPixels(value()); QRect symbolRect = symbol()->boundingRect(); - return QRect(symbolRect.topLeft() + markerPixPos, symbolRect.size()); } diff --git a/gui/src/spinbox_a.cpp b/gui/src/spinbox_a.cpp index 10b594538f..bee91f2c49 100644 --- a/gui/src/spinbox_a.cpp +++ b/gui/src/spinbox_a.cpp @@ -19,22 +19,23 @@ */ #include "spinbox_a.hpp" + #include "completion_circle.h" + #include "ui_spinbox_a.h" -#include -#include -#include -#include -#include -#include #include +#include +#include #include -#include -#include +#include +#include #include - -#include +#include +#include +#include +#include +#include using namespace std; using namespace scopy; @@ -45,12 +46,16 @@ using namespace scopy; unsigned int SpinBoxA::current_id(0); -SpinBoxA::SpinBoxA(QWidget *parent) : QWidget(parent), - ui(new Ui::SpinBoxA), m_value(0.0), m_min_value(0.0), m_max_value(0.0), - m_decimal_count(3), - m_validator(new QRegExpValidator(this)) +SpinBoxA::SpinBoxA(QWidget *parent) + : QWidget(parent) + , ui(new Ui::SpinBoxA) + , m_value(0.0) + , m_min_value(0.0) + , m_max_value(0.0) + , m_decimal_count(3) + , m_validator(new QRegExpValidator(this)) #ifdef SPINBOX_API - ,m_sba_api(new SpinBoxA_API(this)) + , m_sba_api(new SpinBoxA_API(this)) #endif { ui->setupUi(this); @@ -59,33 +64,27 @@ SpinBoxA::SpinBoxA(QWidget *parent) : QWidget(parent), ui->SBA_LineEdit->installEventFilter(this); ui->SBA_CompletionCircle->installEventFilter(this); - connect(ui->SBA_Combobox, SIGNAL(currentIndexChanged(int)), - SLOT(onComboboxIndexChanged(int))); - connect(ui->SBA_LineEdit, SIGNAL(editingFinished()), - SLOT(onLineEditTextEdited())); - connect(ui->SBA_UpButton, SIGNAL(clicked()), - SLOT(onUpButtonPressed())); - connect(ui->SBA_DownButton, SIGNAL(clicked()), - SLOT(onDownButtonPressed())); + connect(ui->SBA_Combobox, SIGNAL(currentIndexChanged(int)), SLOT(onComboboxIndexChanged(int))); + connect(ui->SBA_LineEdit, SIGNAL(editingFinished()), SLOT(onLineEditTextEdited())); + connect(ui->SBA_UpButton, SIGNAL(clicked()), SLOT(onUpButtonPressed())); + connect(ui->SBA_DownButton, SIGNAL(clicked()), SLOT(onDownButtonPressed())); - connect(this, SIGNAL(valueChanged(double)), - ui->SBA_CompletionCircle, SLOT(setValueDouble(double))); - connect(ui->SBA_CompletionCircle, SIGNAL(toggled(bool)), - SLOT(setFineMode(bool))); + connect(this, SIGNAL(valueChanged(double)), ui->SBA_CompletionCircle, SLOT(setValueDouble(double))); + connect(ui->SBA_CompletionCircle, SIGNAL(toggled(bool)), SLOT(setFineMode(bool))); m_displayScale = 1; } -SpinBoxA::SpinBoxA(vector >units, const QString& name, - double min_value, double max_value, bool hasProgressWidget, - bool invertCircle, QWidget *parent) : SpinBoxA(parent) +SpinBoxA::SpinBoxA(vector> units, const QString &name, double min_value, double max_value, + bool hasProgressWidget, bool invertCircle, QWidget *parent) + : SpinBoxA(parent) { showProgress(hasProgressWidget); /* Compat */ QStringList list; - for (const auto &unit : units) { + for(const auto &unit : units) { list.append(QString("%1=%2").arg(unit.first).arg(unit.second)); } @@ -99,9 +98,9 @@ SpinBoxA::SpinBoxA(vector >units, const QString& name, m_displayScale = 1; - if (m_value < min_value) { + if(m_value < min_value) { setValue(min_value); - } else if (m_value > max_value) { + } else if(m_value > max_value) { setValue(max_value); } @@ -132,10 +131,7 @@ SpinBoxA::~SpinBoxA() delete ui; } -void SpinBoxA::updateCompletionCircle(double value) -{ - ui->SBA_CompletionCircle->setValueDouble(value); -} +void SpinBoxA::updateCompletionCircle(double value) { ui->SBA_CompletionCircle->setValueDouble(value); } void SpinBoxA::silentSetValue(double value) { @@ -160,15 +156,9 @@ void SpinBoxA::silentSetMaxValue(double value) setMaxValue(value); } -void SpinBoxA::onUpButtonPressed() -{ - stepUp(); -} +void SpinBoxA::onUpButtonPressed() { stepUp(); } -void SpinBoxA::onDownButtonPressed() -{ - stepDown(); -} +void SpinBoxA::onDownButtonPressed() { stepDown(); } void SpinBoxA::onComboboxIndexChanged(int index) { @@ -189,49 +179,48 @@ void SpinBoxA::onLineEditTextEdited() rx.indexIn(text); value = rx.cap(1).toDouble(&ok); - if (!ok) { + if(!ok) { return; } unit = rx.cap(6); - if (unit.isEmpty()) { + if(unit.isEmpty()) { unit = m_units[ui->SBA_Combobox->currentIndex()].first; - } else if (unit.startsWith(QString("u"), Qt::CaseInsensitive)) { - qDebug()<<"before unit "< pair) { - return pair.first.at(0) == unit.at(0); - }) - m_units.begin(); + [=](const pair pair) { return pair.first.at(0) == unit.at(0); }) - + m_units.begin(); - if (i < m_units.size()) { + if(i < m_units.size()) { value *= m_units[i].second; value /= m_displayScale; setValue(value); @@ -242,61 +231,37 @@ bool SpinBoxA::isUnitMatched(const QString& unit, double value) return false; } -QPushButton *SpinBoxA::upButton() -{ - return ui->SBA_UpButton; -} +QPushButton *SpinBoxA::upButton() { return ui->SBA_UpButton; } -QPushButton *SpinBoxA::downButton() -{ - return ui->SBA_DownButton; -} +QPushButton *SpinBoxA::downButton() { return ui->SBA_DownButton; } -QLabel *SpinBoxA::nameLabel() -{ - return ui->SBA_Label; -} +QLabel *SpinBoxA::nameLabel() { return ui->SBA_Label; } -QLineEdit *SpinBoxA::lineEdit() -{ - return ui->SBA_LineEdit; -} +QLineEdit *SpinBoxA::lineEdit() { return ui->SBA_LineEdit; } -QFrame *SpinBoxA::line() -{ - return ui->SBA_Line; -} +QFrame *SpinBoxA::line() { return ui->SBA_Line; } -QComboBox *SpinBoxA::comboBox() -{ - return ui->SBA_Combobox; -} +QComboBox *SpinBoxA::comboBox() { return ui->SBA_Combobox; } -double SpinBoxA::value() -{ - return m_value; -} +double SpinBoxA::value() { return m_value; } -static bool isZero(double value, double threshold) -{ - return (value >= -threshold && value <= threshold); -} +static bool isZero(double value, double threshold) { return (value >= -threshold && value <= threshold); } void SpinBoxA::setValue(double value) { bool emitValueChanged = false; - if (isZero(value, 1E-12)) { + if(isZero(value, 1E-12)) { value = 0; } - if (value < m_min_value) { + if(value < m_min_value) { value = m_min_value; - } else if (value > m_max_value) { + } else if(value > m_max_value) { value = m_max_value; } - if (m_value != value) { + if(m_value != value) { m_value = value; emitValueChanged = true; } @@ -308,161 +273,144 @@ void SpinBoxA::setValue(double value) double abs_number = qAbs(number); int significant_digits = m_decimal_count; - if (abs_number >= 100) { + if(abs_number >= 100) { significant_digits += 3; - } else if (abs_number >= 10) { + } else if(abs_number >= 10) { significant_digits += 2; - } else if (abs_number >= 1) { + } else if(abs_number >= 1) { significant_digits += 1; } number *= m_displayScale; - ui->SBA_LineEdit->setText(QString::number(number, 'g', - significant_digits)); + ui->SBA_LineEdit->setText(QString::number(number, 'g', significant_digits)); ui->SBA_LineEdit->setCursorPosition(0); - if (m_value != 0) { + if(m_value != 0) { ui->SBA_Combobox->blockSignals(true); ui->SBA_Combobox->setCurrentIndex(index); ui->SBA_Combobox->blockSignals(false); } - if (m_value == m_min_value) { + if(m_value == m_min_value) { ui->SBA_DownButton->setEnabled(false); } else { ui->SBA_DownButton->setEnabled(true); } - if (m_value == m_max_value) { + if(m_value == m_max_value) { ui->SBA_UpButton->setEnabled(false); } else { ui->SBA_UpButton->setEnabled(true); } - if (emitValueChanged) { + if(emitValueChanged) { Q_EMIT valueChanged(m_value); } } -double SpinBoxA::minValue() -{ - return m_min_value; -} +double SpinBoxA::minValue() { return m_min_value; } void SpinBoxA::setMinValue(double value) { m_min_value = value; - if (m_value < m_min_value) { + if(m_value < m_min_value) { setValue(m_min_value); - } else if (m_value > m_min_value) { + } else if(m_value > m_min_value) { ui->SBA_DownButton->setEnabled(true); } ui->SBA_CompletionCircle->setMinimumDouble(value); - } -int SpinBoxA::decimalCount() const -{ - return m_decimal_count; -} +int SpinBoxA::decimalCount() const { return m_decimal_count; } void SpinBoxA::setDecimalCount(int count) { - if (count >= 0) { + if(count >= 0) { m_decimal_count = count; } } -double SpinBoxA::maxValue() -{ - return m_max_value; -} +double SpinBoxA::maxValue() { return m_max_value; } void SpinBoxA::setMaxValue(double value) { m_max_value = value; - if (m_value > m_max_value) { + if(m_value > m_max_value) { setValue(m_max_value); - } else if (m_value < m_max_value) { + } else if(m_value < m_max_value) { ui->SBA_UpButton->setEnabled(true); } ui->SBA_CompletionCircle->setMaximumDouble(value); } -bool SpinBoxA::isInFineMode() -{ - return ui->SBA_CompletionCircle->toggledState(); -} +bool SpinBoxA::isInFineMode() { return ui->SBA_CompletionCircle->toggledState(); } -void SpinBoxA::setFineMode(bool en) -{ - ui->SBA_CompletionCircle->setToggled(en); -} +void SpinBoxA::setFineMode(bool en) { ui->SBA_CompletionCircle->setToggled(en); } bool SpinBoxA::eventFilter(QObject *obj, QEvent *event) { - if (obj == ui->SBA_LineEdit) { - if (event->type() == QEvent::KeyPress) { + if(obj == ui->SBA_LineEdit) { + if(event->type() == QEvent::KeyPress) { QKeyEvent *keyE = static_cast(event); - if (keyE->key() == Qt::Key_Up) { + if(keyE->key() == Qt::Key_Up) { stepUp(); return true; - } else if (keyE->key() == Qt::Key_Down) { + } else if(keyE->key() == Qt::Key_Down) { stepDown(); return true; - } else if (keyE->key() == Qt::Key_PageUp) { + } else if(keyE->key() == Qt::Key_PageUp) { stepUp(); return true; - } else if (keyE->key() == Qt::Key_PageDown) { + } else if(keyE->key() == Qt::Key_PageDown) { stepDown(); return true; } - } else if (event->type() == QEvent::Wheel) { - if (!isEnabled()) { + } else if(event->type() == QEvent::Wheel) { + if(!isEnabled()) { return QWidget::eventFilter(obj, event); } QWheelEvent *wheelE = static_cast(event); - if (wheelE->angleDelta().y() > 0) { + if(wheelE->angleDelta().y() > 0) { stepUp(); event->accept(); return true; - } else if (wheelE->angleDelta().y() < 0) { + } else if(wheelE->angleDelta().y() < 0) { stepDown(); event->accept(); return true; } - } else if (event->type() == QEvent::FocusOut) { + } else if(event->type() == QEvent::FocusOut) { setValue(m_value); } } - if (obj == ui->SBA_CompletionCircle) { - if (!isEnabled()) { + if(obj == ui->SBA_CompletionCircle) { + if(!isEnabled()) { return QWidget::eventFilter(obj, event); } - if (event->type() == QEvent::Enter) { + if(event->type() == QEvent::Enter) { setCursor(Qt::SizeVerCursor); - } else if (event->type() == QEvent::Leave) { + } else if(event->type() == QEvent::Leave) { setCursor(Qt::ArrowCursor); - } else if (event->type() == QEvent::Wheel) { + } else if(event->type() == QEvent::Wheel) { QWheelEvent *wheelE = static_cast(event); - if (wheelE->angleDelta().y() > 0) { + if(wheelE->angleDelta().y() > 0) { stepUp(); event->accept(); return true; - } else if (wheelE->angleDelta().y() < 0) { + } else if(wheelE->angleDelta().y() < 0) { stepDown(); event->accept(); return true; @@ -479,68 +427,38 @@ double SpinBoxA::findUnitOfValue(double val, int *posInUnitsList) val = qFabs(val); - for (auto it = m_units.rbegin(); it != m_units.rend(); ++it) { - if (val >= (*it).second) { + for(auto it = m_units.rbegin(); it != m_units.rend(); ++it) { + if(val >= (*it).second) { index = m_units.rend() - it - 1; break; } } - if (posInUnitsList) { + if(posInUnitsList) { *posInUnitsList = index; } return m_units[index].second; } -bool SpinBoxA::isCircleInverted() const -{ - return ui->SBA_CompletionCircle->property("inverted").toBool(); -} +bool SpinBoxA::isCircleInverted() const { return ui->SBA_CompletionCircle->property("inverted").toBool(); } -void SpinBoxA::setInvertCircle(bool invert) -{ - ui->SBA_CompletionCircle->setProperty("inverted", QVariant(invert)); -} +void SpinBoxA::setInvertCircle(bool invert) { ui->SBA_CompletionCircle->setProperty("inverted", QVariant(invert)); } -bool SpinBoxA::progressShown() const -{ - return ui->SBA_CompletionCircle->isVisible(); -} +bool SpinBoxA::progressShown() const { return ui->SBA_CompletionCircle->isVisible(); } -void SpinBoxA::showProgress(bool show) -{ - ui->SBA_CompletionCircle->setVisible(show); -} +void SpinBoxA::showProgress(bool show) { ui->SBA_CompletionCircle->setVisible(show); } -bool SpinBoxA::fineModeAvailable() -{ - return ui->SBA_CompletionCircle->toggleable(); -} -void SpinBoxA::setFineModeAvailable(bool tog) -{ - ui->SBA_CompletionCircle->setToggleable(tog); -} +bool SpinBoxA::fineModeAvailable() { return ui->SBA_CompletionCircle->toggleable(); } +void SpinBoxA::setFineModeAvailable(bool tog) { ui->SBA_CompletionCircle->setToggleable(tog); } -bool SpinBoxA::isStepDown() const -{ - return m_is_step_down; -} +bool SpinBoxA::isStepDown() const { return m_is_step_down; } -void SpinBoxA::triggerCircleRedraw() -{ - ui->SBA_CompletionCircle->setValueDouble(value()); -} +void SpinBoxA::triggerCircleRedraw() { ui->SBA_CompletionCircle->setValueDouble(value()); } -QString SpinBoxA::getName() const -{ - return ui->SBA_Label->text(); -} +QString SpinBoxA::getName() const { return ui->SBA_Label->text(); } -void SpinBoxA::setName(const QString& name) -{ - ui->SBA_Label->setText(name); -} +void SpinBoxA::setName(const QString &name) { ui->SBA_Label->setText(name); } void SpinBoxA::setDisplayScale(double value) { @@ -548,19 +466,18 @@ void SpinBoxA::setDisplayScale(double value) setValue(m_value); } -void SpinBoxA::setUnits(const QStringList& list) +void SpinBoxA::setUnits(const QStringList &list) { QString regex = "^(?!^.{18})(([+,-]?)([0-9]*)([.]?)([0-9]+))"; QString sufixes; ui->SBA_Combobox->clear(); - - if (list.at(0).section("=",0,0).trimmed().isEmpty() || list.count()==1) { + if(list.at(0).section("=", 0, 0).trimmed().isEmpty() || list.count() == 1) { ui->SBA_Combobox->setEnabled(false); } - for (auto it = list.begin(); it != list.end(); ++it) { + for(auto it = list.begin(); it != list.end(); ++it) { QStringList curr = it->split('='); QString s = curr.at(0); double val = curr.at(1).toDouble(); @@ -570,13 +487,13 @@ void SpinBoxA::setUnits(const QStringList& list) ui->SBA_Combobox->addItem(s); } - if (!sufixes.isEmpty()) { - if (sufixes.contains("μ", Qt::CaseInsensitive)) { + if(!sufixes.isEmpty()) { + if(sufixes.contains("μ", Qt::CaseInsensitive)) { sufixes += 'u', Qt::CaseInsensitive; sufixes += '|'; } - if (sufixes.contains("π", Qt::CaseInsensitive)) { + if(sufixes.contains("π", Qt::CaseInsensitive)) { sufixes += 'r', Qt::CaseInsensitive; sufixes += '|'; } @@ -598,28 +515,22 @@ void SpinBoxA::setUnits(const QStringList& list) /* * ScaleSpinButton class implementation */ -ScaleSpinButton::ScaleSpinButton(QWidget *parent) : SpinBoxA(parent), - m_steps(1E-3, 1E+3, 10, -{ - 1, 2, 5 -}), -m_fine_increment(1) +ScaleSpinButton::ScaleSpinButton(QWidget *parent) + : SpinBoxA(parent) + , m_steps(1E-3, 1E+3, 10, {1, 2, 5}) + , m_fine_increment(1) { ui->SBA_CompletionCircle->setIsLogScale(true); } -ScaleSpinButton::ScaleSpinButton(vector >units, - const QString& name, - double min_value, double max_value, - bool hasProgressWidget, bool invertCircle, QWidget *parent, - std::vector steps): - SpinBoxA(units, name, min_value, max_value, - hasProgressWidget, invertCircle, parent), - m_steps(1E-3, 1E+3, 10, - steps), - m_fine_increment(1), - m_numberSeriesRebuild(true), - integer_divider(0) +ScaleSpinButton::ScaleSpinButton(vector> units, const QString &name, double min_value, + double max_value, bool hasProgressWidget, bool invertCircle, QWidget *parent, + std::vector steps) + : SpinBoxA(units, name, min_value, max_value, hasProgressWidget, invertCircle, parent) + , m_steps(1E-3, 1E+3, 10, steps) + , m_fine_increment(1) + , m_numberSeriesRebuild(true) + , integer_divider(0) { ui->SBA_CompletionCircle->setIsLogScale(true); @@ -629,12 +540,12 @@ ScaleSpinButton::ScaleSpinButton(vector >units, void ScaleSpinButton::setMinValue(double value) { - if (m_numberSeriesRebuild) { + if(m_numberSeriesRebuild) { m_steps.setLower(value); } SpinBoxA::setMinValue(value); - if (m_value == m_min_value) { + if(m_value == m_min_value) { ui->SBA_DownButton->setEnabled(false); } else { ui->SBA_DownButton->setEnabled(true); @@ -643,33 +554,23 @@ void ScaleSpinButton::setMinValue(double value) void ScaleSpinButton::setMaxValue(double value) { - if (m_numberSeriesRebuild) { + if(m_numberSeriesRebuild) { m_steps.setUpper(value); } SpinBoxA::setMaxValue(value); - if (m_value == m_max_value) { + if(m_value == m_max_value) { ui->SBA_UpButton->setEnabled(false); } else { ui->SBA_UpButton->setEnabled(true); } } -void ScaleSpinButton::enableNumberSeriesRebuild(bool enable) -{ - m_numberSeriesRebuild = enable; -} - -void ScaleSpinButton::setIntegerDivider(int val) -{ - integer_divider = val; -} +void ScaleSpinButton::enableNumberSeriesRebuild(bool enable) { m_numberSeriesRebuild = enable; } -int ScaleSpinButton::getIntegerDivider() -{ - return integer_divider; -} +void ScaleSpinButton::setIntegerDivider(int val) { integer_divider = val; } +int ScaleSpinButton::getIntegerDivider() { return integer_divider; } void ScaleSpinButton::setValue(double newVal) { @@ -680,10 +581,9 @@ void ScaleSpinButton::setValue(double newVal) newVal = m_min_value; } - if(integer_divider) - { + if(integer_divider) { integer_step = round(integer_divider / newVal); - newVal = integer_divider/integer_step; + newVal = integer_divider / integer_step; } SpinBoxA::setValue(newVal); } @@ -697,19 +597,17 @@ void ScaleSpinButton::stepUp() double epsilon = 1E-12; - if (isInFineMode()) { + if(isInFineMode()) { newVal = (current_val + m_fine_increment) * current_scale; } else { auto oldVal = current_val * current_scale + epsilon; - newVal = m_steps.getNumberAfter(oldVal); + newVal = m_steps.getNumberAfter(oldVal); - if (oldVal>=newVal) { // reached end of scale + if(oldVal >= newVal) { // reached end of scale newVal = maxValue(); } - } - if(integer_divider) - { + if(integer_divider) { auto new_integer_step = ceil(integer_divider / newVal); if(new_integer_step == integer_step && new_integer_step > 1) integer_step--; @@ -730,21 +628,18 @@ void ScaleSpinButton::stepDown() double epsilon = 1E-12; - if (isInFineMode()) { + if(isInFineMode()) { newVal = (current_val - m_fine_increment) * current_scale; - if (current_val - m_fine_increment < 1 - && current_val - m_fine_increment > 0) { + if(current_val - m_fine_increment < 1 && current_val - m_fine_increment > 0) { newVal = 0; } - if ((m_min_value > 0 && newVal <= m_min_value) && - (ui->SBA_Combobox->currentIndex() > 0)) { + if((m_min_value > 0 && newVal <= m_min_value) && (ui->SBA_Combobox->currentIndex() > 0)) { int i = ui->SBA_Combobox->currentIndex() - 1; double nextLowerScale = m_units[i].second; - newVal = current_scale / nextLowerScale - - m_fine_increment; + newVal = current_scale / nextLowerScale - m_fine_increment; newVal *= nextLowerScale; } @@ -752,8 +647,7 @@ void ScaleSpinButton::stepDown() newVal = m_steps.getNumberBefore(current_val * current_scale - epsilon); } - if(integer_divider) - { + if(integer_divider) { auto new_integer_step = floor(integer_divider / newVal); if(new_integer_step == integer_step) integer_step++; @@ -767,30 +661,20 @@ void ScaleSpinButton::stepDown() /* * PositionSpinButton class implementation */ -PositionSpinButton::PositionSpinButton(QWidget *parent) : SpinBoxA(parent), - m_step(1) -{ -} +PositionSpinButton::PositionSpinButton(QWidget *parent) + : SpinBoxA(parent) + , m_step(1) +{} -PositionSpinButton::PositionSpinButton(vector >units, - const QString& name, - double min_value, double max_value, - bool hasProgressWidget, bool invertCircle, QWidget *parent): - SpinBoxA(units, name, min_value, max_value, - hasProgressWidget, invertCircle, parent), - m_step(1) -{ -} +PositionSpinButton::PositionSpinButton(vector> units, const QString &name, double min_value, + double max_value, bool hasProgressWidget, bool invertCircle, QWidget *parent) + : SpinBoxA(units, name, min_value, max_value, hasProgressWidget, invertCircle, parent) + , m_step(1) +{} -double PositionSpinButton:: step() -{ - return m_step; -} +double PositionSpinButton::step() { return m_step; } -void PositionSpinButton::setStep(double step) -{ - m_step = step; -} +void PositionSpinButton::setStep(double step) { m_step = step; } void PositionSpinButton::stepUp() { @@ -802,15 +686,15 @@ void PositionSpinButton::stepUp() double ratio = current_scale / m_step; - if (ratio > 1e3) { + if(ratio > 1e3) { step = step * 1e3; } - if (isInFineMode()) { + if(isInFineMode()) { step /= 10; } - newVal = current_val * current_scale + step; + newVal = current_val * current_scale + step; setValue(newVal); } @@ -825,11 +709,11 @@ void PositionSpinButton::stepDown() double ratio = current_scale / m_step; - if (ratio > 1e3) { + if(ratio > 1e3) { step = step * 1e3; } - if (isInFineMode()) { + if(isInFineMode()) { step /= 10; } @@ -838,32 +722,29 @@ void PositionSpinButton::stepDown() setValue(newVal); } -PhaseSpinButton::PhaseSpinButton(QWidget *parent) : SpinBoxA(parent), - m_fine_increment(1), - m_inSeconds(false), - m_indexValue(0), - m_step(15), - m_secondsValue(0), - m_scale(1), - m_frequency(1) +PhaseSpinButton::PhaseSpinButton(QWidget *parent) + : SpinBoxA(parent) + , m_fine_increment(1) + , m_inSeconds(false) + , m_indexValue(0) + , m_step(15) + , m_secondsValue(0) + , m_scale(1) + , m_frequency(1) { ui->SBA_CompletionCircle->setIsLogScale(false); ui->SBA_CompletionCircle->setOrigin(0); } -PhaseSpinButton::PhaseSpinButton(std::vector > units, - const QString& name, - double min_value, double max_value, - bool hasProgressWidget, - bool invertCircle, QWidget *parent): - SpinBoxA(units, name, min_value, max_value, - hasProgressWidget, invertCircle, parent), - m_fine_increment(1), - m_inSeconds(false), - m_indexValue(0), - m_step(15), - m_secondsValue(0), - m_scale(1) +PhaseSpinButton::PhaseSpinButton(std::vector> units, const QString &name, double min_value, + double max_value, bool hasProgressWidget, bool invertCircle, QWidget *parent) + : SpinBoxA(units, name, min_value, max_value, hasProgressWidget, invertCircle, parent) + , m_fine_increment(1) + , m_inSeconds(false) + , m_indexValue(0) + , m_step(15) + , m_secondsValue(0) + , m_scale(1) { ui->SBA_CompletionCircle->setIsLogScale(false); setMinValue(min_value); @@ -872,31 +753,31 @@ PhaseSpinButton::PhaseSpinButton(std::vector > units, setFrequency(0.01); ui->SBA_CompletionCircle->setOrigin(0); - ui->SBA_DownButton->setEnabled(true); - ui->SBA_UpButton->setEnabled(true); + ui->SBA_DownButton->setEnabled(true); + ui->SBA_UpButton->setEnabled(true); } void PhaseSpinButton::setValue(double value) { /* This method might be called when the PhaseSpinButton looses focus with - * value = m_value. In this case value would be the real value (m_value) - * not the one that is displayed. In this case we ignore the call and - * return immediately */ - if (m_value == value && !QObject::sender()) { + * value = m_value. In this case value would be the real value (m_value) + * not the one that is displayed. In this case we ignore the call and + * return immediately */ + if(m_value == value && !QObject::sender()) { return; } bool emitValueChanged = false; - if (isZero(value, 1E-12)) { + if(isZero(value, 1E-12)) { value = 0; } - if (inSeconds()) { + if(inSeconds()) { double periodInSeconds = changeValueFromDegreesToSeconds(360); - if (value < 0) { + if(value < 0) { value = value + periodInSeconds; - } else if (value > periodInSeconds) { + } else if(value > periodInSeconds) { int full_periods = value / periodInSeconds; value -= full_periods * periodInSeconds; } @@ -905,7 +786,7 @@ void PhaseSpinButton::setValue(double value) double period = 360; double scale; - if (inSeconds()) { + if(inSeconds()) { int index; scale = findUnitOfValue(value, &index); value = computeSecondsTransformation(scale, index, value); @@ -918,50 +799,47 @@ void PhaseSpinButton::setValue(double value) int full_periods = value / period; value -= full_periods * period; - if (value < 0) { + if(value < 0) { value = value + period; } - if (m_value != value) { + if(m_value != value) { m_value = value; emitValueChanged = true; } - if (m_value == 0) { + if(m_value == 0) { setSecondsValue(0); } - if (m_scale != scale) { + if(m_scale != scale) { m_scale = scale; emitValueChanged = true; } - if (!inSeconds() || m_value == 0) { + if(!inSeconds() || m_value == 0) { ui->SBA_LineEdit->setText(QString::number(round((m_value * 10) / 10) / scale)); } // adjust scale for the ecurrent measure unit and handle unit measure change - if (emitValueChanged) { + if(emitValueChanged) { Q_EMIT valueChanged(m_value); } } -void PhaseSpinButton::setComboboxIndex(int index) -{ - ui->SBA_Combobox->setCurrentIndex(index); -} +void PhaseSpinButton::setComboboxIndex(int index) { ui->SBA_Combobox->setCurrentIndex(index); } void PhaseSpinButton::onComboboxIndexChanged(int index) { m_indexValue = index; - if (index < 2) { + if(index < 2) { setInSeconds(false); } else { bool isGoingFromDegreesToSeconds = false; - if (!inSeconds()) { + if(!inSeconds()) { double period = 360; m_secondsValue = m_value / frequency(); m_secondsValue /= period; @@ -970,7 +848,7 @@ void PhaseSpinButton::onComboboxIndexChanged(int index) setInSeconds(true); - if (isGoingFromDegreesToSeconds) { + if(isGoingFromDegreesToSeconds) { setValue(m_secondsValue); } else { double value = ui->SBA_LineEdit->text().toDouble(); @@ -983,29 +861,17 @@ void PhaseSpinButton::onComboboxIndexChanged(int index) setValue(m_value); } -void PhaseSpinButton::setInSeconds(bool val) -{ - m_inSeconds = val; -} +void PhaseSpinButton::setInSeconds(bool val) { m_inSeconds = val; } -bool PhaseSpinButton::inSeconds() -{ - return m_inSeconds; -} +bool PhaseSpinButton::inSeconds() { return m_inSeconds; } -void PhaseSpinButton::setSecondsValue(double val) -{ - m_secondsValue = val; -} +void PhaseSpinButton::setSecondsValue(double val) { m_secondsValue = val; } -double PhaseSpinButton::secondsValue() -{ - return m_secondsValue; -} +double PhaseSpinButton::secondsValue() { return m_secondsValue; } void PhaseSpinButton::setFrequency(double val) { - if (inSeconds()) { + if(inSeconds()) { qDebug() << "frequency changed:" << val << "update phase"; updatePhaseAfterFrequenceChanged(val); @@ -1014,15 +880,9 @@ void PhaseSpinButton::setFrequency(double val) m_frequency = val; } -double PhaseSpinButton::frequency() -{ - return m_frequency; -} +double PhaseSpinButton::frequency() { return m_frequency; } -double PhaseSpinButton::value() -{ - return m_value; -} +double PhaseSpinButton::value() { return m_value; } double PhaseSpinButton::changeValueFromDegreesToSeconds(double val) { @@ -1033,14 +893,11 @@ double PhaseSpinButton::changeValueFromDegreesToSeconds(double val) return valueInSeconds; } -int PhaseSpinButton::indexValue() -{ - return m_indexValue; -} +int PhaseSpinButton::indexValue() { return m_indexValue; } void PhaseSpinButton::updatePhaseAfterFrequenceChanged(double val) { - if (!inSeconds()) { + if(!inSeconds()) { return; } @@ -1048,8 +905,7 @@ void PhaseSpinButton::updatePhaseAfterFrequenceChanged(double val) m_value = secondsValue() * period * val; } -double PhaseSpinButton::computeSecondsTransformation(double scale, int index, - double value) +double PhaseSpinButton::computeSecondsTransformation(double scale, int index, double value) { setSecondsValue(value); @@ -1058,11 +914,11 @@ double PhaseSpinButton::computeSecondsTransformation(double scale, int index, double abs_number = qAbs(number); int significant_digits = m_decimal_count; - if (abs_number >= 100) { + if(abs_number >= 100) { significant_digits += 3; - } else if (abs_number >= 10) { + } else if(abs_number >= 10) { significant_digits += 2; - } else if (abs_number >= 1) { + } else if(abs_number >= 1) { significant_digits += 1; } @@ -1072,19 +928,18 @@ double PhaseSpinButton::computeSecondsTransformation(double scale, int index, int full_periods = degreesValue / period; degreesValue -= full_periods * period; - if (value != 0 && degreesValue != 0) { + if(value != 0 && degreesValue != 0) { ui->SBA_Combobox->blockSignals(true); ui->SBA_Combobox->setCurrentIndex(index); - if (index < 2) { + if(index < 2) { setInSeconds(false); } else { setInSeconds(true); } ui->SBA_Combobox->blockSignals(false); - ui->SBA_LineEdit->setText(QString::number(number, 'g', - significant_digits)); + ui->SBA_LineEdit->setText(QString::number(number, 'g', significant_digits)); ui->SBA_LineEdit->setCursorPosition(0); } value = degreesValue; @@ -1097,22 +952,19 @@ void PhaseSpinButton::stepUp() m_is_step_down = false; double current_scale = m_units[ui->SBA_Combobox->currentIndex()].second; double newVal; - double step = inSeconds() ? changeValueFromDegreesToSeconds(45) - : 45; + double step = inSeconds() ? changeValueFromDegreesToSeconds(45) : 45; - if (isInFineMode()) { - step = inSeconds() ? changeValueFromDegreesToSeconds(1) - : 1; + if(isInFineMode()) { + step = inSeconds() ? changeValueFromDegreesToSeconds(1) : 1; } - if (inSeconds()) { + if(inSeconds()) { m_value = secondsValue(); } - newVal = m_value + step; + newVal = m_value + step; - ui->SBA_LineEdit->setText(QString::number(round((newVal * 10) / 10) / - current_scale)); + ui->SBA_LineEdit->setText(QString::number(round((newVal * 10) / 10) / current_scale)); setValue(newVal); } @@ -1121,132 +973,70 @@ void PhaseSpinButton::stepDown() m_is_step_down = true; double current_scale = m_units[ui->SBA_Combobox->currentIndex()].second; double newVal; - double step = inSeconds() ? changeValueFromDegreesToSeconds(45) - : 45; + double step = inSeconds() ? changeValueFromDegreesToSeconds(45) : 45; - if (inSeconds()) { + if(inSeconds()) { m_value = secondsValue(); } - if (isInFineMode()) { - step = inSeconds() ? changeValueFromDegreesToSeconds(1) - : 1; + if(isInFineMode()) { + step = inSeconds() ? changeValueFromDegreesToSeconds(1) : 1; } newVal = m_value - step; - ui->SBA_LineEdit->setText(QString::number(round((newVal * 10) / 10) / - current_scale)); + ui->SBA_LineEdit->setText(QString::number(round((newVal * 10) / 10) / current_scale)); setValue(newVal); } -void PhaseSpinButton::setStep(double step) -{ - m_step = step; -} +void PhaseSpinButton::setStep(double step) { m_step = step; } #ifdef SPINBOX_API -SpinBoxA_API::SpinBoxA_API(SpinBoxA *sba) : - ApiObject(), sba(sba) +SpinBoxA_API::SpinBoxA_API(SpinBoxA *sba) + : ApiObject() + , sba(sba) { ApiObjectManager::getInstance().registerApiObject(this); } -SpinBoxA_API::~SpinBoxA_API() -{ - ApiObjectManager::getInstance().unregisterApiObject(this); -} +SpinBoxA_API::~SpinBoxA_API() { ApiObjectManager::getInstance().unregisterApiObject(this); } -double SpinBoxA_API::value() const -{ - return sba->value(); -} +double SpinBoxA_API::value() const { return sba->value(); } -void SpinBoxA_API::setValue(double value) -{ - sba->setValue(value); -} +void SpinBoxA_API::setValue(double value) { sba->setValue(value); } -double SpinBoxA_API::minValue() const -{ - return sba->minValue(); -} +double SpinBoxA_API::minValue() const { return sba->minValue(); } -void SpinBoxA_API::setMinValue(double value) -{ - sba->setMinValue(value); -} +void SpinBoxA_API::setMinValue(double value) { sba->setMinValue(value); } -double SpinBoxA_API::maxValue() const -{ - return sba->maxValue(); -} +double SpinBoxA_API::maxValue() const { return sba->maxValue(); } -void SpinBoxA_API::setMaxValue(double value) -{ - sba->setMaxValue(value); -} +void SpinBoxA_API::setMaxValue(double value) { sba->setMaxValue(value); } -int SpinBoxA_API::decimalCount() const -{ - return sba->decimalCount(); -} +int SpinBoxA_API::decimalCount() const { return sba->decimalCount(); } -void SpinBoxA_API::setDecimalCount(int count) -{ - sba->setDecimalCount(count); -} +void SpinBoxA_API::setDecimalCount(int count) { sba->setDecimalCount(count); } -bool SpinBoxA_API::isInFineMode() -{ - return sba->isInFineMode(); -} +bool SpinBoxA_API::isInFineMode() { return sba->isInFineMode(); } -void SpinBoxA_API::setFineMode(bool enabled) -{ - sba->setFineMode(enabled); -} +void SpinBoxA_API::setFineMode(bool enabled) { sba->setFineMode(enabled); } -bool SpinBoxA_API::isCircleInverted() const -{ - return sba->isCircleInverted(); -} +bool SpinBoxA_API::isCircleInverted() const { return sba->isCircleInverted(); } -void SpinBoxA_API::invertCircle(bool invert) -{ - sba->invertCircle(invert); -} +void SpinBoxA_API::invertCircle(bool invert) { sba->invertCircle(invert); } -bool SpinBoxA_API::progressShown() const -{ - return sba->progressShown(); -} +bool SpinBoxA_API::progressShown() const { return sba->progressShown(); } -void SpinBoxA_API::showProgress(bool show) -{ - sba->showProgress(show); -} +void SpinBoxA_API::showProgress(bool show) { sba->showProgress(show); } -bool SpinBoxA_API::fineModeAvailable() -{ - return sba->fineModeAvailable(); -} +bool SpinBoxA_API::fineModeAvailable() { return sba->fineModeAvailable(); } -void SpinBoxA_API::setFineModeAvailable(bool available) -{ - sba->setFineModeAvailable(available); -} +void SpinBoxA_API::setFineModeAvailable(bool available) { sba->setFineModeAvailable(available); } -QString SpinBoxA_API::getName() const -{ - return sba->getName(); -} +QString SpinBoxA_API::getName() const { return sba->getName(); } -void SpinBoxA_API::setName(const QString &name) -{ - sba->setName(name); -} +void SpinBoxA_API::setName(const QString &name) { sba->setName(name); } #endif #include "moc_spinbox_a.cpp" diff --git a/gui/src/startstoprangewidget.cpp b/gui/src/startstoprangewidget.cpp index 82a76fd7ef..204f84e7f5 100644 --- a/gui/src/startstoprangewidget.cpp +++ b/gui/src/startstoprangewidget.cpp @@ -19,18 +19,18 @@ */ #include "startstoprangewidget.h" + #include "ui_startstoprangewidget.h" using namespace scopy; -StartStopRangeWidget::StartStopRangeWidget(double min, double max, double minSpan, - bool hasProgressWidget, - QWidget *parent) : - QWidget(parent), - ui(new Ui::StartStopRangeWidget), - minValue(min), - maxValue(max), - minSpan(minSpan) +StartStopRangeWidget::StartStopRangeWidget(double min, double max, double minSpan, bool hasProgressWidget, + QWidget *parent) + : QWidget(parent) + , ui(new Ui::StartStopRangeWidget) + , minValue(min) + , maxValue(max) + , minSpan(minSpan) { ui->setupUi(this); @@ -38,35 +38,17 @@ StartStopRangeWidget::StartStopRangeWidget(double min, double max, double minSpa _setupSignalsAndSlots(); } -StartStopRangeWidget::~StartStopRangeWidget() -{ - delete ui; -} +StartStopRangeWidget::~StartStopRangeWidget() { delete ui; } -double StartStopRangeWidget::getStartValue() const -{ - return start_freq->value(); -} +double StartStopRangeWidget::getStartValue() const { return start_freq->value(); } -void StartStopRangeWidget::setStartValue(double value) -{ - start_freq->setValue(value); -} +void StartStopRangeWidget::setStartValue(double value) { start_freq->setValue(value); } -double StartStopRangeWidget::getStopValue() const -{ - return stop_freq->value(); -} +double StartStopRangeWidget::getStopValue() const { return stop_freq->value(); } -void StartStopRangeWidget::setStopValue(double value) -{ - stop_freq->setValue(value); -} +void StartStopRangeWidget::setStopValue(double value) { stop_freq->setValue(value); } -double StartStopRangeWidget::getCenterValue() const -{ - return center_freq->value(); -} +double StartStopRangeWidget::getCenterValue() const { return center_freq->value(); } void StartStopRangeWidget::insertWidgetIntoLayout(QWidget *widget, int row, int column) { @@ -103,15 +85,15 @@ void StartStopRangeWidget::_onCenterSpanFrequencyChanged() double start = center - (span / 2); double stop = center + (span / 2); - if (QObject::sender() == center_freq) { + if(QObject::sender() == center_freq) { // Center value was changed by the user, so we // check if the span value is valid, if not we // adjust it - if (start < 0) { + if(start < 0) { start = 1; span = (center - start) * 2; stop = center + (span / 2); - } else if (stop > stop_freq->maxValue()) { + } else if(stop > stop_freq->maxValue()) { stop = stop_freq->maxValue(); span = (stop - center) * 2; start = center - (span / 2); @@ -122,11 +104,11 @@ void StartStopRangeWidget::_onCenterSpanFrequencyChanged() // Span value was changed by the user, so we // check if the center value is valid, if not we // adjust it - if (start < 0) { + if(start < 0) { start = 1; center = start + (span / 2); stop = center + (span / 2); - } else if (stop > stop_freq->maxValue()) { + } else if(stop > stop_freq->maxValue()) { stop = stop_freq->maxValue(); center = stop - (span / 2); start = center - (span / 2); @@ -156,34 +138,14 @@ void StartStopRangeWidget::setMinimumValue(double value) void StartStopRangeWidget::_createSpinButtons(bool hasProgressWidget) { // Create spin buttons - start_freq = new ScaleSpinButton({ - {"Hz",1e0}, - {"kHz",1e3}, - {"MHz",1e6} - },tr("Start"), minValue, maxValue, - hasProgressWidget, false, this, - {1, 2.5, 5, 7.5}); - stop_freq = new ScaleSpinButton({ - {"Hz",1e0}, - {"kHz",1e3}, - {"MHz",1e6} - },tr("Stop"), minValue, maxValue, - hasProgressWidget, false, this, - {1, 2.5, 5, 7.5}); - center_freq = new ScaleSpinButton({ - {"Hz",1e0}, - {"kHz",1e3}, - {"MHz",1e6} - },tr("Center"), minValue, maxValue - 1, - hasProgressWidget, false, this, - {1, 2.5, 5, 7.5}); - span_freq = new ScaleSpinButton({ - {"Hz",1e0}, - {"kHz",1e3}, - {"MHz",1e6} - },tr("Span"), minValue, maxValue - 1, - hasProgressWidget, false, this, - {1, 2.5, 5, 7.5}); + start_freq = new ScaleSpinButton({{"Hz", 1e0}, {"kHz", 1e3}, {"MHz", 1e6}}, tr("Start"), minValue, maxValue, + hasProgressWidget, false, this, {1, 2.5, 5, 7.5}); + stop_freq = new ScaleSpinButton({{"Hz", 1e0}, {"kHz", 1e3}, {"MHz", 1e6}}, tr("Stop"), minValue, maxValue, + hasProgressWidget, false, this, {1, 2.5, 5, 7.5}); + center_freq = new ScaleSpinButton({{"Hz", 1e0}, {"kHz", 1e3}, {"MHz", 1e6}}, tr("Center"), minValue, + maxValue - 1, hasProgressWidget, false, this, {1, 2.5, 5, 7.5}); + span_freq = new ScaleSpinButton({{"Hz", 1e0}, {"kHz", 1e3}, {"MHz", 1e6}}, tr("Span"), minValue, maxValue - 1, + hasProgressWidget, false, this, {1, 2.5, 5, 7.5}); // Set limits and initial values start_freq->setValue(1000); @@ -202,12 +164,11 @@ void StartStopRangeWidget::_createSpinButtons(bool hasProgressWidget) void StartStopRangeWidget::_setupSignalsAndSlots() { - connect(start_freq, &ScaleSpinButton::valueChanged, - this, &StartStopRangeWidget::_onStartStopFrequencyChanged); - connect(stop_freq, &ScaleSpinButton::valueChanged, - this, &StartStopRangeWidget::_onStartStopFrequencyChanged); - connect(center_freq, &ScaleSpinButton::valueChanged, - this, &StartStopRangeWidget::_onCenterSpanFrequencyChanged); - connect(span_freq, &ScaleSpinButton::valueChanged, - this, &StartStopRangeWidget::_onCenterSpanFrequencyChanged); + connect(start_freq, &ScaleSpinButton::valueChanged, this, &StartStopRangeWidget::_onStartStopFrequencyChanged); + connect(stop_freq, &ScaleSpinButton::valueChanged, this, &StartStopRangeWidget::_onStartStopFrequencyChanged); + connect(center_freq, &ScaleSpinButton::valueChanged, this, + &StartStopRangeWidget::_onCenterSpanFrequencyChanged); + connect(span_freq, &ScaleSpinButton::valueChanged, this, &StartStopRangeWidget::_onCenterSpanFrequencyChanged); } + +#include "moc_startstoprangewidget.cpp" diff --git a/gui/src/stylehelper.cpp b/gui/src/stylehelper.cpp index 534cdcb1b3..85567a85f2 100644 --- a/gui/src/stylehelper.cpp +++ b/gui/src/stylehelper.cpp @@ -1,64 +1,64 @@ #include "stylehelper.h" -#include + #include "ui_spinbox_a.h" +#include + +#include #include -#include #include +#include #include -#include #include -#include +#include #include using namespace scopy; -StyleHelper* StyleHelper::pinstance_{nullptr}; +StyleHelper *StyleHelper::pinstance_{nullptr}; -StyleHelper::StyleHelper(QObject *parent) -{ -} +StyleHelper::StyleHelper(QObject *parent) {} StyleHelper *StyleHelper::GetInstance() { - if (pinstance_ == nullptr) - { + if(pinstance_ == nullptr) { pinstance_ = new StyleHelper(QApplication::instance()); // singleton has the app as parent } return pinstance_; } -StyleHelper::~StyleHelper() -{ - -} +StyleHelper::~StyleHelper() {} -void StyleHelper::initColorMap() { +void StyleHelper::initColorMap() +{ auto sh = StyleHelper::GetInstance(); - sh->colorMap.insert("CH0", "#FF7200"); - sh->colorMap.insert("CH1", "#9013FE"); - sh->colorMap.insert("CH2", "#27B34F"); - sh->colorMap.insert("CH3", "#F8E71C"); - sh->colorMap.insert("CH4", "#4A64FF"); - sh->colorMap.insert("CH5", "#02BCD4"); - sh->colorMap.insert("CH6", "#F44336"); - sh->colorMap.insert("CH7", "#F5A623"); - sh->colorMap.insert("ScopyBlue", "#4A64FF"); - sh->colorMap.insert("UIElementBackground", "#272730"); - sh->colorMap.insert("UIElementHighlight", "#373740"); - sh->colorMap.insert("LabelText", "#FFFFFF"); - sh->colorMap.insert("ScopyBackground", "#141416"); - sh->colorMap.insert("ScopyBlueHover", "#4A34FF"); - sh->colorMap.insert("ScopyBlueSelected", "#3324B1"); -} - -QString StyleHelper::getColor(QString id) { + sh->colorMap.insert("CH0", "#FF7200"); + sh->colorMap.insert("CH1", "#9013FE"); + sh->colorMap.insert("CH2", "#27B34F"); + sh->colorMap.insert("CH3", "#F8E71C"); + sh->colorMap.insert("CH4", "#4A64FF"); + sh->colorMap.insert("CH5", "#02BCD4"); + sh->colorMap.insert("CH6", "#F44336"); + sh->colorMap.insert("CH7", "#F5A623"); + sh->colorMap.insert("ScopyBlue", "#4A64FF"); + sh->colorMap.insert("UIElementBackground", "#272730"); + sh->colorMap.insert("UIElementHighlight", "#373740"); + sh->colorMap.insert("LabelText", "#FFFFFF"); + sh->colorMap.insert("ScopyBackground", "#141416"); + sh->colorMap.insert("ScopyBlueHover", "#4A34FF"); + sh->colorMap.insert("ScopyBlueSelected", "#3324B1"); +} + +QString StyleHelper::getColor(QString id) +{ auto sh = StyleHelper::GetInstance(); return sh->colorMap[id]; } -void StyleHelper::SquareToggleButtonWithIcon(QPushButton *btn, QString objectName, bool checkable) { - if(!objectName.isEmpty()) btn->setObjectName(objectName); +void StyleHelper::SquareToggleButtonWithIcon(QPushButton *btn, QString objectName, bool checkable) +{ + if(!objectName.isEmpty()) + btn->setObjectName(objectName); btn->setCheckable(checkable); btn->setChecked(false); QString style = QString(R"css( @@ -79,13 +79,14 @@ void StyleHelper::SquareToggleButtonWithIcon(QPushButton *btn, QString objectNam } )css"); - btn->setStyleSheet(style); - btn->setIconSize(QSize(48,48)); + btn->setStyleSheet(style); + btn->setIconSize(QSize(48, 48)); } - -void StyleHelper::BlueGrayButton(QPushButton *btn, QString objectName) { - if(!objectName.isEmpty()) btn->setObjectName(objectName); +void StyleHelper::BlueGrayButton(QPushButton *btn, QString objectName) +{ + if(!objectName.isEmpty()) + btn->setObjectName(objectName); btn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); btn->setFixedHeight(48); QString style = QString(R"css( @@ -109,7 +110,7 @@ void StyleHelper::BlueGrayButton(QPushButton *btn, QString objectName) { )css"); btn->setStyleSheet(style); - btn->setIconSize(QSize(48,48)); + btn->setIconSize(QSize(48, 48)); } void StyleHelper::MeasurementPanelLabel(MeasurementLabel *w, QString objectName) @@ -117,7 +118,7 @@ void StyleHelper::MeasurementPanelLabel(MeasurementLabel *w, QString objectName) QString style = QString(R"css( color: &&colorname&&; )css"); - style.replace(QString("&&colorname&&"),w->m_color.name()); + style.replace(QString("&&colorname&&"), w->m_color.name()); w->m_nameLabel->setStyleSheet(style); w->m_valueLabel->setStyleSheet(style); } @@ -131,13 +132,13 @@ void StyleHelper::StatsPanelLabel(StatsLabel *w, QString objectName) font-style: normal; color: &&colorname&&; )css"); - style.replace(QString("&&colorname&&"),w->m_color.name()); + style.replace(QString("&&colorname&&"), w->m_color.name()); w->m_nameLabel->setStyleSheet(style); style = QString(R"css(e font-size: 12px; )css"); - style.replace(QString("&&colorname&&"),w->m_color.name()); + style.replace(QString("&&colorname&&"), w->m_color.name()); w->m_avgLabel->setStyleSheet(style); w->m_minLabel->setStyleSheet(style); w->m_maxLabel->setStyleSheet(style); @@ -145,36 +146,35 @@ void StyleHelper::StatsPanelLabel(StatsLabel *w, QString objectName) void StyleHelper::MeasurementSelectorItemWidget(QString iconPath, MeasurementSelectorItem *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); - QHBoxLayout *lay = dynamic_cast(w->layout()); + if(!objectName.isEmpty()) + w->setObjectName(objectName); + QHBoxLayout *lay = dynamic_cast(w->layout()); Q_ASSERT(lay); lay->setMargin(0); lay->setSpacing(0); - w->m_icon->setPixmap(QPixmap(iconPath)); - w->m_icon->setFixedSize(24,24); + w->m_icon->setFixedSize(24, 24); - w->m_name->setContentsMargins(5,0,0,0); + w->m_name->setContentsMargins(5, 0, 0, 0); StyleHelper::MenuMediumLabel(w->m_name); -// // Add "M" letter on top of combobox -// QWidget *msrStack = new QWidget(w); -// QStackedLayout *msr_layout = new QStackedLayout(w); -// msrStack->setLayout(msr_layout); -// lay->replaceWidget(w->m_measureCheckbox, msrStack); -// auto measureLabel = new QLabel("M", msrStack); -// StyleHelper::MenuSmallLabel(measureLabel); -// measureLabel->setAttribute(Qt::WA_TransparentForMouseEvents); -// msr_layout->setStackingMode(QStackedLayout::StackAll); -// msr_layout->addWidget(measureLabel); -// msr_layout->addWidget(w->m_measureCheckbox); - -// auto statsLabel = new QLabel(" S", w->m_statsCheckbox); -// statsLabel->setFixedSize(18,18); -// StyleHelper::MenuSmallLabel(statsLabel); + // // Add "M" letter on top of combobox + // QWidget *msrStack = new QWidget(w); + // QStackedLayout *msr_layout = new QStackedLayout(w); + // msrStack->setLayout(msr_layout); + // lay->replaceWidget(w->m_measureCheckbox, msrStack); + // auto measureLabel = new QLabel("M", msrStack); + // StyleHelper::MenuSmallLabel(measureLabel); + // measureLabel->setAttribute(Qt::WA_TransparentForMouseEvents); + // msr_layout->setStackingMode(QStackedLayout::StackAll); + // msr_layout->addWidget(measureLabel); + // msr_layout->addWidget(w->m_measureCheckbox); + // auto statsLabel = new QLabel(" S", w->m_statsCheckbox); + // statsLabel->setFixedSize(18,18); + // StyleHelper::MenuSmallLabel(statsLabel); } void StyleHelper::TimePlotHDivInfo(QLabel *w, QString objectName) @@ -184,22 +184,24 @@ void StyleHelper::TimePlotHDivInfo(QLabel *w, QString objectName) font-weight: 500; font-size: 12px; )css"); - style.replace("&&ScopyBlue&&",StyleHelper::getColor("ScopyBlue")); + style.replace("&&ScopyBlue&&", StyleHelper::getColor("ScopyBlue")); w->setStyleSheet(style); - } -void StyleHelper::TimePlotSamplingInfo(QLabel *w, QString objectName) { +void StyleHelper::TimePlotSamplingInfo(QLabel *w, QString objectName) +{ QString style = QString(R"css( color: rgba(192,192,192,255); font-weight: 400; font-size: 12px; )css"); - style.replace("&&LabelText&&",StyleHelper::getColor("LabelText")); + style.replace("&&LabelText&&", StyleHelper::getColor("LabelText")); w->setStyleSheet(style); } -void StyleHelper::BlueButton(QPushButton *btn, QString objectName) { - if(!objectName.isEmpty()) btn->setObjectName(objectName); +void StyleHelper::BlueButton(QPushButton *btn, QString objectName) +{ + if(!objectName.isEmpty()) + btn->setObjectName(objectName); btn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); btn->setFixedHeight(36); QString style = QString(R"css( @@ -227,13 +229,15 @@ void StyleHelper::BlueButton(QPushButton *btn, QString objectName) { )css"); - style.replace("&&ScopyBlue&&",StyleHelper::getColor("ScopyBlue")); + style.replace("&&ScopyBlue&&", StyleHelper::getColor("ScopyBlue")); btn->setStyleSheet(style); - btn->setIconSize(QSize(48,48)); + btn->setIconSize(QSize(48, 48)); } -void StyleHelper::SmallBlueButton(QPushButton *btn, QString objectName) { - if(!objectName.isEmpty()) btn->setObjectName(objectName); +void StyleHelper::SmallBlueButton(QPushButton *btn, QString objectName) +{ + if(!objectName.isEmpty()) + btn->setObjectName(objectName); btn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); btn->setFixedHeight(24); QString style = QString(R"css( @@ -261,13 +265,15 @@ void StyleHelper::SmallBlueButton(QPushButton *btn, QString objectName) { )css"); - style.replace("&&ScopyBlue&&",StyleHelper::getColor("ScopyBlue")); + style.replace("&&ScopyBlue&&", StyleHelper::getColor("ScopyBlue")); btn->setStyleSheet(style); - btn->setIconSize(QSize(48,48)); + btn->setIconSize(QSize(48, 48)); } -void StyleHelper::BlueSquareCheckbox(QCheckBox *chk, QString objectName) { - if(!objectName.isEmpty()) chk->setObjectName(objectName); +void StyleHelper::BlueSquareCheckbox(QCheckBox *chk, QString objectName) +{ + if(!objectName.isEmpty()) + chk->setObjectName(objectName); QString style = QString(R"css( QCheckBox { spacing: 8px; @@ -285,12 +291,14 @@ void StyleHelper::BlueSquareCheckbox(QCheckBox *chk, QString objectName) { QCheckBox::indicator:unchecked { background-color: black; } QCheckBox::indicator:checked { background-color: rgb(74,100,255); } )css"); - chk->setStyleSheet(style); + chk->setStyleSheet(style); } -void StyleHelper::ColoredCircleCheckbox(QCheckBox *chk, QColor color, QString objectName) { - if(!objectName.isEmpty()) chk->setObjectName(objectName); - chk->setFixedSize(16,16); +void StyleHelper::ColoredCircleCheckbox(QCheckBox *chk, QColor color, QString objectName) +{ + if(!objectName.isEmpty()) + chk->setObjectName(objectName); + chk->setFixedSize(16, 16); QString style = QString(R"css( QCheckBox { width:16px; @@ -307,14 +315,16 @@ void StyleHelper::ColoredCircleCheckbox(QCheckBox *chk, QColor color, QString ob QCheckBox::indicator:unchecked { background-color: &&UIElementBackground&&; } QCheckBox::indicator:checked { background-color: &&colorname&&; } )css"); - style.replace("&&colorname&&",color.name()); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); + style.replace("&&colorname&&", color.name()); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); chk->setStyleSheet(style); } -void StyleHelper::CollapseCheckbox(QCheckBox *chk, QString objectName) { - if(!objectName.isEmpty()) chk->setObjectName(objectName); - chk->setFixedSize(16,16); +void StyleHelper::CollapseCheckbox(QCheckBox *chk, QString objectName) +{ + if(!objectName.isEmpty()) + chk->setObjectName(objectName); + chk->setFixedSize(16, 16); QString style = QString(R"css( QCheckBox { width:16px; @@ -337,13 +347,15 @@ void StyleHelper::CollapseCheckbox(QCheckBox *chk, QString objectName) { background-color: transparent; } )css"); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); chk->setStyleSheet(style); } -void StyleHelper::ColoredSquareCheckbox(QCheckBox *chk, QColor color, QString objectName) { - if(!objectName.isEmpty()) chk->setObjectName(objectName); - chk->setFixedSize(16,16); +void StyleHelper::ColoredSquareCheckbox(QCheckBox *chk, QColor color, QString objectName) +{ + if(!objectName.isEmpty()) + chk->setObjectName(objectName); + chk->setFixedSize(16, 16); QString style = QString(R"css( QCheckBox { width:16px; @@ -360,16 +372,18 @@ void StyleHelper::ColoredSquareCheckbox(QCheckBox *chk, QColor color, QString ob QCheckBox::indicator:unchecked { background-color: &&UIElementBackground&&; } QCheckBox::indicator:checked { background-color: &&colorname&&; } )css"); - style.replace("&&colorname&&",color.name()); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); + style.replace("&&colorname&&", color.name()); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); chk->setStyleSheet(style); } -void StyleHelper::MenuMediumLabel(QLabel *lbl, QString objectName) { - if(!objectName.isEmpty()) lbl->setObjectName(objectName); +void StyleHelper::MenuMediumLabel(QLabel *lbl, QString objectName) +{ + if(!objectName.isEmpty()) + lbl->setObjectName(objectName); lbl->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); lbl->setMinimumWidth(80); -// lbl->setMaximumWidth(80); + // lbl->setMaximumWidth(80); QString style = QString(R"css( QLabel { color: white; @@ -381,11 +395,13 @@ void StyleHelper::MenuMediumLabel(QLabel *lbl, QString objectName) { lbl->setStyleSheet(style); } -void StyleHelper::MenuControlButton(QPushButton *btn, QString objectName, bool checkable) { - if(!objectName.isEmpty()) btn->setObjectName(objectName); +void StyleHelper::MenuControlButton(QPushButton *btn, QString objectName, bool checkable) +{ + if(!objectName.isEmpty()) + btn->setObjectName(objectName); btn->setCheckable(checkable); btn->setChecked(false); - btn->setFixedSize(32,16); + btn->setFixedSize(32, 16); QString style = QString(R"css( QPushButton { background-color: transparent; @@ -403,23 +419,23 @@ void StyleHelper::MenuControlButton(QPushButton *btn, QString objectName, bool c border-image: url(:/gui/icons/setup_btn_checked.svg) } )css"); - btn->setStyleSheet(style); - btn->setIconSize(QSize(48,48)); + btn->setStyleSheet(style); + btn->setIconSize(QSize(48, 48)); } void StyleHelper::MenuControlWidget(QWidget *w, QColor color, QString objectName) { QString style = "scopy--MenuControlButton {background-color: &&UIElementBackground&&; border-radius: 2px;}" - "scopy--MenuControlButton[selected=true] { background-color:&&colorname&&;}"; - style.replace("&&colorname&&",color.name()); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); + "scopy--MenuControlButton[selected=true] { background-color:&&colorname&&;}"; + style.replace("&&colorname&&", color.name()); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); w->setStyleSheet(style); } - void StyleHelper::MenuComboBox(QComboBox *cb, QString objectName) { - if(!objectName.isEmpty()) cb->setObjectName(objectName); + if(!objectName.isEmpty()) + cb->setObjectName(objectName); cb->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); QString style = QString(R"css( QWidget { @@ -467,14 +483,15 @@ QComboBox::indicator { } )css"); - style.replace("&&ScopyBackground&&",StyleHelper::getColor("ScopyBackground")); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); + style.replace("&&ScopyBackground&&", StyleHelper::getColor("ScopyBackground")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); cb->setStyleSheet(style); } void StyleHelper::MenuSmallLabel(QLabel *m_lbl, QString objectName) { - if(!objectName.isEmpty()) m_lbl->setObjectName(objectName); + if(!objectName.isEmpty()) + m_lbl->setObjectName(objectName); m_lbl->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); QString style = QString(R"css( @@ -496,21 +513,23 @@ void StyleHelper::MenuSmallLabel(QLabel *m_lbl, QString objectName) void StyleHelper::MenuComboWidget(QWidget *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); + if(!objectName.isEmpty()) + w->setObjectName(objectName); w->setFixedHeight(72); - w->layout()->setContentsMargins(10,2,10,2); + w->layout()->setContentsMargins(10, 2, 10, 2); QString style = QString(R"css( scopy--MenuComboWidget {background-color: &&UIElementBackground&&; border-radius: 4px; } )css"); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); w->setStyleSheet(style); } void StyleHelper::MenuLargeLabel(QLabel *m_lbl, QString objectName) { - if(!objectName.isEmpty()) m_lbl->setObjectName(objectName); + if(!objectName.isEmpty()) + m_lbl->setObjectName(objectName); m_lbl->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); QString style = QString(R"css( @@ -529,38 +548,41 @@ void StyleHelper::MenuLargeLabel(QLabel *m_lbl, QString objectName) void StyleHelper::MenuHeaderLine(QFrame *m_line, QPen pen, QString objectName) { - if(!objectName.isEmpty()) m_line->setObjectName(objectName); + if(!objectName.isEmpty()) + m_line->setObjectName(objectName); m_line->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_line->setFrameShape(QFrame::HLine); m_line->setFrameShadow(QFrame::Plain); m_line->setFixedHeight(2); -// m_line->setLineWidth(1); - + // m_line->setLineWidth(1); QString style = QString(R"css( QFrame { border: 2px solid &&colorname&&; } )css"); - style.replace("&&colorname&&",pen.color().name()); + style.replace("&&colorname&&", pen.color().name()); m_line->setStyleSheet(style); } -void StyleHelper::MenuHeaderWidget(QWidget *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); +void StyleHelper::MenuHeaderWidget(QWidget *w, QString objectName) +{ + if(!objectName.isEmpty()) + w->setObjectName(objectName); w->setFixedHeight(48); - w->layout()->setContentsMargins(10,2,10,2); + w->layout()->setContentsMargins(10, 2, 10, 2); QString style = QString(R"css( scopy--MenuHeaderWidget {background-color: &&UIElementBackground&&; border-radius: 4px; } )css"); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); w->setStyleSheet(style); } -void StyleHelper::MenuSpinComboBox(QComboBox *w, QString objectName) { - MenuComboBox(w,objectName); +void StyleHelper::MenuSpinComboBox(QComboBox *w, QString objectName) +{ + MenuComboBox(w, objectName); QString style = QString(R"css( QComboBox { font-size: 12px; @@ -571,29 +593,30 @@ void StyleHelper::MenuSpinComboBox(QComboBox *w, QString objectName) { } )css"); - style.replace("&&ScopyBackground&&",StyleHelper::getColor("ScopyBackground")); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); + style.replace("&&ScopyBackground&&", StyleHelper::getColor("ScopyBackground")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); w->setStyleSheet(style); } void StyleHelper::MenuOnOffSwitch(QWidget *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); + if(!objectName.isEmpty()) + w->setObjectName(objectName); QString style = QString(R"css( scopy--MenuOnOffSwitch { background-color: transparent; } )css"); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); - style.replace("&&ScopyBlue&&",StyleHelper::getColor("ScopyBlue")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); + style.replace("&&ScopyBlue&&", StyleHelper::getColor("ScopyBlue")); w->setStyleSheet(style); } - void StyleHelper::MenuBigSwitchButton(CustomSwitch *w, QString objectName) { // This needs to be redone ... - if(!objectName.isEmpty()) w->setObjectName(objectName); + if(!objectName.isEmpty()) + w->setObjectName(objectName); QString style = QString(R"css( QPushButton { min-height: 30px; @@ -653,14 +676,15 @@ QLabel#off:disabled { color: rgba(255,255,255,51); } )css"); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); - style.replace("&&ScopyBlue&&",StyleHelper::getColor("ScopyBlue")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); + style.replace("&&ScopyBlue&&", StyleHelper::getColor("ScopyBlue")); w->setStyleSheet(style); } void StyleHelper::MenuLineEdit(QLineEdit *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); + if(!objectName.isEmpty()) + w->setObjectName(objectName); QString style = QString(R"css( QLineEdit { background-color: transparent; @@ -671,41 +695,43 @@ QLineEdit { padding: 2px; } )css"); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); - style.replace("&&ScopyBlue&&",StyleHelper::getColor("ScopyBlue")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); + style.replace("&&ScopyBlue&&", StyleHelper::getColor("ScopyBlue")); w->setStyleSheet(style); } void StyleHelper::MenuLineEditWidget(QWidget *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); + if(!objectName.isEmpty()) + w->setObjectName(objectName); QString style = QString(R"css( scopy--MenuLineEdit { background-color: transparent; } )css"); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); - style.replace("&&ScopyBlue&&",StyleHelper::getColor("ScopyBlue")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); + style.replace("&&ScopyBlue&&", StyleHelper::getColor("ScopyBlue")); w->setStyleSheet(style); } void StyleHelper::MenuBigSwitch(QWidget *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); + if(!objectName.isEmpty()) + w->setObjectName(objectName); QString style = QString(R"css( scopy--MenuBigSwitch { background-color: transparent; } )css"); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); - style.replace("&&ScopyBlue&&",StyleHelper::getColor("ScopyBlue")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); + style.replace("&&ScopyBlue&&", StyleHelper::getColor("ScopyBlue")); w->setStyleSheet(style); } - void StyleHelper::MenuCollapseSection(QWidget *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); + if(!objectName.isEmpty()) + w->setObjectName(objectName); /// ???? QString style = QString(R"css( @@ -714,15 +740,15 @@ QWidget { } )css"); /// ???? - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); - style.replace("&&ScopyBlue&&",StyleHelper::getColor("ScopyBlue")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); + style.replace("&&ScopyBlue&&", StyleHelper::getColor("ScopyBlue")); w->setStyleSheet(style); } - - -void StyleHelper::MenuSpinBox(SpinBoxA *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); +void StyleHelper::MenuSpinBox(SpinBoxA *w, QString objectName) +{ + if(!objectName.isEmpty()) + w->setObjectName(objectName); QString style = QString(R"css( scopy--SpinBoxA { @@ -782,28 +808,31 @@ scopy--SpinBoxA QDial#SBA_CompletionCircle { color: &&ScopyBlue&&; } )css"); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); - style.replace("&&ScopyBlue&&",StyleHelper::getColor("ScopyBlue")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); + style.replace("&&ScopyBlue&&", StyleHelper::getColor("ScopyBlue")); w->setStyleSheet(style); - MenuSpinComboBox(w->ui->SBA_Combobox,""); // Should this be refactored ? + MenuSpinComboBox(w->ui->SBA_Combobox, ""); // Should this be refactored ? } - -void StyleHelper::MenuSectionWidget(QWidget *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); - w->layout()->setContentsMargins(10,10,10,10); +void StyleHelper::MenuSectionWidget(QWidget *w, QString objectName) +{ + if(!objectName.isEmpty()) + w->setObjectName(objectName); + w->layout()->setContentsMargins(10, 10, 10, 10); QString style = QString(R"css( scopy--MenuSectionWidget {background-color: &&UIElementBackground&&; border-radius: 4px; margin-bottom: 3px; } )css"); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); w->setStyleSheet(style); } -void StyleHelper::BlueIconButton(QPushButton *w, QIcon icon, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); +void StyleHelper::BlueIconButton(QPushButton *w, QIcon icon, QString objectName) +{ + if(!objectName.isEmpty()) + w->setObjectName(objectName); int size = 30; w->setIcon(icon); w->setIconSize(QSize(size, size)); @@ -822,40 +851,43 @@ void StyleHelper::BlueIconButton(QPushButton *w, QIcon icon, QString objectName) QPushButton:pressed { background-color: &&ScopyBlueSelected&&; } QPushButton:disabled { background-color: grey; } )css"); - style.replace("&&ScopyBlue&&",StyleHelper::getColor("ScopyBlue")); - style.replace("&&LabelText&&",StyleHelper::getColor("LabelText")); - style.replace("&&ScopyBlueHover&&",StyleHelper::getColor("ScopyBlueHover")); - style.replace("&&ScopyBlueSelected&&",StyleHelper::getColor("ScopyBlueSelected")); + style.replace("&&ScopyBlue&&", StyleHelper::getColor("ScopyBlue")); + style.replace("&&LabelText&&", StyleHelper::getColor("LabelText")); + style.replace("&&ScopyBlueHover&&", StyleHelper::getColor("ScopyBlueHover")); + style.replace("&&ScopyBlueSelected&&", StyleHelper::getColor("ScopyBlueSelected")); w->setStyleSheet(style); } void StyleHelper::BackgroundPage(QWidget *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); + if(!objectName.isEmpty()) + w->setObjectName(objectName); QString style = QString(R"css( .QWidget { background-color: &&ScopyBackground&&; } )css"); - style.replace("&&ScopyBackground&&",StyleHelper::getColor("ScopyBackground")); + style.replace("&&ScopyBackground&&", StyleHelper::getColor("ScopyBackground")); w->setStyleSheet(style); } void StyleHelper::BackgroundWidget(QWidget *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); + if(!objectName.isEmpty()) + w->setObjectName(objectName); QString style = QString(R"css( QWidget { background-color: &&UIElementBackground&&; } )css"); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); w->setStyleSheet(style); } void StyleHelper::TabWidgetLabel(QLabel *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); + if(!objectName.isEmpty()) + w->setObjectName(objectName); QString style = QString(R"css( QLabel { font-weight: bold; @@ -867,7 +899,8 @@ void StyleHelper::TabWidgetLabel(QLabel *w, QString objectName) void StyleHelper::TabWidgetEastMenu(QTabWidget *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); + if(!objectName.isEmpty()) + w->setObjectName(objectName); w->setTabPosition(QTabWidget::TabPosition::East); QString style = QString(R"css( QTabWidget::tab-bar { left: 0; } @@ -891,30 +924,19 @@ void StyleHelper::TabWidgetEastMenu(QTabWidget *w, QString objectName) width: 25px; } )css"); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); - style.replace("&&UIElementHighlight&&",StyleHelper::getColor("UIElementHighlight")); - style.replace("&&ScopyBlue&&",StyleHelper::getColor("ScopyBlue")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); + style.replace("&&UIElementHighlight&&", StyleHelper::getColor("UIElementHighlight")); + style.replace("&&ScopyBlue&&", StyleHelper::getColor("ScopyBlue")); w->tabBar()->setStyleSheet(style); } -void StyleHelper::MenuComboLabel(QLabel *w, QString objectName) { - StyleHelper::MenuSmallLabel(w, objectName); -} +void StyleHelper::MenuComboLabel(QLabel *w, QString objectName) { StyleHelper::MenuSmallLabel(w, objectName); } -void StyleHelper::MenuHeaderLabel(QLabel *w, QString objectName) -{ - StyleHelper::MenuLargeLabel(w, objectName); -} +void StyleHelper::MenuHeaderLabel(QLabel *w, QString objectName) { StyleHelper::MenuLargeLabel(w, objectName); } -void StyleHelper::MenuControlLabel(QLabel *w, QString objectName) -{ - StyleHelper::MenuMediumLabel(w, objectName); -} +void StyleHelper::MenuControlLabel(QLabel *w, QString objectName) { StyleHelper::MenuMediumLabel(w, objectName); } -void StyleHelper::MenuOnOffSwitchLabel(QLabel *w, QString objectName) -{ - StyleHelper::MenuSmallLabel(w, objectName); -} +void StyleHelper::MenuOnOffSwitchLabel(QLabel *w, QString objectName) { StyleHelper::MenuSmallLabel(w, objectName); } void StyleHelper::MenuCollapseHeaderLabel(QLabel *w, QString objectName) { @@ -923,23 +945,27 @@ void StyleHelper::MenuCollapseHeaderLabel(QLabel *w, QString objectName) void StyleHelper::MenuOnOffSwitchButton(SmallOnOffSwitch *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); - + if(!objectName.isEmpty()) + w->setObjectName(objectName); } -void StyleHelper::OverlayMenu(QWidget *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); +void StyleHelper::OverlayMenu(QWidget *w, QString objectName) +{ + if(!objectName.isEmpty()) + w->setObjectName(objectName); QString style = QString(R"css( .QWidget { background-color: &&UIElementBackground&&; border-radius: 4px; })css"); - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); w->setStyleSheet(style); } -void StyleHelper::TutorialChapterTitleLabel(QLabel *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); +void StyleHelper::TutorialChapterTitleLabel(QLabel *w, QString objectName) +{ + if(!objectName.isEmpty()) + w->setObjectName(objectName); QString style = QString(R"css( QLabel { font-weight: bold; @@ -950,8 +976,10 @@ void StyleHelper::TutorialChapterTitleLabel(QLabel *w, QString objectName) { w->setStyleSheet(style); } -void StyleHelper::DeviceIconBackgroundShadow(QAbstractButton *w, QString objectName) { - if (!objectName.isEmpty()) w->setObjectName(objectName); +void StyleHelper::DeviceIconBackgroundShadow(QAbstractButton *w, QString objectName) +{ + if(!objectName.isEmpty()) + w->setObjectName(objectName); QString style = QString(R"css( QAbstractButton[selected=true] { @@ -963,8 +991,10 @@ void StyleHelper::DeviceIconBackgroundShadow(QAbstractButton *w, QString objectN w->setStyleSheet(style); } -void StyleHelper::FrameBackgroundShadow(QFrame *w, QString objectName) { - if (!objectName.isEmpty()) w->setObjectName(objectName); +void StyleHelper::FrameBackgroundShadow(QFrame *w, QString objectName) +{ + if(!objectName.isEmpty()) + w->setObjectName(objectName); QString style = QString(R"css( .QFrame[selected=true] { @@ -974,12 +1004,14 @@ void StyleHelper::FrameBackgroundShadow(QFrame *w, QString objectName) { )css"); } -void StyleHelper::HoverWidget(QWidget *w, bool draggable, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); +void StyleHelper::HoverWidget(QWidget *w, bool draggable, QString objectName) +{ + if(!objectName.isEmpty()) + w->setObjectName(objectName); w->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); QString style; - if (draggable) { + if(draggable) { style = QString(R"css( .QWidget { background-color: transparent; @@ -991,12 +1023,16 @@ void StyleHelper::HoverWidget(QWidget *w, bool draggable, QString objectName) { } )css"); } - style.replace("&&UIElementBackground&&",StyleHelper::getColor("UIElementBackground")); + style.replace("&&UIElementBackground&&", StyleHelper::getColor("UIElementBackground")); w->setStyleSheet(style); } -void StyleHelper::TransparentWidget(QWidget *w, QString objectName) { - if(!objectName.isEmpty()) w->setObjectName(objectName); +void StyleHelper::TransparentWidget(QWidget *w, QString objectName) +{ + if(!objectName.isEmpty()) + w->setObjectName(objectName); QString style = QString(R"css(background-color: transparent;)css"); w->setStyleSheet(style); } + +#include "moc_stylehelper.cpp" diff --git a/gui/src/subsection_separator.cpp b/gui/src/subsection_separator.cpp index 32b0920575..940146df30 100644 --- a/gui/src/subsection_separator.cpp +++ b/gui/src/subsection_separator.cpp @@ -1,12 +1,12 @@ +#include "subsection_separator.hpp" + #include "ui_subsection_separator.h" #include -#include "subsection_separator.hpp" - using namespace scopy::gui; -SubsectionSeparator::SubsectionSeparator(QWidget* parent) +SubsectionSeparator::SubsectionSeparator(QWidget *parent) : QWidget(parent) , m_ui(new Ui::SubsectionSeparator) { @@ -17,7 +17,7 @@ SubsectionSeparator::SubsectionSeparator(QWidget* parent) [=](bool toggled) { m_ui->widgetSubsectionContent->setVisible(toggled); }); } -SubsectionSeparator::SubsectionSeparator(const QString& text, const bool buttonVisible, QWidget* parent) +SubsectionSeparator::SubsectionSeparator(const QString &text, const bool buttonVisible, QWidget *parent) : SubsectionSeparator(parent) { setLabel(text); @@ -26,7 +26,7 @@ SubsectionSeparator::SubsectionSeparator(const QString& text, const bool buttonV SubsectionSeparator::~SubsectionSeparator() { delete m_ui; } -QPushButton* SubsectionSeparator::getButton() { return m_ui->btnSubsectionSeparator; } +QPushButton *SubsectionSeparator::getButton() { return m_ui->btnSubsectionSeparator; } void SubsectionSeparator::setButtonVisible(bool buttonVisible) { @@ -37,17 +37,16 @@ bool SubsectionSeparator::getButtonChecked() { return m_ui->btnSubsectionSeparat void SubsectionSeparator::setButtonChecked(bool checked) { m_ui->btnSubsectionSeparator->setChecked(checked); } -QLabel* SubsectionSeparator::getLabel() { return m_ui->lblSubsectionSeparator; } +QLabel *SubsectionSeparator::getLabel() { return m_ui->lblSubsectionSeparator; } -void SubsectionSeparator::setLabel(const QString& text) { m_ui->lblSubsectionSeparator->setText(text); } +void SubsectionSeparator::setLabel(const QString &text) { m_ui->lblSubsectionSeparator->setText(text); } void SubsectionSeparator::setLabelVisible(bool visible) { m_ui->lblSubsectionSeparator->setVisible(visible); } void SubsectionSeparator::setLineVisible(bool visible) { m_ui->lineSubsectionSeparator->setVisible(visible); } -void SubsectionSeparator::setContent(QWidget* content) { m_ui->vLayoutContent->addWidget(content); } +void SubsectionSeparator::setContent(QWidget *content) { m_ui->vLayoutContent->addWidget(content); } -QWidget* SubsectionSeparator::getContentWidget() -{ - return m_ui->widgetSubsectionContent; -} +QWidget *SubsectionSeparator::getContentWidget() { return m_ui->widgetSubsectionContent; } + +#include "moc_subsection_separator.cpp" diff --git a/gui/src/symbol.cpp b/gui/src/symbol.cpp index 86d75b6df3..2867077fb2 100644 --- a/gui/src/symbol.cpp +++ b/gui/src/symbol.cpp @@ -20,80 +20,58 @@ #include "symbol.h" -#include -#include -#include #include #include +#include +#include +#include /* * Abstract Class Symbol */ -Symbol::Symbol(QObject *parent, const QSize& size, QwtAxisId fixedAxis, - QwtAxisId mobileAxis, bool opposedToFixed, bool floats): - QObject(parent), - d_surface(QRect(QPoint(0, 0), size)), - d_anchor(0, 0), - d_plotCoord(QPointF(0, 0)), - d_selected(false), - d_fixedAxis(fixedAxis), - d_mobileAxis(mobileAxis), - d_stepSize(0), - d_oppToFixed(opposedToFixed), - d_floats(floats), - d_within_plot(true), - d_visible(true), - d_pen(Qt::black) +Symbol::Symbol(QObject *parent, const QSize &size, QwtAxisId fixedAxis, QwtAxisId mobileAxis, bool opposedToFixed, + bool floats) + : QObject(parent) + , d_surface(QRect(QPoint(0, 0), size)) + , d_anchor(0, 0) + , d_plotCoord(QPointF(0, 0)) + , d_selected(false) + , d_fixedAxis(fixedAxis) + , d_mobileAxis(mobileAxis) + , d_stepSize(0) + , d_oppToFixed(opposedToFixed) + , d_floats(floats) + , d_within_plot(true) + , d_visible(true) + , d_pen(Qt::black) { const QwtScaleWidget *fAxis = plot()->axisWidget(d_fixedAxis); const QwtScaleWidget *mAxis = plot()->axisWidget(d_mobileAxis); - QObject::connect((const QObject *)fAxis, SIGNAL(scaleDivChanged()), - this, SLOT(onFixedScaleChanged())); - QObject::connect((const QObject *)mAxis, SIGNAL(scaleDivChanged()), - this, SLOT(onMobileScaleChanged())); + QObject::connect((const QObject *)fAxis, SIGNAL(scaleDivChanged()), this, SLOT(onFixedScaleChanged())); + QObject::connect((const QObject *)mAxis, SIGNAL(scaleDivChanged()), this, SLOT(onMobileScaleChanged())); onFixedScaleChanged(); onMobileScaleChanged(); } -Symbol::~Symbol() -{ -} +Symbol::~Symbol() {} -QwtPlot *Symbol::plot() -{ - return static_cast(parent()); -} +QwtPlot *Symbol::plot() { return static_cast(parent()); } -const QwtPlot *Symbol::plot() const -{ - return static_cast(parent()); -} +const QwtPlot *Symbol::plot() const { return static_cast(parent()); } -void Symbol::setSurface(const QRect& rect) -{ - d_surface = rect; -} +void Symbol::setSurface(const QRect &rect) { d_surface = rect; } -QRect Symbol::surface() -{ - return d_surface; -} +QRect Symbol::surface() { return d_surface; } -void Symbol::setAnchor(const QPoint& anchor) -{ - d_anchor = anchor; -} +void Symbol::setAnchor(const QPoint &anchor) { d_anchor = anchor; } -QPoint Symbol::anchor() -{ - return d_anchor; -} +QPoint Symbol::anchor() { return d_anchor; } void Symbol::setPlotCoord(const QPointF &pos) { - if (pos != d_plotCoord) { + if(pos != d_plotCoord) { d_plotCoord = pos; updateSurfacePos(); @@ -101,10 +79,7 @@ void Symbol::setPlotCoord(const QPointF &pos) } } -QPointF Symbol::plotCoord() -{ - return d_plotCoord; -} +QPointF Symbol::plotCoord() { return d_plotCoord; } void Symbol::setSelected(bool sel) { @@ -112,106 +87,63 @@ void Symbol::setSelected(bool sel) Q_EMIT selected(sel); } -bool Symbol::isSelected() -{ - return d_selected; -} +bool Symbol::isSelected() { return d_selected; } -QwtAxisId Symbol::fixedAxis() const -{ - return d_fixedAxis; -} +QwtAxisId Symbol::fixedAxis() const { return d_fixedAxis; } -QwtAxisId Symbol::mobileAxis() const -{ - return d_mobileAxis; -} +QwtAxisId Symbol::mobileAxis() const { return d_mobileAxis; } void Symbol::setMobileAxis(QwtAxisId newAxis) { - if (d_mobileAxis != newAxis) { + if(d_mobileAxis != newAxis) { const QwtScaleWidget *mAxis = plot()->axisWidget(d_mobileAxis); - disconnect((const QObject *)mAxis, SIGNAL(scaleDivChanged()), - this, SLOT(onMobileScaleChanged())); + disconnect((const QObject *)mAxis, SIGNAL(scaleDivChanged()), this, SLOT(onMobileScaleChanged())); d_mobileAxis = newAxis; mAxis = plot()->axisWidget(newAxis); - connect((const QObject *)mAxis, SIGNAL(scaleDivChanged()), - this, SLOT(onMobileScaleChanged())); + connect((const QObject *)mAxis, SIGNAL(scaleDivChanged()), this, SLOT(onMobileScaleChanged())); onMobileScaleChanged(); - } } void Symbol::setFixedAxis(QwtAxisId newAxis) { - if (d_fixedAxis != newAxis) { + if(d_fixedAxis != newAxis) { const QwtScaleWidget *fAxis = plot()->axisWidget(d_fixedAxis); - disconnect((const QObject *)fAxis, SIGNAL(scaleDivChanged()), - this, SLOT(onFixedScaleChanged())); + disconnect((const QObject *)fAxis, SIGNAL(scaleDivChanged()), this, SLOT(onFixedScaleChanged())); d_fixedAxis = newAxis; fAxis = plot()->axisWidget(newAxis); - connect((const QObject *)fAxis, SIGNAL(scaleDivChanged()), - this, SLOT(onFixedScaleChanged())); + connect((const QObject *)fAxis, SIGNAL(scaleDivChanged()), this, SLOT(onFixedScaleChanged())); onFixedScaleChanged(); } } -void Symbol::setStepSize(double step) -{ - d_stepSize = step; -} - -double Symbol::stepSize() -{ - return d_stepSize; -} +void Symbol::setStepSize(double step) { d_stepSize = step; } +double Symbol::stepSize() { return d_stepSize; } -bool Symbol::opposedToFixed() -{ - return d_oppToFixed; -} +bool Symbol::opposedToFixed() { return d_oppToFixed; } +bool Symbol::floats() { return d_floats; } -bool Symbol::floats() -{ - return d_floats; -} +void Symbol::setCanLeavePlot(bool on) { d_within_plot = !on; } -void Symbol::setCanLeavePlot(bool on) -{ - d_within_plot = !on; -} - -bool Symbol::canLeavePlot() -{ - return (!d_within_plot); -} +bool Symbol::canLeavePlot() { return (!d_within_plot); } void Symbol::setVisible(bool en) { - if (d_visible != en) { + if(d_visible != en) { d_visible = en; Q_EMIT visibilityChanged(en); } } -bool Symbol::isVisible() -{ - return d_visible; -} +bool Symbol::isVisible() { return d_visible; } -void Symbol::setPen(const QPen& pen) -{ - d_pen = pen; -} +void Symbol::setPen(const QPen &pen) { d_pen = pen; } -const QPen& Symbol::pen() -{ - return d_pen; -} +const QPen &Symbol::pen() { return d_pen; } QPointF Symbol::invTransform(const QPointF &point) const { @@ -239,16 +171,16 @@ void Symbol::updateSurfacePos() QPoint pixelPos; QwtInterval interval = plot()->axisInterval(d_mobileAxis); - if (d_within_plot) { - if ((d_mobileAxis.pos == QwtAxis::YLeft) || (d_mobileAxis.pos == QwtAxis::YRight) ) { - if (plotCoord.y() < interval.minValue()) + if(d_within_plot) { + if((d_mobileAxis.pos == QwtAxis::YLeft) || (d_mobileAxis.pos == QwtAxis::YRight)) { + if(plotCoord.y() < interval.minValue()) plotCoord.setY(interval.minValue()); - else if (plotCoord.y() > interval.maxValue()) + else if(plotCoord.y() > interval.maxValue()) plotCoord.setY(interval.maxValue()); } else { - if (plotCoord.x() < interval.minValue()) + if(plotCoord.x() < interval.minValue()) plotCoord.setX(interval.minValue()); - else if (plotCoord.x() > interval.maxValue()) + else if(plotCoord.x() > interval.maxValue()) plotCoord.setX(interval.maxValue()); } } @@ -267,7 +199,8 @@ void Symbol::updatePlotCoordFromSurfacePos() } /* emit a signal for the handle to update position */ -void Symbol::triggerMove(){ +void Symbol::triggerMove() +{ QPoint pixelPos = transform(d_plotCoord).toPoint(); Q_EMIT pixelPositionChanged(pixelPos.x(), pixelPos.y()); } @@ -278,12 +211,12 @@ void Symbol::onFixedScaleChanged() QPointF pos = plotCoord(); double f; - if (opposedToFixed()) + if(opposedToFixed()) f = interval.maxValue(); else f = interval.minValue(); - if (fixedAxis().isXAxis()) + if(fixedAxis().isXAxis()) pos.setX(f); else pos.setY(f); @@ -296,12 +229,12 @@ void Symbol::onMobileScaleChanged() QwtScaleDiv scaleDiv = plot()->axisScaleDiv(mobileAxis()); QList minorTicks = scaleDiv.ticks(QwtScaleDiv::MinorTick); - if (minorTicks.size() < 2) + if(minorTicks.size() < 2) return; setStepSize(qAbs(minorTicks[1] - minorTicks[0])); - if (this->floats()) + if(this->floats()) updatePlotCoordFromSurfacePos(); else updateSurfacePos(); @@ -311,20 +244,16 @@ void Symbol::onMobileScaleChanged() * Class VertDebugSymbol */ -VertDebugSymbol::VertDebugSymbol(QObject *parent, const QSize& size, - bool opposedToFixed, bool floats): - Symbol(parent, size, QwtAxis::XBottom, QwtAxis::YLeft, opposedToFixed, - floats) +VertDebugSymbol::VertDebugSymbol(QObject *parent, const QSize &size, bool opposedToFixed, bool floats) + : Symbol(parent, size, QwtAxis::XBottom, QwtAxis::YLeft, opposedToFixed, floats) { int x = opposedToFixed ? surface().width() : 0; setAnchor(QPoint(x, surface().height() / 2)); // Pass the base positionChanged(double, double) signal as positionChanged(double) - connect(this, SIGNAL(positionChanged(double, double)), - this, SLOT(onBasePositionChanged(double, double))); - connect(this, SIGNAL(pixelPositionChanged(int, int)), - this, SLOT(onBasePixelPositionChanged(int, int))); + connect(this, SIGNAL(positionChanged(double, double)), this, SLOT(onBasePositionChanged(double, double))); + connect(this, SIGNAL(pixelPositionChanged(int, int)), this, SLOT(onBasePixelPositionChanged(int, int))); } void VertDebugSymbol::draw(QPainter *painter) const @@ -350,10 +279,10 @@ bool VertDebugSymbol::moveWith(double plotDeltaX, double plotDeltaY) QPointF deltaPoint; bool canMove = false; - if (qAbs(d_stepSize) > 0) { + if(qAbs(d_stepSize) > 0) { int stepsInDelta = (int)(plotDeltaY / d_stepSize); - if (qAbs(stepsInDelta) > 0) { + if(qAbs(stepsInDelta) > 0) { deltaPoint = QPointF(0, stepsInDelta * d_stepSize); canMove = true; } @@ -362,7 +291,7 @@ bool VertDebugSymbol::moveWith(double plotDeltaX, double plotDeltaY) canMove = true; } - if (canMove) + if(canMove) setPlotCoord(plotCoord() + deltaPoint); return canMove; @@ -377,7 +306,7 @@ double VertDebugSymbol::getPosition() void VertDebugSymbol::setPosition(double vertPos) { QPointF p = plotCoord(); - if (p.y() != vertPos) { + if(p.y() != vertPos) { p.setY(vertPos); setPlotCoord(p); } @@ -409,19 +338,15 @@ void VertDebugSymbol::onBasePixelPositionChanged(int x, int y) * Class HorizDebugSymbol */ -HorizDebugSymbol::HorizDebugSymbol(QObject *parent, const QSize& size, - bool opposedToFixed, bool floats): - Symbol(parent, size, QwtAxis::YLeft, QwtAxis::XBottom, opposedToFixed, - floats) +HorizDebugSymbol::HorizDebugSymbol(QObject *parent, const QSize &size, bool opposedToFixed, bool floats) + : Symbol(parent, size, QwtAxis::YLeft, QwtAxis::XBottom, opposedToFixed, floats) { int y = opposedToFixed ? 0 : surface().height(); setAnchor(QPoint(surface().width() / 2, y)); // Pass the base positionChanged(double, double) signal as positionChanged(double) - connect(this, SIGNAL(positionChanged(double, double)), - this, SLOT(onBasePositionChanged(double, double))); - connect(this, SIGNAL(pixelPositionChanged(int, int)), - this, SLOT(onBasePixelPositionChanged(int, int))); + connect(this, SIGNAL(positionChanged(double, double)), this, SLOT(onBasePositionChanged(double, double))); + connect(this, SIGNAL(pixelPositionChanged(int, int)), this, SLOT(onBasePixelPositionChanged(int, int))); } void HorizDebugSymbol::draw(QPainter *painter) const @@ -447,10 +372,10 @@ bool HorizDebugSymbol::moveWith(double plotDeltaX, double plotDeltaY) QPointF deltaPoint; bool canMove = false; - if (qAbs(d_stepSize) > 0) { + if(qAbs(d_stepSize) > 0) { int stepsInDelta = (int)(plotDeltaX / d_stepSize); - if (qAbs(stepsInDelta) > 0) { + if(qAbs(stepsInDelta) > 0) { deltaPoint = QPointF(stepsInDelta * d_stepSize, 0); canMove = true; } @@ -459,7 +384,7 @@ bool HorizDebugSymbol::moveWith(double plotDeltaX, double plotDeltaY) canMove = true; } - if (canMove) + if(canMove) Q_EMIT positionChanged(deltaPoint.x()); return canMove; @@ -474,7 +399,7 @@ double HorizDebugSymbol::getPosition() void HorizDebugSymbol::setPosition(double horizPos) { QPointF p = plotCoord(); - if (p.x() != horizPos) { + if(p.x() != horizPos) { p.setX(horizPos); setPlotCoord(p); } @@ -506,9 +431,9 @@ void HorizDebugSymbol::onBasePixelPositionChanged(int x, int y) * Class TriggerLevelCursor */ -TriggerLevelCursor::TriggerLevelCursor(QObject *parent, const QPixmap& pixmap): - VertDebugSymbol(parent, QSize(pixmap.size()), true), - d_cursorPixmap(pixmap) +TriggerLevelCursor::TriggerLevelCursor(QObject *parent, const QPixmap &pixmap) + : VertDebugSymbol(parent, QSize(pixmap.size()), true) + , d_cursorPixmap(pixmap) { setAnchor(QPoint(surface().width() - 7, surface().height() / 2)); } @@ -521,7 +446,7 @@ void TriggerLevelCursor::draw(QPainter *painter) const int y0 = d_surface.y(); QwtInterval interval = plot()->axisInterval(mobileAxis()); - if (d_plotCoord.y() < interval.minValue()) { + if(d_plotCoord.y() < interval.minValue()) { painter->setPen(d_pen); QRect r(x0 + 13, y0, w - 13, h); QPainterPath path; @@ -530,7 +455,7 @@ void TriggerLevelCursor::draw(QPainter *painter) const path.lineTo(r.left() + r.width() / 2, r.bottom()); path.lineTo(r.topLeft()); painter->fillPath(path, QBrush(d_pen.color())); - } else if (d_plotCoord.y() > interval.maxValue()) { + } else if(d_plotCoord.y() > interval.maxValue()) { painter->setPen(d_pen); QRect r(x0 + 13, y0, w - 13, h); QPainterPath path; @@ -541,13 +466,12 @@ void TriggerLevelCursor::draw(QPainter *painter) const painter->fillPath(path, QBrush(d_pen.color())); } else { painter->drawPixmap(x0, y0, w, h, d_cursorPixmap); - if (d_selected) { + if(d_selected) { QPointF p = d_plotCoord; p.setX(plot()->axisInterval(fixedAxis()).minValue()); painter->setPen(d_pen); - painter->drawLine(x0, y0 + d_anchor.y(), - transform(p).toPoint().x(), y0 + d_anchor.y()); + painter->drawLine(x0, y0 + d_anchor.y(), transform(p).toPoint().x(), y0 + d_anchor.y()); } } } @@ -556,9 +480,9 @@ void TriggerLevelCursor::draw(QPainter *painter) const * Class TriggerLevelCursor */ -TriggerDelayCursor::TriggerDelayCursor(QObject *parent, const QPixmap& pixmap): - HorizDebugSymbol(parent, QSize(pixmap.size()), true), - d_cursorPixmap(pixmap) +TriggerDelayCursor::TriggerDelayCursor(QObject *parent, const QPixmap &pixmap) + : HorizDebugSymbol(parent, QSize(pixmap.size()), true) + , d_cursorPixmap(pixmap) { setAnchor(QPoint(surface().width() / 2, surface().height() / 2 - 6)); } @@ -572,7 +496,7 @@ void TriggerDelayCursor::draw(QPainter *painter) const QwtInterval interval = plot()->axisInterval(mobileAxis()); - if (d_plotCoord.x() < interval.minValue()) { + if(d_plotCoord.x() < interval.minValue()) { painter->setPen(d_pen); QRect r(x0 + 2, y0 + 2, w, h - 12); QPainterPath path; @@ -581,7 +505,7 @@ void TriggerDelayCursor::draw(QPainter *painter) const path.lineTo(r.left(), r.top() + r.height() / 2); path.lineTo(r.topRight()); painter->fillPath(path, QBrush(d_pen.color())); - } else if (d_plotCoord.x() > interval.maxValue()) { + } else if(d_plotCoord.x() > interval.maxValue()) { painter->setPen(d_pen); QRect r(x0 + 2, y0 + 2, w, h - 12); QPainterPath path; @@ -596,8 +520,7 @@ void TriggerDelayCursor::draw(QPainter *painter) const painter->drawPixmap(x0, y0, w, h, d_cursorPixmap); painter->setPen(d_pen); - painter->drawLine(x0 + d_anchor.x(), y0 + h - 1, x0 + d_anchor.x(), - transform(p).toPoint().y()); + painter->drawLine(x0 + d_anchor.x(), y0 + h - 1, x0 + d_anchor.x(), transform(p).toPoint().y()); } } @@ -605,10 +528,9 @@ void TriggerDelayCursor::draw(QPainter *painter) const * Class VertBar */ -HorizBar::HorizBar(QObject *parent, bool floats): - VertDebugSymbol(parent, QSize(0, 0), false, floats) -{ -} +HorizBar::HorizBar(QObject *parent, bool floats) + : VertDebugSymbol(parent, QSize(0, 0), false, floats) +{} void HorizBar::draw(QPainter *painter) const { @@ -625,10 +547,9 @@ void HorizBar::draw(QPainter *painter) const * Class HorizBar */ -VertBar::VertBar(QObject *parent, bool floats): - HorizDebugSymbol(parent, QSize(0, 0), true, floats) -{ -} +VertBar::VertBar(QObject *parent, bool floats) + : HorizDebugSymbol(parent, QSize(0, 0), true, floats) +{} void VertBar::draw(QPainter *painter) const { diff --git a/gui/src/symbol_controller.cpp b/gui/src/symbol_controller.cpp index 50e13936f2..9e94dd6082 100644 --- a/gui/src/symbol_controller.cpp +++ b/gui/src/symbol_controller.cpp @@ -19,42 +19,37 @@ */ #include "symbol_controller.h" + #include "qwt_painter.h" -#include -#include -#include -#include + #include +#include +#include +#include +#include -class Overlay: public QwtWidgetOverlay +class Overlay : public QwtWidgetOverlay { public: - Overlay(QWidget *parent, SymbolController *symbolController): - QwtWidgetOverlay(parent), - d_symbolCtrl(symbolController) - { - } + Overlay(QWidget *parent, SymbolController *symbolController) + : QwtWidgetOverlay(parent) + , d_symbolCtrl(symbolController) + {} protected: - virtual void drawOverlay(QPainter *painter) const - { - d_symbolCtrl->drawOverlay(painter); - } + virtual void drawOverlay(QPainter *painter) const { d_symbolCtrl->drawOverlay(painter); } - virtual QRegion maskHint() const - { - return d_symbolCtrl->maskHint(); - } + virtual QRegion maskHint() const { return d_symbolCtrl->maskHint(); } private: SymbolController *d_symbolCtrl; }; -SymbolController::SymbolController(QwtPlot *plot): - QObject(plot), - d_isEnabled(false), - d_selectedSymbol(NULL), - axesCreated(0) +SymbolController::SymbolController(QwtPlot *plot) + : QObject(plot) + , d_isEnabled(false) + , d_selectedSymbol(NULL) + , axesCreated(0) { setEnabled(true); @@ -66,24 +61,16 @@ SymbolController::~SymbolController() // d_overlay gets destroyed with parent } -QwtPlot *SymbolController::plot() -{ - return static_cast(parent()); -} +QwtPlot *SymbolController::plot() { return static_cast(parent()); } -const QwtPlot *SymbolController::plot() const -{ - return static_cast(parent()); -} +const QwtPlot *SymbolController::plot() const { return static_cast(parent()); } void SymbolController::attachSymbol(Symbol *symbol) { - if (d_symbols.indexOf(symbol) == -1) { + if(d_symbols.indexOf(symbol) == -1) { d_symbols.push_back(symbol); - QObject::connect((const QObject *)symbol, SIGNAL(positionChanged(double)), - this, SLOT(updateOverlay())); - QObject::connect((const QObject *)symbol, SIGNAL(visibilityChanged(bool)), - this, SLOT(updateOverlay())); + QObject::connect((const QObject *)symbol, SIGNAL(positionChanged(double)), this, SLOT(updateOverlay())); + QObject::connect((const QObject *)symbol, SIGNAL(visibilityChanged(bool)), this, SLOT(updateOverlay())); d_overlay->updateOverlay(); } @@ -92,23 +79,21 @@ void SymbolController::attachSymbol(Symbol *symbol) void SymbolController::detachSymbol(Symbol *symbol) { d_symbols.removeOne(symbol); - QObject::disconnect((const QObject *)symbol, SIGNAL(positionChanged(double)), - this, SLOT(updateOverlay())); - QObject::disconnect((const QObject *)symbol, SIGNAL(visibilityChanged(bool)), - this, SLOT(updateOverlay())); + QObject::disconnect((const QObject *)symbol, SIGNAL(positionChanged(double)), this, SLOT(updateOverlay())); + QObject::disconnect((const QObject *)symbol, SIGNAL(visibilityChanged(bool)), this, SLOT(updateOverlay())); d_overlay->updateOverlay(); } void SymbolController::setEnabled(bool on) { - if (on == d_isEnabled) + if(on == d_isEnabled) return; QwtPlot *plot = static_cast(parent()); - if (plot) { + if(plot) { d_isEnabled = on; - if (on) { + if(on) { plot->canvas()->installEventFilter(this); } else { plot->canvas()->removeEventFilter(this); @@ -116,63 +101,57 @@ void SymbolController::setEnabled(bool on) } } -bool SymbolController::isEnabled() const -{ - return d_isEnabled; -} +bool SymbolController::isEnabled() const { return d_isEnabled; } -void SymbolController::updateOverlay() -{ - d_overlay->updateOverlay(); -} +void SymbolController::updateOverlay() { d_overlay->updateOverlay(); } bool SymbolController::eventFilter(QObject *object, QEvent *event) { QwtPlot *plot = static_cast(parent()); - if (plot && object == plot->canvas()) { + if(plot && object == plot->canvas()) { switch(event->type()) { - case QEvent::MouseButtonPress: { - const QMouseEvent *mouseEvent = dynamic_cast(event); + case QEvent::MouseButtonPress: { + const QMouseEvent *mouseEvent = dynamic_cast(event); - if (mouseEvent->button() == Qt::LeftButton) { - const bool accepted = pressed(mouseEvent->pos()); + if(mouseEvent->button() == Qt::LeftButton) { + const bool accepted = pressed(mouseEvent->pos()); - if (accepted) { - d_overlay->updateOverlay(); - d_overlay->show(); - } + if(accepted) { + d_overlay->updateOverlay(); + d_overlay->show(); } - - break; } - case QEvent::MouseMove: { - const QMouseEvent *mouseEvent = dynamic_cast(event); - const bool accepted = moved(mouseEvent->pos()); - if (accepted) - d_overlay->updateOverlay(); + break; + } + case QEvent::MouseMove: { + const QMouseEvent *mouseEvent = dynamic_cast(event); + const bool accepted = moved(mouseEvent->pos()); - break; - } - case QEvent::MouseButtonRelease: { - const QMouseEvent* mouseEvent = dynamic_cast(event); + if(accepted) + d_overlay->updateOverlay(); - if (mouseEvent->button() == Qt::LeftButton) { - released(mouseEvent->pos()); - } + break; + } + case QEvent::MouseButtonRelease: { + const QMouseEvent *mouseEvent = dynamic_cast(event); - break; - } - case QEvent::Resize: { - for (int i = 0; i < d_symbols.size(); i++) - d_symbols[i]->updateSurfacePos(); - break; - } - default: - break; + if(mouseEvent->button() == Qt::LeftButton) { + released(mouseEvent->pos()); } + break; + } + case QEvent::Resize: { + for(int i = 0; i < d_symbols.size(); i++) + d_symbols[i]->updateSurfacePos(); + break; + } + default: + break; + } + return false; } @@ -181,10 +160,10 @@ bool SymbolController::eventFilter(QObject *object, QEvent *event) bool SymbolController::pressed(const QPoint &pos) { - for (int i = 0; i < d_symbols.size(); i++) { + for(int i = 0; i < d_symbols.size(); i++) { Symbol *symbol = d_symbols[i]; - if (symbol->surface().contains(pos)) { + if(symbol->surface().contains(pos)) { symbol->setSelected(true); d_selectedSymbol = symbol; d_prevPos = pos; @@ -197,14 +176,13 @@ bool SymbolController::pressed(const QPoint &pos) bool SymbolController::moved(const QPoint &pos) { - if (plot() == NULL) + if(plot() == NULL) return false; - if (d_selectedSymbol && d_selectedSymbol->isSelected()) { - QPointF delta = d_selectedSymbol->invTransform(pos) - - d_selectedSymbol->invTransform(d_prevPos); + if(d_selectedSymbol && d_selectedSymbol->isSelected()) { + QPointF delta = d_selectedSymbol->invTransform(pos) - d_selectedSymbol->invTransform(d_prevPos); bool moved = d_selectedSymbol->moveWith(delta.x(), delta.y()); - if (moved) + if(moved) d_prevPos = pos; } @@ -215,7 +193,7 @@ void SymbolController::released(const QPoint &pos) { Q_UNUSED(pos); - if (d_selectedSymbol && d_selectedSymbol->isSelected()) { + if(d_selectedSymbol && d_selectedSymbol->isSelected()) { d_selectedSymbol->setSelected(false); d_selectedSymbol = NULL; } @@ -223,19 +201,13 @@ void SymbolController::released(const QPoint &pos) void SymbolController::drawCursor(QPainter *painter) const { - for (int i = 0; i < d_symbols.size(); i++) - if (d_symbols[i]->isVisible()) + for(int i = 0; i < d_symbols.size(); i++) + if(d_symbols[i]->isVisible()) d_symbols[i]->draw(painter); } -void SymbolController::drawOverlay(QPainter *painter) const -{ - drawCursor(painter); -} +void SymbolController::drawOverlay(QPainter *painter) const { drawCursor(painter); } -QRegion SymbolController::maskHint() const -{ - return QRegion(); -} +QRegion SymbolController::maskHint() const { return QRegion(); } #include "moc_symbol_controller.cpp" diff --git a/gui/src/tintedoverlay.cpp b/gui/src/tintedoverlay.cpp index 8c770ece72..4a7fc773ac 100644 --- a/gui/src/tintedoverlay.cpp +++ b/gui/src/tintedoverlay.cpp @@ -1,7 +1,10 @@ #include "tintedoverlay.h" using namespace scopy::gui; -TintedOverlay::TintedOverlay(QWidget *parent, QColor color) : QWidget(parent), color(color) { +TintedOverlay::TintedOverlay(QWidget *parent, QColor color) + : QWidget(parent) + , color(color) +{ setAttribute(Qt::WA_TranslucentBackground); this->parent = parent; holes.clear(); @@ -11,48 +14,40 @@ TintedOverlay::TintedOverlay(QWidget *parent, QColor color) : QWidget(parent), c setAttribute(Qt::WA_TransparentForMouseEvents, false); } -TintedOverlay::~TintedOverlay() -{ +TintedOverlay::~TintedOverlay() {} -} +const QList &TintedOverlay::getHoles() const { return holes; } -const QList &TintedOverlay::getHoles() const -{ - return holes; -} +void TintedOverlay::setHoles(const QList &newHoles) { holes = newHoles; } -void TintedOverlay::setHoles(const QList &newHoles) -{ - holes = newHoles; -} +void TintedOverlay::clearHoles() { holes.clear(); } -void TintedOverlay::clearHoles() +void TintedOverlay::paintEvent(QPaintEvent *ev) { - holes.clear(); -} - -void TintedOverlay::paintEvent(QPaintEvent *ev) { QPainter painter(this); if(!holes.isEmpty()) { - QPainterPath p1,p2; + QPainterPath p1, p2; p1.addRect(rect()); - for(QWidget* holeWidget : qAsConst(holes)) { - QPoint offset = holeWidget->mapTo(parent,QPoint(0,0)); + for(QWidget *holeWidget : qAsConst(holes)) { + QPoint offset = holeWidget->mapTo(parent, QPoint(0, 0)); QRect hole = holeWidget->geometry(); hole.moveTo(offset); p2.addRect(hole); - p1-=p2; + p1 -= p2; } QRegion r(p1.toFillPolygon().toPolygon()); setMask(r); } else { setMask(rect()); } - painter.fillRect(rect(),color); + painter.fillRect(rect(), color); } -void TintedOverlay::mousePressEvent(QMouseEvent *ev) { +void TintedOverlay::mousePressEvent(QMouseEvent *ev) +{ // prevent clicks from being sent to parents ev->accept(); } + +#include "moc_tintedoverlay.cpp" diff --git a/gui/src/tool_view.cpp b/gui/src/tool_view.cpp index 2b9b2a0709..18bd955243 100644 --- a/gui/src/tool_view.cpp +++ b/gui/src/tool_view.cpp @@ -1,14 +1,17 @@ #include "channel_widget.hpp" //#include "menu_header.hpp" #include "tool_view.hpp" + #include "utils.h" -#include + #include "ui_tool_view.h" + #include +#include using namespace scopy::gui; -ToolView::ToolView(QWidget* parent) +ToolView::ToolView(QWidget *parent) : QWidget(parent) , m_ui(new Ui::ToolView) , m_nextMenuIndex(0) @@ -43,17 +46,17 @@ ToolView::~ToolView() { delete m_ui; } void ToolView::configureLastOpenedMenu() { - QPushButton* settingsBtn = m_ui->widgetSettingsPairBtns->getSettingsBtn(); + QPushButton *settingsBtn = m_ui->widgetSettingsPairBtns->getSettingsBtn(); connect(settingsBtn, &QPushButton::clicked, this, [=](bool checked) { - if (!m_menuOrder.isEmpty()) { - CustomPushButton* btn = nullptr; + if(!m_menuOrder.isEmpty()) { + CustomPushButton *btn = nullptr; - if (checked) { + if(checked) { btn = m_menuOrder.back(); m_menuOrder.pop_back(); } else { - btn = static_cast(m_group.checkedButton()); + btn = static_cast(m_group.checkedButton()); } btn->setChecked(checked); @@ -70,7 +73,7 @@ void ToolView::rightMenuFinished(bool opened) // At the end of each animation, check if there are other button check // actions that might have happened while animating and execute all // these queued actions - while (m_menuButtonActions.size()) { + while(m_menuButtonActions.size()) { auto pair = m_menuButtonActions.dequeue(); toggleRightMenu(pair.first, pair.second); } @@ -81,20 +84,20 @@ void ToolView::triggerRightMenuToggle(bool checked) // Queue the action, if right menu animation is in progress. This way // the action will be remembered and performed right after the animation // finishes - CustomPushButton* btn = static_cast(QObject::sender()); - if (m_ui->widgetMenuHAnim->animInProgress()) { - m_menuButtonActions.enqueue(QPair(btn, checked)); + CustomPushButton *btn = static_cast(QObject::sender()); + if(m_ui->widgetMenuHAnim->animInProgress()) { + m_menuButtonActions.enqueue(QPair(btn, checked)); } else { toggleRightMenu(btn, checked); } } -void ToolView::toggleRightMenu(CustomPushButton* btn, bool checked) +void ToolView::toggleRightMenu(CustomPushButton *btn, bool checked) { int id = btn->property("id").toInt(); - if (id != -m_generalSettingsMenuId) { - if (!m_menuOrder.contains(btn)) { + if(id != -m_generalSettingsMenuId) { + if(!m_menuOrder.contains(btn)) { m_ui->stackedWidget->addWidget(m_menuList[-id]); m_menuOrder.push_back(btn); } else { @@ -103,7 +106,7 @@ void ToolView::toggleRightMenu(CustomPushButton* btn, bool checked) } } - if (checked) { + if(checked) { settingsPanelUpdate(id); } @@ -112,41 +115,40 @@ void ToolView::toggleRightMenu(CustomPushButton* btn, bool checked) void ToolView::settingsPanelUpdate(int id) { - if (id > 0) { + if(id > 0) { m_ui->stackedWidget->setCurrentIndex(0); } else { m_ui->stackedWidget->setCurrentWidget(m_menuList[-id]); } - for (int i = 0; i < m_ui->stackedWidget->count(); i++) { + for(int i = 0; i < m_ui->stackedWidget->count(); i++) { QSizePolicy::Policy policy = QSizePolicy::Ignored; bool visible = false; - if (i == m_ui->stackedWidget->currentIndex()) { + if(i == m_ui->stackedWidget->currentIndex()) { policy = QSizePolicy::Expanding; visible = true; } - QWidget* widget = m_ui->stackedWidget->widget(i); + QWidget *widget = m_ui->stackedWidget->widget(i); widget->setSizePolicy(policy, policy); widget->setVisible(visible); } m_ui->stackedWidget->adjustSize(); } -void ToolView::buildChannelsContainer(ChannelManager* cm, ChannelsPositionEnum position) +void ToolView::buildChannelsContainer(ChannelManager *cm, ChannelsPositionEnum position) { - connect(cm, &ChannelManager::channelManagerToggle, this, [=](bool toggled){ - m_ui->widgetVerticalChannels->toggleMenu(toggled); - }); + connect(cm, &ChannelManager::channelManagerToggle, this, + [=](bool toggled) { m_ui->widgetVerticalChannels->toggleMenu(toggled); }); connect(cm, &ChannelManager::configureAddBtn, this, &ToolView::configureAddMathBtn); connect(this, &ToolView::changeParent, cm, &ChannelManager::changeParent); connect(cm, &ChannelManager::positionChanged, this, [=](ChannelsPositionEnum position) { - if (position == ChannelsPositionEnum::VERTICAL) { + if(position == ChannelsPositionEnum::VERTICAL) { m_ui->widgetHorizontalChannels->setVisible(false); m_ui->widgetVerticalChannels->setVisible(true); - if (!m_ui->widgetMenuBtns->isVisible()) { + if(!m_ui->widgetMenuBtns->isVisible()) { m_ui->widgetFooter->setVisible(false); } @@ -166,13 +168,12 @@ void ToolView::buildChannelsContainer(ChannelManager* cm, ChannelsPositionEnum p // if it's horizontal, will be later updated (needs rework) m_ui->widgetVerticalChannels->setVisible(true); cm->build(m_ui->widgetVerticalChannelsContainer); - } -QDockWidget* ToolView::createDetachableMenu(QWidget* menu, int& id) +QDockWidget *ToolView::createDetachableMenu(QWidget *menu, int &id) { - QMainWindow* subWindow = new QMainWindow(this); - QDockWidget* docker = new QDockWidget(subWindow); + QMainWindow *subWindow = new QMainWindow(this); + QDockWidget *docker = new QDockWidget(subWindow); docker->setFeatures(docker->features() & ~QDockWidget::DockWidgetClosable); docker->setAllowedAreas(Qt::DockWidgetArea::NoDockWidgetArea); subWindow->addDockWidget(Qt::RightDockWidgetArea, docker); @@ -190,9 +191,9 @@ QDockWidget* ToolView::createDetachableMenu(QWidget* menu, int& id) return docker; } -QDockWidget *ToolView::createDockableWidget(QWidget *widget, const QString& dockerName) +QDockWidget *ToolView::createDockableWidget(QWidget *widget, const QString &dockerName) { - QDockWidget* docker = new QDockWidget(m_centralMainWindow); + QDockWidget *docker = new QDockWidget(m_centralMainWindow); docker->setWindowTitle(dockerName); docker->setFeatures(docker->features() & ~QDockWidget::DockWidgetClosable); docker->setAllowedAreas(Qt::DockWidgetArea::AllDockWidgetAreas); @@ -208,20 +209,20 @@ QDockWidget *ToolView::createDockableWidget(QWidget *widget, const QString& dock return docker; } -void ToolView::configureAddMathBtn(QWidget* menu, bool dockable) +void ToolView::configureAddMathBtn(QWidget *menu, bool dockable) { - ChannelManager* cm = static_cast(QObject::sender()); - CustomPushButton* addBtn = cm->getAddChannelBtn(); + ChannelManager *cm = static_cast(QObject::sender()); + CustomPushButton *addBtn = cm->getAddChannelBtn(); int id; - if (dockable) { - QDockWidget* docker = this->createDetachableMenu(menu, id); + if(dockable) { + QDockWidget *docker = this->createDetachableMenu(menu, id); connect(docker, &QDockWidget::topLevelChanged, addBtn, [=](bool topLevel) { addBtn->setChecked(!topLevel); addBtn->setDisabled(topLevel); - if (topLevel) { + if(topLevel) { m_menuOrder.removeOne(addBtn); } }); @@ -239,33 +240,33 @@ void ToolView::configureAddMathBtn(QWidget* menu, bool dockable) &QPushButton::setChecked); } -ChannelWidget* ToolView::buildNewChannel(ChannelManager* channelManager, GenericMenu* menu, bool dockable, int chId, - bool deletable, bool simplefied, QColor color, const QString& fullName, - const QString& shortName) +ChannelWidget *ToolView::buildNewChannel(ChannelManager *channelManager, GenericMenu *menu, bool dockable, int chId, + bool deletable, bool simplefied, QColor color, const QString &fullName, + const QString &shortName) { - if (chId == -1) { + if(chId == -1) { chId = getNewID(); } - ChannelWidget* ch = channelManager->buildNewChannel(chId, deletable, simplefied, color, fullName, shortName); + ChannelWidget *ch = channelManager->buildNewChannel(chId, deletable, simplefied, color, fullName, shortName); int id; - if (dockable) { - QDockWidget* docker = this->createDetachableMenu(menu, id); + if(dockable) { + QDockWidget *docker = this->createDetachableMenu(menu, id); connect(docker, &QDockWidget::topLevelChanged, ch->menuButton(), [=](bool topLevel) { - CustomPushButton* btn = static_cast(ch->menuButton()); + CustomPushButton *btn = static_cast(ch->menuButton()); btn->setChecked(!topLevel); btn->setDisabled(topLevel); ch->setMenuFloating(topLevel); - if (topLevel) { + if(topLevel) { m_menuOrder.removeOne(btn); } }); - if (deletable) { + if(deletable) { connect(ch, &ChannelWidget::deleteClicked, this, [=]() { docker->close(); }); } @@ -282,11 +283,11 @@ ChannelWidget* ToolView::buildNewChannel(ChannelManager* channelManager, Generic connect(ch->menuButton(), &CustomPushButton::toggled, m_ui->widgetSettingsPairBtns->getSettingsBtn(), &QPushButton::setChecked); connect(ch->enableButton(), &QAbstractButton::toggled, [=](bool toggled) { - if (!toggled) { + if(!toggled) { // we also remove the button from the history // so that the last menu opened button on top // won't open the menu when it is disabled - m_menuOrder.removeOne(qobject_cast(ch->menuButton())); + m_menuOrder.removeOne(qobject_cast(ch->menuButton())); } // mirror menu btn @@ -295,14 +296,14 @@ ChannelWidget* ToolView::buildNewChannel(ChannelManager* channelManager, Generic connect(menu, &GenericMenu::enableBtnToggled, [=](bool toggled) { ch->enableButton()->setChecked(toggled); }); - if (deletable) { + if(deletable) { connect(ch, &ChannelWidget::deleteClicked, this, [=]() { - if (ch->menuButton()->isChecked()) { - m_menuButtonActions.removeAll(QPair( - qobject_cast(ch->menuButton()), true)); - toggleRightMenu(qobject_cast(ch->menuButton()), false); + if(ch->menuButton()->isChecked()) { + m_menuButtonActions.removeAll(QPair( + qobject_cast(ch->menuButton()), true)); + toggleRightMenu(qobject_cast(ch->menuButton()), false); } - m_menuOrder.removeOne(qobject_cast(ch->menuButton())); + m_menuOrder.removeOne(qobject_cast(ch->menuButton())); channelManager->removeChannel(ch); }); @@ -311,22 +312,20 @@ ChannelWidget* ToolView::buildNewChannel(ChannelManager* channelManager, Generic return ch; } -scopy::MenuHAnim* ToolView::addMenuToStack() -{ - return m_ui->widgetMenuHAnim; -} +scopy::MenuHAnim *ToolView::addMenuToStack() { return m_ui->widgetMenuHAnim; } -void ToolView::buildChannelGroup(ChannelManager* channelManager, ChannelWidget* mainChannel, std::vector channelGroup) +void ToolView::buildChannelGroup(ChannelManager *channelManager, ChannelWidget *mainChannel, + std::vector channelGroup) { - for (ChannelWidget* ch : channelGroup) { - channelManager->setChannelAlignment(ch,Qt::AlignLeft); + for(ChannelWidget *ch : channelGroup) { + channelManager->setChannelAlignment(ch, Qt::AlignLeft); } mainChannel->setIsMainChannel(true); - channelManager->setChannelAlignment(mainChannel,Qt::AlignLeft); + channelManager->setChannelAlignment(mainChannel, Qt::AlignLeft); - connect(mainChannel, &ChannelWidget::enabled,this, [=](){ - for (ChannelWidget* ch : channelGroup) { - if (mainChannel->toggleChannelsButton()->isChecked()) { + connect(mainChannel, &ChannelWidget::enabled, this, [=]() { + for(ChannelWidget *ch : channelGroup) { + if(mainChannel->toggleChannelsButton()->isChecked()) { ch->show(); } else { ch->hide(); @@ -335,22 +334,19 @@ void ToolView::buildChannelGroup(ChannelManager* channelManager, ChannelWidget* }); } -int ToolView::getNewID() -{ - return m_nextMenuIndex++; -} +int ToolView::getNewID() { return m_nextMenuIndex++; } -CustomMenuButton *ToolView::buildNewInstrumentMenu(GenericMenu* menu, bool dockable, const QString& name, bool checkBoxVisible, - bool checkBoxChecked) +CustomMenuButton *ToolView::buildNewInstrumentMenu(GenericMenu *menu, bool dockable, const QString &name, + bool checkBoxVisible, bool checkBoxChecked) { m_ui->widgetFooter->setVisible(true); m_ui->widgetMenuBtns->setVisible(true); - CustomMenuButton* btn = new CustomMenuButton(name, checkBoxVisible, checkBoxChecked); + CustomMenuButton *btn = new CustomMenuButton(name, checkBoxVisible, checkBoxChecked); int id; - if (dockable) { - QDockWidget* docker = this->createDetachableMenu(menu, id); + if(dockable) { + QDockWidget *docker = this->createDetachableMenu(menu, id); connect(docker, &QDockWidget::topLevelChanged, btn, [=](bool topLevel) { btn->getBtn()->setChecked(!topLevel); @@ -358,7 +354,7 @@ CustomMenuButton *ToolView::buildNewInstrumentMenu(GenericMenu* menu, bool docka btn->setMenuFloating(topLevel); - if (topLevel) { + if(topLevel) { m_menuOrder.removeOne(btn->getBtn()); } }); @@ -377,7 +373,7 @@ CustomMenuButton *ToolView::buildNewInstrumentMenu(GenericMenu* menu, bool docka connect(btn->getBtn(), &CustomPushButton::toggled, m_ui->widgetSettingsPairBtns->getSettingsBtn(), &QPushButton::setChecked); connect(btn->getCheckBox(), &QCheckBox::toggled, [=](bool toggled) { - if (!toggled) { + if(!toggled) { // we also remove the button from the history // so that the last menu opened button on top // won't open the menu when it is disabled @@ -390,7 +386,7 @@ CustomMenuButton *ToolView::buildNewInstrumentMenu(GenericMenu* menu, bool docka // what is this for? connect(menu, &GenericMenu::enableBtnToggled, [=](bool toggled) { btn->getCheckBox()->setChecked(toggled); }); - if ((checkBoxVisible && checkBoxChecked) || !checkBoxVisible) { + if((checkBoxVisible && checkBoxChecked) || !checkBoxVisible) { m_menuOrder.push_back(btn->getBtn()); } @@ -399,10 +395,10 @@ CustomMenuButton *ToolView::buildNewInstrumentMenu(GenericMenu* menu, bool docka void ToolView::addFixedCentralWidget(QWidget *widget, int row, int column, int rowspan, int columnspan) { - if (row == -1 || column == -1) { - m_ui->gridWidgetCentral->addWidget(widget); + if(row == -1 || column == -1) { + m_ui->gridWidgetCentral->addWidget(widget); } else { - if (rowspan == -1 || columnspan == -1) { + if(rowspan == -1 || columnspan == -1) { m_ui->gridWidgetCentral->addWidget(widget, row, column); } else { m_ui->gridWidgetCentral->addWidget(widget, row, column, rowspan, columnspan); @@ -412,7 +408,7 @@ void ToolView::addFixedCentralWidget(QWidget *widget, int row, int column, int r int ToolView::addDockableCentralWidget(QWidget *widget, Qt::DockWidgetArea area, const QString &dockerName) { - QDockWidget* docker = this->createDockableWidget(widget, dockerName); + QDockWidget *docker = this->createDockableWidget(widget, dockerName); m_centralMainWindow->addDockWidget(area, docker); m_docksList.append(docker); @@ -420,44 +416,36 @@ int ToolView::addDockableCentralWidget(QWidget *widget, Qt::DockWidgetArea area, return m_docksList.size() - 1; } -void ToolView::addPlotInfoWidget(QWidget *widget) -{ - m_ui->widgetPlotInfo->layout()->addWidget(widget); -} +void ToolView::addPlotInfoWidget(QWidget *widget) { m_ui->widgetPlotInfo->layout()->addWidget(widget); } void ToolView::setWidgetVisibility(int widgetId, bool visible) { - if (visible) { + if(visible) { m_docksList.at(widgetId)->show(); } else { m_docksList.at(widgetId)->hide(); } } -bool ToolView::isWidgetHidden(int widgetId) -{ - return m_docksList.at(widgetId)->isHidden(); -} +bool ToolView::isWidgetHidden(int widgetId) { return m_docksList.at(widgetId)->isHidden(); } -void ToolView::setHeaderVisibility(bool visible) -{ - m_ui->widgetHeader->setVisible(visible); -} +void ToolView::setHeaderVisibility(bool visible) { m_ui->widgetHeader->setVisible(visible); } -QDockWidget *ToolView::addDockableTabbedWidget(QWidget* plot, const QString &dockerName) +QDockWidget *ToolView::addDockableTabbedWidget(QWidget *plot, const QString &dockerName) { - QDockWidget* docker = DockerUtils::createDockWidget(m_centralMainWindow, plot, dockerName); + QDockWidget *docker = DockerUtils::createDockWidget(m_centralMainWindow, plot, dockerName); m_centralMainWindow->addDockWidget(Qt::LeftDockWidgetArea, docker); return docker; } -int ToolView::addFixedTabbedWidget(QWidget *widget, const QString& title, int plotId, int row, int column, int rowspan, int columnspan) +int ToolView::addFixedTabbedWidget(QWidget *widget, const QString &title, int plotId, int row, int column, int rowspan, + int columnspan) { if(m_centralFixedWidgets.size() > plotId && plotId != -1) { // adding widget to an existing TabWidget - QTabWidget* tabWidget = static_cast(m_centralFixedWidgets.at(plotId)); + QTabWidget *tabWidget = static_cast(m_centralFixedWidgets.at(plotId)); tabWidget->addTab(widget, title); return plotId; @@ -465,7 +453,7 @@ int ToolView::addFixedTabbedWidget(QWidget *widget, const QString& title, int pl } else { // creating new TabWidget - QTabWidget* tabWidget = new QTabWidget(m_ui->widgetCentral); + QTabWidget *tabWidget = new QTabWidget(m_ui->widgetCentral); tabWidget->addTab(widget, title); m_centralFixedWidgets.append(tabWidget); @@ -475,12 +463,12 @@ int ToolView::addFixedTabbedWidget(QWidget *widget, const QString& title, int pl } } -void ToolView::setGeneralSettingsMenu(QWidget* menu, bool dockable) +void ToolView::setGeneralSettingsMenu(QWidget *menu, bool dockable) { - CustomPushButton* generalSettingsBtn = m_ui->widgetSettingsPairBtns->getGeneralSettingsBtn(); + CustomPushButton *generalSettingsBtn = m_ui->widgetSettingsPairBtns->getGeneralSettingsBtn(); - if (dockable) { - QDockWidget* docker = this->createDetachableMenu(menu, m_generalSettingsMenuId); + if(dockable) { + QDockWidget *docker = this->createDetachableMenu(menu, m_generalSettingsMenuId); connect(docker, &QDockWidget::topLevelChanged, generalSettingsBtn, [=](bool topLevel) { generalSettingsBtn->setChecked(!topLevel); @@ -497,22 +485,22 @@ void ToolView::setGeneralSettingsMenu(QWidget* menu, bool dockable) connect(generalSettingsBtn, &CustomPushButton::toggled, this, [=](bool toggled) { triggerRightMenuToggle(toggled); - if (toggled) { + if(toggled) { m_ui->widgetSettingsPairBtns->getSettingsBtn()->setChecked(!toggled); } }); - if (!getGeneralSettingsBtn()->isVisible()) { + if(!getGeneralSettingsBtn()->isVisible()) { getGeneralSettingsBtn()->setVisible(true); } } -void ToolView::setFixedMenu(QWidget* menu, bool dockable) +void ToolView::setFixedMenu(QWidget *menu, bool dockable) { int id; - if (dockable) { - QDockWidget* docker = this->createDetachableMenu(menu, id); + if(dockable) { + QDockWidget *docker = this->createDetachableMenu(menu, id); connect(docker, &QDockWidget::topLevelChanged, [=](bool topLevel) { m_ui->widgetMenuHAnim->toggleMenu(!topLevel); }); @@ -525,49 +513,48 @@ void ToolView::setFixedMenu(QWidget* menu, bool dockable) m_ui->widgetMenuHAnim->toggleMenu(true); } -QWidget* ToolView::getTopExtraWidget() { return m_ui->widgetTopExtra; } +QWidget *ToolView::getTopExtraWidget() { return m_ui->widgetTopExtra; } void ToolView::setVisibleTopExtraWidget(bool visible) { m_ui->widgetTopExtra->setVisible(visible); } -void ToolView::addTopExtraWidget(QWidget* widget) { m_ui->widgetTopExtra->layout()->addWidget(widget); } +void ToolView::addTopExtraWidget(QWidget *widget) { m_ui->widgetTopExtra->layout()->addWidget(widget); } -QWidget* ToolView::getBottomExtraWidget() { return m_ui->widgetBottomExtra; } +QWidget *ToolView::getBottomExtraWidget() { return m_ui->widgetBottomExtra; } void ToolView::setVisibleBottomExtraWidget(bool visible) { m_ui->widgetBottomExtra->setVisible(visible); } -void ToolView::addBottomExtraWidget(QWidget* widget) { m_ui->widgetBottomExtra->layout()->addWidget(widget); } +void ToolView::addBottomExtraWidget(QWidget *widget) { m_ui->widgetBottomExtra->layout()->addWidget(widget); } -QWidget* ToolView::getCentralWidget() { return m_ui->widgetCentral; } +QWidget *ToolView::getCentralWidget() { return m_ui->widgetCentral; } -QStackedWidget* ToolView::getStackedWidget() { return m_ui->stackedWidget; } +QStackedWidget *ToolView::getStackedWidget() { return m_ui->stackedWidget; } -void ToolView::setStackedWidget(QStackedWidget* sw) -{ - m_ui->stackedWidget = sw; -} +void ToolView::setStackedWidget(QStackedWidget *sw) { m_ui->stackedWidget = sw; } void ToolView::setInstrumentNotesVisible(bool visible) { m_ui->widgetInstrumentNotes->setVisible(visible); } -LinkedButton* ToolView::getHelpBtn() { return m_ui->btnHelp; } +LinkedButton *ToolView::getHelpBtn() { return m_ui->btnHelp; } void ToolView::setHelpBtnVisible(bool visible) { m_ui->btnHelp->setVisible(visible); } -void ToolView::setUrlHelpBtn(const QString& url) { m_ui->btnHelp->setUrl(url); } +void ToolView::setUrlHelpBtn(const QString &url) { m_ui->btnHelp->setUrl(url); } -QPushButton* ToolView::getRunBtn() { return m_ui->widgetRunSingleBtns->getRunButton(); } +QPushButton *ToolView::getRunBtn() { return m_ui->widgetRunSingleBtns->getRunButton(); } void ToolView::setRunBtnVisible(bool visible) { m_ui->widgetRunSingleBtns->enableRunButton(visible); } -QPushButton* ToolView::getSingleBtn() { return m_ui->widgetRunSingleBtns->getSingleButton(); } +QPushButton *ToolView::getSingleBtn() { return m_ui->widgetRunSingleBtns->getSingleButton(); } void ToolView::setSingleBtnVisible(bool visible) { m_ui->widgetRunSingleBtns->enableSingleButton(visible); } -QPushButton* ToolView::getPrintBtn() { return m_ui->btnPrint; } +QPushButton *ToolView::getPrintBtn() { return m_ui->btnPrint; } void ToolView::setPrintBtnVisible(bool visible) { m_ui->btnPrint->setVisible(visible); } void ToolView::setPairSettingsVisible(bool visible) { m_ui->widgetSettingsPairBtns->setVisible(visible); } -CustomPushButton* ToolView::getGeneralSettingsBtn() { return m_ui->widgetSettingsPairBtns->getGeneralSettingsBtn(); } +CustomPushButton *ToolView::getGeneralSettingsBtn() { return m_ui->widgetSettingsPairBtns->getGeneralSettingsBtn(); } + +QPushButton *ToolView::getSettingsBtn() { return m_ui->widgetSettingsPairBtns->getSettingsBtn(); } -QPushButton* ToolView::getSettingsBtn() { return m_ui->widgetSettingsPairBtns->getSettingsBtn(); } +#include "moc_tool_view.cpp" diff --git a/gui/src/tool_view_builder.cpp b/gui/src/tool_view_builder.cpp index 2687eaa2c1..91a6f0ab90 100644 --- a/gui/src/tool_view_builder.cpp +++ b/gui/src/tool_view_builder.cpp @@ -1,28 +1,28 @@ -#include "dynamicWidget.h" - #include "tool_view_builder.hpp" +#include "dynamicWidget.h" + using namespace scopy::gui; -ToolViewBuilder::ToolViewBuilder(const ToolViewRecipe& recipe, ChannelManager* channelManager, QWidget* parent) +ToolViewBuilder::ToolViewBuilder(const ToolViewRecipe &recipe, ChannelManager *channelManager, QWidget *parent) { m_toolView = new ToolView(parent); - if (recipe.hasRunBtn) { + if(recipe.hasRunBtn) { m_toolView->setRunBtnVisible(true); } - if (recipe.hasSingleBtn) { + if(recipe.hasSingleBtn) { m_toolView->setSingleBtnVisible(true); } - if (recipe.hasHelpBtn) { + if(recipe.hasHelpBtn) { m_toolView->setHelpBtnVisible(true); m_toolView->setUrlHelpBtn(recipe.helpBtnUrl); } - if (recipe.hasPrintBtn) { + if(recipe.hasPrintBtn) { m_toolView->setPrintBtnVisible(true); } - if (recipe.hasGroupBtn) { - QPushButton* btn = new QPushButton; + if(recipe.hasGroupBtn) { + QPushButton *btn = new QPushButton; btn->setStyleSheet("QPushButton{ width: 80px;" "height: 40px;" "text-align: left;" @@ -34,12 +34,12 @@ ToolViewBuilder::ToolViewBuilder(const ToolViewRecipe& recipe, ChannelManager* c m_toolView->addTopExtraWidget(btn); } - if (recipe.hasPairSettingsBtn) { + if(recipe.hasPairSettingsBtn) { m_toolView->setPairSettingsVisible(true); m_toolView->configureLastOpenedMenu(); } - if (recipe.hasChannels) { + if(recipe.hasChannels) { m_toolView->buildChannelsContainer(channelManager, recipe.channelsPosition); } @@ -47,4 +47,4 @@ ToolViewBuilder::ToolViewBuilder(const ToolViewRecipe& recipe, ChannelManager* c m_toolView->getSettingsBtn()->setVisible(recipe.hasHamburgerMenuBtn); } -ToolView* ToolViewBuilder::build() { return m_toolView; } +ToolView *ToolViewBuilder::build() { return m_toolView; } diff --git a/gui/src/tooltemplate.cpp b/gui/src/tooltemplate.cpp index 0075270de1..b24840bfdc 100644 --- a/gui/src/tooltemplate.cpp +++ b/gui/src/tooltemplate.cpp @@ -1,8 +1,10 @@ #include "tooltemplate.h" + #include "ui_tooltemplate.h" using namespace scopy; -ToolTemplate::ToolTemplate(QWidget *parent) : QWidget(parent) +ToolTemplate::ToolTemplate(QWidget *parent) + : QWidget(parent) { m_ui = new Ui::ToolTemplate(); m_ui->setupUi(this); @@ -28,75 +30,36 @@ ToolTemplate::ToolTemplate(QWidget *parent) : QWidget(parent) m_bottomStack->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); } -ToolTemplate::~ToolTemplate() -{ - delete m_ui; -} +ToolTemplate::~ToolTemplate() { delete m_ui; } -QWidget *ToolTemplate::bottomContainer() -{ - return m_ui->bottomContainer; -} +QWidget *ToolTemplate::bottomContainer() { return m_ui->bottomContainer; } -QWidget *ToolTemplate::topContainer() -{ - return m_ui->topContainer; -} +QWidget *ToolTemplate::topContainer() { return m_ui->topContainer; } -QWidget *ToolTemplate::topCentral() -{ - return m_ui->topCentral; -} +QWidget *ToolTemplate::topCentral() { return m_ui->topCentral; } -QWidget *ToolTemplate::bottomCentral() -{ - return m_ui->bottomCentral; -} +QWidget *ToolTemplate::bottomCentral() { return m_ui->bottomCentral; } -QWidget *ToolTemplate::rightContainer() -{ - return m_ui->rightContainer; -} +QWidget *ToolTemplate::rightContainer() { return m_ui->rightContainer; } -QWidget *ToolTemplate::topContainerMenuControl() -{ - return m_ui->topContainerMenuControl; -} +QWidget *ToolTemplate::topContainerMenuControl() { return m_ui->topContainerMenuControl; } -QWidget *ToolTemplate::centralContainer() -{ - return m_ui->centralContainer; -} +QWidget *ToolTemplate::centralContainer() { return m_ui->centralContainer; } -MapStackedWidget *ToolTemplate::leftStack() -{ - return m_leftStack; -} +MapStackedWidget *ToolTemplate::leftStack() { return m_leftStack; } -MapStackedWidget *ToolTemplate::rightStack() -{ - return m_rightStack; -} +MapStackedWidget *ToolTemplate::rightStack() { return m_rightStack; } -MapStackedWidget *ToolTemplate::topStack() -{ - return m_topStack; -} +MapStackedWidget *ToolTemplate::topStack() { return m_topStack; } -MapStackedWidget *ToolTemplate::bottomStack() -{ - return m_bottomStack; -} +MapStackedWidget *ToolTemplate::bottomStack() { return m_bottomStack; } -QWidget *ToolTemplate::leftContainer() -{ - return m_ui->leftContainer; -} +QWidget *ToolTemplate::leftContainer() { return m_ui->leftContainer; } void ToolTemplate::setLeftContainerWidth(int w) { - dynamic_cast(m_ui->leftContainer)->setAnimMin(0); - dynamic_cast(m_ui->leftContainer)->setAnimMax(w); + dynamic_cast(m_ui->leftContainer)->setAnimMin(0); + dynamic_cast(m_ui->leftContainer)->setAnimMax(w); m_ui->leftContainer->setMaximumWidth(w); m_ui->leftContainer->setMinimumWidth(w); } @@ -105,92 +68,79 @@ void ToolTemplate::setRightContainerWidth(int w) { m_ui->topContainerMenuControl->setMaximumWidth(w); m_ui->topContainerMenuControl->setMinimumWidth(w); - dynamic_cast(m_ui->rightContainer)->setAnimMin(0); - dynamic_cast(m_ui->rightContainer)->setAnimMax(w); + dynamic_cast(m_ui->rightContainer)->setAnimMin(0); + dynamic_cast(m_ui->rightContainer)->setAnimMax(w); m_ui->rightContainer->setMaximumWidth(w); m_ui->rightContainer->setMinimumWidth(w); } void ToolTemplate::setTopContainerHeight(int h) { - dynamic_cast(m_ui->topCentral)->setAnimMin(0); - dynamic_cast(m_ui->topCentral)->setAnimMax(h); + dynamic_cast(m_ui->topCentral)->setAnimMin(0); + dynamic_cast(m_ui->topCentral)->setAnimMax(h); m_ui->topCentral->setMaximumHeight(h); m_ui->topCentral->setMinimumHeight(h); } void ToolTemplate::setBottomContainerHeight(int h) { - dynamic_cast(m_ui->bottomCentral)->setAnimMin(0); - dynamic_cast(m_ui->bottomCentral)->setAnimMax(h); + dynamic_cast(m_ui->bottomCentral)->setAnimMin(0); + dynamic_cast(m_ui->bottomCentral)->setAnimMax(h); m_ui->bottomCentral->setMaximumHeight(h); m_ui->bottomCentral->setMinimumHeight(h); } -void ToolTemplate::openLeftContainerHelper(bool open) -{ - m_ui->leftContainer->toggleMenu(open); -} +void ToolTemplate::openLeftContainerHelper(bool open) { m_ui->leftContainer->toggleMenu(open); } -void ToolTemplate::openRightContainerHelper(bool open) -{ - m_ui->rightContainer->toggleMenu(open); -} +void ToolTemplate::openRightContainerHelper(bool open) { m_ui->rightContainer->toggleMenu(open); } -void ToolTemplate::openTopContainerHelper(bool open) -{ - m_ui->topCentral->toggleMenu(open); -} - -void ToolTemplate::openBottomContainerHelper(bool open) -{ - m_ui->bottomCentral->toggleMenu(open); -} +void ToolTemplate::openTopContainerHelper(bool open) { m_ui->topCentral->toggleMenu(open); } +void ToolTemplate::openBottomContainerHelper(bool open) { m_ui->bottomCentral->toggleMenu(open); } void ToolTemplate::addWidgetToTopContainerHelper(QWidget *w, ToolTemplateAlignment a) { - auto lay1 = dynamic_cast(topContainer()->layout()); + auto lay1 = dynamic_cast(topContainer()->layout()); Q_ASSERT(lay1 != nullptr); auto idx = lay1->indexOf(m_ui->topContainerSpacer); int offset; if(a == TTA_LEFT) { - lay1->insertWidget(idx,w); + lay1->insertWidget(idx, w); } else { - lay1->insertWidget(-1,w); + lay1->insertWidget(-1, w); } } -void ToolTemplate::addWidgetToTopContainerMenuControlHelper(QWidget *w, ToolTemplateAlignment a) { - auto lay1 = dynamic_cast(topContainerMenuControl()->layout()); +void ToolTemplate::addWidgetToTopContainerMenuControlHelper(QWidget *w, ToolTemplateAlignment a) +{ + auto lay1 = dynamic_cast(topContainerMenuControl()->layout()); Q_ASSERT(lay1 != nullptr); auto idx = lay1->indexOf(m_ui->topContainerMenuControlSpacer); int offset; if(a == TTA_LEFT) { - lay1->insertWidget(idx,w); + lay1->insertWidget(idx, w); } else { - lay1->insertWidget(-1,w); - } + lay1->insertWidget(-1, w); + } } void ToolTemplate::addWidgetToBottomContainerHelper(QWidget *w, ToolTemplateAlignment a) { - auto lay1 = dynamic_cast(bottomContainer()->layout()); + auto lay1 = dynamic_cast(bottomContainer()->layout()); Q_ASSERT(lay1 != nullptr); auto idx = lay1->indexOf(m_ui->bottomContainerSpacer); int offset; if(a == TTA_LEFT) { - lay1->insertWidget(idx,w); + lay1->insertWidget(idx, w); } else { - lay1->insertWidget(-1,w); + lay1->insertWidget(-1, w); } - } void ToolTemplate::addWidgetToCentralContainerHelper(QWidget *w) { - auto lay1 = dynamic_cast(centralContainer()->layout()); + auto lay1 = dynamic_cast(centralContainer()->layout()); Q_ASSERT(lay1 != nullptr); lay1->addWidget(w); @@ -218,7 +168,3 @@ void ToolTemplate::requestMenu(QString key) return; } } - - - - diff --git a/gui/src/tutorialbuilder.cpp b/gui/src/tutorialbuilder.cpp index 76210b58cf..78594a10e8 100644 --- a/gui/src/tutorialbuilder.cpp +++ b/gui/src/tutorialbuilder.cpp @@ -18,134 +18,127 @@ * along with this program. If not, see . */ - #include "tutorialbuilder.h" -#include -#include -#include -#include -#include + #include +#include +#include +#include + +#include +#include using namespace scopy::gui; Q_LOGGING_CATEGORY(CAT_TUTORIALBUILDER, "TutorialBuilder") -TutorialBuilder::TutorialBuilder(QWidget *topWidget, const QString& jsonFile, QString jsonEntry, QWidget *parent) : - scopy::gui::TutorialOverlay(parent), - m_topWidget(topWidget), - m_jsonFile(jsonFile), - m_jsonEntry(std::move(jsonEntry)) +TutorialBuilder::TutorialBuilder(QWidget *topWidget, const QString &jsonFile, QString jsonEntry, QWidget *parent) + : scopy::gui::TutorialOverlay(parent) + , m_topWidget(topWidget) + , m_jsonFile(jsonFile) + , m_jsonEntry(std::move(jsonEntry)) { - if (!m_jsonFile.exists()) { + if(!m_jsonFile.exists()) { qWarning(CAT_TUTORIALBUILDER) << "The file" << jsonFile << "does not exist."; } qDebug(CAT_TUTORIALBUILDER) << "Tutorial Builder constructed for json entry" << m_jsonEntry; } -TutorialBuilder::TutorialBuilder(QWidget *parent) : - scopy::gui::TutorialOverlay(parent), - m_topWidget(nullptr), - m_jsonFile(nullptr) +TutorialBuilder::TutorialBuilder(QWidget *parent) + : scopy::gui::TutorialOverlay(parent) + , m_topWidget(nullptr) + , m_jsonFile(nullptr) { qDebug(CAT_TUTORIALBUILDER) << "Tutorial Builder constructed"; } -QString TutorialBuilder::getJsonFileName() const { - return m_jsonFile.fileName(); -} +QString TutorialBuilder::getJsonFileName() const { return m_jsonFile.fileName(); } -void TutorialBuilder::setJsonFileName(const QString &jsonFile) { +void TutorialBuilder::setJsonFileName(const QString &jsonFile) +{ m_jsonFile.setFileName(jsonFile); - if (!m_jsonFile.exists()) { + if(!m_jsonFile.exists()) { qWarning(CAT_TUTORIALBUILDER) << "The file" << jsonFile << "does not exist."; } } -const QString &TutorialBuilder::getJsonEntry() const { - return m_jsonEntry; -} +const QString &TutorialBuilder::getJsonEntry() const { return m_jsonEntry; } -void TutorialBuilder::setJsonEntry(const QString &jsonEntry) { - m_jsonEntry = jsonEntry; -} +void TutorialBuilder::setJsonEntry(const QString &jsonEntry) { m_jsonEntry = jsonEntry; } -QWidget *TutorialBuilder::getTopWidget() const { - return m_topWidget; -} +QWidget *TutorialBuilder::getTopWidget() const { return m_topWidget; } -void TutorialBuilder::setTopWidget(QWidget *topWidget) { - m_topWidget = topWidget; -} +void TutorialBuilder::setTopWidget(QWidget *topWidget) { m_topWidget = topWidget; } -void TutorialBuilder::start() { +void TutorialBuilder::start() +{ try { this->readTutorialRequirements(); uint16_t chaptersCollected = this->collectChapters(); qInfo(CAT_TUTORIALBUILDER) << "Chapters collected" << chaptersCollected; TutorialOverlay::start(); - } catch (std::runtime_error& error) { + } catch(std::runtime_error &error) { qCritical(CAT_TUTORIALBUILDER) << "Cannot start tutorial:" << error.what(); } } -uint16_t TutorialBuilder::collectChapters() { - if (!m_topWidget) { +uint16_t TutorialBuilder::collectChapters() +{ + if(!m_topWidget) { throw std::runtime_error("No top widget was provided."); } - uint16_t chaptersCollected = 0; // number of objects that are part of the tutorial + uint16_t chaptersCollected = 0; // number of objects that are part of the tutorial uint16_t totalChaptersCollected = 0; // total number of objects collected, used only as debug statistic // collect all children objects from m_topWidget recursively - QObjectList childrenList = m_topWidget->findChildren(QRegularExpression(".*"), Qt::FindChildrenRecursively); + QObjectList childrenList = + m_topWidget->findChildren(QRegularExpression(".*"), Qt::FindChildrenRecursively); - for (auto child: childrenList) { + for(auto child : childrenList) { QString currentObjectName = child->property("tutorial_name").toString(); // if the object has no property named "tutorial_name", then it is not part of the tutorial - if (!currentObjectName.isEmpty()) { + if(!currentObjectName.isEmpty()) { try { // get the chapters that use the widget with the property name currentObjectName - QList chapters = this->getChapterInstructionFromName(currentObjectName); - for (auto chapter: chapters) { - chapter->widgets[currentObjectName] = qobject_cast(child); + QList chapters = + this->getChapterInstructionFromName(currentObjectName); + for(auto chapter : chapters) { + chapter->widgets[currentObjectName] = qobject_cast(child); } ++chaptersCollected; - } catch (std::runtime_error &error) { + } catch(std::runtime_error &error) { qCritical(CAT_TUTORIALBUILDER) << error.what(); } } ++totalChaptersCollected; } - qDebug(CAT_TUTORIALBUILDER) << "Collected a total of" << totalChaptersCollected << "in the" << m_jsonEntry << "entry."; + qDebug(CAT_TUTORIALBUILDER) << "Collected a total of" << totalChaptersCollected << "in the" << m_jsonEntry + << "entry."; // add the now sorted chapters into the tutorial overlay - for (const ChapterInstructions *chapter: qAsConst(m_chapters)) { + for(const ChapterInstructions *chapter : qAsConst(m_chapters)) { // if there is no mainWidget specified, the first widget from the list will be set to be the mainWidget - this->addChapter( - chapter->widgets.values(), - chapter->description, - (chapter->mainWidget.isNull()) ? chapter->widgets.first() : chapter->widgets[chapter->mainWidget], - chapter->x_offset, - chapter->y_offset, - chapter->anchor, - chapter->content - ); + this->addChapter(chapter->widgets.values(), chapter->description, + (chapter->mainWidget.isNull()) ? chapter->widgets.first() + : chapter->widgets[chapter->mainWidget], + chapter->x_offset, chapter->y_offset, chapter->anchor, chapter->content); } return chaptersCollected; } -void TutorialBuilder::readTutorialRequirements() { +void TutorialBuilder::readTutorialRequirements() +{ // open and read the file - if (m_jsonFile.fileName().isEmpty()) { + if(m_jsonFile.fileName().isEmpty()) { throw std::runtime_error("No file name was provided."); } m_jsonFile.open(QIODevice::ReadOnly | QIODevice::Text); - if (!m_jsonFile.isOpen()) { + if(!m_jsonFile.isOpen()) { throw std::runtime_error("File could not be opened (read): " + m_jsonFile.fileName().toStdString()); } else { qDebug(CAT_TUTORIALBUILDER) << "File opened (read): " << m_jsonFile.fileName(); @@ -156,14 +149,14 @@ void TutorialBuilder::readTutorialRequirements() { // try to parse the contents as a json QJsonParseError parse_error{}; QJsonDocument document = QJsonDocument::fromJson(contents.toUtf8(), &parse_error); - if (document.isNull()) { + if(document.isNull()) { throw std::runtime_error("Invalid json: " + parse_error.errorString().toStdString()); } // extract the values related to the m_jsonEntry mode QJsonObject document_object = document.object(); QJsonValue value = document_object.value(m_jsonEntry); - if (value == QJsonValue::Undefined) { + if(value == QJsonValue::Undefined) { throw std::runtime_error("Invalid json: Could not extract value " + m_jsonEntry.toStdString()); } @@ -180,12 +173,12 @@ void TutorialBuilder::readTutorialRequirements() { // "content": string, HoverPosition, optional // } QJsonArray chapters_array = value.toArray(); - for (QJsonValueRef item: chapters_array) { + for(QJsonValueRef item : chapters_array) { QJsonObject item_object = item.toObject(); int index = item_object.value("index").toInt(-1); QStringList names; QJsonArray jsonNameArray = item_object.value("names").toArray(); - for (auto name: jsonNameArray) { + for(auto name : jsonNameArray) { names.push_back(name.toString()); } QString description = item_object.value("description").toString(); @@ -198,7 +191,7 @@ void TutorialBuilder::readTutorialRequirements() { HoverPosition content = convertStringToHoverPosition(contentString); auto *chapterInstructions = new ChapterInstructions; - for (const auto& name: qAsConst(names)) { + for(const auto &name : qAsConst(names)) { chapterInstructions->widgets.insert(name, nullptr); // the widgets will be set later } chapterInstructions->mainWidget = mainWidget; @@ -207,7 +200,7 @@ void TutorialBuilder::readTutorialRequirements() { chapterInstructions->y_offset = y_offset; chapterInstructions->anchor = anchor; chapterInstructions->content = content; - if (m_chapters.contains(index)) { + if(m_chapters.contains(index)) { qWarning(CAT_TUTORIALBUILDER) << "There is already a chapter with the key" << index; } else { m_chapters.insert(index, chapterInstructions); @@ -215,40 +208,42 @@ void TutorialBuilder::readTutorialRequirements() { } } -QList TutorialBuilder::getChapterInstructionFromName(const QString& name) { - QList result; - for (auto& chapter: m_chapters) { +QList TutorialBuilder::getChapterInstructionFromName(const QString &name) +{ + QList result; + for(auto &chapter : m_chapters) { const QList keys = chapter->widgets.keys(); - for (const auto& itemName: keys) { - if (itemName == name) { + for(const auto &itemName : keys) { + if(itemName == name) { result.push_back(chapter); } } } - if (result.isEmpty()) { + if(result.isEmpty()) { throw std::runtime_error("No ChapterInstructions that need this name were found."); } else { return result; } } -scopy::HoverPosition TutorialBuilder::convertStringToHoverPosition(const QString &position) noexcept { - if (position == "HP_LEFT") { +scopy::HoverPosition TutorialBuilder::convertStringToHoverPosition(const QString &position) noexcept +{ + if(position == "HP_LEFT") { return scopy::HoverPosition::HP_LEFT; - } else if (position == "HP_TOPLEFT") { + } else if(position == "HP_TOPLEFT") { return scopy::HoverPosition::HP_TOPLEFT; - } else if (position == "HP_TOP") { + } else if(position == "HP_TOP") { return scopy::HoverPosition::HP_TOP; - } else if (position == "HP_TOPRIGHT") { + } else if(position == "HP_TOPRIGHT") { return scopy::HoverPosition::HP_TOPRIGHT; - } else if (position == "HP_RIGHT") { + } else if(position == "HP_RIGHT") { return scopy::HoverPosition::HP_RIGHT; - } else if (position == "HP_BOTTOMRIGHT") { + } else if(position == "HP_BOTTOMRIGHT") { return scopy::HoverPosition::HP_BOTTOMRIGHT; - } else if (position == "HP_BOTTOM") { + } else if(position == "HP_BOTTOM") { return scopy::HoverPosition::HP_BOTTOM; - } else if (position == "HP_BOTTOMLEFT") { + } else if(position == "HP_BOTTOMLEFT") { return scopy::HoverPosition::HP_BOTTOMLEFT; } else { // position == "HP_CENTER" return scopy::HoverPosition::HP_CENTER; diff --git a/gui/src/tutorialchapter.cpp b/gui/src/tutorialchapter.cpp index b2308b14e9..7ed6d5d73c 100644 --- a/gui/src/tutorialchapter.cpp +++ b/gui/src/tutorialchapter.cpp @@ -18,30 +18,22 @@ * along with this program. If not, see . */ - #include "tutorialchapter.h" + #include using namespace scopy::gui; Q_LOGGING_CATEGORY(CAT_TUTORIALCHAPTER, "TutorialChapter") -TutorialChapter::TutorialChapter(QObject *parent) : QObject(parent) -{ +TutorialChapter::TutorialChapter(QObject *parent) + : QObject(parent) +{} -} +TutorialChapter::~TutorialChapter() {} -TutorialChapter::~TutorialChapter() -{ - -} - -TutorialChapter *TutorialChapter::build(const QList& subjects, - const QString& description, - QWidget* mainSubject, - int x_offset, - int y_offset, - HoverPosition anchor, +TutorialChapter *TutorialChapter::build(const QList &subjects, const QString &description, + QWidget *mainSubject, int x_offset, int y_offset, HoverPosition anchor, HoverPosition content, QObject *parent) { TutorialChapter *ch = new TutorialChapter(parent); @@ -57,60 +49,36 @@ TutorialChapter *TutorialChapter::build(const QList& subjects, return ch; } -void TutorialChapter::addSubject(QWidget *s) -{ - subjects.append(s); -} +void TutorialChapter::addSubject(QWidget *s) { subjects.append(s); } -const QString &TutorialChapter::getDescription() const -{ - return description; -} +const QString &TutorialChapter::getDescription() const { return description; } -void TutorialChapter::setDescription(const QString &newDescription) -{ - description = newDescription; -} +void TutorialChapter::setDescription(const QString &newDescription) { description = newDescription; } -QWidget *TutorialChapter::getMainSubject() const { - return mainSubject; -} +QWidget *TutorialChapter::getMainSubject() const { return mainSubject; } -void TutorialChapter::setMainSubject(QWidget *newMainSubject) { - if (!subjects.contains(newMainSubject)) { +void TutorialChapter::setMainSubject(QWidget *newMainSubject) +{ + if(!subjects.contains(newMainSubject)) { qWarning(CAT_TUTORIALCHAPTER) << "The new main subject is not part of the subject list."; } this->mainSubject = newMainSubject; } -int TutorialChapter::getXOffset() const { - return x_offset; -} +int TutorialChapter::getXOffset() const { return x_offset; } -void TutorialChapter::setXOffset(int xOffset) { - x_offset = xOffset; -} +void TutorialChapter::setXOffset(int xOffset) { x_offset = xOffset; } -int TutorialChapter::getYOffset() const { - return y_offset; -} +int TutorialChapter::getYOffset() const { return y_offset; } -void TutorialChapter::setYOffset(int yOffset) { - y_offset = yOffset; -} +void TutorialChapter::setYOffset(int yOffset) { y_offset = yOffset; } -scopy::HoverPosition TutorialChapter::getAnchor() const { - return anchor; -} +scopy::HoverPosition TutorialChapter::getAnchor() const { return anchor; } -void TutorialChapter::setAnchor(scopy::HoverPosition newAnchor) { - anchor = newAnchor; -} +void TutorialChapter::setAnchor(scopy::HoverPosition newAnchor) { anchor = newAnchor; } -scopy::HoverPosition TutorialChapter::getContent() const { - return content; -} +scopy::HoverPosition TutorialChapter::getContent() const { return content; } -void TutorialChapter::setContent(scopy::HoverPosition newContent) { - content = newContent; -} +void TutorialChapter::setContent(scopy::HoverPosition newContent) { content = newContent; } + +#include "moc_tutorialchapter.cpp" diff --git a/gui/src/tutorialoverlay.cpp b/gui/src/tutorialoverlay.cpp index 902889d2b1..9d115693f9 100644 --- a/gui/src/tutorialoverlay.cpp +++ b/gui/src/tutorialoverlay.cpp @@ -18,43 +18,37 @@ * along with this program. If not, see . */ - #include "tutorialoverlay.h" + +#include "ui_tutorial.h" + #include #include + #include -#include "ui_tutorial.h" -Q_LOGGING_CATEGORY(CAT_TUTORIALOVERLAY,"TutorialOverlay"); +Q_LOGGING_CATEGORY(CAT_TUTORIALOVERLAY, "TutorialOverlay"); using namespace scopy::gui; TutorialOverlay::TutorialOverlay(QWidget *parent) - : QWidget(parent), parent(parent) + : QWidget(parent) + , parent(parent) { - qDebug(CAT_TUTORIALOVERLAY)<<"ctor"; + qDebug(CAT_TUTORIALOVERLAY) << "ctor"; overlay = nullptr; } -TutorialOverlay::~TutorialOverlay() -{ - qDebug(CAT_TUTORIALOVERLAY)<<"dtor"; -} +TutorialOverlay::~TutorialOverlay() { qDebug(CAT_TUTORIALOVERLAY) << "dtor"; } -TutorialChapter* TutorialOverlay::addChapter(const QList& subjects, - const QString& description, - QWidget* mainWidget, - int x_offset, - int y_offset, - HoverPosition anchor, +TutorialChapter *TutorialOverlay::addChapter(const QList &subjects, const QString &description, + QWidget *mainWidget, int x_offset, int y_offset, HoverPosition anchor, HoverPosition content) { // in case TutorialOverlay is used without TutorialBuilder - if (!mainWidget) { + if(!mainWidget) { mainWidget = subjects[0]; } - TutorialChapter* ch = TutorialChapter::build(subjects, description, - mainWidget, - x_offset, y_offset, - anchor, content, this); + TutorialChapter *ch = + TutorialChapter::build(subjects, description, mainWidget, x_offset, y_offset, anchor, content, this); chapter.append(ch); ch->setMainSubject(mainWidget); return ch; @@ -62,7 +56,7 @@ TutorialChapter* TutorialOverlay::addChapter(const QList& subjects, TutorialChapter *TutorialOverlay::addChapter(QWidget *subject, QString description) { - QList list; + QList list; // pass empty list if subject is nullptr if(subject != nullptr) @@ -71,14 +65,11 @@ TutorialChapter *TutorialOverlay::addChapter(QWidget *subject, QString descripti return addChapter(list, description, subject); // if there is only one widget, it will be the main widget } -void TutorialOverlay::addChapter(TutorialChapter *ch) -{ - chapter.append(ch); -} +void TutorialOverlay::addChapter(TutorialChapter *ch) { chapter.append(ch); } void TutorialOverlay::start() { - qInfo(CAT_TUTORIALOVERLAY)<<"Tutorial started"; + qInfo(CAT_TUTORIALOVERLAY) << "Tutorial started"; cnt = 0; buildUi(); @@ -106,7 +97,7 @@ void TutorialOverlay::next() overlay->raise(); overlay->clearHoles(); - QList subjects = chapter[cnt]->subjects; + QList subjects = chapter[cnt]->subjects; if(!subjects.isEmpty()) { overlay->setHoles(subjects); @@ -117,10 +108,10 @@ void TutorialOverlay::next() m_hoverWidget->raise(); m_hoverWidget->setVisible(true); - for (QWidget *subj : qAsConst(subjects)) { + for(QWidget *subj : qAsConst(subjects)) { subj->raise(); m_popupWidget->setFocusOnContinueButton(); - auto* highlight = new TintedOverlay(subj,QColor(255,255,255,35)); + auto *highlight = new TintedOverlay(subj, QColor(255, 255, 255, 35)); highlight->raise(); highlight->show(); highlights.append(highlight); @@ -139,15 +130,17 @@ void TutorialOverlay::next() m_popupWidget->getContinueBtn()->setText("Finish"); } -void TutorialOverlay::finish() { - qInfo(CAT_TUTORIALOVERLAY)<<"Tutorial Finished"; +void TutorialOverlay::finish() +{ + qInfo(CAT_TUTORIALOVERLAY) << "Tutorial Finished"; overlay->deleteLater(); cleanupChapter(); Q_EMIT finished(); } -void TutorialOverlay::abort() { +void TutorialOverlay::abort() +{ qInfo(CAT_TUTORIALOVERLAY) << "Tutorial Aborted"; cleanupChapter(); overlay->deleteLater(); @@ -158,7 +151,7 @@ void TutorialOverlay::abort() { void TutorialOverlay::buildUi() { - qDebug(CAT_TUTORIALOVERLAY)<<"build"; + qDebug(CAT_TUTORIALOVERLAY) << "build"; overlay = new TintedOverlay(parent); initPopupWidget(); @@ -167,17 +160,19 @@ void TutorialOverlay::buildUi() overlay->show(); } -void TutorialOverlay::initPopupWidget() { +void TutorialOverlay::initPopupWidget() +{ m_popupWidget = new PopupWidget(); m_popupWidget->setFocusOnContinueButton(); connect(m_popupWidget, &PopupWidget::continueButtonClicked, this, &TutorialOverlay::next); connect(m_popupWidget, &PopupWidget::exitButtonClicked, this, &TutorialOverlay::abort); } -void TutorialOverlay::cleanupChapter() { +void TutorialOverlay::cleanupChapter() +{ if(!highlights.isEmpty()) { // delete previous highlight - for (TintedOverlay *highlight : qAsConst(highlights)) { + for(TintedOverlay *highlight : qAsConst(highlights)) { delete highlight; } highlights.clear(); @@ -187,21 +182,15 @@ void TutorialOverlay::cleanupChapter() { } } +const QString &TutorialOverlay::getTitle() const { return title; } -const QString &TutorialOverlay::getTitle() const -{ - return title; -} +void TutorialOverlay::setTitle(const QString &newTitle) { title = newTitle; } -void TutorialOverlay::setTitle(const QString &newTitle) +bool TutorialOverlay::eventFilter(QObject *watched, QEvent *event) { - title = newTitle; -} - -bool TutorialOverlay::eventFilter(QObject *watched, QEvent *event) { - if (watched == this->parent && event->type() == QEvent::Resize) { - QWidget* w = qobject_cast(watched); - if (w) { + if(watched == this->parent && event->type() == QEvent::Resize) { + QWidget *w = qobject_cast(watched); + if(w) { QSize s = w->size(); this->overlay->resize(s); } diff --git a/gui/src/utils.cpp b/gui/src/utils.cpp index 68f81c9106..6151816d88 100644 --- a/gui/src/utils.cpp +++ b/gui/src/utils.cpp @@ -40,15 +40,17 @@ */ #include "utils.h" + #include "QtSvg/qsvgrenderer.h" #include "qpainter.h" -#include -#include -#include + #include -#include #include +#include +#include +#include +#include void Util::retainWidgetSizeWhenHidden(QWidget *w, bool retain) { @@ -57,16 +59,15 @@ void Util::retainWidgetSizeWhenHidden(QWidget *w, bool retain) w->setSizePolicy(sp_retain); } -void Util::setWidgetNrOfChars(QWidget *w, - int minNrOfChars, int maxNrOfChars) +void Util::setWidgetNrOfChars(QWidget *w, int minNrOfChars, int maxNrOfChars) { QFontMetrics labelm(w->font()); - auto label_min_width = labelm.horizontalAdvance(QString(minNrOfChars,'X')); + auto label_min_width = labelm.horizontalAdvance(QString(minNrOfChars, 'X')); w->setMinimumWidth(label_min_width); - if (maxNrOfChars!=0) { - auto label_max_width = labelm.horizontalAdvance(QString(maxNrOfChars,'X')); + if(maxNrOfChars != 0) { + auto label_max_width = labelm.horizontalAdvance(QString(maxNrOfChars, 'X')); w->setMaximumWidth(label_max_width); } } @@ -79,19 +80,20 @@ QString Util::loadStylesheetFromFile(const QString &path) return stylesheet; } -bool Util::compareNatural(const std::string& a, const std::string& b) { - if (a == b) { +bool Util::compareNatural(const std::string &a, const std::string &b) +{ + if(a == b) { return (a < b); - } else if (a.empty()) { + } else if(a.empty()) { return true; - } else if (b.empty()) { + } else if(b.empty()) { return false; - } else if (std::isdigit(a[0]) && !std::isdigit(b[0])) { + } else if(std::isdigit(a[0]) && !std::isdigit(b[0])) { return true; - } else if (!std::isdigit(a[0]) && std::isdigit(b[0])) { + } else if(!std::isdigit(a[0]) && std::isdigit(b[0])) { return false; - } else if (!std::isdigit(a[0]) && !std::isdigit(b[0])) { - if (a[0] == b[0]) { + } else if(!std::isdigit(a[0]) && !std::isdigit(b[0])) { + if(a[0] == b[0]) { return compareNatural(a.substr(1), b.substr(1)); } return (a < b); @@ -105,7 +107,7 @@ bool Util::compareNatural(const std::string& a, const std::string& b) { string_stream_a >> int_a; string_stream_b >> int_b; - if (int_a != int_b) { + if(int_a != int_b) { return (int_a < int_b); } @@ -116,21 +118,21 @@ bool Util::compareNatural(const std::string& a, const std::string& b) { QWidget *Util::findContainingWindow(QWidget *w) { - while(dynamic_cast(w->parent())!=nullptr) - w = dynamic_cast(w->parent()); + while(dynamic_cast(w->parent()) != nullptr) + w = dynamic_cast(w->parent()); return w; } QDockWidget *DockerUtils::createDockWidget(QMainWindow *mainWindow, QWidget *widget, const QString &title) { - QDockWidget* dockWidget = new QDockWidget(title, mainWindow); + QDockWidget *dockWidget = new QDockWidget(title, mainWindow); dockWidget->setFeatures(dockWidget->features() & ~QDockWidget::DockWidgetClosable); dockWidget->setAllowedAreas(Qt::AllDockWidgetAreas); dockWidget->setWidget(widget); #ifdef __ANDROID__ - dockWidget->setFeatures(dockWidget->features() & ~QDockWidget::DockWidgetClosable - & ~QDockWidget::DockWidgetFloatable); + dockWidget->setFeatures(dockWidget->features() & ~QDockWidget::DockWidgetClosable & + ~QDockWidget::DockWidgetFloatable); #endif return dockWidget; @@ -138,30 +140,32 @@ QDockWidget *DockerUtils::createDockWidget(QMainWindow *mainWindow, QWidget *wid void DockerUtils::configureTopBar(QDockWidget *docker) { - connect(docker, &QDockWidget::topLevelChanged, [=](bool topLevel){ + connect(docker, &QDockWidget::topLevelChanged, [=](bool topLevel) { QString icon_path = ""; - if (QIcon::themeName() == "scopy-default") { - icon_path +=":/gui/icons/scopy-default/icons"; + if(QIcon::themeName() == "scopy-default") { + icon_path += ":/gui/icons/scopy-default/icons"; } else { - icon_path +=":/gui/icons/scopy-light/icons"; + icon_path += ":/gui/icons/scopy-light/icons"; } if(topLevel) { - docker->setWindowFlags(Qt::CustomizeWindowHint | - Qt::Window | - Qt::WindowMinimizeButtonHint | + docker->setWindowFlags(Qt::CustomizeWindowHint | Qt::Window | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint); docker->show(); docker->setStyleSheet("QDockWidget {" - "titlebar-normal-icon: url(" + icon_path + "/sba_cmb_box_arrow.svg);" - "}"); + "titlebar-normal-icon: url(" + + icon_path + + "/sba_cmb_box_arrow.svg);" + "}"); docker->setContentsMargins(10, 0, 10, 10); } else { docker->setStyleSheet("QDockWidget {" - "titlebar-normal-icon: url(" + icon_path + "/sba_cmb_box_arrow_right.svg);" - "}"); + "titlebar-normal-icon: url(" + + icon_path + + "/sba_cmb_box_arrow_right.svg);" + "}"); docker->setContentsMargins(0, 0, 0, 0); } }); @@ -170,15 +174,12 @@ void DockerUtils::configureTopBar(QDockWidget *docker) void Util::SetAttrRecur(QDomElement &elem, QString strtagname, QString strattr, QString strattrval) { // if it has the tagname then overwritte desired attribute - if (elem.tagName().compare(strtagname) == 0) - { + if(elem.tagName().compare(strtagname) == 0) { elem.setAttribute(strattr, strattrval); } // loop all children - for (int i = 0; i < elem.childNodes().count(); i++) - { - if (!elem.childNodes().at(i).isElement()) - { + for(int i = 0; i < elem.childNodes().count(); i++) { + if(!elem.childNodes().at(i).isElement()) { continue; } QDomElement docElem = elem.childNodes().at(i).toElement(); //<-- make const "variable" @@ -199,7 +200,7 @@ void Util::SetAttrRecur(QDomElement &elem, QString strtagname, QString strattr, // recurivelly change color QDomElement docElem = doc.documentElement(); //<-- make const "variable" SetAttrRecur(docElem, "path", "fill", color); - SetAttrRecur(docElem, "path", "opacity", QString::number(opacity,'g', 2)); + SetAttrRecur(docElem, "path", "opacity", QString::number(opacity, 'g', 2)); // create svg renderer with edited contents QSvgRenderer svgRenderer(doc.toByteArray()); // create pixmap target (could be a QImage) @@ -210,6 +211,6 @@ void Util::SetAttrRecur(QDomElement &elem, QString strtagname, QString strattr, // use renderer to render over painter which paints on pixmap svgRenderer.render(&pixPainter); return pix; -// QIcon myicon(pix); -// return myicon; + // QIcon myicon(pix); + // return myicon; } diff --git a/gui/src/vcursor.cpp b/gui/src/vcursor.cpp index 6af1507b05..0648a7dde8 100644 --- a/gui/src/vcursor.cpp +++ b/gui/src/vcursor.cpp @@ -2,13 +2,12 @@ using namespace scopy; - -VCursor::VCursor(PlotWidget *p, PlotAxis *ax, bool right, QPen pen) : - Cursor(p, ax, pen) +VCursor::VCursor(PlotWidget *p, PlotAxis *ax, bool right, QPen pen) + : Cursor(p, ax, pen) { m_symbolCtrl = p->symbolCtrl(); m_cursorBar = new HorizBar(p->plot()); - auto hCursorBar = static_cast(m_cursorBar); + auto hCursorBar = static_cast(m_cursorBar); m_symbolCtrl->attachSymbol(m_cursorBar); m_cursorBar->setCanLeavePlot(!m_canLeavePlot); @@ -16,41 +15,33 @@ VCursor::VCursor(PlotWidget *p, PlotAxis *ax, bool right, QPen pen) : m_cursorBar->setMobileAxis(m_axis->axisId()); m_cursorBar->setPen(pen); - m_cursorHandle = new PlotLineHandleV( - QPixmap(":/gui/icons/v_cursor_handle.svg"), - (right) ? p->rightHandlesArea() : p->leftHandlesArea(), !right); + m_cursorHandle = new PlotLineHandleV(QPixmap(":/gui/icons/v_cursor_handle.svg"), + (right) ? p->rightHandlesArea() : p->leftHandlesArea(), !right); - auto m_hCursorHandle = static_cast(m_cursorHandle); + auto m_hCursorHandle = static_cast(m_cursorHandle); m_hCursorHandle->setPen(pen); m_hCursorHandle->setVisible(true); /* When bar position changes due to plot resizes update the handle */ - connect(p->rightHandlesArea(), &HandlesArea::sizeChanged, m_cursorHandle, [=](){ - m_hCursorHandle->updatePosition(); - }); + connect(p->rightHandlesArea(), &HandlesArea::sizeChanged, m_cursorHandle, + [=]() { m_hCursorHandle->updatePosition(); }); connect(hCursorBar, &HorizBar::pixelPositionChanged, this, - [=](int pos) { - m_hCursorHandle->setPositionSilenty(pos); - }); - - connect(m_cursorHandle, &PlotLineHandleV::positionChanged, this, - [=](int pos) { - double new_pos = computePosition(pos); - if (!m_canLeavePlot) { - new_pos = std::max(std::min(m_axis->max(), new_pos), m_axis->min()); - } - hCursorBar->setPosition(new_pos); - Q_EMIT positionChanged(new_pos); - }); + [=](int pos) { m_hCursorHandle->setPositionSilenty(pos); }); + + connect(m_cursorHandle, &PlotLineHandleV::positionChanged, this, [=](int pos) { + double new_pos = computePosition(pos); + if(!m_canLeavePlot) { + new_pos = std::max(std::min(m_axis->max(), new_pos), m_axis->min()); + } + hCursorBar->setPosition(new_pos); + Q_EMIT positionChanged(new_pos); + }); connect(this, &VCursor::update, m_hCursorHandle, &PlotLineHandleV::triggerMove); } -VCursor::~VCursor() -{ - -} +VCursor::~VCursor() {} void VCursor::setCanLeavePlot(bool leave) { @@ -58,20 +49,20 @@ void VCursor::setCanLeavePlot(bool leave) m_cursorBar->setCanLeavePlot(m_canLeavePlot); } -double VCursor::getPosition() -{ - return static_cast(m_cursorBar)->getPosition(); -} +double VCursor::getPosition() { return static_cast(m_cursorBar)->getPosition(); } void VCursor::setPosition(double pos) { // cursors cannot be outside of the axis pos = std::max(std::min(m_axis->max(), pos), m_axis->min()); - static_cast(m_cursorBar)->setPosition(pos); + static_cast(m_cursorBar)->setPosition(pos); } -double VCursor::computePosition(int pos) { +double VCursor::computePosition(int pos) +{ QwtScaleMap yMap = m_plot->canvasMap(m_axis->axisId()); double offset = yMap.invTransform(pos); return offset; } + +#include "moc_vcursor.cpp" diff --git a/gui/src/waterfallGlobalData.cc b/gui/src/waterfallGlobalData.cc index 829e5b1c49..2247a89cc2 100644 --- a/gui/src/waterfallGlobalData.cc +++ b/gui/src/waterfallGlobalData.cc @@ -31,26 +31,26 @@ #define WATERFALL_GLOBAL_DATA_CPP #include "waterfallGlobalData.h" -#include + #include +#include -WaterfallData::WaterfallData(const double minimumFrequency, - const double maximumFrequency, - const uint64_t fftPoints, +WaterfallData::WaterfallData(const double minimumFrequency, const double maximumFrequency, const uint64_t fftPoints, const unsigned int historyExtent) #if QWT_VERSION < 0x060000 - : QwtRasterData(QwtDoubleRect(minimumFrequency /* X START */, - 0 /* Y START */, + : QwtRasterData(QwtDoubleRect(minimumFrequency /* X START */, 0 /* Y START */, maximumFrequency - minimumFrequency /* WIDTH */, - static_cast(historyExtent) /* HEIGHT */)), - #else - : QwtRasterData(), - #endif - _spectrumData(fftPoints * historyExtent), - _fftPoints(fftPoints), - _historyLength(historyExtent), - flow_direction(WaterfallFlowDirection::UP), - _intensityRange(QwtDoubleInterval(-200.0, 0.0)) + static_cast(historyExtent) /* HEIGHT */)) + , +#else + : QwtRasterData() + , +#endif + _spectrumData(fftPoints * historyExtent) + , _fftPoints(fftPoints) + , _historyLength(historyExtent) + , flow_direction(WaterfallFlowDirection::UP) + , _intensityRange(QwtDoubleInterval(-200.0, 0.0)) { #if QWT_VERSION >= 0x060000 setInterval(Qt::XAxis, QwtInterval(minimumFrequency, maximumFrequency)); @@ -69,17 +69,16 @@ void WaterfallData::reset() _numLinesToUpdate = -1; } -void WaterfallData::copy(const WaterfallData* rhs) +void WaterfallData::copy(const WaterfallData *rhs) { #if QWT_VERSION < 0x060000 - if ((_fftPoints != rhs->getNumFFTPoints()) || - (boundingRect() != rhs->boundingRect())) { + if((_fftPoints != rhs->getNumFFTPoints()) || (boundingRect() != rhs->boundingRect())) { _fftPoints = rhs->getNumFFTPoints(); setBoundingRect(rhs->boundingRect()); _spectrumData.clear(); } #else - if (_fftPoints != rhs->getNumFFTPoints()) { + if(_fftPoints != rhs->getNumFFTPoints()) { _fftPoints = rhs->getNumFFTPoints(); _spectrumData.clear(); } @@ -96,84 +95,67 @@ void WaterfallData::copy(const WaterfallData* rhs) #endif } -void WaterfallData::resizeData(const double startFreq, - const double stopFreq, - const uint64_t fftPoints, +void WaterfallData::resizeData(const double startFreq, const double stopFreq, const uint64_t fftPoints, const int history) { #if QWT_VERSION < 0x060000 - if ((fftPoints != getNumFFTPoints()) || - (boundingRect().width() != (stopFreq - startFreq)) || - (boundingRect().left() != startFreq)) { + if((fftPoints != getNumFFTPoints()) || (boundingRect().width() != (stopFreq - startFreq)) || + (boundingRect().left() != startFreq)) { - setBoundingRect(QwtDoubleRect( - startFreq, 0, stopFreq - startFreq, static_cast(_historyLength))); + setBoundingRect(QwtDoubleRect(startFreq, 0, stopFreq - startFreq, static_cast(_historyLength))); _fftPoints = fftPoints; _spectrumData.clear(); } #else - if ((fftPoints != getNumFFTPoints()) || - (interval(Qt::XAxis).width() != (stopFreq - startFreq)) || - (interval(Qt::XAxis).minValue() != startFreq)) { + if((fftPoints != getNumFFTPoints()) || (interval(Qt::XAxis).width() != (stopFreq - startFreq)) || + (interval(Qt::XAxis).minValue() != startFreq)) { reset(); setInterval(Qt::XAxis, QwtInterval(startFreq, stopFreq)); _fftPoints = fftPoints; } - if (_historyLength != history && history > 0) { + if(_historyLength != history && history > 0) { _historyLength = history; setInterval(Qt::YAxis, QwtInterval(0, _historyLength)); } #endif } -QwtRasterData* WaterfallData::copy() const +QwtRasterData *WaterfallData::copy() const { #if QWT_VERSION < 0x060000 - WaterfallData* returnData = new WaterfallData( - boundingRect().left(), boundingRect().right(), _fftPoints, _historyLength); + WaterfallData *returnData = + new WaterfallData(boundingRect().left(), boundingRect().right(), _fftPoints, _historyLength); #else - WaterfallData* returnData = new WaterfallData(interval(Qt::XAxis).minValue(), - interval(Qt::XAxis).maxValue(), - _fftPoints, - _historyLength); + WaterfallData *returnData = new WaterfallData(interval(Qt::XAxis).minValue(), interval(Qt::XAxis).maxValue(), + _fftPoints, _historyLength); #endif returnData->copy(this); return returnData; } - #if QWT_VERSION < 0x060000 QwtDoubleInterval WaterfallData::range() const { return _intensityRange; } -void WaterfallData::setRange(const QwtDoubleInterval& newRange) -{ - _intensityRange = newRange; -} +void WaterfallData::setRange(const QwtDoubleInterval &newRange) { _intensityRange = newRange; } #elif QWT_VERSION >= 0x060200 -void WaterfallData::setInterval(Qt::Axis axis, const QwtInterval& interval) -{ - d_intervals[axis] = interval; -} +void WaterfallData::setInterval(Qt::Axis axis, const QwtInterval &interval) { d_intervals[axis] = interval; } QwtInterval WaterfallData::interval(Qt::Axis a) const { return d_intervals[a]; } #endif - double WaterfallData::value(double x, double y) const { double returnValue = -DBL_MAX; #if QWT_VERSION < 0x060000 - const unsigned int intY = static_cast( - (1.0 - (y / boundingRect().height())) * static_cast(_historyLength - 1)); + const unsigned int intY = static_cast((1.0 - (y / boundingRect().height())) * + static_cast(_historyLength - 1)); const unsigned int intX = static_cast( - (((x - boundingRect().left()) / boundingRect().width()) * - static_cast(_fftPoints - 1)) + - 0.5); + (((x - boundingRect().left()) / boundingRect().width()) * static_cast(_fftPoints - 1)) + 0.5); #else double height = interval(Qt::YAxis).maxValue(); double left = interval(Qt::XAxis).minValue(); @@ -186,16 +168,16 @@ double WaterfallData::value(double x, double y) const size_t spectrumData_size = _spectrumData.size(); #endif - if (spectrumData_size > 0 && intY >= 0 && intY < _historyLength && intX >= 0 && intX < _fftPoints) { - switch (flow_direction) { + if(spectrumData_size > 0 && intY >= 0 && intY < _historyLength && intX >= 0 && intX < _fftPoints) { + switch(flow_direction) { case WaterfallFlowDirection::DOWN: - if (intY < spectrumData_size) { + if(intY < spectrumData_size) { returnValue = _spectrumData.at(spectrumData_size - intY - 1).at(intX); } break; case WaterfallFlowDirection::UP: - auto empty_lines = _historyLength -spectrumData_size; - if (intY > empty_lines + 1) { + auto empty_lines = _historyLength - spectrumData_size; + if(intY > empty_lines + 1) { returnValue = _spectrumData.at(intY - (empty_lines)).at(intX); } break; @@ -207,49 +189,36 @@ double WaterfallData::value(double x, double y) const uint64_t WaterfallData::getNumFFTPoints() const { return _fftPoints; } -WaterfallFlowDirection WaterfallData::getFlowDirection() -{ - return flow_direction; -} +WaterfallFlowDirection WaterfallData::getFlowDirection() { return flow_direction; } -void WaterfallData::setFlowDirection(WaterfallFlowDirection direction) -{ - flow_direction = direction; -} +void WaterfallData::setFlowDirection(WaterfallFlowDirection direction) { flow_direction = direction; } -void WaterfallData::addFFTData(const double* fftData, - const uint64_t fftDataSize) +void WaterfallData::addFFTData(const double *fftData, const uint64_t fftDataSize) { - if (fftDataSize == _fftPoints) { + if(fftDataSize == _fftPoints) { int64_t heightOffset = _historyLength - 1; // Any valid data rolled off the display so just fill in zeros and write new data - if (heightOffset < 0) { + if(heightOffset < 0) { heightOffset = 0; } std::vector new_data; - for (int i = 0; i < fftDataSize; i++) { + for(int i = 0; i < fftDataSize; i++) { new_data.push_back(fftData[i]); } _spectrumData.push_back(new_data); - while (_spectrumData.size() > _historyLength) { + while(_spectrumData.size() > _historyLength) { _spectrumData.pop_front(); } } } -const std::deque> WaterfallData::getSpectrumDataBuffer() const -{ - return _spectrumData; -} +const std::deque> WaterfallData::getSpectrumDataBuffer() const { return _spectrumData; } -void WaterfallData::setSpectrumDataBuffer(const std::deque> newData) -{ - _spectrumData = newData; -} +void WaterfallData::setSpectrumDataBuffer(const std::deque> newData) { _spectrumData = newData; } int WaterfallData::getNumLinesToUpdate() const { return _numLinesToUpdate; } diff --git a/gui/src/widgets/cursorsettings.cpp b/gui/src/widgets/cursorsettings.cpp index 5e1aa763b0..eceb6a8971 100644 --- a/gui/src/widgets/cursorsettings.cpp +++ b/gui/src/widgets/cursorsettings.cpp @@ -1,6 +1,7 @@ -#include #include + #include +#include using namespace scopy; @@ -74,32 +75,16 @@ void CursorSettings::connectSignals() }); } -QAbstractButton *CursorSettings::getHorizEn() -{ - return horizEn->onOffswitch(); -} +QAbstractButton *CursorSettings::getHorizEn() { return horizEn->onOffswitch(); } -QAbstractButton *CursorSettings::getHorizLock() -{ - return horizLock->onOffswitch(); -} +QAbstractButton *CursorSettings::getHorizLock() { return horizLock->onOffswitch(); } -QAbstractButton *CursorSettings::getHorizTrack() -{ - return horizTrack->onOffswitch(); -} +QAbstractButton *CursorSettings::getHorizTrack() { return horizTrack->onOffswitch(); } -QAbstractButton *CursorSettings::getVertEn() -{ - return vertEn->onOffswitch(); -} +QAbstractButton *CursorSettings::getVertEn() { return vertEn->onOffswitch(); } -QAbstractButton *CursorSettings::getVertLock() -{ - return vertLock->onOffswitch(); -} +QAbstractButton *CursorSettings::getVertLock() { return vertLock->onOffswitch(); } -QAbstractButton *CursorSettings::getReadoutsDrag() -{ - return readoutsDrag->onOffswitch(); -} +QAbstractButton *CursorSettings::getReadoutsDrag() { return readoutsDrag->onOffswitch(); } + +#include "moc_cursorsettings.cpp" diff --git a/gui/src/widgets/hoverwidget.cpp b/gui/src/widgets/hoverwidget.cpp index 1c6ca5e3c7..db5f0a0253 100644 --- a/gui/src/widgets/hoverwidget.cpp +++ b/gui/src/widgets/hoverwidget.cpp @@ -1,15 +1,26 @@ #include "widgets/hoverwidget.h" + #include "stylehelper.h" + #include #include + #include using namespace scopy; Q_LOGGING_CATEGORY(CAT_HOVERWIDGET, "HoverWidget") HoverWidget::HoverWidget(QWidget *content, QWidget *anchor, QWidget *parent) - : QWidget(parent), m_parent(parent), m_anchor(anchor), m_content(content), - m_anchorPos(HP_TOPLEFT), m_contentPos(HP_TOPRIGHT), is_dragging(false), - m_draggable(false), m_relative(false), m_relativeOffset(nullptr) { + : QWidget(parent) + , m_parent(parent) + , m_anchor(anchor) + , m_content(content) + , m_anchorPos(HP_TOPLEFT) + , m_contentPos(HP_TOPRIGHT) + , is_dragging(false) + , m_draggable(false) + , m_relative(false) + , m_relativeOffset(nullptr) +{ StyleHelper::TransparentWidget(this, "hoverWidget"); m_lay = new QHBoxLayout(this); m_lay->setSizeConstraint(QLayout::SetFixedSize); @@ -17,13 +28,13 @@ HoverWidget::HoverWidget(QWidget *content, QWidget *anchor, QWidget *parent) setLayout(m_lay); m_lay->addWidget(content); - if (m_content) { + if(m_content) { setContent(m_content); } - if (m_anchor) { + if(m_anchor) { setAnchor(m_anchor); } - if (m_parent) { + if(m_parent) { setParent(m_parent); } @@ -34,7 +45,7 @@ void HoverWidget::setDraggable(bool draggable) { m_draggable = draggable; StyleHelper::HoverWidget(this, m_draggable); - if (!m_draggable) { + if(!m_draggable) { updatePos(); } } @@ -42,9 +53,7 @@ void HoverWidget::setDraggable(bool draggable) void HoverWidget::mousePressEvent(QMouseEvent *event) { raise(); - if (event->button() == Qt::LeftButton && - m_content->geometry().contains(event->pos()) && - m_draggable) { + if(event->button() == Qt::LeftButton && m_content->geometry().contains(event->pos()) && m_draggable) { is_dragging = true; mouse_pos = new QPoint(event->pos()); } @@ -52,8 +61,7 @@ void HoverWidget::mousePressEvent(QMouseEvent *event) void HoverWidget::mouseReleaseEvent(QMouseEvent *event) { - if (event->button() == Qt::LeftButton && - is_dragging) { + if(event->button() == Qt::LeftButton && is_dragging) { is_dragging = false; mouse_pos = new QPoint(); updateRelativeOffset(); @@ -62,7 +70,7 @@ void HoverWidget::mouseReleaseEvent(QMouseEvent *event) void HoverWidget::mouseMoveEvent(QMouseEvent *event) { - if (!is_dragging) { + if(!is_dragging) { return; } @@ -73,16 +81,16 @@ void HoverWidget::mouseMoveEvent(QMouseEvent *event) QPoint new_bottomRight = mapToParent(m_content->geometry().bottomRight() + new_pos); // restrict horizontal movement - if (new_topLeft.x() < 0) { - new_pos.rx() = - topLeft.x(); - } else if (new_bottomRight.x() > m_parent->width()) { + if(new_topLeft.x() < 0) { + new_pos.rx() = -topLeft.x(); + } else if(new_bottomRight.x() > m_parent->width()) { new_pos.rx() = m_parent->width() - bottomRight.x(); } // restrict vertical movement - if (new_topLeft.y() < 0) { - new_pos.ry() = - topLeft.y(); - } else if (new_bottomRight.y() > m_parent->height()) { + if(new_topLeft.y() < 0) { + new_pos.ry() = -topLeft.y(); + } else if(new_bottomRight.y() > m_parent->height()) { new_pos.ry() = m_parent->height() - bottomRight.y(); } @@ -95,13 +103,10 @@ void HoverWidget::updateRelativeOffset() float width_diff = m_parent->width() - m_content->width(); m_relativeOffset = new QPointF((width_diff - mapToParent(m_content->geometry().topLeft()).x()) / width_diff, - (height_diff - mapToParent(m_content->geometry().topLeft()).y()) / height_diff); + (height_diff - mapToParent(m_content->geometry().topLeft()).y()) / height_diff); } -void HoverWidget::setRelative(bool relative) -{ - m_relative = relative; -} +void HoverWidget::setRelative(bool relative) { m_relative = relative; } void HoverWidget::setRelativeOffset(QPointF offset) { @@ -111,7 +116,7 @@ void HoverWidget::setRelativeOffset(QPointF offset) void HoverWidget::setContent(QWidget *content) { - if (m_content) { + if(m_content) { m_lay->removeWidget(m_content); m_content->setParent(nullptr); m_content->removeEventFilter(this); @@ -127,7 +132,7 @@ void HoverWidget::setContent(QWidget *content) void HoverWidget::setAnchor(QWidget *anchor) { - if (m_anchor) { + if(m_anchor) { m_anchor->removeEventFilter(this); } @@ -139,7 +144,7 @@ void HoverWidget::setAnchor(QWidget *anchor) void HoverWidget::setParent(QWidget *parent) { - if (m_parent) { + if(m_parent) { m_parent->removeEventFilter(this); } @@ -151,17 +156,14 @@ void HoverWidget::setParent(QWidget *parent) setVisible(visible); } -HoverWidget::~HoverWidget() -{ - -} +HoverWidget::~HoverWidget() {} bool HoverWidget::eventFilter(QObject *watched, QEvent *event) { if(watched == m_content) { - if (event->type() == QEvent::HoverMove) { - QMouseEvent* e = static_cast(event); - if (m_content->geometry().contains(e->pos()) && m_draggable) + if(event->type() == QEvent::HoverMove) { + QMouseEvent *e = static_cast(event); + if(m_content->geometry().contains(e->pos()) && m_draggable) m_content->setCursor(Qt::ClosedHandCursor); else m_content->setCursor(Qt::ArrowCursor); @@ -176,21 +178,16 @@ bool HoverWidget::eventFilter(QObject *watched, QEvent *event) return QObject::eventFilter(watched, event); } -QPoint HoverWidget::getAnchorOffset() -{ - return m_anchorOffset; -} +QPoint HoverWidget::getAnchorOffset() { return m_anchorOffset; } -void HoverWidget::setAnchorOffset(QPoint pt) { +void HoverWidget::setAnchorOffset(QPoint pt) +{ m_anchorOffset = pt; m_relativeOffset = nullptr; updatePos(); } -HoverPosition HoverWidget::getAnchorPos() -{ - return m_anchorPos; -} +HoverPosition HoverWidget::getAnchorPos() { return m_anchorPos; } void HoverWidget::setAnchorPos(HoverPosition pos) { @@ -199,10 +196,7 @@ void HoverWidget::setAnchorPos(HoverPosition pos) updatePos(); } -HoverPosition HoverWidget::getContentPos() -{ - return m_contentPos; -} +HoverPosition HoverWidget::getContentPos() { return m_contentPos; } void HoverWidget::setContentPos(HoverPosition pos) { @@ -238,26 +232,26 @@ void HoverWidget::moveToAnchor() if(!m_content || !m_anchor || !m_parent) return; - QPoint global = m_anchor->mapToGlobal(QPoint(0,0)); - QPoint mappedPoint = m_parent->mapFromGlobal(global); - QPoint anchorPosition = QPoint(0,0); - QPoint contentPosition = QPoint(0,0); + QPoint global = m_anchor->mapToGlobal(QPoint(0, 0)); + QPoint mappedPoint = m_parent->mapFromGlobal(global); + QPoint anchorPosition = QPoint(0, 0); + QPoint contentPosition = QPoint(0, 0); - switch (m_anchorPos) { + switch(m_anchorPos) { case HP_LEFT: - anchorPosition = QPoint(0 , m_anchor->height() / 2); + anchorPosition = QPoint(0, m_anchor->height() / 2); break; case HP_TOPLEFT: - anchorPosition = QPoint(0,0); + anchorPosition = QPoint(0, 0); break; case HP_TOP: - anchorPosition = QPoint(m_anchor->width() / 2 , 0); + anchorPosition = QPoint(m_anchor->width() / 2, 0); break; case HP_TOPRIGHT: anchorPosition = QPoint(m_anchor->width(), 0); break; case HP_RIGHT: - anchorPosition = QPoint(m_anchor->width(), m_anchor->height()/2); + anchorPosition = QPoint(m_anchor->width(), m_anchor->height() / 2); break; case HP_BOTTOMRIGHT: anchorPosition = QPoint(m_anchor->width(), m_anchor->height()); @@ -269,48 +263,49 @@ void HoverWidget::moveToAnchor() anchorPosition = QPoint(0, m_anchor->height()); break; case HP_CENTER: - anchorPosition = QPoint(m_anchor->width() / 2, m_anchor->height()/2); + anchorPosition = QPoint(m_anchor->width() / 2, m_anchor->height() / 2); break; default: - anchorPosition = QPoint(0,0); + anchorPosition = QPoint(0, 0); break; } - switch (m_contentPos) { + switch(m_contentPos) { case HP_LEFT: - contentPosition = QPoint(-m_content->width(), -m_content->height()/2); + contentPosition = QPoint(-m_content->width(), -m_content->height() / 2); break; case HP_TOPLEFT: contentPosition = QPoint(-m_content->width(), -m_content->height()); break; case HP_TOP: - contentPosition = QPoint(-m_content->width()/2, -m_content->height()); + contentPosition = QPoint(-m_content->width() / 2, -m_content->height()); break; case HP_TOPRIGHT: contentPosition = QPoint(0, -m_content->height()); break; case HP_RIGHT: - contentPosition = QPoint(0, -m_content->height()/2); + contentPosition = QPoint(0, -m_content->height() / 2); break; case HP_BOTTOMRIGHT: contentPosition = QPoint(0, 0); break; case HP_BOTTOM: - contentPosition = QPoint(-m_content->width()/2, 0); + contentPosition = QPoint(-m_content->width() / 2, 0); break; case HP_BOTTOMLEFT: contentPosition = QPoint(-m_content->width(), 0); break; case HP_CENTER: - contentPosition = QPoint(-m_content->width()/2, -m_content->height()/2); + contentPosition = QPoint(-m_content->width() / 2, -m_content->height() / 2); break; default: - contentPosition = QPoint(0,0); + contentPosition = QPoint(0, 0); break; } - qDebug(CAT_HOVERWIDGET)<<"moveAnchor"<<"mapped"<. */ #include "widgets/measurementlabel.h" + #include using namespace scopy; @@ -26,7 +27,9 @@ using namespace scopy; * Class MeasurementLabel implementation */ -MeasurementLabel::MeasurementLabel(QWidget *parent) : QWidget(parent) { +MeasurementLabel::MeasurementLabel(QWidget *parent) + : QWidget(parent) +{ QHBoxLayout *lay = new QHBoxLayout(this); m_unit = ""; setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); @@ -40,70 +43,54 @@ MeasurementLabel::MeasurementLabel(QWidget *parent) : QWidget(parent) { m_precision = 2; lay->addWidget(m_nameLabel); - lay->addSpacerItem(new QSpacerItem(10,0,QSizePolicy::Expanding,QSizePolicy::Maximum)); + lay->addSpacerItem(new QSpacerItem(10, 0, QSizePolicy::Expanding, QSizePolicy::Maximum)); lay->addWidget(m_valueLabel); m_valueLabel->setAlignment(Qt::AlignRight); m_color = StyleHelper::getColor("LabelText"); StyleHelper::MeasurementPanelLabel(this, m_name + "MeasurementLabel"); - } -MeasurementLabel::~MeasurementLabel() { - -} +MeasurementLabel::~MeasurementLabel() {} -void MeasurementLabel::setName(QString str) { +void MeasurementLabel::setName(QString str) +{ m_name = str; - m_nameLabel->setText(str+" : "); + m_nameLabel->setText(str + " : "); } -void MeasurementLabel::setUnit(QString str) { - m_unit = str; -} +void MeasurementLabel::setUnit(QString str) { m_unit = str; } -void MeasurementLabel::setPrecision(int val) { - m_precision = val; -} +void MeasurementLabel::setPrecision(int val) { m_precision = val; } -void MeasurementLabel::setColor(QColor color) { +void MeasurementLabel::setColor(QColor color) +{ m_color = color; StyleHelper::MeasurementPanelLabel(this, m_name + "MeasurementLabel"); } -void MeasurementLabel::setValue(double val) { +void MeasurementLabel::setValue(double val) +{ if(!m_formatter) { - m_valueLabel->setText( QString::number(val,'g', m_precision) + " " + m_unit); + m_valueLabel->setText(QString::number(val, 'g', m_precision) + " " + m_unit); } else { - m_valueLabel->setText( m_formatter->format(val, m_unit, m_precision)); + m_valueLabel->setText(m_formatter->format(val, m_unit, m_precision)); } } -void MeasurementLabel::setMeasurementValueFormatter(PrefixFormatter *f) { - m_formatter = f; -} +void MeasurementLabel::setMeasurementValueFormatter(PrefixFormatter *f) { m_formatter = f; } -QString MeasurementLabel::name() const -{ - return m_name; -} +QString MeasurementLabel::name() const { return m_name; } -QColor MeasurementLabel::color() const -{ - return m_color; -} +QColor MeasurementLabel::color() const { return m_color; } -int MeasurementLabel::idx() const -{ - return m_idx; -} +int MeasurementLabel::idx() const { return m_idx; } -void MeasurementLabel::setIdx(int newIdx) -{ - m_idx = newIdx; -} +void MeasurementLabel::setIdx(int newIdx) { m_idx = newIdx; } -StatsLabel::StatsLabel(QWidget *parent) : QWidget(parent) { +StatsLabel::StatsLabel(QWidget *parent) + : QWidget(parent) +{ QVBoxLayout *lay = new QVBoxLayout(this); m_unit = ""; @@ -125,63 +112,48 @@ StatsLabel::StatsLabel(QWidget *parent) : QWidget(parent) { lay->addWidget(m_avgLabel); lay->addWidget(m_minLabel); lay->addWidget(m_maxLabel); - lay->addSpacerItem(new QSpacerItem(0,0,QSizePolicy::Maximum,QSizePolicy::Expanding)); + lay->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Maximum, QSizePolicy::Expanding)); } -StatsLabel::~StatsLabel() { - -} +StatsLabel::~StatsLabel() {} -void StatsLabel::setName(QString str) { +void StatsLabel::setName(QString str) +{ m_name = str; m_nameLabel->setText(str); } -void StatsLabel::setUnit(QString str) { - m_unit = str; -} +void StatsLabel::setUnit(QString str) { m_unit = str; } -void StatsLabel::setPrecision(int val) { - m_precision = val; -} +void StatsLabel::setPrecision(int val) { m_precision = val; } -void StatsLabel::setColor(QColor color) { +void StatsLabel::setColor(QColor color) +{ m_color = color; StyleHelper::StatsPanelLabel(this, m_name + "MeasurementLabel"); } -void StatsLabel::setValue(double avg, double min, double max) { +void StatsLabel::setValue(double avg, double min, double max) +{ if(!m_formatter) { - m_avgLabel->setText( "Avg: " + QString::number(avg,'g', m_precision) + " " + m_unit); - m_minLabel->setText( "Min: " + QString::number(min,'g', m_precision) + " " + m_unit); - m_maxLabel->setText( "Max: " + QString::number(max,'g', m_precision) + " " + m_unit); + m_avgLabel->setText("Avg: " + QString::number(avg, 'g', m_precision) + " " + m_unit); + m_minLabel->setText("Min: " + QString::number(min, 'g', m_precision) + " " + m_unit); + m_maxLabel->setText("Max: " + QString::number(max, 'g', m_precision) + " " + m_unit); } else { - m_avgLabel->setText( "Avg: " + m_formatter->format(avg, m_unit, m_precision)); - m_minLabel->setText( "Min: " + m_formatter->format(min, m_unit, m_precision)); - m_maxLabel->setText( "Max: " + m_formatter->format(max, m_unit, m_precision)); + m_avgLabel->setText("Avg: " + m_formatter->format(avg, m_unit, m_precision)); + m_minLabel->setText("Min: " + m_formatter->format(min, m_unit, m_precision)); + m_maxLabel->setText("Max: " + m_formatter->format(max, m_unit, m_precision)); } } -void StatsLabel::setMeasurementValueFormatter(PrefixFormatter *f) { - m_formatter = f; -} +void StatsLabel::setMeasurementValueFormatter(PrefixFormatter *f) { m_formatter = f; } -QString StatsLabel::name() const -{ - return m_name; -} +QString StatsLabel::name() const { return m_name; } -QColor StatsLabel::color() const -{ - return m_color; -} +QColor StatsLabel::color() const { return m_color; } -int StatsLabel::idx() const -{ - return m_idx; -} +int StatsLabel::idx() const { return m_idx; } -void StatsLabel::setIdx(int newIdx) -{ - m_idx = newIdx; -} +void StatsLabel::setIdx(int newIdx) { m_idx = newIdx; } + +#include "moc_measurementlabel.cpp" diff --git a/gui/src/widgets/measurementpanel.cpp b/gui/src/widgets/measurementpanel.cpp index af55d638c3..4f4b61bf08 100644 --- a/gui/src/widgets/measurementpanel.cpp +++ b/gui/src/widgets/measurementpanel.cpp @@ -1,14 +1,17 @@ #include "widgets/measurementpanel.h" + +#include #include #include -#include + #include using namespace scopy; -MeasurementsPanel::MeasurementsPanel(QWidget *parent) : QWidget(parent) +MeasurementsPanel::MeasurementsPanel(QWidget *parent) + : QWidget(parent) { - QVBoxLayout* lay = new QVBoxLayout(this); + QVBoxLayout *lay = new QVBoxLayout(this); setLayout(lay); QScrollBar *scrollBar = new QScrollBar(this); @@ -40,10 +43,11 @@ MeasurementsPanel::MeasurementsPanel(QWidget *parent) : QWidget(parent) lay->addWidget(scrollBar); lay->addWidget(scrollArea); - connect(scrollArea->horizontalScrollBar(), &QAbstractSlider::rangeChanged, scrollBar, [=](double min, double max) { - auto singleStep = scrollArea->horizontalScrollBar()->singleStep(); - scrollBar->setVisible(singleStep < (max-min)); - }); + connect(scrollArea->horizontalScrollBar(), &QAbstractSlider::rangeChanged, scrollBar, + [=](double min, double max) { + auto singleStep = scrollArea->horizontalScrollBar()->singleStep(); + scrollBar->setVisible(singleStep < (max - min)); + }); m_cursor = new QWidget(panel); panelLayout->addWidget(m_cursor); @@ -51,13 +55,13 @@ MeasurementsPanel::MeasurementsPanel(QWidget *parent) : QWidget(parent) spacer = new QSpacerItem(10, 10, QSizePolicy::Expanding, QSizePolicy::Expanding); panelLayout->addSpacerItem(spacer); - int idx = panelLayout->indexOf(spacer); + int idx = panelLayout->indexOf(spacer); m_stacks.append(new VerticalWidgetStack(this)); panelLayout->insertWidget(idx, m_stacks.last()); - } -void MeasurementsPanel::addWidget(QWidget *meas) { +void MeasurementsPanel::addWidget(QWidget *meas) +{ if(m_stacks.last()->full()) { m_stacks.append(new VerticalWidgetStack(this)); int idx = panelLayout->indexOf(spacer); @@ -66,27 +70,30 @@ void MeasurementsPanel::addWidget(QWidget *meas) { m_stacks.last()->addWidget(meas); } -void MeasurementsPanel::addMeasurement(MeasurementLabel *meas) { +void MeasurementsPanel::addMeasurement(MeasurementLabel *meas) +{ addWidget(meas); m_labels.append(meas); } -void MeasurementsPanel::removeMeasurement(MeasurementLabel *meas) { +void MeasurementsPanel::removeMeasurement(MeasurementLabel *meas) +{ m_labels.removeAll(meas); -// updateOrder(); + // updateOrder(); } -void MeasurementsPanel::sort(int sortType) { +void MeasurementsPanel::sort(int sortType) +{ if(sortType == 0) { - std::sort(m_labels.begin(), m_labels.end(), [=](MeasurementLabel* first, MeasurementLabel* second){ + std::sort(m_labels.begin(), m_labels.end(), [=](MeasurementLabel *first, MeasurementLabel *second) { if(first->idx() == second->idx()) { return first->color().name() > second->color().name(); } return first->idx() < second->idx(); }); } else { - std::sort(m_labels.begin(), m_labels.end(), [=](MeasurementLabel* first, MeasurementLabel* second){ + std::sort(m_labels.begin(), m_labels.end(), [=](MeasurementLabel *first, MeasurementLabel *second) { if(first->color().name() == second->color().name()) { return first->idx() < second->idx(); } @@ -102,8 +109,9 @@ void MeasurementsPanel::sort(int sortType) { updateOrder(); }*/ -void MeasurementsPanel::updateOrder() { - for(VerticalWidgetStack* stack : m_stacks) { +void MeasurementsPanel::updateOrder() +{ + for(VerticalWidgetStack *stack : m_stacks) { stack->reparentWidgets(nullptr); panelLayout->removeWidget(stack); delete stack; @@ -117,18 +125,13 @@ void MeasurementsPanel::updateOrder() { for(QWidget *label : m_labels) { addWidget(label); } - } -QWidget *MeasurementsPanel::cursorArea() { - return m_cursor; -} - - +QWidget *MeasurementsPanel::cursorArea() { return m_cursor; } StatsPanel::StatsPanel(QWidget *parent) { - QVBoxLayout* lay = new QVBoxLayout(this); + QVBoxLayout *lay = new QVBoxLayout(this); setLayout(lay); lay->setMargin(0); @@ -150,10 +153,7 @@ StatsPanel::StatsPanel(QWidget *parent) lay->addWidget(scrollArea); } -StatsPanel::~StatsPanel() -{ - -} +StatsPanel::~StatsPanel() {} void StatsPanel::addStat(StatsLabel *stat) { @@ -178,18 +178,17 @@ void StatsPanel::updateOrder() } } - void StatsPanel::sort(int sortType) { if(sortType == 0) { - std::sort(m_labels.begin(), m_labels.end(), [=](StatsLabel* first, StatsLabel* second){ + std::sort(m_labels.begin(), m_labels.end(), [=](StatsLabel *first, StatsLabel *second) { if(first->idx() == second->idx()) { return first->color().name() > second->color().name(); } return first->idx() < second->idx(); }); } else { - std::sort(m_labels.begin(), m_labels.end(), [=](StatsLabel* first, StatsLabel* second){ + std::sort(m_labels.begin(), m_labels.end(), [=](StatsLabel *first, StatsLabel *second) { if(first->color().name() == second->color().name()) { return first->idx() < second->idx(); } @@ -198,3 +197,5 @@ void StatsPanel::sort(int sortType) } updateOrder(); } + +#include "moc_measurementpanel.cpp" diff --git a/gui/src/widgets/measurementselector.cpp b/gui/src/widgets/measurementselector.cpp index 10459ca77b..71ccdcfc0f 100644 --- a/gui/src/widgets/measurementselector.cpp +++ b/gui/src/widgets/measurementselector.cpp @@ -1,14 +1,16 @@ #include "widgets/measurementselector.h" -#include +#include #include #include -#include #include +#include + #include using namespace scopy; -MeasurementSelector::MeasurementSelector(QWidget *parent) : QWidget(parent) +MeasurementSelector::MeasurementSelector(QWidget *parent) + : QWidget(parent) { lay = new QVBoxLayout(this); setLayout(lay); @@ -16,16 +18,13 @@ MeasurementSelector::MeasurementSelector(QWidget *parent) : QWidget(parent) lay->setSpacing(6); } -MeasurementSelector::~MeasurementSelector() -{ - -} +MeasurementSelector::~MeasurementSelector() {} void MeasurementSelector::addMeasurement(QString name, QString icon) { - MeasurementSelectorItem *item= new MeasurementSelectorItem(name, icon ,this); + MeasurementSelectorItem *item = new MeasurementSelectorItem(name, icon, this); lay->addWidget(item); - m_map.insert(name,item); + m_map.insert(name, item); } void MeasurementSelector::removeMeasurement(QString name) @@ -34,14 +33,12 @@ void MeasurementSelector::removeMeasurement(QString name) m_map.remove(name); } -MeasurementSelectorItem* MeasurementSelector::measurement(QString name) { - return m_map.value(name); -} +MeasurementSelectorItem *MeasurementSelector::measurement(QString name) { return m_map.value(name); } void MeasurementSelector::toggleAllMeasurement(bool b) { for(int i = 0; i < children().count(); i++) { - MeasurementSelectorItem* item = dynamic_cast(children()[i]); + MeasurementSelectorItem *item = dynamic_cast(children()[i]); if(!item) continue; item->measureCheckbox()->setChecked(b); @@ -51,23 +48,22 @@ void MeasurementSelector::toggleAllMeasurement(bool b) void MeasurementSelector::toggleAllStats(bool b) { for(int i = 0; i < children().count(); i++) { - MeasurementSelectorItem* item = dynamic_cast(children()[i]); + MeasurementSelectorItem *item = dynamic_cast(children()[i]); if(!item) continue; item->statsCheckbox()->setChecked(b); } } -MeasurementSelectorItem::MeasurementSelectorItem(QString name, QString iconPath, QWidget *parent) : QWidget(parent) +MeasurementSelectorItem::MeasurementSelectorItem(QString name, QString iconPath, QWidget *parent) + : QWidget(parent) { QHBoxLayout *lay = new QHBoxLayout(this); setLayout(lay); - - m_icon = new QLabel("",this); + m_icon = new QLabel("", this); m_name = new QLabel(name, this); - m_measureCheckbox = new QCheckBox(this); m_statsCheckbox = new QCheckBox(this); @@ -76,25 +72,17 @@ MeasurementSelectorItem::MeasurementSelectorItem(QString name, QString iconPath, lay->addWidget(m_measureCheckbox); lay->addWidget(m_statsCheckbox); - lay->setStretch(0,1); - lay->setStretch(1,5); - lay->setStretch(2,1); - lay->setStretch(3,1); + lay->setStretch(0, 1); + lay->setStretch(1, 5); + lay->setStretch(2, 1); + lay->setStretch(3, 1); StyleHelper::MeasurementSelectorItemWidget(iconPath, this, "MeasurementSelectorItem" + name); - } -MeasurementSelectorItem::~MeasurementSelectorItem() -{ +MeasurementSelectorItem::~MeasurementSelectorItem() {} -} +QCheckBox *MeasurementSelectorItem::measureCheckbox() const { return m_measureCheckbox; } -QCheckBox *MeasurementSelectorItem::measureCheckbox() const -{ - return m_measureCheckbox; -} +QCheckBox *MeasurementSelectorItem::statsCheckbox() const { return m_statsCheckbox; } -QCheckBox *MeasurementSelectorItem::statsCheckbox() const -{ - return m_statsCheckbox; -} +#include "moc_measurementselector.cpp" diff --git a/gui/src/widgets/measurementsettings.cpp b/gui/src/widgets/measurementsettings.cpp index aa5849ac9c..72ea053b2a 100644 --- a/gui/src/widgets/measurementsettings.cpp +++ b/gui/src/widgets/measurementsettings.cpp @@ -1,11 +1,12 @@ #include "measurementsettings.h" -#include #include +#include using namespace scopy; -MeasurementSettings::MeasurementSettings(QWidget *parent) { +MeasurementSettings::MeasurementSettings(QWidget *parent) +{ QVBoxLayout *lay = new QVBoxLayout(this); setLayout(lay); @@ -16,7 +17,7 @@ MeasurementSettings::MeasurementSettings(QWidget *parent) { MenuOnOffSwitch *measurePanelSwitch = new MenuOnOffSwitch("Measure Panel", this); measurePanelSwitch->onOffswitch()->setChecked(true); QHBoxLayout *hlay1 = new QHBoxLayout(measureSection); - hlay1->setContentsMargins(0,6,0,6); + hlay1->setContentsMargins(0, 6, 0, 6); hlay1->setSpacing(9); measureSection->contentLayout()->addWidget(measurePanelSwitch); measureSection->contentLayout()->addLayout(hlay1); @@ -29,16 +30,15 @@ MeasurementSettings::MeasurementSettings(QWidget *parent) { hideAllMeasure->setVisible(false); - connect(measurePanelSwitch->onOffswitch(), &QAbstractButton::toggled, this, [=](bool b) { - Q_EMIT enableMeasurementPanel(b); - }); - connect(showAllMeasure, &QPushButton::clicked, this, [=](){ + connect(measurePanelSwitch->onOffswitch(), &QAbstractButton::toggled, this, + [=](bool b) { Q_EMIT enableMeasurementPanel(b); }); + connect(showAllMeasure, &QPushButton::clicked, this, [=]() { Q_EMIT toggleAllMeasurements(true); showAllMeasure->setVisible(false); hideAllMeasure->setVisible(true); }); - connect(hideAllMeasure, &QPushButton::clicked, this, [=](){ + connect(hideAllMeasure, &QPushButton::clicked, this, [=]() { Q_EMIT toggleAllMeasurements(false); hideAllMeasure->setVisible(false); showAllMeasure->setVisible(true); @@ -47,7 +47,7 @@ MeasurementSettings::MeasurementSettings(QWidget *parent) { hlay1->addWidget(hideAllMeasure); QHBoxLayout *hlay2 = new QHBoxLayout(measureSection); - hlay2->setContentsMargins(0,6,0,6); + hlay2->setContentsMargins(0, 6, 0, 6); hlay2->setSpacing(9); measureSection->contentLayout()->addLayout(hlay2); @@ -59,14 +59,13 @@ MeasurementSettings::MeasurementSettings(QWidget *parent) { mesaureSortByChannel->setVisible(false); - connect(mesaureSortByChannel, &QPushButton::clicked, this, [=](){ - + connect(mesaureSortByChannel, &QPushButton::clicked, this, [=]() { Q_EMIT sortMeasurements(MPM_SORT_CHANNEL); mesaureSortByChannel->setVisible(false); measureSortByType->setVisible(true); }); - connect(measureSortByType, &QPushButton::clicked, this, [=](){ + connect(measureSortByType, &QPushButton::clicked, this, [=]() { Q_EMIT sortMeasurements(MPM_SORT_TYPE); measureSortByType->setVisible(false); mesaureSortByChannel->setVisible(true); @@ -74,40 +73,37 @@ MeasurementSettings::MeasurementSettings(QWidget *parent) { hlay2->addWidget(mesaureSortByChannel); hlay2->addWidget(measureSortByType); - MenuSectionWidget *statsSection = new MenuSectionWidget(this); MenuOnOffSwitch *statsPanelSwitch = new MenuOnOffSwitch("Stats Panel", this); - connect(statsPanelSwitch->onOffswitch(), &QAbstractButton::toggled, this, [=](bool b) { - Q_EMIT enableStatsPanel(b); - }); + connect(statsPanelSwitch->onOffswitch(), &QAbstractButton::toggled, this, + [=](bool b) { Q_EMIT enableStatsPanel(b); }); statsSection->contentLayout()->addWidget(statsPanelSwitch); statsPanelSwitch->onOffswitch()->setChecked(false); QHBoxLayout *hlay3 = new QHBoxLayout(statsSection); - hlay3->setContentsMargins(0,6,0,6); + hlay3->setContentsMargins(0, 6, 0, 6); hlay3->setSpacing(9); statsSection->contentLayout()->addWidget(statsPanelSwitch); statsSection->contentLayout()->addLayout(hlay3); - QPushButton *showAllStats= new QPushButton("Show All", statsSection); + QPushButton *showAllStats = new QPushButton("Show All", statsSection); StyleHelper::SmallBlueButton(showAllStats); - QPushButton *hideAllStats= new QPushButton("Hide All", statsSection); + QPushButton *hideAllStats = new QPushButton("Hide All", statsSection); StyleHelper::SmallBlueButton(hideAllStats); hideAllStats->setVisible(false); - connect(statsPanelSwitch->onOffswitch(), &QAbstractButton::toggled, this, [=](bool b) { - Q_EMIT enableStatsPanel(b); - }); - connect(showAllStats, &QPushButton::clicked, this, [=](){ + connect(statsPanelSwitch->onOffswitch(), &QAbstractButton::toggled, this, + [=](bool b) { Q_EMIT enableStatsPanel(b); }); + connect(showAllStats, &QPushButton::clicked, this, [=]() { Q_EMIT toggleAllStats(true); showAllStats->setVisible(false); hideAllStats->setVisible(true); }); - connect(hideAllStats, &QPushButton::clicked, this, [=](){ + connect(hideAllStats, &QPushButton::clicked, this, [=]() { Q_EMIT toggleAllStats(false); hideAllStats->setVisible(false); showAllStats->setVisible(true); @@ -116,7 +112,7 @@ MeasurementSettings::MeasurementSettings(QWidget *parent) { hlay3->addWidget(hideAllStats); QHBoxLayout *hlay4 = new QHBoxLayout(statsSection); - hlay4->setContentsMargins(0,6,0,6); + hlay4->setContentsMargins(0, 6, 0, 6); hlay4->setSpacing(9); statsSection->contentLayout()->addLayout(hlay4); @@ -128,14 +124,13 @@ MeasurementSettings::MeasurementSettings(QWidget *parent) { statsSortByChannel->setVisible(false); - connect(statsSortByChannel, &QPushButton::clicked, this, [=](){ - + connect(statsSortByChannel, &QPushButton::clicked, this, [=]() { Q_EMIT sortStats(MPM_SORT_CHANNEL); statsSortByChannel->setVisible(false); statsSortByType->setVisible(true); }); - connect(statsSortByType, &QPushButton::clicked, this, [=](){ + connect(statsSortByType, &QPushButton::clicked, this, [=]() { Q_EMIT sortStats(MPM_SORT_TYPE); statsSortByType->setVisible(false); statsSortByChannel->setVisible(true); @@ -148,3 +143,5 @@ MeasurementSettings::MeasurementSettings(QWidget *parent) { } MeasurementSettings::~MeasurementSettings() {} + +#include "moc_measurementsettings.cpp" diff --git a/gui/src/widgets/menubigswitch.cpp b/gui/src/widgets/menubigswitch.cpp index 6dcb427b3b..0d88531b0b 100644 --- a/gui/src/widgets/menubigswitch.cpp +++ b/gui/src/widgets/menubigswitch.cpp @@ -2,7 +2,9 @@ using namespace scopy; -MenuBigSwitch::MenuBigSwitch(QString on, QString off, QWidget *parent) : QWidget(parent) { +MenuBigSwitch::MenuBigSwitch(QString on, QString off, QWidget *parent) + : QWidget(parent) +{ auto lay = new QHBoxLayout(this); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); setLayout(lay); @@ -17,11 +19,14 @@ MenuBigSwitch::MenuBigSwitch(QString on, QString off, QWidget *parent) : QWidget applyStylesheet(); } -MenuBigSwitch::~MenuBigSwitch() { } +MenuBigSwitch::~MenuBigSwitch() {} CustomSwitch *MenuBigSwitch::onOffswitch() { return m_switch; } -void MenuBigSwitch::applyStylesheet() { +void MenuBigSwitch::applyStylesheet() +{ StyleHelper::MenuBigSwitchButton(m_switch, "menuButton"); StyleHelper::MenuBigSwitch(this, "menuBigSwitch"); } + +#include "moc_menubigswitch.cpp" diff --git a/gui/src/widgets/menucollapsesection.cpp b/gui/src/widgets/menucollapsesection.cpp index b39adce39e..44dfd1eea3 100644 --- a/gui/src/widgets/menucollapsesection.cpp +++ b/gui/src/widgets/menucollapsesection.cpp @@ -1,34 +1,34 @@ -#include #include +#include using namespace scopy; -MenuCollapseHeader::MenuCollapseHeader(QString title, MenuCollapseSection::MenuHeaderCollapseStyle style, QWidget *parent) - : QAbstractButton(parent) +MenuCollapseHeader::MenuCollapseHeader(QString title, MenuCollapseSection::MenuHeaderCollapseStyle style, + QWidget *parent) + : QAbstractButton(parent) { lay = new QHBoxLayout(this); lay->setMargin(0); - lay->setContentsMargins(0,2,0,6); + lay->setContentsMargins(0, 2, 0, 6); lay->setSpacing(0); - setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Maximum); + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); setCheckable(true); setLayout(lay); m_label = new QLabel(title, this); StyleHelper::MenuCollapseHeaderLabel(m_label, "menuCollapseLabel"); - - switch(style){ + switch(style) { case MenuCollapseSection::MHCW_ARROW: m_ctrl = new QCheckBox(this); - StyleHelper::CollapseCheckbox(dynamic_cast(m_ctrl), "menuCollapseButton"); - connect(this, &QAbstractButton::toggled, this, [=](bool b) {m_ctrl->setChecked(!b);}); + StyleHelper::CollapseCheckbox(dynamic_cast(m_ctrl), "menuCollapseButton"); + connect(this, &QAbstractButton::toggled, this, [=](bool b) { m_ctrl->setChecked(!b); }); m_ctrl->setChecked(false); break; case MenuCollapseSection::MHCW_ONOFF: m_ctrl = new SmallOnOffSwitch(this); - StyleHelper::MenuOnOffSwitchButton(dynamic_cast(m_ctrl), "menuCollapseButton"); + StyleHelper::MenuOnOffSwitchButton(dynamic_cast(m_ctrl), "menuCollapseButton"); connect(this, &QAbstractButton::toggled, m_ctrl, &QAbstractButton::toggled); m_ctrl->setChecked(true); break; @@ -42,17 +42,16 @@ MenuCollapseHeader::MenuCollapseHeader(QString title, MenuCollapseSection::MenuH m_ctrl->setAttribute(Qt::WA_TransparentForMouseEvents); lay->addWidget(m_label); - lay->addSpacerItem(new QSpacerItem(40,40,QSizePolicy::Expanding,QSizePolicy::Maximum)); + lay->addSpacerItem(new QSpacerItem(40, 40, QSizePolicy::Expanding, QSizePolicy::Maximum)); lay->addWidget(m_ctrl); - } -MenuCollapseHeader::~MenuCollapseHeader() { +MenuCollapseHeader::~MenuCollapseHeader() {} -} - -MenuCollapseSection::MenuCollapseSection(QString title, MenuCollapseSection::MenuHeaderCollapseStyle style, QWidget *parent) - : QWidget(parent) { +MenuCollapseSection::MenuCollapseSection(QString title, MenuCollapseSection::MenuHeaderCollapseStyle style, + QWidget *parent) + : QWidget(parent) +{ m_lay = new QVBoxLayout(this); m_lay->setMargin(0); @@ -67,17 +66,17 @@ MenuCollapseSection::MenuCollapseSection(QString title, MenuCollapseSection::Men m_contLayout->setMargin(0); m_contLayout->setSpacing(0); - StyleHelper::MenuCollapseSection(this,"menuCollapse"); + StyleHelper::MenuCollapseSection(this, "menuCollapse"); connect(m_header, &QAbstractButton::toggled, container, &QWidget::setVisible); } MenuCollapseSection::~MenuCollapseSection() {} QAbstractButton *MenuCollapseSection::header() { return m_header; } -QVBoxLayout* MenuCollapseSection::contentLayout() const { return m_contLayout; } - +QVBoxLayout *MenuCollapseSection::contentLayout() const { return m_contLayout; } -//void MenuCollapseSection::add(QWidget *ch) { +// void MenuCollapseSection::add(QWidget *ch) { // m_contLayout->addWidget(ch); //} +#include "moc_menucollapsesection.cpp" diff --git a/gui/src/widgets/menucombo.cpp b/gui/src/widgets/menucombo.cpp index 309b8db57f..cf8195c62b 100644 --- a/gui/src/widgets/menucombo.cpp +++ b/gui/src/widgets/menucombo.cpp @@ -1,10 +1,13 @@ -#include #include + #include +#include using namespace scopy; -MenuComboWidget::MenuComboWidget(QString title, QWidget *parent) : QWidget(parent) { +MenuComboWidget::MenuComboWidget(QString title, QWidget *parent) + : QWidget(parent) +{ auto lay = new QVBoxLayout(this); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); @@ -18,15 +21,15 @@ MenuComboWidget::MenuComboWidget(QString title, QWidget *parent) : QWidget(paren applyStylesheet(); } -MenuComboWidget::~MenuComboWidget() { } +MenuComboWidget::~MenuComboWidget() {} QComboBox *MenuComboWidget::combo() { return m_combo->combo(); } -void MenuComboWidget::applyStylesheet() { - StyleHelper::MenuComboWidget(this, "menuComboWidget"); -} +void MenuComboWidget::applyStylesheet() { StyleHelper::MenuComboWidget(this, "menuComboWidget"); } -MenuCombo::MenuCombo(QString title, QWidget *parent) : QWidget(parent) { +MenuCombo::MenuCombo(QString title, QWidget *parent) + : QWidget(parent) +{ auto lay = new QVBoxLayout(this); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); @@ -42,11 +45,13 @@ MenuCombo::MenuCombo(QString title, QWidget *parent) : QWidget(parent) { applyStylesheet(); } -MenuCombo::~MenuCombo() { } +MenuCombo::~MenuCombo() {} QComboBox *MenuCombo::combo() { return m_combo; } -void MenuCombo::applyStylesheet() { +void MenuCombo::applyStylesheet() +{ StyleHelper::MenuComboLabel(m_label, "menuLabel"); StyleHelper::MenuComboBox(m_combo, "menuCombobox"); } +#include "moc_menucombo.cpp" diff --git a/gui/src/widgets/menucontrolbutton.cpp b/gui/src/widgets/menucontrolbutton.cpp index 4a0f31efaa..45cf591ccf 100644 --- a/gui/src/widgets/menucontrolbutton.cpp +++ b/gui/src/widgets/menucontrolbutton.cpp @@ -1,22 +1,24 @@ -#include #include -#include #include +#include +#include using namespace scopy; -MenuControlButton::MenuControlButton(QWidget *parent) : QAbstractButton(parent) { +MenuControlButton::MenuControlButton(QWidget *parent) + : QAbstractButton(parent) +{ lay = new QHBoxLayout(this); lay->setMargin(16); lay->setSpacing(16); - setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Maximum); + setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); setCheckable(true); setLayout(lay); - m_chk = new QCheckBox("",this); + m_chk = new QCheckBox("", this); m_label = new QLabel("", this); - m_btn = new QPushButton("",this); + m_btn = new QPushButton("", this); m_color = StyleHelper::getColor("ScopyBlue"); m_cs = CS_SQUARE; @@ -25,38 +27,33 @@ MenuControlButton::MenuControlButton(QWidget *parent) : QAbstractButton(parent) lay->addWidget(m_btn); applyStylesheet(); - connect(this, &QAbstractButton::toggled, this, [=](bool b){ - setDynamicProperty(this,"selected",b); - }); // Hackish - QStyle should be implemented + connect(this, &QAbstractButton::toggled, this, + [=](bool b) { setDynamicProperty(this, "selected", b); }); // Hackish - QStyle should be implemented dblClickToOpenMenu = QMetaObject::Connection(); openMenuChecksThis = QMetaObject::Connection(); } -MenuControlButton::~MenuControlButton() -{ - -} +MenuControlButton::~MenuControlButton() {} -void MenuControlButton::setColor(QColor c) { +void MenuControlButton::setColor(QColor c) +{ m_color = c; applyStylesheet(); } -void MenuControlButton::setCheckBoxStyle(CheckboxStyle cs) { +void MenuControlButton::setCheckBoxStyle(CheckboxStyle cs) +{ m_cs = cs; applyStylesheet(); } -void MenuControlButton::setName(QString s) { - m_label->setText(s); -} +void MenuControlButton::setName(QString s) { m_label->setText(s); } void MenuControlButton::setDoubleClickToOpenMenu(bool b) { if(b) { - dblClickToOpenMenu = - connect(this, &MenuControlButton::doubleClicked, this, [=](){ + dblClickToOpenMenu = connect(this, &MenuControlButton::doubleClicked, this, [=]() { setChecked(true); if(m_btn->isVisible()) { m_btn->toggle(); @@ -70,8 +67,7 @@ void MenuControlButton::setDoubleClickToOpenMenu(bool b) void MenuControlButton::setOpenMenuChecksThis(bool b) { if(b) { - openMenuChecksThis = - connect(m_btn, &QAbstractButton::toggled, this, [=](bool b) { + openMenuChecksThis = connect(m_btn, &QAbstractButton::toggled, this, [=](bool b) { if(b) setChecked(true); }); @@ -80,8 +76,9 @@ void MenuControlButton::setOpenMenuChecksThis(bool b) } } -void MenuControlButton::mouseDoubleClickEvent(QMouseEvent * e) { - if ( e->button() == Qt::LeftButton ) { +void MenuControlButton::mouseDoubleClickEvent(QMouseEvent *e) +{ + if(e->button() == Qt::LeftButton) { if(Preferences::get("general_doubleclick_ctrl_opens_menu").toBool() == true) { Q_EMIT doubleClicked(); return; @@ -90,8 +87,9 @@ void MenuControlButton::mouseDoubleClickEvent(QMouseEvent * e) { QAbstractButton::mouseDoubleClickEvent(e); } -void MenuControlButton::mousePressEvent(QMouseEvent *e) { - if (e->button() == Qt::LeftButton) { +void MenuControlButton::mousePressEvent(QMouseEvent *e) +{ + if(e->button() == Qt::LeftButton) { if(Preferences::get("general_doubleclick_ctrl_opens_menu").toBool() == true) { if(m_btn->isChecked()) { m_btn->setChecked(false); @@ -102,38 +100,41 @@ void MenuControlButton::mousePressEvent(QMouseEvent *e) { QAbstractButton::mousePressEvent(e); } -QCheckBox *MenuControlButton::checkBox() { return m_chk;} +QCheckBox *MenuControlButton::checkBox() { return m_chk; } -QPushButton *MenuControlButton::button() { return m_btn;} +QPushButton *MenuControlButton::button() { return m_btn; } -void MenuControlButton::applyStylesheet() { +void MenuControlButton::applyStylesheet() +{ - StyleHelper::MenuControlWidget(this,m_color,"controlButton"); + StyleHelper::MenuControlWidget(this, m_color, "controlButton"); switch(m_cs) { case CS_CIRCLE: - StyleHelper::ColoredCircleCheckbox(m_chk,m_color,"chk"); + StyleHelper::ColoredCircleCheckbox(m_chk, m_color, "chk"); break; case CS_SQUARE: - StyleHelper::ColoredSquareCheckbox(m_chk,0xFFFFFF,"chk"); + StyleHelper::ColoredSquareCheckbox(m_chk, 0xFFFFFF, "chk"); break; case CS_COLLAPSE: - StyleHelper::CollapseCheckbox(m_chk,"chk"); + StyleHelper::CollapseCheckbox(m_chk, "chk"); break; default: - StyleHelper::BlueSquareCheckbox(m_chk,"chk"); + StyleHelper::BlueSquareCheckbox(m_chk, "chk"); break; } - StyleHelper::MenuControlLabel(m_label,"name"); + StyleHelper::MenuControlLabel(m_label, "name"); StyleHelper::MenuControlButton(m_btn, "btn"); } -CollapsableMenuControlButton::CollapsableMenuControlButton(QWidget *parent) : QWidget(parent) { +CollapsableMenuControlButton::CollapsableMenuControlButton(QWidget *parent) + : QWidget(parent) +{ m_lay = new QVBoxLayout(this); m_lay->setMargin(0); m_lay->setSpacing(0); setLayout(m_lay); m_ctrl = new MenuControlButton(this); - m_ctrl->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed); + m_ctrl->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_ctrl->setCheckBoxStyle(MenuControlButton::CS_COLLAPSE); m_ctrl->setCheckable(false); m_ctrl->checkBox()->setChecked(true); @@ -145,16 +146,17 @@ CollapsableMenuControlButton::CollapsableMenuControlButton(QWidget *parent) : QW m_contLayout->setMargin(0); m_contLayout->setSpacing(0); - connect(m_ctrl->checkBox(),SIGNAL(toggled(bool)),container,SLOT(setVisible(bool))); + connect(m_ctrl->checkBox(), SIGNAL(toggled(bool)), container, SLOT(setVisible(bool))); } CollapsableMenuControlButton::~CollapsableMenuControlButton() {} -void CollapsableMenuControlButton::add(QWidget *ch) { - ch->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed); +void CollapsableMenuControlButton::add(QWidget *ch) +{ + ch->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_contLayout->addWidget(ch); } -MenuControlButton *CollapsableMenuControlButton::getControlBtn() { - return m_ctrl; -} +MenuControlButton *CollapsableMenuControlButton::getControlBtn() { return m_ctrl; } + +#include "moc_menucontrolbutton.cpp" diff --git a/gui/src/widgets/menuheader.cpp b/gui/src/widgets/menuheader.cpp index 1da102ed2e..21625c038b 100644 --- a/gui/src/widgets/menuheader.cpp +++ b/gui/src/widgets/menuheader.cpp @@ -1,9 +1,11 @@ -#include #include +#include using namespace scopy; -MenuHeaderWidget::MenuHeaderWidget(QString title, QPen pen, QWidget *parent) : QWidget(parent) { +MenuHeaderWidget::MenuHeaderWidget(QString title, QPen pen, QWidget *parent) + : QWidget(parent) +{ auto lay = new QVBoxLayout(this); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); @@ -21,12 +23,15 @@ MenuHeaderWidget::MenuHeaderWidget(QString title, QPen pen, QWidget *parent) : Q applyStylesheet(); } -MenuHeaderWidget::~MenuHeaderWidget() { } +MenuHeaderWidget::~MenuHeaderWidget() {} QLabel *MenuHeaderWidget::label() { return m_label; } -void MenuHeaderWidget::applyStylesheet() { +void MenuHeaderWidget::applyStylesheet() +{ StyleHelper::MenuHeaderLabel(m_label, "menuLabel"); StyleHelper::MenuHeaderLine(m_line, m_pen, "menuSeparator"); StyleHelper::MenuHeaderWidget(this, "menuHeader"); } + +#include "moc_menuheader.cpp" diff --git a/gui/src/widgets/menulineedit.cpp b/gui/src/widgets/menulineedit.cpp index 6c8f46fa4e..44d045de69 100644 --- a/gui/src/widgets/menulineedit.cpp +++ b/gui/src/widgets/menulineedit.cpp @@ -2,7 +2,9 @@ using namespace scopy; -MenuLineEdit::MenuLineEdit(QWidget *parent) : QWidget(parent) { +MenuLineEdit::MenuLineEdit(QWidget *parent) + : QWidget(parent) +{ auto lay = new QHBoxLayout(this); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); setLayout(lay); @@ -15,11 +17,14 @@ MenuLineEdit::MenuLineEdit(QWidget *parent) : QWidget(parent) { applyStylesheet(); } -MenuLineEdit::~MenuLineEdit() { } +MenuLineEdit::~MenuLineEdit() {} QLineEdit *MenuLineEdit::edit() { return m_edit; } -void MenuLineEdit::applyStylesheet() { +void MenuLineEdit::applyStylesheet() +{ StyleHelper::MenuLineEdit(m_edit, "menuButton"); StyleHelper::MenuLineEditWidget(this, "menuBigSwitch"); } + +#include "moc_menulineedit.cpp" diff --git a/gui/src/widgets/menuonoffswitch.cpp b/gui/src/widgets/menuonoffswitch.cpp index 479cac1bf2..8e0b98aa24 100644 --- a/gui/src/widgets/menuonoffswitch.cpp +++ b/gui/src/widgets/menuonoffswitch.cpp @@ -1,10 +1,12 @@ -#include -#include #include +#include +#include using namespace scopy; -MenuOnOffSwitch::MenuOnOffSwitch(QString title, QWidget *parent, bool medium) : QWidget(parent) { +MenuOnOffSwitch::MenuOnOffSwitch(QString title, QWidget *parent, bool medium) + : QWidget(parent) +{ auto lay = new QHBoxLayout(this); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); @@ -15,7 +17,7 @@ MenuOnOffSwitch::MenuOnOffSwitch(QString title, QWidget *parent, bool medium) : m_label = new QLabel(title, this); if(medium == false) { m_switch = new SmallOnOffSwitch(this); - StyleHelper::MenuOnOffSwitchButton(dynamic_cast(m_switch), "menuButton"); + StyleHelper::MenuOnOffSwitchButton(dynamic_cast(m_switch), "menuButton"); StyleHelper::MenuSmallLabel(m_label, "menuLabel"); } else { m_switch = new CustomSwitch(this); @@ -23,16 +25,15 @@ MenuOnOffSwitch::MenuOnOffSwitch(QString title, QWidget *parent, bool medium) : } lay->addWidget(m_label); - lay->addSpacerItem(new QSpacerItem(10,10,QSizePolicy::Expanding, QSizePolicy::Fixed)); + lay->addSpacerItem(new QSpacerItem(10, 10, QSizePolicy::Expanding, QSizePolicy::Fixed)); lay->addWidget(m_switch); applyStylesheet(); } -MenuOnOffSwitch::~MenuOnOffSwitch() { } +MenuOnOffSwitch::~MenuOnOffSwitch() {} QAbstractButton *MenuOnOffSwitch::onOffswitch() { return m_switch; } -void MenuOnOffSwitch::applyStylesheet() { +void MenuOnOffSwitch::applyStylesheet() { StyleHelper::MenuOnOffSwitch(this, "menuOnOffSwitch"); } - StyleHelper::MenuOnOffSwitch(this, "menuOnOffSwitch"); -} +#include "moc_menuonoffswitch.cpp" diff --git a/gui/src/widgets/menusectionwidget.cpp b/gui/src/widgets/menusectionwidget.cpp index 3aa7d95c45..eefbbc1e53 100644 --- a/gui/src/widgets/menusectionwidget.cpp +++ b/gui/src/widgets/menusectionwidget.cpp @@ -1,8 +1,10 @@ -#include #include +#include using namespace scopy; -MenuSectionWidget::MenuSectionWidget(QWidget *parent) : QWidget(parent) { +MenuSectionWidget::MenuSectionWidget(QWidget *parent) + : QWidget(parent) +{ m_layout = new QVBoxLayout(this); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); @@ -12,7 +14,7 @@ MenuSectionWidget::MenuSectionWidget(QWidget *parent) : QWidget(parent) { StyleHelper::MenuSectionWidget(this, "menuSection"); } -MenuSectionWidget::~MenuSectionWidget() { } +MenuSectionWidget::~MenuSectionWidget() {} QVBoxLayout *MenuSectionWidget::contentLayout() const { return m_layout; } @@ -28,12 +30,8 @@ MenuVScrollArea::MenuVScrollArea(QWidget *parent) m_layout->setMargin(0); } -MenuVScrollArea::~MenuVScrollArea() -{ +MenuVScrollArea::~MenuVScrollArea() {} -} +QVBoxLayout *MenuVScrollArea::contentLayout() const { return m_layout; } -QVBoxLayout *MenuVScrollArea::contentLayout() const -{ - return m_layout; -} +#include "moc_menusectionwidget.cpp" diff --git a/gui/src/widgets/pagenavigationwidget.cpp b/gui/src/widgets/pagenavigationwidget.cpp index c98eeeafc2..8127bed1c1 100644 --- a/gui/src/widgets/pagenavigationwidget.cpp +++ b/gui/src/widgets/pagenavigationwidget.cpp @@ -1,11 +1,13 @@ #include "widgets/pagenavigationwidget.h" + #include #include #include + #include using namespace scopy; -Q_LOGGING_CATEGORY(CAT_NAVIGATIONWIDGET,"PageNavigationWidget") +Q_LOGGING_CATEGORY(CAT_NAVIGATIONWIDGET, "PageNavigationWidget") PageNavigationWidget::PageNavigationWidget(bool hasHome, bool hasOpen, QWidget *parent) : QWidget(parent) @@ -16,10 +18,7 @@ PageNavigationWidget::PageNavigationWidget(bool hasHome, bool hasOpen, QWidget * setOpenBtnVisible(hasOpen); } -PageNavigationWidget::~PageNavigationWidget() -{ - -} +PageNavigationWidget::~PageNavigationWidget() {} void PageNavigationWidget::initUI(QWidget *parent) { @@ -46,7 +45,7 @@ void PageNavigationWidget::initUI(QWidget *parent) buttonsLayout->addWidget(openButton); openButton->hide(); - buttonsLayout->addSpacerItem(new QSpacerItem(1,1,QSizePolicy::Expanding,QSizePolicy::Fixed)); + buttonsLayout->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Fixed)); } void PageNavigationWidget::setHomeBtnVisible(bool en) @@ -61,22 +60,12 @@ void PageNavigationWidget::setOpenBtnVisible(bool en) setMinimumSize(sizeHint()); } -QPushButton *PageNavigationWidget::getHomeBtn() -{ - return homeButton; -} +QPushButton *PageNavigationWidget::getHomeBtn() { return homeButton; } -QPushButton *PageNavigationWidget::getBackwardBtn() -{ - return backwardButton; -} +QPushButton *PageNavigationWidget::getBackwardBtn() { return backwardButton; } -QPushButton *PageNavigationWidget::getForwardBtn() -{ - return forwardButton; -} +QPushButton *PageNavigationWidget::getForwardBtn() { return forwardButton; } -QPushButton *PageNavigationWidget::getOpenBtn() -{ - return openButton; -} +QPushButton *PageNavigationWidget::getOpenBtn() { return openButton; } + +#include "moc_pagenavigationwidget.cpp" diff --git a/gui/src/widgets/plotcursorreadouts.cpp b/gui/src/widgets/plotcursorreadouts.cpp index 6a02ac4700..afcbaad9dc 100644 --- a/gui/src/widgets/plotcursorreadouts.cpp +++ b/gui/src/widgets/plotcursorreadouts.cpp @@ -2,24 +2,38 @@ using namespace scopy; -PlotCursorReadouts::PlotCursorReadouts(QWidget *parent) : QWidget(parent), - formatter(static_cast(new MetricPrefixFormatter)) +PlotCursorReadouts::PlotCursorReadouts(QWidget *parent) + : QWidget(parent) + , formatter(static_cast(new MetricPrefixFormatter)) { initContent(); } -PlotCursorReadouts::~PlotCursorReadouts() -{ +PlotCursorReadouts::~PlotCursorReadouts() {} +void PlotCursorReadouts::setV1(double val) +{ + v1 = val; + update(); } -void PlotCursorReadouts::setV1(double val) { v1 = val; update();} - -void PlotCursorReadouts::setV2(double val) { v2 = val; update();} +void PlotCursorReadouts::setV2(double val) +{ + v2 = val; + update(); +} -void PlotCursorReadouts::setH1(double val) { h1 = val; update();} +void PlotCursorReadouts::setH1(double val) +{ + h1 = val; + update(); +} -void PlotCursorReadouts::setH2(double val) { h2 = val; update();} +void PlotCursorReadouts::setH2(double val) +{ + h2 = val; + update(); +} void PlotCursorReadouts::update() { @@ -27,9 +41,9 @@ void PlotCursorReadouts::update() V2_val->setText(formatter->format(v2, "Hz", 3)); H1_val->setText(formatter->format(h1, "s", 3)); H2_val->setText(formatter->format(h2, "s", 3)); - deltaV_val->setText(formatter->format(v2-v1, "Hz", 3)); - deltaH_val->setText(formatter->format(h2-h1, "s", 3)); - invDeltaH_val->setText(formatter->format(1/(h2-h1), "s", 3)); + deltaV_val->setText(formatter->format(v2 - v1, "Hz", 3)); + deltaH_val->setText(formatter->format(h2 - h1, "s", 3)); + invDeltaH_val->setText(formatter->format(1 / (h2 - h1), "s", 3)); } void PlotCursorReadouts::initContent() @@ -50,15 +64,15 @@ void PlotCursorReadouts::initContent() content_lay->addWidget(vert_contents); vert_contents_lay->addWidget(new QLabel("V1:", vert_contents), 0, 0); - V1_val = new QLabel("",this); + V1_val = new QLabel("", this); vert_contents_lay->addWidget(V1_val, 0, 1); vert_contents_lay->addWidget(new QLabel("V2:", vert_contents), 1, 0); - V2_val = new QLabel("",this); + V2_val = new QLabel("", this); vert_contents_lay->addWidget(V2_val, 1, 1); vert_contents_lay->addWidget(new QLabel("ΔV:", vert_contents), 2, 0); - deltaV_val = new QLabel("",this); + deltaV_val = new QLabel("", this); vert_contents_lay->addWidget(deltaV_val, 2, 1); vert_contents_lay->addItem(new QSpacerItem(0, 0, QSizePolicy::Fixed, QSizePolicy::Expanding), 3, 0); @@ -73,42 +87,32 @@ void PlotCursorReadouts::initContent() content_lay->addWidget(horiz_contents); horiz_contents_lay->addWidget(new QLabel("H1:", horiz_contents), 0, 0); - H1_val = new QLabel("",this); + H1_val = new QLabel("", this); horiz_contents_lay->addWidget(H1_val, 0, 1); horiz_contents_lay->addWidget(new QLabel("H2:", horiz_contents), 1, 0); - H2_val = new QLabel("",this); + H2_val = new QLabel("", this); horiz_contents_lay->addWidget(H2_val, 1, 1); horiz_contents_lay->addWidget(new QLabel("ΔH:", horiz_contents), 2, 0); - deltaH_val = new QLabel("",this); + deltaH_val = new QLabel("", this); horiz_contents_lay->addWidget(deltaH_val, 2, 1); horiz_contents_lay->addWidget(new QLabel("1/ΔH:", horiz_contents), 3, 0); - invDeltaH_val = new QLabel("",this); + invDeltaH_val = new QLabel("", this); horiz_contents_lay->addWidget(invDeltaH_val, 3, 1); - for (auto w: this->findChildren()) { + for(auto w : this->findChildren()) { StyleHelper::TransparentWidget(w); } } -void PlotCursorReadouts::horizSetVisible(bool visible) -{ - horiz_contents->setVisible(visible); -} +void PlotCursorReadouts::horizSetVisible(bool visible) { horiz_contents->setVisible(visible); } -void PlotCursorReadouts::vertSetVisible(bool visible) -{ - vert_contents->setVisible(visible); -} +void PlotCursorReadouts::vertSetVisible(bool visible) { vert_contents->setVisible(visible); } -bool PlotCursorReadouts::horizIsVisible() -{ - return horiz_contents->isVisible(); -} +bool PlotCursorReadouts::horizIsVisible() { return horiz_contents->isVisible(); } -bool PlotCursorReadouts::vertIsVisible() -{ - return vert_contents->isVisible(); -} +bool PlotCursorReadouts::vertIsVisible() { return vert_contents->isVisible(); } + +#include "moc_plotcursorreadouts.cpp" diff --git a/gui/src/widgets/plotinfo.cpp b/gui/src/widgets/plotinfo.cpp index 818572a3d6..5843adc9bd 100644 --- a/gui/src/widgets/plotinfo.cpp +++ b/gui/src/widgets/plotinfo.cpp @@ -1,41 +1,36 @@ #include "plotinfo.h" + #include "hoverwidget.h" #include "plotaxis.h" using namespace scopy; -TimePlotHDivInfo::TimePlotHDivInfo(QWidget *parent) { +TimePlotHDivInfo::TimePlotHDivInfo(QWidget *parent) +{ StyleHelper::TimePlotHDivInfo(this); setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); m_mpf = new MetricPrefixFormatter(this); - } -TimePlotHDivInfo::~TimePlotHDivInfo() -{ - -} +TimePlotHDivInfo::~TimePlotHDivInfo() {} -void TimePlotHDivInfo::update(double val) { - setText(m_mpf->format(val, "s", 2) + "/div"); -} +void TimePlotHDivInfo::update(double val) { setText(m_mpf->format(val, "s", 2) + "/div"); } -TimePlotSamplingInfo::TimePlotSamplingInfo(QWidget *parent) { +TimePlotSamplingInfo::TimePlotSamplingInfo(QWidget *parent) +{ StyleHelper::TimePlotSamplingInfo(this); setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); m_mpf = new MetricPrefixFormatter(this); } -TimePlotSamplingInfo::~TimePlotSamplingInfo() -{ - -} +TimePlotSamplingInfo::~TimePlotSamplingInfo() {} -void TimePlotSamplingInfo::update(int ps, int bs, double sr) { +void TimePlotSamplingInfo::update(int ps, int bs, double sr) +{ QString text; - text = QString("%1").arg(m_mpf->format(ps, "samples", 2));//.arg(m_mpf->format(bs, "samples", 2)); -// if(sr != 1.0) - text += QString(" at %2").arg(m_mpf->format(sr, "sps", 2)); + text = QString("%1").arg(m_mpf->format(ps, "samples", 2)); //.arg(m_mpf->format(bs, "samples", 2)); + // if(sr != 1.0) + text += QString(" at %2").arg(m_mpf->format(sr, "sps", 2)); setText(text); } @@ -46,12 +41,10 @@ TimePlotStatusInfo::TimePlotStatusInfo(QWidget *parent) StyleHelper::TimePlotSamplingInfo(this); } -TimePlotStatusInfo::~TimePlotStatusInfo() -{ - -} +TimePlotStatusInfo::~TimePlotStatusInfo() {} -void PlotBufferPreviewerController::setupBufferPreviewer() { +void PlotBufferPreviewerController::setupBufferPreviewer() +{ m_bufferPreviewer->setMinimumHeight(20); m_bufferPreviewer->setCursorPos(0.5); m_bufferPreviewer->setHighlightPos(0.05); @@ -62,8 +55,7 @@ void PlotBufferPreviewerController::setupBufferPreviewer() { updateDataLimits(m_plot->xAxis()->min(), m_plot->xAxis()->max()); - connect(m_bufferPreviewer, &BufferPreviewer::bufferStopDrag, this, [=]() { - }); + connect(m_bufferPreviewer, &BufferPreviewer::bufferStopDrag, this, [=]() {}); connect(m_bufferPreviewer, &BufferPreviewer::bufferStartDrag, this, [=]() { m_bufferPrevInitMin = m_plot->xAxis()->min(); @@ -77,28 +69,30 @@ void PlotBufferPreviewerController::setupBufferPreviewer() { double xAxisWidth = m_bufferPrevData; moveTo = value * xAxisWidth / width; - m_plot->xAxis()->setInterval(m_bufferPrevInitMin + moveTo, m_bufferPrevInitMax + moveTo); + m_plot->xAxis()->setInterval(m_bufferPrevInitMin + moveTo, m_bufferPrevInitMax + moveTo); m_plot->replot(); updateBufferPreviewer(); - } ); + }); connect(m_bufferPreviewer, &BufferPreviewer::bufferResetPosition, this, [=]() { - m_plot->xAxis()->setInterval(m_bufferPrevInitMin, m_bufferPrevInitMax); + m_plot->xAxis()->setInterval(m_bufferPrevInitMin, m_bufferPrevInitMax); m_plot->replot(); updateBufferPreviewer(); - } ); + }); } -void PlotBufferPreviewerController::updateDataLimits(double min, double max) { +void PlotBufferPreviewerController::updateDataLimits(double min, double max) +{ m_bufferPrevData = max - min; updateBufferPreviewer(); } -void PlotBufferPreviewerController::updateBufferPreviewer() { +void PlotBufferPreviewerController::updateBufferPreviewer() +{ // Time interval within the plot canvas - QwtInterval plotInterval(m_plot->xAxis()->min(), m_plot->xAxis()->max()); + QwtInterval plotInterval(m_plot->xAxis()->min(), m_plot->xAxis()->max()); // Time interval that represents the captured data QwtInterval dataInterval(0.0, m_bufferPrevData); @@ -106,15 +100,12 @@ void PlotBufferPreviewerController::updateBufferPreviewer() { // Use the two intervals to determine the width and position of the // waveform and of the highlighted area QwtInterval fullInterval = plotInterval | dataInterval; - double wPos = 1 - (fullInterval.maxValue() - dataInterval.minValue()) / - fullInterval.width(); + double wPos = 1 - (fullInterval.maxValue() - dataInterval.minValue()) / fullInterval.width(); double wWidth = dataInterval.width() / fullInterval.width(); - double hPos = 1 - (fullInterval.maxValue() - plotInterval.minValue()) / - fullInterval.width(); + double hPos = 1 - (fullInterval.maxValue() - plotInterval.minValue()) / fullInterval.width(); double hWidth = plotInterval.width() / fullInterval.width(); - m_bufferPreviewer->setWaveformWidth(wWidth); m_bufferPreviewer->setWaveformPos(wPos); m_bufferPreviewer->setHighlightWidth(hWidth); @@ -128,10 +119,7 @@ PlotBufferPreviewerController::PlotBufferPreviewerController(PlotWidget *p, Buff setupBufferPreviewer(); } -PlotBufferPreviewerController::~PlotBufferPreviewerController() -{ - -} +PlotBufferPreviewerController::~PlotBufferPreviewerController() {} TimePlotInfo::TimePlotInfo(PlotWidget *plot, QWidget *parent) { @@ -157,33 +145,31 @@ TimePlotInfo::TimePlotInfo(PlotWidget *plot, QWidget *parent) #ifdef HOVER_INFO lay->addWidget(m_hdiv); lay->addWidget(m_sampling); - lay->setAlignment(m_sampling,Qt::AlignRight); + lay->setAlignment(m_sampling, Qt::AlignRight); #else HoverWidget *hdivhover = new HoverWidget(nullptr, plot->plot()->canvas(), plot->plot()); hdivhover->setContent(m_hdiv); hdivhover->setAnchorPos(HoverPosition::HP_TOPLEFT); hdivhover->setContentPos(HoverPosition::HP_BOTTOMRIGHT); - hdivhover->setAnchorOffset(QPoint(8,6)); + hdivhover->setAnchorOffset(QPoint(8, 6)); hdivhover->show(); m_hdiv->setAttribute(Qt::WA_TransparentForMouseEvents); - HoverWidget *samplinginfohover = new HoverWidget(nullptr, plot->plot()->canvas(), plot->plot()); + HoverWidget *samplinginfohover = new HoverWidget(nullptr, plot->plot()->canvas(), plot->plot()); samplinginfohover->setContent(m_sampling); samplinginfohover->setAnchorPos(HoverPosition::HP_TOPRIGHT); samplinginfohover->setContentPos(HoverPosition::HP_BOTTOMLEFT); - samplinginfohover->setAnchorOffset(QPoint(-8,6)); + samplinginfohover->setAnchorOffset(QPoint(-8, 6)); samplinginfohover->show(); samplinginfohover->setAttribute(Qt::WA_TransparentForMouseEvents); #endif } -TimePlotInfo::~TimePlotInfo() -{ - -} +TimePlotInfo::~TimePlotInfo() {} -void TimePlotInfo::update(PlotSamplingInfo info) { +void TimePlotInfo::update(PlotSamplingInfo info) +{ auto x = m_plot->xAxis(); auto max = x->max(); auto min = x->min(); @@ -194,7 +180,6 @@ void TimePlotInfo::update(PlotSamplingInfo info) { m_bufferController->updateDataLimits(min, max); } -void TimePlotInfo::updateBufferPreviewer() -{ - m_bufferController->updateBufferPreviewer(); -} +void TimePlotInfo::updateBufferPreviewer() { m_bufferController->updateBufferPreviewer(); } + +#include "moc_plotinfo.cpp" diff --git a/gui/src/widgets/popupwidget.cpp b/gui/src/widgets/popupwidget.cpp index f1314330e1..bcb20bc37f 100644 --- a/gui/src/widgets/popupwidget.cpp +++ b/gui/src/widgets/popupwidget.cpp @@ -18,15 +18,15 @@ * along with this program. If not, see . */ - #include "widgets/popupwidget.h" + #include "stylehelper.h" using namespace scopy; -PopupWidget::PopupWidget(QWidget* parent) : - m_tintedOverlay(nullptr), - QWidget(parent) +PopupWidget::PopupWidget(QWidget *parent) + : m_tintedOverlay(nullptr) + , QWidget(parent) { this->initUI(); @@ -36,11 +36,10 @@ PopupWidget::PopupWidget(QWidget* parent) : m_continueButton->setFocus(); } -PopupWidget::~PopupWidget() { - delete m_tintedOverlay; -} +PopupWidget::~PopupWidget() { delete m_tintedOverlay; } -void PopupWidget::initUI() { +void PopupWidget::initUI() +{ this->setObjectName("PopupWidget"); this->setStyleSheet(""); this->resize(500, 300); @@ -83,50 +82,42 @@ void PopupWidget::initUI() { StyleHelper::OverlayMenu(this, "popupOverlay"); } -void PopupWidget::setFocusOnContinueButton() { +void PopupWidget::setFocusOnContinueButton() +{ m_continueButton->setAutoDefault(true); m_continueButton->setFocus(); } -void PopupWidget::setFocusOnExitButton() { +void PopupWidget::setFocusOnExitButton() +{ m_exitButton->setAutoDefault(true); m_exitButton->setFocus(); } -QString PopupWidget::getDescription() { - return m_descriptionTextBrowser->toMarkdown(); -} +QString PopupWidget::getDescription() { return m_descriptionTextBrowser->toMarkdown(); } -void PopupWidget::setDescription(const QString& description) { - m_descriptionTextBrowser->setMarkdown(description); -} +void PopupWidget::setDescription(const QString &description) { m_descriptionTextBrowser->setMarkdown(description); } -QString PopupWidget::getTitle() { - return m_titleLabel->text(); -} +QString PopupWidget::getTitle() { return m_titleLabel->text(); } -void PopupWidget::setTitle(const QString &title) { - m_titleLabel->setText(title); -} +void PopupWidget::setTitle(const QString &title) { m_titleLabel->setText(title); } -void PopupWidget::enableTitleBar(bool enable) { - if (enable) { +void PopupWidget::enableTitleBar(bool enable) +{ + if(enable) { m_titleLabel->show(); } else { m_titleLabel->hide(); } } -QPushButton *PopupWidget::getExitBtn() { - return m_exitButton; -} +QPushButton *PopupWidget::getExitBtn() { return m_exitButton; } -QPushButton *PopupWidget::getContinueBtn() { - return m_continueButton; -} +QPushButton *PopupWidget::getContinueBtn() { return m_continueButton; } -void PopupWidget::enableTintedOverlay(bool enable) { - if (enable) { +void PopupWidget::enableTintedOverlay(bool enable) +{ + if(enable) { delete m_tintedOverlay; m_tintedOverlay = new gui::TintedOverlay(parentWidget()); diff --git a/gui/src/widgets/semiexclusivebuttongroup.cpp b/gui/src/widgets/semiexclusivebuttongroup.cpp index a03a5aecb9..fccc4e2854 100644 --- a/gui/src/widgets/semiexclusivebuttongroup.cpp +++ b/gui/src/widgets/semiexclusivebuttongroup.cpp @@ -2,7 +2,9 @@ using namespace scopy; -SemiExclusiveButtonGroup::SemiExclusiveButtonGroup(QObject *parent) : QButtonGroup(parent) { +SemiExclusiveButtonGroup::SemiExclusiveButtonGroup(QObject *parent) + : QButtonGroup(parent) +{ m_exclusive = true; m_lastBtn = nullptr; QButtonGroup::setExclusive(false); @@ -13,9 +15,10 @@ void SemiExclusiveButtonGroup::setExclusive(bool bExclusive) { m_exclusive = bEx bool SemiExclusiveButtonGroup::exclusive() const { return m_exclusive; } -QAbstractButton *SemiExclusiveButtonGroup::getSelectedButton() { +QAbstractButton *SemiExclusiveButtonGroup::getSelectedButton() +{ QList buttonlist = buttons(); - for (auto iBtn = buttonlist.begin(); iBtn != buttonlist.end(); ++iBtn) { + for(auto iBtn = buttonlist.begin(); iBtn != buttonlist.end(); ++iBtn) { QAbstractButton *pBtn = *iBtn; if(pBtn->isChecked()) { return pBtn; @@ -24,22 +27,25 @@ QAbstractButton *SemiExclusiveButtonGroup::getSelectedButton() { return nullptr; } -QAbstractButton *SemiExclusiveButtonGroup::getLastButton() { +QAbstractButton *SemiExclusiveButtonGroup::getLastButton() +{ if(m_lastBtn == nullptr) { m_lastBtn = buttons()[0]; } return m_lastBtn; } -void SemiExclusiveButtonGroup::buttonClicked(QAbstractButton *button) { +void SemiExclusiveButtonGroup::buttonClicked(QAbstractButton *button) +{ QList buttonlist = buttons(); m_lastBtn = button; - if (m_exclusive) { + if(m_exclusive) { // just uncheck all other buttons regardless of the state of the clicked button - for (auto iBtn = buttonlist.begin(); iBtn != buttonlist.end(); ++iBtn) { + for(auto iBtn = buttonlist.begin(); iBtn != buttonlist.end(); ++iBtn) { QAbstractButton *pBtn = *iBtn; - if (pBtn && pBtn != button && pBtn->isCheckable()) pBtn->setChecked(false); + if(pBtn && pBtn != button && pBtn->isCheckable()) + pBtn->setChecked(false); } } Q_EMIT buttonSelected(getSelectedButton()); diff --git a/gui/src/widgets/toolbuttons.cpp b/gui/src/widgets/toolbuttons.cpp index 5d471c52df..859b2f2111 100644 --- a/gui/src/widgets/toolbuttons.cpp +++ b/gui/src/widgets/toolbuttons.cpp @@ -1,67 +1,74 @@ -#include #include +#include using namespace scopy; -PrintBtn::PrintBtn(QWidget *parent) : QPushButton(parent) { - StyleHelper::BlueGrayButton(this,"print_btn"); +PrintBtn::PrintBtn(QWidget *parent) + : QPushButton(parent) +{ + StyleHelper::BlueGrayButton(this, "print_btn"); setFixedWidth(128); setCheckable(false); setText("Print"); } -OpenLastMenuBtn::OpenLastMenuBtn(MenuHAnim *menu, bool opened, QWidget *parent) : QPushButton(parent), m_menu(menu) { +OpenLastMenuBtn::OpenLastMenuBtn(MenuHAnim *menu, bool opened, QWidget *parent) + : QPushButton(parent) + , m_menu(menu) +{ QIcon icon1; - icon1.addPixmap(Util::ChangeSVGColor(":/gui/icons/scopy-default/icons/setup3_unchecked_hover.svg","white",1)); + icon1.addPixmap(Util::ChangeSVGColor(":/gui/icons/scopy-default/icons/setup3_unchecked_hover.svg", "white", 1)); setIcon(icon1); - StyleHelper::SquareToggleButtonWithIcon(this,"open_last_menu_btn",true); + StyleHelper::SquareToggleButtonWithIcon(this, "open_last_menu_btn", true); setChecked(opened); grp = new SemiExclusiveButtonGroup(this); connect(this, &QPushButton::toggled, m_menu, &MenuHAnim::toggleMenu); - connect(grp,&SemiExclusiveButtonGroup::buttonSelected, this, [=](QAbstractButton* btn) { - if(btn == nullptr){ + connect(grp, &SemiExclusiveButtonGroup::buttonSelected, this, [=](QAbstractButton *btn) { + if(btn == nullptr) { this->setChecked(false); - } - else { + } else { this->setChecked(true); } }); - connect(this,&QAbstractButton::toggled, this, [=](bool b){ + connect(this, &QAbstractButton::toggled, this, [=](bool b) { if(b) { grp->getLastButton()->setChecked(true); } else { grp->getLastButton()->setChecked(false); - } }); } -QButtonGroup *OpenLastMenuBtn::getButtonGroup() { - return grp; -} +QButtonGroup *OpenLastMenuBtn::getButtonGroup() { return grp; } -GearBtn::GearBtn(QWidget *parent) : QPushButton(parent) { +GearBtn::GearBtn(QWidget *parent) + : QPushButton(parent) +{ QIcon icon1; - icon1.addPixmap(Util::ChangeSVGColor(":/gui/icons/scopy-default/icons/gear_wheel_hover.svg","white",1)); - StyleHelper::SquareToggleButtonWithIcon(this,"gear_btn",true); + icon1.addPixmap(Util::ChangeSVGColor(":/gui/icons/scopy-default/icons/gear_wheel_hover.svg", "white", 1)); + StyleHelper::SquareToggleButtonWithIcon(this, "gear_btn", true); setIcon(icon1); } -InfoBtn::InfoBtn(QWidget *parent) : QPushButton(parent) { +InfoBtn::InfoBtn(QWidget *parent) + : QPushButton(parent) +{ QIcon icon1; - icon1.addPixmap(Util::ChangeSVGColor(":/gui/icons/scopy-default/icons/info.svg","white",1)); - StyleHelper::SquareToggleButtonWithIcon(this,"info_btn",false); + icon1.addPixmap(Util::ChangeSVGColor(":/gui/icons/scopy-default/icons/info.svg", "white", 1)); + StyleHelper::SquareToggleButtonWithIcon(this, "info_btn", false); setIcon(icon1); } -RunBtn::RunBtn(QWidget *parent) : QPushButton(parent) { +RunBtn::RunBtn(QWidget *parent) + : QPushButton(parent) +{ setObjectName("run_btn"); setCheckable(true); setChecked(false); - setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setText("Run"); - connect(this,&QPushButton::toggled,this,[=](bool b){ setText(b ? "Stop" : "Run");}); + connect(this, &QPushButton::toggled, this, [=](bool b) { setText(b ? "Stop" : "Run"); }); QString style = QString(R"css( QPushButton { width: 88px; @@ -89,18 +96,21 @@ RunBtn::RunBtn(QWidget *parent) : QPushButton(parent) { setStyleSheet(style); QIcon icon1; - icon1.addPixmap(Util::ChangeSVGColor(":/gui/icons/play.svg","white",1), QIcon::Normal, QIcon::Off); - icon1.addPixmap(Util::ChangeSVGColor(":/gui/icons/scopy-default/icons/play_stop.svg","white",1), QIcon::Normal, QIcon::On); + icon1.addPixmap(Util::ChangeSVGColor(":/gui/icons/play.svg", "white", 1), QIcon::Normal, QIcon::Off); + icon1.addPixmap(Util::ChangeSVGColor(":/gui/icons/scopy-default/icons/play_stop.svg", "white", 1), + QIcon::Normal, QIcon::On); setIcon(icon1); setLayoutDirection(Qt::RightToLeft); } -SingleShotBtn::SingleShotBtn(QWidget *parent) : QPushButton(parent) { +SingleShotBtn::SingleShotBtn(QWidget *parent) + : QPushButton(parent) +{ setObjectName("single_btn"); setCheckable(true); setChecked(false); setText("Single"); - connect(this,&QPushButton::toggled,this,[=](bool b){ setText( b ? "Stop" : "Single");}); + connect(this, &QPushButton::toggled, this, [=](bool b) { setText(b ? "Stop" : "Single"); }); QString style = QString(R"css( QPushButton { width: 88px; @@ -130,8 +140,11 @@ SingleShotBtn::SingleShotBtn(QWidget *parent) : QPushButton(parent) { setStyleSheet(style); QIcon icon1; - icon1.addPixmap(Util::ChangeSVGColor(":/gui/icons/play_oneshot.svg","white",1), QIcon::Normal, QIcon::Off); - icon1.addPixmap(Util::ChangeSVGColor(":/gui/icons/scopy-default/icons/play_stop.svg","white",1), QIcon::Normal, QIcon::On); + icon1.addPixmap(Util::ChangeSVGColor(":/gui/icons/play_oneshot.svg", "white", 1), QIcon::Normal, QIcon::Off); + icon1.addPixmap(Util::ChangeSVGColor(":/gui/icons/scopy-default/icons/play_stop.svg", "white", 1), + QIcon::Normal, QIcon::On); setIcon(icon1); setLayoutDirection(Qt::RightToLeft); } + +#include "moc_toolbuttons.cpp" diff --git a/gui/src/widgets/verticalchannelmanager.cpp b/gui/src/widgets/verticalchannelmanager.cpp index cae9ee9762..9e63ac1699 100644 --- a/gui/src/widgets/verticalchannelmanager.cpp +++ b/gui/src/widgets/verticalchannelmanager.cpp @@ -1,21 +1,25 @@ #include using namespace scopy; -VerticalChannelManager::VerticalChannelManager(QWidget *parent) : QWidget(parent) { +VerticalChannelManager::VerticalChannelManager(QWidget *parent) + : QWidget(parent) +{ lay = new QVBoxLayout(this); setLayout(lay); lay->setMargin(0); lay->setSpacing(6); - spacer = new QSpacerItem(20,20,QSizePolicy::Expanding,QSizePolicy::Expanding); + spacer = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Expanding); lay->addSpacerItem(spacer); - setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Expanding); - + setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding); } -VerticalChannelManager::~VerticalChannelManager(){} +VerticalChannelManager::~VerticalChannelManager() {} -void VerticalChannelManager::add(QWidget *ch) { +void VerticalChannelManager::add(QWidget *ch) +{ int position = lay->indexOf(spacer); - lay->insertWidget(position,ch); - ch->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed); + lay->insertWidget(position, ch); + ch->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); } + +#include "moc_verticalchannelmanager.cpp" diff --git a/gui/src/x_axis_scale_zoomer.cpp b/gui/src/x_axis_scale_zoomer.cpp index 114b34c39a..f2ca36b5b3 100644 --- a/gui/src/x_axis_scale_zoomer.cpp +++ b/gui/src/x_axis_scale_zoomer.cpp @@ -18,23 +18,22 @@ * along with this program. If not, see . */ #include "x_axis_scale_zoomer.h" + #include "qwt_scale_draw.h" + #include #include using namespace scopy; -XAxisScaleZoomer::XAxisScaleZoomer(QWidget *parent): - OscScaleZoomer(parent) -{ -} +XAxisScaleZoomer::XAxisScaleZoomer(QWidget *parent) + : OscScaleZoomer(parent) +{} -XAxisScaleZoomer::~XAxisScaleZoomer() -{ -} +XAxisScaleZoomer::~XAxisScaleZoomer() {} -void XAxisScaleZoomer::zoom(const QRectF& rect) +void XAxisScaleZoomer::zoom(const QRectF &rect) { QRectF boundedRect = rect & zoomBase(); QRectF baseRect = zoomBase(); @@ -55,3 +54,5 @@ QwtText XAxisScaleZoomer::trackerText(const QPoint &p) const plt->getScaleValueFormat(dp.y(), QwtAxis::YLeft)); return t; } + +#include "moc_x_axis_scale_zoomer.cpp" diff --git a/gui/test/CMakeLists.txt b/gui/test/CMakeLists.txt index 9f4c228527..72baa8a4f8 100644 --- a/gui/test/CMakeLists.txt +++ b/gui/test/CMakeLists.txt @@ -1,23 +1,18 @@ cmake_minimum_required(VERSION 3.5) function(SETUP_TESTS) - foreach(_testname ${ARGS}) - add_executable(_testname ${ARGS}) - add_test(NAME ${_testname} COMMAND ${_testname}) - target_link_libraries(${_testname} Qt${QT_VERSION_MAJOR}::Test) - endforeach() + foreach(_testname ${ARGS}) + add_executable(_testname ${ARGS}) + add_test(NAME ${_testname} COMMAND ${_testname}) + target_link_libraries(${_testname} Qt${QT_VERSION_MAJOR}::Test) + endforeach() endfunction() - # Tell CMake to run moc when necessary: set(CMAKE_AUTOMOC ON) -# As moc files are generated in the binary dir, tell CMake -# to always look for includes there: +# As moc files are generated in the binary dir, tell CMake to always look for includes there: set(CMAKE_INCLUDE_CURRENT_DIR ON) find_package(Qt${QT_VERSION_MAJOR}Test REQUIRED) -SETUP_TESTS( - tst_test1 -) - +setup_tests(tst_test1) diff --git a/iioutil/CMakeLists.txt b/iioutil/CMakeLists.txt index 7e23325384..41fee4c796 100644 --- a/iioutil/CMakeLists.txt +++ b/iioutil/CMakeLists.txt @@ -5,8 +5,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -22,47 +21,61 @@ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) set(CMAKE_CXX_VISIBILITY_PRESET hidden) set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) -FILE(GLOB SRC_LIST src/*.cpp src/*.cc src/*/*.cpp src/*/*.cc) -FILE(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp - include/${SCOPY_MODULE}/*/*.h include/${SCOPY_MODULE}/*/*.hpp) -FILE(GLOB UI_LIST ui/*.ui) +file( + GLOB + SRC_LIST + src/*.cpp + src/*.cc + src/*/*.cpp + src/*/*.cc +) +file( + GLOB + HEADER_LIST + include/${SCOPY_MODULE}/*.h + include/${SCOPY_MODULE}/*.hpp + include/${SCOPY_MODULE}/*/*.h + include/${SCOPY_MODULE}/*/*.hpp +) +file(GLOB UI_LIST ui/*.ui) if(ENABLE_TESTING) - add_subdirectory(test) + add_subdirectory(test) endif() option(WITH_LIBSERIALPORT "Add serial backend support to Scopy - also needs to be enabled in libiio" ON) find_library(IIO_LIBRARIES NAMES iio libiio REQUIRED) find_path(IIO_INCLUDE_DIRS iio.h REQUIRED) -if (${WITH_LIBSERIALPORT}) +if(${WITH_LIBSERIALPORT}) find_library(LIBSERIALPORT_LIBRARIES serialport REQUIRED) find_path(LIBSERIALPORT_INCLUDE_DIR libserialport.h REQUIRED) message(STATUS "Building with libserialport support") endif() -configure_file(include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h.cmakein - ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h @ONLY) +configure_file( + include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h.cmakein + ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h @ONLY +) set(SRC_LIST ${SRC_LIST} ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_config.h) -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} -) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Widgets REQUIRED) -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) -target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include/ ${IIO_INCLUDE_DIRS} ${LIBSERIALPORT_INCLUDE_DIR}) -target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE} ${IIO_INCLUDE_DIRS} ${LIBSERIALPORT_INCLUDE_DIR}) +target_include_directories( + ${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include/ ${IIO_INCLUDE_DIRS} ${LIBSERIALPORT_INCLUDE_DIR} +) +target_include_directories( + ${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE} ${IIO_INCLUDE_DIRS} + ${LIBSERIALPORT_INCLUDE_DIR} +) target_link_libraries(${PROJECT_NAME} PUBLIC Qt${QT_VERSION_MAJOR}::Widgets ${IIO_LIBRARIES} ${LIBSERIALPORT_LIBRARIES}) -install(TARGETS ${PROJECT_NAME} - LIBRARY DESTINATION ${SCOPY_DLL_PATH} - RUNTIME DESTINATION ${SCOPY_DLL_PATH}) +install(TARGETS ${PROJECT_NAME} LIBRARY DESTINATION ${SCOPY_DLL_PATH} RUNTIME DESTINATION ${SCOPY_DLL_PATH}) diff --git a/iioutil/include/iioutil/command.h b/iioutil/include/iioutil/command.h index 63f527a3f8..f2c4eed849 100644 --- a/iioutil/include/iioutil/command.h +++ b/iioutil/include/iioutil/command.h @@ -2,45 +2,43 @@ #define COMMAND_H #include "scopy-iioutil_export.h" -#include + #include +#include namespace scopy { -class SCOPY_IIOUTIL_EXPORT CommandResult { +class SCOPY_IIOUTIL_EXPORT CommandResult +{ public: ssize_t errorCode; void *results = nullptr; }; -class SCOPY_IIOUTIL_EXPORT Command : public QObject { +class SCOPY_IIOUTIL_EXPORT Command : public QObject +{ Q_OBJECT public: - virtual ~Command() { + virtual ~Command() + { qDebug() << "Command deleted"; delete m_cmdResult; m_cmdResult = nullptr; - }; virtual void execute() = 0; - virtual ssize_t getReturnCode() { - return m_cmdResult->errorCode; - } - virtual bool isOverwrite() { - return m_overwrite; - } + virtual ssize_t getReturnCode() { return m_cmdResult->errorCode; } + virtual bool isOverwrite() { return m_overwrite; } Q_SIGNALS: void started(scopy::Command *command = nullptr); void finished(scopy::Command *command = nullptr); + protected: - void setOverwrite(bool overwrite) { - m_overwrite = overwrite; - } + void setOverwrite(bool overwrite) { m_overwrite = overwrite; } protected: CommandResult *m_cmdResult = nullptr; bool m_overwrite = false; }; -} +} // namespace scopy Q_DECLARE_METATYPE(scopy::Command *) #endif // COMMAND_H diff --git a/iioutil/include/iioutil/commandqueue.h b/iioutil/include/iioutil/commandqueue.h index 1f3bab5322..06867575e4 100644 --- a/iioutil/include/iioutil/commandqueue.h +++ b/iioutil/include/iioutil/commandqueue.h @@ -1,18 +1,18 @@ #ifndef IIOCOMMANDQUEUE_H #define IIOCOMMANDQUEUE_H -#include -#include +#include "command.h" + #include +#include -#include "command.h" +#include namespace scopy { class SCOPY_IIOUTIL_EXPORT CommandQueue : public QObject { Q_OBJECT public: - /** * @brief IioCommandQueue::IioCommandQueue * @param numberOfThreads @@ -31,9 +31,10 @@ private Q_SLOTS: void work(); void cmdStarted(scopy::Command *cmd); void cmdFinished(scopy::Command *cmd); + private: Command *m_currentCommand; - std::deque m_commandQueue; + std::deque m_commandQueue; std::mutex m_commandMutex; std::atomic m_running; QThreadPool m_commandExecThreadPool; @@ -41,5 +42,5 @@ private Q_SLOTS: bool m_async; bool m_workNewThread; }; -} +} // namespace scopy #endif // IIOCOMMANDQUEUE_H diff --git a/iioutil/include/iioutil/commandqueueprovider.h b/iioutil/include/iioutil/commandqueueprovider.h index 67cc16614f..6f659e5e03 100644 --- a/iioutil/include/iioutil/commandqueueprovider.h +++ b/iioutil/include/iioutil/commandqueueprovider.h @@ -1,13 +1,16 @@ #ifndef COMMANDQUEUEPROVIDER_H #define COMMANDQUEUEPROVIDER_H -#include "scopy-iioutil_export.h" #include "commandqueue.h" -#include +#include "scopy-iioutil_export.h" + #include +#include + namespace scopy { -class SCOPY_IIOUTIL_EXPORT CommandQueueRefCounter { +class SCOPY_IIOUTIL_EXPORT CommandQueueRefCounter +{ public: CommandQueueRefCounter(struct iio_context *ctx); ~CommandQueueRefCounter(); @@ -18,26 +21,25 @@ class SCOPY_IIOUTIL_EXPORT CommandQueueRefCounter { class SCOPY_IIOUTIL_EXPORT CommandQueueProvider : public QObject { -Q_OBJECT + Q_OBJECT protected: CommandQueueProvider(QObject *parent = nullptr); ~CommandQueueProvider(); QString name; -public: +public: CommandQueueProvider(CommandQueueProvider &other) = delete; void operator=(const CommandQueueProvider &) = delete; static CommandQueueProvider *GetInstance(); - CommandQueue* open(struct iio_context *ctx); + CommandQueue *open(struct iio_context *ctx); void close(struct iio_context *ctx); private: - static CommandQueueProvider * pinstance_; + static CommandQueueProvider *pinstance_; static std::mutex mutex_; - QMap map; - + QMap map; }; -} +} // namespace scopy #endif diff --git a/iioutil/include/iioutil/contextprovider.h b/iioutil/include/iioutil/contextprovider.h index 6ebc8eaff8..3931cbe5ee 100644 --- a/iioutil/include/iioutil/contextprovider.h +++ b/iioutil/include/iioutil/contextprovider.h @@ -2,44 +2,47 @@ #define CONTEXTPROVIDER_H #include "scopy-iioutil_export.h" -#include + +#include + #include +#include + #include -#include #include namespace scopy { -class SCOPY_IIOUTIL_EXPORT ContextRefCounter { +class SCOPY_IIOUTIL_EXPORT ContextRefCounter +{ public: ContextRefCounter(QString uri); ~ContextRefCounter(); QString uri; - struct iio_context* ctx = nullptr; + struct iio_context *ctx = nullptr; int refcnt = 0; }; class SCOPY_IIOUTIL_EXPORT ContextProvider : public QObject { -Q_OBJECT + Q_OBJECT protected: ContextProvider(QObject *parent = nullptr); ~ContextProvider(); QString name; -public: +public: ContextProvider(ContextProvider &other) = delete; void operator=(const ContextProvider &) = delete; static ContextProvider *GetInstance(); - struct iio_context* open(QString uri); + struct iio_context *open(QString uri); void close(QString uri); private: - static ContextProvider * pinstance_; + static ContextProvider *pinstance_; static std::mutex mutex_; - QMap map; - + QMap map; }; -} +} // namespace scopy #endif // CONTEXTPROVIDER_H diff --git a/iioutil/include/iioutil/cyclicaltask.h b/iioutil/include/iioutil/cyclicaltask.h index 37f2d0dde4..bbc3d875be 100644 --- a/iioutil/include/iioutil/cyclicaltask.h +++ b/iioutil/include/iioutil/cyclicaltask.h @@ -1,12 +1,14 @@ #ifndef CYCLICALTASK_H #define CYCLICALTASK_H -#include -#include -#include -#include #include "scopy-iioutil_export.h" + +#include + #include +#include +#include +#include namespace scopy { /** @@ -24,14 +26,13 @@ class SCOPY_IIOUTIL_EXPORT CyclicalTask : public QObject private Q_SLOTS: void startThread(); + private: QTimer *t; bool enabled = false; - QThread* task; + QThread *task; const int THREAD_FINISH_TIMEOUT = 30000; }; -} - - +} // namespace scopy #endif // CYCLICALTASK_H diff --git a/iioutil/include/iioutil/iiocommand/iiobuffercancel.h b/iioutil/include/iioutil/iiocommand/iiobuffercancel.h index 5e058c92ae..f749cb4d38 100644 --- a/iioutil/include/iioutil/iiocommand/iiobuffercancel.h +++ b/iioutil/include/iioutil/iiocommand/iiobuffercancel.h @@ -2,20 +2,23 @@ #define IIOBUFFERCANCEL_H #include "../command.h" + #include namespace scopy { -class SCOPY_IIOUTIL_EXPORT IioBufferCancel : public Command { +class SCOPY_IIOUTIL_EXPORT IioBufferCancel : public Command +{ Q_OBJECT public: - explicit IioBufferCancel(struct iio_buffer *buffer, - QObject *parent) - : m_buffer(buffer) { + explicit IioBufferCancel(struct iio_buffer *buffer, QObject *parent) + : m_buffer(buffer) + { this->setParent(parent); m_cmdResult = new CommandResult(); } - virtual void execute() override { + virtual void execute() override + { Q_EMIT started(this); iio_buffer_cancel(m_buffer); m_cmdResult->errorCode = 0; @@ -25,6 +28,6 @@ class SCOPY_IIOUTIL_EXPORT IioBufferCancel : public Command { private: struct iio_buffer *m_buffer; }; -} +} // namespace scopy #endif // IIOBUFFERCANCEL_H diff --git a/iioutil/include/iioutil/iiocommand/iiobufferdestroy.h b/iioutil/include/iioutil/iiocommand/iiobufferdestroy.h index c26bbc2473..2ad11d2157 100644 --- a/iioutil/include/iioutil/iiocommand/iiobufferdestroy.h +++ b/iioutil/include/iioutil/iiocommand/iiobufferdestroy.h @@ -2,24 +2,27 @@ #define IIOBUFFERDESTROY_H #include "../command.h" + #include namespace scopy { -class SCOPY_IIOUTIL_EXPORT IioBufferDestroy : public Command { +class SCOPY_IIOUTIL_EXPORT IioBufferDestroy : public Command +{ Q_OBJECT public: - explicit IioBufferDestroy(struct iio_buffer *buffer, - QObject *parent) - : m_buffer(buffer) { + explicit IioBufferDestroy(struct iio_buffer *buffer, QObject *parent) + : m_buffer(buffer) + { this->setParent(parent); m_cmdResult = new CommandResult(); } - virtual void execute() override { + virtual void execute() override + { Q_EMIT started(this); m_cmdResult->errorCode = 0; iio_buffer_destroy(m_buffer); - if (!m_buffer) { + if(!m_buffer) { m_cmdResult->errorCode = -errno; } Q_EMIT finished(this); @@ -28,6 +31,6 @@ class SCOPY_IIOUTIL_EXPORT IioBufferDestroy : public Command { private: struct iio_buffer *m_buffer; }; -} +} // namespace scopy #endif // IIOBUFFERDESTROY_H diff --git a/iioutil/include/iioutil/iiocommand/iiobufferpush.h b/iioutil/include/iioutil/iiocommand/iiobufferpush.h index dfb1418759..bb4cb3101a 100644 --- a/iioutil/include/iioutil/iiocommand/iiobufferpush.h +++ b/iioutil/include/iioutil/iiocommand/iiobufferpush.h @@ -2,20 +2,23 @@ #define IIOBUFFERPUSH_H #include "../command.h" + #include namespace scopy { -class SCOPY_IIOUTIL_EXPORT IioBufferPush : public Command { +class SCOPY_IIOUTIL_EXPORT IioBufferPush : public Command +{ Q_OBJECT public: - explicit IioBufferPush(struct iio_buffer *buffer, - QObject *parent) - : m_buffer(buffer) { + explicit IioBufferPush(struct iio_buffer *buffer, QObject *parent) + : m_buffer(buffer) + { this->setParent(parent); m_cmdResult = new CommandResult(); } - virtual void execute() override { + virtual void execute() override + { Q_EMIT started(this); ssize_t ret = iio_buffer_push(m_buffer); m_cmdResult->errorCode = ret; @@ -25,7 +28,6 @@ class SCOPY_IIOUTIL_EXPORT IioBufferPush : public Command { private: struct iio_buffer *m_buffer; }; -} +} // namespace scopy #endif // IIOBUFFERPUSH_H - diff --git a/iioutil/include/iioutil/iiocommand/iiobufferrefill.h b/iioutil/include/iioutil/iiocommand/iiobufferrefill.h index f4ed9e8e8b..4d38bb3d7e 100644 --- a/iioutil/include/iioutil/iiocommand/iiobufferrefill.h +++ b/iioutil/include/iioutil/iiocommand/iiobufferrefill.h @@ -2,20 +2,23 @@ #define IIOBUFFERREFILL_H #include "../command.h" + #include namespace scopy { -class SCOPY_IIOUTIL_EXPORT IioBufferRefill : public Command { +class SCOPY_IIOUTIL_EXPORT IioBufferRefill : public Command +{ Q_OBJECT public: - explicit IioBufferRefill(struct iio_buffer *buffer, - QObject *parent) - : m_buffer(buffer) { + explicit IioBufferRefill(struct iio_buffer *buffer, QObject *parent) + : m_buffer(buffer) + { this->setParent(parent); m_cmdResult = new CommandResult(); } - virtual void execute() override { + virtual void execute() override + { Q_EMIT started(this); ssize_t ret = iio_buffer_refill(m_buffer); m_cmdResult->errorCode = ret; @@ -25,6 +28,6 @@ class SCOPY_IIOUTIL_EXPORT IioBufferRefill : public Command { private: struct iio_buffer *m_buffer; }; -} +} // namespace scopy #endif // IIOBUFFERREFILL_H diff --git a/iioutil/include/iioutil/iiocommand/iiochannelattributeread.h b/iioutil/include/iioutil/iiocommand/iiochannelattributeread.h index 68db88713e..514f9d2c70 100644 --- a/iioutil/include/iioutil/iiocommand/iiochannelattributeread.h +++ b/iioutil/include/iioutil/iiocommand/iiochannelattributeread.h @@ -2,16 +2,16 @@ #define IIOCHANNELATTRIBUTEREAD_H #include "../command.h" + #include namespace scopy { -class SCOPY_IIOUTIL_EXPORT IioChannelAttributeRead : public Command { +class SCOPY_IIOUTIL_EXPORT IioChannelAttributeRead : public Command +{ Q_OBJECT public: - explicit IioChannelAttributeRead(struct iio_channel *channel, - const char *attribute, - QObject *parent, - bool overwrite = false) + explicit IioChannelAttributeRead(struct iio_channel *channel, const char *attribute, QObject *parent, + bool overwrite = false) : m_channel(channel) , m_attribute_name(std::string(attribute)) { @@ -20,36 +20,35 @@ class SCOPY_IIOUTIL_EXPORT IioChannelAttributeRead : public Command { m_cmdResult = new CommandResult(); } - virtual ~IioChannelAttributeRead() { - if (m_cmdResult->results) { - delete[] (char*)m_cmdResult->results; + virtual ~IioChannelAttributeRead() + { + if(m_cmdResult->results) { + delete[](char *) m_cmdResult->results; m_cmdResult->results = nullptr; } } - virtual void execute() override { + virtual void execute() override + { Q_EMIT started(this); - if (!m_cmdResult->results) { + if(!m_cmdResult->results) { m_cmdResult->results = new char[m_maxAttrSize]; } - ssize_t ret = iio_channel_attr_read(m_channel, m_attribute_name.c_str(), (char*)m_cmdResult->results, m_maxAttrSize); + ssize_t ret = iio_channel_attr_read(m_channel, m_attribute_name.c_str(), (char *)m_cmdResult->results, + m_maxAttrSize); m_cmdResult->errorCode = ret; Q_EMIT finished(this); } - char* getResult() { - return static_cast(m_cmdResult->results); - } + char *getResult() { return static_cast(m_cmdResult->results); } - struct iio_channel *getChannel() { - return m_channel; - } + struct iio_channel *getChannel() { return m_channel; } private: struct iio_channel *m_channel; std::string m_attribute_name; const ssize_t m_maxAttrSize = 1024; }; -} +} // namespace scopy #endif // IIOCHANNELATTRIBUTEREAD_H diff --git a/iioutil/include/iioutil/iiocommand/iiochannelattributewrite.h b/iioutil/include/iioutil/iiocommand/iiochannelattributewrite.h index 5cb61114b7..8f1b3b4278 100644 --- a/iioutil/include/iioutil/iiocommand/iiochannelattributewrite.h +++ b/iioutil/include/iioutil/iiocommand/iiochannelattributewrite.h @@ -2,17 +2,16 @@ #define IIOCHANNELATTRIBUTEWRITE_H #include "../command.h" + #include namespace scopy { -class SCOPY_IIOUTIL_EXPORT IioChannelAttributeWrite : public Command { +class SCOPY_IIOUTIL_EXPORT IioChannelAttributeWrite : public Command +{ Q_OBJECT public: - explicit IioChannelAttributeWrite(struct iio_channel *channel, - const char *attribute, - const char *value, - QObject *parent, - bool overwrite = false) + explicit IioChannelAttributeWrite(struct iio_channel *channel, const char *attribute, const char *value, + QObject *parent, bool overwrite = false) : m_channel(channel) , m_attribute_name(std::string(attribute)) , m_value(std::string(value)) @@ -22,7 +21,8 @@ class SCOPY_IIOUTIL_EXPORT IioChannelAttributeWrite : public Command { m_cmdResult = new CommandResult(); } - virtual void execute() override { + virtual void execute() override + { Q_EMIT started(this); ssize_t ret = iio_channel_attr_write(m_channel, m_attribute_name.c_str(), m_value.c_str()); m_cmdResult->errorCode = ret; @@ -34,6 +34,6 @@ class SCOPY_IIOUTIL_EXPORT IioChannelAttributeWrite : public Command { std::string m_attribute_name; std::string m_value; }; -} +} // namespace scopy #endif // IIOCHANNELATTRIBUTEWRITE_H diff --git a/iioutil/include/iioutil/iiocommand/iiochannelenable.h b/iioutil/include/iioutil/iiocommand/iiochannelenable.h index 4508c30476..98d0c00f9d 100644 --- a/iioutil/include/iioutil/iiocommand/iiochannelenable.h +++ b/iioutil/include/iioutil/iiocommand/iiochannelenable.h @@ -2,24 +2,26 @@ #define IIOCHANNELENABLE_H #include "../command.h" + #include namespace scopy { -class SCOPY_IIOUTIL_EXPORT IioChannelEnable : public Command { +class SCOPY_IIOUTIL_EXPORT IioChannelEnable : public Command +{ Q_OBJECT public: - explicit IioChannelEnable(struct iio_channel *channel, - bool enable, - QObject *parent) + explicit IioChannelEnable(struct iio_channel *channel, bool enable, QObject *parent) : m_channel(channel) - , m_enable(enable) { + , m_enable(enable) + { this->setParent(parent); m_cmdResult = new CommandResult(); } - virtual void execute() override { + virtual void execute() override + { Q_EMIT started(this); - if (m_enable) { + if(m_enable) { iio_channel_enable(m_channel); } else { iio_channel_disable(m_channel); @@ -33,6 +35,6 @@ class SCOPY_IIOUTIL_EXPORT IioChannelEnable : public Command { const char *m_attribute_name; bool m_enable; }; -} +} // namespace scopy #endif // IIOCHANNELENABLE_H diff --git a/iioutil/include/iioutil/iiocommand/iiodeviceattributeread.h b/iioutil/include/iioutil/iiocommand/iiodeviceattributeread.h index f06bcdc170..657c21d1e2 100644 --- a/iioutil/include/iioutil/iiocommand/iiodeviceattributeread.h +++ b/iioutil/include/iioutil/iiocommand/iiodeviceattributeread.h @@ -2,15 +2,15 @@ #define IIODEVICEATTRIBUTEREAD_H #include "../command.h" + #include namespace scopy { -class SCOPY_IIOUTIL_EXPORT IioDeviceAttributeRead : public Command { +class SCOPY_IIOUTIL_EXPORT IioDeviceAttributeRead : public Command +{ Q_OBJECT public: - explicit IioDeviceAttributeRead(struct iio_device *device, - const char *attribute, - QObject *parent, + explicit IioDeviceAttributeRead(struct iio_device *device, const char *attribute, QObject *parent, bool overwrite = false) : m_device(device) , m_attribute_name(std::string(attribute)) @@ -20,32 +20,33 @@ class SCOPY_IIOUTIL_EXPORT IioDeviceAttributeRead : public Command { m_cmdResult = new CommandResult(); } - virtual ~IioDeviceAttributeRead() { - if (m_cmdResult->results) { - delete[] (char*)m_cmdResult->results; + virtual ~IioDeviceAttributeRead() + { + if(m_cmdResult->results) { + delete[](char *) m_cmdResult->results; m_cmdResult->results = nullptr; } } - virtual void execute() override { + virtual void execute() override + { Q_EMIT started(this); - if (!m_cmdResult->results) { + if(!m_cmdResult->results) { m_cmdResult->results = new char[m_maxAttrSize]; } - ssize_t ret = iio_device_attr_read(m_device, m_attribute_name.c_str(), (char*)m_cmdResult->results, m_maxAttrSize); + ssize_t ret = iio_device_attr_read(m_device, m_attribute_name.c_str(), (char *)m_cmdResult->results, + m_maxAttrSize); m_cmdResult->errorCode = ret; Q_EMIT finished(this); } - char* getResult() { - return static_cast(m_cmdResult->results); - } + char *getResult() { return static_cast(m_cmdResult->results); } private: struct iio_device *m_device; std::string m_attribute_name; const ssize_t m_maxAttrSize = 1024; }; -} +} // namespace scopy #endif // IIODEVICEATTRIBUTEREAD_H diff --git a/iioutil/include/iioutil/iiocommand/iiodeviceattributewrite.h b/iioutil/include/iioutil/iiocommand/iiodeviceattributewrite.h index 3ae7a1380b..b94172f637 100644 --- a/iioutil/include/iioutil/iiocommand/iiodeviceattributewrite.h +++ b/iioutil/include/iioutil/iiocommand/iiodeviceattributewrite.h @@ -2,17 +2,16 @@ #define IIODEVICEATTRIBUTEWRITE_H #include "../command.h" + #include namespace scopy { -class SCOPY_IIOUTIL_EXPORT IioDeviceAttributeWrite : public Command { +class SCOPY_IIOUTIL_EXPORT IioDeviceAttributeWrite : public Command +{ Q_OBJECT public: - explicit IioDeviceAttributeWrite(struct iio_device *device, - const char *attribute, - const char *value, - QObject *parent, - bool overwrite = false) + explicit IioDeviceAttributeWrite(struct iio_device *device, const char *attribute, const char *value, + QObject *parent, bool overwrite = false) : m_device(device) , m_attribute_name(std::string(attribute)) , m_value(std::string(value)) @@ -22,22 +21,21 @@ class SCOPY_IIOUTIL_EXPORT IioDeviceAttributeWrite : public Command { m_cmdResult = new CommandResult(); } - virtual void execute() override { + virtual void execute() override + { Q_EMIT started(this); ssize_t ret = iio_device_attr_write(m_device, m_attribute_name.c_str(), m_value.c_str()); m_cmdResult->errorCode = ret; Q_EMIT finished(this); } - std::string getAttributeValue() { - return m_value; - } + std::string getAttributeValue() { return m_value; } private: struct iio_device *m_device; std::string m_attribute_name; std::string m_value; }; -} +} // namespace scopy #endif // IIODEVICEATTRIBUTEWRITE_H diff --git a/iioutil/include/iioutil/iiocommand/iiodevicecreatebuffer.h b/iioutil/include/iioutil/iiocommand/iiodevicecreatebuffer.h index ead2248773..dcfa96f004 100644 --- a/iioutil/include/iioutil/iiocommand/iiodevicecreatebuffer.h +++ b/iioutil/include/iioutil/iiocommand/iiodevicecreatebuffer.h @@ -2,27 +2,28 @@ #define IIODEVICECREATEBUFFER_H #include "../command.h" + #include namespace scopy { -class SCOPY_IIOUTIL_EXPORT IioDeviceCreateBuffer : public Command { +class SCOPY_IIOUTIL_EXPORT IioDeviceCreateBuffer : public Command +{ Q_OBJECT public: - explicit IioDeviceCreateBuffer(struct iio_device *device, - size_t samples_count, - bool cyclic, - QObject *parent) + explicit IioDeviceCreateBuffer(struct iio_device *device, size_t samples_count, bool cyclic, QObject *parent) : m_device(device) , m_samplesCount(samples_count) - , m_cyclic(cyclic) { + , m_cyclic(cyclic) + { this->setParent(parent); m_cmdResult = new CommandResult(); } - virtual void execute() override { + virtual void execute() override + { Q_EMIT started(this); struct iio_buffer *buffer = iio_device_create_buffer(m_device, m_samplesCount, m_cyclic); - if (!buffer) { + if(!buffer) { m_cmdResult->errorCode = -errno; } else { m_cmdResult->errorCode = 0; @@ -31,15 +32,13 @@ class SCOPY_IIOUTIL_EXPORT IioDeviceCreateBuffer : public Command { Q_EMIT finished(this); } + iio_buffer *getResult() { return static_cast(m_cmdResult->results); } - iio_buffer* getResult() { - return static_cast(m_cmdResult->results); - } private: struct iio_device *m_device; ssize_t m_samplesCount; bool m_cyclic; }; -} +} // namespace scopy #endif // IIODEVICECREATEBUFFER_H diff --git a/iioutil/include/iioutil/iiocommand/iiodevicegettrigger.h b/iioutil/include/iioutil/iiocommand/iiodevicegettrigger.h index 94262922b0..077b905de4 100644 --- a/iioutil/include/iioutil/iiocommand/iiodevicegettrigger.h +++ b/iioutil/include/iioutil/iiocommand/iiodevicegettrigger.h @@ -2,20 +2,23 @@ #define IIODEVICEGETTRIGGER_H #include "../command.h" + #include namespace scopy { -class SCOPY_IIOUTIL_EXPORT IioDeviceGetTrigger : public Command { +class SCOPY_IIOUTIL_EXPORT IioDeviceGetTrigger : public Command +{ Q_OBJECT public: - explicit IioDeviceGetTrigger(struct iio_device *device, - QObject *parent) - : m_device(device) { + explicit IioDeviceGetTrigger(struct iio_device *device, QObject *parent) + : m_device(device) + { this->setParent(parent); m_cmdResult = new CommandResult(); } - virtual void execute() override { + virtual void execute() override + { Q_EMIT started(this); const iio_device *test_dev; ssize_t ret = iio_device_get_trigger(m_device, &test_dev); @@ -23,13 +26,11 @@ class SCOPY_IIOUTIL_EXPORT IioDeviceGetTrigger : public Command { Q_EMIT finished(this); } - iio_device* getResult() { - return static_cast(m_cmdResult->results); - } + iio_device *getResult() { return static_cast(m_cmdResult->results); } private: struct iio_device *m_device; }; -} +} // namespace scopy #endif // IIODEVICEGETTRIGGER_H diff --git a/iioutil/include/iioutil/iiocommand/iiodevicesettrigger.h b/iioutil/include/iioutil/iiocommand/iiodevicesettrigger.h index 09f03d26ba..6e3d8a15b2 100644 --- a/iioutil/include/iioutil/iiocommand/iiodevicesettrigger.h +++ b/iioutil/include/iioutil/iiocommand/iiodevicesettrigger.h @@ -2,22 +2,24 @@ #define IIODEVICESETTRIGGER_H #include "../command.h" + #include namespace scopy { -class SCOPY_IIOUTIL_EXPORT IioDeviceSetTrigger : public Command { +class SCOPY_IIOUTIL_EXPORT IioDeviceSetTrigger : public Command +{ Q_OBJECT public: - explicit IioDeviceSetTrigger(struct iio_device *device, - struct iio_device *trigger_device, - QObject *parent) + explicit IioDeviceSetTrigger(struct iio_device *device, struct iio_device *trigger_device, QObject *parent) : m_device(device) - , m_trigger_device(trigger_device) { + , m_trigger_device(trigger_device) + { this->setParent(parent); m_cmdResult = new CommandResult(); } - virtual void execute() override { + virtual void execute() override + { Q_EMIT started(this); ssize_t ret = iio_device_set_trigger(m_device, m_trigger_device); m_cmdResult->errorCode = ret; @@ -28,6 +30,6 @@ class SCOPY_IIOUTIL_EXPORT IioDeviceSetTrigger : public Command { struct iio_device *m_device; struct iio_device *m_trigger_device; }; -} +} // namespace scopy #endif // IIODEVICESETTRIGGER_H diff --git a/iioutil/include/iioutil/iiocommand/iioregisterread.h b/iioutil/include/iioutil/iiocommand/iioregisterread.h index d6a59e7d2f..73abc05088 100644 --- a/iioutil/include/iioutil/iiocommand/iioregisterread.h +++ b/iioutil/include/iioutil/iiocommand/iioregisterread.h @@ -2,15 +2,15 @@ #define IIOREGISTERREAD_H #include "../command.h" + #include namespace scopy { -class SCOPY_IIOUTIL_EXPORT IioRegisterRead : public Command { +class SCOPY_IIOUTIL_EXPORT IioRegisterRead : public Command +{ Q_OBJECT public: - explicit IioRegisterRead(struct iio_device *device, - uint32_t regAddr, - QObject *parent) + explicit IioRegisterRead(struct iio_device *device, uint32_t regAddr, QObject *parent) : m_device(device) , m_registerAddress(regAddr) { @@ -18,37 +18,34 @@ class SCOPY_IIOUTIL_EXPORT IioRegisterRead : public Command { m_cmdResult = new CommandResult(); } - virtual ~IioRegisterRead() { - if (m_cmdResult->results) { - delete[] (uint32_t*)m_cmdResult->results; + virtual ~IioRegisterRead() + { + if(m_cmdResult->results) { + delete[](uint32_t *) m_cmdResult->results; m_cmdResult->results = nullptr; } } - virtual void execute() override { + virtual void execute() override + { Q_EMIT started(this); - if (!m_cmdResult->results) { - m_cmdResult->results = (uint32_t*)malloc(sizeof(uint32_t)); + if(!m_cmdResult->results) { + m_cmdResult->results = (uint32_t *)malloc(sizeof(uint32_t)); } - ssize_t ret = iio_device_reg_read(m_device, m_registerAddress, (uint32_t*)m_cmdResult->results); + ssize_t ret = iio_device_reg_read(m_device, m_registerAddress, (uint32_t *)m_cmdResult->results); m_cmdResult->errorCode = ret; Q_EMIT finished(this); } - uint32_t getResult() { - return *(uint32_t*)m_cmdResult->results; - } + uint32_t getResult() { return *(uint32_t *)m_cmdResult->results; } - uint32_t getRegisterAddress() { - return m_registerAddress; - } + uint32_t getRegisterAddress() { return m_registerAddress; } private: struct iio_device *m_device; uint32_t m_registerAddress; const ssize_t m_maxAttrSize = 1024; }; -} - +} // namespace scopy #endif diff --git a/iioutil/include/iioutil/iiopingtask.h b/iioutil/include/iioutil/iiopingtask.h index 7a83f3f8e3..200b3f986b 100644 --- a/iioutil/include/iioutil/iiopingtask.h +++ b/iioutil/include/iioutil/iiopingtask.h @@ -1,16 +1,19 @@ #ifndef IIOPINGTASK_H #define IIOPINGTASK_H -#include -#include #include "scopy-iioutil_export.h" +#include + +#include + namespace scopy { /** * @brief The IIOPingTask class * IIOPingTask verifies IIO connection and emits pingSuccess/pingFailed */ -class SCOPY_IIOUTIL_EXPORT IIOPingTask : public QThread { +class SCOPY_IIOUTIL_EXPORT IIOPingTask : public QThread +{ Q_OBJECT public: IIOPingTask(iio_context *c, QObject *parent = nullptr); @@ -22,10 +25,10 @@ class SCOPY_IIOUTIL_EXPORT IIOPingTask : public QThread { Q_SIGNALS: void pingSuccess(); void pingFailed(); + protected: iio_context *c; bool enabled; - }; -} +} // namespace scopy #endif // IIOPINGTASK_H diff --git a/iioutil/include/iioutil/iioscantask.h b/iioutil/include/iioutil/iioscantask.h index f9afb25a4c..4735852223 100644 --- a/iioutil/include/iioutil/iioscantask.h +++ b/iioutil/include/iioutil/iioscantask.h @@ -1,15 +1,17 @@ #ifndef IIOSCANTASK_H #define IIOSCANTASK_H -#include #include "scopy-iioutil_export.h" +#include + namespace scopy { /** * @brief The IIOScanTask class * IIOScanTask - scans for IIO context and emits a scanFinished signal */ -class SCOPY_IIOUTIL_EXPORT IIOScanTask : public QThread { +class SCOPY_IIOUTIL_EXPORT IIOScanTask : public QThread +{ Q_OBJECT public: IIOScanTask(QObject *parent); @@ -26,7 +28,6 @@ class SCOPY_IIOUTIL_EXPORT IIOScanTask : public QThread { protected: QString scanParams = ""; bool enabled; - }; -} +} // namespace scopy #endif // IIOSCANTASK_H diff --git a/iioutil/src/commandqueue.cpp b/iioutil/src/commandqueue.cpp index 1e96f894a8..ee160d334b 100644 --- a/iioutil/src/commandqueue.cpp +++ b/iioutil/src/commandqueue.cpp @@ -1,8 +1,9 @@ #include "commandqueue.h" -#include -#include #include +#include + +#include using namespace std; using namespace scopy; @@ -25,11 +26,10 @@ CommandQueue::~CommandQueue() requestStop(); wait(); - for (auto c : m_commandQueue) { + for(auto c : m_commandQueue) { delete c; } m_commandQueue.clear(); - } void CommandQueue::enqueue(Command *command) @@ -43,16 +43,15 @@ void CommandQueue::enqueue(Command *command) m_commandQueue.push_back(command); } - void CommandQueue::start() { - if (!m_running) { + if(!m_running) { qDebug(CAT_COMMANDQUEUE) << "CommandQueue set running to true (start)"; m_running = true; - if (m_workNewThread) { + if(m_workNewThread) { m_commandExecThreadPool.start(std::bind(&CommandQueue::work, this)); } else { - // trigger work on Main Thread + // trigger work on Main Thread QMetaObject::invokeMethod(this, "work", Qt::QueuedConnection); } } @@ -60,10 +59,10 @@ void CommandQueue::start() void CommandQueue::requestStop() { - if (m_running) { + if(m_running) { qDebug(CAT_COMMANDQUEUE) << "CommandQueue set running to false (stop)"; m_running = false; - if (m_workNewThread) { + if(m_workNewThread) { std::unique_lock lock(m_commandMutex); m_commandQueue.clear(); } @@ -72,33 +71,32 @@ void CommandQueue::requestStop() void CommandQueue::wait() { - if (m_running) { + if(m_running) { qDebug(CAT_COMMANDQUEUE) << "CommandQueue set running to true (wait)"; m_running = false; } - if (m_workNewThread) { + if(m_workNewThread) { m_commandExecThreadPool.waitForDone(); } } void CommandQueue::work() { - while (m_running) { + while(m_running) { std::unique_lock lock(m_commandMutex); - if (m_commandQueue.empty()) { + if(m_commandQueue.empty()) { m_running = false; break; } m_currentCommand = m_commandQueue.front(); - if (m_async) { - QtConcurrent::run(&m_commandExecThreadPool, std::bind([=]() { - m_currentCommand->execute(); - })); + if(m_async) { + QtConcurrent::run(&m_commandExecThreadPool, std::bind([=]() { m_currentCommand->execute(); })); } else { int size = m_commandQueue.size(); lock.unlock(); - qDebug(CAT_COMMANDQUEUE) << "CommandQueue executing " << m_currentCommand << " cmdq size: " << size; + qDebug(CAT_COMMANDQUEUE) + << "CommandQueue executing " << m_currentCommand << " cmdq size: " << size; m_currentCommand->execute(); m_currentCommand->deleteLater(); m_currentCommand = nullptr; @@ -110,20 +108,22 @@ void CommandQueue::work() void CommandQueue::cmdFinished(scopy::Command *cmd) { - if (!cmd) { - cmd = dynamic_cast(QObject::sender()); + if(!cmd) { + cmd = dynamic_cast(QObject::sender()); } - if (cmd) { + if(cmd) { Q_EMIT finished(cmd); } } void CommandQueue::cmdStarted(scopy::Command *cmd) { - if (!cmd) { - cmd = dynamic_cast(QObject::sender()); + if(!cmd) { + cmd = dynamic_cast(QObject::sender()); } - if (cmd) { + if(cmd) { Q_EMIT started(cmd); } } + +#include "moc_commandqueue.cpp" diff --git a/iioutil/src/commandqueueprovider.cpp b/iioutil/src/commandqueueprovider.cpp index c36aac55d7..327663b9b5 100644 --- a/iioutil/src/commandqueueprovider.cpp +++ b/iioutil/src/commandqueueprovider.cpp @@ -1,6 +1,7 @@ #include "commandqueueprovider.h" -#include + #include +#include Q_LOGGING_CATEGORY(CAT_CMDQMGR, "CommandQueueProvider") @@ -14,34 +15,28 @@ CommandQueueRefCounter::CommandQueueRefCounter(struct iio_context *ctx) this->cmdQueue = new CommandQueue(1); } -CommandQueueRefCounter::~CommandQueueRefCounter() { +CommandQueueRefCounter::~CommandQueueRefCounter() +{ if(this->cmdQueue) { delete cmdQueue; cmdQueue = nullptr; } } -CommandQueueProvider* CommandQueueProvider::pinstance_{nullptr}; +CommandQueueProvider *CommandQueueProvider::pinstance_{nullptr}; std::mutex CommandQueueProvider::mutex_; -CommandQueueProvider::CommandQueueProvider(QObject *parent) -{ - qDebug(CAT_CMDQMGR)<<"ctor"; -} +CommandQueueProvider::CommandQueueProvider(QObject *parent) { qDebug(CAT_CMDQMGR) << "ctor"; } -CommandQueueProvider::~CommandQueueProvider() -{ - qDebug(CAT_CMDQMGR)<<"dtor"; -} +CommandQueueProvider::~CommandQueueProvider() { qDebug(CAT_CMDQMGR) << "dtor"; } CommandQueueProvider *scopy::CommandQueueProvider::GetInstance() { std::lock_guard lock(mutex_); - if (pinstance_ == nullptr) - { + if(pinstance_ == nullptr) { pinstance_ = new CommandQueueProvider(QApplication::instance()); } else { - qDebug(CAT_CMDQMGR)<<"got instance from singleton"; + qDebug(CAT_CMDQMGR) << "got instance from singleton"; } return pinstance_; } @@ -54,14 +49,14 @@ CommandQueue *scopy::CommandQueueProvider::open(iio_context *ctx) map.value(ctx)->refcnt++; qDebug(CAT_CMDQMGR) << "opening command queue - found - refcnt++ = "; } else { - CommandQueueRefCounter* cmdQRef = new CommandQueueRefCounter(ctx); + CommandQueueRefCounter *cmdQRef = new CommandQueueRefCounter(ctx); if(cmdQRef->cmdQueue == nullptr) { qWarning(CAT_CMDQMGR) << " not a valid Command Queue"; delete cmdQRef; return nullptr; } map.insert(ctx, cmdQRef); - qDebug(CAT_CMDQMGR)<< " created command queue - refcnt = "<< map.value(ctx)->refcnt; + qDebug(CAT_CMDQMGR) << " created command queue - refcnt = " << map.value(ctx)->refcnt; } cmdQueue = map.value(ctx)->cmdQueue; @@ -73,7 +68,7 @@ void CommandQueueProvider::close(struct iio_context *ctx) std::lock_guard lock(mutex_); if(map.contains(ctx)) { map.value(ctx)->refcnt--; - qDebug(CAT_CMDQMGR)<< " closing command queue - refcnt-- = " << map.value(ctx)->refcnt; + qDebug(CAT_CMDQMGR) << " closing command queue - refcnt-- = " << map.value(ctx)->refcnt; if(map[ctx]->refcnt == 0) { delete map[ctx]; map.remove(ctx); diff --git a/iioutil/src/contextprovider.cpp b/iioutil/src/contextprovider.cpp index 042a5a56b1..ed176273fb 100644 --- a/iioutil/src/contextprovider.cpp +++ b/iioutil/src/contextprovider.cpp @@ -1,8 +1,9 @@ #include "contextprovider.h" -#include -#include + #include +#include #include +#include Q_LOGGING_CATEGORY(CAT_CTXMGR, "ContextProvider") @@ -14,37 +15,34 @@ ContextRefCounter::ContextRefCounter(QString uri) QElapsedTimer t; t.start(); this->ctx = iio_create_context_from_uri(uri.toStdString().c_str()); - qInfo(CAT_CTXMGR) << "Acquiring context "<< uri <<"took "<ctx) { iio_context_destroy(this->ctx); } } - -ContextProvider* ContextProvider::pinstance_{nullptr}; +ContextProvider *ContextProvider::pinstance_{nullptr}; std::mutex ContextProvider::mutex_; -ContextProvider::ContextProvider(QObject *parent) : QObject(parent) +ContextProvider::ContextProvider(QObject *parent) + : QObject(parent) { - qDebug(CAT_CTXMGR)<<"ctor"; + qDebug(CAT_CTXMGR) << "ctor"; } -ContextProvider::~ContextProvider() -{ - qDebug(CAT_CTXMGR)<<"dtor"; -} +ContextProvider::~ContextProvider() { qDebug(CAT_CTXMGR) << "dtor"; } ContextProvider *ContextProvider::GetInstance() { std::lock_guard lock(mutex_); - if (pinstance_ == nullptr) - { + if(pinstance_ == nullptr) { pinstance_ = new ContextProvider(QApplication::instance()); // singleton has the app as parent } else { - qDebug(CAT_CTXMGR)<<"got instance from singleton"; + qDebug(CAT_CTXMGR) << "got instance from singleton"; } return pinstance_; } @@ -55,16 +53,16 @@ iio_context *ContextProvider::open(QString uri) iio_context *ctx = nullptr; if(map.contains(uri)) { map.value(uri)->refcnt++; - qDebug(CAT_CTXMGR)<< uri << "opening - found - refcnt++ = " << map.value(uri)->refcnt; + qDebug(CAT_CTXMGR) << uri << "opening - found - refcnt++ = " << map.value(uri)->refcnt; } else { - ContextRefCounter* ctxref = new ContextRefCounter(uri); - if(ctxref->ctx==nullptr) { + ContextRefCounter *ctxref = new ContextRefCounter(uri); + if(ctxref->ctx == nullptr) { qWarning(CAT_CTXMGR) << uri << "not a valid context"; delete ctxref; return nullptr; } map.insert(uri, ctxref); - qDebug(CAT_CTXMGR)<< uri << "opening - created in map - refcnt = "<< map.value(uri)->refcnt; + qDebug(CAT_CTXMGR) << uri << "opening - created in map - refcnt = " << map.value(uri)->refcnt; } ctx = map.value(uri)->ctx; @@ -76,11 +74,11 @@ void ContextProvider::close(QString uri) std::lock_guard lock(mutex_); if(map.contains(uri)) { map.value(uri)->refcnt--; - qDebug(CAT_CTXMGR)<< uri << "closing - found in map - refcnt-- = " << map.value(uri)->refcnt; + qDebug(CAT_CTXMGR) << uri << "closing - found in map - refcnt-- = " << map.value(uri)->refcnt; if(map[uri]->refcnt == 0) { delete map[uri]; map.remove(uri); - qDebug(CAT_CTXMGR)<< uri << "removed from map"; + qDebug(CAT_CTXMGR) << uri << "removed from map"; } } else { qInfo(CAT_CTXMGR) << uri << "not found in map. nop"; @@ -99,6 +97,4 @@ auto cd = ContextManager::GetInstance(); cd->close("ip:192.168.2.1"); cd->close("ip:192.168.2.1");*/ - - #include "moc_contextprovider.cpp" diff --git a/iioutil/src/cyclicaltask.cpp b/iioutil/src/cyclicaltask.cpp index d255f09fd0..de9c21a387 100644 --- a/iioutil/src/cyclicaltask.cpp +++ b/iioutil/src/cyclicaltask.cpp @@ -1,27 +1,30 @@ #include "cyclicaltask.h" + #include -#include #include +#include Q_LOGGING_CATEGORY(CAT_CYCLICALTASK, "CyclicalTask") using namespace scopy; -CyclicalTask::CyclicalTask(QThread *task, QObject *parent) : QObject(parent) +CyclicalTask::CyclicalTask(QThread *task, QObject *parent) + : QObject(parent) { - qDebug(CAT_CYCLICALTASK)<< "ctor "; + qDebug(CAT_CYCLICALTASK) << "ctor "; t = new QTimer(this); this->task = task; this->task->setParent(this); - connect(t,SIGNAL(timeout()),this,SLOT(startThread())); + connect(t, SIGNAL(timeout()), this, SLOT(startThread())); } -CyclicalTask::~CyclicalTask() { +CyclicalTask::~CyclicalTask() +{ stop(); if(!task->isFinished()) { - qDebug(CAT_CYCLICALTASK)<< "Waiting to finish thread - max 30 seconds"; + qDebug(CAT_CYCLICALTASK) << "Waiting to finish thread - max 30 seconds"; task->wait(THREAD_FINISH_TIMEOUT); } - qDebug(CAT_CYCLICALTASK)<< "dtor "; + qDebug(CAT_CYCLICALTASK) << "dtor "; } void CyclicalTask::start(int period) @@ -31,21 +34,20 @@ void CyclicalTask::start(int period) t->start(period); enabled = true; } - } -void CyclicalTask::startThread() { - qDebug(CAT_CYCLICALTASK)<<"Attempting to start thread"; +void CyclicalTask::startThread() +{ + qDebug(CAT_CYCLICALTASK) << "Attempting to start thread"; if(task->isFinished()) { task->start(); } } - void CyclicalTask::stop() { if(enabled) { - qDebug(CAT_CYCLICALTASK)<<"Stopping scanner thread"; + qDebug(CAT_CYCLICALTASK) << "Stopping scanner thread"; task->requestInterruption(); t->stop(); enabled = false; diff --git a/iioutil/src/iiopingtask.cpp b/iioutil/src/iiopingtask.cpp index 2f8a509cc6..c70c8b90d5 100644 --- a/iioutil/src/iiopingtask.cpp +++ b/iioutil/src/iiopingtask.cpp @@ -1,12 +1,17 @@ #include "iiopingtask.h" + #include using namespace scopy; -IIOPingTask::IIOPingTask(iio_context *c ,QObject *parent) : QThread(parent), c(c) {} +IIOPingTask::IIOPingTask(iio_context *c, QObject *parent) + : QThread(parent) + , c(c) +{} IIOPingTask::~IIOPingTask() {} -void IIOPingTask::run() { +void IIOPingTask::run() +{ enabled = true; bool ret = ping(c); @@ -19,13 +24,14 @@ void IIOPingTask::run() { Q_EMIT pingFailed(); } -bool IIOPingTask::ping(iio_context *ctx) { +bool IIOPingTask::ping(iio_context *ctx) +{ auto dev = iio_context_get_device(ctx, 0); - const iio_device* test_device = nullptr; + const iio_device *test_device = nullptr; int ret = iio_device_get_trigger(dev, &test_device); - if (ret < 0 && ret != -ENOENT) { + if(ret < 0 && ret != -ENOENT) { return false; } return true; diff --git a/iioutil/src/iioscantask.cpp b/iioutil/src/iioscantask.cpp index 7f6e3fa757..a111f2f50f 100644 --- a/iioutil/src/iioscantask.cpp +++ b/iioutil/src/iioscantask.cpp @@ -1,32 +1,36 @@ #include "iioscantask.h" + #include -#include + #include +#include + #include using namespace scopy; -IIOScanTask::IIOScanTask(QObject *parent) : QThread(parent) {} +IIOScanTask::IIOScanTask(QObject *parent) + : QThread(parent) +{} IIOScanTask::~IIOScanTask() {} - Q_LOGGING_CATEGORY(CAT_IIOSCANCTX, "IIOScanTask"); -void IIOScanTask::run() { +void IIOScanTask::run() +{ QStringList ctxs; - int ret = IIOScanTask::scan(&ctxs,scanParams); + int ret = IIOScanTask::scan(&ctxs, scanParams); if(isInterruptionRequested()) return; - if( ret >= 0 ) + if(ret >= 0) Q_EMIT scanFinished(ctxs); } -void IIOScanTask::setScanParams(QString s) { - scanParams = s; -} +void IIOScanTask::setScanParams(QString s) { scanParams = s; } -int IIOScanTask::scan(QStringList *ctxs, QString scanParams) { - qDebug(CAT_IIOSCANCTX)<< "start scanning"; +int IIOScanTask::scan(QStringList *ctxs, QString scanParams) +{ + qDebug(CAT_IIOSCANCTX) << "start scanning"; struct iio_scan_context *scan_ctx = NULL; struct iio_context_info **info; int num_contexts; @@ -41,24 +45,25 @@ int IIOScanTask::scan(QStringList *ctxs, QString scanParams) { scan_ctx = iio_create_scan_context(scanParams.toStdString().c_str(), 0); } - if (!scan_ctx) { - qWarning(CAT_IIOSCANCTX)<< "no scan context - " << errno << " " <append(QString(iio_context_info_get_uri(info[i]))); } iio_context_info_list_free(info); - qDebug(CAT_IIOSCANCTX)<<"scanned "<<*ctxs; + qDebug(CAT_IIOSCANCTX) << "scanned " << *ctxs; scan_err: iio_scan_context_destroy(scan_ctx); @@ -68,11 +73,11 @@ int IIOScanTask::scan(QStringList *ctxs, QString scanParams) { QVector IIOScanTask::getSerialPortsName() { QVector serialPortsName; - struct sp_port** serialPorts; + struct sp_port **serialPorts; int retCode = sp_list_ports(&serialPorts); - if (retCode == SP_OK) { - for (int i = 0; serialPorts[i]; i++) { - serialPortsName.push_back(QString(sp_get_port_name(serialPorts[i]))); + if(retCode == SP_OK) { + for(int i = 0; serialPorts[i]; i++) { + serialPortsName.push_back(QString(sp_get_port_name(serialPorts[i]))); } sp_free_port_list(serialPorts); } diff --git a/iioutil/test/CMakeLists.txt b/iioutil/test/CMakeLists.txt index 950c8d1597..dada5cfc27 100644 --- a/iioutil/test/CMakeLists.txt +++ b/iioutil/test/CMakeLists.txt @@ -2,7 +2,4 @@ cmake_minimum_required(VERSION 3.5) include(ScopyTest) -SETUP_SCOPY_TESTS( - iiocommandqueue -) - +setup_scopy_tests(iiocommandqueue) diff --git a/iioutil/test/tst_iiocommandqueue.cpp b/iioutil/test/tst_iiocommandqueue.cpp index 671ff768b7..fa15e7ce7b 100644 --- a/iioutil/test/tst_iiocommandqueue.cpp +++ b/iioutil/test/tst_iiocommandqueue.cpp @@ -1,19 +1,19 @@ -#include -#include +#include "iioutil/command.h" +#include "iioutil/commandqueue.h" + #include #include #include +#include +#include #include -#include "iioutil/command.h" -#include "iioutil/commandqueue.h" - using namespace scopy; -Q_DECLARE_METATYPE(QSignalSpy*); -Q_DECLARE_METATYPE(CommandQueue*); +Q_DECLARE_METATYPE(QSignalSpy *); +Q_DECLARE_METATYPE(CommandQueue *); - -class TestCommandCounter : public Command { +class TestCommandCounter : public Command +{ Q_OBJECT public: explicit TestCommandCounter(QObject *parent) @@ -22,20 +22,17 @@ class TestCommandCounter : public Command { m_cmdResult = new CommandResult(); } - virtual ~TestCommandCounter() { - qDebug() << "TestCommandCounter deleted"; - } + virtual ~TestCommandCounter() { qDebug() << "TestCommandCounter deleted"; } - virtual void execute() override { - m_commandCounter++; - } + virtual void execute() override { m_commandCounter++; } public: static std::atomic m_commandCounter; }; std::atomic TestCommandCounter::m_commandCounter = 0; -class TestCommandAdd : public Command { +class TestCommandAdd : public Command +{ Q_OBJECT public: explicit TestCommandAdd(int a, int b, QObject *parent) @@ -46,11 +43,10 @@ class TestCommandAdd : public Command { m_cmdResult = new CommandResult(); } - virtual ~TestCommandAdd() { - qDebug() << "TestCommand deleted"; - } + virtual ~TestCommandAdd() { qDebug() << "TestCommand deleted"; } - virtual void execute() override { + virtual void execute() override + { Q_EMIT started(this); m_cmdResult->errorCode = m_a + m_b; Q_EMIT finished(this); @@ -60,10 +56,11 @@ class TestCommandAdd : public Command { int m_a, m_b; }; -class TestCommandMultiply : public Command { +class TestCommandMultiply : public Command +{ Q_OBJECT public: - explicit TestCommandMultiply(int a, int b, QObject *parent) + explicit TestCommandMultiply(int a, int b, QObject *parent) : m_a(a) , m_b(b) { @@ -71,56 +68,55 @@ class TestCommandMultiply : public Command { m_cmdResult = new CommandResult(); } - virtual ~TestCommandMultiply() { - qDebug() << "TestCommandMultiply deleted"; - } + virtual ~TestCommandMultiply() { qDebug() << "TestCommandMultiply deleted"; } - virtual void execute() override { + virtual void execute() override + { Q_EMIT started(this); m_cmdResult->errorCode = m_a * m_b; - const char* tmp = "TEST OK"; - m_cmdResult->results = (char*)tmp; + const char *tmp = "TEST OK"; + m_cmdResult->results = (char *)tmp; Q_EMIT finished(this); } - std::string getResult() - { - return std::string((char*)m_cmdResult->results); - } + std::string getResult() { return std::string((char *)m_cmdResult->results); } + private: int m_a, m_b; std::string m_msg; }; -class TestCommandMsg : public Command { +class TestCommandMsg : public Command +{ Q_OBJECT public: explicit TestCommandMsg(int sleep, QString message, QObject *parent) : m_sleep(sleep) - , m_msg_btn(new QPushButton(message)) { + , m_msg_btn(new QPushButton(message)) + { this->setParent(parent); m_cmdResult = new CommandResult(); } - virtual ~TestCommandMsg() { + virtual ~TestCommandMsg() + { qDebug() << "TestCommandMsg deleted"; - if (m_cmdResult->results) { - delete (QPushButton*)m_cmdResult->results; + if(m_cmdResult->results) { + delete(QPushButton *)m_cmdResult->results; m_cmdResult->results = nullptr; } } - virtual void execute() override { + virtual void execute() override + { Q_EMIT started(this); QThread::msleep(m_sleep); m_cmdResult->errorCode = m_sleep; - m_cmdResult->results = (void*)m_msg_btn; + m_cmdResult->results = (void *)m_msg_btn; Q_EMIT finished(this); } - QPushButton* getResult() { - return static_cast(m_cmdResult->results); - } + QPushButton *getResult() { return static_cast(m_cmdResult->results); } private: int m_sleep; @@ -133,56 +129,63 @@ class TST_IioCommandQueue : public QObject private Q_SLOTS: void testResults(); void testCommandOrder(); -// void testLaunchCommandFromThread(); + // void testLaunchCommandFromThread(); private: int TEST_A = 100; int TEST_B = 20; QThreadPool m_commandExecThreadPool; }; -void TST_IioCommandQueue::testResults() { +void TST_IioCommandQueue::testResults() +{ CommandQueue *cmdQ = new CommandQueue(1, nullptr); Command *cmd1 = new TestCommandAdd(TEST_A, TEST_B, nullptr); Command *cmd2 = new TestCommandMultiply(TEST_A, TEST_B, nullptr); Command *cmd3 = new TestCommandMsg(TEST_A, "Test command 300", nullptr); - connect(cmd1, &scopy::Command::finished, - this, [=](scopy::Command* cmd) { - if (!cmd) { - cmd = dynamic_cast(QObject::sender()); - } - TestCommandAdd *tcmd = dynamic_cast(cmd); - QVERIFY2(tcmd != nullptr, "Capture command is null"); - QVERIFY2(tcmd == cmd1, "Captured command not the expected one"); - QVERIFY2(tcmd->getReturnCode() == (TEST_B + TEST_A), "TestCommandAdd did not execute"); - }, Qt::QueuedConnection); - - connect(cmd2, &scopy::Command::finished, - this, [=](scopy::Command* cmd) { - if (!cmd) { - cmd = dynamic_cast(QObject::sender()); - } - TestCommandMultiply *tcmd = dynamic_cast(cmd); - QVERIFY2(tcmd != nullptr, "Capture command is null"); - QVERIFY2(tcmd == cmd2, "Captured command not the expected one"); - QVERIFY2(tcmd->getResult() == "TEST OK", "TestCommandMultiply not executed properly"); - QVERIFY2(tcmd->getReturnCode() == (TEST_B * TEST_A), "TestCommandMultiply did not execute"); - }, Qt::QueuedConnection); - - connect(cmd3, &scopy::Command::finished, - this, [=](scopy::Command* cmd) { - if (!cmd) { - cmd = dynamic_cast(QObject::sender()); - } - TestCommandMsg *tcmd = dynamic_cast(cmd); - QVERIFY2(tcmd != nullptr, "Capture command is null"); - QVERIFY2(tcmd == cmd3, "Captured command not the expected one"); - QVERIFY2(tcmd->getReturnCode() == TEST_A, "TestCommandMsg did not execute"); - QPushButton *testBtn = tcmd->getResult(); - QVERIFY2(testBtn != nullptr, "TestCommandMsg did not generate results"); - qDebug() << "TestBtn text: " << testBtn->text(); - QVERIFY2(testBtn->text() == "Test command 300", "TestCommandMsg generated wrong results"); - }, Qt::QueuedConnection); + connect( + cmd1, &scopy::Command::finished, this, + [=](scopy::Command *cmd) { + if(!cmd) { + cmd = dynamic_cast(QObject::sender()); + } + TestCommandAdd *tcmd = dynamic_cast(cmd); + QVERIFY2(tcmd != nullptr, "Capture command is null"); + QVERIFY2(tcmd == cmd1, "Captured command not the expected one"); + QVERIFY2(tcmd->getReturnCode() == (TEST_B + TEST_A), "TestCommandAdd did not execute"); + }, + Qt::QueuedConnection); + + connect( + cmd2, &scopy::Command::finished, this, + [=](scopy::Command *cmd) { + if(!cmd) { + cmd = dynamic_cast(QObject::sender()); + } + TestCommandMultiply *tcmd = dynamic_cast(cmd); + QVERIFY2(tcmd != nullptr, "Capture command is null"); + QVERIFY2(tcmd == cmd2, "Captured command not the expected one"); + QVERIFY2(tcmd->getResult() == "TEST OK", "TestCommandMultiply not executed properly"); + QVERIFY2(tcmd->getReturnCode() == (TEST_B * TEST_A), "TestCommandMultiply did not execute"); + }, + Qt::QueuedConnection); + + connect( + cmd3, &scopy::Command::finished, this, + [=](scopy::Command *cmd) { + if(!cmd) { + cmd = dynamic_cast(QObject::sender()); + } + TestCommandMsg *tcmd = dynamic_cast(cmd); + QVERIFY2(tcmd != nullptr, "Capture command is null"); + QVERIFY2(tcmd == cmd3, "Captured command not the expected one"); + QVERIFY2(tcmd->getReturnCode() == TEST_A, "TestCommandMsg did not execute"); + QPushButton *testBtn = tcmd->getResult(); + QVERIFY2(testBtn != nullptr, "TestCommandMsg did not generate results"); + qDebug() << "TestBtn text: " << testBtn->text(); + QVERIFY2(testBtn->text() == "Test command 300", "TestCommandMsg generated wrong results"); + }, + Qt::QueuedConnection); cmdQ->enqueue(cmd1); cmdQ->enqueue(cmd2); @@ -191,51 +194,60 @@ void TST_IioCommandQueue::testResults() { delete cmdQ; } -void TST_IioCommandQueue::testCommandOrder() { +void TST_IioCommandQueue::testCommandOrder() +{ CommandQueue *cmdQ = new CommandQueue(1, nullptr); Command *cmd1 = new TestCommandAdd(TEST_A, TEST_B, nullptr); Command *cmd3 = new TestCommandMsg(TEST_A, "Test command 300", nullptr); - connect(cmd1, &scopy::Command::finished, - this, [=](scopy::Command* cmd) { - if (!cmd) { - cmd = dynamic_cast(QObject::sender()); - } - TestCommandAdd *tcmd = dynamic_cast(cmd); - QVERIFY2(tcmd != nullptr, "Capture command is null"); - QVERIFY2(tcmd == cmd1, "Captured command not the expected one"); - QVERIFY2(tcmd->getReturnCode() == (TEST_B + TEST_A), "TestCommandAdd did not execute"); - - Command *cmd2 = new TestCommandMultiply(tcmd->getReturnCode(), TEST_B, nullptr); - cmdQ->enqueue(cmd2); - connect(cmd2, &scopy::Command::finished, - this, [=](scopy::Command* cmd) { - if (!cmd) { - cmd = dynamic_cast(QObject::sender()); + connect( + cmd1, &scopy::Command::finished, this, + [=](scopy::Command *cmd) { + if(!cmd) { + cmd = dynamic_cast(QObject::sender()); } - TestCommandMultiply *tcmd = dynamic_cast(cmd); + TestCommandAdd *tcmd = dynamic_cast(cmd); QVERIFY2(tcmd != nullptr, "Capture command is null"); - QVERIFY2(tcmd == cmd2, "Captured command not the expected one"); - QVERIFY2(tcmd->getResult() == "TEST OK", "TestCommandMultiply not executed properly"); - QVERIFY2(tcmd->getReturnCode() == (TEST_B * (TEST_B + TEST_A)), "TestCommandMultiply did not execute"); - }, Qt::QueuedConnection); - }, Qt::QueuedConnection); - - connect(cmd3, &scopy::Command::finished, - this, [=](scopy::Command* cmd) { - if (!cmd) { - cmd = dynamic_cast(QObject::sender()); - } - TestCommandMsg *tcmd = dynamic_cast(cmd); - QVERIFY2(tcmd != nullptr, "Capture command is null"); - QVERIFY2(tcmd == cmd3, "Captured command not the expected one"); - QVERIFY2(tcmd->getReturnCode() == TEST_A, "TestCommandMsg did not execute"); - QPushButton *testBtn = tcmd->getResult(); - QVERIFY2(testBtn != nullptr, "TestCommandMsg did not generate results"); - qDebug() << "TestBtn text: " << testBtn->text(); - QVERIFY2(testBtn->text() == "Test command 300", "TestCommandMsg generated wrong results"); - }, Qt::QueuedConnection); + QVERIFY2(tcmd == cmd1, "Captured command not the expected one"); + QVERIFY2(tcmd->getReturnCode() == (TEST_B + TEST_A), "TestCommandAdd did not execute"); + + Command *cmd2 = new TestCommandMultiply(tcmd->getReturnCode(), TEST_B, nullptr); + cmdQ->enqueue(cmd2); + connect( + cmd2, &scopy::Command::finished, this, + [=](scopy::Command *cmd) { + if(!cmd) { + cmd = dynamic_cast(QObject::sender()); + } + TestCommandMultiply *tcmd = dynamic_cast(cmd); + QVERIFY2(tcmd != nullptr, "Capture command is null"); + QVERIFY2(tcmd == cmd2, "Captured command not the expected one"); + QVERIFY2(tcmd->getResult() == "TEST OK", + "TestCommandMultiply not executed properly"); + QVERIFY2(tcmd->getReturnCode() == (TEST_B * (TEST_B + TEST_A)), + "TestCommandMultiply did not execute"); + }, + Qt::QueuedConnection); + }, + Qt::QueuedConnection); + + connect( + cmd3, &scopy::Command::finished, this, + [=](scopy::Command *cmd) { + if(!cmd) { + cmd = dynamic_cast(QObject::sender()); + } + TestCommandMsg *tcmd = dynamic_cast(cmd); + QVERIFY2(tcmd != nullptr, "Capture command is null"); + QVERIFY2(tcmd == cmd3, "Captured command not the expected one"); + QVERIFY2(tcmd->getReturnCode() == TEST_A, "TestCommandMsg did not execute"); + QPushButton *testBtn = tcmd->getResult(); + QVERIFY2(testBtn != nullptr, "TestCommandMsg did not generate results"); + qDebug() << "TestBtn text: " << testBtn->text(); + QVERIFY2(testBtn->text() == "Test command 300", "TestCommandMsg generated wrong results"); + }, + Qt::QueuedConnection); cmdQ->enqueue(cmd1); cmdQ->enqueue(cmd3); @@ -249,7 +261,7 @@ void TST_IioCommandQueue::testCommandOrder() { * the CommandQueue should ensure that the commands are executed in order, * one at a time, all on just one running thread. */ -//void TST_IioCommandQueue::testLaunchCommandFromThread() { +// void TST_IioCommandQueue::testLaunchCommandFromThread() { // CommandQueue *cmdQ = new CommandQueue(1, nullptr); // int m_nbOfThreads = 5; // m_commandExecThreadPool.setMaxThreadCount(m_nbOfThreads); @@ -266,12 +278,9 @@ void TST_IioCommandQueue::testCommandOrder() { // qInfo() << "Command counter: " << TestCommandCounter::m_commandCounter; // qInfo() << "Thread pool expiry timeout: " << m_commandExecThreadPool.expiryTimeout(); -// QVERIFY2(TestCommandCounter::m_commandCounter == m_nbOfThreads * 2, "The threaded cmds were not executed in order/properly."); -// delete cmdQ; +// QVERIFY2(TestCommandCounter::m_commandCounter == m_nbOfThreads * 2, "The threaded cmds were not executed in +// order/properly."); delete cmdQ; //} - QTEST_MAIN(TST_IioCommandQueue) #include "tst_iiocommandqueue.moc" - - diff --git a/main.cpp b/main.cpp index 3759a454fa..2c6a6110f2 100644 --- a/main.cpp +++ b/main.cpp @@ -1,7 +1,9 @@ -#include "core/scopymainwindow.h" #include "core/logging_categories.h" +#include "core/scopymainwindow.h" + #include #include + #include #include #include @@ -14,34 +16,31 @@ Q_LOGGING_CATEGORY(CAT_RUNTIME_ENVIRONMENT_INFO, "RuntimeEnvironmentInfo") void SetScopyQDebugMessagePattern() { - qSetMessagePattern( - "[ " - #ifdef QDEBUG_LOG_MSG_TYPE - QDEBUG_LOG_MSG_TYPE_STR " " - QDEBUG_CATEGORY_STR " " - #endif - #ifdef QDEBUG_LOG_TIME - QDEBUG_LOG_TIME_STR - #endif - #ifdef QDEBUG_LOG_DATE - QDEBUG_LOG_DATE_STR - #endif - #ifdef QDEBUG_LOG_CATEGORY - QDEBUG_CATEGORY_STR - #endif - " ] " - #ifdef QDEBUG_LOG_FILE - QDEBUG_LOG_FILE_STR - #endif - - " - " - "%{message}" - ); + qSetMessagePattern("[ " +#ifdef QDEBUG_LOG_MSG_TYPE + QDEBUG_LOG_MSG_TYPE_STR " " QDEBUG_CATEGORY_STR " " +#endif +#ifdef QDEBUG_LOG_TIME + QDEBUG_LOG_TIME_STR +#endif +#ifdef QDEBUG_LOG_DATE + QDEBUG_LOG_DATE_STR +#endif +#ifdef QDEBUG_LOG_CATEGORY + QDEBUG_CATEGORY_STR +#endif + " ] " +#ifdef QDEBUG_LOG_FILE + QDEBUG_LOG_FILE_STR +#endif + + " - " + "%{message}"); } void initLogging() { - if (!getenv("QT_LOGGING_RULES")) { + if(!getenv("QT_LOGGING_RULES")) { QLoggingCategory::setFilterRules("" "*.debug=false\n" "ToolStack.debug=true\n" @@ -56,7 +55,7 @@ void initLogging() "AD74413R.debug=true\n" "ScopyTranslations.debug=true\n"); } - if (!getenv("QT_MESSAGE_PATTERN")) { + if(!getenv("QT_MESSAGE_PATTERN")) { SetScopyQDebugMessagePattern(); } } @@ -64,7 +63,7 @@ void initLogging() void printRuntimeEnvironmentInfo() { QStringList infoList = scopy::config::dump().split("\n"); - for (const QString &info : infoList) { + for(const QString &info : infoList) { qInfo(CAT_RUNTIME_ENVIRONMENT_INFO) << info; } } @@ -77,7 +76,7 @@ int main(int argc, char *argv[]) QCoreApplication::setApplicationName("Scopy-v2"); QSettings::setDefaultFormat(QSettings::IniFormat); - QApplication::setAttribute(Qt::AA_ShareOpenGLContexts,true); + QApplication::setAttribute(Qt::AA_ShareOpenGLContexts, true); QGuiApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); QApplication a(argc, argv); @@ -85,12 +84,12 @@ int main(int argc, char *argv[]) parser.addHelpOption(); parser.addVersionOption(); parser.addOptions({ - { {"s", "script"}, "Run given script.", "script" }, - { {"a", "accept-license"}, "Accept the license in advance." }, - { {"l", "logfile"}, "Saves all the logging messages into a file.", "filename"}, - { {"c", "connect"}, "Establish the connection to a given device by URI.","URI"}, - { {"t", "tool"}, "Select the desired tool for the device.", "tool"} , - }); + {{"s", "script"}, "Run given script.", "script"}, + {{"a", "accept-license"}, "Accept the license in advance."}, + {{"l", "logfile"}, "Saves all the logging messages into a file.", "filename"}, + {{"c", "connect"}, "Establish the connection to a given device by URI.", "URI"}, + {{"t", "tool"}, "Select the desired tool for the device.", "tool"}, + }); parser.process(a); CmdLineHandler::withLogFileOption(parser); @@ -105,7 +104,7 @@ int main(int argc, char *argv[]) ScopyMainWindow_API scopyApi(&w); int retHandler = CmdLineHandler::handle(parser, scopyApi); - if (retHandler == EXIT_FAILURE) { + if(retHandler == EXIT_FAILURE) { return retHandler; } diff --git a/pluginbase/CMakeLists.txt b/pluginbase/CMakeLists.txt index 4791e3e7a4..29b6d83b54 100644 --- a/pluginbase/CMakeLists.txt +++ b/pluginbase/CMakeLists.txt @@ -5,8 +5,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -22,52 +21,55 @@ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) set(CMAKE_CXX_VISIBILITY_PRESET hidden) set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) -FILE(GLOB SRC_LIST src/*.cpp src/*.cc) -FILE(GLOB HEADER_LIST src/*.hpp src/*.h include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) -FILE(GLOB UI_LIST ui/*.ui) +file(GLOB SRC_LIST src/*.cpp src/*.cc) +file( + GLOB + HEADER_LIST + src/*.hpp + src/*.h + include/${SCOPY_MODULE}/*.h + include/${SCOPY_MODULE}/*.hpp +) +file(GLOB UI_LIST ui/*.ui) if(ENABLE_TESTING) - add_subdirectory(test) + add_subdirectory(test) endif() set(SCOPY_QT_COMPONENTS Core Widgets Concurrent) option(ENABLE_SCOPYJS "Enable plugin scripting via JSEngine - requires QML" ON) if(ENABLE_SCOPYJS) - set(SCOPY_QT_COMPONENTS ${SCOPY_QT_COMPONENTS} Qml) - message(STATUS "PLUGINBASE: scopy-js enabled") + set(SCOPY_QT_COMPONENTS ${SCOPY_QT_COMPONENTS} Qml) + message(STATUS "PLUGINBASE: scopy-js enabled") endif() -configure_file(include/${SCOPY_MODULE}/scopy-${SCOPY_MODULE}_config.h.cmakein - ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/scopy-${SCOPY_MODULE}_config.h @ONLY) +configure_file( + include/${SCOPY_MODULE}/scopy-${SCOPY_MODULE}_config.h.cmakein + ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/scopy-${SCOPY_MODULE}_config.h @ONLY +) set(SRC_LIST ${SRC_LIST} ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/scopy-${SCOPY_MODULE}_config.h) -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} -) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS ${SCOPY_QT_COMPONENTS} REQUIRED) -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) -target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE} scopy-common) +target_include_directories( + ${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE} + scopy-common +) foreach(comp ${SCOPY_QT_COMPONENTS}) - set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) + set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) endforeach() -target_link_libraries(${PROJECT_NAME} PUBLIC - ${SCOPY_QT_LIBRARIES} - ${IIO_LIBRARIES} - scopy-common) +target_link_libraries(${PROJECT_NAME} PUBLIC ${SCOPY_QT_LIBRARIES} ${IIO_LIBRARIES} scopy-common) -install(TARGETS ${PROJECT_NAME} - LIBRARY DESTINATION ${SCOPY_DLL_PATH} - RUNTIME DESTINATION ${SCOPY_DLL_PATH}) +install(TARGETS ${PROJECT_NAME} LIBRARY DESTINATION ${SCOPY_DLL_PATH} RUNTIME DESTINATION ${SCOPY_DLL_PATH}) diff --git a/pluginbase/include/pluginbase/apiobject.h b/pluginbase/include/pluginbase/apiobject.h index b0243ade3f..f539927146 100644 --- a/pluginbase/include/pluginbase/apiobject.h +++ b/pluginbase/include/pluginbase/apiobject.h @@ -21,43 +21,43 @@ #ifndef APIOBJECT_HPP #define APIOBJECT_HPP -#include #include "scopy-pluginbase_export.h" +#include + class QJSEngine; class QSettings; -template class QList; +template +class QList; namespace scopy { - class SCOPY_PLUGINBASE_EXPORT ApiObject : public QObject - { - Q_OBJECT +class SCOPY_PLUGINBASE_EXPORT ApiObject : public QObject +{ + Q_OBJECT - Q_SIGNALS: - void loadingFinished(); +Q_SIGNALS: + void loadingFinished(); - public: - ApiObject(QObject *parent = nullptr); - ~ApiObject(); +public: + ApiObject(QObject *parent = nullptr); + ~ApiObject(); - virtual void load(QSettings& settings); - virtual void save(QSettings& settings); + virtual void load(QSettings &settings); + virtual void save(QSettings &settings); - private: - template void save(QSettings& settings, - const QString& prop, const QList& list); - template QList load(QSettings& settings, - const QString& prop); +private: + template + void save(QSettings &settings, const QString &prop, const QList &list); + template + QList load(QSettings &settings, const QString &prop); - void save(QSettings& settings, const QString& prop, - const QVariantList& list); - void load(QSettings& settings, const QString& prop, - const QVariantList& list); + void save(QSettings &settings, const QString &prop, const QVariantList &list); + void load(QSettings &settings, const QString &prop, const QVariantList &list); - void save_nogroup(ApiObject *, QSettings&); - void load_nogroup(ApiObject *, QSettings&); - }; -} + void save_nogroup(ApiObject *, QSettings &); + void load_nogroup(ApiObject *, QSettings &); +}; +} // namespace scopy Q_DECLARE_METATYPE(scopy::ApiObject *) diff --git a/pluginbase/include/pluginbase/messagebroker.h b/pluginbase/include/pluginbase/messagebroker.h index 377f48eb82..50a518389a 100644 --- a/pluginbase/include/pluginbase/messagebroker.h +++ b/pluginbase/include/pluginbase/messagebroker.h @@ -1,9 +1,10 @@ #ifndef MESSAGEBROKER_H #define MESSAGEBROKER_H -#include #include "scopy-pluginbase_export.h" + #include +#include #include namespace scopy { @@ -51,10 +52,9 @@ class SCOPY_PLUGINBASE_EXPORT MessageBroker : public QObject void publish(QString topic, QString message); private: - QMap> map; - static MessageBroker * pinstance_; - + QMap> map; + static MessageBroker *pinstance_; }; -} +} // namespace scopy #endif // MESSAGEBROKER_H diff --git a/pluginbase/include/pluginbase/plugin.h b/pluginbase/include/pluginbase/plugin.h index 567b31134a..2100504f76 100644 --- a/pluginbase/include/pluginbase/plugin.h +++ b/pluginbase/include/pluginbase/plugin.h @@ -1,14 +1,15 @@ #ifndef PLUGIN_H #define PLUGIN_H +#include "apiobject.h" +#include "scopy-pluginbase_export.h" +#include "toolmenuentry.h" + +#include +#include #include #include -#include "toolmenuentry.h" -#include "scopy-pluginbase_export.h" #include -#include -#include -#include "apiobject.h" namespace scopy { @@ -21,7 +22,8 @@ namespace scopy { * onConnect() * onDisconnect() */ -class SCOPY_PLUGINBASE_EXPORT Plugin { +class SCOPY_PLUGINBASE_EXPORT Plugin +{ public: virtual ~Plugin() {} @@ -43,7 +45,6 @@ class SCOPY_PLUGINBASE_EXPORT Plugin { virtual void setEnabled(bool) = 0; - /** * @brief initMetadata * initializes plugin metadata. initialize m_metadata @@ -110,7 +111,6 @@ class SCOPY_PLUGINBASE_EXPORT Plugin { */ virtual bool loadPreferencesPage() = 0; - /** * @brief compatible * @param param @@ -133,7 +133,7 @@ class SCOPY_PLUGINBASE_EXPORT Plugin { * @return * Default implementation in SCOPY_PLUGIN macro - override not recomended */ - virtual Plugin* clone(QObject *parent = nullptr) = 0; + virtual Plugin *clone(QObject *parent = nullptr) = 0; /** * @brief cloneExtra @@ -141,7 +141,7 @@ class SCOPY_PLUGINBASE_EXPORT Plugin { * which is not part of the boilerplate implementation * Default implementation in PluginBase - can be overriden */ - virtual void cloneExtra(Plugin*) = 0; + virtual void cloneExtra(Plugin *) = 0; /** * @brief preload @@ -209,7 +209,6 @@ class SCOPY_PLUGINBASE_EXPORT Plugin { */ virtual void unload() = 0; - /** * @brief param * @return plugin m_enabled getter - shows whether the plugin will load or not on loadPlugin() @@ -257,35 +256,35 @@ class SCOPY_PLUGINBASE_EXPORT Plugin { * @return plugin m_icon getter - icon widget * Default implementation in PluginBase - override not recommended */ - virtual QWidget* icon() = 0; + virtual QWidget *icon() = 0; /** * @brief page * @return plugin m_page getter - plugin infopage widget. used to create device infopage * Default implementation in PluginBase - override not recommended */ - virtual QWidget* page() = 0; + virtual QWidget *page() = 0; /** * @brief preferencesPage * @return plugin m_preferencesPage getter - preferences widget * Default implementation in PluginBase - override not recommended */ - virtual QWidget* preferencesPage() = 0; + virtual QWidget *preferencesPage() = 0; /** * @brief extraButtons * @return plugin m_extraButtons getter - list of buttons used to create device infopage * Default implementation in PluginBase - override not recommended */ - virtual QList extraButtons() = 0; + virtual QList extraButtons() = 0; /** * @brief toolList * @return plugin m_toolList getter - list of tools used to populate device toolmenu * Default implementation in PluginBase - override not recommended */ - virtual QList toolList() = 0; + virtual QList toolList() = 0; /** * @brief metadata @@ -318,17 +317,15 @@ public Q_SLOTS: /** * @brief showPageCallback - * is called postcompatible. when the Device infopage comes in foreground (by selecting the device in the DeviceBrowser) - * useful for interactive infopages - * Default implementation in PluginBase - can be overriden + * is called postcompatible. when the Device infopage comes in foreground (by selecting the device in the + * DeviceBrowser) useful for interactive infopages Default implementation in PluginBase - can be overriden */ virtual void showPageCallback() = 0; /** * @brief hidePageCallback - * is called postcompatible when the device infopage goes in the background (by selecting another device in the DeviceBrowser) - * useful for interactive infopages - * Default implementation in PluginBase - can be overriden + * is called postcompatible when the device infopage goes in the background (by selecting another device in the + * DeviceBrowser) useful for interactive infopages Default implementation in PluginBase - can be overriden */ virtual void hidePageCallback() = 0; @@ -340,7 +337,7 @@ public Q_SLOTS: * Default implementation in PluginBase - can be overriden */ virtual void messageCallback(QString topic, QString message) = 0; -//Q_SIGNALS: + // Q_SIGNALS: /** * @brief connectDevice @@ -371,10 +368,8 @@ public Q_SLOTS: */ virtual void toolListChanged() = 0; virtual void restartDevice() = 0; - - }; -} +} // namespace scopy #define ScopyPlugin_iid "org.adi.Scopy.Plugins.Pluginbase/0.1" Q_DECLARE_INTERFACE(scopy::Plugin, ScopyPlugin_iid) diff --git a/pluginbase/include/pluginbase/pluginbase.h b/pluginbase/include/pluginbase/pluginbase.h index 59b78c9b63..9bbe4502c0 100644 --- a/pluginbase/include/pluginbase/pluginbase.h +++ b/pluginbase/include/pluginbase/pluginbase.h @@ -1,17 +1,18 @@ #ifndef PLUGINBASE_H #define PLUGINBASE_H +#include "apiobject.h" #include "plugin.h" #include "scopy-pluginbase_export.h" -#include -#include "apiobject.h" +#include namespace scopy { /** * @brief The PluginBase class * PluginBase is used to provide default implementation to the plugin interface */ -class SCOPY_PLUGINBASE_EXPORT PluginBase : public Plugin { +class SCOPY_PLUGINBASE_EXPORT PluginBase : public Plugin +{ public: virtual ~PluginBase() {} @@ -42,11 +43,11 @@ class SCOPY_PLUGINBASE_EXPORT PluginBase : public Plugin { virtual QString name() override; virtual QString displayName() override; virtual QString displayParam() override; - virtual QWidget* icon() override; - virtual QWidget* page() override; - virtual QWidget* preferencesPage() override; - virtual QList extraButtons() override; - virtual QList toolList() override; + virtual QWidget *icon() override; + virtual QWidget *page() override; + virtual QWidget *preferencesPage() override; + virtual QList extraButtons() override; + virtual QList toolList() override; virtual QJsonObject metadata() override; virtual QString about() override; @@ -54,7 +55,7 @@ class SCOPY_PLUGINBASE_EXPORT PluginBase : public Plugin { virtual QString description() override; virtual void loadMetadata(QString data); - virtual void cloneExtra(Plugin*) override; + virtual void cloneExtra(Plugin *) override; public Q_SLOTS: virtual void showPageCallback() override; @@ -71,42 +72,45 @@ public Q_SLOTS: QWidget *m_page; QWidget *m_preferencesPage; QWidget *m_icon; - QList m_toolList; - QList m_extraButtons; + QList m_toolList; + QList m_extraButtons; QJsonObject m_metadata; bool m_enabled; }; -} +} // namespace scopy #define scopyxstr(a) scopystr(a) #define scopystr(a) #a -#define SCOPY_PLUGIN \ - Q_PLUGIN_METADATA(IID ScopyPlugin_iid)\ - Q_INTERFACES(scopy::Plugin)\ -public:\ - virtual ~SCOPY_PLUGIN_NAME () override {}\ - SCOPY_PLUGIN_NAME* clone(QObject *parent) override { \ - SCOPY_PLUGIN_NAME* ret = new SCOPY_PLUGIN_NAME(); \ - /* copy metadata from this object to the next one */\ - ret->m_name = scopyxstr(SCOPY_PLUGIN_NAME);\ - ret->setParent(parent);\ - ret->m_displayName = ret->m_name;\ - ret->setMetadata(metadata()); \ - ret->cloneExtra(this);\ - return ret;\ - }\ -\ -Q_SIGNALS:\ - void connectDevice() override;\ - void disconnectDevice() override;\ - void restartDevice() override;\ - void toolListChanged() override;\ - void requestToolByUuid(QString) override;\ -private:\ - -#define SCOPY_PLUGIN_ICON(x) m_icon = new QLabel(""); m_icon->setStyleSheet("border-image: url(" x ");") -#define SCOPY_NEW_TOOLMENUENTRY(id, name, icon) new ToolMenuEntry(id,name,icon,this->m_name,this) - +#define SCOPY_PLUGIN \ + Q_PLUGIN_METADATA(IID ScopyPlugin_iid) \ + Q_INTERFACES(scopy::Plugin) \ +public: \ + virtual ~SCOPY_PLUGIN_NAME() override {} \ + SCOPY_PLUGIN_NAME *clone(QObject *parent) override \ + { \ + SCOPY_PLUGIN_NAME *ret = new SCOPY_PLUGIN_NAME(); \ + /* copy metadata from this object to the next one */ \ + ret->m_name = scopyxstr(SCOPY_PLUGIN_NAME); \ + ret->setParent(parent); \ + ret->m_displayName = ret->m_name; \ + ret->setMetadata(metadata()); \ + ret->cloneExtra(this); \ + return ret; \ + } \ + \ +Q_SIGNALS: \ + void connectDevice() override; \ + void disconnectDevice() override; \ + void restartDevice() override; \ + void toolListChanged() override; \ + void requestToolByUuid(QString) override; \ + \ +private: + +#define SCOPY_PLUGIN_ICON(x) \ + m_icon = new QLabel(""); \ + m_icon->setStyleSheet("border-image: url(" x ");") +#define SCOPY_NEW_TOOLMENUENTRY(id, name, icon) new ToolMenuEntry(id, name, icon, this->m_name, this) #endif // PLUGINBASE_H diff --git a/pluginbase/include/pluginbase/preferences.h b/pluginbase/include/pluginbase/preferences.h index 202194260a..64be3e49bf 100644 --- a/pluginbase/include/pluginbase/preferences.h +++ b/pluginbase/include/pluginbase/preferences.h @@ -1,10 +1,11 @@ #ifndef PREFERENCES_H #define PREFERENCES_H -#include +#include "scopy-pluginbase_export.h" + #include +#include #include -#include "scopy-pluginbase_export.h" namespace scopy { /** @@ -86,12 +87,10 @@ public Q_SLOTS: void restartRequired(); private: - - QMap p; + QMap p; QSettings *s; - static Preferences * pinstance_; - + static Preferences *pinstance_; }; -} +} // namespace scopy #endif // PREFERENCES_H diff --git a/pluginbase/include/pluginbase/preferenceshelper.h b/pluginbase/include/pluginbase/preferenceshelper.h index 8f4ffa42c7..34885bbedf 100644 --- a/pluginbase/include/pluginbase/preferenceshelper.h +++ b/pluginbase/include/pluginbase/preferenceshelper.h @@ -1,23 +1,28 @@ #ifndef PREFERENCESHELPER_H #define PREFERENCESHELPER_H +#include "preferences.h" +#include "scopy-pluginbase_export.h" + #include #include #include -#include "preferences.h" -#include "scopy-pluginbase_export.h" namespace scopy { /** * @brief The PreferencesHelper class * PreferencesHelper class used to create widgets and connect the widgets to the Preferences singleton */ -class SCOPY_PLUGINBASE_EXPORT PreferencesHelper { +class SCOPY_PLUGINBASE_EXPORT PreferencesHelper +{ public: - static QCheckBox *addPreferenceCheckBox(Preferences *p, QString id, QString description, QObject *parent = nullptr); + static QCheckBox *addPreferenceCheckBox(Preferences *p, QString id, QString description, + QObject *parent = nullptr); static QWidget *addPreferenceEdit(Preferences *p, QString id, QString description, QObject *parent = nullptr); - static QWidget *addPreferenceCombo(Preferences *p, QString id, QString description, QStringList options, QObject *parent = nullptr); - static QWidget *addPreferenceComboList(Preferences *p, QString id, QString description, QList > options, QObject *parent); + static QWidget *addPreferenceCombo(Preferences *p, QString id, QString description, QStringList options, + QObject *parent = nullptr); + static QWidget *addPreferenceComboList(Preferences *p, QString id, QString description, + QList> options, QObject *parent); }; -} +} // namespace scopy #endif // PREFERENCESHELPER_H diff --git a/pluginbase/include/pluginbase/resourcemanager.h b/pluginbase/include/pluginbase/resourcemanager.h index fd14cc55cd..3fe38399b3 100644 --- a/pluginbase/include/pluginbase/resourcemanager.h +++ b/pluginbase/include/pluginbase/resourcemanager.h @@ -1,13 +1,15 @@ #ifndef RESOURCEMANAGER_H #define RESOURCEMANAGER_H -#include -#include #include "scopy-pluginbase_export.h" +#include +#include + namespace scopy { -class SCOPY_PLUGINBASE_EXPORT ResourceUser { +class SCOPY_PLUGINBASE_EXPORT ResourceUser +{ public: virtual void stop() = 0; // call ResourceManager::close }; @@ -29,8 +31,8 @@ class SCOPY_PLUGINBASE_EXPORT ResourceManager : public QObject static void close(QString resource); private: - QMap map; - static ResourceManager * pinstance_; + QMap map; + static ResourceManager *pinstance_; }; -} +} // namespace scopy #endif // RESOURCEMANAGER_H diff --git a/pluginbase/include/pluginbase/scopyjs.h b/pluginbase/include/pluginbase/scopyjs.h index d8bb1d1fee..2cbd88b2e7 100644 --- a/pluginbase/include/pluginbase/scopyjs.h +++ b/pluginbase/include/pluginbase/scopyjs.h @@ -21,14 +21,15 @@ #ifndef SCOPY_QTJS_HPP #define SCOPY_QTJS_HPP -#include -#include -#include -#include #include "apiobject.h" #include "qloggingcategory.h" -#include "scopy-pluginbase_export.h" #include "scopy-pluginbase_config.h" +#include "scopy-pluginbase_export.h" + +#include +#include +#include +#include #include class QJSEngine; @@ -53,17 +54,17 @@ class SCOPY_PLUGINBASE_EXPORT ScopyJS : public QObject Q_INVOKABLE void exit(); Q_INVOKABLE void sleep(unsigned long s); Q_INVOKABLE void msleep(unsigned long ms); - Q_INVOKABLE void printToConsole(const QString& text); - Q_INVOKABLE QString readFromConsole(const QString& text); + Q_INVOKABLE void printToConsole(const QString &text); + Q_INVOKABLE QString readFromConsole(const QString &text); Q_INVOKABLE void returnToApplication(); Q_INVOKABLE void suppressScopyMessages(bool b); QJSEngine *engine(); - void registerApi(ApiObject* obj); - void unregisterApi(ApiObject* obj); - void registerApi(ApiObject* obj, QJSValue parentObj); - void unregisterApi(ApiObject* obj, QJSValue parentObj); + void registerApi(ApiObject *obj); + void unregisterApi(ApiObject *obj); + void registerApi(ApiObject *obj, QJSValue parentObj); + void unregisterApi(ApiObject *obj, QJSValue parentObj); public Q_SLOTS: void hasText(); @@ -79,11 +80,11 @@ public Q_SLOTS: #endif QSocketNotifier *notifier; bool done; - static ScopyJS * pinstance_; + static ScopyJS *pinstance_; static QLoggingCategory::CategoryFilter oldCategoryFilter; static void jsCategoryFilter(QLoggingCategory *category); }; -} +} // namespace scopy #endif /* SCOPY_QTJS_HPP */ diff --git a/pluginbase/include/pluginbase/toolmenuentry.h b/pluginbase/include/pluginbase/toolmenuentry.h index 1aed385809..98bdd6ead9 100644 --- a/pluginbase/include/pluginbase/toolmenuentry.h +++ b/pluginbase/include/pluginbase/toolmenuentry.h @@ -1,10 +1,12 @@ #ifndef TOOLMENUENTRY_H #define TOOLMENUENTRY_H +#include "scopy-pluginbase_export.h" + #include #include + #include -#include "scopy-pluginbase_export.h" namespace scopy { /** @@ -12,16 +14,27 @@ namespace scopy { * Class used by plugin and scopy to populate the tool menu * SCOPY_NEW_TOOLMENUENTRY macro can be used to instantiate ToolMenuEntry objects */ -class SCOPY_PLUGINBASE_EXPORT ToolMenuEntry : public QObject { +class SCOPY_PLUGINBASE_EXPORT ToolMenuEntry : public QObject +{ Q_OBJECT public: - ToolMenuEntry(QString id, QString name, QString icon, QString pluginName, QObject *parent = nullptr) : - QObject(parent), m_id(id), m_uuid("tme_"+pluginName+"_"+id+"_"+scopy::config::getUuid()), - m_name(name), m_icon(icon), m_pluginName(pluginName), m_visible(true), - m_enabled(false), m_running(false), m_runBtnVisible(false), - m_attached(true), m_tool(nullptr) {} + ToolMenuEntry(QString id, QString name, QString icon, QString pluginName, QObject *parent = nullptr) + : QObject(parent) + , m_id(id) + , m_uuid("tme_" + pluginName + "_" + id + "_" + scopy::config::getUuid()) + , m_name(name) + , m_icon(icon) + , m_pluginName(pluginName) + , m_visible(true) + , m_enabled(false) + , m_running(false) + , m_runBtnVisible(false) + , m_attached(true) + , m_tool(nullptr) + {} - ToolMenuEntry(const ToolMenuEntry &other) { + ToolMenuEntry(const ToolMenuEntry &other) + { m_id = other.m_id; m_uuid = other.m_uuid; m_name = other.m_name; @@ -45,13 +58,13 @@ class SCOPY_PLUGINBASE_EXPORT ToolMenuEntry : public QObject { inline bool enabled() const { return m_enabled; } inline bool running() const { return m_running; } inline bool attached() const { return m_attached; } - inline bool runEnabled() const { return m_runEnabled; } + inline bool runEnabled() const { return m_runEnabled; } inline bool runBtnVisible() const { return m_runBtnVisible; } inline QWidget *tool() const { return m_tool; } - static ToolMenuEntry *findToolMenuEntryByName(QList list, QString id); - static ToolMenuEntry *findToolMenuEntryById(QList list, QString id); - static ToolMenuEntry *findToolMenuEntryByTool(QList list, QWidget *w); + static ToolMenuEntry *findToolMenuEntryByName(QList list, QString id); + static ToolMenuEntry *findToolMenuEntryById(QList list, QString id); + static ToolMenuEntry *findToolMenuEntryByTool(QList list, QWidget *w); /** * @brief setName * @param newName @@ -82,7 +95,7 @@ public Q_SLOTS: * @brief setRunning * @param newRunning * Sets the tool in run state - */ + */ void setRunning(bool newRunning); /** @@ -111,7 +124,7 @@ public Q_SLOTS: * @param newTool * links a widget to the tool menu entry. Remove tool from the menu entry by setting newtool to nullptr */ - QWidget* setTool(QWidget *newTool); + QWidget *setTool(QWidget *newTool); Q_SIGNALS: /** @@ -124,7 +137,7 @@ public Q_SLOTS: * signal is emitted automatically when changing a tool linked to the tool entry */ void updateToolAttached(bool); - void updateTool(QWidget*); + void updateTool(QWidget *); /** * @brief requestRun @@ -150,13 +163,13 @@ public Q_SLOTS: bool m_runEnabled; bool m_runBtnVisible; bool m_attached; - QWidget* m_tool; + QWidget *m_tool; }; inline ToolMenuEntry *ToolMenuEntry::findToolMenuEntryByName(QList list, QString name) { for(auto &&tme : list) { - if(tme->name()==name) { + if(tme->name() == name) { return tme; } } @@ -166,7 +179,7 @@ inline ToolMenuEntry *ToolMenuEntry::findToolMenuEntryByName(QList list, QString id) { for(auto &&tme : list) { - if(tme->id()==id) { + if(tme->id() == id) { return tme; } } @@ -176,7 +189,7 @@ inline ToolMenuEntry *ToolMenuEntry::findToolMenuEntryById(QList list, QWidget *w) { for(auto &&tme : list) { - if(tme->tool()==w) { + if(tme->tool() == w) { return tme; } } @@ -219,9 +232,9 @@ inline void ToolMenuEntry::setRunBtnVisible(bool newRunBtnVisible) Q_EMIT updateToolEntry(); } -inline QWidget* ToolMenuEntry::setTool(QWidget *newTool) +inline QWidget *ToolMenuEntry::setTool(QWidget *newTool) { - QWidget* oldTool; + QWidget *oldTool; oldTool = m_tool; m_tool = newTool; if(oldTool != m_tool) { @@ -230,7 +243,6 @@ inline QWidget* ToolMenuEntry::setTool(QWidget *newTool) return oldTool; } - inline void ToolMenuEntry::setAttached(bool attach) { bool oldAttach = m_attached; @@ -240,13 +252,12 @@ inline void ToolMenuEntry::setAttached(bool attach) } } - inline void ToolMenuEntry::setRunEnabled(bool newRunEnabled) { m_runEnabled = newRunEnabled; Q_EMIT updateToolEntry(); } -} +} // namespace scopy #endif // TOOLMENUENTRY_H diff --git a/pluginbase/include/pluginbase/versionchecker.h b/pluginbase/include/pluginbase/versionchecker.h index 431683bf58..0ad05fdeb5 100644 --- a/pluginbase/include/pluginbase/versionchecker.h +++ b/pluginbase/include/pluginbase/versionchecker.h @@ -1,13 +1,15 @@ #ifndef VERSIONCHECKER_H #define VERSIONCHECKER_H -#include +#include "scopy-pluginbase_export.h" + #include #include +#include +#include + #include #include -#include -#include "scopy-pluginbase_export.h" namespace scopy { class SCOPY_PLUGINBASE_EXPORT VersionChecker : public QObject @@ -25,14 +27,16 @@ class SCOPY_PLUGINBASE_EXPORT VersionChecker : public QObject static VersionChecker *GetInstance(); - typedef enum { + typedef enum + { NOT_INIT, IN_PROGRESS, DONE } state; - template - void subscribe(T* object, R(T::* function)(QJsonDocument)){ + template + void subscribe(T *object, R (T::*function)(QJsonDocument)) + { auto f = std::bind(function, object, std::placeholders::_1); m_subscriptions.push_back(f); Q_EMIT addedNewSubscription(); @@ -46,7 +50,6 @@ private Q_SLOTS: void updateSubscriptions(); private: - /** * @brief Pull the json file with the current version from m_url and save it in the m_cache variable. * */ @@ -64,16 +67,15 @@ private Q_SLOTS: * */ bool cacheOutdated(); - static VersionChecker * pinstance_; + static VersionChecker *pinstance_; const QString m_url = "https://swdownloads.analog.com/cse/sw_versions.json"; - QList< std::function > m_subscriptions; + QList> m_subscriptions; QJsonDocument m_cache; QString m_cacheFilePath; QNetworkAccessManager *m_nam; int m_ttl; // maximum number of redirects allowed state currentState; - }; -} +} // namespace scopy #endif // VERSIONCHECKER_H diff --git a/pluginbase/src/apiobject.cpp b/pluginbase/src/apiobject.cpp index 59aedb90a7..7ddfa9ed5b 100644 --- a/pluginbase/src/apiobject.cpp +++ b/pluginbase/src/apiobject.cpp @@ -22,27 +22,25 @@ #include #include +#include #include #include -#include -Q_LOGGING_CATEGORY(CAT_APIOBJECT,"ApiObject"); +Q_LOGGING_CATEGORY(CAT_APIOBJECT, "ApiObject"); using namespace scopy; -ApiObject::ApiObject(QObject *parent) : QObject(parent) -{ -} +ApiObject::ApiObject(QObject *parent) + : QObject(parent) +{} -ApiObject::~ApiObject() -{ -} +ApiObject::~ApiObject() {} -template void ApiObject::save(QSettings& settings, - const QString& prop, const QList& list) +template +void ApiObject::save(QSettings &settings, const QString &prop, const QList &list) { settings.beginWriteArray(prop, list.size()); - for (int i = 0; i < list.size(); i++) { + for(int i = 0; i < list.size(); i++) { settings.setArrayIndex(i); settings.setValue("idx", QVariant(list.at(i))); } @@ -50,12 +48,11 @@ template void ApiObject::save(QSettings& settings, settings.endArray(); } -void ApiObject::save(QSettings& settings, const QString& prop, - const QVariantList& list) +void ApiObject::save(QSettings &settings, const QString &prop, const QVariantList &list) { settings.beginWriteArray(prop, list.size()); - for (int i = 0; i < list.size(); i++) { + for(int i = 0; i < list.size(); i++) { settings.setArrayIndex(i); save_nogroup(list.at(i).value(), settings); } @@ -63,13 +60,13 @@ void ApiObject::save(QSettings& settings, const QString& prop, settings.endArray(); } -template QList ApiObject::load( - QSettings& settings, const QString& prop) +template +QList ApiObject::load(QSettings &settings, const QString &prop) { int nb = settings.beginReadArray(prop); QList list; - for (int i = 0; i < nb; i++) { + for(int i = 0; i < nb; i++) { settings.setArrayIndex(i); list.append(settings.value("idx").value()); } @@ -78,12 +75,11 @@ template QList ApiObject::load( return list; } -void ApiObject::load(QSettings& settings, const QString& prop, - const QVariantList& list) +void ApiObject::load(QSettings &settings, const QString &prop, const QVariantList &list) { int nb = settings.beginReadArray(prop); - for (int i = 0; i < nb; i++) { + for(int i = 0; i < nb; i++) { settings.setArrayIndex(i); load_nogroup(list.at(i).value(), settings); } @@ -91,111 +87,98 @@ void ApiObject::load(QSettings& settings, const QString& prop, settings.endArray(); } -void ApiObject::load_nogroup(ApiObject *obj, QSettings& settings) +void ApiObject::load_nogroup(ApiObject *obj, QSettings &settings) { auto meta = obj->metaObject(); - for (int i = meta->propertyOffset(); - i < meta->propertyCount(); i++) { + for(int i = meta->propertyOffset(); i < meta->propertyCount(); i++) { auto prop = meta->property(i); - if (!prop.isStored() || !prop.isReadable()) + if(!prop.isStored() || !prop.isReadable()) continue; auto data = prop.read(obj); - if (prop.isWritable()) { - if (data.canConvert>()) { + if(prop.isWritable()) { + if(data.canConvert>()) { auto list = load(settings, prop.name()); - if (!list.empty()) + if(!list.empty()) prop.write(obj, QVariant::fromValue(list)); - } else if (data.canConvert>()) { + } else if(data.canConvert>()) { auto list = load(settings, prop.name()); - if (!list.empty()) + if(!list.empty()) prop.write(obj, QVariant::fromValue(list)); - } else if (data.canConvert>()) { + } else if(data.canConvert>()) { auto list = load(settings, prop.name()); - if (!list.empty()) + if(!list.empty()) prop.write(obj, QVariant::fromValue(list)); - } else if (data.canConvert>()) { + } else if(data.canConvert>()) { auto list = load(settings, prop.name()); - if (!list.empty()) + if(!list.empty()) prop.write(obj, QVariant::fromValue(list)); } else { auto value = settings.value(prop.name()); - qDebug(CAT_APIOBJECT) << "Loading property" - << prop.name() - << "value" << value; + qDebug(CAT_APIOBJECT) << "Loading property" << prop.name() << "value" << value; - if (!value.isNull()) + if(!value.isNull()) prop.write(obj, value); } } else { - if (data.canConvert()) { + if(data.canConvert()) { settings.beginGroup(prop.name()); load_nogroup(data.value(), settings); settings.endGroup(); - } else if (data.canConvert()) { - load(settings, prop.name(), - data.value()); + } else if(data.canConvert()) { + load(settings, prop.name(), data.value()); } } } } -void ApiObject::save_nogroup(ApiObject *obj, QSettings& settings) +void ApiObject::save_nogroup(ApiObject *obj, QSettings &settings) { auto meta = obj->metaObject(); - for(int i=0;ipropertyCount();i++) { - qDebug()<property(i).name(); + for(int i = 0; i < meta->propertyCount(); i++) { + qDebug() << i << " " << meta->property(i).name(); } - for (int i = meta->propertyOffset(); - i < meta->propertyCount(); i++) { + for(int i = meta->propertyOffset(); i < meta->propertyCount(); i++) { auto prop = meta->property(i); - if (!prop.isStored() || !prop.isReadable()) + if(!prop.isStored() || !prop.isReadable()) continue; auto data = prop.read(obj); - if (prop.isWritable()) { - if (data.canConvert>()) { - save(settings, prop.name(), - data.value>()); - } else if (data.canConvert>()) { - save(settings, prop.name(), - data.value>()); - } else if (data.canConvert>()) { - save(settings, prop.name(), - data.value>()); - } else if (data.canConvert>()) { - save(settings, prop.name(), - data.value>()); + if(prop.isWritable()) { + if(data.canConvert>()) { + save(settings, prop.name(), data.value>()); + } else if(data.canConvert>()) { + save(settings, prop.name(), data.value>()); + } else if(data.canConvert>()) { + save(settings, prop.name(), data.value>()); + } else if(data.canConvert>()) { + save(settings, prop.name(), data.value>()); } else { - qDebug(CAT_APIOBJECT) << "Saving property" - << prop.name() - << "value" << data; + qDebug(CAT_APIOBJECT) << "Saving property" << prop.name() << "value" << data; settings.setValue(prop.name(), data); } } else { - if (data.canConvert()) { + if(data.canConvert()) { settings.beginGroup(prop.name()); - save_nogroup(data.value(), - settings); + save_nogroup(data.value(), settings); settings.endGroup(); - } else if (data.canConvert()) { - save(settings, prop.name(), - data.value()); + } else if(data.canConvert()) { + save(settings, prop.name(), data.value()); } } } } -void ApiObject::load(QSettings& settings) +void ApiObject::load(QSettings &settings) { - qInfo(CAT_APIOBJECT)<<"Loading "<. */ #include "jsfileio.h" + #include #include using namespace scopy; -JsFileIo::JsFileIo(QObject *parent): QObject(parent) -{ -} +JsFileIo::JsFileIo(QObject *parent) + : QObject(parent) +{} -void JsFileIo::writeToFile(const QString& data, const QString& path) +void JsFileIo::writeToFile(const QString &data, const QString &path) { QFile file(path); - if (file.open(QIODevice::WriteOnly)) { + if(file.open(QIODevice::WriteOnly)) { QTextStream stream(&file); stream << data; } } -void JsFileIo::appendToFile(const QString& data, const QString& path) +void JsFileIo::appendToFile(const QString &data, const QString &path) { QFile file(path); - if (file.open(QIODevice::Append)) { + if(file.open(QIODevice::Append)) { QTextStream stream(&file); stream << data; } } -QString JsFileIo::readAll(const QString& path) +QString JsFileIo::readAll(const QString &path) { QFile file(path); QString data; - if (file.open(QIODevice::ReadOnly)) { + if(file.open(QIODevice::ReadOnly)) { QTextStream stream(&file); data = stream.readAll(); } return data; } -QString JsFileIo::readLine(const QString& path, const int lineNumber) +QString JsFileIo::readLine(const QString &path, const int lineNumber) { QFile file(path); int i = 0; QString data; - if (file.open(QIODevice::ReadOnly)) { + if(file.open(QIODevice::ReadOnly)) { QTextStream stream(&file); - while( i <= lineNumber ){ + while(i <= lineNumber) { data = stream.readLine(); if(stream.atEnd()) break; diff --git a/pluginbase/src/jsfileio.h b/pluginbase/src/jsfileio.h index 037f0f286c..96aeefa816 100644 --- a/pluginbase/src/jsfileio.h +++ b/pluginbase/src/jsfileio.h @@ -24,17 +24,17 @@ /* Private header */ namespace scopy { -class JsFileIo: public QObject +class JsFileIo : public QObject { Q_OBJECT public: JsFileIo(QObject *parent = 0); - Q_INVOKABLE void writeToFile(const QString& data, const QString& path); - Q_INVOKABLE void appendToFile(const QString& data, const QString& path); - Q_INVOKABLE QString readAll(const QString& path); - Q_INVOKABLE QString readLine(const QString& path, const int lineNumber); + Q_INVOKABLE void writeToFile(const QString &data, const QString &path); + Q_INVOKABLE void appendToFile(const QString &data, const QString &path); + Q_INVOKABLE QString readAll(const QString &path); + Q_INVOKABLE QString readLine(const QString &path, const int lineNumber); }; } /* namespace scopy */ diff --git a/pluginbase/src/messagebroker.cpp b/pluginbase/src/messagebroker.cpp index 17edb51047..556d48a3f1 100644 --- a/pluginbase/src/messagebroker.cpp +++ b/pluginbase/src/messagebroker.cpp @@ -1,26 +1,20 @@ #include "messagebroker.h" -#include +#include using namespace scopy; -MessageBroker* MessageBroker::pinstance_{nullptr}; - -MessageBroker::MessageBroker(QObject *parent) : QObject(parent) -{ +MessageBroker *MessageBroker::pinstance_{nullptr}; -} - -MessageBroker::~MessageBroker() -{ - -} +MessageBroker::MessageBroker(QObject *parent) + : QObject(parent) +{} +MessageBroker::~MessageBroker() {} MessageBroker *MessageBroker::GetInstance() { - if (pinstance_ == nullptr) - { + if(pinstance_ == nullptr) { pinstance_ = new MessageBroker(QApplication::instance()); // singleton has the app as parent } return pinstance_; @@ -29,7 +23,7 @@ MessageBroker *MessageBroker::GetInstance() void MessageBroker::subscribe(QObject *obj, QString topic) { if(!map.contains(obj)) - map.insert(obj,{"broadcast"}); + map.insert(obj, {"broadcast"}); map[obj].insert(topic); } @@ -41,24 +35,21 @@ void MessageBroker::unsubscribe(QObject *obj, QString topic) map.remove(obj); } } - } void MessageBroker::publish(QString topic, QString message) { bool processed; - QList keys = map.keys(); + QList keys = map.keys(); for(auto &&k : keys) { if(map.value(k).contains(topic)) { - QMetaObject::invokeMethod(k, "messageCallback", - Qt::AutoConnection, -// Q_RETURN_ARG(bool, processed), - Q_ARG(QString, topic), - Q_ARG(QString, message)); + QMetaObject::invokeMethod( + k, "messageCallback", Qt::AutoConnection, + // Q_RETURN_ARG(bool, processed), + Q_ARG(QString, topic), Q_ARG(QString, message)); } } } - #include "moc_messagebroker.cpp" diff --git a/pluginbase/src/pluginbase.cpp b/pluginbase/src/pluginbase.cpp index c49ee40aa4..6fdbf41c84 100644 --- a/pluginbase/src/pluginbase.cpp +++ b/pluginbase/src/pluginbase.cpp @@ -1,45 +1,41 @@ #include "pluginbase.h" -#include + #include +#include -Q_LOGGING_CATEGORY(CAT_PLUGIN,"Plugin"); +Q_LOGGING_CATEGORY(CAT_PLUGIN, "Plugin"); using namespace scopy; -void PluginBase::setParam(QString param, QString category) { +void PluginBase::setParam(QString param, QString category) +{ m_param = param; m_category = category; m_displayParam = param; m_enabled = true; } -void PluginBase::setEnabled(bool en) -{ - m_enabled = en; -} +void PluginBase::setEnabled(bool en) { m_enabled = en; } -void PluginBase::preload() { -} +void PluginBase::preload() {} -void PluginBase::postload() { -} +void PluginBase::postload() {} -void PluginBase::unload() { +void PluginBase::unload() {} -} - -bool PluginBase::loadIcon() { +bool PluginBase::loadIcon() +{ m_icon = nullptr; return false; } -bool PluginBase::loadPage(){ +bool PluginBase::loadPage() +{ m_page = nullptr; return false; } -void PluginBase::loadToolList() { -} +void PluginBase::loadToolList() {} bool PluginBase::loadPreferencesPage() { @@ -47,138 +43,77 @@ bool PluginBase::loadPreferencesPage() return false; } -bool PluginBase::loadExtraButtons() -{ - return false; -} - -void PluginBase::saveSettings(QSettings &s) { - -} - -void PluginBase::loadSettings(QSettings &s) { +bool PluginBase::loadExtraButtons() { return false; } -} +void PluginBase::saveSettings(QSettings &s) {} -void PluginBase::messageCallback(QString topic, QString message) -{ +void PluginBase::loadSettings(QSettings &s) {} -} +void PluginBase::messageCallback(QString topic, QString message) {} void PluginBase::requestTool(QString id) { - Q_EMIT requestToolByUuid(ToolMenuEntry::findToolMenuEntryById(m_toolList,id)->uuid()); + Q_EMIT requestToolByUuid(ToolMenuEntry::findToolMenuEntryById(m_toolList, id)->uuid()); } -bool PluginBase::enabled() { - return m_enabled; -} +bool PluginBase::enabled() { return m_enabled; } -QString PluginBase::param() { - return m_param; -} +QString PluginBase::param() { return m_param; } -QString PluginBase::name() { - return m_name; -} +QString PluginBase::name() { return m_name; } -QString PluginBase::displayName() { - return m_displayName; -} +QString PluginBase::displayName() { return m_displayName; } -QString PluginBase::displayParam() { - return m_displayParam; -} +QString PluginBase::displayParam() { return m_displayParam; } -QWidget* PluginBase::icon() { - return m_icon; -} -QWidget* PluginBase::page() { - return m_page; -} +QWidget *PluginBase::icon() { return m_icon; } +QWidget *PluginBase::page() { return m_page; } -QWidget *PluginBase::preferencesPage() -{ - return m_preferencesPage; -} +QWidget *PluginBase::preferencesPage() { return m_preferencesPage; } -QList PluginBase::extraButtons() -{ - return m_extraButtons; -} +QList PluginBase::extraButtons() { return m_extraButtons; } -QList PluginBase::toolList() { - return m_toolList; -} -void PluginBase::showPageCallback() { - qDebug(CAT_PLUGIN)< PluginBase::toolList() { return m_toolList; } +void PluginBase::showPageCallback() { qDebug(CAT_PLUGIN) << m_name << "showpage callback"; } +void PluginBase::hidePageCallback() { qDebug(CAT_PLUGIN) << m_name << "hidepage callback"; } -QJsonObject PluginBase::metadata() { - return m_metadata; -} +QJsonObject PluginBase::metadata() { return m_metadata; } -QString PluginBase::about() -{ - return ""; -} +QString PluginBase::about() { return ""; } -QString PluginBase::version() -{ - return ""; -} +QString PluginBase::version() { return ""; } -QString PluginBase::description() { - return ""; -} +QString PluginBase::description() { return ""; } +void PluginBase::setMetadata(QJsonObject obj) { m_metadata = obj; } -void PluginBase::setMetadata(QJsonObject obj) -{ - m_metadata = obj; -} +void PluginBase::initPreferences() {} -void PluginBase::initPreferences() -{ - -} - -void PluginBase::init() -{ - -} +void PluginBase::init() {} -void PluginBase::deinit() -{ +void PluginBase::deinit() {} -} +void PluginBase::cloneExtra(Plugin *) {} -void PluginBase::cloneExtra(Plugin *) +void PluginBase::initMetadata() { - -} - -void PluginBase::initMetadata() { loadMetadata( -R"plugin( + R"plugin( { "priority":1, } )plugin"); - } -void PluginBase::loadMetadata(QString data) { +void PluginBase::loadMetadata(QString data) +{ QJsonParseError err; QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8(), &err); if(err.error != QJsonParseError::NoError) { - qCritical(CAT_PLUGIN) << m_name <<" plugin - JSON Parse error !" << err.errorString(); + qCritical(CAT_PLUGIN) << m_name << " plugin - JSON Parse error !" << err.errorString(); qCritical(CAT_PLUGIN) << data; - qCritical(CAT_PLUGIN) << QString(" ").repeated(err.offset)+"^"; + qCritical(CAT_PLUGIN) << QString(" ").repeated(err.offset) + "^"; } m_metadata = doc.object(); } diff --git a/pluginbase/src/preferences.cpp b/pluginbase/src/preferences.cpp index a6da276b64..47a39a742c 100644 --- a/pluginbase/src/preferences.cpp +++ b/pluginbase/src/preferences.cpp @@ -1,28 +1,26 @@ #include "preferences.h" -#include +#include #include -Q_LOGGING_CATEGORY(CAT_PREFERENCES,"Preferences"); +Q_LOGGING_CATEGORY(CAT_PREFERENCES, "Preferences"); using namespace scopy; -Preferences* Preferences::pinstance_{nullptr}; +Preferences *Preferences::pinstance_{nullptr}; -Preferences::Preferences(QObject *parent) : QObject(parent) +Preferences::Preferences(QObject *parent) + : QObject(parent) { - connect(parent, SIGNAL(aboutToQuit()),this,SLOT(save())); + connect(parent, SIGNAL(aboutToQuit()), this, SLOT(save())); } -Preferences::~Preferences() -{ - -} +Preferences::~Preferences() {} void Preferences::_init(QString k, QVariant v) { if(!p.contains(k)) { - p.insert(k,v); + p.insert(k, v); } // else - map contains key so it is already initialized to the correct value, nothing to do } @@ -35,9 +33,7 @@ QVariant Preferences::_get(QString k) return v; } -void Preferences::set(QString k, QVariant v) { - return Preferences::GetInstance()->_set(k,v); -} +void Preferences::set(QString k, QVariant v) { return Preferences::GetInstance()->_set(k, v); } void Preferences::_set(QString k, QVariant v) { @@ -47,29 +43,18 @@ void Preferences::_set(QString k, QVariant v) Q_EMIT preferenceChanged(k, v); } -void Preferences::clear() -{ - p.clear(); -} +void Preferences::clear() { p.clear(); } -QVariant Preferences::get(QString val) { - return Preferences::GetInstance()->_get(val); -} +QVariant Preferences::get(QString val) { return Preferences::GetInstance()->_get(val); } -QMap Preferences::getPreferences() const -{ - return p; -} +QMap Preferences::getPreferences() const { return p; } -void Preferences::setPreferences(QMap s) -{ - p = s; -} +void Preferences::setPreferences(QMap s) { p = s; } void Preferences::setPreferencesFilename(QString f) { - s = new QSettings(f,QSettings::IniFormat, this); - qInfo(CAT_PREFERENCES)<fileName(); + s = new QSettings(f, QSettings::IniFormat, this); + qInfo(CAT_PREFERENCES) << s->fileName(); } void Preferences::save() @@ -79,7 +64,7 @@ void Preferences::save() QStringList keys = p.keys(); for(const QString &key : keys) { - s->setValue(key,p[key]); + s->setValue(key, p[key]); } s->sync(); @@ -98,19 +83,12 @@ void Preferences::load() Preferences *Preferences::GetInstance() { - if (pinstance_ == nullptr) - { + if(pinstance_ == nullptr) { pinstance_ = new Preferences(QApplication::instance()); // singleton has the app as parent } return pinstance_; } -void Preferences::init(QString k, QVariant v) -{ - return Preferences::GetInstance()->_init(k,v); -} - - - +void Preferences::init(QString k, QVariant v) { return Preferences::GetInstance()->_init(k, v); } #include "moc_preferences.cpp" diff --git a/pluginbase/src/preferenceshelper.cpp b/pluginbase/src/preferenceshelper.cpp index cee9ffac10..43b6c4a700 100644 --- a/pluginbase/src/preferenceshelper.cpp +++ b/pluginbase/src/preferenceshelper.cpp @@ -4,17 +4,19 @@ #include using namespace scopy; -QCheckBox* PreferencesHelper::addPreferenceCheckBox(Preferences *p, QString id, QString description, QObject *parent) { +QCheckBox *PreferencesHelper::addPreferenceCheckBox(Preferences *p, QString id, QString description, QObject *parent) +{ bool pref1Val = p->get(id).toBool(); QCheckBox *pref = new QCheckBox(description); pref->setChecked(pref1Val); - parent->connect(pref,&QCheckBox::toggled,parent,[p,id](bool b) { p->set(id,b);}); + parent->connect(pref, &QCheckBox::toggled, parent, [p, id](bool b) { p->set(id, b); }); return pref; } -QWidget* PreferencesHelper::addPreferenceEdit(Preferences *p, QString id, QString description, QObject *parent) { - QWidget* widget = new QWidget(); - QHBoxLayout* layout = new QHBoxLayout(); +QWidget *PreferencesHelper::addPreferenceEdit(Preferences *p, QString id, QString description, QObject *parent) +{ + QWidget *widget = new QWidget(); + QHBoxLayout *layout = new QHBoxLayout(); layout->setMargin(0); widget->setLayout(layout); @@ -22,9 +24,9 @@ QWidget* PreferencesHelper::addPreferenceEdit(Preferences *p, QString id, QStrin QLineEdit *pref = new QLineEdit(); pref->setMaximumWidth(200); pref->setText(pref1Val); - parent->connect(pref,&QLineEdit::textChanged,parent,[p,id](QString b) { p->set(id,b);}); + parent->connect(pref, &QLineEdit::textChanged, parent, [p, id](QString b) { p->set(id, b); }); - QLabel* label = new QLabel(description); + QLabel *label = new QLabel(description); label->setStyleSheet("font-weight: bold"); layout->addWidget(label); @@ -33,7 +35,9 @@ QWidget* PreferencesHelper::addPreferenceEdit(Preferences *p, QString id, QStrin return widget; } -QWidget* PreferencesHelper::addPreferenceComboList(Preferences *p, QString id, QString description, QList> options, QObject *parent) { +QWidget *PreferencesHelper::addPreferenceComboList(Preferences *p, QString id, QString description, + QList> options, QObject *parent) +{ QWidget *w = new QWidget(); QHBoxLayout *lay = new QHBoxLayout(); lay->setMargin(0); @@ -42,31 +46,32 @@ QWidget* PreferencesHelper::addPreferenceComboList(Preferences *p, QString id, Q w->setLayout(lay); QLabel *lab = new QLabel(description); lab->setStyleSheet("font-weight: bold;"); - QSpacerItem *space = new QSpacerItem(20,20,QSizePolicy::Preferred,QSizePolicy::Preferred); + QSpacerItem *space = new QSpacerItem(20, 20, QSizePolicy::Preferred, QSizePolicy::Preferred); QString pref1Val; - QComboBox *pref = new QComboBox(); - for( auto option : options) { - pref->addItem(option.first,option.second); - if(option.second == p->get(id) ) { + for(auto option : options) { + pref->addItem(option.first, option.second); + if(option.second == p->get(id)) { pref1Val = option.first; } } pref->setCurrentText(pref1Val); - lay->addWidget(lab,1); + lay->addWidget(lab, 1); lay->addSpacerItem(space); - lay->addWidget(pref,1); + lay->addWidget(pref, 1); - parent->connect(pref,qOverload(&QComboBox::currentIndexChanged),parent,[pref, p,id](int idx) { + parent->connect(pref, qOverload(&QComboBox::currentIndexChanged), parent, [pref, p, id](int idx) { auto data = pref->itemData(idx); - p->set(id,data); + p->set(id, data); }); return w; } -QWidget* PreferencesHelper::addPreferenceCombo(Preferences *p, QString id, QString description, QStringList options, QObject *parent) { +QWidget *PreferencesHelper::addPreferenceCombo(Preferences *p, QString id, QString description, QStringList options, + QObject *parent) +{ QWidget *w = new QWidget(); QHBoxLayout *lay = new QHBoxLayout(); lay->setSpacing(0); @@ -74,15 +79,15 @@ QWidget* PreferencesHelper::addPreferenceCombo(Preferences *p, QString id, QStri w->setLayout(lay); QLabel *lab = new QLabel(description); lab->setStyleSheet("font-weight: bold;"); - QSpacerItem *space = new QSpacerItem(20,20,QSizePolicy::Preferred,QSizePolicy::Preferred); + QSpacerItem *space = new QSpacerItem(20, 20, QSizePolicy::Preferred, QSizePolicy::Preferred); QString pref1Val = p->get(id).toString(); QComboBox *pref = new QComboBox(); pref->addItems(options); pref->setCurrentText(pref1Val); - lay->addWidget(lab,1); + lay->addWidget(lab, 1); lay->addSpacerItem(space); - lay->addWidget(pref,1); + lay->addWidget(pref, 1); - parent->connect(pref,&QComboBox::currentTextChanged,parent,[p,id](QString b) { p->set(id,b);}); + parent->connect(pref, &QComboBox::currentTextChanged, parent, [p, id](QString b) { p->set(id, b); }); return w; } diff --git a/pluginbase/src/resourcemanager.cpp b/pluginbase/src/resourcemanager.cpp index 14926b7a0b..b57c3ac669 100644 --- a/pluginbase/src/resourcemanager.cpp +++ b/pluginbase/src/resourcemanager.cpp @@ -1,20 +1,17 @@ #include "resourcemanager.h" + #include #include -Q_LOGGING_CATEGORY(CAT_RESOURCEMANAGER,"ResourceManager"); +Q_LOGGING_CATEGORY(CAT_RESOURCEMANAGER, "ResourceManager"); using namespace scopy; +ResourceManager *ResourceManager::pinstance_{nullptr}; +ResourceManager::ResourceManager(QObject *parent) + : QObject(parent) +{} -ResourceManager* ResourceManager::pinstance_{nullptr}; -ResourceManager::ResourceManager(QObject *parent) : QObject(parent) -{ - -} - -ResourceManager::~ResourceManager() { - -} +ResourceManager::~ResourceManager() {} bool ResourceManager::open(QString resource, ResourceUser *res, bool force) { @@ -22,17 +19,18 @@ bool ResourceManager::open(QString resource, ResourceUser *res, bool force) if(rm->map.contains(resource)) { if(force) { rm->map[resource]->stop(); - rm->map.insert(resource,res); + rm->map.insert(resource, res); return true; } } else { - rm->map.insert(resource,res); + rm->map.insert(resource, res); return true; } return false; } -void ResourceManager::close(QString resource) { +void ResourceManager::close(QString resource) +{ ResourceManager *rm = ResourceManager::GetInstance(); if(rm->map.contains(resource)) { rm->map.remove(resource); @@ -41,14 +39,10 @@ void ResourceManager::close(QString resource) { ResourceManager *ResourceManager::GetInstance() { - if (pinstance_ == nullptr) - { + if(pinstance_ == nullptr) { pinstance_ = new ResourceManager(QApplication::instance()); // singleton has the app as parent } return pinstance_; } - - - #include "moc_resourcemanager.cpp" diff --git a/pluginbase/src/scopyjs.cpp b/pluginbase/src/scopyjs.cpp index 6ecfc0f81a..6fe1c49612 100644 --- a/pluginbase/src/scopyjs.cpp +++ b/pluginbase/src/scopyjs.cpp @@ -19,18 +19,19 @@ */ #include "scopyjs.h" + #include "jsfileio.h" -#include #include - +#include #include #include -#include #include -#include -#include + #include +#include +#include +#include Q_LOGGING_CATEGORY(CAT_JS, "Scopy_JS") @@ -39,49 +40,42 @@ using namespace scopy; QLoggingCategory::CategoryFilter ScopyJS::oldCategoryFilter{nullptr}; -ScopyJS* ScopyJS::pinstance_{nullptr}; -ScopyJS::ScopyJS(QObject *parent) : QObject(parent) { -} - -ScopyJS::~ScopyJS() -{ +ScopyJS *ScopyJS::pinstance_{nullptr}; +ScopyJS::ScopyJS(QObject *parent) + : QObject(parent) +{} -} +ScopyJS::~ScopyJS() {} ScopyJS *ScopyJS::GetInstance() { - if (pinstance_ == nullptr) - { + if(pinstance_ == nullptr) { pinstance_ = new ScopyJS(QApplication::instance()); // singleton has the app as parent pinstance_->init(); } return pinstance_; } -void ScopyJS::exit() -{ - QApplication::closeAllWindows(); -} +void ScopyJS::exit() { QApplication::closeAllWindows(); } -void ScopyJS::init() { +void ScopyJS::init() +{ QJSValue js_obj = m_engine.newQObject(this); auto meta = metaObject(); input = ""; - for (int i = meta->methodOffset(); - i < meta->methodCount(); i++) { + for(int i = meta->methodOffset(); i < meta->methodCount(); i++) { QString name(meta->method(i).name()); m_engine.globalObject().setProperty(name, js_obj.property(name)); } m_engine.globalObject().setProperty("inspect()", - m_engine.evaluate("(function(o) { for (each in o) { print(each); } })")); + m_engine.evaluate("(function(o) { for (each in o) { print(each); } })")); m_engine.installExtensions(QJSEngine::ConsoleExtension); - m_engine.globalObject().setProperty("fileIO", - m_engine.newQObject(new JsFileIo(this))); + m_engine.globalObject().setProperty("fileIO", m_engine.newQObject(new JsFileIo(this))); - if (isatty(STDIN_FILENO)) { + if(isatty(STDIN_FILENO)) { // verify if stdin is a true TTY - prevents QtCreator Application output from flooding the application // notifier->setEnabled(false); notifier = new QSocketNotifier(STDIN_FILENO, QSocketNotifier::Read); @@ -89,13 +83,10 @@ void ScopyJS::init() { } } - void ScopyJS::returnToApplication() { bool done; - connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit,[&done](){ - done=true; - }); + connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, [&done]() { done = true; }); while(!done) { QCoreApplication::processEvents(); @@ -105,79 +96,60 @@ void ScopyJS::returnToApplication() void ScopyJS::suppressScopyMessages(bool b) { - if (b) { + if(b) { QLoggingCategory::installFilter(jsCategoryFilter); } else { QLoggingCategory::installFilter(oldCategoryFilter); } } -QJSEngine *ScopyJS::engine() -{ - return &m_engine; -} +QJSEngine *ScopyJS::engine() { return &m_engine; } -void ScopyJS::registerApi(ApiObject *obj) -{ - registerApi(obj,m_engine.globalObject()); -} +void ScopyJS::registerApi(ApiObject *obj) { registerApi(obj, m_engine.globalObject()); } -void ScopyJS::unregisterApi(ApiObject *obj) -{ - unregisterApi(obj,m_engine.globalObject()); -} +void ScopyJS::unregisterApi(ApiObject *obj) { unregisterApi(obj, m_engine.globalObject()); } void ScopyJS::registerApi(ApiObject *obj, QJSValue parentObj) { auto newjsobj = m_engine.newQObject(obj); parentObj.setProperty(obj->objectName(), newjsobj); -// auto meta = obj->metaObject(); - -// for (int i = meta->propertyOffset(); -// i < meta->propertyCount(); i++) { -// auto prop = meta->property(i); + // auto meta = obj->metaObject(); -// auto data = prop.read(obj); -// if (data.canConvert()) { -// registerApi(data.value(),newjsobj); -// } -// } + // for (int i = meta->propertyOffset(); + // i < meta->propertyCount(); i++) { + // auto prop = meta->property(i); -// QList list = obj->findChildren(QString(),Qt::FindDirectChildrenOnly); -// for(auto &&apiobj : list) { -// registerApi(apiobj,newjsobj); -// } + // auto data = prop.read(obj); + // if (data.canConvert()) { + // registerApi(data.value(),newjsobj); + // } + // } + // QList list = obj->findChildren(QString(),Qt::FindDirectChildrenOnly); + // for(auto &&apiobj : list) { + // registerApi(apiobj,newjsobj); + // } } -void ScopyJS::unregisterApi(ApiObject *obj, QJSValue parentObj) -{ - parentObj.deleteProperty(obj->objectName()); -} +void ScopyJS::unregisterApi(ApiObject *obj, QJSValue parentObj) { parentObj.deleteProperty(obj->objectName()); } -void ScopyJS::sleep(unsigned long s) -{ - msleep(s * 1000); -} +void ScopyJS::sleep(unsigned long s) { msleep(s * 1000); } void ScopyJS::msleep(unsigned long ms) { QElapsedTimer timer; timer.start(); - while (!timer.hasExpired(ms)) { + while(!timer.hasExpired(ms)) { QCoreApplication::processEvents(); QThread::msleep(1); } } -void ScopyJS::printToConsole(const QString& text) -{ - cout << text.toStdString() << std::endl; -} +void ScopyJS::printToConsole(const QString &text) { cout << text.toStdString() << std::endl; } -QString ScopyJS::readFromConsole(const QString& request) +QString ScopyJS::readFromConsole(const QString &request) { done = false; input = ""; @@ -187,13 +159,13 @@ QString ScopyJS::readFromConsole(const QString& request) input = watcher.result(); done = true; }); - future = QtConcurrent::run(std::bind(&ScopyJS::readInput,this)); + future = QtConcurrent::run(std::bind(&ScopyJS::readInput, this)); watcher.setFuture(future); do { QCoreApplication::processEvents(); QThread::msleep(10); - } while (!done && (input == "")); + } while(!done && (input == "")); return input; } @@ -213,16 +185,16 @@ void ScopyJS::hasText() QString str = in.readLine(); js_cmd.append(str); - qWarning()<setEnabled(QtDebugMsg, false); @@ -248,7 +220,7 @@ void ScopyJS::jsCategoryFilter(QLoggingCategory *category) category->setEnabled(QtCriticalMsg, false); category->setEnabled(QtFatalMsg, false); - if (qstrcmp(category->categoryName(), "Scopy_JS") == 0) { + if(qstrcmp(category->categoryName(), "Scopy_JS") == 0) { category->setEnabled(QtDebugMsg, true); category->setEnabled(QtInfoMsg, true); category->setEnabled(QtWarningMsg, true); @@ -256,7 +228,7 @@ void ScopyJS::jsCategoryFilter(QLoggingCategory *category) category->setEnabled(QtFatalMsg, true); } - if (qstrcmp(category->categoryName(), "Scopy_API") == 0) { + if(qstrcmp(category->categoryName(), "Scopy_API") == 0) { category->setEnabled(QtWarningMsg, true); } } diff --git a/pluginbase/src/versionchecker.cpp b/pluginbase/src/versionchecker.cpp index 54ca9d3ffd..fca824f925 100644 --- a/pluginbase/src/versionchecker.cpp +++ b/pluginbase/src/versionchecker.cpp @@ -1,63 +1,65 @@ #include "versionchecker.h" + #include -#include #include #include -#include #include +#include #include -#include -#include - +#include #include +#include +#include + Q_LOGGING_CATEGORY(CAT_VERSION, "VersionCache") using namespace scopy; -VersionChecker* VersionChecker::pinstance_{nullptr}; +VersionChecker *VersionChecker::pinstance_{nullptr}; -VersionChecker::VersionChecker(QObject *parent) : QObject(nullptr), - m_nam(nullptr), - m_ttl(10), - m_cacheFilePath(scopy::config::settingsFolderPath() + "/version.json") +VersionChecker::VersionChecker(QObject *parent) + : QObject(nullptr) + , m_nam(nullptr) + , m_ttl(10) + , m_cacheFilePath(scopy::config::settingsFolderPath() + "/version.json") { currentState = NOT_INIT; } -VersionChecker::~VersionChecker() -{ -} +VersionChecker::~VersionChecker() {} -void VersionChecker::init() { +void VersionChecker::init() +{ bool checkOnline = Preferences::get("general_check_online_version").toBool(); - if (!checkOnline) { + if(!checkOnline) { qInfo(CAT_VERSION) << "update checks disabled"; return; } currentState = IN_PROGRESS; - if (cacheOutdated()) { + if(cacheOutdated()) { pullNewCache(); - } else { + } else { readCache(); } } VersionChecker *VersionChecker::GetInstance() { - if (pinstance_ == nullptr) - { + if(pinstance_ == nullptr) { pinstance_ = new VersionChecker(QApplication::instance()); // singleton has the app as parent connect(pinstance_, &VersionChecker::cacheUpdated, pinstance_, &VersionChecker::updateSubscriptions); - connect(pinstance_, &VersionChecker::addedNewSubscription, pinstance_, &VersionChecker::updateSubscriptions); + connect(pinstance_, &VersionChecker::addedNewSubscription, pinstance_, + &VersionChecker::updateSubscriptions); pinstance_->init(); } return pinstance_; } -void VersionChecker::readCache() { +void VersionChecker::readCache() +{ qInfo(CAT_VERSION) << "Reading cache."; QFile f(m_cacheFilePath); @@ -67,49 +69,52 @@ void VersionChecker::readCache() { f.close(); currentState = DONE; Q_EMIT cacheUpdated(); - } -bool VersionChecker::cacheOutdated() { +bool VersionChecker::cacheOutdated() +{ QFileInfo fi(m_cacheFilePath); - if (fi.exists()) { + if(fi.exists()) { return fi.fileTime(QFile::FileModificationTime).addDays(1) < QDateTime::currentDateTime(); } return true; } -void VersionChecker::pullNewCache() { +void VersionChecker::pullNewCache() +{ qInfo(CAT_VERSION) << "Updating cache."; if(!m_nam) m_nam = new QNetworkAccessManager(this); - // we might receive ssl errors saying that the QNetworkAccessManager does not 'like' the peer certificate, in which - // case we ignore these ssl errors for the current ssl/tls session. QNetworkAccessManager::sslErrors is called - // before QNetworkAccessManager::finished. - connect(m_nam, &QNetworkAccessManager::sslErrors, this, [] (QNetworkReply *reply, const QList &errors) { - qDebug(CAT_VERSION) << "Ignoring ssl errors:" << errors; - reply->ignoreSslErrors({QSslError::NoPeerCertificate}); - }); + // we might receive ssl errors saying that the QNetworkAccessManager does not 'like' the peer certificate, in + // which case we ignore these ssl errors for the current ssl/tls session. QNetworkAccessManager::sslErrors is + // called before QNetworkAccessManager::finished. + connect(m_nam, &QNetworkAccessManager::sslErrors, this, + [](QNetworkReply *reply, const QList &errors) { + qDebug(CAT_VERSION) << "Ignoring ssl errors:" << errors; + reply->ignoreSslErrors({QSslError::NoPeerCertificate}); + }); - connect(m_nam, &QNetworkAccessManager::finished, this, [this] (QNetworkReply *r){ + connect(m_nam, &QNetworkAccessManager::finished, this, [this](QNetworkReply *r) { int statusCode = r->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); qDebug(CAT_VERSION) << "Status code:" << QVariant(statusCode).toString(); - if (statusCode == 301 && m_ttl > 0) { // REDIRECT + if(statusCode == 301 && m_ttl > 0) { // REDIRECT --m_ttl; QUrl newUrl = r->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); - qDebug(CAT_VERSION) << "Redirected from" << r->request().url().toString() << "to" << newUrl.toString(); + qDebug(CAT_VERSION) + << "Redirected from" << r->request().url().toString() << "to" << newUrl.toString(); QNetworkRequest newRequest(newUrl); m_nam->get(newRequest); return; } // 200 -> OK, 304 -> NOT MODIFIED - if (statusCode != 200 && statusCode != 304) { - qWarning(CAT_VERSION) << "Reply errors:" << r->errorString(); + if(statusCode != 200 && statusCode != 304) { + qWarning(CAT_VERSION) << "Reply errors:" << r->errorString(); currentState = NOT_INIT; return; } @@ -127,27 +132,28 @@ void VersionChecker::pullNewCache() { currentState = DONE; Q_EMIT cacheUpdated(); - }); + }); m_nam->get(QNetworkRequest(m_url)); } -void VersionChecker::updateSubscriptions() { - switch (currentState) { - case NOT_INIT: - qWarning(CAT_VERSION) << "VersionChecker is not initialized."; - break; - case IN_PROGRESS: - qDebug(CAT_VERSION) << "VersionChecker is in progress"; - break; - case DONE: - for (auto& function: qAsConst(m_subscriptions)) { - std::invoke(function, m_cache); - } - - // the functions that were called should not be called again, in case a new class subscribes - m_subscriptions.clear(); - break; +void VersionChecker::updateSubscriptions() +{ + switch(currentState) { + case NOT_INIT: + qWarning(CAT_VERSION) << "VersionChecker is not initialized."; + break; + case IN_PROGRESS: + qDebug(CAT_VERSION) << "VersionChecker is in progress"; + break; + case DONE: + for(auto &function : qAsConst(m_subscriptions)) { + std::invoke(function, m_cache); + } + + // the functions that were called should not be called again, in case a new class subscribes + m_subscriptions.clear(); + break; } } diff --git a/pluginbase/test/CMakeLists.txt b/pluginbase/test/CMakeLists.txt index b5e5dff743..af5ae1926b 100644 --- a/pluginbase/test/CMakeLists.txt +++ b/pluginbase/test/CMakeLists.txt @@ -2,7 +2,4 @@ cmake_minimum_required(VERSION 3.5) include(ScopyTest) -SETUP_SCOPY_TESTS( - preferences -) - +setup_scopy_tests(preferences) diff --git a/pluginbase/test/tst_preferences.cpp b/pluginbase/test/tst_preferences.cpp index cfeacd4f21..b682b0e41e 100644 --- a/pluginbase/test/tst_preferences.cpp +++ b/pluginbase/test/tst_preferences.cpp @@ -1,7 +1,8 @@ -#include +#include #include +#include + #include -#include using namespace scopy; @@ -16,15 +17,15 @@ private Q_SLOTS: QSettings *s; }; -const QString filePath = QDir::currentPath()+"Pref.ini"; +const QString filePath = QDir::currentPath() + "Pref.ini"; void TST_Preferences::initPreferences() { Preferences *p = Preferences::GetInstance(); p->setPreferencesFilename(filePath); - p->init("test","true"); + p->init("test", "true"); QString t = p->get("test").toString(); - QVERIFY("true"==t); + QVERIFY("true" == t); p->save(); p->clear(); } @@ -35,10 +36,9 @@ void TST_Preferences::getPreferences() p->setPreferencesFilename(filePath); p->load(); QString t = p->get("test").toString(); - QVERIFY("true"==t); + QVERIFY("true" == t); } - QTEST_MAIN(TST_Preferences) #include "tst_preferences.moc" diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt index 95f514bad9..b5090af7ac 100644 --- a/plugins/CMakeLists.txt +++ b/plugins/CMakeLists.txt @@ -13,59 +13,58 @@ option(ENABLE_PLUGIN_DATALOGGER "Enable datalogger plugin" OFF) option(ENABLE_PLUGIN_ADC "Enable ADC plugin" ON) if(ENABLE_PLUGIN_TEST) - add_subdirectory(guitestplugin) - list(APPEND PLUGINS ${PLUGIN_NAME}) - add_subdirectory(testplugin) - list(APPEND PLUGINS ${PLUGIN_NAME}) - add_subdirectory(testplugin2) - list(APPEND PLUGINS ${PLUGIN_NAME}) - add_subdirectory(bareminimumplugin) - list(APPEND PLUGINS ${PLUGIN_NAME}) + add_subdirectory(guitestplugin) + list(APPEND PLUGINS ${PLUGIN_NAME}) + add_subdirectory(testplugin) + list(APPEND PLUGINS ${PLUGIN_NAME}) + add_subdirectory(testplugin2) + list(APPEND PLUGINS ${PLUGIN_NAME}) + add_subdirectory(bareminimumplugin) + list(APPEND PLUGINS ${PLUGIN_NAME}) endif() if(ENABLE_PLUGIN_ADC) - add_subdirectory(adc) - list(APPEND PLUGINS ${PLUGIN_NAME}) + add_subdirectory(adc) + list(APPEND PLUGINS ${PLUGIN_NAME}) endif() if(ENABLE_PLUGIN_SWIOT) - add_subdirectory(swiot) - list(APPEND PLUGINS ${PLUGIN_NAME}) + add_subdirectory(swiot) + list(APPEND PLUGINS ${PLUGIN_NAME}) endif() if(ENABLE_PLUGIN_M2K) - if(NOT WITH_PYTHON) - message(STATUS "Python is disabled or not found, M2K plugin disabled") - endif() + if(NOT WITH_PYTHON) + message(STATUS "Python is disabled or not found, M2K plugin disabled") + endif() - if(NOT WITH_SIGROK) - message(STATUS "Libsigrokdecode is disabled or not found, M2K plugin disabled") - endif() + if(NOT WITH_SIGROK) + message(STATUS "Libsigrokdecode is disabled or not found, M2K plugin disabled") + endif() - if(WITH_SIGROK AND WITH_PYTHON) - add_subdirectory(m2k) - list(APPEND PLUGINS ${PLUGIN_NAME}) - endif() + if(WITH_SIGROK AND WITH_PYTHON) + add_subdirectory(m2k) + list(APPEND PLUGINS ${PLUGIN_NAME}) + endif() endif() if(ENABLE_PLUGIN_REGMAP) - add_subdirectory(regmap) - list(APPEND PLUGINS ${PLUGIN_NAME}) + add_subdirectory(regmap) + list(APPEND PLUGINS ${PLUGIN_NAME}) endif() if(ENABLE_PLUGIN_DEBUGGER) - add_subdirectory(debugger) -list(APPEND PLUGINS ${PLUGIN_NAME}) + add_subdirectory(debugger) + list(APPEND PLUGINS ${PLUGIN_NAME}) endif() if(ENABLE_PLUGIN_DATALOGGER) - add_subdirectory(datalogger) - list(APPEND PLUGINS ${PLUGIN_NAME}) + add_subdirectory(datalogger) + list(APPEND PLUGINS ${PLUGIN_NAME}) endif() message(STATUS "Building plugins:" ${PLUGINS}) -install(TARGETS ${PLUGINS} - LIBRARY DESTINATION ${SCOPY_PLUGIN_INSTALL_PATH} +install(TARGETS ${PLUGINS} LIBRARY DESTINATION ${SCOPY_PLUGIN_INSTALL_PATH} RUNTIME DESTINATION ${SCOPY_PLUGIN_INSTALL_PATH} ) diff --git a/plugins/adc/CMakeLists.txt b/plugins/adc/CMakeLists.txt index 2595a208fe..273227fdb4 100644 --- a/plugins/adc/CMakeLists.txt +++ b/plugins/adc/CMakeLists.txt @@ -8,8 +8,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -24,48 +23,43 @@ set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_CXX_VISIBILITY_PRESET hidden) set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) -FILE(GLOB SRC_LIST src/*.cpp src/*.cc) -FILE(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) -FILE(GLOB UI_LIST ui/*.ui) +file(GLOB SRC_LIST src/*.cpp src/*.cc) +file(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) +file(GLOB UI_LIST ui/*.ui) set(ENABLE_TESTING ON) if(ENABLE_TESTING) - add_subdirectory(test) + add_subdirectory(test) endif() -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} -) -find_package(Qt${QT_VERSION_MAJOR} COMPONENTS REQUIRED Widgets Core ) - +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) +find_package(Qt${QT_VERSION_MAJOR} COMPONENTS REQUIRED Widgets Core) if(NOT "${SCOPY_PLUGIN_BUILD_PATH}" STREQUAL "") - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) endif() qt_add_resources(PROJECT_RESOURCES res/resources.qrc) -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} - ${PROJECT_RESOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES} ${PROJECT_RESOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}) target_include_directories(${PROJECT_NAME} PUBLIC scopy-pluginbase scopy-gui) -target_link_libraries(${PROJECT_NAME} PUBLIC Qt::Widgets Qt::Core - scopy-pluginbase - scopy-gui - scopy-iioutil - scopy-gr-util +target_link_libraries( + ${PROJECT_NAME} + PUBLIC Qt::Widgets + Qt::Core + scopy-pluginbase + scopy-gui + scopy-iioutil + scopy-gr-util ) set(PLUGIN_NAME ${PROJECT_NAME} PARENT_SCOPE) -install(TARGETS ${PROJECT_NAME} - RUNTIME - DESTINATION ${SCOPY_PLUGIN_INSTALL_DIR}) +install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION ${SCOPY_PLUGIN_INSTALL_DIR}) diff --git a/plugins/adc/include/adcplugin/adcplugin.h b/plugins/adc/include/adcplugin/adcplugin.h index d52d391bc4..2af36d7f3d 100644 --- a/plugins/adc/include/adcplugin/adcplugin.h +++ b/plugins/adc/include/adcplugin/adcplugin.h @@ -3,26 +3,26 @@ #define SCOPY_PLUGIN_NAME ADCPlugin -#include -#include -#include -#include #include "scopy-adcplugin_export.h" -#include + #include -#include -#include +#include +#include +#include + +#include #include #include +#include #include -#include - +#include #include #include -#include -#include - +#include +#include +#include +#include namespace scopy { using namespace grutil; @@ -41,64 +41,51 @@ using namespace grutil; // fft sweep addon // waterfall plot addon - - -class SCOPY_ADCPLUGIN_EXPORT PlotProxy { +class SCOPY_ADCPLUGIN_EXPORT PlotProxy +{ public: - virtual ToolAddon* getPlotAddon() = 0; - virtual ToolAddon* getPlotSettings() = 0; - virtual QList getDeviceAddons() = 0; - virtual QList getChannelAddons() = 0; - virtual QList getAddons() = 0; + virtual ToolAddon *getPlotAddon() = 0; + virtual ToolAddon *getPlotSettings() = 0; + virtual QList getDeviceAddons() = 0; + virtual QList getChannelAddons() = 0; + virtual QList getAddons() = 0; virtual void init() = 0; - }; -class SCOPY_ADCPLUGIN_EXPORT GRTimePlotProxy : public QObject, public PlotProxy { +class SCOPY_ADCPLUGIN_EXPORT GRTimePlotProxy : public QObject, public PlotProxy +{ Q_OBJECT public: - GRTimePlotProxy(QObject *parent = nullptr) : QObject(parent) { } + GRTimePlotProxy(QObject *parent = nullptr) + : QObject(parent) + {} ~GRTimePlotProxy() {} - void setPlotAddon(GRTimePlotAddon *p, GRTimePlotAddonSettings *s) { + void setPlotAddon(GRTimePlotAddon *p, GRTimePlotAddonSettings *s) + { this->plotAddon = p; this->plotSettingsAddon = s; } - void addDeviceAddon(ToolAddon* d) { - deviceAddons.append(d); - } + void addDeviceAddon(ToolAddon *d) { deviceAddons.append(d); } - void removeDeviceAddon(ToolAddon* d) { - deviceAddons.removeAll(d); - } + void removeDeviceAddon(ToolAddon *d) { deviceAddons.removeAll(d); } - void addChannelAddon(ToolAddon *c) { - channelAddons.append(c); - } + void addChannelAddon(ToolAddon *c) { channelAddons.append(c); } - void removeChannelAddon(ToolAddon *c) { - channelAddons.removeAll(c); - } + void removeChannelAddon(ToolAddon *c) { channelAddons.removeAll(c); } - ToolAddon* getPlotAddon() override { - return plotAddon; - } + ToolAddon *getPlotAddon() override { return plotAddon; } - ToolAddon* getPlotSettings() override { - return plotSettingsAddon; - } + ToolAddon *getPlotSettings() override { return plotSettingsAddon; } - QList getDeviceAddons() override { - return deviceAddons; - } + QList getDeviceAddons() override { return deviceAddons; } - QList getChannelAddons() override { - return channelAddons; - } + QList getChannelAddons() override { return channelAddons; } - QList getAddons() override { - QList addons; + QList getAddons() override + { + QList addons; addons.append(channelAddons); addons.append(deviceAddons); addons.append(plotSettingsAddon); @@ -106,35 +93,37 @@ class SCOPY_ADCPLUGIN_EXPORT GRTimePlotProxy : public QObject, public PlotProxy return addons; } - void init() override { + void init() override + { for(auto *addon : getAddons()) { - if(dynamic_cast(addon)) { - auto GRAddon = dynamic_cast(addon); - connect(topBlock,&GRTopBlock::aboutToStart, this, [=](){GRAddon->preFlowStart();}); - connect(topBlock,&GRTopBlock::started, this, [=](){GRAddon->postFlowStart();}); - connect(topBlock,&GRTopBlock::aboutToStop, this, [=](){GRAddon->preFlowStop();}); - connect(topBlock,&GRTopBlock::stopped, this, [=](){GRAddon->postFlowStop();}); - connect(topBlock, &GRTopBlock::aboutToBuild, this,[=](){GRAddon->preFlowBuild();}); - connect(topBlock, &GRTopBlock::builtSignalPaths, this,[=](){GRAddon->postFlowBuild();}); - connect(topBlock, &GRTopBlock::aboutToTeardown, this,[=](){GRAddon->preFlowTeardown();}); - connect(topBlock, &GRTopBlock::teardownSignalPaths, this,[=](){GRAddon->postFlowTeardown();}); + if(dynamic_cast(addon)) { + auto GRAddon = dynamic_cast(addon); + connect(topBlock, &GRTopBlock::aboutToStart, this, [=]() { GRAddon->preFlowStart(); }); + connect(topBlock, &GRTopBlock::started, this, [=]() { GRAddon->postFlowStart(); }); + connect(topBlock, &GRTopBlock::aboutToStop, this, [=]() { GRAddon->preFlowStop(); }); + connect(topBlock, &GRTopBlock::stopped, this, [=]() { GRAddon->postFlowStop(); }); + connect(topBlock, &GRTopBlock::aboutToBuild, this, [=]() { GRAddon->preFlowBuild(); }); + connect(topBlock, &GRTopBlock::builtSignalPaths, this, + [=]() { GRAddon->postFlowBuild(); }); + connect(topBlock, &GRTopBlock::aboutToTeardown, this, + [=]() { GRAddon->preFlowTeardown(); }); + connect(topBlock, &GRTopBlock::teardownSignalPaths, this, + [=]() { GRAddon->postFlowTeardown(); }); } } } - QString getPrefix() { return prefix; } - void setPrefix(QString p) { prefix = p;} - GRTopBlock *getTopBlock() const { return topBlock; } - void setTopBlock(GRTopBlock *newTopBlock) { topBlock = newTopBlock; } + void setPrefix(QString p) { prefix = p; } + GRTopBlock *getTopBlock() const { return topBlock; } + void setTopBlock(GRTopBlock *newTopBlock) { topBlock = newTopBlock; } private: - GRTimePlotAddon *plotAddon; GRTimePlotAddonSettings *plotSettingsAddon; - QList deviceAddons; - QList channelAddons; - GRTopBlock* topBlock; + QList deviceAddons; + QList channelAddons; + GRTopBlock *topBlock; QString prefix; }; @@ -164,10 +153,10 @@ class SCOPY_ADCPLUGIN_EXPORT ADCPlugin : public QObject, public PluginBase iio_context *m_ctx; QWidget *time; QLineEdit *edit; - PlotProxy* createRecipe(iio_context *ctx); + PlotProxy *createRecipe(iio_context *ctx); GRTimePlotProxy *recipe; }; -} +} // namespace scopy #endif // TESTPLUGIN_H diff --git a/plugins/adc/src/adcinstrument.cpp b/plugins/adc/src/adcinstrument.cpp index 6cf2ad6821..8d158d72a8 100644 --- a/plugins/adc/src/adcinstrument.cpp +++ b/plugins/adc/src/adcinstrument.cpp @@ -1,16 +1,19 @@ #include "adcinstrument.h" -#include +#include "gui/widgets/measurementsettings.h" + +#include +#include #include +#include #include -#include -#include -#include "gui/widgets/measurementsettings.h" using namespace scopy; using namespace scopy::grutil; -AdcInstrument::AdcInstrument(PlotProxy* proxy, QWidget *parent) : QWidget(parent), proxy(proxy) +AdcInstrument::AdcInstrument(PlotProxy *proxy, QWidget *parent) + : QWidget(parent) + , proxy(proxy) { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); QHBoxLayout *lay = new QHBoxLayout(this); @@ -29,8 +32,8 @@ AdcInstrument::AdcInstrument(PlotProxy* proxy, QWidget *parent) : QWidget(parent tool->setTopContainerHeight(100); tool->setBottomContainerHeight(90); - openLastMenuBtn = new OpenLastMenuBtn(dynamic_cast(tool->rightContainer()),true,this); - rightMenuBtnGrp = dynamic_cast(openLastMenuBtn)->getButtonGroup(); + openLastMenuBtn = new OpenLastMenuBtn(dynamic_cast(tool->rightContainer()), true, this); + rightMenuBtnGrp = dynamic_cast(openLastMenuBtn)->getButtonGroup(); tool->openBottomContainerHelper(false); tool->openTopContainerHelper(false); @@ -44,10 +47,10 @@ AdcInstrument::AdcInstrument(PlotProxy* proxy, QWidget *parent) : QWidget(parent channelsBtn = new MenuControlButton(this); setupChannelsButtonHelper(channelsBtn); - plotAddon = dynamic_cast(proxy->getPlotAddon()); + plotAddon = dynamic_cast(proxy->getPlotAddon()); tool->addWidgetToCentralContainerHelper(plotAddon->getWidget()); - plotAddonSettings = dynamic_cast(proxy->getPlotSettings()); + plotAddonSettings = dynamic_cast(proxy->getPlotSettings()); rightMenuBtnGrp->addButton(settingsBtn); QString settingsMenuId = plotAddonSettings->getName() + QString(uuid++); @@ -74,7 +77,7 @@ AdcInstrument::AdcInstrument(PlotProxy* proxy, QWidget *parent) : QWidget(parent stats_panel = new StatsPanel(this); tool->bottomStack()->add(statsMenuId, stats_panel); - MeasurementSettings* measureSettings = new MeasurementSettings(this); + MeasurementSettings *measureSettings = new MeasurementSettings(this); HoverWidget *measurePanelManagerHover = new HoverWidget(nullptr, measure, tool); measurePanelManagerHover->setContent(measureSettings); measurePanelManagerHover->setAnchorPos(HoverPosition::HP_TOPRIGHT); @@ -83,34 +86,36 @@ AdcInstrument::AdcInstrument(PlotProxy* proxy, QWidget *parent) : QWidget(parent measurePanelManagerHover->setVisible(b); measurePanelManagerHover->raise(); }); - connect(measureSettings, &MeasurementSettings::enableMeasurementPanel, tool->topCentral(), &QWidget::setVisible); + connect(measureSettings, &MeasurementSettings::enableMeasurementPanel, tool->topCentral(), + &QWidget::setVisible); connect(measureSettings, &MeasurementSettings::enableStatsPanel, tool->bottomCentral(), &QWidget::setVisible); connect(measureSettings, &MeasurementSettings::sortMeasurements, measure_panel, &MeasurementsPanel::sort); connect(measureSettings, &MeasurementSettings::sortStats, stats_panel, &StatsPanel::sort); - tool->addWidgetToTopContainerMenuControlHelper(openLastMenuBtn,TTA_RIGHT); - tool->addWidgetToTopContainerMenuControlHelper(settingsBtn,TTA_LEFT); + tool->addWidgetToTopContainerMenuControlHelper(openLastMenuBtn, TTA_RIGHT); + tool->addWidgetToTopContainerMenuControlHelper(settingsBtn, TTA_LEFT); - tool->addWidgetToTopContainerHelper(runBtn,TTA_RIGHT); - tool->addWidgetToTopContainerHelper(singleBtn,TTA_RIGHT); + tool->addWidgetToTopContainerHelper(runBtn, TTA_RIGHT); + tool->addWidgetToTopContainerHelper(singleBtn, TTA_RIGHT); - tool->addWidgetToTopContainerHelper(infoBtn,TTA_LEFT); - tool->addWidgetToTopContainerHelper(printBtn,TTA_LEFT); + tool->addWidgetToTopContainerHelper(infoBtn, TTA_LEFT); + tool->addWidgetToTopContainerHelper(printBtn, TTA_LEFT); tool->addWidgetToBottomContainerHelper(channelsBtn, TTA_LEFT); tool->addWidgetToBottomContainerHelper(cursor, TTA_RIGHT); tool->addWidgetToBottomContainerHelper(measure, TTA_RIGHT); - connect(channelsBtn, &QPushButton::toggled, dynamic_cast(tool->leftContainer()), &MenuHAnim::toggleMenu); + connect(channelsBtn, &QPushButton::toggled, dynamic_cast(tool->leftContainer()), + &MenuHAnim::toggleMenu); VerticalChannelManager *vcm = new VerticalChannelManager(this); tool->leftStack()->add(verticalChannelManagerId, vcm); channelGroup = new QButtonGroup(this); - for(auto d: proxy->getDeviceAddons()) { - GRDeviceAddon *dev = dynamic_cast(d); + for(auto d : proxy->getDeviceAddons()) { + GRDeviceAddon *dev = dynamic_cast(d); if(!dev) return; CollapsableMenuControlButton *devBtn = new CollapsableMenuControlButton(this); @@ -126,7 +131,7 @@ AdcInstrument::AdcInstrument(PlotProxy* proxy, QWidget *parent) : QWidget(parent }); vcm->add(devBtn); - for(GRTimeChannelAddon* ch : dev->getRegisteredChannels()) { + for(GRTimeChannelAddon *ch : dev->getRegisteredChannels()) { MenuControlButton *btn = new MenuControlButton(devBtn); devBtn->add(btn); channelGroup->addButton(btn); @@ -136,10 +141,11 @@ AdcInstrument::AdcInstrument(PlotProxy* proxy, QWidget *parent) : QWidget(parent channelStack->add(id, ch->getWidget()); - connect(btn, &QAbstractButton::clicked, this, [=](bool b){ + connect(btn, &QAbstractButton::clicked, this, [=](bool b) { if(b) { if(!channelsBtn->button()->isChecked()) { - // Workaround because QButtonGroup and setChecked do not interact programatically + // Workaround because QButtonGroup and setChecked do not interact + // programatically channelsBtn->button()->animateClick(1); } @@ -148,22 +154,25 @@ AdcInstrument::AdcInstrument(PlotProxy* proxy, QWidget *parent) : QWidget(parent } }); - connect(ch,&GRTimeChannelAddon::enableMeasurement, measure_panel, &MeasurementsPanel::addMeasurement); - connect(ch,&GRTimeChannelAddon::disableMeasurement, measure_panel, &MeasurementsPanel::removeMeasurement); - connect(measureSettings, &MeasurementSettings::toggleAllMeasurements, ch, &GRTimeChannelAddon::toggleAllMeasurement); - connect(measureSettings, &MeasurementSettings::toggleAllStats, ch, &GRTimeChannelAddon::toggleAllStats); - connect(ch,&GRTimeChannelAddon::enableStat, stats_panel, &StatsPanel::addStat); - connect(ch,&GRTimeChannelAddon::disableStat, stats_panel, &StatsPanel::removeStat); + connect(ch, &GRTimeChannelAddon::enableMeasurement, measure_panel, + &MeasurementsPanel::addMeasurement); + connect(ch, &GRTimeChannelAddon::disableMeasurement, measure_panel, + &MeasurementsPanel::removeMeasurement); + connect(measureSettings, &MeasurementSettings::toggleAllMeasurements, ch, + &GRTimeChannelAddon::toggleAllMeasurement); + connect(measureSettings, &MeasurementSettings::toggleAllStats, ch, + &GRTimeChannelAddon::toggleAllStats); + connect(ch, &GRTimeChannelAddon::enableStat, stats_panel, &StatsPanel::addStat); + connect(ch, &GRTimeChannelAddon::disableStat, stats_panel, &StatsPanel::removeStat); plotAddon->onChannelAdded(ch); plotAddonSettings->onChannelAdded(ch); - } } - connect(runBtn,&QPushButton::toggled, this, &AdcInstrument::setRunning); - connect(singleBtn,&QPushButton::toggled, plotAddon, &GRTimePlotAddon::setSingleShot); - connect(singleBtn,&QPushButton::toggled, this, &AdcInstrument::setRunning); + connect(runBtn, &QPushButton::toggled, this, &AdcInstrument::setRunning); + connect(singleBtn, &QPushButton::toggled, plotAddon, &GRTimePlotAddon::setSingleShot); + connect(singleBtn, &QPushButton::toggled, this, &AdcInstrument::setRunning); connect(this, &AdcInstrument::runningChanged, this, &AdcInstrument::run); connect(this, &AdcInstrument::runningChanged, runBtn, &QAbstractButton::setChecked); @@ -187,12 +196,10 @@ void AdcInstrument::initCursors() cursorController->getPlotCursors()->getV2Cursor()->setPosition(0); } -AdcInstrument::~AdcInstrument() -{ - deinit(); -} +AdcInstrument::~AdcInstrument() { deinit(); } -void AdcInstrument::setupCursorButtonHelper(MenuControlButton *cursor) { +void AdcInstrument::setupCursorButtonHelper(MenuControlButton *cursor) +{ cursor->setName("Cursors"); cursor->setOpenMenuChecksThis(true); cursor->setDoubleClickToOpenMenu(true); @@ -200,7 +207,8 @@ void AdcInstrument::setupCursorButtonHelper(MenuControlButton *cursor) { cursor->setCheckBoxStyle(MenuControlButton::CS_SQUARE); } -void AdcInstrument::setupMeasureButtonHelper(MenuControlButton *btn) { +void AdcInstrument::setupMeasureButtonHelper(MenuControlButton *btn) +{ btn->setName("Measure"); btn->setOpenMenuChecksThis(true); btn->setDoubleClickToOpenMenu(true); @@ -216,7 +224,8 @@ void AdcInstrument::setupDeviceMenuControlButtonHelper(MenuControlButton *devBtn devBtn->setDoubleClickToOpenMenu(true); } -void AdcInstrument::setupChannelMenuControlButtonHelper(MenuControlButton *btn, GRTimeChannelAddon *ch) { +void AdcInstrument::setupChannelMenuControlButtonHelper(MenuControlButton *btn, GRTimeChannelAddon *ch) +{ btn->setName(ch->getName()); btn->setCheckBoxStyle(MenuControlButton::CS_CIRCLE); btn->setOpenMenuChecksThis(true); @@ -226,8 +235,11 @@ void AdcInstrument::setupChannelMenuControlButtonHelper(MenuControlButton *btn, btn->setCheckable(true); connect(btn->checkBox(), &QCheckBox::toggled, this, [=](bool b) { - if(b) ch->enable(); else ch->disable(); - } ); + if(b) + ch->enable(); + else + ch->disable(); + }); btn->checkBox()->setChecked(true); } @@ -239,15 +251,16 @@ void AdcInstrument::setupChannelsButtonHelper(MenuControlButton *channelsBtn) channelsBtn->checkBox()->setVisible(false); channelsBtn->setChecked(true); channelStack = new MapStackedWidget(this); - tool->rightStack()->add(channelsMenuId,channelStack); - connect(channelsBtn->button(), &QAbstractButton::toggled, this, [=](bool b){ + tool->rightStack()->add(channelsMenuId, channelStack); + connect(channelsBtn->button(), &QAbstractButton::toggled, this, [=](bool b) { if(b) tool->requestMenu(channelsMenuId); }); rightMenuBtnGrp->addButton(channelsBtn->button()); } -void AdcInstrument::init() { +void AdcInstrument::init() +{ auto addons = proxy->getAddons(); proxy->init(); initCursors(); @@ -256,18 +269,20 @@ void AdcInstrument::init() { } } -void AdcInstrument::deinit() { +void AdcInstrument::deinit() +{ auto addons = proxy->getAddons(); for(auto addon : addons) { - addon->onDeinit(); + addon->onDeinit(); } } -void AdcInstrument::restart() { +void AdcInstrument::restart() +{ if(m_running) { - run(false); - run(true); + run(false); + run(true); } } @@ -281,44 +296,40 @@ void AdcInstrument::showMeasurements(bool b) tool->openBottomContainerHelper(b); } -bool AdcInstrument::running() const -{ - return m_running; -} +bool AdcInstrument::running() const { return m_running; } void AdcInstrument::setRunning(bool newRunning) { - if (m_running == newRunning) - return; + if(m_running == newRunning) + return; m_running = newRunning; Q_EMIT runningChanged(newRunning); } -void AdcInstrument::start() { - run(true); -} +void AdcInstrument::start() { run(true); } -void AdcInstrument::stop() { - run(false); -} +void AdcInstrument::stop() { run(false); } -void AdcInstrument::startAddons() { +void AdcInstrument::startAddons() +{ auto addons = proxy->getAddons(); for(auto addon : addons) { - addon->onStart(); + addon->onStart(); } } -void AdcInstrument::stopAddons() { +void AdcInstrument::stopAddons() +{ auto addons = proxy->getAddons(); for(auto addon : addons) { - addon->onStop(); + addon->onStop(); } } -void AdcInstrument::run(bool b) { - qInfo()<setChecked(false); } - if(b) { + if(b) { startAddons(); } else { stopAddons(); } } - - - - - diff --git a/plugins/adc/src/adcinstrument.h b/plugins/adc/src/adcinstrument.h index 466b3e9ed7..cdacab0280 100644 --- a/plugins/adc/src/adcinstrument.h +++ b/plugins/adc/src/adcinstrument.h @@ -1,12 +1,14 @@ #ifndef ADCINSTRUMENT_H #define ADCINSTRUMENT_H +#include "gui/tooltemplate.h" + +#include #include + #include #include -#include "gui/tooltemplate.h" #include -#include namespace scopy { class MenuControlButton; @@ -40,19 +42,19 @@ public Q_SLOTS: RunBtn *runBtn; SingleShotBtn *singleBtn; ToolTemplate *tool; - PlotProxy* proxy; + PlotProxy *proxy; QPushButton *openLastMenuBtn; MenuControlButton *channelsBtn; - MeasurementsPanel* measure_panel; - StatsPanel* stats_panel; + MeasurementsPanel *measure_panel; + StatsPanel *stats_panel; - GRTimePlotAddon* plotAddon; - GRTimePlotAddonSettings* plotAddonSettings; + GRTimePlotAddon *plotAddon; + GRTimePlotAddonSettings *plotAddonSettings; MapStackedWidget *channelStack; - QButtonGroup* rightMenuBtnGrp; + QButtonGroup *rightMenuBtnGrp; QButtonGroup *channelGroup; CursorController *cursorController; @@ -72,5 +74,5 @@ public Q_SLOTS: const QString statsMenuId = "stats"; const QString verticalChannelManagerId = "vcm"; }; -} +} // namespace scopy #endif // ADCINSTRUMENT_H diff --git a/plugins/adc/src/adcplugin.cpp b/plugins/adc/src/adcplugin.cpp index 7e42197cc3..9bce07fe15 100644 --- a/plugins/adc/src/adcplugin.cpp +++ b/plugins/adc/src/adcplugin.cpp @@ -1,24 +1,28 @@ #include "adcplugin.h" + +#include "adcinstrument.h" +#include "gui/stylehelper.h" + #include #include #include -#include #include +#include #include + +#include #include #include -#include #include #include -#include "adcinstrument.h" -#include "gui/stylehelper.h" -Q_LOGGING_CATEGORY(CAT_ADCPLUGIN,"ADCPlugin"); +Q_LOGGING_CATEGORY(CAT_ADCPLUGIN, "ADCPlugin"); using namespace scopy; using namespace scopy::grutil; -bool ADCPlugin::compatible(QString m_param, QString category) { - qDebug(CAT_ADCPLUGIN)<<"compatible"; +bool ADCPlugin::compatible(QString m_param, QString category) +{ + qDebug(CAT_ADCPLUGIN) << "compatible"; bool ret = false; iio_context *ctx = ContextProvider::GetInstance()->open(m_param); @@ -26,11 +30,11 @@ bool ADCPlugin::compatible(QString m_param, QString category) { if(ctx == nullptr) return ret; - for(int i=0;iinit("adc_plot_xaxis_label_position",QwtAxis::XBottom); - p->init("adc_plot_yaxis_label_position",QwtAxis::YLeft); - p->init("adc_plot_yaxis_handle_position",QwtAxis::YLeft); - p->init("adc_plot_xcursor_position",QwtAxis::XBottom); - p->init("adc_plot_ycursor_position",QwtAxis::YLeft); - p->init("adc_plot_show_buffer_previewer",true); + p->init("adc_plot_xaxis_label_position", QwtAxis::XBottom); + p->init("adc_plot_yaxis_label_position", QwtAxis::YLeft); + p->init("adc_plot_yaxis_handle_position", QwtAxis::YLeft); + p->init("adc_plot_xcursor_position", QwtAxis::XBottom); + p->init("adc_plot_ycursor_position", QwtAxis::YLeft); + p->init("adc_plot_show_buffer_previewer", true); } bool ADCPlugin::loadPreferencesPage() @@ -62,20 +66,32 @@ bool ADCPlugin::loadPreferencesPage() QVBoxLayout *lay = new QVBoxLayout(m_preferencesPage); MenuSectionWidget *generalWidget = new MenuSectionWidget(m_preferencesPage); - MenuCollapseSection *generalSection = new MenuCollapseSection("General",MenuCollapseSection::MHCW_NONE, generalWidget); + MenuCollapseSection *generalSection = + new MenuCollapseSection("General", MenuCollapseSection::MHCW_NONE, generalWidget); generalWidget->contentLayout()->setSpacing(10); generalWidget->contentLayout()->addWidget(generalSection); generalSection->contentLayout()->setSpacing(10); lay->addWidget(generalWidget); lay->setMargin(0); - lay->addSpacerItem(new QSpacerItem(0,0,QSizePolicy::Minimum,QSizePolicy::Expanding)); - - auto adc_plot_xaxis_label_position = PreferencesHelper::addPreferenceComboList(p,"adc_plot_xaxis_label_position", "Plot X-Axis scale position", {{"Top",QwtAxis::XTop}, {"Bottom",QwtAxis::XBottom}},generalSection); - auto adc_plot_yaxis_label_position = PreferencesHelper::addPreferenceComboList(p,"adc_plot_yaxis_label_position", "Plot Y-Axis scale position", {{"Left",QwtAxis::YLeft}, {"Right",QwtAxis::YRight}},generalSection); - auto adc_plot_yaxis_handle_position = PreferencesHelper::addPreferenceComboList(p,"adc_plot_yaxis_handle_position", "Plot channel Y-handle position", {{"Left",QwtAxis::YLeft}, {"Right",QwtAxis::YRight}},generalSection); - auto adc_plot_xcursor_position = PreferencesHelper::addPreferenceComboList(p,"adc_plot_xcursor_position", "Plot X-Cursor position", {{"Top",QwtAxis::XTop}, {"Bottom",QwtAxis::XBottom}},generalSection); - auto adc_plot_ycursor_position = PreferencesHelper::addPreferenceComboList(p,"adc_plot_ycursor_position", "Plot Y-Curosr position", {{"Left",QwtAxis::YLeft}, {"Right",QwtAxis::YRight}},generalSection); - auto adc_plot_show_buffer_previewer = PreferencesHelper::addPreferenceCheckBox(p,"adc_plot_show_buffer_previewer", "Show buffer previewer", m_preferencesPage); + lay->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); + + auto adc_plot_xaxis_label_position = PreferencesHelper::addPreferenceComboList( + p, "adc_plot_xaxis_label_position", "Plot X-Axis scale position", + {{"Top", QwtAxis::XTop}, {"Bottom", QwtAxis::XBottom}}, generalSection); + auto adc_plot_yaxis_label_position = PreferencesHelper::addPreferenceComboList( + p, "adc_plot_yaxis_label_position", "Plot Y-Axis scale position", + {{"Left", QwtAxis::YLeft}, {"Right", QwtAxis::YRight}}, generalSection); + auto adc_plot_yaxis_handle_position = PreferencesHelper::addPreferenceComboList( + p, "adc_plot_yaxis_handle_position", "Plot channel Y-handle position", + {{"Left", QwtAxis::YLeft}, {"Right", QwtAxis::YRight}}, generalSection); + auto adc_plot_xcursor_position = PreferencesHelper::addPreferenceComboList( + p, "adc_plot_xcursor_position", "Plot X-Cursor position", + {{"Top", QwtAxis::XTop}, {"Bottom", QwtAxis::XBottom}}, generalSection); + auto adc_plot_ycursor_position = PreferencesHelper::addPreferenceComboList( + p, "adc_plot_ycursor_position", "Plot Y-Curosr position", + {{"Left", QwtAxis::YLeft}, {"Right", QwtAxis::YRight}}, generalSection); + auto adc_plot_show_buffer_previewer = PreferencesHelper::addPreferenceCheckBox( + p, "adc_plot_show_buffer_previewer", "Show buffer previewer", m_preferencesPage); generalSection->contentLayout()->addWidget(adc_plot_xaxis_label_position); generalSection->contentLayout()->addWidget(adc_plot_yaxis_label_position); @@ -84,7 +100,7 @@ bool ADCPlugin::loadPreferencesPage() generalSection->contentLayout()->addWidget(adc_plot_ycursor_position); generalSection->contentLayout()->addWidget(adc_plot_show_buffer_previewer); -// connect(p, &Preferences::preferenceChanged, ) + // connect(p, &Preferences::preferenceChanged, ) return true; } @@ -104,62 +120,64 @@ bool ADCPlugin::loadPage() void ADCPlugin::loadToolList() { - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("time","Time",":/gui/icons/scopy-default/icons/tool_home.svg")); + m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("time", "Time", ":/gui/icons/scopy-default/icons/tool_home.svg")); } -PlotProxy* ADCPlugin::createRecipe(iio_context *ctx) { +PlotProxy *ADCPlugin::createRecipe(iio_context *ctx) +{ QStringList deviceList; QMap devChannelMap; int devCount = iio_context_get_devices_count(ctx); - qDebug(CAT_ADCPLUGIN)<<" Found " << devCount << "devices"; - for(int i = 0;i < devCount;i++) { - iio_device *dev = iio_context_get_device(ctx,i); + qDebug(CAT_ADCPLUGIN) << " Found " << devCount << "devices"; + for(int i = 0; i < devCount; i++) { + iio_device *dev = iio_context_get_device(ctx, i); QString dev_name = QString::fromLocal8Bit(iio_device_get_name(dev)); - qDebug(CAT_ADCPLUGIN)<< "Looking for scanelements in "<< dev_name; + qDebug(CAT_ADCPLUGIN) << "Looking for scanelements in " << dev_name; if(dev_name == "m2k-logic-analyzer-rx") continue; QStringList channelList; - for (int j = 0; j < iio_device_get_channels_count(dev); j++) { + for(int j = 0; j < iio_device_get_channels_count(dev); j++) { struct iio_channel *chn = iio_device_get_channel(dev, j); QString chn_name = QString::fromLocal8Bit(iio_channel_get_id(chn)); - qDebug(CAT_ADCPLUGIN)<< "Verify if "<< chn_name << "is scan element"; + qDebug(CAT_ADCPLUGIN) << "Verify if " << chn_name << "is scan element"; if(chn_name == "timestamp" /*|| chn_name == "accel_z" || chn_name =="accel_y"*/) continue; - if (!iio_channel_is_output(chn) && iio_channel_is_scan_element(chn)) { + if(!iio_channel_is_output(chn) && iio_channel_is_scan_element(chn)) { channelList.append(chn_name); } } if(channelList.isEmpty()) continue; deviceList.append(dev_name); - devChannelMap.insert(dev_name,channelList); + devChannelMap.insert(dev_name, channelList); } // should this be wrapped to a register function (?) - GRTopBlock* top = new grutil::GRTopBlock("Time",this); + GRTopBlock *top = new grutil::GRTopBlock("Time", this); recipe = new GRTimePlotProxy(this); QString plotRecipePrefix = "time_"; recipe->setPrefix(plotRecipePrefix); - GRTimePlotAddon *p = new GRTimePlotAddon(plotRecipePrefix, top,this); - GRTimePlotAddonSettings *s = new GRTimePlotAddonSettings(p,this); + GRTimePlotAddon *p = new GRTimePlotAddon(plotRecipePrefix, top, this); + GRTimePlotAddonSettings *s = new GRTimePlotAddonSettings(p, this); - recipe->setPlotAddon(p,s); + recipe->setPlotAddon(p, s); int i = 0; for(const QString &iio_dev : deviceList) { - GRIIODeviceSource *gr_dev = new GRIIODeviceSource(m_ctx,iio_dev,iio_dev,0x400,this); + GRIIODeviceSource *gr_dev = new GRIIODeviceSource(m_ctx, iio_dev, iio_dev, 0x400, this); top->registerIIODeviceSource(gr_dev); GRDeviceAddon *d = new GRDeviceAddon(gr_dev, this); connect(s, &GRTimePlotAddonSettings::bufferSizeChanged, d, &GRDeviceAddon::updateBufferSize); recipe->addDeviceAddon(d); - for(const QString &ch : devChannelMap.value(iio_dev,{})) { - GRTimeChannelAddon *t = new GRTimeChannelAddon(ch, d, p, QPen(StyleHelper::getColor("CH"+QString::number(i))), this); + for(const QString &ch : devChannelMap.value(iio_dev, {})) { + GRTimeChannelAddon *t = new GRTimeChannelAddon( + ch, d, p, QPen(StyleHelper::getColor("CH" + QString::number(i))), this); top->registerSignalPath(t->signalPath()); recipe->addChannelAddon(t); i++; @@ -167,8 +185,8 @@ PlotProxy* ADCPlugin::createRecipe(iio_context *ctx) { } recipe->setTopBlock(top); - qDebug(CAT_ADCPLUGIN)<setTool(time); - return true; } bool ADCPlugin::onDisconnect() { - qDebug(CAT_ADCPLUGIN)<<"disconnect"; + qDebug(CAT_ADCPLUGIN) << "disconnect"; for(auto &tool : m_toolList) { tool->setEnabled(false); tool->setRunBtnVisible(false); @@ -207,13 +223,9 @@ bool ADCPlugin::onDisconnect() return true; } -void ADCPlugin::saveSettings(QSettings &s) -{ -} +void ADCPlugin::saveSettings(QSettings &s) {} -void ADCPlugin::loadSettings(QSettings &s) -{ -} +void ADCPlugin::loadSettings(QSettings &s) {} QString ADCPlugin::about() { @@ -224,7 +236,7 @@ QString ADCPlugin::about() void ADCPlugin::initMetadata() { loadMetadata( -R"plugin( + R"plugin( { "priority":2, "category":[ @@ -235,6 +247,4 @@ R"plugin( )plugin"); } -QString ADCPlugin::version() { - return "0.1"; -} +QString ADCPlugin::version() { return "0.1"; } diff --git a/plugins/adc/test/CMakeLists.txt b/plugins/adc/test/CMakeLists.txt index ff0d566e02..646197d6f9 100644 --- a/plugins/adc/test/CMakeLists.txt +++ b/plugins/adc/test/CMakeLists.txt @@ -2,7 +2,4 @@ cmake_minimum_required(VERSION 3.5) include(ScopyTest) -SETUP_SCOPY_TESTS( - pluginloader -) - +setup_scopy_tests(pluginloader) diff --git a/plugins/adc/test/tst_pluginloader.cpp b/plugins/adc/test/tst_pluginloader.cpp index f58c2d4cad..de5a6f74d9 100644 --- a/plugins/adc/test/tst_pluginloader.cpp +++ b/plugins/adc/test/tst_pluginloader.cpp @@ -1,6 +1,8 @@ #include "qpluginloader.h" -#include + #include +#include + #include using namespace scopy; @@ -19,71 +21,64 @@ private Q_SLOTS: void clone(); void name(); void metadata(); - }; #define PLUGIN_LOCATION "../../plugins" #define FILENAME PLUGIN_LOCATION "/libscopy-adcplugin.so" - void TST_ADCPlugin::fileExists() { QFile f(FILENAME); bool ret; - qDebug()<(qp.instance()); - QVERIFY(instance != nullptr ); + QPluginLoader qp(FILENAME, this); + auto instance = qobject_cast(qp.instance()); + QVERIFY(instance != nullptr); } - void TST_ADCPlugin::clone() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(); QVERIFY(p1 != nullptr); p2 = original->clone(); @@ -91,28 +86,28 @@ void TST_ADCPlugin::clone() QVERIFY(p1 != p2); } -void TST_ADCPlugin::name() { - QPluginLoader qp(FILENAME,this); +void TST_ADCPlugin::name() +{ + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(); - qDebug()<name(); + qDebug() << p1->name(); } void TST_ADCPlugin::metadata() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); original->initMetadata(); p1 = original->clone(); - qDebug()<metadata(); + qDebug() << p1->metadata(); QVERIFY(!p1->metadata().isEmpty()); } - QTEST_MAIN(TST_ADCPlugin) #include "tst_pluginloader.moc" diff --git a/plugins/bareminimumplugin/CMakeLists.txt b/plugins/bareminimumplugin/CMakeLists.txt index b5a64cab8e..e794e74d2a 100644 --- a/plugins/bareminimumplugin/CMakeLists.txt +++ b/plugins/bareminimumplugin/CMakeLists.txt @@ -8,8 +8,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -26,39 +25,33 @@ set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) set(SCOPY_QT_COMPONENTS Core Widgets) -FILE(GLOB SRC_LIST src/*.cpp src/*.cc) -FILE(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) -FILE(GLOB UI_LIST ui/*.ui) +file(GLOB SRC_LIST src/*.cpp src/*.cc) +file(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) +file(GLOB UI_LIST ui/*.ui) set(ENABLE_TESTING ON) if(ENABLE_TESTING) - add_subdirectory(test) + add_subdirectory(test) endif() -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} -) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS ${SCOPY_QT_COMPONENTS} REQUIRED) - if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") - set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY - "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") else() - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) endif() -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} -# ${PROJECT_RESOURCES} +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES} # ${PROJECT_RESOURCES} ) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}) @@ -66,11 +59,9 @@ target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/i target_include_directories(${PROJECT_NAME} PUBLIC scopy-pluginbase) foreach(comp ${SCOPY_QT_COMPONENTS}) - set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) + set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) endforeach() -target_link_libraries(${PROJECT_NAME} PUBLIC - ${SCOPY_QT_LIBRARIES} - scopy-pluginbase) +target_link_libraries(${PROJECT_NAME} PUBLIC ${SCOPY_QT_LIBRARIES} scopy-pluginbase) -set(PLUGIN_NAME ${PROJECT_NAME} PARENT_SCOPE) \ No newline at end of file +set(PLUGIN_NAME ${PROJECT_NAME} PARENT_SCOPE) diff --git a/plugins/bareminimumplugin/include/bareminimumplugin/bareminimum.h b/plugins/bareminimumplugin/include/bareminimumplugin/bareminimum.h index 57069a2ea5..05b364f130 100644 --- a/plugins/bareminimumplugin/include/bareminimumplugin/bareminimum.h +++ b/plugins/bareminimumplugin/include/bareminimumplugin/bareminimum.h @@ -3,11 +3,13 @@ #define SCOPY_PLUGIN_NAME BareMinimum +#include "scopy-bareminimumplugin_export.h" + +#include #include + #include #include -#include "scopy-bareminimumplugin_export.h" -#include namespace scopy { @@ -15,18 +17,16 @@ class SCOPY_BAREMINIMUMPLUGIN_EXPORT BareMinimum : public QObject, public Plugin { Q_OBJECT SCOPY_PLUGIN; -public: +public: void initMetadata() override; bool compatible(QString m_param, QString category) override; void loadToolList() override; bool onConnect() override; bool onDisconnect() override; - }; -} - +} // namespace scopy #endif // TESTPLUGIN_H diff --git a/plugins/bareminimumplugin/src/bareminimum.cpp b/plugins/bareminimumplugin/src/bareminimum.cpp index 5cd32ff21a..43f67e003b 100644 --- a/plugins/bareminimumplugin/src/bareminimum.cpp +++ b/plugins/bareminimumplugin/src/bareminimum.cpp @@ -1,26 +1,29 @@ #include "bareminimum.h" + #include #include #include -#include #include +#include #include -#include + #include +#include #include -Q_LOGGING_CATEGORY(CAT_TESTPLUGIN,"BareMinimum"); +Q_LOGGING_CATEGORY(CAT_TESTPLUGIN, "BareMinimum"); using namespace scopy; -bool BareMinimum::compatible(QString m_param, QString category) { - qDebug(CAT_TESTPLUGIN)<<"compatible"; +bool BareMinimum::compatible(QString m_param, QString category) +{ + qDebug(CAT_TESTPLUGIN) << "compatible"; return true; } - void BareMinimum::loadToolList() { - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("bareminimum_tool","MinimumTool",":/gui/icons/scopy-default/icons/tool_home.svg")); + m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("bareminimum_tool", "MinimumTool", + ":/gui/icons/scopy-default/icons/tool_home.svg")); } bool BareMinimum::onConnect() @@ -37,12 +40,10 @@ bool BareMinimum::onDisconnect() return true; } - - void BareMinimum::initMetadata() // not actually needed - putting it here to set priority { loadMetadata( -R"plugin( + R"plugin( { "priority":-255, "category":[ @@ -52,6 +53,4 @@ R"plugin( )plugin"); } - - #include "moc_bareminimum.cpp" diff --git a/plugins/bareminimumplugin/test/CMakeLists.txt b/plugins/bareminimumplugin/test/CMakeLists.txt index ff0d566e02..646197d6f9 100644 --- a/plugins/bareminimumplugin/test/CMakeLists.txt +++ b/plugins/bareminimumplugin/test/CMakeLists.txt @@ -2,7 +2,4 @@ cmake_minimum_required(VERSION 3.5) include(ScopyTest) -SETUP_SCOPY_TESTS( - pluginloader -) - +setup_scopy_tests(pluginloader) diff --git a/plugins/bareminimumplugin/test/tst_pluginloader.cpp b/plugins/bareminimumplugin/test/tst_pluginloader.cpp index 483fde1152..5e4620b708 100644 --- a/plugins/bareminimumplugin/test/tst_pluginloader.cpp +++ b/plugins/bareminimumplugin/test/tst_pluginloader.cpp @@ -1,6 +1,8 @@ #include "qpluginloader.h" -#include + #include +#include + #include using namespace scopy; @@ -19,71 +21,64 @@ private Q_SLOTS: void clone(); void name(); void metadata(); - }; #define PLUGIN_LOCATION "../../plugins" #define FILENAME PLUGIN_LOCATION "/libscopy-bareminimumplugin.so" - void TST_BareMinimum::fileExists() { QFile f(FILENAME); bool ret; - qDebug()<(qp.instance()); - QVERIFY(instance != nullptr ); + QPluginLoader qp(FILENAME, this); + auto instance = qobject_cast(qp.instance()); + QVERIFY(instance != nullptr); } - void TST_BareMinimum::clone() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(); QVERIFY(p1 != nullptr); p2 = original->clone(); @@ -91,28 +86,28 @@ void TST_BareMinimum::clone() QVERIFY(p1 != p2); } -void TST_BareMinimum::name() { - QPluginLoader qp(FILENAME,this); +void TST_BareMinimum::name() +{ + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(); - qDebug()<name(); + qDebug() << p1->name(); } void TST_BareMinimum::metadata() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); original->initMetadata(); p1 = original->clone(); - qDebug()<metadata(); + qDebug() << p1->metadata(); QVERIFY(!p1->metadata().isEmpty()); } - QTEST_MAIN(TST_BareMinimum) #include "tst_pluginloader.moc" diff --git a/plugins/datalogger/CMakeLists.txt b/plugins/datalogger/CMakeLists.txt index 6e6cba0b0d..a86f4b9416 100644 --- a/plugins/datalogger/CMakeLists.txt +++ b/plugins/datalogger/CMakeLists.txt @@ -8,8 +8,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -24,37 +23,34 @@ set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_CXX_VISIBILITY_PRESET hidden) set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) -FILE(GLOB SRC_LIST +file( + GLOB + SRC_LIST src/*.cpp - src/*.hpp - src/gui/*.cpp - src/gui/*.hpp + src/*.hpp + src/gui/*.cpp + src/gui/*.hpp ) -FILE(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) -FILE(GLOB UI_LIST ui/*.ui) +file(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) +file(GLOB UI_LIST ui/*.ui) if(ENABLE_TESTING) - add_subdirectory(test) + add_subdirectory(test) endif() -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} -) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) find_package(libm2k REQUIRED) find_package(Qt5 COMPONENTS Widgets REQUIRED) find_package(Qt5Concurrent REQUIRED) if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") - set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY - "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") else() - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) endif() if(ANDROID) @@ -63,26 +59,27 @@ else() find_library(QWT_LIBRARIES REQUIRED NAMES qwt) endif() -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} - ${PROJECT_RESOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES} ${PROJECT_RESOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}) include_directories(${Qt5Concurrent_INCLUDE_DIRS} ${GLIBCONFIG_INCLUDE_DIRS} ${Qt5Concurrent_INCLUDE_DIRS}) -target_link_libraries(${PROJECT_NAME} PUBLIC - Qt5::Widgets - libm2k::libm2k - scopy-pluginbase - scopy-iioutil - scopy-gui - scopy-core - ${QWT_LIBRARIES} - ${GLIB_LINK_LIBRARIES}) - -set(PLUGIN_NAME ${PROJECT_NAME} PARENT_SCOPE) \ No newline at end of file +target_link_libraries( + ${PROJECT_NAME} + PUBLIC Qt5::Widgets + libm2k::libm2k + scopy-pluginbase + scopy-iioutil + scopy-gui + scopy-core + ${QWT_LIBRARIES} + ${GLIB_LINK_LIBRARIES} +) + +set(PLUGIN_NAME ${PROJECT_NAME} PARENT_SCOPE) diff --git a/plugins/datalogger/include/dataloggerplugin/dataloggerplugin.h b/plugins/datalogger/include/dataloggerplugin/dataloggerplugin.h index f2f8b7a1ed..7718b45275 100644 --- a/plugins/datalogger/include/dataloggerplugin/dataloggerplugin.h +++ b/plugins/datalogger/include/dataloggerplugin/dataloggerplugin.h @@ -4,22 +4,21 @@ #include "src/datalogger_api.h" #define SCOPY_PLUGIN_NAME DataLoggerPlugin -#include -#include -#include "scopy-dataloggerplugin_export.h" -#include #include "iioutil/cyclicaltask.h" #include "iioutil/iiopingtask.h" +#include "scopy-dataloggerplugin_export.h" -#include #include +#include #include +#include +#include +#include Q_DECLARE_LOGGING_CATEGORY(CAT_DATALOGGER); Q_DECLARE_LOGGING_CATEGORY(CAT_DATALOGGER_TOOL); - namespace Ui { class DataLoggerInfoPage; } @@ -57,7 +56,7 @@ public Q_SLOTS: libm2k::context::Context *libm2k_context; }; -} -} +} // namespace datalogger +} // namespace scopy #endif // DATALOGGERPLUGIN_H diff --git a/plugins/datalogger/src/datalogger.cpp b/plugins/datalogger/src/datalogger.cpp index 7c32bbefb9..fa74e395bc 100644 --- a/plugins/datalogger/src/datalogger.cpp +++ b/plugins/datalogger/src/datalogger.cpp @@ -1,27 +1,30 @@ -#include "dataloggerplugin.h" #include "datalogger.hpp" + #include "dataloggercontroller.hpp" -#include -#include -#include +#include "dataloggerplugin.h" #include "gui/channelmonitorcomponent.hpp" #include "gui/dataloggergenericmenu.hpp" +#include +#include + +#include + using namespace scopy; using namespace scopy::gui; using namespace datalogger; using namespace datalogger::gui; -DataLogger::DataLogger(libm2k::context::Context *ctx, QWidget *parent): - QWidget(parent), - m_timer(new QTimer(this)), - m_elapsed(new QElapsedTimer()), - readerThread(new DataLoggerReaderThread()), - m_context(ctx) +DataLogger::DataLogger(libm2k::context::Context *ctx, QWidget *parent) + : QWidget(parent) + , m_timer(new QTimer(this)) + , m_elapsed(new QElapsedTimer()) + , readerThread(new DataLoggerReaderThread()) + , m_context(ctx) { - m_colors = {QColor("#ff7200"),QColor("#9013fe"), QColor(Qt::green),QColor(Qt::cyan), QColor(Qt::magenta), - QColor(Qt::yellow), QColor(Qt::gray), QColor(Qt::darkRed), QColor(Qt::darkGreen), - QColor(Qt::darkBlue), QColor(Qt::darkGray),QColor(Qt::black)}; + m_colors = {QColor("#ff7200"), QColor("#9013fe"), QColor(Qt::green), QColor(Qt::cyan), + QColor(Qt::magenta), QColor(Qt::yellow), QColor(Qt::gray), QColor(Qt::darkRed), + QColor(Qt::darkGreen), QColor(Qt::darkBlue), QColor(Qt::darkGray), QColor(Qt::black)}; ToolViewRecipe recipe; recipe.helpBtnUrl = ""; @@ -41,7 +44,7 @@ DataLogger::DataLogger(libm2k::context::Context *ctx, QWidget *parent): m_timer->setSingleShot(true); // on timeout read on thread connect(m_timer, &QTimer::timeout, this, [=]() { - if (!m_elapsed->isValid()) { + if(!m_elapsed->isValid()) { m_elapsed->start(); } readerThread->start(); @@ -49,45 +52,41 @@ DataLogger::DataLogger(libm2k::context::Context *ctx, QWidget *parent): connect(readerThread, &DataLoggerReaderThread::finished, this, [=]() { // after read is done check if another read is needed - if (m_toolView->getRunBtn()->isChecked()) { + if(m_toolView->getRunBtn()->isChecked()) { int newInterval = VALUE_READING_TIME_INTERVAL - m_elapsed->elapsed(); m_elapsed->invalidate(); - if (newInterval < 0) { + if(newInterval < 0) { newInterval = 0; } m_timer->start(newInterval); } - if (m_toolView->getSingleBtn()->isChecked()) { + if(m_toolView->getSingleBtn()->isChecked()) { m_toolView->getSingleBtn()->setChecked(false); } }); - m_generalSettingsMenu = - generateMenu("General settings", new QColor("#4a64ff")); + m_generalSettingsMenu = generateMenu("General settings", new QColor("#4a64ff")); m_toolView->setGeneralSettingsMenu(m_generalSettingsMenu, true); m_dmmList = getDmmList(m_context); - connect(this, &DataLogger::recordingIntervalChanged, this, - [=](double interval) { + connect(this, &DataLogger::recordingIntervalChanged, this, [=](double interval) { VALUE_READING_TIME_INTERVAL = interval; recording_timer->setValue(interval / 1000); }); - connect(m_toolView->getRunBtn(), &QPushButton::toggled, this, - [=](bool toggled) { - dataLoggerController->setIsRunningOn( - m_toolView->getRunBtn()->isChecked()); + connect(m_toolView->getRunBtn(), &QPushButton::toggled, this, [=](bool toggled) { + dataLoggerController->setIsRunningOn(m_toolView->getRunBtn()->isChecked()); // update status and if needed start data logging - if (!m_toolView->getRunBtn()->isChecked()) { + if(!m_toolView->getRunBtn()->isChecked()) { m_monitorChannelManager->setToolStatus("Stopped"); showAllSWitch->setEnabled(true); readerThread->setDataLoggerStatus(false); dataLoggerController->stopLogger(); } else { - if (dataLoggerController->isDataLoggerOn()) { + if(dataLoggerController->isDataLoggerOn()) { m_monitorChannelManager->setToolStatus("Data Logging"); readerThread->setDataLoggerStatus(true); } else { @@ -95,22 +94,21 @@ DataLogger::DataLogger(libm2k::context::Context *ctx, QWidget *parent): } } - if (toggled) { + if(toggled) { m_timer->start(VALUE_READING_TIME_INTERVAL); } else { // if thread is running after current action on thread is done // stop thread - if (readerThread->isRunning()) { + if(readerThread->isRunning()) { readerThread->quit(); readerThread->wait(); } } }); - connect(m_toolView->getSingleBtn(), &QPushButton::toggled, this, - [=](bool toggled) { - if (toggled) { - if (m_toolView->getRunBtn()->isChecked()) { + connect(m_toolView->getSingleBtn(), &QPushButton::toggled, this, [=](bool toggled) { + if(toggled) { + if(m_toolView->getRunBtn()->isChecked()) { m_toolView->getRunBtn()->toggled(false); } @@ -120,10 +118,10 @@ DataLogger::DataLogger(libm2k::context::Context *ctx, QWidget *parent): m_scrollArea = new QScrollArea(this); m_scrollArea->setWidgetResizable(true); - m_flexGridLayout = new FlexGridLayout(100,this); + m_flexGridLayout = new FlexGridLayout(100, this); m_scrollArea->setWidget(m_flexGridLayout); - m_toolView->addFixedCentralWidget(m_scrollArea,0,0,0,0); + m_toolView->addFixedCentralWidget(m_scrollArea, 0, 0, 0, 0); this->setLayout(new QVBoxLayout()); this->layout()->addWidget(m_toolView); @@ -139,206 +137,192 @@ void DataLogger::initMonitorToolView() bool first = true; setUpdatesEnabled(false); - for (libm2k::analog::DMM* dmm : m_dmmList) { + for(libm2k::analog::DMM *dmm : m_dmmList) { auto dmmName = dmm->getName(); - std::vector channelList; + std::vector channelList; DataLoggerGenericMenu *menu = new DataLoggerGenericMenu(this); - menu->init(QString::fromStdString(dmmName),new QColor("green")); + menu->init(QString::fromStdString(dmmName), new QColor("green")); - ChannelWidget *mainCh_widget = - m_toolView->buildNewChannel(m_monitorChannelManager, menu, false, chId, false, false, QColor("green"), - QString::fromStdString(dmmName), QString::fromStdString(dmmName)); - if (first) { + ChannelWidget *mainCh_widget = m_toolView->buildNewChannel( + m_monitorChannelManager, menu, false, chId, false, false, QColor("green"), + QString::fromStdString(dmmName), QString::fromStdString(dmmName)); + if(first) { mainCh_widget->menuButton()->click(); first = false; } chId++; auto dmmList = dmm->readAll(); - for (const auto &channel : dmmList) { + for(const auto &channel : dmmList) { QColor channelColor = getChannelColor(chId); DataLoggerGenericMenu *channelMenu = new DataLoggerGenericMenu(this); - channelMenu->init(QString::fromStdString(dmmName + ": " + channel.id),new QColor(channelColor)); + channelMenu->init(QString::fromStdString(dmmName + ": " + channel.id), + new QColor(channelColor)); - ChannelWidget *ch_widget = m_toolView->buildNewChannel(m_monitorChannelManager, channelMenu , false, chId, false, false, - channelColor, QString::fromStdString(channel.id), QString::fromStdString(channel.id)); + ChannelWidget *ch_widget = m_toolView->buildNewChannel( + m_monitorChannelManager, channelMenu, false, chId, false, false, channelColor, + QString::fromStdString(channel.id), QString::fromStdString(channel.id)); channelList.push_back(ch_widget); ch_widget->enableButton()->setChecked(false); - ChannelMonitorComponent* monitor = new ChannelMonitorComponent(); + ChannelMonitorComponent *monitor = new ChannelMonitorComponent(); monitor->setID(chId); - monitor->init(0,QString::fromStdString(channel.unit_name),QString::fromStdString(channel.unit_symbol), - QString::fromStdString(dmmName + ": " + channel.id),channelColor ); + monitor->init(0, QString::fromStdString(channel.unit_name), + QString::fromStdString(channel.unit_symbol), + QString::fromStdString(dmmName + ": " + channel.id), channelColor); monitor->setChannelId(channel.id); - monitor->setRecordingInterval(VALUE_READING_TIME_INTERVAL/1000); + monitor->setRecordingInterval(VALUE_READING_TIME_INTERVAL / 1000); monitor->setHistoryDuration(10); - connect(readerThread, &DataLoggerReaderThread::updateChannelData, monitor, [=](int chId, double value,QString nameOfUnitOfMeasure,QString symbolOfUnitOfMeasure){ - if (chId == monitor->getID()) { - monitor->updateValue(value, nameOfUnitOfMeasure, symbolOfUnitOfMeasure); - } - }); + connect(readerThread, &DataLoggerReaderThread::updateChannelData, monitor, + [=](int chId, double value, QString nameOfUnitOfMeasure, + QString symbolOfUnitOfMeasure) { + if(chId == monitor->getID()) { + monitor->updateValue(value, nameOfUnitOfMeasure, symbolOfUnitOfMeasure); + } + }); - connect(monitor, &ChannelMonitorComponent::contentChanged, m_flexGridLayout, [=](){ - m_flexGridLayout->itemSizeChanged(); - }, Qt::QueuedConnection); + connect( + monitor, &ChannelMonitorComponent::contentChanged, m_flexGridLayout, + [=]() { m_flexGridLayout->itemSizeChanged(); }, Qt::QueuedConnection); - connect(this, &DataLogger::recordingIntervalChanged, monitor , [=](double interval){ - monitor->setRecordingInterval(interval/1000); - }); + connect(this, &DataLogger::recordingIntervalChanged, monitor, + [=](double interval) { monitor->setRecordingInterval(interval / 1000); }); - //connect menu switches to widget - createConnections(menu,channelMenu,monitor); + // connect menu switches to widget + createConnections(menu, channelMenu, monitor); - connect(this, &DataLogger::toggleAll, this, [=](bool toggled){ - if (ch_widget->enableButton()->isChecked() != toggled) { + connect(this, &DataLogger::toggleAll, this, [=](bool toggled) { + if(ch_widget->enableButton()->isChecked() != toggled) { ch_widget->enableButton()->click(); } }); - //add connections from general settings - connect(this, &DataLogger::precisionChanged, this, [=](int precision){ - monitor->updateLcdNumberPrecision(precision); - }); + // add connections from general settings + connect(this, &DataLogger::precisionChanged, this, + [=](int precision) { monitor->updateLcdNumberPrecision(precision); }); - connect(this, &DataLogger::disableActivateChannel,this, [=](bool toggled){ + connect(this, &DataLogger::disableActivateChannel, this, [=](bool toggled) { if(m_toolView->getRunBtn()->isChecked() && toggled) ch_widget->enableButton()->setDisabled(true); else ch_widget->enableButton()->setDisabled(false); - }); int widgetId = m_flexGridLayout->addQWidgetToList(monitor); - readerThread->addChannel(chId, channel.id,dmm); + readerThread->addChannel(chId, channel.id, dmm); // logic for enable/disable channels - connect(ch_widget, &ChannelWidget::enabled,this, [=](bool enabled){ - - readerThread->channelToggled(chId,enabled); - if (enabled) { + connect(ch_widget, &ChannelWidget::enabled, this, [=](bool enabled) { + readerThread->channelToggled(chId, enabled); + if(enabled) { m_flexGridLayout->addWidget(widgetId); m_activeChannels[chId] = monitor; } else { m_activeChannels.remove(chId); m_flexGridLayout->removeWidget(widgetId); - - } }); ch_widget->enableButton()->click(); chId++; } - m_toolView->buildChannelGroup(m_monitorChannelManager, mainCh_widget,channelList); + m_toolView->buildChannelGroup(m_monitorChannelManager, mainCh_widget, channelList); } setUpdatesEnabled(true); } -void DataLogger::createConnections(DataLoggerGenericMenu* mainMenu, DataLoggerGenericMenu* menu, ChannelMonitorComponent* monitor) +void DataLogger::createConnections(DataLoggerGenericMenu *mainMenu, DataLoggerGenericMenu *menu, + ChannelMonitorComponent *monitor) { - connect(menu,&DataLoggerGenericMenu::togglePeakHolder, monitor, &ChannelMonitorComponent::displayPeakHold); - connect(mainMenu,&DataLoggerGenericMenu::togglePeakHolder, menu, &DataLoggerGenericMenu::peakHolderToggle); + connect(menu, &DataLoggerGenericMenu::togglePeakHolder, monitor, &ChannelMonitorComponent::displayPeakHold); + connect(mainMenu, &DataLoggerGenericMenu::togglePeakHolder, menu, &DataLoggerGenericMenu::peakHolderToggle); connect(menu, &DataLoggerGenericMenu::resetPeakHolder, monitor, &ChannelMonitorComponent::resetPeakHolder); - connect(mainMenu,&DataLoggerGenericMenu::resetPeakHolder, menu, &DataLoggerGenericMenu::peakHolderResetClicked); + connect(mainMenu, &DataLoggerGenericMenu::resetPeakHolder, menu, + &DataLoggerGenericMenu::peakHolderResetClicked); connect(menu, &DataLoggerGenericMenu::toggleScale, monitor, &ChannelMonitorComponent::displayScale); - connect(mainMenu,&DataLoggerGenericMenu::toggleScale, menu, &DataLoggerGenericMenu::scaleToggle); + connect(mainMenu, &DataLoggerGenericMenu::toggleScale, menu, &DataLoggerGenericMenu::scaleToggle); connect(menu, &DataLoggerGenericMenu::toggleHistory, monitor, &ChannelMonitorComponent::displayHistory); - connect(mainMenu,&DataLoggerGenericMenu::toggleHistory, menu, &DataLoggerGenericMenu::historyToggle); + connect(mainMenu, &DataLoggerGenericMenu::toggleHistory, menu, &DataLoggerGenericMenu::historyToggle); connect(menu, &DataLoggerGenericMenu::changeHistorySize, monitor, &ChannelMonitorComponent::setHistoryDuration); - connect(mainMenu,&DataLoggerGenericMenu::historySizeIndexChanged, menu, &DataLoggerGenericMenu::historySizeChanged); + connect(mainMenu, &DataLoggerGenericMenu::historySizeIndexChanged, menu, + &DataLoggerGenericMenu::historySizeChanged); connect(menu, &DataLoggerGenericMenu::lineStyleChanged, monitor, &ChannelMonitorComponent::setLineStyle); - connect(mainMenu,&DataLoggerGenericMenu::lineStyleIndexChanged, menu, &DataLoggerGenericMenu::changeLineStyle); + connect(mainMenu, &DataLoggerGenericMenu::lineStyleIndexChanged, menu, &DataLoggerGenericMenu::changeLineStyle); connect(menu, &DataLoggerGenericMenu::monitorColorChanged, monitor, &ChannelMonitorComponent::setMonitorColor); } -scopy::gui::ToolView* DataLogger::getToolView() -{ - return m_toolView; -} +scopy::gui::ToolView *DataLogger::getToolView() { return m_toolView; } void DataLogger::setNativeDialogs(bool nativeDialogs) { -// Tool::setNativeDialogs(nativeDialogs); + // Tool::setNativeDialogs(nativeDialogs); dataLoggerController->setUseNativeDialog(nativeDialogs); } -QPushButton *DataLogger::getRunButton() -{ - return m_toolView->getRunBtn(); -} +QPushButton *DataLogger::getRunButton() { return m_toolView->getRunBtn(); } -int DataLogger::getPrecision() -{ - return precisionValue->text().toInt(); -} +int DataLogger::getPrecision() { return precisionValue->text().toInt(); } -void DataLogger::setPrecision(int precision) -{ - precisionValue->setText(QString::number(precision)); -} - -int DataLogger::getValueReadingTimeInterval() -{ - return VALUE_READING_TIME_INTERVAL; -} +void DataLogger::setPrecision(int precision) { precisionValue->setText(QString::number(precision)); } +int DataLogger::getValueReadingTimeInterval() { return VALUE_READING_TIME_INTERVAL; } -std::vector DataLogger::getDmmList(libm2k::context::Context* context) +std::vector DataLogger::getDmmList(libm2k::context::Context *context) { return context->getAllDmm(); } QColor DataLogger::generateColor() { - if (m_color.size() < m_colors.size()) { + if(m_color.size() < m_colors.size()) { return m_colors.at(m_color.size()); } int red = rand() % 256; int blue = rand() % 256; int green = rand() % 256; - return QColor(red,green,blue); + return QColor(red, green, blue); } QColor DataLogger::getChannelColor(int chId) { - if (m_color.contains(chId)) { + if(m_color.contains(chId)) { return m_color[chId]; } else { - if (m_color.isEmpty()) { - m_color[chId]= generateColor(); + if(m_color.isEmpty()) { + m_color[chId] = generateColor(); return m_color[chId]; } QColor color; bool colorExists = true; - while(colorExists){ + while(colorExists) { color = generateColor(); - for (auto it = m_color.begin(); it != m_color.end(); it++) { - if (it.value() != color) { + for(auto it = m_color.begin(); it != m_color.end(); it++) { + if(it.value() != color) { colorExists = false; break; } } } - m_color[chId]=color; + m_color[chId] = color; return color; } } -scopy::gui::GenericMenu* DataLogger::generateMenu(QString title, QColor* color) +scopy::gui::GenericMenu *DataLogger::generateMenu(QString title, QColor *color) { scopy::gui::GenericMenu *menu = new scopy::gui::GenericMenu(this); menu->initInteractiveMenu(); - menu->setMenuHeader(title,color,false); + menu->setMenuHeader(title, color, false); auto *showAllSection = new scopy::gui::SubsectionSeparator("Show all", false, this); @@ -347,37 +331,36 @@ scopy::gui::GenericMenu* DataLogger::generateMenu(QString title, QColor* color) showAllSWitch = new CustomSwitch(showAllWidget); showAllSWitch->setChecked(true); - showAllLayout->addWidget(new QLabel("Show all",showAllWidget)); + showAllLayout->addWidget(new QLabel("Show all", showAllWidget)); showAllLayout->addWidget(showAllSWitch); showAllSection->setContent(showAllWidget); - connect(showAllSWitch, &CustomSwitch::toggled, this, [=](bool toggled){ - Q_EMIT DataLogger::toggleAll(toggled); - }); + connect(showAllSWitch, &CustomSwitch::toggled, this, + [=](bool toggled) { Q_EMIT DataLogger::toggleAll(toggled); }); - auto *precisionSection = new scopy::gui::SubsectionSeparator("Precision", false,this); + auto *precisionSection = new scopy::gui::SubsectionSeparator("Precision", false, this); QWidget *precisionWidget = new QWidget(this); auto *precisionLayout = new QHBoxLayout(precisionWidget); - precisionLayout->setAlignment(precisionWidget,Qt::AlignLeft); - auto *precisionBtn = new QPushButton("Set",precisionWidget); - precisionBtn->setMinimumSize(50,30); - precisionBtn->setProperty("blue_button",true); + precisionLayout->setAlignment(precisionWidget, Qt::AlignLeft); + auto *precisionBtn = new QPushButton("Set", precisionWidget); + precisionBtn->setMinimumSize(50, 30); + precisionBtn->setProperty("blue_button", true); precisionValue = new QLineEdit(precisionWidget); - precisionValue->setValidator( new QIntValidator(this) ); + precisionValue->setValidator(new QIntValidator(this)); precisionValue->setText("3"); precisionLayout->addWidget(precisionBtn); - precisionLayout->addItem(new QSpacerItem(1,1,QSizePolicy::Expanding,QSizePolicy::Fixed)); + precisionLayout->addItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Fixed)); precisionLayout->addWidget(precisionValue); - connect(precisionBtn, &QPushButton::clicked,this, [=](){ + connect(precisionBtn, &QPushButton::clicked, this, [=]() { auto value = precisionValue->text().toInt(); - if (value < 0) { + if(value < 0) { precisionValue->setText("0"); } - if (value >= 10) { + if(value >= 10) { precisionValue->setText("9"); } @@ -390,46 +373,39 @@ scopy::gui::GenericMenu* DataLogger::generateMenu(QString title, QColor* color) auto recordingIntervalWidget = new QWidget(this); auto *recordingIntevlaLayout = new QVBoxLayout(recordingIntervalWidget); - recording_timer = new PositionSpinButton({ - {"s", 1}, - {"min", 60}, - {"h", 3600} - }, tr("Timer"), 0, 3600, - true, false, this); + recording_timer = + new PositionSpinButton({{"s", 1}, {"min", 60}, {"h", 3600}}, tr("Timer"), 0, 3600, true, false, this); recording_timer->setValue(1); recordingIntevlaLayout->addWidget(recording_timer); - connect(recording_timer, &PositionSpinButton::valueChanged, this, [=](){ + connect(recording_timer, &PositionSpinButton::valueChanged, this, [=]() { double interval = recording_timer->value() * 1000; - if (interval < 100) { + if(interval < 100) { interval = 100; recording_timer->setValue(interval); - } Q_EMIT recordingIntervalChanged(interval); }); recordingIntervalSection->setContent(recordingIntervalWidget); - auto dataLoggingSection = new scopy::gui::SubsectionSeparator("Data Logging",true,this); + auto dataLoggingSection = new scopy::gui::SubsectionSeparator("Data Logging", true, this); - dataLoggerController = new DataLoggerController(true,true,false); + dataLoggerController = new DataLoggerController(true, true, false); dataLoggerController->setWarningMessage("* While data logging you won't be able to add/remove channels"); dataLoggingSection->setContent(dataLoggerController->getWidget()); - connect(readerThread, &DataLoggerReaderThread::updateDataLoggerValue, this , [=](QString name, QString value){ - dataLoggerController->receiveValue(name,value); - }); - - connect(dataLoggerController, &DataLoggerController::isDataLogging, this, [=](bool toggled){ + connect(readerThread, &DataLoggerReaderThread::updateDataLoggerValue, this, + [=](QString name, QString value) { dataLoggerController->receiveValue(name, value); }); - if (m_toolView->getRunBtn()->isChecked()) { + connect(dataLoggerController, &DataLoggerController::isDataLogging, this, [=](bool toggled) { + if(m_toolView->getRunBtn()->isChecked()) { showAllSWitch->setEnabled(!toggled); } - if (toggled) { - if (!m_activeChannels.empty()) { - for (int ch : m_activeChannels.keys()) { + if(toggled) { + if(!m_activeChannels.empty()) { + for(int ch : m_activeChannels.keys()) { QString name = m_activeChannels[ch]->getTitle(); dataLoggerController->createChannel(name, CHANNEL_DATA_TYPE::DOUBLE); } @@ -450,24 +426,24 @@ scopy::gui::GenericMenu* DataLogger::generateMenu(QString title, QColor* color) DataLogger::~DataLogger() { - if (m_toolView->getRunBtn()->isChecked()) { + if(m_toolView->getRunBtn()->isChecked()) { m_toolView->getRunBtn()->setChecked(false); } - if (readerThread->isRunning()) { + if(readerThread->isRunning()) { readerThread->quit(); readerThread->wait(); } - if (readerThread) { + if(readerThread) { delete readerThread; } - if (m_timer) { + if(m_timer) { delete m_timer; } - if (m_elapsed) { + if(m_elapsed) { delete m_elapsed; } - if (m_toolView) { + if(m_toolView) { delete m_toolView; } } diff --git a/plugins/datalogger/src/datalogger.hpp b/plugins/datalogger/src/datalogger.hpp index 83bdc72777..1a286ebdb0 100644 --- a/plugins/datalogger/src/datalogger.hpp +++ b/plugins/datalogger/src/datalogger.hpp @@ -1,26 +1,27 @@ #ifndef DATALOGGER_H #define DATALOGGER_H +#include +#include +#include +#include #include +#include #include #include -#include -#include -#include -#include -#include -#include -#include + #include +#include +#include /* libm2k includes */ +#include "dataloggerreaderthread.hpp" + +#include #include #include -#include #include -#include "dataloggerreaderthread.hpp" - namespace libm2k::context { class ContextBuilder; } @@ -30,7 +31,7 @@ namespace gui { class GenericMenu; class ChannelManager; class ChannelWidget; -} +} // namespace gui class CustomSwitch; @@ -38,7 +39,7 @@ namespace datalogger { namespace gui { class ChannelMonitorComponent; class DataLoggerGenericMenu; -} +} // namespace gui class DataLogger_API; class DataLoggerController; @@ -53,19 +54,19 @@ class DataLogger : public QWidget explicit DataLogger(libm2k::context::Context *ctx, QWidget *parent = nullptr); ~DataLogger(); - scopy::gui::ToolView* getToolView(); + scopy::gui::ToolView *getToolView(); - CustomSwitch* showAllSWitch; + CustomSwitch *showAllSWitch; int getPrecision(); void setPrecision(int precision); int getValueReadingTimeInterval(); void setNativeDialogs(bool nativeDialogs); - QPushButton* getRunButton(); + QPushButton *getRunButton(); private: int VALUE_READING_TIME_INTERVAL = 1000; - QWidget* parent; + QWidget *parent; QTimer *m_timer; QElapsedTimer *m_elapsed; @@ -73,31 +74,32 @@ class DataLogger : public QWidget PositionSpinButton *recording_timer; QList m_colors; - QMap m_color; + QMap m_color; DataLoggerController *dataLoggerController; - scopy::gui::ToolView* m_toolView; - QScrollArea* m_scrollArea; - FlexGridLayout* m_flexGridLayout; - libm2k::context::Context* m_context; - std::vector m_dmmList; - scopy::gui::GenericMenu* m_generalSettingsMenu; - scopy::gui::ChannelManager* m_monitorChannelManager; - QMap m_activeChannels; + scopy::gui::ToolView *m_toolView; + QScrollArea *m_scrollArea; + FlexGridLayout *m_flexGridLayout; + libm2k::context::Context *m_context; + std::vector m_dmmList; + scopy::gui::GenericMenu *m_generalSettingsMenu; + scopy::gui::ChannelManager *m_monitorChannelManager; + QMap m_activeChannels; DataLoggerReaderThread *readerThread; QColor generateColor(); void initMonitorToolView(); QColor getChannelColor(int chId); - scopy::gui::GenericMenu* generateMenu(QString title, QColor* color); - std::vector getDmmList(libm2k::context::Context* m2k_context); - void createConnections(gui::DataLoggerGenericMenu* mainMenu, gui::DataLoggerGenericMenu* menu, gui::ChannelMonitorComponent* monitor); + scopy::gui::GenericMenu *generateMenu(QString title, QColor *color); + std::vector getDmmList(libm2k::context::Context *m2k_context); + void createConnections(gui::DataLoggerGenericMenu *mainMenu, gui::DataLoggerGenericMenu *menu, + gui::ChannelMonitorComponent *monitor); Q_SIGNALS: void precisionChanged(int precision); - void channelValueUpdated(int chId, double value,QString nameOfUnitOfMeasure,QString symbolOfUnitOfMeasure); + void channelValueUpdated(int chId, double value, QString nameOfUnitOfMeasure, QString symbolOfUnitOfMeasure); void recordingIntervalChanged(double recordingInterval); void toggleAll(bool showAll); void disableActivateChannel(bool disable); }; -} -} +} // namespace datalogger +} // namespace scopy #endif // DATALOGGER_H diff --git a/plugins/datalogger/src/datalogger_api.cpp b/plugins/datalogger/src/datalogger_api.cpp index 709223571f..34ea10494e 100644 --- a/plugins/datalogger/src/datalogger_api.cpp +++ b/plugins/datalogger/src/datalogger_api.cpp @@ -1,25 +1,18 @@ #include "datalogger_api.h" -#include "dataloggercontroller.hpp" + #include "datalogger.hpp" +#include "dataloggercontroller.hpp" + #include using namespace scopy; using namespace datalogger; -bool DataLogger_API::get_show_all() -{ - return dataLogger->showAllSWitch->isChecked(); -} +bool DataLogger_API::get_show_all() { return dataLogger->showAllSWitch->isChecked(); } -void DataLogger_API::set_show_all(bool en) -{ - dataLogger->showAllSWitch->setChecked(en); -} +void DataLogger_API::set_show_all(bool en) { dataLogger->showAllSWitch->setChecked(en); } -int DataLogger_API::get_precision() -{ - return dataLogger->getPrecision(); -} +int DataLogger_API::get_precision() { return dataLogger->getPrecision(); } void DataLogger_API::set_precision(int precision) { @@ -27,45 +20,29 @@ void DataLogger_API::set_precision(int precision) Q_EMIT dataLogger->precisionChanged(precision); } -int DataLogger_API::get_recording_interval() -{ - return dataLogger->getValueReadingTimeInterval(); -} +int DataLogger_API::get_recording_interval() { return dataLogger->getValueReadingTimeInterval(); } -void DataLogger_API::set_recording_interval(int interval) -{ - Q_EMIT dataLogger->recordingIntervalChanged(interval); -} +void DataLogger_API::set_recording_interval(int interval) { Q_EMIT dataLogger->recordingIntervalChanged(interval); } -bool DataLogger_API::get_data_logging_on(){ - return dataLogger->dataLoggerController->isDataLoggerOn(); -} -void DataLogger_API::set_data_logging_on(bool en){ - dataLogger->dataLoggerController->dataLoggerToggled(en); -} +bool DataLogger_API::get_data_logging_on() { return dataLogger->dataLoggerController->isDataLoggerOn(); } +void DataLogger_API::set_data_logging_on(bool en) { dataLogger->dataLoggerController->dataLoggerToggled(en); } -QString DataLogger_API::get_data_logging_path() -{ - return dataLogger->dataLoggerController->getPath(); -} +QString DataLogger_API::get_data_logging_path() { return dataLogger->dataLoggerController->getPath(); } void DataLogger_API::set_data_logging_path(QString path) { - if (dataLogger->dataLoggerController->isDataLoggerOn()) { + if(dataLogger->dataLoggerController->isDataLoggerOn()) { dataLogger->dataLoggerController->setPath(path); } else { dataLogger->dataLoggerController->setPath(""); } } -bool DataLogger_API::get_data_logger_overwrite_append() -{ - return dataLogger->dataLoggerController->isOverwrite(); -} +bool DataLogger_API::get_data_logger_overwrite_append() { return dataLogger->dataLoggerController->isOverwrite(); } void DataLogger_API::set_data_logger_overwrite_append(bool en) { - if (dataLogger->dataLoggerController->isDataLoggerOn()) { + if(dataLogger->dataLoggerController->isDataLoggerOn()) { dataLogger->dataLoggerController->setOverwrite(en); } } @@ -77,7 +54,7 @@ int DataLogger_API::get_data_logger_recording_interval() void DataLogger_API::set_data_logger_recording_interval(int interval) { - if (dataLogger->dataLoggerController->isDataLoggerOn()) { + if(dataLogger->dataLoggerController->isDataLoggerOn()) { dataLogger->dataLoggerController->setRecodingTimeInterval(interval); } } diff --git a/plugins/datalogger/src/datalogger_api.h b/plugins/datalogger/src/datalogger_api.h index 5b1b709cfd..041f8109ff 100644 --- a/plugins/datalogger/src/datalogger_api.h +++ b/plugins/datalogger/src/datalogger_api.h @@ -2,6 +2,7 @@ #define DATALOGGER_API_H #include + #include #include @@ -11,28 +12,23 @@ class CustomSwitch; namespace datalogger { class DataLoggerController; -class DataLogger_API:public ApiObject +class DataLogger_API : public ApiObject { friend class ToolLauncher_API; Q_OBJECT - Q_PROPERTY(bool show_all - READ get_show_all WRITE set_show_all); - Q_PROPERTY(int precision - READ get_precision WRITE set_precision); - Q_PROPERTY(int recording_interval - READ get_recording_interval WRITE set_recording_interval); - Q_PROPERTY(bool data_logging_on - READ get_data_logging_on WRITE set_data_logging_on); - Q_PROPERTY(QString data_logging_path - READ get_data_logging_path WRITE set_data_logging_path); - Q_PROPERTY(bool data_logger_overwrite_append - READ get_data_logger_overwrite_append WRITE set_data_logger_overwrite_append); - Q_PROPERTY(int data_logger_recording_interval - READ get_data_logger_recording_interval WRITE set_data_logger_recording_interval); -public: + Q_PROPERTY(bool show_all READ get_show_all WRITE set_show_all); + Q_PROPERTY(int precision READ get_precision WRITE set_precision); + Q_PROPERTY(int recording_interval READ get_recording_interval WRITE set_recording_interval); + Q_PROPERTY(bool data_logging_on READ get_data_logging_on WRITE set_data_logging_on); + Q_PROPERTY(QString data_logging_path READ get_data_logging_path WRITE set_data_logging_path); + Q_PROPERTY(bool data_logger_overwrite_append READ get_data_logger_overwrite_append WRITE + set_data_logger_overwrite_append); + Q_PROPERTY(int data_logger_recording_interval READ get_data_logger_recording_interval WRITE + set_data_logger_recording_interval); +public: bool get_show_all(); void set_show_all(bool en); @@ -54,12 +50,14 @@ class DataLogger_API:public ApiObject int get_data_logger_recording_interval(); void set_data_logger_recording_interval(int interval); - explicit DataLogger_API(DataLogger *dataLogger) : ApiObject(dataLogger), dataLogger(dataLogger) {}; + explicit DataLogger_API(DataLogger *dataLogger) + : ApiObject(dataLogger) + , dataLogger(dataLogger){}; private: DataLogger *dataLogger; }; -} -} +} // namespace datalogger +} // namespace scopy #endif // DATALOGGER_API_H diff --git a/plugins/datalogger/src/dataloggercontroller.cpp b/plugins/datalogger/src/dataloggercontroller.cpp index f343b5c685..73d9e3ef32 100644 --- a/plugins/datalogger/src/dataloggercontroller.cpp +++ b/plugins/datalogger/src/dataloggercontroller.cpp @@ -7,78 +7,52 @@ using namespace datalogger::gui; DataLoggerController::DataLoggerController(bool lastValue, bool average, bool all) { dataLoggerModel = new DataLoggerModel(); - dataLoggerView = new DataLoggerView(lastValue,average,all); + dataLoggerView = new DataLoggerView(lastValue, average, all); connect(dataLoggerView, &DataLoggerView::pathChanged, dataLoggerModel, &DataLoggerModel::setPath); - connect(dataLoggerView, &DataLoggerView::timeIntervalChanged, dataLoggerModel, &DataLoggerModel::setTimerInterval); + connect(dataLoggerView, &DataLoggerView::timeIntervalChanged, dataLoggerModel, + &DataLoggerModel::setTimerInterval); connect(dataLoggerView, &DataLoggerView::toggleDataLogger, this, &DataLoggerController::dataLoggerToggled); dataLoggerModel->setTimerInterval(5000); isRunningOn = false; } -void DataLoggerController::startLogger() -{ - dataLoggerModel->startLogger(dataLoggerView->isOverwrite()); -} +void DataLoggerController::startLogger() { dataLoggerModel->startLogger(dataLoggerView->isOverwrite()); } -void DataLoggerController::stopLogger() -{ - dataLoggerModel->stopLogger(); -} +void DataLoggerController::stopLogger() { dataLoggerModel->stopLogger(); } -void DataLoggerController::setUseNativeDialog(bool nativeDialog) -{ - dataLoggerView->setUseNativeDialog(nativeDialog); -} +void DataLoggerController::setUseNativeDialog(bool nativeDialog) { dataLoggerView->setUseNativeDialog(nativeDialog); } void DataLoggerController::createChannel(QString name, CHANNEL_DATA_TYPE type) { - CHANNEL_FILTER filter = CHANNEL_FILTER::LAST_VALUE ; + CHANNEL_FILTER filter = CHANNEL_FILTER::LAST_VALUE; QString uiFilter = dataLoggerView->getFilter(); - if (uiFilter == "Average") { + if(uiFilter == "Average") { filter = CHANNEL_FILTER::AVERAGE; } - if (uiFilter == "All") { + if(uiFilter == "All") { filter = CHANNEL_FILTER::ALL; } - dataLoggerModel->createChannel(name,type,filter); + dataLoggerModel->createChannel(name, type, filter); } -void DataLoggerController::destroyChannel(QString name) -{ - dataLoggerModel->destroyChannel(name); -} +void DataLoggerController::destroyChannel(QString name) { dataLoggerModel->destroyChannel(name); } -void DataLoggerController::resetChannel(QString name) -{ - dataLoggerModel->resetChannel(name); -} +void DataLoggerController::resetChannel(QString name) { dataLoggerModel->resetChannel(name); } -void DataLoggerController::receiveValue(QString name, QString value) -{ - dataLoggerModel->receiveValue(name,value); -} +void DataLoggerController::receiveValue(QString name, QString value) { dataLoggerModel->receiveValue(name, value); } -QWidget* DataLoggerController::getWidget() -{ - return dataLoggerView->getDataLoggerViewWidget(); -} +QWidget *DataLoggerController::getWidget() { return dataLoggerView->getDataLoggerViewWidget(); } -bool DataLoggerController::isDataLoggerOn() -{ - return dataLoggerView->isDataLoggingOn(); -} +bool DataLoggerController::isDataLoggerOn() { return dataLoggerView->isDataLoggingOn(); } -void DataLoggerController::setWarningMessage(QString message) -{ - dataLoggerView->setWarningMessage(message); -} +void DataLoggerController::setWarningMessage(QString message) { dataLoggerView->setWarningMessage(message); } void DataLoggerController::setIsRunningOn(bool newIsRunningOn) { isRunningOn = newIsRunningOn; - if (isRunningOn) { + if(isRunningOn) { attemptDataLogging(); } else { Q_EMIT isDataLogging(false); @@ -89,16 +63,16 @@ void DataLoggerController::setIsRunningOn(bool newIsRunningOn) void DataLoggerController::dataLoggerToggled(bool toggled) { dataLoggerView->toggleDataLoggerSwitch(toggled); - if (isRunningOn && !toggled) { + if(isRunningOn && !toggled) { dataLoggerView->disableDataLogging(true); stopLogger(); Q_EMIT isDataLogging(false); } - } -void DataLoggerController::attemptDataLogging(){ - if (dataLoggerView->isDataLoggingOn() && !dataLoggerView->getDataLoggerPath().isEmpty()) { +void DataLoggerController::attemptDataLogging() +{ + if(dataLoggerView->isDataLoggingOn() && !dataLoggerView->getDataLoggerPath().isEmpty()) { startLogger(); dataLoggerView->disableDataLogging(false); Q_EMIT isDataLogging(true); @@ -116,25 +90,13 @@ void DataLoggerController::setPath(QString path) dataLoggerModel->setPath(path); } -QString DataLoggerController::getPath() -{ - return dataLoggerView->getDataLoggerPath(); -} +QString DataLoggerController::getPath() { return dataLoggerView->getDataLoggerPath(); } -bool DataLoggerController::isOverwrite() -{ - return dataLoggerView->isOverwrite(); -} +bool DataLoggerController::isOverwrite() { return dataLoggerView->isOverwrite(); } -void DataLoggerController::setOverwrite(bool en) -{ - dataLoggerView->setOverwrite(en); -} +void DataLoggerController::setOverwrite(bool en) { dataLoggerView->setOverwrite(en); } -int DataLoggerController::getRecordingTimeInterval() -{ - return dataLoggerView->getTimerInterval(); -} +int DataLoggerController::getRecordingTimeInterval() { return dataLoggerView->getTimerInterval(); } void DataLoggerController::setRecodingTimeInterval(int interval) { @@ -147,4 +109,3 @@ DataLoggerController::~DataLoggerController() delete dataLoggerModel; delete dataLoggerView; } - diff --git a/plugins/datalogger/src/dataloggercontroller.hpp b/plugins/datalogger/src/dataloggercontroller.hpp index 2093a134a4..b88f69a968 100644 --- a/plugins/datalogger/src/dataloggercontroller.hpp +++ b/plugins/datalogger/src/dataloggercontroller.hpp @@ -1,14 +1,13 @@ #ifndef DATALOGGERCONTROLLER_H #define DATALOGGERCONTROLLER_H -#include "gui/dataloggerview.hpp" #include "dataloggermodel.h" - +#include "gui/dataloggerview.hpp" namespace scopy { namespace datalogger { -class DataLoggerController: public QObject +class DataLoggerController : public QObject { Q_OBJECT public: @@ -48,9 +47,8 @@ public Q_SLOTS: gui::DataLoggerView *dataLoggerView; bool isRunningOn; void attemptDataLogging(); - }; -} -} +} // namespace datalogger +} // namespace scopy #endif // DATALOGGERCONTROLLER_H diff --git a/plugins/datalogger/src/dataloggermodel.cpp b/plugins/datalogger/src/dataloggermodel.cpp index 25bdaab73e..44d0583187 100644 --- a/plugins/datalogger/src/dataloggermodel.cpp +++ b/plugins/datalogger/src/dataloggermodel.cpp @@ -5,54 +5,47 @@ using namespace scopy; using namespace datalogger; -DataLoggerModel::DataLoggerModel(): - m_path(""), - m_timer(new QTimer()) +DataLoggerModel::DataLoggerModel() + : m_path("") + , m_timer(new QTimer()) { - QObject::connect(m_timer, &QTimer::timeout , this, [=](){ - QtConcurrent::run(this, &DataLoggerModel::logData); - }); + QObject::connect(m_timer, &QTimer::timeout, this, + [=]() { QtConcurrent::run(this, &DataLoggerModel::logData); }); } -void DataLoggerModel::setPath(QString path) -{ - m_path = path; -} +void DataLoggerModel::setPath(QString path) { m_path = path; } -void DataLoggerModel::setTimerInterval(double interval) -{ - m_timer->setInterval(interval); -} +void DataLoggerModel::setTimerInterval(double interval) { m_timer->setInterval(interval); } void DataLoggerModel::startLogger(bool overwrite) { m_timer->start(); - //when overwrite also create file header - if (overwrite) { + // when overwrite also create file header + if(overwrite) { FileManager *fm = new FileManager("Data Logger"); fm->open(m_path, FileManager::EXPORT); QStringList chNames; - if (!m_channels.empty()) { - for (auto ch: m_channels.keys()) { + if(!m_channels.empty()) { + for(auto ch : m_channels.keys()) { chNames.push_back(ch); } } - QMap> dataToLog; + QMap> dataToLog; - dataToLog["Timestamp"]= {}; - if (!m_channels.empty()) { - for (auto ch: m_channels.keys()) { - dataToLog[ch]= {}; + dataToLog["Timestamp"] = {}; + if(!m_channels.empty()) { + for(auto ch : m_channels.keys()) { + dataToLog[ch] = {}; } } - fm->writeToFile(overwrite,dataToLog); + fm->writeToFile(overwrite, dataToLog); } } void DataLoggerModel::stopLogger() { - if (m_timer->isActive()) { + if(m_timer->isActive()) { m_timer->stop(); } } @@ -63,46 +56,37 @@ void DataLoggerModel::createChannel(QString name, CHANNEL_DATA_TYPE type, CHANNE m_channels[name].filter = filter; } -void DataLoggerModel::destroyChannel(QString name) -{ - m_channels.remove(name); -} +void DataLoggerModel::destroyChannel(QString name) { m_channels.remove(name); } -void DataLoggerModel::resetChannel(QString name) -{ - m_channels[name].values.clear(); -} +void DataLoggerModel::resetChannel(QString name) { m_channels[name].values.clear(); } -void DataLoggerModel::receiveValue(QString name, QString value) -{ - m_channels[name].values.push_back(value); -} +void DataLoggerModel::receiveValue(QString name, QString value) { m_channels[name].values.push_back(value); } void DataLoggerModel::logData() { - QMap> dataToLog; + QMap> dataToLog; QString data = ""; - for (auto ch: m_channels.keys()) { - if (ch == "Timestamp") { + for(auto ch : m_channels.keys()) { + if(ch == "Timestamp") { continue; } data = ""; - //apply filter on stored data - if (m_channels[ch].filter == CHANNEL_FILTER::LAST_VALUE && !m_channels[ch].values.empty()) { + // apply filter on stored data + if(m_channels[ch].filter == CHANNEL_FILTER::LAST_VALUE && !m_channels[ch].values.empty()) { data += m_channels[ch].values.last(); dataToLog[ch].push_back(data); resetChannel(ch); continue; } - if (m_channels[ch].filter == CHANNEL_FILTER::AVERAGE && !m_channels[ch].values.empty()) { + if(m_channels[ch].filter == CHANNEL_FILTER::AVERAGE && !m_channels[ch].values.empty()) { double avg = computeAvg(m_channels[ch].values); dataToLog[ch].push_back(QString::number(avg)); resetChannel(ch); continue; } - if (m_channels[ch].filter == CHANNEL_FILTER::ALL && !m_channels[ch].values.empty()) { - for(auto v : m_channels[ch].values){ + if(m_channels[ch].filter == CHANNEL_FILTER::ALL && !m_channels[ch].values.empty()) { + for(auto v : m_channels[ch].values) { data += v + " "; } dataToLog[ch].push_back(data); @@ -115,19 +99,19 @@ void DataLoggerModel::logData() fm->open(m_path, FileManager::EXPORT); QStringList chNames; - if (!m_channels.empty()) { - for (auto ch: m_channels.keys()) { + if(!m_channels.empty()) { + for(auto ch : m_channels.keys()) { chNames.push_back(ch); } } - dataToLog["Timestamp"]={QDateTime::currentDateTime().time().toString()}; - fm->writeToFile(false,dataToLog); + dataToLog["Timestamp"] = {QDateTime::currentDateTime().time().toString()}; + fm->writeToFile(false, dataToLog); } double DataLoggerModel::computeAvg(QVector values) { double result = 0; - for (QString v : values) { + for(QString v : values) { assert(isNumber(v)); result += v.toDouble(); } @@ -135,15 +119,13 @@ double DataLoggerModel::computeAvg(QVector values) return result; } -bool DataLoggerModel::isNumber(const QString& str) +bool DataLoggerModel::isNumber(const QString &str) { - for (QChar const &c : str) { - if (!( c.isDigit() || c == ".")) return false; + for(QChar const &c : str) { + if(!(c.isDigit() || c == ".")) + return false; } return true; } -DataLoggerModel::~DataLoggerModel() -{ - delete m_timer; -} +DataLoggerModel::~DataLoggerModel() { delete m_timer; } diff --git a/plugins/datalogger/src/dataloggermodel.h b/plugins/datalogger/src/dataloggermodel.h index 7fbff5f99d..bc21b65449 100644 --- a/plugins/datalogger/src/dataloggermodel.h +++ b/plugins/datalogger/src/dataloggermodel.h @@ -1,35 +1,38 @@ #ifndef DataLoggerModel_H #define DataLoggerModel_H +#include +#include #include -#include #include -#include -#include #include +#include namespace scopy { namespace datalogger { -enum class CHANNEL_DATA_TYPE{ +enum class CHANNEL_DATA_TYPE +{ INT, DOUBLE, QSTRING }; -enum class CHANNEL_FILTER{ +enum class CHANNEL_FILTER +{ LAST_VALUE, AVERAGE, ALL }; -struct Channel{ +struct Channel +{ CHANNEL_DATA_TYPE type; CHANNEL_FILTER filter; QVector values; }; -class DataLoggerModel: public QObject +class DataLoggerModel : public QObject { Q_OBJECT @@ -50,14 +53,14 @@ public Q_SLOTS: private: QString m_path; - QTimer *m_timer; - QMap m_channels; + QTimer *m_timer; + QMap m_channels; const QString SEPARATOR = ","; double computeAvg(QVector values); bool isNumber(const QString &str); }; -} -} +} // namespace datalogger +} // namespace scopy #endif // DataLoggerModel_H diff --git a/plugins/datalogger/src/dataloggerplugin.cpp b/plugins/datalogger/src/dataloggerplugin.cpp index befa43f5f9..9907ecb15c 100644 --- a/plugins/datalogger/src/dataloggerplugin.cpp +++ b/plugins/datalogger/src/dataloggerplugin.cpp @@ -1,20 +1,23 @@ #include "dataloggerplugin.h" -#include "qloggingcategory.h" + #include "datalogger_api.h" +#include "pluginbase/scopyjs.h" +#include "qloggingcategory.h" + #include -#include -#include + #include +#include #include -#include "pluginbase/scopyjs.h" -#include +#include +#include using namespace scopy; using namespace datalogger; -Q_LOGGING_CATEGORY(CAT_DATALOGGER,"DataLoggerPlugin"); -Q_LOGGING_CATEGORY(CAT_DATALOGGER_TOOL,"dataloggerTool"); +Q_LOGGING_CATEGORY(CAT_DATALOGGER, "DataLoggerPlugin"); +Q_LOGGING_CATEGORY(CAT_DATALOGGER_TOOL, "dataloggerTool"); bool DataLoggerPlugin::loadPage() { @@ -31,19 +34,18 @@ bool DataLoggerPlugin::loadIcon() void DataLoggerPlugin::loadToolList() { - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("datalogger", "Datalogger", ":/gui/icons/scopy-default/icons/tool_debugger.svg")); + m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("datalogger", "Datalogger", + ":/gui/icons/scopy-default/icons/tool_debugger.svg")); } -void DataLoggerPlugin::unload() -{ -} +void DataLoggerPlugin::unload() {} bool DataLoggerPlugin::compatible(QString param, QString cateogory) { m_name = "Datalogger"; ContextProvider *cp = ContextProvider::GetInstance(); - iio_context* ctx = cp->open(param); + iio_context *ctx = cp->open(param); if(!ctx) { qWarning(CAT_DATALOGGER) << "No context available for datalogger"; @@ -58,10 +60,10 @@ bool DataLoggerPlugin::compatible(QString param, QString cateogory) bool DataLoggerPlugin::onConnect() { ContextProvider *cp = ContextProvider::GetInstance(); - iio_context* ctx = cp->open(m_param); + iio_context *ctx = cp->open(m_param); libm2k_context = libm2k::context::contextOpen(ctx, ""); ping = new IIOPingTask(ctx); - cs = new CyclicalTask(ping,this); + cs = new CyclicalTask(ping, this); cs->start(2000); tool = new DataLogger(libm2k_context); @@ -72,15 +74,15 @@ bool DataLoggerPlugin::onConnect() m_toolList[0]->setTool(tool); m_toolList[0]->setRunBtnVisible(true); - connect(ping, &IIOPingTask::pingFailed, this, [this](){Q_EMIT disconnectDevice();} ); - connect(ping, &IIOPingTask::pingSuccess, this, [](){qDebug(CAT_DATALOGGER)<<"Ping Success";} ); - connect(tool->getRunButton(),&QPushButton::toggled, this,[=](bool en){ - if (m_toolList[0]->running() != en) { + connect(ping, &IIOPingTask::pingFailed, this, [this]() { Q_EMIT disconnectDevice(); }); + connect(ping, &IIOPingTask::pingSuccess, this, []() { qDebug(CAT_DATALOGGER) << "Ping Success"; }); + connect(tool->getRunButton(), &QPushButton::toggled, this, [=](bool en) { + if(m_toolList[0]->running() != en) { m_toolList[0]->setRunning(en); } }); - connect(m_toolList[0],&ToolMenuEntry::runToggled, this,[=](bool en){ - if (tool->getRunButton()->isChecked() != en) { + connect(m_toolList[0], &ToolMenuEntry::runToggled, this, [=](bool en) { + if(tool->getRunButton()->isChecked() != en) { tool->getRunButton()->setChecked(en); } }); @@ -93,17 +95,16 @@ bool DataLoggerPlugin::onDisconnect() delete tool; cs->stop(); - for (auto & tool : m_toolList) { + for(auto &tool : m_toolList) { tool->setEnabled(false); tool->setTool(nullptr); m_toolList[0]->setRunBtnVisible(false); } try { - contextClose(libm2k_context,true); + contextClose(libm2k_context, true); } catch(std::exception &ex) { - qDebug(CAT_DATALOGGER)<save(s); -} - -void DataLoggerPlugin::loadSettings(QSettings &s) -{ - api->load(s); -} - -QString DataLoggerPlugin::description() -{ - return "Use IIO raw and scale attributes to plot and save data"; -} +void DataLoggerPlugin::saveSettings(QSettings &s) { api->save(s); } +void DataLoggerPlugin::loadSettings(QSettings &s) { api->load(s); } +QString DataLoggerPlugin::description() { return "Use IIO raw and scale attributes to plot and save data"; } #include "moc_dataloggerplugin.cpp" diff --git a/plugins/datalogger/src/dataloggerreaderthread.cpp b/plugins/datalogger/src/dataloggerreaderthread.cpp index 5b5f5b13c6..9dd777654b 100644 --- a/plugins/datalogger/src/dataloggerreaderthread.cpp +++ b/plugins/datalogger/src/dataloggerreaderthread.cpp @@ -1,24 +1,17 @@ #include "dataloggerreaderthread.hpp" + #include "qdebug.h" + #include using namespace scopy; using namespace datalogger; -DataLoggerReaderThread::DataLoggerReaderThread() -{ - -} +DataLoggerReaderThread::DataLoggerReaderThread() {} -void DataLoggerReaderThread::setDataLoggerStatus(bool status) -{ - dataLoggerStatus = status; -} +void DataLoggerReaderThread::setDataLoggerStatus(bool status) { dataLoggerStatus = status; } -void DataLoggerReaderThread::channelToggled(int id, bool toggled) -{ - m_activeChannels[id].first = toggled; -} +void DataLoggerReaderThread::channelToggled(int id, bool toggled) { m_activeChannels[id].first = toggled; } void DataLoggerReaderThread::addChannel(int id, std::string dmmId, libm2k::analog::DMM *dmm) { @@ -30,22 +23,26 @@ void DataLoggerReaderThread::addChannel(int id, std::string dmmId, libm2k::analo void DataLoggerReaderThread::run() { try { - if (!m_activeChannels.empty()) { - for (int ch : m_activeChannels.keys()) { - //check if channel was closed before reading - if (m_activeChannels[ch].first) { - auto updatedRead = m_activeChannels[ch].second.dmm->readChannel(m_activeChannels[ch].second.dmmId); - Q_EMIT updateChannelData(ch, updatedRead.value, QString::fromStdString(updatedRead.unit_name), - QString::fromStdString(updatedRead.unit_symbol)); - if (dataLoggerStatus) { - Q_EMIT updateDataLoggerValue(QString::fromStdString(m_activeChannels[ch].second.dmm->getName() + ":" + m_activeChannels[ch].second.dmmId), - QString::number(updatedRead.value)); + if(!m_activeChannels.empty()) { + for(int ch : m_activeChannels.keys()) { + // check if channel was closed before reading + if(m_activeChannels[ch].first) { + auto updatedRead = m_activeChannels[ch].second.dmm->readChannel( + m_activeChannels[ch].second.dmmId); + Q_EMIT updateChannelData(ch, updatedRead.value, + QString::fromStdString(updatedRead.unit_name), + QString::fromStdString(updatedRead.unit_symbol)); + if(dataLoggerStatus) { + Q_EMIT updateDataLoggerValue( + QString::fromStdString( + m_activeChannels[ch].second.dmm->getName() + ":" + + m_activeChannels[ch].second.dmmId), + QString::number(updatedRead.value)); } } } } - } catch (...) { - qDebug()<<"Failed to acquire data on DataLogger:dmmReadChannel"; + } catch(...) { + qDebug() << "Failed to acquire data on DataLogger:dmmReadChannel"; } - } diff --git a/plugins/datalogger/src/dataloggerreaderthread.hpp b/plugins/datalogger/src/dataloggerreaderthread.hpp index d7656814bf..b9dbb16398 100644 --- a/plugins/datalogger/src/dataloggerreaderthread.hpp +++ b/plugins/datalogger/src/dataloggerreaderthread.hpp @@ -1,23 +1,22 @@ #ifndef DATALOGGERREADERTHREAD_HPP #define DATALOGGERREADERTHREAD_HPP - +#include #include #include -#include #include namespace scopy { namespace datalogger { -struct activeChannel{ +struct activeChannel +{ std::string dmmId; - libm2k::analog::DMM* dmm; + libm2k::analog::DMM *dmm; }; - -class DataLoggerReaderThread : public QThread +class DataLoggerReaderThread : public QThread { Q_OBJECT public: @@ -26,20 +25,19 @@ class DataLoggerReaderThread : public QThread public Q_SLOTS: void setDataLoggerStatus(bool status); void channelToggled(int id, bool toggled); - void addChannel(int id, std::string dmmId, libm2k::analog::DMM* dmm); + void addChannel(int id, std::string dmmId, libm2k::analog::DMM *dmm); Q_SIGNALS: - void updateChannelData(int chId, double value,QString nameOfUnitOfMeasure,QString symbolOfUnitOfMeasure); + void updateChannelData(int chId, double value, QString nameOfUnitOfMeasure, QString symbolOfUnitOfMeasure); void updateDataLoggerValue(QString name, QString value); private: void run() override; bool dataLoggerStatus; - QMap> m_activeChannels ; - + QMap> m_activeChannels; }; -} -} +} // namespace datalogger +} // namespace scopy #endif // DATALOGGERREADERTHREAD_HPP diff --git a/plugins/datalogger/src/gui/channelmonitorcomponent.cpp b/plugins/datalogger/src/gui/channelmonitorcomponent.cpp index 347c58b03d..5e5c088024 100644 --- a/plugins/datalogger/src/gui/channelmonitorcomponent.cpp +++ b/plugins/datalogger/src/gui/channelmonitorcomponent.cpp @@ -1,25 +1,25 @@ #include "channelmonitorcomponent.hpp" + #include "ui_channelmonitorcomponent.h" #include - using namespace scopy; using namespace datalogger; using namespace gui; -ChannelMonitorComponent::ChannelMonitorComponent(QWidget *parent) : - QWidget(parent), - ui(new Ui::ChannelMonitorComponent), - m_minValue(Q_INFINITY), - m_maxValue(-Q_INFINITY) +ChannelMonitorComponent::ChannelMonitorComponent(QWidget *parent) + : QWidget(parent) + , ui(new Ui::ChannelMonitorComponent) + , m_minValue(Q_INFINITY) + , m_maxValue(-Q_INFINITY) { ui->setupUi(this); ui->frame->setStyleSheet("QWidget#frame{border: 3px solid grey;}"); - } -void ChannelMonitorComponent::init(double value,QString nameOfUnitOfMeasure,QString symbolOfUnitOfMeasure, QString title,QColor color) +void ChannelMonitorComponent::init(double value, QString nameOfUnitOfMeasure, QString symbolOfUnitOfMeasure, + QString title, QColor color) { ui->scaleCh1->setOrientation(Qt::Horizontal); @@ -30,11 +30,11 @@ void ChannelMonitorComponent::init(double value,QString nameOfUnitOfMeasure,QStr ui->monitorTitle->setText(title); - //set unit of measure for components + // set unit of measure for components ui->labelCh1->setText(symbolOfUnitOfMeasure); ui->label_minUnitOfMeasure->setText(symbolOfUnitOfMeasure); ui->label_maxUnitOfMeasure->setText(symbolOfUnitOfMeasure); - ui->sismograph_ch1_2->setPlotAxisXTitle(nameOfUnitOfMeasure + "(" +symbolOfUnitOfMeasure + ")"); + ui->sismograph_ch1_2->setPlotAxisXTitle(nameOfUnitOfMeasure + "(" + symbolOfUnitOfMeasure + ")"); setColor(color); @@ -45,7 +45,7 @@ void ChannelMonitorComponent::init(double value,QString nameOfUnitOfMeasure,QStr setMonitorColor(color.name()); } -void ChannelMonitorComponent::updateValue(double value,QString nameOfUnitOfMeasure,QString symbolOfUnitOfMeasure) +void ChannelMonitorComponent::updateValue(double value, QString nameOfUnitOfMeasure, QString symbolOfUnitOfMeasure) { MetricPrefixFormatter m_prefixFormater; @@ -62,24 +62,20 @@ void ChannelMonitorComponent::updateValue(double value,QString nameOfUnitOfMeasu checkPeakValues(value, symbolOfUnitOfMeasure); } -void ChannelMonitorComponent::resizeEvent(QResizeEvent *event) -{ - Q_EMIT contentChanged(); -} - +void ChannelMonitorComponent::resizeEvent(QResizeEvent *event) { Q_EMIT contentChanged(); } -void ChannelMonitorComponent::checkPeakValues(double value,QString unitOfMeasure) +void ChannelMonitorComponent::checkPeakValues(double value, QString unitOfMeasure) { MetricPrefixFormatter m_prefixFormater; QString formatedPrefix = m_prefixFormater.getFormatedMeasureUnit(value); double formatedValue = m_prefixFormater.getFormatedValue(value); - if (value < m_minValue) { + if(value < m_minValue) { m_minValue = value; ui->minCh1->display(formatedValue); ui->label_minUnitOfMeasure->setText(formatedPrefix + unitOfMeasure); } - if (value > m_maxValue) { + if(value > m_maxValue) { m_maxValue = value; ui->maxCh1->display(formatedValue); ui->label_maxUnitOfMeasure->setText(formatedPrefix + unitOfMeasure); @@ -96,7 +92,7 @@ void ChannelMonitorComponent::resetPeakHolder() void ChannelMonitorComponent::displayPeakHold(bool checked) { - if (checked) { + if(checked) { ui->minCh1->show(); ui->label_min->show(); ui->label_minUnitOfMeasure->show(); @@ -115,7 +111,7 @@ void ChannelMonitorComponent::displayPeakHold(bool checked) void ChannelMonitorComponent::displayHistory(bool checked) { - if (checked) { + if(checked) { ui->sismograph_ch1_2->show(); } else { ui->sismograph_ch1_2->hide(); @@ -124,36 +120,24 @@ void ChannelMonitorComponent::displayHistory(bool checked) void ChannelMonitorComponent::displayScale(bool checked) { - if (checked) { + if(checked) { ui->scaleCh1->show(); } else { ui->scaleCh1->hide(); } } -std::string ChannelMonitorComponent::getChannelId() -{ - return m_channelId; -} +std::string ChannelMonitorComponent::getChannelId() { return m_channelId; } -void ChannelMonitorComponent::setChannelId(std::string channelId) -{ - m_channelId = channelId; -} +void ChannelMonitorComponent::setChannelId(std::string channelId) { m_channelId = channelId; } -QString ChannelMonitorComponent::getTitle() -{ - return ui->monitorTitle->text(); -} +QString ChannelMonitorComponent::getTitle() { return ui->monitorTitle->text(); } void ChannelMonitorComponent::updateUnitOfMeasure(QString unitOfMeasure) { m_unitOfMeasure = unitOfMeasure; ui->labelCh1->setText(unitOfMeasure); } -QString ChannelMonitorComponent::getUnitOfMeasure() -{ - return m_unitOfMeasure; -} +QString ChannelMonitorComponent::getUnitOfMeasure() { return m_unitOfMeasure; } void ChannelMonitorComponent::updateLcdNumberPrecision(int precision) { @@ -167,10 +151,10 @@ void ChannelMonitorComponent::updateLcdNumberPrecision(int precision) ui->maxCh1->setPrecision(precision); ui->maxCh1->setDigitCount(4 + precision); - if (m_minValue != Q_INFINITY) { + if(m_minValue != Q_INFINITY) { ui->minCh1->display(m_minValue); } - if (m_maxValue != -Q_INFINITY) { + if(m_maxValue != -Q_INFINITY) { ui->maxCh1->display(m_maxValue); } } @@ -178,51 +162,33 @@ void ChannelMonitorComponent::updateLcdNumberPrecision(int precision) void ChannelMonitorComponent::setMonitorColor(QString color) { ui->sismograph_ch1_2->setColor(QColor(color)); - ui->lcdCh1->setStyleSheet("QLCDNumber{color: "+color+" ;}"); - ui->minCh1->setStyleSheet("QLCDNumber{color: "+color+" ;}"); - ui->maxCh1->setStyleSheet("QLCDNumber{color: "+color+" ;}"); + ui->lcdCh1->setStyleSheet("QLCDNumber{color: " + color + " ;}"); + ui->minCh1->setStyleSheet("QLCDNumber{color: " + color + " ;}"); + ui->maxCh1->setStyleSheet("QLCDNumber{color: " + color + " ;}"); } -void ChannelMonitorComponent::setHistoryDuration(int duration) -{ - ui->sismograph_ch1_2->setHistoryDuration(duration); -} +void ChannelMonitorComponent::setHistoryDuration(int duration) { ui->sismograph_ch1_2->setHistoryDuration(duration); } void ChannelMonitorComponent::setRecordingInterval(double interval) { - ui->sismograph_ch1_2->setSampleRate(1/interval); + ui->sismograph_ch1_2->setSampleRate(1 / interval); } void ChannelMonitorComponent::setColor(QColor color) { m_color = color; ui->sismograph_ch1_2->setColor(color); - ui->lcdCh1->setStyleSheet("QLCDNumber{color: "+color.name()+" ;}"); - ui->minCh1->setStyleSheet("QLCDNumber{color: "+color.name()+" ;}"); - ui->maxCh1->setStyleSheet("QLCDNumber{color: "+color.name()+" ;}"); + ui->lcdCh1->setStyleSheet("QLCDNumber{color: " + color.name() + " ;}"); + ui->minCh1->setStyleSheet("QLCDNumber{color: " + color.name() + " ;}"); + ui->maxCh1->setStyleSheet("QLCDNumber{color: " + color.name() + " ;}"); } -QColor ChannelMonitorComponent::getColor() -{ - return m_color; -} +QColor ChannelMonitorComponent::getColor() { return m_color; } -void ChannelMonitorComponent::setID(int id) -{ - m_id = id; -} +void ChannelMonitorComponent::setID(int id) { m_id = id; } -int ChannelMonitorComponent::getID() -{ - return m_id; -} +int ChannelMonitorComponent::getID() { return m_id; } -void ChannelMonitorComponent::setLineStyle(Qt::PenStyle lineStyle) -{ - ui->sismograph_ch1_2->setLineStyle(lineStyle); -} +void ChannelMonitorComponent::setLineStyle(Qt::PenStyle lineStyle) { ui->sismograph_ch1_2->setLineStyle(lineStyle); } -ChannelMonitorComponent::~ChannelMonitorComponent() -{ - delete ui; -} +ChannelMonitorComponent::~ChannelMonitorComponent() { delete ui; } diff --git a/plugins/datalogger/src/gui/channelmonitorcomponent.hpp b/plugins/datalogger/src/gui/channelmonitorcomponent.hpp index 0245c20745..c6d8b0c482 100644 --- a/plugins/datalogger/src/gui/channelmonitorcomponent.hpp +++ b/plugins/datalogger/src/gui/channelmonitorcomponent.hpp @@ -1,8 +1,8 @@ #ifndef CHANNELMONITORCOMPONENT_H #define CHANNELMONITORCOMPONENT_H -#include #include +#include namespace Ui { class ChannelMonitorComponent; @@ -20,7 +20,8 @@ class ChannelMonitorComponent : public QWidget explicit ChannelMonitorComponent(QWidget *parent = nullptr); ~ChannelMonitorComponent(); - void init(double value, QString nameOfUnitOfMeasure,QString symbolOfUnitOfMeasure, QString title, QColor color); + void init(double value, QString nameOfUnitOfMeasure, QString symbolOfUnitOfMeasure, QString title, + QColor color); std::string getChannelId(); void setChannelId(std::string channelId); void checkPeakValues(double value, QString unitOfMeasure); @@ -38,7 +39,6 @@ class ChannelMonitorComponent : public QWidget Q_SIGNALS: void contentChanged(); - public Q_SLOTS: void displayPeakHold(bool checked); void resetPeakHolder(); @@ -49,7 +49,7 @@ public Q_SLOTS: void setHistoryDuration(int duration); void setRecordingInterval(double interval); void setLineStyle(Qt::PenStyle lineStyle); - void updateValue(double value, QString nameOfUnitOfMeasure,QString symbolOfUnitOfMeasure); + void updateValue(double value, QString nameOfUnitOfMeasure, QString symbolOfUnitOfMeasure); private: Ui::ChannelMonitorComponent *ui; @@ -61,8 +61,8 @@ public Q_SLOTS: int m_id; void resizeEvent(QResizeEvent *event); }; -} -} -} +} // namespace gui +} // namespace datalogger +} // namespace scopy #endif // CHANNELMONITORCOMPONENT_H diff --git a/plugins/datalogger/src/gui/dataloggergenericmenu.cpp b/plugins/datalogger/src/gui/dataloggergenericmenu.cpp index 574f43575c..16c9ad9918 100644 --- a/plugins/datalogger/src/gui/dataloggergenericmenu.cpp +++ b/plugins/datalogger/src/gui/dataloggergenericmenu.cpp @@ -1,38 +1,38 @@ #include "dataloggergenericmenu.hpp" -#include #include +#include #include + #include using namespace scopy; using namespace datalogger; using namespace datalogger::gui; -DataLoggerGenericMenu::DataLoggerGenericMenu(QWidget *parent): - GenericMenu(parent) +DataLoggerGenericMenu::DataLoggerGenericMenu(QWidget *parent) + : GenericMenu(parent) { - connect(this, &DataLoggerGenericMenu::historySizeIndexChanged, this, &DataLoggerGenericMenu::setHistorySize ); - connect(this, &DataLoggerGenericMenu::lineStyleIndexChanged, this, &DataLoggerGenericMenu::changeLineStyle ); + connect(this, &DataLoggerGenericMenu::historySizeIndexChanged, this, &DataLoggerGenericMenu::setHistorySize); + connect(this, &DataLoggerGenericMenu::lineStyleIndexChanged, this, &DataLoggerGenericMenu::changeLineStyle); } -DataLoggerGenericMenu::~DataLoggerGenericMenu() -{} +DataLoggerGenericMenu::~DataLoggerGenericMenu() {} -void DataLoggerGenericMenu::init(QString title, QColor* color) +void DataLoggerGenericMenu::init(QString title, QColor *color) { initInteractiveMenu(); - setMenuHeader(title,color,false); + setMenuHeader(title, color, false); scopy::gui::SubsectionSeparator *scaleSection = new scopy::gui::SubsectionSeparator("Settings", false); insertSection(scaleSection); - //scale + // scale QHBoxLayout *scaleLayout = new QHBoxLayout(); scaleSWitch = new CustomSwitch(scaleSection->getContentWidget()); scaleSWitch->setChecked(true); - scaleLayout->addWidget(new QLabel("Scale",scaleSection->getContentWidget())); + scaleLayout->addWidget(new QLabel("Scale", scaleSection->getContentWidget())); scaleLayout->addWidget(scaleSWitch); scaleSection->getContentWidget()->layout()->addItem(scaleLayout); @@ -44,7 +44,7 @@ void DataLoggerGenericMenu::init(QString title, QColor* color) historySwitch = new CustomSwitch(historySection->getContentWidget()); historySwitch->setChecked(true); historySection->getContentWidget()->layout()->addWidget(historySwitch); - historySection->getContentWidget()->layout()->setAlignment(historySwitch,Qt::AlignRight); + historySection->getContentWidget()->layout()->setAlignment(historySwitch, Qt::AlignRight); historySize = new QComboBox(historySection->getContentWidget()); historySize->addItem(QString("1s")); @@ -54,7 +54,7 @@ void DataLoggerGenericMenu::init(QString title, QColor* color) QHBoxLayout *h1layout = new QHBoxLayout(); - h1layout->addWidget(new QLabel("History Size",historySection->getContentWidget())); + h1layout->addWidget(new QLabel("History Size", historySection->getContentWidget())); h1layout->addWidget(historySize); historySection->getContentWidget()->layout()->addItem(h1layout); @@ -68,7 +68,7 @@ void DataLoggerGenericMenu::init(QString title, QColor* color) historyStyle->addItem(QString("Dash-Dot-Dot Line")); historyStyle->setCurrentIndex(0); - h2layout->addWidget(new QLabel("History Style",historySection->getContentWidget())); + h2layout->addWidget(new QLabel("History Style", historySection->getContentWidget())); h2layout->addWidget(historyStyle); historySection->getContentWidget()->layout()->addItem(h2layout); @@ -80,46 +80,36 @@ void DataLoggerGenericMenu::init(QString title, QColor* color) QHBoxLayout *peakHolderLayout = new QHBoxLayout(); peakHolderSwitch = new CustomSwitch(peakHolderSection->getContentWidget()); peakHolderSwitch->setChecked(true); - peakHolderReset = new QPushButton("Reset",peakHolderSection->getContentWidget()); - peakHolderReset->setProperty("blue_button",true); + peakHolderReset = new QPushButton("Reset", peakHolderSection->getContentWidget()); + peakHolderReset->setProperty("blue_button", true); peakHolderReset->setMinimumHeight(30); peakHolderLayout->addWidget(peakHolderReset); peakHolderLayout->addWidget(peakHolderSwitch); - peakHolderLayout->setAlignment(peakHolderSwitch,Qt::AlignRight); + peakHolderLayout->setAlignment(peakHolderSwitch, Qt::AlignRight); peakHolderSection->getContentWidget()->layout()->addItem(peakHolderLayout); - layout()->addItem( new QSpacerItem(10,10, QSizePolicy::Fixed, QSizePolicy::Expanding)); + layout()->addItem(new QSpacerItem(10, 10, QSizePolicy::Fixed, QSizePolicy::Expanding)); connect(scaleSWitch, &CustomSwitch::toggled, this, &DataLoggerGenericMenu::toggleScale); - connect(historySwitch, &CustomSwitch::toggled, this, &DataLoggerGenericMenu::toggleHistory); - connect(peakHolderReset, &QPushButton::clicked,this, &DataLoggerGenericMenu::resetPeakHolder); + connect(historySwitch, &CustomSwitch::toggled, this, &DataLoggerGenericMenu::toggleHistory); + connect(peakHolderReset, &QPushButton::clicked, this, &DataLoggerGenericMenu::resetPeakHolder); connect(peakHolderSwitch, &CustomSwitch::toggled, this, &DataLoggerGenericMenu::togglePeakHolder); - connect(historySize, QOverload::of(&QComboBox::currentIndexChanged), this, &DataLoggerGenericMenu::historySizeIndexChanged); - connect(historyStyle, QOverload::of(&QComboBox::currentIndexChanged), this, &DataLoggerGenericMenu::lineStyleIndexChanged); + connect(historySize, QOverload::of(&QComboBox::currentIndexChanged), this, + &DataLoggerGenericMenu::historySizeIndexChanged); + connect(historyStyle, QOverload::of(&QComboBox::currentIndexChanged), this, + &DataLoggerGenericMenu::lineStyleIndexChanged); } -void DataLoggerGenericMenu::scaleToggle(bool toggled) -{ - scaleSWitch->setChecked(toggled); -} +void DataLoggerGenericMenu::scaleToggle(bool toggled) { scaleSWitch->setChecked(toggled); } -void DataLoggerGenericMenu::peakHolderToggle(bool toggled) -{ - peakHolderSwitch->setChecked(toggled); -} +void DataLoggerGenericMenu::peakHolderToggle(bool toggled) { peakHolderSwitch->setChecked(toggled); } -void DataLoggerGenericMenu::historyToggle(bool toggled) -{ - historySwitch->setChecked(toggled); -} +void DataLoggerGenericMenu::historyToggle(bool toggled) { historySwitch->setChecked(toggled); } -void DataLoggerGenericMenu::peakHolderResetClicked() -{ - peakHolderReset->click(); -} +void DataLoggerGenericMenu::peakHolderResetClicked() { peakHolderReset->click(); } void DataLoggerGenericMenu::historySizeChanged(int size) { @@ -133,30 +123,35 @@ void DataLoggerGenericMenu::changeLineStyle(int index) Q_EMIT lineStyleChanged(lineStyleFromIdx(index)); } -void DataLoggerGenericMenu::setHistorySize(int idx) -{ - Q_EMIT changeHistorySize(numSamplesFromIdx(idx)); -} +void DataLoggerGenericMenu::setHistorySize(int idx) { Q_EMIT changeHistorySize(numSamplesFromIdx(idx)); } double DataLoggerGenericMenu::numSamplesFromIdx(int idx) { switch(idx) { - case 0: return 1.0; - case 1: return 10.0; - case 2: return 60.0; - default:throw std::runtime_error("Invalid INDEX"); + case 0: + return 1.0; + case 1: + return 10.0; + case 2: + return 60.0; + default: + throw std::runtime_error("Invalid INDEX"); } } Qt::PenStyle DataLoggerGenericMenu::lineStyleFromIdx(int idx) { - switch (idx) { - case 0: return Qt::PenStyle::SolidLine; - case 1: return Qt::PenStyle::DotLine; - case 2: return Qt::PenStyle::DashLine; - case 3: return Qt::PenStyle::DashDotLine; - case 4: return Qt::PenStyle::DashDotDotLine; + switch(idx) { + case 0: + return Qt::PenStyle::SolidLine; + case 1: + return Qt::PenStyle::DotLine; + case 2: + return Qt::PenStyle::DashLine; + case 3: + return Qt::PenStyle::DashDotLine; + case 4: + return Qt::PenStyle::DashDotDotLine; } return Qt::PenStyle::SolidLine; } - diff --git a/plugins/datalogger/src/gui/dataloggergenericmenu.hpp b/plugins/datalogger/src/gui/dataloggergenericmenu.hpp index cfa01c52b1..be63774042 100644 --- a/plugins/datalogger/src/gui/dataloggergenericmenu.hpp +++ b/plugins/datalogger/src/gui/dataloggergenericmenu.hpp @@ -1,10 +1,11 @@ #ifndef DATALOGGERGENERICMENU_H #define DATALOGGERGENERICMENU_H -#include -#include #include "qcombobox.h" +#include + +#include namespace scopy { class CustomSwitch; @@ -19,7 +20,7 @@ class DataLoggerGenericMenu : public scopy::gui::GenericMenu explicit DataLoggerGenericMenu(QWidget *parent = nullptr); ~DataLoggerGenericMenu(); - void init(QString title, QColor* color); + void init(QString title, QColor *color); public Q_SLOTS: void scaleToggle(bool toggled); @@ -52,8 +53,8 @@ public Q_SLOTS: QComboBox *historyStyle; QComboBox *historySize; }; -} -} -} +} // namespace gui +} // namespace datalogger +} // namespace scopy #endif // DATALOGGERGENERICMENU_H diff --git a/plugins/datalogger/src/gui/dataloggerview.cpp b/plugins/datalogger/src/gui/dataloggerview.cpp index d07f79f3a9..ae5e6e4a59 100644 --- a/plugins/datalogger/src/gui/dataloggerview.cpp +++ b/plugins/datalogger/src/gui/dataloggerview.cpp @@ -4,21 +4,21 @@ using namespace scopy; using namespace datalogger; using namespace gui; -DataLoggerView::DataLoggerView(bool lastValue, bool average, bool all, QWidget *parent) : - QWidget(parent) +DataLoggerView::DataLoggerView(bool lastValue, bool average, bool all, QWidget *parent) + : QWidget(parent) { dataLoggingWidget = new QWidget(this); dataLoggingLayout = new QVBoxLayout(dataLoggingWidget); dataLoggingLayout->layout()->setSpacing(10); dataLoggerFilter = new QComboBox(dataLoggingWidget); - if (lastValue) { + if(lastValue) { dataLoggerFilter->addItem(QString("Last Value")); } - if (average) { + if(average) { dataLoggerFilter->addItem(QString("Average")); } - if (all) { + if(all) { dataLoggerFilter->addItem(QString("All")); } dataLoggerFilter->setCurrentIndex(0); @@ -27,20 +27,19 @@ DataLoggerView::DataLoggerView(bool lastValue, bool average, bool all, QWidget * init(); } - void DataLoggerView::init() { dataLoggingSwitch = new CustomSwitch(dataLoggingWidget); dataLoggingLayout->addWidget(dataLoggingSwitch); - dataLoggingLayout->setAlignment(dataLoggingSwitch,Qt::AlignRight); + dataLoggingLayout->setAlignment(dataLoggingSwitch, Qt::AlignRight); dataLoggingLayout->addWidget(new QLabel("Choose file")); dataLoggingFilePath = new QLineEdit(dataLoggingWidget); dataLoggingFilePath->setReadOnly(true); dataLoggingFilePath->setDisabled(true); - connect(dataLoggingFilePath, &QLineEdit::textChanged, this, [=](QString path){ - if (filename.isEmpty() && dataLoggingFilePath->isEnabled()) { + connect(dataLoggingFilePath, &QLineEdit::textChanged, this, [=](QString path) { + if(filename.isEmpty() && dataLoggingFilePath->isEnabled()) { dataLoggingFilePath->setText(tr("No file selected")); dataLoggingFilePath->setStyleSheet("color:red"); } else { @@ -51,12 +50,12 @@ void DataLoggerView::init() dataLoggingLayout->addWidget(dataLoggingFilePath); dataLoggingBrowseBtn = new QPushButton("Browse"); - dataLoggingBrowseBtn->setProperty("blue_button",true); + dataLoggingBrowseBtn->setProperty("blue_button", true); dataLoggingBrowseBtn->setMinimumHeight(30); dataLoggingBrowseBtn->setDisabled(true); dataLoggingLayout->addWidget(dataLoggingBrowseBtn); - connect(dataLoggingBrowseBtn, &QPushButton::clicked, this , & DataLoggerView::chooseFile); + connect(dataLoggingBrowseBtn, &QPushButton::clicked, this, &DataLoggerView::chooseFile); overwriteRadio = new QRadioButton("Overwrite"); overwriteRadio->setChecked(true); @@ -66,30 +65,21 @@ void DataLoggerView::init() dataLoggingLayout->addWidget(appendRadio); appendRadio->setDisabled(true); - connect(overwriteRadio, &QRadioButton::toggled, [=](bool en) { - appendRadio->setChecked(!en); - }); + connect(overwriteRadio, &QRadioButton::toggled, [=](bool en) { appendRadio->setChecked(!en); }); - connect(appendRadio, &QRadioButton::toggled, [=](bool en) { - overwriteRadio->setChecked(!en); - }); + connect(appendRadio, &QRadioButton::toggled, [=](bool en) { overwriteRadio->setChecked(!en); }); - data_logging_timer = new PositionSpinButton({ - {"s", 1}, - {"min", 60}, - {"h", 3600} - }, tr("Timer"), 0, 3600, - true, false, this); + data_logging_timer = + new PositionSpinButton({{"s", 1}, {"min", 60}, {"h", 3600}}, tr("Timer"), 0, 3600, true, false, this); data_logging_timer->setValue(5); data_logging_timer->setDisabled(true); - connect(data_logging_timer, &PositionSpinButton::valueChanged, this, [=](){ - double interval = data_logging_timer->value() * 1000; //converts to seconds before emiting value - if (interval < 100) { + connect(data_logging_timer, &PositionSpinButton::valueChanged, this, [=]() { + double interval = data_logging_timer->value() * 1000; // converts to seconds before emiting value + if(interval < 100) { interval = 100; - data_logging_timer->setValue(interval/1000); - + data_logging_timer->setValue(interval / 1000); } Q_EMIT timeIntervalChanged(interval); }); @@ -104,53 +94,38 @@ void DataLoggerView::init() dataLoggingLayout->addWidget(warningMessage); - //on data logging switch pressed enable/disable data logging section and emit data loggin toggled - connect(dataLoggingSwitch, &CustomSwitch::toggled, this, [=](bool toggled){ + // on data logging switch pressed enable/disable data logging section and emit data loggin toggled + connect(dataLoggingSwitch, &CustomSwitch::toggled, this, [=](bool toggled) { Q_EMIT toggleDataLogger(toggled); enableDataLoggerFields(toggled); }); - } -void DataLoggerView::setUseNativeDialog(bool nativeDialog) -{ - useNativeDialog = nativeDialog; -} +void DataLoggerView::setUseNativeDialog(bool nativeDialog) { useNativeDialog = nativeDialog; } void DataLoggerView::chooseFile() { QString selectedFilter; if(!useNativeDialog) - filename = QFileDialog::getSaveFileName(this,tr("Export"), "", tr("Comma-separated values files (*.csv);;All Files(*)"),&selectedFilter, QFileDialog::Options(QFileDialog::DontUseNativeDialog)); + filename = QFileDialog::getSaveFileName( + this, tr("Export"), "", tr("Comma-separated values files (*.csv);;All Files(*)"), + &selectedFilter, QFileDialog::Options(QFileDialog::DontUseNativeDialog)); else - filename = QFileDialog::getSaveFileName(this,tr("Export"), "", tr("Comma-separated values files (*.csv);;All Files(*)"),&selectedFilter, QFileDialog::Options()); + filename = QFileDialog::getSaveFileName(this, tr("Export"), "", + tr("Comma-separated values files (*.csv);;All Files(*)"), + &selectedFilter, QFileDialog::Options()); dataLoggingFilePath->setText(filename); } -QWidget* DataLoggerView::getDataLoggerViewWidget() -{ - return dataLoggingWidget; -} +QWidget *DataLoggerView::getDataLoggerViewWidget() { return dataLoggingWidget; } -bool DataLoggerView::isDataLoggingOn() -{ - return dataLoggingSwitch->isChecked(); -} +bool DataLoggerView::isDataLoggingOn() { return dataLoggingSwitch->isChecked(); } -bool DataLoggerView::isOverwrite() -{ - return overwriteRadio->isChecked(); -} +bool DataLoggerView::isOverwrite() { return overwriteRadio->isChecked(); } -QString DataLoggerView::getFilter() -{ - return dataLoggerFilter->currentText(); -} +QString DataLoggerView::getFilter() { return dataLoggerFilter->currentText(); } -void DataLoggerView::setWarningMessage(QString message) -{ - warningMessage->setText(message); -} +void DataLoggerView::setWarningMessage(QString message) { warningMessage->setText(message); } void DataLoggerView::enableDataLoggerFields(bool en) { @@ -162,21 +137,15 @@ void DataLoggerView::enableDataLoggerFields(bool en) dataLoggerFilter->setDisabled(!en); warningMessage->setVisible(en); - if (filename.isEmpty() && dataLoggingFilePath->isEnabled()) { + if(filename.isEmpty() && dataLoggingFilePath->isEnabled()) { dataLoggingFilePath->setText(tr("No file selected")); dataLoggingFilePath->setStyleSheet("color:red"); } } -void DataLoggerView::disableDataLogging(bool en) -{ - dataLoggingSwitch->setEnabled(!en); -} +void DataLoggerView::disableDataLogging(bool en) { dataLoggingSwitch->setEnabled(!en); } -void DataLoggerView::toggleDataLoggerSwitch(bool toggle) -{ - dataLoggingSwitch->setChecked(toggle); -} +void DataLoggerView::toggleDataLoggerSwitch(bool toggle) { dataLoggingSwitch->setChecked(toggle); } void DataLoggerView::setDataLoggerPath(QString path) { @@ -184,29 +153,20 @@ void DataLoggerView::setDataLoggerPath(QString path) dataLoggingFilePath->setText(path); } -QString DataLoggerView::getDataLoggerPath() -{ - return filename; -} +QString DataLoggerView::getDataLoggerPath() { return filename; } void DataLoggerView::setOverwrite(bool en) { - if (en) { + if(en) { overwriteRadio->setChecked(true); } else { appendRadio->setChecked(true); } } -int DataLoggerView::getTimerInterval() -{ - return data_logging_timer->value(); -} +int DataLoggerView::getTimerInterval() { return data_logging_timer->value(); } -void DataLoggerView::setTimerInterval(int interval) -{ - data_logging_timer->setValue(interval); -} +void DataLoggerView::setTimerInterval(int interval) { data_logging_timer->setValue(interval); } void DataLoggerView::isDataLoggerRunning(bool en) { @@ -225,4 +185,3 @@ DataLoggerView::~DataLoggerView() delete dataLoggerFilter; delete dataLoggingBrowseBtn; } - diff --git a/plugins/datalogger/src/gui/dataloggerview.hpp b/plugins/datalogger/src/gui/dataloggerview.hpp index 89048791d2..62927ce6d7 100644 --- a/plugins/datalogger/src/gui/dataloggerview.hpp +++ b/plugins/datalogger/src/gui/dataloggerview.hpp @@ -1,15 +1,16 @@ #ifndef DATALOGGERVIEW_H #define DATALOGGERVIEW_H -#include -#include +#include +#include #include #include -#include #include -#include +#include #include -#include + +#include +#include namespace scopy { namespace datalogger { @@ -25,7 +26,7 @@ class DataLoggerView : public QWidget void init(); void chooseFile(); - QWidget* getDataLoggerViewWidget(); + QWidget *getDataLoggerViewWidget(); bool isDataLoggingOn(); bool isOverwrite(); QString getFilter(); @@ -61,10 +62,9 @@ class DataLoggerView : public QWidget void toggleDataLogger(bool toggled); void pathChanged(QString path); void timeIntervalChanged(double inetrval); - }; -} -} -} +} // namespace gui +} // namespace datalogger +} // namespace scopy #endif // DATALOGGERVIEW_H diff --git a/plugins/datalogger/test/CMakeLists.txt b/plugins/datalogger/test/CMakeLists.txt index ff0d566e02..646197d6f9 100644 --- a/plugins/datalogger/test/CMakeLists.txt +++ b/plugins/datalogger/test/CMakeLists.txt @@ -2,7 +2,4 @@ cmake_minimum_required(VERSION 3.5) include(ScopyTest) -SETUP_SCOPY_TESTS( - pluginloader -) - +setup_scopy_tests(pluginloader) diff --git a/plugins/datalogger/test/tst_pluginloader.cpp b/plugins/datalogger/test/tst_pluginloader.cpp index 9c44f98a2a..c294231d0b 100644 --- a/plugins/datalogger/test/tst_pluginloader.cpp +++ b/plugins/datalogger/test/tst_pluginloader.cpp @@ -1,6 +1,8 @@ #include "qpluginloader.h" -#include + #include +#include + #include using namespace scopy; @@ -19,71 +21,64 @@ private Q_SLOTS: void clone(); void name(); void metadata(); - }; #define PLUGIN_LOCATION "../../plugins" #define FILENAME PLUGIN_LOCATION "/libscopy-datalogger.so" - void TST_DataLoggerPlugin::fileExists() { QFile f(FILENAME); bool ret; - qDebug()<(qp.instance()); - QVERIFY(instance != nullptr ); + QPluginLoader qp(FILENAME, this); + auto instance = qobject_cast(qp.instance()); + QVERIFY(instance != nullptr); } - void TST_DataLoggerPlugin::clone() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(); QVERIFY(p1 != nullptr); p2 = original->clone(); @@ -91,28 +86,28 @@ void TST_DataLoggerPlugin::clone() QVERIFY(p1 != p2); } -void TST_DataLoggerPlugin::name() { - QPluginLoader qp(FILENAME,this); +void TST_DataLoggerPlugin::name() +{ + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(); - qDebug()<name(); + qDebug() << p1->name(); } void TST_DataLoggerPlugin::metadata() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); original->initMetadata(); p1 = original->clone(); - qDebug()<metadata(); + qDebug() << p1->metadata(); QVERIFY(!p1->metadata().isEmpty()); } - QTEST_MAIN(TST_DataLoggerPlugin) #include "tst_pluginloader.moc" diff --git a/plugins/debugger/CMakeLists.txt b/plugins/debugger/CMakeLists.txt index 213c9be59f..b0f5ff8d26 100644 --- a/plugins/debugger/CMakeLists.txt +++ b/plugins/debugger/CMakeLists.txt @@ -8,8 +8,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -26,44 +25,34 @@ set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) set(SCOPY_QT_COMPONENTS Widgets Concurrent Svg Xml) -FILE(GLOB SRC_LIST - src/*.cpp - model/* -) +file(GLOB SRC_LIST src/*.cpp model/*) -FILE(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) -FILE(GLOB UI_LIST ui/*.ui) +file(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) +file(GLOB UI_LIST ui/*.ui) if(ENABLE_TESTING) add_subdirectory(test) endif() -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} -) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS ${SCOPY_QT_COMPONENTS} REQUIRED) - if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") - set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY - "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") else() - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) endif() qt_add_resources(PROJECT_RESOURCES resources/resources.qrc ../../resources/resources.qrc) -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} - ${PROJECT_RESOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES} ${PROJECT_RESOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}) @@ -71,14 +60,16 @@ target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/i include_directories(${Qt${QT_VERSION_MAJOR}Concurrent_INCLUDE_DIRS}) foreach(comp ${SCOPY_QT_COMPONENTS}) - set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) + set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) endforeach() -target_link_libraries(${PROJECT_NAME} PUBLIC - ${SCOPY_QT_LIBRARIES} - scopy-pluginbase - scopy-iioutil - scopy-gui - scopy-core) +target_link_libraries( + ${PROJECT_NAME} + PUBLIC ${SCOPY_QT_LIBRARIES} + scopy-pluginbase + scopy-iioutil + scopy-gui + scopy-core +) set(PLUGIN_NAME ${PROJECT_NAME} PARENT_SCOPE) diff --git a/plugins/debugger/include/debuggerplugin/debuggerplugin.h b/plugins/debugger/include/debuggerplugin/debuggerplugin.h index c87997e2d1..e50446d57f 100644 --- a/plugins/debugger/include/debuggerplugin/debuggerplugin.h +++ b/plugins/debugger/include/debuggerplugin/debuggerplugin.h @@ -3,16 +3,19 @@ #define SCOPY_PLUGIN_NAME DebuggerPlugin +#include "QLabel" +#include "scopy-debuggerplugin_export.h" + #include + #include -#include "scopy-debuggerplugin_export.h" -#include "QLabel" namespace scopy::debugger { class SCOPY_DEBUGGERPLUGIN_EXPORT DebuggerPlugin : public QObject, public PluginBase { Q_OBJECT SCOPY_PLUGIN; + public: void initMetadata() override; bool compatible(QString param, QString category) override; @@ -24,6 +27,6 @@ public Q_SLOTS: bool onConnect() override; bool onDisconnect() override; }; -} +} // namespace scopy::debugger #endif // DEBUGGERPLUGIN_H diff --git a/plugins/debugger/src/bitfieldwidget.cpp b/plugins/debugger/src/bitfieldwidget.cpp index ebec7f028f..e3d16fe0bb 100644 --- a/plugins/debugger/src/bitfieldwidget.cpp +++ b/plugins/debugger/src/bitfieldwidget.cpp @@ -19,17 +19,18 @@ */ #include "bitfieldwidget.h" -#include "ui_bitfieldwidget.h" #include "math.h" +#include "ui_bitfieldwidget.h" + using namespace scopy; using namespace scopy::debugger; -BitfieldWidget::BitfieldWidget(QWidget *parent, QDomElement *bitfield) : - QWidget(parent), - ui(new Ui::BitfieldWidget()), - bitfield(bitfield) +BitfieldWidget::BitfieldWidget(QWidget *parent, QDomElement *bitfield) + : QWidget(parent) + , ui(new Ui::BitfieldWidget()) + , bitfield(bitfield) { ui->setupUi(this); @@ -46,12 +47,12 @@ BitfieldWidget::BitfieldWidget(QWidget *parent, QDomElement *bitfield) : options = bitfield->firstChildElement("Options"); - createWidget(); //build the widget + createWidget(); // build the widget } -BitfieldWidget::BitfieldWidget(QWidget *parent, int bitNumber) : - QWidget(parent), - ui(new Ui::BitfieldWidget()) +BitfieldWidget::BitfieldWidget(QWidget *parent, int bitNumber) + : QWidget(parent) + , ui(new Ui::BitfieldWidget()) { ui->setupUi(this); @@ -67,13 +68,10 @@ BitfieldWidget::BitfieldWidget(QWidget *parent, int bitNumber) : ui->valueSpinBox->setEnabled(false); ui->valueSpinBox->setMaximum(1); connect(ui->valueSpinBox, SIGNAL(valueChanged(int)), this, - SLOT(setValue(int))); //connect spinBox singnal to the value changed signal + SLOT(setValue(int))); // connect spinBox singnal to the value changed signal } -BitfieldWidget::~BitfieldWidget() -{ - delete ui; -} +BitfieldWidget::~BitfieldWidget() { delete ui; } void BitfieldWidget::createWidget() { @@ -82,43 +80,43 @@ void BitfieldWidget::createWidget() ui->descriptionLabel->setText(name); ui->bitLabel->setText(QString("Bit %1 ").arg(regOffset)); - for (int i = 1; i < width; i++) { + for(int i = 1; i < width; i++) { label = new QLabel(this); label->setText(QString("Bit %1 ").arg(regOffset + i)); - ui->bitHorizontalLayout->insertWidget(1,label); + ui->bitHorizontalLayout->insertWidget(1, label); } /*Set comboBox or spinBox*/ - if (options.isNull()) { + if(options.isNull()) { /*set spinBox*/ ui->stackedWidget->setCurrentIndex(1); int temp = (int)pow(2, width) - 1; ui->valueSpinBox->setMaximum(temp); connect(ui->valueSpinBox, SIGNAL(valueChanged(int)), this, - SLOT(setValue(int))); //connect spinBox singnal to the value changed signal + SLOT(setValue(int))); // connect spinBox singnal to the value changed signal } else { /*set comboBox*/ ui->stackedWidget->setCurrentIndex(0); QDomElement temp = options.firstChildElement("Option"); - while (options.lastChildElement() != temp) { + while(options.lastChildElement() != temp) { ui->valueComboBox->addItem(temp.firstChildElement("Description").text()); temp = temp.nextSiblingElement(); } ui->valueComboBox->addItem(temp.firstChildElement("Description").text()); - connect(ui->valueComboBox,SIGNAL(currentIndexChanged(int)), this, - SLOT(setValue(int))); //connect comboBox signal to the value changed signal + connect(ui->valueComboBox, SIGNAL(currentIndexChanged(int)), this, + SLOT(setValue(int))); // connect comboBox signal to the value changed signal } } -void BitfieldWidget::updateValue(uint32_t& value) +void BitfieldWidget::updateValue(uint32_t &value) { - int temp = value & ((uint32_t)pow(2, width) - 1); + int temp = value & ((uint32_t)pow(2, width) - 1); - if (ui->stackedWidget->currentIndex() == 1) { + if(ui->stackedWidget->currentIndex() == 1) { ui->valueSpinBox->setValue(temp); } else { ui->valueComboBox->setCurrentIndex(value & ((uint32_t)pow(2, width) - 1)); @@ -127,15 +125,9 @@ void BitfieldWidget::updateValue(uint32_t& value) value = (value >> width); } -int BitfieldWidget::getRegOffset() const -{ - return regOffset; -} +int BitfieldWidget::getRegOffset() const { return regOffset; } -int BitfieldWidget::getSliceWidth() const -{ - return sliceWidth; -} +int BitfieldWidget::getSliceWidth() const { return sliceWidth; } void BitfieldWidget::setValue(int value) { @@ -145,7 +137,4 @@ void BitfieldWidget::setValue(int value) Q_EMIT valueChanged(this->value, mask); } -uint32_t BitfieldWidget::getDefaultValue(void) const -{ - return defaultValue; -} +uint32_t BitfieldWidget::getDefaultValue(void) const { return defaultValue; } diff --git a/plugins/debugger/src/bitfieldwidget.h b/plugins/debugger/src/bitfieldwidget.h index 71b623509d..9928904759 100644 --- a/plugins/debugger/src/bitfieldwidget.h +++ b/plugins/debugger/src/bitfieldwidget.h @@ -21,8 +21,8 @@ #ifndef BITFIELDWIDGET_H #define BITFIELDWIDGET_H -#include #include +#include #include @@ -30,7 +30,6 @@ namespace Ui { class BitfieldWidget; } - namespace scopy { namespace debugger { @@ -43,7 +42,7 @@ class BitfieldWidget : public QWidget explicit BitfieldWidget(QWidget *parent, int bitNumber); ~BitfieldWidget(); - void updateValue(uint32_t& value); + void updateValue(uint32_t &value); int getRegOffset(void) const; int getSliceWidth(void) const; uint32_t getDefaultValue(void) const; @@ -73,8 +72,7 @@ private Q_SLOTS: QString notes; QString name, access; QString option; - }; -} -} +} // namespace debugger +} // namespace scopy #endif // BITFIELDWIDGET_H diff --git a/plugins/debugger/src/debuggercontroller.cpp b/plugins/debugger/src/debuggercontroller.cpp index d133fd4af6..9494adbe1e 100644 --- a/plugins/debugger/src/debuggercontroller.cpp +++ b/plugins/debugger/src/debuggercontroller.cpp @@ -25,14 +25,11 @@ static const size_t maxAttrSize = 512; using namespace scopy; using namespace scopy::debugger; -DebuggerController::DebuggerController(QObject *parent) : QObject(parent) -{ - -} +DebuggerController::DebuggerController(QObject *parent) + : QObject(parent) +{} -DebuggerController::~DebuggerController() -{ -} +DebuggerController::~DebuggerController() {} void DebuggerController::scanDevices(void) { @@ -44,13 +41,12 @@ void DebuggerController::scanDevices(void) scan_ctx = iio_create_scan_context(NULL, 0); Size = iio_scan_context_get_info_list(scan_ctx, &info); - if (Size) { + if(Size) { connected = true; /*Display context info*/ - for (size_t i = 0; i < (size_t)Size; i++) { - qDebug("\t %d: %s [%s]\n\r", (int)i, - iio_context_info_get_description(info[i]), + for(size_t i = 0; i < (size_t)Size; i++) { + qDebug("\t %d: %s [%s]\n\r", (int)i, iio_context_info_get_description(info[i]), iio_context_info_get_uri(info[i])); } @@ -59,7 +55,7 @@ void DebuggerController::scanDevices(void) Size = iio_context_get_devices_count(ctx); - for (size_t i = 0; i < (size_t)Size; i++) { + for(size_t i = 0; i < (size_t)Size; i++) { device = iio_context_get_device(ctx, i); deviceList.append(iio_device_get_name(device)); @@ -67,8 +63,6 @@ void DebuggerController::scanDevices(void) } else { connected = false; } - - } void DebuggerController::setIioContext(struct iio_context *ctx) @@ -81,56 +75,41 @@ void DebuggerController::setIioContext(struct iio_context *ctx) Size = iio_context_get_devices_count(ctx); - for (size_t i = 0; i < (size_t)Size; i++) { + for(size_t i = 0; i < (size_t)Size; i++) { device = iio_context_get_device(ctx, i); deviceList.append(iio_device_get_name(device)); } } -QStringList DebuggerController::getDeviceList() const -{ - return deviceList; -} +QStringList DebuggerController::getDeviceList() const { return deviceList; } -QStringList DebuggerController::getChannelList() const -{ - return channelList; -} +QStringList DebuggerController::getChannelList() const { return channelList; } -QStringList DebuggerController::getAttributeList() const -{ - return attributeList; -} +QStringList DebuggerController::getAttributeList() const { return attributeList; } -QStringList DebuggerController::getFileName() const -{ - return filename; -} +QStringList DebuggerController::getFileName() const { return filename; } -QVector DebuggerController::getAttributeVector() const -{ - return attributeAvailable; -} +QVector DebuggerController::getAttributeVector() const { return attributeAvailable; } -void DebuggerController::scanChannels(const QString& devName) +void DebuggerController::scanChannels(const QString &devName) { int nb_channels; struct iio_device *device; struct iio_channel *ch; QString type; - if (connected) { + if(connected) { device = iio_context_find_device(ctx, devName.toLatin1().data()); nb_channels = iio_device_get_channels_count(device); channelList.clear(); - for (int j = 0; j < nb_channels; j++) { + for(int j = 0; j < nb_channels; j++) { /*get channel*/ ch = iio_device_get_channel(device, j); - if (iio_channel_is_output(ch)) { + if(iio_channel_is_output(ch)) { type = "output "; } else { type = "input "; @@ -145,7 +124,7 @@ void DebuggerController::scanChannels(const QString& devName) } } -void DebuggerController::scanChannelAttributes(QString devName, QString& channel) +void DebuggerController::scanChannelAttributes(QString devName, QString &channel) { struct iio_device *device; struct iio_channel *ch = nullptr; @@ -153,10 +132,10 @@ void DebuggerController::scanChannelAttributes(QString devName, QString& channel unsigned int nb_attrs; bool isOutput; - if (connected) { //check if M2K is connected + if(connected) { // check if M2K is connected isOutput = channel.contains("output", Qt::CaseInsensitive); - if (isOutput) { + if(isOutput) { channel.remove("output ", Qt::CaseInsensitive); } else { channel.remove("input ", Qt::CaseInsensitive); @@ -168,30 +147,30 @@ void DebuggerController::scanChannelAttributes(QString devName, QString& channel filename.clear(); const bool isGlobal = (channel == QString("Global")); - if (isGlobal) { + if(isGlobal) { nb_attrs = iio_device_get_attrs_count(device); } else { ch = iio_device_find_channel(device, channel.toLatin1().data(), isOutput); nb_attrs = iio_channel_get_attrs_count(ch); } - for (unsigned int k = 0; k < nb_attrs; k++) { - if (isGlobal) { + for(unsigned int k = 0; k < nb_attrs; k++) { + if(isGlobal) { attr = iio_device_get_attr(device, k); } else { attr = iio_channel_get_attr(ch, k); } - if (QString(attr).contains("available", Qt::CaseInsensitive)) { + if(QString(attr).contains("available", Qt::CaseInsensitive)) { std::string tmp_attr = std::string(attr); std::string to_erase = "_available"; size_t pos = tmp_attr.find(to_erase); - if (pos != std::string::npos) { + if(pos != std::string::npos) { tmp_attr.erase(pos, to_erase.length()); } attributeAvailable.append(QString::fromStdString(tmp_attr)); } else { - if (isGlobal) { + if(isGlobal) { filename << QString(attr); } else { filename << QString(iio_channel_attr_get_filename(ch, attr)); @@ -200,11 +179,9 @@ void DebuggerController::scanChannelAttributes(QString devName, QString& channel } } } - } -QStringList DebuggerController::getAvailableValues(const QString& devName, QString& channel, - QString& attribute) const +QStringList DebuggerController::getAvailableValues(const QString &devName, QString &channel, QString &attribute) const { struct iio_device *device; struct iio_channel *ch; @@ -214,20 +191,20 @@ QStringList DebuggerController::getAvailableValues(const QString& devName, QStri attribute.append("_available"); - if (channel.contains("Global", Qt::CaseInsensitive)) { + if(channel.contains("Global", Qt::CaseInsensitive)) { channel.clear(); } - if (connected) { + if(connected) { device = iio_context_find_device(ctx, devName.toLatin1().data()); - if (channel.isNull()) { + if(channel.isNull()) { iio_device_attr_read(device, attribute.toLatin1().data(), value, maxAttrSize); } else { isOutput = channel.contains("output", Qt::CaseInsensitive); - if (isOutput) { + if(isOutput) { channel.remove("output ", Qt::CaseInsensitive); } else { channel.remove("input ", Qt::CaseInsensitive); @@ -245,74 +222,65 @@ QStringList DebuggerController::getAvailableValues(const QString& devName, QStri } } -QString DebuggerController::readAttribute(const QString& devName, QString& channel, - const QString& attribute) +QString DebuggerController::readAttribute(const QString &devName, QString &channel, const QString &attribute) { struct iio_device *device; struct iio_channel *ch; char value[maxAttrSize] = ""; bool isOutput; - if (connected) { + if(connected) { device = iio_context_find_device(ctx, devName.toLatin1().data()); - if (channel.isNull()) { + if(channel.isNull()) { iio_device_attr_read(device, attribute.toLatin1().data(), value, maxAttrSize); } else { isOutput = channel.contains("output", Qt::CaseInsensitive); - if (isOutput) { + if(isOutput) { channel.remove("output ", Qt::CaseInsensitive); } else { channel.remove("input ", Qt::CaseInsensitive); } ch = iio_device_find_channel(device, channel.toLatin1().data(), isOutput); - ssize_t ret = iio_channel_attr_read(ch, attribute.toLatin1().data(),value, maxAttrSize); + ssize_t ret = iio_channel_attr_read(ch, attribute.toLatin1().data(), value, maxAttrSize); } } return QString(value); } -QString DebuggerController::writeAttribute(const QString& devName, QString& channel, - const QString& attribute, - const QString& value) +QString DebuggerController::writeAttribute(const QString &devName, QString &channel, const QString &attribute, + const QString &value) { struct iio_device *device; struct iio_channel *ch; bool isOutput; char feedbackValue[maxAttrSize] = ""; - if (connected) { + if(connected) { device = iio_context_find_device(ctx, devName.toLatin1().data()); - if (channel.isNull()) { - iio_device_attr_write(device, attribute.toLatin1().data(), - value.toLatin1().data()); - iio_device_attr_read(device, attribute.toLatin1().data(), - feedbackValue, maxAttrSize); + if(channel.isNull()) { + iio_device_attr_write(device, attribute.toLatin1().data(), value.toLatin1().data()); + iio_device_attr_read(device, attribute.toLatin1().data(), feedbackValue, maxAttrSize); } else { isOutput = channel.contains("output", Qt::CaseInsensitive); - if (isOutput) { + if(isOutput) { channel.remove("output ", Qt::CaseInsensitive); } else { channel.remove("input ", Qt::CaseInsensitive); } ch = iio_device_find_channel(device, channel.toLatin1().data(), isOutput); - ssize_t ret = iio_channel_attr_write(ch, attribute.toLatin1().data(), - value.toLatin1().data()); - ret = iio_channel_attr_read(ch, attribute.toLatin1().data(),feedbackValue, maxAttrSize); + ssize_t ret = iio_channel_attr_write(ch, attribute.toLatin1().data(), value.toLatin1().data()); + ret = iio_channel_attr_read(ch, attribute.toLatin1().data(), feedbackValue, maxAttrSize); } } return QString(feedbackValue); } -struct iio_context *DebuggerController::getIioContext(void) -{ - return ctx; -} - +struct iio_context *DebuggerController::getIioContext(void) { return ctx; } diff --git a/plugins/debugger/src/debuggercontroller.h b/plugins/debugger/src/debuggercontroller.h index 4135297be9..bdf9a0b5e8 100644 --- a/plugins/debugger/src/debuggercontroller.h +++ b/plugins/debugger/src/debuggercontroller.h @@ -22,9 +22,10 @@ #define DEBUGGERCONTROLLER_H #include + #include -#include #include +#include namespace scopy { @@ -44,26 +45,21 @@ class DebuggerController : public QObject struct iio_context *getIioContext(void); void setIioContext(struct iio_context *ctx); - QString readAttribute(const QString& devName, QString& channel, - const QString& attribute); - QString writeAttribute(const QString& devName, QString& channel, - const QString& attribute, - const QString& value); - QStringList getAvailableValues(const QString& devName, QString& channel, - QString& attribute) const; - QString getAttributeValue(const QString& devName, const QString& channel, - const QString& attribute) const; - void setAttributeValue(const QString& devName, const QString& channel, - const QString& attribute, - const QString& value); + QString readAttribute(const QString &devName, QString &channel, const QString &attribute); + QString writeAttribute(const QString &devName, QString &channel, const QString &attribute, + const QString &value); + QStringList getAvailableValues(const QString &devName, QString &channel, QString &attribute) const; + QString getAttributeValue(const QString &devName, const QString &channel, const QString &attribute) const; + void setAttributeValue(const QString &devName, const QString &channel, const QString &attribute, + const QString &value); Q_SIGNALS: void channelsChanged(const QStringList channelList); public Q_SLOTS: void scanDevices(void); - void scanChannels(const QString& devName); - void scanChannelAttributes(QString devName, QString& channel); + void scanChannels(const QString &devName); + void scanChannelAttributes(QString devName, QString &channel); private: struct iio_context *ctx; @@ -74,7 +70,7 @@ public Q_SLOTS: bool connected = false; QVector attributeAvailable; }; -} -} +} // namespace debugger +} // namespace scopy #endif // DEBUGGERCONTROLLER_H diff --git a/plugins/debugger/src/debuggerinstrument.cpp b/plugins/debugger/src/debuggerinstrument.cpp index 1ea9adf761..35602aac9f 100644 --- a/plugins/debugger/src/debuggerinstrument.cpp +++ b/plugins/debugger/src/debuggerinstrument.cpp @@ -19,25 +19,24 @@ */ #include "debuggerinstrument.h" -#include "ui_debuggerinstrument.h" -#include -#include +#include "ui_debuggerinstrument.h" #include #include #include +#include +#include using namespace scopy; using namespace scopy::debugger; using namespace std; -DebuggerInstrument::DebuggerInstrument(struct iio_context *ctx, QJSEngine *engine, - QWidget *parent) : - QWidget(parent), - ui(new Ui::DebuggerInstrument), - eng(engine) +DebuggerInstrument::DebuggerInstrument(struct iio_context *ctx, QJSEngine *engine, QWidget *parent) + : QWidget(parent) + , ui(new Ui::DebuggerInstrument) + , eng(engine) , m_toolView(nullptr) { ui->setupUi(this); @@ -58,39 +57,27 @@ DebuggerInstrument::DebuggerInstrument(struct iio_context *ctx, QJSEngine *engin this->updateFilename(ui->AttributeComboBox->currentIndex()); on_ReadButton_clicked(); - QObject::connect(ui->DevicecomboBox, &QComboBox::currentTextChanged,this, + QObject::connect(ui->DevicecomboBox, &QComboBox::currentTextChanged, this, &DebuggerInstrument::updateChannelComboBox); QObject::connect(ui->ChannelComboBox, &QComboBox::currentTextChanged, this, &DebuggerInstrument::updateAttributeComboBox); - QObject::connect(ui->AttributeComboBox, SIGNAL(currentIndexChanged(int)), this, - SLOT(updateFilename(int))); + QObject::connect(ui->AttributeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(updateFilename(int))); QObject::connect(ui->AttributeComboBox, &QComboBox::currentTextChanged, this, &DebuggerInstrument::updateValueWidget); - QObject::connect(ui->DevicecomboBox, &QComboBox::currentTextChanged, this, - &DebuggerInstrument::updateSources); + QObject::connect(ui->DevicecomboBox, &QComboBox::currentTextChanged, this, &DebuggerInstrument::updateSources); - QObject::connect(ui->addressSpinBox, SIGNAL(valueChanged(int)), this, - SLOT(updateRegMap())); + QObject::connect(ui->addressSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateRegMap())); - QObject::connect(ui->valueRegisterSpinBox, SIGNAL(valueChanged(int)), this->reg, - SLOT(setValue(int))); - QObject::connect(this->reg, SIGNAL(valueChanged(int)), ui->valueRegisterSpinBox, - SLOT(setValue(int))); + QObject::connect(ui->valueRegisterSpinBox, SIGNAL(valueChanged(int)), this->reg, SLOT(setValue(int))); + QObject::connect(this->reg, SIGNAL(valueChanged(int)), ui->valueRegisterSpinBox, SLOT(setValue(int))); - QObject::connect(ui->DevicecomboBox, &QComboBox::currentTextChanged, this, - &DebuggerInstrument::updateRegMap); - QObject::connect(ui->sourceComboBox, &QComboBox::currentTextChanged, this, - &DebuggerInstrument::updateRegMap); + QObject::connect(ui->DevicecomboBox, &QComboBox::currentTextChanged, this, &DebuggerInstrument::updateRegMap); + QObject::connect(ui->sourceComboBox, &QComboBox::currentTextChanged, this, &DebuggerInstrument::updateRegMap); on_detailedRegMapCheckBox_stateChanged(0); - } -DebuggerInstrument::~DebuggerInstrument() -{ - - delete ui; -} +DebuggerInstrument::~DebuggerInstrument() { delete ui; } void DebuggerInstrument::updateChannelComboBox(QString devName) { @@ -106,13 +93,12 @@ void DebuggerInstrument::updateChannelComboBox(QString devName) m_debugController.scanChannels(devName); channels = m_debugController.getChannelList(); - if (channels.isEmpty()) { + if(channels.isEmpty()) { channels.append(QString("None")); } - std::sort(channels.begin(), channels.end(), [](QString a, QString b) { - return Util::compareNatural(a.toStdString(), b.toStdString()); - }); + std::sort(channels.begin(), channels.end(), + [](QString a, QString b) { return Util::compareNatural(a.toStdString(), b.toStdString()); }); ui->ChannelComboBox->addItems(channels); @@ -130,7 +116,7 @@ void DebuggerInstrument::updateAttributeComboBox(QString channel) m_debugController.scanChannelAttributes(ui->DevicecomboBox->currentText(), channel); attributes = m_debugController.getAttributeList(); - if (attributes.isEmpty()) { + if(attributes.isEmpty()) { attributes.append(QString("None")); } @@ -144,7 +130,7 @@ void DebuggerInstrument::updateFilename(int index) { QStringList filename = m_debugController.getFileName(); - if (!filename.isEmpty()) { + if(!filename.isEmpty()) { ui->filenameLineEdit->setText(filename[index]); // ui->filenameLineEdit->setFixedWidth(700); } else { @@ -161,8 +147,8 @@ void DebuggerInstrument::updateValueWidget(QString attribute) QVector availableValues = m_debugController.getAttributeVector(); ui->valueStackedWidget->setEnabled(true); - for (const QString &t : qAsConst(availableValues)) { - if (!QString::compare(t, attribute, Qt::CaseInsensitive)) { + for(const QString &t : qAsConst(availableValues)) { + if(!QString::compare(t, attribute, Qt::CaseInsensitive)) { available = true; /*read device, channel and get values to update widget*/ @@ -171,15 +157,15 @@ void DebuggerInstrument::updateValueWidget(QString attribute) valueList = m_debugController.getAvailableValues(dev, ch, attribute); /* Don't treat value range [min step max] as combobox items */ - if (valueList.at(0).startsWith("[")) { - if (valueList.size() == 3) { + if(valueList.at(0).startsWith("[")) { + if(valueList.size() == 3) { QString min = valueList.at(0); min.remove(0, 1); min.squeeze(); QString step = valueList.at(1); QString max = valueList.at(2); - if (max.endsWith("]")) { + if(max.endsWith("]")) { max.chop(1); } ui->valueSpinBox->clear(); @@ -197,11 +183,10 @@ void DebuggerInstrument::updateValueWidget(QString attribute) ui->valueStackedWidget->setCurrentWidget(ui->pageComboBox); } break; - } } - if (!available) { + if(!available) { ui->valueStackedWidget->setCurrentWidget(ui->pageLineEdit); ui->valueLineEdit->clear(); } @@ -212,14 +197,14 @@ void DebuggerInstrument::updateValueWidget(QString attribute) void DebuggerInstrument::updateReadValue(QString value) { auto currentPageWidget = ui->valueStackedWidget->currentWidget(); - if (currentPageWidget == ui->pageLineEdit) { + if(currentPageWidget == ui->pageLineEdit) { ui->valueLineEdit->setText(value); - } else if (currentPageWidget == ui->pageComboBox) { + } else if(currentPageWidget == ui->pageComboBox) { int index = ui->valueComboBox->findText(value, Qt::MatchCaseSensitive); ui->valueComboBox->setCurrentIndex(index); - } else if (currentPageWidget == ui->pageSpinBox) { + } else if(currentPageWidget == ui->pageSpinBox) { QStringList valueAndUnit = value.split(" "); - if (valueAndUnit.size() > 1) { + if(valueAndUnit.size() > 1) { ui->valueSpinBox->setSuffix(" " + valueAndUnit.at(1)); value = valueAndUnit.at(0); } else { @@ -241,15 +226,12 @@ void DebuggerInstrument::on_ReadButton_clicked() channel = ui->ChannelComboBox->currentText(); attribute = ui->AttributeComboBox->currentText(); - - - if (channel.contains("Global", Qt::CaseInsensitive)) { + if(channel.contains("Global", Qt::CaseInsensitive)) { channel.clear(); } - - if (!attribute.contains("None", Qt::CaseInsensitive)) { - if (!attribute.isNull()) { + if(!attribute.contains("None", Qt::CaseInsensitive)) { + if(!attribute.isNull()) { value = m_debugController.readAttribute(dev, channel, attribute); updateReadValue(value); } else { @@ -270,25 +252,25 @@ void DebuggerInstrument::on_WriteButton_clicked() channel = ui->ChannelComboBox->currentText(); attribute = ui->AttributeComboBox->currentText(); - if (channel.contains("Global", Qt::CaseInsensitive)) { + if(channel.contains("Global", Qt::CaseInsensitive)) { channel.clear(); } auto currentPageWidget = ui->valueStackedWidget->currentWidget(); - if (currentPageWidget == ui->pageLineEdit) { + if(currentPageWidget == ui->pageLineEdit) { value = ui->valueLineEdit->text(); - } else if (currentPageWidget == ui->pageComboBox) { + } else if(currentPageWidget == ui->pageComboBox) { value = ui->valueComboBox->currentText(); - } else if (currentPageWidget == ui->pageSpinBox) { + } else if(currentPageWidget == ui->pageSpinBox) { value = ui->valueSpinBox->text(); QStringList valueAndUnit = value.split(' '); - if (valueAndUnit.size() > 1) { + if(valueAndUnit.size() > 1) { value = valueAndUnit.at(1); } ui->valueSpinBox->setValue(value.toDouble()); } - if (!attribute.isNull()) { + if(!attribute.isNull()) { feedbackValue = m_debugController.writeAttribute(dev, channel, attribute, value); updateReadValue(feedbackValue); } @@ -304,8 +286,7 @@ void DebuggerInstrument::updateSources() ui->sourceComboBox->addItems(list); ui->sourceComboBox->blockSignals(false); - Q_EMIT ui->sourceComboBox->currentTextChanged( - ui->sourceComboBox->currentText()); + Q_EMIT ui->sourceComboBox->currentTextChanged(ui->sourceComboBox->currentText()); } void DebuggerInstrument::updateRegMap() @@ -314,24 +295,23 @@ void DebuggerInstrument::updateRegMap() QString source = ui->sourceComboBox->currentText(); int address = ui->addressSpinBox->value(); - ui->addressSpinBox->blockSignals(true); //block signals from Address spinbox + ui->addressSpinBox->blockSignals(true); // block signals from Address spinbox reg->createRegMap(&device, &address, &source); ui->addressSpinBox->setValue(address); - if (!ui->sourceComboBox->currentText().isEmpty()) { + if(!ui->sourceComboBox->currentText().isEmpty()) { ui->addressSpinBox->setMaximum(reg->getLastAddress()); } - if (ui->enableAutoReadCheckBox->isChecked()) { + if(ui->enableAutoReadCheckBox->isChecked()) { on_readRegPushButton_clicked(); } ui->descriptionLineEdit->setText(reg->getDescription()); - ui->defaultValueLabel->setText(QString("0x%1").arg(reg->getDefaultValue(), 0, - 16)); + ui->defaultValueLabel->setText(QString("0x%1").arg(reg->getDefaultValue(), 0, 16)); - ui->addressSpinBox->blockSignals(false); //activate signals from Address spinbox + ui->addressSpinBox->blockSignals(false); // activate signals from Address spinbox } void DebuggerInstrument::on_readRegPushButton_clicked() @@ -340,7 +320,7 @@ void DebuggerInstrument::on_readRegPushButton_clicked() uint32_t value = 0; /*Read register*/ - ui->addressSpinBox->blockSignals(true); //block signals from Address spinbox + ui->addressSpinBox->blockSignals(true); // block signals from Address spinbox value = reg->readRegister(&device, ui->addressSpinBox->value()); ui->valueRegisterSpinBox->blockSignals(true); @@ -348,7 +328,7 @@ void DebuggerInstrument::on_readRegPushButton_clicked() ui->valueRegisterSpinBox->blockSignals(false); ui->valueHexLabel->setText(QString("0x%1").arg(value, 0, 16)); - ui->addressSpinBox->blockSignals(false); //activate signals from Address spinbox + ui->addressSpinBox->blockSignals(false); // activate signals from Address spinbox } void DebuggerInstrument::on_writeRegPushButton_clicked() @@ -357,12 +337,11 @@ void DebuggerInstrument::on_writeRegPushButton_clicked() uint32_t address = ui->addressSpinBox->value(); reg->writeRegister(&device, address, ui->valueRegisterSpinBox->value()); - } void DebuggerInstrument::on_detailedRegMapCheckBox_stateChanged(int arg1) { - if (!arg1) { + if(!arg1) { ui->widget->hide(); } else { ui->widget->show(); diff --git a/plugins/debugger/src/debuggerinstrument.h b/plugins/debugger/src/debuggerinstrument.h index d463967415..37b1836e82 100644 --- a/plugins/debugger/src/debuggerinstrument.h +++ b/plugins/debugger/src/debuggerinstrument.h @@ -22,16 +22,17 @@ #define DEBUGGERINSTRUMENT_H #include + #include /* Qt includes */ +#include #include #include -#include /* Local includes */ -#include "debuggercontroller.h" #include "bitfieldwidget.h" +#include "debuggercontroller.h" #include "registerwidget.h" class QJSEngine; @@ -47,8 +48,7 @@ class DebuggerInstrument : public QWidget Q_OBJECT public: - explicit DebuggerInstrument(struct iio_context *ctx, QJSEngine *engine, - QWidget *parent = 0); + explicit DebuggerInstrument(struct iio_context *ctx, QJSEngine *engine, QWidget *parent = 0); ~DebuggerInstrument(); void updateReadValue(QString value); @@ -69,7 +69,6 @@ public Q_SLOTS: void on_readRegPushButton_clicked(); void on_writeRegPushButton_clicked(); - private Q_SLOTS: void on_detailedRegMapCheckBox_stateChanged(int arg1); @@ -87,7 +86,7 @@ private Q_SLOTS: RegisterWidget *reg; QVector bitfieldsVector; }; -} -} +} // namespace debugger +} // namespace scopy #endif // DEBUGGERINSTRUMENT_H diff --git a/plugins/debugger/src/debuggerplugin.cpp b/plugins/debugger/src/debuggerplugin.cpp index 8590010432..9da17d1459 100644 --- a/plugins/debugger/src/debuggerplugin.cpp +++ b/plugins/debugger/src/debuggerplugin.cpp @@ -1,17 +1,18 @@ #include "debuggerplugin.h" + #include "debuggerinstrument.h" + #include -#include -#include + #include +#include +#include #include +#include -#include #include #include -#include - - +#include using namespace scopy; using namespace scopy::debugger; @@ -35,29 +36,26 @@ bool DebuggerPlugin::compatible(QString m_param, QString category) void DebuggerPlugin::loadToolList() { - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("debugger","Debugger",":/gui/icons/scopy-default/icons/tool_debugger.svg")); + m_toolList.append( + SCOPY_NEW_TOOLMENUENTRY("debugger", "Debugger", ":/gui/icons/scopy-default/icons/tool_debugger.svg")); ToolMenuEntry::findToolMenuEntryById(m_toolList, "debugger")->setVisible(true); } -QString DebuggerPlugin::description() -{ - return "IIO context explorer tool"; -} +QString DebuggerPlugin::description() { return "IIO context explorer tool"; } bool DebuggerPlugin::onConnect() { ContextProvider *c = ContextProvider::GetInstance(); iio_context *ctx = c->open(m_param); - if (!ctx) { + if(!ctx) { return false; } - auto dbgTme = ToolMenuEntry::findToolMenuEntryById(m_toolList,"debugger"); + auto dbgTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, "debugger"); dbgTme->setTool(new DebuggerInstrument(ctx, nullptr, nullptr)); dbgTme->setEnabled(true); dbgTme->setRunBtnVisible(true); return true; - } bool DebuggerPlugin::onDisconnect() @@ -86,7 +84,7 @@ bool DebuggerPlugin::loadPage() void DebuggerPlugin::initMetadata() { loadMetadata( -R"plugin( + R"plugin( { "priority":3, "category":[ diff --git a/plugins/debugger/src/registerwidget.cpp b/plugins/debugger/src/registerwidget.cpp index 0336a4ad64..9be839b4d6 100644 --- a/plugins/debugger/src/registerwidget.cpp +++ b/plugins/debugger/src/registerwidget.cpp @@ -19,49 +19,40 @@ */ #include "registerwidget.h" + #include "ui_registerwidget.h" using namespace scopy; using namespace scopy::debugger; -RegisterWidget::RegisterWidget(QWidget *parent, DebuggerController *debug) : - QWidget(parent), - ui(new Ui::RegisterWidget), - address(0), - value(0) +RegisterWidget::RegisterWidget(QWidget *parent, DebuggerController *debug) + : QWidget(parent) + , ui(new Ui::RegisterWidget) + , address(0) + , value(0) { ui->setupUi(this); regMap.setIioContext(debug->getIioContext()); - - QObject::connect(this, &RegisterWidget::valueChanged, this, - &RegisterWidget::updateBitfields); + QObject::connect(this, &RegisterWidget::valueChanged, this, &RegisterWidget::updateBitfields); } -RegisterWidget::~RegisterWidget() -{ - delete ui; -} +RegisterWidget::~RegisterWidget() { delete ui; } -uint32_t RegisterWidget::getLastAddress(void) const -{ - return regMap.getLastAddress(); -} +uint32_t RegisterWidget::getLastAddress(void) const { return regMap.getLastAddress(); } -void RegisterWidget::createRegMap(const QString *device, int *address, - const QString *source) +void RegisterWidget::createRegMap(const QString *device, int *address, const QString *source) { QString filename; QString addr; bool goHigh = false; - if (*address >= this->address) { + if(*address >= this->address) { goHigh = true; } - for (auto iterator = bitfieldsVector.rbegin(); - iterator != bitfieldsVector.rend(); ++iterator) { + for(auto iterator = bitfieldsVector.rbegin(); iterator != bitfieldsVector.rend(); ++iterator) { ui->horizontalLayout->removeWidget(*iterator); delete(*iterator); } @@ -73,17 +64,17 @@ void RegisterWidget::createRegMap(const QString *device, int *address, regMap.deviceXmlFileSelection(device, &filename, *source); regMap.deviceXmlFileLoad(&filename); - if (!filename.isEmpty()) { - if (regNode != 0) { + if(!filename.isEmpty()) { + if(regNode != 0) { regNode = nullptr; } - while (regNode == 0) { + while(regNode == 0) { addr = QString("0x%1").arg(*address, 0, 16); regNode = regMap.getRegisterNode(addr); - if (regNode == 0) { - if (goHigh) { + if(regNode == 0) { + if(goHigh) { (*address)++; } else { (*address)--; @@ -94,8 +85,7 @@ void RegisterWidget::createRegMap(const QString *device, int *address, } bool status; - this->address = - regNode->firstChildElement("Address").text().split("0x")[1].toUInt(&status, 16); + this->address = regNode->firstChildElement("Address").text().split("0x")[1].toUInt(&status, 16); /*get register information from the node*/ name = regNode->firstChildElement("Name").text(); @@ -106,12 +96,12 @@ void RegisterWidget::createRegMap(const QString *device, int *address, QDomElement bitfieldList = regNode->firstChildElement("BitFields"); QDomElement bitfieldElement = bitfieldList.firstChildElement("BitField"); - while (bitfieldList.lastChildElement() != bitfieldElement) { + while(bitfieldList.lastChildElement() != bitfieldElement) { bitfieldsVector.append(new BitfieldWidget(this, &bitfieldElement)); bitfieldElement = bitfieldElement.nextSiblingElement(); } - if (!bitfieldElement.isNull()) { + if(!bitfieldElement.isNull()) { bitfieldsVector.append(new BitfieldWidget(this, &bitfieldElement)); } @@ -119,12 +109,11 @@ void RegisterWidget::createRegMap(const QString *device, int *address, defaultValue = 0; - for (auto iterator = bitfieldsVector.rbegin(); - iterator != bitfieldsVector.rend(); ++iterator) { + for(auto iterator = bitfieldsVector.rbegin(); iterator != bitfieldsVector.rend(); ++iterator) { defaultValue += (*iterator)->getDefaultValue() << (*iterator)->getRegOffset(); connect(*iterator, SIGNAL(valueChanged(uint32_t, uint32_t)), this, - SLOT(setValue(uint32_t,uint32_t))); + SLOT(setValue(uint32_t, uint32_t))); ui->horizontalLayout->addWidget(*iterator); } } @@ -132,7 +121,7 @@ void RegisterWidget::createRegMap(const QString *device, int *address, bool lessThan(const BitfieldWidget *b1, const BitfieldWidget *b2) { - if (b1->getRegOffset() <= b2->getRegOffset()) { + if(b1->getRegOffset() <= b2->getRegOffset()) { return true; } else { return false; @@ -152,8 +141,7 @@ void RegisterWidget::checkRegisterMap() /*sort vector using bit number*/ std::sort(bitfieldsVector.begin(), bitfieldsVector.end(), lessThan); - for (auto iterator = bitfieldsVector.begin(); iterator != bitfieldsVector.end(); - ++iterator) { + for(auto iterator = bitfieldsVector.begin(); iterator != bitfieldsVector.end(); ++iterator) { size += (*iterator)->getSliceWidth(); slice[count] = (*iterator)->getSliceWidth(); regOffsets[count] = (*iterator)->getRegOffset(); @@ -165,8 +153,8 @@ void RegisterWidget::checkRegisterMap() /*If bits are missing at the start of register*/ before = regOffsets[0]; - if (before != 0) { - for (int i = 0; i < before; i++) { + if(before != 0) { + for(int i = 0; i < before; i++) { bitfieldsVector.insert(i, new BitfieldWidget(this, i)); size++; } @@ -174,8 +162,7 @@ void RegisterWidget::checkRegisterMap() size = 0; count = 0; - for (auto iterator = bitfieldsVector.begin(); iterator != bitfieldsVector.end(); - ++iterator) { + for(auto iterator = bitfieldsVector.begin(); iterator != bitfieldsVector.end(); ++iterator) { size += (*iterator)->getSliceWidth(); slice[count] = (*iterator)->getSliceWidth(); regOffsets[count] = (*iterator)->getRegOffset(); @@ -185,16 +172,15 @@ void RegisterWidget::checkRegisterMap() bit = size; } - if (size < width) { + if(size < width) { /*if bits are missing inside the register*/ before = regOffsets[0]; - for (int i = 1; i < (count); ++i) { + for(int i = 1; i < (count); ++i) { gap = (regOffsets[i] - before) - slice[i - 1]; - for (int j = 0; j < gap; j++) { - bitfieldsVector.insert(i + j , new BitfieldWidget(this, - i + j + slice[i - 1] - 1)); + for(int j = 0; j < gap; j++) { + bitfieldsVector.insert(i + j, new BitfieldWidget(this, i + j + slice[i - 1] - 1)); size++; } @@ -205,8 +191,7 @@ void RegisterWidget::checkRegisterMap() size = 0; count = 0; - for (auto iterator = bitfieldsVector.begin(); iterator != bitfieldsVector.end(); - ++iterator) { + for(auto iterator = bitfieldsVector.begin(); iterator != bitfieldsVector.end(); ++iterator) { size += (*iterator)->getSliceWidth(); slice[count] = (*iterator)->getSliceWidth(); regOffsets[count] = (*iterator)->getRegOffset(); @@ -215,7 +200,7 @@ void RegisterWidget::checkRegisterMap() bit = size; - while (size < width) { + while(size < width) { bitfieldsVector.insert(count, new BitfieldWidget(this, bit++)); count++; size++; @@ -227,30 +212,24 @@ void RegisterWidget::verifyAvailableSources(const QString device) { QString filename; - fileSources.clear(); //clear the fileSource list + fileSources.clear(); // clear the fileSource list regMap.deviceXmlFileSelection(&device, &filename, QString("SPI")); - if (!filename.isNull()) { + if(!filename.isNull()) { fileSources.append(QString("SPI")); } regMap.deviceXmlFileSelection(&device, &filename, QString("AXI CORE")); - if (!filename.isNull()) { + if(!filename.isNull()) { fileSources.append(QString("AXI CORE")); } } -QStringList RegisterWidget::getSources() const -{ - return fileSources; -} +QStringList RegisterWidget::getSources() const { return fileSources; } -uint32_t RegisterWidget::getValue() const -{ - return value; -} +uint32_t RegisterWidget::getValue() const { return value; } void RegisterWidget::setValue(int var) { @@ -263,13 +242,12 @@ void RegisterWidget::setValue(int var) void RegisterWidget::setValue(uint32_t var, uint32_t mask) { value &= ~mask; - value |=var; + value |= var; Q_EMIT valueChanged((int)value); } -uint32_t RegisterWidget::readRegister(const QString *device, - const uint32_t address) +uint32_t RegisterWidget::readRegister(const QString *device, const uint32_t address) { /*Read register*/ value = regMap.readRegister(device, address); @@ -279,8 +257,7 @@ uint32_t RegisterWidget::readRegister(const QString *device, return value; } -void RegisterWidget::writeRegister(const QString *device, - const uint32_t address, uint32_t regVal) +void RegisterWidget::writeRegister(const QString *device, const uint32_t address, uint32_t regVal) { regMap.writeRegister(device, address, regVal); value = regVal; @@ -291,19 +268,11 @@ void RegisterWidget::updateBitfields() uint32_t temp = value; /*Update bitfield widgets*/ - for (auto iterator = bitfieldsVector.begin(); iterator != bitfieldsVector.end(); - ++iterator) { + for(auto iterator = bitfieldsVector.begin(); iterator != bitfieldsVector.end(); ++iterator) { (*iterator)->updateValue(temp); } } -QString RegisterWidget::getDescription() const -{ - return description; -} - +QString RegisterWidget::getDescription() const { return description; } -uint32_t RegisterWidget::getDefaultValue() const -{ - return defaultValue; -} +uint32_t RegisterWidget::getDefaultValue() const { return defaultValue; } diff --git a/plugins/debugger/src/registerwidget.h b/plugins/debugger/src/registerwidget.h index 8acb44777a..98d7da4c58 100644 --- a/plugins/debugger/src/registerwidget.h +++ b/plugins/debugger/src/registerwidget.h @@ -21,12 +21,12 @@ #ifndef REGISTERWIDGET_H #define REGISTERWIDGET_H -#include -#include - -#include "regmapparser.h" #include "bitfieldwidget.h" #include "debuggercontroller.h" +#include "regmapparser.h" + +#include +#include namespace Ui { class RegisterWidget; @@ -45,8 +45,7 @@ class RegisterWidget : public QWidget uint32_t getValue(void) const; QStringList getSources(void) const; uint32_t readRegister(const QString *device, const uint32_t address); - void writeRegister(const QString *device, const uint32_t address, - uint32_t regVal); + void writeRegister(const QString *device, const uint32_t address, uint32_t regVal); void verifyAvailableSources(const QString device); QString getDescription() const; uint32_t getDefaultValue(void) const; @@ -56,7 +55,7 @@ class RegisterWidget : public QWidget void valueChanged(int); public Q_SLOTS: - void createRegMap(const QString *device, int *address,const QString *source); + void createRegMap(const QString *device, int *address, const QString *source); void setValue(int var); void setValue(uint32_t var, uint32_t mask); void updateBitfields(); @@ -83,9 +82,7 @@ public Q_SLOTS: QString notes; QStringList fileSources; - - }; -} -} +} // namespace debugger +} // namespace scopy #endif // REGISTERWIDGET_H diff --git a/plugins/debugger/src/regmapparser.cpp b/plugins/debugger/src/regmapparser.cpp index 37eecb4d2c..63156099ba 100644 --- a/plugins/debugger/src/regmapparser.cpp +++ b/plugins/debugger/src/regmapparser.cpp @@ -19,39 +19,33 @@ */ #include "regmapparser.h" + #include using namespace scopy; using namespace scopy::debugger; -RegmapParser::RegmapParser(QObject *parent, - struct iio_context *context) : QObject(parent), - ctx(context) -{ +RegmapParser::RegmapParser(QObject *parent, struct iio_context *context) + : QObject(parent) + , ctx(context) +{} -} - -void RegmapParser::setIioContext(struct iio_context *ctx) -{ - this->ctx = ctx; -} +void RegmapParser::setIioContext(struct iio_context *ctx) { this->ctx = ctx; } -void RegmapParser::deviceXmlFileSelection(const QString *device, - QString *filename, const QString source) +void RegmapParser::deviceXmlFileSelection(const QString *device, QString *filename, const QString source) { - struct iio_device *dev = iio_context_find_device(ctx, - device->toLatin1().data()); + struct iio_device *dev = iio_context_find_device(ctx, device->toLatin1().data()); filename->clear(); - if (source.contains("SPI")) { + if(source.contains("SPI")) { findDeviceXmlFile(&xmlsFolderPath, device, filename); } else { - if (source.contains("AXI CORE")) { + if(source.contains("AXI CORE")) { QString adcRegmapName, dacRegmapName; int pcoreMajor; - if (pcoreGetVersion(device, &pcoreMajor) && pcoreMajor > 8) { + if(pcoreGetVersion(device, &pcoreMajor) && pcoreMajor > 8) { adcRegmapName.append(QString("adi_regmap_adc_v%1.xml").arg(pcoreMajor)); dacRegmapName.append(QString("adi_regmap_dac_v%1.xml").arg(pcoreMajor)); } else { @@ -60,10 +54,9 @@ void RegmapParser::deviceXmlFileSelection(const QString *device, } /* Attempt to associate AXI Core ADC xml or AXI Core DAC xml to the device */ - if (isInputDevice(dev) && xmlFileExists(adcRegmapName.toLatin1().data())) { + if(isInputDevice(dev) && xmlFileExists(adcRegmapName.toLatin1().data())) { filename->append(adcRegmapName); - } else if (isOutputDevice(dev) - && xmlFileExists(dacRegmapName.toLatin1().data())) { + } else if(isOutputDevice(dev) && xmlFileExists(dacRegmapName.toLatin1().data())) { filename->append(dacRegmapName); } } else { @@ -72,8 +65,7 @@ void RegmapParser::deviceXmlFileSelection(const QString *device, } } -void RegmapParser::findDeviceXmlFile(const QString *xmlsFolderPath, - const QString *device, QString *filename) +void RegmapParser::findDeviceXmlFile(const QString *xmlsFolderPath, const QString *device, QString *filename) { filename->append(xmlsFolderPath->toLatin1().data()); filename->append(device->toLatin1().data()); @@ -81,7 +73,7 @@ void RegmapParser::findDeviceXmlFile(const QString *xmlsFolderPath, QFile file(filename->toLatin1().data()); - if (!file.exists()) { + if(!file.exists()) { filename->clear(); } } @@ -113,17 +105,17 @@ bool RegmapParser::xmlFileExists(char *filename) } int RegmapParser::deviceXmlFileLoad(QString *filename) { - if (!file.isOpen()) { + if(!file.isOpen()) { file.setFileName(*filename); - if (!file.exists()) { + if(!file.exists()) { qDebug() << "No file available"; } /*Xml content loaded inside doc*/ doc.clear(); - if (!file.open(QIODevice::ReadOnly) || !doc.setContent(&file)) { + if(!file.open(QIODevice::ReadOnly) || !doc.setContent(&file)) { return 0; } } @@ -134,29 +126,32 @@ int RegmapParser::deviceXmlFileLoad(QString *filename) QDomNode *RegmapParser::getRegisterNode(const QString address) { - int i ; + int i; bool status; QDomNodeList registers = doc.elementsByTagName("Register"); - uint32_t lastAddress = registers.item(registers.size() - - 1).firstChildElement("Address").text().split("0x")[1].toUInt(&status,16); + uint32_t lastAddress = registers.item(registers.size() - 1) + .firstChildElement("Address") + .text() + .split("0x")[1] + .toUInt(&status, 16); lastNode = registers.item(registers.size() - 1); - for (i = 0; i < registers.size(); i++) { + for(i = 0; i < registers.size(); i++) { node = registers.item(i); QDomElement addr = node.firstChildElement("Address"); uint hexNode = addr.text().split("0x")[1].toUInt(&status, 16); uint hexAddress = address.split("0x")[1].toUInt(&status, 16); - if (hexAddress > lastAddress) { + if(hexAddress > lastAddress) { return &lastNode; } - if (addr.isNull()) { + if(addr.isNull()) { continue; } - if (hexNode == hexAddress) { + if(hexNode == hexAddress) { return &node; } } @@ -173,37 +168,30 @@ uint32_t RegmapParser::getLastAddress(void) const QDomElement addr = n.firstChildElement("Address"); QStringList temp = addr.text().split("0x"); - uint32_t lastAddress = addr.text().split("0x")[1].toUInt(&status,16); + uint32_t lastAddress = addr.text().split("0x")[1].toUInt(&status, 16); return lastAddress; } -bool RegmapParser::isInputDevice(const struct iio_device *dev) -{ - return deviceTypeGet(dev, 1); -} +bool RegmapParser::isInputDevice(const struct iio_device *dev) { return deviceTypeGet(dev, 1); } -bool RegmapParser::isOutputDevice(const iio_device *dev) -{ - return deviceTypeGet(dev, 0); -} +bool RegmapParser::isOutputDevice(const iio_device *dev) { return deviceTypeGet(dev, 0); } bool RegmapParser::deviceTypeGet(const iio_device *dev, int type) { struct iio_channel *ch; int nbChannels, i; - if (!dev) { + if(!dev) { return false; } nbChannels = iio_device_get_channels_count(dev); - for (i = 0; i < nbChannels; i++) { + for(i = 0; i < nbChannels; i++) { ch = iio_device_get_channel(dev, i); - if (iio_channel_is_scan_element(ch) && - (type ? !iio_channel_is_output(ch) : iio_channel_is_output(ch))) { + if(iio_channel_is_scan_element(ch) && (type ? !iio_channel_is_output(ch) : iio_channel_is_output(ch))) { return true; } } @@ -211,17 +199,15 @@ bool RegmapParser::deviceTypeGet(const iio_device *dev, int type) return false; } -uint32_t RegmapParser::readRegister(const QString *device, - const uint32_t u32Address) +uint32_t RegmapParser::readRegister(const QString *device, const uint32_t u32Address) { - struct iio_device *dev = iio_context_find_device(ctx, - device->toLatin1().data()); + struct iio_device *dev = iio_context_find_device(ctx, device->toLatin1().data()); int ret; uint32_t i; ret = iio_device_reg_read(dev, u32Address, &i); - if (ret == 0) { + if(ret == 0) { return i; } @@ -230,11 +216,9 @@ uint32_t RegmapParser::readRegister(const QString *device, } } -void RegmapParser::writeRegister(const QString *device, - const uint32_t u32Address, const uint32_t value) +void RegmapParser::writeRegister(const QString *device, const uint32_t u32Address, const uint32_t value) { - struct iio_device *dev = iio_context_find_device(ctx, - device->toLatin1().data()); + struct iio_device *dev = iio_context_find_device(ctx, device->toLatin1().data()); iio_device_reg_write(dev, u32Address, value); } diff --git a/plugins/debugger/src/regmapparser.h b/plugins/debugger/src/regmapparser.h index 32ffaa57cd..3722a09561 100644 --- a/plugins/debugger/src/regmapparser.h +++ b/plugins/debugger/src/regmapparser.h @@ -21,11 +21,12 @@ #ifndef REGMAPPARSER_H #define REGMAPPARSER_H -#include #include -#include + #include #include +#include +#include #define PCORE_VERSION_MAJOR(version) (version >> 16) @@ -37,22 +38,18 @@ class RegmapParser : public QObject Q_OBJECT public: - explicit RegmapParser(QObject *parent = nullptr, - struct iio_context *context = nullptr); - void deviceXmlFileSelection(const QString *device, QString *filename, - const QString source); + explicit RegmapParser(QObject *parent = nullptr, struct iio_context *context = nullptr); + void deviceXmlFileSelection(const QString *device, QString *filename, const QString source); int deviceXmlFileLoad(QString *filename); void regMapChooserInit(QString *device); QDomNode *getRegisterNode(const QString address); void setIioContext(struct iio_context *ctx); uint32_t readRegister(const QString *device, const uint32_t u8Address); - void writeRegister(const QString *device, const uint32_t u8Address, - const uint32_t value); + void writeRegister(const QString *device, const uint32_t u8Address, const uint32_t value); uint32_t getLastAddress(void) const; private: - void findDeviceXmlFile(const QString *xmlsFolderPath, const QString *device, - QString *filename); + void findDeviceXmlFile(const QString *xmlsFolderPath, const QString *device, QString *filename); int pcoreGetVersion(const QString *device, int *pcoreMajor); bool xmlFileExists(char *filename); bool isInputDevice(const struct iio_device *dev); @@ -67,7 +64,7 @@ class RegmapParser : public QObject QDomNode node; QDomNode lastNode; }; -} -} +} // namespace debugger +} // namespace scopy #endif // REGMAPPARSER_H diff --git a/plugins/debugger/test/CMakeLists.txt b/plugins/debugger/test/CMakeLists.txt index 26b7903d9a..646197d6f9 100644 --- a/plugins/debugger/test/CMakeLists.txt +++ b/plugins/debugger/test/CMakeLists.txt @@ -2,6 +2,4 @@ cmake_minimum_required(VERSION 3.5) include(ScopyTest) -SETUP_SCOPY_TESTS( - pluginloader -) +setup_scopy_tests(pluginloader) diff --git a/plugins/debugger/test/tst_pluginloader.cpp b/plugins/debugger/test/tst_pluginloader.cpp index f29f678d6c..6aba877999 100644 --- a/plugins/debugger/test/tst_pluginloader.cpp +++ b/plugins/debugger/test/tst_pluginloader.cpp @@ -1,6 +1,8 @@ #include "qpluginloader.h" -#include + #include +#include + #include using namespace scopy; @@ -20,72 +22,65 @@ private Q_SLOTS: void name(); void metadata(); void unload(); - }; #define PLUGIN_LOCATION "../../plugins" #define FILENAME PLUGIN_LOCATION "/libscopy-debuggerplugin.so" - void TST_Debugger::fileExists() { QFile f(FILENAME); bool ret; - qDebug()<(qp.instance()); - QVERIFY(instance != nullptr ); + QPluginLoader qp(FILENAME, this); + auto instance = qobject_cast(qp.instance()); + QVERIFY(instance != nullptr); } - void TST_Debugger::clone() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(this); QVERIFY(p1 != nullptr); p2 = original->clone(this); @@ -93,38 +88,37 @@ void TST_Debugger::clone() QVERIFY(p1 != p2); } -void TST_Debugger::name() { - QPluginLoader qp(FILENAME,this); +void TST_Debugger::name() +{ + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(this); - qDebug()<name(); + qDebug() << p1->name(); } void TST_Debugger::metadata() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); original->initMetadata(); p1 = original->clone(this); - qDebug()<metadata(); + qDebug() << p1->metadata(); QVERIFY(!p1->metadata().isEmpty()); } void TST_Debugger::unload() { - QPluginLoader qp(FILENAME,this); - auto original = qobject_cast(qp.instance()); + QPluginLoader qp(FILENAME, this); + auto original = qobject_cast(qp.instance()); -// qp.unload(); + // qp.unload(); QVERIFY(!qp.isLoaded() == false); - } - QTEST_MAIN(TST_Debugger) #include "tst_pluginloader.moc" diff --git a/plugins/guitestplugin/CMakeLists.txt b/plugins/guitestplugin/CMakeLists.txt index 78238f543c..b9f4dd4e50 100644 --- a/plugins/guitestplugin/CMakeLists.txt +++ b/plugins/guitestplugin/CMakeLists.txt @@ -8,8 +8,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -26,52 +25,42 @@ set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) set(SCOPY_QT_COMPONENTS Widgets Core) -FILE(GLOB SRC_LIST src/*.cpp src/*.cc) -FILE(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) -FILE(GLOB UI_LIST ui/*.ui) +file(GLOB SRC_LIST src/*.cpp src/*.cc) +file(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) +file(GLOB UI_LIST ui/*.ui) set(ENABLE_TESTING ON) if(ENABLE_TESTING) - add_subdirectory(test) + add_subdirectory(test) endif() -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} -) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS ${SCOPY_QT_COMPONENTS} REQUIRED) if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") - set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY - "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") else() - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) endif() qt_add_resources(PROJECT_RESOURCES res/resources.qrc) -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} - ${PROJECT_RESOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES} ${PROJECT_RESOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}) -target_include_directories(${PROJECT_NAME} PUBLIC scopy-gui scopy-pluginbase) +target_include_directories(${PROJECT_NAME} PUBLIC scopy-gui scopy-pluginbase) foreach(comp ${SCOPY_QT_COMPONENTS}) - set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) + set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) endforeach() -target_link_libraries(${PROJECT_NAME} PUBLIC - ${SCOPY_QT_LIBRARIES} - scopy-gui - scopy-pluginbase) - +target_link_libraries(${PROJECT_NAME} PUBLIC ${SCOPY_QT_LIBRARIES} scopy-gui scopy-pluginbase) -set(PLUGIN_NAME ${PROJECT_NAME} PARENT_SCOPE) \ No newline at end of file +set(PLUGIN_NAME ${PROJECT_NAME} PARENT_SCOPE) diff --git a/plugins/guitestplugin/include/guitestplugin/guitestplugin.h b/plugins/guitestplugin/include/guitestplugin/guitestplugin.h index 30d9cc5b12..da27019128 100644 --- a/plugins/guitestplugin/include/guitestplugin/guitestplugin.h +++ b/plugins/guitestplugin/include/guitestplugin/guitestplugin.h @@ -3,11 +3,13 @@ #define SCOPY_PLUGIN_NAME TestPlugin +#include "scopy-guitestplugin_export.h" + +#include #include + #include #include -#include "scopy-guitestplugin_export.h" -#include namespace scopy { @@ -33,9 +35,6 @@ class SCOPY_GUITESTPLUGIN_EXPORT TestPlugin : public QObject, public PluginBase QLineEdit *edit; }; - - -} - +} // namespace scopy #endif // TESTPLUGIN_H diff --git a/plugins/guitestplugin/src/guitestplugin.cpp b/plugins/guitestplugin/src/guitestplugin.cpp index e1d038bae3..eb77b27317 100644 --- a/plugins/guitestplugin/src/guitestplugin.cpp +++ b/plugins/guitestplugin/src/guitestplugin.cpp @@ -1,15 +1,14 @@ #include "guitestplugin.h" + #include +#include #include #include -#include -Q_LOGGING_CATEGORY(CAT_GUITESTPLUGIN,"GUITestPlugin"); +Q_LOGGING_CATEGORY(CAT_GUITESTPLUGIN, "GUITestPlugin"); using namespace scopy; -bool TestPlugin::compatible(QString m_param, QString category) { - return (m_param=="gui"); -} +bool TestPlugin::compatible(QString m_param, QString category) { return (m_param == "gui"); } bool TestPlugin::loadIcon() { @@ -21,12 +20,12 @@ bool TestPlugin::loadPage() { m_page = new QWidget(); return true; - } void TestPlugin::loadToolList() { - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("Buttons","Buttons",":/gui/icons/scopy-default/icons/tool_home.svg")); + m_toolList.append( + SCOPY_NEW_TOOLMENUENTRY("Buttons", "Buttons", ":/gui/icons/scopy-default/icons/tool_home.svg")); } bool TestPlugin::onConnect() @@ -38,19 +37,16 @@ bool TestPlugin::onConnect() QVBoxLayout *lay = new QVBoxLayout(tool); QLabel *lbl = new QLabel("TestPlugin", tool); lay->addWidget(lbl); - lay->addSpacerItem(new QSpacerItem(20,20,QSizePolicy::Expanding,QSizePolicy::Expanding)); - - + lay->addSpacerItem(new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Expanding)); m_toolList[0]->setTool(tool); return true; } - bool TestPlugin::onDisconnect() { - qDebug(CAT_GUITESTPLUGIN)<<"disconnect"; + qDebug(CAT_GUITESTPLUGIN) << "disconnect"; for(auto &tool : m_toolList) { tool->setEnabled(false); tool->setRunBtnVisible(false); @@ -66,7 +62,7 @@ bool TestPlugin::onDisconnect() void TestPlugin::initMetadata() { loadMetadata( -R"plugin( + R"plugin( { "priority":2, "category":[ diff --git a/plugins/guitestplugin/test/CMakeLists.txt b/plugins/guitestplugin/test/CMakeLists.txt index ff0d566e02..646197d6f9 100644 --- a/plugins/guitestplugin/test/CMakeLists.txt +++ b/plugins/guitestplugin/test/CMakeLists.txt @@ -2,7 +2,4 @@ cmake_minimum_required(VERSION 3.5) include(ScopyTest) -SETUP_SCOPY_TESTS( - pluginloader -) - +setup_scopy_tests(pluginloader) diff --git a/plugins/guitestplugin/test/tst_pluginloader.cpp b/plugins/guitestplugin/test/tst_pluginloader.cpp index 87a2cdf8cb..6c4f87f2bf 100644 --- a/plugins/guitestplugin/test/tst_pluginloader.cpp +++ b/plugins/guitestplugin/test/tst_pluginloader.cpp @@ -1,6 +1,8 @@ #include "qpluginloader.h" -#include + #include +#include + #include using namespace scopy; @@ -19,71 +21,64 @@ private Q_SLOTS: void clone(); void name(); void metadata(); - }; #define PLUGIN_LOCATION "../../plugins" #define FILENAME PLUGIN_LOCATION "/libscopy-guitestplugin.so" - void TST_TestPlugin::fileExists() { QFile f(FILENAME); bool ret; - qDebug()<(qp.instance()); - QVERIFY(instance != nullptr ); + QPluginLoader qp(FILENAME, this); + auto instance = qobject_cast(qp.instance()); + QVERIFY(instance != nullptr); } - void TST_TestPlugin::clone() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(); QVERIFY(p1 != nullptr); p2 = original->clone(); @@ -91,28 +86,28 @@ void TST_TestPlugin::clone() QVERIFY(p1 != p2); } -void TST_TestPlugin::name() { - QPluginLoader qp(FILENAME,this); +void TST_TestPlugin::name() +{ + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(); - qDebug()<name(); + qDebug() << p1->name(); } void TST_TestPlugin::metadata() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); original->initMetadata(); p1 = original->clone(); - qDebug()<metadata(); + qDebug() << p1->metadata(); QVERIFY(!p1->metadata().isEmpty()); } - QTEST_MAIN(TST_TestPlugin) #include "tst_pluginloader.moc" diff --git a/plugins/m2k/CMakeLists.txt b/plugins/m2k/CMakeLists.txt index 9c9941672b..c665c55d84 100644 --- a/plugins/m2k/CMakeLists.txt +++ b/plugins/m2k/CMakeLists.txt @@ -23,98 +23,107 @@ set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) set(SCOPY_QT_COMPONENTS Core Widgets UiTools) -FILE(GLOB SRC_LIST src/*.cpp src/*.cc) -FILE(GLOB OLD_SCOPY_FILES - src/old/*.cpp - src/old/logicanalyzer/*.cpp - src/old/logicanalyzer/*.hpp - src/old/patterngenerator/*.cpp - src/old/patterngenerator/*.hpp - src/old/patterngenerator/patterns/*.cpp - src/old/patterngenerator/patterns/*.hpp - src/old/*.hpp - src/old/*.cc - src/old/*.hh - src/old/*.c - src/old/*.h) -FILE(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) -FILE(GLOB UI_LIST ui/*.ui ui/patterns/*.ui) +file(GLOB SRC_LIST src/*.cpp src/*.cc) +file( + GLOB + OLD_SCOPY_FILES + src/old/*.cpp + src/old/logicanalyzer/*.cpp + src/old/logicanalyzer/*.hpp + src/old/patterngenerator/*.cpp + src/old/patterngenerator/*.hpp + src/old/patterngenerator/patterns/*.cpp + src/old/patterngenerator/patterns/*.hpp + src/old/*.hpp + src/old/*.cc + src/old/*.hh + src/old/*.c + src/old/*.h +) +file(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) +file(GLOB UI_LIST ui/*.ui ui/patterns/*.ui) set(ENABLE_TESTING ON) if(ENABLE_TESTING) - add_subdirectory(test) + add_subdirectory(test) endif() -set(PROJECT_SOURCES - ${SRC_LIST} - ${OLD_SCOPY_FILES} - ${HEADER_LIST} - ${UI_LIST} -) +set(PROJECT_SOURCES ${SRC_LIST} ${OLD_SCOPY_FILES} ${HEADER_LIST} ${UI_LIST}) set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH};/usr/local/lib/cmake) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS ${SCOPY_QT_COMPONENTS} REQUIRED) find_package(libm2k REQUIRED) -find_package(Boost COMPONENTS system filesystem thread chrono REQUIRED) # workaround for Gnuradio not finding Boost::chrono -find_package(Gnuradio "3.10" REQUIRED COMPONENTS runtime analog blocks fft filter volk pmt iio) +find_package(Boost COMPONENTS system filesystem thread chrono REQUIRED) # workaround for Gnuradio not finding +# Boost::chrono +find_package( + Gnuradio "3.10" REQUIRED + COMPONENTS runtime + analog + blocks + fft + filter + volk + pmt + iio +) find_package(gnuradio-scopy REQUIRED PATH_SUFFIXES scopy) find_package(gnuradio-m2k REQUIRED PATH_SUFFIXES m2k) if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") - set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY - "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") else() - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) endif() - qt_add_resources(PROJECT_RESOURCES res/resources.qrc) -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} - ${PROJECT_RESOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES} ${PROJECT_RESOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) -target_include_directories(${PROJECT_NAME} PRIVATE - Qt::Widgets - Qt::Core - scopy-gui - scopy-pluginbase - scopy-common - ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE} ${CMAKE_CURRENT_SOURCE_DIR}/src/old - ) +target_include_directories( + ${PROJECT_NAME} + PRIVATE Qt::Widgets + Qt::Core + scopy-gui + scopy-pluginbase + scopy-common + ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE} + ${CMAKE_CURRENT_SOURCE_DIR}/src/old +) target_include_directories(${PROJECT_NAME} PUBLIC scopy-pluginbase ${QWT_INCLUDE_DIRS}) foreach(comp ${SCOPY_QT_COMPONENTS}) - set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) + set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) endforeach() -target_link_libraries(${PROJECT_NAME} PUBLIC - ${SCOPY_QT_LIBRARIES} - ${QWT_LIBRARIES} - scopy-common - scopy-pluginbase - scopy-iioutil - scopy-gui - scopy-gr-gui - scopy-sigrok-gui - libm2k::libm2k - gnuradio::gnuradio-runtime - gnuradio::gnuradio-analog - gnuradio::gnuradio-blocks - gnuradio::gnuradio-fft - gnuradio::gnuradio-filter - gnuradio::gnuradio-pmt - gnuradio::gnuradio-iio - gnuradio::gnuradio-scopy - gnuradio::gnuradio-m2k +target_link_libraries( + ${PROJECT_NAME} + PUBLIC ${SCOPY_QT_LIBRARIES} + ${QWT_LIBRARIES} + scopy-common + scopy-pluginbase + scopy-iioutil + scopy-gui + scopy-gr-gui + scopy-sigrok-gui + libm2k::libm2k + gnuradio::gnuradio-runtime + gnuradio::gnuradio-analog + gnuradio::gnuradio-blocks + gnuradio::gnuradio-fft + gnuradio::gnuradio-filter + gnuradio::gnuradio-pmt + gnuradio::gnuradio-iio + gnuradio::gnuradio-scopy + gnuradio::gnuradio-m2k ) set(PLUGIN_NAME ${PROJECT_NAME} PARENT_SCOPE) diff --git a/plugins/m2k/include/m2kplugin/m2kcontroller.h b/plugins/m2k/include/m2kplugin/m2kcontroller.h index 0d9281c8e7..c70f0ca67f 100644 --- a/plugins/m2k/include/m2kplugin/m2kcontroller.h +++ b/plugins/m2k/include/m2kplugin/m2kcontroller.h @@ -1,17 +1,17 @@ #ifndef M2KCONTROLLER_H #define M2KCONTROLLER_H +#include "iioutil/cyclicaltask.h" +#include "iioutil/iiopingtask.h" +#include "libm2k/m2k.hpp" +#include "m2kidentifytask.h" +#include "m2kreadtemperaturetask.h" + #include #include -#include "m2kreadtemperaturetask.h" -#include "m2kidentifytask.h" -#include "iioutil/iiopingtask.h" -#include "iioutil/cyclicaltask.h" -#include "libm2k/m2k.hpp" #include - namespace scopy::m2k { class M2kController : public QObject { @@ -56,6 +56,5 @@ public Q_SLOTS: CyclicalTask *pingTimer; }; - -} +} // namespace scopy::m2k #endif // M2KCONTROLLER_H diff --git a/plugins/m2k/include/m2kplugin/m2kidentifytask.h b/plugins/m2k/include/m2kplugin/m2kidentifytask.h index c88c14ceb1..5dcd60963f 100644 --- a/plugins/m2k/include/m2kplugin/m2kidentifytask.h +++ b/plugins/m2k/include/m2kplugin/m2kidentifytask.h @@ -3,13 +3,15 @@ #include namespace scopy::m2k { -class M2kIdentifyTask : public QThread { +class M2kIdentifyTask : public QThread +{ public: M2kIdentifyTask(QString uri, QObject *parent = nullptr); ~M2kIdentifyTask(); void run() override; + private: QString m_uri; }; -} +} // namespace scopy::m2k #endif // M2KIDENTIFYTASK_H diff --git a/plugins/m2k/include/m2kplugin/m2kplugin.h b/plugins/m2k/include/m2kplugin/m2kplugin.h index f8ebabbe70..1ebb586f8e 100644 --- a/plugins/m2k/include/m2kplugin/m2kplugin.h +++ b/plugins/m2k/include/m2kplugin/m2kplugin.h @@ -6,15 +6,16 @@ #include //#include -#include +#include "iio_manager.hpp" +#include "m2kcontroller.h" #include "scopy-m2kplugin_export.h" + #include #include -#include "m2kcontroller.h" -#include -#include -#include "iio_manager.hpp" +#include +#include +#include namespace scopy { @@ -23,12 +24,11 @@ class SCOPY_M2KPLUGIN_EXPORT M2kPlugin : public QObject, public PluginBase { Q_OBJECT SCOPY_PLUGIN; -public: +public: void initMetadata() override; bool compatible(QString m_param, QString category) override; - void preload() override; void loadToolList() override; bool loadPage() override; @@ -71,17 +71,16 @@ public Q_SLOTS: InfoPage *m_m2kInfoPage; const int infoPageTimerTimeout = 1000; - const QStringList calibrationToolNames = {"Oscilloscope", "Spectrum Analyzer", "Network Analyzer", "Signal Generator", "Voltmeter", "Calibration"}; + const QStringList calibrationToolNames = {"Oscilloscope", "Spectrum Analyzer", "Network Analyzer", + "Signal Generator", "Voltmeter", "Calibration"}; - QMap tools; - QMap toolMenuEntryCalibrationCache; + QMap tools; + QMap toolMenuEntryCalibrationCache; void storeToolState(QStringList tools); void restoreToolState(QStringList tools); void cleanup(); - }; -} -} - +} // namespace m2k +} // namespace scopy #endif // M2KPLUGIN_H diff --git a/plugins/m2k/include/m2kplugin/m2kreadtemperaturetask.h b/plugins/m2k/include/m2kplugin/m2kreadtemperaturetask.h index d4fb1206a4..44abb3b716 100644 --- a/plugins/m2k/include/m2kplugin/m2kreadtemperaturetask.h +++ b/plugins/m2k/include/m2kplugin/m2kreadtemperaturetask.h @@ -1,9 +1,10 @@ #ifndef M2KREADTEMPERATURETASK_H #define M2KREADTEMPERATURETASK_H +#include + #include #include -#include namespace scopy::m2k { class M2kReadTemperatureTask : public QThread @@ -15,9 +16,9 @@ class M2kReadTemperatureTask : public QThread Q_SIGNALS: void newTemperature(double); + private: QString m_uri; - }; -} +} // namespace scopy::m2k #endif // M2KREADTEMPERATURETASK_H diff --git a/plugins/m2k/src/m2kcontroller.cpp b/plugins/m2k/src/m2kcontroller.cpp index 404bb56a4c..bed37eb007 100644 --- a/plugins/m2k/src/m2kcontroller.cpp +++ b/plugins/m2k/src/m2kcontroller.cpp @@ -1,7 +1,10 @@ #include "m2kcontroller.h" + #include "m2kcommon.h" + #include #include + #include #include @@ -12,30 +15,29 @@ using namespace libm2k::context; using namespace scopy; using namespace scopy::m2k; -M2kController::M2kController(QString uri, QObject *parent) : QObject(parent), uri(uri) -{ +M2kController::M2kController(QString uri, QObject *parent) + : QObject(parent) + , uri(uri) +{ identifyTask = nullptr; pingTask = nullptr; m_m2k = nullptr; } -M2kController::~M2kController() -{ - -} +M2kController::~M2kController() {} void M2kController::startPingTask() { pingTask = new IIOPingTask(m_iioctx); pingTimer = new CyclicalTask(pingTask, this); - connect(pingTask,SIGNAL(pingSuccess()),this,SIGNAL(pingSuccess())); - connect(pingTask,SIGNAL(pingFailed()),this,SIGNAL(pingFailed())); + connect(pingTask, SIGNAL(pingSuccess()), this, SIGNAL(pingSuccess())); + connect(pingTask, SIGNAL(pingFailed()), this, SIGNAL(pingFailed())); pingTimer->start(); } void M2kController::stopPingTask() { - if (!pingTask) { + if(!pingTask) { return; } pingTask->requestInterruption(); @@ -49,7 +51,7 @@ void M2kController::startTemperatureTask() { tempTask = new M2kReadTemperatureTask(uri); tempTimer = new CyclicalTask(tempTask); - connect(tempTask,SIGNAL(newTemperature(double)),this,SIGNAL(newTemperature(double))); + connect(tempTask, SIGNAL(newTemperature(double)), this, SIGNAL(newTemperature(double))); tempTimer->start(); } @@ -57,41 +59,39 @@ void M2kController::stopTemperatureTask() { tempTimer->stop(); tempTask->requestInterruption(); - disconnect(tempTask,SIGNAL(newTemperature(double)),this,SIGNAL(newTemperature(double))); + disconnect(tempTask, SIGNAL(newTemperature(double)), this, SIGNAL(newTemperature(double))); } void M2kController::connectM2k(iio_context *ctx) { m_iioctx = ctx; - m_m2k = m2kOpen(ctx,""); + m_m2k = m2kOpen(ctx, ""); identify(); } void M2kController::disconnectM2k() { - if (!m_m2k) { + if(!m_m2k) { return; } try { - if (identifyTask && identifyTask->isRunning()) { + if(identifyTask && identifyTask->isRunning()) { identifyTask->requestInterruption(); } - contextClose(m_m2k,true); + contextClose(m_m2k, true); } catch(std::exception &ex) { - qDebug(CAT_M2KPLUGIN)<start(); - connect(identifyTask,&QThread::finished,this,[=](){ + connect(identifyTask, &QThread::finished, this, [=]() { delete identifyTask; identifyTask = nullptr; }); @@ -100,7 +100,7 @@ void M2kController::identify() void M2kController::initialCalibration() { - if(!m_m2k->isCalibrated()) { + if(!m_m2k->isCalibrated()) { calibrate(); } else { // already calibrated / or skipped @@ -110,17 +110,17 @@ void M2kController::initialCalibration() void M2kController::calibrate() { QFutureWatcher *fw = new QFutureWatcher(this); - QFuture f = QtConcurrent::run(std::bind(&libm2k::context::M2k::calibrate,m_m2k)); - connect(fw,&QFutureWatcher::finished,this,[=](){ + QFuture f = QtConcurrent::run(std::bind(&libm2k::context::M2k::calibrate, m_m2k)); + connect(fw, &QFutureWatcher::finished, this, [=]() { try { if(fw->result()) { Q_EMIT calibrationSuccess(); - } else { + } else { Q_EMIT calibrationFailed(); } } catch(...) { Q_EMIT calibrationFailed(); - qWarning(CAT_M2KPLUGIN) <<"An exception occurred during CALIBRATION!"; + qWarning(CAT_M2KPLUGIN) << "An exception occurred during CALIBRATION!"; } Q_EMIT calibrationFinished(); fw->deleteLater(); diff --git a/plugins/m2k/src/m2kidentifytask.cpp b/plugins/m2k/src/m2kidentifytask.cpp index 1a80894fd6..d87d1a329e 100644 --- a/plugins/m2k/src/m2kidentifytask.cpp +++ b/plugins/m2k/src/m2kidentifytask.cpp @@ -1,34 +1,40 @@ #include "m2kidentifytask.h" -#include + #include "iioutil/contextprovider.h" +#include + using namespace scopy::m2k; -M2kIdentifyTask::M2kIdentifyTask(QString uri, QObject *parent) : QThread(parent), m_uri(uri) {} +M2kIdentifyTask::M2kIdentifyTask(QString uri, QObject *parent) + : QThread(parent) + , m_uri(uri) +{} M2kIdentifyTask::~M2kIdentifyTask() {} -void M2kIdentifyTask::run() { +void M2kIdentifyTask::run() +{ iio_context *ctx = ContextProvider::GetInstance()->open(m_uri); iio_device *dev; iio_channel *ch; if(!ctx) return; - dev = iio_context_find_device(ctx,"m2k-fabric"); + dev = iio_context_find_device(ctx, "m2k-fabric"); if(!dev) return; - ch = iio_device_find_channel(dev,"voltage4",true); + ch = iio_device_find_channel(dev, "voltage4", true); if(!ch) return; - for( int i = 0;i<10;i++) { + for(int i = 0; i < 10; i++) { if(isInterruptionRequested()) break; - iio_channel_attr_write(ch,"done_led_overwrite_powerdown","1"); + iio_channel_attr_write(ch, "done_led_overwrite_powerdown", "1"); QThread::msleep(100); if(isInterruptionRequested()) break; - iio_channel_attr_write(ch,"done_led_overwrite_powerdown","0"); + iio_channel_attr_write(ch, "done_led_overwrite_powerdown", "0"); QThread::msleep(100); } diff --git a/plugins/m2k/src/m2kplugin.cpp b/plugins/m2k/src/m2kplugin.cpp index f0fabe398a..9b2239a709 100644 --- a/plugins/m2k/src/m2kplugin.cpp +++ b/plugins/m2k/src/m2kplugin.cpp @@ -1,43 +1,47 @@ #include "m2kplugin.h" + +#include "digitalchannel_manager.hpp" #include "digitalio.hpp" +#include "dmm.hpp" +#include "filter.hpp" +#include "iioutil/contextprovider.h" #include "m2kcommon.h" +#include "manualcalibration.h" +#include "network_analyzer.hpp" +#include "oscilloscope.hpp" +#include "patterngenerator/pattern_generator.h" +#include "power_controller.hpp" +#include "qtextbrowser.h" +#include "signal_generator.hpp" +#include "spectrum_analyzer.hpp" + +#include + #include #include #include -#include #include +#include #include #include + #include -#include #include +#include #include #include #include #include -#include "iioutil/contextprovider.h" -#include - -#include "filter.hpp" -#include "dmm.hpp" -#include "manualcalibration.h" -#include "digitalchannel_manager.hpp" -#include "network_analyzer.hpp" -#include "oscilloscope.hpp" -#include "patterngenerator/pattern_generator.h" -#include "power_controller.hpp" -#include "qtextbrowser.h" -#include "signal_generator.hpp" -#include "spectrum_analyzer.hpp" using namespace scopy; using namespace scopy::m2k; -Q_LOGGING_CATEGORY(CAT_M2KPLUGIN,"M2KPLUGIN"); +Q_LOGGING_CATEGORY(CAT_M2KPLUGIN, "M2KPLUGIN"); Q_LOGGING_CATEGORY(CAT_BENCHMARK, "Benchmark") -bool M2kPlugin::compatible(QString m_param, QString category) { - qDebug(CAT_M2KPLUGIN)<<"compatible"; +bool M2kPlugin::compatible(QString m_param, QString category) +{ + qDebug(CAT_M2KPLUGIN) << "compatible"; bool ret = false; ContextProvider *c = ContextProvider::GetInstance(); iio_context *ctx = c->open(m_param); @@ -45,9 +49,9 @@ bool M2kPlugin::compatible(QString m_param, QString category) { if(!ctx) return false; -// ret = !!iio_context_find_device(ctx,"m2k-adc"); -// ret = ret && !!iio_context_find_device(ctx,"m2k-dac-a"); -// ret = ret && !!iio_context_find_device(ctx,"m2k-dac-b"); + // ret = !!iio_context_find_device(ctx,"m2k-adc"); + // ret = ret && !!iio_context_find_device(ctx,"m2k-dac-a"); + // ret = ret && !!iio_context_find_device(ctx,"m2k-dac-b"); Filter *f = new Filter(ctx); ret = (f->hw_name().compare("M2K") == 0); @@ -59,36 +63,45 @@ bool M2kPlugin::compatible(QString m_param, QString category) { void M2kPlugin::preload() { - m_m2kController = new M2kController(m_param,this); + m_m2kController = new M2kController(m_param, this); m_displayName = "M2k"; } - void M2kPlugin::loadToolList() { Preferences *p = Preferences::GetInstance(); - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2kosc",tr("Oscilloscope"),":/gui/icons/scopy-default/icons/tool_oscilloscope.svg")); - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2kspec",tr("Spectrum Analyzer"),":/gui/icons/scopy-default/icons/tool_spectrum_analyzer.svg")); - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2knet",tr("Network Analyzer"),":/gui/icons/scopy-default/icons/tool_network_analyzer.svg")); - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2ksiggen",tr("Signal Generator"),":/gui/icons/scopy-default/icons/tool_signal_generator.svg")); - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2klogic",tr("Logic Analyzer"),":/gui/icons/scopy-default/icons/tool_logic_analyzer.svg")); - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2kpattern",tr("Pattern Generator"),":/gui/icons/scopy-default/icons/tool_pattern_generator.svg")); - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2kdio",tr("Digital I/O"),":/gui/icons/scopy-default/icons/tool_io.svg")); - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2kdmm",tr("Voltmeter"),":/gui/icons/scopy-default/icons/tool_voltmeter.svg")); - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2kpower",tr("Power Supply"),":/gui/icons/scopy-default/icons/tool_power_supply.svg")); - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2kcal",tr("Calibration"),":/gui/icons/scopy-default/icons/tool_calibration.svg")); - ToolMenuEntry::findToolMenuEntryById(m_toolList,"m2kcal")->setVisible(p->get("m2k_manual_calibration_enable").toBool()); - + m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2kosc", tr("Oscilloscope"), + ":/gui/icons/scopy-default/icons/tool_oscilloscope.svg")); + m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2kspec", tr("Spectrum Analyzer"), + ":/gui/icons/scopy-default/icons/tool_spectrum_analyzer.svg")); + m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2knet", tr("Network Analyzer"), + ":/gui/icons/scopy-default/icons/tool_network_analyzer.svg")); + m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2ksiggen", tr("Signal Generator"), + ":/gui/icons/scopy-default/icons/tool_signal_generator.svg")); + m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2klogic", tr("Logic Analyzer"), + ":/gui/icons/scopy-default/icons/tool_logic_analyzer.svg")); + m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2kpattern", tr("Pattern Generator"), + ":/gui/icons/scopy-default/icons/tool_pattern_generator.svg")); + m_toolList.append( + SCOPY_NEW_TOOLMENUENTRY("m2kdio", tr("Digital I/O"), ":/gui/icons/scopy-default/icons/tool_io.svg")); + m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2kdmm", tr("Voltmeter"), + ":/gui/icons/scopy-default/icons/tool_voltmeter.svg")); + m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2kpower", tr("Power Supply"), + ":/gui/icons/scopy-default/icons/tool_power_supply.svg")); + m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("m2kcal", tr("Calibration"), + ":/gui/icons/scopy-default/icons/tool_calibration.svg")); + ToolMenuEntry::findToolMenuEntryById(m_toolList, "m2kcal") + ->setVisible(p->get("m2k_manual_calibration_enable").toBool()); } bool M2kPlugin::loadPage() { m_infoPageTimer = new QTimer(this); - m_infoPageTimer->setInterval(infoPageTimerTimeout); - connect(m_m2kController,SIGNAL(newTemperature(double)),this, SLOT(updateTemperature(double))); + m_infoPageTimer->setInterval(infoPageTimerTimeout); + connect(m_m2kController, SIGNAL(newTemperature(double)), this, SLOT(updateTemperature(double))); m_page = new QWidget(); QVBoxLayout *lay = new QVBoxLayout(m_page); - m_page->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); + m_page->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_m2kInfoPage = new InfoPage(m_page); lay->addWidget(m_m2kInfoPage); @@ -99,46 +112,49 @@ bool M2kPlugin::loadPage() textBrowser->setFixedHeight(800); lay->addWidget(textBrowser); - m_m2kInfoPage->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); + m_m2kInfoPage->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); ContextProvider *c = ContextProvider::GetInstance(); iio_context *ctx = c->open(m_param); - for(int i=0;iupdate(name,value); - + m_m2kInfoPage->update(name, value); } c->close(m_param); - return true; } bool M2kPlugin::loadExtraButtons() { - m_btnIdentify = new QPushButton("Identify"); m_extraButtons.append(m_btnIdentify); - m_btnCalibrate = new QPushButton("Calibrate"); m_extraButtons.append(m_btnCalibrate); - m_btnRegister = new QPushButton("Register"); m_extraButtons.append(m_btnRegister); + m_btnIdentify = new QPushButton("Identify"); + m_extraButtons.append(m_btnIdentify); + m_btnCalibrate = new QPushButton("Calibrate"); + m_extraButtons.append(m_btnCalibrate); + m_btnRegister = new QPushButton("Register"); + m_extraButtons.append(m_btnRegister); m_btnCalibrate->setDisabled(true); - connect(m_btnIdentify,SIGNAL(clicked()),m_m2kController,SLOT(identify())); - connect(m_btnCalibrate,SIGNAL(clicked()),m_m2kController,SLOT(calibrate())); - connect(m_m2kController,&M2kController::calibrationStarted, this, [=](){m_btnCalibrate->setEnabled(false);}); - connect(m_m2kController,&M2kController::calibrationFinished, this, [=](){m_btnCalibrate->setEnabled(true);}); - connect(m_btnRegister,&QPushButton::clicked,this,[=](){ + connect(m_btnIdentify, SIGNAL(clicked()), m_m2kController, SLOT(identify())); + connect(m_btnCalibrate, SIGNAL(clicked()), m_m2kController, SLOT(calibrate())); + connect(m_m2kController, &M2kController::calibrationStarted, this, + [=]() { m_btnCalibrate->setEnabled(false); }); + connect(m_m2kController, &M2kController::calibrationFinished, this, + [=]() { m_btnCalibrate->setEnabled(true); }); + connect(m_btnRegister, &QPushButton::clicked, this, [=]() { ; -// QString versionString = QString(m_info_params["Model"].split("Rev")[1][1]); -// QString url = "https://my.analog.com/en/app/registration/hardware/ADALM2000?sn="+QString(getSerialNumber())+"&v=Rev."+versionString; -// QDesktopServices::openUrl(QUrl(url)); + // QString versionString = QString(m_info_params["Model"].split("Rev")[1][1]); + // QString url = + //"https://my.analog.com/en/app/registration/hardware/ADALM2000?sn="+QString(getSerialNumber())+"&v=Rev."+versionString; + // QDesktopServices::openUrl(QUrl(url)); }); - return true; } @@ -148,21 +164,15 @@ bool M2kPlugin::loadIcon() return true; } -void M2kPlugin::showPageCallback() -{ - m_m2kController->startTemperatureTask(); -} +void M2kPlugin::showPageCallback() { m_m2kController->startTemperatureTask(); } -void M2kPlugin::hidePageCallback() -{ - m_m2kController->stopTemperatureTask(); -} +void M2kPlugin::hidePageCallback() { m_m2kController->stopTemperatureTask(); } void M2kPlugin::calibrationStarted() { storeToolState(calibrationToolNames); for(const QString &tool : calibrationToolNames) { - auto tme = ToolMenuEntry::findToolMenuEntryByName(m_toolList,tool); + auto tme = ToolMenuEntry::findToolMenuEntryByName(m_toolList, tool); tme->setName("Calibrating ... "); tme->setEnabled(false); tme->setRunning(false); @@ -170,35 +180,28 @@ void M2kPlugin::calibrationStarted() } } -void M2kPlugin::calibrationSuccess() -{ - restoreToolState(calibrationToolNames); -} +void M2kPlugin::calibrationSuccess() { restoreToolState(calibrationToolNames); } -void M2kPlugin::calibrationFinished() -{ - restoreToolState(calibrationToolNames); -} +void M2kPlugin::calibrationFinished() { restoreToolState(calibrationToolNames); } -void M2kPlugin::updateTemperature(double val) -{ - m_m2kInfoPage->update("Temperature", QString::number(val)); -} +void M2kPlugin::updateTemperature(double val) { m_m2kInfoPage->update("Temperature", QString::number(val)); } -void M2kPlugin::storeToolState(QStringList tools) { +void M2kPlugin::storeToolState(QStringList tools) +{ for(const QString &tool : calibrationToolNames) { - auto tme = ToolMenuEntry::findToolMenuEntryByName(m_toolList,tool); + auto tme = ToolMenuEntry::findToolMenuEntryByName(m_toolList, tool); toolMenuEntryCalibrationCache[tool] = new ToolMenuEntry(*tme); // save tool state } } -void M2kPlugin::restoreToolState(QStringList tools) { +void M2kPlugin::restoreToolState(QStringList tools) +{ for(const QString &tool : calibrationToolNames) { if(!toolMenuEntryCalibrationCache.contains(tool)) continue; - ToolMenuEntry* cachedTme = toolMenuEntryCalibrationCache[tool]; + ToolMenuEntry *cachedTme = toolMenuEntryCalibrationCache[tool]; auto id = toolMenuEntryCalibrationCache[tool]->id(); - auto tme = ToolMenuEntry::findToolMenuEntryById(m_toolList,id); + auto tme = ToolMenuEntry::findToolMenuEntryById(m_toolList, id); tme->setName(cachedTme->name()); tme->setEnabled(cachedTme->enabled()); tme->setRunning(cachedTme->running()); @@ -210,22 +213,21 @@ void M2kPlugin::restoreToolState(QStringList tools) { void M2kPlugin::initPreferences() { Preferences *p = Preferences::GetInstance(); - p->init("m2k_instrument_notes_active",false); - p->init("m2k_manual_calibration_enable",false); - - p->init("m2k_show_adc_filters",false); - p->init("m2k_show_graticule",false); - p->init("m2k_mini_histogram",false); - p->init("m2k_osc_filtering",true); - p->init("m2k_osc_label",false); - p->init("m2k_siggen_periods",2); - p->init("m2k_spectrum_visible_peak_search",true); - p->init("m2k_na_show_zero",false); - - p->init("m2k_logic_separate_annotations",false); - p->init("m2k_logic_display_sampling_points",false); - p->init("m2k_logic_display_sample_time",true); - + p->init("m2k_instrument_notes_active", false); + p->init("m2k_manual_calibration_enable", false); + + p->init("m2k_show_adc_filters", false); + p->init("m2k_show_graticule", false); + p->init("m2k_mini_histogram", false); + p->init("m2k_osc_filtering", true); + p->init("m2k_osc_label", false); + p->init("m2k_siggen_periods", 2); + p->init("m2k_spectrum_visible_peak_search", true); + p->init("m2k_na_show_zero", false); + + p->init("m2k_logic_separate_annotations", false); + p->init("m2k_logic_display_sampling_points", false); + p->init("m2k_logic_display_sample_time", true); } bool M2kPlugin::loadPreferencesPage() @@ -239,52 +241,65 @@ bool M2kPlugin::loadPreferencesPage() // General preferences MenuSectionWidget *generalWidget = new MenuSectionWidget(m_preferencesPage); - MenuCollapseSection *generalSection = new MenuCollapseSection("General",MenuCollapseSection::MHCW_NONE, generalWidget); + MenuCollapseSection *generalSection = + new MenuCollapseSection("General", MenuCollapseSection::MHCW_NONE, generalWidget); generalWidget->contentLayout()->setSpacing(10); generalWidget->contentLayout()->addWidget(generalSection); generalSection->contentLayout()->setSpacing(10); lay->addWidget(generalWidget); - lay->addSpacerItem(new QSpacerItem(0,0,QSizePolicy::Minimum,QSizePolicy::Expanding)); + lay->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); - generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"m2k_instrument_notes_active","Instrument Notes",generalSection)); + generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox( + p, "m2k_instrument_notes_active", "Instrument Notes", generalSection)); // Analog tools preferences MenuSectionWidget *analogWidget = new MenuSectionWidget(m_preferencesPage); - MenuCollapseSection *analogSection = new MenuCollapseSection("Analog tools",MenuCollapseSection::MHCW_NONE, analogWidget); + MenuCollapseSection *analogSection = + new MenuCollapseSection("Analog tools", MenuCollapseSection::MHCW_NONE, analogWidget); analogWidget->contentLayout()->setSpacing(10); analogWidget->contentLayout()->addWidget(analogSection); analogSection->contentLayout()->setSpacing(10); lay->addWidget(analogWidget); - lay->addSpacerItem(new QSpacerItem(0,0,QSizePolicy::Minimum,QSizePolicy::Expanding)); - - analogSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"m2k_show_adc_filters","Show ADC digital filter config",analogSection)); - analogSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"m2k_show_graticule","Enable graticule",analogSection)); - analogSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"m2k_mini_histogram","Enable mini histogram",analogSection)); - analogSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"m2k_osc_filtering","Enable sample rate filters",analogSection)); - analogSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"m2k_osc_label","Enable labels on the plot",analogSection)); - analogSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"m2k_spectrum_visible_peak_search","Only search marker peaks in visible domain",analogSection)); - analogSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"m2k_na_show_zero","Always display 0db value on the graph",analogSection)); - analogSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceEdit(p,"m2k_siggen_periods","Number of displayed periods",analogSection)); + lay->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); + + analogSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox( + p, "m2k_show_adc_filters", "Show ADC digital filter config", analogSection)); + analogSection->contentLayout()->addWidget( + PreferencesHelper::addPreferenceCheckBox(p, "m2k_show_graticule", "Enable graticule", analogSection)); + analogSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox( + p, "m2k_mini_histogram", "Enable mini histogram", analogSection)); + analogSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox( + p, "m2k_osc_filtering", "Enable sample rate filters", analogSection)); + analogSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox( + p, "m2k_osc_label", "Enable labels on the plot", analogSection)); + analogSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox( + p, "m2k_spectrum_visible_peak_search", "Only search marker peaks in visible domain", analogSection)); + analogSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox( + p, "m2k_na_show_zero", "Always display 0db value on the graph", analogSection)); + analogSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceEdit( + p, "m2k_siggen_periods", "Number of displayed periods", analogSection)); // Logic tools preferences MenuSectionWidget *logicWidget = new MenuSectionWidget(m_preferencesPage); - MenuCollapseSection *logicSection = new MenuCollapseSection("Logic tools",MenuCollapseSection::MHCW_NONE, logicWidget); + MenuCollapseSection *logicSection = + new MenuCollapseSection("Logic tools", MenuCollapseSection::MHCW_NONE, logicWidget); logicWidget->contentLayout()->setSpacing(10); logicWidget->contentLayout()->addWidget(logicSection); logicSection->contentLayout()->setSpacing(10); lay->addWidget(logicWidget); - lay->addSpacerItem(new QSpacerItem(0,0,QSizePolicy::Minimum,QSizePolicy::Expanding)); + lay->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); - logicSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"m2k_logic_separate_annotations","Separate decoder annotaions when exporting",logicSection)); - logicSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"m2k_logic_display_sampling_points","Display sampling points when zoomed",logicSection)); - logicSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"m2k_logic_display_sample_time","Show sample and time info in decoder table",logicSection)); + logicSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox( + p, "m2k_logic_separate_annotations", "Separate decoder annotaions when exporting", logicSection)); + logicSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox( + p, "m2k_logic_display_sampling_points", "Display sampling points when zoomed", logicSection)); + logicSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox( + p, "m2k_logic_display_sample_time", "Show sample and time info in decoder table", logicSection)); return true; } -void M2kPlugin::init() -{ -} +void M2kPlugin::init() {} void M2kPlugin::saveSettings(QSettings &s) { @@ -308,11 +323,11 @@ void M2kPlugin::loadSettings(QSettings &s) void M2kPlugin::cleanup() { - if (m2k_man) { + if(m2k_man) { delete m2k_man; m2k_man = nullptr; } - if (calib) { + if(calib) { delete calib; calib = nullptr; } @@ -324,10 +339,10 @@ void M2kPlugin::cleanup() tme->setTool(nullptr); } - disconnect(m_m2kController,&M2kController::pingFailed,this,&M2kPlugin::disconnectDevice); + disconnect(m_m2kController, &M2kController::pingFailed, this, &M2kPlugin::disconnectDevice); disconnect(m_m2kController, SIGNAL(calibrationStarted()), this, SLOT(calibrationStarted())); disconnect(m_m2kController, SIGNAL(calibrationSuccess()), this, SLOT(calibrationSuccess())); - disconnect(m_m2kController, SIGNAL(calibrationFailed()) , this, SLOT(calibrationFinished())); + disconnect(m_m2kController, SIGNAL(calibrationFailed()), this, SLOT(calibrationFinished())); m_m2kController->stopPingTask(); m_m2kController->disconnectM2k(); @@ -342,7 +357,7 @@ bool M2kPlugin::onConnect() ContextProvider *c = ContextProvider::GetInstance(); iio_context *ctx = c->open(m_param); - if (!ctx) { + if(!ctx) { return false; } try { @@ -351,63 +366,81 @@ bool M2kPlugin::onConnect() m_m2kController->connectM2k(ctx); m_m2kController->startPingTask(); - connect(m_m2kController,&M2kController::pingFailed,this,&M2kPlugin::disconnectDevice); + connect(m_m2kController, &M2kController::pingFailed, this, &M2kPlugin::disconnectDevice); Filter *f = new Filter(ctx); QJSEngine *js = ScopyJS::GetInstance()->engine(); auto calib = new Calibration(ctx); - auto diom = new DIOManager(ctx,f); - auto dmmTme = ToolMenuEntry::findToolMenuEntryById(m_toolList,"m2kdmm"); - auto mancalTme = ToolMenuEntry::findToolMenuEntryById(m_toolList,"m2kcal"); - auto dioTme = ToolMenuEntry::findToolMenuEntryById(m_toolList,"m2kdio"); - auto pwrTme = ToolMenuEntry::findToolMenuEntryById(m_toolList,"m2kpower"); - auto siggenTme = ToolMenuEntry::findToolMenuEntryById(m_toolList,"m2ksiggen"); - auto specTme = ToolMenuEntry::findToolMenuEntryById(m_toolList,"m2kspec"); - auto oscTme = ToolMenuEntry::findToolMenuEntryById(m_toolList,"m2kosc"); - auto netTme = ToolMenuEntry::findToolMenuEntryById(m_toolList,"m2knet"); - auto laTme = ToolMenuEntry::findToolMenuEntryById(m_toolList,"m2klogic"); - auto pgTme = ToolMenuEntry::findToolMenuEntryById(m_toolList,"m2kpattern"); + auto diom = new DIOManager(ctx, f); + auto dmmTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, "m2kdmm"); + auto mancalTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, "m2kcal"); + auto dioTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, "m2kdio"); + auto pwrTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, "m2kpower"); + auto siggenTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, "m2ksiggen"); + auto specTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, "m2kspec"); + auto oscTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, "m2kosc"); + auto netTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, "m2knet"); + auto laTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, "m2klogic"); + auto pgTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, "m2kpattern"); m_adcBtnGrp = new QButtonGroup(this); - tools.insert("m2kdmm",new DMM(ctx, f, dmmTme, m2k_man)); dmmTme->setTool(tools["m2kdmm"]); - tools.insert("m2kcal",new ManualCalibration(ctx,f,mancalTme,nullptr,calib)); mancalTme->setTool(tools["m2kcal"]); - tools.insert("m2kdio",new DigitalIO(ctx,f,dioTme,diom,js,nullptr));dioTme->setTool(tools["m2kdio"]); - tools.insert("m2kpower",new PowerController(ctx,pwrTme,js,nullptr));pwrTme->setTool(tools["m2kpower"]); - tools.insert("m2ksiggen",new SignalGenerator(ctx,f,siggenTme,js,nullptr));siggenTme->setTool(tools["m2ksiggen"]); - tools.insert("m2kspec",new SpectrumAnalyzer(ctx,f,specTme,m2k_man,js,nullptr));specTme->setTool(tools["m2kspec"]); - tools.insert("m2kosc",new Oscilloscope(ctx,f,oscTme,m2k_man,js,nullptr));oscTme->setTool(tools["m2kosc"]); - tools.insert("m2knet",new NetworkAnalyzer(ctx,f,netTme,m2k_man,js,nullptr));netTme->setTool(tools["m2knet"]); - tools.insert("m2klogic",new logic::LogicAnalyzer(ctx,f,laTme,js,nullptr));laTme->setTool(tools["m2klogic"]); - - logic::LogicAnalyzer* logic_analyzer = dynamic_cast(tools["m2klogic"]); - Oscilloscope* oscilloscope = dynamic_cast(tools["m2kosc"]); - NetworkAnalyzer* network_analyzer = dynamic_cast(tools["m2knet"]); + tools.insert("m2kdmm", new DMM(ctx, f, dmmTme, m2k_man)); + dmmTme->setTool(tools["m2kdmm"]); + tools.insert("m2kcal", new ManualCalibration(ctx, f, mancalTme, nullptr, calib)); + mancalTme->setTool(tools["m2kcal"]); + tools.insert("m2kdio", new DigitalIO(ctx, f, dioTme, diom, js, nullptr)); + dioTme->setTool(tools["m2kdio"]); + tools.insert("m2kpower", new PowerController(ctx, pwrTme, js, nullptr)); + pwrTme->setTool(tools["m2kpower"]); + tools.insert("m2ksiggen", new SignalGenerator(ctx, f, siggenTme, js, nullptr)); + siggenTme->setTool(tools["m2ksiggen"]); + tools.insert("m2kspec", new SpectrumAnalyzer(ctx, f, specTme, m2k_man, js, nullptr)); + specTme->setTool(tools["m2kspec"]); + tools.insert("m2kosc", new Oscilloscope(ctx, f, oscTme, m2k_man, js, nullptr)); + oscTme->setTool(tools["m2kosc"]); + tools.insert("m2knet", new NetworkAnalyzer(ctx, f, netTme, m2k_man, js, nullptr)); + netTme->setTool(tools["m2knet"]); + tools.insert("m2klogic", new logic::LogicAnalyzer(ctx, f, laTme, js, nullptr)); + laTme->setTool(tools["m2klogic"]); + + logic::LogicAnalyzer *logic_analyzer = dynamic_cast(tools["m2klogic"]); + Oscilloscope *oscilloscope = dynamic_cast(tools["m2kosc"]); + NetworkAnalyzer *network_analyzer = dynamic_cast(tools["m2knet"]); oscilloscope->setLogicAnalyzer(logic_analyzer); network_analyzer->setOscilloscope(oscilloscope); - tools.insert("m2kpattern",new logic::PatternGenerator(ctx,f,pgTme,js,diom,nullptr));pgTme->setTool(tools["m2kpattern"]); - connect(dynamic_cast(siggenTme->tool())->getRunButton(),&QPushButton::toggled, this,[=](bool en){ - if(en) { - if(dynamic_cast(netTme->tool())->getRunButton()->isChecked()) - dynamic_cast(netTme->tool())->getRunButton()->setChecked(false); - } - }); - - connect(dynamic_cast(netTme->tool())->getRunButton(),&QPushButton::toggled, this,[=](bool en){ - if(en) { - if(dynamic_cast(siggenTme->tool())->getRunButton()->isChecked()) - dynamic_cast(siggenTme->tool())->getRunButton()->setChecked(false); - } - }); + tools.insert("m2kpattern", new logic::PatternGenerator(ctx, f, pgTme, js, diom, nullptr)); + pgTme->setTool(tools["m2kpattern"]); + connect(dynamic_cast(siggenTme->tool())->getRunButton(), &QPushButton::toggled, this, + [=](bool en) { + if(en) { + if(dynamic_cast(netTme->tool())->getRunButton()->isChecked()) + dynamic_cast(netTme->tool()) + ->getRunButton() + ->setChecked(false); + } + }); + + connect(dynamic_cast(netTme->tool())->getRunButton(), &QPushButton::toggled, this, + [=](bool en) { + if(en) { + if(dynamic_cast(siggenTme->tool()) + ->getRunButton() + ->isChecked()) + dynamic_cast(siggenTme->tool()) + ->getRunButton() + ->setChecked(false); + } + }); // m_dacBtnGrp->addButton(dynamic_cast(netTme->tool())->getRunButton()); // m_dacBtnGrp->addButton(dynamic_cast(siggenTme->tool())->getRunButton()); connect(m_m2kController, SIGNAL(calibrationStarted()), this, SLOT(calibrationStarted())); connect(m_m2kController, SIGNAL(calibrationSuccess()), this, SLOT(calibrationSuccess())); - connect(m_m2kController, SIGNAL(calibrationFailed()) , this, SLOT(calibrationFinished())); + connect(m_m2kController, SIGNAL(calibrationFailed()), this, SLOT(calibrationFinished())); for(ToolMenuEntry *tme : qAsConst(m_toolList)) { tme->setEnabled(true); @@ -424,19 +457,21 @@ bool M2kPlugin::onConnect() } bool M2kPlugin::onDisconnect() -{ +{ cleanup(); return true; } -QString M2kPlugin::description() { - return "Implements ADALM2000 instruments - Oscilloscope, Spectrum Analyzer, Voltmeter, Network Analyzer, Signal Generator, Logic Analyzer, Pattern Generator, Digital I/O"; +QString M2kPlugin::description() +{ + return "Implements ADALM2000 instruments - Oscilloscope, Spectrum Analyzer, Voltmeter, Network Analyzer, " + "Signal Generator, Logic Analyzer, Pattern Generator, Digital I/O"; } void M2kPlugin::initMetadata() { loadMetadata( -R"plugin( + R"plugin( { "disconnectDevOnConnectFailure":true, "priority":100, @@ -449,6 +484,4 @@ R"plugin( )plugin"); } - - #include "moc_m2kplugin.cpp" diff --git a/plugins/m2k/src/m2kreadtemperaturetask.cpp b/plugins/m2k/src/m2kreadtemperaturetask.cpp index abedc9ed8e..cb61c5949f 100644 --- a/plugins/m2k/src/m2kreadtemperaturetask.cpp +++ b/plugins/m2k/src/m2kreadtemperaturetask.cpp @@ -1,18 +1,22 @@ #include "m2kreadtemperaturetask.h" -#include + #include "m2kcommon.h" + #include +#include + using namespace scopy::m2k; -M2kReadTemperatureTask::M2kReadTemperatureTask(QString uri) : QThread() +M2kReadTemperatureTask::M2kReadTemperatureTask(QString uri) + : QThread() { m_uri = uri; } void M2kReadTemperatureTask::run() { - double val,scale,offset, temperature; + double val, scale, offset, temperature; iio_device *dev; iio_channel *ch; int ret; @@ -20,25 +24,25 @@ void M2kReadTemperatureTask::run() iio_context *ctx = ContextProvider::GetInstance()->open(m_uri); if(!ctx) goto finish; - dev = iio_context_find_device(ctx,"ad9963"); + dev = iio_context_find_device(ctx, "ad9963"); if(!dev) goto finish; - ch = iio_device_find_channel(dev,"temp0",false); + ch = iio_device_find_channel(dev, "temp0", false); if(!ch) goto finish; - ret = iio_channel_attr_read_double(ch,"raw",&val); + ret = iio_channel_attr_read_double(ch, "raw", &val); if(ret) goto finish; - iio_channel_attr_read_double(ch,"scale",&scale); + iio_channel_attr_read_double(ch, "scale", &scale); if(ret) goto finish; - iio_channel_attr_read_double(ch,"offset",&offset); + iio_channel_attr_read_double(ch, "offset", &offset); if(ret) goto finish; temperature = (val + offset) * scale / 1000; - qDebug(CAT_M2KPLUGIN)<<"Read temperature"<< temperature; + qDebug(CAT_M2KPLUGIN) << "Read temperature" << temperature; Q_EMIT newTemperature(temperature); diff --git a/plugins/m2k/src/old/adc_sample_conv.cpp b/plugins/m2k/src/old/adc_sample_conv.cpp index 70f3a71123..f0aa06d41a 100644 --- a/plugins/m2k/src/old/adc_sample_conv.cpp +++ b/plugins/m2k/src/old/adc_sample_conv.cpp @@ -20,64 +20,56 @@ #include "adc_sample_conv.hpp" -#include -#include +#include "m2kpluginExceptionHandler.h" -#include #include -#include "m2kpluginExceptionHandler.h" +#include +#include +#include using namespace gr; using namespace scopy; using namespace libm2k::analog; -adc_sample_conv::adc_sample_conv(int nconnections, - M2kAnalogIn* adc, - bool inverse) : - gr::sync_block("adc_sample_conv", - gr::io_signature::make(nconnections, nconnections, sizeof(float)), - gr::io_signature::make(nconnections, nconnections, sizeof(float))), - d_nconnections(nconnections), - inverse(inverse), - m2k_adc(adc) -{ -} +adc_sample_conv::adc_sample_conv(int nconnections, M2kAnalogIn *adc, bool inverse) + : gr::sync_block("adc_sample_conv", gr::io_signature::make(nconnections, nconnections, sizeof(float)), + gr::io_signature::make(nconnections, nconnections, sizeof(float))) + , d_nconnections(nconnections) + , inverse(inverse) + , m2k_adc(adc) +{} -adc_sample_conv::~adc_sample_conv() -{ -} +adc_sample_conv::~adc_sample_conv() {} double adc_sample_conv::conversionWrapper(unsigned int chn_idx, double sample, bool raw_to_volts) { try { - if (raw_to_volts) { + if(raw_to_volts) { return m2k_adc->convertRawToVolts(chn_idx, (short)sample); } else { return m2k_adc->convertVoltsToRaw(chn_idx, sample); } - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) return 0; } } -int adc_sample_conv::work(int noutput_items, - gr_vector_const_void_star &input_items, - gr_vector_void_star &output_items) +int adc_sample_conv::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock lock(d_setlock); - for (unsigned int i = 0; i < input_items.size(); i++) { - const float* in = static_cast(input_items[i]); + for(unsigned int i = 0; i < input_items.size(); i++) { + const float *in = static_cast(input_items[i]); float *out = static_cast(output_items[i]); - if (inverse) { - for (int j = 0; j < noutput_items; j++) { + if(inverse) { + for(int j = 0; j < noutput_items; j++) { out[j] = m2k_adc->convertVoltsToRaw(i, in[j]); } } else { - for (int j = 0; j < noutput_items; j++) + for(int j = 0; j < noutput_items; j++) out[j] = m2k_adc->convertRawToVolts(i, in[j]); } } diff --git a/plugins/m2k/src/old/adc_sample_conv.hpp b/plugins/m2k/src/old/adc_sample_conv.hpp index e694514f41..0d54f5732b 100644 --- a/plugins/m2k/src/old/adc_sample_conv.hpp +++ b/plugins/m2k/src/old/adc_sample_conv.hpp @@ -22,32 +22,29 @@ #define ADC_SAMPLE_CONV_HPP #include + #include namespace libm2k { namespace analog { class M2kAnalogIn; } -} +} // namespace libm2k namespace scopy { - class adc_sample_conv : public gr::sync_block - { - private: - int d_nconnections; - bool inverse; - libm2k::analog::M2kAnalogIn* m2k_adc; +class adc_sample_conv : public gr::sync_block +{ +private: + int d_nconnections; + bool inverse; + libm2k::analog::M2kAnalogIn *m2k_adc; - public: - explicit adc_sample_conv(int nconnections, - libm2k::analog::M2kAnalogIn* m2k_adc, - bool inverse = false); +public: + explicit adc_sample_conv(int nconnections, libm2k::analog::M2kAnalogIn *m2k_adc, bool inverse = false); - ~adc_sample_conv(); + ~adc_sample_conv(); - int work(int noutput_items, - gr_vector_const_void_star &input_items, - gr_vector_void_star &output_items); - double conversionWrapper(unsigned int chn_idx, double sample, bool raw_to_volts); - }; -} + int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); + double conversionWrapper(unsigned int chn_idx, double sample, bool raw_to_volts); +}; +} // namespace scopy #endif /* ADC_SAMPLE_CONV_HPP */ diff --git a/plugins/m2k/src/old/calibration.cpp b/plugins/m2k/src/old/calibration.cpp index 57b1eca50f..0b1a0ca1fc 100644 --- a/plugins/m2k/src/old/calibration.cpp +++ b/plugins/m2k/src/old/calibration.cpp @@ -19,47 +19,46 @@ */ #include "calibration.hpp" -#include -#include -#include -#include +#include "calibration_api.hpp" +#include "pluginbase/scopyjs.h" + #include -#include -#include "calibration_api.hpp" +#include #include -#include "pluginbase/scopyjs.h" +#include +#include -Q_LOGGING_CATEGORY(CAT_M2K_CALIBRATION,"M2KCalibration"); +#include +#include + +Q_LOGGING_CATEGORY(CAT_M2K_CALIBRATION, "M2KCalibration"); using namespace scopy; -Calibration::Calibration(struct iio_context *ctx): - m_api(new Calibration_API(this)), - m_cancel(false), - m_ctx(ctx), - m_initialized(false) +Calibration::Calibration(struct iio_context *ctx) + : m_api(new Calibration_API(this)) + , m_cancel(false) + , m_ctx(ctx) + , m_initialized(false) { m_api->setObjectName("calib"); ScopyJS::GetInstance()->registerApi(m_api); } -Calibration::~Calibration() -{ - delete m_api; -} +Calibration::~Calibration() { delete m_api; } bool Calibration::initialize() { m_initialized = false; - if (!m_ctx) { + if(!m_ctx) { return false; } m_m2k = libm2k::context::m2kOpen(m_ctx, ""); - if (!m_m2k) { + if(!m_m2k) { return false; } @@ -68,20 +67,13 @@ bool Calibration::initialize() return m_initialized; } -bool Calibration::isInitialized() const -{ - return m_initialized; -} - -bool Calibration::isCalibrated() -{ - return m_m2k->isCalibrated(); -} +bool Calibration::isInitialized() const { return m_initialized; } +bool Calibration::isCalibrated() { return m_m2k->isCalibrated(); } bool Calibration::resetCalibration() { - if (!m_initialized) { + if(!m_initialized) { qDebug(CAT_M2K_CALIBRATION) << "Rx path is not initialized for calibration."; return false; } @@ -93,14 +85,14 @@ bool Calibration::resetCalibration() bool Calibration::calibrateAll() { - if (!m_m2k) { + if(!m_m2k) { return false; } bool ok = false; try { ok = m_m2k->calibrateADC(); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { qDebug(CAT_M2K_CALIBRATION) << e.what(); ok = false; } @@ -109,7 +101,7 @@ bool Calibration::calibrateAll() try { ok = m_m2k->calibrateDAC(); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { qDebug(CAT_M2K_CALIBRATION) << e.what(); ok = false; } @@ -119,47 +111,30 @@ bool Calibration::calibrateAll() return true; calibration_fail: - m_cancel=false; + m_cancel = false; return false; } -bool Calibration::calibrateAdc() -{ - return m_m2k->calibrateADC(); -} +bool Calibration::calibrateAdc() { return m_m2k->calibrateADC(); } -bool Calibration::calibrateDac() -{ - return m_m2k->calibrateDAC(); -} +bool Calibration::calibrateDac() { return m_m2k->calibrateDAC(); } -void Calibration::cancelCalibration() -{ - m_cancel = true; -} +void Calibration::cancelCalibration() { m_cancel = true; } -bool Calibration::hasContextCalibration() const -{ - return m_m2k->hasContextCalibration(); -} +bool Calibration::hasContextCalibration() const { return m_m2k->hasContextCalibration(); } -float Calibration::calibrateFromContext() -{ - return m_m2k->calibrateFromContext(); -} +float Calibration::calibrateFromContext() { return m_m2k->calibrateFromContext(); } /* FIXME: TODO: Move this into a HW class / lib M2k */ -double Calibration::getIioDevTemp(const QString& devName) const +double Calibration::getIioDevTemp(const QString &devName) const { double temp = -273.15; - struct iio_device *dev = iio_context_find_device(m_ctx, - devName.toLatin1().data()); + struct iio_device *dev = iio_context_find_device(m_ctx, devName.toLatin1().data()); - if (dev) { - struct iio_channel *chn = iio_device_find_channel(dev, "temp0", - false); - if (chn) { + if(dev) { + struct iio_channel *chn = iio_device_find_channel(dev, "temp0", false); + if(chn) { double offset; double raw; double scale; diff --git a/plugins/m2k/src/old/calibration.hpp b/plugins/m2k/src/old/calibration.hpp index 9b99c0c3cd..7fe59d93d4 100644 --- a/plugins/m2k/src/old/calibration.hpp +++ b/plugins/m2k/src/old/calibration.hpp @@ -25,12 +25,13 @@ #include #include -#include -#include -#include #include +#include +#include +#include -extern "C" { +extern "C" +{ struct iio_context; struct iio_device; struct iio_channel; @@ -48,7 +49,8 @@ class Calibration friend class Calibration_API; public: - enum calibration_mode { + enum calibration_mode + { ADC_REF1, ADC_REF2, ADC_GND, @@ -56,10 +58,11 @@ class Calibration NONE }; - enum gain_mode { - LOW, - HIGH - }; + enum gain_mode + { + LOW, + HIGH + }; Calibration(struct iio_context *ctx); ~Calibration(); @@ -77,11 +80,11 @@ class Calibration bool resetCalibration(); void updateCorrections(); - double getIioDevTemp(const QString& devName) const; + double getIioDevTemp(const QString &devName) const; void cancelCalibration(); -private: +private: ApiObject *m_api; volatile bool m_cancel; @@ -90,7 +93,6 @@ class Calibration bool m_initialized; }; - } // namespace scopy #endif /* CALIBRATION_HPP */ diff --git a/plugins/m2k/src/old/calibration_api.cpp b/plugins/m2k/src/old/calibration_api.cpp index da2a1c880d..979899d64a 100644 --- a/plugins/m2k/src/old/calibration_api.cpp +++ b/plugins/m2k/src/old/calibration_api.cpp @@ -21,35 +21,19 @@ namespace scopy { -Calibration_API::Calibration_API(Calibration *calib) : ApiObject(), - calib(calib) -{ -} - -bool Calibration_API::calibrateAll() -{ - return calib->calibrateAll(); -} - -bool Calibration_API::calibrateAdc() -{ - return calib->calibrateAdc(); -} - -bool Calibration_API::calibrateDac() -{ - return calib->calibrateDac(); -} - -bool Calibration_API::resetCalibration() -{ - return calib->resetCalibration(); -} - -double Calibration_API::devTemp(const QString& devName) -{ - return calib->getIioDevTemp(devName); -} - - -} +Calibration_API::Calibration_API(Calibration *calib) + : ApiObject() + , calib(calib) +{} + +bool Calibration_API::calibrateAll() { return calib->calibrateAll(); } + +bool Calibration_API::calibrateAdc() { return calib->calibrateAdc(); } + +bool Calibration_API::calibrateDac() { return calib->calibrateDac(); } + +bool Calibration_API::resetCalibration() { return calib->resetCalibration(); } + +double Calibration_API::devTemp(const QString &devName) { return calib->getIioDevTemp(devName); } + +} // namespace scopy diff --git a/plugins/m2k/src/old/calibration_api.hpp b/plugins/m2k/src/old/calibration_api.hpp index 07ed93375c..ba1944785d 100644 --- a/plugins/m2k/src/old/calibration_api.hpp +++ b/plugins/m2k/src/old/calibration_api.hpp @@ -24,7 +24,7 @@ namespace scopy { -class Calibration_API: public ApiObject +class Calibration_API : public ApiObject { Q_OBJECT @@ -35,11 +35,11 @@ class Calibration_API: public ApiObject Q_INVOKABLE bool calibrateAdc(); Q_INVOKABLE bool calibrateDac(); - Q_INVOKABLE double devTemp(const QString& devName); + Q_INVOKABLE double devTemp(const QString &devName); private: Calibration *calib; }; -} +} // namespace scopy #endif // CALIBRATION_API_HPP diff --git a/plugins/m2k/src/old/cancel_dc_offset_block.cpp b/plugins/m2k/src/old/cancel_dc_offset_block.cpp index 5874f73a84..d5579aca80 100644 --- a/plugins/m2k/src/old/cancel_dc_offset_block.cpp +++ b/plugins/m2k/src/old/cancel_dc_offset_block.cpp @@ -19,39 +19,34 @@ */ #include "cancel_dc_offset_block.h" +#include +#include #include #include #include -#include -#include using namespace scopy::m2k; using namespace gr; -cancel_dc_offset_block::cancel_dc_offset_block(size_t buffer_size, bool enabled): - hier_block2("DCOFFSET", - io_signature::make(1, 1, sizeof(float)), - io_signature::make(1, 1, sizeof(float))), - QObject(), - d_enabled(enabled), - d_buffer_size(buffer_size), - d_dc_offset(0.0), - d_signal(std::make_shared()) +cancel_dc_offset_block::cancel_dc_offset_block(size_t buffer_size, bool enabled) + : hier_block2("DCOFFSET", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(float))) + , QObject() + , d_enabled(enabled) + , d_buffer_size(buffer_size) + , d_dc_offset(0.0) + , d_signal(std::make_shared()) { _build_and_connect_blocks(); - QObject::connect(&*d_signal, &signal_sample::triggered, [=](std::vector samples){ - d_dc_offset = samples[0]; - }); + QObject::connect(&*d_signal, &signal_sample::triggered, + [=](std::vector samples) { d_dc_offset = samples[0]; }); } -cancel_dc_offset_block::~cancel_dc_offset_block() -{ -} +cancel_dc_offset_block::~cancel_dc_offset_block() {} void cancel_dc_offset_block::set_enabled(bool enabled) { - if (d_enabled != enabled) { + if(d_enabled != enabled) { d_enabled = enabled; _build_and_connect_blocks(); } @@ -59,23 +54,20 @@ void cancel_dc_offset_block::set_enabled(bool enabled) void cancel_dc_offset_block::set_buffer_size(size_t buffer_size) { - if (d_buffer_size != buffer_size) { + if(d_buffer_size != buffer_size) { d_buffer_size = buffer_size; _build_and_connect_blocks(); } } -float cancel_dc_offset_block::get_dc_offset() const -{ - return d_dc_offset; -} +float cancel_dc_offset_block::get_dc_offset() const { return d_dc_offset; } void cancel_dc_offset_block::_build_and_connect_blocks() { // Remove all connections hier_block2::disconnect_all(); - if (d_enabled) { + if(d_enabled) { if(d_buffer_size == 0) d_buffer_size = 1; auto avg = gr::blocks::moving_average_ff::make(d_buffer_size, 1.0 / d_buffer_size, d_buffer_size); diff --git a/plugins/m2k/src/old/cancel_dc_offset_block.h b/plugins/m2k/src/old/cancel_dc_offset_block.h index d00543a228..c3412cecad 100644 --- a/plugins/m2k/src/old/cancel_dc_offset_block.h +++ b/plugins/m2k/src/old/cancel_dc_offset_block.h @@ -20,32 +20,31 @@ #ifndef CANCEL_DC_OFFSET_BLOCK_H #define CANCEL_DC_OFFSET_BLOCK_H -#include - #include "signal_sample.hpp" +#include + namespace scopy::m2k { class cancel_dc_offset_block : public gr::hier_block2, public QObject { public: - cancel_dc_offset_block(size_t buffer_size, bool enabled); - ~cancel_dc_offset_block(); + cancel_dc_offset_block(size_t buffer_size, bool enabled); + ~cancel_dc_offset_block(); - void set_enabled(bool enabled); + void set_enabled(bool enabled); void set_buffer_size(size_t buffer_size); float get_dc_offset() const; private: - bool d_enabled; - size_t d_buffer_size; + bool d_enabled; + size_t d_buffer_size; float d_dc_offset; std::shared_ptr d_signal; - void _build_and_connect_blocks(); - + void _build_and_connect_blocks(); }; -} +} // namespace scopy::m2k #endif // CANCEL_DC_OFFSET_BLOCK_H diff --git a/plugins/m2k/src/old/detachdragzone.cpp b/plugins/m2k/src/old/detachdragzone.cpp index ad9dcf07ca..5f4326d37f 100644 --- a/plugins/m2k/src/old/detachdragzone.cpp +++ b/plugins/m2k/src/old/detachdragzone.cpp @@ -18,37 +18,36 @@ * along with this program. If not, see . */ #include "detachdragzone.h" -#include #include "basemenuitem.h" +#include + using namespace scopy; -DetachDragZone::DetachDragZone(QWidget *parent) : - QWidget(parent) +DetachDragZone::DetachDragZone(QWidget *parent) + : QWidget(parent) { setAttribute(Qt::WA_StyledBackground, true); setAcceptDrops(true); this->installEventFilter(this); } -DetachDragZone::~DetachDragZone() -{ -} +DetachDragZone::~DetachDragZone() {} bool DetachDragZone::eventFilter(QObject *watched, QEvent *event) { - if (event->type() == QEvent::DragEnter){ + if(event->type() == QEvent::DragEnter) { QDragEnterEvent *enterEvent = static_cast(event); - if (!enterEvent->mimeData()->hasFormat(BaseMenuItem::menuItemMimeDataType)) + if(!enterEvent->mimeData()->hasFormat(BaseMenuItem::menuItemMimeDataType)) return true; - } + } return QWidget::event(event); } void DetachDragZone::dragEnterEvent(QDragEnterEvent *event) { - if (!event->source()) { + if(!event->source()) { event->ignore(); return; } @@ -57,10 +56,7 @@ void DetachDragZone::dragEnterEvent(QDragEnterEvent *event) event->accept(); } -void DetachDragZone::dragMoveEvent(QDragMoveEvent *event) -{ - event->accept(); -} +void DetachDragZone::dragMoveEvent(QDragMoveEvent *event) { event->accept(); } void DetachDragZone::dragLeaveEvent(QDragLeaveEvent *event) { @@ -70,17 +66,17 @@ void DetachDragZone::dragLeaveEvent(QDragLeaveEvent *event) void DetachDragZone::dropEvent(QDropEvent *event) { - if (event->source() == this && event->possibleActions() & Qt::MoveAction){ + if(event->source() == this && event->possibleActions() & Qt::MoveAction) { return; } - if (event->mimeData()->hasFormat(BaseMenuItem::menuItemMimeDataType)){ + if(event->mimeData()->hasFormat(BaseMenuItem::menuItemMimeDataType)) { QObject *source = event->source(); -// if (source) { -// ToolMenuItem *toolMenuItem = qobject_cast(source); -// if (toolMenuItem) { -// toolMenuItem->detach(); -// } -// } + // if (source) { + // ToolMenuItem *toolMenuItem = qobject_cast(source); + // if (toolMenuItem) { + // toolMenuItem->detach(); + // } + // } } } diff --git a/plugins/m2k/src/old/detachdragzone.h b/plugins/m2k/src/old/detachdragzone.h index 73913726ac..864c378c7d 100644 --- a/plugins/m2k/src/old/detachdragzone.h +++ b/plugins/m2k/src/old/detachdragzone.h @@ -20,12 +20,11 @@ #ifndef DETACHDRAGZONE_H #define DETACHDRAGZONE_H -#include -#include #include #include +#include #include - +#include namespace scopy { class DetachDragZone : public QWidget @@ -47,8 +46,7 @@ private Q_SLOTS: void dragMoveEvent(QDragMoveEvent *event); void dragLeaveEvent(QDragLeaveEvent *event); void dropEvent(QDropEvent *event); - }; -} +} // namespace scopy #endif // DETACHDRAGZONE_H diff --git a/plugins/m2k/src/old/digitalchannel_manager.cpp b/plugins/m2k/src/old/digitalchannel_manager.cpp index 089e7af337..4a63860402 100644 --- a/plugins/m2k/src/old/digitalchannel_manager.cpp +++ b/plugins/m2k/src/old/digitalchannel_manager.cpp @@ -17,25 +17,26 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -#include -#include -#include -#include -#include - #include + #include +#include +#include +#include #include #include #include #include +#include #include -#include #include #include -#include -#include -#include + +#include +#include +#include +#include +#include //#include "pattern_generator.hpp" @@ -48,10 +49,7 @@ constexpr int DIGITAL_NR_CHANNELS = 16; namespace scopy { -void DIOManager::init() -{ - -} +void DIOManager::init() {} DIOManager::DIOManager(struct iio_context *ctx, Filter *filt) : m_m2k_context(m2kOpen(ctx, "")) @@ -59,7 +57,7 @@ DIOManager::DIOManager(struct iio_context *ctx, Filter *filt) { outputEnabled = false; - for (int i = 0; i < DIGITAL_NR_CHANNELS; ++i) { + for(int i = 0; i < DIGITAL_NR_CHANNELS; ++i) { digital->setDirection(i, DIO_DIRECTION::DIO_INPUT); digital->setValueRaw(i, DIO_LEVEL::LOW); } @@ -67,52 +65,40 @@ DIOManager::DIOManager(struct iio_context *ctx, Filter *filt) direction = gpi = gpo = lockMask = outputEnabled = 0x00; } -DIOManager::~DIOManager() -{ - -} +DIOManager::~DIOManager() {} void DIOManager::setOutputMode(int chid, bool mode) { - digital->setOutputMode(chid, mode ? DIO_MODE::DIO_OPENDRAIN - : DIO_MODE::DIO_PUSHPULL); + digital->setOutputMode(chid, mode ? DIO_MODE::DIO_OPENDRAIN : DIO_MODE::DIO_PUSHPULL); } void DIOManager::setDeviceDirection(int chid, bool force) { - if (!isLocked(chid)) { + if(!isLocked(chid)) { const bool output = (outputEnabled & getDirection(chid)) | force; - digital->setDirection(chid, output ? DIO_DIRECTION::DIO_OUTPUT - : DIO_DIRECTION::DIO_INPUT); + digital->setDirection(chid, output ? DIO_DIRECTION::DIO_OUTPUT : DIO_DIRECTION::DIO_INPUT); } } -int DIOManager::getGpo() -{ - return gpo; -} +int DIOManager::getGpo() { return gpo; } void DIOManager::setOutRaw(int ch, bool val) { - if (val) { - gpo |= 1<setValueRaw(ch, getOutRaw(ch) ? DIO_LEVEL::HIGH - : DIO_LEVEL::LOW); + if(outputEnabled) { + digital->setValueRaw(ch, getOutRaw(ch) ? DIO_LEVEL::HIGH : DIO_LEVEL::LOW); } } @@ -120,38 +106,31 @@ int DIOManager::getGpi() { gpi = 0; - for (int i = 0; i < DIGITAL_NR_CHANNELS; ++i) { + for(int i = 0; i < DIGITAL_NR_CHANNELS; ++i) { gpi |= (getInRaw(i) << i); } return gpi; } -bool DIOManager::getInRaw(int ch) -{ - return static_cast(digital->getValueRaw(ch)); - -} +bool DIOManager::getInRaw(int ch) { return static_cast(digital->getValueRaw(ch)); } void DIOManager::setDirection(int ch, bool output) { - if (output) { - direction |= (1<> 1; } @@ -162,54 +141,45 @@ void DIOManager::lock(int mask) lockMask = mask; int i = 0; - while (mask) { - if (mask & 0x01) { + while(mask) { + if(mask & 0x01) { setDeviceDirection(i, true); } - mask= mask >> 1; + mask = mask >> 1; i++; } Q_EMIT locked(); } -bool DIOManager::isLocked(int ch) -{ - return lockMask & (1 << ch); -} +bool DIOManager::isLocked(int ch) { return lockMask & (1 << ch); } -int DIOManager::getLockMask() -{ - return lockMask; -} +int DIOManager::getLockMask() { return lockMask; } void DIOManager::unlock() { lockMask = 0; - for (auto i=0; i < DIGITAL_NR_CHANNELS; ++i) { + for(auto i = 0; i < DIGITAL_NR_CHANNELS; ++i) { setDeviceDirection(i, false); } Q_EMIT unlocked(); } -bool DIOManager::getOutputEnabled() -{ - return outputEnabled; -} +bool DIOManager::getOutputEnabled() { return outputEnabled; } void DIOManager::enableOutput(bool output) { - if (outputEnabled != output) { + if(outputEnabled != output) { outputEnabled = output; - for (auto i=0; i < DIGITAL_NR_CHANNELS; ++i) { + for(auto i = 0; i < DIGITAL_NR_CHANNELS; ++i) { setDeviceDirection(i, false); setDeviceOutRaw(i); } } } -} +} // namespace scopy diff --git a/plugins/m2k/src/old/digitalchannel_manager.hpp b/plugins/m2k/src/old/digitalchannel_manager.hpp index 3798ff78b9..7180de337d 100644 --- a/plugins/m2k/src/old/digitalchannel_manager.hpp +++ b/plugins/m2k/src/old/digitalchannel_manager.hpp @@ -20,23 +20,23 @@ #ifndef DIGITAL_CHANNEL_MANAGER_H #define DIGITAL_CHANNEL_MANAGER_H +#include "filter.hpp" -#include -#include -#include #include +#include +#include +#include #include #include -#include -#include -#include "filter.hpp" +#include +#include //#include "pg_patterns.hpp" -#include #include #include +#include using namespace libm2k::context; using namespace libm2k::digital; @@ -52,7 +52,7 @@ class DIOManager : public QObject int gpo; int gpi; bool outputEnabled; - M2k* m_m2k_context; + M2k *m_m2k_context; M2kDigital *digital; public: @@ -83,7 +83,6 @@ class DIOManager : public QObject void unlocked(); }; -} +} // namespace scopy::m2k #endif // PG_CHANNEL_MANAGER_H - diff --git a/plugins/m2k/src/old/digitalio.cpp b/plugins/m2k/src/old/digitalio.cpp index 5089b55bad..e55faaad14 100644 --- a/plugins/m2k/src/old/digitalio.cpp +++ b/plugins/m2k/src/old/digitalio.cpp @@ -18,79 +18,85 @@ * along with this program. If not, see . */ -#include -#include -#include -#include -#include +#include "digitalio.hpp" + +#include "digitalio_api.hpp" +#include "gui/dynamicWidget.h" #include + #include #include #include -#include "digitalio.hpp" -#include "gui/dynamicWidget.h" -#include "digitalio_api.hpp" +#include +#include +#include +#include +#include // Generated UI -#include "ui_digitalio.h" -#include "ui_digitalIoElement.h" -#include "ui_digitalIoChannel.h" #include "pluginbase/scopyjs.h" + +#include "ui_digitalIoChannel.h" +#include "ui_digitalIoElement.h" +#include "ui_digitalio.h" + #include -Q_LOGGING_CATEGORY(CAT_M2K_DIGITAL_IO,"M2kDigitalIo") +Q_LOGGING_CATEGORY(CAT_M2K_DIGITAL_IO, "M2kDigitalIo") using namespace std; using namespace scopy::m2k; namespace scopy { -DigitalIoGroup::DigitalIoGroup(QString label, int ch_mask,int io_mask, - DigitalIO *dio, QWidget *parent) : QWidget(parent), ch_mask(ch_mask), - io_mask(io_mask), dio(dio) +DigitalIoGroup::DigitalIoGroup(QString label, int ch_mask, int io_mask, DigitalIO *dio, QWidget *parent) + : QWidget(parent) + , ch_mask(ch_mask) + , io_mask(io_mask) + , dio(dio) { ui = new Ui::dioElement(); ui->setupUi(this); auto ch_mask_temp = ch_mask; - auto j=0; + auto j = 0; nr_of_channels = 0; - while (ch_mask_temp) { - if (ch_mask_temp&0x01) { - nr_of_channels ++; + while(ch_mask_temp) { + if(ch_mask_temp & 0x01) { + nr_of_channels++; QWidget *wid = new QWidget(this); Ui::dioChannel *dioUi = new Ui::dioChannel; dioUi->setupUi(wid); ui->horizontalLayout_4->addWidget(wid); - wid->setProperty("dio",j); + wid->setProperty("dio", j); dioUi->label->setText(QString::number(j)); - wid->setProperty("locked",false); - chui.append(new QPair(wid,dioUi)); - connect(chui.last()->second->inout,SIGNAL(clicked()),dio,SLOT(setDirection())); - connect(chui.last()->second->output,SIGNAL(clicked()),dio,SLOT(setOutput())); + wid->setProperty("locked", false); + chui.append(new QPair(wid, dioUi)); + connect(chui.last()->second->inout, SIGNAL(clicked()), dio, SLOT(setDirection())); + connect(chui.last()->second->output, SIGNAL(clicked()), dio, SLOT(setOutput())); } - ch_mask_temp>>=1; + ch_mask_temp >>= 1; j++; } - connect(ui->inout,SIGNAL(clicked()),this,SLOT(changeDirection())); - connect(this,SIGNAL(slider(int)),dio,SLOT(setSlider(int))); + connect(ui->inout, SIGNAL(clicked()), this, SLOT(changeDirection())); + connect(this, SIGNAL(slider(int)), dio, SLOT(setSlider(int))); ui->label_2->setText(label); - auto max = (1<lineEdit->setText(QString::number(max/2)); - ui->horizontalSlider->setValue(max/2); + auto max = (1 << nr_of_channels) - 1; + ui->lineEdit->setText(QString::number(max / 2)); + ui->horizontalSlider->setValue(max / 2); ui->comboBox->setCurrentIndex(0); ui->stackedWidget->setCurrentIndex(0); } DigitalIoGroup::~DigitalIoGroup() { - for (auto it = chui.begin(); it != chui.end(); ++it) { - //delete Ui::dioChannel from pair - delete (*it)->second; - //delete the pair + for(auto it = chui.begin(); it != chui.end(); ++it) { + // delete Ui::dioChannel from pair + delete(*it)->second; + // delete the pair delete *it; } delete ui; @@ -98,8 +104,8 @@ DigitalIoGroup::~DigitalIoGroup() void DigitalIO::setDirection(int ch, int direction) { - if (!offline_mode) { - diom->setDirection(ch,direction); + if(!offline_mode) { + diom->setDirection(ch, direction); } } @@ -107,19 +113,19 @@ void DigitalIO::setDirection() { auto direction = static_cast(sender())->isChecked(); auto ch = sender()->parent()->property("dio").toInt(); - setDirection(ch,direction); + setDirection(ch, direction); } void DigitalIO::setOutput(int ch, int out) { - if (!offline_mode) { - diom->setOutRaw(ch,out); + if(!offline_mode) { + diom->setOutRaw(ch, out); } } void DigitalIO::setVisible(bool visible) { - if (visible) + if(visible) poll->start(polling_rate); else poll->stop(); @@ -132,11 +138,11 @@ void DigitalIO::setSlider(int val) auto v = groups.indexOf(grp); auto tempval = val; - for (auto i=0; i<8; i++) { + for(auto i = 0; i < 8; i++) { auto output = tempval & 1; - tempval>>=1; - setOutput(i+v*8, output); - findIndividualUi(i+v*8)->second->output->setChecked(output); + tempval >>= 1; + setOutput(i + v * 8, output); + findIndividualUi(i + v * 8)->second->output->setChecked(output); } } @@ -146,39 +152,37 @@ void DigitalIO::setOutput() auto ch = sender()->parent()->property("dio").toInt(); setOutput(ch, output); - if (diom->getDirection(ch) && diom->getOutputEnabled()) { // only if output - setDynamicProperty(findIndividualUi(ch)->second->input,"high",output); + if(diom->getDirection(ch) && diom->getOutputEnabled()) { // only if output + setDynamicProperty(findIndividualUi(ch)->second->input, "high", output); } } -DigitalIO::DigitalIO(struct iio_context *ctx, Filter *filt, ToolMenuEntry *toolMenuItem, - DIOManager *diom, QJSEngine *engine, - QWidget *parent, bool offline_mode) : - M2kTool(ctx, toolMenuItem, new DigitalIO_API(this), "Digital IO", parent), - ui(new Ui::DigitalIO), - offline_mode(offline_mode), - diom(diom) +DigitalIO::DigitalIO(struct iio_context *ctx, Filter *filt, ToolMenuEntry *toolMenuItem, DIOManager *diom, + QJSEngine *engine, QWidget *parent, bool offline_mode) + : M2kTool(ctx, toolMenuItem, new DigitalIO_API(this), "Digital IO", parent) + , ui(new Ui::DigitalIO) + , offline_mode(offline_mode) + , diom(diom) { // UI ui->setupUi(this); - groups.append(new DigitalIoGroup("DIO 0 - 7 ",0xff,0xff,this,ui->dioContainer)); + groups.append(new DigitalIoGroup("DIO 0 - 7 ", 0xff, 0xff, this, ui->dioContainer)); ui->containerLayout->addWidget(groups.last()); - groups.append(new DigitalIoGroup("DIO 8 - 15",0xff00,0xff00,this, - ui->dioContainer)); + groups.append(new DigitalIoGroup("DIO 8 - 15", 0xff00, 0xff00, this, ui->dioContainer)); ui->containerLayout->addWidget(groups.last()); connect(ui->btnRunStop, SIGNAL(toggled(bool)), this, SLOT(startStop(bool))); connect(tme, SIGNAL(runToggled(bool)), ui->btnRunStop, SLOT(setChecked(bool))); connect(ui->btnRunStop, SIGNAL(toggled(bool)), tme, SLOT(setRunning(bool))); - if (!offline_mode) { - connect(diom,SIGNAL(locked()),this,SLOT(lockUi())); - connect(diom,SIGNAL(unlocked()),this,SLOT(lockUi())); + if(!offline_mode) { + connect(diom, SIGNAL(locked()), this, SLOT(lockUi())); + connect(diom, SIGNAL(unlocked()), this, SLOT(lockUi())); } poll = new QTimer(this); - connect(poll,SIGNAL(timeout()),this,SLOT(updateUi())); + connect(poll, SIGNAL(timeout()), this, SLOT(updateUi())); api->setObjectName(Filter::tool_name(TOOL_DIGITALIO)); ScopyJS::GetInstance()->registerApi(api); @@ -186,7 +190,6 @@ DigitalIO::DigitalIO(struct iio_context *ctx, Filter *filt, ToolMenuEntry *toolM readPreferences(); ui->btnHelp->setUrl("https://wiki.analog.com/university/tools/m2k/scopy/digitalio"); - } void DigitalIO::readPreferences() @@ -201,14 +204,14 @@ DigitalIO::~DigitalIO() delete ui; } -QPair *DigitalIO::findIndividualUi(int ch) +QPair *DigitalIO::findIndividualUi(int ch) { - for (auto &&group : groups) { - auto i=0; + for(auto &&group : groups) { + auto i = 0; - for (auto wid : qAsConst(group->chui)) { - if (wid->first->property("dio")==ch) { + for(auto wid : qAsConst(group->chui)) { + if(wid->first->property("dio") == ch) { return group->chui[i]; } @@ -221,37 +224,37 @@ QPair *DigitalIO::findIndividualUi(int ch) void DigitalIO::updateUi() { - if (!offline_mode) { + if(!offline_mode) { auto gpi = diom->getGpi(); auto gpigrp1 = gpi & 0xff; auto gpigrp2 = (gpi & 0xff00) >> 8; - for (auto i=0; i<16; i++) { + for(auto i = 0; i < 16; i++) { Ui::dioChannel *chui = findIndividualUi(i)->second; - bool chk = gpi&0x01; + bool chk = gpi & 0x01; gpi >>= 1; - setDynamicProperty(chui->input,"high",chk); + setDynamicProperty(chui->input, "high", chk); - auto isLocked = diom->getLockMask() & 1<getLockMask() & 1 << i; auto isOutput = diom->getDirection(i); - if (!isLocked && isOutput && diom->getOutputEnabled()) - if (chk != diom->getOutRaw(i)) { - setDynamicProperty(chui->input,"short",true); + if(!isLocked && isOutput && diom->getOutputEnabled()) + if(chk != diom->getOutRaw(i)) { + setDynamicProperty(chui->input, "short", true); } else { - setDynamicProperty(chui->input,"short",false); + setDynamicProperty(chui->input, "short", false); } else { - setDynamicProperty(chui->input,"short",false); + setDynamicProperty(chui->input, "short", false); } } - if (groups[0]->ui->inout->isChecked()) { + if(groups[0]->ui->inout->isChecked()) { groups[0]->ui->horizontalSlider->setValue(gpigrp1); } - if (groups[1]->ui->inout->isChecked()) { + if(groups[1]->ui->inout->isChecked()) { groups[1]->ui->horizontalSlider->setValue(gpigrp2); } } @@ -259,52 +262,49 @@ void DigitalIO::updateUi() void DigitalIoGroup::changeDirection() { - qDebug(CAT_M2K_DIGITAL_IO)<<"PB"; + qDebug(CAT_M2K_DIGITAL_IO) << "PB"; auto chk = ui->inout->isChecked(); ui->lineEdit->setEnabled(!chk); ui->horizontalSlider->setEnabled(!chk); auto val = 0; - auto i=0; + auto i = 0; - for (auto ch:qAsConst(chui)) { + for(auto ch : qAsConst(chui)) { ch->second->inout->setChecked(!chk); auto channel = ch->first->property("dio").toInt(); - dio->setDirection(channel,!chk); + dio->setDirection(channel, !chk); auto bit = ch->second->output->isChecked(); val = val | (bit << i); i++; - } - if (!chk) { + if(!chk) { ui->horizontalSlider->setValue(val); } } void DigitalIoGroup::on_horizontalSlider_valueChanged(int value) { - qDebug(CAT_M2K_DIGITAL_IO)<<"horizontalSlider"; + qDebug(CAT_M2K_DIGITAL_IO) << "horizontalSlider"; - if (ui->horizontalSlider->hasTracking()) { + if(ui->horizontalSlider->hasTracking()) { ui->lineEdit->setText(QString::number(value)); - if (!ui->inout->isChecked() && ui->inout->isEnabled()) { + if(!ui->inout->isChecked() && ui->inout->isEnabled()) { auto val = ui->lineEdit->text().toInt(); Q_EMIT slider(val); - } } } void DigitalIoGroup::on_lineEdit_editingFinished() { - qDebug(CAT_M2K_DIGITAL_IO)<<"lineedit"; - auto max = (1<lineEdit->text().toInt(); - if(nr > max) - { + if(nr > max) { nr = max; } ui->horizontalSlider->setValue(nr); @@ -322,45 +322,38 @@ void DigitalIO::lockUi() bool g0Lock = false; bool g1Lock = false; - if (lockmask&0xff) { + if(lockmask & 0xff) { g0Lock = true; } groups[0]->ui->inout->setDisabled(g0Lock); groups[0]->ui->horizontalSlider->setDisabled(g0Lock); - setDynamicProperty(groups[0]->ui->stackedWidgetPage1,"locked",g0Lock); + setDynamicProperty(groups[0]->ui->stackedWidgetPage1, "locked", g0Lock); - if (lockmask&0xff00) { + if(lockmask & 0xff00) { g1Lock = true; } groups[1]->ui->inout->setDisabled(g1Lock); groups[1]->ui->horizontalSlider->setDisabled(g1Lock); - setDynamicProperty(groups[1]->ui->stackedWidgetPage1,"locked",g1Lock); + setDynamicProperty(groups[1]->ui->stackedWidgetPage1, "locked", g1Lock); - for (auto i=0; i<16; i++) { + for(auto i = 0; i < 16; i++) { auto wid = findIndividualUi(i)->first; - bool locked = static_cast(lockmask&0x01); + bool locked = static_cast(lockmask & 0x01); - setDynamicProperty(wid,"locked",locked); + setDynamicProperty(wid, "locked", locked); wid->setDisabled(locked); - lockmask>>=1; + lockmask >>= 1; } - } -void DigitalIO::run() -{ - startStop(true); -} -void DigitalIO::stop() -{ - startStop(false); -} +void DigitalIO::run() { startStop(true); } +void DigitalIO::stop() { startStop(false); } void DigitalIO::startStop(bool checked) { - if (checked) { + if(checked) { ui->btnRunStop->setText(tr("Stop")); diom->enableOutput(true); } else { @@ -368,5 +361,4 @@ void DigitalIO::startStop(bool checked) diom->enableOutput(false); } } -} - +} // namespace scopy diff --git a/plugins/m2k/src/old/digitalio.hpp b/plugins/m2k/src/old/digitalio.hpp index 2db2189474..590b564505 100644 --- a/plugins/m2k/src/old/digitalio.hpp +++ b/plugins/m2k/src/old/digitalio.hpp @@ -21,22 +21,23 @@ #ifndef DIGITAL_IO_H #define DIGITAL_IO_H -#include -#include -#include -#include -#include +#include "digitalchannel_manager.hpp" +#include "filter.hpp" +#include "m2ktool.hpp" +#include "pluginbase/apiobject.h" + #include #include +#include #include -#include "filter.hpp" -#include "digitalchannel_manager.hpp" - -#include "pluginbase/apiobject.h" -#include "m2ktool.hpp" +#include +#include +#include +#include -extern "C" { +extern "C" +{ struct iio_context; struct iio_device; struct iio_channel; @@ -49,7 +50,7 @@ class DigitalIoMenu; class dioElement; class dioGroup; class dioChannel; -} +} // namespace Ui namespace scopy::m2k { class DigitalIO; @@ -64,12 +65,12 @@ class DigitalIoGroup : public QWidget int ch_mask; int io_mask; DigitalIO *dio; + public: - DigitalIoGroup(QString label, int ch_mask, int io_mask, DigitalIO *dio, - QWidget *parent=0); + DigitalIoGroup(QString label, int ch_mask, int io_mask, DigitalIO *dio, QWidget *parent = 0); ~DigitalIoGroup(); Ui::dioElement *ui; - QList*> chui; + QList *> chui; Q_SIGNALS: void slider(int val); @@ -97,15 +98,14 @@ class DigitalIO : public M2kTool DIOManager *diom; int polling_rate = 500; // ms - QPair *findIndividualUi(int ch); + QPair *findIndividualUi(int ch); private Q_SLOTS: void readPreferences() override; public: - explicit DigitalIO(struct iio_context *ctx, Filter *filt, ToolMenuEntry *toolMenuItem, - DIOManager *diom, QJSEngine *engine, - QWidget *parent, bool offline_mode = 0); + explicit DigitalIO(struct iio_context *ctx, Filter *filt, ToolMenuEntry *toolMenuItem, DIOManager *diom, + QJSEngine *engine, QWidget *parent, bool offline_mode = 0); ~DigitalIO(); void setDirection(int ch, int direction); void setOutput(int ch, int out); @@ -123,7 +123,6 @@ public Q_SLOTS: Q_SIGNALS: void showTool(); }; -} /* namespace scopy */ +} // namespace scopy::m2k #endif // DIGITAL_IO_H - diff --git a/plugins/m2k/src/old/digitalio_api.cpp b/plugins/m2k/src/old/digitalio_api.cpp index e017b05ea6..6c23778998 100644 --- a/plugins/m2k/src/old/digitalio_api.cpp +++ b/plugins/m2k/src/old/digitalio_api.cpp @@ -18,22 +18,20 @@ * along with this program. If not, see . */ #include "digitalio_api.hpp" + #include "ui_digitalIoChannel.h" -#include "ui_digitalio.h" #include "ui_digitalIoElement.h" +#include "ui_digitalio.h" namespace scopy::m2k { -void DigitalIO_API::show() -{ - Q_EMIT dio->showTool(); -} +void DigitalIO_API::show() { Q_EMIT dio->showTool(); } QList DigitalIO_API::direction() const { QList list; unsigned int i; - for (i = 0; i < 16; i++) { + for(i = 0; i < 16; i++) { auto ch = dio->findIndividualUi(i); list.append(ch->second->inout->isChecked()); } @@ -41,24 +39,23 @@ QList DigitalIO_API::direction() const return list; } -void DigitalIO_API::setDirection(const QList& list) +void DigitalIO_API::setDirection(const QList &list) { unsigned int i; - for (i=0; i<16; i++) { + for(i = 0; i < 16; i++) { auto ch = dio->findIndividualUi(i); ch->second->inout->setChecked(list.at(i)); - dio->setDirection(i,list.at(i)); + dio->setDirection(i, list.at(i)); } } - QList DigitalIO_API::output() const { QList list; unsigned int i; - for (i = 0; i < 16; i++) { + for(i = 0; i < 16; i++) { auto ch = dio->findIndividualUi(i); list.append(ch->second->output->isChecked()); } @@ -70,31 +67,25 @@ QList DigitalIO_API::gpi() const { QList list; unsigned int i; - for (i = 0; i < 16; i++) { + for(i = 0; i < 16; i++) { auto GPI = dio->diom->getGpi() & (1 << i); list.append(GPI); } return list; } -bool DigitalIO_API::running() const -{ - return dio->ui->btnRunStop->isChecked(); -} +bool DigitalIO_API::running() const { return dio->ui->btnRunStop->isChecked(); } -void DigitalIO_API::run(bool en) -{ - dio->ui->btnRunStop->setChecked(en); -} +void DigitalIO_API::run(bool en) { dio->ui->btnRunStop->setChecked(en); } -void DigitalIO_API::setOutput(const QList& list) +void DigitalIO_API::setOutput(const QList &list) { unsigned int i; - for (i=0; i<16; i++) { + for(i = 0; i < 16; i++) { auto ch = dio->findIndividualUi(i); ch->second->output->setChecked(list.at(i)); - dio->setOutput(i,list.at(i)); + dio->setOutput(i, list.at(i)); } } @@ -102,7 +93,7 @@ QList DigitalIO_API::grouped() const { QList list; - for (int i = 0; i < dio->groups.size(); ++i) { + for(int i = 0; i < dio->groups.size(); ++i) { bool grouped = dio->groups[i]->ui->stackedWidget->currentIndex() == 1; list.push_back(grouped); } @@ -111,32 +102,25 @@ QList DigitalIO_API::grouped() const void DigitalIO_API::setGrouped(const QList &grouped) { - for (int i = 0; i < grouped.size(); ++i) { + for(int i = 0; i < grouped.size(); ++i) { int index = grouped[i] ? 1 : 0; dio->groups[i]->ui->stackedWidget->setCurrentIndex(index); dio->groups[i]->ui->comboBox->setCurrentIndex(index); dio->groups[i]->changeDirection(); } - } QList DigitalIO_API::locked() const { QList list; unsigned int i; - for (i = 0; i < 16; i++) { + for(i = 0; i < 16; i++) { auto GPI = dio->diom->isLocked(i); list.append(GPI); } return list; } -QString DigitalIO_API::getNotes() -{ - return dio->ui->instrumentNotes->getNotes(); -} -void DigitalIO_API::setNotes(QString str) -{ - dio->ui->instrumentNotes->setNotes(str); -} -} +QString DigitalIO_API::getNotes() { return dio->ui->instrumentNotes->getNotes(); } +void DigitalIO_API::setNotes(QString str) { dio->ui->instrumentNotes->setNotes(str); } +} // namespace scopy::m2k diff --git a/plugins/m2k/src/old/digitalio_api.hpp b/plugins/m2k/src/old/digitalio_api.hpp index 146b0b9132..be8a3edc45 100644 --- a/plugins/m2k/src/old/digitalio_api.hpp +++ b/plugins/m2k/src/old/digitalio_api.hpp @@ -29,7 +29,7 @@ class DigitalIO_API : public ApiObject Q_PROPERTY(QList group READ grouped WRITE setGrouped SCRIPTABLE false); Q_PROPERTY(QList dir READ direction WRITE setDirection SCRIPTABLE true); - Q_PROPERTY(QList out READ output WRITE setOutput SCRIPTABLE true); + Q_PROPERTY(QList out READ output WRITE setOutput SCRIPTABLE true); Q_PROPERTY(QList gpi READ gpi STORED false); Q_PROPERTY(QList locked READ locked STORED false); @@ -37,16 +37,19 @@ class DigitalIO_API : public ApiObject Q_PROPERTY(QString notes READ getNotes WRITE setNotes); public: - explicit DigitalIO_API(DigitalIO *dio) : ApiObject(), dio(dio) {} + explicit DigitalIO_API(DigitalIO *dio) + : ApiObject() + , dio(dio) + {} ~DigitalIO_API() {} QList direction() const; - void setDirection(const QList& list); + void setDirection(const QList &list); QList output() const; - void setOutput(const QList& list); + void setOutput(const QList &list); void setOutput(int ch, int direction); QList grouped() const; - void setGrouped(const QList& grouped); + void setGrouped(const QList &grouped); QList gpi() const; QList locked() const; @@ -61,6 +64,6 @@ class DigitalIO_API : public ApiObject private: DigitalIO *dio; }; -} +} // namespace scopy::m2k #endif // DIGITALIO_API_HPP diff --git a/plugins/m2k/src/old/dmm.cpp b/plugins/m2k/src/old/dmm.cpp index b7a5ab0194..62f5a5ff5a 100644 --- a/plugins/m2k/src/old/dmm.cpp +++ b/plugins/m2k/src/old/dmm.cpp @@ -19,24 +19,25 @@ */ #include "dmm.hpp" + #include "gui/dynamicWidget.h" -#include "ui_dmm.h" #include "utils.h" +#include "ui_dmm.h" + +#include #include +#include +#include #include #include #include -#include #include -#include -#include -#include -#include #include +#include #include +#include -#include #include #include #include @@ -44,37 +45,41 @@ #include #include +#include + /* libm2k includes */ +#include "dmm_api.hpp" + +#include + +#include #include #include -#include -#include "dmm_api.hpp" #include #include -#include -Q_LOGGING_CATEGORY(CAT_VOLTMETER,"M2kDMM"); +Q_LOGGING_CATEGORY(CAT_VOLTMETER, "M2kDMM"); using namespace scopy::m2k; using namespace libm2k; using namespace libm2k::context; -DMM::DMM(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, m2k_iio_manager* m2k_man, - QWidget *parent) - : M2kTool(ctx, tme, new DMM_API(this), "Voltmeter", parent), - ui(new Ui::DMM), signal(std::make_shared()), - manager(m2k_man->get_instance(ctx, filt->device_name(TOOL_DMM))), - m_m2k_context(m2kOpen(ctx, "")), - m_m2k_analogin(m_m2k_context->getAnalogIn()), - m_adc_nb_channels(m_m2k_analogin->getNbChannels()), - interrupt_data_logging(false), - data_logging(false), - filename(""), - use_timer(false), - logging_refresh_rate(0), - wheelEventGuard(nullptr), - m_autoGainEnabled({true, true}), - m_gainHistorySize(25) +DMM::DMM(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, m2k_iio_manager *m2k_man, QWidget *parent) + : M2kTool(ctx, tme, new DMM_API(this), "Voltmeter", parent) + , ui(new Ui::DMM) + , signal(std::make_shared()) + , manager(m2k_man->get_instance(ctx, filt->device_name(TOOL_DMM))) + , m_m2k_context(m2kOpen(ctx, "")) + , m_m2k_analogin(m_m2k_context->getAnalogIn()) + , m_adc_nb_channels(m_m2k_analogin->getNbChannels()) + , interrupt_data_logging(false) + , data_logging(false) + , filename("") + , use_timer(false) + , logging_refresh_rate(0) + , wheelEventGuard(nullptr) + , m_autoGainEnabled({true, true}) + , m_gainHistorySize(25) { ui->setupUi(this); @@ -97,8 +102,8 @@ DMM::DMM(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, m2k_iio_mana ui->sismograph_ch1->setUnitOfMeasure("Voltage", "V"); ui->sismograph_ch2->setUnitOfMeasure("Voltage", "V"); - std::vector scales {ui->scaleCh1, ui->scaleCh2}; - for (auto scale : scales) { + std::vector scales{ui->scaleCh1, ui->scaleCh2}; + for(auto scale : scales) { scale->setOrientation(Qt::Horizontal); scale->setScalePosition(QwtThermo::LeadingScale); scale->setOriginMode(QwtThermo::OriginCustom); @@ -108,35 +113,24 @@ DMM::DMM(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, m2k_iio_mana scale->addScale(-25.0, 25.0, 10, 5); } - data_logging_timer = new PositionSpinButton({ - {"s", 1}, - {"min", 60}, - {"h", 3600} - }, tr("Timer"), 0, 3600, - true, false, this); + data_logging_timer = + new PositionSpinButton({{"s", 1}, {"min", 60}, {"h", 3600}}, tr("Timer"), 0, 3600, true, false, this); ui->horizontalLayout_2->addWidget(data_logging_timer); - for (unsigned int i = 0; i < m_adc_nb_channels; i++) - { + for(unsigned int i = 0; i < m_adc_nb_channels; i++) { m_min.push_back(Q_INFINITY); m_max.push_back(-Q_INFINITY); } - connect(ui->run_button, SIGNAL(toggled(bool)), - this, SLOT(toggleTimer(bool))); - connect(ui->run_button, SIGNAL(toggled(bool)), - tme, SLOT(setRunning(bool))); - connect(tme, SIGNAL(runToggled(bool)), ui->run_button, - SLOT(setChecked(bool))); - connect(ui->run_button, SIGNAL(toggled(bool)), - this, SLOT(startDataLogging(bool))); + connect(ui->run_button, SIGNAL(toggled(bool)), this, SLOT(toggleTimer(bool))); + connect(ui->run_button, SIGNAL(toggled(bool)), tme, SLOT(setRunning(bool))); + connect(tme, SIGNAL(runToggled(bool)), ui->run_button, SLOT(setChecked(bool))); + connect(ui->run_button, SIGNAL(toggled(bool)), this, SLOT(startDataLogging(bool))); - connect(ui->btnDataLogging, SIGNAL(toggled(bool)), - this, SLOT(toggleDataLogging(bool))); + connect(ui->btnDataLogging, SIGNAL(toggled(bool)), this, SLOT(toggleDataLogging(bool))); - connect(ui->btnChooseFile, SIGNAL(clicked()), - this, SLOT(chooseFile())); + connect(ui->btnChooseFile, SIGNAL(clicked()), this, SLOT(chooseFile())); connect(ui->btn_overwrite, &QRadioButton::toggled, [&](bool en) { if(!ui->run_button->isChecked()) { @@ -153,7 +147,8 @@ DMM::DMM(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, m2k_iio_mana connect(data_logging_timer, &PositionSpinButton::valueChanged, [&](double value) { if(value == 0) use_timer = false; - else use_timer = true; + else + use_timer = true; logging_refresh_rate = value * 1000; }); @@ -163,37 +158,24 @@ DMM::DMM(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, m2k_iio_mana connect(ui->btn_ch1_ac, SIGNAL(toggled(bool)), this, SLOT(toggleAC())); connect(ui->btn_ch2_ac, SIGNAL(toggled(bool)), this, SLOT(toggleAC())); - connect(ui->btn_ch1_dc, &QPushButton::toggled, [&](bool en) { - setDynamicProperty(ui->labelCh1, "ac", !en); - }); - connect(ui->btn_ch2_dc, &QPushButton::toggled, [&](bool en) { - setDynamicProperty(ui->labelCh2, "ac", !en); - }); + connect(ui->btn_ch1_dc, &QPushButton::toggled, [&](bool en) { setDynamicProperty(ui->labelCh1, "ac", !en); }); + connect(ui->btn_ch2_dc, &QPushButton::toggled, [&](bool en) { setDynamicProperty(ui->labelCh2, "ac", !en); }); + + connect(ui->historySizeCh1, SIGNAL(currentIndexChanged(int)), this, SLOT(setHistorySizeCh1(int))); + connect(ui->historySizeCh2, SIGNAL(currentIndexChanged(int)), this, SLOT(setHistorySizeCh2(int))); + + connect(ui->cbLineThicknessCh1, SIGNAL(currentIndexChanged(int)), this, SLOT(setLineThicknessCh1(int))); + connect(ui->cbLineThicknessCh2, SIGNAL(currentIndexChanged(int)), this, SLOT(setLineThicknessCh2(int))); - connect(ui->historySizeCh1, SIGNAL(currentIndexChanged(int)), - this, SLOT(setHistorySizeCh1(int))); - connect(ui->historySizeCh2, SIGNAL(currentIndexChanged(int)), - this, SLOT(setHistorySizeCh2(int))); - - connect(ui->cbLineThicknessCh1, SIGNAL(currentIndexChanged(int)), - this, SLOT(setLineThicknessCh1(int))); - connect(ui->cbLineThicknessCh2, SIGNAL(currentIndexChanged(int)), - this, SLOT(setLineThicknessCh2(int))); - - connect(ui->btnResetPeakHold, SIGNAL(clicked(bool)), - SLOT(resetPeakHold(bool))); - connect(ui->btnDisplayPeakHold, SIGNAL(toggled(bool)), - SLOT(displayPeakHold(bool))); - connect(ui->btnCollapseDataLog, SIGNAL(toggled(bool)), - SLOT(collapseDataLog(bool))); - connect(ui->btnCollapsePeakHold, SIGNAL(toggled(bool)), - SLOT(collapsePeakHold(bool))); - - std::vector comboBoxes {ui->gainCh1ComboBox, ui->gainCh2ComboBox}; - - for (auto cb : comboBoxes) { - connect(cb, QOverload::of(&QComboBox::currentIndexChanged), - this, &DMM::gainModeChanged); + connect(ui->btnResetPeakHold, SIGNAL(clicked(bool)), SLOT(resetPeakHold(bool))); + connect(ui->btnDisplayPeakHold, SIGNAL(toggled(bool)), SLOT(displayPeakHold(bool))); + connect(ui->btnCollapseDataLog, SIGNAL(toggled(bool)), SLOT(collapseDataLog(bool))); + connect(ui->btnCollapsePeakHold, SIGNAL(toggled(bool)), SLOT(collapsePeakHold(bool))); + + std::vector comboBoxes{ui->gainCh1ComboBox, ui->gainCh2ComboBox}; + + for(auto cb : comboBoxes) { + connect(cb, QOverload::of(&QComboBox::currentIndexChanged), this, &DMM::gainModeChanged); cb->setCurrentIndex(0); } @@ -201,19 +183,18 @@ DMM::DMM(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, m2k_iio_mana setHistorySizeCh2(ui->historySizeCh2->currentIndex()); setLineThicknessCh1(ui->cbLineThicknessCh1->currentIndex()); - setLineThicknessCh2(ui->cbLineThicknessCh2->currentIndex()); + setLineThicknessCh2(ui->cbLineThicknessCh2->currentIndex()); /* Lock the flowgraph if we are already started */ bool started = isIioManagerStarted(); - if (started) + if(started) manager->lock(); configureModes(); - connect(&*signal, SIGNAL(triggered(std::vector)), - this, SLOT(updateValuesList(std::vector))); + connect(&*signal, SIGNAL(triggered(std::vector)), this, SLOT(updateValuesList(std::vector))); - if (started) + if(started) manager->unlock(); api->setObjectName(Filter::tool_name(TOOL_DMM)); @@ -222,20 +203,16 @@ DMM::DMM(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, m2k_iio_mana if(!wheelEventGuard) wheelEventGuard = new MouseWheelWidgetGuard(ui->widget_2); wheelEventGuard->installEventRecursively(ui->widget_2); - readPreferences(); + readPreferences(); ui->btnHelp->setUrl("https://wiki.analog.com/university/tools/m2k/scopy/voltmeter"); - for(unsigned int i=0;i < m_adc_nb_channels;i++) - { + for(unsigned int i = 0; i < m_adc_nb_channels; i++) { m_gainHistory.push_back(std::deque(m_gainHistorySize)); } } -QPushButton *DMM::getRunButton() -{ - return ui->run_button; -} +QPushButton *DMM::getRunButton() { return ui->run_button; } void DMM::readPreferences() { @@ -248,14 +225,14 @@ void DMM::gainModeChanged(int idx) const QObject *who = QObject::sender(); const int channelIdx = who == ui->gainCh1ComboBox ? 0 : (who == ui->gainCh2ComboBox ? 1 : -1); - if (channelIdx == -1 || !who) { + if(channelIdx == -1 || !who) { return; } QLabel *gainLabel = channelIdx == 0 ? ui->currentGainCh1Label : ui->currentGainCh2Label; const bool started = isIioManagerStarted(); - if (started) { + if(started) { manager->lock(); } @@ -270,19 +247,19 @@ void DMM::gainModeChanged(int idx) configureModes(); m_autoGainEnabled[channelIdx] = false; - if (idx == 0) { // auto + if(idx == 0) { // auto m_autoGainEnabled[channelIdx] = true; - } else if (idx == 1) { // low + } else if(idx == 1) { // low gainLabel->setText("±25V"); m_m2k_analogin->setRange(static_cast(channelIdx), libm2k::analog::PLUS_MINUS_25V); - } else if (idx == 2) { // high + } else if(idx == 2) { // high gainLabel->setText("±2.5V"); m_m2k_analogin->setRange(static_cast(channelIdx), libm2k::analog::PLUS_MINUS_2_5V); } - if (started) { + if(started) { manager->start(id_ch1); manager->start(id_ch2); manager->unlock(); @@ -292,13 +269,13 @@ void DMM::gainModeChanged(int idx) void DMM::disconnectAll() { bool started = isIioManagerStarted(); - if (started) + if(started) manager->lock(); manager->disconnect(id_ch1); manager->disconnect(id_ch2); - if (started) + if(started) manager->unlock(); } @@ -331,9 +308,9 @@ void DMM::updateValuesList(std::vector values) checkPeakValues(1, volts_ch2); checkAndUpdateGainMode({m_m2k_analogin->convertRawToVolts(0, static_cast(values[2])), - m_m2k_analogin->convertRawToVolts(0, static_cast(values[3])), - m_m2k_analogin->convertRawToVolts(1, static_cast(values[4])), - m_m2k_analogin->convertRawToVolts(1, static_cast(values[5]))}); + m_m2k_analogin->convertRawToVolts(0, static_cast(values[3])), + m_m2k_analogin->convertRawToVolts(1, static_cast(values[4])), + m_m2k_analogin->convertRawToVolts(1, static_cast(values[5]))}); if(!use_timer) data_cond.notify_all(); @@ -341,24 +318,23 @@ void DMM::updateValuesList(std::vector values) void DMM::checkPeakValues(int ch, double peak) { - if(peak < m_min[ch]) - { + if(peak < m_min[ch]) { m_min[ch] = peak; - if(ch == 0) ui->minCh1->display(m_min[ch]); - if(ch == 1) ui->minCh2->display(m_min[ch]); + if(ch == 0) + ui->minCh1->display(m_min[ch]); + if(ch == 1) + ui->minCh2->display(m_min[ch]); } - if(peak > m_max[ch]) - { + if(peak > m_max[ch]) { m_max[ch] = peak; - if(ch == 0) ui->maxCh1->display(m_max[ch]); - if(ch == 1) ui->maxCh2->display(m_max[ch]); + if(ch == 0) + ui->maxCh1->display(m_max[ch]); + if(ch == 1) + ui->maxCh2->display(m_max[ch]); } } -bool DMM::isIioManagerStarted() const -{ - return manager->started() && ui->run_button->isChecked(); -} +bool DMM::isIioManagerStarted() const { return manager->started() && ui->run_button->isChecked(); } libm2k::analog::M2K_RANGE DMM::suggestRange(double volt_max, double volt_min) { @@ -369,16 +345,16 @@ libm2k::analog::M2K_RANGE DMM::suggestRange(double volt_max, double volt_min) libm2k::analog::M2K_RANGE gain = libm2k::analog::PLUS_MINUS_25V; - if (volt_max > 0.0) { - if (volt_max >= hi) { + if(volt_max > 0.0) { + if(volt_max >= hi) { gain = libm2k::analog::PLUS_MINUS_25V; } else { gain = libm2k::analog::PLUS_MINUS_2_5V; } } - if (volt_min <= 0.0) { - if (volt_min >= lo ) { + if(volt_min <= 0.0) { + if(volt_min >= lo) { gain = libm2k::analog::PLUS_MINUS_2_5V; } else { gain = libm2k::analog::PLUS_MINUS_25V; @@ -390,48 +366,43 @@ libm2k::analog::M2K_RANGE DMM::suggestRange(double volt_max, double volt_min) void DMM::checkAndUpdateGainMode(const std::vector &volts) { - if (volts.size() < m_adc_nb_channels * 2) { + if(volts.size() < m_adc_nb_channels * 2) { return; } - std::vector gainLabels {ui->currentGainCh1Label, ui->currentGainCh2Label}; - std::vector errorLabels {ui->ch1ErrorLabel, ui->ch2ErrorLabel}; - + std::vector gainLabels{ui->currentGainCh1Label, ui->currentGainCh2Label}; + std::vector errorLabels{ui->ch1ErrorLabel, ui->ch2ErrorLabel}; libm2k::analog::M2K_RANGE gain[m_adc_nb_channels]; libm2k::analog::M2K_RANGE currentChannelGain[m_adc_nb_channels]; bool recreateFlowGraph = false; - for (unsigned int i = 0; i < m_adc_nb_channels; ++i) { - gain[i]=libm2k::analog::PLUS_MINUS_25V; + for(unsigned int i = 0; i < m_adc_nb_channels; ++i) { + gain[i] = libm2k::analog::PLUS_MINUS_25V; currentChannelGain[i] = m_m2k_analogin->getRange(static_cast(i)); - //gain[i] = currentChannelGain[i];//libm2k::analog::PLUS_MINUS_25V; + // gain[i] = currentChannelGain[i];//libm2k::analog::PLUS_MINUS_25V; // add all gains to circular buffer - auto suggested_range = suggestRange (volts[m_adc_nb_channels * i], volts[(m_adc_nb_channels * i) + 1]); + auto suggested_range = suggestRange(volts[m_adc_nb_channels * i], volts[(m_adc_nb_channels * i) + 1]); if(m_gainHistory[i].size() == m_gainHistorySize) { m_gainHistory[i].pop_front(); } m_gainHistory[i].push_back(suggested_range); - // define m2k_range sum computation operation as lambda - auto range_sum = [](double a, libm2k::analog::M2K_RANGE b) { - return (a) + static_cast(b); - }; - - + auto range_sum = [](double a, libm2k::analog::M2K_RANGE b) { return (a) + static_cast(b); }; // compute average of circular buffer - moving average - double sum = std::accumulate(m_gainHistory[i].begin(),m_gainHistory[i].end(), 0.0, range_sum); + double sum = std::accumulate(m_gainHistory[i].begin(), m_gainHistory[i].end(), 0.0, range_sum); double avg = sum / m_gainHistory[i].size(); // only change to high gain if ALL values in circular buffer == HIGH_GAIN - // this means as soon as we find a value out of HIGH range we switch immediately - but wait m_gainHistorySize to change back to HIGH + // this means as soon as we find a value out of HIGH range we switch immediately - but wait + // m_gainHistorySize to change back to HIGH if(avg == libm2k::analog::PLUS_MINUS_2_5V) { gain[i] = libm2k::analog::PLUS_MINUS_2_5V; } - if(gain[i] != currentChannelGain[i] ) { + if(gain[i] != currentChannelGain[i]) { if(m_autoGainEnabled[i]) { errorLabels[i]->setText(""); m_m2k_analogin->setRange(static_cast(i), gain[i]); @@ -439,22 +410,21 @@ void DMM::checkAndUpdateGainMode(const std::vector &volts) recreateFlowGraph = true; } else { - if(currentChannelGain[i] == libm2k::analog::PLUS_MINUS_2_5V) { // only show out of range for +/- 2.5 + if(currentChannelGain[i] == + libm2k::analog::PLUS_MINUS_2_5V) { // only show out of range for +/- 2.5 errorLabels[i]->setText("Out of range"); - } else { + } else { errorLabels[i]->setText(""); } } } else { errorLabels[i]->setText(""); } - - } if(recreateFlowGraph) { const bool started = isIioManagerStarted(); - if (started) { + if(started) { manager->lock(); } @@ -468,7 +438,7 @@ void DMM::checkAndUpdateGainMode(const std::vector &volts) configureModes(); - if (started) { + if(started) { manager->start(id_ch1); manager->start(id_ch2); manager->unlock(); @@ -476,7 +446,6 @@ void DMM::checkAndUpdateGainMode(const std::vector &volts) } } - void DMM::collapseDataLog(bool checked) { if(checked) @@ -500,8 +469,7 @@ void DMM::displayPeakHold(bool checked) Util::retainWidgetSizeWhenHidden(ui->peakCh2Widget); ui->peakCh1Widget->hide(); ui->peakCh2Widget->hide(); - } - else { + } else { ui->peakCh1Widget->show(); ui->peakCh2Widget->show(); } @@ -525,8 +493,8 @@ void DMM::resetPeakHold(bool clicked) void DMM::toggleTimer(bool start) { enableDataLogging(start); - if (start) { - ResourceManager::open("m2k-adc",this); + if(start) { + ResourceManager::open("m2k-adc", this); manager->set_kernel_buffer_count(4); writeAllSettingsToHardware(); manager->start(id_ch1); @@ -549,20 +517,17 @@ void DMM::toggleTimer(bool start) m_running = start; } - -gr::basic_block_sptr DMM::configureGraph(gr::basic_block_sptr s2f, - bool is_ac) +gr::basic_block_sptr DMM::configureGraph(gr::basic_block_sptr s2f, bool is_ac) { /* 10 fps refresh rate for the plot */ - auto keep_one = gr::blocks::keep_one_in_n::make(sizeof(float), - sample_rate / 10.0); + auto keep_one = gr::blocks::keep_one_in_n::make(sizeof(float), sample_rate / 10.0); auto blocker_val = 4000; auto blocker = gr::filter::dc_blocker_ff::make(blocker_val, true); manager->connect(s2f, 0, blocker, 0); - if (is_ac) { + if(is_ac) { /* TODO: figure out best value for the RMS parameter */ auto rms = gr::blocks::rms_ff::make(0.0001); manager->connect(blocker, 0, rms, 0); @@ -571,8 +536,8 @@ gr::basic_block_sptr DMM::configureGraph(gr::basic_block_sptr s2f, auto sub = gr::blocks::sub_ff::make(); manager->connect(s2f, 0, sub, 0); manager->connect(blocker, 0, sub, 1); - auto moving = gr::blocks::moving_average_ff::make(4000,1.0/4000); - manager->connect(sub, 0, moving,0 ); + auto moving = gr::blocks::moving_average_ff::make(4000, 1.0 / 4000); + manager->connect(sub, 0, moving, 0); manager->connect(moving, 0, keep_one, 0); } @@ -620,27 +585,26 @@ void DMM::chooseFile() { QString selectedFilter; -// filename = QFileDialog::getSaveFileName(this, -// tr("Export"), "", tr("Comma-separated values files (*.csv);;All Files(*)"), -// &selectedFilter, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); + // filename = QFileDialog::getSaveFileName(this, + // tr("Export"), "", tr("Comma-separated values files (*.csv);;All Files(*)"), + // &selectedFilter, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); -// ui->filename->setText(filename); + // ui->filename->setText(filename); -// if(!ui->run_button->isChecked()) { -// toggleDataLogging(data_logging); -// } - -// if (ui->run_button->isChecked() && data_logging) { -// toggleDataLogging(false); -// toggleDataLogging(true); -// } + // if(!ui->run_button->isChecked()) { + // toggleDataLogging(data_logging); + // } + // if (ui->run_button->isChecked() && data_logging) { + // toggleDataLogging(false); + // toggleDataLogging(true); + // } } void DMM::enableDataLogging(bool en) { ui->gridLayout_3Widget->setEnabled(en); - if (!en) { + if(!en) { setDynamicProperty(ui->filename, "invalid", false); } } @@ -648,10 +612,10 @@ void DMM::enableDataLogging(bool en) void DMM::toggleDataLogging(bool en) { data_logging = en; - if (en) { + if(en) { enableDataLogging(en); setDynamicProperty(ui->filename, "invalid", false); - } else if (!ui->run_button->isChecked()) { + } else if(!ui->run_button->isChecked()) { enableDataLogging(en); } @@ -675,7 +639,7 @@ void DMM::toggleDataLogging(bool en) QFile file(filename); if(ui->btn_overwrite->isChecked() || file.size() == 0) { - if( !file.open(QIODevice::WriteOnly)) { + if(!file.open(QIODevice::WriteOnly)) { ui->lblFileStatus->setText(tr("File is open in another program")); setDynamicProperty(ui->filename, "invalid", true); if(ui->run_button->isChecked()) { @@ -689,14 +653,13 @@ void DMM::toggleDataLogging(bool en) QTextStream out(&file); /* Write the header */ - out << ";Generated by Scopy-" << SCOPY_VERSION_GIT << "\n" << - ";Started on " << QDateTime::currentDateTime().toString() << "\n"; + out << ";Generated by Scopy-" << SCOPY_VERSION_GIT << "\n" + << ";Started on " << QDateTime::currentDateTime().toString() << "\n"; out << "Timestamp,Channel_0_DC_RMS,Channel_0_AC_RMS,Channel_1_DC_RMS,Channel_1_AC_RMS\n"; file.close(); } - } - else { + } else { ui->btn_overwrite->setEnabled(true); ui->btn_append->setEnabled(true); } @@ -708,8 +671,7 @@ void DMM::toggleDataLogging(bool en) interrupt_data_logging = false; data_logging_thread = std::thread(&DMM::dataLoggingThread, this); - } - else if(!en) { + } else if(!en) { if(!use_timer) data_cond.notify_all(); interrupt_data_logging = true; @@ -736,8 +698,7 @@ void DMM::startDataLogging(bool start) ui->btn_append->setEnabled(false); data_logging_thread = std::thread(&DMM::dataLoggingThread, this); - } - else { + } else { if(!use_timer) data_cond.notify_all(); interrupt_data_logging = true; @@ -757,8 +718,8 @@ void DMM::dataLoggingThread() QTextStream out(&file); while(!interrupt_data_logging) { - if (!file.isOpen()) { - if (!file.open(QIODevice::Append)) { + if(!file.isOpen()) { + if(!file.open(QIODevice::Append)) { ui->lblFileStatus->setText(tr("File is open in another program")); setDynamicProperty(ui->filename, "invalid", true); if(ui->run_button->isChecked()) { @@ -772,7 +733,7 @@ void DMM::dataLoggingThread() bool is_ac_ch1 = ui->btn_ch1_ac->isChecked(); bool is_ac_ch2 = ui->btn_ch2_ac->isChecked(); - QString ch1_dc_rms="-", ch2_dc_rms="-", ch1_ac_rms="-", ch2_ac_rms="-"; + QString ch1_dc_rms = "-", ch2_dc_rms = "-", ch1_ac_rms = "-", ch2_ac_rms = "-"; out << QDateTime::currentDateTime().time().toString() << separator; @@ -781,36 +742,30 @@ void DMM::dataLoggingThread() data_cond.wait(lock); } - if(!is_ac_ch1) { ch1_dc_rms = QString::number(ui->lcdCh1->value()); - } - else { + } else { ch1_ac_rms = QString::number(ui->lcdCh1->value()); } - if(!is_ac_ch2) { ch2_dc_rms = QString::number(ui->lcdCh2->value()); - } - else { + } else { ch2_ac_rms = QString::number(ui->lcdCh2->value()); } /* Write the values to file */ - out << ch1_dc_rms << separator << - ch1_ac_rms << separator << - ch2_dc_rms << separator << - ch2_ac_rms << "\n"; + out << ch1_dc_rms << separator << ch1_ac_rms << separator << ch2_dc_rms << separator << ch2_ac_rms + << "\n"; - if (file.isOpen()) { + if(file.isOpen()) { file.close(); } - if (use_timer) { + if(use_timer) { QThread::msleep(logging_refresh_rate); } } - if (file.isOpen()) { + if(file.isOpen()) { file.close(); } } @@ -818,7 +773,7 @@ void DMM::dataLoggingThread() void DMM::toggleAC() { bool started = isIioManagerStarted(); - if (started) + if(started) manager->lock(); manager->disconnect(id_ch1); @@ -826,7 +781,7 @@ void DMM::toggleAC() configureModes(); - if (started) { + if(started) { writeAllSettingsToHardware(); manager->start(id_ch1); manager->start(id_ch2); @@ -864,37 +819,37 @@ void DMM::setHistorySizeCh2(int idx) void DMM::setLineThicknessCh1(int idx) { - float thickness = 0.5 * (idx + 1); + float thickness = 0.5 * (idx + 1); - ui->cbLineThicknessCh1->setCurrentIndex(idx); - ui->sismograph_ch1->setLineWidth(thickness); - ui->sismograph_ch1->replot(); + ui->cbLineThicknessCh1->setCurrentIndex(idx); + ui->sismograph_ch1->setLineWidth(thickness); + ui->sismograph_ch1->replot(); } void DMM::setLineThicknessCh2(int idx) { - float thickness = 0.5 * (idx + 1); + float thickness = 0.5 * (idx + 1); - ui->cbLineThicknessCh2->setCurrentIndex(idx); - ui->sismograph_ch2->setLineWidth(thickness); - ui->sismograph_ch2->replot(); + ui->cbLineThicknessCh2->setCurrentIndex(idx); + ui->sismograph_ch2->setLineWidth(thickness); + ui->sismograph_ch2->replot(); } void DMM::writeAllSettingsToHardware() { - if (m_m2k_analogin) { + if(m_m2k_analogin) { try { m_m2k_analogin->setSampleRate(sample_rate); m_m2k_analogin->setOversamplingRatio(1); auto trigger = m_m2k_analogin->getTrigger(); - for (unsigned int i = 0; i < m_adc_nb_channels; i++) { + for(unsigned int i = 0; i < m_adc_nb_channels; i++) { auto chn = static_cast(i); m_m2k_analogin->setVerticalOffset(chn, 0.0); - if (trigger) { + if(trigger) { trigger->setAnalogMode(i, libm2k::ALWAYS); } } - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { qDebug(CAT_VOLTMETER) << "Can't write to hardware: " << e.what(); } } diff --git a/plugins/m2k/src/old/dmm.hpp b/plugins/m2k/src/old/dmm.hpp index d66224d23d..45226fdfc6 100644 --- a/plugins/m2k/src/old/dmm.hpp +++ b/plugins/m2k/src/old/dmm.hpp @@ -21,128 +21,128 @@ #ifndef DMM_HPP #define DMM_HPP +#include "filter.hpp" +#include "gui/mousewheelwidgetguard.h" +#include "gui/spinbox_a.hpp" +#include "iio_manager.hpp" +#include "pluginbase/toolmenuentry.h" +#include "signal_sample.hpp" + #include #include + #include #include -#include "pluginbase/toolmenuentry.h" -#include "filter.hpp" -#include "iio_manager.hpp" -#include "signal_sample.hpp" -#include "gui/mousewheelwidgetguard.h" -#include -#include "gui/spinbox_a.hpp" #include +#include /* libm2k includes */ -#include -#include #include "m2ktool.hpp" +#include +#include namespace Ui { - class DMM; +class DMM; } class QJSEngine; namespace scopy::m2k { - class DMM_API; +class DMM_API; - class DMM : public M2kTool - { - friend class DMM_API; - friend class ToolLauncher_API; +class DMM : public M2kTool +{ + friend class DMM_API; + friend class ToolLauncher_API; - Q_OBJECT + Q_OBJECT - public: - explicit DMM(struct iio_context *ctx, Filter *filt, - ToolMenuEntry *toolMenuItem, m2k_iio_manager* m2k_man, - QWidget *parent = nullptr); - QPushButton* getRunButton(); - ~DMM(); +public: + explicit DMM(struct iio_context *ctx, Filter *filt, ToolMenuEntry *toolMenuItem, m2k_iio_manager *m2k_man, + QWidget *parent = nullptr); + QPushButton *getRunButton(); + ~DMM(); - private: - libm2k::context::M2k* m_m2k_context; - libm2k::analog::M2kAnalogIn* m_m2k_analogin; - unsigned int m_adc_nb_channels; - Ui::DMM *ui; - std::shared_ptr manager; - iio_manager::port_id id_ch1, id_ch2; - std::shared_ptr signal; - unsigned long sample_rate; - bool m_running; +private: + libm2k::context::M2k *m_m2k_context; + libm2k::analog::M2kAnalogIn *m_m2k_analogin; + unsigned int m_adc_nb_channels; + Ui::DMM *ui; + std::shared_ptr manager; + iio_manager::port_id id_ch1, id_ch2; + std::shared_ptr signal; + unsigned long sample_rate; + bool m_running; - std::atomic interrupt_data_logging; - std::atomic data_logging; - QString filename; - std::thread data_logging_thread; - bool use_timer; - unsigned long logging_refresh_rate; - PositionSpinButton *data_logging_timer; + std::atomic interrupt_data_logging; + std::atomic data_logging; + QString filename; + std::thread data_logging_thread; + bool use_timer; + unsigned long logging_refresh_rate; + PositionSpinButton *data_logging_timer; - std::mutex data_mutex; - std::condition_variable data_cond; - MouseWheelWidgetGuard *wheelEventGuard; + std::mutex data_mutex; + std::condition_variable data_cond; + MouseWheelWidgetGuard *wheelEventGuard; - std::vector m_min, m_max; + std::vector m_min, m_max; - std::vector m_autoGainEnabled; - std::vector> m_gainHistory; - int m_gainHistorySize; + std::vector m_autoGainEnabled; + std::vector> m_gainHistory; + int m_gainHistorySize; - void disconnectAll(); - gr::basic_block_sptr configureGraph(gr::basic_block_sptr s2f, - bool is_ac); - void configureModes(); - libm2k::analog::M2K_RANGE suggestRange(double volt_max, double volt_min); - int numSamplesFromIdx(int idx); - void writeAllSettingsToHardware(); - void checkPeakValues(int, double); - bool isIioManagerStarted() const; - void checkAndUpdateGainMode(const std::vector &volts); + void disconnectAll(); + gr::basic_block_sptr configureGraph(gr::basic_block_sptr s2f, bool is_ac); + void configureModes(); + libm2k::analog::M2K_RANGE suggestRange(double volt_max, double volt_min); + int numSamplesFromIdx(int idx); + void writeAllSettingsToHardware(); + void checkPeakValues(int, double); + bool isIioManagerStarted() const; + void checkAndUpdateGainMode(const std::vector &volts); - public Q_SLOTS: - void toggleTimer(bool start); - void run(); - void stop(); +public Q_SLOTS: + void toggleTimer(bool start); + void run(); + void stop(); - private Q_SLOTS: - void setHistorySizeCh1(int idx); - void setHistorySizeCh2(int idx); +private Q_SLOTS: + void setHistorySizeCh1(int idx); + void setHistorySizeCh2(int idx); - void setLineThicknessCh1(int idx); - void setLineThicknessCh2(int idx); + void setLineThicknessCh1(int idx); + void setLineThicknessCh2(int idx); - void updateValuesList(std::vector values); + void updateValuesList(std::vector values); - void toggleAC(); + void toggleAC(); - void enableDataLogging(bool); + void enableDataLogging(bool); - void toggleDataLogging(bool); + void toggleDataLogging(bool); - void startDataLogging(bool); + void startDataLogging(bool); - void dataLoggingThread(); + void dataLoggingThread(); - void chooseFile(); + void chooseFile(); - void resetPeakHold(bool); + void resetPeakHold(bool); - void displayPeakHold(bool); + void displayPeakHold(bool); - void collapsePeakHold(bool); - void collapseDataLog(bool); + void collapsePeakHold(bool); + void collapseDataLog(bool); - void readPreferences(); + void readPreferences(); - void gainModeChanged(int idx); + void gainModeChanged(int idx); - Q_SIGNALS: - void showTool(); - }; -} +Q_SIGNALS: + void showTool(); +}; +} // namespace scopy::m2k #endif /* DMM_HPP */ diff --git a/plugins/m2k/src/old/dmm_api.cpp b/plugins/m2k/src/old/dmm_api.cpp index 6c48ea3d72..2af0729f99 100644 --- a/plugins/m2k/src/old/dmm_api.cpp +++ b/plugins/m2k/src/old/dmm_api.cpp @@ -18,29 +18,21 @@ * along with this program. If not, see . */ #include "dmm_api.hpp" + #include "ui_dmm.h" namespace scopy::m2k { -void DMM_API::show() -{ - Q_EMIT dmm->showTool(); -} +void DMM_API::show() { Q_EMIT dmm->showTool(); } -bool DMM_API::get_mode_ac_ch1() const -{ - return dmm->ui->btn_ch1_ac->isChecked(); -} +bool DMM_API::get_mode_ac_ch1() const { return dmm->ui->btn_ch1_ac->isChecked(); } -bool DMM_API::get_mode_ac_ch2() const -{ - return dmm->ui->btn_ch2_ac->isChecked(); -} +bool DMM_API::get_mode_ac_ch2() const { return dmm->ui->btn_ch2_ac->isChecked(); } void DMM_API::set_mode_ac_ch1(bool en) { /* Set DC mode as default */ - if (!get_mode_ac_ch1() && !en) { + if(!get_mode_ac_ch1() && !en) { dmm->ui->btn_ch1_dc->setChecked(!en); } dmm->ui->btn_ch1_ac->setChecked(en); @@ -49,130 +41,73 @@ void DMM_API::set_mode_ac_ch1(bool en) void DMM_API::set_mode_ac_ch2(bool en) { /* Set DC mode as default */ - if (!get_mode_ac_ch2() && !en) { + if(!get_mode_ac_ch2() && !en) { dmm->ui->btn_ch2_dc->setChecked(!en); } dmm->ui->btn_ch2_ac->setChecked(en); } -bool DMM_API::running() const -{ - return dmm->ui->run_button->isChecked(); -} +bool DMM_API::running() const { return dmm->ui->run_button->isChecked(); } -void DMM_API::run(bool en) -{ - dmm->ui->run_button->setChecked(en); -} +void DMM_API::run(bool en) { dmm->ui->run_button->setChecked(en); } -double DMM_API::read_ch1() const -{ - return dmm->ui->lcdCh1->value(); -} +double DMM_API::read_ch1() const { return dmm->ui->lcdCh1->value(); } -double DMM_API::read_ch2() const -{ - return dmm->ui->lcdCh2->value(); -} +double DMM_API::read_ch2() const { return dmm->ui->lcdCh2->value(); } -bool DMM_API::get_histogram_ch1() const -{ - return dmm->ui->histogramCh1->isChecked(); -} +bool DMM_API::get_histogram_ch1() const { return dmm->ui->histogramCh1->isChecked(); } -void DMM_API::set_histogram_ch1(bool en) -{ - dmm->ui->histogramCh1->setChecked(en); -} +void DMM_API::set_histogram_ch1(bool en) { dmm->ui->histogramCh1->setChecked(en); } -void DMM_API::set_histogram_ch2(bool en) -{ - dmm->ui->histogramCh2->setChecked(en); -} +void DMM_API::set_histogram_ch2(bool en) { dmm->ui->histogramCh2->setChecked(en); } -bool DMM_API::get_histogram_ch2() const -{ - return dmm->ui->histogramCh2->isChecked(); -} +bool DMM_API::get_histogram_ch2() const { return dmm->ui->histogramCh2->isChecked(); } -int DMM_API::get_history_ch1_size_idx() const -{ - return dmm->ui->historySizeCh1->currentIndex(); -} +int DMM_API::get_history_ch1_size_idx() const { return dmm->ui->historySizeCh1->currentIndex(); } -int DMM_API::get_history_ch2_size_idx() const -{ - return dmm->ui->historySizeCh2->currentIndex(); -} +int DMM_API::get_history_ch2_size_idx() const { return dmm->ui->historySizeCh2->currentIndex(); } -void DMM_API::set_history_ch1_size_idx(int index) -{ - dmm->ui->historySizeCh1->setCurrentIndex(index); -} +void DMM_API::set_history_ch1_size_idx(int index) { dmm->ui->historySizeCh1->setCurrentIndex(index); } -void DMM_API::set_history_ch2_size_idx(int index) -{ - dmm->ui->historySizeCh2->setCurrentIndex(index); -} +void DMM_API::set_history_ch2_size_idx(int index) { dmm->ui->historySizeCh2->setCurrentIndex(index); } float DMM_API::get_line_thickness_ch1() const { - int index = dmm->ui->cbLineThicknessCh1->currentIndex(); - return 0.5 * (index + 1); + int index = dmm->ui->cbLineThicknessCh1->currentIndex(); + return 0.5 * (index + 1); } float DMM_API::get_line_thickness_ch2() const { - int index = dmm->ui->cbLineThicknessCh2->currentIndex(); - return 0.5 * (index + 1); + int index = dmm->ui->cbLineThicknessCh2->currentIndex(); + return 0.5 * (index + 1); } void DMM_API::set_line_thickness_ch1(float thickness) { - int thicknessIdx = (int)(thickness / 0.5) - 1; - dmm->ui->cbLineThicknessCh1->setCurrentIndex(thicknessIdx); + int thicknessIdx = (int)(thickness / 0.5) - 1; + dmm->ui->cbLineThicknessCh1->setCurrentIndex(thicknessIdx); } void DMM_API::set_line_thickness_ch2(float thickness) { - int thicknessIdx = (int)(thickness / 0.5) - 1; - dmm->ui->cbLineThicknessCh2->setCurrentIndex(thicknessIdx); + int thicknessIdx = (int)(thickness / 0.5) - 1; + dmm->ui->cbLineThicknessCh2->setCurrentIndex(thicknessIdx); } -bool DMM_API::getDataLoggingEn() const -{ - return dmm->ui->btnDataLogging->isChecked(); -} +bool DMM_API::getDataLoggingEn() const { return dmm->ui->btnDataLogging->isChecked(); } -void DMM_API::setDataLoggingEn(bool en) -{ - dmm->ui->btnDataLogging->setChecked(en); -} +void DMM_API::setDataLoggingEn(bool en) { dmm->ui->btnDataLogging->setChecked(en); } -double DMM_API::getDataLoggingTimer() const -{ - return dmm->data_logging_timer->value(); -} +double DMM_API::getDataLoggingTimer() const { return dmm->data_logging_timer->value(); } -void DMM_API::setDataLoggingTimer(double val) -{ - dmm->data_logging_timer->setValue(val); -} +void DMM_API::setDataLoggingTimer(double val) { dmm->data_logging_timer->setValue(val); } -bool DMM_API::getPeakHoldEn() const -{ - return dmm->ui->btnDisplayPeakHold->isChecked(); -} +bool DMM_API::getPeakHoldEn() const { return dmm->ui->btnDisplayPeakHold->isChecked(); } -void DMM_API::setPeakHoldEn(bool val) -{ - dmm->ui->btnDisplayPeakHold->setChecked(val); -} +void DMM_API::setPeakHoldEn(bool val) { dmm->ui->btnDisplayPeakHold->setChecked(val); } -bool DMM_API::getDataLoggingAppend() const -{ - return dmm->ui->btn_append->isChecked(); -} +bool DMM_API::getDataLoggingAppend() const { return dmm->ui->btn_append->isChecked(); } void DMM_API::setDataLoggingAppend(bool val) { @@ -180,24 +115,17 @@ void DMM_API::setDataLoggingAppend(bool val) dmm->ui->btn_overwrite->setChecked(!val); } -QString DMM_API::getNotes() -{ - return dmm->ui->instrumentNotes->getNotes(); -} -void DMM_API::setNotes(QString str) -{ - dmm->ui->instrumentNotes->setNotes(str); -} +QString DMM_API::getNotes() { return dmm->ui->instrumentNotes->getNotes(); } +void DMM_API::setNotes(QString str) { dmm->ui->instrumentNotes->setNotes(str); } QVector DMM_API::getGainModes() const { - return {dmm->ui->gainCh1ComboBox->currentIndex(), - dmm->ui->gainCh2ComboBox->currentIndex()}; + return {dmm->ui->gainCh1ComboBox->currentIndex(), dmm->ui->gainCh2ComboBox->currentIndex()}; } void DMM_API::setGainModes(const QVector &gainModes) { - if (gainModes.size() < dmm->m_adc_nb_channels) { + if(gainModes.size() < dmm->m_adc_nb_channels) { return; } @@ -205,4 +133,4 @@ void DMM_API::setGainModes(const QVector &gainModes) dmm->ui->gainCh2ComboBox->setCurrentIndex(gainModes[1]); } -} +} // namespace scopy::m2k diff --git a/plugins/m2k/src/old/dmm_api.hpp b/plugins/m2k/src/old/dmm_api.hpp index 255a6f6d23..9667b3d92e 100644 --- a/plugins/m2k/src/old/dmm_api.hpp +++ b/plugins/m2k/src/old/dmm_api.hpp @@ -30,44 +30,26 @@ class DMM_API : public ApiObject Q_OBJECT - Q_PROPERTY(bool mode_ac_ch1 - READ get_mode_ac_ch1 WRITE set_mode_ac_ch1); - Q_PROPERTY(bool mode_ac_ch2 - READ get_mode_ac_ch2 WRITE set_mode_ac_ch1); + Q_PROPERTY(bool mode_ac_ch1 READ get_mode_ac_ch1 WRITE set_mode_ac_ch1); + Q_PROPERTY(bool mode_ac_ch2 READ get_mode_ac_ch2 WRITE set_mode_ac_ch1); Q_PROPERTY(bool running READ running WRITE run STORED false); - Q_PROPERTY(bool histogram_ch1 - READ get_histogram_ch1 - WRITE set_histogram_ch1); - Q_PROPERTY(bool histogram_ch2 - READ get_histogram_ch2 - WRITE set_histogram_ch2); - - Q_PROPERTY(int history_ch1_size_idx - READ get_history_ch1_size_idx - WRITE set_history_ch1_size_idx); - Q_PROPERTY(int history_ch2_size_idx - READ get_history_ch2_size_idx - WRITE set_history_ch2_size_idx); - - Q_PROPERTY(float line_thickness_ch1 - READ get_line_thickness_ch1 - WRITE set_line_thickness_ch1); - Q_PROPERTY(float line_thickness_ch2 - READ get_line_thickness_ch2 - WRITE set_line_thickness_ch2); + Q_PROPERTY(bool histogram_ch1 READ get_histogram_ch1 WRITE set_histogram_ch1); + Q_PROPERTY(bool histogram_ch2 READ get_histogram_ch2 WRITE set_histogram_ch2); + + Q_PROPERTY(int history_ch1_size_idx READ get_history_ch1_size_idx WRITE set_history_ch1_size_idx); + Q_PROPERTY(int history_ch2_size_idx READ get_history_ch2_size_idx WRITE set_history_ch2_size_idx); + + Q_PROPERTY(float line_thickness_ch1 READ get_line_thickness_ch1 WRITE set_line_thickness_ch1); + Q_PROPERTY(float line_thickness_ch2 READ get_line_thickness_ch2 WRITE set_line_thickness_ch2); Q_PROPERTY(double value_ch1 READ read_ch1); Q_PROPERTY(double value_ch2 READ read_ch2); - Q_PROPERTY(bool data_logging_en READ getDataLoggingEn - WRITE setDataLoggingEn) - Q_PROPERTY(double data_logging_timer READ getDataLoggingTimer - WRITE setDataLoggingTimer) - Q_PROPERTY(bool data_logging_append READ getDataLoggingAppend - WRITE setDataLoggingAppend) - Q_PROPERTY(bool peak_hold_en READ getPeakHoldEn - WRITE setPeakHoldEn) + Q_PROPERTY(bool data_logging_en READ getDataLoggingEn WRITE setDataLoggingEn) + Q_PROPERTY(double data_logging_timer READ getDataLoggingTimer WRITE setDataLoggingTimer) + Q_PROPERTY(bool data_logging_append READ getDataLoggingAppend WRITE setDataLoggingAppend) + Q_PROPERTY(bool peak_hold_en READ getPeakHoldEn WRITE setPeakHoldEn) Q_PROPERTY(QString notes READ getNotes WRITE setNotes) Q_PROPERTY(QVector gainModes READ getGainModes WRITE setGainModes) @@ -79,7 +61,6 @@ class DMM_API : public ApiObject void set_mode_ac_ch1(bool en); void set_mode_ac_ch2(bool en); - bool get_histogram_ch1() const; bool get_histogram_ch2() const; void set_histogram_ch1(bool en); @@ -121,10 +102,14 @@ class DMM_API : public ApiObject Q_INVOKABLE void show(); - explicit DMM_API(DMM *dmm) : ApiObject(), dmm(dmm) {} + explicit DMM_API(DMM *dmm) + : ApiObject() + , dmm(dmm) + {} ~DMM_API() {} + private: DMM *dmm; }; -} +} // namespace scopy::m2k #endif // DMM_API_HPP diff --git a/plugins/m2k/src/old/externalloadlineedit.cpp b/plugins/m2k/src/old/externalloadlineedit.cpp index 7a776e0640..cc48e4feac 100644 --- a/plugins/m2k/src/old/externalloadlineedit.cpp +++ b/plugins/m2k/src/old/externalloadlineedit.cpp @@ -1,32 +1,28 @@ #include - using namespace scopy::m2k; constexpr double ExternalLoadLineEdit::MAX_EXTERNAL_LOAD; constexpr double ExternalLoadLineEdit::MIN_EXTERNAL_LOAD; constexpr double ExternalLoadLineEdit::OUTPUT_AWG_RESISTANCE; -ExternalLoadLineEdit::ExternalLoadLineEdit(QWidget *parent) : QLineEdit(parent) { +ExternalLoadLineEdit::ExternalLoadLineEdit(QWidget *parent) + : QLineEdit(parent) +{ value = MAX_EXTERNAL_LOAD; - connect(this,SIGNAL(editingFinished()),this,SLOT(setValue())); + connect(this, SIGNAL(editingFinished()), this, SLOT(setValue())); } -ExternalLoadLineEdit::~ExternalLoadLineEdit() { +ExternalLoadLineEdit::~ExternalLoadLineEdit(){ }; -double ExternalLoadLineEdit::getValue() { - return value; -} +double ExternalLoadLineEdit::getValue() { return value; } -void ExternalLoadLineEdit::setValue() { - setValue(text().toDouble()); -} +void ExternalLoadLineEdit::setValue() { setValue(text().toDouble()); } -void ExternalLoadLineEdit::setValue(QString val) { - setValue(val.toDouble()); -} -void ExternalLoadLineEdit::setValue(double val) { +void ExternalLoadLineEdit::setValue(QString val) { setValue(val.toDouble()); } +void ExternalLoadLineEdit::setValue(double val) +{ QString textVal; val = std::max(val, MIN_EXTERNAL_LOAD); if(val >= MAX_EXTERNAL_LOAD) { diff --git a/plugins/m2k/src/old/externalloadlineedit.h b/plugins/m2k/src/old/externalloadlineedit.h index 78d23dc8b9..f256dfdba4 100644 --- a/plugins/m2k/src/old/externalloadlineedit.h +++ b/plugins/m2k/src/old/externalloadlineedit.h @@ -25,9 +25,9 @@ public Q_SLOTS: Q_SIGNALS: void valueChanged(double); + protected: double value; - }; -} +} // namespace scopy::m2k #endif // EXTERNALLOADLINEEDIT diff --git a/plugins/m2k/src/old/fft_block.cpp b/plugins/m2k/src/old/fft_block.cpp index 55e5fef0ad..bdd435eb92 100644 --- a/plugins/m2k/src/old/fft_block.cpp +++ b/plugins/m2k/src/old/fft_block.cpp @@ -18,40 +18,36 @@ * along with this program. If not, see . */ +#include "fft_block.hpp" + +#include "stream_to_vector_overlap.h" + #include #include #include #include -#include "stream_to_vector_overlap.h" - -#include "fft_block.hpp" using namespace scopy; using namespace gr; fft_block::fft_block(bool use_complex, size_t fft_size, unsigned int nbthreads) - : hier_block2("FFT", - io_signature::make(1, 1, use_complex ? - sizeof(gr_complex) : sizeof(float)), - io_signature::make(1, 1, sizeof(gr_complex))), - d_complex(use_complex) + : hier_block2("FFT", io_signature::make(1, 1, use_complex ? sizeof(gr_complex) : sizeof(float)), + io_signature::make(1, 1, sizeof(gr_complex))) + , d_complex(use_complex) { auto v2s = blocks::vector_to_stream::make(sizeof(gr_complex), fft_size); - d_s2v_overlap = scopy::stream_to_vector_overlap::make( - use_complex ? sizeof(gr_complex) : sizeof(float), - fft_size, 0.0); + d_s2v_overlap = + scopy::stream_to_vector_overlap::make(use_complex ? sizeof(gr_complex) : sizeof(float), fft_size, 0.0); /* We use a Hamming window for now */ auto window = fft::window::hamming(fft_size); - //basic_block_sptr fft; - if (use_complex) - d_fft = fft::fft_v::make(fft_size, - window, false, nbthreads); + // basic_block_sptr fft; + if(use_complex) + d_fft = fft::fft_v::make(fft_size, window, false, nbthreads); else - d_fft = fft::fft_v::make(fft_size, - window, false, nbthreads); + d_fft = fft::fft_v::make(fft_size, window, false, nbthreads); /* Connect everything */ hier_block2::connect(this->self(), 0, d_s2v_overlap, 0); @@ -60,21 +56,18 @@ fft_block::fft_block(bool use_complex, size_t fft_size, unsigned int nbthreads) hier_block2::connect(v2s, 0, this->self(), 0); } -fft_block::~fft_block() -{ -} +fft_block::~fft_block() {} void fft_block::set_overlap_factor(double overlap_factor) { - std::dynamic_pointer_cast( - d_s2v_overlap)->set_overlap_factor(overlap_factor); + std::dynamic_pointer_cast(d_s2v_overlap)->set_overlap_factor(overlap_factor); } -void fft_block::set_window(const std::vector& window) +void fft_block::set_window(const std::vector &window) { - if (d_complex) { + if(d_complex) { std::dynamic_pointer_cast>(d_fft)->set_window(window); } else { - std::dynamic_pointer_cast>(d_fft)->set_window(window); + std::dynamic_pointer_cast>(d_fft)->set_window(window); } } diff --git a/plugins/m2k/src/old/fft_block.hpp b/plugins/m2k/src/old/fft_block.hpp index ce1115eb1b..03d6c68ab5 100644 --- a/plugins/m2k/src/old/fft_block.hpp +++ b/plugins/m2k/src/old/fft_block.hpp @@ -24,21 +24,20 @@ #include namespace scopy { - class fft_block : public gr::hier_block2 - { - public: - fft_block(bool use_complex, size_t fft_size, - unsigned int nbthreads = 1); - ~fft_block(); +class fft_block : public gr::hier_block2 +{ +public: + fft_block(bool use_complex, size_t fft_size, unsigned int nbthreads = 1); + ~fft_block(); - void set_window(const std::vector& window); - void set_overlap_factor(double overlap_factor); + void set_window(const std::vector &window); + void set_overlap_factor(double overlap_factor); - private: - bool d_complex; - gr::basic_block_sptr d_fft; - gr::basic_block_sptr d_s2v_overlap; - }; -} +private: + bool d_complex; + gr::basic_block_sptr d_fft; + gr::basic_block_sptr d_s2v_overlap; +}; +} // namespace scopy #endif /* FFT_BLOCK_HPP */ diff --git a/plugins/m2k/src/old/filter.cpp b/plugins/m2k/src/old/filter.cpp index 821a2d229e..c186ffb27e 100644 --- a/plugins/m2k/src/old/filter.cpp +++ b/plugins/m2k/src/old/filter.cpp @@ -20,36 +20,22 @@ #include "filter.hpp" -#include +#include +#include #include #include #include -#include - -#include -#include #include +#include +#include Q_DECLARE_LOGGING_CATEGORY(CAT_M2KPLUGIN); using namespace scopy::m2k; -static const QStringList tool_names = { - "osc", - "spectrum", - "network", - "siggen", - "logic", - "pattern", - "dio", - "dmm", - "power", - "debugger", - "calibration", - "datalogger", - "launcher" -}; +static const QStringList tool_names = {"osc", "spectrum", "network", "siggen", "logic", "pattern", "dio", + "dmm", "power", "debugger", "calibration", "datalogger", "launcher"}; Filter::Filter(const struct iio_context *ctx) { @@ -61,62 +47,53 @@ Filter::Filter(const struct iio_context *ctx) auto obj = doc.object(); auto obj_keys = obj.keys(); - for (const auto &key : qAsConst(obj_keys)) { + for(const auto &key : qAsConst(obj_keys)) { const auto child = obj[key].toObject(); - if (!child.contains("compatible-devices")) + if(!child.contains("compatible-devices")) continue; const auto compatible_devices = child["compatible-devices"]; - if (!compatible_devices.isArray()) + if(!compatible_devices.isArray()) continue; bool compatible = true; auto comp_dev = compatible_devices.toArray(); - for (const auto &value : qAsConst(comp_dev)) { - if (!value.isString()) { + for(const auto &value : qAsConst(comp_dev)) { + if(!value.isString()) { compatible = false; break; } const auto str = value.toString().toStdString(); - compatible = !!iio_context_find_device( - ctx, str.c_str()); - if (!compatible) + compatible = !!iio_context_find_device(ctx, str.c_str()); + if(!compatible) break; } - if (compatible) { + if(compatible) { this->root = child; hwname = key; return; } } - qDebug(CAT_M2KPLUGIN)<<("Unable to find device in filter file\n"); + qDebug(CAT_M2KPLUGIN) << ("Unable to find device in filter file\n"); this->root = obj["generic"].toObject(); hwname = "generic"; } -Filter::~Filter() -{ -} +Filter::~Filter() {} -QString& Filter::hw_name() -{ - return hwname; -} +QString &Filter::hw_name() { return hwname; } -const QString Filter::tool_name(enum tool tool) -{ - return tool_names[tool]; -} +const QString Filter::tool_name(enum tool tool) { return tool_names[tool]; } bool Filter::compatible(enum tool tool) const { auto hdl = root["compatible"]; - if (!hdl.isArray()) + if(!hdl.isArray()) return false; else return hdl.toArray().contains(tool_names[tool]); @@ -125,9 +102,9 @@ bool Filter::compatible(enum tool tool) const bool Filter::usable(enum tool tool, QString dev) const { auto hdl = root[tool_names[tool] + "-devices"]; - if (hdl.isNull()) + if(hdl.isNull()) return true; - if (!hdl.isArray()) + if(!hdl.isArray()) return false; return hdl.toArray().contains(dev); @@ -136,35 +113,31 @@ bool Filter::usable(enum tool tool, QString dev) const const QString Filter::device_name(enum tool tool, int idx) const { auto hdl = root[tool_names[tool] + "-devices"]; - if (hdl.isNull() || !hdl.isArray()) + if(hdl.isNull() || !hdl.isArray()) return ""; auto array = hdl.toArray(); - if (idx >= array.size()) + if(idx >= array.size()) throw std::runtime_error("Invalid IDX"); return array[idx].toString(); } -struct iio_device * Filter::find_device(const struct iio_context *ctx, - enum tool tool, int idx) const +struct iio_device *Filter::find_device(const struct iio_context *ctx, enum tool tool, int idx) const { return iio_context_find_device(ctx, device_name(tool, idx).toStdString().c_str()); } -struct iio_channel * Filter::find_channel(const struct iio_context *ctx, - enum tool tool, int idx, bool output) const +struct iio_channel *Filter::find_channel(const struct iio_context *ctx, enum tool tool, int idx, bool output) const { QString name = device_name(tool, idx); - if (!name.contains(':')) + if(!name.contains(':')) throw std::runtime_error("Filter entry not iio_channel"); - struct iio_device *dev = iio_context_find_device(ctx, - name.section(':', 0, 0).toStdString().c_str()); - if (!dev) + struct iio_device *dev = iio_context_find_device(ctx, name.section(':', 0, 0).toStdString().c_str()); + if(!dev) return nullptr; - return iio_device_find_channel(dev, - name.section(':', 1, 1).toStdString().c_str(), output); + return iio_device_find_channel(dev, name.section(':', 1, 1).toStdString().c_str(), output); } diff --git a/plugins/m2k/src/old/filter.hpp b/plugins/m2k/src/old/filter.hpp index 2415a07423..92d207db5e 100644 --- a/plugins/m2k/src/old/filter.hpp +++ b/plugins/m2k/src/old/filter.hpp @@ -21,60 +21,59 @@ #ifndef FILTER_HPP #define FILTER_HPP -#include - #include #include -extern "C" { +#include + +extern "C" +{ struct iio_channel; struct iio_context; struct iio_device; } -namespace scopy::m2k{ +namespace scopy::m2k { - enum tool { - TOOL_OSCILLOSCOPE = 0, - TOOL_SPECTRUM_ANALYZER, - TOOL_NETWORK_ANALYZER, - TOOL_SIGNAL_GENERATOR, - TOOL_LOGIC_ANALYZER, - TOOL_PATTERN_GENERATOR, - TOOL_DIGITALIO, - TOOL_DMM, - TOOL_POWER_CONTROLLER, - TOOL_DEBUGGER, - TOOL_CALIBRATION, - TOOL_DATALOGGER, - TOOL_LAUNCHER, - }; +enum tool +{ + TOOL_OSCILLOSCOPE = 0, + TOOL_SPECTRUM_ANALYZER, + TOOL_NETWORK_ANALYZER, + TOOL_SIGNAL_GENERATOR, + TOOL_LOGIC_ANALYZER, + TOOL_PATTERN_GENERATOR, + TOOL_DIGITALIO, + TOOL_DMM, + TOOL_POWER_CONTROLLER, + TOOL_DEBUGGER, + TOOL_CALIBRATION, + TOOL_DATALOGGER, + TOOL_LAUNCHER, +}; - class Filter - { - private: - QJsonObject root; - QString hwname; +class Filter +{ +private: + QJsonObject root; + QString hwname; - public: - Filter(const struct iio_context *ctx); - ~Filter(); +public: + Filter(const struct iio_context *ctx); + ~Filter(); - QString& hw_name(); + QString &hw_name(); - bool compatible(enum tool tool) const; - bool usable(enum tool tool, const QString dev) const; - const QString device_name(enum tool tool, - int idx = 0) const; + bool compatible(enum tool tool) const; + bool usable(enum tool tool, const QString dev) const; + const QString device_name(enum tool tool, int idx = 0) const; - struct iio_device * find_device(const struct iio_context *ctx, - enum tool tool, int idx = 0) const; - struct iio_channel * find_channel(const struct iio_context *ctx, - enum tool tool, int idx = 0, - bool output = false) const; + struct iio_device *find_device(const struct iio_context *ctx, enum tool tool, int idx = 0) const; + struct iio_channel *find_channel(const struct iio_context *ctx, enum tool tool, int idx = 0, + bool output = false) const; - static const QString tool_name(enum tool tool); - }; -} + static const QString tool_name(enum tool tool); +}; +} // namespace scopy::m2k #endif /* FILTER_HPP */ diff --git a/plugins/m2k/src/old/frequency_compensation_filter.h b/plugins/m2k/src/old/frequency_compensation_filter.h index 5b27a61682..ccfea41684 100644 --- a/plugins/m2k/src/old/frequency_compensation_filter.h +++ b/plugins/m2k/src/old/frequency_compensation_filter.h @@ -41,8 +41,7 @@ class frequency_compensation_filter : virtual public gr::sync_block * \param gain - gain of the filter * \param sample_rate - sample rate used in filter response */ - static sptr make(bool enable = true, float TC = 1, float gain = 0, - float sample_rate = 100000000); + static sptr make(bool enable = true, float TC = 1, float gain = 0, float sample_rate = 100000000); virtual void set_enable(bool en, int gain_mode = 2) = 0; virtual bool get_enable(int gain_mode = 2) = 0; virtual void set_TC(float TC, int gain_mode = 2) = 0; diff --git a/plugins/m2k/src/old/frequency_compensation_filter_impl.cc b/plugins/m2k/src/old/frequency_compensation_filter_impl.cc index f972ae80a1..0614cab08c 100644 --- a/plugins/m2k/src/old/frequency_compensation_filter_impl.cc +++ b/plugins/m2k/src/old/frequency_compensation_filter_impl.cc @@ -19,23 +19,23 @@ */ #include "frequency_compensation_filter_impl.h" -#include + #include +#include using namespace gr; namespace scopy { -frequency_compensation_filter_impl::frequency_compensation_filter_impl( - bool enable, float TC, float gain, - float sample_rate) +frequency_compensation_filter_impl::frequency_compensation_filter_impl(bool enable, float TC, float gain, + float sample_rate) - : sync_block("overshoot_filter", - io_signature::make(1,1, sizeof(short)), - io_signature::make(1, 1, sizeof(short))), - sample_rate(sample_rate), high_gain(false) + : sync_block("overshoot_filter", io_signature::make(1, 1, sizeof(short)), + io_signature::make(1, 1, sizeof(short))) + , sample_rate(sample_rate) + , high_gain(false) { - for (auto i=0; i < 2; i++) { + for(auto i = 0; i < 2; i++) { config[i].enable = enable; config[i].TC = TC; config[i].gain = gain; @@ -44,50 +44,45 @@ frequency_compensation_filter_impl::frequency_compensation_filter_impl( set_history(1); } -frequency_compensation_filter::sptr -frequency_compensation_filter::make(bool enable, float TC, float gain, - float sample_rate) +frequency_compensation_filter::sptr frequency_compensation_filter::make(bool enable, float TC, float gain, + float sample_rate) { - return gnuradio::get_initial_sptr - (new frequency_compensation_filter_impl(enable, TC, gain, - sample_rate)); + return gnuradio::get_initial_sptr(new frequency_compensation_filter_impl(enable, TC, gain, sample_rate)); } -int -frequency_compensation_filter_impl::work(int noutput_items, - gr_vector_const_void_star& input_items, - gr_vector_void_star& output_items) +int frequency_compensation_filter_impl::work(int noutput_items, gr_vector_const_void_star &input_items, + gr_vector_void_star &output_items) { - const short *in = (const short *) input_items[0]; + const short *in = (const short *)input_items[0]; float *out_f = new float[noutput_items]; - short *out = (short *) output_items[0]; + short *out = (short *)output_items[0]; float delta = 1.0 / sample_rate; float TC1 = config[high_gain].TC * float(1.0E-6); - float Alpha = TC1/(TC1+delta); - out_f[0]=(in[1]-in[0]); + float Alpha = TC1 / (TC1 + delta); + out_f[0] = (in[1] - in[0]); int i = 1; - if (config[high_gain].enable) { - for (i = 1; i < noutput_items; i++) { - out_f[i]=(Alpha*(out_f[i-1]+(float)(in[i]-in[i-1]))); + if(config[high_gain].enable) { + for(i = 1; i < noutput_items; i++) { + out_f[i] = (Alpha * (out_f[i - 1] + (float)(in[i] - in[i - 1]))); } - for (i = 0; i < noutput_items; i++) { - out[i]=in[i]+(short)((out_f[i])*config[high_gain].gain); + for(i = 0; i < noutput_items; i++) { + out[i] = in[i] + (short)((out_f[i]) * config[high_gain].gain); } } else { - memcpy(out,in,noutput_items*sizeof(short)); + memcpy(out, in, noutput_items * sizeof(short)); } - delete []out_f; + delete[] out_f; return noutput_items; } void frequency_compensation_filter_impl::set_enable(bool en, int gain_mode) { - if (gain_mode == 2) { + if(gain_mode == 2) { gain_mode = high_gain; } @@ -96,7 +91,7 @@ void frequency_compensation_filter_impl::set_enable(bool en, int gain_mode) bool frequency_compensation_filter_impl::get_enable(int gain_mode) { - if (gain_mode == 2) { + if(gain_mode == 2) { gain_mode = high_gain; } @@ -105,7 +100,7 @@ bool frequency_compensation_filter_impl::get_enable(int gain_mode) void frequency_compensation_filter_impl::set_TC(float TC, int gain_mode) { - if (gain_mode == 2) { + if(gain_mode == 2) { gain_mode = high_gain; } @@ -114,17 +109,16 @@ void frequency_compensation_filter_impl::set_TC(float TC, int gain_mode) float frequency_compensation_filter_impl::get_TC(int gain_mode) { - if (gain_mode == 2) { + if(gain_mode == 2) { gain_mode = high_gain; } return this->config[gain_mode].TC; } -void frequency_compensation_filter_impl::set_filter_gain(float gain, - int gain_mode) +void frequency_compensation_filter_impl::set_filter_gain(float gain, int gain_mode) { - if (gain_mode == 2) { + if(gain_mode == 2) { gain_mode = high_gain; } @@ -133,24 +127,15 @@ void frequency_compensation_filter_impl::set_filter_gain(float gain, float frequency_compensation_filter_impl::get_filter_gain(int gain_mode) { - if (gain_mode == 2) { + if(gain_mode == 2) { gain_mode = high_gain; } return this->config[gain_mode].gain; } -void frequency_compensation_filter_impl::set_sample_rate(float sample_rate) -{ - this->sample_rate = sample_rate; -} +void frequency_compensation_filter_impl::set_sample_rate(float sample_rate) { this->sample_rate = sample_rate; } -bool frequency_compensation_filter_impl::get_high_gain() -{ - return this->high_gain; -} -void frequency_compensation_filter_impl::set_high_gain(bool en) -{ - this->high_gain=en; -} -} +bool frequency_compensation_filter_impl::get_high_gain() { return this->high_gain; } +void frequency_compensation_filter_impl::set_high_gain(bool en) { this->high_gain = en; } +} // namespace scopy diff --git a/plugins/m2k/src/old/frequency_compensation_filter_impl.h b/plugins/m2k/src/old/frequency_compensation_filter_impl.h index c4b597588c..05bb709efe 100644 --- a/plugins/m2k/src/old/frequency_compensation_filter_impl.h +++ b/plugins/m2k/src/old/frequency_compensation_filter_impl.h @@ -22,6 +22,7 @@ #define OVERSHOOT_FILTER_HPP #include "frequency_compensation_filter.h" + #include using namespace gr; @@ -30,7 +31,8 @@ namespace scopy { class frequency_compensation_filter_impl : public frequency_compensation_filter { private: - typedef struct { + typedef struct + { bool enable; float TC, gain; } filter_config_t; @@ -41,11 +43,8 @@ class frequency_compensation_filter_impl : public frequency_compensation_filter public: typedef std::shared_ptr sptr; - frequency_compensation_filter_impl(bool enable, float TC, float gain, - float sample_rate); - int work(int noutput_items, - gr_vector_const_void_star& input_items, - gr_vector_void_star& output_items); + frequency_compensation_filter_impl(bool enable, float TC, float gain, float sample_rate); + int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); void set_enable(bool en, int gain_mode); bool get_enable(int gain_mode) override; @@ -57,5 +56,5 @@ class frequency_compensation_filter_impl : public frequency_compensation_filter bool get_high_gain() override; void set_high_gain(bool en); }; -} +} // namespace scopy #endif diff --git a/plugins/m2k/src/old/hardware_trigger.cpp b/plugins/m2k/src/old/hardware_trigger.cpp index 1d23e91f43..89573acb79 100644 --- a/plugins/m2k/src/old/hardware_trigger.cpp +++ b/plugins/m2k/src/old/hardware_trigger.cpp @@ -18,6 +18,7 @@ * along with this program. If not, see . */ #include "hardware_trigger.hpp" + #include #include @@ -32,11 +33,7 @@ const QVector HardwareTrigger::lut_analog_trigg_cond = { }; const QVector HardwareTrigger::lut_digital_trigg_cond = { - "edge-rising", - "edge-falling", - "level-low", - "level-high", - "edge-any", + "edge-rising", "edge-falling", "level-low", "level-high", "edge-any", }; const QVector HardwareTrigger::lut_trigg_mode = { @@ -51,17 +48,10 @@ const QVector HardwareTrigger::lut_trigg_mode = { "!digital_XOR_analog", }; -const QVector HardwareTrigger::lut_digital_out_direction = { - "in", - "out" -}; +const QVector HardwareTrigger::lut_digital_out_direction = {"in", "out"}; -const QVector HardwareTrigger::lut_digital_out_select= { - "sw-trigger", - "trigger-i-same-chn", - "trigger-i-swap-chn", - "trigger-adc", - "trigger-in", +const QVector HardwareTrigger::lut_digital_out_select = { + "sw-trigger", "trigger-i-same-chn", "trigger-i-swap-chn", "trigger-adc", "trigger-in", }; // This is still not generic. It is specific to only 2 channels! @@ -80,19 +70,19 @@ const QVector HardwareTrigger::lut_trigg_source = { typedef QPair channel_pair; -HardwareTrigger::HardwareTrigger(struct iio_device *trigg_dev) : - m_trigger_device(trigg_dev) +HardwareTrigger::HardwareTrigger(struct iio_device *trigg_dev) + : m_trigger_device(trigg_dev) { - if (!trigg_dev) { + if(!trigg_dev) { throw std::invalid_argument("trigger_device=NULL"); } // Get all channels and sort them ascending by name QList> channels; - for (uint i = 0; i < iio_device_get_channels_count(trigg_dev); i++) { + for(uint i = 0; i < iio_device_get_channels_count(trigg_dev); i++) { struct iio_channel *chn = iio_device_get_channel(trigg_dev, i); - if (iio_channel_is_output(chn)) { + if(iio_channel_is_output(chn)) { continue; } @@ -100,122 +90,101 @@ HardwareTrigger::HardwareTrigger(struct iio_device *trigg_dev) : QPair chn_pair(chn, name); channels.push_back(chn_pair); } - std::sort(channels.begin(), channels.end(), - [](channel_pair a, channel_pair b) - { return a.second < b.second; }); + std::sort(channels.begin(), channels.end(), [](channel_pair a, channel_pair b) { return a.second < b.second; }); // Pick the analog, digital, trigger_logic and delay channels - for (int i = 0; i < channels.size(); i++) { + for(int i = 0; i < channels.size(); i++) { struct iio_channel *chn = channels[i].first; bool mode = iio_channel_find_attr(chn, "mode"); bool trigger = iio_channel_find_attr(chn, "trigger"); - bool trigger_level = iio_channel_find_attr(chn, - "trigger_level"); - bool trigger_hysteresis = iio_channel_find_attr(chn, - "trigger_hysteresis"); + bool trigger_level = iio_channel_find_attr(chn, "trigger_level"); + bool trigger_hysteresis = iio_channel_find_attr(chn, "trigger_hysteresis"); - if (trigger) { - if (trigger_level && trigger_hysteresis) { + if(trigger) { + if(trigger_level && trigger_hysteresis) { m_analog_channels.push_back(chn); - } else if (!trigger_level && !trigger_hysteresis) { + } else if(!trigger_level && !trigger_hysteresis) { m_digital_channels.push_back(chn); } - } else if (mode) { + } else if(mode) { m_logic_channels.push_back(chn); } } - m_delay_trigger = iio_device_find_channel(trigg_dev, "trigger", - false); + m_delay_trigger = iio_device_find_channel(trigg_dev, "trigger", false); m_num_channels = m_analog_channels.size(); - if (m_analog_channels.size() < 1) { - throw std::runtime_error( - "hardware trigger has no analog channels"); + if(m_analog_channels.size() < 1) { + throw std::runtime_error("hardware trigger has no analog channels"); } - if (m_digital_channels.size() < 1) { - throw std::runtime_error( - "hardware trigger has no digital channels"); + if(m_digital_channels.size() < 1) { + throw std::runtime_error("hardware trigger has no digital channels"); } - if (m_logic_channels.size() < 1) { - throw std::runtime_error( - "hardware trigger has no trigger_logic channels"); + if(m_logic_channels.size() < 1) { + throw std::runtime_error("hardware trigger has no trigger_logic channels"); } - if (!m_delay_trigger) { + if(!m_delay_trigger) { throw std::runtime_error("no delay trigger available"); } - setStreamingFlag(false); } -uint HardwareTrigger::numChannels() const -{ - return m_num_channels; -} +uint HardwareTrigger::numChannels() const { return m_num_channels; } -HardwareTrigger::condition HardwareTrigger::analogCondition(uint chnIdx) - const +HardwareTrigger::condition HardwareTrigger::analogCondition(uint chnIdx) const { - if (chnIdx >= numChannels()) { + if(chnIdx >= numChannels()) { throw std::invalid_argument("Channel index is out of range"); } ssize_t ret; char buf[4096]; - ret = iio_channel_attr_read(m_analog_channels[chnIdx], "trigger", buf, - sizeof(buf)); - if (ret < 0) { + ret = iio_channel_attr_read(m_analog_channels[chnIdx], "trigger", buf, sizeof(buf)); + if(ret < 0) { throw std::runtime_error("failed to read attribute: trigger"); } - auto it = std::find(lut_analog_trigg_cond.begin(), - lut_analog_trigg_cond.end(), buf); - if (it == lut_analog_trigg_cond.end()) { - throw std::runtime_error( - "unexpected value read from attribute: trigger"); + auto it = std::find(lut_analog_trigg_cond.begin(), lut_analog_trigg_cond.end(), buf); + if(it == lut_analog_trigg_cond.end()) { + throw std::runtime_error("unexpected value read from attribute: trigger"); } return static_cast(it - lut_analog_trigg_cond.begin()); - } void HardwareTrigger::setAnalogCondition(uint chnIdx, condition cond) { - if (chnIdx >= numChannels()) { + if(chnIdx >= numChannels()) { throw std::invalid_argument("Channel index is out of range"); } - if (cond == ANY_EDGE) { - return; //or throw? + if(cond == ANY_EDGE) { + return; // or throw? } - QByteArray byteArray = lut_analog_trigg_cond[cond].toLatin1(); - iio_channel_attr_write(m_analog_channels[chnIdx], "trigger", - byteArray.data()); + QByteArray byteArray = lut_analog_trigg_cond[cond].toLatin1(); + iio_channel_attr_write(m_analog_channels[chnIdx], "trigger", byteArray.data()); } -HardwareTrigger::condition HardwareTrigger::digitalCondition(uint chnIdx) - const +HardwareTrigger::condition HardwareTrigger::digitalCondition(uint chnIdx) const { - if (chnIdx >= numChannels()) { + if(chnIdx >= numChannels()) { throw std::invalid_argument("Channel index is out of range"); } ssize_t ret; char buf[4096]; - ret = iio_channel_attr_read(m_digital_channels[chnIdx], "trigger", buf, - sizeof(buf)); - if (ret < 0) + ret = iio_channel_attr_read(m_digital_channels[chnIdx], "trigger", buf, sizeof(buf)); + if(ret < 0) throw "failed to read attribute: trigger"; - auto it = std::find(lut_digital_trigg_cond.begin(), - lut_digital_trigg_cond.end(), buf); - if (it == lut_digital_trigg_cond.end()) { + auto it = std::find(lut_digital_trigg_cond.begin(), lut_digital_trigg_cond.end(), buf); + if(it == lut_digital_trigg_cond.end()) { throw "unexpected value read from attribute: trigger"; } @@ -225,123 +194,112 @@ HardwareTrigger::condition HardwareTrigger::digitalCondition(uint chnIdx) bool HardwareTrigger::hasExternalTriggerOut() const { auto ret = iio_channel_find_attr(m_logic_channels[1], "out_select"); - return (ret==NULL) ? false : true; + return (ret == NULL) ? false : true; } -bool HardwareTrigger::hasExternalTriggerIn() const -{ - return true; -} +bool HardwareTrigger::hasExternalTriggerIn() const { return true; } bool HardwareTrigger::hasCrossInstrumentTrigger() const { auto ret = iio_channel_find_attr(m_logic_channels[1], "out_select"); - return (ret==NULL) ? false : true; + return (ret == NULL) ? false : true; } void HardwareTrigger::setExternalDirection(uint chnIdx, direction dir) { if(hasExternalTriggerOut()) { - if (chnIdx >= numChannels()) { - throw std::invalid_argument("Channel index is out of range"); - } + if(chnIdx >= numChannels()) { + throw std::invalid_argument("Channel index is out of range"); + } - QByteArray byteArray = lut_digital_out_direction[dir].toLatin1(); - iio_channel_attr_write(m_logic_channels[chnIdx], "out_direction", - byteArray.data()); + QByteArray byteArray = lut_digital_out_direction[dir].toLatin1(); + iio_channel_attr_write(m_logic_channels[chnIdx], "out_direction", byteArray.data()); } } void HardwareTrigger::setExternalOutSelect(uint chnIdx, out_select out) { if(hasExternalTriggerOut()) { - if (chnIdx >= numChannels()) { - throw std::invalid_argument("Channel index is out of range"); - } + if(chnIdx >= numChannels()) { + throw std::invalid_argument("Channel index is out of range"); + } - QByteArray byteArray = lut_digital_out_select[out].toLatin1(); - iio_channel_attr_write(m_logic_channels[chnIdx], "out_select", - byteArray.data()); + QByteArray byteArray = lut_digital_out_select[out].toLatin1(); + iio_channel_attr_write(m_logic_channels[chnIdx], "out_select", byteArray.data()); } } void HardwareTrigger::setDigitalCondition(uint chnIdx, condition cond) { - if (chnIdx >= numChannels()) { + if(chnIdx >= numChannels()) { throw std::invalid_argument("Channel index is out of range"); } - QByteArray byteArray = lut_digital_trigg_cond[cond].toLatin1(); - iio_channel_attr_write(m_digital_channels[chnIdx], "trigger", - byteArray.data()); + QByteArray byteArray = lut_digital_trigg_cond[cond].toLatin1(); + iio_channel_attr_write(m_digital_channels[chnIdx], "trigger", byteArray.data()); } int HardwareTrigger::level(uint chnIdx) const { - if (chnIdx >= numChannels()) { + if(chnIdx >= numChannels()) { throw std::invalid_argument("Channel index is out of range"); } long long val; - iio_channel_attr_read_longlong(m_analog_channels[chnIdx], - "trigger_level", &val); + iio_channel_attr_read_longlong(m_analog_channels[chnIdx], "trigger_level", &val); return static_cast(val); } void HardwareTrigger::setLevel(uint chnIdx, int level) { - if (chnIdx >= numChannels()) { + if(chnIdx >= numChannels()) { throw std::invalid_argument("Channel index is out of range"); } - iio_channel_attr_write_longlong(m_analog_channels[chnIdx], - "trigger_level", static_cast (level)); + iio_channel_attr_write_longlong(m_analog_channels[chnIdx], "trigger_level", static_cast(level)); } int HardwareTrigger::hysteresis(uint chnIdx) const { - if (chnIdx >= numChannels()) { + if(chnIdx >= numChannels()) { throw std::invalid_argument("Channel index is out of range"); } long long val; - iio_channel_attr_read_longlong(m_analog_channels[chnIdx], - "trigger_hysteresis", &val); + iio_channel_attr_read_longlong(m_analog_channels[chnIdx], "trigger_hysteresis", &val); return static_cast(val); } void HardwareTrigger::setHysteresis(uint chnIdx, int histeresis) { - if (chnIdx >= numChannels()) { + if(chnIdx >= numChannels()) { throw std::invalid_argument("Channel index is out of range"); } - iio_channel_attr_write_longlong(m_analog_channels[chnIdx], - "trigger_hysteresis", static_cast(histeresis)); + iio_channel_attr_write_longlong(m_analog_channels[chnIdx], "trigger_hysteresis", + static_cast(histeresis)); } HardwareTrigger::mode HardwareTrigger::triggerMode(uint chnIdx) const { - if (chnIdx >= numChannels()) { + if(chnIdx >= numChannels()) { throw std::invalid_argument("Channel index is out of range"); } ssize_t ret; char buf[4096]; - ret = iio_channel_attr_read(m_logic_channels[chnIdx], "mode", buf, - sizeof(buf)); - if (ret < 0) { - throw ("failed to read attribute: mode"); + ret = iio_channel_attr_read(m_logic_channels[chnIdx], "mode", buf, sizeof(buf)); + if(ret < 0) { + throw("failed to read attribute: mode"); } - auto it = std::find(lut_trigg_mode.begin(), - lut_trigg_mode.end(), buf); - if (it == lut_trigg_mode.end()) { - throw ("unexpected value read from attribute: mode"); + auto it = std::find(lut_trigg_mode.begin(), lut_trigg_mode.end(), buf); + if(it == lut_trigg_mode.end()) { + throw("unexpected value read from attribute: mode"); } return static_cast(it - lut_trigg_mode.begin()); @@ -349,13 +307,12 @@ HardwareTrigger::mode HardwareTrigger::triggerMode(uint chnIdx) const void HardwareTrigger::setTriggerMode(uint chnIdx, HardwareTrigger::mode mode) { - if (chnIdx >= numChannels()) { + if(chnIdx >= numChannels()) { throw std::invalid_argument("Channel index is out of range"); } - QByteArray byteArray = lut_trigg_mode[mode].toLatin1(); - iio_channel_attr_write(m_logic_channels[chnIdx], "mode", - byteArray.data()); + QByteArray byteArray = lut_trigg_mode[mode].toLatin1(); + iio_channel_attr_write(m_logic_channels[chnIdx], "mode", byteArray.data()); } QString HardwareTrigger::source() const @@ -367,11 +324,10 @@ QString HardwareTrigger::source() const return QString(buf); } -void HardwareTrigger::setSource(const QString& source) +void HardwareTrigger::setSource(const QString &source) { QByteArray byteArray = source.toLatin1(); - iio_channel_attr_write(m_delay_trigger, "logic_mode", - byteArray.data()); + iio_channel_attr_write(m_delay_trigger, "logic_mode", byteArray.data()); } /* @@ -379,15 +335,9 @@ void HardwareTrigger::setSource(const QString& source) * channel at a time. */ -bool HardwareTrigger::triggerIn() const -{ - return m_trigger_in; -} +bool HardwareTrigger::triggerIn() const { return m_trigger_in; } -void HardwareTrigger::setTriggerIn(bool bo) -{ - m_trigger_in = bo; -} +void HardwareTrigger::setTriggerIn(bool bo) { m_trigger_in = bo; } int HardwareTrigger::sourceChannel() const { @@ -397,7 +347,7 @@ int HardwareTrigger::sourceChannel() const // Returning the channel index if a single channel is set as a source // and -1 if multiple channels are set. - if (mode.length() == 1) { + if(mode.length() == 1) { chnIdx = mode.at(0).digitValue() - QChar('a').digitValue(); } @@ -410,7 +360,7 @@ int HardwareTrigger::sourceChannel() const */ void HardwareTrigger::setSourceChannel(uint chnIdx, bool intern_checked, bool extern_trigger_in_checked) { - if (chnIdx >= numChannels()) { + if(chnIdx >= numChannels()) { throw std::invalid_argument("Channel index is out of range"); } @@ -437,10 +387,7 @@ int HardwareTrigger::delay() const return static_cast(delay); } -void HardwareTrigger::setDelay(int delay) -{ - iio_channel_attr_write_longlong(m_delay_trigger, "delay", delay); -} +void HardwareTrigger::setDelay(int delay) { iio_channel_attr_write_longlong(m_delay_trigger, "delay", delay); } void HardwareTrigger::setStreamingFlag(bool val) { @@ -448,16 +395,13 @@ void HardwareTrigger::setStreamingFlag(bool val) iio_device_attr_write_bool(m_trigger_device, "streaming", val); } -bool HardwareTrigger::getStreamingFlag() -{ - return m_streaming_flag; -} +bool HardwareTrigger::getStreamingFlag() { return m_streaming_flag; } HardwareTrigger::settings_uptr HardwareTrigger::getCurrentHwSettings() { settings_uptr settings(new Settings); - for (uint i = 0; i < numChannels(); i++) { + for(uint i = 0; i < numChannels(); i++) { settings->analog_condition.push_back(analogCondition(i)); settings->digital_condition.push_back(digitalCondition(i)); settings->level.push_back(level(i)); @@ -472,7 +416,7 @@ HardwareTrigger::settings_uptr HardwareTrigger::getCurrentHwSettings() void HardwareTrigger::setHwTriggerSettings(struct Settings *settings) { - for (uint i = 0; i < numChannels(); i++) { + for(uint i = 0; i < numChannels(); i++) { setAnalogCondition(i, settings->analog_condition[i]); setDigitalCondition(i, settings->digital_condition[i]); setLevel(i, settings->level[i]); diff --git a/plugins/m2k/src/old/hardware_trigger.hpp b/plugins/m2k/src/old/hardware_trigger.hpp index 2da34b2d45..bdf024d4ad 100644 --- a/plugins/m2k/src/old/hardware_trigger.hpp +++ b/plugins/m2k/src/old/hardware_trigger.hpp @@ -21,12 +21,15 @@ #define HARDWARE_TRIGGER_H #include + #include -#include #include +#include + #include -extern "C" { +extern "C" +{ struct iio_device; struct iio_channel; } @@ -36,7 +39,8 @@ namespace scopy { class HardwareTrigger { public: - enum condition { + enum condition + { RISING_EDGE = 0, FALLING_EDGE = 1, LOW = 3, @@ -44,25 +48,28 @@ class HardwareTrigger ANY_EDGE = 5, }; - enum mode { - ALWAYS = 0, - ANALOG = 1, - DIGITAL = 2, - DIGITAL_OR_ANALOG = 3, - DIGITAL_AND_ANALOG = 4, - DIGITAL_XOR_ANALOG = 5, - TRIGGER_IN = 6, - ANALOG_OR_TRIGGER_IN = 7, - DIGITAL_OR_TRIGGER_IN = 8, - DIGITAL_OR_ANALOG_OR_TRIGGER_IN = 9, + enum mode + { + ALWAYS = 0, + ANALOG = 1, + DIGITAL = 2, + DIGITAL_OR_ANALOG = 3, + DIGITAL_AND_ANALOG = 4, + DIGITAL_XOR_ANALOG = 5, + TRIGGER_IN = 6, + ANALOG_OR_TRIGGER_IN = 7, + DIGITAL_OR_TRIGGER_IN = 8, + DIGITAL_OR_ANALOG_OR_TRIGGER_IN = 9, }; - enum direction { + enum direction + { TRIGGER_INPUT = 0, TRIGGER_OUT = 1, }; - enum out_select { + enum out_select + { sw_trigger = 0, trigger_i_same_channel = 1, trigger_i_swap_channel = 2, @@ -70,7 +77,8 @@ class HardwareTrigger trigger_in = 4, }; - struct Settings { + struct Settings + { QList analog_condition; QList digital_condition; QList level; @@ -83,7 +91,6 @@ class HardwareTrigger typedef std::unique_ptr settings_uptr; public: - HardwareTrigger(struct iio_device *trigger_dev); uint numChannels() const; @@ -104,7 +111,7 @@ class HardwareTrigger void setTriggerMode(uint chnIdx, mode mode); QString source() const; - void setSource(const QString& source); + void setSource(const QString &source); int sourceChannel() const; void setSourceChannel(uint chnIdx, bool intern_checked, bool extern_trigger_in_checked); @@ -127,7 +134,6 @@ class HardwareTrigger void setExternalDirection(uint chnIdx, direction dir); void setExternalOutSelect(uint chnIdx, out_select out); - private: struct iio_device *m_trigger_device; QList m_analog_channels; diff --git a/plugins/m2k/src/old/iio_manager.cpp b/plugins/m2k/src/old/iio_manager.cpp index 14dd1d1694..41956c6ad4 100644 --- a/plugins/m2k/src/old/iio_manager.cpp +++ b/plugins/m2k/src/old/iio_manager.cpp @@ -18,14 +18,18 @@ * along with this program. If not, see . */ #include "iio_manager.hpp" -#include -#include #include "pluginbase/preferences.h" -#include + #include -#include + +#include +#include + #include +#include + +#include using namespace scopy::m2k; using namespace gr; @@ -34,52 +38,49 @@ static constexpr int KERNEL_BUFFERS_DEFAULT = 1; Q_LOGGING_CATEGORY(CAT_M2K_IIO_MANAGER, "M2kIIOManager"); -iio_manager::iio_manager(unsigned int block_id, - struct iio_context *ctx, QString _dev, - unsigned long _buffer_size) : - QObject(nullptr), - top_block("IIO Manager " + std::to_string(block_id)), - id(block_id), _started(false), buffer_size(_buffer_size), - m_mixed_source(nullptr) +iio_manager::iio_manager(unsigned int block_id, struct iio_context *ctx, QString _dev, unsigned long _buffer_size) + : QObject(nullptr) + , top_block("IIO Manager " + std::to_string(block_id)) + , id(block_id) + , _started(false) + , buffer_size(_buffer_size) + , m_mixed_source(nullptr) { m_context = libm2k::context::m2kOpen(ctx, ""); m_analogin = m_context->getAnalogIn(); - if (!ctx) + if(!ctx) throw std::runtime_error("IIO context not created"); struct iio_device *dev = iio_context_find_device(ctx, _dev.toStdString().c_str()); - if (!dev) + if(!dev) throw std::runtime_error("Device not found"); nb_channels = iio_device_get_channels_count(dev); - Preferences *p = Preferences::GetInstance(); double targetFps = p->get("general_plot_target_fps").toString().toDouble(); // get target fps from preferences iio_block = gr::m2k::analog_in_source::make_from(m_context, _buffer_size, {1, 1}, {0, 0}, 10000, 1, - KERNEL_BUFFERS_DEFAULT, false, false, {0, 0}, {0, 0}, 0, 0, {0, 0}, - false, false, targetFps); + KERNEL_BUFFERS_DEFAULT, false, false, {0, 0}, {0, 0}, 0, 0, + {0, 0}, false, false, targetFps); /* Avoid unconnected channel errors by connecting a dummy sink */ auto dummy_copy = blocks::copy::make(sizeof(short)); auto dummy = blocks::null_sink::make(sizeof(short)); - - //TODO - make dynamic + // TODO - make dynamic freq_comp_filt[0][0] = scopy::frequency_compensation_filter::make(false); freq_comp_filt[0][1] = scopy::frequency_compensation_filter::make(false); freq_comp_filt[1][0] = scopy::frequency_compensation_filter::make(false); freq_comp_filt[1][1] = scopy::frequency_compensation_filter::make(false); - for (unsigned i = 0; i < nb_channels; i++) { - hier_block2::connect(iio_block,i,freq_comp_filt[i][0],0); - hier_block2::connect(freq_comp_filt[i][0],0,freq_comp_filt[i][1],0); + for(unsigned i = 0; i < nb_channels; i++) { + hier_block2::connect(iio_block, i, freq_comp_filt[i][0], 0); + hier_block2::connect(freq_comp_filt[i][0], 0, freq_comp_filt[i][1], 0); hier_block2::connect(freq_comp_filt[i][1], 0, dummy_copy, i); hier_block2::connect(dummy_copy, i, dummy, i); - } dummy_copy->set_enabled(true); @@ -87,25 +88,22 @@ iio_manager::iio_manager(unsigned int block_id, timeout_b = gnuradio::get_initial_sptr(new timeout_block("msg")); hier_block2::msg_connect(iio_block, "msg", timeout_b, "msg"); - QObject::connect(&*timeout_b, SIGNAL(timeout()), this, - SLOT(got_timeout())); + QObject::connect(&*timeout_b, SIGNAL(timeout()), this, SLOT(got_timeout())); } -iio_manager::~iio_manager() -{ -} +iio_manager::~iio_manager() {} std::shared_ptr m2k_iio_manager::has_instance(QString _dev) { /* Search the dev_map if we already have a manager for the * given device */ - if (!dev_map.empty()) { - for (auto it = dev_map.begin(); it != dev_map.end(); ++it) { - if (it->first.compare(_dev) != 0) + if(!dev_map.empty()) { + for(auto it = dev_map.begin(); it != dev_map.end(); ++it) { + if(it->first.compare(_dev) != 0) continue; /* We found the entry. */ - if (!it->second.expired()) + if(!it->second.expired()) return it->second.lock(); else break; @@ -114,31 +112,29 @@ std::shared_ptr m2k_iio_manager::has_instance(QString _dev) return nullptr; } -std::shared_ptr m2k_iio_manager::get_instance( - struct iio_context *ctx, QString _dev, - unsigned long buffer_size) +std::shared_ptr m2k_iio_manager::get_instance(struct iio_context *ctx, QString _dev, + unsigned long buffer_size) { auto instance = has_instance(_dev); - if (instance) { + if(instance) { return instance; } - /* No manager found - create a new one */ + /* No manager found - create a new one */ auto manager = new iio_manager(_id++, ctx, _dev, buffer_size); std::shared_ptr shared_manager(manager); /* Add it to the map */ - auto p = std::pair( _dev, shared_manager); + auto p = std::pair(_dev, shared_manager); auto it = dev_map.insert(p); - if (it.second == false) + if(it.second == false) it.first->second = shared_manager; return shared_manager; } -iio_manager::port_id iio_manager::connect(basic_block_sptr dst, - int src_port, int dst_port, bool use_float, - unsigned long _buffer_size) +iio_manager::port_id iio_manager::connect(basic_block_sptr dst, int src_port, int dst_port, bool use_float, + unsigned long _buffer_size) { std::unique_lock lock(copy_mutex); @@ -156,7 +152,7 @@ iio_manager::port_id iio_manager::connect(basic_block_sptr dst, /* TODO: Find a way to share one short_to_float block per channel, * instead of having each client instanciate its own */ - if (use_float) { + if(use_float) { auto s2f = blocks::short_to_float::make(); iio_manager::connect(copy, 0, s2f, 0); iio_manager::connect(s2f, 0, dst, dst_port); @@ -175,8 +171,8 @@ void iio_manager::disconnect(iio_manager::port_id copy) copy->set_enabled(false); - for (auto it = copy_blocks.begin(); it != copy_blocks.end(); ++it) { - if (it->first == copy) { + for(auto it = copy_blocks.begin(); it != copy_blocks.end(); ++it) { + if(it->first == copy) { copy_blocks.erase(it); break; } @@ -190,14 +186,14 @@ void iio_manager::update_buffer_size_unlocked() { unsigned long size = 0; - for (auto it = copy_blocks.begin(); it != copy_blocks.end(); ++it) { - if (it->first->enabled() && size < it->second) + for(auto it = copy_blocks.begin(); it != copy_blocks.end(); ++it) { + if(it->first->enabled() && size < it->second) size = it->second; } - if (size) { + if(size) { iio_block->set_buffer_size(size); - if (m_mixed_source) { + if(m_mixed_source) { m_mixed_source->set_buffer_size(size); } this->buffer_size = size; @@ -208,7 +204,7 @@ void iio_manager::start(iio_manager::port_id copy) { std::unique_lock lock(copy_mutex); - if (copy->enabled()) + if(copy->enabled()) return; qDebug(CAT_M2K_IIO_MANAGER) << "Enabling copy block" << copy->alias().c_str(); @@ -216,7 +212,7 @@ void iio_manager::start(iio_manager::port_id copy) update_buffer_size_unlocked(); - if (!_started) { + if(!_started) { qDebug(CAT_M2K_IIO_MANAGER) << "Starting top block"; top_block::start(); } @@ -224,7 +220,7 @@ void iio_manager::start(iio_manager::port_id copy) _started = true; } -void iio_manager::set_filter_parameters(int channel, int index, bool enable, float TC, float gain, float sample_rate ) +void iio_manager::set_filter_parameters(int channel, int index, bool enable, float TC, float gain, float sample_rate) { freq_comp_filt[channel][index]->set_enable(enable); freq_comp_filt[channel][index]->set_TC(TC); @@ -237,18 +233,17 @@ void iio_manager::stop(iio_manager::port_id copy) std::unique_lock lock(copy_mutex); bool inuse = false; - if (!_started || !copy->enabled()) + if(!_started || !copy->enabled()) return; qDebug(CAT_M2K_IIO_MANAGER) << "Disabling copy block" << copy->alias().c_str(); copy->set_enabled(false); /* Verify whether all blocks are disabled */ - for (auto it = copy_blocks.cbegin(); - !inuse && it != copy_blocks.cend(); ++it) + for(auto it = copy_blocks.cbegin(); !inuse && it != copy_blocks.cend(); ++it) inuse = it->first->enabled(); - if (!inuse) { + if(!inuse) { qDebug(CAT_M2K_IIO_MANAGER) << "Stopping top block"; top_block::stop(); top_block::wait(); @@ -261,12 +256,11 @@ void iio_manager::stop(iio_manager::port_id copy) void iio_manager::stop_all() { - for (auto it = copy_blocks.begin(); it != copy_blocks.end(); ++it) + for(auto it = copy_blocks.begin(); it != copy_blocks.end(); ++it) stop(it->first); } -void iio_manager::connect(gr::basic_block_sptr src, int src_port, - gr::basic_block_sptr dst, int dst_port) +void iio_manager::connect(gr::basic_block_sptr src, int src_port, gr::basic_block_sptr dst, int dst_port) { struct connection entry; entry.src = src; @@ -278,13 +272,10 @@ void iio_manager::connect(gr::basic_block_sptr src, int src_port, hier_block2::connect(src, src_port, dst, dst_port); } -void iio_manager::disconnect(basic_block_sptr src, int src_port, - basic_block_sptr dst, int dst_port) +void iio_manager::disconnect(basic_block_sptr src, int src_port, basic_block_sptr dst, int dst_port) { - for (auto it = connections.begin(); it != connections.end(); ++it) { - if (it->src == src && it->dst == dst && - it->src_port == src_port && - it->dst_port == dst_port) { + for(auto it = connections.begin(); it != connections.end(); ++it) { + if(it->src == src && it->dst == dst && it->src_port == src_port && it->dst_port == dst_port) { connections.erase(it); break; } @@ -300,37 +291,33 @@ void iio_manager::del_connection(gr::basic_block_sptr block, bool reverse) do { found = false; - for (auto it = connections.begin(); - it != connections.end(); ++it) { - if (reverse) { - if (block != it->dst || it->src == freq_comp_filt[0][1] || it->src == freq_comp_filt[1][1]) + for(auto it = connections.begin(); it != connections.end(); ++it) { + if(reverse) { + if(block != it->dst || it->src == freq_comp_filt[0][1] || + it->src == freq_comp_filt[1][1]) continue; - } else if (block != it->src) { + } else if(block != it->src) { continue; } - qDebug(CAT_M2K_IIO_MANAGER) << "Removing" << - (reverse ? "backwards" : "forward") - << "connection between" - << it->src->alias().c_str() - << "port" << it->src_port << "and" - << it->dst->alias().c_str() - << "port" << it->dst_port; - hier_block2::disconnect(it->src, it->src_port, - it->dst, it->dst_port); + qDebug(CAT_M2K_IIO_MANAGER) + << "Removing" << (reverse ? "backwards" : "forward") << "connection between" + << it->src->alias().c_str() << "port" << it->src_port << "and" + << it->dst->alias().c_str() << "port" << it->dst_port; + hier_block2::disconnect(it->src, it->src_port, it->dst, it->dst_port); auto src = it->src, dst = it->dst; connections.erase(it); - if (reverse) + if(reverse) del_connection(src, true); else del_connection(dst, true); found = true; break; } - } while (found); + } while(found); - if (reverse) + if(reverse) del_connection(block, false); } @@ -338,8 +325,8 @@ void iio_manager::set_buffer_size(iio_manager::port_id copy, unsigned long size) { std::unique_lock lock(copy_mutex); - for (auto it = copy_blocks.begin(); it != copy_blocks.end(); ++it) { - if (it->first == copy) { + for(auto it = copy_blocks.begin(); it != copy_blocks.end(); ++it) { + if(it->first == copy) { it->second = size; break; } @@ -348,24 +335,20 @@ void iio_manager::set_buffer_size(iio_manager::port_id copy, unsigned long size) update_buffer_size_unlocked(); } -void iio_manager::got_timeout() -{ - Q_EMIT timeout(); -} +void iio_manager::got_timeout() { Q_EMIT timeout(); } void iio_manager::set_device_timeout(unsigned int mseconds) { iio_block->set_timeout_ms(mseconds); - if (m_mixed_source) { + if(m_mixed_source) { m_mixed_source->set_timeout_ms(mseconds); } } -void iio_manager::set_data_rate(double rate) { - iio_block->set_data_rate(rate); -} +void iio_manager::set_data_rate(double rate) { iio_block->set_data_rate(rate); } -void iio_manager::set_kernel_buffer_count(int kb) { +void iio_manager::set_kernel_buffer_count(int kb) +{ if(kb) { m_analogin->setKernelBuffersCount(kb); } else { @@ -375,7 +358,7 @@ void iio_manager::set_kernel_buffer_count(int kb) { void iio_manager::enableMixedSignal(gr::m2k::mixed_signal_source::sptr mixed_source) { - for (size_t i = 0; i < nb_channels; ++i) { + for(size_t i = 0; i < nb_channels; ++i) { hier_block2::disconnect(iio_block, i, freq_comp_filt[i][0], 0); hier_block2::connect(mixed_source, i, freq_comp_filt[i][0], 0); } @@ -388,7 +371,7 @@ void iio_manager::enableMixedSignal(gr::m2k::mixed_signal_source::sptr mixed_sou void iio_manager::disableMixedSignal(gr::m2k::mixed_signal_source::sptr mixed_source) { - for (size_t i = 0; i < nb_channels; ++i) { + for(size_t i = 0; i < nb_channels; ++i) { hier_block2::disconnect(mixed_source, i, freq_comp_filt[i][0], 0); hier_block2::connect(iio_block, i, freq_comp_filt[i][0], 0); } @@ -399,7 +382,7 @@ void iio_manager::disableMixedSignal(gr::m2k::mixed_signal_source::sptr mixed_so m_mixed_source = nullptr; try { m_analogin->setKernelBuffersCount(KERNEL_BUFFERS_DEFAULT); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { qDebug() << e.what(); } } diff --git a/plugins/m2k/src/old/iio_manager.hpp b/plugins/m2k/src/old/iio_manager.hpp index 20ce035bc7..639309613a 100644 --- a/plugins/m2k/src/old/iio_manager.hpp +++ b/plugins/m2k/src/old/iio_manager.hpp @@ -21,33 +21,29 @@ #ifndef IIO_MANAGER_HPP #define IIO_MANAGER_HPP -#include +#include "timeout_block.hpp" -#include -#include #include #include +#include #include +#include +#include -#include +#include -#include -#include +#include #include +#include #include - -#include - +#include #include -#include "timeout_block.hpp" - /* 1k samples by default */ #define IIO_BUFFER_SIZE 0x400 namespace scopy::m2k { - class iio_manager : public QObject, public gr::top_block { Q_OBJECT @@ -57,29 +53,24 @@ class iio_manager : public QObject, public gr::top_block typedef gr::blocks::copy::sptr port_id; const unsigned id; - iio_manager(unsigned int id, struct iio_context *ctx, - QString dev, - unsigned long buffer_size); + iio_manager(unsigned int id, struct iio_context *ctx, QString dev, unsigned long buffer_size); ~iio_manager(); /* Connect a block to one of the channels of the IIO source. - * This function returns the ID, that can later be used with - * start() and stop(). - * Warning: the flowgraph needs to be locked first! */ - port_id connect(gr::basic_block_sptr dst, int src_port, - int dst_port, bool use_float = false, + * This function returns the ID, that can later be used with + * start() and stop(). + * Warning: the flowgraph needs to be locked first! */ + port_id connect(gr::basic_block_sptr dst, int src_port, int dst_port, bool use_float = false, unsigned long buffer_size = IIO_BUFFER_SIZE); /* Connect two regular blocks between themselves. */ - void connect(gr::basic_block_sptr src, int src_port, - gr::basic_block_sptr dst, int dst_port); + void connect(gr::basic_block_sptr src, int src_port, gr::basic_block_sptr dst, int dst_port); /* Disconnect the whole tree of blocks connected to this port ID */ void disconnect(port_id id); /* Disconnect two regular blocks. */ - void disconnect(gr::basic_block_sptr src, int src_port, - gr::basic_block_sptr dst, int dst_port); + void disconnect(gr::basic_block_sptr src, int src_port, gr::basic_block_sptr dst, int dst_port); /* Start feeding data to the client connected at [port, id] */ void start(port_id id); @@ -94,9 +85,9 @@ class iio_manager : public QObject, public gr::top_block bool started() { return _started; } /* Change the buffer size at runtime. - * Warning: the flowgraph needs to be locked first! */ + * Warning: the flowgraph needs to be locked first! */ void set_buffer_size(port_id id, unsigned long size); - void set_filter_parameters(int channel, int index, bool enable, float TC, float gain, float sample_rate ); + void set_filter_parameters(int channel, int index, bool enable, float TC, float gain, float sample_rate); void set_data_rate(double rate); void set_kernel_buffer_count(int kb = 0); @@ -105,7 +96,8 @@ class iio_manager : public QObject, public gr::top_block * are not properly routed to the blocks connected during the * reconfiguration. So until GNU Radio gets fixed, we just force * the whole flowgraph to stop when connecting new blocks. */ - void lock() { + void lock() + { gr::top_block::stop(); // cancel acquisition, work might be blocked waiting for a trigger // and the timeout. Don't wait for it just cancel the acquisition @@ -119,9 +111,11 @@ class iio_manager : public QObject, public gr::top_block gr::top_block::wait(); } - void unlock() { + void unlock() + { // m_context->startMixedSignalAcquisition(buffer_size); - gr::top_block::start(); } + gr::top_block::start(); + } /* Set the timeout for the source device */ void set_device_timeout(unsigned int mseconds); @@ -145,7 +139,7 @@ class iio_manager : public QObject, public gr::top_block unsigned long buffer_size; std::vector buffer_sizes; - std::vector > copy_blocks; + std::vector> copy_blocks; gr::m2k::analog_in_source::sptr iio_block; unsigned int nb_channels; @@ -153,7 +147,8 @@ class iio_manager : public QObject, public gr::top_block std::shared_ptr timeout_b; gr::m2k::mixed_signal_source::sptr m_mixed_source; - struct connection { + struct connection + { gr::basic_block_sptr src; gr::basic_block_sptr dst; int src_port, dst_port; @@ -171,8 +166,8 @@ private Q_SLOTS: void timeout(); }; - -class m2k_iio_manager { +class m2k_iio_manager +{ public: m2k_iio_manager() {} ~m2k_iio_manager() {} @@ -185,17 +180,14 @@ class m2k_iio_manager { /* Get a shared pointer to the instance of iio_manager that * manages the requested device */ - std::shared_ptr get_instance( - struct iio_context *ctx, - QString dev, - unsigned long buffer_size = IIO_BUFFER_SIZE); + std::shared_ptr get_instance(struct iio_context *ctx, QString dev, + unsigned long buffer_size = IIO_BUFFER_SIZE); private: std::map dev_map; unsigned _id; }; - -} +} // namespace scopy::m2k #endif /* IIO_MANAGER_HPP */ diff --git a/plugins/m2k/src/old/logic_analyzer_sink.h b/plugins/m2k/src/old/logic_analyzer_sink.h index 3cdffa45ef..ff5a0285dd 100644 --- a/plugins/m2k/src/old/logic_analyzer_sink.h +++ b/plugins/m2k/src/old/logic_analyzer_sink.h @@ -1,10 +1,10 @@ #ifndef LOGIC_ANALYZER_SINK_H #define LOGIC_ANALYZER_SINK_H -#include - #include "logicanalyzer/logic_analyzer.h" +#include + class logic_analyzer_sink : virtual public gr::sync_block { public: diff --git a/plugins/m2k/src/old/logic_analyzer_sink_impl.cpp b/plugins/m2k/src/old/logic_analyzer_sink_impl.cpp index 85405c899f..ab417e19bd 100644 --- a/plugins/m2k/src/old/logic_analyzer_sink_impl.cpp +++ b/plugins/m2k/src/old/logic_analyzer_sink_impl.cpp @@ -6,18 +6,13 @@ using namespace gr; -logic_analyzer_sink::sptr logic_analyzer_sink::make(scopy::m2k::logic::LogicAnalyzer *logicAnalyzer, - int bufferSize) +logic_analyzer_sink::sptr logic_analyzer_sink::make(scopy::m2k::logic::LogicAnalyzer *logicAnalyzer, int bufferSize) { - return gnuradio::get_initial_sptr( - new logic_analyzer_sink_impl(logicAnalyzer, bufferSize)); + return gnuradio::get_initial_sptr(new logic_analyzer_sink_impl(logicAnalyzer, bufferSize)); } -logic_analyzer_sink_impl::logic_analyzer_sink_impl(scopy::m2k::logic::LogicAnalyzer *logicAnalyzer, - int bufferSize) - : sync_block("logic_analyzer_sync", - io_signature::make(1, 1, sizeof(uint16_t)), - io_signature::make(0, 0, 0)) +logic_analyzer_sink_impl::logic_analyzer_sink_impl(scopy::m2k::logic::LogicAnalyzer *logicAnalyzer, int bufferSize) + : sync_block("logic_analyzer_sync", io_signature::make(1, 1, sizeof(uint16_t)), io_signature::make(0, 0, 0)) , d_logic_analyzer(logicAnalyzer) , d_buffer(nullptr) , d_buffer_temp(nullptr) @@ -25,26 +20,24 @@ logic_analyzer_sink_impl::logic_analyzer_sink_impl(scopy::m2k::logic::LogicAnaly , d_buffer_size(2 * bufferSize) , d_index(0) , d_end(d_size) - , d_tags(std::vector< std::vector >(1)) + , d_tags(std::vector>(1)) , d_trigger_tag_key(pmt::intern("buffer_start")) , d_triggered(false) , d_update_time(0.1 * gr::high_res_timer_tps()) , d_last_time(0) { - d_buffer = (uint16_t*)volk_malloc(d_buffer_size * sizeof(uint16_t), volk_get_alignment()); + d_buffer = (uint16_t *)volk_malloc(d_buffer_size * sizeof(uint16_t), volk_get_alignment()); memset(d_buffer, 0, sizeof(uint16_t) * d_buffer_size); - d_buffer_temp = (uint16_t*)volk_malloc(d_buffer_size * sizeof(uint16_t), volk_get_alignment()); + d_buffer_temp = (uint16_t *)volk_malloc(d_buffer_size * sizeof(uint16_t), volk_get_alignment()); memset(d_buffer_temp, 0, sizeof(uint16_t) * d_buffer_size); - const int alignment_multiple = - volk_get_alignment() / sizeof(uint16_t); - set_alignment(std::max(1,alignment_multiple)); + const int alignment_multiple = volk_get_alignment() / sizeof(uint16_t); + set_alignment(std::max(1, alignment_multiple)); } -int logic_analyzer_sink_impl::work(int noutput_items, - gr_vector_const_void_star &input_items, +int logic_analyzer_sink_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock lock(d_setlock); @@ -72,8 +65,8 @@ int logic_analyzer_sink_impl::work(int noutput_items, d_index += nitems; - if (d_triggered && (d_index == d_end) && d_end != 0) { - if (gr::high_res_timer_now() - d_last_time > d_update_time) { + if(d_triggered && (d_index == d_end) && d_end != 0) { + if(gr::high_res_timer_now() - d_last_time > d_update_time) { d_last_time = gr::high_res_timer_now(); d_logic_analyzer->setData(d_buffer_temp + d_start, d_size); } @@ -81,7 +74,7 @@ int logic_analyzer_sink_impl::work(int noutput_items, _reset(); } - if (d_index == d_end) { + if(d_index == d_end) { _reset(); } @@ -95,11 +88,11 @@ void logic_analyzer_sink_impl::clean_buffers() d_buffer_size = 2 * d_size; volk_free(d_buffer); - d_buffer = (uint16_t*)volk_malloc(d_buffer_size * sizeof(uint16_t), volk_get_alignment()); + d_buffer = (uint16_t *)volk_malloc(d_buffer_size * sizeof(uint16_t), volk_get_alignment()); memset(d_buffer, 0, sizeof(uint16_t) * d_buffer_size); volk_free(d_buffer_temp); - d_buffer_temp = (uint16_t*)volk_malloc(d_buffer_size * sizeof(uint16_t), volk_get_alignment()); + d_buffer_temp = (uint16_t *)volk_malloc(d_buffer_size * sizeof(uint16_t), volk_get_alignment()); memset(d_buffer_temp, 0, sizeof(uint16_t) * d_buffer_size); _reset(); @@ -107,7 +100,7 @@ void logic_analyzer_sink_impl::clean_buffers() void logic_analyzer_sink_impl::set_nsamps(int newsize) { - if (newsize != d_size) { + if(newsize != d_size) { gr::thread::scoped_lock lock(d_setlock); // set new size @@ -119,9 +112,9 @@ void logic_analyzer_sink_impl::set_nsamps(int newsize) volk_free(d_buffer_temp); // create new buffers - d_buffer = (uint16_t*)volk_malloc(d_buffer_size * sizeof(uint16_t), volk_get_alignment()); + d_buffer = (uint16_t *)volk_malloc(d_buffer_size * sizeof(uint16_t), volk_get_alignment()); memset(d_buffer, 0, sizeof(uint16_t) * d_buffer_size); - d_buffer_temp = (uint16_t*)volk_malloc(d_buffer_size * sizeof(uint16_t), volk_get_alignment()); + d_buffer_temp = (uint16_t *)volk_malloc(d_buffer_size * sizeof(uint16_t), volk_get_alignment()); memset(d_buffer_temp, 0, sizeof(uint16_t) * d_buffer_size); _reset(); @@ -132,7 +125,7 @@ void logic_analyzer_sink_impl::_adjust_tags(int adj) { for(size_t n = 0; n < d_tags.size(); n++) { for(size_t t = 0; t < d_tags[n].size(); t++) { - d_tags[n][t].offset += adj; + d_tags[n][t].offset += adj; } } } @@ -144,7 +137,7 @@ void logic_analyzer_sink_impl::_test_trigger_tags(int nitems) uint64_t nr = nitems_read(0); std::vector tags; get_tags_in_range(tags, 0, nr, nr + nitems + 1, d_trigger_tag_key); - if (tags.size() > 0) { + if(tags.size() > 0) { d_triggered = true; trigger_index = tags[0].offset - nr; d_start = d_index + trigger_index; diff --git a/plugins/m2k/src/old/logic_analyzer_sink_impl.h b/plugins/m2k/src/old/logic_analyzer_sink_impl.h index e642bff21f..09f37ae306 100644 --- a/plugins/m2k/src/old/logic_analyzer_sink_impl.h +++ b/plugins/m2k/src/old/logic_analyzer_sink_impl.h @@ -8,9 +8,7 @@ class logic_analyzer_sink_impl : public logic_analyzer_sink public: logic_analyzer_sink_impl(scopy::m2k::logic::LogicAnalyzer *logicAnalyzer, int bufferSize); - int work(int noutput_items, - gr_vector_const_void_star &input_items, - gr_vector_void_star &output_items); + int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); void clean_buffers(); void set_nsamps(int newsize); @@ -30,7 +28,7 @@ class logic_analyzer_sink_impl : public logic_analyzer_sink int d_end; int d_start; - std::vector< std::vector > d_tags; + std::vector> d_tags; pmt::pmt_t d_trigger_tag_key; bool d_triggered; diff --git a/plugins/m2k/src/old/logicanalyzer/decoder_table.cpp b/plugins/m2k/src/old/logicanalyzer/decoder_table.cpp index 022be18a11..89bdf3ee0f 100644 --- a/plugins/m2k/src/old/logicanalyzer/decoder_table.cpp +++ b/plugins/m2k/src/old/logicanalyzer/decoder_table.cpp @@ -18,23 +18,24 @@ * along with this program. If not, see . */ #include "decoder_table.hpp" -#include "decoder_table_model.hpp" + #include "decoder_table_item.hpp" +#include "decoder_table_model.hpp" +#include "filemanager.h" +#include "logic_analyzer.h" +#include "qtconcurrentrun.h" + #include #include #include #include -#include "logic_analyzer.h" -#include "filemanager.h" -#include "qtconcurrentrun.h" namespace scopy::m2k { - namespace logic { - -DecoderTable::DecoderTable(QWidget *parent) : QTableView(parent) +DecoderTable::DecoderTable(QWidget *parent) + : QTableView(parent) { setItemDelegate(new DecoderTableItemDelegate); @@ -51,11 +52,11 @@ DecoderTable::DecoderTable(QWidget *parent) : QTableView(parent) installEventFilter(this); } -bool DecoderTable::eventFilter(QObject* object, QEvent* event) +bool DecoderTable::eventFilter(QObject *object, QEvent *event) { // prevent user from swiping through columns using touchscreen - if (event->type() == QEvent::Paint && tableModel->getCurrentColumn() != horizontalScrollBar()->value()) { + if(event->type() == QEvent::Paint && tableModel->getCurrentColumn() != horizontalScrollBar()->value()) { horizontalScrollBar()->setValue(tableModel->getCurrentColumn()); return true; } @@ -64,9 +65,9 @@ bool DecoderTable::eventFilter(QObject* object, QEvent* event) void DecoderTable::setLogicAnalyzer(LogicAnalyzer *logicAnalyzer) { - if (logicAnalyzer != nullptr) { - if (const auto oldDecoderModel = dynamic_cast(model())) { - if (oldDecoderModel != nullptr) { + if(logicAnalyzer != nullptr) { + if(const auto oldDecoderModel = dynamic_cast(model())) { + if(oldDecoderModel != nullptr) { delete oldDecoderModel; } } @@ -84,10 +85,7 @@ QVector DecoderTable::getDecoderCruves() return temp_curves; } -DecoderTableModel* DecoderTable::decoderModel() const -{ - return dynamic_cast(model()); -} +DecoderTableModel *DecoderTable::decoderModel() const { return dynamic_cast(model()); } void DecoderTable::exportData() { @@ -97,16 +95,15 @@ void DecoderTable::exportData() filter += QString(tr("Comma-separated row per sample (*.csv)")); filter += QString(tr("Tab-delimited row per annotation (*.txt)")); - QString fileName = QFileDialog::getSaveFileName(this, - tr("Export"), "", filter.join(";;"), - &selectedFilter, QFileDialog::DontUseNativeDialog); + QString fileName = QFileDialog::getSaveFileName(this, tr("Export"), "", filter.join(";;"), &selectedFilter, + QFileDialog::DontUseNativeDialog); - if (fileName.isEmpty()) { + if(fileName.isEmpty()) { return; } // Check the selected file type - if (selectedFilter != "") { + if(selectedFilter != "") { if(selectedFilter.contains("comma", Qt::CaseInsensitive)) { fileType = "csv"; } @@ -115,7 +112,7 @@ void DecoderTable::exportData() } } - if (fileName.split(".").size() <= 1) { + if(fileName.split(".").size() <= 1) { // file name w/o extension. Let's append it QString ext = selectedFilter.split(".")[1].split(")")[0]; fileName += "." + ext; @@ -124,16 +121,14 @@ void DecoderTable::exportData() m_logicAnalyzer->setStatusLabel("Exporting ..."); QFuture future; - if (fileType == "csv") { + if(fileType == "csv") { future = QtConcurrent::run(this, &DecoderTable::exportCsv, fileName); - } else if (fileType == "txt") { + } else if(fileType == "txt") { future = QtConcurrent::run(this, &DecoderTable::exportTxt, fileName); } QFutureWatcher *watcher = new QFutureWatcher(this); - connect(watcher, &QFutureWatcher::finished, this, [=](){ - m_logicAnalyzer->setStatusLabel(""); - }); + connect(watcher, &QFutureWatcher::finished, this, [=]() { m_logicAnalyzer->setStatusLabel(""); }); connect(watcher, SIGNAL(finished()), watcher, SLOT(deleteLater())); watcher->setFuture(future); } @@ -147,21 +142,21 @@ QVector> DecoderTable::getSearchSampleMask() vector row; QVector> sampleMask; - for (const auto &row_map : decoder) { - if (row_map.first.index() == tableModel->getPrimaryAnnotationIndex()) { + for(const auto &row_map : decoder) { + if(row_map.first.index() == tableModel->getPrimaryAnnotationIndex()) { row = row_map.second.get_annotations(); break; } } - for (auto index: tableModel->getSearchMask()) { + for(auto index : tableModel->getSearchMask()) { int size = m_logicAnalyzer->getGroupSize(); int off = (m_logicAnalyzer->getGroupOffset() == 0) ? size : m_logicAnalyzer->getGroupOffset(); int start_ann = (index == 0) ? 0 : off + size * (index - 1); int end_ann = std::min(uint64_t(off + size * (index)) - 1, uint64_t(row.size() - 1)); - if (off == 0) { + if(off == 0) { start_ann--; end_ann--; } @@ -183,13 +178,16 @@ bool DecoderTable::exportTxt(QString fileName) // set decoder data std::map::iterator it; - for (it = decoder.begin(); it != decoder.end(); it++) { + for(it = decoder.begin(); it != decoder.end(); it++) { auto annotations = it->second.get_annotations(); QString title = curve->fromTitleToRowType(it->first.title()); - if (tableModel->getFiltered().value(tableModel->getCurrentColumn()).contains(title)) continue; + if(tableModel->getFiltered().value(tableModel->getCurrentColumn()).contains(title)) + continue; - for (const auto &ann : annotations) { - QVector str = {QString::number(ann.start_sample()) + "-" + QString::number(ann.end_sample()), ann.row()->title(), ann.annotations()[0]}; + for(const auto &ann : annotations) { + QVector str = {QString::number(ann.start_sample()) + "-" + + QString::number(ann.end_sample()), + ann.row()->title(), ann.annotations()[0]}; decoder_data.append(str); } } @@ -214,7 +212,7 @@ bool DecoderTable::exportCsv(QString fileName) QVector> decoder_data; AnnotationCurve *curve = dynamic_cast(getDecoderCruves().at(col)); std::map decoder(curve->getAnnotationRows()); - QRegExp rx = QRegExp(tableModel->getsearchString(), Qt::CaseInsensitive); + QRegExp rx = QRegExp(tableModel->getsearchString(), Qt::CaseInsensitive); int row_count = 0; int primaryCol = 0; @@ -222,12 +220,12 @@ bool DecoderTable::exportCsv(QString fileName) // set column names columnNames += "Time"; - for (it = decoder.begin(); it != decoder.end(); it++) { + for(it = decoder.begin(); it != decoder.end(); it++) { last_sample = std::max(last_sample, it->second.get_max_sample()); auto title = curve->fromTitleToRowType(it->first.title()); - if (!it->second.get_annotations().empty() && !tableModel->getFiltered()[col].contains(title)) { - if (it->first.index() == tableModel->getPrimaryAnnotationIndex()) { + if(!it->second.get_annotations().empty() && !tableModel->getFiltered()[col].contains(title)) { + if(it->first.index() == tableModel->getPrimaryAnnotationIndex()) { primaryCol = columnNames.size(); } columnNames += it->first.title(); @@ -236,43 +234,45 @@ bool DecoderTable::exportCsv(QString fileName) // initialize decoder_data QVector aux; - for (uint64_t i = 0; i < last_sample; i++) { + for(uint64_t i = 0; i < last_sample; i++) { aux = QVector(); - for (uint64_t j = 0; j < columnNames.count(); j++) { + for(uint64_t j = 0; j < columnNames.count(); j++) { aux.append(""); } decoder_data.append(aux); } // set time - for (int i = 0; i < last_sample; i++) { - decoder_data[i][0] = QString::fromStdString(std::to_string(curve->fromSampleToTime(i))).replace(",", "."); + for(int i = 0; i < last_sample; i++) { + decoder_data[i][0] = + QString::fromStdString(std::to_string(curve->fromSampleToTime(i))).replace(",", "."); } // populate decoder_data - for (it = decoder.begin(); it != decoder.end(); it++) { + for(it = decoder.begin(); it != decoder.end(); it++) { auto row = it->second.get_annotations(); auto title = curve->fromTitleToRowType(it->first.title()); - if (tableModel->getFiltered()[col].contains(title) || row.empty()) continue; + if(tableModel->getFiltered()[col].contains(title) || row.empty()) + continue; row_count++; - for (unsigned int ann_index = 0; ann_index < row.size(); ann_index++) { - for (uint64_t i = row[ann_index].start_sample(); i < row[ann_index].end_sample(); i++) { + for(unsigned int ann_index = 0; ann_index < row.size(); ann_index++) { + for(uint64_t i = row[ann_index].start_sample(); i < row[ann_index].end_sample(); i++) { decoder_data[i][row_count] = row[ann_index].annotations()[0]; } } } // apply search - for (uint64_t i = 0; i < last_sample; i++) { - if (decoder_data[i][primaryCol] == "") { + for(uint64_t i = 0; i < last_sample; i++) { + if(decoder_data[i][primaryCol] == "") { decoder_data[i] = QVector(); } } - for (auto sample_range: sampleMask) { - for (uint64_t i = sample_range.first; i <= sample_range.second; i++) { - if (i < last_sample) - decoder_data[i] = QVector(); + for(auto sample_range : sampleMask) { + for(uint64_t i = sample_range.first; i <= sample_range.second; i++) { + if(i < last_sample) + decoder_data[i] = QVector(); } } @@ -286,21 +286,15 @@ bool DecoderTable::exportCsv(QString fileName) void DecoderTable::activate(bool logic) { setLogicAnalyzer(m_logicAnalyzer); - if (const auto m = decoderModel()) { + if(const auto m = decoderModel()) { m->reloadDecoders(logic); m_active = true; } } -void DecoderTable::deactivate() -{ - m_active = false; -} +void DecoderTable::deactivate() { m_active = false; } -void DecoderTable::showEvent(QShowEvent *event) -{ - tableModel->to_be_refreshed = true; -} +void DecoderTable::showEvent(QShowEvent *event) { tableModel->to_be_refreshed = true; } void DecoderTable::groupValuesChanged(int value) { @@ -308,5 +302,4 @@ void DecoderTable::groupValuesChanged(int value) tableModel->to_be_refreshed = true; } } // namespace logic -} // namespace scopy - +} // namespace scopy::m2k diff --git a/plugins/m2k/src/old/logicanalyzer/decoder_table.hpp b/plugins/m2k/src/old/logicanalyzer/decoder_table.hpp index 2aad5885c4..e1cf5fb35c 100644 --- a/plugins/m2k/src/old/logicanalyzer/decoder_table.hpp +++ b/plugins/m2k/src/old/logicanalyzer/decoder_table.hpp @@ -21,52 +21,53 @@ #ifndef DECODER_TABLE_H #define DECODER_TABLE_H -#include -#include #include "decoder.h" #include "decoder_table_item.hpp" #include "logic_analyzer.h" -namespace scopy::m2k { +#include +#include +namespace scopy::m2k { namespace logic { class DecoderTableModel; -class DecoderTable : public QTableView { - Q_OBJECT +class DecoderTable : public QTableView +{ + Q_OBJECT public: - DecoderTable(QWidget *parent = nullptr); + DecoderTable(QWidget *parent = nullptr); - void setLogicAnalyzer(LogicAnalyzer* logicAnalyzer); - void activate(bool logic); - void deactivate(); - QVector getDecoderCruves(); - inline bool isActive() const { return m_active; } + void setLogicAnalyzer(LogicAnalyzer *logicAnalyzer); + void activate(bool logic); + void deactivate(); + QVector getDecoderCruves(); + inline bool isActive() const { return m_active; } - // Shortcut to get a reference to the model. - DecoderTableModel* decoderModel() const; - bool eventFilter(QObject *object, QEvent *event); + // Shortcut to get a reference to the model. + DecoderTableModel *decoderModel() const; + bool eventFilter(QObject *object, QEvent *event); public Q_SLOTS: - void groupValuesChanged(int value); - void exportData(); + void groupValuesChanged(int value); + void exportData(); private: - bool m_active; - DecoderTableModel* tableModel; - LogicAnalyzer* m_logicAnalyzer; - QVector *temp_curves; - bool exportCsv(QString fileName); - bool exportTxt(QString fileName); - QVector > getSearchSampleMask(); + bool m_active; + DecoderTableModel *tableModel; + LogicAnalyzer *m_logicAnalyzer; + QVector *temp_curves; + bool exportCsv(QString fileName); + bool exportTxt(QString fileName); + QVector> getSearchSampleMask(); protected: - void showEvent(QShowEvent *event); + void showEvent(QShowEvent *event); }; } // namespace logic -} // namespace scopy +} // namespace scopy::m2k #endif // DECODER_TABLE_H diff --git a/plugins/m2k/src/old/logicanalyzer/decoder_table_item.cpp b/plugins/m2k/src/old/logicanalyzer/decoder_table_item.cpp index 8fd276d610..7c102daf94 100644 --- a/plugins/m2k/src/old/logicanalyzer/decoder_table_item.cpp +++ b/plugins/m2k/src/old/logicanalyzer/decoder_table_item.cpp @@ -18,25 +18,22 @@ * along with this program. If not, see . */ #include "decoder_table_item.hpp" + +#include #include #include #include -#include #include namespace scopy::m2k { - namespace logic { - -void DecoderTableItemDelegate::paint( - QPainter *painter, - const QStyleOptionViewItem &option, - const QModelIndex &index - ) const { +void DecoderTableItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const +{ auto data = index.data(); - if (data.canConvert()) { + if(data.canConvert()) { DecoderTableItem decoderItem = qvariant_cast(data); decoderItem.paint(painter, option.rect, option.palette); } else { @@ -44,51 +41,42 @@ void DecoderTableItemDelegate::paint( } } - - -QSize DecoderTableItemDelegate::sizeHint( - const QStyleOptionViewItem &option, - const QModelIndex &index - ) const { - if (index.data().canConvert()) { +QSize DecoderTableItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const +{ + if(index.data().canConvert()) { DecoderTableItem decoderItem = qvariant_cast(index.data()); return decoderItem.sizeHint(); } return QStyledItemDelegate::sizeHint(option, index); } - -DecoderTableItem::DecoderTableItem(AnnotationCurve *curve, uint64_t start, uint64_t end, QVector filter, bool flag): - curve(curve), - startSample(start), - endSample(end), - filteredMessages(filter), - tableInfoFlag(flag) -{ - -} +DecoderTableItem::DecoderTableItem(AnnotationCurve *curve, uint64_t start, uint64_t end, QVector filter, + bool flag) + : curve(curve) + , startSample(start) + , endSample(end) + , filteredMessages(filter) + , tableInfoFlag(flag) +{} double DecoderTableItem::startTime() const { - if (curve != nullptr) + if(curve != nullptr) return curve->fromSampleToTime(startSample); return 0; } double DecoderTableItem::endTime() const { - if (curve != nullptr) + if(curve != nullptr) return curve->fromSampleToTime(endSample); return 0; } -void DecoderTableItem::paint( - QPainter *painter, - const QRect &rect, - const QPalette &palette - ) const { +void DecoderTableItem::paint(QPainter *painter, const QRect &rect, const QPalette &palette) const +{ - if (curve == nullptr){ + if(curve == nullptr) { return; } painter->save(); @@ -101,7 +89,7 @@ void DecoderTableItem::paint( QwtScaleMap xmap, ymap; xmap.setPaintInterval(0, rect.width()); - if (tableInfoFlag) { + if(tableInfoFlag) { ymap.setPaintInterval(4 + curve->m_infoHeight, rect.height()); } else { ymap.setPaintInterval(4, rect.height()); @@ -109,18 +97,18 @@ void DecoderTableItem::paint( // qDebug() << "rect: " << rect << Qt::endl; QwtPointMapper mapper; - mapper.setFlag( QwtPointMapper::RoundPoints, QwtPainter::roundingAlignment( painter ) ); + mapper.setFlag(QwtPointMapper::RoundPoints, QwtPainter::roundingAlignment(painter)); // mapper.setBoundingRect(rect); // Seems to have no effect? // Scale the annotation to fit in the column const double lower = startTime(); const double upper = endTime(); double padding = (upper - lower) * 0.05; - if (padding == 0) { + if(padding == 0) { padding = 0.0001; } - const QwtInterval interval = QwtInterval(lower-padding, upper+padding); + const QwtInterval interval = QwtInterval(lower - padding, upper + padding); xmap.setScaleInterval(interval.minValue(), interval.maxValue()); // Shift curve offset to 0 and block any signals while doing it since the @@ -137,33 +125,32 @@ void DecoderTableItem::paint( // Draw all annotations in the sample range int offset = 0; // TODO: This does not retain the original order - if (curve->getAnnotationRows().size() == 0) { + if(curve->getAnnotationRows().size() == 0) { return; } - if (tableInfoFlag) { + if(tableInfoFlag) { curve->drawAnnotationInfo(offset, startSample, endSample, painter, xmap, ymap, rect); } - for (int row = 0; row < curve->getAnnotationRows().size(); ++row) { - auto entry = *std::find_if(curve->getAnnotationRows().begin(), curve->getAnnotationRows().end(), - [row](const std::pair &t) -> bool{ - return t.first.index() == row; - }); + for(int row = 0; row < curve->getAnnotationRows().size(); ++row) { + auto entry = *std::find_if( + curve->getAnnotationRows().begin(), curve->getAnnotationRows().end(), + [row](const std::pair &t) -> bool { return t.first.index() == row; }); const RowData &data = entry.second; - if (filteredMessages.contains(curve->fromTitleToRowType(entry.first.title()))) continue; - if (data.size() == 0) continue; + if(filteredMessages.contains(curve->fromTitleToRowType(entry.first.title()))) + continue; + if(data.size() == 0) + continue; vector range; - if (startSample == 0) { + if(startSample == 0) { data.get_annotation_subset(range, startSample, endSample); } else { data.get_annotation_subset(range, startSample - 1, endSample); } - for (const auto &ann : range) { - curve->drawAnnotation( - offset, ann, painter, xmap, ymap, rect, mapper, - interval, titleSize); + for(const auto &ann : range) { + curve->drawAnnotation(offset, ann, painter, xmap, ymap, rect, mapper, interval, titleSize); } offset += 1; } @@ -174,13 +161,7 @@ void DecoderTableItem::paint( painter->restore(); } -QSize DecoderTableItem::sizeHint() const -{ - return itemSize; -} - - +QSize DecoderTableItem::sizeHint() const { return itemSize; } } // namespace logic -} // namespace scopy - +} // namespace scopy::m2k diff --git a/plugins/m2k/src/old/logicanalyzer/decoder_table_item.hpp b/plugins/m2k/src/old/logicanalyzer/decoder_table_item.hpp index edfeae0b03..4740e7f278 100644 --- a/plugins/m2k/src/old/logicanalyzer/decoder_table_item.hpp +++ b/plugins/m2k/src/old/logicanalyzer/decoder_table_item.hpp @@ -21,65 +21,53 @@ #define DECODER_TABLE_ITEM_H #include "annotationcurve.h" -#include + #include #include +#include namespace scopy::m2k { namespace logic { - -class DecoderTableItemDelegate : public QStyledItemDelegate { - Q_OBJECT +class DecoderTableItemDelegate : public QStyledItemDelegate +{ + Q_OBJECT public: - using QStyledItemDelegate::QStyledItemDelegate; - virtual ~DecoderTableItemDelegate() {}; + using QStyledItemDelegate::QStyledItemDelegate; + virtual ~DecoderTableItemDelegate(){}; - void paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index) const override; - QSize sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const override; + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; }; - - -class DecoderTableItem { +class DecoderTableItem +{ public: + explicit DecoderTableItem(AnnotationCurve *curve = nullptr, uint64_t start = 0, uint64_t end = 0, + QVector filter = QVector(), bool flag = true); - explicit DecoderTableItem( - AnnotationCurve* curve=nullptr, - uint64_t start=0, - uint64_t end=0, - QVector filter= QVector(), - bool flag=true - ); + void paint(QPainter *painter, const QRect &rect, const QPalette &palette) const; + QSize sizeHint() const; - void paint(QPainter *painter, const QRect &rect, const QPalette &palette) const; - QSize sizeHint() const; + double startTime() const; + double endTime() const; - double startTime() const; - double endTime() const; - - AnnotationCurve* curve; - uint64_t startSample; - uint64_t endSample; - QSize itemSize = QSize(300, 40); - QVector filteredMessages; - - bool tableInfoFlag; + AnnotationCurve *curve; + uint64_t startSample; + uint64_t endSample; + QSize itemSize = QSize(300, 40); + QVector filteredMessages; + bool tableInfoFlag; }; } // namespace logic -} // namespace scopy - +} // namespace scopy::m2k // This is needed so it can be stored as a QVariant Q_DECLARE_METATYPE(scopy::m2k::logic::DecoderTableItem) - - #endif // DECODER_TABLE_ITEM_H diff --git a/plugins/m2k/src/old/logicanalyzer/decoder_table_model.cpp b/plugins/m2k/src/old/logicanalyzer/decoder_table_model.cpp index 20592f38a7..b4688828b5 100644 --- a/plugins/m2k/src/old/logicanalyzer/decoder_table_model.cpp +++ b/plugins/m2k/src/old/logicanalyzer/decoder_table_model.cpp @@ -18,9 +18,11 @@ * along with this program. If not, see . */ #include "decoder_table_model.hpp" + #include "logic_analyzer.h" #include "qcombobox.h" #include "qtconcurrentrun.h" + #include #include #include @@ -29,13 +31,12 @@ namespace scopy::m2k { - namespace logic { -DecoderTableModel::DecoderTableModel(DecoderTable *decoderTable, LogicAnalyzer *logicAnalyzer): - QAbstractTableModel(decoderTable), - m_decoderTable(decoderTable), - m_logic(logicAnalyzer) +DecoderTableModel::DecoderTableModel(DecoderTable *decoderTable, LogicAnalyzer *logicAnalyzer) + : QAbstractTableModel(decoderTable) + , m_decoderTable(decoderTable) + , m_logic(logicAnalyzer) { m_plotCurves = m_logic->getPlotCurves(true); m_decoderTable->verticalHeader()->setMinimumSectionSize(1); @@ -46,14 +47,14 @@ DecoderTableModel::DecoderTableModel(DecoderTable *decoderTable, LogicAnalyzer * void DecoderTableModel::setDefaultPrimaryAnnotations() { - for (int i=DIGITAL_NR_CHANNELS; i::iterator it; AnnotationCurve *curve = dynamic_cast(m_plotCurves[i]); std::map decoder(curve->getAnnotationRows()); - for (it = decoder.begin(); it != decoder.end(); it++) { - if (!it->second.get_annotations().empty()) { + for(it = decoder.begin(); it != decoder.end(); it++) { + if(!it->second.get_annotations().empty()) { count = it->first.index(); break; } @@ -65,7 +66,7 @@ void DecoderTableModel::setDefaultPrimaryAnnotations() int DecoderTableModel::rowCount(const QModelIndex &parent) const { // Return max of all packets - if (!m_active) { + if(!m_active) { return 0; } @@ -75,7 +76,7 @@ int DecoderTableModel::rowCount(const QModelIndex &parent) const int DecoderTableModel::columnCount(const QModelIndex &parent) const { // One column per curve - if (!m_active) { + if(!m_active) { return 0; } return m_decoderTable->getDecoderCruves().size(); @@ -83,8 +84,9 @@ int DecoderTableModel::columnCount(const QModelIndex &parent) const int DecoderTableModel::indexOfCurve(const AnnotationCurve *curve) const { - for (size_t i=0; i < m_curves.size(); i++) { - if (m_curves[i] == curve) return i; + for(size_t i = 0; i < m_curves.size(); i++) { + if(m_curves[i] == curve) + return i; } return -1; } @@ -96,11 +98,14 @@ void DecoderTableModel::setPrimaryAnnotation(int index) m_primary_annoations->insert(m_current_column, index); m_decoderTable->reset(); - if(m_decoderTable->isActive() && m_curves.at(m_current_column)->getMaxAnnotationCount(index) != m_curves.at(m_current_column)->getMaxAnnotationCount(prev_index)) { + if(m_decoderTable->isActive() && + m_curves.at(m_current_column)->getMaxAnnotationCount(index) != + m_curves.at(m_current_column)->getMaxAnnotationCount(prev_index)) { refreshColumn(m_current_column); } - int max_value = m_curves.at(m_current_column)->getMaxAnnotationCount(m_primary_annoations->value(m_current_column)); + int max_value = + m_curves.at(m_current_column)->getMaxAnnotationCount(m_primary_annoations->value(m_current_column)); m_logic->setMaxGroupValues(max_value); } @@ -109,27 +114,20 @@ void DecoderTableModel::populateDecoderComboBox() const auto decoderComboBox = m_logic->getDecoderComboBox(); decoderComboBox->clear(); - for (const auto &curve: m_curves) { + for(const auto &curve : m_curves) { decoderComboBox->addItem(curve->getName()); } } +int DecoderTableModel::getCurrentColumn() const { return m_current_column; } -int DecoderTableModel::getCurrentColumn() const -{ - return m_current_column; -} - - -QMap>& DecoderTableModel::getFiltered() -{ - return m_filteredMessages; -} +QMap> &DecoderTableModel::getFiltered() { return m_filteredMessages; } void DecoderTableModel::setCurrentRow(int index) { - auto curve = dynamic_cast (m_plotCurves.at(m_current_column)); - if (index >= curve->getMaxAnnotationCount(m_primary_annoations->value((int) m_current_column))) return; + auto curve = dynamic_cast(m_plotCurves.at(m_current_column)); + if(index >= curve->getMaxAnnotationCount(m_primary_annoations->value((int)m_current_column))) + return; m_decoderTable->scrollTo(this->index(index, m_current_column), QAbstractItemView::PositionAtCenter); @@ -140,7 +138,7 @@ void DecoderTableModel::setMaxRowCount() { uint64_t count = 0; std::map decoder; - for (const auto &entry: m_decoderTable->getDecoderCruves()) { + for(const auto &entry : m_decoderTable->getDecoderCruves()) { const auto &curve = dynamic_cast(entry); count = std::max(count, curve->getMaxAnnotationCount()); } @@ -149,7 +147,7 @@ void DecoderTableModel::setMaxRowCount() void DecoderTableModel::refreshSettings(int column) { - if (column == -1) { + if(column == -1) { column = m_current_column; } beginResetModel(); @@ -167,20 +165,11 @@ void DecoderTableModel::refreshSettings(int column) endResetModel(); } -void DecoderTableModel::setSearchString(QString str) const -{ - searchString = str; -} +void DecoderTableModel::setSearchString(QString str) const { searchString = str; } -QVector DecoderTableModel::getSearchMask() -{ - return searchMask; -} +QVector DecoderTableModel::getSearchMask() { return searchMask; } -QString DecoderTableModel::getsearchString() -{ - return searchString; -} +QString DecoderTableModel::getsearchString() { return searchString; } void DecoderTableModel::reloadDecoders(bool logic) { @@ -188,14 +177,14 @@ void DecoderTableModel::reloadDecoders(bool logic) m_curves.clear(); // Reconnect signals for all the annotation curves - for (const auto &curve : qAsConst(m_plotCurves)) { - if (const auto annCurve = dynamic_cast(curve)) { + for(const auto &curve : qAsConst(m_plotCurves)) { + if(const auto annCurve = dynamic_cast(curve)) { m_curves.emplace_back(annCurve); } } m_filteredMessages.clear(); - for (int i=0; i()); } @@ -205,19 +194,20 @@ void DecoderTableModel::reloadDecoders(bool logic) void DecoderTableModel::refreshColumn(double column) const { - if (m_plotCurves.empty()) return; + if(m_plotCurves.empty()) + return; - if (column == -1) { + if(column == -1) { column = m_current_column; } - auto curve = dynamic_cast (m_plotCurves.at(column)); + auto curve = dynamic_cast(m_plotCurves.at(column)); const auto verticalHeader = m_decoderTable->verticalHeader(); - int index = curve->getMaxAnnotationCount(m_primary_annoations->value((int) column)); + int index = curve->getMaxAnnotationCount(m_primary_annoations->value((int)column)); // resize rows int spacing; - if (m_logic->getTableInfo()) { + if(m_logic->getTableInfo()) { spacing = 10 + curve->m_infoHeight; } else { spacing = 10; @@ -228,14 +218,14 @@ void DecoderTableModel::refreshColumn(double column) const std::map::iterator it; std::map decoder(curve->getAnnotationRows()); - for (it = decoder.begin(); it != decoder.end(); it++) { - if (!it->second.get_annotations().empty()) { - row_count ++; + for(it = decoder.begin(); it != decoder.end(); it++) { + if(!it->second.get_annotations().empty()) { + row_count++; } } auto new_height = rowHeight * (row_count - m_filteredMessages.value(column).size()) + spacing; - if (verticalHeader->minimumSectionSize() != new_height || verticalHeader->maximumSectionSize() != new_height) { + if(verticalHeader->minimumSectionSize() != new_height || verticalHeader->maximumSectionSize() != new_height) { verticalHeader->setMinimumSectionSize(new_height); verticalHeader->setDefaultSectionSize(new_height); verticalHeader->setMaximumSectionSize(new_height); @@ -243,20 +233,21 @@ void DecoderTableModel::refreshColumn(double column) const // hide/show rows bool no_rows = true; - int grouped_rows = (index - m_logic->getGroupOffset()) / m_logic->getGroupSize() + (m_logic->getGroupOffset() != 0); - if ((index - m_logic->getGroupOffset()) % m_logic->getGroupSize() != 0) { + int grouped_rows = + (index - m_logic->getGroupOffset()) / m_logic->getGroupSize() + (m_logic->getGroupOffset() != 0); + if((index - m_logic->getGroupOffset()) % m_logic->getGroupSize() != 0) { grouped_rows++; } - for (int row = 0; row < rowCount(); row++) { - if (row < index && !searchMask.contains(row) && row < grouped_rows) { + for(int row = 0; row < rowCount(); row++) { + if(row < index && !searchMask.contains(row) && row < grouped_rows) { m_decoderTable->showRow(row); no_rows = false; } else { m_decoderTable->hideRow(row); } } - if (no_rows) { + if(no_rows) { m_decoderTable->showRow(0); verticalHeader->setMinimumSectionSize(1); verticalHeader->setDefaultSectionSize(1); @@ -266,12 +257,12 @@ void DecoderTableModel::refreshColumn(double column) const void DecoderTableModel::selectedDecoderChanged(int index) const { - if (index >= 0) { + if(index >= 0) { m_decoderTable->scrollTo(QAbstractTableModel::index(0, index)); m_current_column = index; m_logic->setPrimaryAnntations(index, m_primary_annoations->value(index)); - if (m_decoderTable->isActive()) { + if(m_decoderTable->isActive()) { refreshColumn(index); populateFilter(index); } @@ -280,73 +271,76 @@ void DecoderTableModel::selectedDecoderChanged(int index) const void DecoderTableModel::populateFilter(int index) const { - if (index < 0 || m_plotCurves.empty()) return; + if(index < 0 || m_plotCurves.empty()) + return; auto temp_curve = dynamic_cast(m_plotCurves.at(index)); std::map decoder(temp_curve->getAnnotationRows()); m_logic->clearFilter(); int count = 0; - for (int row = 0; row < temp_curve->getAnnotationRows().size(); ++row) { - auto row_map = *std::find_if(temp_curve->getAnnotationRows().begin(), temp_curve->getAnnotationRows().end(), - [row](const std::pair &t) -> bool{ - return t.first.index() == row; - }); - if (!row_map.second.get_annotations().empty()) { - count ++; + for(int row = 0; row < temp_curve->getAnnotationRows().size(); ++row) { + auto row_map = *std::find_if( + temp_curve->getAnnotationRows().begin(), temp_curve->getAnnotationRows().end(), + [row](const std::pair &t) -> bool { return t.first.index() == row; }); + if(!row_map.second.get_annotations().empty()) { + count++; m_logic->addFilterRow(QIcon(), temp_curve->fromTitleToRowType(row_map.first.title())); } } } -int DecoderTableModel::getPrimaryAnnotationIndex() const -{ - return m_primary_annoations->value(getCurrentColumn()); -} +int DecoderTableModel::getPrimaryAnnotationIndex() const { return m_primary_annoations->value(getCurrentColumn()); } QVariant DecoderTableModel::data(const QModelIndex &index, int role) const { - if (!index.isValid() || m_decoderTable->signalsBlocked() || m_plotCurves.empty()) return QVariant(); + if(!index.isValid() || m_decoderTable->signalsBlocked() || m_plotCurves.empty()) + return QVariant(); const size_t col = index.column(); - if ( col >= m_curves.size() ) return QVariant(); + if(col >= m_curves.size()) + return QVariant(); const auto &curve = m_curves.at(col); - if (curve.isNull()) return QVariant(); + if(curve.isNull()) + return QVariant(); - if (curve->getAnnotationRows().size() == 0) { + if(curve->getAnnotationRows().size() == 0) { return QVariant(); } - if (index.row() < m_decoderTable->rowAt(m_decoderTable->rect().top()) || - (m_decoderTable->rowAt(m_decoderTable->rect().bottom()) < index.row() && - m_decoderTable->rowAt(m_decoderTable->rect().bottom()) != -1) || - !m_decoderTable->isVisible()) return QVariant(); + if(index.row() < m_decoderTable->rowAt(m_decoderTable->rect().top()) || + (m_decoderTable->rowAt(m_decoderTable->rect().bottom()) < index.row() && + m_decoderTable->rowAt(m_decoderTable->rect().bottom()) != -1) || + !m_decoderTable->isVisible()) + return QVariant(); auto temp_curve = dynamic_cast(m_plotCurves.at(index.column())); std::map decoder(temp_curve->getAnnotationRows()); vector row; - for (const auto &row_map : decoder) { + for(const auto &row_map : decoder) { row = row_map.second.get_annotations(); - if (!row.empty() && row_map.first.index() == getPrimaryAnnotationIndex()) { + if(!row.empty() && row_map.first.index() == getPrimaryAnnotationIndex()) { break; } } - if (row.empty()) { + if(row.empty()) { return QVariant(); } - if (to_be_refreshed) { + if(to_be_refreshed) { refreshColumn(col); to_be_refreshed = false; - if (to_be_refreshed == 2) selectedDecoderChanged(col); + if(to_be_refreshed == 2) + selectedDecoderChanged(col); } - int64_t total_rows = (m_logic->getGroupOffset() == 0) ? (row.size() - m_logic->getGroupOffset()) / m_logic->getGroupSize() - : (row.size() - m_logic->getGroupOffset()) / m_logic->getGroupSize() + 1; - if ((row.size() - m_logic->getGroupOffset()) % m_logic->getGroupSize() != 0) { + int64_t total_rows = (m_logic->getGroupOffset() == 0) + ? (row.size() - m_logic->getGroupOffset()) / m_logic->getGroupSize() + : (row.size() - m_logic->getGroupOffset()) / m_logic->getGroupSize() + 1; + if((row.size() - m_logic->getGroupOffset()) % m_logic->getGroupSize() != 0) { total_rows++; } - if (searchMask.count() == total_rows) { + if(searchMask.count() == total_rows) { return QVariant(); } @@ -356,29 +350,26 @@ QVariant DecoderTableModel::data(const QModelIndex &index, int role) const int start_ann = (index.row() == 0) ? 0 : off + size * (index.row() - 1); int end_ann = std::min(uint64_t(off + size * (index.row())) - 1, uint64_t(row.size() - 1)); - if (off == 0) { + if(off == 0) { start_ann--; end_ann--; } - return QVariant::fromValue(DecoderTableItem( - temp_curve, - row[start_ann].start_sample(), - row[end_ann].end_sample(), - m_filteredMessages.value(index.column()), - m_logic->getTableInfo() - )); + return QVariant::fromValue(DecoderTableItem(temp_curve, row[start_ann].start_sample(), + row[end_ann].end_sample(), m_filteredMessages.value(index.column()), + m_logic->getTableInfo())); } void DecoderTableModel::searchBoxSlot(QString text) { - if (m_decoderTable->signalsBlocked()) return; + if(m_decoderTable->signalsBlocked()) + return; m_decoderTable->blockSignals(true); m_logic->setStatusLabel("Searching ..."); QFuture future = QtConcurrent::run(this, &DecoderTableModel::searchTable, text); QFutureWatcher *watcher = new QFutureWatcher(this); - connect(watcher, &QFutureWatcher::finished, this, [=](){ + connect(watcher, &QFutureWatcher::finished, this, [=]() { m_decoderTable->blockSignals(false); beginResetModel(); @@ -396,8 +387,8 @@ void DecoderTableModel::searchTable(QString text) setSearchString(text); searchMask.clear(); - if (!searchString.isEmpty()) { - QRegExp rx = QRegExp(searchString, Qt::CaseInsensitive); + if(!searchString.isEmpty()) { + QRegExp rx = QRegExp(searchString, Qt::CaseInsensitive); auto temp_curve = dynamic_cast(m_plotCurves.at(m_current_column)); std::map decoder(temp_curve->getAnnotationRows()); @@ -406,11 +397,11 @@ void DecoderTableModel::searchTable(QString text) QString primary_title; // get primary annotation - for (const auto &row_map : decoder) { + for(const auto &row_map : decoder) { row = row_map.second.get_annotations(); primary_title = temp_curve->fromTitleToRowType(row_map.first.title()); - if (!row.empty() && row_map.first.index() == m_primary_annoations->value(m_current_column)) { + if(!row.empty() && row_map.first.index() == m_primary_annoations->value(m_current_column)) { break; } } @@ -421,31 +412,37 @@ void DecoderTableModel::searchTable(QString text) while(i < row.size()) { start_sample = row[i].start_sample(); - if (i == 0 && m_logic->getGroupOffset() != 0) { + if(i == 0 && m_logic->getGroupOffset() != 0) { end_sample = row[m_logic->getGroupOffset() - 1].end_sample(); } else { - end_sample = row[std::min(uint64_t(i + m_logic->getGroupSize() - 1), uint64_t(row.size() - 1))].end_sample(); + end_sample = row[std::min(uint64_t(i + m_logic->getGroupSize() - 1), + uint64_t(row.size() - 1))] + .end_sample(); } row_index++; - for (const auto &row_map : decoder) { - if (row_map.second.get_annotations().empty()) continue; + for(const auto &row_map : decoder) { + if(row_map.second.get_annotations().empty()) + continue; QString title = temp_curve->fromTitleToRowType(row_map.first.title()); - if (m_filteredMessages.value(m_current_column).contains(title)) continue; + if(m_filteredMessages.value(m_current_column).contains(title)) + continue; auto index_range = row_map.second.get_annotation_subset(start_sample, end_sample); uint64_t j = index_range.first; - while (j <= index_range.second && j < row_map.second.size()) { + while(j <= index_range.second && j < row_map.second.size()) { auto ann = row_map.second.getAnnAt(j); - if ((title != primary_title && - (((unsigned)(ann.end_sample()-start_sample-1) <= (end_sample-start_sample-1) || - (unsigned)(ann.start_sample()-start_sample) < (end_sample-start_sample)) || + if((title != primary_title && + (((unsigned)(ann.end_sample() - start_sample - 1) <= + (end_sample - start_sample - 1) || + (unsigned)(ann.start_sample() - start_sample) < + (end_sample - start_sample)) || (ann.start_sample() <= start_sample && ann.end_sample() >= end_sample))) || - (start_sample <= ann.start_sample() && ann.end_sample() <= end_sample)) { - for (const auto &value : ann.annotations()) { - if (rx.indexIn(value) != -1) { + (start_sample <= ann.start_sample() && ann.end_sample() <= end_sample)) { + for(const auto &value : ann.annotations()) { + if(rx.indexIn(value) != -1) { goto skip_loop; } } @@ -455,8 +452,8 @@ void DecoderTableModel::searchTable(QString text) } // add to mask if not found searchMask.append(row_index); -skip_loop: - if (i == 0 && m_logic->getGroupOffset() != 0) { + skip_loop: + if(i == 0 && m_logic->getGroupOffset() != 0) { i = m_logic->getGroupOffset(); } else { i += m_logic->getGroupSize(); @@ -466,4 +463,4 @@ void DecoderTableModel::searchTable(QString text) } } // namespace logic -} // namespace scopy +} // namespace scopy::m2k diff --git a/plugins/m2k/src/old/logicanalyzer/decoder_table_model.hpp b/plugins/m2k/src/old/logicanalyzer/decoder_table_model.hpp index 3e1af42bc7..a61ff0e1eb 100644 --- a/plugins/m2k/src/old/logicanalyzer/decoder_table_model.hpp +++ b/plugins/m2k/src/old/logicanalyzer/decoder_table_model.hpp @@ -21,81 +21,81 @@ #ifndef DECODER_TABLE_MODEL_H #define DECODER_TABLE_MODEL_H -#include -#include -#include #include "annotationcurve.h" #include "decoder_table.hpp" #include "decoder_table_item.hpp" +#include +#include -namespace scopy::m2k { +#include +namespace scopy::m2k { namespace logic { -class DecoderTableModel : public QAbstractTableModel { - Q_OBJECT +class DecoderTableModel : public QAbstractTableModel +{ + Q_OBJECT public: - DecoderTableModel(DecoderTable *decoderTable, LogicAnalyzer *logicAnalyzer); - int rowCount(const QModelIndex &parent = QModelIndex()) const override; - int columnCount(const QModelIndex &parent = QModelIndex()) const override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - void setDefaultPrimaryAnnotations(); - - // resize table cells and hide/show rows - void refreshColumn(double column = -1) const; - - // Get index of the curve - int indexOfCurve(const AnnotationCurve* curve) const; - - void setPrimaryAnnotation(int index); - void selectedDecoderChanged(int index) const; - - void populateFilter(int index) const; - QMap>& getFiltered(); - int getCurrentColumn() const; - void setCurrentRow(int index); - void setMaxRowCount(); - mutable int to_be_refreshed; - void refreshSettings(int column = -1); - void setSearchString(QString str) const; - QVector getSearchMask(); - QString getsearchString(); - int getPrimaryAnnotationIndex() const; + DecoderTableModel(DecoderTable *decoderTable, LogicAnalyzer *logicAnalyzer); + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + int columnCount(const QModelIndex &parent = QModelIndex()) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + void setDefaultPrimaryAnnotations(); + + // resize table cells and hide/show rows + void refreshColumn(double column = -1) const; + + // Get index of the curve + int indexOfCurve(const AnnotationCurve *curve) const; + + void setPrimaryAnnotation(int index); + void selectedDecoderChanged(int index) const; + + void populateFilter(int index) const; + QMap> &getFiltered(); + int getCurrentColumn() const; + void setCurrentRow(int index); + void setMaxRowCount(); + mutable int to_be_refreshed; + void refreshSettings(int column = -1); + void setSearchString(QString str) const; + QVector getSearchMask(); + QString getsearchString(); + int getPrimaryAnnotationIndex() const; public Q_SLOTS: - // This slot should be used when any of the decoders / annotation curves - // have been modified (eg adding/removing decoders, etc..). This clears - // the curves vecotr reconnects up signals to watch for annotation changes. - void reloadDecoders(bool logic); + // This slot should be used when any of the decoders / annotation curves + // have been modified (eg adding/removing decoders, etc..). This clears + // the curves vecotr reconnects up signals to watch for annotation changes. + void reloadDecoders(bool logic); - void searchBoxSlot(QString text); + void searchBoxSlot(QString text); protected: + // Set of curves to observe. Each should have an entry in the dataset + std::vector> m_curves; + + DecoderTable *m_decoderTable; + LogicAnalyzer *m_logic; + QVector m_plotCurves; + bool m_active = false; + QMap *m_primary_annoations; + void populateDecoderComboBox() const; + mutable int m_current_column; + QMap> m_filteredMessages; + mutable int max_row_count = 0; + mutable QString searchString; + QVector searchMask; - // Set of curves to observe. Each should have an entry in the dataset - std::vector> m_curves; - - DecoderTable *m_decoderTable; - LogicAnalyzer *m_logic; - QVector m_plotCurves; - bool m_active = false; - QMap *m_primary_annoations; - void populateDecoderComboBox() const; - mutable int m_current_column; - QMap> m_filteredMessages; - mutable int max_row_count = 0; - mutable QString searchString; - QVector searchMask; private: - void searchTable(QString text); + void searchTable(QString text); }; } // namespace logic -} // namespace scopy +} // namespace scopy::m2k #endif // DECODER_TABLE_MODEL_H - diff --git a/plugins/m2k/src/old/logicanalyzer/logic_analyzer.cpp b/plugins/m2k/src/old/logicanalyzer/logic_analyzer.cpp index a43bf295cc..9357d06099 100644 --- a/plugins/m2k/src/old/logicanalyzer/logic_analyzer.cpp +++ b/plugins/m2k/src/old/logicanalyzer/logic_analyzer.cpp @@ -19,44 +19,36 @@ * along with this program. If not, see . */ - #include "logic_analyzer.h" -#include "ui_logic_analyzer.h" -#include "ui_cursors_settings.h" -#include "oscilloscope_plot.hpp" - -#include - +#include "filemanager.h" +#include "filter.hpp" +#include "gui/basemenu.h" +#include "gui/dynamicWidget.h" #include "gui/logicdatacurve.h" -#include "sigrok-gui/annotationcurve.h" -#include "sigrok-gui/decoder.h" +#include "gui/osc_export_settings.h" #include "logicanalyzer/decoder_table_model.hpp" - -#include "gui/basemenu.h" -#include "logicgroupitem.h" - #include "logicanalyzer_api.h" +#include "logicgroupitem.h" +#include "oscilloscope_plot.hpp" +#include "sigrok-gui/annotationcurve.h" +#include "sigrok-gui/decoder.h" +#include "state_updater.h" -#include "gui/dynamicWidget.h" +#include "ui_cursors_settings.h" +#include "ui_logic_analyzer.h" +#include #include #include #include -#include #include -#include - #include - -#include "filter.hpp" +#include #include +#include #include - -#include "gui/osc_export_settings.h" -#include "filemanager.h" -#include "state_updater.h" #include using namespace scopy; @@ -64,78 +56,71 @@ using namespace scopy::logic; using namespace scopy::m2k; using namespace scopy::m2k::logic; -constexpr int MAX_BUFFER_SIZE_ONESHOT = 4 * 1024 * 1024; // 4M +constexpr int MAX_BUFFER_SIZE_ONESHOT = 4 * 1024 * 1024; // 4M constexpr int MAX_BUFFER_SIZE_STREAM = 1024 * 1024 * 1024; // 1Gb -constexpr int MAX_SR_STREAM = 5e6; // 10M +constexpr int MAX_SR_STREAM = 5e6; // 10M constexpr int MAX_KERNEL_BUFFERS = 64; /* helper method to sort srd_decoder objects based on ids(name) */ static gint sort_pds(gconstpointer a, gconstpointer b) { - const struct srd_decoder *sda, *sdb; + const struct srd_decoder *sda, *sdb; - sda = (const struct srd_decoder *)a; - sdb = (const struct srd_decoder *)b; - return strcmp(sda->id, sdb->id); + sda = (const struct srd_decoder *)a; + sdb = (const struct srd_decoder *)b; + return strcmp(sda->id, sdb->id); } -LogicAnalyzer::LogicAnalyzer(struct iio_context *ctx, Filter *filt, - ToolMenuEntry *tme, - QJSEngine *engine, QWidget *parent, - bool offline_mode_): - M2kTool(nullptr, tme, new LogicAnalyzer_API(this), "Logic Analyzer", parent), - ui(new Ui::LogicAnalyzer), - m_plot(this, false, 16, 10, new TimePrefixFormatter, new MetricPrefixFormatter), - m_bufferPreviewer(new DigitalBufferPreviewer(40, this)), - m_plotScrollBar(new QScrollBar(Qt::Vertical, this)), - m_sampleRateButton(new ScaleSpinButton({ - {"sps", 1E0}, - {"ksps", 1E+3}, - {"Msps", 1E+6} - }, tr("Sample Rate"), 1, - 10e7, - true, false, this, {1, 2, 5})), - m_bufferSizeButton(new ScaleSpinButton({ - {"samples", 1E0}, - {"k samples", 1E+3}, - {"M samples", 1E+6}, - {"G samples", 1E+9}, - }, tr("Nr of samples"), 1000, - MAX_BUFFER_SIZE_ONESHOT, - true, false, this, {1, 2, 5})), - m_timePositionButton(new PositionSpinButton({ - {"samples", 1E0}, - }, tr("Delay"), - (1 << 13), - (1 << 13) - 1, - true, false, this)), - m_sampleRate(1000000), - m_bufferSize(1000), - m_lastCapturedSample(0), - m_m2k_context(m2kOpen(ctx, "")), - m_m2kDigital(m_m2k_context->getDigital()), - m_nbChannels(DIGITAL_NR_CHANNELS), - m_horizOffset(0.0), - m_timeTriggerOffset(0.0), - m_resetHorizAxisOffset(true), - m_captureThread(nullptr), - m_stopRequested(false), - m_acquisitionStarted(false), - m_started(false), - m_selectedChannel(-1), - m_wheelEventGuard(nullptr), - m_decoderMenu(nullptr), - m_currentGroupMenu(nullptr), - m_autoMode(false), - m_timer(new QTimer(this)), - m_timerTimeout(1000), - m_exportSettings(nullptr), - m_saveRestoreSettings(nullptr), - m_oscPlot(nullptr), - m_oscChannelSelected(-1), - m_oscDecoderMenu(nullptr), - m_currentKernelBuffers(4), - m_triggerUpdater(new StateUpdater(250, this)), - m_buffer(nullptr) +LogicAnalyzer::LogicAnalyzer(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, QJSEngine *engine, + QWidget *parent, bool offline_mode_) + : M2kTool(nullptr, tme, new LogicAnalyzer_API(this), "Logic Analyzer", parent) + , ui(new Ui::LogicAnalyzer) + , m_plot(this, false, 16, 10, new TimePrefixFormatter, new MetricPrefixFormatter) + , m_bufferPreviewer(new DigitalBufferPreviewer(40, this)) + , m_plotScrollBar(new QScrollBar(Qt::Vertical, this)) + , m_sampleRateButton(new ScaleSpinButton({{"sps", 1E0}, {"ksps", 1E+3}, {"Msps", 1E+6}}, tr("Sample Rate"), 1, + 10e7, true, false, this, {1, 2, 5})) + , m_bufferSizeButton(new ScaleSpinButton( + { + {"samples", 1E0}, + {"k samples", 1E+3}, + {"M samples", 1E+6}, + {"G samples", 1E+9}, + }, + tr("Nr of samples"), 1000, MAX_BUFFER_SIZE_ONESHOT, true, false, this, {1, 2, 5})) + , m_timePositionButton(new PositionSpinButton( + { + {"samples", 1E0}, + }, + tr("Delay"), -(1 << 13), (1 << 13) - 1, true, false, this)) + , m_sampleRate(1000000) + , m_bufferSize(1000) + , m_lastCapturedSample(0) + , m_m2k_context(m2kOpen(ctx, "")) + , m_m2kDigital(m_m2k_context->getDigital()) + , m_nbChannels(DIGITAL_NR_CHANNELS) + , m_horizOffset(0.0) + , m_timeTriggerOffset(0.0) + , m_resetHorizAxisOffset(true) + , m_captureThread(nullptr) + , m_stopRequested(false) + , m_acquisitionStarted(false) + , m_started(false) + , m_selectedChannel(-1) + , m_wheelEventGuard(nullptr) + , m_decoderMenu(nullptr) + , m_currentGroupMenu(nullptr) + , m_autoMode(false) + , m_timer(new QTimer(this)) + , m_timerTimeout(1000) + , m_exportSettings(nullptr) + , m_saveRestoreSettings(nullptr) + , m_oscPlot(nullptr) + , m_oscChannelSelected(-1) + , m_oscDecoderMenu(nullptr) + , m_currentKernelBuffers(4) + , m_triggerUpdater(new StateUpdater(250, this)) + , m_buffer(nullptr) { // setup ui setupUi(); @@ -145,7 +130,7 @@ LogicAnalyzer::LogicAnalyzer(struct iio_context *ctx, Filter *filt, m_plot.setLeftVertAxesCount(1); - for (uint8_t i = 0; i < m_nbChannels; ++i) { + for(uint8_t i = 0; i < m_nbChannels; ++i) { QCheckBox *channelBox = new QCheckBox("DIO " + QString::number(i)); QHBoxLayout *hBoxLayout = new QHBoxLayout(); @@ -161,20 +146,20 @@ LogicAnalyzer::LogicAnalyzer(struct iio_context *ctx, Filter *filt, channelBox->setChecked(true); - triggerBox->setStyleSheet("QComboBox { max-width: 60px; } QComboBox QAbstractItemView { min-width: 130px; }"); + triggerBox->setStyleSheet( + "QComboBox { max-width: 60px; } QComboBox QAbstractItemView { min-width: 130px; }"); triggerBox->setSizeAdjustPolicy(QComboBox::AdjustToContentsOnFirstShow); - for (int i = 1; i < ui->triggerComboBox->count(); ++i) { + for(int i = 1; i < ui->triggerComboBox->count(); ++i) { triggerBox->addItem(ui->triggerComboBox->itemText(i)); } - int condition = static_cast( - m_m2kDigital->getTrigger()->getDigitalCondition(i)); + int condition = static_cast(m_m2kDigital->getTrigger()->getDigitalCondition(i)); triggerBox->setCurrentIndex((condition + 1) % 6); connect(triggerBox, QOverload::of(&QComboBox::currentIndexChanged), [=](int index) { - m_m2kDigital->getTrigger()->setDigitalCondition(i, - static_cast((index + 5) % 6)); + m_m2kDigital->getTrigger()->setDigitalCondition( + i, static_cast((index + 5) % 6)); }); // 1 for each channel @@ -185,16 +170,18 @@ LogicAnalyzer::LogicAnalyzer(struct iio_context *ctx, Filter *filt, // use direct connection we want the processing // of the available data to be done in the capture thread - connect(this, &LogicAnalyzer::dataAvailable, this, - [=](uint64_t from, uint64_t to, uint16_t* m_buffer){ - if (!m_oscPlot) { - curve->dataAvailable(from, to, m_buffer); - } - }, Qt::DirectConnection); + connect( + this, &LogicAnalyzer::dataAvailable, this, + [=](uint64_t from, uint64_t to, uint16_t *m_buffer) { + if(!m_oscPlot) { + curve->dataAvailable(from, to, m_buffer); + } + }, + Qt::DirectConnection); m_plotCurves.push_back(curve); - connect(channelBox, &QCheckBox::toggled, [=](bool toggled){ + connect(channelBox, &QCheckBox::toggled, [=](bool toggled) { m_plot.enableDigitalPlotCurve(i, toggled); m_plot.setOffsetWidgetVisible(i, toggled); m_plot.positionInGroupChanged(i, 0, 0); @@ -204,10 +191,8 @@ LogicAnalyzer::LogicAnalyzer(struct iio_context *ctx, Filter *filt, } // decoder table dropdown menu - connect(ui->btnCollapseSettings,&QPushButton::clicked, - [=](bool check) { - ui->wDecoderSettings_2->setVisible(check); - }); + connect(ui->btnCollapseSettings, &QPushButton::clicked, + [=](bool check) { ui->wDecoderSettings_2->setVisible(check); }); ui->btnCollapseSettings->click(); ui->statusLabel->setStyleSheet("QLabel { color : #4A64FF; }"); @@ -218,12 +203,11 @@ LogicAnalyzer::LogicAnalyzer(struct iio_context *ctx, Filter *filt, m_plot.zoomBaseUpdate(); - connect(&m_plot, &CapturePlot::timeTriggerValueChanged, [=](double value){ - double delay = (value - 1.0 / m_sampleRate * m_bufferSize / 2.0 ) / (1.0 / m_sampleRate); + connect(&m_plot, &CapturePlot::timeTriggerValueChanged, [=](double value) { + double delay = (value - 1.0 / m_sampleRate * m_bufferSize / 2.0) / (1.0 / m_sampleRate); onTimeTriggerValueChanged(static_cast(delay)); }); - m_plot.enableXaxisLabels(); initBufferScrolling(); @@ -247,8 +231,7 @@ LogicAnalyzer::LogicAnalyzer(struct iio_context *ctx, Filter *filt, m_bufferSizeButton->setValue(m_bufferSize); m_triggerUpdater->setOffState(CapturePlot::Stop); - connect(m_triggerUpdater, &StateUpdater::outputChanged, - &m_plot, &CapturePlot::setTriggerState); + connect(m_triggerUpdater, &StateUpdater::outputChanged, &m_plot, &CapturePlot::setTriggerState); readPreferences(); @@ -268,7 +251,7 @@ LogicAnalyzer::~LogicAnalyzer() { delete api; - if (m_captureThread) { + if(m_captureThread) { m_stopRequested = true; m_m2kDigital->cancelAcquisition(); m_captureThread->join(); @@ -276,12 +259,12 @@ LogicAnalyzer::~LogicAnalyzer() m_captureThread = nullptr; } - for (auto &curve : m_plotCurves) { + for(auto &curve : m_plotCurves) { m_plot.removeDigitalPlotCurve(curve); delete curve; } - if (m_buffer) { + if(m_buffer) { delete[] m_buffer; m_buffer = nullptr; } @@ -296,12 +279,12 @@ void LogicAnalyzer::setNativeDialogs(bool nativeDialogs) m_plot.setUseNativeDialog(nativeDialogs); } -void LogicAnalyzer::setData(const uint16_t * const data, int size) +void LogicAnalyzer::setData(const uint16_t *const data, int size) { qDebug() << "Set data arrived: "; - if (m_buffer) { + if(m_buffer) { delete m_buffer; m_buffer = nullptr; } @@ -311,22 +294,20 @@ void LogicAnalyzer::setData(const uint16_t * const data, int size) memcpy(m_buffer, data, size * sizeof(uint16_t)); Q_EMIT dataAvailable(0, size, m_buffer); -// if (m_oscPlot) { -// QMetaObject::invokeMethod(this, [=](){ -// m_oscPlot->replot(); -// }, Qt::QueuedConnection); -// } - + // if (m_oscPlot) { + // QMetaObject::invokeMethod(this, [=](){ + // m_oscPlot->replot(); + // }, Qt::QueuedConnection); + // } } -QVector LogicAnalyzer::getPlotCurves(bool logic) const +QVector LogicAnalyzer::getPlotCurves(bool logic) const { - if (logic) { + if(logic) { return m_plotCurves; } else { return m_oscPlotCurves; } - } std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, int oscAnalogChannels) @@ -334,8 +315,8 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in // save the state of the tool m_saveRestoreSettings = std::unique_ptr(new SaveRestoreToolSettings(this)); - if (m_started) { - tme->setRunning(false); + if(m_started) { + tme->setRunning(false); } // disable the menu item for the logic analyzer when mixed signal view is enabled @@ -364,7 +345,7 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in layout->insertLayout(0, chEnumeratorLayout); // move plot curves (logic + decoder) to osc plot - for (uint8_t i = 0; i < m_nbChannels; ++i) { + for(uint8_t i = 0; i < m_nbChannels; ++i) { LogicDataCurve *curve = new LogicDataCurve(nullptr, i); curve->setTraceHeight(25); @@ -372,14 +353,12 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in m_oscPlotCurves.push_back(curve); - auto handle = connect(this, &LogicAnalyzer::dataAvailable, this, - [=](uint64_t from, uint64_t to, uint16_t *buffer){ - curve->dataAvailable(from, to, buffer); - }, Qt::DirectConnection); + auto handle = connect( + this, &LogicAnalyzer::dataAvailable, this, + [=](uint64_t from, uint64_t to, uint16_t *buffer) { curve->dataAvailable(from, to, buffer); }, + Qt::DirectConnection); - connect(curve, &GenericLogicPlotCurve::destroyed, [=](){ - disconnect(handle); - }); + connect(curve, &GenericLogicPlotCurve::destroyed, [=]() { disconnect(handle); }); QCheckBox *channelBox = new QCheckBox("DIO " + QString::number(i)); curve->setName("DIO " + QString::number(i)); @@ -397,21 +376,19 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in channelBox->setChecked(true); - for (int i = 1; i < ui->triggerComboBox->count(); ++i) { - triggerBox->addItem(ui->triggerComboBox->itemIcon(i), - ui->triggerComboBox->itemText(i)); + for(int i = 1; i < ui->triggerComboBox->count(); ++i) { + triggerBox->addItem(ui->triggerComboBox->itemIcon(i), ui->triggerComboBox->itemText(i)); } - int condition = static_cast( - m_m2kDigital->getTrigger()->getDigitalCondition(i)); + int condition = static_cast(m_m2kDigital->getTrigger()->getDigitalCondition(i)); triggerBox->setCurrentIndex((condition + 1) % 6); connect(triggerBox, QOverload::of(&QComboBox::currentIndexChanged), [=](int index) { - m_m2kDigital->getTrigger()->setDigitalCondition(i, - static_cast((index + 5) % 6)); + m_m2kDigital->getTrigger()->setDigitalCondition( + i, static_cast((index + 5) % 6)); }); - connect(channelBox, &QCheckBox::toggled, [=](bool toggled){ + connect(channelBox, &QCheckBox::toggled, [=](bool toggled) { const int oscAnalogChannels = m_oscPlot->getAnalogChannels(); m_oscPlot->enableDigitalPlotCurve(i, toggled); m_oscPlot->setOffsetWidgetVisible(i + oscAnalogChannels, toggled); @@ -429,25 +406,24 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in decoderComboBox->addItem("Select a decoder to add"); - GSList *decoderList = g_slist_copy((GSList *)srd_decoder_list()); decoderList = g_slist_sort(decoderList, sort_pds); - for (const GSList *sl = decoderList; sl; sl = sl->next) { + for(const GSList *sl = decoderList; sl; sl = sl->next) { - srd_decoder *dec = (struct srd_decoder *)sl->data; + srd_decoder *dec = (struct srd_decoder *)sl->data; - QString decoderInput = ""; + QString decoderInput = ""; - GSList *dec_channels = g_slist_copy(dec->inputs); - for (const GSList *sl = dec_channels; sl; sl = sl->next) { - decoderInput = QString::fromUtf8((char*)sl->data); - } - g_slist_free(dec_channels); + GSList *dec_channels = g_slist_copy(dec->inputs); + for(const GSList *sl = dec_channels; sl; sl = sl->next) { + decoderInput = QString::fromUtf8((char *)sl->data); + } + g_slist_free(dec_channels); - if (decoderInput == "logic") { - decoderComboBox->addItem(QString::fromUtf8(dec->id)); - } + if(decoderInput == "logic") { + decoderComboBox->addItem(QString::fromUtf8(dec->id)); + } } g_slist_free(decoderList); @@ -463,19 +439,19 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in QComboBox *stackDecoderComboBox = new QComboBox(); stackDecoderComboBox->setVisible(false); - auto updateButtonStackedDecoder = [=](){ - if (m_oscChannelSelected < m_nbChannels) { + auto updateButtonStackedDecoder = [=]() { + if(m_oscChannelSelected < m_nbChannels) { stackDecoderComboBox->setVisible(false); return; } - if (m_oscChannelSelected > m_oscPlotCurves.size() - 1) { + if(m_oscChannelSelected > m_oscPlotCurves.size() - 1) { return; } AnnotationCurve *curve = dynamic_cast(m_oscPlotCurves[m_oscChannelSelected]); - if (!curve) { + if(!curve) { return; } @@ -490,26 +466,26 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in GSList *decoderList = g_slist_copy((GSList *)srd_decoder_list()); decoderList = g_slist_sort(decoderList, sort_pds); GSList *dec_channels = g_slist_copy(top->decoder()->outputs); - for (const GSList *sl = dec_channels; sl; sl = sl->next) { - decoderOutput = QString::fromUtf8((char*)sl->data); + for(const GSList *sl = dec_channels; sl; sl = sl->next) { + decoderOutput = QString::fromUtf8((char *)sl->data); } g_slist_free(dec_channels); - for (const GSList *sl = decoderList; sl; sl = sl->next) { + for(const GSList *sl = decoderList; sl; sl = sl->next) { - srd_decoder *dec = (struct srd_decoder *)sl->data; + srd_decoder *dec = (struct srd_decoder *)sl->data; - QString decoderInput = ""; + QString decoderInput = ""; - GSList *dec_channels = g_slist_copy(dec->inputs); - for (const GSList *sl = dec_channels; sl; sl = sl->next) { - decoderInput = QString::fromUtf8((char*)sl->data); - } - g_slist_free(dec_channels); + GSList *dec_channels = g_slist_copy(dec->inputs); + for(const GSList *sl = dec_channels; sl; sl = sl->next) { + decoderInput = QString::fromUtf8((char *)sl->data); + } + g_slist_free(dec_channels); - if (decoderInput == decoderOutput) { - qDebug() << "Added: " << QString::fromUtf8(dec->id); - stackDecoderComboBox->addItem(QString::fromUtf8(dec->id)); - } + if(decoderInput == decoderOutput) { + qDebug() << "Added: " << QString::fromUtf8(dec->id); + stackDecoderComboBox->addItem(QString::fromUtf8(dec->id)); + } } g_slist_free(decoderList); @@ -518,21 +494,21 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in stackDecoderComboBox->setVisible(shouldBeVisible); }; - connect(decoderComboBox, qOverload(&QComboBox::currentIndexChanged), this ,[=](int index) { + connect(decoderComboBox, qOverload(&QComboBox::currentIndexChanged), this, [=](int index) { const QString &decoder = decoderComboBox->itemText(index); decoderComboBox->clearFocus(); - if (!decoderComboBox->currentIndex()) { + if(!decoderComboBox->currentIndex()) { return; } std::shared_ptr initialDecoder = nullptr; GSList *decoderList = g_slist_copy((GSList *)srd_decoder_list()); - for (const GSList *sl = decoderList; sl; sl = sl->next) { - srd_decoder *dec = (struct srd_decoder *)sl->data; - if (QString::fromUtf8(dec->id) == decoder) { - initialDecoder = std::make_shared(dec); - } + for(const GSList *sl = decoderList; sl; sl = sl->next) { + srd_decoder *dec = (struct srd_decoder *)sl->data; + if(QString::fromUtf8(dec->id) == decoder) { + initialDecoder = std::make_shared(dec); + } } AnnotationCurve *curve = new AnnotationCurve(initialDecoder); @@ -543,7 +519,7 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in // be displayed properly due to lack of information about // sr buffer size and trigger offset. We borrow this values // from a logic curve on the plot - QwtPlotCurve* dummyCurve = m_oscPlot->getDigitalPlotCurve(0); + QwtPlotCurve *dummyCurve = m_oscPlot->getDigitalPlotCurve(0); GenericLogicPlotCurve *logicCurve = dynamic_cast(dummyCurve); curve->setSampleRate(logicCurve->getSampleRate()); curve->setBufferSize(logicCurve->getBufferSize()); @@ -553,14 +529,12 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in // use direct connection we want the processing // of the available data to be done in the capture thread - auto connectionHandle = connect(this, &LogicAnalyzer::dataAvailable, - this, [=](uint64_t from, uint64_t to, uint16_t *buffer){ - curve->dataAvailable(from, to, buffer); - }, Qt::DirectConnection); + auto connectionHandle = connect( + this, &LogicAnalyzer::dataAvailable, this, + [=](uint64_t from, uint64_t to, uint16_t *buffer) { curve->dataAvailable(from, to, buffer); }, + Qt::DirectConnection); - connect(curve, &QObject::destroyed, [=](){ - disconnect(connectionHandle); - }); + connect(curve, &QObject::destroyed, [=]() { disconnect(connectionHandle); }); g_slist_free(decoderList); @@ -583,23 +557,21 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in decoderBox->setVisible(true); deleteBtn->setVisible(true); - connect(deleteBtn, &QPushButton::clicked, [=](){ + connect(deleteBtn, &QPushButton::clicked, [=]() { decoderMenuItem->deleteLater(); int chIdx = m_oscPlotCurves.indexOf(curve); - if (chIdx == m_oscChannelSelected) { + if(chIdx == m_oscChannelSelected) { Q_EMIT m_oscPlot->channelSelected(chIdx + m_oscAnalogChannels, false); - } else if (chIdx < m_oscChannelSelected) { + } else if(chIdx < m_oscChannelSelected) { m_oscChannelSelected--; } bool groupDeleted = false; - m_oscPlot->removeFromGroup(chIdx, - m_plot.getGroupOfChannel(chIdx).indexOf(chIdx), - groupDeleted); + m_oscPlot->removeFromGroup(chIdx, m_plot.getGroupOfChannel(chIdx).indexOf(chIdx), groupDeleted); - if (groupDeleted) { + if(groupDeleted) { ui->groupWidget->setVisible(false); m_currentGroup.clear(); ui->groupWidgetLayout->removeWidget(m_currentGroupMenu); @@ -615,7 +587,7 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in delete curve; // reposition decoder menu items after deleting one - for (int i = chIdx; i < m_oscPlotCurves.size(); ++i) { + for(int i = chIdx; i < m_oscPlotCurves.size(); ++i) { const int index = i - 16; // subtract logic channels count QLayoutItem *next = decoderEnumerator->itemAtPosition((index + 1) / 2, (index + 1) % 2); decoderEnumerator->removeItem(next); @@ -630,7 +602,7 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in decoderComboBox->setCurrentIndex(0); - connect(decoderBox, &QCheckBox::toggled, [=](bool toggled){ + connect(decoderBox, &QCheckBox::toggled, [=](bool toggled) { const int analogChannels = m_oscPlot->getAnalogChannels(); m_oscPlot->enableDigitalPlotCurve(analogChannels + m_nbChannels + itemsInLayout, toggled); m_oscPlot->setOffsetWidgetVisible(analogChannels + m_nbChannels + itemsInLayout, toggled); @@ -640,12 +612,12 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in int chId = m_oscPlotCurves.size() - 1; - connect(curve, &AnnotationCurve::decoderMenuChanged, [=](){ - if (m_oscChannelSelected != chId) { + connect(curve, &AnnotationCurve::decoderMenuChanged, [=]() { + if(m_oscChannelSelected != chId) { return; } - if (m_oscDecoderMenu) { + if(m_oscDecoderMenu) { decoderSettingsLayout->removeWidget(m_oscDecoderMenu); m_oscDecoderMenu->deleteLater(); m_oscDecoderMenu = nullptr; @@ -686,8 +658,8 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in QComboBox *traceColorComboBox = new QComboBox(); traceColorComboBox->setObjectName("traceColorComboBox"); - for (const auto &name : QColor::colorNames()) { - QPixmap pixmap(100,100); + for(const auto &name : QColor::colorNames()) { + QPixmap pixmap(100, 100); QColor color(name); pixmap.fill(color); QIcon colorIcon(pixmap); @@ -697,9 +669,9 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in QComboBox *currentChannelTriggerComboBox = new QComboBox(); currentChannelTriggerComboBox->addItem("-"); - for (int i = 1; i < ui->triggerComboBox->count(); ++i) { + for(int i = 1; i < ui->triggerComboBox->count(); ++i) { currentChannelTriggerComboBox->addItem(ui->triggerComboBox->itemIcon(i), - ui->triggerComboBox->itemText(i)); + ui->triggerComboBox->itemText(i)); } currentChannelMenuLayout->addWidget(nameLineEdit); @@ -758,13 +730,13 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in comboBoxCondition->setDisabled(true); - connect(externalOnOff, &CustomSwitch::toggled, [=](bool on){ - if (on) { + connect(externalOnOff, &CustomSwitch::toggled, [=](bool on) { + if(on) { comboBoxCondition->setEnabled(true); m_m2kDigital->getTrigger()->setDigitalSource(SRC_TRIGGER_IN); const int condition = comboBoxCondition->currentIndex(); m_m2kDigital->getTrigger()->setDigitalExternalCondition( - static_cast((condition + 5) % 6)); + static_cast((condition + 5) % 6)); } else { comboBoxCondition->setCurrentIndex(0); comboBoxCondition->setDisabled(true); @@ -772,14 +744,13 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in } }); comboBoxCondition->addItem("-"); - for (int i = 1; i < ui->triggerComboBox->count(); ++i) { - comboBoxCondition->addItem(ui->triggerComboBox->itemIcon(i), - ui->triggerComboBox->itemText(i)); + for(int i = 1; i < ui->triggerComboBox->count(); ++i) { + comboBoxCondition->addItem(ui->triggerComboBox->itemIcon(i), ui->triggerComboBox->itemText(i)); } - connect(comboBoxCondition, QOverload::of(&QComboBox::currentIndexChanged), [=](int index){ + connect(comboBoxCondition, QOverload::of(&QComboBox::currentIndexChanged), [=](int index) { m_m2kDigital->getTrigger()->setDigitalExternalCondition( - static_cast((index + 5) % 6)); + static_cast((index + 5) % 6)); }); externalTriggerLayout->addLayout(externalGridLayout); @@ -790,66 +761,73 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in tabWidget->addTab(channelEnumerator, "General"); const int channelMenuTabId = tabWidget->addTab(currentChannelMenuScrollArea, "Channel"); - m_oscChannelSelectedConnection = connect(m_oscPlot, &CapturePlot::channelSelected, [=](int chIdx, bool selected){ - chIdx -= m_oscAnalogChannels; - if (m_oscChannelSelected != chIdx && selected) { - m_oscChannelSelected = chIdx; - nameLineEdit->setEnabled(true); - nameLineEdit->setText(m_oscPlotCurves[chIdx]->getName()); - traceHeightLineEdit->setEnabled(true); - traceHeightLineEdit->setText(QString::number(m_oscPlotCurves[chIdx]->getTraceHeight())); - traceColorComboBox->setEnabled(true); - - if (m_oscChannelSelected < m_nbChannels) { - currentChannelTriggerComboBox->setEnabled(true); - QComboBox *triggerBox = qobject_cast(chEnumeratorLayout->itemAtPosition(m_oscChannelSelected % 8, - m_oscChannelSelected / 8)->layout()->itemAt(1)->widget()); - currentChannelTriggerComboBox->setCurrentIndex(triggerBox->currentIndex()); - } else { - currentChannelTriggerComboBox->setDisabled(true); - QSignalBlocker sb(currentChannelTriggerComboBox); - currentChannelTriggerComboBox->setCurrentIndex(0); - } + m_oscChannelSelectedConnection = + connect(m_oscPlot, &CapturePlot::channelSelected, [=](int chIdx, bool selected) { + chIdx -= m_oscAnalogChannels; + if(m_oscChannelSelected != chIdx && selected) { + m_oscChannelSelected = chIdx; + nameLineEdit->setEnabled(true); + nameLineEdit->setText(m_oscPlotCurves[chIdx]->getName()); + traceHeightLineEdit->setEnabled(true); + traceHeightLineEdit->setText(QString::number(m_oscPlotCurves[chIdx]->getTraceHeight())); + traceColorComboBox->setEnabled(true); + + if(m_oscChannelSelected < m_nbChannels) { + currentChannelTriggerComboBox->setEnabled(true); + QComboBox *triggerBox = qobject_cast( + chEnumeratorLayout + ->itemAtPosition(m_oscChannelSelected % 8, + m_oscChannelSelected / 8) + ->layout() + ->itemAt(1) + ->widget()); + currentChannelTriggerComboBox->setCurrentIndex(triggerBox->currentIndex()); + } else { + currentChannelTriggerComboBox->setDisabled(true); + QSignalBlocker sb(currentChannelTriggerComboBox); + currentChannelTriggerComboBox->setCurrentIndex(0); + } - tabWidget->setCurrentIndex(channelMenuTabId); + tabWidget->setCurrentIndex(channelMenuTabId); - if (m_oscChannelSelected < m_nbChannels) { - if (m_oscDecoderMenu) { - decoderSettingsLayout->removeWidget(m_oscDecoderMenu); - m_oscDecoderMenu->deleteLater(); - m_oscDecoderMenu = nullptr; + if(m_oscChannelSelected < m_nbChannels) { + if(m_oscDecoderMenu) { + decoderSettingsLayout->removeWidget(m_oscDecoderMenu); + m_oscDecoderMenu->deleteLater(); + m_oscDecoderMenu = nullptr; + } + } else { + if(m_oscDecoderMenu) { + decoderSettingsLayout->removeWidget(m_oscDecoderMenu); + m_oscDecoderMenu->deleteLater(); + m_oscDecoderMenu = nullptr; + } + + AnnotationCurve *annCurve = + dynamic_cast(m_oscPlotCurves[m_oscChannelSelected]); + m_oscDecoderMenu = annCurve->getCurrentDecoderStackMenu(); + decoderSettingsLayout->addWidget(m_oscDecoderMenu); } - } else { - if (m_oscDecoderMenu) { + } else if(m_oscChannelSelected == chIdx && !selected) { + m_oscChannelSelected = -1; + nameLineEdit->setDisabled(true); + nameLineEdit->setText("No channel selected!"); + traceHeightLineEdit->setDisabled(true); + traceHeightLineEdit->setText(""); + currentChannelTriggerComboBox->setDisabled(true); + currentChannelTriggerComboBox->setCurrentIndex(0); + + if(m_oscDecoderMenu) { decoderSettingsLayout->removeWidget(m_oscDecoderMenu); m_oscDecoderMenu->deleteLater(); m_oscDecoderMenu = nullptr; } - - AnnotationCurve *annCurve = dynamic_cast(m_oscPlotCurves[m_oscChannelSelected]); - m_oscDecoderMenu = annCurve->getCurrentDecoderStackMenu(); - decoderSettingsLayout->addWidget(m_oscDecoderMenu); - } - } else if (m_oscChannelSelected == chIdx && !selected) { - m_oscChannelSelected = -1; - nameLineEdit->setDisabled(true); - nameLineEdit->setText("No channel selected!"); - traceHeightLineEdit->setDisabled(true); - traceHeightLineEdit->setText(""); - currentChannelTriggerComboBox->setDisabled(true); - currentChannelTriggerComboBox->setCurrentIndex(0); - - if (m_oscDecoderMenu) { - decoderSettingsLayout->removeWidget(m_oscDecoderMenu); - m_oscDecoderMenu->deleteLater(); - m_oscDecoderMenu = nullptr; } - } - updateButtonStackedDecoder(); - }); + updateButtonStackedDecoder(); + }); - connect(traceHeightLineEdit, &QLineEdit::editingFinished, [=](){ + connect(traceHeightLineEdit, &QLineEdit::editingFinished, [=]() { int value = traceHeightLineEdit->text().toInt(); m_oscPlotCurves[m_oscChannelSelected]->setTraceHeight(value); m_oscPlot->replot(); @@ -863,56 +841,63 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in }); connect(currentChannelTriggerComboBox, QOverload::of(&QComboBox::currentIndexChanged), [=](int index) { - if (m_oscChannelSelected != -1 && m_oscChannelSelected < m_nbChannels) { - QComboBox *triggerBox = qobject_cast(chEnumeratorLayout->itemAtPosition(m_oscChannelSelected % 8, - m_oscChannelSelected / 8)->layout()->itemAt(1)->widget()); + if(m_oscChannelSelected != -1 && m_oscChannelSelected < m_nbChannels) { + QComboBox *triggerBox = qobject_cast( + chEnumeratorLayout->itemAtPosition(m_oscChannelSelected % 8, m_oscChannelSelected / 8) + ->layout() + ->itemAt(1) + ->widget()); triggerBox->setCurrentIndex(index); } }); - connect(tabWidget, &QTabWidget::currentChanged, [=](int index){ - if (index == tabWidget->indexOf(currentChannelMenuScrollArea)) { - if (m_oscChannelSelected != -1 && m_oscChannelSelected < m_nbChannels) { + connect(tabWidget, &QTabWidget::currentChanged, [=](int index) { + if(index == tabWidget->indexOf(currentChannelMenuScrollArea)) { + if(m_oscChannelSelected != -1 && m_oscChannelSelected < m_nbChannels) { currentChannelTriggerComboBox->setEnabled(true); - QComboBox *triggerBox = qobject_cast(chEnumeratorLayout->itemAtPosition(m_oscChannelSelected % 8, - m_oscChannelSelected / 8)->layout()->itemAt(1)->widget()); + QComboBox *triggerBox = qobject_cast( + chEnumeratorLayout + ->itemAtPosition(m_oscChannelSelected % 8, m_oscChannelSelected / 8) + ->layout() + ->itemAt(1) + ->widget()); currentChannelTriggerComboBox->setCurrentIndex(triggerBox->currentIndex()); } } }); connect(stackDecoderComboBox, &QComboBox::currentTextChanged, [=](const QString &text) { - if (m_oscChannelSelected < m_nbChannels) { + if(m_oscChannelSelected < m_nbChannels) { return; } - if (m_oscChannelSelected > m_oscPlotCurves.size() - 1) { + if(m_oscChannelSelected > m_oscPlotCurves.size() - 1) { return; } - if (!stackDecoderComboBox->currentIndex()) { + if(!stackDecoderComboBox->currentIndex()) { return; } AnnotationCurve *curve = dynamic_cast(m_oscPlotCurves[m_oscChannelSelected]); - if (!curve) { + if(!curve) { return; } GSList *dl = g_slist_copy((GSList *)srd_decoder_list()); - for (const GSList *sl = dl; sl; sl = sl->next) { - srd_decoder *dec = (struct srd_decoder *)sl->data; - if (QString::fromUtf8(dec->id) == text) { - curve->stackDecoder(std::make_shared(dec)); - break; - } + for(const GSList *sl = dl; sl; sl = sl->next) { + srd_decoder *dec = (struct srd_decoder *)sl->data; + if(QString::fromUtf8(dec->id) == text) { + curve->stackDecoder(std::make_shared(dec)); + break; + } } // Update decoder menu. New decoder must be shown // and it might also have some options that can // be modified - if (m_oscDecoderMenu) { + if(m_oscDecoderMenu) { decoderSettingsLayout->removeWidget(m_oscDecoderMenu); m_oscDecoderMenu->deleteLater(); m_oscDecoderMenu = nullptr; @@ -930,7 +915,7 @@ std::vector LogicAnalyzer::enableMixedSignalView(CapturePlot *osc, in tabWidget->addTab(generalScrollArea, "General"); tabWidget->addTab(currentChannelMenuScrollArea, "Channel"); - MouseWheelWidgetGuard* m_wheelEventGuard1 = new MouseWheelWidgetGuard(generalScrollArea); + MouseWheelWidgetGuard *m_wheelEventGuard1 = new MouseWheelWidgetGuard(generalScrollArea); m_wheelEventGuard1->installEventRecursively(generalScrollArea); return {tabWidget, generalScrollArea}; @@ -946,7 +931,7 @@ void LogicAnalyzer::disableMixedSignalView() // remove from osc plot the logic curves QwtPlotCurve *curve = m_oscPlot->getDigitalPlotCurve(0); - while (curve != nullptr) { + while(curve != nullptr) { m_oscPlot->removeDigitalPlotCurve(curve); delete curve; @@ -960,33 +945,22 @@ void LogicAnalyzer::disableMixedSignalView() m_oscPlot = nullptr; } -void LogicAnalyzer::addCurveToPlot(QwtPlotCurve *curve) -{ +void LogicAnalyzer::addCurveToPlot(QwtPlotCurve *curve) {} -} +QwtPlot *LogicAnalyzer::getCurrentPlot() { return nullptr; } -QwtPlot *LogicAnalyzer::getCurrentPlot() -{ - return nullptr; -} - -void LogicAnalyzer::connectSignalsAndSlotsForPlot(CapturePlot *plot) -{ - -} +void LogicAnalyzer::connectSignalsAndSlotsForPlot(CapturePlot *plot) {} void LogicAnalyzer::on_btnChannelSettings_toggled(bool checked) { - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); + triggerRightMenuToggle(static_cast(QObject::sender()), checked); - if (checked && m_selectedChannel != -1) { + if(checked && m_selectedChannel != -1) { ui->nameLineEdit->setText(m_plot.getChannelName(m_selectedChannel)); - ui->traceHeightLineEdit->setText(QString::number( - m_plotCurves[m_selectedChannel]->getTraceHeight())); - if (m_selectedChannel < m_nbChannels) { - int condition = static_cast( - m_m2kDigital->getTrigger()->getDigitalCondition(m_selectedChannel)); + ui->traceHeightLineEdit->setText(QString::number(m_plotCurves[m_selectedChannel]->getTraceHeight())); + if(m_selectedChannel < m_nbChannels) { + int condition = + static_cast(m_m2kDigital->getTrigger()->getDigitalCondition(m_selectedChannel)); ui->triggerComboBox->setCurrentIndex((condition + 1) % 6); } } @@ -994,14 +968,12 @@ void LogicAnalyzer::on_btnChannelSettings_toggled(bool checked) void LogicAnalyzer::on_btnCursors_toggled(bool checked) { - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); + triggerRightMenuToggle(static_cast(QObject::sender()), checked); } void LogicAnalyzer::on_btnTrigger_toggled(bool checked) { - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); + triggerRightMenuToggle(static_cast(QObject::sender()), checked); } void LogicAnalyzer::on_cursorsBox_toggled(bool on) @@ -1014,12 +986,11 @@ void LogicAnalyzer::on_btnSettings_clicked(bool checked) { CustomPushButton *btn = nullptr; - if (checked && !m_menuOrder.isEmpty()) { + if(checked && !m_menuOrder.isEmpty()) { btn = m_menuOrder.back(); m_menuOrder.pop_back(); } else { - btn = static_cast( - ui->settings_group->checkedButton()); + btn = static_cast(ui->settings_group->checkedButton()); } btn->setChecked(checked); @@ -1027,34 +998,31 @@ void LogicAnalyzer::on_btnSettings_clicked(bool checked) void LogicAnalyzer::on_btnGeneralSettings_toggled(bool checked) { - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); + triggerRightMenuToggle(static_cast(QObject::sender()), checked); if(checked) ui->btnSettings->setChecked(!checked); } void LogicAnalyzer::on_btnDecoderTable_toggled(bool checked) { - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); + triggerRightMenuToggle(static_cast(QObject::sender()), checked); // When the bottom decoder button is clicked show/hide the right menu // and ativate or deactivate the decoder table. - if (checked) { - if (!ui->btnStreamOneShot->isChecked()) { + if(checked) { + if(!ui->btnStreamOneShot->isChecked()) { ui->btnStreamOneShot->click(); } ui->decoderTableView->blockSignals(true); QFuture future = QtConcurrent::run(this, &LogicAnalyzer::waitForDecoders); QFutureWatcher *watcher = new QFutureWatcher(this); - connect(watcher, &QFutureWatcher::finished, this, [=](){ - if (ui->btnDecoderTable->isChecked()) { + connect(watcher, &QFutureWatcher::finished, this, [=]() { + if(ui->btnDecoderTable->isChecked()) { ui->decoderTableView->blockSignals(false); activateRunButton(false); ui->decoderTableView->activate(true); } - }); // delete the watcher when finished too connect(watcher, SIGNAL(finished()), watcher, SLOT(deleteLater())); @@ -1073,7 +1041,7 @@ void LogicAnalyzer::rightMenuFinished(bool opened) // At the end of each animation, check if there are other button check // actions that might have happened while animating and execute all // these queued actions - while (m_menuButtonActions.size()) { + while(m_menuButtonActions.size()) { auto pair = m_menuButtonActions.dequeue(); toggleRightMenu(pair.first, pair.second); } @@ -1081,13 +1049,12 @@ void LogicAnalyzer::rightMenuFinished(bool opened) void LogicAnalyzer::onTimeTriggerValueChanged(double value) { - if (value > m_timePositionButton->maxValue() || - value < m_timePositionButton->minValue()) { + if(value > m_timePositionButton->maxValue() || value < m_timePositionButton->minValue()) { return; } const bool wasRunning = m_started; - if (wasRunning) { + if(wasRunning) { startStop(false); } @@ -1099,7 +1066,7 @@ void LogicAnalyzer::onTimeTriggerValueChanged(double value) m_plot.setHorizOffset(1.0 / m_sampleRate * m_bufferSize / 2.0 + m_timeTriggerOffset); m_plot.replot(); - if (m_resetHorizAxisOffset) { + if(m_resetHorizAxisOffset) { m_horizOffset = 1.0 / m_sampleRate * m_bufferSize / 2.0 + m_timeTriggerOffset; } @@ -1107,7 +1074,7 @@ void LogicAnalyzer::onTimeTriggerValueChanged(double value) updateBufferPreviewer(0, m_lastCapturedSample); - if (wasRunning) { + if(wasRunning) { startStop(true); } } @@ -1115,7 +1082,7 @@ void LogicAnalyzer::onTimeTriggerValueChanged(double value) void LogicAnalyzer::onSampleRateValueChanged(double value) { const bool wasRunning = m_started; - if (wasRunning) { + if(wasRunning) { startStop(false); } @@ -1124,7 +1091,7 @@ void LogicAnalyzer::onSampleRateValueChanged(double value) resetViewport(); - if (wasRunning) { + if(wasRunning) { startStop(true); } } @@ -1132,13 +1099,13 @@ void LogicAnalyzer::onSampleRateValueChanged(double value) void LogicAnalyzer::onBufferSizeChanged(double value) { const bool wasRunning = m_started; - if (wasRunning) { + if(wasRunning) { startStop(false); } m_bufferSize = value; resetViewport(); - if (wasRunning) { + if(wasRunning) { startStop(true); } } @@ -1146,7 +1113,7 @@ void LogicAnalyzer::onBufferSizeChanged(double value) void LogicAnalyzer::on_btnStreamOneShot_toggled(bool toggled) { const bool wasRunning = m_started; - if (wasRunning) { + if(wasRunning) { startStop(false); } @@ -1155,7 +1122,7 @@ void LogicAnalyzer::on_btnStreamOneShot_toggled(bool toggled) m_m2kDigital->getTrigger()->setDigitalStreamingFlag(toggled); - if (toggled) { // oneshot + if(toggled) { // oneshot m_plot.cancelZoom(); m_timePositionButton->setValue(m_timeTriggerOffset * m_sampleRate); m_plot.setHorizOffset(1.0 / m_sampleRate * m_bufferSize / 2.0 + m_timeTriggerOffset); @@ -1171,11 +1138,10 @@ void LogicAnalyzer::on_btnStreamOneShot_toggled(bool toggled) m_plot.zoomBaseUpdate(); } - m_bufferSizeButton->setMaxValue(toggled ? MAX_BUFFER_SIZE_ONESHOT - : MAX_BUFFER_SIZE_STREAM); + m_bufferSizeButton->setMaxValue(toggled ? MAX_BUFFER_SIZE_ONESHOT : MAX_BUFFER_SIZE_STREAM); m_bufferPreviewer->setCursorVisible(toggled); - if (wasRunning) { + if(wasRunning) { startStop(true); } } @@ -1185,11 +1151,11 @@ void LogicAnalyzer::on_btnGroupChannels_toggled(bool checked) qDebug() << checked; ui->btnGroupChannels->setText(checked ? "Done" : "Group"); - if (checked) { + if(checked) { m_plot.beginGroupSelection(); } else { - if (m_plot.endGroupSelection()) { -// channelSelectedChanged(m_selectedChannel, false); + if(m_plot.endGroupSelection()) { + // channelSelectedChanged(m_selectedChannel, false); } } } @@ -1200,9 +1166,9 @@ void LogicAnalyzer::channelSelectedChanged(int chIdx, bool selected) QSignalBlocker traceHeightLineEditBlocker(ui->traceHeightLineEdit); QSignalBlocker traceColorComboBoxBlocker(ui->traceColorComboBox); QSignalBlocker triggerComboBoxBlocker(ui->triggerComboBox); - if (m_selectedChannel != chIdx && selected) { + if(m_selectedChannel != chIdx && selected) { - if (!ui->btnChannelSettings->isChecked()) { + if(!ui->btnChannelSettings->isChecked()) { ui->btnChannelSettings->setChecked(true); } @@ -1210,7 +1176,7 @@ void LogicAnalyzer::channelSelectedChanged(int chIdx, bool selected) m_selectedChannel = chIdx; - if (m_selectedChannel < m_nbChannels) { + if(m_selectedChannel < m_nbChannels) { ui->hardwareName->setText("DIO " + QString::number(m_selectedChannel)); } else { ui->hardwareName->setText(""); @@ -1219,14 +1185,13 @@ void LogicAnalyzer::channelSelectedChanged(int chIdx, bool selected) ui->nameLineEdit->setEnabled(true); ui->nameLineEdit->setText(m_plotCurves[m_selectedChannel]->getName()); ui->traceHeightLineEdit->setEnabled(true); - ui->traceHeightLineEdit->setText( - QString::number(m_plotCurves[m_selectedChannel]->getTraceHeight())); + ui->traceHeightLineEdit->setText(QString::number(m_plotCurves[m_selectedChannel]->getTraceHeight())); // Sync color ui->traceColorComboBox->setEnabled(true); - const auto traceColorindex = ui->traceColorComboBox->findData( - m_plotCurves[m_selectedChannel]->getTraceColor().name()); - if (traceColorindex >= 0) { + const auto traceColorindex = + ui->traceColorComboBox->findData(m_plotCurves[m_selectedChannel]->getTraceColor().name()); + if(traceColorindex >= 0) { ui->traceColorComboBox->setCurrentIndex(traceColorindex); } @@ -1236,14 +1201,14 @@ void LogicAnalyzer::channelSelectedChanged(int chIdx, bool selected) updateChannelGroupWidget(true); - if (m_selectedChannel < m_nbChannels) { + if(m_selectedChannel < m_nbChannels) { ui->triggerComboBox->setVisible(true); ui->labelTrigger->setVisible(true); - int condition = static_cast( - m_m2kDigital->getTrigger()->getDigitalCondition(m_selectedChannel)); + int condition = + static_cast(m_m2kDigital->getTrigger()->getDigitalCondition(m_selectedChannel)); ui->triggerComboBox->setCurrentIndex((condition + 1) % 6); - if (m_decoderMenu) { + if(m_decoderMenu) { ui->decoderSettingsLayout->removeWidget(m_decoderMenu); m_decoderMenu->deleteLater(); m_decoderMenu = nullptr; @@ -1254,7 +1219,7 @@ void LogicAnalyzer::channelSelectedChanged(int chIdx, bool selected) } else { ui->triggerComboBox->setVisible(false); ui->labelTrigger->setVisible(false); - if (m_decoderMenu) { + if(m_decoderMenu) { ui->decoderSettingsLayout->removeWidget(m_decoderMenu); m_decoderMenu->deleteLater(); m_decoderMenu = nullptr; @@ -1265,7 +1230,7 @@ void LogicAnalyzer::channelSelectedChanged(int chIdx, bool selected) updateStackDecoderButton(); } - } else if (m_selectedChannel == chIdx && !selected) { + } else if(m_selectedChannel == chIdx && !selected) { m_selectedChannel = -1; ui->hardwareName->setText(""); ui->nameLineEdit->setDisabled(true); @@ -1275,8 +1240,7 @@ void LogicAnalyzer::channelSelectedChanged(int chIdx, bool selected) ui->triggerComboBox->setDisabled(true); ui->triggerComboBox->setCurrentIndex(0); - - if (m_decoderMenu) { + if(m_decoderMenu) { ui->decoderSettingsLayout->removeWidget(m_decoderMenu); m_decoderMenu->deleteLater(); m_decoderMenu = nullptr; @@ -1293,7 +1257,7 @@ void LogicAnalyzer::setupUi() ui->setupUi(this); // Hide the run button -// ui->runSingleWidget->enableRunButton(false); + // ui->runSingleWidget->enableRunButton(false); int gsettings_panel = ui->stackedWidget->indexOf(ui->generalSettings); ui->btnGeneralSettings->setProperty("id", QVariant(-gsettings_panel)); @@ -1322,11 +1286,10 @@ void LogicAnalyzer::setupUi() // Plot positioning and settings m_plot.disableLegend(); - // Build central widget - QWidget* centralWidget = new QWidget(this); - QVBoxLayout* vLayout = new QVBoxLayout(centralWidget); + QWidget *centralWidget = new QWidget(this); + QVBoxLayout *vLayout = new QVBoxLayout(centralWidget); vLayout->setContentsMargins(0, 0, 0, 0); vLayout->setSpacing(0); @@ -1335,17 +1298,16 @@ void LogicAnalyzer::setupUi() vLayout->addWidget(ui->hLayoutBufferPreview); // add plot elements - QWidget* plotWidget = new QWidget(this); + QWidget *plotWidget = new QWidget(this); plotWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored); - QGridLayout* gridLayout = new QGridLayout(plotWidget); + QGridLayout *gridLayout = new QGridLayout(plotWidget); gridLayout->setVerticalSpacing(0); gridLayout->setHorizontalSpacing(0); gridLayout->setContentsMargins(15, 0, 15, 0); plotWidget->setLayout(gridLayout); plotWidget->setMinimumWidth(200); - QSpacerItem *plotSpacer = new QSpacerItem(0, 5, - QSizePolicy::Fixed, QSizePolicy::Fixed); + QSpacerItem *plotSpacer = new QSpacerItem(0, 5, QSizePolicy::Fixed, QSizePolicy::Fixed); gridLayout->addWidget(m_plot.topArea(), 0, 0, 1, 4); gridLayout->addWidget(m_plot.topHandlesArea(), 1, 0, 1, 4); @@ -1376,14 +1338,13 @@ void LogicAnalyzer::setupUi() m_bufferPreviewer->setMinimumHeight(20); m_bufferPreviewer->setMaximumHeight(20); m_bufferPreviewer->setMinimumWidth(200); -// m_bufferPreviewer->setMaximumWidth(375); + // m_bufferPreviewer->setMaximumWidth(375); m_bufferPreviewer->setCursorPos(0.5); m_bufferPreviewer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); ui->vLayoutBufferSlot->addWidget(m_bufferPreviewer); - // Setup sweep settings menu ui->sweepSettingLayout->addWidget(m_sampleRateButton); @@ -1394,8 +1355,8 @@ void LogicAnalyzer::setupUi() // Setup channel / decoder menu - for (const auto &name : QColor::colorNames()) { - QPixmap pixmap(100,100); + for(const auto &name : QColor::colorNames()) { + QPixmap pixmap(100, 100); QColor color(name); pixmap.fill(color); QIcon colorIcon(pixmap); @@ -1418,9 +1379,7 @@ void LogicAnalyzer::setupUi() cursorsPositionButton = new CustomPlotPositionButton(cr_ui->posSelect); connect(cursorsPositionButton, &CustomPlotPositionButton::positionChanged, - [=](CustomPlotPositionButton::ReadoutsPosition position){ - m_plot.moveCursorReadouts(position); - }); + [=](CustomPlotPositionButton::ReadoutsPosition position) { m_plot.moveCursorReadouts(position); }); cursorsPositionButton->setPosition(CustomPlotPositionButton::ReadoutsPosition::bottomRight); @@ -1447,13 +1406,11 @@ void LogicAnalyzer::setupUi() m_exportSettings = new ExportSettings(this); m_exportSettings->enableExportButton(false); ui->exportLayout->addWidget(m_exportSettings); - for (int i = 0; i < DIGITAL_NR_CHANNELS; ++i) { + for(int i = 0; i < DIGITAL_NR_CHANNELS; ++i) { m_exportSettings->addChannel(i, "DIO" + QString::number(i)); } m_exportSettings->disableUIMargins(); - connect(m_exportSettings->getExportButton(), &QPushButton::clicked, - this, &LogicAnalyzer::exportData); - + connect(m_exportSettings->getExportButton(), &QPushButton::clicked, this, &LogicAnalyzer::exportData); // Filter in decoder table filterMessages = new DropdownSwitchList(1, this); @@ -1461,31 +1418,29 @@ void LogicAnalyzer::setupUi() filterMessages->setColumnTitle(0, tr("Type")); filterMessages->setColumnTitle(1, tr("Visible")); - connect(filterMessages->model(), - SIGNAL(itemChanged(QStandardItem*)), - SLOT(onFilterChanged(QStandardItem*))); + connect(filterMessages->model(), SIGNAL(itemChanged(QStandardItem *)), SLOT(onFilterChanged(QStandardItem *))); ui->filterLayout->addWidget(filterMessages); - connect(ui->btnTableExport, &QPushButton::clicked, - ui->decoderTableView, &DecoderTable::exportData); + connect(ui->btnTableExport, &QPushButton::clicked, ui->decoderTableView, &DecoderTable::exportData); } void LogicAnalyzer::onFilterChanged(QStandardItem *item) { - if (!ui->decoderTableView->decoderModel()) + if(!ui->decoderTableView->decoderModel()) return; auto name = item->model()->item(item->index().row(), 0)->text(); int column = ui->decoderTableView->decoderModel()->getCurrentColumn(); auto filtered = ui->decoderTableView->decoderModel()->getFiltered()[column]; - if (item->data(Qt::EditRole).toBool() && filtered.contains(name)) { - for (int i=0; idecoderTableView->decoderModel()->getFiltered()[column].remove(i); ; + if(item->data(Qt::EditRole).toBool() && filtered.contains(name)) { + for(int i = 0; i < filtered.size(); i++) { + if(filtered[i] == name) { + ui->decoderTableView->decoderModel()->getFiltered()[column].remove(i); + ; } } - } else if (!item->data(Qt::EditRole).toBool() && !filtered.contains(name)) { + } else if(!item->data(Qt::EditRole).toBool() && !filtered.contains(name)) { ui->decoderTableView->decoderModel()->getFiltered()[column].append(name); } @@ -1496,21 +1451,18 @@ void LogicAnalyzer::onFilterChanged(QStandardItem *item) void LogicAnalyzer::addFilterRow(QIcon icon, QString name) { filterMessages->addDropdownElement(icon, name); - filterCount ++; + filterCount++; } void LogicAnalyzer::clearFilter() { - for (int i = 0; i< filterCount; i++) { + for(int i = 0; i < filterCount; i++) { filterMessages->removeItem(0); } filterCount = 0; } -bool LogicAnalyzer::getTableInfo() -{ - return m_tableInfo; -} +bool LogicAnalyzer::getTableInfo() { return m_tableInfo; } bool LogicAnalyzer::setPrimaryAnntations(int column, int index) { @@ -1519,44 +1471,33 @@ bool LogicAnalyzer::setPrimaryAnntations(int column, int index) auto curve = dynamic_cast(getPlotCurves(true)[DIGITAL_NR_CHANNELS + column]); std::map decoder(curve->getAnnotationRows()); - for (int row = 0; row < curve->getAnnotationRows().size(); ++row) { - auto it = std::find_if(curve->getAnnotationRows().begin(), curve->getAnnotationRows().end(), - [row](const std::pair &t) -> bool{ - return t.first.index() == row; - }); + for(int row = 0; row < curve->getAnnotationRows().size(); ++row) { + auto it = std::find_if( + curve->getAnnotationRows().begin(), curve->getAnnotationRows().end(), + [row](const std::pair &t) -> bool { return t.first.index() == row; }); - if (!it->second.get_annotations().empty()) { + if(!it->second.get_annotations().empty()) { auto title = curve->fromTitleToRowType(it->first.title()); ui->primaryAnnotationComboBox->addItem(title, it->first.index()); } - } - if (index != ui->primaryAnnotationComboBox->currentData().toInt()) { + if(index != ui->primaryAnnotationComboBox->currentData().toInt()) { changed = true; } - if (index != -1) { + if(index != -1) { ui->primaryAnnotationComboBox->setCurrentIndex(ui->primaryAnnotationComboBox->findData(index)); } return changed; } -QComboBox* LogicAnalyzer::getDecoderComboBox() -{ - return ui->DecoderComboBox; -} +QComboBox *LogicAnalyzer::getDecoderComboBox() { return ui->DecoderComboBox; } -void LogicAnalyzer::enableRunButton(bool flag) -{ - ui->runSingleWidget->getRunButton()->setEnabled(flag); -} +void LogicAnalyzer::enableRunButton(bool flag) { ui->runSingleWidget->getRunButton()->setEnabled(flag); } -void LogicAnalyzer::enableSingleButton(bool flag) -{ - ui->runSingleWidget->getSingleButton()->setEnabled(flag); -} +void LogicAnalyzer::enableSingleButton(bool flag) { ui->runSingleWidget->getSingleButton()->setEnabled(flag); } void LogicAnalyzer::emitSearchSignal(int index) { @@ -1566,7 +1507,7 @@ void LogicAnalyzer::emitSearchSignal(int index) void LogicAnalyzer::clearSearch(int index) { - if (!ui->decoderTableView->decoderModel()) + if(!ui->decoderTableView->decoderModel()) return; ui->searchBox->clear(); @@ -1577,16 +1518,17 @@ void LogicAnalyzer::PrimaryAnnotationChanged(int index) { clearSearch(); - if (index == -1) { + if(index == -1) { index = 0; ui->primaryAnnotationComboBox->setCurrentIndex(index); } - ui->decoderTableView->decoderModel()->setPrimaryAnnotation(ui->primaryAnnotationComboBox->currentData().toInt()); + ui->decoderTableView->decoderModel()->setPrimaryAnnotation( + ui->primaryAnnotationComboBox->currentData().toInt()); } void LogicAnalyzer::selectedDecoderChanged(int index) { - if (ui->decoderTableView->decoderModel()) { + if(ui->decoderTableView->decoderModel()) { ui->decoderTableView->decoderModel()->selectedDecoderChanged(index); } } @@ -1601,14 +1543,14 @@ void LogicAnalyzer::waitForDecoders() while(this->isVisible()) { usleep(100); all_finished = true; - for (int row = DIGITAL_NR_CHANNELS; row < m_plotCurves.size(); row++) { - auto curve = dynamic_cast(m_plotCurves[row]); - if (abs(curve->getState()) != 2) { + for(int row = DIGITAL_NR_CHANNELS; row < m_plotCurves.size(); row++) { + auto curve = dynamic_cast(m_plotCurves[row]); + if(abs(curve->getState()) != 2) { all_finished = false; break; } } - if (all_finished) { + if(all_finished) { break; } } @@ -1617,15 +1559,9 @@ void LogicAnalyzer::waitForDecoders() setStatusLabel(""); } -int LogicAnalyzer::getGroupSize() -{ - return (ui->groupSizeSpinBox->value() != 0) ? ui->groupSizeSpinBox->value() : 1; -} +int LogicAnalyzer::getGroupSize() { return (ui->groupSizeSpinBox->value() != 0) ? ui->groupSizeSpinBox->value() : 1; } -int LogicAnalyzer::getGroupOffset() -{ - return ui->groupOffsetSpinBox->value(); -} +int LogicAnalyzer::getGroupOffset() { return ui->groupOffsetSpinBox->value(); } void LogicAnalyzer::setMaxGroupValues(int value) { @@ -1636,14 +1572,11 @@ void LogicAnalyzer::setMaxGroupValues(int value) ui->groupOffsetSpinBox->setMinimum(0); } -void LogicAnalyzer::setStatusLabel(QString text) -{ - ui->statusLabel->setText(text); -} +void LogicAnalyzer::setStatusLabel(QString text) { ui->statusLabel->setText(text); } void LogicAnalyzer::activateRunButton(bool en) { - if (!en && getTme()->running()) { + if(!en && getTme()->running()) { getTme()->setRunning(false); } @@ -1655,29 +1588,28 @@ void LogicAnalyzer::connectSignalsAndSlots() { // connect all the signals and slots here - - connect(ui->primaryAnnotationComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(PrimaryAnnotationChanged(int))); -// connect(ui->primaryAnnotationComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(emitSearchSignal(int))); + connect(ui->primaryAnnotationComboBox, SIGNAL(currentIndexChanged(int)), this, + SLOT(PrimaryAnnotationChanged(int))); + // connect(ui->primaryAnnotationComboBox, SIGNAL(currentIndexChanged(int)), this, + // SLOT(emitSearchSignal(int))); connect(ui->DecoderComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(selectedDecoderChanged(int))); -// connect(ui->DecoderComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(clearSearch(int))); + // connect(ui->DecoderComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(clearSearch(int))); - connect(ui->runSingleWidget->getSingleButton(), &QPushButton::toggled, this, - [=](bool checked){ - if (checked) { - if (ui->decoderTableView->isActive()) { + connect(ui->runSingleWidget->getSingleButton(), &QPushButton::toggled, this, [=](bool checked) { + if(checked) { + if(ui->decoderTableView->isActive()) { ui->decoderTableView->blockSignals(true); QFuture future = QtConcurrent::run(this, &LogicAnalyzer::waitForDecoders); QFutureWatcher *watcher = new QFutureWatcher(this); - connect(watcher, &QFutureWatcher::finished, this, [=](){ + connect(watcher, &QFutureWatcher::finished, this, [=]() { ui->decoderTableView->blockSignals(false); int currentCol = ui->decoderTableView->decoderModel()->getCurrentColumn(); ui->decoderTableView->decoderModel()->refreshSettings(currentCol); ui->DecoderComboBox->setCurrentIndex(currentCol); - }); connect(watcher, SIGNAL(finished()), watcher, SLOT(deleteLater())); watcher->setFuture(future); @@ -1689,32 +1621,25 @@ void LogicAnalyzer::connectSignalsAndSlots() connect(ui->groupOffsetSpinBox, SIGNAL(valueChanged(int)), ui->decoderTableView, SLOT(groupValuesChanged(int))); - connect(ui->searchBox, &QLineEdit::returnPressed, - [=](){ + connect(ui->searchBox, &QLineEdit::returnPressed, [=]() { QString text = ui->searchBox->text(); ui->decoderTableView->decoderModel()->searchBoxSlot(text); }); - connect(ui->runSingleWidget, &RunSingleWidget::toggled, - [=](bool checked){ + connect(ui->runSingleWidget, &RunSingleWidget::toggled, [=](bool checked) { tme->setRunning(checked); -// if (!checked) { -// m_plot.setTriggerState(CapturePlot::Stop); -// } + // if (!checked) { + // m_plot.setTriggerState(CapturePlot::Stop); + // } }); - connect(tme, &ToolMenuEntry::runToggled, - ui->runSingleWidget, &RunSingleWidget::toggle); - connect(ui->runSingleWidget, &RunSingleWidget::toggled, - this, &LogicAnalyzer::startStop); - - - connect(ui->rightMenu, &MenuHAnim::finished, - this, &LogicAnalyzer::rightMenuFinished); + connect(tme, &ToolMenuEntry::runToggled, ui->runSingleWidget, &RunSingleWidget::toggle); + connect(ui->runSingleWidget, &RunSingleWidget::toggled, this, &LogicAnalyzer::startStop); + connect(ui->rightMenu, &MenuHAnim::finished, this, &LogicAnalyzer::rightMenuFinished); // TODO: can be moved away from here into on_cursorsBox_toggled - connect(ui->cursorsBox, &QCheckBox::toggled, [=](bool toggled){ - if (!toggled) { + connect(ui->cursorsBox, &QCheckBox::toggled, [=](bool toggled) { + if(!toggled) { // make sure to deselect the cursors button if // the cursors are disabled ui->btnCursors->setChecked(false); @@ -1726,66 +1651,58 @@ void LogicAnalyzer::connectSignalsAndSlots() } }); - connect(&m_plot, &CapturePlot::plotSizeChanged, [=](){ + connect(&m_plot, &CapturePlot::plotSizeChanged, [=]() { m_bufferPreviewer->setFixedWidth(m_plot.canvas()->size().width()); m_plotScrollBar->setFixedHeight(m_plot.canvas()->size().height()); }); // some conenctions for the cursors menu - connect(cr_ui->hCursorsEnable, &CustomSwitch::toggled, - &m_plot, &CapturePlot::setVertCursorsEnabled); - connect(cr_ui->btnLockHorizontal, &QPushButton::toggled, - &m_plot, &CapturePlot::setHorizCursorsLocked); + connect(cr_ui->hCursorsEnable, &CustomSwitch::toggled, &m_plot, &CapturePlot::setVertCursorsEnabled); + connect(cr_ui->btnLockHorizontal, &QPushButton::toggled, &m_plot, &CapturePlot::setHorizCursorsLocked); - connect(cr_ui->horizontalSlider, &QSlider::valueChanged, [=](int value){ + connect(cr_ui->horizontalSlider, &QSlider::valueChanged, [=](int value) { cr_ui->transLabel->setText(tr("Transparency ") + QString::number(value) + "%"); m_plot.setCursorReadoutsTransparency(value); }); // default: full transparency cr_ui->horizontalSlider->setSliderPosition(100); - connect(m_plot.getZoomer(), &OscPlotZoomer::zoomFinished, [=](bool isZoomOut){ - updateBufferPreviewer(0, m_lastCapturedSample); - }); + connect(m_plot.getZoomer(), &OscPlotZoomer::zoomFinished, + [=](bool isZoomOut) { updateBufferPreviewer(0, m_lastCapturedSample); }); - connect(m_sampleRateButton, &ScaleSpinButton::valueChanged, - this, &LogicAnalyzer::onSampleRateValueChanged); - connect(m_bufferSizeButton, &ScaleSpinButton::valueChanged, - this, &LogicAnalyzer::onBufferSizeChanged); + connect(m_sampleRateButton, &ScaleSpinButton::valueChanged, this, &LogicAnalyzer::onSampleRateValueChanged); + connect(m_bufferSizeButton, &ScaleSpinButton::valueChanged, this, &LogicAnalyzer::onBufferSizeChanged); - connect(&m_plot, &CapturePlot::timeTriggerValueChanged, [=](double value){ - double delay = (value - 1.0 / m_sampleRate * m_bufferSize / 2.0 ) / (1.0 / m_sampleRate); + connect(&m_plot, &CapturePlot::timeTriggerValueChanged, [=](double value) { + double delay = (value - 1.0 / m_sampleRate * m_bufferSize / 2.0) / (1.0 / m_sampleRate); m_timePositionButton->setValue(static_cast(delay)); }); - connect(m_timePositionButton, &PositionSpinButton::valueChanged, - this, &LogicAnalyzer::onTimeTriggerValueChanged); - + connect(m_timePositionButton, &PositionSpinButton::valueChanged, this, + &LogicAnalyzer::onTimeTriggerValueChanged); connect(m_plotScrollBar, &QScrollBar::valueChanged, [=](double value) { m_plot.setAllYAxis(-5 - (value * 0.05), 5 - (value * 0.05)); m_plot.replot(); }); - connect(&m_plot, &CapturePlot::channelSelected, - this, &LogicAnalyzer::channelSelectedChanged); + connect(&m_plot, &CapturePlot::channelSelected, this, &LogicAnalyzer::channelSelectedChanged); - connect(ui->nameLineEdit, &QLineEdit::textChanged, [=](const QString &text){ + connect(ui->nameLineEdit, &QLineEdit::textChanged, [=](const QString &text) { m_plot.setChannelName(text, m_selectedChannel); m_plotCurves[m_selectedChannel]->setName(text); }); - connect(ui->traceHeightLineEdit, &QLineEdit::textChanged, [=](const QString &text){ + connect(ui->traceHeightLineEdit, &QLineEdit::textChanged, [=](const QString &text) { auto validator = ui->traceHeightLineEdit->validator(); QString toCheck = text; int pos; - setDynamicProperty(ui->traceHeightLineEdit, - "invalid", + setDynamicProperty(ui->traceHeightLineEdit, "invalid", validator->validate(toCheck, pos) == QIntValidator::Intermediate); }); - connect(ui->traceHeightLineEdit, &QLineEdit::editingFinished, [=](){ + connect(ui->traceHeightLineEdit, &QLineEdit::editingFinished, [=]() { int value = ui->traceHeightLineEdit->text().toInt(); m_plotCurves[m_selectedChannel]->setTraceHeight(value); m_plot.replot(); @@ -1799,47 +1716,48 @@ void LogicAnalyzer::connectSignalsAndSlots() }); connect(ui->triggerComboBox, QOverload::of(&QComboBox::currentIndexChanged), [=](int index) { - m_m2kDigital->getTrigger()->setDigitalCondition(m_selectedChannel, - static_cast((index + 5) % 6)); - QLayout *widgetInLayout = ui->channelEnumeratorLayout->itemAtPosition(m_selectedChannel % 8, - m_selectedChannel / 8)->layout(); + m_m2kDigital->getTrigger()->setDigitalCondition( + m_selectedChannel, static_cast((index + 5) % 6)); + QLayout *widgetInLayout = + ui->channelEnumeratorLayout->itemAtPosition(m_selectedChannel % 8, m_selectedChannel / 8) + ->layout(); auto triggerBox = dynamic_cast(widgetInLayout->itemAt(1)->widget()); QSignalBlocker triggerBlocker(triggerBox); triggerBox->setCurrentIndex(index); }); connect(ui->stackDecoderComboBox, &QComboBox::currentTextChanged, [=](const QString &text) { - if (m_selectedChannel < m_nbChannels) { + if(m_selectedChannel < m_nbChannels) { return; } - if (m_selectedChannel > m_plotCurves.size() - 1) { + if(m_selectedChannel > m_plotCurves.size() - 1) { return; } - if (!ui->stackDecoderComboBox->currentIndex()) { + if(!ui->stackDecoderComboBox->currentIndex()) { return; } AnnotationCurve *curve = dynamic_cast(m_plotCurves[m_selectedChannel]); - if (!curve) { + if(!curve) { return; } GSList *dl = g_slist_copy((GSList *)srd_decoder_list()); - for (const GSList *sl = dl; sl; sl = sl->next) { - srd_decoder *dec = (struct srd_decoder *)sl->data; - if (QString::fromUtf8(dec->id) == text) { - curve->stackDecoder(std::make_shared(dec)); - break; - } + for(const GSList *sl = dl; sl; sl = sl->next) { + srd_decoder *dec = (struct srd_decoder *)sl->data; + if(QString::fromUtf8(dec->id) == text) { + curve->stackDecoder(std::make_shared(dec)); + break; + } } // Update decoder menu. New decoder must be shown // and it might also have some options that can // be modified - if (m_decoderMenu) { + if(m_decoderMenu) { ui->decoderSettingsLayout->removeWidget(m_decoderMenu); m_decoderMenu->deleteLater(); m_decoderMenu = nullptr; @@ -1851,17 +1769,15 @@ void LogicAnalyzer::connectSignalsAndSlots() updateStackDecoderButton(); }); - connect(ui->printBtn, &QPushButton::clicked, [=](){ - m_plot.printWithNoBackground("Logic Analyzer"); - }); + connect(ui->printBtn, &QPushButton::clicked, [=]() { m_plot.printWithNoBackground("Logic Analyzer"); }); - connect(ui->decoderTableView, &DecoderTable::clicked, [=](const QModelIndex& index) { + connect(ui->decoderTableView, &DecoderTable::clicked, [=](const QModelIndex &index) { // When a row is clicked in the decoder table, update the plot // to zoom into the sample area that was clicked. // qDebug() << "Decoder item clicked " << index << Qt::endl; - if (index.data().canConvert()) { + if(index.data().canConvert()) { DecoderTableItem item = qvariant_cast(index.data()); - if (item.curve != nullptr) { + if(item.curve != nullptr) { fitViewport(item.startTime(), item.endTime()); } } @@ -1873,9 +1789,8 @@ void LogicAnalyzer::triggerRightMenuToggle(CustomPushButton *btn, bool checked) // Queue the action, if right menu animation is in progress. This way // the action will be remembered and performed right after the animation // finishes - if (ui->rightMenu->animInProgress()) { - m_menuButtonActions.enqueue( - QPair(btn, checked)); + if(ui->rightMenu->animInProgress()) { + m_menuButtonActions.enqueue(QPair(btn, checked)); } else { toggleRightMenu(btn, checked); } @@ -1888,8 +1803,8 @@ void LogicAnalyzer::toggleRightMenu(CustomPushButton *btn, bool checked) int id = btn->property("id").toInt(); - if (id != -ui->stackedWidget->indexOf(ui->generalSettings)){ - if (!m_menuOrder.contains(btn)){ + if(id != -ui->stackedWidget->indexOf(ui->generalSettings)) { + if(!m_menuOrder.contains(btn)) { m_menuOrder.push_back(btn); } else { m_menuOrder.removeOne(btn); @@ -1897,7 +1812,7 @@ void LogicAnalyzer::toggleRightMenu(CustomPushButton *btn, bool checked) } } - if (checked) { + if(checked) { settingsPanelUpdate(id); } @@ -1906,16 +1821,16 @@ void LogicAnalyzer::toggleRightMenu(CustomPushButton *btn, bool checked) void LogicAnalyzer::settingsPanelUpdate(int id) { - if (id >= 0) { + if(id >= 0) { ui->stackedWidget->setCurrentIndex(0); } else { ui->stackedWidget->setCurrentIndex(-id); } - for (int i = 0; i < ui->stackedWidget->count(); i++) { + for(int i = 0; i < ui->stackedWidget->count(); i++) { QSizePolicy::Policy policy = QSizePolicy::Ignored; - if (i == ui->stackedWidget->currentIndex()) { + if(i == ui->stackedWidget->currentIndex()) { policy = QSizePolicy::Expanding; } QWidget *widget = ui->stackedWidget->widget(i); @@ -1933,9 +1848,8 @@ void LogicAnalyzer::updateBufferPreviewer(int64_t min, int64_t max) QwtInterval dataInterval(0.0, 0.0); long long totalSamples = m_bufferSize; - if (totalSamples > 0) { - const int offset = ui->btnStreamOneShot->isChecked() ? m_timePositionButton->value() - : 0; + if(totalSamples > 0) { + const int offset = ui->btnStreamOneShot->isChecked() ? m_timePositionButton->value() : 0; dataInterval.setMinValue(offset / m_sampleRate); dataInterval.setMaxValue((offset + max) / m_sampleRate); } @@ -1943,21 +1857,17 @@ void LogicAnalyzer::updateBufferPreviewer(int64_t min, int64_t max) // Use the two intervals to determine the width and position of the // waveform and of the highlighted area QwtInterval fullInterval = plotInterval | dataInterval; - double wPos = 1 - (fullInterval.maxValue() - dataInterval.minValue()) / - fullInterval.width(); + double wPos = 1 - (fullInterval.maxValue() - dataInterval.minValue()) / fullInterval.width(); double wWidth = dataInterval.width() / fullInterval.width(); - double hPos = 1 - (fullInterval.maxValue() - plotInterval.minValue()) / - fullInterval.width(); + double hPos = 1 - (fullInterval.maxValue() - plotInterval.minValue()) / fullInterval.width(); double hWidth = plotInterval.width() / fullInterval.width(); // Determine the cursor position - QwtInterval containerInterval = (totalSamples > 0) ? dataInterval : - fullInterval; + QwtInterval containerInterval = (totalSamples > 0) ? dataInterval : fullInterval; double containerWidth = (totalSamples > 0) ? wWidth : 1; double containerPos = (totalSamples > 0) ? wPos : 0; - double cPosInContainer = 1 - (containerInterval.maxValue() - 0) / - containerInterval.width(); + double cPosInContainer = 1 - (containerInterval.maxValue() - 0) / containerInterval.width(); double cPos = cPosInContainer * containerWidth + containerPos; // Update the widget @@ -1970,9 +1880,8 @@ void LogicAnalyzer::updateBufferPreviewer(int64_t min, int64_t max) void LogicAnalyzer::initBufferScrolling() { - connect(m_plot.getZoomer(), &OscPlotZoomer::zoomFinished, [=](bool isZoomOut){ - m_horizOffset = m_plot.HorizOffset(); - }); + connect(m_plot.getZoomer(), &OscPlotZoomer::zoomFinished, + [=](bool isZoomOut) { m_horizOffset = m_plot.HorizOffset(); }); connect(m_bufferPreviewer, &BufferPreviewer::bufferMovedBy, [=](int value) { m_resetHorizAxisOffset = false; @@ -1988,27 +1897,28 @@ void LogicAnalyzer::initBufferScrolling() m_plot.replot(); updateBufferPreviewer(0, m_lastCapturedSample); }); - connect(m_bufferPreviewer, &BufferPreviewer::bufferStopDrag, [=](){ + connect(m_bufferPreviewer, &BufferPreviewer::bufferStopDrag, [=]() { m_horizOffset = m_plot.HorizOffset(); m_resetHorizAxisOffset = true; }); - connect(m_bufferPreviewer, &BufferPreviewer::bufferResetPosition, [=](){ + connect(m_bufferPreviewer, &BufferPreviewer::bufferResetPosition, [=]() { m_plot.setHorizOffset(1.0 / m_sampleRate * m_bufferSize / 2.0 + (ui->btnStreamOneShot ? 0 : m_timeTriggerOffset / m_sampleRate)); m_plot.replot(); updateBufferPreviewer(0, m_lastCapturedSample); m_horizOffset = 1.0 / m_sampleRate * m_bufferSize / 2.0 + - (ui->btnStreamOneShot ? 0 : m_timeTriggerOffset / m_sampleRate); + (ui->btnStreamOneShot ? 0 : m_timeTriggerOffset / m_sampleRate); }); // When the plot is clicked emit the clicked signal on the curve m_plot.setMouseTracking(true); connect(&m_plot, &CapturePlot::mouseButtonRelease, [=](const QMouseEvent *event) { - if (event == nullptr) return; + if(event == nullptr) + return; - if (event->button() == Qt::LeftButton) { + if(event->button() == Qt::LeftButton) { // qDebug() << "Plot clicked" << Qt::endl; - if (const auto curve = m_plot.curveAt(event->pos())) { + if(const auto curve = m_plot.curveAt(event->pos())) { const QPointF p = curve->screenPosToCurvePoint(event->pos()); Q_EMIT curve->clicked(p); } @@ -2018,7 +1928,7 @@ void LogicAnalyzer::initBufferScrolling() void LogicAnalyzer::fitViewport(double min, double max) { - if (min > max) { + if(min > max) { return; } @@ -2026,7 +1936,7 @@ void LogicAnalyzer::fitViewport(double min, double max) auto dx = max - min; // for 1 sample long annotations - if (min == max) { + if(min == max) { dx = 0.0001; min -= 0.00005; } @@ -2044,9 +1954,9 @@ void LogicAnalyzer::fitViewport(double min, double max) void LogicAnalyzer::resetViewport() { - if (ui->btnStreamOneShot->isChecked()) { // oneshot + if(ui->btnStreamOneShot->isChecked()) { // oneshot m_plot.cancelZoom(); -// m_timePositionButton->setValue(m_timeTriggerOffset * m_sampleRate); + // m_timePositionButton->setValue(m_timeTriggerOffset * m_sampleRate); m_plot.setHorizOffset(1.0 / m_sampleRate * m_bufferSize / 2.0 + m_timeTriggerOffset); m_horizOffset = 1.0 / m_sampleRate * m_bufferSize / 2.0 + m_timeTriggerOffset; m_plot.replot(); @@ -2069,23 +1979,25 @@ void LogicAnalyzer::resetViewport() updateBufferPreviewer(0, m_lastCapturedSample); - double maxT = (1 << 13) * (1.0 / m_sampleRate) - 1.0 / m_sampleRate * m_bufferSize / 2.0; // 8192 * time between samples - double minT = -((1 << 13) - 1) * (1.0 / m_sampleRate) - 1.0 / m_sampleRate * m_bufferSize / 2.0; // (2 << 13) - 1 max hdl fifo depth + double maxT = (1 << 13) * (1.0 / m_sampleRate) - + 1.0 / m_sampleRate * m_bufferSize / 2.0; // 8192 * time between samples + double minT = -((1 << 13) - 1) * (1.0 / m_sampleRate) - + 1.0 / m_sampleRate * m_bufferSize / 2.0; // (2 << 13) - 1 max hdl fifo depth m_plot.setTimeTriggerInterval(minT, maxT); } void LogicAnalyzer::startStop(bool start) { - if (m_started == start) { - return; + if(m_started == start) { + return; } m_started = start; m_plot.startStop(start); m_triggerUpdater->setEnabled(start); - if (start) { - if (m_captureThread) { + if(start) { + if(m_captureThread) { m_stopRequested = true; m_captureThread->join(); delete m_captureThread; @@ -2100,24 +2012,22 @@ void LogicAnalyzer::startStop(bool start) m_m2kDigital->stopAcquisition(); - const double sampleRate = m_sampleRateButton->value(); const uint64_t bufferSize = m_bufferSizeButton->value(); - const int bufferSizeAdjusted = static_cast(((bufferSize + 3 ) / 4) * 4); + const int bufferSizeAdjusted = static_cast(((bufferSize + 3) / 4) * 4); m_bufferSizeButton->setValue(bufferSizeAdjusted); const bool oneShotOrStream = ui->btnStreamOneShot->isChecked(); qDebug() << "stream one shot is set to: " << oneShotOrStream; - const double delay = oneShotOrStream ? m_timeTriggerOffset * m_sampleRate - : 0; + const double delay = oneShotOrStream ? m_timeTriggerOffset * m_sampleRate : 0; const double setSampleRate = m_m2kDigital->setSampleRateIn((sampleRate + 1)); m_sampleRateButton->setValue(setSampleRate); m_m2kDigital->getTrigger()->setDigitalStreamingFlag(!oneShotOrStream); - for (int i = 0; i < m_plotCurves.size(); ++i) { + for(int i = 0; i < m_plotCurves.size(); ++i) { QwtPlotCurve *curve = m_plot.getDigitalPlotCurve(i); GenericLogicPlotCurve *logic_curve = dynamic_cast(curve); logic_curve->reset(); @@ -2129,17 +2039,15 @@ void LogicAnalyzer::startStop(bool start) m_lastCapturedSample = 0; - m_captureThread = new std::thread([=](){ - - if (m_buffer) { + m_captureThread = new std::thread([=]() { + if(m_buffer) { delete[] m_buffer; m_buffer = nullptr; } m_buffer = new uint16_t[bufferSizeAdjusted]; - QMetaObject::invokeMethod(this, [=](){ - m_exportSettings->enableExportButton(true); - }, Qt::DirectConnection); + QMetaObject::invokeMethod( + this, [=]() { m_exportSettings->enableExportButton(true); }, Qt::DirectConnection); uint64_t totalSamples = bufferSizeAdjusted; uint64_t chunk_size = 0; @@ -2149,10 +2057,10 @@ void LogicAnalyzer::startStop(bool start) // clear any warning m_plot.setMaxBufferSizeErrorLabel(false); - if (oneShotOrStream) { // oneshot + if(oneShotOrStream) { // oneshot try { m_m2kDigital->setKernelBuffersCountIn(1); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { qDebug() << e.what(); } @@ -2167,8 +2075,8 @@ void LogicAnalyzer::startStop(bool start) /* ensure we have the minimum amount of kernel buffers to fit the buffer * ex: we want to capture a 40M buffer, we will use (at least) 10 kernel buffers * */ - while (bufferSizeAdjusted > (m_currentKernelBuffers * oneBufferMaxSize) - && m_currentKernelBuffers < MAX_KERNEL_BUFFERS) { + while(bufferSizeAdjusted > (m_currentKernelBuffers * oneBufferMaxSize) && + m_currentKernelBuffers < MAX_KERNEL_BUFFERS) { m_currentKernelBuffers++; } @@ -2176,9 +2084,9 @@ void LogicAnalyzer::startStop(bool start) * further divide it into smaller buffers (kernel buffers still available) * */ const double maxCaptureDuration = 0.1; // 100ms - while (((static_cast(bufferSizeAdjusted) / setSampleRate) - / static_cast(m_currentKernelBuffers)) > maxCaptureDuration - && m_currentKernelBuffers < MAX_KERNEL_BUFFERS) { + while(((static_cast(bufferSizeAdjusted) / setSampleRate) / + static_cast(m_currentKernelBuffers)) > maxCaptureDuration && + m_currentKernelBuffers < MAX_KERNEL_BUFFERS) { m_currentKernelBuffers++; } @@ -2191,30 +2099,32 @@ void LogicAnalyzer::startStop(bool start) chunk_size = 4 * (chunk_size / 4); /* If the chunk_size was not disible by 4 in the first place we would get a smaller - * value for it. Let's check if we can increase the chunk_size to the next divisible by 4 - * number otherwise we need to add another kernel buffer if this is possible + * value for it. Let's check if we can increase the chunk_size to the next divisible by + * 4 number otherwise we need to add another kernel buffer if this is possible * */ - if (chunk_size + 4 <= oneBufferMaxSize && chunkSizeBeforeAdjust != chunk_size) { + if(chunk_size + 4 <= oneBufferMaxSize && chunkSizeBeforeAdjust != chunk_size) { chunk_size += 4; } // If the buffer size is > 64 * 4M we need to cap the chunk_size to 4M - if (chunk_size > oneBufferMaxSize) { + if(chunk_size > oneBufferMaxSize) { chunk_size = oneBufferMaxSize; } - if (bufferSizeAdjusted >= MAX_KERNEL_BUFFERS * oneBufferMaxSize) { + if(bufferSizeAdjusted >= MAX_KERNEL_BUFFERS * oneBufferMaxSize) { /* in this case if the sample rate is greater than 5M samples / s * warn that data might not be continuos * */ - if (setSampleRate > MAX_SR_STREAM) { - m_plot.setMaxBufferSizeErrorLabel(true, "Data might not be continuous, lower sample rate or buffer size"); + if(setSampleRate > MAX_SR_STREAM) { + m_plot.setMaxBufferSizeErrorLabel(true, + "Data might not be continuous, lower " + "sample rate or buffer size"); } } try { m_m2kDigital->setKernelBuffersCountIn(m_currentKernelBuffers); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { qDebug() << e.what(); } @@ -2237,56 +2147,51 @@ void LogicAnalyzer::startStop(bool start) const uint64_t captureSize = std::min(chunk_size, totalSamples); try { - if (m_autoMode) { - QMetaObject::invokeMethod(this, [=](){ - m_timer->start(oneBufferTimeout); - }); + if(m_autoMode) { + QMetaObject::invokeMethod(this, + [=]() { m_timer->start(oneBufferTimeout); }); } - const uint16_t * const temp = m_m2kDigital->getSamplesP(chunk_size); + const uint16_t *const temp = m_m2kDigital->getSamplesP(chunk_size); memcpy(m_buffer + absIndex, temp, sizeof(uint16_t) * captureSize); absIndex += captureSize; totalSamples -= captureSize; - if (m_autoMode) { - QMetaObject::invokeMethod(this, [=](){ - m_timer->stop(); - }); + if(m_autoMode) { + QMetaObject::invokeMethod(this, [=]() { m_timer->stop(); }); } - if (m_triggerState.empty()) { - QMetaObject::invokeMethod(this, [=](){ - m_triggerUpdater->setInput(CapturePlot::Triggered); - }, Qt::QueuedConnection); + if(m_triggerState.empty()) { + QMetaObject::invokeMethod( + this, + [=]() { m_triggerUpdater->setInput(CapturePlot::Triggered); }, + Qt::QueuedConnection); } else { - QMetaObject::invokeMethod(this, [=](){ - m_triggerUpdater->setInput(CapturePlot::Auto); - }, Qt::QueuedConnection); + QMetaObject::invokeMethod( + this, [=]() { m_triggerUpdater->setInput(CapturePlot::Auto); }, + Qt::QueuedConnection); } - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { qDebug() << e.what() << " code: " << e.iioCode(); break; } - if (m_stopRequested) { + if(m_stopRequested) { break; } Q_EMIT dataAvailable(absIndex - captureSize, absIndex, m_buffer); QMetaObject::invokeMethod(&m_plot, // trigger replot on Main Thread - "replot", - Qt::QueuedConnection); + "replot", Qt::QueuedConnection); m_lastCapturedSample = absIndex; updateBufferPreviewer(0, m_lastCapturedSample); - QMetaObject::invokeMethod(this, - "restoreTriggerState", - Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "restoreTriggerState", Qt::QueuedConnection); - if (!totalSamples && ui->runSingleWidget->runButtonChecked()) { + if(!totalSamples && ui->runSingleWidget->runButtonChecked()) { m_m2kDigital->stopAcquisition(); { std::unique_lock lock(m_acquisitionStartedMutex); @@ -2310,42 +2215,37 @@ void LogicAnalyzer::startStop(bool start) int ms = (int)(1000.0 / fps); std::this_thread::sleep_for(std::chrono::milliseconds(ms)); } - } while (totalSamples && !m_stopRequested); + } while(totalSamples && !m_stopRequested); m_started = false; - if (ui->runSingleWidget->singleButtonChecked()) { - QMetaObject::invokeMethod(ui->runSingleWidget, - "toggle", - Qt::QueuedConnection, + if(ui->runSingleWidget->singleButtonChecked()) { + QMetaObject::invokeMethod(ui->runSingleWidget, "toggle", Qt::QueuedConnection, Q_ARG(bool, false)); m_triggerUpdater->setEnabled(false); } m_m2kDigital->stopAcquisition(); - QMetaObject::invokeMethod(&m_plot, - "replot"); - - QMetaObject::invokeMethod(this, [=](){ - m_exportSettings->enableExportButton(true); - }, Qt::DirectConnection); + QMetaObject::invokeMethod(&m_plot, "replot"); + QMetaObject::invokeMethod( + this, [=]() { m_exportSettings->enableExportButton(true); }, Qt::DirectConnection); }); } else { - if (m_captureThread) { + if(m_captureThread) { // a stop request might be triggered before getting to getSamplesP, // thus cancelAcquisition in this case will be a no-op. In order to avoid // this issue we wait for acquisition to be started { std::unique_lock lock(m_acquisitionStartedMutex); - m_acquisitionStartedCv.wait(lock, [=]{ return m_acquisitionStarted; }); + m_acquisitionStartedCv.wait(lock, [=] { return m_acquisitionStarted; }); } m_stopRequested = true; try { m_m2kDigital->cancelAcquisition(); // cancelBufferIn - } catch (...) { + } catch(...) { qDebug() << "Error"; } @@ -2361,50 +2261,49 @@ void LogicAnalyzer::startStop(bool start) void LogicAnalyzer::setupDecoders() { - if (srd_decoder_load_all() != SRD_OK) { + if(srd_decoder_load_all() != SRD_OK) { qDebug() << "Error: srd_decoder_load_all failed!"; } ui->addDecoderComboBox->addItem(tr("Select a decoder to add")); - GSList *decoderList = g_slist_copy((GSList *)srd_decoder_list()); decoderList = g_slist_sort(decoderList, sort_pds); - for (const GSList *sl = decoderList; sl; sl = sl->next) { + for(const GSList *sl = decoderList; sl; sl = sl->next) { - srd_decoder *dec = (struct srd_decoder *)sl->data; + srd_decoder *dec = (struct srd_decoder *)sl->data; - QString decoderInput = ""; + QString decoderInput = ""; - GSList *dec_channels = g_slist_copy(dec->inputs); - for (const GSList *sl = dec_channels; sl; sl = sl->next) { - decoderInput = QString::fromUtf8((char*)sl->data); - } - g_slist_free(dec_channels); + GSList *dec_channels = g_slist_copy(dec->inputs); + for(const GSList *sl = dec_channels; sl; sl = sl->next) { + decoderInput = QString::fromUtf8((char *)sl->data); + } + g_slist_free(dec_channels); - if (decoderInput == "logic") { - ui->addDecoderComboBox->addItem(QString::fromUtf8(dec->id)); - } + if(decoderInput == "logic") { + ui->addDecoderComboBox->addItem(QString::fromUtf8(dec->id)); + } } g_slist_free(decoderList); - connect(ui->addDecoderComboBox, qOverload(&QComboBox::currentIndexChanged), [=](int index) { + connect(ui->addDecoderComboBox, qOverload(&QComboBox::currentIndexChanged), [=](int index) { const QString &decoder = ui->addDecoderComboBox->itemText(index); ui->addDecoderComboBox->clearFocus(); - if (!ui->addDecoderComboBox->currentIndex()) { + if(!ui->addDecoderComboBox->currentIndex()) { return; } std::shared_ptr initialDecoder = nullptr; GSList *decoderList = g_slist_copy((GSList *)srd_decoder_list()); - for (const GSList *sl = decoderList; sl; sl = sl->next) { - srd_decoder *dec = (struct srd_decoder *)sl->data; - if (QString::fromUtf8(dec->id) == decoder) { - initialDecoder = std::make_shared(dec); - } + for(const GSList *sl = decoderList; sl; sl = sl->next) { + srd_decoder *dec = (struct srd_decoder *)sl->data; + if(QString::fromUtf8(dec->id) == decoder) { + initialDecoder = std::make_shared(dec); + } } g_slist_free(decoderList); @@ -2415,18 +2314,19 @@ void LogicAnalyzer::setupDecoders() // use direct connection we want the processing // of the available data to be done in the capture thread - auto connectionHandle = connect(this, &LogicAnalyzer::dataAvailable, - this, [=](uint64_t from, uint64_t to, uint16_t *buffer){ - if (!m_oscPlot) { - curve->dataAvailable(from, to, buffer); - } - }, Qt::DirectConnection); + auto connectionHandle = connect( + this, &LogicAnalyzer::dataAvailable, this, + [=](uint64_t from, uint64_t to, uint16_t *buffer) { + if(!m_oscPlot) { + curve->dataAvailable(from, to, buffer); + } + }, + Qt::DirectConnection); curve->setSampleRate(m_sampleRate); curve->setBufferSize(m_bufferSize); - const double delay = ui->btnStreamOneShot ? m_timeTriggerOffset * m_sampleRate - : 0; + const double delay = ui->btnStreamOneShot ? m_timeTriggerOffset * m_sampleRate : 0; curve->setTimeTriggerOffset(delay); curve->dataAvailable(0, m_lastCapturedSample, m_buffer); @@ -2453,23 +2353,21 @@ void LogicAnalyzer::setupDecoders() decoderBox->setVisible(true); deleteBtn->setVisible(true); - connect(deleteBtn, &QPushButton::clicked, [=](){ + connect(deleteBtn, &QPushButton::clicked, [=]() { decoderMenuItem->deleteLater(); int chIdx = m_plotCurves.indexOf(curve); - if (chIdx == m_selectedChannel) { + if(chIdx == m_selectedChannel) { channelSelectedChanged(chIdx, false); - } else if (chIdx < m_selectedChannel) { + } else if(chIdx < m_selectedChannel) { m_selectedChannel--; } bool groupDeleted = false; - m_plot.removeFromGroup(chIdx, - m_plot.getGroupOfChannel(chIdx).indexOf(chIdx), - groupDeleted); + m_plot.removeFromGroup(chIdx, m_plot.getGroupOfChannel(chIdx).indexOf(chIdx), groupDeleted); - if (groupDeleted) { + if(groupDeleted) { ui->groupWidget->setVisible(false); m_currentGroup.clear(); ui->groupWidgetLayout->removeWidget(m_currentGroupMenu); @@ -2485,21 +2383,21 @@ void LogicAnalyzer::setupDecoders() delete curve; // reposition decoder menu items after deleting one - for (int i = chIdx; i < m_plotCurves.size(); ++i) { + for(int i = chIdx; i < m_plotCurves.size(); ++i) { const int index = i - 16; // subtract logic channels count - QLayoutItem *next = ui->decoderEnumeratorLayout->itemAtPosition((index + 1) / 2, (index + 1) % 2); + QLayoutItem *next = + ui->decoderEnumeratorLayout->itemAtPosition((index + 1) / 2, (index + 1) % 2); ui->decoderEnumeratorLayout->removeItem(next); ui->decoderEnumeratorLayout->addItem(next, index / 2, index % 2); } }); const int itemsInLayout = ui->decoderEnumeratorLayout->count(); - ui->decoderEnumeratorLayout->addWidget(decoderMenuItem, itemsInLayout / 2, - itemsInLayout % 2); + ui->decoderEnumeratorLayout->addWidget(decoderMenuItem, itemsInLayout / 2, itemsInLayout % 2); ui->addDecoderComboBox->setCurrentIndex(0); - connect(decoderBox, &QCheckBox::toggled, [=](bool toggled){ + connect(decoderBox, &QCheckBox::toggled, [=](bool toggled) { m_plot.enableDigitalPlotCurve(m_nbChannels + itemsInLayout, toggled); m_plot.setOffsetWidgetVisible(m_nbChannels + itemsInLayout, toggled); m_plot.positionInGroupChanged(m_nbChannels + itemsInLayout, 0, 0); @@ -2508,12 +2406,12 @@ void LogicAnalyzer::setupDecoders() decoderBox->setChecked(true); - connect(curve, &AnnotationCurve::decoderMenuChanged, [=](){ - if (m_selectedChannel != chId) { + connect(curve, &AnnotationCurve::decoderMenuChanged, [=]() { + if(m_selectedChannel != chId) { return; } - if (m_decoderMenu) { + if(m_decoderMenu) { ui->decoderSettingsLayout->removeWidget(m_decoderMenu); m_decoderMenu->deleteLater(); m_decoderMenu = nullptr; @@ -2525,7 +2423,8 @@ void LogicAnalyzer::setupDecoders() }); connect(curve, &AnnotationCurve::annotationClicked, [=](AnnotationQueryResult result) { - if (!result.isValid() or !ui->decoderTableView->isActive()) return; + if(!result.isValid() or !ui->decoderTableView->isActive()) + return; const auto model = ui->decoderTableView->decoderModel(); const auto col = model->indexOfCurve(curve); ui->DecoderComboBox->setCurrentIndex(col); @@ -2534,9 +2433,9 @@ void LogicAnalyzer::setupDecoders() title = title.erase(0, title.find(':') + 1); int row_index = ui->primaryAnnotationComboBox->findText(QString::fromStdString(title)); - if (row_index != -1) { + if(row_index != -1) { int row = 0; - if (getGroupOffset() < result.index) { + if(getGroupOffset() < result.index) { row = result.index / getGroupSize(); } ui->primaryAnnotationComboBox->setCurrentIndex(row_index); @@ -2544,25 +2443,24 @@ void LogicAnalyzer::setupDecoders() } }); }); - } void LogicAnalyzer::updateStackDecoderButton() { qDebug() << "updateStackDecoderButton called!"; - if (m_selectedChannel < m_nbChannels) { + if(m_selectedChannel < m_nbChannels) { ui->stackDecoderWidget->setVisible(false); return; } - if (m_selectedChannel > m_plotCurves.size() - 1) { + if(m_selectedChannel > m_plotCurves.size() - 1) { return; } AnnotationCurve *curve = dynamic_cast(m_plotCurves[m_selectedChannel]); - if (!curve) { + if(!curve) { return; } @@ -2577,26 +2475,26 @@ void LogicAnalyzer::updateStackDecoderButton() GSList *decoderList = g_slist_copy((GSList *)srd_decoder_list()); decoderList = g_slist_sort(decoderList, sort_pds); GSList *dec_channels = g_slist_copy(top->decoder()->outputs); - for (const GSList *sl = dec_channels; sl; sl = sl->next) { - decoderOutput = QString::fromUtf8((char*)sl->data); + for(const GSList *sl = dec_channels; sl; sl = sl->next) { + decoderOutput = QString::fromUtf8((char *)sl->data); } g_slist_free(dec_channels); - for (const GSList *sl = decoderList; sl; sl = sl->next) { + for(const GSList *sl = decoderList; sl; sl = sl->next) { - srd_decoder *dec = (struct srd_decoder *)sl->data; + srd_decoder *dec = (struct srd_decoder *)sl->data; - QString decoderInput = ""; + QString decoderInput = ""; - GSList *dec_channels = g_slist_copy(dec->inputs); - for (const GSList *sl = dec_channels; sl; sl = sl->next) { - decoderInput = QString::fromUtf8((char*)sl->data); - } - g_slist_free(dec_channels); + GSList *dec_channels = g_slist_copy(dec->inputs); + for(const GSList *sl = dec_channels; sl; sl = sl->next) { + decoderInput = QString::fromUtf8((char *)sl->data); + } + g_slist_free(dec_channels); - if (decoderInput == decoderOutput) { - qDebug() << "Added: " << QString::fromUtf8(dec->id); - ui->stackDecoderComboBox->addItem(QString::fromUtf8(dec->id)); - } + if(decoderInput == decoderOutput) { + qDebug() << "Added: " << QString::fromUtf8(dec->id); + ui->stackDecoderComboBox->addItem(QString::fromUtf8(dec->id)); + } } g_slist_free(decoderList); @@ -2614,20 +2512,20 @@ void LogicAnalyzer::updateChannelGroupWidget(bool visible) ui->groupWidget->setVisible(shouldBeVisible); - qDebug() << "channel group widget should be visible: " << shouldBeVisible - << " visible: " << visible << " channelsInGroup: " << channelsInGroup.size(); + qDebug() << "channel group widget should be visible: " << shouldBeVisible << " visible: " << visible + << " channelsInGroup: " << channelsInGroup.size(); - if (!shouldBeVisible) { + if(!shouldBeVisible) { return; } - if (channelsInGroup == m_currentGroup) { + if(channelsInGroup == m_currentGroup) { return; } m_currentGroup = channelsInGroup; - if (m_currentGroupMenu) { + if(m_currentGroupMenu) { ui->groupWidgetLayout->removeWidget(m_currentGroupMenu); m_currentGroupMenu->deleteLater(); m_currentGroupMenu = nullptr; @@ -2636,26 +2534,26 @@ void LogicAnalyzer::updateChannelGroupWidget(bool visible) m_currentGroupMenu = new BaseMenu(ui->groupWidget); ui->groupWidgetLayout->addWidget(m_currentGroupMenu); - connect(m_currentGroupMenu, &BaseMenu::itemMovedFromTo, [=](short from, short to){ - m_plot.positionInGroupChanged(m_selectedChannel, from, to); - }); + connect(m_currentGroupMenu, &BaseMenu::itemMovedFromTo, + [=](short from, short to) { m_plot.positionInGroupChanged(m_selectedChannel, from, to); }); - for (int i = 0; i < channelsInGroup.size(); ++i) { + for(int i = 0; i < channelsInGroup.size(); ++i) { QString name = m_plotCurves[channelsInGroup[i]]->getName(); LogicGroupItem *item = new LogicGroupItem(name, m_currentGroupMenu); - connect(m_plotCurves[channelsInGroup[i]], &GenericLogicPlotCurve::nameChanged, - item, &LogicGroupItem::setName); - connect(item, &LogicGroupItem::deleteBtnClicked, [=](){ + connect(m_plotCurves[channelsInGroup[i]], &GenericLogicPlotCurve::nameChanged, item, + &LogicGroupItem::setName); + connect(item, &LogicGroupItem::deleteBtnClicked, [=]() { bool groupDeleted = false; m_plot.removeFromGroup(m_selectedChannel, item->position(), groupDeleted); - qDebug() << "m_selectedChannel: " << m_selectedChannel << " deleted: " << m_currentGroup[item->position()]; - if (m_selectedChannel == m_currentGroup[item->position()] && !groupDeleted) { + qDebug() << "m_selectedChannel: " << m_selectedChannel + << " deleted: " << m_currentGroup[item->position()]; + if(m_selectedChannel == m_currentGroup[item->position()] && !groupDeleted) { ui->groupWidget->setVisible(false); } m_currentGroup.removeAt(item->position()); - if (groupDeleted) { + if(groupDeleted) { ui->groupWidget->setVisible(false); m_currentGroup.clear(); ui->groupWidgetLayout->removeWidget(m_currentGroupMenu); @@ -2672,23 +2570,23 @@ void LogicAnalyzer::updateChannelGroupWidget(bool visible) void LogicAnalyzer::setupTriggerMenu() { - connect(ui->btnTriggerMode, &CustomSwitch::toggled, [=](bool toggled){ + connect(ui->btnTriggerMode, &CustomSwitch::toggled, [=](bool toggled) { m_autoMode = toggled; - if (m_autoMode && m_started) { + if(m_autoMode && m_started) { double oneBufferTimeOut = m_timerTimeout; - if (!ui->btnStreamOneShot->isChecked()) { + if(!ui->btnStreamOneShot->isChecked()) { oneBufferTimeOut /= m_currentKernelBuffers; } m_timer->start(oneBufferTimeOut); - qDebug() << "auto mode: " << m_autoMode << " with timeout: " - << oneBufferTimeOut << " when logic is started: " << m_started; + qDebug() << "auto mode: " << m_autoMode << " with timeout: " << oneBufferTimeOut + << " when logic is started: " << m_started; } - if (toggled) { + if(toggled) { m_triggerUpdater->setIdleState(CapturePlot::Auto); m_triggerUpdater->setInput(CapturePlot::Auto); } else { @@ -2696,7 +2594,7 @@ void LogicAnalyzer::setupTriggerMenu() m_triggerUpdater->setInput(CapturePlot::Waiting); } - if (!m_autoMode) { + if(!m_autoMode) { m_timer->stop(); } }); @@ -2704,46 +2602,49 @@ void LogicAnalyzer::setupTriggerMenu() ui->triggerLogicComboBox->addItem("OR"); ui->triggerLogicComboBox->addItem("AND"); - connect(ui->triggerLogicComboBox, QOverload::of(&QComboBox::currentIndexChanged), [=](int index){ + connect(ui->triggerLogicComboBox, QOverload::of(&QComboBox::currentIndexChanged), [=](int index) { m_m2kDigital->getTrigger()->setDigitalMode(static_cast(index)); }); - if (m_m2kDigital->getTrigger()->hasCrossInstrumentTrigger()) { + if(m_m2kDigital->getTrigger()->hasCrossInstrumentTrigger()) { ui->externalWidget->setEnabled(true); ui->lblWarningFw->setVisible(false); ui->externalTriggerSourceComboBox->addItem(tr("External Trigger In")); ui->externalTriggerSourceComboBox->addItem(tr("Oscilloscope")); - connect(ui->externalTriggerSourceComboBox, QOverload::of(&QComboBox::currentIndexChanged), [=](int index){ - m_m2kDigital->getTrigger()->setDigitalSource(static_cast(index)); - if (index) { // oscilloscope - /* set external trigger condition to none if the source is - * set to oscilloscope (trigger in) - * */ - ui->externalTriggerConditionComboBox->setCurrentIndex(0); // None - } - - /* - * Disable the condition combo box if oscilloscope (trigger in) is selected - * and enable it if external trigger in is selected (trigger logic) - * */ - ui->externalTriggerConditionComboBox->setDisabled(index); - }); + connect(ui->externalTriggerSourceComboBox, QOverload::of(&QComboBox::currentIndexChanged), + [=](int index) { + m_m2kDigital->getTrigger()->setDigitalSource( + static_cast(index)); + if(index) { // oscilloscope + /* set external trigger condition to none if the source is + * set to oscilloscope (trigger in) + * */ + ui->externalTriggerConditionComboBox->setCurrentIndex(0); // None + } - connect(ui->externalTriggerConditionComboBox, QOverload::of(&QComboBox::currentIndexChanged), [=](int index) { - m_m2kDigital->getTrigger()->setDigitalExternalCondition( - static_cast((index + 5) % 6)); - }); + /* + * Disable the condition combo box if oscilloscope (trigger in) is selected + * and enable it if external trigger in is selected (trigger logic) + * */ + ui->externalTriggerConditionComboBox->setDisabled(index); + }); + connect(ui->externalTriggerConditionComboBox, QOverload::of(&QComboBox::currentIndexChanged), + [=](int index) { + m_m2kDigital->getTrigger()->setDigitalExternalCondition( + static_cast((index + 5) % 6)); + }); - connect(ui->btnEnableExternalTrigger, &CustomSwitch::toggled, [=](bool on){ - if (on) { + connect(ui->btnEnableExternalTrigger, &CustomSwitch::toggled, [=](bool on) { + if(on) { const int source = ui->externalTriggerSourceComboBox->currentIndex(); const int condition = ui->externalTriggerConditionComboBox->currentIndex(); - m_m2kDigital->getTrigger()->setDigitalSource(static_cast(source)); + m_m2kDigital->getTrigger()->setDigitalSource( + static_cast(source)); m_m2kDigital->getTrigger()->setDigitalExternalCondition( - static_cast((condition + 5) % 6)); + static_cast((condition + 5) % 6)); ui->externalTriggerConditionComboBox->setDisabled(source); } else { m_m2kDigital->getTrigger()->setDigitalSource(M2K_TRIGGER_SOURCE_DIGITAL::SRC_NONE); @@ -2751,8 +2652,7 @@ void LogicAnalyzer::setupTriggerMenu() }); QSignalBlocker blockerExternalTriggerConditionComboBox(ui->externalTriggerConditionComboBox); - const int condition = static_cast( - m_m2kDigital->getTrigger()->getDigitalExternalCondition()); + const int condition = static_cast(m_m2kDigital->getTrigger()->getDigitalExternalCondition()); ui->externalTriggerConditionComboBox->setCurrentIndex((condition + 1) % 6); QSignalBlocker blockerExternalTriggerSourceComboBox(ui->externalTriggerSourceComboBox); @@ -2763,29 +2663,30 @@ void LogicAnalyzer::setupTriggerMenu() ui->lblWarningFw->setVisible(true); } - connect(m_timer, &QTimer::timeout, - this, &LogicAnalyzer::saveTriggerState); + connect(m_timer, &QTimer::timeout, this, &LogicAnalyzer::saveTriggerState); } void LogicAnalyzer::saveTriggerState() { // save trigger state and set to no trigger each channel - if (m_started && !m_triggerState.size()) { + if(m_started && !m_triggerState.size()) { const bool streaming = !ui->btnStreamOneShot->isChecked(); - if (streaming) { + if(streaming) { m_m2kDigital->getTrigger()->setDigitalStreamingFlag(false); } - for (int i = 0; i < m_nbChannels; ++i) { + for(int i = 0; i < m_nbChannels; ++i) { m_triggerState.push_back(m_m2kDigital->getTrigger()->getDigitalCondition(i)); - m_m2kDigital->getTrigger()->setDigitalCondition(i, M2K_TRIGGER_CONDITION_DIGITAL::NO_TRIGGER_DIGITAL); + m_m2kDigital->getTrigger()->setDigitalCondition( + i, M2K_TRIGGER_CONDITION_DIGITAL::NO_TRIGGER_DIGITAL); } auto externalTriggerCondition = m_m2kDigital->getTrigger()->getDigitalExternalCondition(); m_triggerState.push_back(externalTriggerCondition); - m_m2kDigital->getTrigger()->setDigitalExternalCondition(M2K_TRIGGER_CONDITION_DIGITAL::NO_TRIGGER_DIGITAL); + m_m2kDigital->getTrigger()->setDigitalExternalCondition( + M2K_TRIGGER_CONDITION_DIGITAL::NO_TRIGGER_DIGITAL); - if (streaming) { + if(streaming) { m_m2kDigital->getTrigger()->setDigitalStreamingFlag(true); } } @@ -2794,20 +2695,20 @@ void LogicAnalyzer::saveTriggerState() void LogicAnalyzer::restoreTriggerState() { // restored saved trigger state - if (m_triggerState.size()) { + if(m_triggerState.size()) { const bool streaming = !ui->btnStreamOneShot->isChecked(); - if (streaming) { + if(streaming) { m_m2kDigital->getTrigger()->setDigitalStreamingFlag(false); } - for (int i = 0; i < m_nbChannels; ++i) { + for(int i = 0; i < m_nbChannels; ++i) { m_triggerState.push_back(m_m2kDigital->getTrigger()->getDigitalCondition(i)); m_m2kDigital->getTrigger()->setDigitalCondition(i, m_triggerState[i]); } m_m2kDigital->getTrigger()->setDigitalExternalCondition(m_triggerState.back()); - if (streaming) { + if(streaming) { m_m2kDigital->getTrigger()->setDigitalStreamingFlag(true); } @@ -2819,18 +2720,20 @@ void LogicAnalyzer::readPreferences() { bool showFps = p->get("general_show_plot_fps").toBool(); - m_tableInfo = p->get("m2k_logic_table_info").toBool(); //prefPanel->getTableInfo(); - m_separateAnnotations = p->get("m2k_logic_separate_annotations").toBool(); //prefPanel->getSeparateAnnotations(); + m_tableInfo = p->get("m2k_logic_table_info").toBool(); // prefPanel->getTableInfo(); + m_separateAnnotations = + p->get("m2k_logic_separate_annotations").toBool(); // prefPanel->getSeparateAnnotations(); m_plot.setVisibleFpsLabel(showFps); - for (GenericLogicPlotCurve *curve : qAsConst(m_plotCurves)) { - if (curve->getType() == LogicPlotCurveType::Data) { - LogicDataCurve *ldc = dynamic_cast(curve); - if (!ldc) { + for(GenericLogicPlotCurve *curve : qAsConst(m_plotCurves)) { + if(curve->getType() == LogicPlotCurveType::Data) { + LogicDataCurve *ldc = dynamic_cast(curve); + if(!ldc) { continue; } - ldc->setDisplaySampling(p->get("m2k_logic_display_sampling_points").toBool()/*prefPanel->getDisplaySamplingPoints()*/); + ldc->setDisplaySampling(p->get("m2k_logic_display_sampling_points") + .toBool() /*prefPanel->getDisplaySamplingPoints()*/); } } ui->instrumentNotes->setVisible(p->get("m2k_instrument_notes_active").toBool()); @@ -2849,14 +2752,14 @@ void LogicAnalyzer::exportData() m_exportConfig = m_exportSettings->getExportConfig(); auto keys = m_exportConfig.keys(); - for (auto x : qAsConst(keys)) { + for(auto x : qAsConst(keys)) { if(m_exportConfig[x]) { - noChannelEnabled = false; + noChannelEnabled = false; break; } } - if (noChannelEnabled) + if(noChannelEnabled) return; QStringList filter; @@ -2865,16 +2768,16 @@ void LogicAnalyzer::exportData() filter += QString(tr("Value Change Dump(*.vcd)")); filter += QString(tr("All Files(*)")); - QString fileName = QFileDialog::getSaveFileName(this, - tr("Export"), "", filter.join(";;"), - &selectedFilter, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); + QString fileName = QFileDialog::getSaveFileName( + this, tr("Export"), "", filter.join(";;"), &selectedFilter, + (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); - if (fileName.isEmpty()) { + if(fileName.isEmpty()) { return; } // Check the selected file type - if (selectedFilter != "") { + if(selectedFilter != "") { if(selectedFilter.contains("comma", Qt::CaseInsensitive)) { separator = ","; } @@ -2887,19 +2790,17 @@ void LogicAnalyzer::exportData() } } - if (fileName.split(".").size() <= 1) { + if(fileName.split(".").size() <= 1) { // file name w/o extension. Let's append it QString ext = selectedFilter.split(".")[1].split(")")[0]; fileName += "." + ext; } - - - if (separator != "") { + if(separator != "") { done = exportTabCsv(separator, fileName); } else { QFile file(fileName); - if (!file.open(QIODevice::WriteOnly)) { + if(!file.open(QIODevice::WriteOnly)) { return; } @@ -2907,11 +2808,9 @@ void LogicAnalyzer::exportData() /* Write the general information */ out << startRow << "date " << QDateTime::currentDateTime().toString() << endRow; -// out << startRow << "version Scopy - " << QString(SCOPY_VERSION_GIT) << endRow; - out << startRow << "comment " << QString::number(m_bufferSize) << - " samples acquired at " << QString::number(m_sampleRate) << - " Hz " << endRow; - + // out << startRow << "version Scopy - " << QString(SCOPY_VERSION_GIT) << endRow; + out << startRow << "comment " << QString::number(m_bufferSize) << " samples acquired at " + << QString::number(m_sampleRate) << " Hz " << endRow; file.close(); @@ -2925,19 +2824,19 @@ bool LogicAnalyzer::exportTabCsv(const QString &separator, const QString &fileNa fm.open(fileName, FileManager::EXPORT); QStringList chNames; - for (unsigned int ch = 0; ch < DIGITAL_NR_CHANNELS; ch++) { - if (m_exportConfig[ch]) { + for(unsigned int ch = 0; ch < DIGITAL_NR_CHANNELS; ch++) { + if(m_exportConfig[ch]) { chNames.push_back("Channel " + QString::number(ch)); } } - for (unsigned int ch = DIGITAL_NR_CHANNELS; ch < m_plotCurves.size(); ch++){ + for(unsigned int ch = DIGITAL_NR_CHANNELS; ch < m_plotCurves.size(); ch++) { auto *curve = dynamic_cast(m_plotCurves[ch]); auto rows = curve->getAnnotationRows(); - for (const auto& [key, value] : rows) { + for(const auto &[key, value] : rows) { vector dest; value.get_annotation_subset(dest, 0, m_lastCapturedSample); - if (!dest.empty()) { + if(!dest.empty()) { chNames.push_back(key.title()); } } @@ -2945,13 +2844,13 @@ bool LogicAnalyzer::exportTabCsv(const QString &separator, const QString &fileNa QVector> data; - if (!m_buffer) { + if(!m_buffer) { return false; } else { - for (unsigned int i = 0; i < m_lastCapturedSample; ++i) { + for(unsigned int i = 0; i < m_lastCapturedSample; ++i) { uint64_t sample = m_buffer[i]; QVector line; - for (unsigned int ch = 0; ch < DIGITAL_NR_CHANNELS; ++ch) { + for(unsigned int ch = 0; ch < DIGITAL_NR_CHANNELS; ++ch) { int bit = (sample >> ch) & 1; if(m_exportConfig[ch]) { line.push_back(bit); @@ -2985,56 +2884,60 @@ QVector> LogicAnalyzer::createDecoderData(bool separate_annotat QString repeated_value = "..."; QString empty_value = ""; - for (int ch=DIGITAL_NR_CHANNELS; ch < m_plotCurves.size(); ch++) { + for(int ch = DIGITAL_NR_CHANNELS; ch < m_plotCurves.size(); ch++) { AnnotationCurve *curve = dynamic_cast(m_plotCurves[ch]); std::map decoder(curve->getAnnotationRows()); std::map::iterator it; - for (it = decoder.begin(); it != decoder.end(); it++) { + for(it = decoder.begin(); it != decoder.end(); it++) { vector row; it->second.get_annotation_subset(row, 0, m_lastCapturedSample); - if (!row.empty()) { + if(!row.empty()) { rows.push_back(row); } } } - for (unsigned int i = 0; i < m_lastCapturedSample; ++i) { + for(unsigned int i = 0; i < m_lastCapturedSample; ++i) { decoder_line.clear(); - for (unsigned int row_index = 0; row_index < rows.size(); row_index++) { + for(unsigned int row_index = 0; row_index < rows.size(); row_index++) { colum_is_visible = false; - for(unsigned int col=0; col < rows[row_index].size(); col++){ + for(unsigned int col = 0; col < rows[row_index].size(); col++) { start_sample = rows[row_index][col].start_sample(); end_sample = rows[row_index][col].end_sample(); new_value = ""; - if (separate_annotations) { + if(separate_annotations) { // overlapping annotations - if ((col + 1) < rows[row_index].size()) { + if((col + 1) < rows[row_index].size()) { if(end_sample == rows[row_index][col + 1].start_sample()) { - end_sample --; + end_sample--; } } - new_value = (start_sample == i && end_sample == i) ? start_separator + rows[row_index][col].annotations()[0] + end_separator - : (start_sample == i && end_sample > i) ? start_separator + rows[row_index][col].annotations()[0] - : (end_sample == i && start_sample < i) ? rows[row_index][col].annotations()[0] + end_separator - : (start_sample < i && end_sample > i) ? repeated_value - : ""; - } else if ((start_sample <= i && end_sample > i) || (start_sample == i && end_sample == i)) { + new_value = (start_sample == i && end_sample == i) + ? start_separator + rows[row_index][col].annotations()[0] + + end_separator + : (start_sample == i && end_sample > i) + ? start_separator + rows[row_index][col].annotations()[0] + : (end_sample == i && start_sample < i) + ? rows[row_index][col].annotations()[0] + end_separator + : (start_sample < i && end_sample > i) ? repeated_value + : ""; + } else if((start_sample <= i && end_sample > i) || + (start_sample == i && end_sample == i)) { new_value = rows[row_index][col].annotations()[0]; } - if (!new_value.isEmpty()) { + if(!new_value.isEmpty()) { decoder_line.push_back(new_value); colum_is_visible = true; break; } - } - if (!colum_is_visible) { + if(!colum_is_visible) { decoder_line.push_back(empty_value); } } @@ -3052,13 +2955,12 @@ bool LogicAnalyzer::exportVcd(const QString &fileName, const QString &startSep, double timescale; bool timestamp_written = false; - if (m_sampleRate == 0) { + if(m_sampleRate == 0) { return false; } - QFile file(fileName); - if (!file.open(QIODevice::Append)) { + if(!file.open(QIODevice::Append)) { return false; } @@ -3066,13 +2968,13 @@ bool LogicAnalyzer::exportVcd(const QString &fileName, const QString &startSep, /* Write the specific header */ timescale = 1 / m_sampleRate; - if (timescale < 1e-6) { + if(timescale < 1e-6) { timescaleFormat = "ns"; timescale *= 1e9; - } else if (timescale < 1e-3) { + } else if(timescale < 1e-3) { timescaleFormat = "us"; timescale *= 1e6; - } else if (timescale < 1) { + } else if(timescale < 1) { timescaleFormat = "ms"; timescale *= 1e3; } else { @@ -3082,11 +2984,10 @@ bool LogicAnalyzer::exportVcd(const QString &fileName, const QString &startSep, out << startSep << "timescale " << QString::number(timescale) << " " << timescaleFormat << endSep; out << startSep << "scope module Scopy" << endSep; int counter = 0; - for (unsigned int ch = 0; ch < DIGITAL_NR_CHANNELS; ++ch) { - if (m_exportConfig[ch]) { + for(unsigned int ch = 0; ch < DIGITAL_NR_CHANNELS; ++ch) { + if(m_exportConfig[ch]) { char c = '!' + counter; - out << startSep << "var wire 1 " << c << " DIO" << - QString::number(ch) << endSep; + out << startSep << "var wire 1 " << c << " DIO" << QString::number(ch) << endSep; counter++; } } @@ -3094,28 +2995,28 @@ bool LogicAnalyzer::exportVcd(const QString &fileName, const QString &startSep, out << startSep << "enddefinitions" << endSep; /* Write the values */ - if (m_buffer) { - for (uint64_t i = 0; i < m_lastCapturedSample; i++) { + if(m_buffer) { + for(uint64_t i = 0; i < m_lastCapturedSample; i++) { current_sample = m_buffer[i]; - if (i == 0) { + if(i == 0) { prev_sample = current_sample; } else { prev_sample = m_buffer[i - 1]; } timestamp_written = false; p = 0; - for (unsigned int ch = 0; ch < DIGITAL_NR_CHANNELS; ch++) { + for(unsigned int ch = 0; ch < DIGITAL_NR_CHANNELS; ch++) { current_bit = (current_sample >> ch) & 1; prev_bit = (prev_sample >> ch) & 1; - if ((current_bit == prev_bit) && (i != 0)) { + if((current_bit == prev_bit) && (i != 0)) { p++; continue; } - if (!timestamp_written) + if(!timestamp_written) out << "#" << QString::number(i); - if (m_exportConfig[ch]) { + if(m_exportConfig[ch]) { char c = '0' + current_bit; char c2 = '!' + p; out << ' ' << c << c2; @@ -3123,7 +3024,7 @@ bool LogicAnalyzer::exportVcd(const QString &fileName, const QString &startSep, timestamp_written = true; } } - if (timestamp_written) { + if(timestamp_written) { out << "\n"; } } diff --git a/plugins/m2k/src/old/logicanalyzer/logic_analyzer.h b/plugins/m2k/src/old/logicanalyzer/logic_analyzer.h index b9ab9595b8..d3b75cb04c 100644 --- a/plugins/m2k/src/old/logicanalyzer/logic_analyzer.h +++ b/plugins/m2k/src/old/logicanalyzer/logic_analyzer.h @@ -18,35 +18,32 @@ * along with this program. If not, see . */ - #ifndef LOGIC_ANALYZER_H #define LOGIC_ANALYZER_H -#include -#include -#include - -#include -#include -#include -#include -#include - #include "../m2ktool.hpp" -#include "oscilloscope_plot.hpp" #include "buffer_previewer.hpp" -#include "gui/spinbox_a.hpp" +#include "genericlogicplotcurve.h" #include "gui/customPushButton.h" +#include "gui/spinbox_a.hpp" #include "mousewheelwidgetguard.h" +#include "oscilloscope_plot.hpp" #include "saverestoretoolsettings.h" -#include "genericlogicplotcurve.h" +#include +#include +#include +#include +#include -#include +#include +#include #include #include #include -#include +#include +#include +#include constexpr int DIGITAL_NR_CHANNELS = 16; @@ -61,9 +58,9 @@ class CursorsSettings; } // namespace Ui namespace scopy { - class ExportSettings; - class BaseMenu; -} +class ExportSettings; +class BaseMenu; +} // namespace scopy namespace scopy::m2k { class Filter; @@ -72,19 +69,19 @@ class StateUpdater; namespace logic { -class LogicAnalyzer : public M2kTool { +class LogicAnalyzer : public M2kTool +{ Q_OBJECT friend class LogicAnalyzer_API; + public: - explicit LogicAnalyzer(struct iio_context *ctx, Filter *filt, - ToolMenuEntry *toolMenuItem, QJSEngine *engine, - QWidget *parent, bool offline_mode_ = 0); + explicit LogicAnalyzer(struct iio_context *ctx, Filter *filt, ToolMenuEntry *toolMenuItem, QJSEngine *engine, + QWidget *parent, bool offline_mode_ = 0); ~LogicAnalyzer(); void setNativeDialogs(bool nativeDialogs) override; public: // Mixed Signal View Interface - // enable mixed signal view // return a list with all the controls available for the Logic Analyzer std::vector enableMixedSignalView(CapturePlot *osc, int oscAnalogChannels); @@ -99,12 +96,12 @@ class LogicAnalyzer : public M2kTool { QwtPlot *getCurrentPlot(); // get list of plot curves - QVector getPlotCurves(bool logic) const; + QVector getPlotCurves(bool logic) const; // connect signals and slots for the plot (logic or osc) void connectSignalsAndSlotsForPlot(CapturePlot *plot); - void setData(const uint16_t * const data, int size); + void setData(const uint16_t *const data, int size); // Update the viewport to fit the min and max time void fitViewport(double min, double max); @@ -165,6 +162,7 @@ private Q_SLOTS: void onFilterChanged(QStandardItem *item); void activateRunButton(bool en); + protected: uint16_t *m_buffer; @@ -209,7 +207,7 @@ private Q_SLOTS: uint64_t m_bufferSize; uint64_t m_lastCapturedSample; - M2k* m_m2k_context; + M2k *m_m2k_context; M2kDigital *m_m2kDigital; int m_nbChannels; @@ -244,7 +242,6 @@ private Q_SLOTS: double m_timerTimeout; QVector m_triggerState; - ExportSettings *m_exportSettings; QMap m_exportConfig; @@ -261,12 +258,10 @@ private Q_SLOTS: StateUpdater *m_triggerUpdater; - DropdownSwitchList* filterMessages; + DropdownSwitchList *filterMessages; int filterCount = 0; - - }; } // namespace logic -} // namespace scopy +} // namespace scopy::m2k #endif // LOGIC_ANALYZER_H diff --git a/plugins/m2k/src/old/logicanalyzer/logicanalyzer_api.cpp b/plugins/m2k/src/old/logicanalyzer/logicanalyzer_api.cpp index d904273644..97c4af1792 100644 --- a/plugins/m2k/src/old/logicanalyzer/logicanalyzer_api.cpp +++ b/plugins/m2k/src/old/logicanalyzer/logicanalyzer_api.cpp @@ -18,55 +18,42 @@ * along with this program. If not, see . */ - #include "logicanalyzer_api.h" -#include "ui_logic_analyzer.h" #include "annotationcurve.h" #include "annotationdecoder.h" +#include "binding/decoder.hpp" + #include "ui_cursors_settings.h" +#include "ui_logic_analyzer.h" #include +#include +#include #include #include -#include -#include -#include -#include "binding/decoder.hpp" +#include using namespace scopy; using namespace scopy::logic; using namespace scopy::m2k::logic; -double LogicAnalyzer_API::getSampleRate() const -{ - return m_logic->m_sampleRateButton->value(); -} +double LogicAnalyzer_API::getSampleRate() const { return m_logic->m_sampleRateButton->value(); } -void LogicAnalyzer_API::setSampleRate(double sampleRate) -{ - m_logic->m_sampleRateButton->setValue(sampleRate); -} +void LogicAnalyzer_API::setSampleRate(double sampleRate) { m_logic->m_sampleRateButton->setValue(sampleRate); } -int LogicAnalyzer_API::getBufferSize() const -{ - return m_logic->m_bufferSizeButton->value(); -} +int LogicAnalyzer_API::getBufferSize() const { return m_logic->m_bufferSizeButton->value(); } -void LogicAnalyzer_API::setBufferSize(int bufferSize) -{ - m_logic->m_bufferSizeButton->setValue(bufferSize); -} +void LogicAnalyzer_API::setBufferSize(int bufferSize) { m_logic->m_bufferSizeButton->setValue(bufferSize); } QList LogicAnalyzer_API::getEnabledChannels() const { QList enabledChannels; - for (int i = 0; i < 16; ++i) { - QLayout *widgetInLayout = m_logic->ui->channelEnumeratorLayout->itemAtPosition(i % 8, - i / 8)->layout(); + for(int i = 0; i < 16; ++i) { + QLayout *widgetInLayout = m_logic->ui->channelEnumeratorLayout->itemAtPosition(i % 8, i / 8)->layout(); auto channelBox = dynamic_cast(widgetInLayout->itemAt(0)->widget()); - if (channelBox->isChecked()) { + if(channelBox->isChecked()) { enabledChannels.push_back(i); } } @@ -75,9 +62,9 @@ QList LogicAnalyzer_API::getEnabledChannels() const void LogicAnalyzer_API::setEnabledChannels(const QList &enabledChannels) { - for (const auto &channel : enabledChannels) { - QLayout *widgetInLayout = m_logic->ui->channelEnumeratorLayout->itemAtPosition(channel % 8, - channel / 8)->layout(); + for(const auto &channel : enabledChannels) { + QLayout *widgetInLayout = + m_logic->ui->channelEnumeratorLayout->itemAtPosition(channel % 8, channel / 8)->layout(); auto channelBox = dynamic_cast(widgetInLayout->itemAt(0)->widget()); channelBox->setChecked(true); } @@ -86,7 +73,7 @@ void LogicAnalyzer_API::setEnabledChannels(const QList &enabledChannels) QStringList LogicAnalyzer_API::getEnabledDecoders() const { QStringList decoders; - for (int i = 16; i < m_logic->m_plotCurves.size(); ++i) { + for(int i = 16; i < m_logic->m_plotCurves.size(); ++i) { decoders.push_back(m_logic->m_plotCurves[i]->getId()); } return decoders; @@ -94,35 +81,26 @@ QStringList LogicAnalyzer_API::getEnabledDecoders() const void LogicAnalyzer_API::setEnabledDecoders(const QStringList &decoders) { - for (const QString &decoder : decoders) { + for(const QString &decoder : decoders) { m_logic->ui->addDecoderComboBox->setCurrentText(decoder); } } -bool LogicAnalyzer_API::getStreamOrOneShot() const -{ - return m_logic->ui->btnStreamOneShot->isChecked(); -} +bool LogicAnalyzer_API::getStreamOrOneShot() const { return m_logic->ui->btnStreamOneShot->isChecked(); } void LogicAnalyzer_API::setStreamOrOneShot(bool streamOrOneShot) { m_logic->ui->btnStreamOneShot->setChecked(streamOrOneShot); } -int LogicAnalyzer_API::getDelay() const -{ - return m_logic->m_timePositionButton->value(); -} +int LogicAnalyzer_API::getDelay() const { return m_logic->m_timePositionButton->value(); } -void LogicAnalyzer_API::setDelay(int delay) -{ - m_logic->m_timePositionButton->setValue(delay); -} +void LogicAnalyzer_API::setDelay(int delay) { m_logic->m_timePositionButton->setValue(delay); } QStringList LogicAnalyzer_API::getChannelNames() const { QStringList names; - for (int i = 0; i < m_logic->m_plotCurves.size(); ++i) { + for(int i = 0; i < m_logic->m_plotCurves.size(); ++i) { names.push_back(m_logic->m_plotCurves[i]->getName()); } return names; @@ -130,7 +108,7 @@ QStringList LogicAnalyzer_API::getChannelNames() const void LogicAnalyzer_API::setChannelNames(const QStringList &channelNames) { - for (int i = 0; i < channelNames.size(); ++i) { + for(int i = 0; i < channelNames.size(); ++i) { m_logic->m_plotCurves[i]->setName(channelNames[i]); } } @@ -138,7 +116,7 @@ void LogicAnalyzer_API::setChannelNames(const QStringList &channelNames) QList LogicAnalyzer_API::getChannelHeights() const { QList heights; - for (int i = 0; i < m_logic->m_plotCurves.size(); ++i) { + for(int i = 0; i < m_logic->m_plotCurves.size(); ++i) { heights.push_back(m_logic->m_plotCurves[i]->getTraceHeight()); } return heights; @@ -146,7 +124,7 @@ QList LogicAnalyzer_API::getChannelHeights() const void LogicAnalyzer_API::setChannelHeights(const QList &channelHeights) { - for (int i = 0; i < channelHeights.size(); ++i) { + for(int i = 0; i < channelHeights.size(); ++i) { m_logic->m_plotCurves[i]->setTraceHeight(channelHeights[i]); } } @@ -154,7 +132,7 @@ void LogicAnalyzer_API::setChannelHeights(const QList &channelHeights) QList LogicAnalyzer_API::getChannelPosition() const { QList channelPosition; - for (int i = 0; i < m_logic->m_plotCurves.size(); ++i) { + for(int i = 0; i < m_logic->m_plotCurves.size(); ++i) { channelPosition.push_back(m_logic->m_plotCurves[i]->getPixelOffset()); } return channelPosition; @@ -162,24 +140,24 @@ QList LogicAnalyzer_API::getChannelPosition() const void LogicAnalyzer_API::setChannelPosition(const QList &channelPosition) { - for (int i = 0; i < channelPosition.size(); ++i) { + for(int i = 0; i < channelPosition.size(); ++i) { m_logic->m_plotCurves[i]->setPixelOffset(channelPosition[i]); } } QList>> LogicAnalyzer_API::getAssignedDecoderChannels() const { - QList > > assignedCh; - for (int i = 16; i < m_logic->m_plotCurves.size(); ++i) { + QList>> assignedCh; + for(int i = 16; i < m_logic->m_plotCurves.size(); ++i) { auto annCurve = dynamic_cast(m_logic->m_plotCurves[i]); - if (!annCurve) { + if(!annCurve) { continue; } auto stack = annCurve->getDecoderStack(); QList> assignedChannels; - for (const std::shared_ptr &decoder : stack) { - for (const auto &ch : decoder->channels()) { - if (ch->assigned_signal) { + for(const std::shared_ptr &decoder : stack) { + for(const auto &ch : decoder->channels()) { + if(ch->assigned_signal) { assignedChannels.push_back({ch->id, ch->bit_id}); } } @@ -192,10 +170,10 @@ QList>> LogicAnalyzer_API::getAssignedDecoderChannels() co void LogicAnalyzer_API::setAssignedDecoderChannels(const QList>> &assignedDecoderChannels) { int currentDecoder = 16; - for (const auto &chls : assignedDecoderChannels) { + for(const auto &chls : assignedDecoderChannels) { auto annCurve = dynamic_cast(m_logic->m_plotCurves[currentDecoder]); auto dec = annCurve->getAnnotationDecoder(); - for (const auto &chbitid : chls) { + for(const auto &chbitid : chls) { dec->assignChannel(chbitid.first, chbitid.second); } currentDecoder++; @@ -205,14 +183,14 @@ void LogicAnalyzer_API::setAssignedDecoderChannels(const QList LogicAnalyzer_API::getDecoderStack() const { QList decoderStack; - for (int i = 16; i < m_logic->m_plotCurves.size(); ++i) { + for(int i = 16; i < m_logic->m_plotCurves.size(); ++i) { auto annCurve = dynamic_cast(m_logic->m_plotCurves[i]); - if (!annCurve) { + if(!annCurve) { continue; } QStringList decStack; auto stack = annCurve->getDecoderStack(); - for (size_t i = 1; i < stack.size(); ++i) { + for(size_t i = 1; i < stack.size(); ++i) { decStack.push_back(stack[i]->decoder()->id); } @@ -225,18 +203,18 @@ QList LogicAnalyzer_API::getDecoderStack() const void LogicAnalyzer_API::setDecoderStack(const QList &decoderStack) { int currentDecoder = 16; - for (const auto &stack : decoderStack) { + for(const auto &stack : decoderStack) { auto annCurve = dynamic_cast(m_logic->m_plotCurves[currentDecoder]); - for (const auto &decoder : stack) { + for(const auto &decoder : stack) { std::shared_ptr dec = nullptr; GSList *decoderList = g_slist_copy((GSList *)srd_decoder_list()); - for (const GSList *sl = decoderList; sl; sl = sl->next) { - srd_decoder *srd_dec = (struct srd_decoder *)sl->data; - if (QString::fromUtf8(srd_dec->id) == decoder) { - dec = std::make_shared(srd_dec); - } + for(const GSList *sl = decoderList; sl; sl = sl->next) { + srd_decoder *srd_dec = (struct srd_decoder *)sl->data; + if(QString::fromUtf8(srd_dec->id) == decoder) { + dec = std::make_shared(srd_dec); + } } g_slist_free(decoderList); @@ -250,14 +228,14 @@ void LogicAnalyzer_API::setDecoderStack(const QList &decoderStack) QList LogicAnalyzer_API::getDecoderSettings() const { QList decoderSettings; - for (int i = 16; i < m_logic->m_plotCurves.size(); ++i) { + for(int i = 16; i < m_logic->m_plotCurves.size(); ++i) { auto annCurve = dynamic_cast(m_logic->m_plotCurves[i]); - if (!annCurve) { + if(!annCurve) { continue; } QStringList decSetting; auto bindings = annCurve->getDecoderBindings(); - for (size_t i = 0; i < bindings.size(); ++i) { + for(size_t i = 0; i < bindings.size(); ++i) { QString settings; QJsonObject obj; @@ -275,45 +253,46 @@ QList LogicAnalyzer_API::getDecoderSettings() const auto type = QMetaType::Type(p_val.type()); std::string type_name(p_val.typeName()); prop_type = QString::fromStdString(type_name); - if (type == QMetaType::QString) { + if(type == QMetaType::QString) { prop_val = p_val.toString(); qDebug() << "Property string: " << prop_name; - } else if (type == QMetaType::Bool) { + } else if(type == QMetaType::Bool) { prop_val = QString::number(p_val.toBool()); qDebug() << "Property boolean: " << prop_name; - } else if (type == QMetaType::Char) { + } else if(type == QMetaType::Char) { prop_val = QString(p_val.toChar()); qDebug() << "Property char: " << prop_name; - } else if (type == QMetaType::Short) { + } else if(type == QMetaType::Short) { prop_val = QString::number(p_val.value()); qDebug() << "Property int16: " << prop_name; - } else if (type == QMetaType::UShort) { + } else if(type == QMetaType::UShort) { prop_val = QString::number(p_val.value()); qDebug() << "Property uint16: " << prop_name; - } else if (type == QMetaType::Int) { + } else if(type == QMetaType::Int) { prop_val = QString::number(p_val.value()); qDebug() << "Property int32: " << prop_name; - } else if (type == QMetaType::UInt) { + } else if(type == QMetaType::UInt) { prop_val = QString::number(p_val.value()); qDebug() << "Property uint32: " << prop_name; - } else if (type == QMetaType::Long) { + } else if(type == QMetaType::Long) { prop_val = QString::number(p_val.value()); qDebug() << "Property int64: " << prop_name; - } else if (type == QMetaType::ULong) { + } else if(type == QMetaType::ULong) { prop_val = QString::number(p_val.value()); - qDebug() << "Property uint64: " << prop_name;; - } else if (type == QMetaType::Double) { + qDebug() << "Property uint64: " << prop_name; + ; + } else if(type == QMetaType::Double) { prop_val = QString::number((p_val.toDouble())); qDebug() << "Property double: " << prop_name; } else { - qDebug()<<"error"; + qDebug() << "error"; } propObj["name"] = prop_name; propObj["type"] = prop_type; propObj["val"] = prop_val; propArray.append(propObj); - qDebug()< LogicAnalyzer_API::getDecoderSettings() const void LogicAnalyzer_API::setDecoderSettings(const QList &decoderSettings) { int currentDecoder = 16; - for (const auto &setting : decoderSettings) { + for(const auto &setting : decoderSettings) { auto annCurve = dynamic_cast(m_logic->m_plotCurves[currentDecoder]); auto bindings = annCurve->getDecoderBindings(); int currentBinding = 0; - for (const auto &sett : setting) { + for(const auto &sett : setting) { auto binding = bindings[currentBinding++]; - QJsonObject obj; QJsonDocument doc = QJsonDocument::fromJson(sett.toUtf8()); - if (!doc.isNull()) { - if (doc.isObject()) { + if(!doc.isNull()) { + if(doc.isObject()) { obj = doc.object(); } else { -// qDebug(CAT_LOGIC_ANALYZER) << "Document is not an object" << endl; + // qDebug(CAT_LOGIC_ANALYZER) << "Document + // is not an object" << endl; } } else { -// qDebug(CAT_LOGIC_ANALYZER) << "Invalid JSON...\n"; + // qDebug(CAT_LOGIC_ANALYZER) << "Invalid JSON...\n"; } QJsonArray propArray = obj["properties"].toArray(); - for (const auto &propRef : qAsConst(propArray)) { + for(const auto &propRef : qAsConst(propArray)) { auto prop = propRef.toObject(); - for(auto p : binding->properties()) - { - qDebug()<name(); - if(p->name() == prop["name"].toString()) - { + for(auto p : binding->properties()) { + qDebug() << p->name(); + if(p->name() == prop["name"].toString()) { QByteArray ba; QVariant value_; @@ -369,96 +346,76 @@ void LogicAnalyzer_API::setDecoderSettings(const QList &decoderSett QString prop_name = prop["name"].toString(); QString prop_val = prop["val"].toString(); - if (type == QMetaType::typeName(QMetaType::QString)) { + if(type == QMetaType::typeName(QMetaType::QString)) { ba = prop_val.toUtf8(); p->set(QVariant::fromValue(ba)); qDebug() << "Property string: " << prop_name; - } else if (type == QMetaType::typeName(QMetaType::Bool)) { + } else if(type == QMetaType::typeName(QMetaType::Bool)) { value_ = QVariant::fromValue(bool(prop_val.toInt())); p->set(value_); qDebug() << "Property boolean: " << prop_name; - } else if (type == QMetaType::typeName(QMetaType::Char)) { + } else if(type == QMetaType::typeName(QMetaType::Char)) { value_ = QVariant::fromValue(prop_val.toLatin1()); p->set(value_); qDebug() << "Property char: " << prop_name; - } else if (type == QMetaType::typeName(QMetaType::Short)) { + } else if(type == QMetaType::typeName(QMetaType::Short)) { value_ = QVariant::fromValue(prop_val.toInt()); p->set(value_); qDebug() << "Property int16: " << prop_name; - } else if (type == QMetaType::typeName(QMetaType::UShort)) { + } else if(type == QMetaType::typeName(QMetaType::UShort)) { value_ = QVariant::fromValue(prop_val.toUInt()); p->set(value_); qDebug() << "Property uint16: " << prop_name; - } else if (type == QMetaType::typeName(QMetaType::Int)) { + } else if(type == QMetaType::typeName(QMetaType::Int)) { value_ = QVariant::fromValue(prop_val.toInt()); p->set(value_); qDebug() << "Property int32: " << prop_name; - } else if (type == QMetaType::typeName(QMetaType::UInt)) { + } else if(type == QMetaType::typeName(QMetaType::UInt)) { value_ = QVariant::fromValue(prop_val.toUInt()); p->set(value_); qDebug() << "Property uint32: " << prop_name; - } else if (type == QMetaType::typeName(QMetaType::Long)) { + } else if(type == QMetaType::typeName(QMetaType::Long)) { value_ = QVariant::fromValue(prop_val.toLong()); p->set(value_); qDebug() << "Property int64: " << prop_name; - } else if (type == QMetaType::typeName(QMetaType::ULong)) { + } else if(type == QMetaType::typeName(QMetaType::ULong)) { value_ = QVariant::fromValue(prop_val.toULong()); p->set(value_); qDebug() << "Property uint64: " << prop_name; - } else if (type == QMetaType::typeName(QMetaType::Double)) { + } else if(type == QMetaType::typeName(QMetaType::Double)) { value_ = QVariant::fromValue(prop_val.toDouble()); p->set(value_); qDebug() << "Property double: " << prop_name; } else { - qDebug()<<"error"; + qDebug() << "error"; } } - } - } } currentDecoder++; } } -QVector > LogicAnalyzer_API::getCurrentGroups() const -{ - return m_logic->m_plot.getAllGroups(); -} +QVector> LogicAnalyzer_API::getCurrentGroups() const { return m_logic->m_plot.getAllGroups(); } -void LogicAnalyzer_API::setCurrentGroups(const QVector > &groups) -{ - m_logic->m_plot.setGroups(groups); -} +void LogicAnalyzer_API::setCurrentGroups(const QVector> &groups) { m_logic->m_plot.setGroups(groups); } -QString LogicAnalyzer_API::getNotes() -{ - return m_logic->ui->instrumentNotes->getNotes(); -} +QString LogicAnalyzer_API::getNotes() { return m_logic->ui->instrumentNotes->getNotes(); } -void LogicAnalyzer_API::setNotes(QString str) -{ - m_logic->ui->instrumentNotes->setNotes(str); -} +void LogicAnalyzer_API::setNotes(QString str) { m_logic->ui->instrumentNotes->setNotes(str); } -bool LogicAnalyzer_API::hasCursors() const -{ - return m_logic->ui->cursorsBox->isChecked(); -} +bool LogicAnalyzer_API::hasCursors() const { return m_logic->ui->cursorsBox->isChecked(); } -void LogicAnalyzer_API::setCursors(bool en) -{ - m_logic->ui->cursorsBox->setChecked(en); -} +void LogicAnalyzer_API::setCursors(bool en) { m_logic->ui->cursorsBox->setChecked(en); } int LogicAnalyzer_API::getCursorsPosition() const { - if (!hasCursors()) { + if(!hasCursors()) { return 0; } auto currentPos = m_logic->m_plot.getCursorReadouts()->getCurrentPosition(); - switch (currentPos) { + switch(currentPos) { case CustomPlotPositionButton::ReadoutsPosition::topLeft: default: return 0; @@ -474,22 +431,21 @@ int LogicAnalyzer_API::getCursorsPosition() const void LogicAnalyzer_API::setCursorsPosition(int val) { - if (!hasCursors()) { + if(!hasCursors()) { return; } enum CustomPlotPositionButton::ReadoutsPosition types[] = { CustomPlotPositionButton::ReadoutsPosition::topLeft, CustomPlotPositionButton::ReadoutsPosition::topRight, CustomPlotPositionButton::ReadoutsPosition::bottomLeft, - CustomPlotPositionButton::ReadoutsPosition::bottomRight - }; + CustomPlotPositionButton::ReadoutsPosition::bottomRight}; m_logic->cursorsPositionButton->setPosition(types[val]); m_logic->m_plot.replot(); } int LogicAnalyzer_API::getCursorsTransparency() const { - if (!hasCursors()) { + if(!hasCursors()) { return 0; } return m_logic->cr_ui->horizontalSlider->value(); @@ -497,7 +453,7 @@ int LogicAnalyzer_API::getCursorsTransparency() const void LogicAnalyzer_API::setCursorsTransparency(int val) { - if (!hasCursors()) { + if(!hasCursors()) { return; } m_logic->cr_ui->horizontalSlider->setValue(val); diff --git a/plugins/m2k/src/old/logicanalyzer/logicanalyzer_api.h b/plugins/m2k/src/old/logicanalyzer/logicanalyzer_api.h index 384a1733b9..fc5f19c18d 100644 --- a/plugins/m2k/src/old/logicanalyzer/logicanalyzer_api.h +++ b/plugins/m2k/src/old/logicanalyzer/logicanalyzer_api.h @@ -18,7 +18,6 @@ * along with this program. If not, see . */ - #ifndef LOGICANALYZER_API_H #define LOGICANALYZER_API_H @@ -33,10 +32,8 @@ class LogicAnalyzer_API : public ApiObject /*cursor settings*/ Q_PROPERTY(bool cursors READ hasCursors WRITE setCursors); - Q_PROPERTY(int cursors_position READ getCursorsPosition - WRITE setCursorsPosition) - Q_PROPERTY(int cursors_transparency READ getCursorsTransparency - WRITE setCursorsTransparency) + Q_PROPERTY(int cursors_position READ getCursorsPosition WRITE setCursorsPosition) + Q_PROPERTY(int cursors_transparency READ getCursorsTransparency WRITE setCursorsTransparency) /* sweep settings */ Q_PROPERTY(bool streamOneShot READ getStreamOrOneShot WRITE setStreamOrOneShot) @@ -49,8 +46,8 @@ class LogicAnalyzer_API : public ApiObject /* decoders */ Q_PROPERTY(QStringList enabledDecoders READ getEnabledDecoders WRITE setEnabledDecoders) - Q_PROPERTY(QList>> assignedDecoderChannels READ getAssignedDecoderChannels - WRITE setAssignedDecoderChannels) + Q_PROPERTY(QList>> assignedDecoderChannels READ getAssignedDecoderChannels WRITE + setAssignedDecoderChannels) Q_PROPERTY(QList decoderStack READ getDecoderStack WRITE setDecoderStack) Q_PROPERTY(QList decoderSettings READ getDecoderSettings WRITE setDecoderSettings) @@ -66,8 +63,10 @@ class LogicAnalyzer_API : public ApiObject Q_PROPERTY(QString notes READ getNotes WRITE setNotes) public: - explicit LogicAnalyzer_API(logic::LogicAnalyzer *logic): - ApiObject(), m_logic(logic) { + explicit LogicAnalyzer_API(logic::LogicAnalyzer *logic) + : ApiObject() + , m_logic(logic) + { // Register type. TODO: maybe a cleaner way of doing this // QVariant needs qRegisterMetaTypeStreamOperators for serialization/deserialization qRegisterMetaType>("pair"); @@ -124,7 +123,7 @@ class LogicAnalyzer_API : public ApiObject void setDecoderSettings(const QList &decoderSettings); QVector> getCurrentGroups() const; - void setCurrentGroups(const QVector > &groups); + void setCurrentGroups(const QVector> &groups); QString getNotes(); void setNotes(QString str); @@ -141,7 +140,7 @@ class LogicAnalyzer_API : public ApiObject int getCursorsTransparency() const; void setCursorsTransparency(int val); }; -} -} +} // namespace logic +} // namespace scopy::m2k #endif // LOGICANALYZER_API_H diff --git a/plugins/m2k/src/old/logicanalyzer/logicgroupitem.cpp b/plugins/m2k/src/old/logicanalyzer/logicgroupitem.cpp index bb5e3d4047..b74cfeb245 100644 --- a/plugins/m2k/src/old/logicanalyzer/logicgroupitem.cpp +++ b/plugins/m2k/src/old/logicanalyzer/logicgroupitem.cpp @@ -18,33 +18,29 @@ * along with this program. If not, see . */ - #include "logicgroupitem.h" +#include "gui/basemenu.h" + +#include #include -#include #include -#include - -#include "gui/basemenu.h" +#include using namespace scopy; -LogicGroupItem::LogicGroupItem(const QString &name, QWidget *parent): - BaseMenuItem(parent), - m_nameLabel(new QLabel(name, this)) +LogicGroupItem::LogicGroupItem(const QString &name, QWidget *parent) + : BaseMenuItem(parent) + , m_nameLabel(new QLabel(name, this)) { buildUi(); } -QString LogicGroupItem::getName() const -{ - return m_nameLabel->text(); -} +QString LogicGroupItem::getName() const { return m_nameLabel->text(); } void LogicGroupItem::setName(const QString &name) { - if (m_nameLabel->text() != name) { + if(m_nameLabel->text() != name) { m_nameLabel->setText(name); qDebug() << "Changing name to: " << name; } @@ -79,7 +75,7 @@ void LogicGroupItem::buildUi() dragWidget->setMinimumSize(QSize(16, 16)); QFrame *frame = new QFrame(dragWidget); - frame->setProperty("drag_widget",true); + frame->setProperty("drag_widget", true); layoutDragWidget->addWidget(frame); QSpacerItem *spacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); @@ -88,12 +84,11 @@ void LogicGroupItem::buildUi() deleteBtn->setFlat(true); deleteBtn->setIcon(QIcon(":/gui/icons/close_hovered.svg")); deleteBtn->setMaximumSize(QSize(16, 16)); - connect(deleteBtn, &QPushButton::clicked, - this, &LogicGroupItem::deleteBtnClicked); - connect(deleteBtn, &QPushButton::clicked, [=](){ + connect(deleteBtn, &QPushButton::clicked, this, &LogicGroupItem::deleteBtnClicked); + connect(deleteBtn, &QPushButton::clicked, [=]() { BaseMenu *menu = getOwner(); - if (!menu) { + if(!menu) { return; } diff --git a/plugins/m2k/src/old/logicanalyzer/logicgroupitem.h b/plugins/m2k/src/old/logicanalyzer/logicgroupitem.h index 3a6ac3096a..6604837a1f 100644 --- a/plugins/m2k/src/old/logicanalyzer/logicgroupitem.h +++ b/plugins/m2k/src/old/logicanalyzer/logicgroupitem.h @@ -18,7 +18,6 @@ * along with this program. If not, see . */ - #ifndef LOGICGROUPITEM_H #define LOGICGROUPITEM_H @@ -47,6 +46,6 @@ public Q_SLOTS: private: QLabel *m_nameLabel; }; -} +} // namespace scopy #endif // LOGICGROUPITEM_H diff --git a/plugins/m2k/src/old/m2kpluginExceptionHandler.h b/plugins/m2k/src/old/m2kpluginExceptionHandler.h index e2c7579711..fc8df8885e 100644 --- a/plugins/m2k/src/old/m2kpluginExceptionHandler.h +++ b/plugins/m2k/src/old/m2kpluginExceptionHandler.h @@ -5,17 +5,17 @@ //#include #include //#include -#include #include +#include -//using namespace scopy::m2k; +// using namespace scopy::m2k; // Debug messages are currently disabled for users, can be used for development. // The message box was removed because exceptions might occur both from the control flow // and for signaling problems. Until those are handled separately, we can't use // QMessageBox to show the exception, since those can be thrown from different threads. -#define HANDLE_EXCEPTION(e) \ +#define HANDLE_EXCEPTION(e) \ //if (GetScopyApplicationInstance()->getDebugMode()) { \ // auto me = dynamic_cast(&e); \ // QString str; \ diff --git a/plugins/m2k/src/old/m2ktool.cpp b/plugins/m2k/src/old/m2ktool.cpp index a6efefc587..3077c9a56d 100644 --- a/plugins/m2k/src/old/m2ktool.cpp +++ b/plugins/m2k/src/old/m2ktool.cpp @@ -19,19 +19,22 @@ */ #include "m2ktool.hpp" -#include +#include using namespace scopy; using namespace scopy::m2k; -M2kTool::M2kTool(struct iio_context *ctx, ToolMenuEntry *tme, - ApiObject *api, const QString& name, - QWidget *parent) : - QWidget(parent), - ctx(ctx), api(api), - name(name), saveOnExit(true), isDetached(false), m_running(false), - window(nullptr), tme(tme) +M2kTool::M2kTool(struct iio_context *ctx, ToolMenuEntry *tme, ApiObject *api, const QString &name, QWidget *parent) + : QWidget(parent) + , ctx(ctx) + , api(api) + , name(name) + , saveOnExit(true) + , isDetached(false) + , m_running(false) + , window(nullptr) + , tme(tme) { tme->setEnabled(true); p = Preferences::GetInstance(); @@ -45,64 +48,30 @@ M2kTool::~M2kTool() tme->setRunning(false); tme->setEnabled(false); - - } -const QString &M2kTool::getName() -{ - return name; -} - -void M2kTool::setName(const QString &name) -{ - this->name = name; -} +const QString &M2kTool::getName() { return name; } -void M2kTool::settingsLoaded() -{ +void M2kTool::setName(const QString &name) { this->name = name; } -} +void M2kTool::settingsLoaded() {} /* Tools that use file dialogs should overload this method to ensure their file dialogs are configured correspondingly */ -void M2kTool::setNativeDialogs(bool nativeDialogs) -{ - m_useNativeDialogs = nativeDialogs; -} +void M2kTool::setNativeDialogs(bool nativeDialogs) { m_useNativeDialogs = nativeDialogs; } -ApiObject *M2kTool::getApi() -{ - return api; -} +ApiObject *M2kTool::getApi() { return api; } void M2kTool::readPreferences() { saveOnExit = p->get("general_save_on_exit").toBool(); - m_useNativeDialogs = p->get("general_native_dialogs").toBool();; + m_useNativeDialogs = p->get("general_native_dialogs").toBool(); + ; } -ToolMenuEntry *M2kTool::getTme() const -{ - return tme; -} - -void M2kTool::run() -{ - -} -void M2kTool::stop() -{ - -} -void M2kTool::single() -{ - -} -bool M2kTool::isRunning() -{ - return m_running; -} - - +ToolMenuEntry *M2kTool::getTme() const { return tme; } +void M2kTool::run() {} +void M2kTool::stop() {} +void M2kTool::single() {} +bool M2kTool::isRunning() { return m_running; } diff --git a/plugins/m2k/src/old/m2ktool.hpp b/plugins/m2k/src/old/m2ktool.hpp index 3886c08877..3fd2358c5d 100644 --- a/plugins/m2k/src/old/m2ktool.hpp +++ b/plugins/m2k/src/old/m2ktool.hpp @@ -21,23 +21,25 @@ #ifndef M2K_TOOL_HPP #define M2K_TOOL_HPP -#include -#include -#include +#include "pluginbase/toolmenuentry.h" + #include #include -#include #include -#include "pluginbase/toolmenuentry.h" +#include +#include +#include +#include + #include #include - class QJSEngine; class QPushButton; -extern "C" { -struct iio_context; +extern "C" +{ + struct iio_context; } namespace scopy { @@ -50,17 +52,16 @@ class M2kTool : public QWidget, public ResourceUser Q_OBJECT public: - explicit M2kTool(struct iio_context *ctx, ToolMenuEntry *tme, - ApiObject *api, const QString& name, - QWidget *parent); + explicit M2kTool(struct iio_context *ctx, ToolMenuEntry *tme, ApiObject *api, const QString &name, + QWidget *parent); ~M2kTool(); - const QString& getName(); - void setName(const QString& name); + const QString &getName(); + void setName(const QString &name); virtual void settingsLoaded(); virtual void setNativeDialogs(bool nativeDialogs); - ApiObject* getApi(); + ApiObject *getApi(); ToolMenuEntry *getTme() const; @@ -75,7 +76,7 @@ public Q_SLOTS: virtual void readPreferences(); protected: - struct iio_context *ctx; + struct iio_context *ctx; ApiObject *api; QString name; bool saveOnExit; @@ -87,6 +88,6 @@ public Q_SLOTS: bool m_useNativeDialogs; QWidget *m_centralWidget; }; -} -} +} // namespace m2k +} // namespace scopy #endif /* SCOPY_TOOL_HPP */ diff --git a/plugins/m2k/src/old/manual_calibration_api.cpp b/plugins/m2k/src/old/manual_calibration_api.cpp index a0d01df7ee..df1dc9fa9d 100644 --- a/plugins/m2k/src/old/manual_calibration_api.cpp +++ b/plugins/m2k/src/old/manual_calibration_api.cpp @@ -19,45 +19,40 @@ */ #include "manual_calibration_api.hpp" -#include "ui_manualcalibration.h" + #include "ui_calibratetemplate.h" +#include "ui_manualcalibration.h" #include +#include #include #include #include -#include using namespace scopy::m2k; -ManualCalibration_API::ManualCalibration_API(ManualCalibration *m_calib) : - ApiObject(), - calib(m_calib), - step_in_progress(-1) -{ - -} +ManualCalibration_API::ManualCalibration_API(ManualCalibration *m_calib) + : ApiObject() + , calib(m_calib) + , step_in_progress(-1) +{} -void ManualCalibration_API::autoCalibration() -{ - calib->ui->autoButton->click(); -} +void ManualCalibration_API::autoCalibration() { calib->ui->autoButton->click(); } int ManualCalibration_API::start(int story) { - if (step_in_progress >= 0) { + if(step_in_progress >= 0) { // Reset the current step if another story // was already started and did not end yet step_in_progress = -1; } - if (story >= calib->ui->calibList->count()) { + if(story >= calib->ui->calibList->count()) { return -1; } calib->ui->calibList->setCurrentRow(story); - Q_EMIT calib->ui->calibList->itemClicked( - calib->ui->calibList->item(story)); + Q_EMIT calib->ui->calibList->itemClicked(calib->ui->calibList->item(story)); int nb_steps = calib->stCalibrationStory.story.count(); - if (nb_steps > 0) { + if(nb_steps > 0) { step_in_progress = 0; } return nb_steps; @@ -68,13 +63,13 @@ int ManualCalibration_API::next() auto currentStory = calib->stCalibrationStory; // If a story was not yet started, return -1 - if (step_in_progress < 0) { + if(step_in_progress < 0) { return -1; } calib->TempUi->nextButton->click(); step_in_progress++; - if ((step_in_progress + 1) > currentStory.story.count()) { + if((step_in_progress + 1) > currentStory.story.count()) { return -1; } return step_in_progress + 1; @@ -85,19 +80,19 @@ int ManualCalibration_API::finish() auto currentStory = calib->stCalibrationStory; // If a story was not yet started, return -1 - if (step_in_progress < 0) { + if(step_in_progress < 0) { return -1; } // Finish the story, if not all the steps are done yet - while (step_in_progress < currentStory.story.count()) { + while(step_in_progress < currentStory.story.count()) { next(); } calib->TempUi->finishButton->click(); step_in_progress = -1; - if ((currentStory.calibProcedure + 1) < calib->calibListString.count()) { + if((currentStory.calibProcedure + 1) < calib->calibListString.count()) { return currentStory.calibProcedure + 1; } return -1; @@ -106,7 +101,7 @@ int ManualCalibration_API::finish() bool ManualCalibration_API::setParam(double value) { auto currentStory = calib->stCalibrationStory; - if (currentStory.story.count() > 0) { + if(currentStory.story.count() > 0) { calib->TempUi->lineEdit->setText(QString::number(value)); return true; } @@ -116,66 +111,41 @@ bool ManualCalibration_API::setParam(double value) void ManualCalibration_API::saveCalibration(QString path) { bool buttonEn = calib->ui->saveButton->isEnabled(); - if (!buttonEn) { + if(!buttonEn) { calib->ui->saveButton->setEnabled(true); } calib->setCalibrationFilePath(path); calib->ui->saveButton->click(); calib->setCalibrationFilePath(""); - if (!buttonEn) { + if(!buttonEn) { calib->ui->saveButton->setEnabled(false); } } - void ManualCalibration_API::loadCalibration() { bool buttonEn = calib->ui->loadButton->isEnabled(); - if (!buttonEn) { + if(!buttonEn) { calib->ui->loadButton->setEnabled(true); } calib->ui->loadButton->click(); - if (!buttonEn) { + if(!buttonEn) { calib->ui->loadButton->setEnabled(false); } } -double ManualCalibration_API::getOffsetPosDac() const -{ - return calib->paramTable->item(0, 1)->text().toDouble(); -} +double ManualCalibration_API::getOffsetPosDac() const { return calib->paramTable->item(0, 1)->text().toDouble(); } -double ManualCalibration_API::getGainPosDac() const -{ - return calib->paramTable->item(1, 1)->text().toDouble(); -} +double ManualCalibration_API::getGainPosDac() const { return calib->paramTable->item(1, 1)->text().toDouble(); } -double ManualCalibration_API::getOffsetPosAdc() const -{ - return calib->paramTable->item(2, 1)->text().toDouble(); -} +double ManualCalibration_API::getOffsetPosAdc() const { return calib->paramTable->item(2, 1)->text().toDouble(); } -double ManualCalibration_API::getGainPosAdc() const -{ - return calib->paramTable->item(3, 1)->text().toDouble(); -} +double ManualCalibration_API::getGainPosAdc() const { return calib->paramTable->item(3, 1)->text().toDouble(); } -double ManualCalibration_API::getOffsetNegDac() const -{ - return calib->paramTable->item(4, 1)->text().toDouble(); -} +double ManualCalibration_API::getOffsetNegDac() const { return calib->paramTable->item(4, 1)->text().toDouble(); } -double ManualCalibration_API::getGainNegDac() const -{ - return calib->paramTable->item(5, 1)->text().toDouble(); -} +double ManualCalibration_API::getGainNegDac() const { return calib->paramTable->item(5, 1)->text().toDouble(); } -double ManualCalibration_API::getOffsetNegAdc() const -{ - return calib->paramTable->item(6, 1)->text().toDouble(); -} +double ManualCalibration_API::getOffsetNegAdc() const { return calib->paramTable->item(6, 1)->text().toDouble(); } -double ManualCalibration_API::getGainNegAdc() const -{ - return calib->paramTable->item(7, 1)->text().toDouble(); -} +double ManualCalibration_API::getGainNegAdc() const { return calib->paramTable->item(7, 1)->text().toDouble(); } diff --git a/plugins/m2k/src/old/manual_calibration_api.hpp b/plugins/m2k/src/old/manual_calibration_api.hpp index 8ea7b6ac48..7d9c1395f2 100644 --- a/plugins/m2k/src/old/manual_calibration_api.hpp +++ b/plugins/m2k/src/old/manual_calibration_api.hpp @@ -21,11 +21,12 @@ #ifndef MANUAL_CALIBRATION_API_HPP #define MANUAL_CALIBRATION_API_HPP -#include -#include #include "manualcalibration.h" #include "pluginbase/apiobject.h" +#include +#include + class QJSEngine; using namespace scopy; @@ -52,21 +53,18 @@ class ManualCalibration_API : public ApiObject Q_INVOKABLE void autoCalibration(); - /* Starts a calib story. * Returns the number of steps in this story. * Returns -1 if there are no steps */ Q_INVOKABLE int start(int story); - /* Moves the execution from the current step, to the next one. * Returns the next step index for this story. * Returns -1 if this was the last step. */ Q_INVOKABLE int next(); - /* Saves the params set for this story. * Should be run after the last step in the story. * Returns the next story index. @@ -74,12 +72,10 @@ class ManualCalibration_API : public ApiObject */ Q_INVOKABLE int finish(); - /* Save a value for the current step, in the current story. */ Q_INVOKABLE bool setParam(double value); - /* Write all the params in the .ini calibration file. */ Q_INVOKABLE void saveCalibration(QString path); @@ -102,7 +98,6 @@ class ManualCalibration_API : public ApiObject int step_in_progress; }; -} +} // namespace scopy::m2k #endif /* MANUAL_CALIBRATION_API_HPP */ - diff --git a/plugins/m2k/src/old/manualcalibration.cpp b/plugins/m2k/src/old/manualcalibration.cpp index cea001ff4c..f15e5ac815 100644 --- a/plugins/m2k/src/old/manualcalibration.cpp +++ b/plugins/m2k/src/old/manualcalibration.cpp @@ -19,28 +19,31 @@ */ #include "manualcalibration.h" -#include "ui_manualcalibration.h" -#include "ui_calibratetemplate.h" + #include "manual_calibration_api.hpp" +#include "ui_calibratetemplate.h" +#include "ui_manualcalibration.h" + +#include #include -#include #include +#include #include -#include #include /* libm2k includes */ +#include "m2kpluginExceptionHandler.h" + +#include + +#include +#include #include #include #include -#include -#include -#include "m2kpluginExceptionHandler.h" #include - -#include -Q_LOGGING_CATEGORY(CAT_M2K_CALIBRATION_MANUAL,"M2kCalibrationManual") +Q_LOGGING_CATEGORY(CAT_M2K_CALIBRATION_MANUAL, "M2kCalibrationManual") using namespace scopy::m2k; using namespace libm2k::context; @@ -53,33 +56,34 @@ static const double SUPPLY_4_5V_NEG_VALUE = -4.5; /*Calibrations procedure stories*/ static const QStringList positiveOffsetStory = (QStringList() << - R"(Calibrate the Positive Supply. + R"(Calibrate the Positive Supply. Measure the Voltage on the "V+" and enter the value in the field below. The value should be around 100mV)" - << R"(Calibrate the Positive Supply + << R"(Calibrate the Positive Supply Measure the Voltage on the "V+" and enter the value in the field below. The value should be around 4.5V)"); static const QStringList negativeOffsetStory = (QStringList() << - R"(Calibrate the Negative Supply + R"(Calibrate the Negative Supply Measure the Voltage on the "V-" and enter the value in the field below. The value should be around -100mV)" - << R"(Calibrate the Negative Supply + << R"(Calibrate the Negative Supply Measure the Voltage on the "V-" and enter the value in the field below. The value should be around -4.5V)"); -ManualCalibration::ManualCalibration(struct iio_context *ctx, Filter *filt, - ToolMenuEntry *tme, - QWidget *parent, Calibration *cal) : - M2kTool(ctx, tme, new ManualCalibration_API(this), "Calibration", parent), - ui(new Ui::ManualCalibration), filter(filt), ctx(ctx), - calib(cal), - calibrationFilePath(""), - m_m2k_context(m2kOpen(ctx, "")), - m_m2k_powersupply(m_m2k_context->getPowerSupply()) +ManualCalibration::ManualCalibration(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, QWidget *parent, + Calibration *cal) + : M2kTool(ctx, tme, new ManualCalibration_API(this), "Calibration", parent) + , ui(new Ui::ManualCalibration) + , filter(filt) + , ctx(ctx) + , calib(cal) + , calibrationFilePath("") + , m_m2k_context(m2kOpen(ctx, "")) + , m_m2k_powersupply(m_m2k_context->getPowerSupply()) { ui->setupUi(this); calibListString << "Positive supply" @@ -110,14 +114,11 @@ ManualCalibration::ManualCalibration(struct iio_context *ctx, Filter *filt, TempUi->inputTableWidget->setRowCount(2); TempUi->inputTableWidget->setEnabled(false); - connect(TempUi->nextButton, &QPushButton::clicked, this, - &ManualCalibration::nextButton_clicked); - connect(TempUi->restartButton, &QPushButton::clicked, this, - &ManualCalibration::restartButton_clicked); - connect(TempUi->finishButton, &QPushButton::clicked, this, - &ManualCalibration::finishButton_clicked); + connect(TempUi->nextButton, &QPushButton::clicked, this, &ManualCalibration::nextButton_clicked); + connect(TempUi->restartButton, &QPushButton::clicked, this, &ManualCalibration::restartButton_clicked); + connect(TempUi->finishButton, &QPushButton::clicked, this, &ManualCalibration::finishButton_clicked); - ui->calibList->setCurrentRow(3); //set to autocalibration parameters + ui->calibList->setCurrentRow(3); // set to autocalibration parameters on_calibList_itemClicked(ui->calibList->currentItem()); m_dmm_ad9963 = m_m2k_context->getDMM("ad9963"); @@ -138,7 +139,7 @@ void ManualCalibration::startCalibration() { qDebug(CAT_M2K_CALIBRATION_MANUAL) << "START: Calibration has started"; - switch (stCalibrationStory.calibProcedure) { + switch(stCalibrationStory.calibProcedure) { case POSITIVE_OFFSET: positivePowerSupplyParam(stCalibrationStory.calibStep); break; @@ -148,16 +149,15 @@ void ManualCalibration::startCalibration() break; } - //go to next step + // go to next step nextStep(); } void ManualCalibration::nextStep() { - if (stCalibrationStory.story.count() > (stCalibrationStory.calibStep + 1)) { + if(stCalibrationStory.story.count() > (stCalibrationStory.calibStep + 1)) { stCalibrationStory.calibStep++; - TempUi->instructionText->setText( - stCalibrationStory.story[stCalibrationStory.calibStep]); + TempUi->instructionText->setText(stCalibrationStory.story[stCalibrationStory.calibStep]); } else { qDebug(CAT_M2K_CALIBRATION_MANUAL) << "Calibration procedure finished"; } @@ -177,7 +177,7 @@ void ManualCalibration::on_calibList_itemClicked(QListWidgetItem *item) stCalibrationStory.story = QStringList(); stCalibrationStory.storyName.clear(); - switch (calibOption[temp]) { + switch(calibOption[temp]) { case POSITIVE_OFFSET: positivePowerSupplySetup(); paramTable->hide(); @@ -222,8 +222,7 @@ void ManualCalibration::positivePowerSupplySetup() stCalibrationStory.storyName.clear(); stCalibrationStory.storyName.append("Positive supply"); ui->storyWidget->layout()->addWidget(TempWidget); - TempUi->instructionText->setText( - stCalibrationStory.story[stCalibrationStory.calibStep]); + TempUi->instructionText->setText(stCalibrationStory.story[stCalibrationStory.calibStep]); /*Set DAC to 0V*/ setEnablePositiveSuppply(true); @@ -239,7 +238,7 @@ void ManualCalibration::positivePowerSupplyParam(const int step) offset_Value = TempUi->lineEdit->text().toDouble(); - switch (step) { + switch(step) { case STEP1: /*dac offset calibration*/ stParameters.offset_pos_dac = SUPPLY_100MV_VALUE - offset_Value; @@ -248,7 +247,7 @@ void ManualCalibration::positivePowerSupplyParam(const int step) /*adc offset calibration*/ try { value = m_m2k_powersupply->readChannel(0, false); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_CALIBRATION_MANUAL) << "Can't read value: " << e.what(); } @@ -257,14 +256,12 @@ void ManualCalibration::positivePowerSupplyParam(const int step) qDebug(CAT_M2K_CALIBRATION_MANUAL) << "Positive offset ADC value: " << stParameters.offset_pos_adc; TempUi->inputTableWidget->setItem(0, 0, new QTableWidgetItem("100mV")); - TempUi->inputTableWidget->setItem(0, 1, new QTableWidgetItem(QString::number( - offset_Value) + QString("V"))); + TempUi->inputTableWidget->setItem(0, 1, + new QTableWidgetItem(QString::number(offset_Value) + QString("V"))); TempUi->lineEdit->clear(); - paramTable->setItem(0, 1, new QTableWidgetItem(QString::number( - stParameters.offset_pos_dac))); - paramTable->setItem(2, 1, new QTableWidgetItem(QString::number( - stParameters.offset_pos_adc))); + paramTable->setItem(0, 1, new QTableWidgetItem(QString::number(stParameters.offset_pos_dac))); + paramTable->setItem(2, 1, new QTableWidgetItem(QString::number(stParameters.offset_pos_adc))); paramTable->resizeColumnsToContents(); /*Set dac to 4.5V*/ @@ -274,32 +271,28 @@ void ManualCalibration::positivePowerSupplyParam(const int step) case STEP2: /*dac gain calibration*/ - if (offset_Value != 0) { - stParameters.gain_pos_dac = SUPPLY_4_5V_VALUE / (offset_Value + - stParameters.offset_pos_dac); + if(offset_Value != 0) { + stParameters.gain_pos_dac = SUPPLY_4_5V_VALUE / (offset_Value + stParameters.offset_pos_dac); qDebug(CAT_M2K_CALIBRATION_MANUAL) << "Positive gain DAC value: " << stParameters.gain_pos_dac; /*adc gain calibration*/ try { value = m_m2k_powersupply->readChannel(0, false); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_CALIBRATION_MANUAL) << "Can't read value: " << e.what(); } - stParameters.gain_pos_adc = offset_Value / (value + - stParameters.offset_pos_adc); + stParameters.gain_pos_adc = offset_Value / (value + stParameters.offset_pos_adc); qDebug(CAT_M2K_CALIBRATION_MANUAL) << "Positive gain ADC value: " << stParameters.gain_pos_adc; } TempUi->restartButton->setVisible(true); TempUi->inputTableWidget->setItem(1, 0, new QTableWidgetItem("4.5V")); - TempUi->inputTableWidget->setItem(1, 1, new QTableWidgetItem(QString::number( - offset_Value) + QString("V"))); + TempUi->inputTableWidget->setItem(1, 1, + new QTableWidgetItem(QString::number(offset_Value) + QString("V"))); - paramTable->setItem(1, 1, new QTableWidgetItem(QString::number( - stParameters.gain_pos_dac))); - paramTable->setItem(3, 1, new QTableWidgetItem(QString::number( - stParameters.gain_pos_adc))); + paramTable->setItem(1, 1, new QTableWidgetItem(QString::number(stParameters.gain_pos_dac))); + paramTable->setItem(3, 1, new QTableWidgetItem(QString::number(stParameters.gain_pos_adc))); paramTable->resizeColumnsToContents(); TempUi->nextButton->setVisible(false); @@ -310,12 +303,11 @@ void ManualCalibration::positivePowerSupplyParam(const int step) TempUi->lineEdit->clear(); } - void ManualCalibration::setEnablePositiveSuppply(bool enabled) { try { m_m2k_powersupply->enableChannel(0, enabled); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_CALIBRATION_MANUAL) << "Can't enable channel: " << e.what(); } @@ -325,7 +317,7 @@ void ManualCalibration::setPositiveValue(double value) { try { m_m2k_powersupply->pushChannel(0, value, false); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_CALIBRATION_MANUAL) << "Can't write value: " << e.what(); } @@ -344,8 +336,7 @@ void ManualCalibration::negativePowerSupplySetup() stCalibrationStory.storyName.clear(); stCalibrationStory.storyName.append("Negative supply"); ui->storyWidget->layout()->addWidget(TempWidget); - TempUi->instructionText->setText( - stCalibrationStory.story[stCalibrationStory.calibStep]); + TempUi->instructionText->setText(stCalibrationStory.story[stCalibrationStory.calibStep]); setEnableNegativeSuppply(true); setNegativeValue(-0.1); @@ -360,7 +351,7 @@ void ManualCalibration::negativePowerSupplyParam(const int step) offset_Value = TempUi->lineEdit->text().toDouble(); - switch (step) { + switch(step) { case STEP1: /*dac offset calibration*/ stParameters.offset_neg_dac = SUPPLY_100MV_NEG_VALUE - offset_Value; @@ -369,7 +360,7 @@ void ManualCalibration::negativePowerSupplyParam(const int step) /*adc offset calibration*/ try { value = m_m2k_powersupply->readChannel(1, false); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_CALIBRATION_MANUAL) << "Can't read value: " << e.what(); } @@ -377,14 +368,12 @@ void ManualCalibration::negativePowerSupplyParam(const int step) qDebug(CAT_M2K_CALIBRATION_MANUAL) << "Negative offset ADC value: " << stParameters.offset_neg_adc; TempUi->inputTableWidget->setItem(0, 0, new QTableWidgetItem("-100mV")); - TempUi->inputTableWidget->setItem(0, 1, new QTableWidgetItem(QString::number( - offset_Value) + QString("V"))); + TempUi->inputTableWidget->setItem(0, 1, + new QTableWidgetItem(QString::number(offset_Value) + QString("V"))); TempUi->lineEdit->clear(); - paramTable->setItem(4, 1, new QTableWidgetItem(QString::number( - stParameters.offset_neg_dac))); - paramTable->setItem(6, 1, new QTableWidgetItem(QString::number( - stParameters.offset_neg_adc))); + paramTable->setItem(4, 1, new QTableWidgetItem(QString::number(stParameters.offset_neg_dac))); + paramTable->setItem(6, 1, new QTableWidgetItem(QString::number(stParameters.offset_neg_adc))); paramTable->resizeColumnsToContents(); /*Set dac to -4.5V*/ @@ -394,32 +383,29 @@ void ManualCalibration::negativePowerSupplyParam(const int step) case STEP2: /*dac gain calibration*/ - if (offset_Value != 0) { - stParameters.gain_neg_dac = SUPPLY_4_5V_NEG_VALUE / (offset_Value + - stParameters.offset_neg_dac); + if(offset_Value != 0) { + stParameters.gain_neg_dac = + SUPPLY_4_5V_NEG_VALUE / (offset_Value + stParameters.offset_neg_dac); qDebug(CAT_M2K_CALIBRATION_MANUAL) << "Negative gain DAC value: " << stParameters.gain_neg_dac; /*adc gain calibration*/ try { value = m_m2k_powersupply->readChannel(1, false); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_CALIBRATION_MANUAL) << "Can't read value: " << e.what(); } - stParameters.gain_neg_adc = offset_Value / (value + - stParameters.offset_neg_adc); + stParameters.gain_neg_adc = offset_Value / (value + stParameters.offset_neg_adc); qDebug(CAT_M2K_CALIBRATION_MANUAL) << "Negative gain ADC value: " << stParameters.gain_neg_adc; } TempUi->restartButton->setVisible(true); TempUi->inputTableWidget->setItem(1, 0, new QTableWidgetItem("4.5V")); - TempUi->inputTableWidget->setItem(1, 1, new QTableWidgetItem(QString::number( - offset_Value) + QString("V"))); + TempUi->inputTableWidget->setItem(1, 1, + new QTableWidgetItem(QString::number(offset_Value) + QString("V"))); - paramTable->setItem(5, 1, new QTableWidgetItem(QString::number( - stParameters.gain_neg_dac))); - paramTable->setItem(7, 1, new QTableWidgetItem(QString::number( - stParameters.gain_neg_adc))); + paramTable->setItem(5, 1, new QTableWidgetItem(QString::number(stParameters.gain_neg_dac))); + paramTable->setItem(7, 1, new QTableWidgetItem(QString::number(stParameters.gain_neg_adc))); paramTable->resizeColumnsToContents(); TempUi->nextButton->setVisible(false); @@ -434,7 +420,7 @@ void ManualCalibration::setEnableNegativeSuppply(bool enabled) { try { m_m2k_powersupply->enableChannel(1, enabled); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_CALIBRATION_MANUAL) << "Can't enable channel: " << e.what(); } @@ -444,29 +430,22 @@ void ManualCalibration::setNegativeValue(double value) { try { m_m2k_powersupply->pushChannel(1, value, false); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_CALIBRATION_MANUAL) << "Can't write value: " << e.what(); } } -void ManualCalibration::nextButton_clicked() -{ - startCalibration(); -} +void ManualCalibration::nextButton_clicked() { startCalibration(); } -void ManualCalibration::setCalibration(Calibration *cal) -{ - calib = cal; -} +void ManualCalibration::setCalibration(Calibration *cal) { calib = cal; } void ManualCalibration::allowManualCalibScript(bool calib_en, bool calib_pref_en) { - if (calib_pref_en && calib_en) { - eng->globalObject().setProperty("manual_calib", - eng->newQObject(api)); + if(calib_pref_en && calib_en) { + eng->globalObject().setProperty("manual_calib", eng->newQObject(api)); } else { - if (eng->globalObject().hasProperty("manual_calib")) { + if(eng->globalObject().hasProperty("manual_calib")) { eng->globalObject().deleteProperty("manual_calib"); } } @@ -476,42 +455,39 @@ void ManualCalibration::displayStartUpCalibrationValues(void) { QStringList tableHeader; - tableHeader <<"Name"<<"Value"; + tableHeader << "Name" + << "Value"; startParamTable->setRowCount(8); startParamTable->setColumnCount(2); startParamTable->setHorizontalHeaderLabels(tableHeader); startParamTable->setItem(0, 0, new QTableWidgetItem("ADC offset Ch0")); - startParamTable->setItem(0, 1, new QTableWidgetItem(QString::number( - m_m2k_context->getAdcCalibrationOffset(0)))); + startParamTable->setItem(0, 1, + new QTableWidgetItem(QString::number(m_m2k_context->getAdcCalibrationOffset(0)))); startParamTable->setItem(1, 0, new QTableWidgetItem("ADC offset Ch1")); - startParamTable->setItem(1, 1, new QTableWidgetItem(QString::number( - m_m2k_context->getAdcCalibrationOffset(1)))); + startParamTable->setItem(1, 1, + new QTableWidgetItem(QString::number(m_m2k_context->getAdcCalibrationOffset(1)))); startParamTable->setItem(2, 0, new QTableWidgetItem("ADC gain Ch0")); - startParamTable->setItem(2, 1, new QTableWidgetItem(QString::number( - m_m2k_context->getAdcCalibrationGain(0)))); + startParamTable->setItem(2, 1, new QTableWidgetItem(QString::number(m_m2k_context->getAdcCalibrationGain(0)))); startParamTable->setItem(3, 0, new QTableWidgetItem("ADC gain Ch1")); - startParamTable->setItem(3, 1, new QTableWidgetItem(QString::number( - m_m2k_context->getAdcCalibrationGain(1)))); + startParamTable->setItem(3, 1, new QTableWidgetItem(QString::number(m_m2k_context->getAdcCalibrationGain(1)))); startParamTable->setItem(4, 0, new QTableWidgetItem("DAC A offset")); - startParamTable->setItem(4, 1, new QTableWidgetItem(QString::number( - m_m2k_context->getDacCalibrationOffset(0)))); + startParamTable->setItem(4, 1, + new QTableWidgetItem(QString::number(m_m2k_context->getDacCalibrationOffset(0)))); startParamTable->setItem(5, 0, new QTableWidgetItem("DAC B offset")); - startParamTable->setItem(5, 1, new QTableWidgetItem(QString::number( - m_m2k_context->getDacCalibrationOffset(1)))); + startParamTable->setItem(5, 1, + new QTableWidgetItem(QString::number(m_m2k_context->getDacCalibrationOffset(1)))); startParamTable->setItem(6, 0, new QTableWidgetItem("DAC A vlsb")); - startParamTable->setItem(6, 1, new QTableWidgetItem(QString::number( - m_m2k_context->getDacCalibrationGain(0)))); + startParamTable->setItem(6, 1, new QTableWidgetItem(QString::number(m_m2k_context->getDacCalibrationGain(0)))); startParamTable->setItem(7, 0, new QTableWidgetItem("DAC B vlsb")); - startParamTable->setItem(7, 1, new QTableWidgetItem(QString::number( - m_m2k_context->getDacCalibrationGain(1)))); + startParamTable->setItem(7, 1, new QTableWidgetItem(QString::number(m_m2k_context->getDacCalibrationGain(1)))); startParamTable->resizeColumnsToContents(); } @@ -523,13 +499,14 @@ void ManualCalibration::initParameters(void) const char *value; QTableWidgetItem *item; - tableHeader <<"Name"<<"Value"; + tableHeader << "Name" + << "Value"; paramTable->setRowCount(8); paramTable->setColumnCount(2); paramTable->setHorizontalHeaderLabels(tableHeader); - for (int i = 4; i < 12; i++) { - if (!iio_context_get_attr(ctx, i, &name, &value)) { + for(int i = 4; i < 12; i++) { + if(!iio_context_get_attr(ctx, i, &name, &value)) { item = new QTableWidgetItem(QString(name + 4)); item->setFlags(Qt::ItemIsSelectable); paramTable->setItem(i - 4, 0, item); @@ -540,62 +517,54 @@ void ManualCalibration::initParameters(void) paramTable->resizeColumnsToContents(); } -void ManualCalibration::updateParameters(void) -{ - -} +void ManualCalibration::updateParameters(void) {} -void ManualCalibration::on_loadButton_clicked() -{ - initParameters(); -} +void ManualCalibration::on_loadButton_clicked() { initParameters(); } void ManualCalibration::on_saveButton_clicked() { QString fileName; QString selectedFilter; - if (calibrationFilePath == "") { - fileName = QFileDialog::getSaveFileName(this, - tr("Save file"), "", tr("Ini files (*.ini)"), - &selectedFilter, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); + if(calibrationFilePath == "") { + fileName = QFileDialog::getSaveFileName( + this, tr("Save file"), "", tr("Ini files (*.ini)"), &selectedFilter, + (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); } else { fileName = calibrationFilePath; } QFile file(fileName); QString temp_ad9963, temp_fpga; - if (m_dmm_ad9963) { + if(m_dmm_ad9963) { temp_ad9963 = QString::number(m_dmm_ad9963->readChannel("temp0").value); } - if (m_dmm_xadc) { + if(m_dmm_xadc) { temp_fpga = QString::number(m_dmm_xadc->readChannel("temp0").value); } - if (file.open(QIODevice::WriteOnly)) { + if(file.open(QIODevice::WriteOnly)) { QTextStream stream(&file); stream << "#Calibration time: " << QDate::currentDate().toString() << ", " - << QTime::currentTime().toString() - << "\n#ad9963 temperature: " << temp_ad9963 - << tr(" °C") << "\n#FPGA temperature: "<< temp_fpga - << tr(" °C") << Qt::endl; - - for (int i = 0; i < paramTable->rowCount(); i++) - stream << "cal," << paramTable->item(i,0)->text() << "=" - << paramTable->item(i,1)->text() << Qt::endl; + << QTime::currentTime().toString() << "\n#ad9963 temperature: " << temp_ad9963 << tr(" °C") + << "\n#FPGA temperature: " << temp_fpga << tr(" °C") << Qt::endl; + + for(int i = 0; i < paramTable->rowCount(); i++) + stream << "cal," << paramTable->item(i, 0)->text() << "=" << paramTable->item(i, 1)->text() + << Qt::endl; } file.close(); - if (calibrationFilePath != "") { + if(calibrationFilePath != "") { calibrationFilePath = ""; } } void ManualCalibration::restartButton_clicked() { - switch (stCalibrationStory.calibProcedure) { + switch(stCalibrationStory.calibProcedure) { case POSITIVE_OFFSET: positivePowerSupplySetup(); break; @@ -626,17 +595,12 @@ void ManualCalibration::finishButton_clicked() setEnableNegativeSuppply(false); } - - void ManualCalibration::on_autoButton_clicked() { - if (calib->isInitialized()) { + if(calib->isInitialized()) { calib->calibrateAll(); } displayStartUpCalibrationValues(); } -void ManualCalibration::setCalibrationFilePath(QString path) -{ - calibrationFilePath = path; -} +void ManualCalibration::setCalibrationFilePath(QString path) { calibrationFilePath = path; } diff --git a/plugins/m2k/src/old/manualcalibration.h b/plugins/m2k/src/old/manualcalibration.h index b283d4b260..0bde940523 100644 --- a/plugins/m2k/src/old/manualcalibration.h +++ b/plugins/m2k/src/old/manualcalibration.h @@ -24,44 +24,48 @@ #include /*Qt includes*/ +#include #include #include -#include #include /*Local includes*/ #include "filter.hpp" +#include "m2ktool.hpp" +#include "pluginbase/toolmenuentry.h" + #include -#include + #include -#include "pluginbase/toolmenuentry.h" -#include "m2ktool.hpp" +#include class QJSEngine; namespace libm2k { namespace context { - class M2k; +class M2k; } namespace analog { - class M2kPowerSupply; -} +class M2kPowerSupply; } +} // namespace libm2k namespace Ui { class ManualCalibration; class CalibrationTemplate; -} +} // namespace Ui namespace scopy::m2k { -struct stCalibStory { +struct stCalibStory +{ int calibProcedure; int calibStep; QStringList story; QString storyName; }; -struct stCalibParam { +struct stCalibParam +{ double offset_pos_dac; double offset_neg_dac; double gain_pos_dac; @@ -73,14 +77,16 @@ struct stCalibParam { double gain_neg_adc; }; -enum calibrations { +enum calibrations +{ POSITIVE_OFFSET = 0, NEGATIVE_OFFSET, CALIB_PARAM, START_CALIB_PARAM }; -enum steps { +enum steps +{ STEP1 = 0, STEP2, STEP3, @@ -96,8 +102,8 @@ class ManualCalibration : public M2kTool Q_OBJECT public: - explicit ManualCalibration(struct iio_context *ctx, Filter *filt, - ToolMenuEntry *tme, QWidget *parent = 0, Calibration *cal = 0); + explicit ManualCalibration(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, QWidget *parent = 0, + Calibration *cal = 0); ~ManualCalibration(); @@ -157,10 +163,10 @@ private Q_SLOTS: QMap calibOption; QString calibrationFilePath; - libm2k::context::M2k* m_m2k_context; - libm2k::analog::M2kPowerSupply* m_m2k_powersupply; - libm2k::analog::DMM* m_dmm_ad9963; - libm2k::analog::DMM* m_dmm_xadc; + libm2k::context::M2k *m_m2k_context; + libm2k::analog::M2kPowerSupply *m_m2k_powersupply; + libm2k::analog::DMM *m_dmm_ad9963; + libm2k::analog::DMM *m_dmm_xadc; }; -} +} // namespace scopy::m2k #endif // MANUALCALIBRATION_H diff --git a/plugins/m2k/src/old/measure_settings.cpp b/plugins/m2k/src/old/measure_settings.cpp index 27a1106ec5..8982557d19 100644 --- a/plugins/m2k/src/old/measure_settings.cpp +++ b/plugins/m2k/src/old/measure_settings.cpp @@ -18,13 +18,15 @@ * along with this program. If not, see . */ #include "measure_settings.h" -#include "oscilloscope_plot.hpp" + #include "gui/dropdown_switch_list.h" +#include "oscilloscope_plot.hpp" + #include "ui_measure_settings.h" +#include #include #include -#include using namespace scopy; using namespace scopy::m2k; @@ -65,230 +67,190 @@ static const std::map icons_spect = { {M2kMeasure::SFDR, ":/gui/icons/measurements/frequency.svg"}, }; -MeasureSettings::MeasureSettings( QList* measures_list, QWidget *parent, bool is_time_domain) : - QWidget(parent), - m_ui(new Ui::MeasureSettings), - m_channelName(""), - m_chnUnderlineColor(), - m_horizMeasurements(nullptr), - m_vertMeasurements(nullptr), - m_is_time_domain(is_time_domain), - m_emitActivated(true), - m_emitStatsChanged(true), - m_emitStatsDeleteAll(true), - m_emitDeleteAll(true), - m_are_dropdowns_filled(false), - m_measures_list(measures_list), - m_selectedChannel(-1), - m_enableDisplayAll(false) -{ - QTreeView *treeView; - - m_ui->setupUi(this); - hide_measure_settings(m_is_time_domain); - - if(m_is_time_domain) - { - m_horizMeasurements = new DropdownSwitchList(2, this); - m_vertMeasurements = new DropdownSwitchList(2, this); - m_ui->hLayout_hMeasurements->addWidget(m_horizMeasurements); - m_ui->hLayout_vMeasurements->addWidget(m_vertMeasurements); - - m_horizMeasurements->setTitle(tr("Horizontal")); - m_horizMeasurements->setColumnTitle(0, tr("Name")); - m_horizMeasurements->setColumnTitle(1, tr("Measure")); - m_horizMeasurements->setColumnTitle(2, tr("Stats")); - m_horizMeasurements->setMaxVisibleItems(4); - treeView = static_cast(m_horizMeasurements->view()); - treeView->header()->resizeSection(0, 122); - treeView->setIconSize(QSize(30, 20)); - - connect(m_horizMeasurements->model(), - SIGNAL(itemChanged(QStandardItem*)), - SLOT(onMeasurementPropertyChanged(QStandardItem*))); - - m_vertMeasurements->setTitle(tr("Vertical")); - m_vertMeasurements->setColumnTitle(0, tr("Name")); - m_vertMeasurements->setColumnTitle(1, tr("Measure")); - m_vertMeasurements->setColumnTitle(2, tr("Stats")); - m_vertMeasurements->setMaxVisibleItems(4); - treeView = static_cast(m_vertMeasurements->view()); - treeView->header()->resizeSection(0, 122); - treeView->setIconSize(QSize(30, 20)); - - connect(m_vertMeasurements->model(), - SIGNAL(itemChanged(QStandardItem*)), - SLOT(onMeasurementPropertyChanged(QStandardItem*))); - } - else - { - m_horizMeasurements = new DropdownSwitchList(1, this); - m_vertMeasurements = new DropdownSwitchList(1, this); - - connect(m_ui->comboBox_harm, SIGNAL(currentIndexChanged(int)), - SLOT(onharmValueChanged(int))); - - m_ui->hLayout_hMeasurements->addWidget(m_horizMeasurements); - m_ui->hLayout_vMeasurements->addWidget(m_vertMeasurements); - - m_horizMeasurements->setTitle(tr("Horizontals")); - m_horizMeasurements->setColumnTitle(0, tr("Name")); - m_horizMeasurements->setColumnTitle(1, tr("Measure")); - m_horizMeasurements->setMaxVisibleItems(4); - treeView = static_cast(m_horizMeasurements->view()); - treeView->header()->resizeSection(0, 150); - treeView->setIconSize(QSize(30, 20)); - - connect(m_horizMeasurements->model(), - SIGNAL(itemChanged(QStandardItem*)), - SLOT(onMeasurementPropertyChanged(QStandardItem*))); - - m_vertMeasurements->setTitle(tr("Verticals")); - m_vertMeasurements->setColumnTitle(0, tr("Name")); - m_vertMeasurements->setColumnTitle(1, tr("Measure")); - - m_vertMeasurements->setMaxVisibleItems(4); - treeView = static_cast(m_vertMeasurements->view()); - treeView->header()->resizeSection(0, 150); - treeView->setIconSize(QSize(30, 20)); - - connect(m_vertMeasurements->model(), - SIGNAL(itemChanged(QStandardItem*)), - SLOT(onMeasurementPropertyChanged(QStandardItem*))); - } -} - -MeasureSettings::~MeasureSettings() -{ - delete m_ui; -} +MeasureSettings::MeasureSettings(QList *measures_list, QWidget *parent, bool is_time_domain) + : QWidget(parent) + , m_ui(new Ui::MeasureSettings) + , m_channelName("") + , m_chnUnderlineColor() + , m_horizMeasurements(nullptr) + , m_vertMeasurements(nullptr) + , m_is_time_domain(is_time_domain) + , m_emitActivated(true) + , m_emitStatsChanged(true) + , m_emitStatsDeleteAll(true) + , m_emitDeleteAll(true) + , m_are_dropdowns_filled(false) + , m_measures_list(measures_list) + , m_selectedChannel(-1) + , m_enableDisplayAll(false) +{ + QTreeView *treeView; + + m_ui->setupUi(this); + hide_measure_settings(m_is_time_domain); + + if(m_is_time_domain) { + m_horizMeasurements = new DropdownSwitchList(2, this); + m_vertMeasurements = new DropdownSwitchList(2, this); + m_ui->hLayout_hMeasurements->addWidget(m_horizMeasurements); + m_ui->hLayout_vMeasurements->addWidget(m_vertMeasurements); + + m_horizMeasurements->setTitle(tr("Horizontal")); + m_horizMeasurements->setColumnTitle(0, tr("Name")); + m_horizMeasurements->setColumnTitle(1, tr("Measure")); + m_horizMeasurements->setColumnTitle(2, tr("Stats")); + m_horizMeasurements->setMaxVisibleItems(4); + treeView = static_cast(m_horizMeasurements->view()); + treeView->header()->resizeSection(0, 122); + treeView->setIconSize(QSize(30, 20)); + + connect(m_horizMeasurements->model(), SIGNAL(itemChanged(QStandardItem *)), + SLOT(onMeasurementPropertyChanged(QStandardItem *))); + + m_vertMeasurements->setTitle(tr("Vertical")); + m_vertMeasurements->setColumnTitle(0, tr("Name")); + m_vertMeasurements->setColumnTitle(1, tr("Measure")); + m_vertMeasurements->setColumnTitle(2, tr("Stats")); + m_vertMeasurements->setMaxVisibleItems(4); + treeView = static_cast(m_vertMeasurements->view()); + treeView->header()->resizeSection(0, 122); + treeView->setIconSize(QSize(30, 20)); + + connect(m_vertMeasurements->model(), SIGNAL(itemChanged(QStandardItem *)), + SLOT(onMeasurementPropertyChanged(QStandardItem *))); + } else { + m_horizMeasurements = new DropdownSwitchList(1, this); + m_vertMeasurements = new DropdownSwitchList(1, this); -void MeasureSettings::onharmValueChanged(int id) -{ - M2kMeasure *measure = measureOfChannel(m_selectedChannel); - measure->setHarmonicNumber(id + 1); -} + connect(m_ui->comboBox_harm, SIGNAL(currentIndexChanged(int)), SLOT(onharmValueChanged(int))); -void MeasureSettings::hide_measure_settings(bool is_time_domain) { - if(is_time_domain) - { - m_ui->comboBox_harm->hide(); - m_ui->label_9->hide(); - m_ui->line_6->hide(); - m_ui->label_10->hide(); - } - else - { - m_ui->label_7->hide(); - m_ui->line_3->hide(); - m_ui->verticalSpacer_6->changeSize(0,0); - m_ui->verticalSpacer_7->changeSize(0,0); + m_ui->hLayout_hMeasurements->addWidget(m_horizMeasurements); + m_ui->hLayout_vMeasurements->addWidget(m_vertMeasurements); - m_ui->button_StatisticsEn->hide(); - m_ui->button_statsDeleteAll->hide(); - m_ui->button_StatisticsReset->hide(); + m_horizMeasurements->setTitle(tr("Horizontals")); + m_horizMeasurements->setColumnTitle(0, tr("Name")); + m_horizMeasurements->setColumnTitle(1, tr("Measure")); + m_horizMeasurements->setMaxVisibleItems(4); + treeView = static_cast(m_horizMeasurements->view()); + treeView->header()->resizeSection(0, 150); + treeView->setIconSize(QSize(30, 20)); - m_ui->button_GatingEnable->hide(); - m_ui->label_4->hide(); - m_ui->label_5->hide(); - m_ui->line_5->hide(); + connect(m_horizMeasurements->model(), SIGNAL(itemChanged(QStandardItem *)), + SLOT(onMeasurementPropertyChanged(QStandardItem *))); - m_ui->comboBox_harm->addItem("1"); - m_ui->comboBox_harm->addItem("2"); - m_ui->comboBox_harm->addItem("3"); - m_ui->comboBox_harm->addItem("4"); - m_ui->comboBox_harm->addItem("5"); - m_ui->comboBox_harm->addItem("6"); - m_ui->comboBox_harm->addItem("7"); - m_ui->comboBox_harm->addItem("8"); - m_ui->comboBox_harm->addItem("9"); + m_vertMeasurements->setTitle(tr("Verticals")); + m_vertMeasurements->setColumnTitle(0, tr("Name")); + m_vertMeasurements->setColumnTitle(1, tr("Measure")); - m_ui->comboBox_harm->setCurrentIndex(6); - } + m_vertMeasurements->setMaxVisibleItems(4); + treeView = static_cast(m_vertMeasurements->view()); + treeView->header()->resizeSection(0, 150); + treeView->setIconSize(QSize(30, 20)); + + connect(m_vertMeasurements->model(), SIGNAL(itemChanged(QStandardItem *)), + SLOT(onMeasurementPropertyChanged(QStandardItem *))); + } } -QString MeasureSettings::channelName() const +MeasureSettings::~MeasureSettings() { delete m_ui; } + +void MeasureSettings::onharmValueChanged(int id) { - return m_channelName; + M2kMeasure *measure = measureOfChannel(m_selectedChannel); + measure->setHarmonicNumber(id + 1); } -void MeasureSettings::setChannelName(const QString& name) +void MeasureSettings::hide_measure_settings(bool is_time_domain) { - m_channelName = name; - m_ui->lblChanName->setText(name); + if(is_time_domain) { + m_ui->comboBox_harm->hide(); + m_ui->label_9->hide(); + m_ui->line_6->hide(); + m_ui->label_10->hide(); + } else { + m_ui->label_7->hide(); + m_ui->line_3->hide(); + m_ui->verticalSpacer_6->changeSize(0, 0); + m_ui->verticalSpacer_7->changeSize(0, 0); + + m_ui->button_StatisticsEn->hide(); + m_ui->button_statsDeleteAll->hide(); + m_ui->button_StatisticsReset->hide(); + + m_ui->button_GatingEnable->hide(); + m_ui->label_4->hide(); + m_ui->label_5->hide(); + m_ui->line_5->hide(); + + m_ui->comboBox_harm->addItem("1"); + m_ui->comboBox_harm->addItem("2"); + m_ui->comboBox_harm->addItem("3"); + m_ui->comboBox_harm->addItem("4"); + m_ui->comboBox_harm->addItem("5"); + m_ui->comboBox_harm->addItem("6"); + m_ui->comboBox_harm->addItem("7"); + m_ui->comboBox_harm->addItem("8"); + m_ui->comboBox_harm->addItem("9"); + + m_ui->comboBox_harm->setCurrentIndex(6); + } } -QColor MeasureSettings::channelUnderlineColor() const +QString MeasureSettings::channelName() const { return m_channelName; } + +void MeasureSettings::setChannelName(const QString &name) { - return m_chnUnderlineColor; + m_channelName = name; + m_ui->lblChanName->setText(name); } -void MeasureSettings::setChannelUnderlineColor(const QColor& color) +QColor MeasureSettings::channelUnderlineColor() const { return m_chnUnderlineColor; } + +void MeasureSettings::setChannelUnderlineColor(const QColor &color) { m_chnUnderlineColor = color; - QString stylesheet = QString("border: 2px solid %1;" - ).arg(color.name()); + QString stylesheet = QString("border: 2px solid %1;").arg(color.name()); m_ui->line->setStyleSheet(stylesheet); } -bool MeasureSettings::emitActivated() const -{ - return m_emitActivated; -} -void MeasureSettings::setEmitActivated(bool en) -{ - m_emitActivated = en; -} +bool MeasureSettings::emitActivated() const { return m_emitActivated; } +void MeasureSettings::setEmitActivated(bool en) { m_emitActivated = en; } -bool MeasureSettings::emitStatsChanged()const -{ - return m_emitStatsChanged; -} -void MeasureSettings::setEmitStatsChanged(bool en) -{ - m_emitStatsChanged = en; -} +bool MeasureSettings::emitStatsChanged() const { return m_emitStatsChanged; } +void MeasureSettings::setEmitStatsChanged(bool en) { m_emitStatsChanged = en; } -QList MeasureSettings::measurementSelection() -{ - return m_selectedMeasurements; -} +QList MeasureSettings::measurementSelection() { return m_selectedMeasurements; } void MeasureSettings::onMeasurementPropertyChanged(QStandardItem *item) { - QAbstractItemModel *model = static_cast - (QObject::sender()); - DropdownSwitchList *dropdown = static_cast - (model->parent()); + QAbstractItemModel *model = static_cast(QObject::sender()); + DropdownSwitchList *dropdown = static_cast(model->parent()); bool en = item->data(Qt::EditRole).toBool(); QStandardItem *nameItem = item->model()->item(item->row(), 0); int id = nameItem->data(Qt::UserRole).toInt(); - if (item->column() == 1) { - if (m_emitActivated) + if(item->column() == 1) { + if(m_emitActivated) onMeasurementActivated(m_selectedChannel, id, en); - } else if (item->column() == 2) { - if (m_emitStatsChanged) + } else if(item->column() == 2) { + if(m_emitStatsChanged) onStatisticActivated(dropdown, id, en); } // Switch from Recover to Delete All if a measurement state gets changed - if (item->column() == 1 && m_emitActivated && - m_ui->button_measDeleteAll->isChecked()) { + if(item->column() == 1 && m_emitActivated && m_ui->button_measDeleteAll->isChecked()) { m_emitDeleteAll = false; m_ui->button_measDeleteAll->setChecked(false); } // Disable Display All if a measurement state gets changed - if (item->column() == 1 &&m_emitActivated && - m_ui->button_measDisplayAll->isChecked()) { + if(item->column() == 1 && m_emitActivated && m_ui->button_measDisplayAll->isChecked()) { m_ui->button_measDisplayAll->setChecked(false); } // Switch from Recover to Delete All if a statistic state gets changed - if (item->column() == 2 && m_emitStatsChanged && - m_ui->button_statsDeleteAll->isChecked()) { + if(item->column() == 2 && m_emitStatsChanged && m_ui->button_statsDeleteAll->isChecked()) { m_emitStatsDeleteAll = false; m_ui->button_statsDeleteAll->setChecked(false); } @@ -298,7 +260,7 @@ void MeasureSettings::on_button_measDisplayAll_toggled(bool checked) { m_ui->button_measDeleteAll->setEnabled(!checked); - if (checked) + if(checked) displayAllMeasurements(); else disableDisplayAllMeasurements(); @@ -306,84 +268,77 @@ void MeasureSettings::on_button_measDisplayAll_toggled(bool checked) void MeasureSettings::on_button_measDeleteAll_toggled(bool checked) { - QPushButton *button = static_cast(QObject::sender()); - if (checked) + QPushButton *button = static_cast(QObject::sender()); + if(checked) button->setText(tr("Recover")); else button->setText(tr("Delete All")); - if (!m_emitDeleteAll) { + if(!m_emitDeleteAll) { m_emitDeleteAll = true; } else { - if (checked) + if(checked) deleteAllMeasurements(); else recoverAllMeasurements(); } } -M2kMeasure* MeasureSettings::measureOfChannel(int chnIdx) const +M2kMeasure *MeasureSettings::measureOfChannel(int chnIdx) const { - M2kMeasure *measure = nullptr; + M2kMeasure *measure = nullptr; - auto it = std::find_if(m_measures_list->begin(), m_measures_list->end(), - [&](M2kMeasure *m) { return m->channel() == chnIdx; }); - if (it != m_measures_list->end()) - measure = *it; + auto it = std::find_if(m_measures_list->begin(), m_measures_list->end(), + [&](M2kMeasure *m) { return m->channel() == chnIdx; }); + if(it != m_measures_list->end()) + measure = *it; - return measure; + return measure; } void MeasureSettings::onChannelAdded(int chnIdx) { - // Use the measurements of the 1st channel to construct the dropdowns. - // All channels have the same set of measurements. - if (m_are_dropdowns_filled) - return; + // Use the measurements of the 1st channel to construct the dropdowns. + // All channels have the same set of measurements. + if(m_are_dropdowns_filled) + return; - M2kMeasure *measure = measureOfChannel(chnIdx); + M2kMeasure *measure = measureOfChannel(chnIdx); auto measurements = QList>(); - if (measure) - measurements = measure->measurments(); - int h = 0; - int v = 0; - - if(m_is_time_domain) - { - for (int i = 0; i < measurements.size(); i++) { + if(measure) + measurements = measure->measurments(); + int h = 0; + int v = 0; + + if(m_is_time_domain) { + for(int i = 0; i < measurements.size(); i++) { enum M2kMeasurementData::axisType axis = measurements[i]->axis(); - - if (axis == M2kMeasurementData::HORIZONTAL) { - m_horizMeasurements->addDropdownElement( - QIcon(icons_lut.at(i)), - measurements[i]->name(), QVariant(i)); - m_measurePosInDropdowns.append(h++); - } else if (axis == M2kMeasurementData::VERTICAL) { - m_vertMeasurements->addDropdownElement( - QIcon(icons_lut.at(i)), - measurements[i]->name(), QVariant(i)); - m_measurePosInDropdowns.append(v++); - } - } - } - else - { - for (int i = 0; i < measurements.size(); i++) { - enum M2kMeasurementData::axisType axis = measurements[i]->axis(); - - if (axis == M2kMeasurementData::HORIZONTAL_F) { - m_horizMeasurements->addDropdownElement( - QIcon(icons_spect.at(i)), - measurements[i]->name(), QVariant(i)); - } else if (axis == M2kMeasurementData::VERTICAL_F) { - m_vertMeasurements->addDropdownElement( - QIcon(icons_spect.at(i)), - measurements[i]->name(), QVariant(i)); - } + + if(axis == M2kMeasurementData::HORIZONTAL) { + m_horizMeasurements->addDropdownElement(QIcon(icons_lut.at(i)), measurements[i]->name(), + QVariant(i)); + m_measurePosInDropdowns.append(h++); + } else if(axis == M2kMeasurementData::VERTICAL) { + m_vertMeasurements->addDropdownElement(QIcon(icons_lut.at(i)), measurements[i]->name(), + QVariant(i)); + m_measurePosInDropdowns.append(v++); + } + } + } else { + for(int i = 0; i < measurements.size(); i++) { + enum M2kMeasurementData::axisType axis = measurements[i]->axis(); + + if(axis == M2kMeasurementData::HORIZONTAL_F) { + m_horizMeasurements->addDropdownElement(QIcon(icons_spect.at(i)), + measurements[i]->name(), QVariant(i)); + } else if(axis == M2kMeasurementData::VERTICAL_F) { + m_vertMeasurements->addDropdownElement(QIcon(icons_spect.at(i)), + measurements[i]->name(), QVariant(i)); + } + } } - } - m_are_dropdowns_filled = true; + m_are_dropdowns_filled = true; } void MeasureSettings::onChannelRemoved(int chnIdx) @@ -403,11 +358,11 @@ void MeasureSettings::onChannelRemoved(int chnIdx) void MeasureSettings::setSelectedChannel(int chnIdx) { - if (m_selectedChannel != chnIdx) { + if(m_selectedChannel != chnIdx) { m_selectedChannel = chnIdx; loadMeasurementStatesFromData(); loadStatisticStatesForChannel(chnIdx); - if (m_ui->button_measDisplayAll->isChecked()){ + if(m_ui->button_measDisplayAll->isChecked()) { disableDisplayAllMeasurements(); displayAllMeasurements(); } @@ -418,51 +373,42 @@ void MeasureSettings::loadMeasurementStatesFromData() { M2kMeasure *measure = measureOfChannel(m_selectedChannel); auto measurements = QList>(); - if (measure) + if(measure) measurements = measure->measurments(); - int h_idx = 0; - int v_idx = 0; - - QStandardItemModel *horiz_model = - static_cast(m_horizMeasurements->model()); - QStandardItemModel *vert_model = - static_cast(m_vertMeasurements->model()); - - setEmitActivated(false); - - if(m_is_time_domain) - { - for (int i = 0; i < measurements.size(); i++) { - int axis = measurements[i]->axis(); - int state = measurements[i]->enabled(); - - if (axis == M2kMeasurementData::HORIZONTAL) { - horiz_model->item(h_idx++, 1)->setData( - QVariant((int) state), Qt::EditRole); - } else if (axis == M2kMeasurementData::VERTICAL) { - vert_model->item(v_idx++, 1)->setData( - QVariant((int) state), Qt::EditRole); - } + int h_idx = 0; + int v_idx = 0; + + QStandardItemModel *horiz_model = static_cast(m_horizMeasurements->model()); + QStandardItemModel *vert_model = static_cast(m_vertMeasurements->model()); + + setEmitActivated(false); + + if(m_is_time_domain) { + for(int i = 0; i < measurements.size(); i++) { + int axis = measurements[i]->axis(); + int state = measurements[i]->enabled(); + + if(axis == M2kMeasurementData::HORIZONTAL) { + horiz_model->item(h_idx++, 1)->setData(QVariant((int)state), Qt::EditRole); + } else if(axis == M2kMeasurementData::VERTICAL) { + vert_model->item(v_idx++, 1)->setData(QVariant((int)state), Qt::EditRole); + } } - } - else - { - for (int i = 0; i < measurements.size(); i++) { + } else { + for(int i = 0; i < measurements.size(); i++) { enum M2kMeasurementData::axisType axis = measurements[i]->axis(); - int state = measurements[i]->enabled(); - - if (axis == M2kMeasurementData::HORIZONTAL_F) { - horiz_model->item(h_idx++, 1)->setData( - QVariant((int) state), Qt::EditRole); - } else if (axis == M2kMeasurementData::VERTICAL_F) { - vert_model->item(v_idx++, 1)->setData( - QVariant((int) state), Qt::EditRole); - } + int state = measurements[i]->enabled(); + + if(axis == M2kMeasurementData::HORIZONTAL_F) { + horiz_model->item(h_idx++, 1)->setData(QVariant((int)state), Qt::EditRole); + } else if(axis == M2kMeasurementData::VERTICAL_F) { + vert_model->item(v_idx++, 1)->setData(QVariant((int)state), Qt::EditRole); + } } - } + } - setEmitActivated(true); + setEmitActivated(true); } void MeasureSettings::deleteAllMeasurements() @@ -488,10 +434,10 @@ void MeasureSettings::displayAllMeasurements() M2kMeasure *measure = measureOfChannel(m_selectedChannel); auto measurements = QList>(); - if (measure) + if(measure) measurements = measure->measurments(); - for (int i = 0; i < measurements.size(); i++) { + for(int i = 0; i < measurements.size(); i++) { MeasurementItem item(i, measurements[i]->channel()); m_selectedMeasurements.push_back(MeasurementItem(item)); } @@ -508,16 +454,16 @@ void MeasureSettings::disableDisplayAllMeasurements() void MeasureSettings::onMeasurementActivated(int chnIdx, int id, bool en) { - if (chnIdx < 0) + if(chnIdx < 0) return; M2kMeasure *measure = measureOfChannel(chnIdx); auto measurements = QList>(); - if (measure) + if(measure) measurements = measure->measurments(); MeasurementItem mItem(id, measurements[id]->channel()); - if (en) { + if(en) { m_selectedMeasurements.push_back(mItem); Q_EMIT measurementActivated(mItem.id(), mItem.channel_id()); } else { @@ -526,13 +472,12 @@ void MeasureSettings::onMeasurementActivated(int chnIdx, int id, bool en) } } -void MeasureSettings::onStatisticActivated(DropdownSwitchList *dropdown, - int id, bool en) +void MeasureSettings::onStatisticActivated(DropdownSwitchList *dropdown, int id, bool en) { - if (m_selectedChannel < 0) + if(m_selectedChannel < 0) return; - if (en) { + if(en) { addStatistic(id, m_selectedChannel); Q_EMIT statisticActivated(id, m_selectedChannel); } else { @@ -544,7 +489,7 @@ void MeasureSettings::onStatisticActivated(DropdownSwitchList *dropdown, void MeasureSettings::loadStatisticStatesForChannel(int chnIdx) { // makes sense only for the oscilloscope - if (m_is_time_domain) { + if(m_is_time_domain) { const int stats_col = 2; setEmitStatsChanged(false); @@ -553,39 +498,30 @@ void MeasureSettings::loadStatisticStatesForChannel(int chnIdx) setAllMeasurements(stats_col, false); // Restore selections that are present in the selected statistics list - for (int i = 0; i < m_selectedStatistics.size(); i++) { - if (m_selectedStatistics[i].measurementItem.channel_id() != - chnIdx) { + for(int i = 0; i < m_selectedStatistics.size(); i++) { + if(m_selectedStatistics[i].measurementItem.channel_id() != chnIdx) { continue; } - QStandardItemModel *model = static_cast - (m_selectedStatistics[i].dropdown->model()); + QStandardItemModel *model = + static_cast(m_selectedStatistics[i].dropdown->model()); int measId = m_selectedStatistics[i].measurementItem.id(); - model->item(m_measurePosInDropdowns[measId], stats_col)-> - setData(QVariant(1), Qt::EditRole); + model->item(m_measurePosInDropdowns[measId], stats_col)->setData(QVariant(1), Qt::EditRole); } setEmitStatsChanged(true); } } -void MeasureSettings::on_button_StatisticsEn_toggled(bool checked) -{ - Q_EMIT statisticsEnabled(checked); -} +void MeasureSettings::on_button_StatisticsEn_toggled(bool checked) { Q_EMIT statisticsEnabled(checked); } -void MeasureSettings::on_button_StatisticsReset_pressed() -{ - Q_EMIT statisticsReset(); -} +void MeasureSettings::on_button_StatisticsReset_pressed() { Q_EMIT statisticsReset(); } -void MeasureSettings::setColumnData(QStandardItemModel *model, int column, - bool en) +void MeasureSettings::setColumnData(QStandardItemModel *model, int column, bool en) { int val = en ? 1 : 0; - for (int i = 0; i < model->rowCount(); i++) + for(int i = 0; i < model->rowCount(); i++) model->item(i, column)->setData(QVariant(val), Qt::EditRole); } @@ -600,29 +536,26 @@ void MeasureSettings::setAllMeasurements(int col, bool en) setColumnData(model, col, en); } -void MeasureSettings::deleteMeasurementsOfChannel(QList& list, - int chnIdx) +void MeasureSettings::deleteMeasurementsOfChannel(QList &list, int chnIdx) { QMutableListIterator i(list); - while (i.hasNext()) { + while(i.hasNext()) { i.next(); - if (i.value().channel_id() == chnIdx) + if(i.value().channel_id() == chnIdx) i.remove(); } } -void MeasureSettings::updateMeasurementsOnChannelDel(QList& list, - int chnIdx) +void MeasureSettings::updateMeasurementsOnChannelDel(QList &list, int chnIdx) { int listSize = list.size(); int idx = 0; int currentItemIdx = 0; - while (idx < listSize) { + while(idx < listSize) { auto item = m_selectedMeasurements.at(currentItemIdx); - if (item.channel_id() > chnIdx) { + if(item.channel_id() > chnIdx) { Q_EMIT measurementDeactivated(item.id(), item.channel_id()); - m_selectedMeasurements.push_back(MeasurementItem(item.id(), - item.channel_id() - 1)); + m_selectedMeasurements.push_back(MeasurementItem(item.id(), item.channel_id() - 1)); Q_EMIT measurementActivated(item.id(), item.channel_id() - 1); m_selectedMeasurements.removeAt(currentItemIdx); } else { @@ -632,13 +565,12 @@ void MeasureSettings::updateMeasurementsOnChannelDel(QList& lis } } -void MeasureSettings::deleteStatisticsOfChannel( - QList& list, int chnIdx) +void MeasureSettings::deleteStatisticsOfChannel(QList &list, int chnIdx) { QMutableListIterator i(list); - while (i.hasNext()) { + while(i.hasNext()) { i.next(); - if (i.value().measurementItem.channel_id() == chnIdx) + if(i.value().measurementItem.channel_id() == chnIdx) i.remove(); } } @@ -647,38 +579,35 @@ QList MeasureSettings::statisticSelection() { QList statistics; - for (int i = 0; i < m_selectedStatistics.size(); i++) + for(int i = 0; i < m_selectedStatistics.size(); i++) statistics.push_back(m_selectedStatistics[i].measurementItem); return statistics; - } void MeasureSettings::on_button_statsDeleteAll_toggled(bool checked) { - QPushButton *button = static_cast(QObject::sender()); - if (checked) + QPushButton *button = static_cast(QObject::sender()); + if(checked) button->setText(tr("Recover")); else button->setText(tr("Delete All")); - if (!m_emitStatsDeleteAll) { + if(!m_emitStatsDeleteAll) { m_emitStatsDeleteAll = true; } else { - if (checked) + if(checked) deleteAllStatistics(); else recoverAllStatistics(); } } -void MeasureSettings::on_button_GatingEnable_toggled(bool checked){ - Q_EMIT gatingEnabled(checked); -} +void MeasureSettings::on_button_GatingEnable_toggled(bool checked) { Q_EMIT gatingEnabled(checked); } void MeasureSettings::disableDisplayAll() { - if (m_ui->button_measDisplayAll->isChecked()){ + if(m_ui->button_measDisplayAll->isChecked()) { m_ui->button_measDisplayAll->setChecked(false); m_enableDisplayAll = true; } else { @@ -686,9 +615,7 @@ void MeasureSettings::disableDisplayAll() } } -void MeasureSettings::activateDisplayAll(){ - m_ui->button_measDisplayAll->setChecked(m_enableDisplayAll); -} +void MeasureSettings::activateDisplayAll() { m_ui->button_measDisplayAll->setChecked(m_enableDisplayAll); } void MeasureSettings::deleteAllStatistics() { @@ -712,15 +639,15 @@ void MeasureSettings::addStatistic(int measure_id, int ch_id) { M2kMeasure *measure = measureOfChannel(ch_id); auto measurements = QList>(); - if (measure) - measurements = measure->measurments(); - + if(measure) + measurements = measure->measurments(); + M2kMeasurementData::axisType axis = measurements[measure_id]->axis(); struct StatisticSelection selection; - - if (axis == M2kMeasurementData::HORIZONTAL) + + if(axis == M2kMeasurementData::HORIZONTAL) selection.dropdown = m_horizMeasurements; - else if (axis == M2kMeasurementData::VERTICAL) + else if(axis == M2kMeasurementData::VERTICAL) selection.dropdown = m_vertMeasurements; else return; @@ -733,13 +660,11 @@ void MeasureSettings::removeStatistic(int measure_id, int ch_id) { MeasurementItem item(measure_id, ch_id); - auto it = std::find_if(m_selectedStatistics.begin(), - m_selectedStatistics.end(), - [&](struct StatisticSelection s) { - return s.measurementItem.id() == measure_id && - s.measurementItem.channel_id() == ch_id; - }); - if (it != m_selectedStatistics.end()) { - m_selectedStatistics.erase(it); - } + auto it = std::find_if( + m_selectedStatistics.begin(), m_selectedStatistics.end(), [&](struct StatisticSelection s) { + return s.measurementItem.id() == measure_id && s.measurementItem.channel_id() == ch_id; + }); + if(it != m_selectedStatistics.end()) { + m_selectedStatistics.erase(it); + } } diff --git a/plugins/m2k/src/old/measure_settings.h b/plugins/m2k/src/old/measure_settings.h index 44f58d5a24..1cdc244823 100644 --- a/plugins/m2k/src/old/measure_settings.h +++ b/plugins/m2k/src/old/measure_settings.h @@ -20,54 +20,52 @@ #ifndef MEASURE_SETTINGS_H #define MEASURE_SETTINGS_H +#include "m2kmeasure.h" + #include + #include -#include "m2kmeasure.h" namespace Ui { - class MeasureSettings; +class MeasureSettings; } class QStandardItem; class QStandardItemModel; - namespace scopy { class CapturePlot; class DropdownSwitchList; class M2kMeasurementData; -} +} // namespace scopy namespace scopy::m2k { class MeasurementItem { public: - MeasurementItem(int id = 0, int chn_id = 0): - m_id(id), - m_chn_id(chn_id) + MeasurementItem(int id = 0, int chn_id = 0) + : m_id(id) + , m_chn_id(chn_id) {} int id() { return m_id; } int channel_id() { return m_chn_id; } - bool operator ==(const MeasurementItem& other) const + bool operator==(const MeasurementItem &other) const { - bool isEqual = (this->m_id == other.m_id) && - (this->m_chn_id == other.m_chn_id); + bool isEqual = (this->m_id == other.m_id) && (this->m_chn_id == other.m_chn_id); return isEqual; } - bool operator !=(const MeasurementItem& other) const - { - return !(*this == other); - } + bool operator!=(const MeasurementItem &other) const { return !(*this == other); } private: int m_id; int m_chn_id; }; -struct StatisticSelection { +struct StatisticSelection +{ DropdownSwitchList *dropdown; MeasurementItem measurementItem; }; @@ -80,14 +78,14 @@ class MeasureSettings : public QWidget Q_OBJECT public: - explicit MeasureSettings(QList* measures_list, QWidget *parent = 0, bool is_time_domain = true); + explicit MeasureSettings(QList *measures_list, QWidget *parent = 0, bool is_time_domain = true); ~MeasureSettings(); QString channelName() const; - void setChannelName(const QString& name); + void setChannelName(const QString &name); QColor channelUnderlineColor() const; - void setChannelUnderlineColor(const QColor& color); + void setChannelUnderlineColor(const QColor &color); void setHorizMeasurementActive(int idx, bool en); void setVertMeasurementActive(int idx, bool en); @@ -95,7 +93,7 @@ class MeasureSettings : public QWidget bool emitActivated() const; void setEmitActivated(bool en); - bool emitStatsChanged()const; + bool emitStatsChanged() const; void setEmitStatsChanged(bool en); void disableDisplayAll(); @@ -128,8 +126,7 @@ private Q_SLOTS: void onMeasurementPropertyChanged(QStandardItem *item); void on_button_measDisplayAll_toggled(bool checked); void on_button_measDeleteAll_toggled(bool checked); - void onStatisticActivated(DropdownSwitchList *dropdown, int id, - bool en); + void onStatisticActivated(DropdownSwitchList *dropdown, int id, bool en); void on_button_StatisticsEn_toggled(bool checked); void on_button_StatisticsReset_pressed(); void on_button_statsDeleteAll_toggled(bool checked); @@ -138,19 +135,16 @@ private Q_SLOTS: private: void hide_measure_settings(bool is_time_domain); void deleteAllMeasurements(); - M2kMeasure* measureOfChannel(int chnIdx) const; + M2kMeasure *measureOfChannel(int chnIdx) const; void recoverAllMeasurements(); void displayAllMeasurements(); void disableDisplayAllMeasurements(); void loadStatisticStatesForChannel(int chnIdx); void setColumnData(QStandardItemModel *model, int column, bool en); void setAllMeasurements(int col, bool en); - void deleteMeasurementsOfChannel(QList& list, - int chnIdx); - void updateMeasurementsOnChannelDel(QList& list, - int chnIdx); - void deleteStatisticsOfChannel(QList& - list, int chnIdx); + void deleteMeasurementsOfChannel(QList &list, int chnIdx); + void updateMeasurementsOnChannelDel(QList &list, int chnIdx); + void deleteStatisticsOfChannel(QList &list, int chnIdx); void deleteAllStatistics(); void recoverAllStatistics(); void addStatistic(int measure_id, int ch_id); @@ -170,7 +164,7 @@ private Q_SLOTS: bool m_enableDisplayAll; bool m_is_time_domain; - QList* m_measures_list; + QList *m_measures_list; int m_selectedChannel; QList m_selectedMeasurements; @@ -181,6 +175,6 @@ private Q_SLOTS: QList m_selectedStatistics; QList m_statsDeleteAllBackup; }; -} // namespace scopy +} // namespace scopy::m2k #endif // MEASURE_SETTINGS_H diff --git a/plugins/m2k/src/old/mixed_signal_sink.h b/plugins/m2k/src/old/mixed_signal_sink.h index f90c4ca310..5c39a3138b 100644 --- a/plugins/m2k/src/old/mixed_signal_sink.h +++ b/plugins/m2k/src/old/mixed_signal_sink.h @@ -21,19 +21,18 @@ #ifndef MIXED_SIGNAL_SINK_H #define MIXED_SIGNAL_SINK_H -#include - -#include "logicanalyzer/logic_analyzer.h" #include "TimeDomainDisplayPlot.h" +#include "logicanalyzer/logic_analyzer.h" + +#include class mixed_signal_sink : virtual public gr::sync_block { public: typedef std::shared_ptr sptr; - static sptr make(scopy::m2k::logic::LogicAnalyzer *logicAnalyzer, - scopy::TimeDomainDisplayPlot *oscPlot, - int bufferSize); + static sptr make(scopy::m2k::logic::LogicAnalyzer *logicAnalyzer, scopy::TimeDomainDisplayPlot *oscPlot, + int bufferSize); virtual void clean_buffers() = 0; virtual void set_nsamps(int newsize) = 0; diff --git a/plugins/m2k/src/old/mixed_signal_sink_impl.cpp b/plugins/m2k/src/old/mixed_signal_sink_impl.cpp index 0b0d0a60c5..1218da3887 100644 --- a/plugins/m2k/src/old/mixed_signal_sink_impl.cpp +++ b/plugins/m2k/src/old/mixed_signal_sink_impl.cpp @@ -20,23 +20,20 @@ #include "mixed_signal_sink_impl.h" -#include #include -using namespace gr; +#include +using namespace gr; mixed_signal_sink::sptr mixed_signal_sink::make(scopy::m2k::logic::LogicAnalyzer *logicAnalyzer, - scopy::TimeDomainDisplayPlot *oscPlot, - int bufferSize) + scopy::TimeDomainDisplayPlot *oscPlot, int bufferSize) { - return gnuradio::get_initial_sptr( - new mixed_signal_sink_impl(logicAnalyzer, oscPlot, bufferSize)); + return gnuradio::get_initial_sptr(new mixed_signal_sink_impl(logicAnalyzer, oscPlot, bufferSize)); } mixed_signal_sink_impl::mixed_signal_sink_impl(scopy::m2k::logic::LogicAnalyzer *logicAnalyzer, - scopy::TimeDomainDisplayPlot *oscPlot, - int bufferSize) + scopy::TimeDomainDisplayPlot *oscPlot, int bufferSize) : sync_block("mixed_signal_sink", io_signature::make3(3, 3, sizeof(float), sizeof(float), sizeof(unsigned short)), io_signature::make(0, 0, 0)) @@ -46,7 +43,7 @@ mixed_signal_sink_impl::mixed_signal_sink_impl(scopy::m2k::logic::LogicAnalyzer , d_buffer_size(2 * bufferSize) , d_index(0) , d_end(d_size) - , d_tags(std::vector< std::vector >(3)) + , d_tags(std::vector>(3)) , d_trigger_tag_key(pmt::intern("buffer_start")) , d_triggered(false) , d_update_time(0.1 * gr::high_res_timer_tps()) @@ -54,29 +51,28 @@ mixed_signal_sink_impl::mixed_signal_sink_impl(scopy::m2k::logic::LogicAnalyzer , d_display_one_buffer(true) , d_cleanBuffers(true) { - d_digital_buffer = static_cast(volk_malloc(d_buffer_size * sizeof(uint16_t), volk_get_alignment())); + d_digital_buffer = static_cast(volk_malloc(d_buffer_size * sizeof(uint16_t), volk_get_alignment())); memset(d_digital_buffer, 0, d_buffer_size * sizeof(uint16_t)); - for (int i = 0; i < 2; ++i) { + for(int i = 0; i < 2; ++i) { d_analog_buffer.push_back( - static_cast(volk_malloc(d_buffer_size * sizeof(float), volk_get_alignment()))); + static_cast(volk_malloc(d_buffer_size * sizeof(float), volk_get_alignment()))); memset(d_analog_buffer[i], 0, d_buffer_size * sizeof(float)); d_analog_plot_buffers.push_back( - static_cast(volk_malloc(d_buffer_size * sizeof(double), volk_get_alignment()))); + static_cast(volk_malloc(d_buffer_size * sizeof(double), volk_get_alignment()))); memset(d_analog_plot_buffers[i], 0, d_buffer_size * sizeof(double)); } - set_update_time(1/60.0); + set_update_time(1 / 60.0); } -int mixed_signal_sink_impl::work(int noutput_items, - gr_vector_const_void_star &input_items, +int mixed_signal_sink_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock lock(d_setlock); - if (!d_display_one_buffer && !d_cleanBuffers) { + if(!d_display_one_buffer && !d_cleanBuffers) { return 0; } @@ -86,12 +82,12 @@ int mixed_signal_sink_impl::work(int noutput_items, const int nitems = std::min(noutput_items, nfill); // look for trigger tag - if (!d_triggered) { + if(!d_triggered) { _test_trigger_tags(nitems); } - for (int i = 0; i < 2; ++i) { - const float *in = static_cast(input_items[i]); + for(int i = 0; i < 2; ++i) { + const float *in = static_cast(input_items[i]); memcpy(&d_analog_buffer[i][d_index], in, sizeof(float) * nitems); } @@ -100,42 +96,38 @@ int mixed_signal_sink_impl::work(int noutput_items, d_index += nitems; - if ((d_end != 0 && !d_display_one_buffer) || - (d_triggered && (d_index == d_end) && d_end != 0 && d_display_one_buffer)) { + if((d_end != 0 && !d_display_one_buffer) || + (d_triggered && (d_index == d_end) && d_end != 0 && d_display_one_buffer)) { int nitemsToSend = d_size; - if (!d_display_one_buffer) { + if(!d_display_one_buffer) { nitemsToSend = d_index; - if (nitemsToSend >= d_size) { + if(nitemsToSend >= d_size) { nitemsToSend = d_size; d_cleanBuffers = false; } } - for (int i = 0; i < 2; ++i) { + for(int i = 0; i < 2; ++i) { volk_32f_convert_64f(d_analog_plot_buffers[i], &d_analog_buffer[i][d_start], nitemsToSend); } - if (gr::high_res_timer_now() - d_last_time > d_update_time - || !d_cleanBuffers) { + if(gr::high_res_timer_now() - d_last_time > d_update_time || !d_cleanBuffers) { d_last_time = gr::high_res_timer_now(); d_logic_analyzer->setData(d_digital_buffer + d_start, nitemsToSend); qApp->postEvent(d_osc_plot, - new IdentifiableTimeUpdateEvent(d_analog_plot_buffers, - nitemsToSend, - d_tags, + new IdentifiableTimeUpdateEvent(d_analog_plot_buffers, nitemsToSend, d_tags, "Osc Time")); } - if (d_display_one_buffer) { + if(d_display_one_buffer) { _reset(); } } - - if (d_index == d_end && d_display_one_buffer) { + if(d_index == d_end && d_display_one_buffer) { _reset(); } @@ -148,7 +140,7 @@ void mixed_signal_sink_impl::clean_buffers() memset(d_digital_buffer, 0, d_buffer_size * sizeof(uint16_t)); - for (int i = 0; i < 2; ++i) { + for(int i = 0; i < 2; ++i) { memset(d_analog_buffer[i], 0, d_buffer_size * sizeof(float)); memset(d_analog_plot_buffers[i], 0, d_buffer_size * sizeof(double)); } @@ -159,7 +151,7 @@ void mixed_signal_sink_impl::clean_buffers() void mixed_signal_sink_impl::set_nsamps(int newsize) { - if (newsize != d_size) { + if(newsize != d_size) { gr::thread::scoped_lock lock(d_setlock); // set new size @@ -168,24 +160,24 @@ void mixed_signal_sink_impl::set_nsamps(int newsize) // free old buffers volk_free(d_digital_buffer); - for (int i = 0; i < 2; ++i) { + for(int i = 0; i < 2; ++i) { volk_free(d_analog_buffer[i]); volk_free(d_analog_plot_buffers[i]); - } d_analog_buffer.clear(); d_analog_plot_buffers.clear(); // create new buffers - d_digital_buffer = static_cast(volk_malloc(d_buffer_size * sizeof(uint16_t), volk_get_alignment())); + d_digital_buffer = + static_cast(volk_malloc(d_buffer_size * sizeof(uint16_t), volk_get_alignment())); memset(d_digital_buffer, 0, d_buffer_size * sizeof(uint16_t)); - for (int i = 0; i < 2; ++i) { + for(int i = 0; i < 2; ++i) { d_analog_buffer.push_back( - static_cast(volk_malloc(d_buffer_size * sizeof(float), volk_get_alignment()))); + static_cast(volk_malloc(d_buffer_size * sizeof(float), volk_get_alignment()))); memset(d_analog_buffer[i], 0, d_buffer_size * sizeof(float)); - d_analog_plot_buffers.push_back( - static_cast(volk_malloc(d_buffer_size * sizeof(double), volk_get_alignment()))); + d_analog_plot_buffers.push_back(static_cast( + volk_malloc(d_buffer_size * sizeof(double), volk_get_alignment()))); memset(d_analog_plot_buffers[i], 0, d_buffer_size * sizeof(double)); } @@ -195,15 +187,15 @@ void mixed_signal_sink_impl::set_nsamps(int newsize) void mixed_signal_sink_impl::set_update_time(double t) { - //convert update time to ticks - gr::high_res_timer_type tps = gr::high_res_timer_tps(); - d_update_time = t * tps; - d_last_time = 0; + // convert update time to ticks + gr::high_res_timer_type tps = gr::high_res_timer_tps(); + d_update_time = t * tps; + d_last_time = 0; } void mixed_signal_sink_impl::set_displayOneBuffer(bool display) { - if (d_display_one_buffer != display) { + if(d_display_one_buffer != display) { gr::thread::scoped_lock lock(d_setlock); d_display_one_buffer = display; @@ -212,8 +204,8 @@ void mixed_signal_sink_impl::set_displayOneBuffer(bool display) void mixed_signal_sink_impl::_adjust_tags(int adj) { - for (size_t n = 0; n < d_tags.size(); ++n) { - for (size_t t = 0; t < d_tags[n].size(); ++t) { + for(size_t n = 0; n < d_tags.size(); ++n) { + for(size_t t = 0; t < d_tags[n].size(); ++t) { d_tags[n][t].offset += adj; } } @@ -226,7 +218,7 @@ void mixed_signal_sink_impl::_test_trigger_tags(int nitems) uint64_t nr = nitems_read(0); std::vector tags; get_tags_in_range(tags, 0, nr, nr + nitems + 1, d_trigger_tag_key); - if (tags.size() > 0) { + if(tags.size() > 0) { d_triggered = true; trigger_index = tags[0].offset - nr; d_start = d_index + trigger_index; @@ -237,7 +229,7 @@ void mixed_signal_sink_impl::_test_trigger_tags(int nitems) void mixed_signal_sink_impl::_reset() { - for (size_t i = 0; i < d_tags.size(); ++i) { + for(size_t i = 0; i < d_tags.size(); ++i) { d_tags[i].clear(); } diff --git a/plugins/m2k/src/old/mixed_signal_sink_impl.h b/plugins/m2k/src/old/mixed_signal_sink_impl.h index a56309c520..bb0c4e25cb 100644 --- a/plugins/m2k/src/old/mixed_signal_sink_impl.h +++ b/plugins/m2k/src/old/mixed_signal_sink_impl.h @@ -26,13 +26,10 @@ class mixed_signal_sink_impl : public mixed_signal_sink { public: - mixed_signal_sink_impl(scopy::m2k::logic::LogicAnalyzer *logicAnalyzer, - scopy::TimeDomainDisplayPlot *oscPlot, + mixed_signal_sink_impl(scopy::m2k::logic::LogicAnalyzer *logicAnalyzer, scopy::TimeDomainDisplayPlot *oscPlot, int bufferSize); - int work(int noutput_items, - gr_vector_const_void_star &input_items, - gr_vector_void_star &output_items) override; + int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) override; void clean_buffers() override; void set_nsamps(int newsize) override; void set_displayOneBuffer(bool display) override; @@ -47,8 +44,8 @@ class mixed_signal_sink_impl : public mixed_signal_sink scopy::m2k::logic::LogicAnalyzer *d_logic_analyzer; scopy::TimeDomainDisplayPlot *d_osc_plot; - std::vector d_analog_buffer; - std::vector d_analog_plot_buffers; + std::vector d_analog_buffer; + std::vector d_analog_plot_buffers; uint16_t *d_digital_buffer; int d_size; @@ -57,7 +54,7 @@ class mixed_signal_sink_impl : public mixed_signal_sink int d_end; int d_start; - std::vector< std::vector > d_tags; + std::vector> d_tags; pmt::pmt_t d_trigger_tag_key; bool d_triggered; diff --git a/plugins/m2k/src/old/network_analyzer.cpp b/plugins/m2k/src/old/network_analyzer.cpp index 8b0aad7ca2..ed563fda86 100644 --- a/plugins/m2k/src/old/network_analyzer.cpp +++ b/plugins/m2k/src/old/network_analyzer.cpp @@ -18,17 +18,20 @@ * along with this program. If not, see . */ -#include "gui/dynamicWidget.h" #include "network_analyzer.hpp" -#include "signal_generator.hpp" + +#include "filemanager.h" +#include "gui/dynamicWidget.h" #include "gui/spinbox_a.hpp" -#include "hardware_trigger.hpp" #include "gui/utils.h" +#include "hardware_trigger.hpp" +#include "signal_generator.hpp" + #include "ui_network_analyzer.h" -#include "filemanager.h" -#include +#include +#include #include #include #include @@ -39,34 +42,32 @@ #include #include #include -#include -#include #include +#include #include #include +#include -#include - -#include -#include #include -#include -#include #include +#include +#include +#include +#include +#include -#include +#include #include -#include - /* libm2k includes */ -#include -#include #include "m2kpluginExceptionHandler.h" -#include #include +#include +#include +#include + Q_LOGGING_CATEGORY(CAT_M2K_NETWORK_ANALYZER, "M2kNetworkAnalyzer") static const int KERNEL_BUFFERS_DEFAULT = 4; @@ -81,8 +82,7 @@ void NetworkAnalyzer::_configureDacFlowgraph() { // Create the blocks that are used to generate sine waves top_block = make_top_block("Signal Generator"); - source_block = gr::analog::sig_source_f::make(1, gr::analog::GR_SIN_WAVE, - 1, 1, 1); + source_block = gr::analog::sig_source_f::make(1, gr::analog::GR_SIN_WAVE, 1, 1, 1); head_block = blocks::head::make(sizeof(float), 1); vector_block = blocks::vector_sink_f::make(); @@ -93,8 +93,7 @@ void NetworkAnalyzer::_configureDacFlowgraph() void NetworkAnalyzer::_configureAdcFlowgraph(size_t buffer_size) { - if (m_initFlowgraph) { - + if(m_initFlowgraph) { capture_top_block = make_top_block("Network capture processing"); @@ -102,10 +101,8 @@ void NetworkAnalyzer::_configureAdcFlowgraph(size_t buffer_size) // Make sure the values are sorted in ascending order (1000,..,100e6) sampleRates = m_m2k_analogin->getAvailableSampleRates(); - dc_cancel1 = gnuradio::get_initial_sptr( - new cancel_dc_offset_block(1, false)); - dc_cancel2 = gnuradio::get_initial_sptr( - new cancel_dc_offset_block(1, false)); + dc_cancel1 = gnuradio::get_initial_sptr(new cancel_dc_offset_block(1, false)); + dc_cancel2 = gnuradio::get_initial_sptr(new cancel_dc_offset_block(1, false)); capture1 = gr::blocks::vector_source_s::make(std::vector(), false, 1); capture2 = gr::blocks::vector_source_s::make(std::vector(), false, 1); @@ -155,8 +152,7 @@ void NetworkAnalyzer::_configureAdcFlowgraph(size_t buffer_size) capture_top_block->connect(c2a, 0, signal, 2); mag1 = 0.0, mag2 = 0.0, phase = 0.0; - connect(&*signal, &signal_sample::triggered, - [&](const std::vector values) { + connect(&*signal, &signal_sample::triggered, [&](const std::vector values) { mag1 = values[0]; mag2 = values[1]; phase = values[2]; @@ -175,36 +171,38 @@ void NetworkAnalyzer::_configureAdcFlowgraph(size_t buffer_size) ui->btnHelp->setUrl("https://wiki.analog.com/university/tools/m2k/scopy/networkanalyzer"); } -NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, - ToolMenuEntry *tme, m2k_iio_manager* m2k_man, - QJSEngine *engine, - QWidget *parent) : - M2kTool(ctx, tme, new NetworkAnalyzer_API(this), "Network Analyzer", parent), - ui(new Ui::NetworkAnalyzer), - m_m2k_context(nullptr), - m_m2k_analogin(nullptr), - m_m2k_analogout(nullptr), - m_adc_nb_channels(0), - m_dac_nb_channels(0), - d_cursorsEnabled(false), - m_stop(true), - m_dBgraph(this, true), - m_phaseGraph(this, true), - wheelEventGuard(nullptr), wasChecked(false), - justStarted(false), - iterationsThreadCanceled(false), iterationsThreadReady(false), - iterationsThread(nullptr), autoAdjustGain(true), - filterDc(false), m_initFlowgraph(true), m_hasReference(false), - m_importDataLoaded(false), - m_nb_averaging(1), - m_nb_periods(2) +NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, m2k_iio_manager *m2k_man, + QJSEngine *engine, QWidget *parent) + : M2kTool(ctx, tme, new NetworkAnalyzer_API(this), "Network Analyzer", parent) + , ui(new Ui::NetworkAnalyzer) + , m_m2k_context(nullptr) + , m_m2k_analogin(nullptr) + , m_m2k_analogout(nullptr) + , m_adc_nb_channels(0) + , m_dac_nb_channels(0) + , d_cursorsEnabled(false) + , m_stop(true) + , m_dBgraph(this, true) + , m_phaseGraph(this, true) + , wheelEventGuard(nullptr) + , wasChecked(false) + , justStarted(false) + , iterationsThreadCanceled(false) + , iterationsThreadReady(false) + , iterationsThread(nullptr) + , autoAdjustGain(true) + , filterDc(false) + , m_initFlowgraph(true) + , m_hasReference(false) + , m_importDataLoaded(false) + , m_nb_averaging(1) + , m_nb_periods(2) { - if (ctx) { - iio = m2k_man->get_instance(ctx, - filt->device_name(TOOL_NETWORK_ANALYZER, 2)); + if(ctx) { + iio = m2k_man->get_instance(ctx, filt->device_name(TOOL_NETWORK_ANALYZER, 2)); m_m2k_context = m2kOpen(ctx, ""); - if (m_m2k_context) { + if(m_m2k_context) { m_m2k_analogin = m_m2k_context->getAnalogIn(); m_m2k_analogout = m_m2k_context->getAnalogOut(); m_adc_nb_channels = m_m2k_analogin->getNbChannels(); @@ -221,28 +219,19 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, ui->statusLabel->setText(tr("Stopped")); - connect(ui->bufferPreviewSwitch, &QCheckBox::toggled, - this, &NetworkAnalyzer::toggleBufferPreview); + connect(ui->bufferPreviewSwitch, &QCheckBox::toggled, this, &NetworkAnalyzer::toggleBufferPreview); - connect(ui->prevBtn, &QPushButton::pressed, - bufferPreviewer, &NetworkAnalyzerBufferViewer::btnPreviousClicked); - connect(ui->nextBtn, &QPushButton::pressed, - bufferPreviewer, &NetworkAnalyzerBufferViewer::btnNextClicked); - connect(ui->viewInOscBtn, &QPushButton::pressed, - bufferPreviewer, &NetworkAnalyzerBufferViewer::sendBufferToOscilloscope); + connect(ui->prevBtn, &QPushButton::pressed, bufferPreviewer, &NetworkAnalyzerBufferViewer::btnPreviousClicked); + connect(ui->nextBtn, &QPushButton::pressed, bufferPreviewer, &NetworkAnalyzerBufferViewer::btnNextClicked); + connect(ui->viewInOscBtn, &QPushButton::pressed, bufferPreviewer, + &NetworkAnalyzerBufferViewer::sendBufferToOscilloscope); - connect(ui->runSingleWidget, &RunSingleWidget::toggled, - [=](bool checked){ - tme->setRunning(checked); - }); - connect(tme, &ToolMenuEntry::runClicked, - ui->runSingleWidget, &RunSingleWidget::toggle); - connect(ui->runSingleWidget, &RunSingleWidget::toggled, - this, &NetworkAnalyzer::startStop); - - connect(this, &NetworkAnalyzer::sweepDone, - [=]() { - if (ui->runSingleWidget->runButtonChecked()) { + connect(ui->runSingleWidget, &RunSingleWidget::toggled, [=](bool checked) { tme->setRunning(checked); }); + connect(tme, &ToolMenuEntry::runClicked, ui->runSingleWidget, &RunSingleWidget::toggle); + connect(ui->runSingleWidget, &RunSingleWidget::toggled, this, &NetworkAnalyzer::startStop); + + connect(this, &NetworkAnalyzer::sweepDone, [=]() { + if(ui->runSingleWidget->runButtonChecked()) { thd = QtConcurrent::run(this, &NetworkAnalyzer::goertzel); return; } @@ -250,32 +239,30 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, tme->setRunning(false); }); - startStopRange = new StartStopRangeWidget(1.0, 25e06); ui->sweepRangeLayout->addWidget(startStopRange); ui->rightMenu->setMaximumWidth(0); - connect(startStopRange, &StartStopRangeWidget::rangeChanged, - [=](double start, double stop){ + connect(startStopRange, &StartStopRangeWidget::rangeChanged, [=](double start, double stop) { // Update plot settings m_dBgraph.setXMin(start); m_dBgraph.setXMax(stop); m_phaseGraph.setXMin(start); m_phaseGraph.setXMax(stop); - QMetaObject::invokeMethod(this, - [=](){ - computeIterations(); - updateNumSamples(true); - }, - Qt::QueuedConnection); + QMetaObject::invokeMethod( + this, + [=]() { + computeIterations(); + updateNumSamples(true); + }, + Qt::QueuedConnection); }); - std::vector values = m_m2k_analogout->getAvailableSampleRates(0); double max_samplerate = values.back(); - m_dBgraph.setColor(QColor(255,114,0)); + m_dBgraph.setColor(QColor(255, 114, 0)); m_dBgraph.setXTitle(tr("Frequency (Hz)")); m_dBgraph.setYTitle(tr("Magnitude(dB)")); m_dBgraph.setXMin(1000.000000); @@ -284,7 +271,7 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, m_dBgraph.setYMax(20.000000); m_dBgraph.useLogFreq(true); - m_phaseGraph.setColor(QColor(144,19,254)); + m_phaseGraph.setColor(QColor(144, 19, 254)); m_phaseGraph.setYTitle(tr("Phase (°)")); m_phaseGraph.setYUnit("°"); m_phaseGraph.setXMin(1000.000000); @@ -294,75 +281,55 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, m_phaseGraph.useLogFreq(true); sampleStackedWidget = new QStackedWidget(this); - samplesCount = new ScaleSpinButton({ - {"samples",1e0}, - }, tr("Samples count"), 10, 10000, false, false, this); + samplesCount = new ScaleSpinButton( + { + {"samples", 1e0}, + }, + tr("Samples count"), 10, 10000, false, false, this); samplesCount->setValue(1000); - samplesPerDecadeCount = new ScaleSpinButton({ - {"samples",1e0}, - }, tr("Samps/decade"), 1, 10000, false, false, this); + samplesPerDecadeCount = new ScaleSpinButton( + { + {"samples", 1e0}, + }, + tr("Samps/decade"), 1, 10000, false, false, this); samplesPerDecadeCount->setValue(1000); - samplesStepSize = new ScaleSpinButton({ - {"Hz",1e0}, - {"kHz",1e3}, - {"MHz",1e6} - },tr("Step"), 1.0, 25e06, - false, false, this, - {1, 2.5, 5, 7.5}); + samplesStepSize = new ScaleSpinButton({{"Hz", 1e0}, {"kHz", 1e3}, {"MHz", 1e6}}, tr("Step"), 1.0, 25e06, false, + false, this, {1, 2.5, 5, 7.5}); sampleStackedWidget->addWidget(samplesStepSize); sampleStackedWidget->addWidget(samplesPerDecadeCount); startStopRange->insertWidgetIntoLayout(sampleStackedWidget, 2, 0); - amplitude = new ScaleSpinButton({ - {"μVolts",1e-6}, - {"mVolts",1e-3}, - {"Volts",1e0} - },tr("Amplitude"), 1e-6, 1e1, false, false, this); + amplitude = new ScaleSpinButton({{"μVolts", 1e-6}, {"mVolts", 1e-3}, {"Volts", 1e0}}, tr("Amplitude"), 1e-6, + 1e1, false, false, this); amplitude->setValue(1); - offset = new PositionSpinButton({ - {"μVolts",1e-6}, - {"mVolts",1e-3}, - {"Volts",1e0} - },tr("Offset"), -5, 5, false, false, this); + offset = new PositionSpinButton({{"μVolts", 1e-6}, {"mVolts", 1e-3}, {"Volts", 1e0}}, tr("Offset"), -5, 5, + false, false, this); offset->setValue(0); - magMax = new PositionSpinButton({ - {"dB",1e0} - }, tr("Max. Magnitude"), -120, 120, false, false, this); + magMax = new PositionSpinButton({{"dB", 1e0}}, tr("Max. Magnitude"), -120, 120, false, false, this); magMax->setValue(20); - magMin = new PositionSpinButton({ - {"dB",1e0} - }, tr("Min. Magnitude"), -120, 120, false, false, this); + magMin = new PositionSpinButton({{"dB", 1e0}}, tr("Min. Magnitude"), -120, 120, false, false, this); magMin->setValue(-80); - phaseMax = new PositionSpinButton({ - {"°",1e0} - }, tr("Max. Phase"), -360, 360, false, false, this); + phaseMax = new PositionSpinButton({{"°", 1e0}}, tr("Max. Phase"), -360, 360, false, false, this); phaseMax->setValue(180); - phaseMin = new PositionSpinButton({ - {"°",1e0} - }, tr("Min. Phase"), -360, 360, false, false, this); + phaseMin = new PositionSpinButton({{"°", 1e0}}, tr("Min. Phase"), -360, 360, false, false, this); phaseMin->setValue(-180); - pushDelay = new PositionSpinButton({ - {"ms",1e0}, - {"s",1e3} - }, tr("Settling time"), 0, 2000, false, false, this); + pushDelay = new PositionSpinButton({{"ms", 1e0}, {"s", 1e3}}, tr("Settling time"), 0, 2000, false, false, this); pushDelay->setValue(0); pushDelay->setStep(10); pushDelay->setToolTip(tr("Before Buffer")); - captureDelay = new PositionSpinButton({ - {"ms",1e0}, - {"s",1e3} - }, tr("Settling time"), 0, 2000, false, false, this); + captureDelay = + new PositionSpinButton({{"ms", 1e0}, {"s", 1e3}}, tr("Settling time"), 0, 2000, false, false, this); captureDelay->setValue(0); captureDelay->setStep(10); captureDelay->setToolTip(tr("After Buffer")); @@ -382,32 +349,20 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, setMinimumDistanceBetween(magMin, magMax, 1); setMinimumDistanceBetween(phaseMin, phaseMax, 1); - connect(magMax, &PositionSpinButton::valueChanged, - ui->xygraph, &NyquistGraph::setMax); - connect(magMax, &PositionSpinButton::valueChanged, - ui->nicholsgraph, &dBgraph::setYMax); - connect(magMin, &PositionSpinButton::valueChanged, - ui->xygraph, &NyquistGraph::setMin); - connect(magMin, &PositionSpinButton::valueChanged, - ui->nicholsgraph, &dBgraph::setYMin); - connect(phaseMax, &PositionSpinButton::valueChanged, - ui->nicholsgraph, &dBgraph::setXMax); - connect(phaseMin, &PositionSpinButton::valueChanged, - ui->nicholsgraph, &dBgraph::setXMin); - - connect(magMin, SIGNAL(valueChanged(double)), - &m_dBgraph, SLOT(setYMin(double))); - connect(magMax, SIGNAL(valueChanged(double)), - &m_dBgraph, SLOT(setYMax(double))); - connect(ui->btnIsLog, SIGNAL(toggled(bool)), - &m_dBgraph, SLOT(useLogFreq(bool))); - - connect(phaseMin, SIGNAL(valueChanged(double)), - &m_phaseGraph, SLOT(setYMin(double))); - connect(phaseMax, SIGNAL(valueChanged(double)), - &m_phaseGraph, SLOT(setYMax(double))); - connect(ui->btnIsLog, SIGNAL(toggled(bool)), - &m_phaseGraph, SLOT(useLogFreq(bool))); + connect(magMax, &PositionSpinButton::valueChanged, ui->xygraph, &NyquistGraph::setMax); + connect(magMax, &PositionSpinButton::valueChanged, ui->nicholsgraph, &dBgraph::setYMax); + connect(magMin, &PositionSpinButton::valueChanged, ui->xygraph, &NyquistGraph::setMin); + connect(magMin, &PositionSpinButton::valueChanged, ui->nicholsgraph, &dBgraph::setYMin); + connect(phaseMax, &PositionSpinButton::valueChanged, ui->nicholsgraph, &dBgraph::setXMax); + connect(phaseMin, &PositionSpinButton::valueChanged, ui->nicholsgraph, &dBgraph::setXMin); + + connect(magMin, SIGNAL(valueChanged(double)), &m_dBgraph, SLOT(setYMin(double))); + connect(magMax, SIGNAL(valueChanged(double)), &m_dBgraph, SLOT(setYMax(double))); + connect(ui->btnIsLog, SIGNAL(toggled(bool)), &m_dBgraph, SLOT(useLogFreq(bool))); + + connect(phaseMin, SIGNAL(valueChanged(double)), &m_phaseGraph, SLOT(setYMin(double))); + connect(phaseMax, SIGNAL(valueChanged(double)), &m_phaseGraph, SLOT(setYMax(double))); + connect(ui->btnIsLog, SIGNAL(toggled(bool)), &m_phaseGraph, SLOT(useLogFreq(bool))); connect(ui->btnIsLog, &CustomSwitch::toggled, [=](bool value) { sampleStackedWidget->setCurrentIndex(value); computeIterations(); @@ -417,26 +372,19 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, ui->nicholsgraph->setAxisVisible(QwtAxis::XTop, true); ui->nicholsgraph->setAxisVisible(QwtAxis::YLeft, true); - connect(phaseMin, &PositionSpinButton::valueChanged, - this, &NetworkAnalyzer::onMinMaxPhaseChanged); - connect(phaseMax, &PositionSpinButton::valueChanged, - this, &NetworkAnalyzer::onMinMaxPhaseChanged); - + connect(phaseMin, &PositionSpinButton::valueChanged, this, &NetworkAnalyzer::onMinMaxPhaseChanged); + connect(phaseMax, &PositionSpinButton::valueChanged, this, &NetworkAnalyzer::onMinMaxPhaseChanged); - connect(ui->cbLineThickness,SIGNAL(currentIndexChanged(int)),&m_dBgraph, - SLOT(setThickness(int))); - connect(ui->cbLineThickness,SIGNAL(currentIndexChanged(int)),&m_phaseGraph, - SLOT(setThickness(int))); - connect(ui->cbLineThickness,SIGNAL(currentIndexChanged(int)),ui->nicholsgraph, - SLOT(setThickness(int))); - connect(ui->cbLineThickness,SIGNAL(currentIndexChanged(int)),ui->xygraph, - SLOT(setThickness(int))); + connect(ui->cbLineThickness, SIGNAL(currentIndexChanged(int)), &m_dBgraph, SLOT(setThickness(int))); + connect(ui->cbLineThickness, SIGNAL(currentIndexChanged(int)), &m_phaseGraph, SLOT(setThickness(int))); + connect(ui->cbLineThickness, SIGNAL(currentIndexChanged(int)), ui->nicholsgraph, SLOT(setThickness(int))); + connect(ui->cbLineThickness, SIGNAL(currentIndexChanged(int)), ui->xygraph, SLOT(setThickness(int))); m_phaseGraph.setVertCursorsHandleEnabled(false); // plot widget - QWidget* centralWidget = new QWidget(this); - QGridLayout* gridLayout = new QGridLayout(centralWidget); + QWidget *centralWidget = new QWidget(this); + QGridLayout *gridLayout = new QGridLayout(centralWidget); gridLayout->setContentsMargins(9, 0, 0, 9); gridLayout->setHorizontalSpacing(10); gridLayout->setVerticalSpacing(0); @@ -461,36 +409,35 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, if(dockingEnabled) { // bode graph - QMainWindow* bodeWindow = new QMainWindow(this); + QMainWindow *bodeWindow = new QMainWindow(this); bodeWindow->setCentralWidget(0); bodeWindow->setWindowFlags(Qt::Widget); ui->gridLayout_plots->addWidget(bodeWindow, 0, 0); - QDockWidget* bodeDockWidget = DockerUtils::createDockWidget(bodeWindow, centralWidget, "Bode"); + QDockWidget *bodeDockWidget = DockerUtils::createDockWidget(bodeWindow, centralWidget, "Bode"); bodeWindow->addDockWidget(Qt::LeftDockWidgetArea, bodeDockWidget); - // nyquist graph - QMainWindow* nyquistWindow = new QMainWindow(this); + QMainWindow *nyquistWindow = new QMainWindow(this); nyquistWindow->setCentralWidget(0); nyquistWindow->setWindowFlags(Qt::Widget); ui->stackedWidgetPage2->layout()->removeWidget(ui->xygraph); ui->stackedWidgetPage2->layout()->addWidget(nyquistWindow); - QDockWidget* nyquistDockWidget = DockerUtils::createDockWidget(nyquistWindow, ui->xygraph, "Nyquist"); + QDockWidget *nyquistDockWidget = DockerUtils::createDockWidget(nyquistWindow, ui->xygraph, "Nyquist"); nyquistWindow->addDockWidget(Qt::LeftDockWidgetArea, nyquistDockWidget); - // nichols graph - QMainWindow* nicholsWindow = new QMainWindow(this); + QMainWindow *nicholsWindow = new QMainWindow(this); nicholsWindow->setCentralWidget(0); nicholsWindow->setWindowFlags(Qt::Widget); ui->stackedWidgetPage3->layout()->removeWidget(ui->nicholsgraph); ui->stackedWidgetPage3->layout()->addWidget(nicholsWindow); - QDockWidget* nicholsDockWidget = DockerUtils::createDockWidget(nicholsWindow, ui->nicholsgraph, "Nichols"); + QDockWidget *nicholsDockWidget = + DockerUtils::createDockWidget(nicholsWindow, ui->nicholsgraph, "Nichols"); nicholsWindow->addDockWidget(Qt::LeftDockWidgetArea, nicholsDockWidget); #ifdef PLOT_MENU_BAR_ENABLED @@ -504,7 +451,6 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, ui->gridLayout_plots->addWidget(centralWidget); } - m_phaseGraph.enableXaxisLabels(); m_dBgraph.enableXaxisLabels(); @@ -512,77 +458,60 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, m_dBgraph.enableYaxisLabels(); connect(m_dBgraph.vBar1(), static_cast(&HorizDebugSymbol::positionChanged), - [=](double x) - { - m_phaseGraph.vBar1()->setPosition(x); - }); + [=](double x) { m_phaseGraph.vBar1()->setPosition(x); }); connect(m_dBgraph.vBar2(), static_cast(&HorizDebugSymbol::positionChanged), - [=](double x) - { - m_phaseGraph.vBar2()->setPosition(x); - }); - - //The inverse connection is neccesary for the change of the boundaries for sweep - connect(m_phaseGraph.vBar1(), static_cast(&HorizDebugSymbol::positionChanged), - [=](double x) - { - m_dBgraph.vBar1()->setPosition(x); - }); + [=](double x) { m_phaseGraph.vBar2()->setPosition(x); }); - connect(m_phaseGraph.vBar2(), static_cast(&HorizDebugSymbol::positionChanged), - [=](double x) - { - m_dBgraph.vBar2()->setPosition(x); - }); + // The inverse connection is neccesary for the change of the boundaries for sweep + connect(m_phaseGraph.vBar1(), + static_cast(&HorizDebugSymbol::positionChanged), + [=](double x) { m_dBgraph.vBar1()->setPosition(x); }); + connect(m_phaseGraph.vBar2(), + static_cast(&HorizDebugSymbol::positionChanged), + [=](double x) { m_dBgraph.vBar2()->setPosition(x); }); ui->currentFrequencyLabel->setVisible(false); ui->currentSampleLabel->setVisible(false); ui->currentAverageLabel->setVisible(false); d_frequencyHandle = new FreePlotLineHandleH( - QPixmap(":/gui/icons/time_trigger_handle.svg"), - QPixmap(":/gui/icons/time_trigger_left.svg"), - QPixmap(":/gui/icons/time_trigger_right.svg"), - m_dBgraph.bottomHandlesArea()); + QPixmap(":/gui/icons/time_trigger_handle.svg"), QPixmap(":/gui/icons/time_trigger_left.svg"), + QPixmap(":/gui/icons/time_trigger_right.svg"), m_dBgraph.bottomHandlesArea()); d_frequencyHandle->setPen(QPen(QColor(74, 100, 255), 2, Qt::SolidLine)); d_frequencyHandle->setVisible(true); d_frequencyHandle->triggerMove(); ui->nicholsgraph->enableFrequencyBar(false); - connect(d_frequencyHandle, &FreePlotLineHandleH::positionChanged, - &m_dBgraph, &dBgraph::onFrequencyCursorPositionChanged); - connect(d_frequencyHandle, &FreePlotLineHandleH::positionChanged, - &m_phaseGraph, &dBgraph::onFrequencyCursorPositionChanged); - connect(&m_dBgraph, &dBgraph::frequencyBarPositionChanged, - this, &NetworkAnalyzer::onFrequencyBarMoved); - connect(&m_phaseGraph, &dBgraph::frequencyBarPositionChanged, - this, &NetworkAnalyzer::onFrequencyBarMoved); - - connect(bufferPreviewer, &NetworkAnalyzerBufferViewer::moveHandleAt, - &m_dBgraph, &dBgraph::onFrequencyBarMoved); - connect(bufferPreviewer, &NetworkAnalyzerBufferViewer::moveHandleAt, - &m_phaseGraph, &dBgraph::onFrequencyBarMoved); - connect(bufferPreviewer, &NetworkAnalyzerBufferViewer::indexChanged, - [=](int value) { + connect(d_frequencyHandle, &FreePlotLineHandleH::positionChanged, &m_dBgraph, + &dBgraph::onFrequencyCursorPositionChanged); + connect(d_frequencyHandle, &FreePlotLineHandleH::positionChanged, &m_phaseGraph, + &dBgraph::onFrequencyCursorPositionChanged); + connect(&m_dBgraph, &dBgraph::frequencyBarPositionChanged, this, &NetworkAnalyzer::onFrequencyBarMoved); + connect(&m_phaseGraph, &dBgraph::frequencyBarPositionChanged, this, &NetworkAnalyzer::onFrequencyBarMoved); + + connect(bufferPreviewer, &NetworkAnalyzerBufferViewer::moveHandleAt, &m_dBgraph, &dBgraph::onFrequencyBarMoved); + connect(bufferPreviewer, &NetworkAnalyzerBufferViewer::moveHandleAt, &m_phaseGraph, + &dBgraph::onFrequencyBarMoved); + connect(bufferPreviewer, &NetworkAnalyzerBufferViewer::indexChanged, [=](int value) { ui->currentFrequencyLabel->setVisible(true); ui->currentSampleLabel->setVisible(true); - ui->currentSampleLabel->setText(QString(tr("Sample: ") + QString::number(1 + value) - + " / " + QString::number(m_dBgraph.getNumSamples()) + " ")); + ui->currentSampleLabel->setText(QString(tr("Sample: ") + QString::number(1 + value) + " / " + + QString::number(m_dBgraph.getNumSamples()) + " ")); ui->currentAverageLabel->setVisible(true); MetricPrefixFormatter d_cursorTimeFormatter; d_cursorTimeFormatter.setTwoDecimalMode(false); QString text = d_cursorTimeFormatter.format(iterations[value].frequency, "Hz", 3); ui->currentFrequencyLabel->setText(QString(tr("Current Frequency: ") + text)); - if (value < iterationStats.size()) { + if(value < iterationStats.size()) { double dcVoltage = iterationStats[value].dcVoltage; text = d_cursorTimeFormatter.format(dcVoltage, "V", 2); ui->dcLabel->setText(tr("DC Voltage: ") + text); - if (iterationStats[value].hasError) { + if(iterationStats[value].hasError) { ui->errorLabel->setText(tr("Response channel voltage < 50mV!")); } else { ui->errorLabel->setText(""); @@ -593,24 +522,17 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, } }); + connect(&m_dBgraph, &dBgraph::frequencySelected, bufferPreviewer, &NetworkAnalyzerBufferViewer::selectBuffers); - connect(&m_dBgraph, &dBgraph::frequencySelected, - bufferPreviewer, &NetworkAnalyzerBufferViewer::selectBuffers); - - startStopRange->setStopValue((double) max_samplerate / 3.0 - 1.0); + startStopRange->setStopValue((double)max_samplerate / 3.0 - 1.0); - connect(samplesCount, SIGNAL(valueChanged(double)), - this, SLOT(updateNumSamples())); - connect(samplesPerDecadeCount, SIGNAL(valueChanged(double)), - this, SLOT(updateNumSamplesPerDecade())); - connect(samplesStepSize, SIGNAL(valueChanged(double)), - this, SLOT(updateSampleStepSize())); + connect(samplesCount, SIGNAL(valueChanged(double)), this, SLOT(updateNumSamples())); + connect(samplesPerDecadeCount, SIGNAL(valueChanged(double)), this, SLOT(updateNumSamplesPerDecade())); + connect(samplesStepSize, SIGNAL(valueChanged(double)), this, SLOT(updateSampleStepSize())); - connect(ui->boxCursors,SIGNAL(toggled(bool)), - SLOT(toggleCursors(bool))); + connect(ui->boxCursors, SIGNAL(toggled(bool)), SLOT(toggleCursors(bool))); - connect(ui->cmb_graphs,SIGNAL(currentIndexChanged(int)), - SLOT(onGraphIndexChanged(int))); + connect(ui->cmb_graphs, SIGNAL(currentIndexChanged(int)), SLOT(onGraphIndexChanged(int))); readPreferences(); @@ -620,38 +542,33 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, ScopyJS::GetInstance()->registerApi(api); - connect((m_dBgraph.getAxisWidget(QwtAxis::XTop)), SIGNAL(scaleDivChanged()), - &m_phaseGraph, SLOT(scaleDivChanged())); - connect((m_phaseGraph.getAxisWidget(QwtAxis::XTop)), SIGNAL(scaleDivChanged()), - &m_dBgraph, SLOT(scaleDivChanged())); + connect((m_dBgraph.getAxisWidget(QwtAxis::XTop)), SIGNAL(scaleDivChanged()), &m_phaseGraph, + SLOT(scaleDivChanged())); + connect((m_phaseGraph.getAxisWidget(QwtAxis::XTop)), SIGNAL(scaleDivChanged()), &m_dBgraph, + SLOT(scaleDivChanged())); - connect(&m_dBgraph,SIGNAL(resetZoom()),&m_phaseGraph,SLOT(onResetZoom())); - connect(&m_phaseGraph,SIGNAL(resetZoom()),&m_dBgraph,SLOT(onResetZoom())); + connect(&m_dBgraph, SIGNAL(resetZoom()), &m_phaseGraph, SLOT(onResetZoom())); + connect(&m_phaseGraph, SIGNAL(resetZoom()), &m_dBgraph, SLOT(onResetZoom())); #ifdef __ANDROID__ connect(&m_dBgraph, &dBgraph::zoomOut, &m_phaseGraph, &dBgraph::onZoomOut); connect(&m_phaseGraph, &dBgraph::zoomOut, &m_dBgraph, &dBgraph::onZoomOut); #endif - connect(ui->rightMenu, &MenuHAnim::finished, this, - &NetworkAnalyzer::rightMenuFinished); + connect(ui->rightMenu, &MenuHAnim::finished, this, &NetworkAnalyzer::rightMenuFinished); - connect(ui->btnSettings, &CustomPushButton::toggled, [=](bool checked) { - triggerRightMenuToggle(ui->btnSettings, checked); - }); - connect(ui->btnGeneralSettings, &CustomPushButton::toggled, [=](bool checked) { - triggerRightMenuToggle(ui->btnGeneralSettings, checked); - }); - connect(ui->btnCursors, &CustomPushButton::toggled, [=](bool checked) { - triggerRightMenuToggle(ui->btnCursors, checked); - }); + connect(ui->btnSettings, &CustomPushButton::toggled, + [=](bool checked) { triggerRightMenuToggle(ui->btnSettings, checked); }); + connect(ui->btnGeneralSettings, &CustomPushButton::toggled, + [=](bool checked) { triggerRightMenuToggle(ui->btnGeneralSettings, checked); }); + connect(ui->btnCursors, &CustomPushButton::toggled, + [=](bool checked) { triggerRightMenuToggle(ui->btnCursors, checked); }); connect(ui->btnApplyAverage, SIGNAL(clicked()), this, SLOT(validateSpinboxAveraging())); connect(ui->btnApplyPeriod, SIGNAL(clicked()), this, SLOT(validateSpinboxPeriods())); - ui->btnSettings->setProperty("id",QVariant(-1)); - ui->btnGeneralSettings->setProperty("id",QVariant(-2)); - ui->btnCursors->setProperty("id",QVariant(-3)); - + ui->btnSettings->setProperty("id", QVariant(-1)); + ui->btnGeneralSettings->setProperty("id", QVariant(-2)); + ui->btnCursors->setProperty("id", QVariant(-3)); connect(ui->horizontalSlider, &QSlider::valueChanged, [=](int value) { ui->transLabel->setText(tr("Transparency ") + QString::number(value) + "%"); @@ -661,25 +578,21 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, setDynamicProperty(ui->btnLockHorizontal, "use_icon", true); - connect(ui->btnLockHorizontal, &QPushButton::toggled, - &m_dBgraph, &dBgraph::setHorizCursorsLocked); + connect(ui->btnLockHorizontal, &QPushButton::toggled, &m_dBgraph, &dBgraph::setHorizCursorsLocked); - connect(ui->btnLockHorizontal, &QPushButton::toggled, - &m_phaseGraph, &dBgraph::setHorizCursorsLocked); + connect(ui->btnLockHorizontal, &QPushButton::toggled, &m_phaseGraph, &dBgraph::setHorizCursorsLocked); - connect(ui->hCursorsEnable, &QPushButton::toggled, - &m_dBgraph, &dBgraph::toggleCursors); + connect(ui->hCursorsEnable, &QPushButton::toggled, &m_dBgraph, &dBgraph::toggleCursors); - connect(ui->hCursorsEnable, &QPushButton::toggled, - &m_phaseGraph, &dBgraph::toggleCursors); + connect(ui->hCursorsEnable, &QPushButton::toggled, &m_phaseGraph, &dBgraph::toggleCursors); connect(ui->posSelect, &CustomPlotPositionButton::positionChanged, - [=](CustomPlotPositionButton::ReadoutsPosition position) { - m_dBgraph.moveCursorReadouts(position); - m_phaseGraph.moveCursorReadouts(position); - }); + [=](CustomPlotPositionButton::ReadoutsPosition position) { + m_dBgraph.moveCursorReadouts(position); + m_phaseGraph.moveCursorReadouts(position); + }); - if (!wheelEventGuard) { + if(!wheelEventGuard) { wheelEventGuard = new MouseWheelWidgetGuard(ui->mainWidget); } @@ -695,26 +608,25 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, QString fileNameHint = "Scopy-" + api->objectName() + "-" + date; - const QList imageFormats = - QImageWriter::supportedImageFormats(); + const QList imageFormats = QImageWriter::supportedImageFormats(); QStringList filter; - if ( imageFormats.size() > 0 ) { - for ( int i = 0; i < imageFormats.size(); i++ ) { - filter += (imageFormats[i].toUpper() + " " - + tr("Image") + " (*." + imageFormats[i] + ")"); - } + if(imageFormats.size() > 0) { + for(int i = 0; i < imageFormats.size(); i++) { + filter += (imageFormats[i].toUpper() + " " + tr("Image") + " (*." + imageFormats[i] + + ")"); + } } QString selectedFilter = filter[0]; - QString fileName = QFileDialog::getSaveFileName(this, - tr("Save to"), fileNameHint, filter.join(";;"), - &selectedFilter, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); - - if (fileName.split(".").size() <= 1) { - // file name w/o extension. Let's append it - QString ext = selectedFilter.split(".")[1].split(")")[0]; - fileName += "." + ext; + QString fileName = QFileDialog::getSaveFileName( + this, tr("Save to"), fileNameHint, filter.join(";;"), &selectedFilter, + (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); + + if(fileName.split(".").size() <= 1) { + // file name w/o extension. Let's append it + QString ext = selectedFilter.split(".")[1].split(")")[0]; + fileName += "." + ext; } painter.end(); @@ -723,22 +635,20 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, ui->deltaBtn->setDisabled(ui->btnIsLog->isChecked()); - connect(ui->deltaBtn, &QPushButton::toggled, - &m_dBgraph, &dBgraph::useDeltaLabel); - connect(ui->deltaBtn, &QPushButton::toggled, - &m_phaseGraph, &dBgraph::useDeltaLabel); + connect(ui->deltaBtn, &QPushButton::toggled, &m_dBgraph, &dBgraph::useDeltaLabel); + connect(ui->deltaBtn, &QPushButton::toggled, &m_phaseGraph, &dBgraph::useDeltaLabel); connect(ui->btnIsLog, &QPushButton::toggled, [=](bool checked) { ui->deltaBtn->setDisabled(checked); - if (checked) { + if(checked) { wasChecked = ui->deltaBtn->isChecked(); ui->deltaBtn->setChecked(false); } else { ui->deltaBtn->setChecked(wasChecked); } }); - connect(ui->dcFilterBtn, &QPushButton::toggled, [=](bool checked){ - if (checked != filterDc) { + connect(ui->dcFilterBtn, &QPushButton::toggled, [=](bool checked) { + if(checked != filterDc) { filterDc = checked; dc_cancel1->set_enabled(filterDc); dc_cancel2->set_enabled(filterDc); @@ -746,16 +656,14 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, }); connect(ui->responseGainCmb, QOverload::of(&QComboBox::currentIndexChanged), - [=](int value) { - autoAdjustGain = (value == 0); - }); + [=](int value) { autoAdjustGain = (value == 0); }); - connect(ui->snapshotBtn, &QCheckBox::clicked, [=](){ + connect(ui->snapshotBtn, &QCheckBox::clicked, [=]() { m_hasReference = true; bool didAddDbgraph = m_dBgraph.addReferenceWaveformFromPlot(); bool didAddPhasegraph = m_phaseGraph.addReferenceWaveformFromPlot(); - if (didAddDbgraph || didAddPhasegraph) { + if(didAddDbgraph || didAddPhasegraph) { ui->removeReferenceBtn->setEnabled(true); } }); @@ -766,11 +674,12 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, ui->removeReferenceBtn->setDisabled(true); }); - connect(ui->importBtn, &QPushButton::clicked, [=](){ - QString fileName = QFileDialog::getOpenFileName(this, - tr("Import"), "", tr("Comma-separated values files (*.csv);;" - "Tab-delimited values files (*.txt)"), - nullptr, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); + connect(ui->importBtn, &QPushButton::clicked, [=]() { + QString fileName = QFileDialog::getOpenFileName( + this, tr("Import"), "", + tr("Comma-separated values files (*.csv);;" + "Tab-delimited values files (*.txt)"), + nullptr, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); FileManager fm("Network Analyzer"); @@ -785,7 +694,7 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, QVector frequency, magnitude, phase; - for (size_t i = 0; i < m_importData.size(); ++i) { + for(size_t i = 0; i < m_importData.size(); ++i) { frequency.push_back(m_importData[i][0]); qDebug() << frequency.back(); magnitude.push_back(m_importData[i][1]); @@ -797,10 +706,9 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, m_hasReference = true; ui->removeReferenceBtn->setEnabled(true); - } catch (FileManagerException &e) { + } catch(FileManagerException &e) { ui->importFileLineEdit->setText(e.what()); } - }); connect(this, SIGNAL(sweepStart()), ui->xygraph, SLOT(reset())); @@ -810,19 +718,19 @@ NetworkAnalyzer::NetworkAnalyzer(struct iio_context *ctx, Filter *filt, NetworkAnalyzer::~NetworkAnalyzer() { -// disconnect(prefPanel,&Preferences::notify,this, -// &NetworkAnalyzer::readPreferences); + // disconnect(prefPanel,&Preferences::notify,this, + // &NetworkAnalyzer::readPreferences); startStop(false); ui->runSingleWidget->toggle(false); -// if (saveOnExit) { -// api->save(*settings); -// } + // if (saveOnExit) { + // api->save(*settings); + // } top_block->disconnect_all(); - if (iterationsThread) { - if (iterationsThread->joinable()) { + if(iterationsThread) { + if(iterationsThread->joinable()) { iterationsThreadCanceled = true; iterationsThread->join(); } @@ -836,36 +744,25 @@ NetworkAnalyzer::~NetworkAnalyzer() delete ui; } -QPushButton *NetworkAnalyzer::getRunButton() -{ - return ui->runSingleWidget->getRunButton(); -} +QPushButton *NetworkAnalyzer::getRunButton() { return ui->runSingleWidget->getRunButton(); } -void NetworkAnalyzer::setOscilloscope(Oscilloscope *osc) -{ - bufferPreviewer->setOscilloscope(osc); -} +void NetworkAnalyzer::setOscilloscope(Oscilloscope *osc) { bufferPreviewer->setOscilloscope(osc); } -bool NetworkAnalyzer::isIterationsThreadReady() -{ - return iterationsThreadReady; -} +bool NetworkAnalyzer::isIterationsThreadReady() { return iterationsThreadReady; } -bool NetworkAnalyzer::isIterationsThreadCanceled() -{ - return iterationsThreadCanceled; -} +bool NetworkAnalyzer::isIterationsThreadCanceled() { return iterationsThreadCanceled; } -void NetworkAnalyzer::onMinMaxPhaseChanged(double value) { +void NetworkAnalyzer::onMinMaxPhaseChanged(double value) +{ - if (QObject::sender() == phaseMin) { + if(QObject::sender() == phaseMin) { double phaseMaxValue = phaseMax->value(); - if (qAbs(phaseMaxValue - value) > 360) { + if(qAbs(phaseMaxValue - value) > 360) { phaseMax->setValue(phaseMaxValue - ((int)qAbs(phaseMaxValue - value) % 360)); } } else { double phaseMinValue = phaseMin->value(); - if (qAbs(value - phaseMinValue) > 360) { + if(qAbs(value - phaseMinValue) > 360) { phaseMin->setValue(phaseMinValue + ((int)qAbs(value - phaseMinValue) % 360)); } } @@ -876,8 +773,8 @@ void NetworkAnalyzer::onMinMaxPhaseChanged(double value) { void NetworkAnalyzer::computeIterations() { - if (iterationsThread) { - if (iterationsThread->joinable()) { + if(iterationsThread) { + if(iterationsThread->joinable()) { iterationsThreadCanceled = true; iterationsThread->join(); delete iterationsThread; @@ -895,26 +792,23 @@ void NetworkAnalyzer::computeIterations() iterationsThread = new std::thread(std::bind(&NetworkAnalyzer::computeFrequencyArray, this)); } -void NetworkAnalyzer::setMinimumDistanceBetween(SpinBoxA *min, SpinBoxA *max, - double distance) +void NetworkAnalyzer::setMinimumDistanceBetween(SpinBoxA *min, SpinBoxA *max, double distance) { connect(max, &SpinBoxA::valueChanged, [=](double value) { min->setMaxValue(value - distance); -// min->setValue(min->value()); + // min->setValue(min->value()); }); connect(min, &SpinBoxA::valueChanged, [=](double value) { max->setMinValue(value + distance); -// max->setValue(max->value()); + // max->setValue(max->value()); }); } -void NetworkAnalyzer::triggerRightMenuToggle(CustomPushButton *btn, - bool checked) +void NetworkAnalyzer::triggerRightMenuToggle(CustomPushButton *btn, bool checked) { - if (ui->rightMenu->animInProgress()) { - menuButtonActions.enqueue( - QPair(btn, checked)); + if(ui->rightMenu->animInProgress()) { + menuButtonActions.enqueue(QPair(btn, checked)); } else { toggleRightMenu(btn, checked); } @@ -924,8 +818,8 @@ void NetworkAnalyzer::toggleRightMenu(CustomPushButton *btn, bool checked) { int id = btn->property("id").toInt(); - if (checked) { - ui->stackedWidget_2->setCurrentIndex(-id-1); + if(checked) { + ui->stackedWidget_2->setCurrentIndex(-id - 1); } ui->rightMenu->toggleMenu(checked); @@ -935,16 +829,13 @@ void NetworkAnalyzer::rightMenuFinished(bool opened) { Q_UNUSED(opened) - while (menuButtonActions.size()) { + while(menuButtonActions.size()) { auto pair = menuButtonActions.dequeue(); toggleRightMenu(pair.first, pair.second); } } -void NetworkAnalyzer::showEvent(QShowEvent *event) -{ - M2kTool::showEvent(event); -} +void NetworkAnalyzer::showEvent(QShowEvent *event) { M2kTool::showEvent(event); } void NetworkAnalyzer::on_btnExport_clicked() { @@ -955,23 +846,23 @@ void NetworkAnalyzer::on_btnExport_clicked() QString selectedFilter = filter[0]; - QString fileName = QFileDialog::getSaveFileName(this, - tr("Export"), "", filter.join(";;"), - &selectedFilter, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); + QString fileName = QFileDialog::getSaveFileName( + this, tr("Export"), "", filter.join(";;"), &selectedFilter, + (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); - if (fileName.split(".").size() <= 1) { + if(fileName.split(".").size() <= 1) { // file name w/o extension. Let's append it QString ext = selectedFilter.split(".")[1].split(")")[0]; fileName += "." + ext; } - if (!fileName.isEmpty()) { + if(!fileName.isEmpty()) { FileManager fm("Network Analyzer"); fm.open(fileName, FileManager::EXPORT); - fm.setAdditionalInformation(ui->btnRefChn->isChecked() ? - "Reference channel: 1" : "Reference channel: 2"); + fm.setAdditionalInformation(ui->btnRefChn->isChecked() ? "Reference channel: 1" + : "Reference channel: 2"); fm.save(m_dBgraph.getXAxisData(), "Frequency(Hz)"); fm.save(m_dBgraph.getYAxisData(), "Magnitude(dB)"); @@ -985,10 +876,10 @@ void NetworkAnalyzer::updateNumSamples(bool force) { unsigned int num_samples; - if (force) { + if(force) { num_samples = iterations.size(); } else { - num_samples = (unsigned int) samplesCount->value(); + num_samples = (unsigned int)samplesCount->value(); } m_dBgraph.setNumSamples(num_samples); @@ -997,7 +888,7 @@ void NetworkAnalyzer::updateNumSamples(bool force) ui->nicholsgraph->setNumSamples(num_samples); bufferPreviewer->setNumBuffers(num_samples); - if (ui->btnIsLog->isChecked()) { + if(ui->btnIsLog->isChecked()) { double num_of_decades = log10(startStopRange->getStopValue() / startStopRange->getStartValue()); samplesPerDecadeCount->blockSignals(true); samplesPerDecadeCount->setValue(num_samples / num_of_decades); @@ -1013,7 +904,7 @@ void NetworkAnalyzer::updateNumSamples(bool force) updateSampleStepSize(); } - if (QObject::sender() == samplesCount) { + if(QObject::sender() == samplesCount) { computeIterations(); } } @@ -1023,12 +914,12 @@ void NetworkAnalyzer::updateNumSamplesPerDecade(bool force) unsigned int num_samples; unsigned int num_samples_per_decade; double num_of_decades; - num_samples_per_decade = (unsigned int) samplesPerDecadeCount->value(); + num_samples_per_decade = (unsigned int)samplesPerDecadeCount->value(); num_of_decades = log10(startStopRange->getStopValue() / startStopRange->getStartValue()); num_samples = num_samples_per_decade * num_of_decades; - if (QObject::sender() == samplesPerDecadeCount) { + if(QObject::sender() == samplesPerDecadeCount) { samplesCount->setValue(num_samples); } } @@ -1038,9 +929,9 @@ void NetworkAnalyzer::updateSampleStepSize(bool force) double step = samplesStepSize->value(); double stop_freq = startStopRange->getStopValue(); double start_freq = startStopRange->getStartValue(); - unsigned int new_num_samples = (unsigned int) (stop_freq - start_freq) / step + 1; + unsigned int new_num_samples = (unsigned int)(stop_freq - start_freq) / step + 1; - if (QObject::sender() == samplesStepSize) { + if(QObject::sender() == samplesStepSize) { samplesCount->setValue(new_num_samples); } } @@ -1051,25 +942,25 @@ void NetworkAnalyzer::updateGainMode() int responseChannel = ui->btnRefChn->isChecked() ? 1 : 0; int referenceChannel = 1 - responseChannel; - if (m_m2k_analogin) { + if(m_m2k_analogin) { double sweep_ampl = amplitude->value(); auto adc_range_limits = m_m2k_analogin->getRangeLimits(libm2k::analog::PLUS_MINUS_2_5V); double threshold = adc_range_limits.second; // - range.first libm2k::analog::M2K_RANGE gain_mode; - if ((sweep_ampl / 2.0) + offset->value() > threshold - || -(sweep_ampl / 2.0) + offset->value() < -threshold) { + if((sweep_ampl / 2.0) + offset->value() > threshold || + -(sweep_ampl / 2.0) + offset->value() < -threshold) { gain_mode = libm2k::analog::PLUS_MINUS_25V; } else { gain_mode = libm2k::analog::PLUS_MINUS_2_5V; } - for (unsigned int chn = 0; chn < m_adc_nb_channels; chn++) { + for(unsigned int chn = 0; chn < m_adc_nb_channels; chn++) { libm2k::analog::ANALOG_IN_CHANNEL channel = static_cast(chn); - if (chn == referenceChannel) { + if(chn == referenceChannel) { m_m2k_analogin->setRange(channel, gain_mode); - } else if (chn == responseChannel) { - if (!autoAdjustGain) { + } else if(chn == responseChannel) { + if(!autoAdjustGain) { auto gain = responseGainCmbIndex == 1 ? libm2k::analog::PLUS_MINUS_25V : libm2k::analog::PLUS_MINUS_2_5V; m_m2k_analogin->setRange(channel, gain); @@ -1086,26 +977,26 @@ unsigned long NetworkAnalyzer::_getBestSampleRate(double frequency, unsigned int std::vector values = m_m2k_analogout->getAvailableSampleRates(chn_idx); std::sort(values.begin(), values.end(), std::less()); - for (const auto &rate : values) { - if (rate == values[0]) { + for(const auto &rate : values) { + if(rate == values[0]) { continue; } size_t bufferSize = _getSamplesCount(frequency, rate, true); - if (bufferSize) { + if(bufferSize) { return rate; } } - for (const auto &rate : values) { - if (rate == values[0]) { + for(const auto &rate : values) { + if(rate == values[0]) { continue; } size_t bufferSize = _getSamplesCount(frequency, rate); - if (bufferSize) { + if(bufferSize) { return rate; } } @@ -1120,34 +1011,34 @@ size_t NetworkAnalyzer::_getSamplesCount(double frequency, unsigned long rate, b double ratio = static_cast(rate) / frequency; - if (ratio < 10.0 && rate < 75e06) { + if(ratio < 10.0 && rate < 75e06) { return 0; } - if (ratio < 2.5) { + if(ratio < 2.5) { return 0; } double fract = 0.0; ratio = SignalGenerator::get_best_ratio(ratio, static_cast(maxBufferSize / 4), &fract); - if (perfect && fract != 0.0) { + if(perfect && fract != 0.0) { return 0; } size_t size = ratio; /* The buffer size must be a multiple of 4 */ - while (size & 0x3) { + while(size & 0x3) { size <<= 1; } /* The buffer size shouldn't be too small */ - while (size < minBufferSize) { + while(size < minBufferSize) { size <<= 1; } - if (size > maxBufferSize) { + if(size > maxBufferSize) { return 0; } @@ -1160,7 +1051,7 @@ void NetworkAnalyzer::computeFrequencyArray() iterations.clear(); - unsigned int steps = (unsigned int) samplesCount->value(); + unsigned int steps = (unsigned int)samplesCount->value(); double min_freq = startStopRange->getStartValue(); double max_freq = startStopRange->getStopValue(); double log10_min_freq = log10(min_freq); @@ -1169,25 +1060,24 @@ void NetworkAnalyzer::computeFrequencyArray() bool is_log = ui->btnIsLog->isChecked(); - if (is_log) { + if(is_log) { step = (log10_max_freq - log10_min_freq) / (double)(steps - 1); } else { step = (max_freq - min_freq) / (double)(steps - 1); } - for (unsigned int i = 0; i < steps; ++i) { + for(unsigned int i = 0; i < steps; ++i) { - if (iterationsThreadCanceled) { + if(iterationsThreadCanceled) { return; } double frequency = 0.0; - if (is_log) { - frequency = pow(10.0, - log10_min_freq + (double) i * step); + if(is_log) { + frequency = pow(10.0, log10_min_freq + (double)i * step); } else { - frequency = min_freq + (double) i * step; + frequency = min_freq + (double)i * step; } unsigned long rate = _getBestSampleRate(frequency, 0); @@ -1197,10 +1087,7 @@ void NetworkAnalyzer::computeFrequencyArray() } // Needs to be invoked on the main thread - QMetaObject::invokeMethod(this, - "updateNumSamples", - Qt::QueuedConnection, - Q_ARG(bool, true)); + QMetaObject::invokeMethod(this, "updateNumSamples", Qt::QueuedConnection, Q_ARG(bool, true)); iterationsThreadReady = true; lock.unlock(); @@ -1224,7 +1111,7 @@ void NetworkAnalyzer::setFilterParameters() f21->set_filter_gain(iio->freq_comp_filt[1][0]->get_filter_gain()); f22->set_filter_gain(iio->freq_comp_filt[1][1]->get_filter_gain()); - if (m_m2k_analogin) { + if(m_m2k_analogin) { try { double adc_samplerate = m_m2k_analogin->getSampleRate(); f11->set_sample_rate(adc_samplerate); @@ -1238,7 +1125,7 @@ void NetworkAnalyzer::setFilterParameters() f12->set_high_gain(range0); f21->set_high_gain(range1); f22->set_high_gain(range1); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_NETWORK_ANALYZER) << e.what(); } @@ -1260,7 +1147,7 @@ void NetworkAnalyzer::goertzel() // Wait for the iterations thread to finish std::unique_lock lock(iterationsReadyMutex); iterationsReadyCv.wait(lock, std::bind(&NetworkAnalyzer::isIterationsThreadReady, this)); - if (iterationsThread) { + if(iterationsThread) { iterationsThread->join(); delete iterationsThread; iterationsThread = nullptr; @@ -1268,14 +1155,14 @@ void NetworkAnalyzer::goertzel() justStarted = true; - if (m_m2k_analogin) { - for (unsigned int chn_idx = 0; chn_idx < m_adc_nb_channels; chn_idx++) { + if(m_m2k_analogin) { + for(unsigned int chn_idx = 0; chn_idx < m_adc_nb_channels; chn_idx++) { m_m2k_analogin->enableChannel(chn_idx, true); } } Q_EMIT sweepStart(); - for (int i = 0; !m_stop && i < iterations.size(); ++i) { + for(int i = 0; !m_stop && i < iterations.size(); ++i) { // Get current sweep settings unsigned long rate = iterations[i].rate; @@ -1288,32 +1175,30 @@ void NetworkAnalyzer::goertzel() // Create and push the generated sine waves to the DACs std::vector> buffers; - if (m_m2k_analogout) { + if(m_m2k_analogout) { try { - for (unsigned int chn_idx = 0; chn_idx < m_dac_nb_channels; chn_idx++) { + for(unsigned int chn_idx = 0; chn_idx < m_dac_nb_channels; chn_idx++) { m_m2k_analogout->enableChannel(chn_idx, true); - std::vector buf_dac = generateSinWave(chn_idx, - frequency, amplitudeValue, offsetValue, - rate, samples_count); + std::vector buf_dac = generateSinWave( + chn_idx, frequency, amplitudeValue, offsetValue, rate, samples_count); buffers.push_back(buf_dac); } // Sleep before DACs start QThread::msleep(pushDelay->value()); m_m2k_analogout->push(buffers); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) return; } } - size_t buffer_size = 0; size_t adc_rate = 0; // Compute capture params for the ADC computeCaptureParams(frequency, buffer_size, adc_rate); - if (buffer_size == 0) { + if(buffer_size == 0) { qDebug(CAT_M2K_NETWORK_ANALYZER) << "buffer size 0"; return; } @@ -1328,41 +1213,39 @@ void NetworkAnalyzer::goertzel() goertzel1->set_rate(adc_rate); goertzel2->set_rate(adc_rate); - - if (m_m2k_analogin) { + if(m_m2k_analogin) { try { m_m2k_analogin->setOversamplingRatio(1); m_m2k_analogin->setSampleRate(adc_rate); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_NETWORK_ANALYZER) << e.what(); } } - setFilterParameters(); // Sleep before ADC capture QThread::msleep(captureDelay->value()); - for (unsigned int avg = 1; avg <= m_nb_averaging; avg++) { - const short* buffer_p = nullptr; - if (m_m2k_analogin) { + for(unsigned int avg = 1; avg <= m_nb_averaging; avg++) { + const short *buffer_p = nullptr; + if(m_m2k_analogin) { try { buffer_p = m_m2k_analogin->getSamplesRawInterleaved(buffer_size); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_NETWORK_ANALYZER) << e.what(); return; } - if (m_stop) { + if(m_stop) { return; } } std::vector data0; std::vector data1; - for (unsigned int data_i = 0; data_i < buffer_size; data_i++) { + for(unsigned int data_i = 0; data_i < buffer_size; data_i++) { data0.push_back(buffer_p[data_i * 2]); data1.push_back(buffer_p[data_i * 2 + 1]); } @@ -1390,55 +1273,43 @@ void NetworkAnalyzer::goertzel() mag1_averaged_sum += mag1; mag2_averaged_sum += mag2; dcOffset_averaged_sum += dcOffset; - ui->currentAverageLabel->setText(QString(tr("Average: ") + QString::number(avg) - + " / " + QString::number(m_nb_averaging))); - if (avg == m_nb_averaging) { + ui->currentAverageLabel->setText(QString(tr("Average: ") + QString::number(avg) + " / " + + QString::number(m_nb_averaging))); + if(avg == m_nb_averaging) { mag1 = mag1_averaged_sum / m_nb_averaging; mag2 = mag2_averaged_sum / m_nb_averaging; dcOffset = dcOffset_averaged_sum / m_nb_averaging; dcOffset = m_m2k_analogin->convertRawToVolts(1, dcOffset); - QMetaObject::invokeMethod(this, - "_saveChannelBuffers", - Qt::QueuedConnection, - Q_ARG(double, frequency), - Q_ARG(double, adc_rate), + QMetaObject::invokeMethod(this, "_saveChannelBuffers", Qt::QueuedConnection, + Q_ARG(double, frequency), Q_ARG(double, adc_rate), Q_ARG(std::vector, sink1->data()), Q_ARG(std::vector, sink2->data())); // Plot the data captured for this iteration - QMetaObject::invokeMethod(this, - "plot", - Qt::QueuedConnection, - Q_ARG(double, frequency), - Q_ARG(double, mag1), - Q_ARG(double, mag2), - Q_ARG(double, phase), - Q_ARG(float, dcOffset)); + QMetaObject::invokeMethod(this, "plot", Qt::QueuedConnection, Q_ARG(double, frequency), + Q_ARG(double, mag1), Q_ARG(double, mag2), + Q_ARG(double, phase), Q_ARG(float, dcOffset)); mag1_averaged_sum = 0; mag2_averaged_sum = 0; dcOffset_averaged_sum = 0; m_averaged_count = 0; - } } m_m2k_analogout->stop(); // Process was cancelled - if (m_stop) { + if(m_stop) { return; } } Q_EMIT sweepDone(); } -void NetworkAnalyzer::onFrequencyBarMoved(int pos) -{ - d_frequencyHandle->setPositionSilenty(pos); -} +void NetworkAnalyzer::onFrequencyBarMoved(int pos) { d_frequencyHandle->setPositionSilenty(pos); } void NetworkAnalyzer::toggleBufferPreview(bool toggle) { @@ -1449,7 +1320,8 @@ void NetworkAnalyzer::toggleBufferPreview(bool toggle) ui->nextBtn->setEnabled(toggle); } -void NetworkAnalyzer::_saveChannelBuffers(double frequency, double sample_rate, std::vector data1, std::vector data2) +void NetworkAnalyzer::_saveChannelBuffers(double frequency, double sample_rate, std::vector data1, + std::vector data2) { std::unique_lock lock(bufferMutex); @@ -1459,29 +1331,28 @@ void NetworkAnalyzer::_saveChannelBuffers(double frequency, double sample_rate, bufferPreviewer->pushBuffers(QPair(buffer1, buffer2)); } -void NetworkAnalyzer::computeCaptureParams(double frequency, - size_t& buffer_size, size_t& adc_rate) +void NetworkAnalyzer::computeCaptureParams(double frequency, size_t &buffer_size, size_t &adc_rate) { size_t nrOfPeriods = m_nb_periods; - for (const auto& rate : sampleRates) { + for(const auto &rate : sampleRates) { - if (rate == sampleRates[0]) { + if(rate == sampleRates[0]) { continue; } double ratio = rate / frequency; buffer_size = ratio * nrOfPeriods; - if (ratio < 2.5) { + if(ratio < 2.5) { continue; } - if (ratio < 10 && rate < sampleRates.back()) { + if(ratio < 10 && rate < sampleRates.back()) { continue; } - while (buffer_size < 160) { + while(buffer_size < 160) { buffer_size <<= 1; } @@ -1504,7 +1375,7 @@ QPair NetworkAnalyzer::getPhaseInterval() intervalMax = maxValue; intervalMin = intervalMax - 360; - if (intervalMin < lo) { + if(intervalMin < lo) { intervalMin = lo; intervalMax = lo + 360; } @@ -1512,14 +1383,13 @@ QPair NetworkAnalyzer::getPhaseInterval() return QPair(intervalMin, intervalMax); } -void NetworkAnalyzer::plot(double frequency, double mag1, double mag2, - double phase, float dcVoltage) +void NetworkAnalyzer::plot(double frequency, double mag1, double mag2, double phase, float dcVoltage) { double mag; static double magBonus = 0; static int currentSample = 0; - if (ui->btnRefChn->isChecked()) { + if(ui->btnRefChn->isChecked()) { phase = -phase; mag = 10.0 * log10(mag2) - 10.0 * log10(mag1); @@ -1533,14 +1403,14 @@ void NetworkAnalyzer::plot(double frequency, double mag1, double mag2, auto interval = getPhaseInterval(); - if (phase_deg > interval.second) { + if(phase_deg > interval.second) { adjusted_phase_deg = (int)phase_deg - 360; - } else if (phase_deg < interval.first) { + } else if(phase_deg < interval.first) { adjusted_phase_deg = (int)phase_deg + 360; } static int index = 0; - if (justStarted) { + if(justStarted) { currentSample = 0; justStarted = false; ui->currentFrequencyLabel->setVisible(true); @@ -1550,8 +1420,8 @@ void NetworkAnalyzer::plot(double frequency, double mag1, double mag2, magBonus = autoUpdateGainMode(mag, magBonus, dcVoltage); } - ui->currentSampleLabel->setText(QString(tr("Sample: ") + QString::number(1 + currentSample++ ) - + " / " + QString::number(m_dBgraph.getNumSamples()) + " ")); + ui->currentSampleLabel->setText(QString(tr("Sample: ") + QString::number(1 + currentSample++) + " / " + + QString::number(m_dBgraph.getNumSamples()) + " ")); MetricPrefixFormatter d_cursorTimeFormatter; d_cursorTimeFormatter.setTwoDecimalMode(false); @@ -1576,11 +1446,11 @@ void NetworkAnalyzer::plot(double frequency, double mag1, double mag2, QString gain = !m_m2k_analogin->getRange(chn) ? tr("Low") : tr("High"); ui->gainLabel->setText(tr("Gain Mode: ") + gain); - if (iterationStats.size() < samplesCount->value()) { + if(iterationStats.size() < samplesCount->value()) { iterationStats.push_back(NetworkIterationStats(dcVoltage, m_m2k_analogin->getRange(chn), hasError)); } else { iterationStats[index++] = NetworkIterationStats(dcVoltage, m_m2k_analogin->getRange(chn), hasError); - if (index == iterationStats.size()) { + if(index == iterationStats.size()) { index = 0; } } @@ -1595,7 +1465,7 @@ bool NetworkAnalyzer::_checkMagForOverrange(double magnitude) try { vlsb = m_m2k_analogin->getScalingFactor(static_cast(responseChannel)); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_NETWORK_ANALYZER) << e.what(); return false; @@ -1603,7 +1473,7 @@ bool NetworkAnalyzer::_checkMagForOverrange(double magnitude) double magnitudeThreshold = 20 * std::log10(3 * vlsb / amplitude->value()); - if (magnitude < magnitudeThreshold) { + if(magnitude < magnitudeThreshold) { ui->errorLabel->setText(tr("Response channel voltage < 50mV!")); m_dBgraph.parametersOverrange(true); m_phaseGraph.parametersOverrange(true); @@ -1635,21 +1505,20 @@ double NetworkAnalyzer::autoUpdateGainMode(double magnitude, double magnitudeGai libm2k::analog::M2K_RANGE gain; auto insideDeltaZone = [&](double voltage) { - return (voltage > hi_lo && voltage < hi_hi) - || (voltage < lo_hi && voltage > lo_lo); + return (voltage > hi_lo && voltage < hi_hi) || (voltage < lo_hi && voltage > lo_lo); }; bool noAdjustAllowedUp = insideDeltaZone(Vout / 2.0 + dcVoltage); bool noAdjustAllowedDown = insideDeltaZone(-Vout / 2.0 + dcVoltage); - if (Vout / 2.0 + dcVoltage >= hi_lo || -Vout / 2.0 + dcVoltage <= lo_hi) { - if (noAdjustAllowedDown && noAdjustAllowedUp) { + if(Vout / 2.0 + dcVoltage >= hi_lo || -Vout / 2.0 + dcVoltage <= lo_hi) { + if(noAdjustAllowedDown && noAdjustAllowedUp) { return magnitudeGain; } gain = libm2k::analog::PLUS_MINUS_25V; } - if (Vout / 2.0 + dcVoltage < hi_hi && -Vout / 2.0 + dcVoltage > lo_lo) { - if (noAdjustAllowedDown || noAdjustAllowedUp) { + if(Vout / 2.0 + dcVoltage < hi_hi && -Vout / 2.0 + dcVoltage > lo_lo) { + if(noAdjustAllowedDown || noAdjustAllowedUp) { return magnitudeGain; } gain = libm2k::analog::PLUS_MINUS_2_5V; @@ -1658,13 +1527,12 @@ double NetworkAnalyzer::autoUpdateGainMode(double magnitude, double magnitudeGai int responseChannel = ui->btnRefChn->isChecked() ? 1 : 0; libm2k::analog::ANALOG_IN_CHANNEL chn = static_cast(responseChannel); - double value = m_m2k_analogin->getValueForRange(PLUS_MINUS_25V) / - m_m2k_analogin->getValueForRange(PLUS_MINUS_2_5V); + double value = + m_m2k_analogin->getValueForRange(PLUS_MINUS_25V) / m_m2k_analogin->getValueForRange(PLUS_MINUS_2_5V); double magnitudeGainBetweenGainModes = 10.0 * log10(1.0 / value) - 10.0 * log10(1.0 * value); - - if (m_m2k_analogin->getRange(chn) != gain) { - if (autoAdjustGain) { + if(m_m2k_analogin->getRange(chn) != gain) { + if(autoAdjustGain) { m_m2k_analogin->setRange(chn, gain); } else { int selectedResponseGain = ui->responseGainCmb->currentIndex(); @@ -1672,14 +1540,18 @@ double NetworkAnalyzer::autoUpdateGainMode(double magnitude, double magnitudeGai : libm2k::analog::PLUS_MINUS_2_5V); } - if (gain == libm2k::analog::PLUS_MINUS_25V) { - if (gain != m_m2k_analogin->getRange(static_cast(1 - responseChannel))) { + if(gain == libm2k::analog::PLUS_MINUS_25V) { + if(gain != + m_m2k_analogin->getRange( + static_cast(1 - responseChannel))) { return magnitudeGainBetweenGainModes; } else { return 0.0; } } else { - if (gain != m_m2k_analogin->getRange(static_cast(1 - responseChannel))) { + if(gain != + m_m2k_analogin->getRange( + static_cast(1 - responseChannel))) { return -magnitudeGainBetweenGainModes; } else { return 0.0; @@ -1690,7 +1562,6 @@ double NetworkAnalyzer::autoUpdateGainMode(double magnitude, double magnitudeGai return magnitudeGain; } - void NetworkAnalyzer::run() { ui->runSingleWidget->toggle(true); @@ -1706,7 +1577,7 @@ void NetworkAnalyzer::startStop(bool pressed) { m_stop = !pressed; - if (m_running == pressed) { + if(m_running == pressed) { return; } @@ -1715,7 +1586,7 @@ void NetworkAnalyzer::startStop(bool pressed) m_phaseGraph.startStop(pressed); bool shouldClear = false; - if (QObject::sender() == ui->runSingleWidget) { + if(QObject::sender() == ui->runSingleWidget) { shouldClear = true; } @@ -1734,11 +1605,11 @@ void NetworkAnalyzer::startStop(bool pressed) ui->spinBox_averaging->setEnabled(!pressed); ui->spinBox_periods->setEnabled(!pressed); - if (pressed) { - ResourceManager::open("m2k-adc",this); - ResourceManager::open("m2k-dac",this); + if(pressed) { + ResourceManager::open("m2k-adc", this); + ResourceManager::open("m2k-dac", this); m_m2k_analogin->setKernelBuffersCount(1); - if (shouldClear) { + if(shouldClear) { m_dBgraph.reset(); m_phaseGraph.reset(); ui->xygraph->reset(); @@ -1761,7 +1632,7 @@ void NetworkAnalyzer::startStop(bool pressed) thd.waitForFinished(); m_m2k_analogin->stopAcquisition(); m_m2k_analogout->stop(); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_NETWORK_ANALYZER) << e.what(); } @@ -1772,26 +1643,24 @@ void NetworkAnalyzer::startStop(bool pressed) ResourceManager::close("m2k-adc"); try { m_m2k_analogin->setKernelBuffersCount(KERNEL_BUFFERS_DEFAULT); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { qDebug() << e.what(); } } } -std::vector NetworkAnalyzer::generateSinWave( - unsigned int chn_idx, double frequency, - double amplitude, double offset, - unsigned long rate, size_t samples_count) +std::vector NetworkAnalyzer::generateSinWave(unsigned int chn_idx, double frequency, double amplitude, + double offset, unsigned long rate, size_t samples_count) { - if (m_m2k_analogout) { + if(m_m2k_analogout) { try { m_m2k_analogout->setSampleRate(chn_idx, rate); m_m2k_analogout->setOversamplingRatio(chn_idx, 1); - if (!m_m2k_analogout->isChannelEnabled(chn_idx)) { + if(!m_m2k_analogout->isChannelEnabled(chn_idx)) { return {}; } - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_NETWORK_ANALYZER) << e.what(); } @@ -1811,7 +1680,7 @@ std::vector NetworkAnalyzer::generateSinWave( head_block->set_length(samples_count); top_block->run(); - const std::vector& f_samples = vector_block->data(); + const std::vector &f_samples = vector_block->data(); std::vector samples(f_samples.begin(), f_samples.end()); return samples; @@ -1819,23 +1688,23 @@ std::vector NetworkAnalyzer::generateSinWave( void NetworkAnalyzer::configHwForNetworkAnalyzing() { - if (m_m2k_analogin) { + if(m_m2k_analogin) { try { m_m2k_analogin->setOversamplingRatio(1); - for (unsigned int i = 0; i < m_m2k_analogin->getNbChannels(); i++) { + for(unsigned int i = 0; i < m_m2k_analogin->getNbChannels(); i++) { m_m2k_analogin->setVerticalOffset(static_cast(i), 0); } auto trigger = m_m2k_analogin->getTrigger(); - if (!trigger) { + if(!trigger) { return; } - for (unsigned int i = 0; i < m_m2k_analogin->getNbChannels(); i++) { + for(unsigned int i = 0; i < m_m2k_analogin->getNbChannels(); i++) { trigger->setAnalogMode(i, libm2k::ALWAYS); trigger->setAnalogDelay(0); } - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_NETWORK_ANALYZER) << e.what(); } @@ -1844,11 +1713,11 @@ void NetworkAnalyzer::configHwForNetworkAnalyzing() void NetworkAnalyzer::toggleCursors(bool en) { - if (!en) { + if(!en) { ui->btnCursors->setChecked(en); } - if (d_cursorsEnabled != en) { + if(d_cursorsEnabled != en) { d_cursorsEnabled = en; m_dBgraph.toggleCursors(en); m_phaseGraph.toggleCursors(en); @@ -1869,30 +1738,15 @@ void NetworkAnalyzer::readPreferences() ui->instrumentNotes->setVisible(p->get("m2k_instrument_notes_active").toBool()); -// autoAdjustGain = prefPanel->getNaGainUpdateEnabled(); + // autoAdjustGain = prefPanel->getNaGainUpdateEnabled(); } -void NetworkAnalyzer::onGraphIndexChanged(int index) -{ - ui->stackedWidget->setCurrentIndex(index); -} +void NetworkAnalyzer::onGraphIndexChanged(int index) { ui->stackedWidget->setCurrentIndex(index); } -void NetworkAnalyzer::on_spinBox_averaging_valueChanged(int n) -{ - m_nb_averaging = n; -} +void NetworkAnalyzer::on_spinBox_averaging_valueChanged(int n) { m_nb_averaging = n; } -void NetworkAnalyzer::validateSpinboxAveraging() -{ - on_spinBox_averaging_valueChanged(ui->spinBox_averaging->value()); -} +void NetworkAnalyzer::validateSpinboxAveraging() { on_spinBox_averaging_valueChanged(ui->spinBox_averaging->value()); } -void NetworkAnalyzer::on_spinBox_periods_valueChanged(int n) -{ - m_nb_periods = n; -} +void NetworkAnalyzer::on_spinBox_periods_valueChanged(int n) { m_nb_periods = n; } -void NetworkAnalyzer::validateSpinboxPeriods() -{ - on_spinBox_periods_valueChanged(ui->spinBox_periods->value()); -} +void NetworkAnalyzer::validateSpinboxPeriods() { on_spinBox_periods_valueChanged(ui->spinBox_periods->value()); } diff --git a/plugins/m2k/src/old/network_analyzer.hpp b/plugins/m2k/src/old/network_analyzer.hpp index a213ee7b89..5b92716d9a 100644 --- a/plugins/m2k/src/old/network_analyzer.hpp +++ b/plugins/m2k/src/old/network_analyzer.hpp @@ -21,46 +21,43 @@ #ifndef SCOPY_NETWORK_ANALYZER_HPP #define SCOPY_NETWORK_ANALYZER_HPP -#include "gui/spinbox_a.hpp" -#include "pluginbase/apiobject.h" -#include "iio_manager.hpp" -#include "signal_sample.hpp" -#include "m2ktool.hpp" +#include "TimeDomainDisplayPlot.h" +#include "cancel_dc_offset_block.h" #include "dbgraph.hpp" -#include "handles_area.hpp" -#include +#include "frequency_compensation_filter.h" #include "gui/customPushButton.h" #include "gui/mousewheelwidgetguard.h" -#include -#include -#include -#include +#include "gui/spinbox_a.hpp" +#include "gui/startstoprangewidget.h" +#include "handles_area.hpp" +#include "iio_manager.hpp" +#include "m2ktool.hpp" +#include "networkanalyzerbufferviewer.h" +#include "oscilloscope.hpp" +#include "pluginbase/apiobject.h" +#include "signal_sample.hpp" + #include -#include -#include -#include -#include -#include -#include #include #include -#include -#include +#include +#include #include +#include +#include #include -#include "cancel_dc_offset_block.h" +#include #include -#include "frequency_compensation_filter.h" +#include +#include +#include +#include #include -#include "oscilloscope.hpp" - -#include "TimeDomainDisplayPlot.h" - -#include "networkanalyzerbufferviewer.h" -#include "gui/startstoprangewidget.h" +#include -extern "C" { +extern "C" +{ struct iio_context; } @@ -83,19 +80,17 @@ class NetworkAnalyzer : public M2kTool Q_OBJECT public: - explicit NetworkAnalyzer(struct iio_context *ctx, Filter *filt, - ToolMenuEntry *toolMenuItem, m2k_iio_manager* m2k_man, - QJSEngine *engine, - QWidget *parent = nullptr); + explicit NetworkAnalyzer(struct iio_context *ctx, Filter *filt, ToolMenuEntry *toolMenuItem, + m2k_iio_manager *m2k_man, QJSEngine *engine, QWidget *parent = nullptr); ~NetworkAnalyzer(); - QPushButton* getRunButton(); + QPushButton *getRunButton(); void setOscilloscope(Oscilloscope *osc); private: Ui::NetworkAnalyzer *ui; - libm2k::context::M2k* m_m2k_context; - libm2k::analog::M2kAnalogOut* m_m2k_analogout; - libm2k::analog::M2kAnalogIn* m_m2k_analogin; + libm2k::context::M2k *m_m2k_context; + libm2k::analog::M2kAnalogOut *m_m2k_analogout; + libm2k::analog::M2kAnalogIn *m_m2k_analogin; unsigned int m_adc_nb_channels, m_dac_nb_channels; std::shared_ptr iio; bool m_initFlowgraph; @@ -112,34 +107,36 @@ class NetworkAnalyzer : public M2kTool dBgraph m_phaseGraph; bool wasChecked; - typedef struct NetworkAnalyzerIteration { - NetworkAnalyzerIteration(): - frequency(0), - rate(0), - bufferSize(0) {} - NetworkAnalyzerIteration(double frequency, - size_t rate, - size_t bufferSize): - frequency(frequency), - rate(rate), - bufferSize(bufferSize) {} + typedef struct NetworkAnalyzerIteration + { + NetworkAnalyzerIteration() + : frequency(0) + , rate(0) + , bufferSize(0) + {} + NetworkAnalyzerIteration(double frequency, size_t rate, size_t bufferSize) + : frequency(frequency) + , rate(rate) + , bufferSize(bufferSize) + {} double frequency; size_t rate; size_t bufferSize; } networkIteration; - typedef struct NetworkAnalyzerIterationStats { - NetworkAnalyzerIterationStats(double dcVoltage, - libm2k::analog::M2K_RANGE gain, - bool hasError): - dcVoltage(dcVoltage), - gain(gain), - hasError(hasError) {} - NetworkAnalyzerIterationStats(): - dcVoltage(0), - gain(libm2k::analog::PLUS_MINUS_25V), - hasError(false) {} + typedef struct NetworkAnalyzerIterationStats + { + NetworkAnalyzerIterationStats(double dcVoltage, libm2k::analog::M2K_RANGE gain, bool hasError) + : dcVoltage(dcVoltage) + , gain(gain) + , hasError(hasError) + {} + NetworkAnalyzerIterationStats() + : dcVoltage(0) + , gain(libm2k::analog::PLUS_MINUS_25V) + , hasError(false) + {} double dcVoltage; libm2k::analog::M2K_RANGE gain; @@ -159,7 +156,7 @@ class NetworkAnalyzer : public M2kTool gr::top_block_sptr capture_top_block; gr::blocks::vector_source_s::sptr capture1; gr::blocks::vector_source_s::sptr capture2; - scopy::frequency_compensation_filter::sptr f11,f12,f21,f22; + scopy::frequency_compensation_filter::sptr f11, f12, f21, f22; gr::blocks::short_to_float::sptr s2f1; gr::blocks::short_to_float::sptr s2f2; gr::scopy::goertzel_scopy_fc::sptr goertzel1; @@ -233,9 +230,7 @@ class NetworkAnalyzer : public M2kTool void goertzel(); void setFilterParameters(); - std::vector generateSinWave(unsigned int chn_idx, - double frequency, - double amplitude, double offset, + std::vector generateSinWave(unsigned int chn_idx, double frequency, double amplitude, double offset, unsigned long rate, size_t samples_count); void configHwForNetworkAnalyzing(); @@ -243,8 +238,7 @@ class NetworkAnalyzer : public M2kTool void triggerRightMenuToggle(CustomPushButton *btn, bool checked); void toggleRightMenu(CustomPushButton *btn, bool checked); void updateGainMode(); - void computeCaptureParams(double frequency, size_t& buffer_size, - size_t& adc_rate); + void computeCaptureParams(double frequency, size_t &buffer_size, size_t &adc_rate); QPair getPhaseInterval(); void computeIterations(); @@ -265,7 +259,8 @@ private Q_SLOTS: void updateNumSamplesPerDecade(bool force = false); void updateSampleStepSize(bool force = false); void plot(double frequency, double mag, double mag2, double phase, float dcVoltage); - void _saveChannelBuffers(double frequency, double sample_rate, std::vector data1, std::vector data2); + void _saveChannelBuffers(double frequency, double sample_rate, std::vector data1, + std::vector data2); void toggleCursors(bool en); void readPreferences() override; @@ -291,6 +286,6 @@ public Q_SLOTS: void sweepStart(); void showTool(); }; -} /* namespace scopy */ +} // namespace scopy::m2k #endif /* SCOPY_NETWORK_ANALYZER_HPP */ diff --git a/plugins/m2k/src/old/network_analyzer_api.cpp b/plugins/m2k/src/old/network_analyzer_api.cpp index 45cebb3346..648357ee7e 100644 --- a/plugins/m2k/src/old/network_analyzer_api.cpp +++ b/plugins/m2k/src/old/network_analyzer_api.cpp @@ -18,131 +18,87 @@ * along with this program. If not, see . */ #include "network_analyzer_api.hpp" + #include "ui_network_analyzer.h" namespace scopy::m2k { -void NetworkAnalyzer_API::show() -{ - Q_EMIT net->showTool(); -} +void NetworkAnalyzer_API::show() { Q_EMIT net->showTool(); } -double NetworkAnalyzer_API::getMinFreq() const -{ - return net->startStopRange->getStartValue(); -} +double NetworkAnalyzer_API::getMinFreq() const { return net->startStopRange->getStartValue(); } -double NetworkAnalyzer_API::getMaxFreq() const -{ - return net->startStopRange->getStopValue(); -} +double NetworkAnalyzer_API::getMaxFreq() const { return net->startStopRange->getStopValue(); } -double NetworkAnalyzer_API::getSamplesCount() const -{ - return net->samplesCount->value(); -} +double NetworkAnalyzer_API::getSamplesCount() const { return net->samplesCount->value(); } -double NetworkAnalyzer_API::getAmplitude() const -{ - return net->amplitude->value(); -} +double NetworkAnalyzer_API::getAmplitude() const { return net->amplitude->value(); } -double NetworkAnalyzer_API::getOffset() const -{ - return net->offset->value(); -} +double NetworkAnalyzer_API::getOffset() const { return net->offset->value(); } void NetworkAnalyzer_API::setMinFreq(double freq) { net->startStopRange->setStartValue(freq); - net->m_dBgraph.setXMin(freq); - net->m_phaseGraph.setXMin(freq); + net->m_dBgraph.setXMin(freq); + net->m_phaseGraph.setXMin(freq); } void NetworkAnalyzer_API::setMaxFreq(double freq) { net->startStopRange->setStopValue(freq); - net->m_dBgraph.setXMax(freq); - net->m_phaseGraph.setXMax(freq); + net->m_dBgraph.setXMax(freq); + net->m_phaseGraph.setXMax(freq); } -void NetworkAnalyzer_API::setSamplesCount(double step) -{ - net->samplesCount->setValue(step); -} +void NetworkAnalyzer_API::setSamplesCount(double step) { net->samplesCount->setValue(step); } -void NetworkAnalyzer_API::setAmplitude(double amp) -{ - net->amplitude->setValue(amp); -} +void NetworkAnalyzer_API::setAmplitude(double amp) { net->amplitude->setValue(amp); } -void NetworkAnalyzer_API::setOffset(double offset) -{ - net->offset->setValue(offset); -} +void NetworkAnalyzer_API::setOffset(double offset) { net->offset->setValue(offset); } -double NetworkAnalyzer_API::getMinMag() const -{ - return net->magMin->value(); -} +double NetworkAnalyzer_API::getMinMag() const { return net->magMin->value(); } -double NetworkAnalyzer_API::getMaxMag() const -{ - return net->magMax->value(); -} +double NetworkAnalyzer_API::getMaxMag() const { return net->magMax->value(); } -double NetworkAnalyzer_API::getMinPhase() const -{ - return net->phaseMin->value(); -} +double NetworkAnalyzer_API::getMinPhase() const { return net->phaseMin->value(); } -double NetworkAnalyzer_API::getMaxPhase() const -{ - return net->phaseMax->value(); -} +double NetworkAnalyzer_API::getMaxPhase() const { return net->phaseMax->value(); } void NetworkAnalyzer_API::setMinMag(double val) { - net->magMin->setValue(val); - net->m_dBgraph.setYMin(val); + net->magMin->setValue(val); + net->m_dBgraph.setYMin(val); net->ui->xygraph->setMin(val); net->ui->nicholsgraph->setYMin(val); } void NetworkAnalyzer_API::setMaxMag(double val) { - net->magMax->setValue(val); - net->m_dBgraph.setYMax(val); + net->magMax->setValue(val); + net->m_dBgraph.setYMax(val); net->ui->xygraph->setMax(val); net->ui->nicholsgraph->setYMax(val); } void NetworkAnalyzer_API::setMinPhase(double val) { - net->phaseMin->setValue(val); - net->m_phaseGraph.setYMin(val); + net->phaseMin->setValue(val); + net->m_phaseGraph.setYMin(val); net->ui->nicholsgraph->setXMin(val); } void NetworkAnalyzer_API::setMaxPhase(double val) { - net->phaseMax->setValue(val); - net->m_phaseGraph.setYMax(val); + net->phaseMax->setValue(val); + net->m_phaseGraph.setYMax(val); net->ui->nicholsgraph->setXMax(val); } -bool NetworkAnalyzer_API::isLogFreq() const -{ - return net->ui->btnIsLog->isChecked(); -} +bool NetworkAnalyzer_API::isLogFreq() const { return net->ui->btnIsLog->isChecked(); } -void NetworkAnalyzer_API::setLogFreq(bool is_log) -{ - net->ui->btnIsLog->setChecked(is_log); -} +void NetworkAnalyzer_API::setLogFreq(bool is_log) { net->ui->btnIsLog->setChecked(is_log); } int NetworkAnalyzer_API::getRefChannel() const { - if (net->ui->btnRefChn->isChecked()) + if(net->ui->btnRefChn->isChecked()) return 1; else return 2; @@ -150,39 +106,29 @@ int NetworkAnalyzer_API::getRefChannel() const void NetworkAnalyzer_API::setRefChannel(int chn) { - if (chn == 1) - net->ui->btnRefChn->setChecked(true); + if(chn == 1) + net->ui->btnRefChn->setChecked(true); else - net->ui->btnRefChn->setChecked(false); + net->ui->btnRefChn->setChecked(false); } -bool NetworkAnalyzer_API::getCursors() const -{ - return net->d_cursorsEnabled; -} +bool NetworkAnalyzer_API::getCursors() const { return net->d_cursorsEnabled; } -void NetworkAnalyzer_API::setCursors(bool enabled) -{ - net->ui->boxCursors->setChecked(enabled); -} +void NetworkAnalyzer_API::setCursors(bool enabled) { net->ui->boxCursors->setChecked(enabled); } bool NetworkAnalyzer_API::running() const { - return net->ui->runSingleWidget->runButtonChecked() - || net->ui->runSingleWidget->singleButtonChecked(); -} -void NetworkAnalyzer_API::run(bool enabled) -{ - net->ui->runSingleWidget->toggle(enabled); + return net->ui->runSingleWidget->runButtonChecked() || net->ui->runSingleWidget->singleButtonChecked(); } +void NetworkAnalyzer_API::run(bool enabled) { net->ui->runSingleWidget->toggle(enabled); } int NetworkAnalyzer_API::getCursorsPosition() const { - if (!net->ui->boxCursors->isChecked()) { + if(!net->ui->boxCursors->isChecked()) { return 0; } auto currentPos = net->m_dBgraph.getCursorReadouts()->getCurrentPosition(); - switch (currentPos) { + switch(currentPos) { case CustomPlotPositionButton::ReadoutsPosition::topLeft: default: return 0; @@ -198,15 +144,14 @@ int NetworkAnalyzer_API::getCursorsPosition() const void NetworkAnalyzer_API::setCursorsPosition(int val) { - if (!net->ui->boxCursors->isChecked()) { + if(!net->ui->boxCursors->isChecked()) { return; } enum CustomPlotPositionButton::ReadoutsPosition types[] = { CustomPlotPositionButton::ReadoutsPosition::topLeft, CustomPlotPositionButton::ReadoutsPosition::topRight, CustomPlotPositionButton::ReadoutsPosition::bottomLeft, - CustomPlotPositionButton::ReadoutsPosition::bottomRight - }; + CustomPlotPositionButton::ReadoutsPosition::bottomRight}; net->ui->posSelect->setPosition(types[val]); net->m_dBgraph.moveCursorReadouts(types[val]); net->m_dBgraph.replot(); @@ -216,7 +161,7 @@ void NetworkAnalyzer_API::setCursorsPosition(int val) int NetworkAnalyzer_API::getCursorsTransparency() const { - if (!net->ui->boxCursors->isChecked()) { + if(!net->ui->boxCursors->isChecked()) { return 0; } return net->ui->horizontalSlider->value(); @@ -224,7 +169,7 @@ int NetworkAnalyzer_API::getCursorsTransparency() const void NetworkAnalyzer_API::setCursorsTransparency(int val) { - if (!net->ui->boxCursors->isChecked()) { + if(!net->ui->boxCursors->isChecked()) { return; } net->ui->horizontalSlider->setValue(val); @@ -233,44 +178,19 @@ void NetworkAnalyzer_API::setCursorsTransparency(int val) net->m_phaseGraph.setCursorReadoutsTransparency(val); } +int NetworkAnalyzer_API::getPlotType() const { return net->ui->cmb_graphs->currentIndex(); } +void NetworkAnalyzer_API::setPlotType(int val) { net->ui->cmb_graphs->setCurrentIndex(val); } -int NetworkAnalyzer_API::getPlotType() const -{ - return net->ui->cmb_graphs->currentIndex(); -} -void NetworkAnalyzer_API::setPlotType(int val) -{ - net->ui->cmb_graphs->setCurrentIndex(val); -} +int NetworkAnalyzer_API::getAveraging() const { return net->ui->spinBox_averaging->value(); } -int NetworkAnalyzer_API::getAveraging() const -{ - return net->ui->spinBox_averaging->value(); -} +void NetworkAnalyzer_API::setAveraging(int val) { net->ui->spinBox_averaging->setValue(val); } -void NetworkAnalyzer_API::setAveraging(int val) -{ - net->ui->spinBox_averaging->setValue(val); -} +int NetworkAnalyzer_API::getPeriods() const { return net->ui->spinBox_periods->value(); } -int NetworkAnalyzer_API::getPeriods() const -{ - return net->ui->spinBox_periods->value(); -} +void NetworkAnalyzer_API::setPeriods(int val) { net->ui->spinBox_periods->setValue(val); } -void NetworkAnalyzer_API::setPeriods(int val) -{ - net->ui->spinBox_periods->setValue(val); -} - -int NetworkAnalyzer_API::getLineThickness() const -{ - return net->ui->cbLineThickness->currentIndex(); -} -void NetworkAnalyzer_API::setLineThickness(int index) -{ - net->ui->cbLineThickness->setCurrentIndex(index); -} +int NetworkAnalyzer_API::getLineThickness() const { return net->ui->cbLineThickness->currentIndex(); } +void NetworkAnalyzer_API::setLineThickness(int index) { net->ui->cbLineThickness->setCurrentIndex(index); } QList NetworkAnalyzer_API::data() const { @@ -290,13 +210,7 @@ QList NetworkAnalyzer_API::phase() const return list; } -QString NetworkAnalyzer_API::getNotes() -{ - return net->ui->instrumentNotes->getNotes(); -} -void NetworkAnalyzer_API::setNotes(QString str) -{ - net->ui->instrumentNotes->setNotes(str); -} +QString NetworkAnalyzer_API::getNotes() { return net->ui->instrumentNotes->getNotes(); } +void NetworkAnalyzer_API::setNotes(QString str) { net->ui->instrumentNotes->setNotes(str); } -} +} // namespace scopy::m2k diff --git a/plugins/m2k/src/old/network_analyzer_api.hpp b/plugins/m2k/src/old/network_analyzer_api.hpp index 0ef6f1c627..66acd6d504 100644 --- a/plugins/m2k/src/old/network_analyzer_api.hpp +++ b/plugins/m2k/src/old/network_analyzer_api.hpp @@ -22,8 +22,7 @@ #include -namespace scopy::m2k -{ +namespace scopy::m2k { class NetworkAnalyzer_API : public ApiObject { @@ -31,10 +30,8 @@ class NetworkAnalyzer_API : public ApiObject Q_PROPERTY(double min_freq READ getMinFreq WRITE setMinFreq); Q_PROPERTY(double max_freq READ getMaxFreq WRITE setMaxFreq); - Q_PROPERTY(double samples_count READ getSamplesCount - WRITE setSamplesCount); - Q_PROPERTY(double amplitude READ getAmplitude - WRITE setAmplitude); + Q_PROPERTY(double samples_count READ getSamplesCount WRITE setSamplesCount); + Q_PROPERTY(double amplitude READ getAmplitude WRITE setAmplitude); Q_PROPERTY(double offset READ getOffset WRITE setOffset); Q_PROPERTY(double min_mag READ getMinMag WRITE setMinMag); @@ -44,18 +41,14 @@ class NetworkAnalyzer_API : public ApiObject Q_PROPERTY(bool log_freq READ isLogFreq WRITE setLogFreq); - Q_PROPERTY(int ref_channel READ getRefChannel - WRITE setRefChannel); + Q_PROPERTY(int ref_channel READ getRefChannel WRITE setRefChannel); Q_PROPERTY(bool running READ running WRITE run STORED false); Q_PROPERTY(bool cursors READ getCursors WRITE setCursors); Q_PROPERTY(int line_thickness READ getLineThickness WRITE setLineThickness); - Q_PROPERTY(int cursors_position READ getCursorsPosition - WRITE setCursorsPosition) - Q_PROPERTY(int cursors_transparency READ getCursorsTransparency - WRITE setCursorsTransparency) - Q_PROPERTY(int plot_type READ getPlotType - WRITE setPlotType) + Q_PROPERTY(int cursors_position READ getCursorsPosition WRITE setCursorsPosition) + Q_PROPERTY(int cursors_transparency READ getCursorsTransparency WRITE setCursorsTransparency) + Q_PROPERTY(int plot_type READ getPlotType WRITE setPlotType) Q_PROPERTY(QList data READ data STORED false) Q_PROPERTY(QList phase READ phase STORED false) Q_PROPERTY(QList freq READ freq STORED false) @@ -63,8 +56,10 @@ class NetworkAnalyzer_API : public ApiObject Q_PROPERTY(int periods READ getPeriods WRITE setPeriods) Q_PROPERTY(QString notes READ getNotes WRITE setNotes) public: - explicit NetworkAnalyzer_API(NetworkAnalyzer *net) : - ApiObject(), net(net) {} + explicit NetworkAnalyzer_API(NetworkAnalyzer *net) + : ApiObject() + , net(net) + {} ~NetworkAnalyzer_API() {} double getMinFreq() const; @@ -131,5 +126,5 @@ class NetworkAnalyzer_API : public ApiObject private: NetworkAnalyzer *net; }; -} +} // namespace scopy::m2k #endif // NETWORK_ANALYZER_API_HPP diff --git a/plugins/m2k/src/old/networkanalyzerbufferviewer.cpp b/plugins/m2k/src/old/networkanalyzerbufferviewer.cpp index bfb9a2d70c..71bd3864c7 100644 --- a/plugins/m2k/src/old/networkanalyzerbufferviewer.cpp +++ b/plugins/m2k/src/old/networkanalyzerbufferviewer.cpp @@ -19,6 +19,7 @@ */ #include "networkanalyzerbufferviewer.h" + #include "ui_networkanalyzerbufferviewer.h" #include @@ -26,39 +27,33 @@ using namespace scopy; using namespace scopy::m2k; -NetworkAnalyzerBufferViewer::NetworkAnalyzerBufferViewer(QWidget *parent) : - QWidget(parent), - d_ui(new Ui::NetworkAnalyzerBufferViewer), - d_osc(nullptr), - d_selectedBuffersIndex(-1), - d_numBuffers(0) +NetworkAnalyzerBufferViewer::NetworkAnalyzerBufferViewer(QWidget *parent) + : QWidget(parent) + , d_ui(new Ui::NetworkAnalyzerBufferViewer) + , d_osc(nullptr) + , d_selectedBuffersIndex(-1) + , d_numBuffers(0) { d_ui->setupUi(this); _setupPlot(); } -NetworkAnalyzerBufferViewer::~NetworkAnalyzerBufferViewer() -{ - delete d_ui; -} +NetworkAnalyzerBufferViewer::~NetworkAnalyzerBufferViewer() { delete d_ui; } -void NetworkAnalyzerBufferViewer::setNumBuffers(unsigned int numBuffers) -{ - d_numBuffers = numBuffers; -} +void NetworkAnalyzerBufferViewer::setNumBuffers(unsigned int numBuffers) { d_numBuffers = numBuffers; } void NetworkAnalyzerBufferViewer::pushBuffers(QPair buffers) { static int currentBuffer = 0; - if (d_data.size() == 0) { + if(d_data.size() == 0) { currentBuffer = 0; } - if (d_data.size() < d_numBuffers) { + if(d_data.size() < d_numBuffers) { d_data.push_back(buffers); } else { d_data[currentBuffer++] = buffers; - if (currentBuffer == d_numBuffers) { + if(currentBuffer == d_numBuffers) { currentBuffer = 0; } } @@ -66,14 +61,14 @@ void NetworkAnalyzerBufferViewer::pushBuffers(QPair buffers) void NetworkAnalyzerBufferViewer::selectBuffersAtIndex(int index, bool moveHandle) { - if (index != d_selectedBuffersIndex) { + if(index != d_selectedBuffersIndex) { Q_EMIT indexChanged(index); } d_selectedBuffersIndex = index; static bool firstTime = true; - if (firstTime) { + if(firstTime) { firstTime = false; } else { d_plot->unregisterReferenceWaveform("data1"); @@ -85,7 +80,7 @@ void NetworkAnalyzerBufferViewer::selectBuffersAtIndex(int index, bool moveHandl double division = 1.0 / d_data[index].first.sampleRate; int n = d_data[index].first.buffer.size() / 2; - for (int i = -n; i < n; ++i) { + for(int i = -n; i < n; ++i) { xData.push_back(division * i); } @@ -96,18 +91,18 @@ void NetworkAnalyzerBufferViewer::selectBuffersAtIndex(int index, bool moveHandl double min = 0.0; QVector yData1, yData2; - for (size_t i = 0; i < d_data[index].first.buffer.size(); ++i) { - if (d_data[index].first.buffer[i] > max) { + for(size_t i = 0; i < d_data[index].first.buffer.size(); ++i) { + if(d_data[index].first.buffer[i] > max) { max = d_data[index].first.buffer[i]; - } else if (d_data[index].first.buffer[i] < min) { + } else if(d_data[index].first.buffer[i] < min) { min = d_data[index].first.buffer[i]; } yData1.push_back(d_data[index].first.buffer[i]); } - for (size_t i = 0; i < d_data[index].second.buffer.size(); ++i) { - if (d_data[index].second.buffer[i] > max) { + for(size_t i = 0; i < d_data[index].second.buffer.size(); ++i) { + if(d_data[index].second.buffer[i] > max) { max = d_data[index].second.buffer[i]; - } else if (d_data[index].second.buffer[i] < min) { + } else if(d_data[index].second.buffer[i] < min) { min = d_data[index].second.buffer[i]; } yData2.push_back(d_data[index].second.buffer[i]); @@ -120,7 +115,7 @@ void NetworkAnalyzerBufferViewer::selectBuffersAtIndex(int index, bool moveHandl // Move freq. handle on plot if prev/next button // are used to navigate through the buffers - if (moveHandle) { + if(moveHandle) { Q_EMIT moveHandleAt(d_data[index].first.frequency); } } @@ -128,26 +123,24 @@ void NetworkAnalyzerBufferViewer::selectBuffersAtIndex(int index, bool moveHandl void NetworkAnalyzerBufferViewer::selectBuffers(double frequency) { int index = -1; - for (int i = 0; i < d_data.size() - 1; ++i) { - if (d_data[i].first.frequency <= frequency - && frequency <= d_data[i + 1].first.frequency) { + for(int i = 0; i < d_data.size() - 1; ++i) { + if(d_data[i].first.frequency <= frequency && frequency <= d_data[i + 1].first.frequency) { index = i; break; } - if (d_data[i + 1].first.frequency < frequency) { + if(d_data[i + 1].first.frequency < frequency) { index = d_data.size() - 1; - } - if (frequency < d_data[i].first.frequency) { + if(frequency < d_data[i].first.frequency) { index = 0; } } - if (index == -1) { + if(index == -1) { return; } - if (index >= d_data.size()) { + if(index >= d_data.size()) { return; } @@ -158,16 +151,13 @@ void NetworkAnalyzerBufferViewer::setVisible(bool visible) { QWidget::setVisible(visible); - if (d_data.size() && d_selectedBuffersIndex == -1) { + if(d_data.size() && d_selectedBuffersIndex == -1) { d_selectedBuffersIndex = 0; selectBuffersAtIndex(d_selectedBuffersIndex); } } -void NetworkAnalyzerBufferViewer::setOscilloscope(Oscilloscope *osc) -{ - d_osc = osc; -} +void NetworkAnalyzerBufferViewer::setOscilloscope(Oscilloscope *osc) { d_osc = osc; } void NetworkAnalyzerBufferViewer::clear() { @@ -177,7 +167,7 @@ void NetworkAnalyzerBufferViewer::clear() void NetworkAnalyzerBufferViewer::sendBufferToOscilloscope() { - if (d_selectedBuffersIndex < 0 || d_selectedBuffersIndex >= d_data.size()) { + if(d_selectedBuffersIndex < 0 || d_selectedBuffersIndex >= d_data.size()) { return; } @@ -186,10 +176,10 @@ void NetworkAnalyzerBufferViewer::sendBufferToOscilloscope() QVector yData1, yData2; auto index = d_selectedBuffersIndex; - for (size_t i = 0; i < d_data[index].first.buffer.size(); ++i) { + for(size_t i = 0; i < d_data[index].first.buffer.size(); ++i) { yData1.push_back(d_data[index].first.buffer[i]); } - for (size_t i = 0; i < d_data[index].second.buffer.size(); ++i) { + for(size_t i = 0; i < d_data[index].second.buffer.size(); ++i) { yData2.push_back(d_data[index].second.buffer[i]); } d_osc->add_ref_waveform("NA1", d_currentXdata, yData1, d_data[index].first.sampleRate); @@ -202,14 +192,14 @@ void NetworkAnalyzerBufferViewer::sendBufferToOscilloscope() void NetworkAnalyzerBufferViewer::btnPreviousClicked() { - if (d_selectedBuffersIndex - 1 >= 0) { + if(d_selectedBuffersIndex - 1 >= 0) { selectBuffersAtIndex(d_selectedBuffersIndex - 1); } } void NetworkAnalyzerBufferViewer::btnNextClicked() { - if (d_selectedBuffersIndex + 1 < d_data.size()) { + if(d_selectedBuffersIndex + 1 < d_data.size()) { selectBuffersAtIndex(d_selectedBuffersIndex + 1); } } @@ -222,14 +212,11 @@ void NetworkAnalyzerBufferViewer::_setupPlot() d_plot->insertLegend(nullptr); d_plot->setUsingLeftAxisScales(false); int nrAxes = d_plot->axesCount(QwtAxis::YLeft); - for (int i = 0; i < nrAxes; ++i) { - d_plot->setAxisVisible(QwtAxisId(QwtAxis::YLeft, i), - false); + for(int i = 0; i < nrAxes; ++i) { + d_plot->setAxisVisible(QwtAxisId(QwtAxis::YLeft, i), false); } - d_plot->setAxisVisible(QwtAxisId(QwtAxis::XBottom, 0), - false); + d_plot->setAxisVisible(QwtAxisId(QwtAxis::XBottom, 0), false); d_plot->plotLayout()->setAlignCanvasToScales(true); d_ui->mainWidget->setMinimumHeight(150); } - diff --git a/plugins/m2k/src/old/networkanalyzerbufferviewer.h b/plugins/m2k/src/old/networkanalyzerbufferviewer.h index 240caa7490..6d853ae44d 100644 --- a/plugins/m2k/src/old/networkanalyzerbufferviewer.h +++ b/plugins/m2k/src/old/networkanalyzerbufferviewer.h @@ -21,22 +21,25 @@ #ifndef NETWORKANALYZERBUFFERVIEWER_H #define NETWORKANALYZERBUFFERVIEWER_H -#include -#include +#include "TimeDomainDisplayPlot.h" #include "oscilloscope.hpp" -#include "TimeDomainDisplayPlot.h" +#include +#include namespace Ui { class NetworkAnalyzerBufferViewer; } -struct Buffer { +struct Buffer +{ Buffer() {} - Buffer(double frequency, unsigned int sampleRate, - unsigned int bufferSize, const std::vector &buffer): - frequency(frequency), sampleRate(sampleRate), - bufferSize(bufferSize), buffer(buffer) {} + Buffer(double frequency, unsigned int sampleRate, unsigned int bufferSize, const std::vector &buffer) + : frequency(frequency) + , sampleRate(sampleRate) + , bufferSize(bufferSize) + , buffer(buffer) + {} double frequency; unsigned int sampleRate; @@ -86,6 +89,6 @@ public Q_SLOTS: QVector d_currentXdata; int d_numBuffers; }; -} +} // namespace scopy::m2k #endif // NETWORKANALYZERBUFFERVIEWER_H diff --git a/plugins/m2k/src/old/osc_adc.cpp b/plugins/m2k/src/old/osc_adc.cpp index 718abbcea7..2d690ab414 100644 --- a/plugins/m2k/src/old/osc_adc.cpp +++ b/plugins/m2k/src/old/osc_adc.cpp @@ -18,13 +18,16 @@ * along with this program. If not, see . */ #include "osc_adc.h" + +#include "hardware_trigger.hpp" +#include "m2kpluginExceptionHandler.h" + #include -#include + #include +#include -#include "hardware_trigger.hpp" #include -#include "m2kpluginExceptionHandler.h" using namespace scopy; @@ -32,15 +35,14 @@ using namespace scopy; * class IioUtils */ -QStringList IioUtils::available_options_list(struct iio_device *dev, - const char *attr_name) +QStringList IioUtils::available_options_list(struct iio_device *dev, const char *attr_name) { char buffer[8192]; ssize_t ret; QStringList list; ret = iio_device_attr_read(dev, attr_name, buffer, sizeof(buffer)); - if (ret >= 0) { + if(ret >= 0) { QString s(buffer); list = s.split(" ", Qt::SkipEmptyParts); } @@ -48,15 +50,14 @@ QStringList IioUtils::available_options_list(struct iio_device *dev, return list; } -QList IioUtils::scan_elem_channel_list( - struct iio_device *dev) +QList IioUtils::scan_elem_channel_list(struct iio_device *dev) { QList list; - for (unsigned int i = 0; i < iio_device_get_channels_count(dev); i++) { + for(unsigned int i = 0; i < iio_device_get_channels_count(dev); i++) { struct iio_channel *chn = iio_device_get_channel(dev, i); - if (!iio_channel_is_scan_element(chn)) + if(!iio_channel_is_scan_element(chn)) continue; list.push_back(chn); @@ -65,17 +66,16 @@ QList IioUtils::scan_elem_channel_list( return list; } -QList IioUtils::pick_channels_with_direction( - const QList& list, bool output) +QList IioUtils::pick_channels_with_direction(const QList &list, bool output) { QList return_list; - for (int i = 0; i < list.size(); i++) { + for(int i = 0; i < list.size(); i++) { struct iio_channel *chn = list.at(i); - if (output && iio_channel_is_output(chn)) + if(output && iio_channel_is_output(chn)) return_list.push_back(chn); - else if (!output && !iio_channel_is_output(chn)) + else if(!output && !iio_channel_is_output(chn)) return_list.push_back(chn); } @@ -84,17 +84,16 @@ QList IioUtils::pick_channels_with_direction( std::string IioUtils::hardware_revision(struct iio_context *ctx) { - const char *hw_rev_attr_val = iio_context_get_attr_value(ctx, - "hw_model"); + const char *hw_rev_attr_val = iio_context_get_attr_value(ctx, "hw_model"); std::string rev; - if (hw_rev_attr_val) { + if(hw_rev_attr_val) { std::string const s = hw_rev_attr_val; std::string const key = "Rev."; int n = s.find(key); n += key.length(); - rev = s.substr(n, 1); + rev = s.substr(n, 1); } else { rev = "A"; } @@ -106,65 +105,39 @@ std::string IioUtils::hardware_revision(struct iio_context *ctx) * class GenericAdc */ -GenericAdc::GenericAdc(struct iio_context *ctx, struct iio_device *adc_dev): - m_ctx(ctx), - m_adc(adc_dev), - m_adc_bits(0) +GenericAdc::GenericAdc(struct iio_context *ctx, struct iio_device *adc_dev) + : m_ctx(ctx) + , m_adc(adc_dev) + , m_adc_bits(0) { - m_adc_channels = IioUtils::pick_channels_with_direction( - IioUtils::scan_elem_channel_list(adc_dev), false); + m_adc_channels = IioUtils::pick_channels_with_direction(IioUtils::scan_elem_channel_list(adc_dev), false); - if (m_adc_channels.size() > 0) { - m_adc_bits = iio_channel_get_data_format( - m_adc_channels[0])->bits; + if(m_adc_channels.size() > 0) { + m_adc_bits = iio_channel_get_data_format(m_adc_channels[0])->bits; } m_sample_rate = readSampleRate(); } -GenericAdc::~GenericAdc() -{ -} +GenericAdc::~GenericAdc() {} -struct iio_context * GenericAdc::iio_context() const -{ - return m_ctx; -} +struct iio_context *GenericAdc::iio_context() const { return m_ctx; } -struct iio_device * GenericAdc::iio_adc_dev() const -{ - return m_adc; -} +struct iio_device *GenericAdc::iio_adc_dev() const { return m_adc; } -std::shared_ptr GenericAdc::getTrigger() const -{ - return m_trigger; -} +std::shared_ptr GenericAdc::getTrigger() const { return m_trigger; } -QList GenericAdc::adcChannelList() const -{ - return m_adc_channels; -} +QList GenericAdc::adcChannelList() const { return m_adc_channels; } -uint GenericAdc::numAdcChannels() const -{ - return m_adc_channels.size(); -} +uint GenericAdc::numAdcChannels() const { return m_adc_channels.size(); } -uint GenericAdc::numAdcBits() const -{ - return m_adc_bits; -} +uint GenericAdc::numAdcBits() const { return m_adc_bits; } -double GenericAdc::sampleRate() const -{ - return m_sample_rate; -} +double GenericAdc::sampleRate() const { return m_sample_rate; } double GenericAdc::readSampleRate() { - iio_device_attr_read_double(m_adc, "sampling_frequency", - &m_sample_rate); + iio_device_attr_read_double(m_adc, "sampling_frequency", &m_sample_rate); return m_sample_rate; } @@ -175,25 +148,13 @@ void GenericAdc::setSampleRate(double sr) m_sample_rate = sr; } -double GenericAdc::convSampleToVolts(uint chnIdx, double sample) const -{ - return sample; -} +double GenericAdc::convSampleToVolts(uint chnIdx, double sample) const { return sample; } -double GenericAdc::convVoltsToSample(uint chnIdx, double volts) const -{ - return volts; -} +double GenericAdc::convVoltsToSample(uint chnIdx, double volts) const { return volts; } -double GenericAdc::convSampleDiffToVoltsDiff(uint chnIdx, double smpl)const -{ - return smpl; -} +double GenericAdc::convSampleDiffToVoltsDiff(uint chnIdx, double smpl) const { return smpl; } -double GenericAdc::convVoltsDiffToSampleDiff(uint chnIdx, double v) const -{ - return v; -} +double GenericAdc::convVoltsDiffToSampleDiff(uint chnIdx, double v) const { return v; } GenericAdc::settings_uptr GenericAdc::getCurrentHwSettings() { @@ -204,59 +165,47 @@ GenericAdc::settings_uptr GenericAdc::getCurrentHwSettings() return settings_uptr; } -void GenericAdc::setHwSettings(GenericAdc::Settings *settings) -{ - setSampleRate(settings->sample_rate); -} +void GenericAdc::setHwSettings(GenericAdc::Settings *settings) { setSampleRate(settings->sample_rate); } /* * Class M2kAdc */ -M2kAdc::M2kAdc(struct iio_context *ctx, struct iio_device *adc_dev): - GenericAdc(ctx, adc_dev), - filtering_enabled(false) +M2kAdc::M2kAdc(struct iio_context *ctx, struct iio_device *adc_dev) + : GenericAdc(ctx, adc_dev) + , filtering_enabled(false) { apply_m2k_fixes(); // Hardware gain channels - struct iio_device *m2k_fabric = iio_context_find_device(ctx, - "m2k-fabric"); - m_gain_channels.push_back(iio_device_find_channel(m2k_fabric, - "voltage0", false)); - m_gain_channels.push_back(iio_device_find_channel(m2k_fabric, - "voltage1", false)); + struct iio_device *m2k_fabric = iio_context_find_device(ctx, "m2k-fabric"); + m_gain_channels.push_back(iio_device_find_channel(m2k_fabric, "voltage0", false)); + m_gain_channels.push_back(iio_device_find_channel(m2k_fabric, "voltage1", false)); // Hardware offset cannels struct iio_device *ad5625 = iio_context_find_device(ctx, "ad5625"); - m_offset_channels.push_back(iio_device_find_channel(ad5625, "voltage2", - true)); - m_offset_channels.push_back(iio_device_find_channel(ad5625, "voltage3", - true)); + m_offset_channels.push_back(iio_device_find_channel(ad5625, "voltage2", true)); + m_offset_channels.push_back(iio_device_find_channel(ad5625, "voltage3", true)); // Check for hardware triggering support - struct iio_device *m2k_trigger = iio_context_find_device(ctx, - "m2k-adc-trigger"); + struct iio_device *m2k_trigger = iio_context_find_device(ctx, "m2k-adc-trigger"); try { m_trigger = std::make_shared(m2k_trigger); - } catch (libm2k::m2k_exception& e){ + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug() << "Disabling hardware trigger support." << e.what(); } // Available frequencies list - QStringList list = IioUtils::available_options_list(adc_dev, - "sampling_frequency_available"); + QStringList list = IioUtils::available_options_list(adc_dev, "sampling_frequency_available"); max_sample_rate = 1; - for (int i = 0; i < list.size(); i++) - { + for(int i = 0; i < list.size(); i++) { auto sr = list.at(i).toDouble(); m_availSampRates.append(sr); - if(max_sample_rate< sr) + if(max_sample_rate < sr) max_sample_rate = sr; } - // Filters applied while decimating affect the amplitude of the received // data m_filt_comp_table[1E8] = 1.00; @@ -267,7 +216,7 @@ M2kAdc::M2kAdc(struct iio_context *ctx, struct iio_device *adc_dev): m_filt_comp_table[1E3] = 1.26; // Channel defaults - for (uint i = 0; i < numAdcChannels(); i++) { + for(uint i = 0; i < numAdcChannels(); i++) { m_chn_corr_offsets.push_back(0.0); m_chn_corr_gains.push_back(1.0); m_chn_hw_offsets.push_back(0.0); @@ -275,21 +224,18 @@ M2kAdc::M2kAdc(struct iio_context *ctx, struct iio_device *adc_dev): } } -M2kAdc::~M2kAdc() -{ -} +M2kAdc::~M2kAdc() {} void M2kAdc::apply_m2k_fixes() { std::string hw_rev = IioUtils::hardware_revision(iio_context()); - struct iio_device *dev = iio_context_find_device(iio_context(), - "ad9963"); + struct iio_device *dev = iio_context_find_device(iio_context(), "ad9963"); int config1 = 0x05; int config2 = 0x05; - if (hw_rev == "A") { + if(hw_rev == "A") { config1 = 0x1B; // IGAIN1 +-6db 0.25db steps config2 = 0x1B; } @@ -297,72 +243,51 @@ void M2kAdc::apply_m2k_fixes() /* Configure TX path */ iio_device_reg_write(dev, 0x68, config1); iio_device_reg_write(dev, 0x6B, config2); - iio_device_reg_write(dev, 0x69, 0x1C); // IGAIN2 +-2.5% + iio_device_reg_write(dev, 0x69, 0x1C); // IGAIN2 +-2.5% iio_device_reg_write(dev, 0x6C, 0x1C); - iio_device_reg_write(dev, 0x6A, 0x20); // IRSET +-20% + iio_device_reg_write(dev, 0x6A, 0x20); // IRSET +-20% iio_device_reg_write(dev, 0x6D, 0x20); } -double M2kAdc::chnCorrectionOffset(uint chnIdx) const -{ - return m_chn_corr_offsets[chnIdx]; -} +double M2kAdc::chnCorrectionOffset(uint chnIdx) const { return m_chn_corr_offsets[chnIdx]; } -void M2kAdc::setChnCorrectionOffset(uint chnIdx, double offset) -{ - m_chn_corr_offsets[chnIdx] = offset; -} +void M2kAdc::setChnCorrectionOffset(uint chnIdx, double offset) { m_chn_corr_offsets[chnIdx] = offset; } -double M2kAdc::chnCorrectionGain(uint chnIdx) const -{ - return m_chn_corr_gains[chnIdx]; -} +double M2kAdc::chnCorrectionGain(uint chnIdx) const { return m_chn_corr_gains[chnIdx]; } -void M2kAdc::setChnCorrectionGain(uint chnIdx, double gain) -{ - m_chn_corr_gains[chnIdx] = gain; -} +void M2kAdc::setChnCorrectionGain(uint chnIdx, double gain) { m_chn_corr_gains[chnIdx] = gain; } -double M2kAdc::chnHwOffset(uint chnIdx) const -{ - return m_chn_hw_offsets[chnIdx]; -} +double M2kAdc::chnHwOffset(uint chnIdx) const { return m_chn_hw_offsets[chnIdx]; } void M2kAdc::setChnHwOffset(uint chnIdx, double offset) { double gain = 1.3; double vref = 1.2; double hw_chn_gain = gainAt(chnHwGainMode(chnIdx)); - int raw_offset = (int)(offset * (1 << numAdcBits()) * hw_chn_gain * - gain / 2.693 / vref) + m_chn_corr_offsets[chnIdx]; + int raw_offset = + (int)(offset * (1 << numAdcBits()) * hw_chn_gain * gain / 2.693 / vref) + m_chn_corr_offsets[chnIdx]; - iio_channel_attr_write_longlong(m_offset_channels[chnIdx], "raw", - (long long)raw_offset); + iio_channel_attr_write_longlong(m_offset_channels[chnIdx], "raw", (long long)raw_offset); m_chn_hw_offsets[chnIdx] = offset; } -M2kAdc::GainMode M2kAdc::chnHwGainMode(uint chnIdx) const -{ - return m_chn_hw_gain_modes[chnIdx]; -} +M2kAdc::GainMode M2kAdc::chnHwGainMode(uint chnIdx) const { return m_chn_hw_gain_modes[chnIdx]; } void M2kAdc::setChnHwGainMode(uint chnIdx, GainMode gain_mode) { - const char *str_gain_mode = (gain_mode == GainMode::HIGH_GAIN_MODE) ? - "high" : "low"; + const char *str_gain_mode = (gain_mode == GainMode::HIGH_GAIN_MODE) ? "high" : "low"; - iio_channel_attr_write_raw(m_gain_channels[chnIdx], "gain", - str_gain_mode, strlen(str_gain_mode)); + iio_channel_attr_write_raw(m_gain_channels[chnIdx], "gain", str_gain_mode, strlen(str_gain_mode)); m_chn_hw_gain_modes[chnIdx] = gain_mode; } double M2kAdc::gainAt(GainMode gain_mode) const { - if (gain_mode == LOW_GAIN_MODE) + if(gain_mode == LOW_GAIN_MODE) return 0.02017; - else if (gain_mode == HIGH_GAIN_MODE) + else if(gain_mode == HIGH_GAIN_MODE) return 0.21229; else return 0; @@ -370,73 +295,56 @@ double M2kAdc::gainAt(GainMode gain_mode) const QPair M2kAdc::inputRange(GainMode gain_mode) const { - if (gain_mode == LOW_GAIN_MODE) + if(gain_mode == LOW_GAIN_MODE) return QPair(-25.0, 25.0); - else if (gain_mode == HIGH_GAIN_MODE) + else if(gain_mode == HIGH_GAIN_MODE) return QPair(-2.5, 2.5); else return QPair(0, 0); } -QList M2kAdc::availSamplRates() const -{ - return m_availSampRates; -} +QList M2kAdc::availSamplRates() const { return m_availSampRates; } -double M2kAdc::maxSampleRate() const -{ - return max_sample_rate; -} +double M2kAdc::maxSampleRate() const { return max_sample_rate; } -double M2kAdc::compTable(double samplRate) const -{ - return m_filt_comp_table.at(samplRate); -} +double M2kAdc::compTable(double samplRate) const { return m_filt_comp_table.at(samplRate); } void M2kAdc::setSampleRate(double sr) { m2k_sample_rate = sr; - if(filteringEnabled()) - { + if(filteringEnabled()) { GenericAdc::setSampleRate(sr); setOversamplingRatio(1); - } - else - { + } else { GenericAdc::setSampleRate(maxSampleRate()); - setOversamplingRatio(maxSampleRate()/sr); + setOversamplingRatio(maxSampleRate() / sr); } } -double M2kAdc::readSampleRate() const -{ - return m2k_sample_rate; -} +double M2kAdc::readSampleRate() const { return m2k_sample_rate; } double M2kAdc::convSampleToVolts(uint chnIdx, double sample) const { double hw_gain = gainAt(m_chn_hw_gain_modes[chnIdx]); - return (((sample * 0.78) / ((1 << (numAdcBits() - 1)) * 1.3 * - hw_gain)) * m_chn_corr_gains[chnIdx] * - m_filt_comp_table.at(sampleRate())) - m_chn_hw_offsets[chnIdx]; + return (((sample * 0.78) / ((1 << (numAdcBits() - 1)) * 1.3 * hw_gain)) * m_chn_corr_gains[chnIdx] * + m_filt_comp_table.at(sampleRate())) - + m_chn_hw_offsets[chnIdx]; } double M2kAdc::convVoltsToSample(uint chnIdx, double volts) const { double hw_gain = gainAt(m_chn_hw_gain_modes[chnIdx]); - return (volts + m_chn_hw_offsets[chnIdx]) / (m_chn_corr_gains[chnIdx] * - m_filt_comp_table.at(sampleRate())) * ((1 << (numAdcBits() - 1)) - * 1.3 * hw_gain) / 0.78; + return (volts + m_chn_hw_offsets[chnIdx]) / (m_chn_corr_gains[chnIdx] * m_filt_comp_table.at(sampleRate())) * + ((1 << (numAdcBits() - 1)) * 1.3 * hw_gain) / 0.78; } double M2kAdc::convSampleDiffToVoltsDiff(uint chnIdx, double smp) const { double hw_gain = gainAt(m_chn_hw_gain_modes[chnIdx]); - return (smp * 0.78) / ((1 << (numAdcBits() - 1)) * 1.3 * - hw_gain) * m_chn_corr_gains[chnIdx] * + return (smp * 0.78) / ((1 << (numAdcBits() - 1)) * 1.3 * hw_gain) * m_chn_corr_gains[chnIdx] * m_filt_comp_table.at(sampleRate()); } @@ -444,9 +352,8 @@ double M2kAdc::convVoltsDiffToSampleDiff(uint chnIdx, double v) const { double hw_gain = gainAt(m_chn_hw_gain_modes[chnIdx]); - return v / (m_chn_corr_gains[chnIdx] * - m_filt_comp_table.at(sampleRate())) * ((1 << (numAdcBits() - 1)) - * 1.3 * hw_gain) / 0.78; + return v / (m_chn_corr_gains[chnIdx] * m_filt_comp_table.at(sampleRate())) * + ((1 << (numAdcBits() - 1)) * 1.3 * hw_gain) / 0.78; } GenericAdc::settings_uptr M2kAdc::getCurrentHwSettings() @@ -456,7 +363,7 @@ GenericAdc::settings_uptr M2kAdc::getCurrentHwSettings() M2KSettings *m2k_settings = new M2KSettings; *(Settings *)m2k_settings = *gsettings_uptr; - for (size_t i = 0; i < numAdcChannels(); i++) { + for(size_t i = 0; i < numAdcChannels(); i++) { m2k_settings->channel_hw_gain_mode.push_back(chnHwGainMode(i)); m2k_settings->channel_hw_offset.push_back(chnHwOffset(i)); } @@ -469,10 +376,9 @@ void M2kAdc::setHwSettings(GenericAdc::Settings *settings) GenericAdc::setHwSettings(settings); M2KSettings *m2k_settings = dynamic_cast(settings); - if (m2k_settings) { - for (size_t i = 0; i < numAdcChannels(); i++) { - setChnHwGainMode(i, - m2k_settings->channel_hw_gain_mode[i]); + if(m2k_settings) { + for(size_t i = 0; i < numAdcChannels(); i++) { + setChnHwGainMode(i, m2k_settings->channel_hw_gain_mode[i]); setChnHwOffset(i, m2k_settings->channel_hw_offset[i]); } } @@ -481,33 +387,25 @@ void M2kAdc::setHwSettings(GenericAdc::Settings *settings) void M2kAdc::setFilteringEnabled(bool set) { filtering_enabled = set; - if(set == false) - { + if(set == false) { GenericAdc::setSampleRate(maxSampleRate()); - setOversamplingRatio(maxSampleRate()/m2k_sample_rate); - } - else - { + setOversamplingRatio(maxSampleRate() / m2k_sample_rate); + } else { GenericAdc::setSampleRate(m2k_sample_rate); setOversamplingRatio(1); } } -bool M2kAdc::filteringEnabled() const -{ - return filtering_enabled; -} +bool M2kAdc::filteringEnabled() const { return filtering_enabled; } uint32_t M2kAdc::oversamplingRatio() const { long long int val; - iio_device_attr_read_longlong(m_adc, - "oversampling_ratio", &val); + iio_device_attr_read_longlong(m_adc, "oversampling_ratio", &val); return val; } void M2kAdc::setOversamplingRatio(uint32_t ratio) const { - iio_device_attr_write_longlong(m_adc, - "oversampling_ratio", ratio); + iio_device_attr_write_longlong(m_adc, "oversampling_ratio", ratio); } diff --git a/plugins/m2k/src/old/osc_adc.h b/plugins/m2k/src/old/osc_adc.h index eaaf3b014f..575f93f63a 100644 --- a/plugins/m2k/src/old/osc_adc.h +++ b/plugins/m2k/src/old/osc_adc.h @@ -21,12 +21,14 @@ #define OSC_ADC_H #include -#include #include +#include + #include #include -extern "C" { +extern "C" +{ struct iio_context; struct iio_device; struct iio_channel; @@ -39,19 +41,18 @@ class HardwareTrigger; class IioUtils { public: - static QStringList available_options_list(struct iio_device *dev, - const char *attr_name); - static QList scan_elem_channel_list( - struct iio_device *dev); - static QList pick_channels_with_direction( - const QList& list, bool output); + static QStringList available_options_list(struct iio_device *dev, const char *attr_name); + static QList scan_elem_channel_list(struct iio_device *dev); + static QList pick_channels_with_direction(const QList &list, + bool output); static std::string hardware_revision(struct iio_context *); }; class GenericAdc { public: - struct Settings { + struct Settings + { double sample_rate; virtual ~Settings() {} @@ -63,8 +64,8 @@ class GenericAdc GenericAdc(struct iio_context *ctx, struct iio_device *adc_dev); virtual ~GenericAdc(); - struct iio_context * iio_context() const; - struct iio_device * iio_adc_dev() const; + struct iio_context *iio_context() const; + struct iio_device *iio_adc_dev() const; std::shared_ptr getTrigger() const; uint numAdcChannels() const; @@ -77,7 +78,7 @@ class GenericAdc virtual double convSampleToVolts(uint chnIdx, double sample) const; virtual double convVoltsToSample(uint chnIdx, double volts) const; - virtual double convSampleDiffToVoltsDiff(uint chnIdx, double smpl)const; + virtual double convSampleDiffToVoltsDiff(uint chnIdx, double smpl) const; virtual double convVoltsDiffToSampleDiff(uint chnIdx, double v) const; virtual std::unique_ptr getCurrentHwSettings(); @@ -89,27 +90,27 @@ class GenericAdc struct iio_device *m_adc; QList m_adc_channels; - private: uint m_adc_bits; double m_sample_rate; }; -class M2kAdc: public GenericAdc +class M2kAdc : public GenericAdc { public: - enum GainMode { + enum GainMode + { LOW_GAIN_MODE = 0, HIGH_GAIN_MODE = 1, }; - struct M2KSettings: public Settings { + struct M2KSettings : public Settings + { QList channel_hw_gain_mode; QList channel_hw_offset; }; public: - M2kAdc(struct iio_context *, struct iio_device *adc_dev); ~M2kAdc(); @@ -124,7 +125,7 @@ class M2kAdc: public GenericAdc double chnHwOffset(uint chnIdx) const; void setChnHwOffset(uint chnIdx, double offset); - GainMode chnHwGainMode(uint chnIdx) const; + GainMode chnHwGainMode(uint chnIdx) const; void setChnHwGainMode(uint chnIdx, GainMode gain_mode); double gainAt(GainMode gain_mode) const; @@ -154,7 +155,7 @@ class M2kAdc: public GenericAdc QList m_offset_channels; QList m_gain_channels; - QList m_availSampRates; + QList m_availSampRates; std::map m_filt_comp_table; QList m_chn_corr_offsets; QList m_chn_corr_gains; @@ -163,23 +164,24 @@ class M2kAdc: public GenericAdc bool filtering_enabled; double max_sample_rate; double m2k_sample_rate; - }; class AdcBuilder { public: - enum AdcType { + enum AdcType + { GENERIC = 0, M2K = 1, }; - static std::shared_ptr newAdc(AdcType adc_type, - struct iio_context *ctx, struct iio_device *adc) + static std::shared_ptr newAdc(AdcType adc_type, struct iio_context *ctx, struct iio_device *adc) { - switch (adc_type) { - case GENERIC: return std::make_shared(ctx, adc); - case M2K: return std::make_shared(ctx, adc); + switch(adc_type) { + case GENERIC: + return std::make_shared(ctx, adc); + case M2K: + return std::make_shared(ctx, adc); } return nullptr; } diff --git a/plugins/m2k/src/old/osc_capture_params.cpp b/plugins/m2k/src/old/osc_capture_params.cpp index 3ca46136f5..949ab8761a 100644 --- a/plugins/m2k/src/old/osc_capture_params.cpp +++ b/plugins/m2k/src/old/osc_capture_params.cpp @@ -20,33 +20,30 @@ #include "osc_capture_params.hpp" -#include #include +#include + /* * Class SymmetricBufferMode implementation */ -SymmetricBufferMode::SymmetricBufferMode() : - m_sampleRates(), - m_entireBufferMaxSize(0), - m_triggerBufferMaxSize(0), - m_timeBase(0.0), - m_triggerPos(0.0), - m_sampleRate(0.0), - m_triggPosSR(0.0), - m_visibleBufferSize(0), - m_triggerBufferSize(0), - m_enhancedMemoryDepth(false), - m_timeDivsCount(10) -{ -} - -SymmetricBufferMode::~SymmetricBufferMode() -{ -} - -SymmetricBufferMode::capture_parameters -SymmetricBufferMode::captureParameters() const +SymmetricBufferMode::SymmetricBufferMode() + : m_sampleRates() + , m_entireBufferMaxSize(0) + , m_triggerBufferMaxSize(0) + , m_timeBase(0.0) + , m_triggerPos(0.0) + , m_sampleRate(0.0) + , m_triggPosSR(0.0) + , m_visibleBufferSize(0) + , m_triggerBufferSize(0) + , m_enhancedMemoryDepth(false) + , m_timeDivsCount(10) +{} + +SymmetricBufferMode::~SymmetricBufferMode() {} + +SymmetricBufferMode::capture_parameters SymmetricBufferMode::captureParameters() const { struct capture_parameters params; double sampleRate; @@ -57,7 +54,7 @@ SymmetricBufferMode::captureParameters() const sampleRate = qMin(m_sampleRate, m_triggPosSR); // If trigger position altered the buffer size, return the altered one - if (m_triggerBufferSize >= 0) { + if(m_triggerBufferSize >= 0) { bufferSize = qMax(m_visibleBufferSize, (unsigned long)m_triggerBufferSize); } else { bufferSize = m_visibleBufferSize; @@ -76,30 +73,21 @@ SymmetricBufferMode::captureParameters() const return params; } -void SymmetricBufferMode::setSampleRates(const std::vector& sampleRates) +void SymmetricBufferMode::setSampleRates(const std::vector &sampleRates) { m_sampleRates = sampleRates; std::sort(m_sampleRates.begin(), m_sampleRates.end()); } -void SymmetricBufferMode::setEntireBufferMaxSize(unsigned long maxSize) -{ - m_entireBufferMaxSize = maxSize; -} +void SymmetricBufferMode::setEntireBufferMaxSize(unsigned long maxSize) { m_entireBufferMaxSize = maxSize; } -void SymmetricBufferMode::setTriggerBufferMaxSize(unsigned long maxSize) -{ - m_triggerBufferMaxSize = maxSize; -} +void SymmetricBufferMode::setTriggerBufferMaxSize(unsigned long maxSize) { m_triggerBufferMaxSize = maxSize; } -void SymmetricBufferMode::setTimeDivisionCount(int count) -{ - m_timeDivsCount = count; -} +void SymmetricBufferMode::setTimeDivisionCount(int count) { m_timeDivsCount = count; } void SymmetricBufferMode::setTimeBase(double secsPerDiv) { - if ((m_timeBase != secsPerDiv) || m_enhancedMemoryDepth) { + if((m_timeBase != secsPerDiv) || m_enhancedMemoryDepth) { m_timeBase = secsPerDiv; configParamsOnTimeBaseChanged(); } @@ -111,19 +99,13 @@ void SymmetricBufferMode::setCustomBufferSize(unsigned long customSize) configParamsOnCustomSizeChanged(); } -bool SymmetricBufferMode::isEnhancedMemDepth() -{ - return m_enhancedMemoryDepth; -} +bool SymmetricBufferMode::isEnhancedMemDepth() { return m_enhancedMemoryDepth; } -void SymmetricBufferMode::setEnhancedMemDepth(bool val) -{ - m_enhancedMemoryDepth = val; -} +void SymmetricBufferMode::setEnhancedMemDepth(bool val) { m_enhancedMemoryDepth = val; } void SymmetricBufferMode::setTriggerPos(double pos) { - if (m_triggerPos != pos) { + if(m_triggerPos != pos) { m_triggerPos = pos; configParamsOnTriggPosChanged(); } @@ -141,15 +123,14 @@ void SymmetricBufferMode::configParamsOnTimeBaseChanged() m_availableBufferSizes.clear(); unsigned long bufferSize = getVisibleBufferSize(sampleRate); - while ((m_triggerBufferMaxSize < bufferSize) && (ratesIt != - m_sampleRates.rend() - 1)) { - if (bufferSize <= m_entireBufferMaxSize) { + while((m_triggerBufferMaxSize < bufferSize) && (ratesIt != m_sampleRates.rend() - 1)) { + if(bufferSize <= m_entireBufferMaxSize) { m_availableBufferSizes.insert(m_availableBufferSizes.begin(), bufferSize); } sampleRate = *(++ratesIt); bufferSize = getVisibleBufferSize(sampleRate); } - if (bufferSize <= m_entireBufferMaxSize) { + if(bufferSize <= m_entireBufferMaxSize) { m_availableBufferSizes.insert(m_availableBufferSizes.begin(), bufferSize); } @@ -159,22 +140,20 @@ void SymmetricBufferMode::configParamsOnTimeBaseChanged() long long triggOffset = bufferSize / 2; // Make sure trigg pos stays inside the boundaries of the entire buffer - long long triggPosInBuffer = qRound64(m_triggerPos * sampleRate) + - triggOffset; + long long triggPosInBuffer = qRound64(m_triggerPos * sampleRate) + triggOffset; long long trigBuffSize = triggPosInBuffer; - if (triggPosInBuffer < 0) { - bufferSize = qRound64(qAbs(m_triggerPos) * sampleRate) + - triggOffset; + if(triggPosInBuffer < 0) { + bufferSize = qRound64(qAbs(m_triggerPos) * sampleRate) + triggOffset; - if (bufferSize > m_entireBufferMaxSize) { + if(bufferSize > m_entireBufferMaxSize) { trigBuffSize = -(bufferSize - m_entireBufferMaxSize); bufferSize = m_entireBufferMaxSize; } else { trigBuffSize = 0; } - } else if (triggPosInBuffer > m_triggerBufferMaxSize) { + } else if(triggPosInBuffer > m_triggerBufferMaxSize) { triggPosInBuffer = m_triggerBufferMaxSize; trigBuffSize = triggPosInBuffer; } @@ -192,7 +171,7 @@ double SymmetricBufferMode::getSamplerateFor(unsigned long buffersize) auto ratesIt = m_sampleRates.begin(); double sampleRate = *ratesIt; - while ( sampleRate < desiredSamplrate && (ratesIt != m_sampleRates.end() - 1)) { + while(sampleRate < desiredSamplrate && (ratesIt != m_sampleRates.end() - 1)) { sampleRate = *(++ratesIt); } return sampleRate; @@ -204,14 +183,13 @@ void SymmetricBufferMode::configParamsOnCustomSizeChanged() m_triggerBufferSize = m_triggerBufferMaxSize; m_triggPosSR = m_sampleRate; /* Move trigger to left such that we have 8192 before the trigger */ - m_triggerPos = (m_timeBase * m_timeDivsCount / 2) - (m_triggerBufferMaxSize/m_sampleRate); + m_triggerPos = (m_timeBase * m_timeDivsCount / 2) - (m_triggerBufferMaxSize / m_sampleRate); m_enhancedMemoryDepth = true; } - void SymmetricBufferMode::configParamsOnTriggPosChanged() { - if (m_enhancedMemoryDepth) + if(m_enhancedMemoryDepth) return; double bufferSize; @@ -222,19 +200,17 @@ void SymmetricBufferMode::configParamsOnTriggPosChanged() // edge of the plot long long triggOffset = m_visibleBufferSize / 2; - long long triggPosInBuffer = qRound64(m_triggerPos * m_sampleRate) + - triggOffset; + long long triggPosInBuffer = qRound64(m_triggerPos * m_sampleRate) + triggOffset; m_triggPosSR = m_sampleRate; - if (triggPosInBuffer < 0) { + if(triggPosInBuffer < 0) { unsigned long delaySamples = -triggPosInBuffer; - bufferSize = (m_timeBase * m_timeDivsCount) * - m_sampleRate + delaySamples; + bufferSize = (m_timeBase * m_timeDivsCount) * m_sampleRate + delaySamples; m_triggerBufferSize = 0; // Limit buffer size and recalculate trigger position - if (bufferSize > m_entireBufferMaxSize) { + if(bufferSize > m_entireBufferMaxSize) { /* Delayed acquisition */ m_triggerBufferSize = -(bufferSize - m_entireBufferMaxSize); bufferSize = m_entireBufferMaxSize; @@ -246,16 +222,13 @@ void SymmetricBufferMode::configParamsOnTriggPosChanged() } // Find the highest sample rate that can be set based on trigger pos - auto ratesIt = find(m_sampleRates.rbegin(), m_sampleRates.rend(), - m_sampleRate); - while ((triggPosInBuffer > m_triggerBufferMaxSize) && (ratesIt < - m_sampleRates.rend() - 1)) { + auto ratesIt = find(m_sampleRates.rbegin(), m_sampleRates.rend(), m_sampleRate); + while((triggPosInBuffer > m_triggerBufferMaxSize) && (ratesIt < m_sampleRates.rend() - 1)) { m_triggPosSR = *(++ratesIt); // New sample rate -> new buffer size m_visibleBufferSize = getVisibleBufferSize(m_triggPosSR); triggOffset = m_visibleBufferSize / 2; - triggPosInBuffer = qRound64(m_triggerPos * m_triggPosSR) + - triggOffset; + triggPosInBuffer = qRound64(m_triggerPos * m_triggPosSR) + triggOffset; } m_triggerBufferSize = triggPosInBuffer; } diff --git a/plugins/m2k/src/old/osc_capture_params.hpp b/plugins/m2k/src/old/osc_capture_params.hpp index af73d2c763..e781a05047 100644 --- a/plugins/m2k/src/old/osc_capture_params.hpp +++ b/plugins/m2k/src/old/osc_capture_params.hpp @@ -26,7 +26,8 @@ class OscCaptureParams { public: - struct capture_parameters { + struct capture_parameters + { double sampleRate; double timePos; unsigned long entireBufferSize; @@ -42,7 +43,7 @@ class OscCaptureParams virtual void setTriggerPos(double pos) = 0; }; -class SymmetricBufferMode: public OscCaptureParams +class SymmetricBufferMode : public OscCaptureParams { public: SymmetricBufferMode(); @@ -50,7 +51,7 @@ class SymmetricBufferMode: public OscCaptureParams capture_parameters captureParameters() const; - void setSampleRates(const std::vector& sampleRates); + void setSampleRates(const std::vector &sampleRates); void setEntireBufferMaxSize(unsigned long maxSize); void setTriggerBufferMaxSize(unsigned long maxSize); void setTimeDivisionCount(int count); diff --git a/plugins/m2k/src/old/oscilloscope.cpp b/plugins/m2k/src/old/oscilloscope.cpp index 915a540d11..7369ce0900 100644 --- a/plugins/m2k/src/old/oscilloscope.cpp +++ b/plugins/m2k/src/old/oscilloscope.cpp @@ -18,28 +18,27 @@ * along with this program. If not, see . */ - /* GNU Radio includes */ #include -#include -#include -#include -#include #include -#include -#include #include +#include +#include +#include +#include +#include +#include /* Qt includes */ -#include -#include -#include -#include -#include #include +#include #include #include +#include +#include #include +#include +#include /* libm2k includes */ #include @@ -47,45 +46,45 @@ /* Local includes */ #include "adc_sample_conv.hpp" +#include "buffer_previewer.hpp" +#include "filemanager.h" +#include "gui/channel_widget.hpp" #include "gui/customPushButton.h" -#include "oscilloscope.hpp" +#include "gui/customplotpositionbutton.h" #include "gui/dynamicWidget.h" +#include "gui/runsinglewidget.h" #include "m2kmeasurement_gui.h" +#include "m2kpluginExceptionHandler.h" #include "measure_settings.h" -#include "statistic_widget.h" -#include "state_updater.h" +#include "mixed_signal_sink.h" #include "osc_capture_params.hpp" -#include "buffer_previewer.hpp" -#include "gui/customplotpositionbutton.h" -#include "gui/channel_widget.hpp" -#include "signal_sample.hpp" -#include "filemanager.h" -#include "m2kpluginExceptionHandler.h" +#include "oscilloscope.hpp" #include "oscilloscope_api.hpp" -#include "mixed_signal_sink.h" - -#include "gui/runsinglewidget.h" +#include "signal_sample.hpp" +#include "state_updater.h" +#include "statistic_widget.h" /* Generated UI */ #include "ui_channel_settings.h" +#include "ui_cursor_readouts.h" #include "ui_cursors_settings.h" -#include "ui_osc_general_settings.h" #include "ui_measure_panel.h" #include "ui_measure_settings.h" -#include "ui_statistics_panel.h" -#include "ui_cursor_readouts.h" +#include "ui_osc_general_settings.h" #include "ui_oscilloscope.h" +#include "ui_statistics_panel.h" #include "ui_trigger_settings.h" -#include -#include -#include -#include #include #include -Q_LOGGING_CATEGORY(CAT_M2K_OSCILLOSCOPE,"M2kOscilloscope"); +#include +#include +#include +#include + +Q_LOGGING_CATEGORY(CAT_M2K_OSCILLOSCOPE, "M2kOscilloscope"); #define MAX_MATH_CHANNELS 4 #define MAX_MATH_RANGE SHRT_MAX @@ -106,75 +105,75 @@ using namespace std::placeholders; constexpr int MAX_BUFFER_SIZE_STREAM = 1024 * 1024; constexpr int MAX_KERNEL_BUFFERS = 64; -Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, - ToolMenuEntry *tme, m2k_iio_manager* m2k_man, - QJSEngine *engine, QWidget *parent) : - M2kTool(ctx, tme, new Oscilloscope_API(this), "Oscilloscope", parent), - m_m2k_context(m2kOpen(ctx, "")), - m_m2k_analogin(m_m2k_context->getAnalogIn()), - m_m2k_digital(m_m2k_context->getDigital()), - nb_channels(m_m2k_analogin->getNbChannels()), - active_sample_rate(getSampleRate()), - nb_math_channels(0), - ui(new Ui::Oscilloscope), - trigger_settings(m_m2k_analogin), - measure_settings(nullptr), - plot(this, false, 16, 10, new TimePrefixFormatter, new MetricPrefixFormatter), - fft_plot(nb_channels, this), - xy_plot(nb_channels / 2, this), - hist_plot(nb_channels, this), - ids(new iio_manager::port_id[nb_channels]), - autoset_id(new iio_manager::port_id), - hist_ids(new iio_manager::port_id[nb_channels]), - fft_is_visible(false), hist_is_visible(false), xy_is_visible(false), - statistics_enabled(false), - trigger_is_forced(false), - new_data_is_triggered(false), - triggerUpdater(new StateUpdater(250, this)), - current_channel(-1), math_chn_counter(0), - channels_group(new QButtonGroup(this)), - zoom_level(0), - current_ch_widget(-1), - addChannel(true), - index_x(0), - index_y(1), - ftc(nullptr), - locked(false), - triggerAcCoupled(false), - autosetRequested(false), - autosetEnabled(true), - memory_adjusted_time_pos(0), - plot_samples_sequentially(false), - d_displayOneBuffer(true), - nb_ref_channels(0), - lastFunctionValid(false), - import_error(""), - hCursorsEnabled(true), - vCursorsEnabled(true), - horiz_offset(0), - reset_horiz_offset(true), - wheelEventGuard(nullptr), - miniHistogram(true), - gatingEnabled(false), - m_filtering_enabled(true), - m_logicAnalyzer(nullptr), - m_mixedSignalViewEnabled(false), - logic_top_block(nullptr) +Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, m2k_iio_manager *m2k_man, + QJSEngine *engine, QWidget *parent) + : M2kTool(ctx, tme, new Oscilloscope_API(this), "Oscilloscope", parent) + , m_m2k_context(m2kOpen(ctx, "")) + , m_m2k_analogin(m_m2k_context->getAnalogIn()) + , m_m2k_digital(m_m2k_context->getDigital()) + , nb_channels(m_m2k_analogin->getNbChannels()) + , active_sample_rate(getSampleRate()) + , nb_math_channels(0) + , ui(new Ui::Oscilloscope) + , trigger_settings(m_m2k_analogin) + , measure_settings(nullptr) + , plot(this, false, 16, 10, new TimePrefixFormatter, new MetricPrefixFormatter) + , fft_plot(nb_channels, this) + , xy_plot(nb_channels / 2, this) + , hist_plot(nb_channels, this) + , ids(new iio_manager::port_id[nb_channels]) + , autoset_id(new iio_manager::port_id) + , hist_ids(new iio_manager::port_id[nb_channels]) + , fft_is_visible(false) + , hist_is_visible(false) + , xy_is_visible(false) + , statistics_enabled(false) + , trigger_is_forced(false) + , new_data_is_triggered(false) + , triggerUpdater(new StateUpdater(250, this)) + , current_channel(-1) + , math_chn_counter(0) + , channels_group(new QButtonGroup(this)) + , zoom_level(0) + , current_ch_widget(-1) + , addChannel(true) + , index_x(0) + , index_y(1) + , ftc(nullptr) + , locked(false) + , triggerAcCoupled(false) + , autosetRequested(false) + , autosetEnabled(true) + , memory_adjusted_time_pos(0) + , plot_samples_sequentially(false) + , d_displayOneBuffer(true) + , nb_ref_channels(0) + , lastFunctionValid(false) + , import_error("") + , hCursorsEnabled(true) + , vCursorsEnabled(true) + , horiz_offset(0) + , reset_horiz_offset(true) + , wheelEventGuard(nullptr) + , miniHistogram(true) + , gatingEnabled(false) + , m_filtering_enabled(true) + , m_logicAnalyzer(nullptr) + , m_mixedSignalViewEnabled(false) + , logic_top_block(nullptr) { ui->setupUi(this); int triggers_panel = ui->stackedWidget->insertWidget(-1, &trigger_settings); - if (m_m2k_analogin) { + if(m_m2k_analogin) { symmBufferMode = make_shared(); symmBufferMode->setSampleRates(m_m2k_analogin->getAvailableSampleRates()); symmBufferMode->setEntireBufferMaxSize(MAX_BUFFER_SIZE_STREAM); symmBufferMode->setTriggerBufferMaxSize(8192); // 8192 is what hardware supports symmBufferMode->setTimeDivisionCount(plot.xAxisNumDiv()); } - dc_cancel.push_back(gnuradio::get_initial_sptr( - new cancel_dc_offset_block(1, true))); - dc_cancel.push_back(gnuradio::get_initial_sptr( - new cancel_dc_offset_block(1, true))); + dc_cancel.push_back(gnuradio::get_initial_sptr(new cancel_dc_offset_block(1, true))); + dc_cancel.push_back(gnuradio::get_initial_sptr(new cancel_dc_offset_block(1, true))); /* Measurements Settings */ measure_settings_init(); @@ -191,17 +190,15 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, /* Gnuradio Blocks */ - this->qt_time_block = scope_sink_f::make(1024, active_sample_rate, - "Osc Time", nb_channels, (QObject *)&plot); + this->qt_time_block = scope_sink_f::make(1024, active_sample_rate, "Osc Time", nb_channels, (QObject *)&plot); - this->qt_fft_block = scope_sink_f::make(fft_plot_size, active_sample_rate, - "Osc Frequency", nb_channels, (QObject *)&fft_plot); + this->qt_fft_block = scope_sink_f::make(fft_plot_size, active_sample_rate, "Osc Frequency", nb_channels, + (QObject *)&fft_plot); - this->qt_hist_block = histogram_sink_f::make(1024, 250, 0, 20, - "Osc Histogram", nb_channels, (QObject *)&hist_plot); + this->qt_hist_block = + histogram_sink_f::make(1024, 250, 0, 20, "Osc Histogram", nb_channels, (QObject *)&hist_plot); - this->qt_xy_block = xy_sink_c::make( - 400, "Osc XY", nb_channels / 2, (QObject*)&xy_plot); + this->qt_xy_block = xy_sink_c::make(400, "Osc XY", nb_channels / 2, (QObject *)&xy_plot); this->qt_time_block->set_trigger_mode(TRIG_MODE_TAG, 0, "buffer_start"); @@ -210,10 +207,10 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, Preferences *p = Preferences::GetInstance(); double targetFps = p->get("general_plot_target_fps").toDouble(); - qt_time_block->set_update_time(1.0/targetFps); - qt_fft_block->set_update_time(1.0/targetFps); - qt_hist_block->set_update_time(1.0/targetFps); - qt_xy_block->set_update_time(1.0/targetFps); + qt_time_block->set_update_time(1.0 / targetFps); + qt_fft_block->set_update_time(1.0 / targetFps); + qt_hist_block->set_update_time(1.0 / targetFps); + qt_xy_block->set_update_time(1.0 / targetFps); // Prevent the application from hanging while waiting for a trigger condition m_m2k_context->setTimeout(UINT_MAX); @@ -223,45 +220,39 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, fft_plot.disableLegend(); fft_plot.setXaxisMouseGesturesEnabled(false); - for (uint i = 0; i < nb_channels; i++) + for(uint i = 0; i < nb_channels; i++) fft_plot.setYaxisMouseGesturesEnabled(i, false); - iio = m2k_man->get_instance(ctx, - filt->device_name(TOOL_OSCILLOSCOPE)); + iio = m2k_man->get_instance(ctx, filt->device_name(TOOL_OSCILLOSCOPE)); gr::hier_block2_sptr hier = iio->to_hier_block2(); qDebug(CAT_M2K_OSCILLOSCOPE) << "Manager created:\n" << gr::dot_graph(hier).c_str(); - for (unsigned int i = 0; i < nb_channels; i++) { + for(unsigned int i = 0; i < nb_channels; i++) { string name = "Channel " + to_string(i + 1); - ChannelWidget *ch_widget = new ChannelWidget(i, false, false, - plot.getLineColor(i).name(), this); + ChannelWidget *ch_widget = new ChannelWidget(i, false, false, plot.getLineColor(i).name(), this); ch_widget->setFullName(name.c_str()); ch_widget->setShortName(QString("CH %1").arg(i + 1)); ch_widget->nameButton()->setText(ch_widget->shortName()); - connect(ch_widget, SIGNAL(enabled(bool)), - SLOT(onChannelWidgetEnabled(bool))); - connect(ch_widget, SIGNAL(selected(bool)), - SLOT(onChannelWidgetSelected(bool))); - connect(&plot, SIGNAL(channelSelected(int, bool)), - this, SLOT(selectChannel(int, bool))); - connect(ch_widget, SIGNAL(menuToggled(bool)), - SLOT(onChannelWidgetMenuToggled(bool))); + connect(ch_widget, SIGNAL(enabled(bool)), SLOT(onChannelWidgetEnabled(bool))); + connect(ch_widget, SIGNAL(selected(bool)), SLOT(onChannelWidgetSelected(bool))); + connect(&plot, SIGNAL(channelSelected(int, bool)), this, SLOT(selectChannel(int, bool))); + connect(ch_widget, SIGNAL(menuToggled(bool)), SLOT(onChannelWidgetMenuToggled(bool))); ui->channelsList->addWidget(ch_widget); channels_group->addButton(ch_widget->nameButton()); ui->settings_group->addButton(ch_widget->menuButton()); - QLabel *label= new QLabel(this); - label->setText(vertMeasureFormat.format( - plot.VertUnitsPerDiv(i), "V/div", 3)); + QLabel *label = new QLabel(this); + label->setText(vertMeasureFormat.format(plot.VertUnitsPerDiv(i), "V/div", 3)); label->setStyleSheet(QString("QLabel {" - "color: %1;" - "font-weight: bold;" - "}").arg(plot.getLineColor(i).name())); + "color: %1;" + "font-weight: bold;" + "}") + .arg(plot.getLineColor(i).name())); ui->chn_scales->addWidget(label); high_gain_modes.push_back(false); @@ -270,11 +261,9 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, channels_api.append(new Channel_API(this)); } - triggerLevelSink = QPair, int>( - nullptr, -1); + triggerLevelSink = QPair, int>(nullptr, -1); - connect(ui->rightMenu, SIGNAL(finished(bool)), this, - SLOT(rightMenuFinished(bool))); + connect(ui->rightMenu, SIGNAL(finished(bool)), this, SLOT(rightMenuFinished(bool))); /* Cursors Settings */ const int cursor_settings = ui->stackedWidget->indexOf(ui->cursorsSettings); @@ -286,10 +275,9 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, /* Trigger Status Updater */ triggerUpdater->setOffState(CapturePlot::Stop); onTriggerModeChanged(trigger_settings.triggerMode()); - connect(triggerUpdater, SIGNAL(outputChanged(int)), - &plot, SLOT(setTriggerState(int))); + connect(triggerUpdater, SIGNAL(outputChanged(int)), &plot, SLOT(setTriggerState(int))); - //plot.setZoomerEnabled(true); + // plot.setZoomerEnabled(true); fft_plot.setZoomerEnabled(); create_add_channel_panel(); @@ -297,28 +285,26 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, /* Lock the flowgraph if we are already started */ bool started = isIioManagerStarted(); - if (started) + if(started) iio->lock(); auto adc_samp_conv = new adc_sample_conv(nb_channels, m_m2k_analogin); adc_samp_conv_block = gnuradio::get_initial_sptr(adc_samp_conv); - - for (unsigned int i = 0; i < nb_channels; i++) { - ids[i] = iio->connect(adc_samp_conv_block, i, i, - true, qt_time_block->nsamps()); + for(unsigned int i = 0; i < nb_channels; i++) { + ids[i] = iio->connect(adc_samp_conv_block, i, i, true, qt_time_block->nsamps()); iio->connect(adc_samp_conv_block, i, qt_time_block, i); iio->connect(adc_samp_conv_block, i, qt_hist_block, i); } - const std::function fp = std::bind( - &adc_sample_conv::conversionWrapper, adc_samp_conv, - std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); + const std::function fp = + std::bind(&adc_sample_conv::conversionWrapper, adc_samp_conv, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3); plot.setConversionFunction(fp); - if (started) + if(started) iio->unlock(); /* Measure panel */ @@ -339,10 +325,9 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, buffer_previewer->setCursorPos(0.5); - // Build central widget - QWidget* centralWidget = new QWidget(this); - QVBoxLayout* vLayout = new QVBoxLayout(centralWidget); + QWidget *centralWidget = new QWidget(this); + QVBoxLayout *vLayout = new QVBoxLayout(centralWidget); vLayout->setContentsMargins(0, 0, 0, 0); vLayout->setSpacing(0); @@ -351,15 +336,14 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, vLayout->addWidget(ui->hLayoutBufferPreview); // add plot elements - QWidget* plotWidget = new QWidget(this); + QWidget *plotWidget = new QWidget(this); gridPlot = new QGridLayout(plotWidget); gridPlot->setVerticalSpacing(0); gridPlot->setHorizontalSpacing(0); gridPlot->setContentsMargins(9, 0, 9, 0); plotWidget->setLayout(gridPlot); - QSpacerItem *plotSpacer = new QSpacerItem(0, 5, - QSizePolicy::Fixed, QSizePolicy::Fixed); + QSpacerItem *plotSpacer = new QSpacerItem(0, 5, QSizePolicy::Fixed, QSizePolicy::Fixed); gridPlot->addWidget(measurePanel, 0, 1, 1, 1); gridPlot->addWidget(plot.topArea(), 1, 0, 1, 4); @@ -395,14 +379,13 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, ui->histogram_container->hide(); // main window for all dock widgets - QMainWindow* mainWindow = new QMainWindow(this); + QMainWindow *mainWindow = new QMainWindow(this); mainWindow->setCentralWidget(0); mainWindow->setWindowFlags(Qt::Widget); ui->gridLayoutPlot->addWidget(mainWindow, 0, 0, 1, 1); // time domain plot dock - QDockWidget* plotDockWidget = DockerUtils::createDockWidget(mainWindow, centralWidget, "TimeDomain"); - + QDockWidget *plotDockWidget = DockerUtils::createDockWidget(mainWindow, centralWidget, "TimeDomain"); // necessary to move around the dockWidgets centralWidget->setMinimumHeight(50); @@ -414,22 +397,19 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, xy_plot.setMinimumHeight(50); xy_plot.setMinimumWidth(50); - // histogram widget histWidget = new QWidget(this); - QVBoxLayout* histLayout = new QVBoxLayout(histWidget); + QVBoxLayout *histLayout = new QVBoxLayout(histWidget); histWidget->setLayout(histLayout); // histogram dock histDockWidget = DockerUtils::createDockWidget(mainWindow, histWidget, "Histogram"); histDockWidget->hide(); - // fft dock fftDockWidget = DockerUtils::createDockWidget(mainWindow, &fft_plot, "FFT"); fftDockWidget->hide(); - // xy widget QWidget *xyWidget = new QWidget(this); QGridLayout *gridL = new QGridLayout(xyWidget); @@ -445,7 +425,6 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, xyDockWidget = DockerUtils::createDockWidget(mainWindow, xyWidget, "XY"); xyDockWidget->hide(); - // arange all dockers #ifdef __ANDROID__ mainWindow->addDockWidget(Qt::LeftDockWidgetArea, fftDockWidget); @@ -486,9 +465,9 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, fft_plot.setMinimumWidth(500); } - hist_plot.setMinimumHeight(60); - hist_plot.setMinimumWidth(25); - hist_plot.setMaximumWidth(25); + hist_plot.setMinimumHeight(60); + hist_plot.setMinimumWidth(25); + hist_plot.setMaximumWidth(25); // xy_plot.setMinimumHeight(50); // xy_plot.setMinimumWidth(50); @@ -498,13 +477,11 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, plot.setActiveVertAxis(0); started = isIioManagerStarted(); - if (started) + if(started) iio->lock(); - for (unsigned int i = 0; i < nb_channels; i++) { - plot.Curve(i)->setAxes( - QwtAxisId(QwtAxis::XBottom, 0), - QwtAxisId(QwtAxis::YLeft, i)); + for(unsigned int i = 0; i < nb_channels; i++) { + plot.Curve(i)->setAxes(QwtAxisId(QwtAxis::XBottom, 0), QwtAxisId(QwtAxis::YLeft, i)); plot.addZoomer(i); probe_attenuation.push_back(1); auto multiply = gr::blocks::multiply_const_ff::make(1); @@ -516,10 +493,9 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, plot.Curve(i)->setTitle("CH " + QString::number(i + 1)); } - if (started) + if(started) iio->unlock(); - plot.levelTriggerA()->setMobileAxis(QwtAxisId(QwtAxis::YLeft, 0)); plot.setTriggerAEnabled(trigger_settings.analogEnabled()); plot.levelTriggerA()->setPosition(trigger_settings.level()); @@ -539,7 +515,7 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, // Disable mouse interactions with the axes until we figure out if we want to use them xy_plot.setXaxisMouseGesturesEnabled(false); - for (uint i = 0; i < nb_channels; i++) + for(uint i = 0; i < nb_channels; i++) xy_plot.setYaxisMouseGesturesEnabled(i, false); xy_plot.setLineColor(0, QColor(0x4a64ff)); @@ -547,45 +523,25 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, ui->rightMenu->setMaximumWidth(0); // Controls for scale/division and position controls (Horizontal & Vertical) - timeBase = new ScaleSpinButton({ - {"ns", 1E-9}, - {"μs", 1E-6}, - {"ms", 1E-3}, - {"s", 1E0} - }, tr("Time Base"), 100e-9, 1E0, - true, false, this); - timePosition = new PositionSpinButton({ - {"ns", 1E-9}, - {"μs", 1E-6}, - {"ms", 1E-3}, - {"s", 1E0}, - {"min", 60E0}, - {"h", 36E2} - }, tr("Position"), - -timeBase->maxValue() * 5, - 36E3, - true, false, this); - voltsPerDiv = new ScaleSpinButton({ -// {"μVolts", 1E-6}, - {"mVolts", 1E-3}, - {"Volts", 1E0} - }, tr("Volts/Div"), 1e-3, 1e1, - true, false, this); - voltsPosition = new PositionSpinButton({ - {"μVolts", 1E-6}, - {"mVolts", 1E-3}, - {"Volts", 1E0} - }, tr("Position"), - -25, 25, true, false, this); + timeBase = new ScaleSpinButton({{"ns", 1E-9}, {"μs", 1E-6}, {"ms", 1E-3}, {"s", 1E0}}, tr("Time Base"), 100e-9, + 1E0, true, false, this); + timePosition = new PositionSpinButton( + {{"ns", 1E-9}, {"μs", 1E-6}, {"ms", 1E-3}, {"s", 1E0}, {"min", 60E0}, {"h", 36E2}}, tr("Position"), + -timeBase->maxValue() * 5, 36E3, true, false, this); + voltsPerDiv = new ScaleSpinButton( + {// {"μVolts", 1E-6}, + {"mVolts", 1E-3}, + {"Volts", 1E0}}, + tr("Volts/Div"), 1e-3, 1e1, true, false, this); + voltsPosition = new PositionSpinButton({{"μVolts", 1E-6}, {"mVolts", 1E-3}, {"Volts", 1E0}}, tr("Position"), + -25, 25, true, false, this); plot.setOffsetInterval(-DBL_MAX, DBL_MAX); - plot.setTimeTriggerInterval(-36E2, - timeBase->maxValue() * 5); + plot.setTimeTriggerInterval(-36E2, timeBase->maxValue() * 5); ch_ui = new Ui::ChannelSettings(); ch_ui->setupUi(ui->channelSettings); - bool showAdcFilters = pref->get("m2k_show_adc_filters").toBool(); ch_ui->filter1->setVisible(showAdcFilters); @@ -599,16 +555,14 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, init_channel_settings(); - connect(ch_ui->filter_en, &QCheckBox::toggled, [&](bool en) { - iio->freq_comp_filt[current_ch_widget][0]->set_enable(en); - }); + connect(ch_ui->filter_en, &QCheckBox::toggled, + [&](bool en) { iio->freq_comp_filt[current_ch_widget][0]->set_enable(en); }); connect(ch_ui->filter_TC, &QLineEdit::textChanged, [&](QString str) { bool ok; float val = str.toFloat(&ok); if(!ok) return; iio->freq_comp_filt[current_ch_widget][0]->set_TC(val); - }); connect(ch_ui->filter_gain, &QLineEdit::textChanged, [&](QString str) { bool ok; @@ -618,17 +572,14 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, iio->freq_comp_filt[current_ch_widget][0]->set_filter_gain(val); }); - - connect(ch_ui->filter2_en, &QCheckBox::toggled, [&](bool en) { - iio->freq_comp_filt[current_ch_widget][1]->set_enable(en); - }); + connect(ch_ui->filter2_en, &QCheckBox::toggled, + [&](bool en) { iio->freq_comp_filt[current_ch_widget][1]->set_enable(en); }); connect(ch_ui->filter2_TC, &QLineEdit::textChanged, [&](QString str) { bool ok; float val = str.toFloat(&ok); if(!ok) return; iio->freq_comp_filt[current_ch_widget][1]->set_TC(val); - }); connect(ch_ui->filter2_gain, &QLineEdit::textChanged, [&](QString str) { bool ok; @@ -650,145 +601,107 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, gsettings_ui->setupUi(ui->generalSettings); for(size_t i = 0; i < nb_channels + nb_math_channels; i++) { - ChannelWidget *cw = static_cast( - ui->channelsList->itemAt(i)->widget()); + ChannelWidget *cw = static_cast(ui->channelsList->itemAt(i)->widget()); gsettings_ui->cmb_x_channel->addItem(cw->shortName()); gsettings_ui->cmb_y_channel->addItem(cw->shortName()); } gsettings_ui->cmb_x_channel->setCurrentIndex(0); gsettings_ui->cmb_y_channel->setCurrentIndex(1); - connect(gsettings_ui->cmb_x_channel, SIGNAL(currentIndexChanged(int)), - this, SLOT(setup_xy_channels())); - connect(gsettings_ui->cmb_y_channel, SIGNAL(currentIndexChanged(int)), - this, SLOT(setup_xy_channels())); - + connect(gsettings_ui->cmb_x_channel, SIGNAL(currentIndexChanged(int)), this, SLOT(setup_xy_channels())); + connect(gsettings_ui->cmb_y_channel, SIGNAL(currentIndexChanged(int)), this, SLOT(setup_xy_channels())); int gsettings_panel = ui->stackedWidget->indexOf(ui->generalSettings); ui->btnGeneralSettings->setProperty("id", QVariant(-gsettings_panel)); - connect(gsettings_ui->FFT_view, SIGNAL(toggled(bool)), - SLOT(onFFT_view_toggled(bool))); - connect(gsettings_ui->XY_view, SIGNAL(toggled(bool)), - SLOT(onXY_view_toggled(bool))); - connect(gsettings_ui->Histogram_view, SIGNAL(toggled(bool)), - SLOT(onHistogram_view_toggled(bool))); + connect(gsettings_ui->FFT_view, SIGNAL(toggled(bool)), SLOT(onFFT_view_toggled(bool))); + connect(gsettings_ui->XY_view, SIGNAL(toggled(bool)), SLOT(onXY_view_toggled(bool))); + connect(gsettings_ui->Histogram_view, SIGNAL(toggled(bool)), SLOT(onHistogram_view_toggled(bool))); ch_ui->btnAutoset->setEnabled(false); - connect(ui->runSingleWidget, &RunSingleWidget::toggled, - ch_ui->btnAutoset, &QPushButton::setEnabled); + connect(ui->runSingleWidget, &RunSingleWidget::toggled, ch_ui->btnAutoset, &QPushButton::setEnabled); - connect(ui->runSingleWidget, &RunSingleWidget::toggled, - [=](bool checked){ - tme->setRunning(checked); - }); - connect(tme, &ToolMenuEntry::runToggled, - ui->runSingleWidget, &RunSingleWidget::toggle); - connect(ui->runSingleWidget, &RunSingleWidget::toggled, - this, &Oscilloscope::runStopToggled); - connect(this, &Oscilloscope::startRunning, - ui->runSingleWidget, &RunSingleWidget::toggle); + connect(ui->runSingleWidget, &RunSingleWidget::toggled, [=](bool checked) { tme->setRunning(checked); }); + connect(tme, &ToolMenuEntry::runToggled, ui->runSingleWidget, &RunSingleWidget::toggle); + connect(ui->runSingleWidget, &RunSingleWidget::toggled, this, &Oscilloscope::runStopToggled); + connect(this, &Oscilloscope::startRunning, ui->runSingleWidget, &RunSingleWidget::toggle); - connect(gsettings_ui->xyPlotLineType, SIGNAL(toggled(bool)), - this, SLOT(xyPlotLineType_toggled(bool))); + connect(gsettings_ui->xyPlotLineType, SIGNAL(toggled(bool)), this, SLOT(xyPlotLineType_toggled(bool))); // Signal-Slot Connections - connect(timeBase, SIGNAL(valueChanged(double)), - SLOT(onHorizScaleValueChanged(double))); - connect(voltsPerDiv, SIGNAL(valueChanged(double)), - SLOT(onVertScaleValueChanged(double))); - connect(timePosition, SIGNAL(valueChanged(double)), - SLOT(onTimePositionChanged(double))); - connect(voltsPosition, SIGNAL(valueChanged(double)), - SLOT(onVertOffsetValueChanged(double))); - connect(ch_ui->btnCoupled, SIGNAL(toggled(bool)), - SLOT(onChannelCouplingChanged(bool))); + connect(timeBase, SIGNAL(valueChanged(double)), SLOT(onHorizScaleValueChanged(double))); + connect(voltsPerDiv, SIGNAL(valueChanged(double)), SLOT(onVertScaleValueChanged(double))); + connect(timePosition, SIGNAL(valueChanged(double)), SLOT(onTimePositionChanged(double))); + connect(voltsPosition, SIGNAL(valueChanged(double)), SLOT(onVertOffsetValueChanged(double))); + connect(ch_ui->btnCoupled, SIGNAL(toggled(bool)), SLOT(onChannelCouplingChanged(bool))); - connect(ch_ui->cmbChnLineWidth, SIGNAL(currentIndexChanged(int)), - SLOT(channelLineWidthChanged(int))); + connect(ch_ui->cmbChnLineWidth, SIGNAL(currentIndexChanged(int)), SLOT(channelLineWidthChanged(int))); /* Sync timePosition with plot time trigger bar */ - connect(&plot, SIGNAL(timeTriggerValueChanged(double)), - this, SLOT(onTimeTriggerDelayChanged(double))); - connect(this, SIGNAL(triggerPositionChanged(double)), - timePosition, SLOT(setValue(double))); + connect(&plot, SIGNAL(timeTriggerValueChanged(double)), this, SLOT(onTimeTriggerDelayChanged(double))); + connect(this, SIGNAL(triggerPositionChanged(double)), timePosition, SLOT(setValue(double))); /* Update Timebase label each time the oscilloscope timebase changes */ - connect(timeBase, SIGNAL(valueChanged(double)), - &plot, SLOT(setTimeBaseLabelValue(double))); + connect(timeBase, SIGNAL(valueChanged(double)), &plot, SLOT(setTimeBaseLabelValue(double))); connect(&plot, SIGNAL(channelOffsetChanged(unsigned int, double)), SLOT(onChannelOffsetChanged(unsigned int, double))); - connect(this, SIGNAL(selectedChannelChanged(int)), - &plot, SLOT(setSelectedChannel(int))); - connect(this, &Oscilloscope::selectedChannelChanged, - &hist_plot, &HistogramDisplayPlot::setSelectedChannel); + connect(this, SIGNAL(selectedChannelChanged(int)), &plot, SLOT(setSelectedChannel(int))); + connect(this, &Oscilloscope::selectedChannelChanged, &hist_plot, &HistogramDisplayPlot::setSelectedChannel); - connect(this, SIGNAL(selectedChannelChanged(int)), - &plot, SLOT(setZoomerVertAxis(int))); + connect(this, SIGNAL(selectedChannelChanged(int)), &plot, SLOT(setZoomerVertAxis(int))); - connect(&plot, - SIGNAL(cursorReadoutsChanged(struct cursorReadoutsText)), + connect(&plot, SIGNAL(cursorReadoutsChanged(struct cursorReadoutsText)), SLOT(onCursorReadoutsChanged(struct cursorReadoutsText))); // Connections with Trigger Settings - connect(&trigger_settings, SIGNAL(sourceChanged(int)), - SLOT(onTriggerSourceChanged(int))); - connect(&trigger_settings, SIGNAL(analogTriggerEnabled(bool)), - &plot, SLOT(setTriggerAEnabled(bool))); - connect(&trigger_settings, SIGNAL(analogTriggerEnabled(bool)), - this, SLOT(configureAcCouplingTrigger(bool))); - connect(&trigger_settings, SIGNAL(levelChanged(double)), - plot.levelTriggerA(), SLOT(setPosition(double))); - connect(plot.levelTriggerA(), SIGNAL(positionChanged(double)), - &trigger_settings, SLOT(setTriggerLevel(double))); - - connect(&trigger_settings, SIGNAL(levelChanged(double)), - SLOT(onTriggerLevelChanged(double))); - - connect(&trigger_settings, SIGNAL(triggerModeChanged(int)), - this, SLOT(onTriggerModeChanged(int))); - - connect(&*iio, SIGNAL(timeout()), - &trigger_settings, SLOT(autoTriggerDisable())); - connect(&plot, SIGNAL(newData()), - &trigger_settings, SLOT(autoTriggerEnable())); + connect(&trigger_settings, SIGNAL(sourceChanged(int)), SLOT(onTriggerSourceChanged(int))); + connect(&trigger_settings, SIGNAL(analogTriggerEnabled(bool)), &plot, SLOT(setTriggerAEnabled(bool))); + connect(&trigger_settings, SIGNAL(analogTriggerEnabled(bool)), this, SLOT(configureAcCouplingTrigger(bool))); + connect(&trigger_settings, SIGNAL(levelChanged(double)), plot.levelTriggerA(), SLOT(setPosition(double))); + connect(plot.levelTriggerA(), SIGNAL(positionChanged(double)), &trigger_settings, + SLOT(setTriggerLevel(double))); + + connect(&trigger_settings, SIGNAL(levelChanged(double)), SLOT(onTriggerLevelChanged(double))); + + connect(&trigger_settings, SIGNAL(triggerModeChanged(int)), this, SLOT(onTriggerModeChanged(int))); + + connect(&*iio, SIGNAL(timeout()), &trigger_settings, SLOT(autoTriggerDisable())); + connect(&plot, SIGNAL(newData()), &trigger_settings, SLOT(autoTriggerEnable())); connect(&plot, SIGNAL(newData()), this, SLOT(singleCaptureDone())); - connect(&plot, SIGNAL(filledScreen(bool, unsigned int)), this, - SLOT(onFilledScreen(bool, unsigned int))); + connect(&plot, SIGNAL(filledScreen(bool, unsigned int)), this, SLOT(onFilledScreen(bool, unsigned int))); - connect(&*iio, SIGNAL(timeout()), - SLOT(onIioDataRefillTimeout())); + connect(&*iio, SIGNAL(timeout()), SLOT(onIioDataRefillTimeout())); connect(&plot, SIGNAL(newData()), this, SLOT(onPlotNewData())); - connect(ch_ui->cmbMemoryDepth, SIGNAL(currentTextChanged(QString)), - this, SLOT(onCmbMemoryDepthChanged(QString))); + connect(ch_ui->cmbMemoryDepth, SIGNAL(currentTextChanged(QString)), this, + SLOT(onCmbMemoryDepthChanged(QString))); - if (nb_channels < 2) + if(nb_channels < 2) gsettings_ui->XY_view->hide(); // Set the first channel to be the selected channel (by default) ChannelWidget *chn0_widget = channelWidgetAtId(0); - if (chn0_widget) { + if(chn0_widget) { chn0_widget->nameButton()->setChecked(true); } // Default hysteresis levels for measurements - for (size_t i = 0; i < nb_channels; i++) + for(size_t i = 0; i < nb_channels; i++) plot.setPeriodDetectHyst(i, 1.0 / 5); // Calculate initial sample count and sample rate onHorizScaleValueChanged(timeBase->value()); onTimePositionChanged(timePosition->value()); - if (m_m2k_analogin) { + if(m_m2k_analogin) { int crt_chn_copy = current_channel; int crt_chn_w_copy = current_ch_widget; - for (size_t i = 0; i < nb_channels; i++) { + for(size_t i = 0; i < nb_channels; i++) { current_channel = i; current_ch_widget = i; updateGainMode(); @@ -808,28 +721,28 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, current_ch_widget = crt_chn_w_copy; } - connect(plot.getZoomer(), &OscPlotZoomer::zoomIn, [=](){ + connect(plot.getZoomer(), &OscPlotZoomer::zoomIn, [=]() { zoom_level++; plot.setTimeBaseZoomed(true); }); - connect(plot.getZoomer(), &OscPlotZoomer::zoomOut, [=](){ - if (zoom_level != 0) zoom_level--; - if (zoom_level == 0) + connect(plot.getZoomer(), &OscPlotZoomer::zoomOut, [=]() { + if(zoom_level != 0) + zoom_level--; + if(zoom_level == 0) plot.setTimeBaseZoomed(false); }); connect(plot.getZoomer(), &OscPlotZoomer::zoomFinished, [=](bool isZoomOut) { plot.setTimeBaseLabelValue(plot.HorizUnitsPerDiv()); - for (size_t i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; ++i) { - QLabel *label = static_cast( - ui->chn_scales->itemAt(i)->widget()); + for(size_t i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; ++i) { + QLabel *label = static_cast(ui->chn_scales->itemAt(i)->widget()); double value = probe_attenuation[i] * plot.VertUnitsPerDiv(i); QString str = vertMeasureFormat.format(value, "V/div", 3); str.append(getChannelRangeStringVDivHelper(i)); label->setText(str); } - if (zoom_level == 0) { + if(zoom_level == 0) { onTimePositionChanged(timePosition->value()); } @@ -841,44 +754,42 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, resetHistogramDataPoints(); }); - - connect(ch_ui->probe_attenuation_value, &QLineEdit::textChanged, this, [=](){ + connect(ch_ui->probe_attenuation_value, &QLineEdit::textChanged, this, [=]() { double value = ch_ui->probe_attenuation_value->text().toDouble(); probe_attenuation[current_ch_widget] = value; - if (current_channel == current_ch_widget) { + if(current_channel == current_ch_widget) { plot.setDisplayScale(probe_attenuation[current_ch_widget]); } bool started = isIioManagerStarted(); - if (started) + if(started) iio->lock(); // Update the multiplier value for this channel - if (current_ch_widget < math_probe_atten.size()) { + if(current_ch_widget < math_probe_atten.size()) { math_probe_atten[current_ch_widget]->set_k(value); } auto max_elem = max_element(probe_attenuation.begin(), probe_attenuation.begin() + nb_channels); auto const values = math_rails.values(); - for (auto rail : values) { + for(auto rail : values) { rail->set_lo(MIN_MATH_RANGE); rail->set_hi(MAX_MATH_RANGE); } - if (started) + if(started) iio->unlock(); - for (size_t i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; ++i) { - QLabel *label = static_cast( - ui->chn_scales->itemAt(i)->widget()); + for(size_t i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; ++i) { + QLabel *label = static_cast(ui->chn_scales->itemAt(i)->widget()); double value = probe_attenuation[i] * plot.VertUnitsPerDiv(i); QString str = vertMeasureFormat.format(value, "V/div", 3); str.append(getChannelRangeStringVDivHelper(i)); label->setText(str); } - if (channelWidgetAtId(current_ch_widget)->isMathChannel()) { + if(channelWidgetAtId(current_ch_widget)->isMathChannel()) { voltsPerDiv->silentSetMaxValue((*max_elem) * 10); voltsPosition->silentSetMaxValue((*max_elem) * MAX_AMPL); voltsPosition->silentSetMinValue((*max_elem) * (-MAX_AMPL)); @@ -891,12 +802,11 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, voltsPerDiv->setDisplayScale(probe_attenuation[current_ch_widget]); voltsPosition->setDisplayScale(probe_attenuation[current_ch_widget]); - if (!tme->running() && plot.measurementsEnabled()) { + if(!tme->running() && plot.measurementsEnabled()) { measureUpdateValues(); } onTriggerSourceChanged(trigger_settings.currentChannel()); - }); init_buffer_scrolling(); @@ -905,7 +815,7 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, cursor_panel_init(); setFFT_params(true); - for (unsigned int i = 0; i < nb_channels + nb_math_channels; i++) { + for(unsigned int i = 0; i < nb_channels + nb_math_channels; i++) { init_selected_measurements(i, {0, 1, 4, 5}); } @@ -915,27 +825,27 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, gsettings_ui->xySettings->hide(); timePosition->setValue(0); - connect(gsettings_ui->xyLineThickness,SIGNAL(currentIndexChanged(int)),this, SLOT(xyLineThickness_currentIndexChanged(int))); + connect(gsettings_ui->xyLineThickness, SIGNAL(currentIndexChanged(int)), this, + SLOT(xyLineThickness_currentIndexChanged(int))); api->setObjectName(Filter::tool_name(TOOL_OSCILLOSCOPE)); ScopyJS::GetInstance()->registerApi(api); plot.setDisplayScale(probe_attenuation[current_channel]); onTriggerSourceChanged(trigger_settings.currentChannel()); - for (size_t i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; ++i) { - QLabel *label = static_cast( - ui->chn_scales->itemAt(i)->widget()); + for(size_t i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; ++i) { + QLabel *label = static_cast(ui->chn_scales->itemAt(i)->widget()); double value = probe_attenuation[i] * plot.VertUnitsPerDiv(i); QString str = vertMeasureFormat.format(value, "V/div", 3); str.append(getChannelRangeStringVDivHelper(i)); label->setText(str); } - for (unsigned int i = nb_channels; i < nb_channels + nb_math_channels; i++) { + for(unsigned int i = nb_channels; i < nb_channels + nb_math_channels; i++) { init_selected_measurements(i, {0, 1, 4, 5}); } - if (!wheelEventGuard) + if(!wheelEventGuard) wheelEventGuard = new MouseWheelWidgetGuard(ui->mainWidget); wheelEventGuard->installEventRecursively(ui->mainWidget); @@ -943,33 +853,28 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, readPreferences(); - connect(ui->printBtn, &QPushButton::clicked, - [=]() { - plot.printWithNoBackground(api->objectName()); - }); + connect(ui->printBtn, &QPushButton::clicked, [=]() { plot.printWithNoBackground(api->objectName()); }); - //workaround for a bug that selected channel settings for disabled channels + // workaround for a bug that selected channel settings for disabled channels bool found = false; - for (size_t i = 0; i < nb_channels + nb_math_channels + - nb_ref_channels; ++i) { + for(size_t i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; ++i) { ChannelWidget *cw = channelWidgetAtId(i); - if (cw->enableButton()->isChecked()) { + if(cw->enableButton()->isChecked()) { cw->menuButton()->setChecked(true); found = true; break; } } - if (!found) { + if(!found) { ui->btnTrigger->setChecked(true); ui->btnTrigger->setChecked(false); } - connect(this, &M2kTool::detachedState, - this, &Oscilloscope::toolDetached); + connect(this, &M2kTool::detachedState, this, &Oscilloscope::toolDetached); toolDetached(false); - connect(&plot,SIGNAL(leftGateChanged(double)),SLOT(onLeftGateChanged(double))); - connect(&plot,SIGNAL(rightGateChanged(double)),SLOT(onRightGateChanged(double))); + connect(&plot, SIGNAL(leftGateChanged(double)), SLOT(onLeftGateChanged(double))); + connect(&plot, SIGNAL(rightGateChanged(double)), SLOT(onRightGateChanged(double))); ui->btnHelp->setUrl("https://wiki.analog.com/university/tools/m2k/scopy/oscilloscope"); @@ -985,21 +890,21 @@ Oscilloscope::Oscilloscope(struct iio_context *ctx, Filter *filt, int Oscilloscope::binSearchPointOnXaxis(double time) { int n = plot.Curve(0)->data()->size(); - if (time <= plot.Curve(0)->data()->sample(0).x()) { + if(time <= plot.Curve(0)->data()->sample(0).x()) { return 0; } - if (time >= plot.Curve(0)->data()->sample(n - 1).x()) { + if(time >= plot.Curve(0)->data()->sample(n - 1).x()) { return n - 1; } int left = 0; int right = n - 1; - while (left <= right) { + while(left <= right) { int mid = (left + right) / 2; double xData = plot.Curve(0)->data()->sample(mid).x(); - if (xData == time) { + if(xData == time) { return mid; - } else if (xData < time) { + } else if(xData < time) { left = mid + 1; } else { right = mid - 1; @@ -1022,15 +927,13 @@ void Oscilloscope::resetHistogramDataPoints() bool Oscilloscope::isIioManagerStarted() const { - return iio->started() && (ui->runSingleWidget->singleButtonChecked() - || ui->runSingleWidget->runButtonChecked()); + return iio->started() && + (ui->runSingleWidget->singleButtonChecked() || ui->runSingleWidget->runButtonChecked()); } void Oscilloscope::init_buffer_scrolling() { - connect(&plot, &CapturePlot::canvasSizeChanged, [=](){ - buffer_previewer->setFixedWidth(plot.width()); - }); + connect(&plot, &CapturePlot::canvasSizeChanged, [=]() { buffer_previewer->setFixedWidth(plot.width()); }); connect(buffer_previewer, &BufferPreviewer::bufferMovedBy, [=](int value) { reset_horiz_offset = false; double moveTo = 0.0; @@ -1045,11 +948,11 @@ void Oscilloscope::init_buffer_scrolling() updateBufferPreviewer(); resetHistogramDataPoints(); }); - connect(buffer_previewer, &BufferPreviewer::bufferStopDrag, [=](){ + connect(buffer_previewer, &BufferPreviewer::bufferStopDrag, [=]() { horiz_offset = plot.HorizOffset(); reset_horiz_offset = true; }); - connect(buffer_previewer, &BufferPreviewer::bufferResetPosition, [=](){ + connect(buffer_previewer, &BufferPreviewer::bufferResetPosition, [=]() { plot.setHorizOffset(time_trigger_offset); plot.replot(); updateBufferPreviewer(); @@ -1058,16 +961,13 @@ void Oscilloscope::init_buffer_scrolling() }); } - -void Oscilloscope::init_selected_measurements(int chnIdx, - std::vector measureIdx) +void Oscilloscope::init_selected_measurements(int chnIdx, std::vector measureIdx) { auto measurements = plot.measurements(chnIdx); - for (size_t i = 0; i < measureIdx.size(); i++) { + for(size_t i = 0; i < measureIdx.size(); i++) { measurements[measureIdx[i]]->setEnabled(true); - measure_settings->onMeasurementActivated( - chnIdx, measureIdx[i], true); + measure_settings->onMeasurementActivated(chnIdx, measureIdx[i], true); } measure_settings->loadMeasurementStatesFromData(); onMeasurementSelectionListChanged(); @@ -1076,9 +976,9 @@ void Oscilloscope::init_selected_measurements(int chnIdx, void Oscilloscope::remove_ref_waveform(QString name) { size_t maxChnId = nb_channels + nb_math_channels + nb_ref_channels; - for (size_t i = 0; i < maxChnId; ++i) { + for(size_t i = 0; i < maxChnId; ++i) { ChannelWidget *cw = channelWidgetAtId(i); - if (cw->fullName() == name) { + if(cw->fullName() == name) { qDebug() << "deleted channel with name: " << cw->fullName(); cw->deleteButton()->click(); } @@ -1107,30 +1007,23 @@ void Oscilloscope::add_ref_waveform(QString name, QVector xData, QVector int curve_id = nb_channels + nb_math_channels + nb_ref_channels; - ChannelWidget *channel_widget = new ChannelWidget(curve_id, true, false, - plot.getLineColor(curve_id).name(), this); + ChannelWidget *channel_widget = + new ChannelWidget(curve_id, true, false, plot.getLineColor(curve_id).name(), this); channel_widget->setFullName(name); channel_widget->setShortName(name); channel_widget->nameButton()->setText(channel_widget->shortName()); channel_widget->setReferenceChannel(true); - channel_widget->setProperty("curve_nb", QVariant(curve_id)); - channel_widget->deleteButton()->setProperty( - "curve_name", QVariant(name)); - - connect(channel_widget, SIGNAL(enabled(bool)), - SLOT(onChannelWidgetEnabled(bool))); - connect(channel_widget, SIGNAL(selected(bool)), - SLOT(onChannelWidgetSelected(bool))); - connect(channel_widget, SIGNAL(menuToggled(bool)), - SLOT(onChannelWidgetMenuToggled(bool))); - connect(channel_widget, SIGNAL(deleteClicked()), - SLOT(onChannelWidgetDeleteClicked())); - connect(channel_widget, &ChannelWidget::menuToggled, - [=](bool on) { - if (!on) { + channel_widget->deleteButton()->setProperty("curve_name", QVariant(name)); + + connect(channel_widget, SIGNAL(enabled(bool)), SLOT(onChannelWidgetEnabled(bool))); + connect(channel_widget, SIGNAL(selected(bool)), SLOT(onChannelWidgetSelected(bool))); + connect(channel_widget, SIGNAL(menuToggled(bool)), SLOT(onChannelWidgetMenuToggled(bool))); + connect(channel_widget, SIGNAL(deleteClicked()), SLOT(onChannelWidgetDeleteClicked())); + connect(channel_widget, &ChannelWidget::menuToggled, [=](bool on) { + if(!on) { ch_ui->btnEditMath->setChecked(false); } }); @@ -1141,19 +1034,17 @@ void Oscilloscope::add_ref_waveform(QString name, QVector xData, QVector ui->settings_group->addButton(channel_widget->menuButton()); channel_widget->nameButton()->setChecked(true); - QLabel *label= new QLabel(this); - label->setText(vertMeasureFormat.format( - plot.VertUnitsPerDiv(curve_id), "V/div", 3)); + QLabel *label = new QLabel(this); + label->setText(vertMeasureFormat.format(plot.VertUnitsPerDiv(curve_id), "V/div", 3)); label->setStyleSheet(QString("QLabel {" "color: %1;" "font-weight: bold;" - "}").arg(plot.getLineColor(curve_id).name())); + "}") + .arg(plot.getLineColor(curve_id).name())); ui->chn_scales->addWidget(label); probe_attenuation.push_back(1); - plot.Curve(curve_id)->setAxes( - QwtAxisId(QwtAxis::XBottom, 0), - QwtAxisId(QwtAxis::YLeft, curve_id)); + plot.Curve(curve_id)->setAxes(QwtAxisId(QwtAxis::XBottom, 0), QwtAxisId(QwtAxis::YLeft, curve_id)); plot.Curve(curve_id)->setTitle("REF " + QString::number(nb_ref_channels + 1)); plot.addZoomer(curve_id); plot.replot(); @@ -1162,8 +1053,8 @@ void Oscilloscope::add_ref_waveform(QString name, QVector xData, QVector plot.setPeriodDetectHyst(2, 1.0 / 5); - if (nb_math_channels + nb_ref_channels == MAX_MATH_CHANNELS) { - if (ui->btnAddMath->isChecked()) { + if(nb_math_channels + nb_ref_channels == MAX_MATH_CHANNELS) { + if(ui->btnAddMath->isChecked()) { ui->btnAddMath->setChecked(false); } @@ -1180,7 +1071,7 @@ void Oscilloscope::add_ref_waveform(QString name, QVector xData, QVector void Oscilloscope::add_ref_waveform(unsigned int chIdx) { - if (nb_math_channels + nb_ref_channels == MAX_MATH_CHANNELS) { + if(nb_math_channels + nb_ref_channels == MAX_MATH_CHANNELS) { return; } @@ -1199,21 +1090,19 @@ void Oscilloscope::add_ref_waveform(unsigned int chIdx) int nr_of_samples_in_file = import_data.size(); - double mid_point_on_screen = (timeBase->value() * 8) - (( - timeBase->value() * 8) - timePosition->value()); + double mid_point_on_screen = (timeBase->value() * 8) - ((timeBase->value() * 8) - timePosition->value()); - double x_axis_step_size = (ref_waveform_timebase / - (nr_of_samples_in_file / plot.xAxisNumDiv())); + double x_axis_step_size = (ref_waveform_timebase / (nr_of_samples_in_file / plot.xAxisNumDiv())); - for (int i = -(nr_of_samples_in_file / 2); i < (nr_of_samples_in_file / 2); - ++i) { + for(int i = -(nr_of_samples_in_file / 2); i < (nr_of_samples_in_file / 2); ++i) { xData.push_back(mid_point_on_screen + ((double)i * x_axis_step_size)); } - if (!refChannelTimeBase->isEnabled()) chIdx++; + if(!refChannelTimeBase->isEnabled()) + chIdx++; - for (int i = 0; i < import_data.size(); ++i) { - if (chIdx >= import_data[i].size()) { + for(int i = 0; i < import_data.size(); ++i) { + if(chIdx >= import_data[i].size()) { continue; } yData.push_back(import_data[i][chIdx]); @@ -1225,30 +1114,23 @@ void Oscilloscope::add_ref_waveform(unsigned int chIdx) plot.registerReferenceWaveform(qname, xData, yData); - ChannelWidget *channel_widget = new ChannelWidget(curve_id, true, false, - plot.getLineColor(curve_id).name(), this); + ChannelWidget *channel_widget = + new ChannelWidget(curve_id, true, false, plot.getLineColor(curve_id).name(), this); channel_widget->setFullName(qname); channel_widget->setShortName(qname); channel_widget->nameButton()->setText(channel_widget->shortName()); channel_widget->setReferenceChannel(true); - channel_widget->setProperty("curve_nb", QVariant(curve_id)); - channel_widget->deleteButton()->setProperty( - "curve_name", QVariant(qname)); - - connect(channel_widget, SIGNAL(enabled(bool)), - SLOT(onChannelWidgetEnabled(bool))); - connect(channel_widget, SIGNAL(selected(bool)), - SLOT(onChannelWidgetSelected(bool))); - connect(channel_widget, SIGNAL(menuToggled(bool)), - SLOT(onChannelWidgetMenuToggled(bool))); - connect(channel_widget, SIGNAL(deleteClicked()), - SLOT(onChannelWidgetDeleteClicked())); - connect(channel_widget, &ChannelWidget::menuToggled, - [=](bool on) { - if (!on) { + channel_widget->deleteButton()->setProperty("curve_name", QVariant(qname)); + + connect(channel_widget, SIGNAL(enabled(bool)), SLOT(onChannelWidgetEnabled(bool))); + connect(channel_widget, SIGNAL(selected(bool)), SLOT(onChannelWidgetSelected(bool))); + connect(channel_widget, SIGNAL(menuToggled(bool)), SLOT(onChannelWidgetMenuToggled(bool))); + connect(channel_widget, SIGNAL(deleteClicked()), SLOT(onChannelWidgetDeleteClicked())); + connect(channel_widget, &ChannelWidget::menuToggled, [=](bool on) { + if(!on) { ch_ui->btnEditMath->setChecked(false); } }); @@ -1259,19 +1141,17 @@ void Oscilloscope::add_ref_waveform(unsigned int chIdx) ui->settings_group->addButton(channel_widget->menuButton()); channel_widget->nameButton()->setChecked(true); - QLabel *label= new QLabel(this); - label->setText(vertMeasureFormat.format( - plot.VertUnitsPerDiv(curve_id), "V/div", 3)); + QLabel *label = new QLabel(this); + label->setText(vertMeasureFormat.format(plot.VertUnitsPerDiv(curve_id), "V/div", 3)); label->setStyleSheet(QString("QLabel {" - "color: %1;" - "font-weight: bold;" - "}").arg(plot.getLineColor(curve_id).name())); + "color: %1;" + "font-weight: bold;" + "}") + .arg(plot.getLineColor(curve_id).name())); ui->chn_scales->addWidget(label); probe_attenuation.push_back(1); - plot.Curve(curve_id)->setAxes( - QwtAxisId(QwtAxis::XBottom, 0), - QwtAxisId(QwtAxis::YLeft, curve_id)); + plot.Curve(curve_id)->setAxes(QwtAxisId(QwtAxis::XBottom, 0), QwtAxisId(QwtAxis::YLeft, curve_id)); plot.Curve(curve_id)->setTitle("REF " + QString::number(nb_ref_channels + 1)); plot.addZoomer(curve_id); plot.replot(); @@ -1280,8 +1160,8 @@ void Oscilloscope::add_ref_waveform(unsigned int chIdx) plot.setPeriodDetectHyst(2, 1.0 / 5); - if (nb_math_channels + nb_ref_channels == MAX_MATH_CHANNELS) { - if (ui->btnAddMath->isChecked()) { + if(nb_math_channels + nb_ref_channels == MAX_MATH_CHANNELS) { + if(ui->btnAddMath->isChecked()) { ui->btnAddMath->setChecked(false); } @@ -1296,7 +1176,7 @@ void Oscilloscope::add_ref_waveform(unsigned int chIdx) void Oscilloscope::updateTriggerLevelValue(std::vector value) { - if (!triggerLevelSink.first) { + if(!triggerLevelSink.first) { return; } @@ -1304,14 +1184,13 @@ void Oscilloscope::updateTriggerLevelValue(std::vector value) float val = dc_cancel.at(triggerLevelSink.second)->get_dc_offset(); double m_dc_level = trigger_settings.dcLevel(); - if ((int)(val*1e3) == (int)(m_dc_level*1e3)) { + if((int)(val * 1e3) == (int)(m_dc_level * 1e3)) { triggerLevelSink.first->blockSignals(false); return; } - if (trigger_settings.analogEnabled()) { + if(trigger_settings.analogEnabled()) { trigger_settings.setDcLevelCoupled(val); - trigger_settings.onSpinboxTriggerLevelChanged( - trigger_settings.level()); + trigger_settings.onSpinboxTriggerLevelChanged(trigger_settings.level()); } triggerLevelSink.first->blockSignals(false); } @@ -1319,40 +1198,40 @@ void Oscilloscope::updateTriggerLevelValue(std::vector value) Oscilloscope::~Oscilloscope() { - if (m_mixedSignalViewEnabled) { + if(m_mixedSignalViewEnabled) { disableMixedSignalView(); } ui->runSingleWidget->toggle(false); -// setDynamicProperty(runButton(), "disabled", false); + // setDynamicProperty(runButton(), "disabled", false); bool started = isIioManagerStarted(); - if (started) + if(started) iio->lock(); - for (unsigned int i = 0; i < nb_channels; i++) + for(unsigned int i = 0; i < nb_channels; i++) iio->disconnect(ids[i]); - if (fft_is_visible) { - if (fft_channels.size() > 0) { + if(fft_is_visible) { + if(fft_channels.size() > 0) { fft_channels.clear(); fft_blocks.clear(); ctm_blocks.clear(); } } - if (started) + if(started) iio->unlock(); gr::hier_block2_sptr hier = iio->to_hier_block2(); qDebug(CAT_M2K_OSCILLOSCOPE) << "OSC disconnected:\n" << gr::dot_graph(hier).c_str(); -// if (saveOnExit) { -// api->save(*settings); -// } + // if (saveOnExit) { + // api->save(*settings); + // } delete api; - for (auto it = channels_api.begin(); it != channels_api.end(); ++it) { + for(auto it = channels_api.begin(); it != channels_api.end(); ++it) { delete *it; } @@ -1370,26 +1249,20 @@ Oscilloscope::~Oscilloscope() delete ui; } -QPushButton *Oscilloscope::getRunButton() -{ - return ui->runSingleWidget->getRunButton(); -} +QPushButton *Oscilloscope::getRunButton() { return ui->runSingleWidget->getRunButton(); } void Oscilloscope::settingsLoaded() { - for (size_t i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; ++i) - if (channelWidgetAtId(i)->menuButton()->isChecked() && - !channelWidgetAtId(i)->isReferenceChannel()) { + for(size_t i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; ++i) + if(channelWidgetAtId(i)->menuButton()->isChecked() && !channelWidgetAtId(i)->isReferenceChannel()) { current_ch_widget = i; channelWidgetAtId(i)->menuButton()->setChecked(true); break; } - disconnect(voltsPerDiv, SIGNAL(valueChanged(double)), this, - SLOT(onVertScaleValueChanged(double))); + disconnect(voltsPerDiv, SIGNAL(valueChanged(double)), this, SLOT(onVertScaleValueChanged(double))); voltsPerDiv->setValue(plot.VertUnitsPerDiv(current_ch_widget)); - connect(voltsPerDiv, SIGNAL(valueChanged(double)), - SLOT(onVertScaleValueChanged(double))); + connect(voltsPerDiv, SIGNAL(valueChanged(double)), SLOT(onVertScaleValueChanged(double))); } void Oscilloscope::readPreferences() @@ -1400,7 +1273,7 @@ void Oscilloscope::readPreferences() plot.setVisibleFpsLabel(showFps); xy_plot.setVisibleFpsLabel(showFps); fft_plot.setVisibleFpsLabel(showFps); - if (!miniHistogram) { + if(!miniHistogram) { hist_plot.setVisibleFpsLabel(showFps); } @@ -1414,12 +1287,10 @@ void Oscilloscope::readPreferences() bool foundChannel = false; bool oscLabels = p->get("m2k_osc_label").toBool(); - for (unsigned int i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; - i++) { - ChannelWidget *cw = static_cast( - ui->channelsList->itemAt(i)->widget()); + for(unsigned int i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; i++) { + ChannelWidget *cw = static_cast(ui->channelsList->itemAt(i)->widget()); - if (cw->enableButton()->isChecked()) { + if(cw->enableButton()->isChecked()) { /* At least one channel is enabled, * so we can enable/disable labels */ enableLabels(oscLabels); @@ -1428,7 +1299,7 @@ void Oscilloscope::readPreferences() } } - if (!foundChannel) { + if(!foundChannel) { /* No channel is enabled, so we disable the labels */ enableLabels(false); } @@ -1439,14 +1310,15 @@ void Oscilloscope::readPreferences() double fps = p->get("general_plot_target_fps").toDouble(); iio->set_data_rate(std::max(fps, 15.0)); // minimum 15 buffers/second - qt_time_block->set_update_time(1.0/fps); - qt_fft_block->set_update_time(1.0/fps);; - qt_xy_block->set_update_time(1.0/fps);; - qt_hist_block->set_update_time(1.0/fps);; - + qt_time_block->set_update_time(1.0 / fps); + qt_fft_block->set_update_time(1.0 / fps); + ; + qt_xy_block->set_update_time(1.0 / fps); + ; + qt_hist_block->set_update_time(1.0 / fps); + ; } - void Oscilloscope::setFilteringEnabled(bool set) { m_filtering_enabled = set; @@ -1456,28 +1328,28 @@ void Oscilloscope::setFilteringEnabled(bool set) void Oscilloscope::enableMixedSignalView(ChannelWidget *cw) { const bool iioStarted = isIioManagerStarted(); - if (iioStarted) { + if(iioStarted) { iio->lock(); } const bool hasLabels = plot.labelsEnabled(); - if (hasLabels) { + if(hasLabels) { enableLabels(false); } m_mixedSignalViewEnabled = true; - m_mixedSignalViewMenu = m_logicAnalyzer->enableMixedSignalView(&plot, nb_channels + - nb_math_channels + nb_ref_channels); + m_mixedSignalViewMenu = + m_logicAnalyzer->enableMixedSignalView(&plot, nb_channels + nb_math_channels + nb_ref_channels); ui->logicSettingsLayout->addWidget(m_mixedSignalViewMenu[0]); QTabWidget *tb = qobject_cast(m_mixedSignalViewMenu[0]); - showLogicAnalyzerTriggerConnection = connect(&trigger_settings, &TriggerSettings::showLogicAnalyzerTriggerSettings, - this, [=](){ - cw->menuButton()->setChecked(true); - tb->setCurrentIndex(tb->indexOf(m_mixedSignalViewMenu[1])); - }); + showLogicAnalyzerTriggerConnection = + connect(&trigger_settings, &TriggerSettings::showLogicAnalyzerTriggerSettings, this, [=]() { + cw->menuButton()->setChecked(true); + tb->setCurrentIndex(tb->indexOf(m_mixedSignalViewMenu[1])); + }); mixed_sink = mixed_signal_sink::make(m_logicAnalyzer, &this->plot, active_sample_count); @@ -1488,14 +1360,14 @@ void Oscilloscope::enableMixedSignalView(ChannelWidget *cw) // workaround consists in using 2 kernel buffers before restarting the acquisition mixed_source = gr::m2k::mixed_signal_source::make_from(m_m2k_context, active_sample_count, targetFps, 2); - if (iioStarted) { + if(iioStarted) { // enable the mixed_source in the iio_manager iio->enableMixedSignal(mixed_source); std::shared_ptr block = dynamic_pointer_cast(adc_samp_conv_block); // connect analog - for (size_t i = 0; i < nb_channels; ++i) { + for(size_t i = 0; i < nb_channels; ++i) { iio->disconnect(block, i, qt_time_block, i); iio->connect(block, i, mixed_sink, i); } @@ -1503,7 +1375,6 @@ void Oscilloscope::enableMixedSignalView(ChannelWidget *cw) // connect digital iio->connect(mixed_source, 2, mixed_sink, 2); - setDigitalPlotCurvesParams(); iio->unlock(); } @@ -1513,7 +1384,7 @@ void Oscilloscope::enableMixedSignalView(ChannelWidget *cw) onHorizScaleValueChanged(timeBase->value()); onTimePositionChanged(timePosition->value()); - if (hasLabels) { + if(hasLabels) { enableLabels(true); } } @@ -1522,7 +1393,7 @@ void Oscilloscope::disableMixedSignalView() { const bool iioStarted = isIioManagerStarted(); - if (iioStarted) { + if(iioStarted) { iio->lock(); } @@ -1536,14 +1407,14 @@ void Oscilloscope::disableMixedSignalView() m_mixedSignalViewMenu[0]->deleteLater(); - if (iioStarted) { + if(iioStarted) { // disable the mixed_source in the iio_manager iio->disableMixedSignal(mixed_source); std::shared_ptr block = dynamic_pointer_cast(adc_samp_conv_block); // disconnect analog - for (size_t i = 0; i < nb_channels; ++i) { + for(size_t i = 0; i < nb_channels; ++i) { iio->disconnect(block, i, mixed_sink, i); iio->connect(block, i, qt_time_block, i); } @@ -1566,24 +1437,26 @@ void Oscilloscope::setDigitalPlotCurvesParams() // active_sample_count qDebug() << "Delay: " << -(static_cast(active_sample_count) / 2) + active_time_pos * active_sample_rate; m_m2k_digital->getTrigger()->setDigitalStreamingFlag(false); - m_m2k_digital->getTrigger()->setDigitalDelay(-(static_cast(active_sample_count) / 2) + active_time_pos * active_sample_rate); -// qDebug() << "time pos: " << active_time_pos << " active sample rate: " << active_sample_rate; - for (int i = 0; i < plot.getNrDigitalPlotCurves(); ++i) { + m_m2k_digital->getTrigger()->setDigitalDelay(-(static_cast(active_sample_count) / 2) + + active_time_pos * active_sample_rate); + // qDebug() << "time pos: " << active_time_pos << " active sample rate: " << active_sample_rate; + for(int i = 0; i < plot.getNrDigitalPlotCurves(); ++i) { QwtPlotCurve *curve = plot.getDigitalPlotCurve(i); GenericLogicPlotCurve *logic_curve = dynamic_cast(curve); -// logic_curve->reset(); + // logic_curve->reset(); logic_curve->setSampleRate(active_sample_rate); logic_curve->setBufferSize(active_sample_count); - logic_curve->setTimeTriggerOffset(-(active_sample_count / 2.0) + (active_time_pos * active_sample_rate)); + logic_curve->setTimeTriggerOffset(-(active_sample_count / 2.0) + + (active_time_pos * active_sample_rate)); } } void Oscilloscope::toggleMiniHistogramPlotVisible(bool enabled) { miniHistogram = enabled; - if (hist_plot.getOrientation() == Qt::Horizontal) { + if(hist_plot.getOrientation() == Qt::Horizontal) { hist_plot.setVisible(enabled); plot.setBonusWidthForHistogram(enabled ? 25 : 0); } @@ -1591,27 +1464,24 @@ void Oscilloscope::toggleMiniHistogramPlotVisible(bool enabled) void Oscilloscope::init_channel_settings() { - connect(ch_ui->btnEditMath, &QPushButton::toggled, this, - &Oscilloscope::openEditMathPanel); + connect(ch_ui->btnEditMath, &QPushButton::toggled, this, &Oscilloscope::openEditMathPanel); - connect(ch_ui->btnAutoset, &QPushButton::clicked, this, - &Oscilloscope::requestAutoset); + connect(ch_ui->btnAutoset, &QPushButton::clicked, this, &Oscilloscope::requestAutoset); - connect(ui->btnAddMath, &QPushButton::toggled, [=](bool on){ - if (on && !addChannel) { + connect(ui->btnAddMath, &QPushButton::toggled, [=](bool on) { + if(on && !addChannel) { addChannel = true; math_pair->first.btnAddChannel->setText(tr("Add Channel")); ch_ui->math_settings_widget->setVisible(false); ch_ui->btnAutoset->setVisible(autosetEnabled); } }); - connect(ch_ui->lineStyle, QOverload::of(&QComboBox::currentIndexChanged), [=](int index) { - plot.setPlotLineStyle(current_ch_widget, index); - }); + connect(ch_ui->lineStyle, QOverload::of(&QComboBox::currentIndexChanged), + [=](int index) { plot.setPlotLineStyle(current_ch_widget, index); }); - connect(ch_ui->snapshotBtn, &QPushButton::clicked, [=](){ + connect(ch_ui->snapshotBtn, &QPushButton::clicked, [=]() { ChannelWidget *cw = channelWidgetAtId(current_ch_widget); - if (current_ch_widget > 1 && cw->isReferenceChannel()) { + if(current_ch_widget > 1 && cw->isReferenceChannel()) { // export QStringList filter; filter += QString(tr("Comma-separated values files (*.csv)")); @@ -1620,17 +1490,17 @@ void Oscilloscope::init_channel_settings() QString selectedFilter = filter[0]; - QString fileName = QFileDialog::getSaveFileName(this, - tr("Export"), "", filter.join(";;"), - &selectedFilter, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); + QString fileName = QFileDialog::getSaveFileName( + this, tr("Export"), "", filter.join(";;"), &selectedFilter, + (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); - if (fileName.split(".").size() <= 1) { + if(fileName.split(".").size() <= 1) { // file name w/o extension. Let's append it QString ext = selectedFilter.split(".")[1].split(")")[0]; fileName += "." + ext; } - if (!fileName.isEmpty()) { + if(!fileName.isEmpty()) { FileManager fm("Oscilloscope"); fm.open(fileName, FileManager::EXPORT); @@ -1638,7 +1508,7 @@ void Oscilloscope::init_channel_settings() QwtPlotCurve *curve = plot.Curve(current_ch_widget); - for (size_t i = 0; i < curve->data()->size(); ++i) { + for(size_t i = 0; i < curve->data()->size(); ++i) { time_data.push_back(curve->sample(i).x()); volts_data.push_back(curve->sample(i).y()); } @@ -1652,19 +1522,19 @@ void Oscilloscope::init_channel_settings() } } else { // snapshot - if (nb_math_channels + nb_ref_channels == MAX_MATH_CHANNELS) { + if(nb_math_channels + nb_ref_channels == MAX_MATH_CHANNELS) { return; } QwtPlotCurve *curve = plot.Curve(current_ch_widget); - if (!curve->data()->size()) { + if(!curve->data()->size()) { return; } QVector xData; QVector yData; - for (size_t i = 0; i < curve->data()->size(); ++i) { + for(size_t i = 0; i < curve->data()->size(); ++i) { xData.push_back(curve->data()->sample(i).x()); yData.push_back(curve->data()->sample(i).y()); } @@ -1676,12 +1546,10 @@ void Oscilloscope::init_channel_settings() }); } - void Oscilloscope::activateAcCoupling(int i) { - bool trigger = (i == trigger_settings.currentChannel()) - && trigger_settings.analogEnabled(); - if (trigger) { + bool trigger = (i == trigger_settings.currentChannel()) && trigger_settings.analogEnabled(); + if(trigger) { trigger_settings.setAcCoupled(true, i); } @@ -1690,9 +1558,7 @@ void Oscilloscope::activateAcCoupling(int i) iio->lock(); } - std::shared_ptr block = - dynamic_pointer_cast( - adc_samp_conv_block); + std::shared_ptr block = dynamic_pointer_cast(adc_samp_conv_block); iio->disconnect(block, i, qt_time_block, i); iio->disconnect(adc_samp_conv_block, i, math_probe_atten.at(i), 0); @@ -1704,57 +1570,47 @@ void Oscilloscope::activateAcCoupling(int i) iio->disconnect(block, i, qt_hist_block, i); iio->connect(dc_cancel.at(i), 0, qt_hist_block, i); - if (trigger && !triggerLevelSink.first) { + if(trigger && !triggerLevelSink.first) { triggerLevelSink.first = std::make_shared(); triggerLevelSink.second = i; keep_one = gr::blocks::keep_one_in_n::make(sizeof(float), active_sample_count); - connect(&*triggerLevelSink.first, SIGNAL(triggered(std::vector)), - this, SLOT(updateTriggerLevelValue(std::vector))); + connect(&*triggerLevelSink.first, SIGNAL(triggered(std::vector)), this, + SLOT(updateTriggerLevelValue(std::vector))); iio->connect(dc_cancel.at(i), 0, keep_one, 0); iio->connect(keep_one, 0, triggerLevelSink.first, 0); } - if (xy_is_visible) { - iio->disconnect(xy_channels.at(index_x).first, xy_channels.at(index_x).second, - ftc, 0); - iio->disconnect(xy_channels.at(index_y).first, xy_channels.at(index_y).second, - ftc, 1); + if(xy_is_visible) { + iio->disconnect(xy_channels.at(index_x).first, xy_channels.at(index_x).second, ftc, 0); + iio->disconnect(xy_channels.at(index_y).first, xy_channels.at(index_y).second, ftc, 1); xy_channels.clear(); for(unsigned int ch = 0; ch < nb_channels; ch++) { - if (chnAcCoupled.at(ch)) { - xy_channels.push_back(QPair( - dc_cancel.at(ch), 0)); + if(chnAcCoupled.at(ch)) { + xy_channels.push_back(QPair(dc_cancel.at(ch), 0)); } else { - xy_channels.push_back(QPair( - adc_samp_conv_block, ch)); + xy_channels.push_back(QPair(adc_samp_conv_block, ch)); } } - iio->connect(xy_channels.at(index_x).first, xy_channels.at(index_x).second, - ftc, 0); - iio->connect(xy_channels.at(index_y).first, xy_channels.at(index_y).second, - ftc, 1); + iio->connect(xy_channels.at(index_x).first, xy_channels.at(index_x).second, ftc, 0); + iio->connect(xy_channels.at(index_y).first, xy_channels.at(index_y).second, ftc, 1); } - if (fft_is_visible) { - for (unsigned int i = 0; i < nb_channels; i++) { - iio->disconnect(fft_channels.at(i).first, fft_channels.at(i).second, - fft_blocks.at(i), 0); + if(fft_is_visible) { + for(unsigned int i = 0; i < nb_channels; i++) { + iio->disconnect(fft_channels.at(i).first, fft_channels.at(i).second, fft_blocks.at(i), 0); } fft_channels.clear(); for(unsigned int ch = 0; ch < nb_channels; ch++) { - if (chnAcCoupled.at(ch)) { - fft_channels.push_back(QPair( - dc_cancel.at(ch), 0)); + if(chnAcCoupled.at(ch)) { + fft_channels.push_back(QPair(dc_cancel.at(ch), 0)); } else { - fft_channels.push_back(QPair( - adc_samp_conv_block, ch)); + fft_channels.push_back(QPair(adc_samp_conv_block, ch)); } - iio->connect(fft_channels.at(ch).first, fft_channels.at(ch).second, - fft_blocks.at(ch), 0); + iio->connect(fft_channels.at(ch).first, fft_channels.at(ch).second, fft_blocks.at(ch), 0); } } @@ -1762,7 +1618,7 @@ void Oscilloscope::activateAcCoupling(int i) iio->set_buffer_size(ids[ch], active_sample_count); dc_cancel.at(ch)->set_buffer_size(active_sample_count); } - if (mixed_source) { + if(mixed_source) { mixed_source->set_buffer_size(active_sample_count); setDigitalPlotCurvesParams(); } @@ -1773,9 +1629,8 @@ void Oscilloscope::activateAcCoupling(int i) void Oscilloscope::deactivateAcCoupling(int i) { - bool trigger = (i == trigger_settings.currentChannel()) - && trigger_settings.analogEnabled(); - if (trigger) { + bool trigger = (i == trigger_settings.currentChannel()) && trigger_settings.analogEnabled(); + if(trigger) { trigger_settings.setAcCoupled(false, i); } @@ -1784,9 +1639,7 @@ void Oscilloscope::deactivateAcCoupling(int i) iio->lock(); } - std::shared_ptr block = - dynamic_pointer_cast( - adc_samp_conv_block); + std::shared_ptr block = dynamic_pointer_cast(adc_samp_conv_block); iio->disconnect(dc_cancel.at(i), 0, math_probe_atten.at(i), 0); iio->connect(adc_samp_conv_block, i, math_probe_atten.at(i), 0); @@ -1799,9 +1652,9 @@ void Oscilloscope::deactivateAcCoupling(int i) iio->disconnect(dc_cancel.at(i), 0, qt_hist_block, i); iio->connect(block, i, qt_hist_block, i); - if (trigger && triggerLevelSink.first) { - disconnect(&*triggerLevelSink.first, SIGNAL(triggered(std::vector)), - this, SLOT(updateTriggerLevelValue(std::vector))); + if(trigger && triggerLevelSink.first) { + disconnect(&*triggerLevelSink.first, SIGNAL(triggered(std::vector)), this, + SLOT(updateTriggerLevelValue(std::vector))); iio->disconnect(dc_cancel.at(i), 0, keep_one, 0); iio->disconnect(keep_one, 0, triggerLevelSink.first, 0); @@ -1811,47 +1664,37 @@ void Oscilloscope::deactivateAcCoupling(int i) keep_one = nullptr; } - if (xy_is_visible) { - iio->disconnect(xy_channels.at(index_x).first, xy_channels.at(index_x).second, - ftc, 0); - iio->disconnect(xy_channels.at(index_y).first, xy_channels.at(index_y).second, - ftc, 1); + if(xy_is_visible) { + iio->disconnect(xy_channels.at(index_x).first, xy_channels.at(index_x).second, ftc, 0); + iio->disconnect(xy_channels.at(index_y).first, xy_channels.at(index_y).second, ftc, 1); xy_channels.clear(); for(unsigned int ch = 0; ch < nb_channels; ch++) { - if (chnAcCoupled.at(ch) && (ch != i)) { - xy_channels.push_back(QPair( - dc_cancel.at(ch), 0)); + if(chnAcCoupled.at(ch) && (ch != i)) { + xy_channels.push_back(QPair(dc_cancel.at(ch), 0)); } else { - xy_channels.push_back(QPair( - adc_samp_conv_block, ch)); + xy_channels.push_back(QPair(adc_samp_conv_block, ch)); } } - iio->connect(xy_channels.at(index_x).first, xy_channels.at(index_x).second, - ftc, 0); - iio->connect(xy_channels.at(index_y).first, xy_channels.at(index_y).second, - ftc, 1); + iio->connect(xy_channels.at(index_x).first, xy_channels.at(index_x).second, ftc, 0); + iio->connect(xy_channels.at(index_y).first, xy_channels.at(index_y).second, ftc, 1); } - if (fft_is_visible) { - for (unsigned int ch = 0; ch < nb_channels; ch++) { - iio->disconnect(fft_channels.at(ch).first, fft_channels.at(ch).second, - fft_blocks.at(ch), 0); + if(fft_is_visible) { + for(unsigned int ch = 0; ch < nb_channels; ch++) { + iio->disconnect(fft_channels.at(ch).first, fft_channels.at(ch).second, fft_blocks.at(ch), 0); } fft_channels.clear(); for(unsigned int ch = 0; ch < nb_channels; ch++) { - if (chnAcCoupled.at(ch) && ch != i) { - fft_channels.push_back(QPair( - dc_cancel.at(ch), 0)); + if(chnAcCoupled.at(ch) && ch != i) { + fft_channels.push_back(QPair(dc_cancel.at(ch), 0)); } else { - fft_channels.push_back(QPair( - adc_samp_conv_block, ch)); + fft_channels.push_back(QPair(adc_samp_conv_block, ch)); } - iio->connect(fft_channels.at(ch).first, fft_channels.at(ch).second, - fft_blocks.at(ch), 0); + iio->connect(fft_channels.at(ch).first, fft_channels.at(ch).second, fft_blocks.at(ch), 0); } } @@ -1859,7 +1702,7 @@ void Oscilloscope::deactivateAcCoupling(int i) iio->set_buffer_size(ids[ch], active_sample_count); dc_cancel.at(ch)->set_buffer_size(active_sample_count); } - if (mixed_source) { + if(mixed_source) { mixed_source->set_buffer_size(active_sample_count); setDigitalPlotCurvesParams(); } @@ -1872,9 +1715,9 @@ void Oscilloscope::deactivateAcCoupling(int i) void Oscilloscope::configureAcCouplingTrigger(bool enabled) { int chIdx = trigger_settings.currentChannel(); - if (enabled && chnAcCoupled.at(chIdx)) { + if(enabled && chnAcCoupled.at(chIdx)) { activateAcCouplingTrigger(chIdx); - } else if (!enabled && chnAcCoupled.at(chIdx)) { + } else if(!enabled && chnAcCoupled.at(chIdx)) { deactivateAcCouplingTrigger(); } triggerAcCoupled = enabled; @@ -1883,20 +1726,20 @@ void Oscilloscope::configureAcCouplingTrigger(bool enabled) void Oscilloscope::activateAcCouplingTrigger(int chIdx) { trigger_settings.setAcCoupled(true, chIdx); - if (!triggerLevelSink.first) { + if(!triggerLevelSink.first) { bool started = isIioManagerStarted(); - if (started) { + if(started) { iio->lock(); } triggerLevelSink.first = std::make_shared(); triggerLevelSink.second = chIdx; keep_one = gr::blocks::keep_one_in_n::make(sizeof(float), 100); - connect(&*triggerLevelSink.first, SIGNAL(triggered(std::vector)), - this, SLOT(updateTriggerLevelValue(std::vector))); + connect(&*triggerLevelSink.first, SIGNAL(triggered(std::vector)), this, + SLOT(updateTriggerLevelValue(std::vector))); iio->connect(dc_cancel.at(triggerLevelSink.second), 0, keep_one, 0); iio->connect(keep_one, 0, triggerLevelSink.first, 0); - if (started) { + if(started) { iio->unlock(); } } @@ -1905,19 +1748,19 @@ void Oscilloscope::activateAcCouplingTrigger(int chIdx) void Oscilloscope::deactivateAcCouplingTrigger() { trigger_settings.setAcCoupled(false, triggerLevelSink.second); - if (triggerLevelSink.first) { + if(triggerLevelSink.first) { bool started = isIioManagerStarted(); - if (started) { + if(started) { iio->lock(); } /* Disconnect the SLOT */ - disconnect(&*triggerLevelSink.first, SIGNAL(triggered(std::vector)), - this, SLOT(updateTriggerLevelValue(std::vector))); + disconnect(&*triggerLevelSink.first, SIGNAL(triggered(std::vector)), this, + SLOT(updateTriggerLevelValue(std::vector))); /* Disconnect the GNU Radio block */ iio->disconnect(dc_cancel.at(triggerLevelSink.second), 0, keep_one, 0); iio->disconnect(keep_one, 0, triggerLevelSink.first, 0); trigger_settings.updateHwVoltLevels(triggerLevelSink.second); - if (started) { + if(started) { iio->unlock(); } } @@ -1931,11 +1774,11 @@ void Oscilloscope::configureAcCoupling(int i, bool coupled) bool tmp = chnAcCoupled[i]; chnAcCoupled[i] = coupled; - if (coupled && !tmp) { + if(coupled && !tmp) { activateAcCoupling(i); - } else if (!coupled && tmp) { + } else if(!coupled && tmp) { deactivateAcCoupling(i); - } else if (coupled && tmp) { + } else if(coupled && tmp) { deactivateAcCoupling(i); activateAcCoupling(i); } @@ -1947,37 +1790,29 @@ void Oscilloscope::enableLabels(bool enable) plot.setUsingLeftAxisScales(enable); plot.enableLabels(enable); - if (enable) { + if(enable) { bool allDisabled = true; - for (unsigned int i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; - i++) { - ChannelWidget *cw = static_cast( - ui->channelsList->itemAt(i)->widget()); + for(unsigned int i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; i++) { + ChannelWidget *cw = static_cast(ui->channelsList->itemAt(i)->widget()); - if (cw->enableButton()->isChecked()) { + if(cw->enableButton()->isChecked()) { allDisabled = false; } } - if (!allDisabled) { + if(!allDisabled) { plot.setActiveVertAxis(current_channel); plot.enableAxisLabels(enable); } } - if (!enable) + if(!enable) plot.enableAxisLabels(enable); } -void Oscilloscope::setTrigger_input(bool value) -{ - trigger_input = value; -} +void Oscilloscope::setTrigger_input(bool value) { trigger_input = value; } -bool Oscilloscope::getTrigger_input() const -{ - return trigger_input; -} +bool Oscilloscope::getTrigger_input() const { return trigger_input; } void Oscilloscope::cursor_panel_init() { @@ -1985,42 +1820,32 @@ void Oscilloscope::cursor_panel_init() cr_ui->setupUi(ui->cursorsSettings); setDynamicProperty(cr_ui->btnLockHorizontal, "use_icon", true); setDynamicProperty(cr_ui->btnLockVertical, "use_icon", true); - //cr_ui->posSelect->setStyleSheet("background-color:red;"); + // cr_ui->posSelect->setStyleSheet("background-color:red;"); - connect(cr_ui->btnLockHorizontal, &QPushButton::toggled, - &plot, &CapturePlot::setHorizCursorsLocked); - connect(cr_ui->btnLockVertical, &QPushButton::toggled, - &plot, &CapturePlot::setVertCursorsLocked); + connect(cr_ui->btnLockHorizontal, &QPushButton::toggled, &plot, &CapturePlot::setHorizCursorsLocked); + connect(cr_ui->btnLockVertical, &QPushButton::toggled, &plot, &CapturePlot::setVertCursorsLocked); cursorsPositionButton = new CustomPlotPositionButton(cr_ui->posSelect); - connect(cr_ui->hCursorsEnable, SIGNAL(toggled(bool)), - &plot, SLOT(setVertCursorsEnabled(bool))); - connect(cr_ui->vCursorsEnable, SIGNAL(toggled(bool)), - &plot, SLOT(setHorizCursorsEnabled(bool))); + connect(cr_ui->hCursorsEnable, SIGNAL(toggled(bool)), &plot, SLOT(setVertCursorsEnabled(bool))); + connect(cr_ui->vCursorsEnable, SIGNAL(toggled(bool)), &plot, SLOT(setHorizCursorsEnabled(bool))); - connect(cr_ui->hCursorsEnable, SIGNAL(toggled(bool)), - cursor_readouts_ui->TimeCursors, - SLOT(setVisible(bool))); - connect(cr_ui->vCursorsEnable, SIGNAL(toggled(bool)), - cursor_readouts_ui->VoltageCursors, + connect(cr_ui->hCursorsEnable, SIGNAL(toggled(bool)), cursor_readouts_ui->TimeCursors, SLOT(setVisible(bool))); + connect(cr_ui->vCursorsEnable, SIGNAL(toggled(bool)), cursor_readouts_ui->VoltageCursors, SLOT(setVisible(bool))); - connect(cr_ui->btnNormalTrack, &QPushButton::toggled, - this, &Oscilloscope::toggleCursorsMode); + connect(cr_ui->btnNormalTrack, &QPushButton::toggled, this, &Oscilloscope::toggleCursorsMode); cr_ui->horizontalSlider->setMaximum(100); cr_ui->horizontalSlider->setMinimum(0); cr_ui->horizontalSlider->setSingleStep(1); - connect(cr_ui->horizontalSlider, &QSlider::valueChanged, [=](int value){ + connect(cr_ui->horizontalSlider, &QSlider::valueChanged, [=](int value) { cr_ui->transLabel->setText(tr("Transparency ") + QString::number(value) + "%"); plot.setCursorReadoutsTransparency(value); }); cr_ui->horizontalSlider->setSliderPosition(0); connect(cursorsPositionButton, &CustomPlotPositionButton::positionChanged, - [=](CustomPlotPositionButton::ReadoutsPosition position){ - plot.moveCursorReadouts(position); - }); + [=](CustomPlotPositionButton::ReadoutsPosition position) { plot.moveCursorReadouts(position); }); } void Oscilloscope::toggleCursorsMode(bool toggled) @@ -2028,7 +1853,7 @@ void Oscilloscope::toggleCursorsMode(bool toggled) cr_ui->hCursorsEnable->setEnabled(toggled); cr_ui->vCursorsEnable->setEnabled(toggled); - if (toggled) { + if(toggled) { plot.setVertCursorsEnabled(hCursorsEnabled); plot.setHorizCursorsEnabled(vCursorsEnabled); cursor_readouts_ui->TimeCursors->setVisible(vCursorsEnabled); @@ -2048,20 +1873,18 @@ void Oscilloscope::toggleCursorsMode(bool toggled) void Oscilloscope::toolDetached(bool detached) { - if (detached) { + if(detached) { this->setMinimumSize(910, 490); - this->setSizePolicy(QSizePolicy::Preferred, - QSizePolicy::Preferred); + this->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); } else { this->setMinimumWidth(0); - this->setSizePolicy(QSizePolicy::MinimumExpanding, - QSizePolicy::MinimumExpanding); + this->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); } } void Oscilloscope::pause(bool paused) { - if (ui->runSingleWidget->runButtonChecked()){ + if(ui->runSingleWidget->runButtonChecked()) { toggle_blockchain_flow(!paused); trigger_settings.setAdcRunningState(!paused); } @@ -2074,20 +1897,16 @@ void Oscilloscope::export_settings_init() exportSettings->enableExportButton(false); gsettings_ui->export_2->addWidget(exportSettings); - for (size_t i = 0; i < nb_channels; ++i){ - exportSettings->addChannel(i, QString("Channel") + - QString::number(i + 1)); + for(size_t i = 0; i < nb_channels; ++i) { + exportSettings->addChannel(i, QString("Channel") + QString::number(i + 1)); } - connect(exportSettings->getExportButton(), SIGNAL(clicked()), this, - SLOT(btnExport_clicked())); - connect(this, &Oscilloscope::activateExportButton, - [=](){ - exportSettings->enableExportButton(true); - }); + connect(exportSettings->getExportButton(), SIGNAL(clicked()), this, SLOT(btnExport_clicked())); + connect(this, &Oscilloscope::activateExportButton, [=]() { exportSettings->enableExportButton(true); }); } -void Oscilloscope::btnExport_clicked(){ +void Oscilloscope::btnExport_clicked() +{ exportConfig = exportSettings->getExportConfig(); pause(true); @@ -2098,11 +1917,11 @@ void Oscilloscope::btnExport_clicked(){ QString selectedFilter = filter[0]; - QString fileName = QFileDialog::getSaveFileName(this, - tr("Export"), "", filter.join(";;"), - &selectedFilter, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); + QString fileName = QFileDialog::getSaveFileName( + this, tr("Export"), "", filter.join(";;"), &selectedFilter, + (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); - if (fileName.split(".").size() <= 1) { + if(fileName.split(".").size() <= 1) { // file name w/o extension. Let's append it QString ext = selectedFilter.split(".")[1].split(")")[0]; fileName += "." + ext; @@ -2110,33 +1929,33 @@ void Oscilloscope::btnExport_clicked(){ bool atleastOneChannelEnabled = false; auto keys = exportConfig.keys(); - for (auto x : qAsConst(keys)) - if (exportConfig[x]){ + for(auto x : qAsConst(keys)) + if(exportConfig[x]) { atleastOneChannelEnabled = true; break; } - if (!atleastOneChannelEnabled){ + if(!atleastOneChannelEnabled) { return; } - if (!fileName.isEmpty()){ + if(!fileName.isEmpty()) { FileManager fm("Oscilloscope"); fm.open(fileName, FileManager::EXPORT); int channels_number = nb_channels + nb_math_channels; QVector time_data; - for (size_t i = 0; i < plot.Curve(0)->data()->size(); ++i) { + for(size_t i = 0; i < plot.Curve(0)->data()->size(); ++i) { time_data.push_back(plot.Curve(0)->sample(i).x()); } fm.save(time_data, "Time(S)"); - for (int i = 0; i < channels_number; ++i){ - if (exportConfig[i]){ + for(int i = 0; i < channels_number; ++i) { + if(exportConfig[i]) { QVector data; int samples = plot.Curve(i)->data()->size(); - for (int j = 0; j < samples; ++j) + for(int j = 0; j < samples; ++j) data.push_back(plot.Curve(i)->data()->sample(j).y()); QString chNo = (i > 1) ? QString::number(i - 1) : QString::number(i + 1); @@ -2164,7 +1983,8 @@ void Oscilloscope::create_add_channel_panel() QVBoxLayout *layout_logic = new QVBoxLayout(logic); logic->setLayout(layout_logic); - QLabel *labelWarningMixedSignal = new QLabel(tr("\"Warning: This feature is not supported on the current firmware version!\"")); + QLabel *labelWarningMixedSignal = + new QLabel(tr("\"Warning: This feature is not supported on the current firmware version!\"")); labelWarningMixedSignal->setObjectName(QString::fromUtf8("lblWarningMixedSignal")); QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); sizePolicy.setHorizontalStretch(0); @@ -2175,11 +1995,14 @@ void Oscilloscope::create_add_channel_panel() labelWarningMixedSignal->setVisible(false); layout_logic->insertSpacerItem(0, new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); - layout_logic->setContentsMargins(0,0,0,0); + layout_logic->setContentsMargins(0, 0, 0, 0); layout_logic->insertWidget(1, labelWarningMixedSignal); - QLabel *infoLabel = new QLabel(tr("* When the Mixed Signal View is enabled the LogicAnalyzer tool will be disabled!\n" - "** The trigger can be disabled or set only on the Digital channels or Analog channels, not on both at the same time!"), panel); + QLabel *infoLabel = + new QLabel(tr("* When the Mixed Signal View is enabled the LogicAnalyzer tool will be disabled!\n" + "** The trigger can be disabled or set only on the Digital channels or Analog channels, " + "not on both at the same time!"), + panel); layout_logic->insertWidget(2, infoLabel); infoLabel->setWordWrap(true); infoLabel->setVisible(true); @@ -2190,11 +2013,9 @@ void Oscilloscope::create_add_channel_panel() math_pair = new QPair(math_ui, math); - connect(math, &Math::functionValid, - [=](const QString &function) { + connect(math, &Math::functionValid, [=](const QString &function) { btn->setEnabled(true); - btn->setProperty("function", - QVariant(function)); + btn->setProperty("function", QVariant(function)); lastFunctionValid = true; }); @@ -2204,11 +2025,10 @@ void Oscilloscope::create_add_channel_panel() }); QHBoxLayout *layout = static_cast(panel->layout()); - QSpacerItem *spacerItem = new QSpacerItem(0, 0, QSizePolicy::Minimum, - QSizePolicy::Expanding); + QSpacerItem *spacerItem = new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding); tabWidget = new QTabWidget(panel); layout->insertWidget(0, tabWidget); - //set top margin to 0 and the rest to 9 + // set top margin to 0 and the rest to 9 layout->setContentsMargins(9, 0, 9, 9); tabWidget->addTab(math, tr("Math")); @@ -2232,32 +2052,25 @@ void Oscilloscope::create_add_channel_panel() "line-height: 14px;" "color: #FFFFFF;}" "QPushButton:hover{" - "background-color: #4a34ff;" + "background-color: #4a34ff;" "}"); btnOpenFile->setText(tr("Browse")); layout_file_select->addWidget(btnOpenFile); - refChannelTimeBase = new ScaleSpinButton({ - {"ns", 1E-9}, - {"μs", 1E-6}, - {"ms", 1E-3}, - {"s", 1E0} - }, tr("Time Base"), 100e-9, 1E0, - true, false, this); + refChannelTimeBase = new ScaleSpinButton({{"ns", 1E-9}, {"μs", 1E-6}, {"ms", 1E-3}, {"s", 1E0}}, + tr("Time Base"), 100e-9, 1E0, true, false, this); refChannelTimeBase->setValue(1e-3); refChannelTimeBase->setDisabled(true); - connect(refChannelTimeBase, &ScaleSpinButton::valueChanged, [=](double value){ - plot.updatePreview(value, timeBase->value(), timePosition->value()); - }); + connect(refChannelTimeBase, &ScaleSpinButton::valueChanged, + [=](double value) { plot.updatePreview(value, timeBase->value(), timePosition->value()); }); layout_ref->addWidget(file_select); layout_ref->addWidget(importSettings); layout_ref->addWidget(refChannelTimeBase); layout_ref->addSpacerItem(spacerItem); - importSettings->setDisabled(true); fileLineEdit->setText(tr("No file selected")); @@ -2267,15 +2080,15 @@ void Oscilloscope::create_add_channel_panel() tabWidget->addTab(logic, tr("Logic")); - connect(ui->mixedSignalBtn, &QPushButton::clicked, [=](){ - if (!m_mixedSignalViewEnabled) { + connect(ui->mixedSignalBtn, &QPushButton::clicked, [=]() { + if(!m_mixedSignalViewEnabled) { ui->btnAddMath->click(); tabWidget->setCurrentIndex(tabWidget->indexOf(logic)); } else { - for (int i = 0; i < ui->channelsList->count(); ++i) { - ChannelWidget *cw = qobject_cast( - ui->channelsList->itemAt(i)->widget()); - if (cw && cw->fullName() == "Logic Analyzer") { + for(int i = 0; i < ui->channelsList->count(); ++i) { + ChannelWidget *cw = + qobject_cast(ui->channelsList->itemAt(i)->widget()); + if(cw && cw->fullName() == "Logic Analyzer") { cw->deleteButton()->click(); break; } @@ -2287,35 +2100,33 @@ void Oscilloscope::create_add_channel_panel() connect(tabWidget, &QTabWidget::currentChanged, [=](int index) { btn->setVisible(true); - if (index == 0) { - btn->setText(tr("Add channel")); - btn->setEnabled(lastFunctionValid); - labelWarningMixedSignal->setVisible(false); - } else if (index == 1) { - btn->setText(tr("Import selected channels")); - btn->setEnabled(importSettings->isEnabled()); - labelWarningMixedSignal->setVisible(false); - } else if (index == 2) { - btn->setText(tr("Enable Mixed Signal View")); - if (m_m2k_context->hasMixedSignal()) { - btn->setEnabled(true); - } else { - btn->setEnabled(false); - labelWarningMixedSignal->setVisible(true); - } - } + if(index == 0) { + btn->setText(tr("Add channel")); + btn->setEnabled(lastFunctionValid); + labelWarningMixedSignal->setVisible(false); + } else if(index == 1) { + btn->setText(tr("Import selected channels")); + btn->setEnabled(importSettings->isEnabled()); + labelWarningMixedSignal->setVisible(false); + } else if(index == 2) { + btn->setText(tr("Enable Mixed Signal View")); + if(m_m2k_context->hasMixedSignal()) { + btn->setEnabled(true); + } else { + btn->setEnabled(false); + labelWarningMixedSignal->setVisible(true); + } + } }); - connect(btn, &QPushButton::clicked, - [=]() { - - if (tabWidget->currentIndex() == 2) { + connect(btn, &QPushButton::clicked, [=]() { + if(tabWidget->currentIndex() == 2) { qDebug() << "Enable mixed signal view!"; ui->mixedSignalBtn->setText("Disable Mixed\nSignal View"); - ChannelWidget *logicAnalyzerChannelWidget = new ChannelWidget(-1, true, false, - QColor(Qt::yellow), this); + ChannelWidget *logicAnalyzerChannelWidget = + new ChannelWidget(-1, true, false, QColor(Qt::yellow), this); logicAnalyzerChannelWidget->setFullName("Logic Analyzer"); logicAnalyzerChannelWidget->setShortName("Logic"); ui->channelsList->addWidget(logicAnalyzerChannelWidget); @@ -2329,24 +2140,29 @@ void Oscilloscope::create_add_channel_panel() const int logicId = ui->stackedWidget->indexOf(ui->logicSettings); logicAnalyzerChannelWidget->menuButton()->setProperty("id", QVariant(-logicId)); - connect(logicAnalyzerChannelWidget->menuButton(), &QAbstractButton::toggled, [=](bool toggled){ + connect(logicAnalyzerChannelWidget->menuButton(), &QAbstractButton::toggled, [=](bool toggled) { triggerRightMenuToggle( - static_cast(logicAnalyzerChannelWidget->menuButton()), toggled); + static_cast(logicAnalyzerChannelWidget->menuButton()), + toggled); }); const int logicTab = tabWidget->currentIndex(); tabWidget->setTabEnabled(logicTab, false); - connect(logicAnalyzerChannelWidget->deleteButton(), &QAbstractButton::clicked, [=](){ - - if (logicAnalyzerChannelWidget->menuButton()->isChecked()) { - menuButtonActions.removeAll(QPair - (static_cast(logicAnalyzerChannelWidget->menuButton()), true)); - toggleRightMenu(static_cast(logicAnalyzerChannelWidget->menuButton()), false); + connect(logicAnalyzerChannelWidget->deleteButton(), &QAbstractButton::clicked, [=]() { + if(logicAnalyzerChannelWidget->menuButton()->isChecked()) { + menuButtonActions.removeAll(QPair( + static_cast( + logicAnalyzerChannelWidget->menuButton()), + true)); + toggleRightMenu(static_cast( + logicAnalyzerChannelWidget->menuButton()), + false); } - menuOrder.removeOne(static_cast(logicAnalyzerChannelWidget->menuButton())); + menuOrder.removeOne( + static_cast(logicAnalyzerChannelWidget->menuButton())); ui->channelsList->removeWidget(logicAnalyzerChannelWidget); logicAnalyzerChannelWidget->deleteLater(); @@ -2364,18 +2180,17 @@ void Oscilloscope::create_add_channel_panel() return; } - if (tabWidget->currentIndex() != 0) { + if(tabWidget->currentIndex() != 0) { QMap import_map = importSettings->getExportConfig(); auto keys = import_map.keys(); - for (int key : qAsConst(keys)) { - if (import_map[key]) { + for(int key : qAsConst(keys)) { + if(import_map[key]) { add_ref_waveform(key); } } plot.clearPreview(); - ChannelWidget *cw = channelWidgetAtId(nb_channels + nb_math_channels + - nb_ref_channels - 1); + ChannelWidget *cw = channelWidgetAtId(nb_channels + nb_math_channels + nb_ref_channels - 1); triggerRightMenuToggle(ui->btnAddMath, false); cw->menuButton()->setChecked(true); refChannelTimeBase->setDisabled(true); @@ -2386,24 +2201,23 @@ void Oscilloscope::create_add_channel_panel() return; } - if (addChannel) { + if(addChannel) { QVariant var = btn->property("function"); add_math_channel(var.toString().toStdString()); } else { QVariant var = btn->property("function"); - editMathChannelFunction(current_ch_widget, - var.toString().toStdString()); + editMathChannelFunction(current_ch_widget, var.toString().toStdString()); } }); connect(this, &Oscilloscope::importFileLoaded, [=](bool loaded) { - btn->setEnabled(loaded); - importSettings->setEnabled(loaded); - fileLineEdit->setText(import_error); - fileLineEdit->setToolTip(loaded ? import_error : ""); - if (!loaded) { - importSettings->clear(); - } + btn->setEnabled(loaded); + importSettings->setEnabled(loaded); + fileLineEdit->setText(import_error); + fileLineEdit->setToolTip(loaded ? import_error : ""); + if(!loaded) { + importSettings->clear(); + } }); int panel_id = ui->stackedWidget->insertWidget(-1, panel); @@ -2412,10 +2226,11 @@ void Oscilloscope::create_add_channel_panel() void Oscilloscope::import() { - QString fileName = QFileDialog::getOpenFileName(this, - tr("Import"), "", tr("Comma-separated values files (*.csv);;" - "Tab-delimited values files (*.txt)"), - nullptr, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); + QString fileName = QFileDialog::getOpenFileName( + this, tr("Import"), "", + tr("Comma-separated values files (*.csv);;" + "Tab-delimited values files (*.txt)"), + nullptr, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); FileManager fm("Oscilloscope"); @@ -2429,7 +2244,7 @@ void Oscilloscope::import() double sampRate = fm.getSampleRate(); double timeBase = (nrOfSamples / 16.0) / sampRate; - if (fm.getFormat() == FileManager::RAW) { + if(fm.getFormat() == FileManager::RAW) { refChannelTimeBase->setEnabled(true); } else { refChannelTimeBase->setEnabled(false); @@ -2437,23 +2252,23 @@ void Oscilloscope::import() } QVector> data = fm.read(); - for (int i = 0; i < data.size(); ++i) { + for(int i = 0; i < data.size(); ++i) { import_data.push_back(data[i]); } import_error = fileName; Q_EMIT importFileLoaded(true); - for (int i = 0; i < fm.getNrOfChannels(); ++i) { + for(int i = 0; i < fm.getNrOfChannels(); ++i) { importSettings->addChannel(i, fm.getColumnName(i).remove("(V)")); } - if (refChannelTimeBase->isEnabled()) { - plot.addPreview(import_data, refChannelTimeBase->value(), - this->timeBase->value(), timePosition->value()); + if(refChannelTimeBase->isEnabled()) { + plot.addPreview(import_data, refChannelTimeBase->value(), this->timeBase->value(), + timePosition->value()); } - } catch (FileManagerException &ex) { + } catch(FileManagerException &ex) { import_error = QString(ex.what()); Q_EMIT importFileLoaded(false); } @@ -2467,12 +2282,12 @@ unsigned int Oscilloscope::find_curve_number() do { found = false; - for (unsigned int i = 0; !found && i < (nb_math_channels + nb_ref_channels); i++) { + for(unsigned int i = 0; !found && i < (nb_math_channels + nb_ref_channels); i++) { QWidget *parent = ui->channelsList->itemAt(nb_channels + i)->widget(); ChannelWidget *cw = static_cast(parent); - if (cw->isReferenceChannel()) { + if(cw->isReferenceChannel()) { continue; } @@ -2480,14 +2295,14 @@ unsigned int Oscilloscope::find_curve_number() } id++; - } while (found); + } while(found); return id - 1; } -void Oscilloscope::add_math_channel(const std::string& function) +void Oscilloscope::add_math_channel(const std::string &function) { - if (nb_math_channels + nb_ref_channels == MAX_MATH_CHANNELS) { + if(nb_math_channels + nb_ref_channels == MAX_MATH_CHANNELS) { return; } @@ -2502,41 +2317,38 @@ void Oscilloscope::add_math_channel(const std::string& function) QString qname = QString("Math %1").arg(math_chn_counter++); std::string name = qname.toStdString(); - auto math_sink = scope_sink_f::make( - noZoomXAxisWidth * getSampleRate() / m_m2k_analogin->getOversamplingRatio(), - getSampleRate() / m_m2k_analogin->getOversamplingRatio(), name, 1, (QObject *)&plot); + auto math_sink = + scope_sink_f::make(noZoomXAxisWidth * getSampleRate() / m_m2k_analogin->getOversamplingRatio(), + getSampleRate() / m_m2k_analogin->getOversamplingRatio(), name, 1, (QObject *)&plot); double targetFps = p->get("general_plot_target_fps").toDouble(); - math_sink->set_update_time(1.0/targetFps); + math_sink->set_update_time(1.0 / targetFps); /* Add the math block and the math scope sink into a container, so that * we can disconnect them when removing the math channel later */ - auto math_pair = QPair( - math, math_sink); + auto math_pair = QPair(math, math_sink); math_sinks.insert(qname, math_pair); math_rails.insert(qname, rail); /* Lock the flowgraph if we are already started */ bool started = isIioManagerStarted(); - if (started) + if(started) iio->lock(); math_sink->set_trigger_mode(TRIG_MODE_TAG, 0, "buffer_start"); - for (unsigned int i = 0; i < nb_channels; i++) { + for(unsigned int i = 0; i < nb_channels; i++) { iio->connect(math_probe_atten.at(i), 0, math, i); } iio->connect(math, 0, rail, 0); iio->connect(rail, 0, math_sink, 0); - if (started) + if(started) iio->unlock(); - plot.registerMathWaveform(name, 1, - noZoomXAxisWidth * - getSampleRate()); + plot.registerMathWaveform(name, 1, noZoomXAxisWidth * getSampleRate()); - ChannelWidget *channel_widget = new ChannelWidget(curve_id, true, false, - plot.getLineColor(curve_id).name(), this); + ChannelWidget *channel_widget = + new ChannelWidget(curve_id, true, false, plot.getLineColor(curve_id).name(), this); channel_widget->setMathChannel(true); channel_widget->setFunction(QString::fromStdString(function)); @@ -2545,24 +2357,17 @@ void Oscilloscope::add_math_channel(const std::string& function) channel_widget->setShortName(QString("M%1").arg(curve_number + 1)); channel_widget->nameButton()->setText(channel_widget->shortName()); - exportSettings->addChannel(curve_id - nb_ref_channels, - channel_widget->fullName()); + exportSettings->addChannel(curve_id - nb_ref_channels, channel_widget->fullName()); channel_widget->setProperty("curve_nb", QVariant(curve_number)); - channel_widget->deleteButton()->setProperty( - "curve_name", QVariant(qname)); - - connect(channel_widget, SIGNAL(enabled(bool)), - SLOT(onChannelWidgetEnabled(bool))); - connect(channel_widget, SIGNAL(selected(bool)), - SLOT(onChannelWidgetSelected(bool))); - connect(channel_widget, SIGNAL(menuToggled(bool)), - SLOT(onChannelWidgetMenuToggled(bool))); - connect(channel_widget, SIGNAL(deleteClicked()), - SLOT(onChannelWidgetDeleteClicked())); - connect(channel_widget, &ChannelWidget::menuToggled, - [=](bool on){ - if (!on) + channel_widget->deleteButton()->setProperty("curve_name", QVariant(qname)); + + connect(channel_widget, SIGNAL(enabled(bool)), SLOT(onChannelWidgetEnabled(bool))); + connect(channel_widget, SIGNAL(selected(bool)), SLOT(onChannelWidgetSelected(bool))); + connect(channel_widget, SIGNAL(menuToggled(bool)), SLOT(onChannelWidgetMenuToggled(bool))); + connect(channel_widget, SIGNAL(deleteClicked()), SLOT(onChannelWidgetDeleteClicked())); + connect(channel_widget, &ChannelWidget::menuToggled, [=](bool on) { + if(!on) ch_ui->btnEditMath->setChecked(false); }); @@ -2572,18 +2377,16 @@ void Oscilloscope::add_math_channel(const std::string& function) ui->settings_group->addButton(channel_widget->menuButton()); channel_widget->nameButton()->setChecked(true); - QLabel *label= new QLabel(this); - label->setText(vertMeasureFormat.format( - plot.VertUnitsPerDiv(curve_id), "V/div", 3)); - label->setStyleSheet(QString("QLabel {" - "color: %1;" - "font-weight: bold;" - "}").arg(plot.getLineColor(curve_id).name())); - ui->chn_scales->addWidget(label); + QLabel *label = new QLabel(this); + label->setText(vertMeasureFormat.format(plot.VertUnitsPerDiv(curve_id), "V/div", 3)); + label->setStyleSheet(QString("QLabel {" + "color: %1;" + "font-weight: bold;" + "}") + .arg(plot.getLineColor(curve_id).name())); + ui->chn_scales->addWidget(label); - plot.Curve(curve_id)->setAxes( - QwtAxisId(QwtAxis::XBottom, 0), - QwtAxisId(QwtAxis::YLeft, curve_id)); + plot.Curve(curve_id)->setAxes(QwtAxisId(QwtAxis::XBottom, 0), QwtAxisId(QwtAxis::YLeft, curve_id)); plot.Curve(curve_id)->setTitle("M " + QString::number(curve_number + 1)); plot.addZoomer(curve_id); plot.replot(); @@ -2596,11 +2399,11 @@ void Oscilloscope::add_math_channel(const std::string& function) plot.setPeriodDetectHyst(curve_id, 1.0 / 5); // Keep the current selected channels curve on top of the other ones - if (isVisible() && channelWidgetAtId(current_channel)->enableButton()->isChecked()) + if(isVisible() && channelWidgetAtId(current_channel)->enableButton()->isChecked()) plot.bringCurveToFront(current_channel); - if (nb_math_channels + nb_ref_channels == MAX_MATH_CHANNELS) { - if (ui->btnAddMath->isChecked()) { + if(nb_math_channels + nb_ref_channels == MAX_MATH_CHANNELS) { + if(ui->btnAddMath->isChecked()) { ui->btnAddMath->setChecked(false); } @@ -2620,7 +2423,7 @@ void Oscilloscope::add_math_channel(const std::string& function) void Oscilloscope::onChannelWidgetDeleteClicked() { - if (nb_math_channels + nb_ref_channels - 1 < MAX_MATH_CHANNELS) { + if(nb_math_channels + nb_ref_channels - 1 < MAX_MATH_CHANNELS) { ui->btnAddMath->show(); } @@ -2630,34 +2433,31 @@ void Oscilloscope::onChannelWidgetDeleteClicked() unsigned int curve_id = cw->id(); probe_attenuation.removeAt(curve_id); - if (curve_id == current_ch_widget && - cw->menuButton()->isChecked()) { - menuButtonActions.removeAll(QPair - (static_cast(cw->menuButton()), true)); - toggleRightMenu(static_cast(cw->menuButton()), false); + if(curve_id == current_ch_widget && cw->menuButton()->isChecked()) { + menuButtonActions.removeAll( + QPair(static_cast(cw->menuButton()), true)); + toggleRightMenu(static_cast(cw->menuButton()), false); } - menuOrder.removeOne(static_cast(cw->menuButton())); + menuOrder.removeOne(static_cast(cw->menuButton())); /*If there are no more channels enabled, we should disable the measurements.*/ bool shouldDisable = true; - for (unsigned int i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; - i++) { - ChannelWidget *cw = static_cast( - ui->channelsList->itemAt(i)->widget()); - if (curve_id == cw->id()) + for(unsigned int i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; i++) { + ChannelWidget *cw = static_cast(ui->channelsList->itemAt(i)->widget()); + if(curve_id == cw->id()) continue; - if (cw->enableButton()->isChecked()) + if(cw->enableButton()->isChecked()) shouldDisable = false; } - if (shouldDisable) + if(shouldDisable) measure_settings->disableDisplayAll(); measure_settings->onChannelRemoved(curve_id); - if (cw->isMathChannel()) { + if(cw->isMathChannel()) { plot.unregisterMathWaveform(qname.toStdString()); exportSettings->removeChannel(curve_id - nb_ref_channels); @@ -2666,7 +2466,7 @@ void Oscilloscope::onChannelWidgetDeleteClicked() /* Lock the flowgraph if we are already started */ bool started = isIioManagerStarted(); - if (started) { + if(started) { iio->lock(); } @@ -2677,12 +2477,12 @@ void Oscilloscope::onChannelWidgetDeleteClicked() gsettings_ui->cmb_x_channel->removeItem(curve_id); gsettings_ui->cmb_y_channel->removeItem(curve_id); - if (index_x >= curve_id) { - gsettings_ui->cmb_x_channel->setCurrentIndex(curve_id-1); + if(index_x >= curve_id) { + gsettings_ui->cmb_x_channel->setCurrentIndex(curve_id - 1); } - if (index_y >= curve_id) { - gsettings_ui->cmb_y_channel->setCurrentIndex(curve_id-1); + if(index_y >= curve_id) { + gsettings_ui->cmb_y_channel->setCurrentIndex(curve_id - 1); } gsettings_ui->cmb_x_channel->blockSignals(false); @@ -2693,40 +2493,36 @@ void Oscilloscope::onChannelWidgetDeleteClicked() auto pair = math_sinks.take(qname); auto rail = math_rails.take(qname); - for (unsigned int i = 0; i < nb_channels; i++) { + for(unsigned int i = 0; i < nb_channels; i++) { iio->disconnect(math_probe_atten.at(i), 0, pair.first, i); } iio->disconnect(pair.first, 0, rail, 0); iio->disconnect(rail, 0, pair.second, 0); - if (xy_is_visible) { + if(xy_is_visible) { setup_xy_channels(); } locked = false; - if (started) { + if(started) { iio->unlock(); } - for (unsigned int i = curve_id + 1; - i < nb_channels + nb_math_channels + nb_ref_channels; i++) { - ChannelWidget *w = static_cast( - ui->channelsList->itemAt(i)->widget()); + for(unsigned int i = curve_id + 1; i < nb_channels + nb_math_channels + nb_ref_channels; i++) { + ChannelWidget *w = static_cast(ui->channelsList->itemAt(i)->widget()); /* Update the IDs */ w->setId(i - 1); } nb_math_channels--; - } else if (cw->isReferenceChannel()) { + } else if(cw->isReferenceChannel()) { plot.unregisterReferenceWaveform(qname); - for (unsigned int i = curve_id + 1; - i < nb_channels + nb_math_channels + nb_ref_channels; i++) { - ChannelWidget *w = static_cast( - ui->channelsList->itemAt(i)->widget()); + for(unsigned int i = curve_id + 1; i < nb_channels + nb_math_channels + nb_ref_channels; i++) { + ChannelWidget *w = static_cast(ui->channelsList->itemAt(i)->widget()); /* Update the IDs */ w->setId(i - 1); @@ -2744,23 +2540,21 @@ void Oscilloscope::onChannelWidgetDeleteClicked() else update the plots axis and zoomer properties from channel 0.*/ bool channelsEnabled = false; - if (curve_id < current_channel) { + if(curve_id < current_channel) { /*If the deleted math channel is before the current channel, we will need to update the current channel to its new value.*/ current_channel -= 1; - if (curve_id < current_ch_widget) { + if(curve_id < current_ch_widget) { current_ch_widget -= 1; } channelsEnabled = true; Q_EMIT selectedChannelChanged(current_channel); update_measure_for_channel(current_channel); - } else if (curve_id == current_channel) { - for (unsigned int i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; - i++) { - ChannelWidget *cw = static_cast( - ui->channelsList->itemAt(i)->widget()); + } else if(curve_id == current_channel) { + for(unsigned int i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; i++) { + ChannelWidget *cw = static_cast(ui->channelsList->itemAt(i)->widget()); - if (cw->enableButton()->isChecked()) { + if(cw->enableButton()->isChecked()) { channelsEnabled = true; Q_EMIT selectedChannelChanged(0); update_measure_for_channel(0); @@ -2770,8 +2564,8 @@ void Oscilloscope::onChannelWidgetDeleteClicked() break; } } - if (channelsEnabled) { - if (curve_id < current_ch_widget) { + if(channelsEnabled) { + if(curve_id < current_ch_widget) { current_ch_widget -= 1; } } else { @@ -2779,7 +2573,7 @@ void Oscilloscope::onChannelWidgetDeleteClicked() Q_EMIT selectedChannelChanged(0); enableLabels(false); } - } else if (curve_id < current_ch_widget) { + } else if(curve_id < current_ch_widget) { current_ch_widget -= 1; channelsEnabled = true; } @@ -2789,7 +2583,7 @@ void Oscilloscope::onChannelWidgetDeleteClicked() /* If the removed channel is before the current axis, we update the * current axis to account for the index change */ int current_axis = plot.activeVertAxis(); - if (channelsEnabled && (current_axis > curve_id)) + if(channelsEnabled && (current_axis > curve_id)) plot.setActiveVertAxis(current_axis - 1); /* Before removing the axis, remove the offset widgets */ @@ -2803,12 +2597,9 @@ void Oscilloscope::onChannelWidgetDeleteClicked() ui->chn_scales->removeWidget(scale_lbl); delete scale_lbl; - for (unsigned int i = nb_channels; - i < nb_channels + nb_math_channels + nb_ref_channels; i++) { + for(unsigned int i = nb_channels; i < nb_channels + nb_math_channels + nb_ref_channels; i++) { /* Update the curve-to-axis map */ - plot.Curve(i)->setAxes( - QwtAxisId(QwtAxis::XBottom, 0), - QwtAxisId(QwtAxis::YLeft, i)); + plot.Curve(i)->setAxes(QwtAxisId(QwtAxis::XBottom, 0), QwtAxisId(QwtAxis::YLeft, i)); } onMeasurementSelectionListChanged(); @@ -2820,33 +2611,30 @@ void Oscilloscope::onChannelWidgetDeleteClicked() void Oscilloscope::clearMathChannels() { int idx = 2; - while (nb_math_channels) { - if (!channelWidgetAtId(idx)->isReferenceChannel()) { + while(nb_math_channels) { + if(!channelWidgetAtId(idx)->isReferenceChannel()) { channelWidgetAtId(idx)->deleteButton()->click(); } else { idx++; } - } } -void Oscilloscope::on_actionClose_triggered() -{ - this->close(); -} +void Oscilloscope::on_actionClose_triggered() { this->close(); } void Oscilloscope::toggle_blockchain_flow(bool en) { - if (en) { + if(en) { - if (m_mixedSignalViewEnabled) { + if(m_mixedSignalViewEnabled) { // enable the mixed_source in the iio_manager iio->enableMixedSignal(mixed_source); - std::shared_ptr block = dynamic_pointer_cast(adc_samp_conv_block); + std::shared_ptr block = + dynamic_pointer_cast(adc_samp_conv_block); // connect analog - for (size_t i = 0; i < nb_channels; ++i) { + for(size_t i = 0; i < nb_channels; ++i) { iio->disconnect(block, i, qt_time_block, i); iio->connect(block, i, mixed_sink, i); } @@ -2861,31 +2649,32 @@ void Oscilloscope::toggle_blockchain_flow(bool en) mixed_sink->set_nsamps(active_sample_count); } - if (autosetRequested) { + if(autosetRequested) { iio->start(autoset_id[0]); } - for (unsigned int i = 0; i < nb_channels; i++) + for(unsigned int i = 0; i < nb_channels; i++) iio->start(ids[i]); scaleHistogramPlot(); } else { - for (unsigned int i = 0; i < nb_channels; i++) + for(unsigned int i = 0; i < nb_channels; i++) iio->stop(ids[i]); - if (autosetRequested) { - iio->stop(autoset_id[0]); + if(autosetRequested) { + iio->stop(autoset_id[0]); } - if (m_mixedSignalViewEnabled) { + if(m_mixedSignalViewEnabled) { iio->disableMixedSignal(mixed_source); - std::shared_ptr block = dynamic_pointer_cast(adc_samp_conv_block); + std::shared_ptr block = + dynamic_pointer_cast(adc_samp_conv_block); // disconnect analog - for (size_t i = 0; i < nb_channels; ++i) { + for(size_t i = 0; i < nb_channels; ++i) { iio->disconnect(block, i, mixed_sink, i); iio->connect(block, i, qt_time_block, i); } @@ -2909,16 +2698,16 @@ void Oscilloscope::stop() void Oscilloscope::runStopToggled(bool checked) { - if (m_running == checked) { + if(m_running == checked) { return; } Q_EMIT activateExportButton(); - if (checked) { - ResourceManager::open("m2k-adc",this); + if(checked) { + ResourceManager::open("m2k-adc", this); periodicFlowRestart(true); - if (symmBufferMode->isEnhancedMemDepth()) { + if(symmBufferMode->isEnhancedMemDepth()) { onCmbMemoryDepthChanged(ch_ui->cmbMemoryDepth->currentText()); } @@ -2933,29 +2722,24 @@ void Oscilloscope::runStopToggled(bool checked) last_set_sample_count = active_plot_sample_count; - if (active_trig_sample_count != - trigger_settings.triggerDelay()) { - trigger_settings.setTriggerDelay( - active_trig_sample_count); + if(active_trig_sample_count != trigger_settings.triggerDelay()) { + trigger_settings.setTriggerDelay(active_trig_sample_count); last_set_time_pos = active_time_pos; } - if ((timePosition->value() != active_time_pos) - && !symmBufferMode->isEnhancedMemDepth()) { + if((timePosition->value() != active_time_pos) && !symmBufferMode->isEnhancedMemDepth()) { timePosition->setValue(active_time_pos); } setTrigger_input(false); - resetStreamingFlag(symmBufferMode->isEnhancedMemDepth() - || plot_samples_sequentially); + resetStreamingFlag(symmBufferMode->isEnhancedMemDepth() || plot_samples_sequentially); toggle_blockchain_flow(true); scaleHistogramPlot(); } else { toggle_blockchain_flow(false); - resetStreamingFlag(symmBufferMode->isEnhancedMemDepth() - || plot_samples_sequentially); + resetStreamingFlag(symmBufferMode->isEnhancedMemDepth() || plot_samples_sequentially); trigger_settings.setAdcRunningState(false); ResourceManager::close("m2k-adc"); } @@ -2973,7 +2757,7 @@ void Oscilloscope::setFFT_params(bool force) if(fft_plot.sampleRate() != getSampleRate() || force) { fft_plot.setSampleRate(getSampleRate(), 1, ""); double start = 0; - double stop = getSampleRate() / 2; + double stop = getSampleRate() / 2; fft_plot.setAxisScale(QwtAxis::XBottom, start, stop); fft_plot.setAxisScale(QwtAxis::YLeft, -200, 0, 10); fft_plot.zoomBaseUpdate(); @@ -2985,9 +2769,8 @@ void Oscilloscope::setChannelWidgetIndex(int chnIdx) current_ch_widget = chnIdx; plot.bringCurveToFront(chnIdx); - for (unsigned int i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; - ++i) { - if (i == chnIdx) { + for(unsigned int i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; ++i) { + if(i == chnIdx) { continue; } @@ -2997,8 +2780,7 @@ void Oscilloscope::setChannelWidgetIndex(int chnIdx) void Oscilloscope::autosetFFT() { - auto fft = gnuradio::get_initial_sptr( - new fft_block(false, autoset_fft_size)); + auto fft = gnuradio::get_initial_sptr(new fft_block(false, autoset_fft_size)); auto ctm = blocks::complex_to_mag_squared::make(1); auto log = blocks::nlog10_ff::make(10); @@ -3009,74 +2791,69 @@ void Oscilloscope::autosetFFT() } autosetFFTSink = blocks::vector_sink_f::make(); - autoset_id[0] = iio->connect(fft,autosetChannel,0,true); + autoset_id[0] = iio->connect(fft, autosetChannel, 0, true); - iio->connect(fft,0,ctm,0); - iio->connect(ctm,0,log,0); - iio->connect(log,0,autosetFFTSink,0); + iio->connect(fft, 0, ctm, 0); + iio->connect(ctm, 0, log, 0); + iio->connect(log, 0, autosetFFTSink, 0); } void Oscilloscope::onFFT_view_toggled(bool visible) { /* Lock the flowgraph if we are already started */ bool started = isIioManagerStarted(); - if (started) + if(started) iio->lock(); - if (visible) { + if(visible) { qt_fft_block->set_nsamps(fft_plot_size); - if (fft_is_visible && (fft_channels.size() > 0)) { - for (unsigned int i = 0; i < nb_channels; i++) { + if(fft_is_visible && (fft_channels.size() > 0)) { + for(unsigned int i = 0; i < nb_channels; i++) { /** GNU Radio flow: iio(i) -> fft -> ctm -> qt_fft_block */ - iio->disconnect(fft_channels.at(i).first, fft_channels.at(i).second, - fft_blocks.at(i), 0); + iio->disconnect(fft_channels.at(i).first, fft_channels.at(i).second, fft_blocks.at(i), + 0); iio->disconnect(fft_blocks.at(i), 0, ctm_blocks.at(i), 0); iio->disconnect(ctm_blocks.at(i), 0, qt_fft_block, i); } } setFFT_params(); - for (unsigned int i = 0; i < nb_channels; i++) { - fft_blocks.push_back(gnuradio::get_initial_sptr( - new fft_block(false, fft_plot_size))); + for(unsigned int i = 0; i < nb_channels; i++) { + fft_blocks.push_back(gnuradio::get_initial_sptr(new fft_block(false, fft_plot_size))); ctm_blocks.push_back(blocks::complex_to_mag_squared::make(1)); - if (chnAcCoupled.at(i)) { - fft_channels.push_back(QPair( - dc_cancel.at(i), 0)); + if(chnAcCoupled.at(i)) { + fft_channels.push_back(QPair(dc_cancel.at(i), 0)); } else { - fft_channels.push_back(QPair( - adc_samp_conv_block, i)); + fft_channels.push_back(QPair(adc_samp_conv_block, i)); } - iio->connect(fft_channels.at(i).first, fft_channels.at(i).second, - fft_blocks.at(i), 0); + iio->connect(fft_channels.at(i).first, fft_channels.at(i).second, fft_blocks.at(i), 0); iio->connect(fft_blocks.at(i), 0, ctm_blocks.at(i), 0); iio->connect(ctm_blocks.at(i), 0, qt_fft_block, i); } - bool dockingEnabled = Preferences::GetInstance()->get("general_dockingenabled").toBool(); if(dockingEnabled) { - fftDockWidget->show(); + fftDockWidget->show(); } else { - ui->container_fft_plot->show(); + ui->container_fft_plot->show(); } } else { bool dockingEnabled = Preferences::GetInstance()->get("general_dockingenabled").toBool(); if(dockingEnabled) { - fftDockWidget->setFloating(false); - fftDockWidget->hide(); + fftDockWidget->setFloating(false); + fftDockWidget->hide(); } else { - ui->container_fft_plot->hide(); + ui->container_fft_plot->hide(); } - if (fft_is_visible && (fft_channels.size() > 0)) { - for (unsigned int i = 0; i < nb_channels; i++) { - iio->disconnect(fft_channels.at(i).first, fft_channels.at(i).second, - fft_blocks.at(i), 0); + if(fft_is_visible && (fft_channels.size() > 0)) { + for(unsigned int i = 0; i < nb_channels; i++) { + iio->disconnect(fft_channels.at(i).first, fft_channels.at(i).second, fft_blocks.at(i), + 0); iio->disconnect(fft_blocks.at(i), 0, ctm_blocks.at(i), 0); iio->disconnect(ctm_blocks.at(i), 0, qt_fft_block, i); } @@ -3088,7 +2865,7 @@ void Oscilloscope::onFFT_view_toggled(bool visible) fft_is_visible = visible; - if (started) + if(started) iio->unlock(); } @@ -3139,7 +2916,7 @@ void Oscilloscope::onHistogram_view_toggled(bool visible) void Oscilloscope::onXY_view_toggled(bool visible) { - if (visible) { + if(visible) { gsettings_ui->xySettings->show(); } else { bool dockingEnabled = Preferences::GetInstance()->get("general_dockingenabled").toBool(); @@ -3151,33 +2928,26 @@ void Oscilloscope::onXY_view_toggled(bool visible) /* Lock the flowgraph if we are already started */ bool started = isIioManagerStarted(); - if (started && !locked) + if(started && !locked) iio->lock(); - if (visible) { - if(xy_is_visible && index_x == gsettings_ui->cmb_x_channel->currentIndex() - && index_y == gsettings_ui->cmb_y_channel->currentIndex()) - { + if(visible) { + if(xy_is_visible && index_x == gsettings_ui->cmb_x_channel->currentIndex() && + index_y == gsettings_ui->cmb_y_channel->currentIndex()) { xy_is_visible = visible; - if (started && !locked) + if(started && !locked) iio->unlock(); return; } - std::shared_ptr block = - dynamic_pointer_cast( - adc_samp_conv_block); + std::shared_ptr block = dynamic_pointer_cast(adc_samp_conv_block); if(!ftc) ftc = blocks::float_to_complex::make(1); if(xy_channels.size() > 0) { - iio->disconnect(xy_channels.at(index_x).first, - xy_channels.at(index_x).second, - ftc, 0); - iio->disconnect(xy_channels.at(index_y).first, - xy_channels.at(index_y).second, - ftc, 1); + iio->disconnect(xy_channels.at(index_x).first, xy_channels.at(index_x).second, ftc, 0); + iio->disconnect(xy_channels.at(index_y).first, xy_channels.at(index_y).second, ftc, 1); xy_channels.clear(); } @@ -3186,25 +2956,20 @@ void Oscilloscope::onXY_view_toggled(bool visible) if(xy_channels.size() == 0) { for(unsigned int i = 0; i < nb_channels; i++) { - if (chnAcCoupled.at(i)) { - xy_channels.push_back(QPair( - dc_cancel.at(i), 0)); + if(chnAcCoupled.at(i)) { + xy_channels.push_back(QPair(dc_cancel.at(i), 0)); } else { - xy_channels.push_back(QPair( - adc_samp_conv_block, i)); + xy_channels.push_back(QPair(adc_samp_conv_block, i)); } } for(const auto &p : qAsConst(math_sinks)) { auto math = p.first; - xy_channels.push_back(QPair( - math, 0)); + xy_channels.push_back(QPair(math, 0)); } } - iio->connect(xy_channels.at(index_x).first, xy_channels.at(index_x).second, - ftc, 0); - iio->connect(xy_channels.at(index_y).first, xy_channels.at(index_y).second, - ftc, 1); + iio->connect(xy_channels.at(index_x).first, xy_channels.at(index_x).second, ftc, 0); + iio->connect(xy_channels.at(index_y).first, xy_channels.at(index_y).second, ftc, 1); if(!xy_is_visible) iio->connect(ftc, 0, this->qt_xy_block, 0); @@ -3226,10 +2991,8 @@ void Oscilloscope::onXY_view_toggled(bool visible) // Disconnect the XY section from the running flowgraph - iio->disconnect(xy_channels.at(index_x).first, xy_channels.at(index_x).second, - ftc, 0); - iio->disconnect(xy_channels.at(index_y).first, xy_channels.at(index_y).second, - ftc, 1); + iio->disconnect(xy_channels.at(index_x).first, xy_channels.at(index_x).second, ftc, 0); + iio->disconnect(xy_channels.at(index_y).first, xy_channels.at(index_y).second, ftc, 1); iio->disconnect(ftc, 0, this->qt_xy_block, 0); @@ -3238,24 +3001,22 @@ void Oscilloscope::onXY_view_toggled(bool visible) xy_is_visible = visible; - if (started && !locked) + if(started && !locked) iio->unlock(); } void Oscilloscope::on_boxCursors_toggled(bool on) { - plot.setHorizCursorsEnabled( - on ? cr_ui->vCursorsEnable->isChecked() : false); - plot.setVertCursorsEnabled( - on ? cr_ui->hCursorsEnable->isChecked() : false); + plot.setHorizCursorsEnabled(on ? cr_ui->vCursorsEnable->isChecked() : false); + plot.setVertCursorsEnabled(on ? cr_ui->hCursorsEnable->isChecked() : false); plot.trackModeEnabled(on ? cr_ui->btnNormalTrack->isChecked() : true); // Set the visibility of the cursor readouts owned by the Oscilloscope - if (on) { + if(on) { plot.setCursorReadoutsVisible(!ui->boxMeasure->isChecked()); } else { - if (ui->btnCursors->isChecked()) + if(ui->btnCursors->isChecked()) ui->btnCursors->setChecked(false); menuOrder.removeOne(ui->btnCursors); @@ -3266,10 +3027,10 @@ void Oscilloscope::on_boxCursors_toggled(bool on) void Oscilloscope::on_boxMeasure_toggled(bool on) { - if (on) { + if(on) { update_measure_for_channel(current_channel); } else { - if (ui->btnMeasure->isChecked()) + if(ui->btnMeasure->isChecked()) ui->btnMeasure->setChecked(false); menuOrder.removeOne(ui->btnMeasure); @@ -3279,29 +3040,27 @@ void Oscilloscope::on_boxMeasure_toggled(bool on) statisticsPanel->setVisible(on && statistics_enabled); // Set the visibility of the cursor readouts owned by the plot - if (ui->boxCursors->isChecked()) + if(ui->boxCursors->isChecked()) plot.setCursorReadoutsVisible(!on); // set the gates enable / disable plot.setGatingEnabled(on && gatingEnabled); buffer_previewer->setGatingEnabled(on && gatingEnabled); - } void Oscilloscope::onTriggerSourceChanged(int chnIdx) { plot.levelTriggerA()->setMobileAxis(QwtAxisId(QwtAxis::YLeft, chnIdx)); trigger_settings.setChannelAttenuation(probe_attenuation[chnIdx]); - if (chnAcCoupled.at(chnIdx)) { + if(chnAcCoupled.at(chnIdx)) { deactivateAcCouplingTrigger(); activateAcCouplingTrigger(chnIdx); } plot.replot(); - } void Oscilloscope::onTimeTriggerDelayChanged(double value) { - if (timePosition->value() != value) + if(timePosition->value() != value) Q_EMIT triggerPositionChanged(value); } @@ -3309,23 +3068,23 @@ void Oscilloscope::onTriggerLevelChanged(double value) { int trigger_chn = trigger_settings.currentChannel(); - if (trigger_chn > -1) + if(trigger_chn > -1) plot.setPeriodDetectLevel(trigger_chn, value); } -void Oscilloscope::comboBoxUpdateToValue(QComboBox *box, double value, std::vectorlist) +void Oscilloscope::comboBoxUpdateToValue(QComboBox *box, double value, std::vector list) { - size_t i = find_if( list.begin(), list.end(), - [&value](const double element) {return element == value;} ) - list.begin(); - if (i < list.size()) + size_t i = find_if(list.begin(), list.end(), [&value](const double element) { return element == value; }) - + list.begin(); + if(i < list.size()) box->setCurrentIndex(i); } void Oscilloscope::updateRunButton(bool ch_enabled) { - for (unsigned int i = 0; !ch_enabled && - i < nb_channels + nb_math_channels + nb_ref_channels; i++) { - if (channelWidgetAtId(i)->isReferenceChannel()) continue; + for(unsigned int i = 0; !ch_enabled && i < nb_channels + nb_math_channels + nb_ref_channels; i++) { + if(channelWidgetAtId(i)->isReferenceChannel()) + continue; QWidget *parent = ui->channelsList->itemAt(i)->widget(); QCheckBox *box = parent->findChild("box"); ch_enabled = box->isChecked(); @@ -3334,7 +3093,7 @@ void Oscilloscope::updateRunButton(bool ch_enabled) ui->runSingleWidget->setEnabled(ch_enabled); tme->setRunBtnVisible(ch_enabled); - if (!ch_enabled) { + if(!ch_enabled) { tme->setRunning(false); ui->runSingleWidget->toggle(false); } @@ -3347,31 +3106,29 @@ void Oscilloscope::onChannelWidgetEnabled(bool en) hist_plot.enableChannel(id, en); - if (id < nb_channels) { - runInHwThreadPool( m_m2k_analogin->enableChannel(id, en);); + if(id < nb_channels) { + runInHwThreadPool(m_m2k_analogin->enableChannel(id, en);); } - if (en) { + if(en) { plot.AttachCurve(id); fft_plot.AttachCurve(id); plot.showYAxisWidget(id, en); bool shouldActivate = true; - for (unsigned int i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; - i++) { - ChannelWidget *cw = static_cast( - ui->channelsList->itemAt(i)->widget()); + for(unsigned int i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; i++) { + ChannelWidget *cw = static_cast(ui->channelsList->itemAt(i)->widget()); - if (id == cw->id()) { + if(id == cw->id()) { continue; } - if (cw->enableButton()->isChecked()) { + if(cw->enableButton()->isChecked()) { shouldActivate = false; } } - if (shouldActivate) { + if(shouldActivate) { plot.setActiveVertAxis(id); Q_EMIT selectedChannelChanged(id); update_measure_for_channel(id); @@ -3384,40 +3141,36 @@ void Oscilloscope::onChannelWidgetEnabled(bool en) plot.showYAxisWidget(id, en); bool shouldDisable = true; - for (unsigned int i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; - i++) { - ChannelWidget *cw = static_cast( - ui->channelsList->itemAt(i)->widget()); + for(unsigned int i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; i++) { + ChannelWidget *cw = static_cast(ui->channelsList->itemAt(i)->widget()); - if (id == cw->id()) { + if(id == cw->id()) { continue; } - if (cw->enableButton()->isChecked()) { + if(cw->enableButton()->isChecked()) { shouldDisable = false; } } - if (shouldDisable) { + if(shouldDisable) { measure_settings->disableDisplayAll(); plot.setActiveVertAxis(0); enableLabels(false); } - if (current_channel == id) { - for (size_t i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; i++) { - ChannelWidget *cw = static_cast( - ui->channelsList->itemAt(i)->widget()); + if(current_channel == id) { + for(size_t i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; i++) { + ChannelWidget *cw = static_cast(ui->channelsList->itemAt(i)->widget()); - if (cw->enableButton()->isChecked()) { + if(cw->enableButton()->isChecked()) { cw->nameButton()->setChecked(true); break; } } } - menuOrder.removeOne(static_cast( - w->menuButton())); + menuOrder.removeOne(static_cast(w->menuButton())); } measureLabelsRearrange(); @@ -3426,16 +3179,16 @@ void Oscilloscope::onChannelWidgetEnabled(bool en) plot.replot(); fft_plot.replot(); - if (!w->isReferenceChannel()) { + if(!w->isReferenceChannel()) { updateRunButton(en); } } void Oscilloscope::selectChannel(int index, bool checked) { - for (int i = 0; i < ui->channelsList->count(); i++) { - auto cw = dynamic_cast(ui->channelsList->itemAt(i)->widget()); - if (cw != nullptr) { + for(int i = 0; i < ui->channelsList->count(); i++) { + auto cw = dynamic_cast(ui->channelsList->itemAt(i)->widget()); + if(cw != nullptr) { cw->nameButton()->setChecked(i == index); } } @@ -3443,19 +3196,19 @@ void Oscilloscope::selectChannel(int index, bool checked) void Oscilloscope::onChannelWidgetSelected(bool checked) { - if (!checked) { + if(!checked) { return; } bool oscLabels = p->get("m2k_osc_label").toBool(); - if (isVisible() && plot.labelsEnabled() != oscLabels) { + if(isVisible() && plot.labelsEnabled() != oscLabels) { enableLabels(oscLabels); } ChannelWidget *w = static_cast(QObject::sender()); int id = w->id(); - if (id != current_channel) { + if(id != current_channel) { current_channel = id; Q_EMIT selectedChannelChanged(id); plot.bringCurveToFront(id); @@ -3464,7 +3217,7 @@ void Oscilloscope::onChannelWidgetSelected(bool checked) plot.setAllAxes(current_channel); } - if (plot.measurementsEnabled()) { + if(plot.measurementsEnabled()) { update_measure_for_channel(id); } } @@ -3475,8 +3228,7 @@ void Oscilloscope::onChannelWidgetMenuToggled(bool checked) current_ch_widget = cw->id(); - triggerRightMenuToggle( - static_cast(cw->menuButton()), checked); + triggerRightMenuToggle(static_cast(cw->menuButton()), checked); } void Oscilloscope::cancelZoom() @@ -3484,33 +3236,30 @@ void Oscilloscope::cancelZoom() zoom_level = 0; plot.cancelZoom(); - for (size_t i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; ++i) { - QLabel *label = static_cast( - ui->chn_scales->itemAt(i)->widget()); + for(size_t i = 0; i < nb_channels + nb_math_channels + nb_ref_channels; ++i) { + QLabel *label = static_cast(ui->chn_scales->itemAt(i)->widget()); double value = probe_attenuation[i] * plot.VertUnitsPerDiv(i); QString str = vertMeasureFormat.format(value, "V/div", 3); str.append(getChannelRangeStringVDivHelper(i)); label->setText(str); - } } void Oscilloscope::onChannelCouplingChanged(bool en) { - if (en && chnAcCoupled.at(current_ch_widget)) + if(en && chnAcCoupled.at(current_ch_widget)) return; configureAcCoupling(current_ch_widget, en); } QString Oscilloscope::getChannelRangeStringVDivHelper(int ch) { - QString str =""; - if(ch >= 0 && ch < nb_channels) - { + QString str = ""; + if(ch >= 0 && ch < nb_channels) { str = " (±"; - double range = (high_gain_modes[ch])? 2.5 : 25; + double range = (high_gain_modes[ch]) ? 2.5 : 25; range = range * probe_attenuation[ch]; - str += QString::number(range,'f',1) + ")"; + str += QString::number(range, 'f', 1) + ")"; } return str; } @@ -3518,7 +3267,7 @@ QString Oscilloscope::getChannelRangeStringVDivHelper(int ch) void Oscilloscope::onVertScaleValueChanged(double value) { cancelZoom(); - if (value != plot.VertUnitsPerDiv(current_ch_widget)) { + if(value != plot.VertUnitsPerDiv(current_ch_widget)) { plot.setVertUnitsPerDiv(value, current_ch_widget); plot.replot(); } @@ -3528,15 +3277,15 @@ void Oscilloscope::onVertScaleValueChanged(double value) updateXyPlotScales(); // TO DO: refactor this once the source of the X and Y axes can be configured - if (current_ch_widget == index_x) { + if(current_ch_widget == index_x) { xy_plot.setHorizUnitsPerDiv(value); } - if (current_ch_widget == index_y) { + if(current_ch_widget == index_y) { xy_plot.setVertUnitsPerDiv(value, QwtAxis::YLeft); } xy_plot.zoomBaseUpdate(); - if (current_ch_widget < nb_channels) { + if(current_ch_widget < nb_channels) { trigger_settings.setTriggerLevelStep(current_ch_widget, value); trigger_settings.setTriggerHystStep(current_ch_widget, value / 10); } @@ -3544,14 +3293,12 @@ void Oscilloscope::onVertScaleValueChanged(double value) // Send scale information to the measure object plot.setPeriodDetectHyst(current_ch_widget, value / 5); - QLabel *label = static_cast( - ui->chn_scales->itemAt(current_ch_widget)->widget()); - double labelValue = probe_attenuation[current_ch_widget] - * plot.VertUnitsPerDiv(current_ch_widget); + QLabel *label = static_cast(ui->chn_scales->itemAt(current_ch_widget)->widget()); + double labelValue = probe_attenuation[current_ch_widget] * plot.VertUnitsPerDiv(current_ch_widget); QString str = vertMeasureFormat.format(labelValue, "V/div", 3); // Switch between high and low gain modes only for the M2K channels - if (m_m2k_analogin && current_ch_widget < nb_channels) { + if(m_m2k_analogin && current_ch_widget < nb_channels) { updateGainMode(); setChannelHwOffset(current_ch_widget, voltsPosition->value()); trigger_settings.updateHwVoltLevels(current_ch_widget); @@ -3560,23 +3307,22 @@ void Oscilloscope::onVertScaleValueChanged(double value) label->setText(str); } - void Oscilloscope::onCmbMemoryDepthChanged(QString value) { bool ok, started; unsigned long bufferSize = value.toInt(&ok); - if (!ok) { + if(!ok) { ch_ui->cmbMemoryDepth->setCurrentIndex(0); return; } - if (ch_ui->cmbMemoryDepth->currentIndex() == 0) { + if(ch_ui->cmbMemoryDepth->currentIndex() == 0) { onHorizScaleValueChanged(timeBase->value()); return; } started = isIioManagerStarted(); - if (started) { + if(started) { toggle_blockchain_flow(false); } @@ -3591,10 +3337,10 @@ void Oscilloscope::onCmbMemoryDepthChanged(QString value) active_trig_sample_count = -(long long)params.triggerBufferSize; plot_samples_sequentially = false; - if (timeBase->value() < TIMEBASE_THRESHOLD) { + if(timeBase->value() < TIMEBASE_THRESHOLD) { active_sample_count = active_plot_sample_count; setSinksDisplayOneBuffer(true); - } else { + } else { setSinksDisplayOneBuffer(false); } @@ -3604,7 +3350,7 @@ void Oscilloscope::onCmbMemoryDepthChanged(QString value) plot.resetXaxisOnNextReceivedData(); plot.cancelZoom(); - if (zoom_level == 0) { + if(zoom_level == 0) { noZoomXAxisWidth = plot.axisInterval(QwtAxis::XBottom).width(); } @@ -3620,11 +3366,11 @@ void Oscilloscope::onCmbMemoryDepthChanged(QString value) last_set_time_pos = active_time_pos; last_set_sample_count = active_plot_sample_count; - for (unsigned int i = 0; i < nb_channels; i++) { + for(unsigned int i = 0; i < nb_channels; i++) { iio->set_buffer_size(ids[i], active_sample_count); dc_cancel.at(i)->set_buffer_size(active_sample_count); } - if (mixed_source) { + if(mixed_source) { mixed_source->set_buffer_size(active_sample_count); setDigitalPlotCurvesParams(); } @@ -3635,7 +3381,7 @@ void Oscilloscope::onCmbMemoryDepthChanged(QString value) // Compute the appropriate value for fft_size double power; - if (symmBufferMode->isEnhancedMemDepth() || plot_samples_sequentially) { + if(symmBufferMode->isEnhancedMemDepth() || plot_samples_sequentially) { power = floor(log2(active_plot_sample_count)); } else { power = ceil(log2(active_plot_sample_count)); @@ -3645,12 +3391,13 @@ void Oscilloscope::onCmbMemoryDepthChanged(QString value) onFFT_view_toggled(fft_is_visible); updateBufferPreviewer(); - if (started) { + if(started) { writeAllSettingsToHardware(); toggle_blockchain_flow(true); } resetStreamingFlag(true); - double maxT = (1 << 13) * (1.0 / active_sample_rate) - 1.0 / active_sample_rate * active_plot_sample_count / 2.0; + double maxT = + (1 << 13) * (1.0 / active_sample_rate) - 1.0 / active_sample_rate * active_plot_sample_count / 2.0; plot.setTimeTriggerInterval(-36E2, maxT); } @@ -3659,14 +3406,13 @@ void Oscilloscope::setSinksDisplayOneBuffer(bool val) d_displayOneBuffer = val; qt_time_block->set_displayOneBuffer(val); - if (mixed_sink) { + if(mixed_sink) { mixed_sink->set_displayOneBuffer(val); } auto it = math_sinks.constBegin(); - while (it != math_sinks.constEnd()) { - scope_sink_f::sptr math_sink = dynamic_pointer_cast< - scope_sink_f>(it.value().second); + while(it != math_sinks.constEnd()) { + scope_sink_f::sptr math_sink = dynamic_pointer_cast(it.value().second); math_sink->set_displayOneBuffer(val); ++it; } @@ -3687,7 +3433,7 @@ void Oscilloscope::onHorizScaleValueChanged(double value) ch_ui->cmbMemoryDepth->blockSignals(true); ch_ui->cmbMemoryDepth->clear(); - for (auto item : params.availableBufferSizes) { + for(auto item : params.availableBufferSizes) { ch_ui->cmbMemoryDepth->addItem(QString::number(item)); } ch_ui->cmbMemoryDepth->blockSignals(false); @@ -3704,42 +3450,45 @@ void Oscilloscope::onHorizScaleValueChanged(double value) ch_ui->cmbMemoryDepth->setCurrentIndex(0); const int minKernelBuffers = 4; int m_currentKernelBuffers = minKernelBuffers; - if (timeBase->value() >= TIMEBASE_THRESHOLD) { - plot_samples_sequentially = true; // streaming + if(timeBase->value() >= TIMEBASE_THRESHOLD) { + plot_samples_sequentially = true; // streaming const int oneBufferMaxSize = 2 * 1024 * 1024; // 2M m_currentKernelBuffers = minKernelBuffers; - if (active_trig_sample_count < 0) { + if(active_trig_sample_count < 0) { active_sample_count = -active_trig_sample_count; m_currentKernelBuffers = (active_plot_sample_count / active_sample_count) + 1; - active_sample_count = (( active_sample_count + 3) / 4) * 4; - m_currentKernelBuffers = (m_currentKernelBuffers > MAX_KERNEL_BUFFERS) ? MAX_KERNEL_BUFFERS : m_currentKernelBuffers; - m_currentKernelBuffers = (m_currentKernelBuffers < minKernelBuffers) ? minKernelBuffers : m_currentKernelBuffers; - } else { // still streaming but without trigger contraints + active_sample_count = ((active_sample_count + 3) / 4) * 4; + m_currentKernelBuffers = (m_currentKernelBuffers > MAX_KERNEL_BUFFERS) ? MAX_KERNEL_BUFFERS + : m_currentKernelBuffers; + m_currentKernelBuffers = + (m_currentKernelBuffers < minKernelBuffers) ? minKernelBuffers : m_currentKernelBuffers; + } else { // still streaming but without trigger contraints /* ensure we have the minimum amount of kernel buffers to fit the buffer */ - while (active_plot_sample_count > (m_currentKernelBuffers * oneBufferMaxSize) - && m_currentKernelBuffers < MAX_KERNEL_BUFFERS) { + while(active_plot_sample_count > (m_currentKernelBuffers * oneBufferMaxSize) && + m_currentKernelBuffers < MAX_KERNEL_BUFFERS) { m_currentKernelBuffers++; } /* ensure we don't spend more than 100ms on a acquiring a buffer if we can * further divide it into smaller buffers */ const double maxCaptureDuration = 0.1; - while (((static_cast(active_plot_sample_count) / active_sample_rate) - / static_cast(m_currentKernelBuffers)) > maxCaptureDuration - && m_currentKernelBuffers < MAX_KERNEL_BUFFERS) { + while(((static_cast(active_plot_sample_count) / active_sample_rate) / + static_cast(m_currentKernelBuffers)) > maxCaptureDuration && + m_currentKernelBuffers < MAX_KERNEL_BUFFERS) { m_currentKernelBuffers++; } uint64_t chunk_size = active_plot_sample_count / m_currentKernelBuffers; uint64_t chunkSizeBeforeAdjust = chunk_size; chunk_size = 4 * (chunk_size / 4); - /* If the chunk_size was not divisible by 4 in the first place we would get a smaller value for it. */ - if (chunk_size + 4 <= oneBufferMaxSize && chunkSizeBeforeAdjust != chunk_size) { + /* If the chunk_size was not divisible by 4 in the first place we would get a smaller value for + * it. */ + if(chunk_size + 4 <= oneBufferMaxSize && chunkSizeBeforeAdjust != chunk_size) { chunk_size += 4; } // If the buffer size is > 64 * 4M we need to cap the chunk_size to 4M - if (chunk_size > oneBufferMaxSize) { + if(chunk_size > oneBufferMaxSize) { chunk_size = oneBufferMaxSize; } active_sample_count = chunk_size; @@ -3754,31 +3503,30 @@ void Oscilloscope::onHorizScaleValueChanged(double value) resetStreamingFlag(false); } - if (zoom_level == 0) { + if(zoom_level == 0) { noZoomXAxisWidth = plot.axisInterval(QwtAxis::XBottom).width(); } /* Reconfigure the GNU Radio block to receive a different number of samples */ bool started = isIioManagerStarted(); - if (started) + if(started) iio->lock(); setAllSinksSampleCount(active_plot_sample_count); - if (timeBase->value() >= TIMEBASE_THRESHOLD) { + if(timeBase->value() >= TIMEBASE_THRESHOLD) { iio->set_kernel_buffer_count(m_currentKernelBuffers); } else { iio->set_kernel_buffer_count(); } - if (started) { + if(started) { plot.setSampleRate(active_sample_rate, 1, ""); plot.setBufferSizeLabelValue(active_plot_sample_count); plot.setSampleRatelabelValue(active_sample_rate); last_set_sample_count = active_plot_sample_count; setSampleRate(active_sample_rate); - for(size_t i=0;ifreq_comp_filt[i][0]->set_sample_rate(active_sample_rate); iio->freq_comp_filt[i][1]->set_sample_rate(active_sample_rate); } @@ -3786,23 +3534,23 @@ void Oscilloscope::onHorizScaleValueChanged(double value) last_set_time_pos = active_time_pos; // Time base changes can limit the time position value - if (timePosition->value() != -params.timePos) + if(timePosition->value() != -params.timePos) timePosition->setValue(-params.timePos); } iio->set_device_timeout((active_sample_count / active_sample_rate) * 1000 + 100); - for (unsigned int i = 0; i < nb_channels; i++) { + for(unsigned int i = 0; i < nb_channels; i++) { iio->set_buffer_size(ids[i], active_sample_count); dc_cancel.at(i)->set_buffer_size(active_sample_count); } - if (mixed_source) { + if(mixed_source) { mixed_source->set_buffer_size(active_sample_count); setDigitalPlotCurvesParams(); } - if (started) { + if(started) { iio->unlock(); } @@ -3810,10 +3558,9 @@ void Oscilloscope::onHorizScaleValueChanged(double value) configureAcCoupling(ch, chnAcCoupled.at(ch)); } - // Compute the appropriate value for fft_size double power; - if (symmBufferMode->isEnhancedMemDepth() || plot_samples_sequentially) { + if(symmBufferMode->isEnhancedMemDepth() || plot_samples_sequentially) { power = floor(log2(active_plot_sample_count)); } else { power = ceil(log2(active_plot_sample_count)); @@ -3827,7 +3574,8 @@ void Oscilloscope::onHorizScaleValueChanged(double value) updateBufferPreviewer(); - double maxT = (1 << 13) * (1.0 / active_sample_rate) - 1.0 / active_sample_rate * active_plot_sample_count / 2.0; + double maxT = + (1 << 13) * (1.0 / active_sample_rate) - 1.0 / active_sample_rate * active_plot_sample_count / 2.0; plot.setTimeTriggerInterval(-36E2, maxT); } @@ -3835,22 +3583,19 @@ bool Oscilloscope::gainUpdateNeeded() { double offset = plot.VertOffset(current_ch_widget); QwtInterval hw_input_itv(-2.5 + offset, 2.5 + offset); - QwtInterval plot_vert_itv = plot.axisScaleDiv( - QwtAxisId(QwtAxis::YLeft, current_ch_widget)).interval(); + QwtInterval plot_vert_itv = plot.axisScaleDiv(QwtAxisId(QwtAxis::YLeft, current_ch_widget)).interval(); - if (plot_vert_itv.minValue() < hw_input_itv.minValue() || - plot_vert_itv.maxValue() > hw_input_itv.maxValue() || - std::abs(offset) > 5.0) { - if (high_gain_modes[current_ch_widget]) { + if(plot_vert_itv.minValue() < hw_input_itv.minValue() || plot_vert_itv.maxValue() > hw_input_itv.maxValue() || + std::abs(offset) > 5.0) { + if(high_gain_modes[current_ch_widget]) { return true; } return false; - } else if (!high_gain_modes[current_ch_widget]) { + } else if(!high_gain_modes[current_ch_widget]) { return true; } return false; - } void Oscilloscope::updateXyPlotScales() @@ -3859,15 +3604,14 @@ void Oscilloscope::updateXyPlotScales() int y = gsettings_ui->cmb_y_channel->currentIndex(); auto xInterval = plot.axisInterval(QwtAxisId(QwtAxis::YLeft, x)); auto yInterval = plot.axisInterval(QwtAxisId(QwtAxis::YLeft, y)); - xy_plot.set_axis(xInterval.minValue(), xInterval.maxValue(), - yInterval.minValue(), yInterval.maxValue()); + xy_plot.set_axis(xInterval.minValue(), xInterval.maxValue(), yInterval.minValue(), yInterval.maxValue()); } void Oscilloscope::onVertOffsetValueChanged(double value) { cancelZoom(); - if (value != -plot.VertOffset(current_ch_widget)) { + if(value != -plot.VertOffset(current_ch_widget)) { plot.setVertOffset(-value, current_ch_widget); } @@ -3875,8 +3619,8 @@ void Oscilloscope::onVertOffsetValueChanged(double value) updateXyPlotScales(); // Switch between high and low gain modes only for the M2K channels - if (m_m2k_analogin && current_ch_widget < nb_channels) { - if (gainUpdateNeeded()) { + if(m_m2k_analogin && current_ch_widget < nb_channels) { + if(gainUpdateNeeded()) { updateGainMode(); } setChannelHwOffset(current_ch_widget, value); @@ -3901,10 +3645,9 @@ void Oscilloscope::onTimePositionChanged(double value) * If the current timebase is greater than a threshold, the buffer size needs to * be computed again, in order to properly display samples. */ - if ((enhancedMemDepth || (timeBase->value() >= TIMEBASE_THRESHOLD)) - && (value != memory_adjusted_time_pos)) { + if((enhancedMemDepth || (timeBase->value() >= TIMEBASE_THRESHOLD)) && (value != memory_adjusted_time_pos)) { onHorizScaleValueChanged(timeBase->value()); - if (enhancedMemDepth) { + if(enhancedMemDepth) { return; } } @@ -3927,38 +3670,36 @@ void Oscilloscope::onTimePositionChanged(double value) plot.setDataStartingPoint(active_trig_sample_count); plot.resetXaxisOnNextReceivedData(); - - if (started) { + if(started) { trigger_settings.setTriggerDelay(active_trig_sample_count); last_set_time_pos = active_time_pos; - if (mixed_source) { + if(mixed_source) { setDigitalPlotCurvesParams(); } } updateBufferPreviewer(); - if (reset_horiz_offset) { + if(reset_horiz_offset) { horiz_offset = value; } - if (active_sample_rate == getSampleRate() && - (active_plot_sample_count == oldSampleCount)) { + if(active_sample_rate == getSampleRate() && (active_plot_sample_count == oldSampleCount)) { return; } /* Reconfigure the GNU Radio block to receive a different number of samples */ auto chnCoupled = chnAcCoupled; for(size_t ch = 0; ch < nb_channels; ch++) { - if (chnAcCoupled.at(ch)) { + if(chnAcCoupled.at(ch)) { configureAcCoupling(ch, !chnAcCoupled.at(ch)); } } - if (started) + if(started) iio->lock(); setAllSinksSampleCount(active_plot_sample_count); - if (started) { + if(started) { plot.setSampleRate(active_sample_rate, 1, ""); plot.setBufferSizeLabelValue(active_plot_sample_count); plot.setSampleRatelabelValue(active_sample_rate); @@ -3966,35 +3707,34 @@ void Oscilloscope::onTimePositionChanged(double value) last_set_sample_count = active_plot_sample_count; setSampleRate(active_sample_rate); - for(size_t i=0;ifreq_comp_filt[i][0]->set_sample_rate(active_sample_rate); iio->freq_comp_filt[i][1]->set_sample_rate(active_sample_rate); } } - for (unsigned int i = 0; i < nb_channels; i++) { + for(unsigned int i = 0; i < nb_channels; i++) { iio->set_buffer_size(ids[i], active_sample_count); dc_cancel.at(i)->set_buffer_size(active_sample_count); } - if (mixed_source) { + if(mixed_source) { mixed_source->set_buffer_size(active_sample_count); setDigitalPlotCurvesParams(); } - if (started) { + if(started) { iio->unlock(); } for(size_t ch = 0; ch < nb_channels; ch++) { - if (chnCoupled.at(ch)) { + if(chnCoupled.at(ch)) { configureAcCoupling(ch, chnCoupled.at(ch)); } } // Compute the appropriate value for fft_size double power; - if (symmBufferMode->isEnhancedMemDepth() || plot_samples_sequentially) { + if(symmBufferMode->isEnhancedMemDepth() || plot_samples_sequentially) { power = floor(log2(active_plot_sample_count)); } else { power = ceil(log2(active_plot_sample_count)); @@ -4011,7 +3751,7 @@ void Oscilloscope::rightMenuFinished(bool opened) // At the end of each animation, check if there are other button check // actions that might have happened while animating and execute all // these queued actions - while (menuButtonActions.size()) { + while(menuButtonActions.size()) { auto pair = menuButtonActions.dequeue(); toggleRightMenu(pair.first, pair.second); } @@ -4021,8 +3761,8 @@ void Oscilloscope::toggleRightMenu(CustomPushButton *btn, bool checked) { int id = btn->property("id").toInt(); - if (id != -ui->stackedWidget->indexOf(ui->generalSettings)){ - if (!menuOrder.contains(btn)){ + if(id != -ui->stackedWidget->indexOf(ui->generalSettings)) { + if(!menuOrder.contains(btn)) { menuOrder.push_back(btn); } else { menuOrder.removeOne(btn); @@ -4030,11 +3770,11 @@ void Oscilloscope::toggleRightMenu(CustomPushButton *btn, bool checked) } } - if (checked) + if(checked) settings_panel_update(id); - if (id >= 0) { - if (checked) { + if(id >= 0) { + if(checked) { update_chn_settings_panel(id); } } @@ -4051,9 +3791,8 @@ void Oscilloscope::triggerRightMenuToggle(CustomPushButton *btn, bool checked) // Queue the action, if right menu animation is in progress. This way // the action will be remembered and performed right after the animation // finishes - if (ui->rightMenu->animInProgress()) { - menuButtonActions.enqueue( - QPair(btn, checked)); + if(ui->rightMenu->animInProgress()) { + menuButtonActions.enqueue(QPair(btn, checked)); } else { toggleRightMenu(btn, checked); } @@ -4061,20 +3800,20 @@ void Oscilloscope::triggerRightMenuToggle(CustomPushButton *btn, bool checked) void Oscilloscope::settings_panel_update(int id) { - if (id >= 0) - ui->stackedWidget->setCurrentIndex(0); - else - ui->stackedWidget->setCurrentIndex(-id); + if(id >= 0) + ui->stackedWidget->setCurrentIndex(0); + else + ui->stackedWidget->setCurrentIndex(-id); - settings_panel_size_adjust(); + settings_panel_size_adjust(); } void Oscilloscope::settings_panel_size_adjust() { - for (int i = 0; i < ui->stackedWidget->count(); i++) { + for(int i = 0; i < ui->stackedWidget->count(); i++) { QSizePolicy::Policy policy = QSizePolicy::Ignored; - if (i == ui->stackedWidget->currentIndex()) { + if(i == ui->stackedWidget->currentIndex()) { policy = QSizePolicy::Expanding; } QWidget *widget = ui->stackedWidget->widget(i); @@ -4096,11 +3835,9 @@ ChannelWidget *Oscilloscope::channelWidgetAtId(int id) ChannelWidget *w = nullptr; bool found = false; - for (unsigned int i = 0; !found && - i < nb_channels + nb_math_channels + nb_ref_channels; i++) { + for(unsigned int i = 0; !found && i < nb_channels + nb_math_channels + nb_ref_channels; i++) { - w = static_cast( - ui->channelsList->itemAt(i)->widget()); + w = static_cast(ui->channelsList->itemAt(i)->widget()); found = w->id() == id; } @@ -4110,27 +3847,24 @@ ChannelWidget *Oscilloscope::channelWidgetAtId(int id) void Oscilloscope::update_chn_settings_panel(int id) { ChannelWidget *chn_widget = channelWidgetAtId(id); - if (!chn_widget) + if(!chn_widget) return; - disconnect(voltsPerDiv, SIGNAL(valueChanged(double)), this, - SLOT(onVertScaleValueChanged(double))); + disconnect(voltsPerDiv, SIGNAL(valueChanged(double)), this, SLOT(onVertScaleValueChanged(double))); voltsPerDiv->setValue(plot.VertUnitsPerDiv(id)); - connect(voltsPerDiv, SIGNAL(valueChanged(double)), - SLOT(onVertScaleValueChanged(double))); + connect(voltsPerDiv, SIGNAL(valueChanged(double)), SLOT(onVertScaleValueChanged(double))); voltsPosition->blockSignals(true); voltsPosition->setValue(-plot.VertOffset(id)); voltsPosition->blockSignals(false); QString name = chn_widget->fullName(); ch_ui->label_channelName->setText(name); - QString stylesheet = QString("border: 2px solid %1" - ).arg(plot.getLineColor(id).name()); + QString stylesheet = QString("border: 2px solid %1").arg(plot.getLineColor(id).name()); ch_ui->line_channelColor->setStyleSheet(stylesheet); int cmbIdx = (int)(plot.getLineWidthF(id) / 0.5) - 1; ch_ui->cmbChnLineWidth->setCurrentIndex(cmbIdx); - if (chn_widget->isMathChannel()) { + if(chn_widget->isMathChannel()) { ch_ui->filter1->setVisible(false); ch_ui->filter2->setVisible(false); ch_ui->math_settings_widget->setVisible(true); @@ -4142,7 +3876,7 @@ void Oscilloscope::update_chn_settings_panel(int id) ch_ui->snapshotBtn->setText(tr("Snapshot")); - } else if (chn_widget->isReferenceChannel()) { + } else if(chn_widget->isReferenceChannel()) { ch_ui->filter1->setVisible(false); ch_ui->filter2->setVisible(false); @@ -4153,7 +3887,6 @@ void Oscilloscope::update_chn_settings_panel(int id) ch_ui->math_settings_widget->setVisible(false); ch_ui->wCoupling->setVisible(false); - } else { bool showAdcFilters = p->get("m2k_show_adc_filters").toBool(); ch_ui->filter1->setVisible(showAdcFilters); @@ -4162,7 +3895,7 @@ void Oscilloscope::update_chn_settings_panel(int id) ch_ui->btnAutoset->setVisible(autosetEnabled); ch_ui->wCoupling->setVisible(true); - if (ch_ui->btnCoupled->isChecked() != chnAcCoupled.at(id)) { + if(ch_ui->btnCoupled->isChecked() != chnAcCoupled.at(id)) { ch_ui->btnCoupled->setChecked(chnAcCoupled.at(id)); } @@ -4171,7 +3904,7 @@ void Oscilloscope::update_chn_settings_panel(int id) ch_ui->snapshotBtn->setText(tr("Snapshot")); } - if (chn_widget->isMathChannel() || chn_widget->isReferenceChannel()) { + if(chn_widget->isMathChannel() || chn_widget->isReferenceChannel()) { ch_ui->probe_attenuation_value->setVisible(false); ch_ui->probe_label->setVisible(false); ch_ui->label_3->setVisible(false); @@ -4187,8 +3920,10 @@ void Oscilloscope::update_chn_settings_panel(int id) ch_ui->btnAutoset->setVisible(true); ch_ui->filter_TC->setText(QString::number(iio->freq_comp_filt[current_ch_widget][0]->get_TC())); ch_ui->filter2_TC->setText(QString::number(iio->freq_comp_filt[current_ch_widget][1]->get_TC())); - ch_ui->filter_gain->setText(QString::number(iio->freq_comp_filt[current_ch_widget][0]->get_filter_gain())); - ch_ui->filter2_gain->setText(QString::number(iio->freq_comp_filt[current_ch_widget][1]->get_filter_gain())); + ch_ui->filter_gain->setText( + QString::number(iio->freq_comp_filt[current_ch_widget][0]->get_filter_gain())); + ch_ui->filter2_gain->setText( + QString::number(iio->freq_comp_filt[current_ch_widget][1]->get_filter_gain())); ch_ui->filter_en->setText(tr("Filter 1 - Enable - ") + getChannelRangeStringVDivHelper(id)); ch_ui->filter2_en->setText(tr("Filter 2 - Enable - ") + getChannelRangeStringVDivHelper(id)); ch_ui->filter_en->setChecked(iio->freq_comp_filt[current_ch_widget][0]->get_enable()); @@ -4196,7 +3931,7 @@ void Oscilloscope::update_chn_settings_panel(int id) } auto max_elem = max_element(probe_attenuation.begin(), probe_attenuation.begin() + nb_channels); - if (chn_widget->isMathChannel()) { + if(chn_widget->isMathChannel()) { voltsPerDiv->silentSetMaxValue((*max_elem) * 10); voltsPosition->silentSetMaxValue((*max_elem) * MAX_AMPL); voltsPosition->silentSetMinValue((*max_elem) * (-MAX_AMPL)); @@ -4216,14 +3951,12 @@ void Oscilloscope::openEditMathPanel(bool on) { ChannelWidget *chn_widget = channelWidgetAtId(current_ch_widget); - if (on) { + if(on) { addChannel = false; - triggerRightMenuToggle( - static_cast(chn_widget->menuButton()), false); + triggerRightMenuToggle(static_cast(chn_widget->menuButton()), false); math_pair->first.btnAddChannel->setText(tr("Save")); math_pair->second->setFunction(chn_widget->function()); - triggerRightMenuToggle( - static_cast(ui->btnAddMath), true); + triggerRightMenuToggle(static_cast(ui->btnAddMath), true); tabWidget->removeTab(1); tabWidget->tabBar()->hide(); @@ -4234,22 +3967,20 @@ void Oscilloscope::openEditMathPanel(bool on) } } -void Oscilloscope::editMathChannelFunction(int id, const std::string& new_function) +void Oscilloscope::editMathChannelFunction(int id, const std::string &new_function) { ChannelWidget *chn_widget = channelWidgetAtId(id); int current_x = index_x; int current_y = index_y; - triggerRightMenuToggle( - static_cast(ui->btnAddMath), false); - triggerRightMenuToggle( - static_cast(chn_widget->menuButton()), true); + triggerRightMenuToggle(static_cast(ui->btnAddMath), false); + triggerRightMenuToggle(static_cast(chn_widget->menuButton()), true); math_pair->first.btnAddChannel->setText(tr("Add Channel")); math_pair->second->setFunction(""); addChannel = true; ch_ui->btnEditMath->setChecked(false); - if (chn_widget->function().toStdString() == new_function) + if(chn_widget->function().toStdString() == new_function) return; QString qname = chn_widget->deleteButton()->property("curve_name").toString(); @@ -4259,35 +3990,34 @@ void Oscilloscope::editMathChannelFunction(int id, const std::string& new_functi auto math = gr::scopy::iio_math::make(new_function, nb_channels); bool started = isIioManagerStarted(); - if (started) + if(started) iio->lock(); locked = true; if(xy_is_visible) { gsettings_ui->cmb_x_channel->blockSignals(true); gsettings_ui->cmb_y_channel->blockSignals(true); if(index_x == id) - gsettings_ui->cmb_x_channel->setCurrentIndex(id-1); + gsettings_ui->cmb_x_channel->setCurrentIndex(id - 1); if(index_y == id) - gsettings_ui->cmb_y_channel->setCurrentIndex(id-1); + gsettings_ui->cmb_y_channel->setCurrentIndex(id - 1); gsettings_ui->cmb_x_channel->blockSignals(false); gsettings_ui->cmb_y_channel->blockSignals(false); setup_xy_channels(); } auto pair = math_sinks.value(qname); auto rail_old = math_rails.value(qname); - for (unsigned int i = 0; i < nb_channels; ++i) { + for(unsigned int i = 0; i < nb_channels; ++i) { iio->disconnect(math_probe_atten.at(i), 0, pair.first, i); } iio->disconnect(pair.first, 0, rail_old, 0); iio->disconnect(rail_old, 0, pair.second, 0); - auto math_pair = QPair( - math, pair.second); + auto math_pair = QPair(math, pair.second); math_sinks.insert(qname, math_pair); math_rails.insert(qname, rail); - for (unsigned int i = 0; i < nb_channels; ++i) { + for(unsigned int i = 0; i < nb_channels; ++i) { iio->connect(math_probe_atten.at(i), 0, math, i); } iio->connect(math, 0, rail, 0); @@ -4303,31 +4033,31 @@ void Oscilloscope::editMathChannelFunction(int id, const std::string& new_functi setup_xy_channels(); } locked = false; - if (started) + if(started) iio->unlock(); // If the oscilloscope is not running, create a single run situation only for // the channel that is edited . -// else { -// QList keys = math_sinks.keys(); -// for (const QString &key : keys) -// if (key != qname) { -// pair = math_sinks.value(key); -// for (unsigned int i = 0; i < nb_channels; ++i) -// iio->disconnect(adc_samp_conv_block, i, pair.first, i); -// iio->disconnect(pair.first, 0, pair.second, 0); -// } - -// ui->pushButtonSingle->setChecked(true); - -// for (const QString &key : keys) -// if (key != qname) { -// pair = math_sinks.value(key); -// for (unsigned int i = 0; i < nb_channels; ++i) -// iio->connect(adc_samp_conv_block, i, pair.first, i); -// iio->connect(pair.first, 0, pair.second, 0); -// } -// } + // else { + // QList keys = math_sinks.keys(); + // for (const QString &key : keys) + // if (key != qname) { + // pair = math_sinks.value(key); + // for (unsigned int i = 0; i < nb_channels; ++i) + // iio->disconnect(adc_samp_conv_block, i, pair.first, i); + // iio->disconnect(pair.first, 0, pair.second, 0); + // } + + // ui->pushButtonSingle->setChecked(true); + + // for (const QString &key : keys) + // if (key != qname) { + // pair = math_sinks.value(key); + // for (unsigned int i = 0; i < nb_channels; ++i) + // iio->connect(adc_samp_conv_block, i, pair.first, i); + // iio->connect(pair.first, 0, pair.second, 0); + // } + // } chn_widget->setFunction(QString::fromStdString(new_function)); setSinksDisplayOneBuffer(d_displayOneBuffer); @@ -4337,7 +4067,7 @@ void Oscilloscope::onMeasuremetsAvailable() { measureUpdateValues(); - if (statistics_enabled) { + if(statistics_enabled) { statisticsUpdateValues(); statisticsUpdateGui(); } @@ -4351,13 +4081,12 @@ void Oscilloscope::update_measure_for_channel(int ch_idx) measure_settings->setChannelUnderlineColor(chn_widget->color()); } -void Oscilloscope::measureCreateAndAppendGuiFrom(const M2kMeasurementData& - measurement) +void Oscilloscope::measureCreateAndAppendGuiFrom(const M2kMeasurementData &measurement) { std::shared_ptr p; switch(measurement.unitType()) { - + case M2kMeasurementData::METRIC: p = std::make_shared(); break; @@ -4373,25 +4102,23 @@ void Oscilloscope::measureCreateAndAppendGuiFrom(const M2kMeasurementData& default: break; } - if (p) + if(p) measurements_gui.push_back(p); } void Oscilloscope::measureLabelsRearrange() { - QWidget *container = measure_panel_ui->measurements-> - findChild("container"); + QWidget *container = measure_panel_ui->measurements->findChild("container"); - if (container) { + if(container) { measure_panel_ui->measurements->layout()->removeWidget(container); delete container; } container = new QWidget(); container->setObjectName("container"); - if (!measure_panel_ui->measurements->layout()) { - QVBoxLayout *measurementsLayout = new - QVBoxLayout(measure_panel_ui->measurements); + if(!measure_panel_ui->measurements->layout()) { + QVBoxLayout *measurementsLayout = new QVBoxLayout(measure_panel_ui->measurements); measurementsLayout->addWidget(container); measurementsLayout->setContentsMargins(0, 0, 0, 0); } else { @@ -4406,22 +4133,21 @@ void Oscilloscope::measureLabelsRearrange() int max_rows = 4; int nb_meas_added = 0; - for (int i = 0; i < measurements_data.size(); i++) { + for(int i = 0; i < measurements_data.size(); i++) { int channel = measurements_data[i]->channel(); - if (channel >= nb_channels + nb_math_channels + nb_ref_channels) { + if(channel >= nb_channels + nb_math_channels + nb_ref_channels) { continue; } ChannelWidget *chn_widget = channelWidgetAtId(channel); - if (!chn_widget->enableButton()->isChecked()) { + if(!chn_widget->enableButton()->isChecked()) { continue; } QLabel *name = new QLabel(); QLabel *value = new QLabel(); - int row = nb_meas_added % max_rows; int col = nb_meas_added / max_rows; @@ -4434,11 +4160,10 @@ void Oscilloscope::measureLabelsRearrange() measurements_gui[i]->init(name, value); double pb_atten = 1; - if (channel < probe_attenuation.size()) { + if(channel < probe_attenuation.size()) { pb_atten = probe_attenuation[channel]; } - measurements_gui[i]->update(*(measurements_data[i]), - pb_atten); + measurements_gui[i]->update(*(measurements_data[i]), pb_atten); measurements_gui[i]->setLabelsColor(plot.getLineColor(channel)); nb_meas_added++; @@ -4448,68 +4173,48 @@ void Oscilloscope::measureLabelsRearrange() void Oscilloscope::measureUpdateValues() { - for (int i = 0; i < measurements_data.size(); i++) { + for(int i = 0; i < measurements_data.size(); i++) { int channel = measurements_data[i]->channel(); ChannelWidget *chn_widget = channelWidgetAtId(channel); - if (!chn_widget->enableButton()->isChecked()) { + if(!chn_widget->enableButton()->isChecked()) { continue; } - measurements_gui[i]->update(*(measurements_data[i]), - probe_attenuation[channel]); + measurements_gui[i]->update(*(measurements_data[i]), probe_attenuation[channel]); } } void Oscilloscope::measure_settings_init() { - QList* measure_obj = plot.getMeasurements(); + QList *measure_obj = plot.getMeasurements(); measure_settings = new MeasureSettings(measure_obj, this); int measure_panel = ui->stackedWidget->insertWidget(-1, measure_settings); - connect(measure_settings, - SIGNAL(measurementActivated(int, int)), - SLOT(onMeasurementActivated(int, int))); + connect(measure_settings, SIGNAL(measurementActivated(int, int)), SLOT(onMeasurementActivated(int, int))); - connect(measure_settings, - SIGNAL(measurementDeactivated(int, int)), - SLOT(onMeasurementDeactivated(int, int))); + connect(measure_settings, SIGNAL(measurementDeactivated(int, int)), SLOT(onMeasurementDeactivated(int, int))); - connect(measure_settings, - SIGNAL(measurementSelectionListChanged()), - SLOT(onMeasurementSelectionListChanged())); + connect(measure_settings, SIGNAL(measurementSelectionListChanged()), SLOT(onMeasurementSelectionListChanged())); - connect(measure_settings, - SIGNAL(statisticActivated(int, int)), - SLOT(onStatisticActivated(int, int))); - connect(measure_settings, - SIGNAL(statisticDeactivated(int, int)), - SLOT(onStatisticDeactivated(int, int))); + connect(measure_settings, SIGNAL(statisticActivated(int, int)), SLOT(onStatisticActivated(int, int))); + connect(measure_settings, SIGNAL(statisticDeactivated(int, int)), SLOT(onStatisticDeactivated(int, int))); - connect(measure_settings, SIGNAL(statisticsEnabled(bool)), - SLOT(onStatisticsEnabled(bool))); + connect(measure_settings, SIGNAL(statisticsEnabled(bool)), SLOT(onStatisticsEnabled(bool))); - connect(measure_settings, SIGNAL(statisticsReset()), - SLOT(onStatisticsReset())); + connect(measure_settings, SIGNAL(statisticsReset()), SLOT(onStatisticsReset())); - connect(measure_settings, SIGNAL(gatingEnabled(bool)),SLOT(onGatingEnabled(bool))); + connect(measure_settings, SIGNAL(gatingEnabled(bool)), SLOT(onGatingEnabled(bool))); - connect(&plot, SIGNAL(channelAdded(int)), - measure_settings, SLOT(onChannelAdded(int))); + connect(&plot, SIGNAL(channelAdded(int)), measure_settings, SLOT(onChannelAdded(int))); - connect(this, SIGNAL(selectedChannelChanged(int)), - measure_settings, SLOT(setSelectedChannel(int))); + connect(this, SIGNAL(selectedChannelChanged(int)), measure_settings, SLOT(setSelectedChannel(int))); - connect(measure_settings, - SIGNAL(statisticSelectionListChanged()), - SLOT(onStatisticSelectionListChanged())); + connect(measure_settings, SIGNAL(statisticSelectionListChanged()), SLOT(onStatisticSelectionListChanged())); ui->btnMeasure->setProperty("id", QVariant(-measure_panel)); - connect(ui->boxMeasure, SIGNAL(toggled(bool)), - &plot, SLOT(setMeasuremensEnabled(bool))); - connect(ui->boxMeasure, &QCheckBox::toggled, [=](bool on){ - cr_ui->readoutsWidget->setVisible(!on); - }); + connect(ui->boxMeasure, SIGNAL(toggled(bool)), &plot, SLOT(setMeasuremensEnabled(bool))); + connect(ui->boxMeasure, &QCheckBox::toggled, [=](bool on) { cr_ui->readoutsWidget->setVisible(!on); }); } void Oscilloscope::onMeasurementActivated(int id, int chnIdx) @@ -4523,7 +4228,7 @@ void Oscilloscope::onMeasurementActivated(int id, int chnIdx) // Even if a measurement had been added after data was captured, it // should display the measurement value corresponding to that data - if (oldActiveMeasCount == 0) { + if(oldActiveMeasCount == 0) { plot.measure(); } @@ -4538,9 +4243,10 @@ void Oscilloscope::onMeasurementDeactivated(int id, int chnIdx) mList[id]->setEnabled(false); auto it = find_if(measurements_data.begin(), measurements_data.end(), - [&](std::shared_ptr const& p) - { return (p->name() == name) && (p->channel() == chnIdx); }); - if (it != measurements_data.end()) { + [&](std::shared_ptr const &p) { + return (p->name() == name) && (p->channel() == chnIdx); + }); + if(it != measurements_data.end()) { int i = it - measurements_data.begin(); measurements_data.removeAt(i); measurements_gui.removeAt(i); @@ -4551,7 +4257,7 @@ void Oscilloscope::onMeasurementDeactivated(int id, int chnIdx) void Oscilloscope::onMeasurementSelectionListChanged() { // Clear all measurements in list - for (int i = 0; i < measurements_data.size(); i++) { + for(int i = 0; i < measurements_data.size(); i++) { measurements_data[i]->setEnabled(false); } measurements_data.clear(); @@ -4559,10 +4265,9 @@ void Oscilloscope::onMeasurementSelectionListChanged() // Use the new list from MeasureSettings auto newList = measure_settings->measurementSelection(); - for (int i = 0; i < newList.size(); i++) { - auto pMeasurement = plot.measurement(newList[i].id(), - newList[i].channel_id()); - if (pMeasurement) { + for(int i = 0; i < newList.size(); i++) { + auto pMeasurement = plot.measurement(newList[i].id(), newList[i].channel_id()); + if(pMeasurement) { pMeasurement->setEnabled(true); measurements_data.push_back(pMeasurement); measureCreateAndAppendGuiFrom(*pMeasurement); @@ -4571,12 +4276,9 @@ void Oscilloscope::onMeasurementSelectionListChanged() measureLabelsRearrange(); } -void Oscilloscope::onCursorReadoutsChanged(struct cursorReadoutsText data) -{ - fillCursorReadouts(data); -} +void Oscilloscope::onCursorReadoutsChanged(struct cursorReadoutsText data) { fillCursorReadouts(data); } -void Oscilloscope::fillCursorReadouts(const struct cursorReadoutsText& data) +void Oscilloscope::fillCursorReadouts(const struct cursorReadoutsText &data) { cursor_readouts_ui->cursorT1->setText(data.t1); cursor_readouts_ui->cursorT2->setText(data.t2); @@ -4602,14 +4304,14 @@ void Oscilloscope::measure_panel_init() measure_panel_ui->scrollArea_2->horizontalScrollBar(), &QScrollBar::setValue); connect(measure_panel_ui->scrollArea->horizontalScrollBar(), &QScrollBar::rangeChanged, - [=](double v1, double v2){ - measure_panel_ui->scrollArea_2->widget()->setFixedWidth(measure_panel_ui->scrollAreaWidgetContents->width()); - }); + [=](double v1, double v2) { + measure_panel_ui->scrollArea_2->widget()->setFixedWidth( + measure_panel_ui->scrollAreaWidgetContents->width()); + }); measurePanel->hide(); - connect(&plot, SIGNAL(measurementsAvailable()), - SLOT(onMeasuremetsAvailable())); + connect(&plot, SIGNAL(measurementsAvailable()), SLOT(onMeasuremetsAvailable())); // The second CursorReadouts belongs to the Measure panel. The first // one is drawn on top of the plot canvas. @@ -4618,11 +4320,9 @@ void Oscilloscope::measure_panel_init() cursor_readouts_ui->setupUi(cursorReadouts); cursor_readouts_ui->TimeCursors->setStyleSheet("QWidget {" - "background-color: transparent;}" - ); + "background-color: transparent;}"); cursor_readouts_ui->VoltageCursors->setStyleSheet("QWidget {" - "background-color: transparent;}" - ); + "background-color: transparent;}"); // Avoid labels jumping around to left or right by imposing a min width QLabel *label = new QLabel(this); @@ -4644,9 +4344,8 @@ void Oscilloscope::measure_panel_init() delete label; - QHBoxLayout *hLayout = static_cast( - measure_panel_ui->cursorReadouts->layout()); - if (hLayout) + QHBoxLayout *hLayout = static_cast(measure_panel_ui->cursorReadouts->layout()); + if(hLayout) hLayout->insertWidget(0, cursorReadouts); fillCursorReadouts(plot.allCursorReadouts()); @@ -4673,7 +4372,7 @@ void Oscilloscope::statistics_panel_init() void Oscilloscope::statisticsUpdateValues() { - for (int i = 0; i < statistics_data.size(); i++) { + for(int i = 0; i < statistics_data.size(); i++) { double meas_data = statistics_data[i].first->value(); statistics_data[i].second.pushNewData(meas_data); } @@ -4681,54 +4380,48 @@ void Oscilloscope::statisticsUpdateValues() void Oscilloscope::statisticsReset() { - for (int i = 0; i < statistics_data.size(); i++) + for(int i = 0; i < statistics_data.size(); i++) statistics_data[i].second.clear(); } void Oscilloscope::statisticsUpdateGui() { - QListstatistics = statistics_panel_ui-> - statistics->findChildren( - QString("Statistic"), Qt::FindDirectChildrenOnly); - for (int i = 0; i < statistics.size(); i++) + QList statistics = statistics_panel_ui->statistics->findChildren( + QString("Statistic"), Qt::FindDirectChildrenOnly); + for(int i = 0; i < statistics.size(); i++) statistics[i]->updateStatistics(statistics_data[i].second); - if (!ui->boxMeasure->isChecked()) + if(!ui->boxMeasure->isChecked()) statisticsPanel->hide(); } void Oscilloscope::statisticsUpdateGuiTitleColor() { - QListstatistics = statistics_panel_ui-> - statistics->findChildren( - QString("Statistic"), Qt::FindDirectChildrenOnly); - for (int i = 0; i < statistics.size(); i++) - statistics[i]->setTitleColor(plot.getLineColor( - statistics[i]->channelId())); + QList statistics = statistics_panel_ui->statistics->findChildren( + QString("Statistic"), Qt::FindDirectChildrenOnly); + for(int i = 0; i < statistics.size(); i++) + statistics[i]->setTitleColor(plot.getLineColor(statistics[i]->channelId())); } void Oscilloscope::statisticsUpdateGuiPosIndex() { - QListstatistics = statistics_panel_ui-> - statistics->findChildren( - QString("Statistic"), Qt::FindDirectChildrenOnly); - for (int i = 0; i < statistics.size(); i++) + QList statistics = statistics_panel_ui->statistics->findChildren( + QString("Statistic"), Qt::FindDirectChildrenOnly); + for(int i = 0; i < statistics.size(); i++) statistics[i]->setPositionIndex(i + 1); } void Oscilloscope::onStatisticActivated(int id, int chnIdx) { std::shared_ptr pmd = plot.measurement(id, chnIdx); - if (!pmd) + if(!pmd) return; - - statistics_data.push_back(QPair, - M2kStatistic>(pmd, M2kStatistic())); + + statistics_data.push_back(QPair, M2kStatistic>(pmd, M2kStatistic())); /* Add a widget for the new statistic */ QWidget *statisticContainer = statistics_panel_ui->statistics; - QHBoxLayout *hLayout = static_cast - (statisticContainer->layout()); + QHBoxLayout *hLayout = static_cast(statisticContainer->layout()); StatisticWidget *statistic = new StatisticWidget(statisticContainer); statistic->initForMeasurement(*pmd); @@ -4741,36 +4434,32 @@ void Oscilloscope::onStatisticActivated(int id, int chnIdx) void Oscilloscope::onStatisticDeactivated(int id, int chnIdx) { std::shared_ptr pmd = plot.measurement(id, chnIdx); - if (!pmd) + if(!pmd) return; QString name = pmd->name(); auto it = std::find_if(statistics_data.begin(), statistics_data.end(), - [&](QPair, M2kStatistic> pair) { - return pair.first->name() == name && - pair.first->channel() == chnIdx; - }); - if (it != statistics_data.end()) { + [&](QPair, M2kStatistic> pair) { + return pair.first->name() == name && pair.first->channel() == chnIdx; + }); + if(it != statistics_data.end()) { statistics_data.erase(it); } /* remove the widget corresponding to the statistic we deleted */ - QListstatistics = statistics_panel_ui->statistics-> - findChildren(QString("Statistic"), - Qt::FindDirectChildrenOnly); - - auto stat_it = std::find_if(statistics.begin(), statistics.end(), - [=](StatisticWidget *statistic){ - return statistic->title() == name && - statistic->channelId() == chnIdx; - }); - if (stat_it != statistics.end()) { - QWidget *w = static_cast (*stat_it); - if (statistics_enabled) // Avoid flickers when panel is visible + QList statistics = statistics_panel_ui->statistics->findChildren( + QString("Statistic"), Qt::FindDirectChildrenOnly); + + auto stat_it = std::find_if(statistics.begin(), statistics.end(), [=](StatisticWidget *statistic) { + return statistic->title() == name && statistic->channelId() == chnIdx; + }); + if(stat_it != statistics.end()) { + QWidget *w = static_cast(*stat_it); + if(statistics_enabled) // Avoid flickers when panel is visible statisticsPanel->hide(); // Avoid flickers statistics_panel_ui->statistics->layout()->removeWidget(w); - if (statistics_enabled) // Avoid flickers when panel is visible + if(statistics_enabled) // Avoid flickers when panel is visible statisticsPanel->show(); delete w; @@ -4783,21 +4472,18 @@ void Oscilloscope::onStatisticSelectionListChanged() // Clear all statistics in list statistics_data.clear(); - QListstatistics = statistics_panel_ui->statistics-> - findChildren(QString("Statistic"), - Qt::FindDirectChildrenOnly); - for (int i = 0; i < statistics.size(); i++) { - statistics_panel_ui->statistics->layout()->removeWidget( - statistics[i]); + QList statistics = statistics_panel_ui->statistics->findChildren( + QString("Statistic"), Qt::FindDirectChildrenOnly); + for(int i = 0; i < statistics.size(); i++) { + statistics_panel_ui->statistics->layout()->removeWidget(statistics[i]); delete statistics[i]; } // Use the new list from MeasureSettings auto newList = measure_settings->statisticSelection(); - for (int i = 0; i < newList.size(); i++) + for(int i = 0; i < newList.size(); i++) onStatisticActivated(newList[i].id(), newList[i].channel_id()); statisticsUpdateGui(); - } void Oscilloscope::onStatisticsEnabled(bool on) @@ -4805,7 +4491,7 @@ void Oscilloscope::onStatisticsEnabled(bool on) statistics_enabled = on; statisticsPanel->setVisible(on); - if (!on) + if(!on) statisticsReset(); else statisticsUpdateGui(); @@ -4817,34 +4503,30 @@ void Oscilloscope::onStatisticsReset() statisticsUpdateGui(); } -void Oscilloscope::onGatingEnabled(bool on){ -//enable / disable gatings +void Oscilloscope::onGatingEnabled(bool on) +{ + // enable / disable gatings gatingEnabled = on; buffer_previewer->setGatingEnabled(on && ui->boxMeasure->isChecked()); plot.setGatingEnabled(on && ui->boxMeasure->isChecked()); } -void Oscilloscope::onLeftGateChanged(double width) -{ - buffer_previewer->setLeftGateWidth(width); -} +void Oscilloscope::onLeftGateChanged(double width) { buffer_previewer->setLeftGateWidth(width); } -void Oscilloscope::onRightGateChanged(double width) -{ - buffer_previewer->setRightGateWidth(width); -} +void Oscilloscope::onRightGateChanged(double width) { buffer_previewer->setRightGateWidth(width); } void Oscilloscope::setupAutosetFreqSweep() -{ bool started = isIioManagerStarted(); - if(started) +{ + bool started = isIioManagerStarted(); + if(started) iio->lock(); qt_time_block->reset(); qt_time_block->clean_buffers(); - if (m_m2k_analogin) { + if(m_m2k_analogin) { runInHwThreadPool({ - high_gain_modes[autosetChannel] = libm2k::analog::PLUS_MINUS_25V; - trigger_settings.autoTriggerDisable(); - trigger_settings.setTriggerEnable(false); + high_gain_modes[autosetChannel] = libm2k::analog::PLUS_MINUS_25V; + trigger_settings.autoTriggerDisable(); + trigger_settings.setTriggerEnable(false); }); } autosetSampleRateCnt--; @@ -4857,15 +4539,15 @@ void Oscilloscope::setupAutosetFreqSweep() last_set_sample_count = active_sample_count; autosetFFT(); iio->set_buffer_size(autoset_id[0], autoset_fft_size); - for (unsigned int i = 0; i < nb_channels; i++) { + for(unsigned int i = 0; i < nb_channels; i++) { iio->set_buffer_size(ids[i], autoset_fft_size); dc_cancel.at(i)->set_buffer_size(active_sample_count); } - if (mixed_source) { + if(mixed_source) { mixed_source->set_buffer_size(active_sample_count); setDigitalPlotCurvesParams(); } - if (keep_one) { + if(keep_one) { iio->disconnect(dc_cancel.at(triggerLevelSink.second), 0, keep_one, 0); iio->disconnect(keep_one, 0, triggerLevelSink.first, 0); keep_one = gr::blocks::keep_one_in_n::make(sizeof(float), active_sample_count); @@ -4880,19 +4562,19 @@ bool Oscilloscope::autosetFindFrequency() { toggle_blockchain_flow(false); - double max=-INFINITY; - size_t maxindex=1; + double max = -INFINITY; + size_t maxindex = 1; // try skipping the DC offset tones and last few tones that cause // weird results - for(int j=autosetNrOfSkippedTones ;j<((autoset_fft_size/2)-5);j++) { + for(int j = autosetNrOfSkippedTones; j < ((autoset_fft_size / 2) - 5); j++) { if(autosetFFTSink->data()[j] > max) { max = autosetFFTSink->data()[j]; - maxindex=j; + maxindex = j; } } - double frequency = (maxindex) * (active_sample_rate/autoset_fft_size); + double frequency = (maxindex) * (active_sample_rate / autoset_fft_size); autosetFFTIndex = maxindex; if(autosetMaxIndexAmpl < max /*&& (autosetFFTIndex > autosetValidTone)*/) { autosetFrequency = frequency; @@ -4904,21 +4586,19 @@ bool Oscilloscope::autosetFindFrequency() void Oscilloscope::autosetFindPeaks() { - for(auto j=autosetSkippedTimeSamples;jdata()->sample(j).y(); - if(data > autosetMaxAmpl) - autosetMaxAmpl = data; - if(data < autosetMinAmpl) - autosetMinAmpl = data; - } - qDebug()<<"autoset min-max" << autosetMinAmpl <data()->sample(j).y(); + if(data > autosetMaxAmpl) + autosetMaxAmpl = data; + if(data < autosetMinAmpl) + autosetMinAmpl = data; + } + qDebug() << "autoset min-max" << autosetMinAmpl << autosetMaxAmpl; } - - void Oscilloscope::requestAutoset() { - if(!autosetRequested && current_ch_widget != -1 && current_ch_widget < nb_channels){ + if(!autosetRequested && current_ch_widget != -1 && current_ch_widget < nb_channels) { toggle_blockchain_flow(false); autosetChannel = current_ch_widget; @@ -4944,31 +4624,31 @@ void Oscilloscope::periodicFlowRestart(bool force) QElapsedTimer t; t.start(); iio->lock(); -// m_m2k_context->stopMixedSignalAcquisition(); -// m_m2k_context->startMixedSignalAcquisition(active_sample_count); + // m_m2k_context->stopMixedSignalAcquisition(); + // m_m2k_context->startMixedSignalAcquisition(active_sample_count); iio->unlock(); - qDebug(CAT_M2K_OSCILLOSCOPE)<<"Restarted flow @ " << QTime::currentTime().toString("hh:mm:ss") <<"restart took " << t.elapsed() << "ms"; + qDebug(CAT_M2K_OSCILLOSCOPE) << "Restarted flow @ " << QTime::currentTime().toString("hh:mm:ss") + << "restart took " << t.elapsed() << "ms"; } restartFlowCounter--; } void Oscilloscope::autosetNextStep() { - static int prevmaxindex=0; + static int prevmaxindex = 0; // Only consider tone valid if it's index is higher than a preset value // This ensures that a good enough resolution bandwidth is achieved - if(autosetSampleRateCnt > 1){ + if(autosetSampleRateCnt > 1) { prevmaxindex = autosetFFTIndex; setupAutosetFreqSweep(); - } - else - { + } else { autosetFinalStep(); } toggle_blockchain_flow(true); } -void Oscilloscope::autosetFinalStep() { +void Oscilloscope::autosetFinalStep() +{ double timebaseval = timeBase->minValue(); double timeposval = 0; double voltspos = 0; @@ -4980,17 +4660,16 @@ void Oscilloscope::autosetFinalStep() { autoset_id[0] = nullptr; } autosetRequested = false; - if (ui->runSingleWidget->runButtonChecked()) { + if(ui->runSingleWidget->runButtonChecked()) { runStopToggled(false); runStopToggled(true); } // autoset frequency found - if(autosetFFTIndex>1) { - timebaseval = (1/autosetFrequency)/2; - voltsperdiv = (max(abs(autosetMaxAmpl), - abs(autosetMinAmpl)))/5; - triggerlevel = (autosetMaxAmpl+autosetMinAmpl)/2; + if(autosetFFTIndex > 1) { + timebaseval = (1 / autosetFrequency) / 2; + voltsperdiv = (max(abs(autosetMaxAmpl), abs(autosetMinAmpl))) / 5; + triggerlevel = (autosetMaxAmpl + autosetMinAmpl) / 2; } timeBase->setValue(timebaseval); @@ -5004,16 +4683,15 @@ void Oscilloscope::autosetFinalStep() { trigger_settings.setTriggerSource(autosetChannel); trigger_settings.setTriggerLevel(triggerlevel); trigger_settings.setTriggerEnable(true); - trigger_settings.autoTriggerEnable(); + trigger_settings.autoTriggerEnable(); onTimePositionChanged(timePosition->value()); } void Oscilloscope::singleCaptureDone() { - if (!symmBufferMode->isEnhancedMemDepth() - && !plot_samples_sequentially) { + if(!symmBufferMode->isEnhancedMemDepth() && !plot_samples_sequentially) { Q_EMIT activateExportButton(); - if (ui->runSingleWidget->singleButtonChecked()){ + if(ui->runSingleWidget->singleButtonChecked()) { Q_EMIT startRunning(false); } } @@ -5022,10 +4700,8 @@ void Oscilloscope::singleCaptureDone() plot.repositionCursors(); scaleHistogramPlot(true); - if(autosetRequested) - { - if(autosetFFTSink->data().size() > autoset_fft_size) - { + if(autosetRequested) { + if(autosetFFTSink->data().size() > autoset_fft_size) { bool found = autosetFindFrequency(); if(found) autosetFindPeaks(); @@ -5036,11 +4712,11 @@ void Oscilloscope::singleCaptureDone() void Oscilloscope::scaleHistogramPlot(bool newData) { - if (hist_plot.isZoomed() && newData) { + if(hist_plot.isZoomed() && newData) { return; } - for (size_t i = 0; i < nb_channels; i++) { + for(size_t i = 0; i < nb_channels; i++) { double min = plot.axisInterval(QwtAxisId(QwtAxis::YLeft, i)).minValue(); double max = plot.axisInterval(QwtAxisId(QwtAxis::YLeft, i)).maxValue(); @@ -5051,7 +4727,7 @@ void Oscilloscope::scaleHistogramPlot(bool newData) void Oscilloscope::onFilledScreen(bool full, unsigned int nb_samples) { - if (nb_samples == active_plot_sample_count) { + if(nb_samples == active_plot_sample_count) { d_shouldResetStreaming = full; resetStreamingFlag(full); } @@ -5060,34 +4736,33 @@ void Oscilloscope::onFilledScreen(bool full, unsigned int nb_samples) void Oscilloscope::resetStreamingFlag(bool enable) { bool started = isIioManagerStarted(); - if (started) + if(started) iio->lock(); try { m_m2k_analogin->getTrigger()->setAnalogStreamingFlag(false); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_OSCILLOSCOPE) << e.what(); } cleanBuffersAllSinks(); - if (started) + if(started) iio->unlock(); try { - if (enable && !d_displayOneBuffer) { + if(enable && !d_displayOneBuffer) { m_m2k_analogin->getTrigger()->setAnalogStreamingFlag(true); } - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_OSCILLOSCOPE) << e.what(); } /* Single capture done */ - if ((symmBufferMode->isEnhancedMemDepth() || plot_samples_sequentially) - && d_shouldResetStreaming) { + if((symmBufferMode->isEnhancedMemDepth() || plot_samples_sequentially) && d_shouldResetStreaming) { Q_EMIT activateExportButton(); - if (ui->runSingleWidget->singleButtonChecked() && started){ + if(ui->runSingleWidget->singleButtonChecked() && started) { Q_EMIT startRunning(false); } } @@ -5098,14 +4773,13 @@ void Oscilloscope::cleanBuffersAllSinks() { this->qt_time_block->clean_buffers(); - if (mixed_sink) { + if(mixed_sink) { mixed_sink->clean_buffers(); } auto it = math_sinks.constBegin(); - while (it != math_sinks.constEnd()) { - scope_sink_f::sptr math_sink = dynamic_pointer_cast< - scope_sink_f>(it.value().second); + while(it != math_sinks.constEnd()) { + scope_sink_f::sptr math_sink = dynamic_pointer_cast(it.value().second); math_sink->clean_buffers(); ++it; } @@ -5114,7 +4788,7 @@ void Oscilloscope::cleanBuffersAllSinks() void Oscilloscope::onIioDataRefillTimeout() { - if (trigger_settings.triggerMode() == TriggerSettings::AUTO) + if(trigger_settings.triggerMode() == TriggerSettings::AUTO) trigger_is_forced = true; } @@ -5123,7 +4797,7 @@ void Oscilloscope::onPlotNewData() // Flag the new received data as Triggered or Untriggered. bool triggerOn = trigger_settings.triggerIsArmed(); - if (triggerOn && !trigger_is_forced) + if(triggerOn && !trigger_is_forced) new_data_is_triggered = true; else new_data_is_triggered = false; @@ -5132,22 +4806,22 @@ void Oscilloscope::onPlotNewData() trigger_is_forced = false; // Update trigger status - if (new_data_is_triggered) + if(new_data_is_triggered) triggerUpdater->setInput(CapturePlot::Triggered); else triggerUpdater->setInput(CapturePlot::Auto); updateBufferPreviewer(); - trigger_input = true; //used to read trigger status from Js + trigger_input = true; // used to read trigger status from Js } void Oscilloscope::onTriggerModeChanged(int mode) { - if (mode == 0) { // normal + if(mode == 0) { // normal triggerUpdater->setIdleState(CapturePlot::Waiting); triggerUpdater->setInput(CapturePlot::Waiting); - } else if (mode == 1) { // auto + } else if(mode == 1) { // auto triggerUpdater->setIdleState(CapturePlot::Auto); triggerUpdater->setInput(CapturePlot::Auto); } @@ -5163,30 +4837,25 @@ void Oscilloscope::updateBufferPreviewer() long long triggerSamples = trigger_settings.triggerDelay(); long long totalSamples = last_set_sample_count; - if (totalSamples > 0) { + if(totalSamples > 0) { dataInterval.setMinValue(triggerSamples / getSampleRate()); - dataInterval.setMaxValue((triggerSamples + totalSamples) - / getSampleRate()); + dataInterval.setMaxValue((triggerSamples + totalSamples) / getSampleRate()); } // Use the two intervals to determine the width and position of the // waveform and of the highlighted area QwtInterval fullInterval = plotInterval | dataInterval; - double wPos = 1 - (fullInterval.maxValue() - dataInterval.minValue()) / - fullInterval.width(); + double wPos = 1 - (fullInterval.maxValue() - dataInterval.minValue()) / fullInterval.width(); double wWidth = dataInterval.width() / fullInterval.width(); - double hPos = 1 - (fullInterval.maxValue() - plotInterval.minValue()) / - fullInterval.width(); + double hPos = 1 - (fullInterval.maxValue() - plotInterval.minValue()) / fullInterval.width(); double hWidth = plotInterval.width() / fullInterval.width(); // Determine the cursor position - QwtInterval containerInterval = (totalSamples > 0) ? dataInterval : - fullInterval; + QwtInterval containerInterval = (totalSamples > 0) ? dataInterval : fullInterval; double containerWidth = (totalSamples > 0) ? wWidth : 1; double containerPos = (totalSamples > 0) ? wPos : 0; - double cPosInContainer = 1 - (containerInterval.maxValue() - 0) / - containerInterval.width(); + double cPosInContainer = 1 - (containerInterval.maxValue() - 0) / containerInterval.width(); double cPos = cPosInContainer * containerWidth + containerPos; // Update the widget @@ -5201,12 +4870,11 @@ void Oscilloscope::on_btnSettings_clicked(bool checked) { CustomPushButton *btn = nullptr; - if (checked && !menuOrder.isEmpty()) { + if(checked && !menuOrder.isEmpty()) { btn = menuOrder.back(); menuOrder.pop_back(); } else { - btn = static_cast( - ui->settings_group->checkedButton()); + btn = static_cast(ui->settings_group->checkedButton()); } btn->setChecked(checked); @@ -5215,32 +4883,29 @@ void Oscilloscope::on_btnSettings_clicked(bool checked) void Oscilloscope::updateGainMode() { - if (current_ch_widget >= nb_channels) { + if(current_ch_widget >= nb_channels) { return; } double offset = plot.VertOffset(current_ch_widget); QwtInterval hw_input_itv(-2.5 + offset, 2.5 + offset); - QwtInterval plot_vert_itv = plot.axisScaleDiv( - QwtAxisId(QwtAxis::YLeft, current_ch_widget)).interval(); + QwtInterval plot_vert_itv = plot.axisScaleDiv(QwtAxisId(QwtAxis::YLeft, current_ch_widget)).interval(); auto chn = static_cast(current_ch_widget); // If max signal span that can be captured is smaller than the plot // screen try to increase the range (switch to low gain mode) - if (plot_vert_itv.minValue() < hw_input_itv.minValue() || - plot_vert_itv.maxValue() > hw_input_itv.maxValue() || - std::abs(offset) > 5.0) { - if (high_gain_modes[current_ch_widget]) { + if(plot_vert_itv.minValue() < hw_input_itv.minValue() || plot_vert_itv.maxValue() > hw_input_itv.maxValue() || + std::abs(offset) > 5.0) { + if(high_gain_modes[current_ch_widget]) { high_gain_modes[current_ch_widget] = false; bool running = ui->runSingleWidget->runButtonChecked(); - if (running) + if(running) toggle_blockchain_flow(false); setGainMode(current_ch_widget, libm2k::analog::PLUS_MINUS_25V); - if (running) + if(running) toggle_blockchain_flow(true); - auto adc_range_limits = m_m2k_analogin->getRangeLimits(libm2k::analog::PLUS_MINUS_25V); auto hyst_range_limits = m_m2k_analogin->getHysteresisRange(chn); @@ -5248,14 +4913,14 @@ void Oscilloscope::updateGainMode() trigger_settings.setTriggerHystRange(current_ch_widget, hyst_range_limits); } } else { - if (!high_gain_modes[current_ch_widget]) { + if(!high_gain_modes[current_ch_widget]) { high_gain_modes[current_ch_widget] = true; bool running = ui->runSingleWidget->runButtonChecked(); - if (running) + if(running) toggle_blockchain_flow(false); setGainMode(current_ch_widget, libm2k::analog::PLUS_MINUS_2_5V); - if (running) + if(running) toggle_blockchain_flow(true); auto adc_range_limits = m_m2k_analogin->getRangeLimits(libm2k::analog::PLUS_MINUS_25V); @@ -5265,17 +4930,16 @@ void Oscilloscope::updateGainMode() trigger_settings.setTriggerHystRange(current_ch_widget, hyst_range_limits); } } - } void Oscilloscope::setGainMode(uint chnIdx, libm2k::analog::M2K_RANGE gain_mode) { - if (ui->runSingleWidget->runButtonChecked()) { + if(ui->runSingleWidget->runButtonChecked()) { try { libm2k::analog::ANALOG_IN_CHANNEL chn = static_cast(chnIdx); - runInHwThreadPool( m_m2k_analogin->setRange(chn, gain_mode) ); + runInHwThreadPool(m_m2k_analogin->setRange(chn, gain_mode)); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_OSCILLOSCOPE) << e.what(); } @@ -5292,17 +4956,16 @@ void Oscilloscope::setGainMode(uint chnIdx, libm2k::analog::M2K_RANGE gain_mode) void Oscilloscope::setChannelHwOffset(uint chnIdx, double offset) { channel_offset[chnIdx] = offset; - if (ui->runSingleWidget->runButtonChecked()) { + if(ui->runSingleWidget->runButtonChecked()) { try { libm2k::analog::ANALOG_IN_CHANNEL chn = static_cast(chnIdx); - runInHwThreadPool(m_m2k_analogin->setVerticalOffset(chn, offset); ); + runInHwThreadPool(m_m2k_analogin->setVerticalOffset(chn, offset);); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_OSCILLOSCOPE) << e.what(); } } - } void Oscilloscope::setAllSinksSampleCount(unsigned long sample_count) @@ -5311,14 +4974,13 @@ void Oscilloscope::setAllSinksSampleCount(unsigned long sample_count) this->qt_xy_block->set_nsamps(sample_count); this->qt_hist_block->set_nsamps(sample_count); - if (mixed_sink) { + if(mixed_sink) { mixed_sink->set_nsamps(sample_count); } auto it = math_sinks.constBegin(); - while (it != math_sinks.constEnd()) { - scope_sink_f::sptr math_sink = dynamic_pointer_cast< - scope_sink_f>(it.value().second); + while(it != math_sinks.constEnd()) { + scope_sink_f::sptr math_sink = dynamic_pointer_cast(it.value().second); math_sink->set_nsamps(sample_count); ++it; } @@ -5328,30 +4990,31 @@ void Oscilloscope::setAllSinksSampleCount(unsigned long sample_count) void Oscilloscope::writeAllSettingsToHardware() { // Sample Rate - if (active_sample_rate != getSampleRate()) { + if(active_sample_rate != getSampleRate()) { setSampleRate(active_sample_rate); } // Offset and Gain - if (m_m2k_analogin) { - for (uint i = 0; i < nb_channels; i++) { + if(m_m2k_analogin) { + for(uint i = 0; i < nb_channels; i++) { try { - runInHwThreadPool( { - libm2k::analog::M2K_RANGE mode = high_gain_modes[i] ? - libm2k::analog::PLUS_MINUS_2_5V : libm2k::analog::PLUS_MINUS_25V; - libm2k::analog::ANALOG_IN_CHANNEL chn = static_cast(i); - m_m2k_analogin->setRange(chn, mode); - m_m2k_analogin->setVerticalOffset(chn, channel_offset[i]); - } ); - } catch (libm2k::m2k_exception &e) { + runInHwThreadPool({ + libm2k::analog::M2K_RANGE mode = high_gain_modes[i] + ? libm2k::analog::PLUS_MINUS_2_5V + : libm2k::analog::PLUS_MINUS_25V; + libm2k::analog::ANALOG_IN_CHANNEL chn = + static_cast(i); + m_m2k_analogin->setRange(chn, mode); + m_m2k_analogin->setVerticalOffset(chn, channel_offset[i]); + }); + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e) qDebug(CAT_M2K_OSCILLOSCOPE) << e.what(); } } setSampleRate(active_sample_rate); } - for(size_t i=0;ifreq_comp_filt[i][0]->set_sample_rate(active_sample_rate); iio->freq_comp_filt[i][1]->set_sample_rate(active_sample_rate); } @@ -5362,7 +5025,7 @@ void Oscilloscope::writeAllSettingsToHardware() void Oscilloscope::xyPlotLineType_toggled(bool checked) { - if (checked) { + if(checked) { xy_plot.setLineStyle(0, Qt::DotLine); } else { xy_plot.setLineStyle(0, Qt::SolidLine); @@ -5370,22 +5033,16 @@ void Oscilloscope::xyPlotLineType_toggled(bool checked) xy_plot.replot(); } - -void Oscilloscope::xyLineThickness_currentIndexChanged(int idx) -{ - xy_plot.setLineWidth(0,idx); -} +void Oscilloscope::xyLineThickness_currentIndexChanged(int idx) { xy_plot.setLineWidth(0, idx); } void Oscilloscope::setup_xy_channels() { int x = gsettings_ui->cmb_x_channel->currentIndex(); int y = gsettings_ui->cmb_y_channel->currentIndex(); QWidget *xsw = xy_plot.axisWidget(QwtAxis::XBottom); - xsw->setStyleSheet( - QString("color: %1").arg(plot.getLineColor(x).name())); + xsw->setStyleSheet(QString("color: %1").arg(plot.getLineColor(x).name())); QWidget *ysw = xy_plot.axisWidget(QwtAxis::YLeft); - ysw->setStyleSheet( - QString("color: %1").arg(plot.getLineColor(y).name())); + ysw->setStyleSheet(QString("color: %1").arg(plot.getLineColor(y).name())); // If XY visible, reconnect the data flow if(xy_is_visible) @@ -5399,32 +5056,27 @@ void Oscilloscope::setup_xy_channels() void Oscilloscope::on_btnAddMath_toggled(bool checked) { - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); + triggerRightMenuToggle(static_cast(QObject::sender()), checked); } void Oscilloscope::on_btnCursors_toggled(bool checked) { - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); + triggerRightMenuToggle(static_cast(QObject::sender()), checked); } void Oscilloscope::on_btnMeasure_toggled(bool checked) { - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); + triggerRightMenuToggle(static_cast(QObject::sender()), checked); } void Oscilloscope::on_btnTrigger_toggled(bool checked) { - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); + triggerRightMenuToggle(static_cast(QObject::sender()), checked); } void Oscilloscope::on_btnGeneralSettings_toggled(bool checked) { - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); + triggerRightMenuToggle(static_cast(QObject::sender()), checked); if(checked) ui->btnSettings->setChecked(!checked); } @@ -5433,7 +5085,7 @@ void Oscilloscope::channelLineWidthChanged(int id) { qreal width = 0.5 * (id + 1); - if (width != plot.getLineWidthF(current_ch_widget)) { + if(width != plot.getLineWidthF(current_ch_widget)) { plot.setLineWidthF(current_ch_widget, width); plot.replot(); } @@ -5441,40 +5093,39 @@ void Oscilloscope::channelLineWidthChanged(int id) void Oscilloscope::setSampleRate(double sample_rate) { - if (!m_m2k_analogin) { + if(!m_m2k_analogin) { return; } - runInHwThreadPool( { - try { - auto maxSampleRate = m_m2k_analogin->getMaximumSamplerate(); - if (m_filtering_enabled == false) { - m_m2k_analogin->setSampleRate(maxSampleRate); - m_m2k_analogin->setOversamplingRatio(maxSampleRate / sample_rate); - } else { - m_m2k_analogin->setSampleRate(sample_rate); - m_m2k_analogin->setOversamplingRatio(1); + runInHwThreadPool({ + try { + auto maxSampleRate = m_m2k_analogin->getMaximumSamplerate(); + if(m_filtering_enabled == false) { + m_m2k_analogin->setSampleRate(maxSampleRate); + m_m2k_analogin->setOversamplingRatio(maxSampleRate / sample_rate); + } else { + m_m2k_analogin->setSampleRate(sample_rate); + m_m2k_analogin->setOversamplingRatio(1); + } + } catch(libm2k::m2k_exception &e) { + HANDLE_EXCEPTION(e) + qDebug(CAT_M2K_OSCILLOSCOPE) << e.what(); } - } catch (libm2k::m2k_exception &e) { - HANDLE_EXCEPTION(e) - qDebug(CAT_M2K_OSCILLOSCOPE) << e.what(); - } }); } - double Oscilloscope::getSampleRate() { - if (!m_m2k_analogin) { + if(!m_m2k_analogin) { return 0; } try { double sr = m_m2k_analogin->getSampleRate(); - if (m_filtering_enabled == false) { + if(m_filtering_enabled == false) { int osr = m_m2k_analogin->getOversamplingRatio(); sr = (double)(sr / osr); } return sr; - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug(CAT_M2K_OSCILLOSCOPE) << e.what(); return 0; diff --git a/plugins/m2k/src/old/oscilloscope.hpp b/plugins/m2k/src/old/oscilloscope.hpp index 7dd4d1015f..d0815527d1 100644 --- a/plugins/m2k/src/old/oscilloscope.hpp +++ b/plugins/m2k/src/old/oscilloscope.hpp @@ -24,51 +24,50 @@ #include /* GNU Radio includes */ -#include -#include -#include #include +#include +#include #include -#include #include -#include #include - +#include +#include +#include /* Qt includes */ +#include +#include #include #include +#include #include +#include #include #include -#include -#include -#include -#include /* Local includes */ -#include "pluginbase/apiobject.h" -#include "gui/oscilloscope_plot.hpp" -#include "iio_manager.hpp" -#include "filter.hpp" -#include "fft_block.hpp" -#include "scope_sink_f.h" -#include "xy_sink_c.h" -#include "histogram_sink_f.h" #include "ConstellationDisplayPlot.h" #include "FftDisplayPlot.h" #include "HistogramDisplayPlot.h" +#include "cancel_dc_offset_block.h" +#include "fft_block.hpp" +#include "filter.hpp" +#include "frequency_compensation_filter.h" +#include "gui/osc_import_settings.h" +#include "gui/oscilloscope_plot.hpp" #include "gui/spinbox_a.hpp" -#include "trigger_settings.hpp" -#include "plot_utils.hpp" +#include "histogram_sink_f.h" +#include "iio_manager.hpp" +#include "logicanalyzer/logic_analyzer.h" #include "m2ktool.hpp" -#include "gui/osc_import_settings.h" #include "math.hpp" #include "mousewheelwidgetguard.h" -#include "cancel_dc_offset_block.h" -#include "frequency_compensation_filter.h" #include "oscilloscope_api.hpp" -#include "logicanalyzer/logic_analyzer.h" +#include "plot_utils.hpp" +#include "pluginbase/apiobject.h" +#include "scope_sink_f.h" +#include "trigger_settings.hpp" +#include "xy_sink_c.h" /* libm2k includes */ #include @@ -76,10 +75,11 @@ #include /* gr-m2k includes */ -#include #include "logic_analyzer_sink.h" #include "mixed_signal_sink.h" +#include + /*Generated UI */ #include "ui_math_panel.h" @@ -89,425 +89,420 @@ class QJSEngine; class SymmetricBufferMode; namespace Ui { - class Oscilloscope; - class OscGeneralSettings; - class ChannelSettings; - class MeasurementsPanel; - class StatisticsPanel; - class CursorReadouts; - class CursorsSettings; -} +class Oscilloscope; +class OscGeneralSettings; +class ChannelSettings; +class MeasurementsPanel; +class StatisticsPanel; +class CursorReadouts; +class CursorsSettings; +} // namespace Ui namespace scopy { - class ChannelWidget; - class AnalogBufferPreviewer; - class M2kMeasurementData; - class CustomPushButton; - class M2kMeasurementGui; +class ChannelWidget; +class AnalogBufferPreviewer; +class M2kMeasurementData; +class CustomPushButton; +class M2kMeasurementGui; -} +} // namespace scopy namespace scopy::m2k { - class Oscilloscope_API; - class Channel_API; - class MeasureSettings; - class StateUpdater; - class signal_sample; - - class Oscilloscope : public M2kTool - { - friend class Oscilloscope_API; - friend class Channel_API; - friend class Channel_Digital_Filter_API; - friend class ToolLauncher_API; - - Q_OBJECT - - public: - explicit Oscilloscope(struct iio_context *ctx, Filter *filt, - ToolMenuEntry *tme, m2k_iio_manager* m2k_man, QJSEngine *engine, - QWidget *parent = 0); - ~Oscilloscope(); - - QPushButton* getRunButton(); - void settingsLoaded(); - - bool getTrigger_input() const; - void setTrigger_input(bool value); - - void add_ref_waveform(QString name, QVector xData, QVector yData, unsigned int sampleRate); - void remove_ref_waveform(QString name); - void setNativeDialogs(bool nativeDialogs) override; - - void setLogicAnalyzer(logic::LogicAnalyzer *la); - - Q_SIGNALS: - void triggerALevelChanged(double); - void triggerBLevelChanged(double); - void triggerPositionChanged(double); - void selectedChannelChanged(int); - void activateExportButton(); - void startRunning(bool); - void importFileLoaded(bool); - void showTool(); - - private Q_SLOTS: - void btnExport_clicked(); - - void on_actionClose_triggered(); - void on_boxCursors_toggled(bool on); - void on_boxMeasure_toggled(bool on); - - void onFFT_view_toggled(bool visible); - void onHistogram_view_toggled(bool visible); - void onXY_view_toggled(bool visible); - - void on_btnAddMath_toggled(bool); - void on_btnCursors_toggled(bool); - void on_btnMeasure_toggled(bool); - void on_btnTrigger_toggled(bool); - void on_btnGeneralSettings_toggled(bool); - - void onTriggerSourceChanged(int); - void onTimeTriggerDelayChanged(double); - void onTriggerLevelChanged(double); - void onTriggerModeChanged(int); - - void onVertScaleValueChanged(double value); - void onHorizScaleValueChanged(double value); - void onVertOffsetValueChanged(double value); - void onTimePositionChanged(double value); - - - void onChannelCouplingChanged(bool en); - void onChannelOffsetChanged(unsigned int chnIdx, double value); - void xyLineThickness_currentIndexChanged(int idx); - - void onChannelWidgetEnabled(bool); - void onChannelWidgetSelected(bool); - void onChannelWidgetMenuToggled(bool); - void onChannelWidgetDeleteClicked(); - - void rightMenuFinished(bool opened); - - void toggle_blockchain_flow(bool); - void runStopToggled(bool); - void periodicFlowRestart(bool force=false); - void autosetNextStep(); - void autosetFinalStep(); - void autosetFindPeaks(); - bool autosetFindFrequency(); - void setupAutosetFreqSweep(); - void singleCaptureDone(); - - void onMeasuremetsAvailable(); - - void onMeasurementActivated(int id, int chnIdx); - void onMeasurementDeactivated(int id, int chnIdx); - void onMeasurementSelectionListChanged(); - - void onStatisticActivated(int id, int chnIdx); - void onStatisticDeactivated(int id, int chnIdx); - void onStatisticSelectionListChanged(); - void onStatisticsEnabled(bool on); - void onStatisticsReset(); - void onGatingEnabled(bool on); - void onLeftGateChanged(double); - void onRightGateChanged(double); - - void onCursorReadoutsChanged(struct cursorReadoutsText); - - void onIioDataRefillTimeout(); - void onPlotNewData(); - - void on_btnSettings_clicked(bool checked); - void channelLineWidthChanged(int id); - - void update_chn_settings_panel(int id); - - void updateGainMode(); - void setGainMode(uint chnIdx, libm2k::analog::M2K_RANGE gain_mode); - void setChannelHwOffset(uint chnIdx, double offset); - - void xyPlotLineType_toggled(bool checked); - void setup_xy_channels(); - - void openEditMathPanel(bool on); - - void updateTriggerLevelValue(std::vector value); - void configureAcCouplingTrigger(bool); - - void readPreferences(); - - void onCmbMemoryDepthChanged(QString); - void setSinksDisplayOneBuffer(bool); - void cleanBuffersAllSinks(); - void resetStreamingFlag(bool); - void onFilledScreen(bool, unsigned int); - - void toggleCursorsMode(bool toggled); - void toolDetached(bool); - void setFilteringEnabled(bool set); - - void enableMixedSignalView(ChannelWidget *cw); - void disableMixedSignalView(); - void setDigitalPlotCurvesParams(); - - void selectChannel(int index, bool checked); - public Q_SLOTS: - void requestAutoset(); - void enableLabels(bool); - void import(); - void run() override; - void stop() override; - - private: - libm2k::context::M2k* m_m2k_context; - libm2k::analog::M2kAnalogIn* m_m2k_analogin; - libm2k::digital::M2kDigital* m_m2k_digital; - bool m_filtering_enabled; - - unsigned int nb_channels, nb_math_channels; - unsigned int nb_ref_channels; - double active_sample_rate; - double noZoomXAxisWidth; - unsigned long active_sample_count; - unsigned long active_plot_sample_count; - long long active_trig_sample_count; - double active_time_pos; - double memory_adjusted_time_pos; - double last_set_time_pos; - unsigned long last_set_sample_count; - int zoom_level; - bool plot_samples_sequentially, d_displayOneBuffer, d_shouldResetStreaming; - double horiz_offset; - bool reset_horiz_offset; - double time_trigger_offset; - int min_detached_width; - bool miniHistogram; - - int autosetMaxIndexAmpl; - int autosetFFTIndex; - double autosetFrequency; - double autosetMaxAmpl; - double autosetMinAmpl; - int autosetSampleRateCnt; - int autosetChannel; - bool autosetEnabled; - const int autosetSkippedTimeSamples = 4096; - const int autosetFFTSize = 8192; - const int autosetNrOfSkippedTones=50; - const int autosetValidTone = 51; - - Ui::Oscilloscope *ui; - Ui::OscGeneralSettings *gsettings_ui; - Ui::ChannelSettings *ch_ui; - scopy::m2k::TriggerSettings trigger_settings; - scopy::m2k::MeasureSettings *measure_settings; - CapturePlot plot; - FftDisplayPlot fft_plot; - ConstellationDisplayPlot xy_plot; - HistogramDisplayPlot hist_plot; - Ui::MeasurementsPanel *measure_panel_ui; - QWidget *measurePanel; - Ui::CursorReadouts *cursor_readouts_ui; - QWidget *cursorReadouts; - Ui::StatisticsPanel *statistics_panel_ui; - Ui::CursorsSettings *cr_ui; - QWidget *statisticsPanel; - AnalogBufferPreviewer *buffer_previewer; - ExportSettings *exportSettings; - CustomPlotPositionButton *cursorsPositionButton; - - QGridLayout* gridPlot; - QDockWidget* fftDockWidget; - QDockWidget* xyDockWidget; - QDockWidget* histDockWidget; - QWidget* histWidget; - - MouseWheelWidgetGuard *wheelEventGuard; - - QPair *math_pair; - bool addChannel; - QTabWidget *tabWidget; - QWidget *ref; - - QVector> import_data; - QString import_error; - ImportSettings *importSettings; - bool lastFunctionValid; - - QMap exportConfig; - - std::shared_ptr symmBufferMode; - - scopy::scope_sink_f::sptr qt_time_block; - scopy::scope_sink_f::sptr qt_fft_block; - scopy::xy_sink_c::sptr qt_xy_block; - scopy::histogram_sink_f::sptr qt_hist_block; - std::shared_ptr iio; - gr::basic_block_sptr adc_samp_conv_block; - - QMap> math_sinks; - QMap> math_rails; - std::vector> math_probe_atten; - - iio_manager::port_id *ids; - iio_manager::port_id *hist_ids; - iio_manager::port_id *autoset_id; - - ScaleSpinButton *timeBase; - PositionSpinButton *timePosition; - ScaleSpinButton *voltsPerDiv; - PositionSpinButton *voltsPosition; - - ScaleSpinButton *refChannelTimeBase; - - bool fft_is_visible, hist_is_visible, xy_is_visible, autosetRequested; - bool statistics_enabled; - QList high_gain_modes; - std::vector channel_offset; - - bool hCursorsEnabled; - bool vCursorsEnabled; - bool gatingEnabled; - - std::vector chnAcCoupled; - bool triggerAcCoupled; - QPair, int> triggerLevelSink; - std::shared_ptr keep_one; - std::shared_ptr autosetFFTSink; - - bool trigger_is_forced; - bool new_data_is_triggered; - bool trigger_input; - CapturePlot::TriggerState trigger_state; - StateUpdater *triggerUpdater; - - int fft_size; - int autoset_fft_size; - int fft_plot_size; - - NumberSeries voltsPerDivList; - NumberSeries secPerDivList; - - MetricPrefixFormatter vertMeasureFormat; - TimePrefixFormatter horizMeasureFormat; - - int current_channel; - int current_ch_widget; - unsigned int math_chn_counter; - - QButtonGroup *channels_group; // selected state of each channel - - QPushButton *menuRunButton; - - QList channels_api; - - QList> measurements_data; - QList> measurements_gui; - - QList, - M2kStatistic>> statistics_data; - - QList menuOrder; - - QQueue> menuButtonActions; - - QVector probe_attenuation; - - void writeAllSettingsToHardware(); - - void comboBoxUpdateToValue(QComboBox *box, double value, std::vectorlist); - - void settings_panel_update(int id); - void settings_panel_size_adjust(); - void triggerRightMenuToggle(CustomPushButton *, bool checked); - void toggleRightMenu(CustomPushButton *, bool checked); - void create_add_channel_panel(); - void add_math_channel(const std::string& function); - unsigned int find_curve_number(); - ChannelWidget *channelWidgetAtId(int id); - void update_measure_for_channel(int ch_idx); - QString getChannelRangeStringVDivHelper(int ch); - void setAllSinksSampleCount(unsigned long sample_count); - void autosetFFT(); - - void updateRunButton(bool ch_enabled); - - void fillCursorReadouts(const struct cursorReadoutsText&); - - void measure_panel_init(); - void measure_settings_init(); - void measureLabelsRearrange(); - void measureUpdateValues(); - void measureCreateAndAppendGuiFrom(const M2kMeasurementData&); - - void statistics_panel_init(); - void statisticsUpdateValues(); - void statisticsReset(); - void statisticsUpdateGui(); - void statisticsUpdateGuiTitleColor(); - void statisticsUpdateGuiPosIndex(); - - void updateBufferPreviewer(); - void export_settings_init(); - void pause(bool paused); - void cursor_panel_init(); - void setFFT_params(bool force=false); - void setChannelWidgetIndex(int chnIdx); - - void init_channel_settings(); - void editMathChannelFunction(int id, const std::string &new_function); - - std::vector> dc_cancel; - std::vector > xy_channels; - std::vector > fft_channels; - int index_x, index_y; - bool locked; - std::shared_ptr ftc; - std::vector fft_blocks; - std::vector ctm_blocks; - - void cancelZoom(); - - void configureAcCoupling(int, bool); - void activateAcCoupling(int); - void deactivateAcCoupling(int); - void activateAcCouplingTrigger(int); - void deactivateAcCouplingTrigger(); - void clearMathChannels(); - void add_ref_waveform(unsigned int chIdx); - void init_selected_measurements(int, std::vector); - void init_buffer_scrolling(); - bool gainUpdateNeeded(); - int binSearchPointOnXaxis(double time); - void scaleHistogramPlot(bool newData = false); - void toggleMiniHistogramPlotVisible(bool enabled); - void resetHistogramDataPoints(); - bool isIioManagerStarted() const; - void updateXyPlotScales(); - void setSampleRate(double sample_rate); - double getSampleRate(); - - logic::LogicAnalyzer *m_logicAnalyzer; - bool m_mixedSignalViewEnabled; - gr::m2k::digital_in_source::sptr logic_source; - gr::top_block_sptr logic_top_block; - logic_analyzer_sink::sptr logic_sink; - gr::blocks::short_to_float::sptr s2f; - gr::blocks::add_ff::sptr add; - gr::blocks::null_sink::sptr nullSink; - std::vector m_mixedSignalViewMenu; - - gr::m2k::mixed_signal_source::sptr mixed_source; - mixed_signal_sink::sptr mixed_sink; - QMetaObject::Connection showLogicAnalyzerTriggerConnection; - - QThreadPool hwSettingsThreadPool; - #define runInHwThreadPool(x) QtConcurrent::run(&hwSettingsThreadPool, std::bind([=]() { x; } )) - - }; -} +class Oscilloscope_API; +class Channel_API; +class MeasureSettings; +class StateUpdater; +class signal_sample; + +class Oscilloscope : public M2kTool +{ + friend class Oscilloscope_API; + friend class Channel_API; + friend class Channel_Digital_Filter_API; + friend class ToolLauncher_API; + + Q_OBJECT + +public: + explicit Oscilloscope(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, m2k_iio_manager *m2k_man, + QJSEngine *engine, QWidget *parent = 0); + ~Oscilloscope(); + + QPushButton *getRunButton(); + void settingsLoaded(); + + bool getTrigger_input() const; + void setTrigger_input(bool value); + + void add_ref_waveform(QString name, QVector xData, QVector yData, unsigned int sampleRate); + void remove_ref_waveform(QString name); + void setNativeDialogs(bool nativeDialogs) override; + + void setLogicAnalyzer(logic::LogicAnalyzer *la); + +Q_SIGNALS: + void triggerALevelChanged(double); + void triggerBLevelChanged(double); + void triggerPositionChanged(double); + void selectedChannelChanged(int); + void activateExportButton(); + void startRunning(bool); + void importFileLoaded(bool); + void showTool(); + +private Q_SLOTS: + void btnExport_clicked(); + + void on_actionClose_triggered(); + void on_boxCursors_toggled(bool on); + void on_boxMeasure_toggled(bool on); + + void onFFT_view_toggled(bool visible); + void onHistogram_view_toggled(bool visible); + void onXY_view_toggled(bool visible); + + void on_btnAddMath_toggled(bool); + void on_btnCursors_toggled(bool); + void on_btnMeasure_toggled(bool); + void on_btnTrigger_toggled(bool); + void on_btnGeneralSettings_toggled(bool); + + void onTriggerSourceChanged(int); + void onTimeTriggerDelayChanged(double); + void onTriggerLevelChanged(double); + void onTriggerModeChanged(int); + + void onVertScaleValueChanged(double value); + void onHorizScaleValueChanged(double value); + void onVertOffsetValueChanged(double value); + void onTimePositionChanged(double value); + + void onChannelCouplingChanged(bool en); + void onChannelOffsetChanged(unsigned int chnIdx, double value); + void xyLineThickness_currentIndexChanged(int idx); + + void onChannelWidgetEnabled(bool); + void onChannelWidgetSelected(bool); + void onChannelWidgetMenuToggled(bool); + void onChannelWidgetDeleteClicked(); + + void rightMenuFinished(bool opened); + + void toggle_blockchain_flow(bool); + void runStopToggled(bool); + void periodicFlowRestart(bool force = false); + void autosetNextStep(); + void autosetFinalStep(); + void autosetFindPeaks(); + bool autosetFindFrequency(); + void setupAutosetFreqSweep(); + void singleCaptureDone(); + + void onMeasuremetsAvailable(); + + void onMeasurementActivated(int id, int chnIdx); + void onMeasurementDeactivated(int id, int chnIdx); + void onMeasurementSelectionListChanged(); + + void onStatisticActivated(int id, int chnIdx); + void onStatisticDeactivated(int id, int chnIdx); + void onStatisticSelectionListChanged(); + void onStatisticsEnabled(bool on); + void onStatisticsReset(); + void onGatingEnabled(bool on); + void onLeftGateChanged(double); + void onRightGateChanged(double); + + void onCursorReadoutsChanged(struct cursorReadoutsText); + + void onIioDataRefillTimeout(); + void onPlotNewData(); + + void on_btnSettings_clicked(bool checked); + void channelLineWidthChanged(int id); + + void update_chn_settings_panel(int id); + + void updateGainMode(); + void setGainMode(uint chnIdx, libm2k::analog::M2K_RANGE gain_mode); + void setChannelHwOffset(uint chnIdx, double offset); + + void xyPlotLineType_toggled(bool checked); + void setup_xy_channels(); + + void openEditMathPanel(bool on); + + void updateTriggerLevelValue(std::vector value); + void configureAcCouplingTrigger(bool); + + void readPreferences(); + + void onCmbMemoryDepthChanged(QString); + void setSinksDisplayOneBuffer(bool); + void cleanBuffersAllSinks(); + void resetStreamingFlag(bool); + void onFilledScreen(bool, unsigned int); + + void toggleCursorsMode(bool toggled); + void toolDetached(bool); + void setFilteringEnabled(bool set); + + void enableMixedSignalView(ChannelWidget *cw); + void disableMixedSignalView(); + void setDigitalPlotCurvesParams(); + + void selectChannel(int index, bool checked); +public Q_SLOTS: + void requestAutoset(); + void enableLabels(bool); + void import(); + void run() override; + void stop() override; + +private: + libm2k::context::M2k *m_m2k_context; + libm2k::analog::M2kAnalogIn *m_m2k_analogin; + libm2k::digital::M2kDigital *m_m2k_digital; + bool m_filtering_enabled; + + unsigned int nb_channels, nb_math_channels; + unsigned int nb_ref_channels; + double active_sample_rate; + double noZoomXAxisWidth; + unsigned long active_sample_count; + unsigned long active_plot_sample_count; + long long active_trig_sample_count; + double active_time_pos; + double memory_adjusted_time_pos; + double last_set_time_pos; + unsigned long last_set_sample_count; + int zoom_level; + bool plot_samples_sequentially, d_displayOneBuffer, d_shouldResetStreaming; + double horiz_offset; + bool reset_horiz_offset; + double time_trigger_offset; + int min_detached_width; + bool miniHistogram; + + int autosetMaxIndexAmpl; + int autosetFFTIndex; + double autosetFrequency; + double autosetMaxAmpl; + double autosetMinAmpl; + int autosetSampleRateCnt; + int autosetChannel; + bool autosetEnabled; + const int autosetSkippedTimeSamples = 4096; + const int autosetFFTSize = 8192; + const int autosetNrOfSkippedTones = 50; + const int autosetValidTone = 51; + + Ui::Oscilloscope *ui; + Ui::OscGeneralSettings *gsettings_ui; + Ui::ChannelSettings *ch_ui; + scopy::m2k::TriggerSettings trigger_settings; + scopy::m2k::MeasureSettings *measure_settings; + CapturePlot plot; + FftDisplayPlot fft_plot; + ConstellationDisplayPlot xy_plot; + HistogramDisplayPlot hist_plot; + Ui::MeasurementsPanel *measure_panel_ui; + QWidget *measurePanel; + Ui::CursorReadouts *cursor_readouts_ui; + QWidget *cursorReadouts; + Ui::StatisticsPanel *statistics_panel_ui; + Ui::CursorsSettings *cr_ui; + QWidget *statisticsPanel; + AnalogBufferPreviewer *buffer_previewer; + ExportSettings *exportSettings; + CustomPlotPositionButton *cursorsPositionButton; + + QGridLayout *gridPlot; + QDockWidget *fftDockWidget; + QDockWidget *xyDockWidget; + QDockWidget *histDockWidget; + QWidget *histWidget; + + MouseWheelWidgetGuard *wheelEventGuard; + + QPair *math_pair; + bool addChannel; + QTabWidget *tabWidget; + QWidget *ref; + + QVector> import_data; + QString import_error; + ImportSettings *importSettings; + bool lastFunctionValid; + + QMap exportConfig; + + std::shared_ptr symmBufferMode; + + scopy::scope_sink_f::sptr qt_time_block; + scopy::scope_sink_f::sptr qt_fft_block; + scopy::xy_sink_c::sptr qt_xy_block; + scopy::histogram_sink_f::sptr qt_hist_block; + std::shared_ptr iio; + gr::basic_block_sptr adc_samp_conv_block; + + QMap> math_sinks; + QMap> math_rails; + std::vector> math_probe_atten; + + iio_manager::port_id *ids; + iio_manager::port_id *hist_ids; + iio_manager::port_id *autoset_id; + + ScaleSpinButton *timeBase; + PositionSpinButton *timePosition; + ScaleSpinButton *voltsPerDiv; + PositionSpinButton *voltsPosition; + + ScaleSpinButton *refChannelTimeBase; + + bool fft_is_visible, hist_is_visible, xy_is_visible, autosetRequested; + bool statistics_enabled; + QList high_gain_modes; + std::vector channel_offset; + + bool hCursorsEnabled; + bool vCursorsEnabled; + bool gatingEnabled; + + std::vector chnAcCoupled; + bool triggerAcCoupled; + QPair, int> triggerLevelSink; + std::shared_ptr keep_one; + std::shared_ptr autosetFFTSink; + + bool trigger_is_forced; + bool new_data_is_triggered; + bool trigger_input; + CapturePlot::TriggerState trigger_state; + StateUpdater *triggerUpdater; + + int fft_size; + int autoset_fft_size; + int fft_plot_size; + + NumberSeries voltsPerDivList; + NumberSeries secPerDivList; + + MetricPrefixFormatter vertMeasureFormat; + TimePrefixFormatter horizMeasureFormat; + + int current_channel; + int current_ch_widget; + unsigned int math_chn_counter; + + QButtonGroup *channels_group; // selected state of each channel + + QPushButton *menuRunButton; + + QList channels_api; + + QList> measurements_data; + QList> measurements_gui; + + QList, M2kStatistic>> statistics_data; + + QList menuOrder; + + QQueue> menuButtonActions; + + QVector probe_attenuation; + + void writeAllSettingsToHardware(); + + void comboBoxUpdateToValue(QComboBox *box, double value, std::vector list); + + void settings_panel_update(int id); + void settings_panel_size_adjust(); + void triggerRightMenuToggle(CustomPushButton *, bool checked); + void toggleRightMenu(CustomPushButton *, bool checked); + void create_add_channel_panel(); + void add_math_channel(const std::string &function); + unsigned int find_curve_number(); + ChannelWidget *channelWidgetAtId(int id); + void update_measure_for_channel(int ch_idx); + QString getChannelRangeStringVDivHelper(int ch); + void setAllSinksSampleCount(unsigned long sample_count); + void autosetFFT(); + + void updateRunButton(bool ch_enabled); + + void fillCursorReadouts(const struct cursorReadoutsText &); + + void measure_panel_init(); + void measure_settings_init(); + void measureLabelsRearrange(); + void measureUpdateValues(); + void measureCreateAndAppendGuiFrom(const M2kMeasurementData &); + + void statistics_panel_init(); + void statisticsUpdateValues(); + void statisticsReset(); + void statisticsUpdateGui(); + void statisticsUpdateGuiTitleColor(); + void statisticsUpdateGuiPosIndex(); + + void updateBufferPreviewer(); + void export_settings_init(); + void pause(bool paused); + void cursor_panel_init(); + void setFFT_params(bool force = false); + void setChannelWidgetIndex(int chnIdx); + + void init_channel_settings(); + void editMathChannelFunction(int id, const std::string &new_function); + + std::vector> dc_cancel; + std::vector> xy_channels; + std::vector> fft_channels; + int index_x, index_y; + bool locked; + std::shared_ptr ftc; + std::vector fft_blocks; + std::vector ctm_blocks; + + void cancelZoom(); + + void configureAcCoupling(int, bool); + void activateAcCoupling(int); + void deactivateAcCoupling(int); + void activateAcCouplingTrigger(int); + void deactivateAcCouplingTrigger(); + void clearMathChannels(); + void add_ref_waveform(unsigned int chIdx); + void init_selected_measurements(int, std::vector); + void init_buffer_scrolling(); + bool gainUpdateNeeded(); + int binSearchPointOnXaxis(double time); + void scaleHistogramPlot(bool newData = false); + void toggleMiniHistogramPlotVisible(bool enabled); + void resetHistogramDataPoints(); + bool isIioManagerStarted() const; + void updateXyPlotScales(); + void setSampleRate(double sample_rate); + double getSampleRate(); + + logic::LogicAnalyzer *m_logicAnalyzer; + bool m_mixedSignalViewEnabled; + gr::m2k::digital_in_source::sptr logic_source; + gr::top_block_sptr logic_top_block; + logic_analyzer_sink::sptr logic_sink; + gr::blocks::short_to_float::sptr s2f; + gr::blocks::add_ff::sptr add; + gr::blocks::null_sink::sptr nullSink; + std::vector m_mixedSignalViewMenu; + + gr::m2k::mixed_signal_source::sptr mixed_source; + mixed_signal_sink::sptr mixed_sink; + QMetaObject::Connection showLogicAnalyzerTriggerConnection; + + QThreadPool hwSettingsThreadPool; +#define runInHwThreadPool(x) QtConcurrent::run(&hwSettingsThreadPool, std::bind([=]() { x; })) +}; +} // namespace scopy::m2k #endif /* M2K_OSCILLOSCOPE_H */ diff --git a/plugins/m2k/src/old/oscilloscope_api.cpp b/plugins/m2k/src/old/oscilloscope_api.cpp index b5976145af..b7ddf01ac5 100644 --- a/plugins/m2k/src/old/oscilloscope_api.cpp +++ b/plugins/m2k/src/old/oscilloscope_api.cpp @@ -19,204 +19,100 @@ */ #include "oscilloscope_api.hpp" -#include "ui_oscilloscope.h" -#include "measure_settings.h" -#include "ui_measure_settings.h" -#include "ui_cursors_settings.h" -#include "ui_trigger_settings.h" #include "gui/channel_widget.hpp" +#include "measure_settings.h" + #include "ui_channel_settings.h" +#include "ui_cursors_settings.h" +#include "ui_measure_settings.h" #include "ui_osc_general_settings.h" +#include "ui_oscilloscope.h" +#include "ui_trigger_settings.h" using namespace scopy; -namespace scopy::m2k -{ +namespace scopy::m2k { /* * class Oscilloscope_API */ -bool Oscilloscope_API::hasCursors() const -{ - return osc->ui->boxCursors->isChecked(); -} - -void Oscilloscope_API::setCursors(bool en) -{ - osc->ui->boxCursors->setChecked(en); -} +bool Oscilloscope_API::hasCursors() const { return osc->ui->boxCursors->isChecked(); } -bool Oscilloscope_API::autosetEnabled() const -{ - return osc->autosetEnabled; -} -void Oscilloscope_API::enableAutoset(bool en) -{ - osc->autosetEnabled=en; -} +void Oscilloscope_API::setCursors(bool en) { osc->ui->boxCursors->setChecked(en); } -bool Oscilloscope_API::hasMeasure() const -{ - return osc->ui->boxMeasure->isChecked(); -} +bool Oscilloscope_API::autosetEnabled() const { return osc->autosetEnabled; } +void Oscilloscope_API::enableAutoset(bool en) { osc->autosetEnabled = en; } -void Oscilloscope_API::setMeasure(bool en) -{ - osc->ui->boxMeasure->setChecked(en); -} +bool Oscilloscope_API::hasMeasure() const { return osc->ui->boxMeasure->isChecked(); } -bool Oscilloscope_API::measureAll() const -{ - return osc->measure_settings->m_ui->button_measDisplayAll->isChecked(); -} +void Oscilloscope_API::setMeasure(bool en) { osc->ui->boxMeasure->setChecked(en); } -void Oscilloscope_API::setMeasureAll(bool en) -{ - osc->measure_settings->m_ui->button_measDisplayAll->setChecked(en); -} +bool Oscilloscope_API::measureAll() const { return osc->measure_settings->m_ui->button_measDisplayAll->isChecked(); } -bool Oscilloscope_API::hasCounter() const -{ - return osc->measure_settings->m_ui->button_Counter->isChecked(); -} +void Oscilloscope_API::setMeasureAll(bool en) { osc->measure_settings->m_ui->button_measDisplayAll->setChecked(en); } -void Oscilloscope_API::setCounter(bool en) -{ - osc->measure_settings->m_ui->button_Counter->setChecked(en); -} +bool Oscilloscope_API::hasCounter() const { return osc->measure_settings->m_ui->button_Counter->isChecked(); } -bool Oscilloscope_API::hasStatistics() const -{ - return osc->measure_settings->m_ui->button_StatisticsEn->isChecked(); -} +void Oscilloscope_API::setCounter(bool en) { osc->measure_settings->m_ui->button_Counter->setChecked(en); } -void Oscilloscope_API::setStatistics(bool en) -{ - osc->measure_settings->m_ui->button_StatisticsEn->setChecked(en); -} +bool Oscilloscope_API::hasStatistics() const { return osc->measure_settings->m_ui->button_StatisticsEn->isChecked(); } -bool Oscilloscope_API::horizontalCursors() const -{ - return osc->cr_ui->hCursorsEnable->isChecked(); -} +void Oscilloscope_API::setStatistics(bool en) { osc->measure_settings->m_ui->button_StatisticsEn->setChecked(en); } -void Oscilloscope_API::setHorizontalCursors(bool en) -{ - osc->cr_ui->hCursorsEnable->setChecked(en); -} +bool Oscilloscope_API::horizontalCursors() const { return osc->cr_ui->hCursorsEnable->isChecked(); } -bool Oscilloscope_API::verticalCursors() const -{ - return osc->cr_ui->vCursorsEnable->isChecked(); -} +void Oscilloscope_API::setHorizontalCursors(bool en) { osc->cr_ui->hCursorsEnable->setChecked(en); } -void Oscilloscope_API::setVerticalCursors(bool en) -{ - osc->cr_ui->vCursorsEnable->setChecked(en); -} +bool Oscilloscope_API::verticalCursors() const { return osc->cr_ui->vCursorsEnable->isChecked(); } -double Oscilloscope_API::cursorV1() const -{ - return osc->plot.getVBar1()->getPosition(); -} +void Oscilloscope_API::setVerticalCursors(bool en) { osc->cr_ui->vCursorsEnable->setChecked(en); } -double Oscilloscope_API::cursorV2() const -{ - return osc->plot.getVBar2()->getPosition(); -} +double Oscilloscope_API::cursorV1() const { return osc->plot.getVBar1()->getPosition(); } -double Oscilloscope_API::cursorH1() const -{ - return osc->plot.getHBar1()->getPosition(); -} +double Oscilloscope_API::cursorV2() const { return osc->plot.getVBar2()->getPosition(); } -double Oscilloscope_API::cursorH2() const -{ - return osc->plot.getHBar2()->getPosition(); -} +double Oscilloscope_API::cursorH1() const { return osc->plot.getHBar1()->getPosition(); } -void Oscilloscope_API::setCursorV1(double val) -{ - osc->plot.getVBar1()->setPosition(val); -} +double Oscilloscope_API::cursorH2() const { return osc->plot.getHBar2()->getPosition(); } -void Oscilloscope_API::setCursorV2(double val) -{ - osc->plot.getVBar2()->setPosition(val); -} +void Oscilloscope_API::setCursorV1(double val) { osc->plot.getVBar1()->setPosition(val); } -void Oscilloscope_API::setCursorH1(double val) -{ - osc->plot.getHBar1()->setPosition(val); -} +void Oscilloscope_API::setCursorV2(double val) { osc->plot.getVBar2()->setPosition(val); } -void Oscilloscope_API::setCursorH2(double val) -{ - osc->plot.getHBar1()->setPosition(val); -} +void Oscilloscope_API::setCursorH1(double val) { osc->plot.getHBar1()->setPosition(val); } -bool Oscilloscope_API::autoTrigger() const -{ - return osc->trigger_settings.ui->btnTrigger->isChecked(); -} +void Oscilloscope_API::setCursorH2(double val) { osc->plot.getHBar1()->setPosition(val); } -void Oscilloscope_API::setAutoTrigger(bool en) -{ - osc->trigger_settings.ui->btnTrigger->setChecked(en); -} +bool Oscilloscope_API::autoTrigger() const { return osc->trigger_settings.ui->btnTrigger->isChecked(); } -bool Oscilloscope_API::internalTrigger() const -{ - return osc->trigger_settings.ui->intern_en->isChecked(); -} +void Oscilloscope_API::setAutoTrigger(bool en) { osc->trigger_settings.ui->btnTrigger->setChecked(en); } -void Oscilloscope_API::setInternalTrigger(bool en) -{ - osc->trigger_settings.ui->intern_en->setChecked(en); -} +bool Oscilloscope_API::internalTrigger() const { return osc->trigger_settings.ui->intern_en->isChecked(); } -bool Oscilloscope_API::externalTrigger() const -{ - return osc->trigger_settings.ui->extern_en->isChecked(); -} +void Oscilloscope_API::setInternalTrigger(bool en) { osc->trigger_settings.ui->intern_en->setChecked(en); } -void Oscilloscope_API::setExternalTrigger(bool en) -{ - osc->trigger_settings.ui->extern_en->setChecked(en); -} +bool Oscilloscope_API::externalTrigger() const { return osc->trigger_settings.ui->extern_en->isChecked(); } +void Oscilloscope_API::setExternalTrigger(bool en) { osc->trigger_settings.ui->extern_en->setChecked(en); } -int Oscilloscope_API::externalTriggerSource() const -{ - return osc->trigger_settings.ui->cmb_extern_src->currentIndex(); -} +int Oscilloscope_API::externalTriggerSource() const { return osc->trigger_settings.ui->cmb_extern_src->currentIndex(); } void Oscilloscope_API::setExternalTriggerSource(int src) { - if (src >= 0 && src < osc->trigger_settings.ui->cmb_extern_src->count()) { + if(src >= 0 && src < osc->trigger_settings.ui->cmb_extern_src->count()) { osc->trigger_settings.ui->cmb_extern_src->setCurrentIndex(src); } else { osc->trigger_settings.ui->cmb_extern_src->setCurrentIndex(0); } - } -int Oscilloscope_API::externalTriggerDaisyOrder() const -{ - return osc->trigger_settings.ui->spin_daisyChain->value(); -} +int Oscilloscope_API::externalTriggerDaisyOrder() const { return osc->trigger_settings.ui->spin_daisyChain->value(); } void Oscilloscope_API::setExternalTriggerDaisyOrder(int src) { osc->trigger_settings.ui->spin_daisyChain->setValue(src); } -bool Oscilloscope_API::externalTriggerOut() const -{ - return osc->trigger_settings.ui->extern_to_en->isChecked(); -} -void Oscilloscope_API::setExternalTriggerOut(bool en) -{ - osc->trigger_settings.ui->extern_to_en->setChecked(en); -} +bool Oscilloscope_API::externalTriggerOut() const { return osc->trigger_settings.ui->extern_to_en->isChecked(); } +void Oscilloscope_API::setExternalTriggerOut(bool en) { osc->trigger_settings.ui->extern_to_en->setChecked(en); } int Oscilloscope_API::externalTriggerOutSource() const { @@ -224,17 +120,14 @@ int Oscilloscope_API::externalTriggerOutSource() const } void Oscilloscope_API::setExternalTriggerOutSource(int src) { - if (src >= 0 && src < osc->trigger_settings.ui->cmb_extern_to_src->count()) { + if(src >= 0 && src < osc->trigger_settings.ui->cmb_extern_to_src->count()) { osc->trigger_settings.ui->cmb_extern_to_src->setCurrentIndex(src); } else { osc->trigger_settings.ui->cmb_extern_to_src->setCurrentIndex(0); } } -int Oscilloscope_API::triggerSource() const -{ - return osc->trigger_settings.ui->cmb_source->currentIndex(); -} +int Oscilloscope_API::triggerSource() const { return osc->trigger_settings.ui->cmb_source->currentIndex(); } void Oscilloscope_API::setTriggerSource(int idx) { @@ -242,34 +135,19 @@ void Oscilloscope_API::setTriggerSource(int idx) osc->trigger_settings.ui->cmb_source->setCurrentIndex(idx); } -double Oscilloscope_API::getTriggerLevel() const -{ - return osc->trigger_settings.trigger_level->value(); -} +double Oscilloscope_API::getTriggerLevel() const { return osc->trigger_settings.trigger_level->value(); } -void Oscilloscope_API::setTriggerLevel(double level) -{ - osc->trigger_settings.trigger_level->setValue(level); -} +void Oscilloscope_API::setTriggerLevel(double level) { osc->trigger_settings.trigger_level->setValue(level); } -double Oscilloscope_API::getTriggerHysteresis() const -{ - return osc->trigger_settings.trigger_hysteresis->value(); -} +double Oscilloscope_API::getTriggerHysteresis() const { return osc->trigger_settings.trigger_hysteresis->value(); } -void Oscilloscope_API::setTriggerHysteresis(double hyst) -{ - osc->trigger_settings.trigger_hysteresis->setValue(hyst); -} +void Oscilloscope_API::setTriggerHysteresis(double hyst) { osc->trigger_settings.trigger_hysteresis->setValue(hyst); } -int Oscilloscope_API::internalCondition() const -{ - return osc->trigger_settings.ui->cmb_condition->currentIndex(); -} +int Oscilloscope_API::internalCondition() const { return osc->trigger_settings.ui->cmb_condition->currentIndex(); } void Oscilloscope_API::setInternalCondition(int cond) { - if (cond >= osc->trigger_settings.ui->cmb_condition->count()) { + if(cond >= osc->trigger_settings.ui->cmb_condition->count()) { cond = osc->trigger_settings.ui->cmb_condition->count() - 1; } osc->trigger_settings.ui->cmb_condition->setCurrentIndex(cond); @@ -280,28 +158,19 @@ int Oscilloscope_API::externalCondition() const return osc->trigger_settings.ui->cmb_extern_condition->currentIndex(); } -bool Oscilloscope_API::getTriggerInput() const -{ - return osc->getTrigger_input(); -} +bool Oscilloscope_API::getTriggerInput() const { return osc->getTrigger_input(); } -void Oscilloscope_API::setTriggerInput(bool en) -{ - osc->setTrigger_input(en); -} +void Oscilloscope_API::setTriggerInput(bool en) { osc->setTrigger_input(en); } void Oscilloscope_API::setExternalCondition(int cond) { - if (cond >= osc->trigger_settings.ui->cmb_extern_condition->count()) { + if(cond >= osc->trigger_settings.ui->cmb_extern_condition->count()) { cond = osc->trigger_settings.ui->cmb_extern_condition->count() - 1; } osc->trigger_settings.ui->cmb_extern_condition->setCurrentIndex(cond); } -int Oscilloscope_API::internExtern() const -{ - return osc->trigger_settings.ui->cmb_analog_extern->currentIndex(); -} +int Oscilloscope_API::internExtern() const { return osc->trigger_settings.ui->cmb_analog_extern->currentIndex(); } void Oscilloscope_API::setInternExtern(int option) { @@ -312,12 +181,11 @@ QList Oscilloscope_API::getMathChannels() const { QList list; - for (unsigned int i = 0; i < osc->nb_math_channels + osc->nb_ref_channels; i++) { - QWidget *obj = osc->ui->channelsList->itemAt( - osc->nb_channels + i)->widget(); + for(unsigned int i = 0; i < osc->nb_math_channels + osc->nb_ref_channels; i++) { + QWidget *obj = osc->ui->channelsList->itemAt(osc->nb_channels + i)->widget(); ChannelWidget *cw = static_cast(obj); - if (cw->isMathChannel()) { + if(cw->isMathChannel()) { list.append(obj->property("function").toString()); } } @@ -325,32 +193,20 @@ QList Oscilloscope_API::getMathChannels() const return list; } -void Oscilloscope_API::setMathChannels(const QList& list) +void Oscilloscope_API::setMathChannels(const QList &list) { osc->clearMathChannels(); - for (unsigned int i = 0; i < list.size(); i++) + for(unsigned int i = 0; i < list.size(); i++) osc->add_math_channel(list.at(i).toStdString()); } -double Oscilloscope_API::getTimePos() const -{ - return osc->timePosition->value(); -} +double Oscilloscope_API::getTimePos() const { return osc->timePosition->value(); } -void Oscilloscope_API::setTimePos(double value) -{ - osc->timePosition->setValue(value); -} +void Oscilloscope_API::setTimePos(double value) { osc->timePosition->setValue(value); } -double Oscilloscope_API::getTimeBase() const -{ - return osc->timeBase->value(); -} +double Oscilloscope_API::getTimeBase() const { return osc->timeBase->value(); } -void Oscilloscope_API::setTimeBase(double value) -{ - osc->timeBase->setValue(value); -} +void Oscilloscope_API::setTimeBase(double value) { osc->timeBase->setValue(value); } void Oscilloscope_API::setMemoryDepth(int val) { @@ -358,15 +214,15 @@ void Oscilloscope_API::setMemoryDepth(int val) unsigned long buffersize = 0; int i = 0; QString currentText; - for (i = 0; i < osc->ch_ui->cmbMemoryDepth->count(); i++) { + for(i = 0; i < osc->ch_ui->cmbMemoryDepth->count(); i++) { ok = false; currentText = osc->ch_ui->cmbMemoryDepth->itemText(i); buffersize = currentText.toInt(&ok); - if (ok && (val == buffersize)) { + if(ok && (val == buffersize)) { break; } } - if (i >= osc->ch_ui->cmbMemoryDepth->count()) { + if(i >= osc->ch_ui->cmbMemoryDepth->count()) { i = 0; } osc->ch_ui->cmbMemoryDepth->setCurrentIndex(i); @@ -380,34 +236,19 @@ int Oscilloscope_API::getMemoryDepth() return bufferSize; } -QString Oscilloscope_API::getNotes() -{ - return osc->ui->instrumentNotes->getNotes(); -} -void Oscilloscope_API::setNotes(QString str) -{ - osc->ui->instrumentNotes->setNotes(str); -} +QString Oscilloscope_API::getNotes() { return osc->ui->instrumentNotes->getNotes(); } +void Oscilloscope_API::setNotes(QString str) { osc->ui->instrumentNotes->setNotes(str); } -void Oscilloscope_API::show() -{ - Q_EMIT osc->showTool(); -} +void Oscilloscope_API::show() { Q_EMIT osc->showTool(); } bool Oscilloscope_API::running() const { return osc->ui->runSingleWidget->runButtonChecked() || osc->ui->runSingleWidget->singleButtonChecked(); } -void Oscilloscope_API::run(bool en) -{ - osc->ui->runSingleWidget->toggle(en); -} +void Oscilloscope_API::run(bool en) { osc->ui->runSingleWidget->toggle(en); } -bool Oscilloscope_API::isSingle() const -{ - return osc->ui->runSingleWidget->singleButtonChecked(); -} +bool Oscilloscope_API::isSingle() const { return osc->ui->runSingleWidget->singleButtonChecked(); } void Oscilloscope_API::single(bool en) { if(!osc->ui->runSingleWidget->singleButtonChecked()) @@ -418,15 +259,15 @@ QList Oscilloscope_API::measureEn() const { QList list; - for (unsigned int i = 0; i < osc->nb_channels; i++) { + for(unsigned int i = 0; i < osc->nb_channels; i++) { auto measurements = osc->plot.measurements(i); int mask = 0; - if (measurements.size() > (sizeof(int) * 8)) + if(measurements.size() > (sizeof(int) * 8)) throw std::runtime_error("Too many measurements"); - for (unsigned int j = 0; j < measurements.size(); j++) { - if (measurements[j]->enabled()) + for(unsigned int j = 0; j < measurements.size(); j++) { + if(measurements[j]->enabled()) mask |= 1 << j; } @@ -436,24 +277,23 @@ QList Oscilloscope_API::measureEn() const return list; } -void Oscilloscope_API::setMeasureEn(const QList& list) +void Oscilloscope_API::setMeasureEn(const QList &list) { - if (list.size() != osc->nb_channels) + if(list.size() != osc->nb_channels) return; osc->measure_settings->m_selectedMeasurements.clear(); - for (unsigned int i = 0; i < osc->nb_channels; i++) { + for(unsigned int i = 0; i < osc->nb_channels; i++) { auto measurements = osc->plot.measurements(i); int mask = list.at(i); - if (measurements.size() > (sizeof(int) * 8)) + if(measurements.size() > (sizeof(int) * 8)) throw std::runtime_error("Too many measurements"); - for (unsigned int j = 0; j < measurements.size(); j++) { + for(unsigned int j = 0; j < measurements.size(); j++) { measurements[j]->setEnabled(!!(mask & (1 << j))); - osc->measure_settings->onMeasurementActivated( - i, j, !!(mask & (1 << j))); + osc->measure_settings->onMeasurementActivated(i, j, !!(mask & (1 << j))); } } @@ -466,115 +306,84 @@ QList Oscilloscope_API::statisticEn() const QList list; auto statistics = osc->measure_settings->statisticSelection(); - for (size_t i = 0; i < osc->nb_channels; i++) { + for(size_t i = 0; i < osc->nb_channels; i++) { int mask = 0; list.append(mask); } - for (unsigned int i = 0; i < statistics.size(); i++) + for(unsigned int i = 0; i < statistics.size(); i++) list[statistics[i].channel_id()] |= 1 << statistics[i].id(); return list; } -void Oscilloscope_API::setStatisticEn(const QList& list) +void Oscilloscope_API::setStatisticEn(const QList &list) { - if (list.size() != osc->nb_channels) + if(list.size() != osc->nb_channels) return; osc->measure_settings->deleteAllStatistics(); - for (unsigned int i = 0; i < osc->nb_channels; i++) { + for(unsigned int i = 0; i < osc->nb_channels; i++) { auto measurements = osc->plot.measurements(i); int mask = list.at(i); - if (measurements.size() > (sizeof(int) * 8)) + if(measurements.size() > (sizeof(int) * 8)) throw std::runtime_error("Too many measurements"); - for (unsigned int j = 0; j < measurements.size(); j++) { - if (!!(mask & (1 << j))) + for(unsigned int j = 0; j < measurements.size(); j++) { + if(!!(mask & (1 << j))) osc->measure_settings->addStatistic(j, i); } } - osc->measure_settings->loadStatisticStatesForChannel( - osc->current_channel); + osc->measure_settings->loadStatisticStatesForChannel(osc->current_channel); osc->onStatisticSelectionListChanged(); } -int Oscilloscope_API::getCurrentChannel() const -{ - return osc->current_channel; -} +int Oscilloscope_API::getCurrentChannel() const { return osc->current_channel; } void Oscilloscope_API::setCurrentChannel(int chn_id) { ChannelWidget *chn_widget = osc->channelWidgetAtId(chn_id); - if (!chn_widget) + if(!chn_widget) return; - if (chn_widget->enableButton()->isChecked()) { + if(chn_widget->enableButton()->isChecked()) { osc->setChannelWidgetIndex(chn_id); chn_widget->nameButton()->setChecked(true); chn_widget->menuButton()->setChecked(true); } } -int Oscilloscope_API::getXyThickness() const -{ - return osc->xy_plot.getLineWidth(0); -} +int Oscilloscope_API::getXyThickness() const { return osc->xy_plot.getLineWidth(0); } void Oscilloscope_API::setXyThickness(int val) { osc->gsettings_ui->xyLineThickness->setCurrentIndex(val); - osc->xy_plot.setLineWidth(0,val); + osc->xy_plot.setLineWidth(0, val); } -bool Oscilloscope_API::getFftEn() const -{ - return osc->fft_is_visible; -} +bool Oscilloscope_API::getFftEn() const { return osc->fft_is_visible; } -void Oscilloscope_API::setFftEn(bool en) -{ - osc->gsettings_ui->FFT_view->setChecked(en); -} +void Oscilloscope_API::setFftEn(bool en) { osc->gsettings_ui->FFT_view->setChecked(en); } -bool Oscilloscope_API::getXyEn() const -{ - return osc->xy_is_visible; -} +bool Oscilloscope_API::getXyEn() const { return osc->xy_is_visible; } -void Oscilloscope_API::setXyEn(bool en) -{ - osc->gsettings_ui->XY_view->setChecked(en); -} +void Oscilloscope_API::setXyEn(bool en) { osc->gsettings_ui->XY_view->setChecked(en); } -bool Oscilloscope_API::getHistEn() const -{ - return osc->hist_is_visible; -} +bool Oscilloscope_API::getHistEn() const { return osc->hist_is_visible; } -void Oscilloscope_API::setHistEn(bool en) -{ - osc->gsettings_ui->Histogram_view->setChecked(en); -} +void Oscilloscope_API::setHistEn(bool en) { osc->gsettings_ui->Histogram_view->setChecked(en); } -bool Oscilloscope_API::getExportAll() const -{ - return osc->exportSettings->getExportAllButton()->isChecked(); -} +bool Oscilloscope_API::getExportAll() const { return osc->exportSettings->getExportAllButton()->isChecked(); } -void Oscilloscope_API::setExportAll(bool en) -{ - osc->exportSettings->getExportAllButton()->setChecked(en); -} +void Oscilloscope_API::setExportAll(bool en) { osc->exportSettings->getExportAllButton()->setChecked(en); } int Oscilloscope_API::getCursorsPosition() const { - if (!hasCursors()) { + if(!hasCursors()) { return 0; } auto currentPos = osc->plot.getCursorReadouts()->getCurrentPosition(); - switch (currentPos) { + switch(currentPos) { case CustomPlotPositionButton::ReadoutsPosition::topLeft: default: return 0; @@ -590,22 +399,21 @@ int Oscilloscope_API::getCursorsPosition() const void Oscilloscope_API::setCursorsPosition(int val) { - if (!hasCursors()) { + if(!hasCursors()) { return; } enum CustomPlotPositionButton::ReadoutsPosition types[] = { CustomPlotPositionButton::ReadoutsPosition::topLeft, CustomPlotPositionButton::ReadoutsPosition::topRight, CustomPlotPositionButton::ReadoutsPosition::bottomLeft, - CustomPlotPositionButton::ReadoutsPosition::bottomRight - }; + CustomPlotPositionButton::ReadoutsPosition::bottomRight}; osc->cursorsPositionButton->setPosition(types[val]); osc->plot.replot(); } int Oscilloscope_API::getCursorsTransparency() const { - if (!hasCursors()) { + if(!hasCursors()) { return 0; } return osc->cr_ui->horizontalSlider->value(); @@ -613,47 +421,29 @@ int Oscilloscope_API::getCursorsTransparency() const void Oscilloscope_API::setCursorsTransparency(int val) { - if (!hasCursors()) { + if(!hasCursors()) { return; } osc->cr_ui->horizontalSlider->setValue(val); } -bool Oscilloscope_API::gatingEnabled() const -{ - return osc->measure_settings->m_ui->button_GatingEnable->isChecked(); -} +bool Oscilloscope_API::gatingEnabled() const { return osc->measure_settings->m_ui->button_GatingEnable->isChecked(); } -void Oscilloscope_API::setGatingEnabled(bool en) -{ - osc->measure_settings->m_ui->button_GatingEnable->setChecked(en); -} +void Oscilloscope_API::setGatingEnabled(bool en) { osc->measure_settings->m_ui->button_GatingEnable->setChecked(en); } -double Oscilloscope_API::cursorGateLeft() const -{ - return osc->plot.getMeasurementGateBar1()->getPosition(); -} +double Oscilloscope_API::cursorGateLeft() const { return osc->plot.getMeasurementGateBar1()->getPosition(); } -double Oscilloscope_API::cursorGateRight() const -{ - return osc->plot.getMeasurementGateBar2()->getPosition(); -} +double Oscilloscope_API::cursorGateRight() const { return osc->plot.getMeasurementGateBar2()->getPosition(); } -void Oscilloscope_API::setCursorGateLeft(double val) -{ - osc->plot.getMeasurementGateBar1()->setPosition(val); -} +void Oscilloscope_API::setCursorGateLeft(double val) { osc->plot.getMeasurementGateBar1()->setPosition(val); } -void Oscilloscope_API::setCursorGateRight(double val) -{ - osc->plot.getMeasurementGateBar2()->setPosition(val); -} +void Oscilloscope_API::setCursorGateRight(double val) { osc->plot.getMeasurementGateBar2()->setPosition(val); } QVariantList Oscilloscope_API::getChannels() { QVariantList list; - for (Channel_API *each : qAsConst(osc->channels_api)) { + for(Channel_API *each : qAsConst(osc->channels_api)) { list.append(QVariant::fromValue(each)); } return list; @@ -663,21 +453,19 @@ QVariantList Channel_API::getDigFilters() const { QVariantList list; - for (Channel_Digital_Filter_API *each : digFilters) { + for(Channel_Digital_Filter_API *each : digFilters) { list.append(QVariant::fromValue(each)); } return list; } - - /* * Channel_API */ bool Channel_API::channelEn() const { - int index = osc->channels_api.indexOf(const_cast(this)); + int index = osc->channels_api.indexOf(const_cast(this)); ChannelWidget *w = osc->channelWidgetAtId(index); return w->enableButton()->isChecked(); @@ -693,8 +481,8 @@ void Channel_API::setChannelEn(bool en) double Channel_API::getVoltsPerDiv() const { - int index = osc->channels_api.indexOf(const_cast(this)); - if(index<0) + int index = osc->channels_api.indexOf(const_cast(this)); + if(index < 0) return 1.0; return osc->plot.VertUnitsPerDiv(index); } @@ -703,34 +491,34 @@ void Channel_API::setVoltsPerDiv(double val) { int index = osc->channels_api.indexOf(this); int prevSelectedChannel = osc->current_ch_widget; - if (index == prevSelectedChannel) { + if(index == prevSelectedChannel) { osc->voltsPerDiv->setValue(val); return; } QWidget *obj = osc->ui->channelsList->itemAt(index)->widget(); ChannelWidget *cw = static_cast(obj); - if (cw) { + if(cw) { cw->menuButton()->setChecked(true); - if (osc->voltsPerDiv->value() == val) { + if(osc->voltsPerDiv->value() == val) { osc->onVertScaleValueChanged(val); } else { osc->voltsPerDiv->setValue(val); } } - if (prevSelectedChannel < 0) { + if(prevSelectedChannel < 0) { return; } QWidget *prevObj = osc->ui->channelsList->itemAt(prevSelectedChannel)->widget(); ChannelWidget *prevCw = static_cast(prevObj); - if (prevCw) { + if(prevCw) { prevCw->menuButton()->setChecked(true); } } double Channel_API::getVOffset() const { - int index = osc->channels_api.indexOf(const_cast(this)); + int index = osc->channels_api.indexOf(const_cast(this)); return -osc->plot.VertOffset(index); } @@ -738,35 +526,35 @@ void Channel_API::setVOffset(double val) { int index = osc->channels_api.indexOf(this); int prevSelectedChannel = osc->current_ch_widget; - if (index == prevSelectedChannel) { + if(index == prevSelectedChannel) { osc->voltsPosition->setValue(val); return; } QWidget *obj = osc->ui->channelsList->itemAt(index)->widget(); ChannelWidget *cw = static_cast(obj); - if (cw) { + if(cw) { cw->menuButton()->setChecked(true); - if (osc->voltsPosition->value() == val) { + if(osc->voltsPosition->value() == val) { osc->onVertOffsetValueChanged(val); } else { osc->voltsPosition->setValue(val); } } - if (prevSelectedChannel < 0) { + if(prevSelectedChannel < 0) { return; } QWidget *prevObj = osc->ui->channelsList->itemAt(prevSelectedChannel)->widget(); ChannelWidget *prevCw = static_cast(prevObj); - if (prevCw) { + if(prevCw) { prevCw->menuButton()->setChecked(true); } } double Channel_API::getLineThickness() const { - int index = osc->channels_api.indexOf(const_cast(this)); + int index = osc->channels_api.indexOf(const_cast(this)); return osc->plot.getLineWidthF(index); } @@ -775,15 +563,15 @@ void Channel_API::setLineThickness(double val) { int index = osc->channels_api.indexOf(this); int cmbIdx = (int)(val / 0.5) - 1; - if (cmbIdx > osc->ch_ui->cmbChnLineWidth->count()) { + if(cmbIdx > osc->ch_ui->cmbChnLineWidth->count()) { cmbIdx = osc->ch_ui->cmbChnLineWidth->count() - 1; val = (cmbIdx + 1) * 0.5; } - if (cmbIdx < 0) { + if(cmbIdx < 0) { cmbIdx = 0; val = 0.5; } - if (index == osc->current_ch_widget) { + if(index == osc->current_ch_widget) { osc->ch_ui->cmbChnLineWidth->setCurrentIndex(cmbIdx); } osc->plot.setLineWidthF(index, val); @@ -791,7 +579,7 @@ void Channel_API::setLineThickness(double val) double Channel_API::getProbeAttenuation() const { - int index = osc->channels_api.indexOf(const_cast(this)); + int index = osc->channels_api.indexOf(const_cast(this)); return osc->probe_attenuation[index]; } @@ -799,7 +587,7 @@ double Channel_API::getProbeAttenuation() const void Channel_API::setProbeAttenuation(double val) { int index = osc->channels_api.indexOf(this); - if (index == osc->current_ch_widget) { + if(index == osc->current_ch_widget) { osc->ch_ui->probe_attenuation_value->setText(QString::number(val)); } else { osc->probe_attenuation[index] = val; @@ -808,23 +596,24 @@ void Channel_API::setProbeAttenuation(double val) void Channel_API::setColor(int r, int g, int b, int a) { - int index = osc->channels_api.indexOf(const_cast(this)); + int index = osc->channels_api.indexOf(const_cast(this)); QWidget *obj = osc->ui->channelsList->itemAt(index)->widget(); ChannelWidget *cw = static_cast(obj); QColor color(r, g, b, a); - if (color.isValid()) { + if(color.isValid()) { osc->plot.setLineColor(index, color); osc->plot.getOffsetHandles().at(index)->setRoundRectColor(color); osc->plot.getOffsetHandles().at(index)->setPen(QPen(color, 2, Qt::SolidLine)); - static_cast( - osc->ui->chn_scales->itemAt(index)->widget())->setStyleSheet(QString("QLabel {" + static_cast(osc->ui->chn_scales->itemAt(index)->widget()) + ->setStyleSheet(QString("QLabel {" "color: %1;" "font-weight: bold;" - "}").arg(color.name())); - if (cw) { + "}") + .arg(color.name())); + if(cw) { cw->setColor(osc->plot.getLineColor(index)); } - if (!osc->tme->running()) { + if(!osc->tme->running()) { osc->plot.replot(); } } @@ -832,96 +621,106 @@ void Channel_API::setColor(int r, int g, int b, int a) bool Channel_API::getAcCoupling() const { - int index = osc->channels_api.indexOf(const_cast(this)); + int index = osc->channels_api.indexOf(const_cast(this)); return osc->chnAcCoupled[index]; } void Channel_API::setAcCoupling(bool val) { - int index = osc->channels_api.indexOf(const_cast(this)); + int index = osc->channels_api.indexOf(const_cast(this)); if(index < 0) return; - if (osc->current_channel == index) { + if(osc->current_channel == index) { osc->ch_ui->btnCoupled->setChecked(val); } else { osc->configureAcCoupling(index, val); } } - -bool Channel_Digital_Filter_API::isEnableLow() const { - int channel = osc->channels_api.indexOf(const_cast(ch_api)); +bool Channel_Digital_Filter_API::isEnableLow() const +{ + int channel = osc->channels_api.indexOf(const_cast(ch_api)); return osc->iio->freq_comp_filt[channel][filterIndex]->get_enable(0); } -bool Channel_Digital_Filter_API::isEnableHigh() const { - int channel = osc->channels_api.indexOf(const_cast(ch_api)); +bool Channel_Digital_Filter_API::isEnableHigh() const +{ + int channel = osc->channels_api.indexOf(const_cast(ch_api)); return osc->iio->freq_comp_filt[channel][filterIndex]->get_enable(1); } -void Channel_Digital_Filter_API::setEnableLow(bool en) { - int channel = osc->channels_api.indexOf(const_cast(ch_api)); +void Channel_Digital_Filter_API::setEnableLow(bool en) +{ + int channel = osc->channels_api.indexOf(const_cast(ch_api)); osc->iio->freq_comp_filt[channel][filterIndex]->set_enable(en, 0); } -void Channel_Digital_Filter_API::setEnableHigh(bool en){ - int channel = osc->channels_api.indexOf(const_cast(ch_api)); +void Channel_Digital_Filter_API::setEnableHigh(bool en) +{ + int channel = osc->channels_api.indexOf(const_cast(ch_api)); osc->iio->freq_comp_filt[channel][filterIndex]->set_enable(en, 1); } -float Channel_Digital_Filter_API::TCLow() const { - int channel = osc->channels_api.indexOf(const_cast(ch_api)); +float Channel_Digital_Filter_API::TCLow() const +{ + int channel = osc->channels_api.indexOf(const_cast(ch_api)); return osc->iio->freq_comp_filt[channel][filterIndex]->get_TC(0); } -float Channel_Digital_Filter_API::TCHigh() const { - int channel = osc->channels_api.indexOf(const_cast(ch_api)); +float Channel_Digital_Filter_API::TCHigh() const +{ + int channel = osc->channels_api.indexOf(const_cast(ch_api)); return osc->iio->freq_comp_filt[channel][filterIndex]->get_TC(1); } -void Channel_Digital_Filter_API::setTCLow(float tc){ - int channel = osc->channels_api.indexOf(const_cast(ch_api)); +void Channel_Digital_Filter_API::setTCLow(float tc) +{ + int channel = osc->channels_api.indexOf(const_cast(ch_api)); osc->iio->freq_comp_filt[channel][filterIndex]->set_TC(tc, 0); } -void Channel_Digital_Filter_API::setTCHigh(float tc){ - int channel = osc->channels_api.indexOf(const_cast(ch_api)); +void Channel_Digital_Filter_API::setTCHigh(float tc) +{ + int channel = osc->channels_api.indexOf(const_cast(ch_api)); osc->iio->freq_comp_filt[channel][filterIndex]->set_TC(tc, 1); } -float Channel_Digital_Filter_API::gainLow() const { - int channel = osc->channels_api.indexOf(const_cast(ch_api)); +float Channel_Digital_Filter_API::gainLow() const +{ + int channel = osc->channels_api.indexOf(const_cast(ch_api)); return osc->iio->freq_comp_filt[channel][filterIndex]->get_filter_gain(0); } -float Channel_Digital_Filter_API::gainHigh() const { - int channel = osc->channels_api.indexOf(const_cast(ch_api)); +float Channel_Digital_Filter_API::gainHigh() const +{ + int channel = osc->channels_api.indexOf(const_cast(ch_api)); return osc->iio->freq_comp_filt[channel][filterIndex]->get_filter_gain(1); } -void Channel_Digital_Filter_API::setGainLow(float gain){ - int channel = osc->channels_api.indexOf(const_cast(ch_api)); +void Channel_Digital_Filter_API::setGainLow(float gain) +{ + int channel = osc->channels_api.indexOf(const_cast(ch_api)); osc->iio->freq_comp_filt[channel][filterIndex]->set_filter_gain(gain, 0); } -void Channel_Digital_Filter_API::setGainHigh(float gain){ - int channel = osc->channels_api.indexOf(const_cast(ch_api)); +void Channel_Digital_Filter_API::setGainHigh(float gain) +{ + int channel = osc->channels_api.indexOf(const_cast(ch_api)); osc->iio->freq_comp_filt[channel][filterIndex]->set_filter_gain(gain, 1); } QList Channel_API::data() const { QList list; - int index = osc->channels_api.indexOf(const_cast(this)); + int index = osc->channels_api.indexOf(const_cast(this)); if(index < 0) return list; /*if(osc->ui->pushButtonRunStop->isChecked() || osc->ui->pushButtonSingle->isChecked()) return list;*/ size_t num_of_samples = osc->plot.Curve(index)->data()->size(); - for(size_t i=0; iplot.Curve(index)->data()->sample(i).y(); + for(size_t i = 0; i < num_of_samples; i++) { + double d = osc->plot.Curve(index)->data()->sample(i).y(); list.append(d); } return list; } -#define DECLARE_MEASURE(m, t) \ - double Channel_API::measured_ ## m () const\ - {\ - int index = osc->channels_api.indexOf(const_cast(this));\ - auto measData = osc->plot.measurement(M2kMeasure::t, index);\ - return measData->value();\ +#define DECLARE_MEASURE(m, t) \ + double Channel_API::measured_##m() const \ + { \ + int index = osc->channels_api.indexOf(const_cast(this)); \ + auto measData = osc->plot.measurement(M2kMeasure::t, index); \ + return measData->value(); \ } DECLARE_MEASURE(period, PERIOD) DECLARE_MEASURE(frequency, FREQUENCY) @@ -947,4 +746,4 @@ DECLARE_MEASURE(pos_width, P_WIDTH) DECLARE_MEASURE(neg_width, N_WIDTH) DECLARE_MEASURE(pos_duty, P_DUTY) DECLARE_MEASURE(neg_duty, N_DUTY) -} +} // namespace scopy::m2k diff --git a/plugins/m2k/src/old/oscilloscope_api.hpp b/plugins/m2k/src/old/oscilloscope_api.hpp index 4d32c0affe..3a44bd54fd 100644 --- a/plugins/m2k/src/old/oscilloscope_api.hpp +++ b/plugins/m2k/src/old/oscilloscope_api.hpp @@ -29,109 +29,84 @@ namespace scopy::m2k { class Oscilloscope; class Channel_API; /** - * @brief osc object - */ + * @brief osc object + */ class Oscilloscope_API : public ApiObject { Q_OBJECT - Q_PROPERTY(QVariantList channels READ getChannels); Q_PROPERTY(bool running READ running WRITE run STORED false); Q_PROPERTY(bool single READ isSingle WRITE single STORED false); /** - * @brief Enables the cursors - */ + * @brief Enables the cursors + */ Q_PROPERTY(bool cursors READ hasCursors WRITE setCursors); Q_PROPERTY(bool measure READ hasMeasure WRITE setMeasure); - Q_PROPERTY(bool measure_all - READ measureAll WRITE setMeasureAll); + Q_PROPERTY(bool measure_all READ measureAll WRITE setMeasureAll); Q_PROPERTY(bool counter READ hasCounter WRITE setCounter); - Q_PROPERTY(bool statistics - READ hasStatistics WRITE setStatistics); + Q_PROPERTY(bool statistics READ hasStatistics WRITE setStatistics); - Q_PROPERTY(bool horizontal_cursors READ horizontalCursors - WRITE setHorizontalCursors) - Q_PROPERTY(bool vertical_cursors READ verticalCursors - WRITE setVerticalCursors) + Q_PROPERTY(bool horizontal_cursors READ horizontalCursors WRITE setHorizontalCursors) + Q_PROPERTY(bool vertical_cursors READ verticalCursors WRITE setVerticalCursors) Q_PROPERTY(double cursor_v1 READ cursorV1 WRITE setCursorV1); Q_PROPERTY(double cursor_v2 READ cursorV2 WRITE setCursorV2); Q_PROPERTY(double cursor_h1 READ cursorH1 WRITE setCursorH1); Q_PROPERTY(double cursor_h2 READ cursorH2 WRITE setCursorH2); - Q_PROPERTY(int cursors_position READ getCursorsPosition - WRITE setCursorsPosition) - Q_PROPERTY(int cursors_transparency READ getCursorsTransparency - WRITE setCursorsTransparency) + Q_PROPERTY(int cursors_position READ getCursorsPosition WRITE setCursorsPosition) + Q_PROPERTY(int cursors_transparency READ getCursorsTransparency WRITE setCursorsTransparency) Q_PROPERTY(bool gating_enabled READ gatingEnabled WRITE setGatingEnabled); Q_PROPERTY(double cursor_gateLeft READ cursorGateLeft WRITE setCursorGateLeft); Q_PROPERTY(double cursor_gateRight READ cursorGateRight WRITE setCursorGateRight); - Q_PROPERTY(bool auto_trigger - READ autoTrigger WRITE setAutoTrigger) - Q_PROPERTY(bool internal_trigger - READ internalTrigger WRITE setInternalTrigger) - Q_PROPERTY(bool external_trigger - READ externalTrigger WRITE setExternalTrigger) - Q_PROPERTY(int external_trigger_source - READ externalTriggerSource WRITE setExternalTriggerSource) - Q_PROPERTY(int external_trigger_daisy_order - READ externalTriggerDaisyOrder WRITE setExternalTriggerDaisyOrder) - Q_PROPERTY(bool external_trigger_out - READ externalTriggerOut WRITE setExternalTriggerOut) - Q_PROPERTY(int external_trigger_out_source - READ externalTriggerOutSource WRITE setExternalTriggerOutSource) - - Q_PROPERTY(int trigger_source - READ triggerSource WRITE setTriggerSource) - Q_PROPERTY(double trigger_level - READ getTriggerLevel WRITE setTriggerLevel) - Q_PROPERTY(double trigger_hysteresis READ getTriggerHysteresis - WRITE setTriggerHysteresis) - Q_PROPERTY(bool internal_condition READ internalCondition - WRITE setInternalCondition) - Q_PROPERTY(bool external_condition READ externalCondition - WRITE setExternalCondition) - Q_PROPERTY(bool trigger_input READ getTriggerInput - WRITE setTriggerInput STORED false) - - Q_PROPERTY(QList math_channels - READ getMathChannels WRITE setMathChannels - SCRIPTABLE false /* too complex for now */); - - Q_PROPERTY(double time_position - READ getTimePos WRITE setTimePos); + Q_PROPERTY(bool auto_trigger READ autoTrigger WRITE setAutoTrigger) + Q_PROPERTY(bool internal_trigger READ internalTrigger WRITE setInternalTrigger) + Q_PROPERTY(bool external_trigger READ externalTrigger WRITE setExternalTrigger) + Q_PROPERTY(int external_trigger_source READ externalTriggerSource WRITE setExternalTriggerSource) + Q_PROPERTY(int external_trigger_daisy_order READ externalTriggerDaisyOrder WRITE setExternalTriggerDaisyOrder) + Q_PROPERTY(bool external_trigger_out READ externalTriggerOut WRITE setExternalTriggerOut) + Q_PROPERTY(int external_trigger_out_source READ externalTriggerOutSource WRITE setExternalTriggerOutSource) + + Q_PROPERTY(int trigger_source READ triggerSource WRITE setTriggerSource) + Q_PROPERTY(double trigger_level READ getTriggerLevel WRITE setTriggerLevel) + Q_PROPERTY(double trigger_hysteresis READ getTriggerHysteresis WRITE setTriggerHysteresis) + Q_PROPERTY(bool internal_condition READ internalCondition WRITE setInternalCondition) + Q_PROPERTY(bool external_condition READ externalCondition WRITE setExternalCondition) + Q_PROPERTY(bool trigger_input READ getTriggerInput WRITE setTriggerInput STORED false) + + Q_PROPERTY(QList math_channels READ getMathChannels WRITE setMathChannels + SCRIPTABLE false /* too complex for now */); + + Q_PROPERTY(double time_position READ getTimePos WRITE setTimePos); Q_PROPERTY(double time_base READ getTimeBase WRITE setTimeBase); - Q_PROPERTY(QList measure_en - READ measureEn WRITE setMeasureEn); + Q_PROPERTY(QList measure_en READ measureEn WRITE setMeasureEn); - Q_PROPERTY(QList statistic_en - READ statisticEn WRITE setStatisticEn) + Q_PROPERTY(QList statistic_en READ statisticEn WRITE setStatisticEn) - Q_PROPERTY(int current_channel READ getCurrentChannel - WRITE setCurrentChannel) + Q_PROPERTY(int current_channel READ getCurrentChannel WRITE setCurrentChannel) Q_PROPERTY(bool fft_en READ getFftEn WRITE setFftEn) Q_PROPERTY(bool xy_en READ getXyEn WRITE setXyEn) Q_PROPERTY(bool hist_en READ getHistEn WRITE setHistEn) - Q_PROPERTY(bool export_all READ getExportAll - WRITE setExportAll) + Q_PROPERTY(bool export_all READ getExportAll WRITE setExportAll) Q_PROPERTY(bool autoset_en READ autosetEnabled WRITE enableAutoset) - Q_PROPERTY(int memory_depth READ getMemoryDepth - WRITE setMemoryDepth) + Q_PROPERTY(int memory_depth READ getMemoryDepth WRITE setMemoryDepth) Q_PROPERTY(int xy_thickness READ getXyThickness WRITE setXyThickness) Q_PROPERTY(QString notes READ getNotes WRITE setNotes) public: - explicit Oscilloscope_API(Oscilloscope *osc) : - ApiObject(), osc(osc) {} + explicit Oscilloscope_API(Oscilloscope *osc) + : ApiObject() + , osc(osc) + {} ~Oscilloscope_API() {} QVariantList getChannels(); @@ -225,7 +200,7 @@ class Oscilloscope_API : public ApiObject void setInternExtern(int option); QList getMathChannels() const; - void setMathChannels(const QList& list); + void setMathChannels(const QList &list); double getTimePos() const; void setTimePos(double pos); @@ -234,10 +209,10 @@ class Oscilloscope_API : public ApiObject void setTimeBase(double base); QList measureEn() const; - void setMeasureEn(const QList& list); + void setMeasureEn(const QList &list); QList statisticEn() const; - void setStatisticEn(const QList& list); + void setStatisticEn(const QList &list); int getCurrentChannel() const; void setCurrentChannel(int chn_id); @@ -271,63 +246,62 @@ class Oscilloscope_API : public ApiObject Q_INVOKABLE void show(); - private: - Oscilloscope *osc; - }; +private: + Oscilloscope *osc; +}; - class Channel_Digital_Filter_API : public ApiObject - { - Q_OBJECT - - Q_PROPERTY(bool enLow READ isEnableLow WRITE setEnableLow) - Q_PROPERTY(float tcLow READ TCLow WRITE setTCLow) - Q_PROPERTY(float gainLow READ gainLow WRITE setGainLow) - Q_PROPERTY(bool enHigh READ isEnableHigh WRITE setEnableHigh) - Q_PROPERTY(float tcHigh READ TCHigh WRITE setTCHigh) - Q_PROPERTY(float gainHigh READ gainHigh WRITE setGainHigh) - public: - explicit Channel_Digital_Filter_API(Oscilloscope *osc, Channel_API *ch_api, int index) : - ApiObject(), osc(osc), ch_api(ch_api), filterIndex(index) {} - ~Channel_Digital_Filter_API() {} - bool isEnableLow() const; - bool isEnableHigh() const; - void setEnableLow(bool en); - void setEnableHigh(bool en); - float TCLow() const; - float TCHigh() const; - void setTCLow(float tc); - void setTCHigh(float tc); - float gainLow() const; - float gainHigh() const; - void setGainLow(float gain); - void setGainHigh(float gain); - - private: - Oscilloscope *osc; - Channel_API *ch_api; - int filterIndex; - }; - - - class Channel_API : public ApiObject - { - Q_OBJECT +class Channel_Digital_Filter_API : public ApiObject +{ + Q_OBJECT + + Q_PROPERTY(bool enLow READ isEnableLow WRITE setEnableLow) + Q_PROPERTY(float tcLow READ TCLow WRITE setTCLow) + Q_PROPERTY(float gainLow READ gainLow WRITE setGainLow) + Q_PROPERTY(bool enHigh READ isEnableHigh WRITE setEnableHigh) + Q_PROPERTY(float tcHigh READ TCHigh WRITE setTCHigh) + Q_PROPERTY(float gainHigh READ gainHigh WRITE setGainHigh) +public: + explicit Channel_Digital_Filter_API(Oscilloscope *osc, Channel_API *ch_api, int index) + : ApiObject() + , osc(osc) + , ch_api(ch_api) + , filterIndex(index) + {} + ~Channel_Digital_Filter_API() {} + bool isEnableLow() const; + bool isEnableHigh() const; + void setEnableLow(bool en); + void setEnableHigh(bool en); + float TCLow() const; + float TCHigh() const; + void setTCLow(float tc); + void setTCHigh(float tc); + float gainLow() const; + float gainHigh() const; + void setGainLow(float gain); + void setGainHigh(float gain); + +private: + Oscilloscope *osc; + Channel_API *ch_api; + int filterIndex; +}; + +class Channel_API : public ApiObject +{ + Q_OBJECT Q_PROPERTY(bool enabled READ channelEn WRITE setChannelEn) - Q_PROPERTY(double volts_per_div - READ getVoltsPerDiv WRITE setVoltsPerDiv) + Q_PROPERTY(double volts_per_div READ getVoltsPerDiv WRITE setVoltsPerDiv) Q_PROPERTY(double v_offset READ getVOffset WRITE setVOffset) - Q_PROPERTY(double line_thickness - READ getLineThickness WRITE setLineThickness) + Q_PROPERTY(double line_thickness READ getLineThickness WRITE setLineThickness) - Q_PROPERTY(double probe_attenuation READ getProbeAttenuation - WRITE setProbeAttenuation) + Q_PROPERTY(double probe_attenuation READ getProbeAttenuation WRITE setProbeAttenuation) - Q_PROPERTY(bool ac_coupling READ getAcCoupling - WRITE setAcCoupling) + Q_PROPERTY(bool ac_coupling READ getAcCoupling WRITE setAcCoupling) Q_PROPERTY(double period READ measured_period) Q_PROPERTY(double frequency READ measured_frequency) @@ -357,18 +331,20 @@ class Oscilloscope_API : public ApiObject Q_PROPERTY(QVariantList digFilter READ getDigFilters /*WRITE setDigFilter1 */) - public: - explicit Channel_API(Oscilloscope *osc) : - ApiObject(), osc(osc) { - for(auto i=0;i<2;i++) - digFilters.append(new Channel_Digital_Filter_API(osc,this,i)); - } + explicit Channel_API(Oscilloscope *osc) + : ApiObject() + , osc(osc) + { + for(auto i = 0; i < 2; i++) + digFilters.append(new Channel_Digital_Filter_API(osc, this, i)); + } - ~Channel_API() { - for(auto it = digFilters.begin();it != digFilters.end(); it++ ) - delete *it; - } + ~Channel_API() + { + for(auto it = digFilters.begin(); it != digFilters.end(); it++) + delete *it; + } bool channelEn() const; void setChannelEn(bool en); @@ -419,9 +395,8 @@ class Oscilloscope_API : public ApiObject private: Oscilloscope *osc; - QList digFilters; - + QList digFilters; }; -} +} // namespace scopy::m2k #endif // OSCILLOSCOPE_API_HPP diff --git a/plugins/m2k/src/old/patterngenerator/pattern_generator.cpp b/plugins/m2k/src/old/patterngenerator/pattern_generator.cpp index 43e5dafdde..ec13803ca2 100644 --- a/plugins/m2k/src/old/patterngenerator/pattern_generator.cpp +++ b/plugins/m2k/src/old/patterngenerator/pattern_generator.cpp @@ -18,25 +18,25 @@ * along with this program. If not, see . */ - #include "pattern_generator.h" -#include -#include -#include "ui_pattern_generator.h" +#include "../logicanalyzer/logicgroupitem.h" #include "digitalchannel_manager.hpp" -#include "gui/dynamicWidget.h" #include "gui/basemenu.h" -#include "../logicanalyzer/logicgroupitem.h" - +#include "gui/dynamicWidget.h" #include "gui/logicdatacurve.h" +#include "m2kpluginExceptionHandler.h" +#include "pattern_generator_api.h" #include "patterns/patterns.hpp" #include "sigrok-gui/annotationcurve.h" #include "sigrok-gui/annotationdecoder.h" -#include "pattern_generator_api.h" + +#include "ui_pattern_generator.h" + +#include +#include #include -#include "m2kpluginExceptionHandler.h" #include using namespace scopy; @@ -51,10 +51,14 @@ constexpr int MAX_SAMPLE_RATE = 100000000; namespace detail { int gcd(int a, int b) { - for (;;) { - if (!a) { return b; } + for(;;) { + if(!a) { + return b; + } b %= a; - if (!b) { return a; } + if(!b) { + return a; + } a %= b; } } @@ -68,8 +72,7 @@ int lcm(int a, int b) } // namespace detail -PatternGenerator::PatternGenerator(struct iio_context *ctx, Filter *filt, - ToolMenuEntry *tme, QJSEngine *engine, +PatternGenerator::PatternGenerator(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, QJSEngine *engine, DIOManager *diom, QWidget *parent) : M2kTool(nullptr, tme, new PatternGenerator_API(this), "Pattern Generator", parent) , m_ui(new Ui::PatternGenerator) @@ -94,7 +97,7 @@ PatternGenerator::PatternGenerator(struct iio_context *ctx, Filter *filt, m_plot.setLeftVertAxesCount(1); - for (uint8_t i = 0; i < DIGITAL_NR_CHANNELS; ++i) { + for(uint8_t i = 0; i < DIGITAL_NR_CHANNELS; ++i) { QCheckBox *channelBox = new QCheckBox("DIO " + QString::number(i)); m_ui->channelEnumeratorLayout->addWidget(channelBox, i % 8, i / 8); @@ -109,14 +112,14 @@ PatternGenerator::PatternGenerator(struct iio_context *ctx, Filter *filt, // use direct connection we want the processing // of the available data to be done in the capture thread - connect(this, &PatternGenerator::dataAvailable, this, - [=](uint64_t from, uint64_t to, uint16_t *buffer){ - curve->dataAvailable(from, to, buffer); - }, Qt::DirectConnection); + connect( + this, &PatternGenerator::dataAvailable, this, + [=](uint64_t from, uint64_t to, uint16_t *buffer) { curve->dataAvailable(from, to, buffer); }, + Qt::DirectConnection); m_plotCurves.push_back(curve); - connect(channelBox, &QCheckBox::toggled, [=](bool toggled){ + connect(channelBox, &QCheckBox::toggled, [=](bool toggled) { m_plot.enableDigitalPlotCurve(i, toggled); m_plot.setOffsetWidgetVisible(i, toggled); m_plot.positionInGroupChanged(i, 0, 0); @@ -124,7 +127,7 @@ PatternGenerator::PatternGenerator(struct iio_context *ctx, Filter *filt, checkEnabledChannels(); - if (m_running) { + if(m_running) { startStop(false); startStop(true); } @@ -167,22 +170,22 @@ PatternGenerator::~PatternGenerator() { delete api; - if (m_running) { + if(m_running) { tme->setRunning(false); } - for (auto &curve : m_plotCurves) { + for(auto &curve : m_plotCurves) { m_plot.removeDigitalPlotCurve(curve); delete curve; } - if (m_buffer) { + if(m_buffer) { delete[] m_buffer; m_buffer = nullptr; } auto i = m_annotationCurvePatternUiMap.begin(); - while (i != m_annotationCurvePatternUiMap.end()) { + while(i != m_annotationCurvePatternUiMap.end()) { delete i.key(); disconnect(i.value().second); ++i; @@ -215,16 +218,15 @@ void PatternGenerator::setupUi() // disable time trigger m_plot.enableTimeTrigger(false); - int gsettings_panel = m_ui->stackedWidget->indexOf(m_ui->generalSettings); m_ui->btnGeneralSettings->setProperty("id", QVariant(-gsettings_panel)); -// /* Cursors Settings */ -// ui->btnCursors->setProperty("id", QVariant(-1)); + // /* Cursors Settings */ + // ui->btnCursors->setProperty("id", QVariant(-1)); -// /* Trigger Settings */ -// int triggers_panel = ui->stackedWidget->indexOf(ui->triggerSettings); -// ui->btnTrigger->setProperty("id", QVariant(-triggers_panel)); + // /* Trigger Settings */ + // int triggers_panel = ui->stackedWidget->indexOf(ui->triggerSettings); + // ui->btnTrigger->setProperty("id", QVariant(-triggers_panel)); /* Channel Settings */ int channelSettings_panel = m_ui->stackedWidget->indexOf(m_ui->channelSettings); @@ -233,17 +235,15 @@ void PatternGenerator::setupUi() // set default menu width to 0 m_ui->rightMenu->setMaximumWidth(0); - // plot widget - QWidget* centralWidget = new QWidget(this); - QGridLayout* gridLayout = new QGridLayout(centralWidget); + QWidget *centralWidget = new QWidget(this); + QGridLayout *gridLayout = new QGridLayout(centralWidget); gridLayout->setVerticalSpacing(0); gridLayout->setHorizontalSpacing(0); gridLayout->setContentsMargins(25, 0, 25, 0); centralWidget->setLayout(gridLayout); - QSpacerItem *plotSpacer = new QSpacerItem(0, 5, - QSizePolicy::Fixed, QSizePolicy::Fixed); + QSpacerItem *plotSpacer = new QSpacerItem(0, 5, QSizePolicy::Fixed, QSizePolicy::Fixed); gridLayout->addWidget(m_plot.topArea(), 0, 0, 1, 4); gridLayout->addWidget(m_plot.topHandlesArea(), 1, 0, 1, 4); @@ -259,7 +259,6 @@ void PatternGenerator::setupUi() m_ui->gridLayoutPlot->addWidget(centralWidget, 0, 0, 1, 1); - // TODO: do we want the buffer previewer in this tool? m_ui->hLayoutBufferPreview->hide(); @@ -287,13 +286,11 @@ void PatternGenerator::setupUi() void PatternGenerator::on_btnChannelSettings_toggled(bool checked) { - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); + triggerRightMenuToggle(static_cast(QObject::sender()), checked); - if (checked && m_selectedChannel != -1) { + if(checked && m_selectedChannel != -1) { m_ui->nameLineEdit->setText(m_plot.getChannelName(m_selectedChannel)); - m_ui->traceHeightLineEdit->setText(QString::number( - m_plotCurves[m_selectedChannel]->getTraceHeight())); + m_ui->traceHeightLineEdit->setText(QString::number(m_plotCurves[m_selectedChannel]->getTraceHeight())); } } @@ -301,12 +298,11 @@ void PatternGenerator::on_btnSettings_clicked(bool checked) { CustomPushButton *btn = nullptr; - if (checked && !m_menuOrder.isEmpty()) { + if(checked && !m_menuOrder.isEmpty()) { btn = m_menuOrder.back(); m_menuOrder.pop_back(); } else { - btn = static_cast( - m_ui->settings_group->checkedButton()); + btn = static_cast(m_ui->settings_group->checkedButton()); } btn->setChecked(checked); @@ -314,8 +310,7 @@ void PatternGenerator::on_btnSettings_clicked(bool checked) void PatternGenerator::on_btnGeneralSettings_toggled(bool checked) { - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); + triggerRightMenuToggle(static_cast(QObject::sender()), checked); if(checked) { m_ui->btnSettings->setChecked(!checked); } @@ -328,7 +323,7 @@ void PatternGenerator::rightMenuFinished(bool opened) // At the end of each animation, check if there are other button check // actions that might have happened while animating and execute all // these queued actions - while (m_menuButtonActions.size()) { + while(m_menuButtonActions.size()) { auto pair = m_menuButtonActions.dequeue(); toggleRightMenu(pair.first, pair.second); } @@ -338,8 +333,8 @@ void PatternGenerator::channelSelectedChanged(int chIdx, bool selected) { QSignalBlocker nameLineEditBlocker(m_ui->nameLineEdit); QSignalBlocker traceHeightLineEditBlocker(m_ui->traceHeightLineEdit); - if (m_selectedChannel != chIdx && selected) { - if (!m_ui->btnChannelSettings->isChecked()) { + if(m_selectedChannel != chIdx && selected) { + if(!m_ui->btnChannelSettings->isChecked()) { m_ui->btnChannelSettings->setChecked(true); } @@ -347,23 +342,20 @@ void PatternGenerator::channelSelectedChanged(int chIdx, bool selected) m_ui->nameLineEdit->setEnabled(true); m_ui->nameLineEdit->setText(m_plotCurves[m_selectedChannel]->getName()); m_ui->traceHeightLineEdit->setEnabled(true); - m_ui->traceHeightLineEdit->setText( - QString::number(m_plotCurves[m_selectedChannel]->getTraceHeight())); + m_ui->traceHeightLineEdit->setText(QString::number(m_plotCurves[m_selectedChannel]->getTraceHeight())); m_ui->patternComboBox->setEnabled(true); m_ui->btnOutputMode->setEnabled(true); - if (m_selectedChannel < m_nbChannels) { + if(m_selectedChannel < m_nbChannels) { const DIO_MODE outputMode = m_m2kDigital->getOutputMode(m_selectedChannel); - const bool btnOutputModeSelected = (outputMode == DIO_MODE::DIO_OPENDRAIN ? true - :false); + const bool btnOutputModeSelected = (outputMode == DIO_MODE::DIO_OPENDRAIN ? true : false); m_ui->btnOutputMode->setChecked(btnOutputModeSelected); } updateChannelGroupWidget(true); updateChannelGroupPattern(true); - - } else if (m_selectedChannel == chIdx && !selected) { + } else if(m_selectedChannel == chIdx && !selected) { m_selectedChannel = -1; m_ui->nameLineEdit->setDisabled(true); m_ui->nameLineEdit->setText(""); @@ -374,7 +366,6 @@ void PatternGenerator::channelSelectedChanged(int chIdx, bool selected) updateChannelGroupWidget(false); updateChannelGroupPattern(false); - } } @@ -382,11 +373,11 @@ void PatternGenerator::on_btnGroupChannels_toggled(bool checked) { m_ui->btnGroupChannels->setText(checked ? "Done" : "Group"); - if (checked) { + if(checked) { m_plot.beginGroupSelection(); } else { - if (m_plot.endGroupSelection(true)) { -// channelSelectedChanged(m_selectedChannel, false); + if(m_plot.endGroupSelection(true)) { + // channelSelectedChanged(m_selectedChannel, false); updateGroupsAndPatterns(); } } @@ -394,7 +385,7 @@ void PatternGenerator::on_btnGroupChannels_toggled(bool checked) void PatternGenerator::removeAnnotationCurveOfPattern(PatternUI *pattern) { - if (m_annotationCurvePatternUiMap.contains(pattern)) { + if(m_annotationCurvePatternUiMap.contains(pattern)) { disconnect(m_annotationCurvePatternUiMap[pattern].second); GenericLogicPlotCurve *curve = m_annotationCurvePatternUiMap[pattern].first; @@ -402,8 +393,7 @@ void PatternGenerator::removeAnnotationCurveOfPattern(PatternUI *pattern) bool dummy = false; int removeIndx = m_plotCurves.indexOf(curve); m_plot.removeFromGroup(m_selectedChannel, - m_plot.getGroupOfChannel(m_selectedChannel).indexOf(removeIndx), - dummy); + m_plot.getGroupOfChannel(m_selectedChannel).indexOf(removeIndx), dummy); m_plot.removeDigitalPlotCurve(curve); @@ -417,18 +407,21 @@ void PatternGenerator::removeAnnotationCurveOfPattern(PatternUI *pattern) void PatternGenerator::updateAnnotationCurveChannelsForPattern(const QPair, PatternUI *> &pattern) { - if (pattern.second->getAnnotationCurve()) { - AnnotationCurve *curve = dynamic_cast( - pattern.second->getAnnotationCurve()); + if(pattern.second->getAnnotationCurve()) { + AnnotationCurve *curve = dynamic_cast(pattern.second->getAnnotationCurve()); QVector chToAssign = pattern.second->getChannelsToAssign(); int skipped = 0; - for (int i = 0; i < curve->getAnnotationDecoder()->getNrOfChannels(); ++i) { - if (!chToAssign.empty() && !chToAssign.contains(i)) { + for(int i = 0; i < curve->getAnnotationDecoder()->getNrOfChannels(); ++i) { + if(!chToAssign.empty() && !chToAssign.contains(i)) { skipped++; continue; } - if (i - skipped >= pattern.first.size()) { break; } - if (pattern.first[i - skipped] >= DIGITAL_NR_CHANNELS) { continue; } + if(i - skipped >= pattern.first.size()) { + break; + } + if(pattern.first[i - skipped] >= DIGITAL_NR_CHANNELS) { + continue; + } curve->getAnnotationDecoder()->assignChannel(i, pattern.first[i - skipped]); } } @@ -437,10 +430,10 @@ void PatternGenerator::updateAnnotationCurveChannelsForPattern(const QPairpatternLayout->addWidget(patternUi); patternUi->setVisible(true); - connect(patternUi, &PatternUI::patternParamsChanged, - this, &PatternGenerator::regenerate); - connect(patternUi, &PatternUI::patternParamsChanged, - this, &PatternGenerator::generateBuffer); + connect(patternUi, &PatternUI::patternParamsChanged, this, &PatternGenerator::regenerate); + connect(patternUi, &PatternUI::patternParamsChanged, this, &PatternGenerator::generateBuffer); bool didSet = false; - for (auto &ep : m_enabledPatterns) { - if (ep.first.contains(selected)) { + for(auto &ep : m_enabledPatterns) { + if(ep.first.contains(selected)) { m_ui->patternLayout->removeWidget(ep.second); removeAnnotationCurveOfPattern(ep.second); - if (patternUi->getDecoder()) { + if(patternUi->getDecoder()) { qDebug() << "This pattern has a decoder!"; AnnotationCurve *curve = new AnnotationCurve(patternUi->getDecoder()); @@ -473,16 +464,19 @@ void PatternGenerator::patternSelected(const QString &pattern, int ch, const QSt // use direct connection we want the processing // of the available data to be done in the capture thread - QMetaObject::Connection connectionHandle = connect(this, &PatternGenerator::dataAvailable, - this, [=](uint64_t from, uint64_t to, uint16_t *buffer){ - curve->dataAvailable(from, to, buffer); - }, Qt::DirectConnection); + QMetaObject::Connection connectionHandle = connect( + this, &PatternGenerator::dataAvailable, this, + [=](uint64_t from, uint64_t to, uint16_t *buffer) { + curve->dataAvailable(from, to, buffer); + }, + Qt::DirectConnection); m_plotCurves.push_back(curve); m_plot.addToGroup(selected, m_plotCurves.size() - 1); - // m_plot.setOffsetHandleVisible(m_plotCurves.size() - 1, false); - m_annotationCurvePatternUiMap[patternUi] = { curve, connectionHandle }; + // m_plot.setOffsetHandleVisible(m_plotCurves.size() - 1, + // false); + m_annotationCurvePatternUiMap[patternUi] = {curve, connectionHandle}; m_plot.setChannelSelectable(m_plotCurves.size() - 1, false); } @@ -503,17 +497,17 @@ void PatternGenerator::patternSelected(const QString &pattern, int ch, const QSt } } - if (!didSet) { + if(!didSet) { // we have a new configuration QVector group = m_plot.getGroupOfChannel(selected); - if (group.empty()) { + if(group.empty()) { m_enabledPatterns.push_back({{selected}, patternUi}); } else { m_enabledPatterns.push_back({group, patternUi}); } - if (patternUi->getDecoder()) { + if(patternUi->getDecoder()) { qDebug() << "This pattern has a decoder!"; AnnotationCurve *curve = new AnnotationCurve(patternUi->getDecoder()); @@ -524,16 +518,18 @@ void PatternGenerator::patternSelected(const QString &pattern, int ch, const QSt // use direct connection we want the processing // of the available data to be done in the capture thread - QMetaObject::Connection connectionHandle = connect(this, &PatternGenerator::dataAvailable, - this, [=](uint64_t from, uint64_t to, uint16_t *buffer){ - curve->dataAvailable(from, to, buffer); - }, Qt::DirectConnection); + QMetaObject::Connection connectionHandle = connect( + this, &PatternGenerator::dataAvailable, this, + [=](uint64_t from, uint64_t to, uint16_t *buffer) { + curve->dataAvailable(from, to, buffer); + }, + Qt::DirectConnection); m_plotCurves.push_back(curve); m_plot.addToGroup(selected, m_plotCurves.size() - 1); - // m_plot.setOffsetHandleVisible(m_plotCurves.size() - 1, false); - m_annotationCurvePatternUiMap[patternUi] = { curve, connectionHandle }; + // m_plot.setOffsetHandleVisible(m_plotCurves.size() - 1, false); + m_annotationCurvePatternUiMap[patternUi] = {curve, connectionHandle}; m_plot.setChannelSelectable(m_plotCurves.size() - 1, false); } @@ -544,13 +540,13 @@ void PatternGenerator::patternSelected(const QString &pattern, int ch, const QSt } } else { int remove = -1; - for (int i = 0; i < m_enabledPatterns.size(); ++i) { - if (m_enabledPatterns[i].first.contains(selected)) { + for(int i = 0; i < m_enabledPatterns.size(); ++i) { + if(m_enabledPatterns[i].first.contains(selected)) { remove = i; break; } } - if (remove != -1) { + if(remove != -1) { // TODO: remove annotation curve if it has one!!! @@ -569,7 +565,7 @@ void PatternGenerator::patternSelected(const QString &pattern, int ch, const QSt void PatternGenerator::on_btnOutputMode_toggled(bool checked) { - if (m_selectedChannel >= DIGITAL_NR_CHANNELS) { + if(m_selectedChannel >= DIGITAL_NR_CHANNELS) { return; } @@ -580,17 +576,17 @@ void PatternGenerator::on_btnOutputMode_toggled(bool checked) uint64_t PatternGenerator::computeSampleRate() const { uint64_t sr = 1; - for (const QPair, PatternUI *> &pattern : m_enabledPatterns) { + for(const QPair, PatternUI *> &pattern : m_enabledPatterns) { const uint64_t patternSamplingFrequency = pattern.second->get_pattern()->get_min_sampling_freq(); - if (!patternSamplingFrequency) { + if(!patternSamplingFrequency) { continue; } sr = detail::lcm(patternSamplingFrequency, sr); } - if (!sr || sr > MAX_SAMPLE_RATE) { + if(!sr || sr > MAX_SAMPLE_RATE) { sr = MAX_SAMPLE_RATE; } else { sr = MAX_SAMPLE_RATE / (MAX_SAMPLE_RATE / sr); @@ -604,36 +600,36 @@ uint64_t PatternGenerator::computeBufferSize(uint64_t sampleRate) const const uint64_t divconst = 50000000 / 256; uint64_t size = sampleRate / divconst; uint64_t minSize = 4; - if (size < minSize) { + if(size < minSize) { size = minSize; } uint64_t bufferSize = detail::lcm(size, 4); uint64_t maxNonPeriodic = size; - for (const QPair, PatternUI *> &pattern : m_enabledPatterns) { - const uint64_t patternBufferSize = pattern.second->get_pattern() - ->get_required_nr_of_samples(sampleRate, pattern.first.size()); + for(const QPair, PatternUI *> &pattern : m_enabledPatterns) { + const uint64_t patternBufferSize = + pattern.second->get_pattern()->get_required_nr_of_samples(sampleRate, pattern.first.size()); qDebug() << patternBufferSize; - if (!patternBufferSize) { + if(!patternBufferSize) { continue; } - if (pattern.second->get_pattern()->is_periodic()) { + if(pattern.second->get_pattern()->is_periodic()) { bufferSize = detail::lcm(patternBufferSize, bufferSize); } else { - if (maxNonPeriodic < patternBufferSize) { + if(maxNonPeriodic < patternBufferSize) { maxNonPeriodic = patternBufferSize; } } } - if (maxNonPeriodic > bufferSize) { + if(maxNonPeriodic > bufferSize) { uint64_t result = 1; - for (int i = 1; result < MAX_BUFFER_SIZE && maxNonPeriodic > result; ++i) { + for(int i = 1; result < MAX_BUFFER_SIZE && maxNonPeriodic > result; ++i) { result = bufferSize * i; } @@ -645,23 +641,22 @@ uint64_t PatternGenerator::computeBufferSize(uint64_t sampleRate) const uint16_t PatternGenerator::remapBuffer(uint8_t *mapping, uint32_t val) { - short ret=0; - int i=0; + short ret = 0; + int i = 0; - while (val) { - if (val&0x01) { - ret = ret | (1<>=1; + val >>= 1; } return ret; } -void PatternGenerator::commitBuffer(const QPair, PatternUI *> &pattern, - uint16_t *buffer, +void PatternGenerator::commitBuffer(const QPair, PatternUI *> &pattern, uint16_t *buffer, uint32_t bufferSize) { uint8_t channelMapping[16]; @@ -671,12 +666,12 @@ void PatternGenerator::commitBuffer(const QPair, PatternUI *> &patt uint16_t chgMask = 0; auto bufferChannelMask = (1 << pattern.first.size()) - 1; - for (int i = 0; i < pattern.first.size(); ++i) { + for(int i = 0; i < pattern.first.size(); ++i) { channelMapping[i] = pattern.first[i]; chgMask = chgMask | (1 << pattern.first[i]); } - for (size_t i = 0; i < bufferSize; ++i) { + for(size_t i = 0; i < bufferSize; ++i) { auto val = (bufferPtr[i] & bufferChannelMask); buffer[i] = (buffer[i] & ~(chgMask)) | remapBuffer(channelMapping, val); } @@ -685,9 +680,9 @@ void PatternGenerator::commitBuffer(const QPair, PatternUI *> &patt void PatternGenerator::checkEnabledChannels() { bool foundOneEnabled = false; - for (int i = 0; i < m_plotCurves.size(); ++i) { + for(int i = 0; i < m_plotCurves.size(); ++i) { const bool enabled = !!m_plotCurves[i]->plot(); - if (enabled) { + if(enabled) { foundOneEnabled = true; break; } @@ -699,7 +694,7 @@ void PatternGenerator::checkEnabledChannels() void PatternGenerator::regenerate() { - if (m_running) { + if(m_running) { startStop(false); startStop(true); } @@ -708,9 +703,9 @@ void PatternGenerator::regenerate() void PatternGenerator::startStop(bool start) { qDebug() << "Started status: " << start; - if (start) { + if(start) { - if (m_singleTimer->isActive()) { + if(m_singleTimer->isActive()) { m_singleTimer->stop(); startStop(false); } @@ -722,10 +717,10 @@ void PatternGenerator::startStop(bool start) m_plot.replot(); uint16_t lockMask = 0; - for (int i = 0; i < DIGITAL_NR_CHANNELS; ++i) { + for(int i = 0; i < DIGITAL_NR_CHANNELS; ++i) { bool enabled = !!m_plotCurves[i]->plot(); lockMask = lockMask | enabled << i; - if (enabled) { + if(enabled) { m_m2kDigital->setDirection(i, DIO_OUTPUT); } m_m2kDigital->enableChannel(i, enabled); @@ -741,11 +736,12 @@ void PatternGenerator::startStop(bool start) m_m2kDigital->push(m_buffer, m_bufferSize); // timeout = buffer duration for the given samplerate + 200 milliseconds usb transfer (push) - const double timeout = 0.2 + static_cast(m_bufferSize) / static_cast(m_sampleRate); + const double timeout = + 0.2 + static_cast(m_bufferSize) / static_cast(m_sampleRate); // * 1000.0 (timeout is in seconds, start expects milliseconds) m_singleTimer->start(timeout * 1000.0); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug() << e.what(); } @@ -757,13 +753,13 @@ void PatternGenerator::startStop(bool start) m_m2kDigital->cancelBufferOut(); m_m2kDigital->stopBufferOut(); - for (int i = 0; i < DIGITAL_NR_CHANNELS; ++i) { + for(int i = 0; i < DIGITAL_NR_CHANNELS; ++i) { bool enabled = !!m_plotCurves[i]->plot(); - if (enabled) { + if(enabled) { m_m2kDigital->enableChannel(i, false); } } - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug() << e.what(); } @@ -788,18 +784,17 @@ void PatternGenerator::generateBuffer() m_plot.setSampleRatelabelValue(m_sampleRate); m_plot.setBufferSizeLabelValue(m_bufferSize); - m_plot.setTimeBaseLabelValue(static_cast(m_bufferSize) / - static_cast(m_sampleRate) / + m_plot.setTimeBaseLabelValue(static_cast(m_bufferSize) / static_cast(m_sampleRate) / m_plot.xAxisNumDiv()); - if (m_buffer) { + if(m_buffer) { delete[] m_buffer; } m_buffer = new uint16_t[bufferSize]; memset(m_buffer, 0x0000, bufferSize * sizeof(uint16_t)); - for (int i = 0; i < m_plotCurves.size(); ++i) { + for(int i = 0; i < m_plotCurves.size(); ++i) { QwtPlotCurve *curve = m_plot.getDigitalPlotCurve(i); GenericLogicPlotCurve *logic_curve = dynamic_cast(curve); logic_curve->reset(); @@ -814,7 +809,7 @@ void PatternGenerator::generateBuffer() m_plot.cancelZoom(); m_plot.zoomBaseUpdate(true); - for (QPair, PatternUI *> &pattern : m_enabledPatterns) { + for(QPair, PatternUI *> &pattern : m_enabledPatterns) { pattern.second->get_pattern()->generate_pattern(sr, bufferSize, pattern.first.size()); commitBuffer(pattern, m_buffer, bufferSize); pattern.second->get_pattern()->delete_buffer(); @@ -822,7 +817,7 @@ void PatternGenerator::generateBuffer() pattern.second->get_pattern()->setNrOfChannels(pattern.first.size()); } - Q_EMIT dataAvailable(0, bufferSize,m_buffer); + Q_EMIT dataAvailable(0, bufferSize, m_buffer); } void PatternGenerator::triggerRightMenuToggle(CustomPushButton *btn, bool checked) @@ -830,9 +825,8 @@ void PatternGenerator::triggerRightMenuToggle(CustomPushButton *btn, bool checke // Queue the action, if right menu animation is in progress. This way // the action will be remembered and performed right after the animation // finishes - if (m_ui->rightMenu->animInProgress()) { - m_menuButtonActions.enqueue( - QPair(btn, checked)); + if(m_ui->rightMenu->animInProgress()) { + m_menuButtonActions.enqueue(QPair(btn, checked)); } else { toggleRightMenu(btn, checked); } @@ -842,8 +836,8 @@ void PatternGenerator::toggleRightMenu(CustomPushButton *btn, bool checked) { int id = btn->property("id").toInt(); - if (id != -m_ui->stackedWidget->indexOf(m_ui->generalSettings)){ - if (!m_menuOrder.contains(btn)){ + if(id != -m_ui->stackedWidget->indexOf(m_ui->generalSettings)) { + if(!m_menuOrder.contains(btn)) { m_menuOrder.push_back(btn); } else { m_menuOrder.removeOne(btn); @@ -851,7 +845,7 @@ void PatternGenerator::toggleRightMenu(CustomPushButton *btn, bool checked) } } - if (checked) { + if(checked) { settingsPanelUpdate(id); } @@ -860,16 +854,16 @@ void PatternGenerator::toggleRightMenu(CustomPushButton *btn, bool checked) void PatternGenerator::settingsPanelUpdate(int id) { - if (id >= 0) { + if(id >= 0) { m_ui->stackedWidget->setCurrentIndex(0); } else { m_ui->stackedWidget->setCurrentIndex(-id); } - for (int i = 0; i < m_ui->stackedWidget->count(); i++) { + for(int i = 0; i < m_ui->stackedWidget->count(); i++) { QSizePolicy::Policy policy = QSizePolicy::Ignored; - if (i == m_ui->stackedWidget->currentIndex()) { + if(i == m_ui->stackedWidget->currentIndex()) { policy = QSizePolicy::Expanding; } QWidget *widget = m_ui->stackedWidget->widget(i); @@ -881,65 +875,53 @@ void PatternGenerator::settingsPanelUpdate(int id) void PatternGenerator::connectSignalsAndSlots() { - connect(m_ui->runSingleWidget, &RunSingleWidget::toggled, - [=](bool checked){ - disconnect(tme, &ToolMenuEntry::runToggled, - m_ui->runSingleWidget, &RunSingleWidget::toggle); + connect(m_ui->runSingleWidget, &RunSingleWidget::toggled, [=](bool checked) { + disconnect(tme, &ToolMenuEntry::runToggled, m_ui->runSingleWidget, &RunSingleWidget::toggle); tme->setRunning(checked); - connect(tme, &ToolMenuEntry::runToggled, - m_ui->runSingleWidget, &RunSingleWidget::toggle); + connect(tme, &ToolMenuEntry::runToggled, m_ui->runSingleWidget, &RunSingleWidget::toggle); // TODO: play with the trigger state when the pattern generator will support // trigger features, till then do not show any trigger state on the plot -// if (!checked) { -// m_plot.setTriggerState(CapturePlot::Stop); -// } + // if (!checked) { + // m_plot.setTriggerState(CapturePlot::Stop); + // } }); - connect(tme, &ToolMenuEntry::runToggled, - m_ui->runSingleWidget, &RunSingleWidget::toggle); - connect(m_ui->runSingleWidget, &RunSingleWidget::toggled, - this, &PatternGenerator::startStop); - + connect(tme, &ToolMenuEntry::runToggled, m_ui->runSingleWidget, &RunSingleWidget::toggle); + connect(m_ui->runSingleWidget, &RunSingleWidget::toggled, this, &PatternGenerator::startStop); - connect(m_ui->rightMenu, &MenuHAnim::finished, - this, &PatternGenerator::rightMenuFinished); - - connect(&m_plot, &CapturePlot::channelSelected, - this, &PatternGenerator::channelSelectedChanged); + connect(m_ui->rightMenu, &MenuHAnim::finished, this, &PatternGenerator::rightMenuFinished); + connect(&m_plot, &CapturePlot::channelSelected, this, &PatternGenerator::channelSelectedChanged); connect(m_plotScrollBar, &QScrollBar::valueChanged, [=](double value) { m_plot.setAllYAxis(-5 - (value * 0.05), 5 - (value * 0.05)); m_plot.replot(); }); - connect(m_ui->traceHeightLineEdit, &QLineEdit::textChanged, [=](const QString &text){ + connect(m_ui->traceHeightLineEdit, &QLineEdit::textChanged, [=](const QString &text) { auto validator = m_ui->traceHeightLineEdit->validator(); QString toCheck = text; int pos; - setDynamicProperty(m_ui->traceHeightLineEdit, - "invalid", + setDynamicProperty(m_ui->traceHeightLineEdit, "invalid", validator->validate(toCheck, pos) == QIntValidator::Intermediate); }); - connect(m_ui->traceHeightLineEdit, &QLineEdit::editingFinished, [=](){ + connect(m_ui->traceHeightLineEdit, &QLineEdit::editingFinished, [=]() { int value = m_ui->traceHeightLineEdit->text().toInt(); m_plotCurves[m_selectedChannel]->setTraceHeight(value); m_plot.replot(); m_plot.positionInGroupChanged(m_selectedChannel, 0, 0); }); - connect(m_ui->nameLineEdit, &QLineEdit::textChanged, [=](const QString &text){ + connect(m_ui->nameLineEdit, &QLineEdit::textChanged, [=](const QString &text) { m_plot.setChannelName(text, m_selectedChannel); m_plotCurves[m_selectedChannel]->setName(text); }); - connect(m_ui->printBtn, &QPushButton::clicked, [=](){ - m_plot.printWithNoBackground("Pattern Generator"); - }); + connect(m_ui->printBtn, &QPushButton::clicked, [=]() { m_plot.printWithNoBackground("Pattern Generator"); }); - connect(m_singleTimer, &QTimer::timeout, [=](){ - if (m_ui->runSingleWidget->singleButtonChecked()) { + connect(m_singleTimer, &QTimer::timeout, [=]() { + if(m_ui->runSingleWidget->singleButtonChecked()) { m_ui->runSingleWidget->toggle(false); } }); @@ -950,8 +932,8 @@ void PatternGenerator::updateChannelGroupWidget(bool visible) QVector channelsInGroup = m_plot.getGroupOfChannel(m_selectedChannel); int channelsInGroupSize = channelsInGroup.size(); - for (int i = 0; i < channelsInGroup.size(); ++i) { - if (channelsInGroup[i] >= DIGITAL_NR_CHANNELS) { + for(int i = 0; i < channelsInGroup.size(); ++i) { + if(channelsInGroup[i] >= DIGITAL_NR_CHANNELS) { channelsInGroupSize--; } } @@ -959,17 +941,17 @@ void PatternGenerator::updateChannelGroupWidget(bool visible) const bool shouldBeVisible = visible & (channelsInGroupSize > 1); m_ui->groupWidget->setVisible(shouldBeVisible); - if (!shouldBeVisible) { + if(!shouldBeVisible) { return; } - if (channelsInGroup == m_currentGroup) { + if(channelsInGroup == m_currentGroup) { return; } m_currentGroup = channelsInGroup; - if (m_currentGroupMenu) { + if(m_currentGroupMenu) { m_ui->groupWidgetLayout->removeWidget(m_currentGroupMenu); m_currentGroupMenu->deleteLater(); m_currentGroupMenu = nullptr; @@ -978,31 +960,32 @@ void PatternGenerator::updateChannelGroupWidget(bool visible) m_currentGroupMenu = new BaseMenu(m_ui->groupWidget); m_ui->groupWidgetLayout->addWidget(m_currentGroupMenu); - connect(m_currentGroupMenu, &BaseMenu::itemMovedFromTo, [=](short from, short to){ + connect(m_currentGroupMenu, &BaseMenu::itemMovedFromTo, [=](short from, short to) { m_plot.positionInGroupChanged(m_selectedChannel, from, to); channelInGroupChangedPosition(from, to); }); - for (int i = 0; i < channelsInGroup.size(); ++i) { - if (channelsInGroup[i] >= DIGITAL_NR_CHANNELS) { + for(int i = 0; i < channelsInGroup.size(); ++i) { + if(channelsInGroup[i] >= DIGITAL_NR_CHANNELS) { continue; } QString name = m_plotCurves[channelsInGroup[i]]->getName(); LogicGroupItem *item = new LogicGroupItem(name, m_currentGroupMenu); - connect(m_plotCurves[channelsInGroup[i]], &GenericLogicPlotCurve::nameChanged, - item, &LogicGroupItem::setName); - connect(item, &LogicGroupItem::deleteBtnClicked, [=](){ + connect(m_plotCurves[channelsInGroup[i]], &GenericLogicPlotCurve::nameChanged, item, + &LogicGroupItem::setName); + connect(item, &LogicGroupItem::deleteBtnClicked, [=]() { bool groupDeleted = false; m_plot.removeFromGroup(m_selectedChannel, item->position(), groupDeleted); - qDebug() << "m_selectedChannel: " << m_selectedChannel << " deleted: " << m_currentGroup[item->position()]; - if (m_selectedChannel == m_currentGroup[item->position()] && !groupDeleted) { + qDebug() << "m_selectedChannel: " << m_selectedChannel + << " deleted: " << m_currentGroup[item->position()]; + if(m_selectedChannel == m_currentGroup[item->position()] && !groupDeleted) { m_ui->groupWidget->setVisible(false); } m_currentGroup.removeAt(item->position()); - if (groupDeleted) { + if(groupDeleted) { m_ui->groupWidget->setVisible(false); m_currentGroup.clear(); m_ui->groupWidgetLayout->removeWidget(m_currentGroupMenu); @@ -1024,9 +1007,7 @@ void PatternGenerator::setupPatterns() m_ui->patternComboBox->addItems(PatternFactory::get_ui_list()); connect(m_ui->patternComboBox, &QComboBox::currentTextChanged, - [=](const QString &pattern){ - patternSelected(pattern); - }); + [=](const QString &pattern) { patternSelected(pattern); }); } void PatternGenerator::updateChannelGroupPattern(bool visible) @@ -1039,8 +1020,8 @@ void PatternGenerator::updateChannelGroupPattern(bool visible) qDebug() << "Enabled patterns: " << m_enabledPatterns; qDebug() << "################################################################"; - for (const auto &ep : qAsConst(m_enabledPatterns)) { - if (ep.first.contains(m_selectedChannel)) { + for(const auto &ep : qAsConst(m_enabledPatterns)) { + if(ep.first.contains(m_selectedChannel)) { pattern = QString::fromStdString(ep.second->get_pattern()->get_name()); ep.second->setVisible(visible); } else { @@ -1060,13 +1041,13 @@ void PatternGenerator::updateChannelGroupPattern(bool visible) void PatternGenerator::updateGroupsAndPatterns() { QVector> allGroups = m_plot.getAllGroups(); - for (int i = 0; i < allGroups.size(); ++i) { + for(int i = 0; i < allGroups.size(); ++i) { PatternUI *firstFound = nullptr; - for (int c = 0; c < allGroups[i].size(); ++c) { + for(int c = 0; c < allGroups[i].size(); ++c) { int currentIndex = 0; - while (currentIndex < m_enabledPatterns.size()) { - if (m_enabledPatterns[currentIndex].first.contains(allGroups[i][c])) { - if (!firstFound) { + while(currentIndex < m_enabledPatterns.size()) { + if(m_enabledPatterns[currentIndex].first.contains(allGroups[i][c])) { + if(!firstFound) { firstFound = m_enabledPatterns[currentIndex].second; } m_enabledPatterns.removeAt(currentIndex); @@ -1075,7 +1056,7 @@ void PatternGenerator::updateGroupsAndPatterns() } } } - if (firstFound) { + if(firstFound) { m_enabledPatterns.append({allGroups[i], firstFound}); firstFound = nullptr; } @@ -1084,14 +1065,14 @@ void PatternGenerator::updateGroupsAndPatterns() generateBuffer(); regenerate(); -// qDebug() << "#### Update groups and patterns ####"; -// qDebug() << m_enabledPatterns; + // qDebug() << "#### Update groups and patterns ####"; + // qDebug() << m_enabledPatterns; } void PatternGenerator::channelInGroupChangedPosition(int from, int to) { - for (int i = 0; i < m_enabledPatterns.size(); ++i) { - if (m_enabledPatterns[i].first.contains(m_selectedChannel)) { + for(int i = 0; i < m_enabledPatterns.size(); ++i) { + if(m_enabledPatterns[i].first.contains(m_selectedChannel)) { auto item = m_enabledPatterns[i].first.takeAt(from); m_enabledPatterns[i].first.insert(to, item); break; @@ -1101,14 +1082,14 @@ void PatternGenerator::channelInGroupChangedPosition(int from, int to) generateBuffer(); regenerate(); -// qDebug() << "#### channel in group changed position ####"; -// qDebug() << m_enabledPatterns; + // qDebug() << "#### channel in group changed position ####"; + // qDebug() << m_enabledPatterns; } void PatternGenerator::channelInGroupRemoved(int position) { - for (int i = 0; i < m_enabledPatterns.size(); ++i) { - if (m_enabledPatterns[i].first.contains(m_selectedChannel)) { + for(int i = 0; i < m_enabledPatterns.size(); ++i) { + if(m_enabledPatterns[i].first.contains(m_selectedChannel)) { m_enabledPatterns[i].first.removeAt(position); break; } @@ -1123,7 +1104,6 @@ void PatternGenerator::channelInGroupRemoved(int position) void PatternGenerator::loadTriggerMenu() { -// auto trigger = m_m2kDigital->getOutTrigger(); + // auto trigger = m_m2kDigital->getOutTrigger(); // TODO: currently not available on libm2k master branch } - diff --git a/plugins/m2k/src/old/patterngenerator/pattern_generator.h b/plugins/m2k/src/old/patterngenerator/pattern_generator.h index 9665f8d274..d54026948c 100644 --- a/plugins/m2k/src/old/patterngenerator/pattern_generator.h +++ b/plugins/m2k/src/old/patterngenerator/pattern_generator.h @@ -18,26 +18,25 @@ * along with this program. If not, see . */ - #ifndef PATTERNGENERATOR_H #define PATTERNGENERATOR_H -#include "m2ktool.hpp" -#include "oscilloscope_plot.hpp" #include "buffer_previewer.hpp" +#include "gui/genericlogicplotcurve.h" #include "gui/spinbox_a.hpp" +#include "m2ktool.hpp" #include "mousewheelwidgetguard.h" -#include "gui/genericlogicplotcurve.h" +#include "oscilloscope_plot.hpp" + +#include +#include +#include +#include -#include #include #include #include - -#include -#include -#include -#include +#include using namespace libm2k; using namespace libm2k::digital; @@ -50,7 +49,7 @@ class PatternGenerator; namespace scopy { class BaseMenu; class CustomPushButton; -} +} // namespace scopy namespace scopy::m2k { class Filter; @@ -65,9 +64,9 @@ class PatternGenerator : public M2kTool Q_OBJECT friend class PatternGenerator_API; + public: - explicit PatternGenerator(struct iio_context *ctx, Filter *filt, - ToolMenuEntry *tme, QJSEngine *engine, + explicit PatternGenerator(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, QJSEngine *engine, DIOManager *diom, QWidget *parent); ~PatternGenerator(); void setNativeDialogs(bool nativeDialogs) override; @@ -86,7 +85,7 @@ private Q_SLOTS: void rightMenuFinished(bool opened); void channelSelectedChanged(int chIdx, bool selected); void on_btnGroupChannels_toggled(bool checked); - void patternSelected(const QString& pattern, int ch = -1, const QString &json = {}); + void patternSelected(const QString &pattern, int ch = -1, const QString &json = {}); void on_btnOutputMode_toggled(bool); void regenerate(); void readPreferences(); @@ -110,9 +109,7 @@ private Q_SLOTS: uint64_t computeSampleRate() const; uint64_t computeBufferSize(uint64_t sampleRate) const; uint16_t remapBuffer(uint8_t *mapping, uint32_t val); - void commitBuffer(const QPair, PatternUI *> &pattern, - uint16_t *buffer, - uint32_t bufferSize); + void commitBuffer(const QPair, PatternUI *> &pattern, uint16_t *buffer, uint32_t bufferSize); void checkEnabledChannels(); void removeAnnotationCurveOfPattern(PatternUI *pattern); void updateAnnotationCurveChannelsForPattern(const QPair, PatternUI *> &pattern); @@ -136,7 +133,7 @@ private Q_SLOTS: QVector, PatternUI *>> m_enabledPatterns; - M2k* m_m2k_context; + M2k *m_m2k_context; M2kDigital *m_m2kDigital; uint64_t m_bufferSize; uint64_t m_sampleRate; @@ -146,9 +143,9 @@ private Q_SLOTS: QTimer *m_singleTimer; - QMap> m_annotationCurvePatternUiMap; + QMap> m_annotationCurvePatternUiMap; }; } // namespace logic -} // namespace scopy +} // namespace scopy::m2k #endif // PATTERNGENERATOR_H diff --git a/plugins/m2k/src/old/patterngenerator/pattern_generator_api.cpp b/plugins/m2k/src/old/patterngenerator/pattern_generator_api.cpp index 2113a94221..4d04f122d5 100644 --- a/plugins/m2k/src/old/patterngenerator/pattern_generator_api.cpp +++ b/plugins/m2k/src/old/patterngenerator/pattern_generator_api.cpp @@ -18,12 +18,12 @@ * along with this program. If not, see . */ - #include "pattern_generator_api.h" -#include "ui_pattern_generator.h" #include "patterns/patterns.hpp" +#include "ui_pattern_generator.h" + #include using namespace scopy; @@ -31,15 +31,14 @@ using namespace scopy::m2k; using namespace scopy::logic; using namespace scopy::m2k::logic; - QList PatternGenerator_API::getEnabledChannels() const { QList enabledChannels; - for (int i = 0; i < 16; ++i) { - QWidget *widgetInLayout = m_pattern->m_ui->channelEnumeratorLayout->itemAtPosition(i % 8, - i / 8)->widget(); + for(int i = 0; i < 16; ++i) { + QWidget *widgetInLayout = + m_pattern->m_ui->channelEnumeratorLayout->itemAtPosition(i % 8, i / 8)->widget(); auto channelBox = dynamic_cast(widgetInLayout); - if (channelBox->isChecked()) { + if(channelBox->isChecked()) { enabledChannels.push_back(i); } } @@ -48,9 +47,9 @@ QList PatternGenerator_API::getEnabledChannels() const void PatternGenerator_API::setEnabledChannels(const QList &enabledChannels) { - for (const auto &channel : enabledChannels) { - QWidget *widgetInLayout = m_pattern->m_ui->channelEnumeratorLayout->itemAtPosition(channel % 8, - channel / 8)->widget(); + for(const auto &channel : enabledChannels) { + QWidget *widgetInLayout = + m_pattern->m_ui->channelEnumeratorLayout->itemAtPosition(channel % 8, channel / 8)->widget(); auto channelBox = dynamic_cast(widgetInLayout); channelBox->setChecked(true); } @@ -59,7 +58,7 @@ void PatternGenerator_API::setEnabledChannels(const QList &enabledChannels) QStringList PatternGenerator_API::getChannelNames() const { QStringList names; - for (int i = 0; i < m_pattern->m_plotCurves.size(); ++i) { + for(int i = 0; i < m_pattern->m_plotCurves.size(); ++i) { names.push_back(m_pattern->m_plotCurves[i]->getName()); } return names; @@ -67,8 +66,10 @@ QStringList PatternGenerator_API::getChannelNames() const void PatternGenerator_API::setChannelNames(const QStringList &channelNames) { - for (int i = 0; i < channelNames.size(); ++i) { - if (i >= m_pattern->m_plotCurves.size()) { break; } + for(int i = 0; i < channelNames.size(); ++i) { + if(i >= m_pattern->m_plotCurves.size()) { + break; + } m_pattern->m_plotCurves[i]->setName(channelNames[i]); } } @@ -76,7 +77,7 @@ void PatternGenerator_API::setChannelNames(const QStringList &channelNames) QList PatternGenerator_API::getChannelHeights() const { QList heights; - for (int i = 0; i < m_pattern->m_plotCurves.size(); ++i) { + for(int i = 0; i < m_pattern->m_plotCurves.size(); ++i) { heights.push_back(m_pattern->m_plotCurves[i]->getTraceHeight()); } return heights; @@ -84,8 +85,10 @@ QList PatternGenerator_API::getChannelHeights() const void PatternGenerator_API::setChannelHeights(const QList &channelHeights) { - for (int i = 0; i < channelHeights.size(); ++i) { - if (i >= m_pattern->m_plotCurves.size()) { break; } + for(int i = 0; i < channelHeights.size(); ++i) { + if(i >= m_pattern->m_plotCurves.size()) { + break; + } m_pattern->m_plotCurves[i]->setTraceHeight(channelHeights[i]); } } @@ -93,7 +96,7 @@ void PatternGenerator_API::setChannelHeights(const QList &channelHeights QList PatternGenerator_API::getChannelPosition() const { QList channelPosition; - for (int i = 0; i < m_pattern->m_plotCurves.size(); ++i) { + for(int i = 0; i < m_pattern->m_plotCurves.size(); ++i) { channelPosition.push_back(m_pattern->m_plotCurves[i]->getPixelOffset()); } return channelPosition; @@ -101,18 +104,20 @@ QList PatternGenerator_API::getChannelPosition() const void PatternGenerator_API::setChannelPosition(const QList &channelPosition) { - for (int i = 0; i < channelPosition.size(); ++i) { - if (i >= m_pattern->m_plotCurves.size()) { break; } + for(int i = 0; i < channelPosition.size(); ++i) { + if(i >= m_pattern->m_plotCurves.size()) { + break; + } m_pattern->m_plotCurves[i]->setPixelOffset(channelPosition[i]); } } -QVector > PatternGenerator_API::getCurrentGroups() const +QVector> PatternGenerator_API::getCurrentGroups() const { - QVector > groups = m_pattern->m_plot.getAllGroups(); - for (auto &group : groups) { - for (auto &ch : group) { - if (ch >= 16) { + QVector> groups = m_pattern->m_plot.getAllGroups(); + for(auto &group : groups) { + for(auto &ch : group) { + if(ch >= 16) { group.removeOne(ch); } } @@ -120,35 +125,27 @@ QVector > PatternGenerator_API::getCurrentGroups() const return groups; } -void PatternGenerator_API::setCurrentGroups(const QVector > &groups) +void PatternGenerator_API::setCurrentGroups(const QVector> &groups) { m_pattern->m_plot.setGroups(groups); } -QVector, QString> > PatternGenerator_API::getEnabledPatterns() const +QVector, QString>> PatternGenerator_API::getEnabledPatterns() const { - QVector, QString> > enabledPatterns; - for (const QPair, PatternUI *> &pattern : qAsConst(m_pattern->m_enabledPatterns)) { - enabledPatterns.push_back({pattern.first, - Pattern_API::toString(pattern.second->get_pattern())}); + QVector, QString>> enabledPatterns; + for(const QPair, PatternUI *> &pattern : qAsConst(m_pattern->m_enabledPatterns)) { + enabledPatterns.push_back({pattern.first, Pattern_API::toString(pattern.second->get_pattern())}); } return enabledPatterns; } -void PatternGenerator_API::setEnabledPatterns(const QVector, QString> > &enabledPatterns) +void PatternGenerator_API::setEnabledPatterns(const QVector, QString>> &enabledPatterns) { - for (const QPair, QString> &pattern : enabledPatterns) { + for(const QPair, QString> &pattern : enabledPatterns) { m_pattern->patternSelected("", pattern.first.first(), pattern.second); } } -QString PatternGenerator_API::getNotes() -{ - return m_pattern->m_ui->instrumentNotes->getNotes(); -} -void PatternGenerator_API::setNotes(QString str) -{ - m_pattern->m_ui->instrumentNotes->setNotes(str); -} - +QString PatternGenerator_API::getNotes() { return m_pattern->m_ui->instrumentNotes->getNotes(); } +void PatternGenerator_API::setNotes(QString str) { m_pattern->m_ui->instrumentNotes->setNotes(str); } diff --git a/plugins/m2k/src/old/patterngenerator/pattern_generator_api.h b/plugins/m2k/src/old/patterngenerator/pattern_generator_api.h index 70850810f8..6bd2d1fa03 100644 --- a/plugins/m2k/src/old/patterngenerator/pattern_generator_api.h +++ b/plugins/m2k/src/old/patterngenerator/pattern_generator_api.h @@ -18,7 +18,6 @@ * along with this program. If not, see . */ - #ifndef PATTERNGENERATOR_API_H #define PATTERNGENERATOR_API_H @@ -37,8 +36,8 @@ class PatternGenerator_API : public ApiObject Q_PROPERTY(QVector> currentGroups READ getCurrentGroups WRITE setCurrentGroups) /* patterns from json */ - Q_PROPERTY(QVector, QString>> enabledPatterns READ getEnabledPatterns - WRITE setEnabledPatterns) + Q_PROPERTY( + QVector, QString>> enabledPatterns READ getEnabledPatterns WRITE setEnabledPatterns) /* common patterns + channels */ Q_PROPERTY(QStringList channelNames READ getChannelNames WRITE setChannelNames) @@ -47,11 +46,11 @@ class PatternGenerator_API : public ApiObject Q_PROPERTY(QString notes READ getNotes WRITE setNotes) - public: explicit PatternGenerator_API(logic::PatternGenerator *pattern) : ApiObject() - , m_pattern(pattern) { + , m_pattern(pattern) + { qRegisterMetaType>("vector(int)"); qRegisterMetaTypeStreamOperators>("vector(int)"); qRegisterMetaType>>("vector(vector(int))"); @@ -60,8 +59,8 @@ class PatternGenerator_API : public ApiObject qRegisterMetaType, QString>>("pair(vector(int), string)"); qRegisterMetaTypeStreamOperators, QString>>("pair(vector(int), string)"); qRegisterMetaType, QString>>>("vector(pair(vector(int), string))"); - qRegisterMetaTypeStreamOperators, QString>>>("vector(pair(vector(int), string))"); - + qRegisterMetaTypeStreamOperators, QString>>>( + "vector(pair(vector(int), string))"); } ~PatternGenerator_API() {} @@ -78,7 +77,7 @@ class PatternGenerator_API : public ApiObject void setChannelPosition(const QList &channelPosition); QVector> getCurrentGroups() const; - void setCurrentGroups(const QVector > &groups); + void setCurrentGroups(const QVector> &groups); QVector, QString>> getEnabledPatterns() const; void setEnabledPatterns(const QVector, QString>> &enabledPatterns); @@ -89,6 +88,6 @@ class PatternGenerator_API : public ApiObject private: logic::PatternGenerator *m_pattern; }; -} // namespace logic +} // namespace scopy::m2k::logic #endif // PATTERNGENERATOR_API_H diff --git a/plugins/m2k/src/old/patterngenerator/patterns/patterns.cpp b/plugins/m2k/src/old/patterngenerator/patterns/patterns.cpp index 21a43abf98..25de487a02 100644 --- a/plugins/m2k/src/old/patterngenerator/patterns/patterns.cpp +++ b/plugins/m2k/src/old/patterngenerator/patterns/patterns.cpp @@ -18,22 +18,23 @@ * along with this program. If not, see . */ +#include "patterns.hpp" + +#include "gui/dynamicWidget.h" +#include "sigrok-gui/annotationcurve.h" +#include "sigrok-gui/annotationdecoder.h" + #include -#include -#include -#include -#include -#include #include +#include #include +#include #include +#include +#include +#include #include -#include "patterns.hpp" -#include "sigrok-gui/annotationcurve.h" -#include "sigrok-gui/annotationdecoder.h" -#include "gui/dynamicWidget.h" - #include using namespace std; @@ -43,15 +44,11 @@ constexpr int PG_MAX_SAMPLERATE = 100000000; // 100MHz namespace scopy::m2k { -JSConsole::JSConsole(QObject *parent) : - QObject(parent) -{ -} +JSConsole::JSConsole(QObject *parent) + : QObject(parent) +{} -void JSConsole::log(QString msg) -{ - qDebug() << "jsConsole: "<< msg; -} +void JSConsole::log(QString msg) { qDebug() << "jsConsole: " << msg; } Pattern::Pattern() { @@ -63,101 +60,58 @@ Pattern::Pattern() Pattern::~Pattern() { - //qDebug()<<"PatternDestroyed"; + // qDebug()<<"PatternDestroyed"; delete_buffer(); } -string Pattern::get_name() -{ - return name; -} +string Pattern::get_name() { return name; } -void Pattern::set_name(const string &name_) -{ - name = name_; -} +void Pattern::set_name(const string &name_) { name = name_; } -string Pattern::get_description() -{ - return description; -} +string Pattern::get_description() { return description; } -void Pattern::set_description(const string &description_) -{ - description = description_; -} - -void Pattern::init() -{ - -} +void Pattern::set_description(const string &description_) { description = description_; } -void Pattern::deinit() -{ +void Pattern::init() {} -} +void Pattern::deinit() {} -bool Pattern::is_periodic() -{ - return periodic; -} +bool Pattern::is_periodic() { return periodic; } -void Pattern::set_periodic(bool periodic_) -{ - periodic=periodic_; -} +void Pattern::set_periodic(bool periodic_) { periodic = periodic_; } -short *Pattern::get_buffer() -{ - return buffer; -} +short *Pattern::get_buffer() { return buffer; } void Pattern::delete_buffer() { - if (buffer) { + if(buffer) { delete[] buffer; } - buffer=nullptr; + buffer = nullptr; } -uint8_t Pattern::pre_generate() -{ - return 0; -} +uint8_t Pattern::pre_generate() { return 0; } -std::string Pattern::toString() -{ - return ""; -} +std::string Pattern::toString() { return ""; } -bool Pattern::fromString(std::string from) -{ - return 0; -} +bool Pattern::fromString(std::string from) { return 0; } -int Pattern::nrOfChannels() const -{ - return channels; -} +int Pattern::nrOfChannels() const { return channels; } -void Pattern::setNrOfChannels(int channels) -{ - this->channels = channels; -} +void Pattern::setNrOfChannels(int channels) { this->channels = channels; } uint32_t Pattern::get_min_sampling_freq() { return 1000; // minimum 1 kHz if not specified otherwise } -uint32_t Pattern::get_required_nr_of_samples(uint32_t sample_rate, - uint32_t number_of_channels) +uint32_t Pattern::get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels) { return 0; // 0 samples required } -uint32_t changeBit(uint32_t number,uint8_t n, bool x) +uint32_t changeBit(uint32_t number, uint8_t n, bool x) { number ^= (-x ^ number) & (1 << n); return number; @@ -177,9 +131,8 @@ Pattern *Pattern_API::fromString(QString str) QJsonObject obj; QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8()); - - if (!doc.isNull()) { - if (doc.isObject()) { + if(!doc.isNull()) { + if(doc.isObject()) { obj = doc.object(); } else { qDebug() << "Document is not an object" << Qt::endl; @@ -216,79 +169,79 @@ QJsonValue Pattern_API::toJson(Pattern *p) QJsonObject params; - if (cp) { + if(cp) { obj["name"] = QString::fromStdString(p->get_name()); - params["freq"] = QJsonValue(cp->get_frequency()); - params["duty"] = QJsonValue(cp->get_duty_cycle()); + params["freq"] = QJsonValue(cp->get_frequency()); + params["duty"] = QJsonValue(cp->get_duty_cycle()); params["phase"] = QJsonValue(cp->get_phase()); obj["params"] = QJsonValue(params); - } else if (np) { + } else if(np) { obj["name"] = QString::fromStdString(p->get_name()); - params["nr"] = QJsonValue((qint64)np->get_nr()); + params["nr"] = QJsonValue((qint64)np->get_nr()); obj["params"] = QJsonValue(params); - } else if (rp) { + } else if(rp) { obj["name"] = QString::fromStdString(p->get_name()); - params["freq"] = QJsonValue((qint64)rp->get_frequency()); + params["freq"] = QJsonValue((qint64)rp->get_frequency()); obj["params"] = QJsonValue(params); - } else if (bcp) { + } else if(bcp) { obj["name"] = QString::fromStdString(p->get_name()); - params["freq"] = QJsonValue((qint64)bcp->get_frequency()); + params["freq"] = QJsonValue((qint64)bcp->get_frequency()); obj["params"] = QJsonValue(params); - } else if (gcp) { + } else if(gcp) { obj["name"] = QString::fromStdString(p->get_name()); - params["freq"] = QJsonValue((qint64)gcp->get_frequency()); + params["freq"] = QJsonValue((qint64)gcp->get_frequency()); obj["params"] = QJsonValue(params); - } else if (up) { + } else if(up) { obj["name"] = QString::fromStdString(p->get_name()); params["uart"] = QString::fromStdString(up->get_params()); params["string"] = QString::fromStdString(up->get_string()); obj["params"] = QJsonValue(params); - } else if (sp) { + } else if(sp) { obj["name"] = QString::fromStdString(p->get_name()); - params["BPF"]=sp->getBytesPerFrame(); - params["IFS"]=sp->getWaitClocks(); - params["freq"]= QJsonValue((qint64)sp->getClkFrequency()); - params["CPHA"]=sp->getCPHA(); - params["CPOL"]=sp->getCPOL(); - params["CS"]=sp->getCSPol(); - params["MSB"]=sp->getMsbFirst(); + params["BPF"] = sp->getBytesPerFrame(); + params["IFS"] = sp->getWaitClocks(); + params["freq"] = QJsonValue((qint64)sp->getClkFrequency()); + params["CPHA"] = sp->getCPHA(); + params["CPOL"] = sp->getCPOL(); + params["CS"] = sp->getCSPol(); + params["MSB"] = sp->getMsbFirst(); QJsonArray spi; - for (auto val : sp->v) { + for(auto val : sp->v) { spi.append(val); } - params["v"]=spi; + params["v"] = spi; obj["params"] = QJsonValue(params); - } else if (ip) { + } else if(ip) { obj["name"] = QString::fromStdString(p->get_name()); - params["BPF"]=ip->getBytesPerFrame(); - params["IFS"]=ip->getInterFrameSpace(); - params["freq"]= QJsonValue((qint64)ip->getClkFrequency()); - params["MSB"]=ip->getMsbFirst(); - params["write"]=ip->getWrite(); - params["address"]=ip->getAddress(); + params["BPF"] = ip->getBytesPerFrame(); + params["IFS"] = ip->getInterFrameSpace(); + params["freq"] = QJsonValue((qint64)ip->getClkFrequency()); + params["MSB"] = ip->getMsbFirst(); + params["write"] = ip->getWrite(); + params["address"] = ip->getAddress(); QJsonArray i2c; - for (auto val : ip->v) { + for(auto val : ip->v) { i2c.append(val); } - params["v"]=i2c; + params["v"] = i2c; obj["params"] = QJsonValue(params); - } else if (imp) { + } else if(imp) { obj["name"] = QString::fromStdString(imp->get_name()); - params["frequency"] = QJsonValue((qint64)imp->get_frequency()); + params["frequency"] = QJsonValue((qint64)imp->get_frequency()); params["file"] = imp->fileName; params["channel_mapping"] = QJsonValue((imp->channel_mapping)); obj["params"] = QJsonValue(params); - } else if (pp) { + } else if(pp) { obj["name"] = QString::fromStdString(pp->get_name()); params["sample_rate"] = pp->get_sample_rate(); params["high"] = QJsonValue((qint32)pp->get_high_number_of_samples()); @@ -303,12 +256,13 @@ QJsonValue Pattern_API::toJson(Pattern *p) obj["name"] = "none"; } - return QJsonValue(obj);; + return QJsonValue(obj); + ; } Pattern *Pattern_API::fromJson(QJsonObject obj) { - //QJsonObject obj = j.toObject(); + // QJsonObject obj = j.toObject(); Pattern *p = PatternFactory::create(obj["name"].toString()); ClockPattern *cp = dynamic_cast(p); @@ -324,22 +278,22 @@ Pattern *Pattern_API::fromJson(QJsonObject obj) QJsonObject params = obj["params"].toObject(); - if (cp) { + if(cp) { cp->set_frequency(params["freq"].toDouble()); cp->set_duty_cycle(params["duty"].toDouble()); cp->set_phase(params["phase"].toInt()); - } else if (np) { + } else if(np) { np->set_nr(params["nr"].toInt()); - } else if (rp) { + } else if(rp) { rp->set_frequency(params["freq"].toInt()); - } else if (bcp) { + } else if(bcp) { bcp->set_frequency(params["freq"].toInt()); - } else if (gcp) { + } else if(gcp) { gcp->set_frequency(params["freq"].toInt()); - } else if (up) { + } else if(up) { up->set_string(params["string"].toString().toStdString()); up->set_params(params["uart"].toString().toStdString()); - } else if (sp) { + } else if(sp) { sp->setBytesPerFrame(params["BPF"].toInt()); sp->setClkFrequency(params["freq"].toInt()); sp->setWaitClocks(params["IFS"].toInt()); @@ -349,10 +303,10 @@ Pattern *Pattern_API::fromJson(QJsonObject obj) sp->setMsbFirst(params["MSB"].toBool()); auto paramsContainer = params["v"].toArray(); - for (const auto &val : qAsConst(paramsContainer)) { + for(const auto &val : qAsConst(paramsContainer)) { sp->v.push_back(val.toInt()); } - } else if (ip) { + } else if(ip) { ip->setBytesPerFrame(params["BPF"].toInt()); ip->setClkFrequency(params["freq"].toInt()); ip->setInterFrameSpace(params["IFS"].toInt()); @@ -361,14 +315,14 @@ Pattern *Pattern_API::fromJson(QJsonObject obj) ip->setWrite(params["write"].toBool()); auto paramsContainer = params["v"].toArray(); - for (const auto &val : qAsConst(paramsContainer)) { + for(const auto &val : qAsConst(paramsContainer)) { ip->v.push_back(val.toInt()); } - } else if (imp) { + } else if(imp) { imp->fileName = params["file"].toString(); imp->channel_mapping = params["channel_mapping"].toInt(); imp->setFrequency(params["frequency"].toDouble()); - } else if (pp) { + } else if(pp) { pp->set_counter_init(params["cnt_init"].toInt()); pp->set_high_number_of_samples(params["high"].toInt()); pp->set_low_number_of_samples(params["low"].toInt()); @@ -381,81 +335,68 @@ Pattern *Pattern_API::fromJson(QJsonObject obj) return p; } -PatternUI::PatternUI(QWidget *parent) : QWidget(parent) +PatternUI::PatternUI(QWidget *parent) + : QWidget(parent) { - qDebug()<<"PatternUICreated"; + qDebug() << "PatternUICreated"; } -PatternUI::~PatternUI() -{ - qDebug()<<"PatternUIDestroyed"; -} +PatternUI::~PatternUI() { qDebug() << "PatternUIDestroyed"; } -void PatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) {} +void PatternUI::build_ui(QWidget *parent, uint16_t number_of_channels) {} void PatternUI::post_load_ui() {} void PatternUI::parse_ui() {} void PatternUI::destroy_ui() {} uint32_t ClockPattern::get_min_sampling_freq() { - return frequency * std::lcm(duty_cycle_granularity,phase_granularity); + return frequency * std::lcm(duty_cycle_granularity, phase_granularity); } -uint32_t ClockPattern::get_required_nr_of_samples(uint32_t sample_rate, - uint32_t number_of_channels) +uint32_t ClockPattern::get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels) { // greatest common divider duty cycle and 1000;0; - uint32_t period_number_of_samples = (uint32_t)sample_rate/frequency; + uint32_t period_number_of_samples = (uint32_t)sample_rate / frequency; return period_number_of_samples; } -float ClockPattern::get_duty_cycle() const -{ - return duty_cycle; -} +float ClockPattern::get_duty_cycle() const { return duty_cycle; } void ClockPattern::set_duty_cycle(float value) { - if (value>100) { + if(value > 100) { value = 100; } duty_cycle = value; auto max = 100; - duty_cycle_granularity = 100/std::gcd((int)value, max); + duty_cycle_granularity = 100 / std::gcd((int)value, max); } -float ClockPattern::get_frequency() const -{ - return frequency; -} +float ClockPattern::get_frequency() const { return frequency; } void ClockPattern::set_frequency(float value) { static const int frequency_precision = 1000; - frequency = round(value * frequency_precision)/ frequency_precision; + frequency = round(value * frequency_precision) / frequency_precision; } -int ClockPattern::get_phase() const -{ - return phase; -} +int ClockPattern::get_phase() const { return phase; } void ClockPattern::set_phase(int value) { phase = value; - if (phase>360) { - phase = phase%360; + if(phase > 360) { + phase = phase % 360; } - if (phase<0) { - phase = 360-(abs(phase)%360); + if(phase < 0) { + phase = 360 - (abs(phase) % 360); } - auto max=360; - phase_granularity=360/std::gcd((int)phase,max); - + auto max = 360; + phase_granularity = 360 / std::gcd((int)phase, max); } ClockPattern::ClockPattern() @@ -468,73 +409,61 @@ ClockPattern::ClockPattern() set_phase(0); } -ClockPattern::~ClockPattern() -{ - -} - +ClockPattern::~ClockPattern() {} -uint8_t ClockPattern::generate_pattern(uint32_t sample_rate, - uint32_t number_of_samples, uint16_t number_of_channels) +uint8_t ClockPattern::generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels) { - float f_period_number_of_samples = (float)sample_rate/frequency; - qDebug()<<"period_number_of_samples - "<setupUi(this); - frequencySpinButton = new ScaleSpinButton({ - {"Hz", 1E0}, - {"kHz", 1E+3}, - {"MHz", 1E+6} - }, tr("Frequency"), 1e0, PG_MAX_SAMPLERATE/2,true,false,this, {1,2.5,5}); + frequencySpinButton = new ScaleSpinButton({{"Hz", 1E0}, {"kHz", 1E+3}, {"MHz", 1E+6}}, tr("Frequency"), 1e0, + PG_MAX_SAMPLERATE / 2, true, false, this, {1, 2.5, 5}); ui->verticalLayout->addWidget(frequencySpinButton); - phaseSpinButton = new PhaseSpinButton({ - {"deg",1}, - {"Ï€ rad",180} - },tr("Phase"),0,360,true,true,this); + phaseSpinButton = new PhaseSpinButton({{"deg", 1}, {"Ï€ rad", 180}}, tr("Phase"), 0, 360, true, true, this); phaseSpinButton->setFineModeAvailable(false); ui->verticalLayout->addWidget(phaseSpinButton); - dutySpinButton = new PositionSpinButton({{"%",1}},tr("Duty"),0,100,true,false,this); + dutySpinButton = new PositionSpinButton({{"%", 1}}, tr("Duty"), 0, 100, true, false, this); dutySpinButton->setFineModeAvailable(false); ui->verticalLayout->addWidget(dutySpinButton); requestedDuty = 50; @@ -545,36 +474,28 @@ ClockPatternUI::ClockPatternUI(ClockPattern *pattern, ClockPatternUI::~ClockPatternUI() { - //qDebug()<<"ClockPatternUI destroyed"; + // qDebug()<<"ClockPatternUI destroyed"; delete ui; } -Pattern *ClockPatternUI::get_pattern() -{ - return pattern; -} +Pattern *ClockPatternUI::get_pattern() { return pattern; } -void ClockPatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) +void ClockPatternUI::build_ui(QWidget *parent, uint16_t number_of_channels) { parent_ = parent; parent->layout()->addWidget(this); - requestedFrequency=pattern->get_frequency(); - requestedPhase=pattern->get_phase(); - requestedDuty=pattern->get_duty_cycle(); + requestedFrequency = pattern->get_frequency(); + requestedPhase = pattern->get_phase(); + requestedDuty = pattern->get_duty_cycle(); frequencySpinButton->setValue(pattern->get_frequency()); phaseSpinButton->setValue(pattern->get_phase()); dutySpinButton->setValue(pattern->get_duty_cycle()); - connect(frequencySpinButton,SIGNAL(valueChanged(double)),this,SLOT(parse_ui())); - connect(phaseSpinButton,SIGNAL(valueChanged(double)),this,SLOT(parse_ui())); - connect(dutySpinButton,SIGNAL(valueChanged(double)),this,SLOT(parse_ui())); - - -} -void ClockPatternUI::destroy_ui() -{ - parent_->layout()->removeWidget(this); + connect(frequencySpinButton, SIGNAL(valueChanged(double)), this, SLOT(parse_ui())); + connect(phaseSpinButton, SIGNAL(valueChanged(double)), this, SLOT(parse_ui())); + connect(dutySpinButton, SIGNAL(valueChanged(double)), this, SLOT(parse_ui())); } +void ClockPatternUI::destroy_ui() { parent_->layout()->removeWidget(this); } void ClockPatternUI::parse_ui() { @@ -582,45 +503,43 @@ void ClockPatternUI::parse_ui() bool freqStepDown = false; bool phaseStepDown = true; - bool phaseNoChange = true; + bool phaseNoChange = true; bool freqChange = false; double oldPhase = 0; - - if (obj==frequencySpinButton) { - if (frequencySpinButton->value() < requestedFrequency) { - freqStepDown=true; + if(obj == frequencySpinButton) { + if(frequencySpinButton->value() < requestedFrequency) { + freqStepDown = true; } requestedFrequency = frequencySpinButton->value(); - freqChange=true; + freqChange = true; } - if (obj==phaseSpinButton) { + if(obj == phaseSpinButton) { oldPhase = requestedPhase; - requestedPhase=phaseSpinButton->value(); + requestedPhase = phaseSpinButton->value(); phaseNoChange = false; phaseStepDown = phaseSpinButton->isStepDown(); } - if (obj==dutySpinButton) { - requestedDuty=dutySpinButton->value(); + if(obj == dutySpinButton) { + requestedDuty = dutySpinButton->value(); } - auto freq=requestedFrequency;//frequencySpinButton->value(); + auto freq = requestedFrequency; // frequencySpinButton->value(); long div; - if(freqChange) - { - if (freqStepDown) { - div=(long)ceil((double)PG_MAX_SAMPLERATE/freq); + if(freqChange) { + if(freqStepDown) { + div = (long)ceil((double)PG_MAX_SAMPLERATE / freq); } else { - div=(long)floor((double)PG_MAX_SAMPLERATE/freq); + div = (long)floor((double)PG_MAX_SAMPLERATE / freq); } - freq=(PG_MAX_SAMPLERATE)/(float)div; - requestedFrequency=freq; + freq = (PG_MAX_SAMPLERATE) / (float)div; + requestedFrequency = freq; frequencySpinButton->blockSignals(true); frequencySpinButton->setValue(freq); @@ -629,11 +548,11 @@ void ClockPatternUI::parse_ui() } pattern->set_frequency(freq); - auto dutystep=100.0/ (PG_MAX_SAMPLERATE / pattern->get_frequency()); - dutystep=(dutystep>1 ? dutystep : 1); - dutystep=floor(dutystep*100+0.5)/100.0; - auto dutyval = requestedDuty;//dutySpinButton->value(); - dutyval=floor((dutyval/dutystep) +0.5)*dutystep; + auto dutystep = 100.0 / (PG_MAX_SAMPLERATE / pattern->get_frequency()); + dutystep = (dutystep > 1 ? dutystep : 1); + dutystep = floor(dutystep * 100 + 0.5) / 100.0; + auto dutyval = requestedDuty; // dutySpinButton->value(); + dutyval = floor((dutyval / dutystep) + 0.5) * dutystep; dutySpinButton->blockSignals(true); dutySpinButton->setStep(dutystep); @@ -642,7 +561,6 @@ void ClockPatternUI::parse_ui() dutySpinButton->blockSignals(false); pattern->set_duty_cycle(dutySpinButton->value()); - /*auto phaseStep=360.0/ (PG_MAX_SAMPLERATE / pattern->get_frequency()); phaseStep=(phaseStep>1 ? phaseStep : 1); phaseStep=floor(phaseStep*360+0.5)/360.0; @@ -668,72 +586,63 @@ void ClockPatternUI::parse_ui() } }*/ - auto phaseStep=360.0/ (PG_MAX_SAMPLERATE / pattern->get_frequency()); - phaseStep=(phaseStep>1 ? phaseStep : 1); - phaseStep=floor(phaseStep*360+0.5)/360.0; + auto phaseStep = 360.0 / (PG_MAX_SAMPLERATE / pattern->get_frequency()); + phaseStep = (phaseStep > 1 ? phaseStep : 1); + phaseStep = floor(phaseStep * 360 + 0.5) / 360.0; auto phaseVal = requestedPhase; - if(fmod(requestedPhase, phaseStep) != 0) - { - if(phaseStep > 45) - { + if(fmod(requestedPhase, phaseStep) != 0) { + if(phaseStep > 45) { if(phaseStepDown) - phaseVal = floor((phaseVal/phaseStep)-0.5)*phaseStep; + phaseVal = floor((phaseVal / phaseStep) - 0.5) * phaseStep; else - phaseVal = ceil((phaseVal/phaseStep)+0.5)*phaseStep; - } - else - { - phaseVal = floor((phaseVal/phaseStep)+0.5)*phaseStep; + phaseVal = ceil((phaseVal / phaseStep) + 0.5) * phaseStep; + } else { + phaseVal = floor((phaseVal / phaseStep) + 0.5) * phaseStep; } requestedPhase = phaseVal; phaseSpinButton->blockSignals(true); phaseSpinButton->setStep(phaseStep); phaseSpinButton->setValue(phaseVal); - if (phaseVal >= 360) phaseVal = (int)phaseVal % 360; - } + if(phaseVal >= 360) + phaseVal = (int)phaseVal % 360; + } phaseSpinButton->updateCompletionCircle(phaseVal); phaseSpinButton->blockSignals(false); pattern->set_phase(phaseSpinButton->value()); Q_EMIT patternParamsChanged(); - } +uint16_t NumberPattern::get_nr() const { return nr; } -uint16_t NumberPattern::get_nr() const -{ - return nr; -} - -void NumberPattern::set_nr(const uint16_t& value) -{ - nr = value; -} +void NumberPattern::set_nr(const uint16_t &value) { nr = value; } -NumberPattern::NumberPattern() : nr(0) +NumberPattern::NumberPattern() + : nr(0) { set_name(NumberPatternName); set_description(NumberPatternDescription); set_periodic(false); } -uint8_t NumberPattern::generate_pattern(uint32_t sample_rate, - uint32_t number_of_samples, uint16_t number_of_channels) +uint8_t NumberPattern::generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels) { delete_buffer(); buffer = new short[number_of_samples]; - for (size_t i=0; isetupUi(this); setVisible(false); @@ -741,44 +650,36 @@ NumberPatternUI::NumberPatternUI(NumberPattern *pattern, NumberPatternUI::~NumberPatternUI() { - qDebug()<<"NumberPatternUI destroyed"; + qDebug() << "NumberPatternUI destroyed"; delete ui; } -Pattern *NumberPatternUI::get_pattern() -{ - return pattern; -} - - +Pattern *NumberPatternUI::get_pattern() { return pattern; } -void NumberPatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) +void NumberPatternUI::build_ui(QWidget *parent, uint16_t number_of_channels) { parent_ = parent; parent->layout()->addWidget(this); - max = (1<numberLineEdit->setValidator(new QIntValidator(0, max, this)); + max = (1 << number_of_channels) - 1; + qDebug() << max; + // ui->numberLineEdit->setValidator(new QIntValidator(0, max, this)); ui->numberLineEdit->setText(QString::number(pattern->get_nr())); - connect(ui->numberLineEdit,SIGNAL(textChanged(QString)),this,SLOT(parse_ui())); -} -void NumberPatternUI::destroy_ui() -{ - parent_->layout()->removeWidget(this); + connect(ui->numberLineEdit, SIGNAL(textChanged(QString)), this, SLOT(parse_ui())); } +void NumberPatternUI::destroy_ui() { parent_->layout()->removeWidget(this); } void NumberPatternUI::parse_ui() { - bool ok =0; + bool ok = 0; - auto val = ui->numberLineEdit->text().toInt(&ok,10); + auto val = ui->numberLineEdit->text().toInt(&ok, 10); - if (!ok) { - qDebug()<<"Cannot set frequency, not an int"; + if(!ok) { + qDebug() << "Cannot set frequency, not an int"; } max = (1 << pattern->nrOfChannels()) - 1; - if (val <= max && ok) { + if(val <= max && ok) { setDynamicProperty(ui->numberLineEdit, "valid", true); setDynamicProperty(ui->numberLineEdit, "invalid", false); } else { @@ -799,84 +700,61 @@ RandomPattern::RandomPattern() set_frequency(5000); } -RandomPattern::~RandomPattern() -{ -} - - -uint32_t RandomPattern::get_min_sampling_freq() -{ +RandomPattern::~RandomPattern() {} - return frequency; -} +uint32_t RandomPattern::get_min_sampling_freq() { return frequency; } -uint32_t RandomPattern::get_required_nr_of_samples(uint32_t sample_rate, - uint32_t number_of_channels) +uint32_t RandomPattern::get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels) { - uint32_t period_number_of_samples = (uint32_t)sample_rate/frequency; - return period_number_of_samples*10; + uint32_t period_number_of_samples = (uint32_t)sample_rate / frequency; + return period_number_of_samples * 10; } -uint32_t RandomPattern::get_frequency() const -{ - return frequency; -} +uint32_t RandomPattern::get_frequency() const { return frequency; } -void RandomPattern::set_frequency(const uint32_t& value) -{ - frequency = value; -} +void RandomPattern::set_frequency(const uint32_t &value) { frequency = value; } -uint8_t RandomPattern::generate_pattern(uint32_t sample_rate, - uint32_t number_of_samples, uint16_t number_of_channels) +uint8_t RandomPattern::generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels) { delete_buffer(); buffer = new short[number_of_samples]; - auto samples_per_count = (int)round(((float)sample_rate/(float)frequency)); - size_t j=0; + auto samples_per_count = (int)round(((float)sample_rate / (float)frequency)); + size_t j = 0; - while (j=number_of_samples) { + for(auto k = 0; k < samples_per_count; k++, j++) { + if(j >= number_of_samples) { break; } buffer[j] = random_value; } - } return 0; } -RandomPatternUI::RandomPatternUI(RandomPattern *pattern, - QWidget *parent): pattern(pattern),parent_(parent) +RandomPatternUI::RandomPatternUI(RandomPattern *pattern, QWidget *parent) + : pattern(pattern) + , parent_(parent) { - //qDebug()<<"RandomPatternUI created"; + // qDebug()<<"RandomPatternUI created"; ui = new Ui::EmptyPatternUI(); ui->setupUi(this); setVisible(false); - frequencySpinButton = new ScaleSpinButton({ - {"Hz", 1E0}, - {"kHz", 1E+3}, - {"MHz", 1E+6} - }, tr("Frequency"), 1e0, PG_MAX_SAMPLERATE/2,true,false,this, {1,2.5,5}); + frequencySpinButton = new ScaleSpinButton({{"Hz", 1E0}, {"kHz", 1E+3}, {"MHz", 1E+6}}, tr("Frequency"), 1e0, + PG_MAX_SAMPLERATE / 2, true, false, this, {1, 2.5, 5}); ui->verticalLayout->addWidget(frequencySpinButton); } RandomPatternUI::~RandomPatternUI() { - //qDebug()<<"NumberPatternUI destroyed"; + // qDebug()<<"NumberPatternUI destroyed"; delete ui; } - -Pattern *RandomPatternUI::get_pattern() -{ - return pattern; -} - +Pattern *RandomPatternUI::get_pattern() { return pattern; } void RandomPatternUI::parse_ui() { @@ -884,84 +762,43 @@ void RandomPatternUI::parse_ui() Q_EMIT patternParamsChanged(); } -void RandomPatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) +void RandomPatternUI::build_ui(QWidget *parent, uint16_t number_of_channels) { parent_ = parent; parent->layout()->addWidget(this); frequencySpinButton->setValue(pattern->get_frequency()); - connect(frequencySpinButton,SIGNAL(valueChanged(double)),this,SLOT(parse_ui())); - + connect(frequencySpinButton, SIGNAL(valueChanged(double)), this, SLOT(parse_ui())); } -void RandomPatternUI::destroy_ui() -{ - parent_->layout()->removeWidget(this); -} - - +void RandomPatternUI::destroy_ui() { parent_->layout()->removeWidget(this); } -uint32_t BinaryCounterPattern::get_min_sampling_freq() -{ - return frequency; -} +uint32_t BinaryCounterPattern::get_min_sampling_freq() { return frequency; } -uint32_t BinaryCounterPattern::get_required_nr_of_samples(uint32_t sample_rate, - uint32_t number_of_channels) +uint32_t BinaryCounterPattern::get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels) { // greatest common divider duty cycle and 1000;0; - return ((float)sample_rate/(float)frequency) * (1<=number_of_samples) { + while(j < number_of_samples) { + for(auto k = 0; k < samples_per_count; k++, j++) { + if(j >= number_of_samples) { break; } buffer[j] = i; } - if (isetupUi(this); setVisible(false); - frequencySpinButton = new ScaleSpinButton({ - {"Hz", 1E0}, - {"kHz", 1E+3}, - {"MHz", 1E+6} - }, tr("Frequency"), 1e0, PG_MAX_SAMPLERATE/2,true,false,this, {1,2.5,5}); + frequencySpinButton = new ScaleSpinButton({{"Hz", 1E0}, {"kHz", 1E+3}, {"MHz", 1E+6}}, tr("Frequency"), 1e0, + PG_MAX_SAMPLERATE / 2, true, false, this, {1, 2.5, 5}); ui->verticalLayout->addWidget(frequencySpinButton); GSList *decoderList = g_slist_copy((GSList *)srd_decoder_list()); - for (const GSList *sl = decoderList; sl; sl = sl->next) { - srd_decoder *dec = (struct srd_decoder *)sl->data; - if (QString::fromUtf8(dec->id) == "parallel") { - m_decoder = std::make_shared(dec); - } + for(const GSList *sl = decoderList; sl; sl = sl->next) { + srd_decoder *dec = (struct srd_decoder *)sl->data; + if(QString::fromUtf8(dec->id) == "parallel") { + m_decoder = std::make_shared(dec); + } } g_slist_free(decoderList); - connect(this, &BinaryCounterPatternUI::patternParamsChanged, [=](){ -// m_decoder->set_option(); + connect(this, &BinaryCounterPatternUI::patternParamsChanged, [=]() { + // m_decoder->set_option(); qDebug() << "Update decoder params parallel!"; }); } BinaryCounterPatternUI::~BinaryCounterPatternUI() { - qDebug()<<"BinaryCounterPatternUI Destroyed"; + qDebug() << "BinaryCounterPatternUI Destroyed"; delete ui; } -void BinaryCounterPatternUI::build_ui(QWidget *parent, - uint16_t number_of_channels) +void BinaryCounterPatternUI::build_ui(QWidget *parent, uint16_t number_of_channels) { parent_ = parent; parent->layout()->addWidget(this); frequencySpinButton->setValue(pattern->get_frequency()); - connect(frequencySpinButton,SIGNAL(valueChanged(double)), this, - SLOT(parse_ui())); + connect(frequencySpinButton, SIGNAL(valueChanged(double)), this, SLOT(parse_ui())); } -void BinaryCounterPatternUI::destroy_ui() -{ - parent_->layout()->removeWidget(this); -} +void BinaryCounterPatternUI::destroy_ui() { parent_->layout()->removeWidget(this); } -GenericLogicPlotCurve *BinaryCounterPatternUI::getAnnotationCurve() -{ - return m_annotationCurve; -} +GenericLogicPlotCurve *BinaryCounterPatternUI::getAnnotationCurve() { return m_annotationCurve; } -std::shared_ptr BinaryCounterPatternUI::getDecoder() -{ - return m_decoder; -} +std::shared_ptr BinaryCounterPatternUI::getDecoder() { return m_decoder; } -void BinaryCounterPatternUI::setAnnotationCurve(GenericLogicPlotCurve *curve) -{ - m_annotationCurve = curve; -} +void BinaryCounterPatternUI::setAnnotationCurve(GenericLogicPlotCurve *curve) { m_annotationCurve = curve; } QVector BinaryCounterPatternUI::getChannelsToAssign() { @@ -1086,19 +904,13 @@ QVector BinaryCounterPatternUI::getChannelsToAssign() return {1, 2, 3, 4, 5, 6, 7, 8}; } -Pattern *BinaryCounterPatternUI::get_pattern() -{ - return pattern; -} - +Pattern *BinaryCounterPatternUI::get_pattern() { return pattern; } void BinaryCounterPatternUI::parse_ui() { /*bool ok = false;*/ pattern->set_frequency(frequencySpinButton->value()); - - /*pattern->set_init_value(ui->inittval_LE->text().toULong(&ok)); if(!ok) qDebug()<<"Cannot set_init_value, not a uint32"; @@ -1118,76 +930,69 @@ GrayCounterPattern::GrayCounterPattern() set_periodic(true); } -uint8_t GrayCounterPattern::generate_pattern(uint32_t sample_rate, - uint32_t number_of_samples, uint16_t number_of_channels) +uint8_t GrayCounterPattern::generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, + uint16_t number_of_channels) { delete_buffer(); buffer = new short[number_of_samples]; - auto samples_per_count = (int)round(((float)sample_rate/(float)frequency)); + auto samples_per_count = (int)round(((float)sample_rate / (float)frequency)); init_value = 0; - end_value =(1<< (number_of_channels))-1; + end_value = (1 << (number_of_channels)) - 1; increment = 1; start_value = 0; - auto i=init_value; - size_t j=0; + auto i = init_value; + size_t j = 0; - while (j=number_of_samples) { + while(j < number_of_samples) { + for(auto k = 0; k < samples_per_count; k++, j++) { + if(j >= number_of_samples) { break; } buffer[j] = i ^ (i >> 1); } - if (isetupUi(this); setVisible(false); - frequencySpinButton = new ScaleSpinButton({ - {"Hz", 1E0}, - {"kHz", 1E+3}, - {"MHz", 1E+6} - }, tr("Frequency"), 1e0, PG_MAX_SAMPLERATE/2,true,false,this, {1,2.5,5}); + frequencySpinButton = new ScaleSpinButton({{"Hz", 1E0}, {"kHz", 1E+3}, {"MHz", 1E+6}}, tr("Frequency"), 1e0, + PG_MAX_SAMPLERATE / 2, true, false, this, {1, 2.5, 5}); ui->verticalLayout->addWidget(frequencySpinButton); } GrayCounterPatternUI::~GrayCounterPatternUI() { - qDebug()<<"BinaryCounterPatternUI Destroyed"; + qDebug() << "BinaryCounterPatternUI Destroyed"; delete ui; } +Pattern *GrayCounterPatternUI::get_pattern() { return pattern; } -Pattern *GrayCounterPatternUI::get_pattern() -{ - return pattern; -} - -void GrayCounterPatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) +void GrayCounterPatternUI::build_ui(QWidget *parent, uint16_t number_of_channels) { parent_ = parent; parent->layout()->addWidget(this); frequencySpinButton->setValue(pattern->get_frequency()); - connect(frequencySpinButton,SIGNAL(valueChanged(double)), this, - SLOT(parse_ui())); - + connect(frequencySpinButton, SIGNAL(valueChanged(double)), this, SLOT(parse_ui())); } void GrayCounterPatternUI::destroy_ui() { parent_->layout()->removeWidget(this); - //delete ui; + // delete ui; } void GrayCounterPatternUI::parse_ui() @@ -1195,8 +1000,6 @@ void GrayCounterPatternUI::parse_ui() /*bool ok = false;*/ pattern->set_frequency(frequencySpinButton->value()); - - /*pattern->set_init_value(ui->inittval_LE->text().toULong(&ok)); if(!ok) qDebug()<<"Cannot set_init_value, not a uint32"; @@ -1209,55 +1012,31 @@ void GrayCounterPatternUI::parse_ui() Q_EMIT patternParamsChanged(); } - UARTPattern::UARTPattern() { parity = SP_PARITY_NONE; stop_bits = 1; baud_rate = 9600; data_bits = 8; - msb_first=false; + msb_first = false; set_periodic(false); set_name(UARTPatternName); set_description(UARTPatternDescription); - } +unsigned int UARTPattern::get_baud_rate() { return baud_rate; } -unsigned int UARTPattern::get_baud_rate() -{ - return baud_rate; -} - -unsigned int UARTPattern::get_data_bits() -{ - return data_bits; -} +unsigned int UARTPattern::get_data_bits() { return data_bits; } -unsigned int UARTPattern::get_stop_bits() -{ - return stop_bits; -} +unsigned int UARTPattern::get_stop_bits() { return stop_bits; } -enum UARTPattern::sp_parity UARTPattern::get_parity() -{ - return parity; -} +enum UARTPattern::sp_parity UARTPattern::get_parity() { return parity; } -void UARTPattern::set_string(const std::string &str_) -{ - str = str_; -} +void UARTPattern::set_string(const std::string &str_) { str = str_; } -std::string UARTPattern::get_string() -{ - return str; -} +std::string UARTPattern::get_string() { return str; } -std::string UARTPattern::get_params() -{ - return params; -} +std::string UARTPattern::get_params() { return params; } int UARTPattern::set_params(std::string params_) { @@ -1268,13 +1047,13 @@ int UARTPattern::set_params(std::string params_) baud_rate = strtoul(params, &end, 10); - if (params == end) { + if(params == end) { return -EINVAL; } - auto uart_format = strchr(params,'/'); + auto uart_format = strchr(params, '/'); - if (uart_format == NULL) { /* / not found, use default settings*/ + if(uart_format == NULL) { /* / not found, use default settings*/ data_bits = 8; parity = SP_PARITY_NONE; stop_bits = 1; @@ -1285,13 +1064,13 @@ int UARTPattern::set_params(std::string params_) data_bits = strtoul(uart_format, &end, 10); - if (params == end) { + if(params == end) { return -EINVAL; } char lowercase_parity = tolower(*end); - switch (lowercase_parity) { + switch(lowercase_parity) { case 'n': parity = SP_PARITY_NONE; break; @@ -1320,17 +1099,14 @@ int UARTPattern::set_params(std::string params_) uart_format = end; stop_bits = strtoul(uart_format, &end, 10); - if (params == end) { + if(params == end) { return -EINVAL; } return 0; } -void UARTPattern::set_msb_first(bool msb_first_) -{ - msb_first = msb_first_; -} +void UARTPattern::set_msb_first(bool msb_first_) { msb_first = msb_first_; } uint16_t UARTPattern::encapsulateUartFrame(char chr, uint16_t *bits_per_frame) { @@ -1339,7 +1115,7 @@ uint16_t UARTPattern::encapsulateUartFrame(char chr, uint16_t *bits_per_frame) uint16_t parity_bit_value = 1; auto chr_to_test = chr; - switch (parity) { + switch(parity) { case SP_PARITY_NONE: parity_bit_available = false; break; @@ -1348,9 +1124,9 @@ uint16_t UARTPattern::encapsulateUartFrame(char chr, uint16_t *bits_per_frame) parity_bit_value = 1; parity_bit_available = true; - for (size_t i=0; i>1; + chr_to_test = chr_to_test >> 1; } break; @@ -1359,9 +1135,9 @@ uint16_t UARTPattern::encapsulateUartFrame(char chr, uint16_t *bits_per_frame) parity_bit_value = 0; parity_bit_available = true; - for (size_t i=0; i>1; + chr_to_test = chr_to_test >> 1; } break; @@ -1380,7 +1156,7 @@ uint16_t UARTPattern::encapsulateUartFrame(char chr, uint16_t *bits_per_frame) qDebug() << "Invalid parity setting detected"; } - if (!msb_first) { + if(!msb_first) { ret = chr; ret = ret << 1; // start bit uint16_t stop_bit_values; @@ -1390,22 +1166,22 @@ uint16_t UARTPattern::encapsulateUartFrame(char chr, uint16_t *bits_per_frame) stop_bit_values = ((1<> 1; } else { - bit_to_send = ((frame_to_send & (1<<(bits_per_frame-1))) ? 1 : - 0); // set bit here + bit_to_send = ((frame_to_send & (1 << (bits_per_frame - 1))) ? 1 : 0); // set bit here frame_to_send = frame_to_send << 1; } - for (size_t k=0; ksetupUi(this); setVisible(false); GSList *decoderList = g_slist_copy((GSList *)srd_decoder_list()); - for (const GSList *sl = decoderList; sl; sl = sl->next) { - srd_decoder *dec = (struct srd_decoder *)sl->data; - if (QString::fromUtf8(dec->id) == "uart") { - m_decoder = std::make_shared(dec); - } + for(const GSList *sl = decoderList; sl; sl = sl->next) { + srd_decoder *dec = (struct srd_decoder *)sl->data; + if(QString::fromUtf8(dec->id) == "uart") { + m_decoder = std::make_shared(dec); + } } g_slist_free(decoderList); - connect(this, &UARTPatternUI::patternParamsChanged, [=](){ -// m_decoder->set_option(); + connect(this, &UARTPatternUI::patternParamsChanged, [=]() { + // m_decoder->set_option(); qDebug() << "Update decoder params uart!"; - m_decoder->set_option("baudrate", - g_variant_new_int64(pattern->get_baud_rate())); - m_decoder->set_option("data_bits", - g_variant_new_int64(8)); + m_decoder->set_option("baudrate", g_variant_new_int64(pattern->get_baud_rate())); + m_decoder->set_option("data_bits", g_variant_new_int64(8)); auto par = pattern->get_parity(); GVariant *parityStr = g_variant_new_string("none"); - switch (par) { + switch(par) { case UARTPattern::SP_PARITY_ODD: parityStr = g_variant_new_string("odd"); @@ -1540,25 +1308,23 @@ UARTPatternUI::UARTPatternUI(UARTPattern *pattern, default: parityStr = g_variant_new_string("none"); break; - } m_decoder->set_option("parity", parityStr); - m_decoder->set_option("stop_bits", - g_variant_new_double(pattern->get_stop_bits())); + m_decoder->set_option("stop_bits", g_variant_new_double(pattern->get_stop_bits())); m_decoder->set_option("format", g_variant_new_string("ascii")); - dynamic_cast(m_annotationCurve)->getAnnotationDecoder()->startDecode(); + dynamic_cast(m_annotationCurve)->getAnnotationDecoder()->startDecode(); }); } UARTPatternUI::~UARTPatternUI() { - qDebug()<<"UARTPatternUI destroyed"; + qDebug() << "UARTPatternUI destroyed"; delete ui; } -void UARTPatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) +void UARTPatternUI::build_ui(QWidget *parent, uint16_t number_of_channels) { parent_ = parent; parent->layout()->addWidget(this); @@ -1566,13 +1332,11 @@ void UARTPatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) ui->CB_Parity->setCurrentIndex(pattern->get_parity()); ui->CB_Stop->setCurrentText(QString::number(pattern->get_stop_bits())); ui->LE_Data->setText(QString::fromStdString(pattern->get_string())); - connect(ui->CB_baud,SIGNAL(activated(QString)),this,SLOT(parse_ui())); - connect(ui->CB_Parity,SIGNAL(activated(QString)),this,SLOT(parse_ui())); - connect(ui->CB_Stop,SIGNAL(activated(QString)),this,SLOT(parse_ui())); - connect(ui->LE_Data,SIGNAL(textChanged(QString)),this,SLOT(parse_ui())); + connect(ui->CB_baud, SIGNAL(activated(QString)), this, SLOT(parse_ui())); + connect(ui->CB_Parity, SIGNAL(activated(QString)), this, SLOT(parse_ui())); + connect(ui->CB_Stop, SIGNAL(activated(QString)), this, SLOT(parse_ui())); + connect(ui->LE_Data, SIGNAL(textChanged(QString)), this, SLOT(parse_ui())); parse_ui(); - - } void UARTPatternUI::destroy_ui() { @@ -1580,195 +1344,131 @@ void UARTPatternUI::destroy_ui() // delete ui; } -GenericLogicPlotCurve *UARTPatternUI::getAnnotationCurve() -{ - return m_annotationCurve; -} - -std::shared_ptr UARTPatternUI::getDecoder() -{ - return m_decoder; -} +GenericLogicPlotCurve *UARTPatternUI::getAnnotationCurve() { return m_annotationCurve; } -void UARTPatternUI::setAnnotationCurve(GenericLogicPlotCurve *curve) -{ - m_annotationCurve = curve; -} +std::shared_ptr UARTPatternUI::getDecoder() { return m_decoder; } -Pattern *UARTPatternUI::get_pattern() -{ - return pattern; -} +void UARTPatternUI::setAnnotationCurve(GenericLogicPlotCurve *curve) { m_annotationCurve = curve; } +Pattern *UARTPatternUI::get_pattern() { return pattern; } void UARTPatternUI::parse_ui() { auto oldStr = ui->LE_paramsOut->text(); - auto newStr = ui->CB_baud->currentText() + "/8" - +ui->CB_Parity->currentText()[0] + ui->CB_Stop->currentText(); + auto newStr = ui->CB_baud->currentText() + "/8" + ui->CB_Parity->currentText()[0] + ui->CB_Stop->currentText(); ui->LE_paramsOut->setText(newStr); - qDebug()<LE_paramsOut->text(); + qDebug() << ui->LE_paramsOut->text(); pattern->set_params(ui->LE_paramsOut->text().toStdString()); - qDebug()<LE_Data->text(); + qDebug() << ui->LE_Data->text(); pattern->set_string(ui->LE_Data->text().toStdString()); Q_EMIT patternParamsChanged(); - if (oldStr != newStr) { + if(oldStr != newStr) { Q_EMIT decoderChanged(); } - -} - - - -uint8_t I2CPattern::getAddress() const -{ - return address; } -void I2CPattern::setAddress(const uint8_t& value) -{ - address = value; -} +uint8_t I2CPattern::getAddress() const { return address; } -bool I2CPattern::getWrite() const -{ - return read; -} +void I2CPattern::setAddress(const uint8_t &value) { address = value; } -void I2CPattern::setWrite(bool value) -{ - read = value; -} +bool I2CPattern::getWrite() const { return read; } -bool I2CPattern::getMsbFirst() const -{ - return msbFirst; -} +void I2CPattern::setWrite(bool value) { read = value; } -void I2CPattern::setMsbFirst(bool value) -{ - msbFirst = value; -} +bool I2CPattern::getMsbFirst() const { return msbFirst; } -uint8_t I2CPattern::getInterFrameSpace() const -{ - return interFrameSpace; -} +void I2CPattern::setMsbFirst(bool value) { msbFirst = value; } -void I2CPattern::setInterFrameSpace(const uint8_t& value) -{ - interFrameSpace = value; -} +uint8_t I2CPattern::getInterFrameSpace() const { return interFrameSpace; } -uint32_t I2CPattern::getClkFrequency() const -{ - return clkFrequency; -} +void I2CPattern::setInterFrameSpace(const uint8_t &value) { interFrameSpace = value; } -void I2CPattern::setClkFrequency(const uint32_t& value) -{ - clkFrequency = value; -} +uint32_t I2CPattern::getClkFrequency() const { return clkFrequency; } -uint8_t I2CPattern::getBytesPerFrame() const -{ - return bytesPerFrame; -} +void I2CPattern::setClkFrequency(const uint32_t &value) { clkFrequency = value; } -void I2CPattern::setBytesPerFrame(const uint8_t& value) -{ - bytesPerFrame = value; -} +uint8_t I2CPattern::getBytesPerFrame() const { return bytesPerFrame; } -bool I2CPattern::getTenbit() const -{ - return tenbit; -} +void I2CPattern::setBytesPerFrame(const uint8_t &value) { bytesPerFrame = value; } -void I2CPattern::setTenbit(bool value) -{ - tenbit = value; -} +bool I2CPattern::getTenbit() const { return tenbit; } + +void I2CPattern::setTenbit(bool value) { tenbit = value; } I2CPattern::I2CPattern() { - clkFrequency=5000; - msbFirst=true; - address=0x72; - samples_per_bit=1; - buf_ptr=nullptr; - interFrameSpace=3; - bytesPerFrame=2; - read=false; - tenbit=false; + clkFrequency = 5000; + msbFirst = true; + address = 0x72; + samples_per_bit = 1; + buf_ptr = nullptr; + interFrameSpace = 3; + bytesPerFrame = 2; + read = false; + tenbit = false; set_periodic(false); set_name(I2CPatternName); set_description(I2CPatternDescription); } -uint32_t I2CPattern::get_min_sampling_freq() -{ - return clkFrequency * (4); -} +uint32_t I2CPattern::get_min_sampling_freq() { return clkFrequency * (4); } -uint32_t I2CPattern::get_required_nr_of_samples(uint32_t sample_rate, - uint32_t number_of_channels) +uint32_t I2CPattern::get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels) { - auto samples_per_bit = 1*(sample_rate/clkFrequency); - auto IFS=interFrameSpace*samples_per_bit; + auto samples_per_bit = 1 * (sample_rate / clkFrequency); + auto IFS = interFrameSpace * samples_per_bit; // size = samples/bit * (IFS+start(2), address(7), ack(1), (data(8) + ack(1))*data_len, stop(2)+IFS) - uint32_t samples=samples_per_bit * (interFrameSpace+2+7+1+(8+1)*v.size()+2+interFrameSpace); + uint32_t samples = samples_per_bit * (interFrameSpace + 2 + 7 + 1 + (8 + 1) * v.size() + 2 + interFrameSpace); return samples; } - void I2CPattern::sample_bit(bool bit) { // SDA Transitions must occur when SCL is LOW (unless starting or stopping) // Set SDA whilst SCL is low from previous bit - for (size_t i=0; i>6); - tmpaddress<<=1; + for(auto i = 0; i < 7; i++) { + sample_bit((tmpaddress & 0x40) >> 6); + tmpaddress <<= 1; } sample_bit(read); - } -void I2CPattern::sample_send_ack() -{ - sample_bit(0); -} +void I2CPattern::sample_send_ack() { sample_bit(0); } -void I2CPattern::sample_await_ack() -{ - sample_bit(1); -} +void I2CPattern::sample_await_ack() { sample_bit(1); } void I2CPattern::sample_payload() { - for (std::deque::iterator it = v.begin(); it != v.end(); - ++it) { + for(std::deque::iterator it = v.begin(); it != v.end(); ++it) { uint8_t val; - if (read) { + if(read) { val = 0xff; } else { val = *it; } - for (auto j=0; j<8; j++) { + for(auto j = 0; j < 8; j++) { bool bit; - if (msbFirst) { + if(msbFirst) { bit = (val & 0x80) >> 7; val = val << 1; } else { @@ -1821,9 +1513,9 @@ void I2CPattern::sample_payload() sample_bit(bit); } - if (read) { + if(read) { // Last bit on a read should be NACKed - if (it == v.end()-1) { + if(it == v.end() - 1) { sample_bit(1); } else { sample_send_ack(); @@ -1837,40 +1529,38 @@ void I2CPattern::sample_payload() void I2CPattern::sample_stop() { // Explicitly set stop condition, consume 2 bits - for (size_t i=0; isetupUi(this); - frequencySpinButton = new ScaleSpinButton({ - {"Hz", 1E0}, - {"kHz", 1E+3}, - {"MHz", 1E+6} - }, tr("Frequency"), 1e0, PG_MAX_SAMPLERATE/2,true,false,this, {1,2.5,5}); - ui->verticalLayout->insertWidget(0,frequencySpinButton); + frequencySpinButton = new ScaleSpinButton({{"Hz", 1E0}, {"kHz", 1E+3}, {"MHz", 1E+6}}, tr("Frequency"), 1e0, + PG_MAX_SAMPLERATE / 2, true, false, this, {1, 2.5, 5}); + ui->verticalLayout->insertWidget(0, frequencySpinButton); setVisible(false); GSList *decoderList = g_slist_copy((GSList *)srd_decoder_list()); - for (const GSList *sl = decoderList; sl; sl = sl->next) { - srd_decoder *dec = (struct srd_decoder *)sl->data; - if (QString::fromUtf8(dec->id) == "i2c") { - m_decoder = std::make_shared(dec); - } + for(const GSList *sl = decoderList; sl; sl = sl->next) { + srd_decoder *dec = (struct srd_decoder *)sl->data; + if(QString::fromUtf8(dec->id) == "i2c") { + m_decoder = std::make_shared(dec); + } } g_slist_free(decoderList); - connect(this, &I2CPatternUI::patternParamsChanged, [=](){ -// m_decoder->set_option(); + connect(this, &I2CPatternUI::patternParamsChanged, [=]() { + // m_decoder->set_option(); qDebug() << "Update decoder params!"; }); } I2CPatternUI::~I2CPatternUI() { - qDebug()<<"UARTPatternUI destroyed"; + qDebug() << "UARTPatternUI destroyed"; delete ui; } -void I2CPatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) +void I2CPatternUI::build_ui(QWidget *parent, uint16_t number_of_channels) { parent_ = parent; parent->layout()->addWidget(this); frequencySpinButton->setValue(pattern->getClkFrequency()); ui->PB_MSB->setChecked(pattern->getMsbFirst()); ui->LE_IFS->setText(QString::number(pattern->getInterFrameSpace())); - ui->LE_address->setText(QString::number(pattern->getAddress(),16)); + ui->LE_address->setText(QString::number(pattern->getAddress(), 16)); ui->PB_readWrite->setChecked(pattern->getWrite()); ui->PB_MSB->setVisible(false); ui->label_8->setVisible(false); - //ui->LE_BPF->setText(QString::number(pattern->getBytesPerFrame())); + // ui->LE_BPF->setText(QString::number(pattern->getBytesPerFrame())); QString buf; - for (auto val:pattern->v) { - buf.append(QString::number(val,16)); + for(auto val : pattern->v) { + buf.append(QString::number(val, 16)); buf.append(" "); } ui->LE_toSend->setText(buf); - //ui->LE_toSend->setText(QString::fromStdString(pattern->get_string())); - connect(frequencySpinButton,SIGNAL(valueChanged(double)),this,SLOT(parse_ui())); - connect(ui->PB_MSB,SIGNAL(clicked()),this,SLOT(parse_ui())); - connect(ui->PB_readWrite,SIGNAL(clicked()),this,SLOT(parse_ui())); - connect(ui->LE_IFS,SIGNAL(textChanged(QString)),this,SLOT(parse_ui())); - connect(ui->LE_address,SIGNAL(textChanged(QString)),this,SLOT(parse_ui())); - connect(ui->LE_toSend,SIGNAL(textChanged(QString)),this,SLOT(parse_ui())); - + // ui->LE_toSend->setText(QString::fromStdString(pattern->get_string())); + connect(frequencySpinButton, SIGNAL(valueChanged(double)), this, SLOT(parse_ui())); + connect(ui->PB_MSB, SIGNAL(clicked()), this, SLOT(parse_ui())); + connect(ui->PB_readWrite, SIGNAL(clicked()), this, SLOT(parse_ui())); + connect(ui->LE_IFS, SIGNAL(textChanged(QString)), this, SLOT(parse_ui())); + connect(ui->LE_address, SIGNAL(textChanged(QString)), this, SLOT(parse_ui())); + connect(ui->LE_toSend, SIGNAL(textChanged(QString)), this, SLOT(parse_ui())); parse_ui(); - - } void I2CPatternUI::destroy_ui() @@ -1962,68 +1646,55 @@ void I2CPatternUI::destroy_ui() // delete ui; } -GenericLogicPlotCurve *I2CPatternUI::getAnnotationCurve() -{ - return m_annotationCurve; -} - -std::shared_ptr I2CPatternUI::getDecoder() -{ - return m_decoder; -} +GenericLogicPlotCurve *I2CPatternUI::getAnnotationCurve() { return m_annotationCurve; } -void I2CPatternUI::setAnnotationCurve(GenericLogicPlotCurve *curve) -{ - m_annotationCurve = curve; -} +std::shared_ptr I2CPatternUI::getDecoder() { return m_decoder; } -Pattern *I2CPatternUI::get_pattern() -{ - return pattern; -} +void I2CPatternUI::setAnnotationCurve(GenericLogicPlotCurve *curve) { m_annotationCurve = curve; } +Pattern *I2CPatternUI::get_pattern() { return pattern; } void I2CPatternUI::parse_ui() { bool ok; pattern->setClkFrequency(frequencySpinButton->value()); - auto address = ui->LE_address->text().toInt(&ok,16); + auto address = ui->LE_address->text().toInt(&ok, 16); - if (ok && address>=0 && address<=0x7f) { + if(ok && address >= 0 && address <= 0x7f) { pattern->setAddress(address); } auto IFS = ui->LE_IFS->text().toInt(&ok); - if (ok && IFS>0) { + if(ok && IFS > 0) { pattern->setInterFrameSpace(IFS); } pattern->setMsbFirst(ui->PB_MSB->isChecked()); pattern->setWrite(ui->PB_readWrite->isChecked()); - QStringList strList = ui->LE_toSend->text().split(' ',Qt::SkipEmptyParts); + QStringList strList = ui->LE_toSend->text().split(' ', Qt::SkipEmptyParts); pattern->v.clear(); bool fail = false; std::vector b; - std::reverse(strList.begin(),strList.end()); + std::reverse(strList.begin(), strList.end()); - for (const QString &str: qAsConst(strList)) { + for(const QString &str : qAsConst(strList)) { uint64_t val; bool ok; b.clear(); - val = str.toULongLong(&ok,16); + val = str.toULongLong(&ok, 16); - if (ok) { + if(ok) { do { auto u8val = val & 0xff; val = val >> 8; b.push_back(u8val); - } while (val); + } while(val); - for (auto u8val : b) { + for(auto u8val : b) { pattern->v.push_front(u8val); } @@ -2033,7 +1704,7 @@ void I2CPatternUI::parse_ui() } } - if (fail) { + if(fail) { setDynamicProperty(ui->LE_toSend, "invalid", true); setDynamicProperty(ui->LE_toSend, "valid", false); } else { @@ -2041,31 +1712,21 @@ void I2CPatternUI::parse_ui() setDynamicProperty(ui->LE_toSend, "invalid", false); } - Q_EMIT patternParamsChanged(); - } +bool SPIPattern::getMsbFirst() const { return msbFirst; } - -bool SPIPattern::getMsbFirst() const -{ - return msbFirst; -} - -void SPIPattern::setMsbFirst(bool value) -{ - msbFirst = value; -} +void SPIPattern::setMsbFirst(bool value) { msbFirst = value; } SPIPattern::SPIPattern() { - CPOL=false; + CPOL = false; CPHA = false; CSPOL = false; - clkFrequency=5000; - bytesPerFrame=2; - waitClocks=3; + clkFrequency = 5000; + bytesPerFrame = 2; + waitClocks = 3; msbFirst = true; set_periodic(false); @@ -2073,47 +1734,28 @@ SPIPattern::SPIPattern() set_description(SPIPatternDescription); } -uint32_t SPIPattern::get_min_sampling_freq() -{ - return clkFrequency * (2); -} +uint32_t SPIPattern::get_min_sampling_freq() { return clkFrequency * (2); } -uint32_t SPIPattern::get_required_nr_of_samples(uint32_t sample_rate, - uint32_t number_of_channels) +uint32_t SPIPattern::get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels) { - auto samples_per_bit = 2*(sample_rate/clkFrequency); - auto IFS=waitClocks*samples_per_bit; + auto samples_per_bit = 2 * (sample_rate / clkFrequency); + auto IFS = waitClocks * samples_per_bit; // number of bytes * samples per bit * 9 (8 bits + 1 account for extra padding) + // 2 * interframespace(beginning and end) + extra frame space between each frame - return (v.size()*samples_per_bit*9) + 2*IFS + IFS *(v.size()/bytesPerFrame); - + return (v.size() * samples_per_bit * 9) + 2 * IFS + IFS * (v.size() / bytesPerFrame); } +uint8_t SPIPattern::getWaitClocks() const { return waitClocks; } -uint8_t SPIPattern::getWaitClocks() const -{ - return waitClocks; -} - -void SPIPattern::setWaitClocks(const uint8_t& value) -{ - waitClocks = value; -} +void SPIPattern::setWaitClocks(const uint8_t &value) { waitClocks = value; } -uint8_t SPIPattern::getBytesPerFrame() const -{ - return bytesPerFrame; -} +uint8_t SPIPattern::getBytesPerFrame() const { return bytesPerFrame; } -void SPIPattern::setBytesPerFrame(const uint8_t& value) -{ - bytesPerFrame = value; -} +void SPIPattern::setBytesPerFrame(const uint8_t &value) { bytesPerFrame = value; } -uint8_t SPIPattern::generate_pattern(uint32_t sample_rate, - uint32_t number_of_samples, uint16_t number_of_channels) +uint8_t SPIPattern::generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels) { delete_buffer(); @@ -2123,38 +1765,37 @@ uint8_t SPIPattern::generate_pattern(uint32_t sample_rate, auto outputBit = 1; auto csBit = 2; - if (CSPOL) { - memset(buffer, (CPOL) ? 0xfffb : 0xfffa, (number_of_samples)*sizeof(short)); + if(CSPOL) { + memset(buffer, (CPOL) ? 0xfffb : 0xfffa, (number_of_samples) * sizeof(short)); } else { - memset(buffer, (CPOL) ? 0xffff : 0xfffe, (number_of_samples)*sizeof(short)); + memset(buffer, (CPOL) ? 0xffff : 0xfffe, (number_of_samples) * sizeof(short)); } short *buf_ptr = buffer; short *buf_ptr_end = buffer + number_of_samples; - auto samples_per_bit = 2 * (sample_rate/clkFrequency); + auto samples_per_bit = 2 * (sample_rate / clkFrequency); buf_ptr += waitClocks * samples_per_bit; auto frameBytesLeft = bytesPerFrame; bool start_new_frame = 1; - for (std::deque::iterator it = v.begin(); it != v.end(); - ++it) { + for(std::deque::iterator it = v.begin(); it != v.end(); ++it) { uint8_t val = *it; bool oldbit = 0; bool bit; - if(CPHA && start_new_frame) - { - for (auto i=samples_per_bit/2; i> 7; val = val << 1; } else { @@ -2162,21 +1803,22 @@ uint8_t SPIPattern::generate_pattern(uint32_t sample_rate, val = val >> 1; } - for (size_t i=0; isetupUi(this); - frequencySpinButton = new ScaleSpinButton({ - {"Hz", 1E0}, - {"kHz", 1E+3}, - {"MHz", 1E+6} - }, tr("Frequency"), 1e0, PG_MAX_SAMPLERATE/2,true,false,this, {1,2.5,5}); - ui->verticalLayout->insertWidget(0,frequencySpinButton); + frequencySpinButton = new ScaleSpinButton({{"Hz", 1E0}, {"kHz", 1E+3}, {"MHz", 1E+6}}, tr("Frequency"), 1e0, + PG_MAX_SAMPLERATE / 2, true, false, this, {1, 2.5, 5}); + ui->verticalLayout->insertWidget(0, frequencySpinButton); setVisible(false); GSList *decoderList = g_slist_copy((GSList *)srd_decoder_list()); - for (const GSList *sl = decoderList; sl; sl = sl->next) { - srd_decoder *dec = (struct srd_decoder *)sl->data; - if (QString::fromUtf8(dec->id) == "spi") { - m_decoder = std::make_shared(dec); - } + for(const GSList *sl = decoderList; sl; sl = sl->next) { + srd_decoder *dec = (struct srd_decoder *)sl->data; + if(QString::fromUtf8(dec->id) == "spi") { + m_decoder = std::make_shared(dec); + } } g_slist_free(decoderList); - - connect(this, &SPIPatternUI::patternParamsChanged, [=](){ -// m_decoder->set_option(); + connect(this, &SPIPatternUI::patternParamsChanged, [=]() { + // m_decoder->set_option(); qDebug() << "Spi decoder params!"; GVariant *cspolstr, *bitorderstr; - if (pattern->getCSPol()) { + if(pattern->getCSPol()) { cspolstr = g_variant_new_string("active-high"); } else { cspolstr = g_variant_new_string("active-low"); } - if (pattern->getMsbFirst()) { + if(pattern->getMsbFirst()) { bitorderstr = g_variant_new_string("msb-first"); } else { bitorderstr = g_variant_new_string("lsb-first"); @@ -2297,16 +1908,15 @@ SPIPatternUI::SPIPatternUI(SPIPattern *pattern, m_decoder->set_option("cpol", g_variant_new_int64(pattern->getCPOL())); m_decoder->set_option("cpha", g_variant_new_int64(pattern->getCPHA())); }); - } SPIPatternUI::~SPIPatternUI() { - qDebug()<<"UARTPatternUI destroyed"; + qDebug() << "UARTPatternUI destroyed"; delete ui; } -void SPIPatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) +void SPIPatternUI::build_ui(QWidget *parent, uint16_t number_of_channels) { parent_ = parent; parent->layout()->addWidget(this); @@ -2319,29 +1929,26 @@ void SPIPatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) ui->LE_BPF->setText(QString::number(pattern->getBytesPerFrame())); QString buf; - for (auto val:pattern->v) { - buf.append(QString::number(val,16)); + for(auto val : pattern->v) { + buf.append(QString::number(val, 16)); buf.append(" "); } ui->LE_toSend->setText(buf); - //ui->LE_toSend->setText(QString::fromStdString(pattern->get_string())); - connect(frequencySpinButton,SIGNAL(valueChanged(double)),this,SLOT(parse_ui())); - - connect(ui->PB_CPHA,SIGNAL(clicked()),this,SLOT(parse_ui())); - connect(ui->PB_CPOL,SIGNAL(clicked()),this,SLOT(parse_ui())); - connect(ui->PB_CS,SIGNAL(clicked()),this,SLOT(parse_ui())); - connect(ui->PB_MSB,SIGNAL(clicked()),this,SLOT(parse_ui())); + // ui->LE_toSend->setText(QString::fromStdString(pattern->get_string())); + connect(frequencySpinButton, SIGNAL(valueChanged(double)), this, SLOT(parse_ui())); - connect(ui->LE_BPF,SIGNAL(textChanged(QString)),this,SLOT(parse_ui())); - connect(ui->LE_IFS,SIGNAL(textChanged(QString)),this,SLOT(parse_ui())); + connect(ui->PB_CPHA, SIGNAL(clicked()), this, SLOT(parse_ui())); + connect(ui->PB_CPOL, SIGNAL(clicked()), this, SLOT(parse_ui())); + connect(ui->PB_CS, SIGNAL(clicked()), this, SLOT(parse_ui())); + connect(ui->PB_MSB, SIGNAL(clicked()), this, SLOT(parse_ui())); + connect(ui->LE_BPF, SIGNAL(textChanged(QString)), this, SLOT(parse_ui())); + connect(ui->LE_IFS, SIGNAL(textChanged(QString)), this, SLOT(parse_ui())); - connect(ui->LE_toSend,SIGNAL(textChanged(QString)),this,SLOT(parse_ui())); + connect(ui->LE_toSend, SIGNAL(textChanged(QString)), this, SLOT(parse_ui())); parse_ui(); - - } void SPIPatternUI::destroy_ui() { @@ -2349,20 +1956,11 @@ void SPIPatternUI::destroy_ui() // delete ui; } -GenericLogicPlotCurve *SPIPatternUI::getAnnotationCurve() -{ - return m_annotationCurve; -} +GenericLogicPlotCurve *SPIPatternUI::getAnnotationCurve() { return m_annotationCurve; } -std::shared_ptr SPIPatternUI::getDecoder() -{ - return m_decoder; -} +std::shared_ptr SPIPatternUI::getDecoder() { return m_decoder; } -void SPIPatternUI::setAnnotationCurve(GenericLogicPlotCurve *curve) -{ - m_annotationCurve = curve; -} +void SPIPatternUI::setAnnotationCurve(GenericLogicPlotCurve *curve) { m_annotationCurve = curve; } QVector SPIPatternUI::getChannelsToAssign() { @@ -2370,11 +1968,7 @@ QVector SPIPatternUI::getChannelsToAssign() return {0, 2, 3}; } -Pattern *SPIPatternUI::get_pattern() -{ - return pattern; -} - +Pattern *SPIPatternUI::get_pattern() { return pattern; } void SPIPatternUI::parse_ui() { @@ -2389,43 +1983,41 @@ void SPIPatternUI::parse_ui() auto oldcspol = pattern->getCSPol(); auto oldmsb = pattern->getMsbFirst(); - if (ok && BPF>0) { + if(ok && BPF > 0) { pattern->setBytesPerFrame(ui->LE_BPF->text().toInt()); } auto IFS = ui->LE_IFS->text().toInt(&ok); - if (ok && IFS>0) { + if(ok && IFS > 0) { pattern->setWaitClocks(IFS); } - - pattern->setCPHA(ui->PB_CPHA->isChecked()); pattern->setCPOL(ui->PB_CPOL->isChecked()); pattern->setCSPol(ui->PB_CS->isChecked()); pattern->setMsbFirst(ui->PB_MSB->isChecked()); - QStringList strList = ui->LE_toSend->text().split(' ',Qt::SkipEmptyParts); + QStringList strList = ui->LE_toSend->text().split(' ', Qt::SkipEmptyParts); pattern->v.clear(); bool fail = false; std::vector b; - std::reverse(strList.begin(),strList.end()); + std::reverse(strList.begin(), strList.end()); - for (const QString &str: qAsConst(strList)) { + for(const QString &str : qAsConst(strList)) { uint64_t val; bool ok; b.clear(); - val = str.toULongLong(&ok,16); + val = str.toULongLong(&ok, 16); - if (ok) { + if(ok) { do { auto u8val = val & 0xff; val = val >> 8; b.push_back(u8val); - } while (val); + } while(val); - for (auto u8val : b) { + for(auto u8val : b) { pattern->v.push_front(u8val); } @@ -2435,7 +2027,7 @@ void SPIPatternUI::parse_ui() } } - if (fail) { + if(fail) { setDynamicProperty(ui->LE_toSend, "invalid", true); setDynamicProperty(ui->LE_toSend, "valid", false); } else { @@ -2443,20 +2035,18 @@ void SPIPatternUI::parse_ui() setDynamicProperty(ui->LE_toSend, "invalid", false); } - Q_EMIT patternParamsChanged(); - if (oldbpf!=pattern->getBytesPerFrame() || oldcpha!=pattern->getCPHA() - || oldcpol!=pattern->getCPOL() || oldcspol != pattern->getCSPol() - || oldmsb!=pattern->getMsbFirst()) { + if(oldbpf != pattern->getBytesPerFrame() || oldcpha != pattern->getCPHA() || oldcpol != pattern->getCPOL() || + oldcspol != pattern->getCSPol() || oldmsb != pattern->getMsbFirst()) { Q_EMIT decoderChanged(); } } - -JSPattern::JSPattern(QJsonObject obj_) : obj(obj_) +JSPattern::JSPattern(QJsonObject obj_) + : obj(obj_) { - qDebug()<<"JSPattern created"; + qDebug() << "JSPattern created"; set_name(obj["name"].toString().toStdString()); console = new JSConsole(); qEngine = nullptr; @@ -2469,7 +2059,7 @@ JSPattern::JSPattern(QJsonObject obj_) : obj(obj_) void JSPattern::init() { - if (qEngine!=nullptr) { + if(qEngine != nullptr) { qEngine->collectGarbage(); delete qEngine; } @@ -2479,7 +2069,7 @@ void JSPattern::init() void JSPattern::deinit() { - if (qEngine!=nullptr) { + if(qEngine != nullptr) { qEngine->collectGarbage(); delete qEngine; qEngine = nullptr; @@ -2490,13 +2080,12 @@ uint32_t JSPattern::get_min_sampling_freq() { QJSValue result = qEngine->evaluate("get_min_sampling_freq()"); - if (result.isNumber()) { + if(result.isNumber()) { return result.toUInt(); - } else if (result.isString()) { - qDebug() << "Error - return value of get_min_sampling_freq() is a string - " << - result.toString(); + } else if(result.isString()) { + qDebug() << "Error - return value of get_min_sampling_freq() is a string - " << result.toString(); } else { - qDebug() << "Error - get_min_sampling_freq - "<< result.toString(); + qDebug() << "Error - get_min_sampling_freq - " << result.toString(); } return 0; @@ -2506,14 +2095,12 @@ uint32_t JSPattern::get_required_nr_of_samples() { QJSValue result = qEngine->evaluate("get_required_nr_of_samples()"); - if (result.isNumber()) { + if(result.isNumber()) { return result.toUInt(); - } else if (result.isString()) { - qDebug() << - "Error - return value of get_required_nr_of_samples() is a string - " << - result.toString(); + } else if(result.isString()) { + qDebug() << "Error - return value of get_required_nr_of_samples() is a string - " << result.toString(); } else { - qDebug() << "Error - get_required_nr_of_samples - "<< result.toString(); + qDebug() << "Error - get_required_nr_of_samples - " << result.toString(); } return 0; @@ -2523,13 +2110,12 @@ bool JSPattern::is_periodic() { QJSValue result = qEngine->evaluate("is_periodic()"); - if (result.isBool()) { + if(result.isBool()) { return result.toBool(); - } else if (result.isString()) { - qDebug() << "Error - return value of is_periodic() is a string - " << - result.toString(); + } else if(result.isString()) { + qDebug() << "Error - return value of is_periodic() is a string - " << result.toString(); } else { - qDebug() << "Error - is_periodic - "<< result.toString(); + qDebug() << "Error - is_periodic - " << result.toString(); } return 0; @@ -2537,9 +2123,8 @@ bool JSPattern::is_periodic() uint8_t JSPattern::pre_generate() { - QString fileName(obj["filepath"].toString() + - obj["generate_script"].toString()); - qDebug()<evaluate("function is_periodic(){ status_window.print(\"is_periodic() not found\")}"); - qEngine->evaluate("function get_required_nr_of_samples(){ status_window.print(\"get_required_nr_of_samples() not found\")}"); - qEngine->evaluate("function get_min_sampling_freq(){ status_window.print(\"get_min_sampling_freq() not found\")}"); + qEngine->evaluate("function get_required_nr_of_samples(){ status_window.print(\"get_required_nr_of_samples() " + "not found\")}"); + qEngine->evaluate( + "function get_min_sampling_freq(){ status_window.print(\"get_min_sampling_freq() not found\")}"); qEngine->evaluate("function generate(){ status_window.print(\"generate() not found\")}"); // if file does not exist, stream will be empty - handle_result(qEngine->evaluate(contents, fileName),"Eval generatescript"); - + handle_result(qEngine->evaluate(contents, fileName), "Eval generatescript"); return 0; } -bool JSPattern::handle_result(QJSValue result,QString str) +bool JSPattern::handle_result(QJSValue result, QString str) { - if (result.isError()) { - qDebug() - << "Uncaught exception at line" - << result.property("lineNumber").toInt() - << ":" << result.toString(); + if(result.isError()) { + qDebug() << "Uncaught exception at line" << result.property("lineNumber").toInt() << ":" + << result.toString(); return -2; } else { - qDebug()<sample_rate = sample_rate; this->number_of_channels = number_of_channels; this->number_of_samples = number_of_samples; - handle_result(qEngine->evaluate("generate()"),"Eval generate"); - commitBuffer(qEngine->evaluate("pg.buffer"),qEngine->evaluate("pg.buffersize")); + handle_result(qEngine->evaluate("generate()"), "Eval generate"); + commitBuffer(qEngine->evaluate("pg.buffer"), qEngine->evaluate("pg.buffersize")); return 0; } -quint32 JSPattern::get_nr_of_samples() -{ - return number_of_samples; -} +quint32 JSPattern::get_nr_of_samples() { return number_of_samples; } -quint32 JSPattern::get_nr_of_channels() -{ - return number_of_channels; -} +quint32 JSPattern::get_nr_of_channels() { return number_of_channels; } -quint32 JSPattern::get_sample_rate() -{ - return sample_rate; -} +quint32 JSPattern::get_sample_rate() { return sample_rate; } -void JSPattern::JSErrorDialog(QString errorMessage) -{ - qDebug()<<"JSErrorDialog: "<parse_ui(); -} +void JSPatternUIScript_API::parse_ui() { pattern->parse_ui(); } -JSPatternUI::JSPatternUI(JSPattern *pat,QJsonObject obj_, - QWidget *parent) : pattern(pat), parent_(parent), jspat_api(nullptr), PatternUI(parent) +JSPatternUI::JSPatternUI(JSPattern *pat, QJsonObject obj_, QWidget *parent) + : pattern(pat) + , parent_(parent) + , jspat_api(nullptr) + , PatternUI(parent) { - qDebug()<<"JSPatternUI created"; + qDebug() << "JSPatternUI created"; loader = nullptr; pattern->ui_form = nullptr; ui = new Ui::GenericJSPatternUI(); ui->setupUi(this); setVisible(false); textedit = new JSPatternUIStatusWindow(ui->jsstatus); - //ui->jsstatus->setVisible(false); - + // ui->jsstatus->setVisible(false); } -JSPatternUI::~JSPatternUI() +JSPatternUI::~JSPatternUI() { qDebug() << "JSPatternUI destroyed"; } +void JSPatternUI::build_ui(QWidget *parent, uint16_t number_of_channels) { - qDebug()<<"JSPatternUI destroyed"; - -} -void JSPatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) -{ - qDebug()<<"JSPatternUI built"; - jspat_api = new JSPatternUIScript_API(this,this); + qDebug() << "JSPatternUI built"; + jspat_api = new JSPatternUIScript_API(this, this); parent_ = parent; parent->layout()->addWidget(this); - QFile file(pattern->obj["filepath"].toString() + - pattern->obj["ui_form"].toString()); + QFile file(pattern->obj["filepath"].toString() + pattern->obj["ui_form"].toString()); file.open(QFile::ReadOnly); - if (file.exists() && file.isReadable()) { + if(file.exists() && file.isReadable()) { loader = new QUiLoader; pattern->ui_form = loader->load(&file, ui->ui_form); file.close(); @@ -2676,35 +2241,33 @@ void JSPatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) } else { qDebug() << "file does not exist"; } - - } void JSPatternUI::destroy_ui() { - if (pattern->ui_form) { + if(pattern->ui_form) { delete pattern->ui_form; } - if (loader) { + if(loader) { delete loader; } parent_->layout()->removeWidget(this); - //delete ui_form; + // delete ui_form; // delete ui; } void JSPatternUI::find_all_children(QObject *parent, QJSValue property) { - if (parent->children().count() == 0) { + if(parent->children().count() == 0) { return; } - for (auto child: parent->children()) { - if (child->objectName()!="") { + for(auto child : parent->children()) { + if(child->objectName() != "") { QJSValue jschild = pattern->qEngine->newQObject(child); - property.setProperty(child->objectName(),jschild); + property.setProperty(child->objectName(), jschild); QQmlEngine::setObjectOwnership(child, QQmlEngine::CppOwnership); find_all_children(child, property.property(child->objectName())); @@ -2714,9 +2277,8 @@ void JSPatternUI::find_all_children(QObject *parent, QJSValue property) void JSPatternUI::post_load_ui() { - QString fileName(pattern->obj["filepath"].toString() + - pattern->obj["ui_script"].toString()); - qDebug()<obj["filepath"].toString() + pattern->obj["ui_script"].toString()); + qDebug() << fileName; QFile scriptFile(fileName); scriptFile.open(QIODevice::ReadOnly); QTextStream stream(&scriptFile); @@ -2725,29 +2287,24 @@ void JSPatternUI::post_load_ui() JSPattern *pg = pattern; JSPatternUIStatusWindow *status_window = textedit; - QJSValue pgObj = pattern->qEngine->newQObject(pg); - QJSValue consoleObj = pattern->qEngine->newQObject(pattern->console); - QJSValue statusTextObj = pattern->qEngine->newQObject(status_window); + QJSValue pgObj = pattern->qEngine->newQObject(pg); + QJSValue consoleObj = pattern->qEngine->newQObject(pattern->console); + QJSValue statusTextObj = pattern->qEngine->newQObject(status_window); QJSValue parseuiobj = pattern->qEngine->newQObject(jspat_api); - QJSValue uiObj = - pattern->qEngine->newQObject(/*ui_form*/ui->ui_form->findChild - (form_name)); + QJSValue uiObj = pattern->qEngine->newQObject(/*ui_form*/ ui->ui_form->findChild(form_name)); - pattern->qEngine->globalObject().setProperty("pg",pgObj); - QQmlEngine::setObjectOwnership(/*(QObject*)*/pg, QQmlEngine::CppOwnership); + pattern->qEngine->globalObject().setProperty("pg", pgObj); + QQmlEngine::setObjectOwnership(/*(QObject*)*/ pg, QQmlEngine::CppOwnership); pattern->qEngine->globalObject().setProperty("console", consoleObj); - QQmlEngine::setObjectOwnership(/*(QObject*)*/pattern->console, - QQmlEngine::CppOwnership); + QQmlEngine::setObjectOwnership(/*(QObject*)*/ pattern->console, QQmlEngine::CppOwnership); pattern->qEngine->globalObject().setProperty("ui", uiObj); - QQmlEngine::setObjectOwnership(/*(QObject*)*/pattern->ui_form, - QQmlEngine::CppOwnership); + QQmlEngine::setObjectOwnership(/*(QObject*)*/ pattern->ui_form, QQmlEngine::CppOwnership); pattern->qEngine->globalObject().setProperty("script", parseuiobj); - QQmlEngine::setObjectOwnership(/*(QObject*)*/this, QQmlEngine::CppOwnership); + QQmlEngine::setObjectOwnership(/*(QObject*)*/ this, QQmlEngine::CppOwnership); pattern->qEngine->globalObject().setProperty("status_window", statusTextObj); - QQmlEngine::setObjectOwnership(/*(QObject*)*/status_window, - QQmlEngine::CppOwnership); + QQmlEngine::setObjectOwnership(/*(QObject*)*/ status_window, QQmlEngine::CppOwnership); pattern->qEngine->evaluate("ui_elements = [];"); @@ -2757,60 +2314,44 @@ void JSPatternUI::post_load_ui() pattern->qEngine->evaluate("pg.buffer = [];").toString(); pattern->qEngine->evaluate("pg.buffersize = 0;").toString(); - pattern->qEngine->evaluate("function post_load_ui(){ status_window.print(\"post_load_ui() not found\")}"); pattern->qEngine->evaluate("function parse_ui(){ status_window.print(\"parse_ui() not found\")}"); - handle_result(pattern->qEngine->evaluate(contents, fileName),"eval ui_script"); - handle_result(pattern->qEngine->evaluate("post_load_ui()"),"post_load_ui"); + handle_result(pattern->qEngine->evaluate(contents, fileName), "eval ui_script"); + handle_result(pattern->qEngine->evaluate("post_load_ui()"), "post_load_ui"); } void JSPatternUI::parse_ui() { - handle_result(pattern->qEngine->evaluate("parse_ui_callback()"),"parse_ui"); + handle_result(pattern->qEngine->evaluate("parse_ui_callback()"), "parse_ui"); Q_EMIT patternParamsChanged(); } -Pattern *JSPatternUI::get_pattern() -{ - return pattern; -} +Pattern *JSPatternUI::get_pattern() { return pattern; } -bool JSPatternUI::handle_result(QJSValue result,QString str) +bool JSPatternUI::handle_result(QJSValue result, QString str) { - pattern->handle_result(result,str); + pattern->handle_result(result, str); - if (result.isError()) { + if(result.isError()) { /* qDebug() << "Uncaught exception at line" << result.property("lineNumber").toInt() << ":" << result.toString(); return -2;*/ - textedit->print((QString)"Uncaught exception at line" + - result.property("lineNumber").toString() + ":" + result.toString()); + textedit->print((QString) "Uncaught exception at line" + result.property("lineNumber").toString() + + ":" + result.toString()); return -2; } else { textedit->print(str + " - Success"); return 0; } - - -} - -JSPatternUIStatusWindow::JSPatternUIStatusWindow(QTextEdit *textedit) -{ - con = textedit; -} -void JSPatternUIStatusWindow::clear() -{ - con->clear(); } -void JSPatternUIStatusWindow::print(QString str) -{ - con->append(str); -} +JSPatternUIStatusWindow::JSPatternUIStatusWindow(QTextEdit *textedit) { con = textedit; } +void JSPatternUIStatusWindow::clear() { con->clear(); } +void JSPatternUIStatusWindow::print(QString str) { con->append(str); } #if 0 @@ -3412,55 +2953,31 @@ void WalkingPatternUI::destroy_ui() #endif -uint32_t ImportPattern::get_min_sampling_freq() -{ - return frequency; -} +uint32_t ImportPattern::get_min_sampling_freq() { return frequency; } -uint32_t ImportPattern::get_required_nr_of_samples(uint32_t sample_rate, - uint32_t number_of_channels) +uint32_t ImportPattern::get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels) { // greatest common divider duty cycle and 1000;0; - uint32_t period_number_of_samples = ((uint32_t)sample_rate/frequency) * data.size(); + uint32_t period_number_of_samples = ((uint32_t)sample_rate / frequency) * data.size(); return period_number_of_samples; } +float ImportPattern::get_frequency() const { return frequency; } -float ImportPattern::get_frequency() const -{ - return frequency; -} - -void ImportPattern::set_frequency(float value) -{ - frequency = value; -} - +void ImportPattern::set_frequency(float value) { frequency = value; } -float ImportPattern::getFrequency() const -{ - return frequency; -} +float ImportPattern::getFrequency() const { return frequency; } -void ImportPattern::setFrequency(float value) -{ - frequency = value; -} +void ImportPattern::setFrequency(float value) { frequency = value; } -bool ImportPattern::useNativeDialog() const -{ - return nativeDialog; -} +bool ImportPattern::useNativeDialog() const { return nativeDialog; } -void ImportPattern::setNativeDialog(bool nativeDialog) -{ - this->nativeDialog = nativeDialog; -} +void ImportPattern::setNativeDialog(bool nativeDialog) { this->nativeDialog = nativeDialog; } -ImportPattern::ImportPattern(): - fileName(""), - channel_mapping(0), - nativeDialog(true) +ImportPattern::ImportPattern() + : fileName("") + , channel_mapping(0) + , nativeDialog(true) { set_name("Import"); set_description("Import pattern"); @@ -3468,49 +2985,42 @@ ImportPattern::ImportPattern(): set_frequency(5000); } -ImportPattern::~ImportPattern() -{ - -} +ImportPattern::~ImportPattern() {} -uint8_t ImportPattern::generate_pattern(uint32_t sample_rate, - uint32_t number_of_samples, uint16_t number_of_channels) +uint8_t ImportPattern::generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels) { - float f_period_number_of_samples = (float)sample_rate/frequency; - qDebug()<<"period_number_of_samples - "<setupUi(this); - frequencySpinButton = new ScaleSpinButton({ - {"Hz", 1E0}, - {"kHz", 1E+3}, - {"MHz", 1E+6} - }, tr("Frequency"), 1e0, PG_MAX_SAMPLERATE/2,true,false,this, {1,2.5,5}); + frequencySpinButton = new ScaleSpinButton({{"Hz", 1E0}, {"kHz", 1E+3}, {"MHz", 1E+6}}, tr("Frequency"), 1e0, + PG_MAX_SAMPLERATE / 2, true, false, this, {1, 2.5, 5}); import_settings = new ImportSettings(this); fileLineEdit = new QLineEdit(this); openFileBtn = new QPushButton(tr("Open file"), this); @@ -3541,36 +3051,33 @@ void ImportPatternUI::setStylesheet() "font-style: normal;" "text-align: center;" "color: #ffffff;" - "}" + "}" "QPushButton:disabled {" "background-color: gray;" "color:white;" "}" - "QPushButton:hover" - "{" + "QPushButton:hover" + "{" "background-color: #4a34ff;" - "}"; + "}"; openFileBtn->setStyleSheet(style); importBtn->setStyleSheet(style); } ImportPatternUI::~ImportPatternUI() { - //qDebug()<<"ClockPatternUI destroyed"; + // qDebug()<<"ClockPatternUI destroyed"; delete ui; } -Pattern *ImportPatternUI::get_pattern() -{ - return pattern; -} +Pattern *ImportPatternUI::get_pattern() { return pattern; } void ImportPatternUI::reloadFileData() { try { loadFileData(this->fileName); parse_ui(); - } catch (FileManagerException &e) { + } catch(FileManagerException &e) { fileLineEdit->setText(QString(e.what())); fileLineEdit->setToolTip(""); importBtn->setDisabled(true); @@ -3579,26 +3086,25 @@ void ImportPatternUI::reloadFileData() void ImportPatternUI::loadFileData(QString fileName) { - FileManager fm("Pattern Generator"); - fm.open(fileName, FileManager::IMPORT); - data.clear(); - data = fm.read(); - this->fileName = fileName; - pattern->fileName = fileName; + FileManager fm("Pattern Generator"); + fm.open(fileName, FileManager::IMPORT); + data.clear(); + data = fm.read(); + this->fileName = fileName; + pattern->fileName = fileName; } - -void ImportPatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) +void ImportPatternUI::build_ui(QWidget *parent, uint16_t number_of_channels) { parent_ = parent; parent->layout()->addWidget(this); - requestedFrequency=pattern->get_frequency(); + requestedFrequency = pattern->get_frequency(); frequencySpinButton->setValue(pattern->get_frequency()); try { loadFileData(fileName); import_settings->clear(); - for (int i = 0; i < data[0].size(); ++i) { + for(int i = 0; i < data[0].size(); ++i) { import_settings->addChannel(i, "CH" + QString::number(i)); } @@ -3610,30 +3116,32 @@ void ImportPatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) unsigned short mask = pattern->channel_mapping; QMap config; - for (int i = 0; i < data[0].size(); ++i) { - config[i] = (bool) (mask & (1 << i)); + for(int i = 0; i < data[0].size(); ++i) { + config[i] = (bool)(mask & (1 << i)); } import_settings->setExportConfig(config); parse_ui(); - } catch (FileManagerException &e) { + } catch(FileManagerException &e) { fileLineEdit->setText(QString(e.what())); fileLineEdit->setToolTip(""); importBtn->setDisabled(true); } - connect(openFileBtn, &QPushButton::clicked, [=](){ - QString fileName = QFileDialog::getOpenFileName(this, - tr("Export"), "", tr("Comma-separated values files (*.csv);;" - "Tab-delimited values files (*.txt)"), - nullptr, (pattern->useNativeDialog() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); + connect(openFileBtn, &QPushButton::clicked, [=]() { + QString fileName = QFileDialog::getOpenFileName( + this, tr("Export"), "", + tr("Comma-separated values files (*.csv);;" + "Tab-delimited values files (*.txt)"), + nullptr, + (pattern->useNativeDialog() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); try { loadFileData(fileName); import_settings->clear(); - for (int i = 0; i < data[0].size(); ++i) { + for(int i = 0; i < data[0].size(); ++i) { import_settings->addChannel(i, "CH" + QString::number(i)); } @@ -3642,56 +3150,51 @@ void ImportPatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) import_settings->setDisabled(false); importBtn->setDisabled(false); - } catch (FileManagerException &e) { + } catch(FileManagerException &e) { fileLineEdit->setText(QString(e.what())); fileLineEdit->setToolTip(""); importBtn->setDisabled(true); } - }); - connect(frequencySpinButton,SIGNAL(valueChanged(double)),this,SLOT(parse_ui())); + connect(frequencySpinButton, SIGNAL(valueChanged(double)), this, SLOT(parse_ui())); connect(importBtn, &QPushButton::clicked, this, &ImportPatternUI::reloadFileData); - -} -void ImportPatternUI::destroy_ui() -{ - parent_->layout()->removeWidget(this); } +void ImportPatternUI::destroy_ui() { parent_->layout()->removeWidget(this); } void ImportPatternUI::parse_ui() { QObject *obj = sender(); bool freqStepDown = false; - if (obj==frequencySpinButton) { - if (frequencySpinButton->value() < requestedFrequency) { - freqStepDown=true; + if(obj == frequencySpinButton) { + if(frequencySpinButton->value() < requestedFrequency) { + freqStepDown = true; } requestedFrequency = frequencySpinButton->value(); } - auto freq=requestedFrequency;//frequencySpinButton->value(); + auto freq = requestedFrequency; // frequencySpinButton->value(); long div; - if (freqStepDown) { - div=(long)ceil((double)PG_MAX_SAMPLERATE/freq); + if(freqStepDown) { + div = (long)ceil((double)PG_MAX_SAMPLERATE / freq); } else { - div=(long)floor((double)PG_MAX_SAMPLERATE/freq); + div = (long)floor((double)PG_MAX_SAMPLERATE / freq); } unsigned short mask = 0; auto keys = import_settings->getExportConfig().keys(); - for (int key : qAsConst(keys)) { + for(int key : qAsConst(keys)) { mask = mask | (import_settings->getExportConfig()[key] << key); } pattern->channel_mapping = mask; pattern->data.clear(); - for (int i = 0; i < data.size(); ++i) { + for(int i = 0; i < data.size(); ++i) { int k = 0; unsigned short line_mask = 0; - for (int j = 0 ; j < data[i].size(); ++j) { - if (mask & (1 << j) ) { + for(int j = 0; j < data[i].size(); ++j) { + if(mask & (1 << j)) { line_mask |= ((int)data[i][j] << k); k++; } @@ -3699,28 +3202,22 @@ void ImportPatternUI::parse_ui() pattern->data.push_back(line_mask); } - freq=(PG_MAX_SAMPLERATE)/(float)div; - requestedFrequency=freq; + freq = (PG_MAX_SAMPLERATE) / (float)div; + requestedFrequency = freq; frequencySpinButton->blockSignals(true); frequencySpinButton->setValue(freq); frequencySpinButton->blockSignals(false); pattern->set_frequency(freq); pattern->fileName = fileName; - - Q_EMIT patternParamsChanged(); - } - - int PatternFactory::static_ui_limit = 0; QStringList PatternFactory::ui_list = {}; QStringList PatternFactory::description_list = {}; QJsonObject PatternFactory::patterns = {}; - void PatternFactory::init() { QJsonObject pattern_object; @@ -3765,11 +3262,10 @@ void PatternFactory::init() static_ui_limit = ui_list.count(); QString searchPattern = "generator.json"; - QDirIterator it("patterngenerator", QStringList() << searchPattern, QDir::Files, - QDirIterator::Subdirectories); + QDirIterator it("patterngenerator", QStringList() << searchPattern, QDir::Files, QDirIterator::Subdirectories); int i = 0; - while (it.hasNext()) { + while(it.hasNext()) { QFile file; QString filename = it.next(); @@ -3780,28 +3276,26 @@ void PatternFactory::init() QJsonObject obj(d.object()); filename.chop(searchPattern.length()); - obj.insert("filepath",filename); + obj.insert("filepath", filename); - if (obj["enabled"] == true) { + if(obj["enabled"] == true) { ui_list.append(obj["name"].toString()); description_list.append(obj["description"].toString()); - pattern_object.insert(QString::number(i),QJsonValue(obj)); + pattern_object.insert(QString::number(i), QJsonValue(obj)); i++; } - } patterns = pattern_object; - qDebug()<=static_ui_limit) { - return new JSPattern(patterns[QString::number(index - -static_ui_limit)].toObject()); + if(index >= static_ui_limit) { + return new JSPattern(patterns[QString::number(index - static_ui_limit)].toObject()); } else { return nullptr; } @@ -3876,67 +3369,58 @@ Pattern *PatternFactory::create(int index) PatternUI *PatternFactory::create_ui(Pattern *pattern, QWidget *parent) { - int i=0; + int i = 0; QString name = QString::fromStdString(pattern->get_name()); - for (const auto &str : qAsConst(ui_list)) { - if (name==str) { - return create_ui(pattern,i,parent); + for(const auto &str : qAsConst(ui_list)) { + if(name == str) { + return create_ui(pattern, i, parent); } i++; } - return create_ui(pattern,0,parent); + return create_ui(pattern, 0, parent); } -PatternUI *PatternFactory::create_ui(Pattern *pattern, int index, - QWidget *parent) +PatternUI *PatternFactory::create_ui(Pattern *pattern, int index, QWidget *parent) { - switch (index) { + switch(index) { case ClockPatternId: - return new ClockPatternUI(dynamic_cast(pattern),parent); + return new ClockPatternUI(dynamic_cast(pattern), parent); case RandomPatternId: - return new RandomPatternUI(dynamic_cast(pattern),parent); + return new RandomPatternUI(dynamic_cast(pattern), parent); case BinaryCounterId: - return new BinaryCounterPatternUI(dynamic_cast(pattern), - parent); + return new BinaryCounterPatternUI(dynamic_cast(pattern), parent); case UARTPatternId: - return new UARTPatternUI(dynamic_cast(pattern), - parent); + return new UARTPatternUI(dynamic_cast(pattern), parent); case PulsePatternId: - return new PulsePatternUI(dynamic_cast(pattern), parent); + return new PulsePatternUI(dynamic_cast(pattern), parent); case NumberPatternId: - return new NumberPatternUI(dynamic_cast(pattern), - parent); + return new NumberPatternUI(dynamic_cast(pattern), parent); case GrayCounterId: - return new GrayCounterPatternUI(dynamic_cast(pattern), - parent); + return new GrayCounterPatternUI(dynamic_cast(pattern), parent); case SPIPatternId: - return new SPIPatternUI(dynamic_cast(pattern), - parent); + return new SPIPatternUI(dynamic_cast(pattern), parent); case I2CPatternId: - return new I2CPatternUI(dynamic_cast(pattern), - parent); + return new I2CPatternUI(dynamic_cast(pattern), parent); case ImportPatternId: - return new ImportPatternUI(dynamic_cast(pattern), - parent); - + return new ImportPatternUI(dynamic_cast(pattern), parent); default: - if (index>=static_ui_limit) { + if(index >= static_ui_limit) { auto jspat = dynamic_cast(pattern); if(jspat) - return new JSPatternUI(jspat, - patterns[QString::number(static_ui_limit-index)].toObject(), parent); + return new JSPatternUI( + jspat, patterns[QString::number(static_ui_limit - index)].toObject(), parent); else return nullptr; } else { @@ -3956,30 +3440,16 @@ PatternUI *PatternFactory::create_ui(Pattern *pattern, int index, } } +QStringList PatternFactory::get_ui_list() { return ui_list; } +QStringList PatternFactory::get_description_list() { return description_list; } -QStringList PatternFactory::get_ui_list() -{ - return ui_list; -} - -QStringList PatternFactory::get_description_list() -{ - return description_list; -} - - -double PulsePattern::get_sample_rate() const -{ - return sample_rate; -} +double PulsePattern::get_sample_rate() const { return sample_rate; } -void PulsePattern::set_sample_rate(double value) -{ - sample_rate = value; -} +void PulsePattern::set_sample_rate(double value) { sample_rate = value; } -PulsePattern::PulsePattern() : Pattern() +PulsePattern::PulsePattern() + : Pattern() { set_name(PulsePatternName); set_description(PulsePatternDescription); @@ -3991,13 +3461,9 @@ PulsePattern::PulsePattern() : Pattern() set_delay(0); set_no_pulses(1); set_start(0); - } -PulsePattern::~PulsePattern() -{ - -} +PulsePattern::~PulsePattern() {} uint8_t PulsePattern::generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels) { @@ -4017,32 +3483,27 @@ uint8_t PulsePattern::generate_pattern(uint32_t sample_rate, uint32_t number_of_ // can happen when specifiyng 0 delay, 0 high, 0 low samples if(period_number_of_samples == 0) { - while(buffer_ptr < buffer_stop){ + while(buffer_ptr < buffer_stop) { *buffer_ptr = buffer_val; buffer_ptr++; } return 0; } - while (buffer_ptr < buffer_stop) - { - for(size_t j = 0; j < delay; j++, buffer_ptr++) - { + while(buffer_ptr < buffer_stop) { + for(size_t j = 0; j < delay; j++, buffer_ptr++) { *buffer_ptr = buffer_val; } - for(size_t j = 0; j < no_pulses; j++) - { + for(size_t j = 0; j < no_pulses; j++) { auto cnt = counter_init % (low_number_of_samples + high_number_of_samples); for(size_t k = 0; k < low_number_of_samples + high_number_of_samples; k++, buffer_ptr++) { if(cnt >= high_number_of_samples + low_number_of_samples) - cnt=0; + cnt = 0; if(cnt < low_number_of_samples) { *buffer_ptr = 0x0000; cnt++; - } - else if (cnt >= low_number_of_samples && - cnt < (low_number_of_samples + high_number_of_samples)) - { + } else if(cnt >= low_number_of_samples && + cnt < (low_number_of_samples + high_number_of_samples)) { *buffer_ptr = 0xffff; cnt++; } @@ -4052,139 +3513,90 @@ uint8_t PulsePattern::generate_pattern(uint32_t sample_rate, uint32_t number_of_ return 0; } -uint32_t PulsePattern::get_min_sampling_freq() -{ - return sample_rate; -} +uint32_t PulsePattern::get_min_sampling_freq() { return sample_rate; } -uint32_t PulsePattern::get_required_nr_of_samples(uint32_t sample_rate, - uint32_t number_of_channels) +uint32_t PulsePattern::get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels) { - return delay+(no_pulses*(high_number_of_samples+low_number_of_samples)); + return delay + (no_pulses * (high_number_of_samples + low_number_of_samples)); } -bool PulsePattern::get_start() -{ - return start; -} +bool PulsePattern::get_start() { return start; } -uint32_t PulsePattern::get_low_number_of_samples() -{ - return low_number_of_samples; -} +uint32_t PulsePattern::get_low_number_of_samples() { return low_number_of_samples; } -uint32_t PulsePattern::get_high_number_of_samples() -{ - return high_number_of_samples; -} +uint32_t PulsePattern::get_high_number_of_samples() { return high_number_of_samples; } -uint32_t PulsePattern::get_counter_init() -{ - return counter_init; -} +uint32_t PulsePattern::get_counter_init() { return counter_init; } -uint32_t PulsePattern::get_delay() -{ - return delay; -} +uint32_t PulsePattern::get_delay() { return delay; } -uint32_t PulsePattern::get_no_pulses() -{ - return no_pulses; -} +uint32_t PulsePattern::get_no_pulses() { return no_pulses; } -void PulsePattern::set_start(bool val) -{ - start=val; -} +void PulsePattern::set_start(bool val) { start = val; } -void PulsePattern::set_low_number_of_samples(uint32_t val) -{ - low_number_of_samples=val; -} +void PulsePattern::set_low_number_of_samples(uint32_t val) { low_number_of_samples = val; } -void PulsePattern::set_high_number_of_samples(uint32_t val) -{ - high_number_of_samples=val; -} +void PulsePattern::set_high_number_of_samples(uint32_t val) { high_number_of_samples = val; } -void PulsePattern::set_counter_init(uint32_t val) -{ - counter_init=val; -} +void PulsePattern::set_counter_init(uint32_t val) { counter_init = val; } -void PulsePattern::set_delay(uint32_t val) -{ - delay=val; -} +void PulsePattern::set_delay(uint32_t val) { delay = val; } -void PulsePattern::set_no_pulses(uint32_t val) -{ - no_pulses=val; -} +void PulsePattern::set_no_pulses(uint32_t val) { no_pulses = val; } -PulsePatternUI::PulsePatternUI(PulsePattern *pattern, - QWidget *parent) : PatternUI(parent), pattern(pattern), parent_(parent) +PulsePatternUI::PulsePatternUI(PulsePattern *pattern, QWidget *parent) + : PatternUI(parent) + , pattern(pattern) + , parent_(parent) { - qDebug()<<"PulsePatternUI created"; + qDebug() << "PulsePatternUI created"; ui = new Ui::PulsePatternUI(); ui->setupUi(this); - frequencySpinButton = new ScaleSpinButton({ - {"Hz", 1E0}, - {"kHz", 1E+3}, - {"MHz", 1E+6} - }, tr("Sample Rate"), 1e0, PG_MAX_SAMPLERATE,true,false,this, {1,2.5,5}); + frequencySpinButton = new ScaleSpinButton({{"Hz", 1E0}, {"kHz", 1E+3}, {"MHz", 1E+6}}, tr("Sample Rate"), 1e0, + PG_MAX_SAMPLERATE, true, false, this, {1, 2.5, 5}); ui->verticalLayout_2->addWidget(frequencySpinButton); setVisible(false); } -PulsePatternUI::~PulsePatternUI() -{ - qDebug()<<"PulsePatternUI destroyed"; -} +PulsePatternUI::~PulsePatternUI() { qDebug() << "PulsePatternUI destroyed"; } -Pattern *PulsePatternUI::get_pattern() -{ - return pattern; -} +Pattern *PulsePatternUI::get_pattern() { return pattern; } void PulsePatternUI::parse_ui() { - bool ok =0; + bool ok = 0; int val; - val = ui->start_CB->currentText().toInt(&ok,10); + val = ui->start_CB->currentText().toInt(&ok, 10); pattern->set_start(val); - val = ui->counterInit_LE->text().toInt(&ok,10); + val = ui->counterInit_LE->text().toInt(&ok, 10); val = (val < 0) ? 0 : val; pattern->set_counter_init(val); - val = ui->low_LE->text().toInt(&ok,10); + val = ui->low_LE->text().toInt(&ok, 10); val = (val < 0) ? 0 : val; pattern->set_low_number_of_samples(val); - val = ui->high_LE->text().toInt(&ok,10); + val = ui->high_LE->text().toInt(&ok, 10); val = (val < 0) ? 0 : val; pattern->set_high_number_of_samples(val); - - val = ui->delay_LE->text().toInt(&ok,10); + val = ui->delay_LE->text().toInt(&ok, 10); val = (val < 0) ? 0 : val; pattern->set_delay(val); - val = ui->noPulses_LE->text().toInt(&ok,10); + val = ui->noPulses_LE->text().toInt(&ok, 10); val = (val < 0) ? 0 : val; pattern->set_no_pulses(val); pattern->set_sample_rate(frequencySpinButton->value()); Q_EMIT patternParamsChanged(); - } -void PulsePatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) +void PulsePatternUI::build_ui(QWidget *parent, uint16_t number_of_channels) { parent_ = parent; parent->layout()->addWidget(this); @@ -4196,20 +3608,16 @@ void PulsePatternUI::build_ui(QWidget *parent,uint16_t number_of_channels) ui->start_CB->setCurrentText(QString::number(pattern->get_start())); frequencySpinButton->setValue(pattern->get_sample_rate()); - connect(ui->counterInit_LE,SIGNAL(textChanged(QString)), this , SLOT(parse_ui())); - connect(ui->delay_LE,SIGNAL(textChanged(QString)), this , SLOT(parse_ui())); - connect(ui->noPulses_LE,SIGNAL(textChanged(QString)), this , SLOT(parse_ui())); - connect(ui->high_LE,SIGNAL(textChanged(QString)), this , SLOT(parse_ui())); - connect(ui->low_LE,SIGNAL(textChanged(QString)), this , SLOT(parse_ui())); - connect(ui->start_CB,SIGNAL(activated(QString)), this , SLOT(parse_ui())); - connect(frequencySpinButton,SIGNAL(valueChanged(double)),this,SLOT(parse_ui())); + connect(ui->counterInit_LE, SIGNAL(textChanged(QString)), this, SLOT(parse_ui())); + connect(ui->delay_LE, SIGNAL(textChanged(QString)), this, SLOT(parse_ui())); + connect(ui->noPulses_LE, SIGNAL(textChanged(QString)), this, SLOT(parse_ui())); + connect(ui->high_LE, SIGNAL(textChanged(QString)), this, SLOT(parse_ui())); + connect(ui->low_LE, SIGNAL(textChanged(QString)), this, SLOT(parse_ui())); + connect(ui->start_CB, SIGNAL(activated(QString)), this, SLOT(parse_ui())); + connect(frequencySpinButton, SIGNAL(valueChanged(double)), this, SLOT(parse_ui())); parse_ui(); } -void PulsePatternUI::destroy_ui() -{ - parent_->layout()->removeWidget(this); -} - -} // namespace scopy +void PulsePatternUI::destroy_ui() { parent_->layout()->removeWidget(this); } +} // namespace scopy::m2k diff --git a/plugins/m2k/src/old/patterngenerator/patterns/patterns.hpp b/plugins/m2k/src/old/patterngenerator/patterns/patterns.hpp index 6c709a9f14..55ba7cbbdc 100644 --- a/plugins/m2k/src/old/patterngenerator/patterns/patterns.hpp +++ b/plugins/m2k/src/old/patterngenerator/patterns/patterns.hpp @@ -21,38 +21,39 @@ #ifndef PG_PATTERNS_HPP #define PG_PATTERNS_HPP -#include -#include +#include "gui/osc_import_settings.h" +#include "gui/spinbox_a.hpp" + +#include #include #include -#include +#include +#include #include #include -#include + #include -#include #include -#include "gui/spinbox_a.hpp" -#include "gui/osc_import_settings.h" +#include +#include // Generated UI +#include "filemanager.h" +#include "gui/genericlogicplotcurve.h" +#include "sigrok-gui/decoder.h" + #include "ui_binarycounterpatternui.h" -#include "ui_uartpatternui.h" -#include "ui_lfsrpatternui.h" +#include "ui_constantpattern.h" #include "ui_emptypatternui.h" +#include "ui_frequencypattern.h" #include "ui_genericjspatternui.h" -#include "ui_constantpattern.h" +#include "ui_i2cpatternui.h" +#include "ui_lfsrpatternui.h" #include "ui_numberpattern.h" -#include "ui_frequencypattern.h" #include "ui_pulsepattern.h" -#include "ui_walkingpattern.h" #include "ui_spipatternui.h" -#include "ui_i2cpatternui.h" -#include "filemanager.h" - -#include "gui/genericlogicplotcurve.h" -#include "sigrok-gui/decoder.h" - +#include "ui_uartpatternui.h" +#include "ui_walkingpattern.h" namespace Ui { class BinaryCounterPatternUI; @@ -67,11 +68,10 @@ class PulsePatternUI; class WalkingPatternUI; class SPIPatternUI; class I2CPatternUI; -} +} // namespace Ui namespace scopy::m2k { - constexpr char ConstantPatternName[] = "Constant"; constexpr char ConstantPatternDescription[] = "Samples a constant 0 or 1 on the active channels"; constexpr char NumberPatternName[] = "Number"; @@ -99,7 +99,8 @@ constexpr char WalkingCounterPatternDescription[] = "Walking counter pattern gen constexpr char ImportPatternName[] = "Import"; constexpr char ImportPatternDescription[] = "Import pattern generator"; -enum { +enum +{ ClockPatternId = 0, NumberPatternId, RandomPatternId, @@ -112,9 +113,6 @@ enum { ImportPatternId }; - - - // http://stackoverflow.com/questions/32040101/qjsengine-print-to-console class JSConsole : public QObject // for logging purposes in QJSEngine { @@ -131,10 +129,11 @@ class Pattern std::string description; bool periodic; int channels; + protected: // temp short *buffer; -public: +public: Pattern(/*string name_, string description_*/); virtual ~Pattern(); std::string get_name(); @@ -148,10 +147,9 @@ class Pattern virtual uint8_t pre_generate(); virtual bool is_periodic(); virtual uint32_t get_min_sampling_freq(); - virtual uint32_t get_required_nr_of_samples(uint32_t sample_rate, - uint32_t number_of_channels); - virtual uint8_t generate_pattern(uint32_t sample_rate, - uint32_t number_of_samples, uint16_t number_of_channels) = 0; + virtual uint32_t get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels); + virtual uint8_t generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, + uint16_t number_of_channels) = 0; virtual void deinit(); virtual std::string toString(); @@ -160,7 +158,7 @@ class Pattern void setNrOfChannels(int channels); }; -uint32_t changeBit(uint32_t number,uint8_t n, bool x); +uint32_t changeBit(uint32_t number, uint8_t n, bool x); class Pattern_API : public QObject { Q_OBJECT @@ -181,8 +179,8 @@ class PatternUI : public QWidget public: PatternUI(QWidget *parent = 0); virtual ~PatternUI(); - //static PatternUI *create_ui(int index, QWidget *parent = 0); - virtual void build_ui(QWidget *parent = 0,uint16_t number_of_channels=0); + // static PatternUI *create_ui(int index, QWidget *parent = 0); + virtual void build_ui(QWidget *parent = 0, uint16_t number_of_channels = 0); virtual Pattern *get_pattern() = 0; virtual void post_load_ui(); virtual void parse_ui(); @@ -194,26 +192,23 @@ class PatternUI : public QWidget virtual void setAnnotationCurve(GenericLogicPlotCurve *curve) {} virtual QVector getChannelsToAssign() { return {}; } - Q_SIGNALS: void patternParamsChanged(); void decoderChanged(); }; - - class ClockPattern : virtual public Pattern { int duty_cycle_granularity = 20; - int phase_granularity=20; + int phase_granularity = 20; float frequency; float duty_cycle; int phase; + public: ClockPattern(); virtual ~ClockPattern(); - uint8_t generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, - uint16_t number_of_channels); + uint8_t generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels); float get_frequency() const; void set_frequency(float value); float get_duty_cycle() const; @@ -221,9 +216,7 @@ class ClockPattern : virtual public Pattern int get_phase() const; void set_phase(int value); uint32_t get_min_sampling_freq(); - uint32_t get_required_nr_of_samples(uint32_t sample_rate, - uint32_t number_of_channels); - + uint32_t get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels); }; class ClockPatternUI : public PatternUI @@ -235,12 +228,13 @@ class ClockPatternUI : public PatternUI ScaleSpinButton *frequencySpinButton; PhaseSpinButton *phaseSpinButton; PositionSpinButton *dutySpinButton; - double requestedFrequency,requestedDuty,requestedPhase; + double requestedFrequency, requestedDuty, requestedPhase; + public: ClockPatternUI(ClockPattern *pattern, QWidget *parent = 0); virtual ~ClockPatternUI(); Pattern *get_pattern(); - void build_ui(QWidget *parent = 0,uint16_t number_of_channels=0); + void build_ui(QWidget *parent = 0, uint16_t number_of_channels = 0); void destroy_ui(); private Q_SLOTS: @@ -251,18 +245,16 @@ class RandomPattern : virtual public Pattern { protected: uint32_t frequency; + public: RandomPattern(); virtual ~RandomPattern(); uint32_t get_min_sampling_freq(); - uint32_t get_required_nr_of_samples(uint32_t sample_rate, - uint32_t number_of_channels); - uint8_t generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, - uint16_t number_of_channels); + uint32_t get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels); + uint8_t generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels); uint32_t get_frequency() const; - void set_frequency(const uint32_t& value); - + void set_frequency(const uint32_t &value); }; class RandomPatternUI : public PatternUI @@ -272,18 +264,18 @@ class RandomPatternUI : public PatternUI QWidget *parent_; RandomPattern *pattern; ScaleSpinButton *frequencySpinButton; + public: RandomPatternUI(RandomPattern *pattern, QWidget *parent = 0); ~RandomPatternUI(); Pattern *get_pattern(); - void build_ui(QWidget *parent = 0,uint16_t number_of_channels=0); + void build_ui(QWidget *parent = 0, uint16_t number_of_channels = 0); void destroy_ui(); private Q_SLOTS: void parse_ui(); }; - class BinaryCounterPattern : virtual public Pattern { protected: @@ -292,25 +284,24 @@ class BinaryCounterPattern : virtual public Pattern uint16_t end_value; uint16_t increment; uint16_t init_value; + public: BinaryCounterPattern(); virtual ~BinaryCounterPattern(); - virtual uint8_t generate_pattern(uint32_t sample_rate, - uint32_t number_of_samples, uint16_t number_of_channels); + virtual uint8_t generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels); uint32_t get_min_sampling_freq(); - uint32_t get_required_nr_of_samples(uint32_t sample_rate, - uint32_t number_of_channels); + uint32_t get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels); uint32_t get_frequency() const; - void set_frequency(const uint32_t& value); + void set_frequency(const uint32_t &value); uint16_t get_start_value() const; - void set_start_value(const uint16_t& value); + void set_start_value(const uint16_t &value); uint16_t get_end_value() const; - void set_end_value(const uint16_t& value); + void set_end_value(const uint16_t &value); uint16_t get_increment() const; - void set_increment(const uint16_t& value); + void set_increment(const uint16_t &value); uint16_t get_init_value() const; - void set_init_value(const uint16_t& value); + void set_init_value(const uint16_t &value); }; class BinaryCounterPatternUI : public PatternUI @@ -327,7 +318,7 @@ class BinaryCounterPatternUI : public PatternUI BinaryCounterPatternUI(BinaryCounterPattern *pattern, QWidget *parent = 0); ~BinaryCounterPatternUI(); Pattern *get_pattern(); - void build_ui(QWidget *parent = 0,uint16_t number_of_channels=0); + void build_ui(QWidget *parent = 0, uint16_t number_of_channels = 0); void destroy_ui(); public: // Decoder related @@ -340,14 +331,12 @@ private Q_SLOTS: void parse_ui(); }; - class GrayCounterPattern : virtual public BinaryCounterPattern { public: GrayCounterPattern(); virtual ~GrayCounterPattern() {} - uint8_t generate_pattern(uint32_t sample_rate, - uint32_t number_of_samples, uint16_t number_of_channels); + uint8_t generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels); }; class GrayCounterPatternUI : public PatternUI @@ -357,24 +346,25 @@ class GrayCounterPatternUI : public PatternUI QWidget *parent_; GrayCounterPattern *pattern; ScaleSpinButton *frequencySpinButton; + public: GrayCounterPatternUI(GrayCounterPattern *pattern, QWidget *parent = 0); ~GrayCounterPatternUI(); Pattern *get_pattern(); - void build_ui(QWidget *parent = 0,uint16_t number_of_channels=0); + void build_ui(QWidget *parent = 0, uint16_t number_of_channels = 0); void destroy_ui(); private Q_SLOTS: void parse_ui(); }; - class UARTPattern : virtual public Pattern { public: /** Parity settings. */ - enum sp_parity { + enum sp_parity + { /** Special value to indicate setting should be left alone. */ SP_PARITY_INVALID = -1, /** No parity. */ @@ -391,11 +381,9 @@ class UARTPattern : virtual public Pattern UARTPattern(); virtual ~UARTPattern() {} - virtual uint8_t generate_pattern(uint32_t sample_rate, - uint32_t number_of_samples, uint16_t number_of_channels); + virtual uint8_t generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels); uint32_t get_min_sampling_freq(); - uint32_t get_required_nr_of_samples(uint32_t sample_rate, - uint32_t number_of_channels); + uint32_t get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels); unsigned int get_baud_rate(); unsigned int get_data_bits(); @@ -417,7 +405,6 @@ class UARTPattern : virtual public Pattern unsigned int data_bits; unsigned int stop_bits; enum sp_parity parity; - }; class UARTPatternUI : public PatternUI @@ -433,7 +420,7 @@ class UARTPatternUI : public PatternUI UARTPatternUI(UARTPattern *pattern, QWidget *parent = 0); ~UARTPatternUI(); Pattern *get_pattern(); - void build_ui(QWidget *parent = 0,uint16_t number_of_channels=0); + void build_ui(QWidget *parent = 0, uint16_t number_of_channels = 0); void destroy_ui(); public: // Decoder related @@ -445,7 +432,7 @@ private Q_SLOTS: void parse_ui(); }; -class I2CPattern: virtual public Pattern +class I2CPattern : virtual public Pattern { bool tenbit; uint8_t address; @@ -470,29 +457,28 @@ class I2CPattern: virtual public Pattern void sample_await_ack(); void sample_payload(); void sample_stop(); + public: std::deque v; I2CPattern(); virtual ~I2CPattern() {} - virtual uint8_t generate_pattern(uint32_t sample_rate, - uint32_t number_of_samples, uint16_t number_of_channels); + virtual uint8_t generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels); uint32_t get_min_sampling_freq(); - uint32_t get_required_nr_of_samples(uint32_t sample_rate, - uint32_t number_of_channels); + uint32_t get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels); bool getTenbit() const; void setTenbit(bool value); uint8_t getAddress() const; - void setAddress(const uint8_t& value); + void setAddress(const uint8_t &value); bool getWrite() const; void setWrite(bool value); bool getMsbFirst() const; void setMsbFirst(bool value); uint8_t getInterFrameSpace() const; - void setInterFrameSpace(const uint8_t& value); + void setInterFrameSpace(const uint8_t &value); uint32_t getClkFrequency() const; - void setClkFrequency(const uint32_t& value); + void setClkFrequency(const uint32_t &value); uint8_t getBytesPerFrame() const; - void setBytesPerFrame(const uint8_t& value); + void setBytesPerFrame(const uint8_t &value); }; class I2CPatternUI : public PatternUI @@ -504,11 +490,12 @@ class I2CPatternUI : public PatternUI ScaleSpinButton *frequencySpinButton; GenericLogicPlotCurve *m_annotationCurve; std::shared_ptr m_decoder; + public: I2CPatternUI(I2CPattern *pattern, QWidget *parent = 0); ~I2CPatternUI(); Pattern *get_pattern(); - void build_ui(QWidget *parent = 0,uint16_t number_of_channels=0); + void build_ui(QWidget *parent = 0, uint16_t number_of_channels = 0); void destroy_ui(); public: // Decoder related @@ -520,7 +507,6 @@ private Q_SLOTS: void parse_ui(); }; - class SPIPattern : virtual public Pattern { private: @@ -536,11 +522,9 @@ class SPIPattern : virtual public Pattern std::deque v; SPIPattern(); virtual ~SPIPattern() {} - virtual uint8_t generate_pattern(uint32_t sample_rate, - uint32_t number_of_samples, uint16_t number_of_channels); + virtual uint8_t generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels); uint32_t get_min_sampling_freq(); - uint32_t get_required_nr_of_samples(uint32_t sample_rate, - uint32_t number_of_channels); + uint32_t get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels); bool getCSPol() const; void setCSPol(bool value); @@ -549,17 +533,15 @@ class SPIPattern : virtual public Pattern bool getCPHA() const; void setCPHA(bool value); uint32_t getClkFrequency() const; - void setClkFrequency(const uint32_t& value); + void setClkFrequency(const uint32_t &value); uint8_t getWaitClocks() const; - void setWaitClocks(const uint8_t& value); + void setWaitClocks(const uint8_t &value); uint8_t getBytesPerFrame() const; - void setBytesPerFrame(const uint8_t& value); + void setBytesPerFrame(const uint8_t &value); bool getMsbFirst() const; void setMsbFirst(bool value); }; - - class SPIPatternUI : public PatternUI { Q_OBJECT @@ -569,11 +551,12 @@ class SPIPatternUI : public PatternUI ScaleSpinButton *frequencySpinButton; GenericLogicPlotCurve *m_annotationCurve; std::shared_ptr m_decoder; + public: SPIPatternUI(SPIPattern *pattern, QWidget *parent = 0); ~SPIPatternUI(); Pattern *get_pattern(); - void build_ui(QWidget *parent = 0,uint16_t number_of_channels=0); + void build_ui(QWidget *parent = 0, uint16_t number_of_channels = 0); void destroy_ui(); public: // Decoder related @@ -590,13 +573,13 @@ class NumberPattern : virtual public Pattern { private: uint16_t nr; + public: NumberPattern(); virtual ~NumberPattern() {} - virtual uint8_t generate_pattern(uint32_t sample_rate, - uint32_t number_of_samples, uint16_t number_of_channels); + virtual uint8_t generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels); uint16_t get_nr() const; - void set_nr(const uint16_t& value); + void set_nr(const uint16_t &value); }; class NumberPatternUI : public PatternUI @@ -606,26 +589,23 @@ class NumberPatternUI : public PatternUI QWidget *parent_; NumberPattern *pattern; uint16_t max; + public: NumberPatternUI(NumberPattern *pattern, QWidget *parent = 0); ~NumberPatternUI(); Pattern *get_pattern(); - void build_ui(QWidget *parent = 0,uint16_t number_of_channels=0); + void build_ui(QWidget *parent = 0, uint16_t number_of_channels = 0); void destroy_ui(); private Q_SLOTS: void parse_ui(); }; - - - class JSPattern : public QObject, virtual public Pattern { Q_OBJECT private: protected: public: - QJSEngine *qEngine; JSConsole *console; QWidget *ui_form; @@ -640,30 +620,28 @@ class JSPattern : public QObject, virtual public Pattern Q_INVOKABLE quint32 get_nr_of_channels(); Q_INVOKABLE quint32 get_sample_rate(); /*Q_INVOKABLE*/ void JSErrorDialog(QString errorMessage); - /*Q_INVOKABLE*/ void commitBuffer(QJSValue jsBufferValue, - QJSValue jsBufferSize); + /*Q_INVOKABLE*/ void commitBuffer(QJSValue jsBufferValue, QJSValue jsBufferSize); bool is_periodic(); uint32_t get_min_sampling_freq(); uint32_t get_required_nr_of_samples(); void init(); uint8_t pre_generate(); - uint8_t generate_pattern(uint32_t sample_rate, - uint32_t number_of_samples, uint16_t number_of_channels); + uint8_t generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels); void deinit(); - virtual bool handle_result(QJSValue result,QString str = ""); + virtual bool handle_result(QJSValue result, QString str = ""); }; class JSPatternUIStatusWindow : public QObject { Q_OBJECT QTextEdit *con; + public: JSPatternUIStatusWindow(QTextEdit *textedit); Q_INVOKABLE void clear(); Q_INVOKABLE void print(QString str); }; - class JSPatternUIScript_API; class JSPatternUI : public PatternUI @@ -671,20 +649,21 @@ class JSPatternUI : public PatternUI Q_OBJECT QUiLoader *loader; Ui::GenericJSPatternUI *ui; -// QWidget *ui_form; + // QWidget *ui_form; JSPattern *pattern; QString form_name; QWidget *parent_; JSPatternUIScript_API *jspat_api; JSPatternUIStatusWindow *textedit; + public: - JSPatternUI(JSPattern *pat,QJsonObject obj_, QWidget *parent = 0); + JSPatternUI(JSPattern *pat, QJsonObject obj_, QWidget *parent = 0); ~JSPatternUI(); Pattern *get_pattern(); - bool handle_result(QJSValue result,QString str = ""); + bool handle_result(QJSValue result, QString str = ""); void find_all_children(QObject *parent, QJSValue property); - void build_ui(QWidget *parent = 0,uint16_t number_of_channels=0); + void build_ui(QWidget *parent = 0, uint16_t number_of_channels = 0); void post_load_ui(); void destroy_ui(); public Q_SLOTS: @@ -695,6 +674,7 @@ class JSPatternUIScript_API : public QObject { Q_OBJECT JSPatternUI *pattern; + public: JSPatternUIScript_API(QObject *parent, JSPatternUI *pat); Q_INVOKABLE void parse_ui(); @@ -867,16 +847,15 @@ class ImportPattern : virtual public Pattern { float frequency; bool nativeDialog; + public: ImportPattern(); virtual ~ImportPattern(); - uint8_t generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, - uint16_t number_of_channels); + uint8_t generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels); float get_frequency() const; void set_frequency(float value); uint32_t get_min_sampling_freq(); - uint32_t get_required_nr_of_samples(uint32_t sample_rate, - uint32_t number_of_channels); + uint32_t get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels); unsigned short channel_mapping; QVector data; QString fileName; @@ -904,11 +883,12 @@ class ImportPatternUI : public PatternUI QVector> data; void setStylesheet(); + public: ImportPatternUI(ImportPattern *pattern, QWidget *parent = 0); virtual ~ImportPatternUI(); Pattern *get_pattern(); - void build_ui(QWidget *parent = 0,uint16_t number_of_channels=0); + void build_ui(QWidget *parent = 0, uint16_t number_of_channels = 0); void destroy_ui(); private Q_SLOTS: @@ -933,7 +913,7 @@ class PulsePattern : public Pattern ~PulsePattern(); uint8_t generate_pattern(uint32_t sample_rate, uint32_t number_of_samples, uint16_t number_of_channels); uint32_t get_min_sampling_freq(); - uint32_t get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels); + uint32_t get_required_nr_of_samples(uint32_t sample_rate, uint32_t number_of_channels); bool get_start(); uint32_t get_low_number_of_samples(); uint32_t get_high_number_of_samples(); @@ -957,13 +937,13 @@ class PulsePatternUI : public PatternUI Ui::PulsePatternUI *ui; QWidget *parent_; PulsePattern *pattern; - ScaleSpinButton* frequencySpinButton; + ScaleSpinButton *frequencySpinButton; public: PulsePatternUI(PulsePattern *pattern, QWidget *parent = 0); ~PulsePatternUI(); Pattern *get_pattern(); - void build_ui(QWidget *parent = 0,uint16_t number_of_channels = 0); + void build_ui(QWidget *parent = 0, uint16_t number_of_channels = 0); void destroy_ui(); public Q_SLOTS: void parse_ui(); @@ -975,17 +955,19 @@ class PatternFactory static QStringList description_list; static int static_ui_limit; static QJsonObject patterns; + public: static void init(); static Pattern *create(QString name); static Pattern *create(int index); static PatternUI *create_ui(Pattern *pattern, int index, QWidget *parent = 0); - static PatternUI *create_ui(Pattern *pattern, QWidget *parent=0); + static PatternUI *create_ui(Pattern *pattern, QWidget *parent = 0); static QStringList get_ui_list(); static QStringList get_description_list(); + private: PatternFactory() {} }; -} +} // namespace scopy::m2k #endif diff --git a/plugins/m2k/src/old/power_controller.cpp b/plugins/m2k/src/old/power_controller.cpp index 05bb9034ca..97187311d5 100644 --- a/plugins/m2k/src/old/power_controller.cpp +++ b/plugins/m2k/src/old/power_controller.cpp @@ -18,39 +18,40 @@ * along with this program. If not, see . */ -#include "gui/dynamicWidget.h" #include "power_controller.hpp" + #include "filter.hpp" +#include "gui/dynamicWidget.h" +#include "power_controller_api.hpp" #include "ui_powercontrol.h" #include -#include "power_controller_api.hpp" /* libm2k includes */ +#include "m2kpluginExceptionHandler.h" + +#include #include #include #include -#include -#include "m2kpluginExceptionHandler.h" #include -#define TIMER_TIMEOUT_MS 200 +#define TIMER_TIMEOUT_MS 200 using namespace scopy::m2k; using namespace libm2k::context; using namespace libm2k::analog; #include -Q_LOGGING_CATEGORY(CAT_M2K_POWERCONTROL,"M2KPowerController"); - -PowerController::PowerController(struct iio_context *ctx, - ToolMenuEntry *tme, QJSEngine *engine, - QWidget *parent) : - M2kTool(ctx, tme, new PowerController_API(this), "Power Supply", parent), - ui(new Ui::PowerController), in_sync(false), - m_m2k_context(m2kOpen(ctx, "")), - m_m2k_powersupply(m_m2k_context->getPowerSupply()) +Q_LOGGING_CATEGORY(CAT_M2K_POWERCONTROL, "M2KPowerController"); + +PowerController::PowerController(struct iio_context *ctx, ToolMenuEntry *tme, QJSEngine *engine, QWidget *parent) + : M2kTool(ctx, tme, new PowerController_API(this), "Power Supply", parent) + , ui(new Ui::PowerController) + , in_sync(false) + , m_m2k_context(m2kOpen(ctx, "")) + , m_m2k_powersupply(m_m2k_context->getPowerSupply()) { ui->setupUi(this); @@ -59,45 +60,33 @@ PowerController::PowerController(struct iio_context *ctx, m_m2k_powersupply->enableChannel(1, false); m_m2k_powersupply->pushChannel(0, 0.0); m_m2k_powersupply->pushChannel(1, 0.0); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug(CAT_M2K_POWERCONTROL) << "Can't write push value: " << e.what(); } ui->btnSync->click(); - valuePos = new PositionSpinButton({ - {tr("mVolts"),1e-3}, - {tr("Volts"),1e0} - }, tr("Value"), 0, 5, true, true, this); + valuePos = + new PositionSpinButton({{tr("mVolts"), 1e-3}, {tr("Volts"), 1e0}}, tr("Value"), 0, 5, true, true, this); - valueNeg = new PositionSpinButton({ - {tr("mVolts"),1e-3}, - {tr("Volts"),1e0} - }, tr("Value"), -5, 0, true, true, this); + valueNeg = new PositionSpinButton({{tr("mVolts"), 1e-3}, {tr("Volts"), 1e0}}, tr("Value"), -5, 0, true, true, + this); ui->valuePosLayout->addWidget(valuePos); ui->valueNegLayout->addWidget(valueNeg); - connect(valuePos, &PositionSpinButton::valueChanged, - ui->lcd1_set, &LcdNumber::display); - connect(valueNeg, &PositionSpinButton::valueChanged, - ui->lcd2_set, &LcdNumber::display); + connect(valuePos, &PositionSpinButton::valueChanged, ui->lcd1_set, &LcdNumber::display); + connect(valueNeg, &PositionSpinButton::valueChanged, ui->lcd2_set, &LcdNumber::display); connect(&this->timer, SIGNAL(timeout()), this, SLOT(update_lcd())); - connect(ui->dac1, SIGNAL(toggled(bool)), this, - SLOT(dac1_set_enabled(bool))); - connect(ui->dac2, SIGNAL(toggled(bool)), this, - SLOT(dac2_set_enabled(bool))); - connect(ui->btnSync, SIGNAL(toggled(bool)), this, - SLOT(sync_enabled(bool))); - connect(valuePos, SIGNAL(valueChanged(double)), this, - SLOT(dac1_set_value(double))); - connect(valueNeg, SIGNAL(valueChanged(double)), this, - SLOT(dac2_set_value(double))); - connect(ui->trackingRatio, SIGNAL(valueChanged(int)), this, - SLOT(ratioChanged(int))); + connect(ui->dac1, SIGNAL(toggled(bool)), this, SLOT(dac1_set_enabled(bool))); + connect(ui->dac2, SIGNAL(toggled(bool)), this, SLOT(dac2_set_enabled(bool))); + connect(ui->btnSync, SIGNAL(toggled(bool)), this, SLOT(sync_enabled(bool))); + connect(valuePos, SIGNAL(valueChanged(double)), this, SLOT(dac1_set_value(double))); + connect(valueNeg, SIGNAL(valueChanged(double)), this, SLOT(dac2_set_value(double))); + connect(ui->trackingRatio, SIGNAL(valueChanged(int)), this, SLOT(ratioChanged(int))); connect(tme, SIGNAL(runClicked(bool)), this, SLOT(startStop(bool))); @@ -107,8 +96,8 @@ PowerController::PowerController(struct iio_context *ctx, connect(ui->dac1, &QPushButton::toggled, this, &PowerController::toggleRunButton); connect(ui->dac2, &QPushButton::toggled, this, &PowerController::toggleRunButton); - std::vector scales {ui->scale_dac1, ui->scale_dac2}; - for (auto scale : scales) { + std::vector scales{ui->scale_dac1, ui->scale_dac2}; + for(auto scale : scales) { scale->setOrientation(Qt::Horizontal); scale->setScalePosition(QwtThermo::LeadingScale); scale->setOriginMode(QwtThermo::OriginCustom); @@ -120,7 +109,6 @@ PowerController::PowerController(struct iio_context *ctx, readPreferences(); ui->btnHelp->setUrl("https://wiki.analog.com/university/tools/m2k/scopy/power-supply"); - } PowerController::~PowerController() @@ -130,7 +118,7 @@ PowerController::~PowerController() try { m_m2k_powersupply->powerDownDacs(true); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug(CAT_M2K_POWERCONTROL) << e.what(); } @@ -149,35 +137,29 @@ void PowerController::readPreferences() void PowerController::toggleRunButton(bool enabled) { bool dac1Enabled = ui->dac1->isChecked(); - bool dac2Enabled = ui->dac2->isChecked(); - if (enabled) { + bool dac2Enabled = ui->dac2->isChecked(); + if(enabled) { tme->setRunning(enabled); } else { tme->setRunning(dac1Enabled | dac2Enabled); - } + } } -void PowerController::showEvent(QShowEvent *event) -{ - timer.start(TIMER_TIMEOUT_MS); -} +void PowerController::showEvent(QShowEvent *event) { timer.start(TIMER_TIMEOUT_MS); } -void PowerController::hideEvent(QHideEvent *event) -{ - timer.stop(); -} +void PowerController::hideEvent(QHideEvent *event) { timer.stop(); } void PowerController::dac1_set_value(double value) { try { m_m2k_powersupply->pushChannel(0, value); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug(CAT_M2K_POWERCONTROL) << "Can't write push value: " << e.what(); } averageVoltageCh1.clear(); - if (in_sync) { + if(in_sync) { value = -value * ui->trackingRatio->value() / 100.0; valueNeg->setValue(value); dac2_set_value(value); @@ -189,7 +171,7 @@ void PowerController::dac2_set_value(double value) { try { m_m2k_powersupply->pushChannel(1, value); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug(CAT_M2K_POWERCONTROL) << "Can't write push value: " << e.what(); } @@ -200,13 +182,13 @@ void PowerController::dac1_set_enabled(bool enabled) { try { m_m2k_powersupply->enableChannel(0, enabled); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug(CAT_M2K_POWERCONTROL) << "Can't enable channel: " << e.what(); } averageVoltageCh1.clear(); - if (in_sync) + if(in_sync) dac2_set_enabled(enabled); setDynamicProperty(ui->dac1, "running", enabled); @@ -217,7 +199,7 @@ void PowerController::dac2_set_enabled(bool enabled) { try { m_m2k_powersupply->enableChannel(1, enabled); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug(CAT_M2K_POWERCONTROL) << "Can't enable channel: " << e.what(); } @@ -228,22 +210,17 @@ void PowerController::dac2_set_enabled(bool enabled) void PowerController::sync_enabled(bool enabled) { - if (ui->dac1->isChecked()) { + if(ui->dac1->isChecked()) { dac2_set_enabled(!enabled); ui->dac2->setChecked(!enabled); } in_sync = !enabled; valueNeg->setDisabled(!enabled); - valueNeg->setValue(-valuePos->value() * - (double) ui->trackingRatio->value() / 100.0); + valueNeg->setValue(-valuePos->value() * (double)ui->trackingRatio->value() / 100.0); } -void PowerController::ratioChanged(int percent) -{ - valueNeg->setValue(-valuePos->value() * - (double) percent / 100.0); -} +void PowerController::ratioChanged(int percent) { valueNeg->setValue(-valuePos->value() * (double)percent / 100.0); } void PowerController::update_lcd() { @@ -253,7 +230,7 @@ void PowerController::update_lcd() try { value1 = m_m2k_powersupply->readChannel(0); value2 = m_m2k_powersupply->readChannel(1); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug(CAT_M2K_POWERCONTROL) << "Can't read value: " << e.what(); } @@ -266,13 +243,13 @@ void PowerController::update_lcd() if(averageVoltageCh2.length() > AVERAGE_COUNT) averageVoltageCh2.pop_front(); - for (int i = 0; i < averageVoltageCh1.size(); ++i) + for(int i = 0; i < averageVoltageCh1.size(); ++i) average1 += averageVoltageCh1.at(i); - for (int i = 0; i < averageVoltageCh2.size(); ++i) + for(int i = 0; i < averageVoltageCh2.size(); ++i) average2 += averageVoltageCh2.at(i); - average1 /= averageVoltageCh1.length(); - average2 /= averageVoltageCh2.length(); + average1 /= averageVoltageCh1.length(); + average2 /= averageVoltageCh2.length(); ui->lcd1->display(average1); ui->scale_dac1->setValue(average1); @@ -283,22 +260,15 @@ void PowerController::update_lcd() timer.start(TIMER_TIMEOUT_MS); } -void PowerController::run() -{ - startStop(true); -} -void PowerController::stop() -{ - startStop(false); -} +void PowerController::run() { startStop(true); } +void PowerController::stop() { startStop(false); } void PowerController::startStop(bool start) -{ +{ dac1_set_enabled(start); ui->dac1->setChecked(start); dac2_set_enabled(start); ui->dac2->setChecked(start); - m_running = start; + m_running = start; } - diff --git a/plugins/m2k/src/old/power_controller.hpp b/plugins/m2k/src/old/power_controller.hpp index 6f2bd00bca..642d186923 100644 --- a/plugins/m2k/src/old/power_controller.hpp +++ b/plugins/m2k/src/old/power_controller.hpp @@ -21,27 +21,28 @@ #ifndef POWER_CONTROLLER_HPP #define POWER_CONTROLLER_HPP -#include -#include - -#include "pluginbase/apiobject.h" #include "gui/spinbox_a.hpp" #include "m2ktool.hpp" +#include "pluginbase/apiobject.h" -extern "C" { +#include +#include + +extern "C" +{ struct iio_context; } namespace libm2k { namespace context { - class M2k; +class M2k; } namespace analog { - class M2kPowerSupply; -} +class M2kPowerSupply; } +} // namespace libm2k namespace Ui { - class PowerController; +class PowerController; } class QJSEngine; @@ -49,55 +50,53 @@ class QShowEvent; class QHideEvent; namespace scopy::m2k { - class PowerController_API; - - class PowerController : public M2kTool - { - friend class PowerController_API; - friend class ToolLauncher_API; - - Q_OBJECT - - public: - const int AVERAGE_COUNT = 5; - - explicit PowerController(struct iio_context *ctx, - ToolMenuEntry *tme, QJSEngine *engine, - QWidget *parent = 0); - ~PowerController(); - - public Q_SLOTS: - void dac1_set_enabled(bool enabled); - void dac2_set_enabled(bool enabled); - void dac1_set_value(double value); - void dac2_set_value(double value); - void update_lcd(); - void sync_enabled(bool enabled); - void run() override; - void stop() override; - - private Q_SLOTS: - void startStop(bool start); - void ratioChanged(int percent); - void toggleRunButton(bool enabled); - void readPreferences(); - - private: - Ui::PowerController *ui; - PositionSpinButton *valuePos; - PositionSpinButton *valueNeg; - QTimer timer; - bool in_sync; - QList averageVoltageCh1; - QList averageVoltageCh2; - libm2k::context::M2k* m_m2k_context; - libm2k::analog::M2kPowerSupply* m_m2k_powersupply; - - void showEvent(QShowEvent *event); - void hideEvent(QHideEvent *event); - - Q_SIGNALS: - void showTool(); - }; -} +class PowerController_API; + +class PowerController : public M2kTool +{ + friend class PowerController_API; + friend class ToolLauncher_API; + + Q_OBJECT + +public: + const int AVERAGE_COUNT = 5; + + explicit PowerController(struct iio_context *ctx, ToolMenuEntry *tme, QJSEngine *engine, QWidget *parent = 0); + ~PowerController(); + +public Q_SLOTS: + void dac1_set_enabled(bool enabled); + void dac2_set_enabled(bool enabled); + void dac1_set_value(double value); + void dac2_set_value(double value); + void update_lcd(); + void sync_enabled(bool enabled); + void run() override; + void stop() override; + +private Q_SLOTS: + void startStop(bool start); + void ratioChanged(int percent); + void toggleRunButton(bool enabled); + void readPreferences(); + +private: + Ui::PowerController *ui; + PositionSpinButton *valuePos; + PositionSpinButton *valueNeg; + QTimer timer; + bool in_sync; + QList averageVoltageCh1; + QList averageVoltageCh2; + libm2k::context::M2k *m_m2k_context; + libm2k::analog::M2kPowerSupply *m_m2k_powersupply; + + void showEvent(QShowEvent *event); + void hideEvent(QHideEvent *event); + +Q_SIGNALS: + void showTool(); +}; +} // namespace scopy::m2k #endif /* POWER_CONTROLLER_HPP */ diff --git a/plugins/m2k/src/old/power_controller_api.cpp b/plugins/m2k/src/old/power_controller_api.cpp index e2ced2282b..d3f84a0690 100644 --- a/plugins/m2k/src/old/power_controller_api.cpp +++ b/plugins/m2k/src/old/power_controller_api.cpp @@ -18,18 +18,13 @@ * along with this program. If not, see . */ #include "power_controller_api.hpp" + #include "ui_powercontrol.h" namespace scopy::m2k { -void PowerController_API::show() -{ - Q_EMIT pw->showTool(); -} +void PowerController_API::show() { Q_EMIT pw->showTool(); } -bool PowerController_API::syncEnabled() const -{ - return !pw->ui->btnSync->isChecked(); -} +bool PowerController_API::syncEnabled() const { return !pw->ui->btnSync->isChecked(); } void PowerController_API::enableSync(bool en) { @@ -37,63 +32,30 @@ void PowerController_API::enableSync(bool en) pw->ui->btnSync->click(); } -int PowerController_API::getTrackingPercent() const -{ - return pw->ui->trackingRatio->value(); -} +int PowerController_API::getTrackingPercent() const { return pw->ui->trackingRatio->value(); } -void PowerController_API::setTrackingPercent(int percent) -{ - pw->ui->trackingRatio->setValue(percent); -} +void PowerController_API::setTrackingPercent(int percent) { pw->ui->trackingRatio->setValue(percent); } -double PowerController_API::valueDac1() const -{ - return pw->valuePos->value(); -} +double PowerController_API::valueDac1() const { return pw->valuePos->value(); } -void PowerController_API::setValueDac1(double value) -{ - pw->valuePos->setValue(value); -} +void PowerController_API::setValueDac1(double value) { pw->valuePos->setValue(value); } -double PowerController_API::valueDac2() const -{ - return pw->valueNeg->value(); -} +double PowerController_API::valueDac2() const { return pw->valueNeg->value(); } void PowerController_API::setValueDac2(double value) { - if (!syncEnabled()) + if(!syncEnabled()) pw->valueNeg->setValue(value); } -bool PowerController_API::Dac1Enabled() const -{ - return pw->ui->dac1->isChecked(); -} +bool PowerController_API::Dac1Enabled() const { return pw->ui->dac1->isChecked(); } -void PowerController_API::setDac1Enabled(bool enable) -{ - pw->ui->dac1->setChecked(enable); -} +void PowerController_API::setDac1Enabled(bool enable) { pw->ui->dac1->setChecked(enable); } -bool PowerController_API::Dac2Enabled() const -{ - return pw->ui->dac2->isChecked(); -} +bool PowerController_API::Dac2Enabled() const { return pw->ui->dac2->isChecked(); } -void PowerController_API::setDac2Enabled(bool enable) -{ - pw->ui->dac2->setChecked(enable); -} +void PowerController_API::setDac2Enabled(bool enable) { pw->ui->dac2->setChecked(enable); } -QString PowerController_API::getNotes() -{ - return pw->ui->instrumentNotes->getNotes(); -} -void PowerController_API::setNotes(QString str) -{ - pw->ui->instrumentNotes->setNotes(str); -} -} +QString PowerController_API::getNotes() { return pw->ui->instrumentNotes->getNotes(); } +void PowerController_API::setNotes(QString str) { pw->ui->instrumentNotes->setNotes(str); } +} // namespace scopy::m2k diff --git a/plugins/m2k/src/old/power_controller_api.hpp b/plugins/m2k/src/old/power_controller_api.hpp index a0d9febea8..9b0e46a1aa 100644 --- a/plugins/m2k/src/old/power_controller_api.hpp +++ b/plugins/m2k/src/old/power_controller_api.hpp @@ -30,9 +30,7 @@ class PowerController_API : public scopy::ApiObject Q_OBJECT Q_PROPERTY(bool sync READ syncEnabled WRITE enableSync); - Q_PROPERTY(int tracking_percent - READ getTrackingPercent - WRITE setTrackingPercent); + Q_PROPERTY(int tracking_percent READ getTrackingPercent WRITE setTrackingPercent); Q_PROPERTY(double dac1_value READ valueDac1 WRITE setValueDac1); Q_PROPERTY(double dac2_value READ valueDac2 WRITE setValueDac2); Q_PROPERTY(bool dac1_enabled READ Dac1Enabled WRITE setDac1Enabled); @@ -40,8 +38,10 @@ class PowerController_API : public scopy::ApiObject Q_PROPERTY(QString notes READ getNotes WRITE setNotes) public: - explicit PowerController_API(PowerController *pw) : - ApiObject(), pw(pw) {} + explicit PowerController_API(PowerController *pw) + : ApiObject() + , pw(pw) + {} ~PowerController_API() {} bool syncEnabled() const; @@ -70,6 +70,6 @@ class PowerController_API : public scopy::ApiObject private: PowerController *pw; }; -} +} // namespace scopy::m2k #endif // POWER_CONTROLLER_API_HPP diff --git a/plugins/m2k/src/old/saverestoretoolsettings.cpp b/plugins/m2k/src/old/saverestoretoolsettings.cpp index 85286246cf..8d497a88c3 100644 --- a/plugins/m2k/src/old/saverestoretoolsettings.cpp +++ b/plugins/m2k/src/old/saverestoretoolsettings.cpp @@ -1,11 +1,13 @@ #include "saverestoretoolsettings.h" -#include + #include +#include + using namespace scopy::m2k; SaveRestoreToolSettings::SaveRestoreToolSettings(M2kTool *tool) - : m_tool(tool) + : m_tool(tool) { QSettings settings(m_temp.fileName(), QSettings::IniFormat); diff --git a/plugins/m2k/src/old/saverestoretoolsettings.h b/plugins/m2k/src/old/saverestoretoolsettings.h index 37414ff007..b6b3a20778 100644 --- a/plugins/m2k/src/old/saverestoretoolsettings.h +++ b/plugins/m2k/src/old/saverestoretoolsettings.h @@ -14,6 +14,7 @@ class SaveRestoreToolSettings SaveRestoreToolSettings(SaveRestoreToolSettings &&) = delete; SaveRestoreToolSettings &operator=(SaveRestoreToolSettings &&) = delete; + public: SaveRestoreToolSettings(M2kTool *tool); ~SaveRestoreToolSettings(); @@ -22,6 +23,6 @@ class SaveRestoreToolSettings QTemporaryFile m_temp; M2kTool *m_tool; }; -} // namespace scopy +} // namespace scopy::m2k #endif // SAVERESTORETOOLSETTINGS_H diff --git a/plugins/m2k/src/old/signal_generator.cpp b/plugins/m2k/src/old/signal_generator.cpp index ae6b5ca6dc..6c65d239b3 100644 --- a/plugins/m2k/src/old/signal_generator.cpp +++ b/plugins/m2k/src/old/signal_generator.cpp @@ -18,75 +18,76 @@ * along with this program. If not, see . */ -#include "gui/dynamicWidget.h" #include "signal_generator.hpp" -#include "gui/spinbox_a.hpp" -#include "ui_signal_generator.h" -#include "gui/channel_widget.hpp" -#include +#include "gnuradio/blocks/multiply_const.h" +#include "gui/channel_widget.hpp" +#include "gui/dynamicWidget.h" +#include "gui/spinbox_a.hpp" +#include "m2kpluginExceptionHandler.h" -#include -#include -#include -#include -#include -#include -#include +#include "ui_signal_generator.h" -#include -#include #include #include #include +#include +#include +#include +#include +#include #include #include -#include -#include #include #include -#include #include -#include -#include -#include -#include -#include #include +#include #include -#include +#include +#include +#include #include +#include #include -#include +#include +#include #include #include #include -#include "m2kpluginExceptionHandler.h" -#include "gnuradio/blocks/multiply_const.h" + +#include +#include +#include +#include +#include #include +#include +#include + +#include #include #ifdef MATLAB_SUPPORT_SIGGEN #include #endif -#include - #include "signal_generator_api.hpp" +#include + /* libm2k includes */ #include #include #include -#define NB_POINTS 32768 -#define DAC_BIT_COUNT 12 +#define NB_POINTS 32768 +#define DAC_BIT_COUNT 12 #define INTERP_BY_100_CORR 1.168 // correction value at an interpolation by 100 -#define AMPLITUDE_VOLTS 5.0 -#define MULTIPLY_CT 4 -#define FREQUENCY_CT 40 - +#define AMPLITUDE_VOLTS 5.0 +#define MULTIPLY_CT 4 +#define FREQUENCY_CT 40 using namespace scopy; using namespace scopy::m2k; @@ -94,69 +95,71 @@ using namespace gr; using namespace libm2k::context; using namespace libm2k::analog; -enum { +enum +{ DATA_IIO_PTR, DATA_SIGNAL_STRUCT, DATA_TIME_BLOCK, }; Q_DECLARE_METATYPE(QSharedPointer); -Q_LOGGING_CATEGORY(CAT_M2K_SIGNAL_GENERATOR,"M2kSiggen"); +Q_LOGGING_CATEGORY(CAT_M2K_SIGNAL_GENERATOR, "M2kSiggen"); -bool SignalGenerator::riffCompare(riff_header_t& ptr,const char *id2) +bool SignalGenerator::riffCompare(riff_header_t &ptr, const char *id2) { - const char riff[]="RIFF"; + const char riff[] = "RIFF"; - for (uint8_t i=0; i<4; i++) - if (ptr.riff[i]!=riff[i]) { + for(uint8_t i = 0; i < 4; i++) + if(ptr.riff[i] != riff[i]) { return false; } - for (uint8_t i=0; i<4; i++) - if (ptr.id[i]!=id2[i]) { + for(uint8_t i = 0; i < 4; i++) + if(ptr.id[i] != id2[i]) { return false; } return true; } -bool SignalGenerator::chunkCompare(chunk_header_t& ptr,const char *id2) +bool SignalGenerator::chunkCompare(chunk_header_t &ptr, const char *id2) { - for (uint8_t i=0; i<4; i++) - if (ptr.id[i]!=id2[i]) { + for(uint8_t i = 0; i < 4; i++) + if(ptr.id[i] != id2[i]) { return false; } return true; } -SignalGenerator::SignalGenerator(struct iio_context *_ctx, Filter *filt, - ToolMenuEntry *tme, QJSEngine *engine, QWidget *parent) : - M2kTool(_ctx, tme, new SignalGenerator_API(this), "Signal Generator", - parent), - ui(new Ui::SignalGenerator), - time_block_data(new struct time_block_data), - m_m2k_context(m2kOpen(ctx, "")), - m_m2k_analogout(m_m2k_context->getAnalogOut()), - nr_of_periods(2), - currentChannel(0), sample_rate(0), - settings_group(new QButtonGroup(this)),nb_points(NB_POINTS), - channels_group(new QButtonGroup(this)), - m_maxNbOfSamples(4 * 1024 * 1024) -{ - zoomT1=0; - zoomT2=1; +SignalGenerator::SignalGenerator(struct iio_context *_ctx, Filter *filt, ToolMenuEntry *tme, QJSEngine *engine, + QWidget *parent) + : M2kTool(_ctx, tme, new SignalGenerator_API(this), "Signal Generator", parent) + , ui(new Ui::SignalGenerator) + , time_block_data(new struct time_block_data) + , m_m2k_context(m2kOpen(ctx, "")) + , m_m2k_analogout(m_m2k_context->getAnalogOut()) + , nr_of_periods(2) + , currentChannel(0) + , sample_rate(0) + , settings_group(new QButtonGroup(this)) + , nb_points(NB_POINTS) + , channels_group(new QButtonGroup(this)) + , m_maxNbOfSamples(4 * 1024 * 1024) +{ + zoomT1 = 0; + zoomT2 = 1; ui->setupUi(this); ui->run_button->enableSingleButton(false); this->setAttribute(Qt::WA_DeleteOnClose, true); - this->m_plot = new CapturePlot(this, false, 10, 10 , new TimePrefixFormatter, new MetricPrefixFormatter); + this->m_plot = new CapturePlot(this, false, 10, 10, new TimePrefixFormatter, new MetricPrefixFormatter); - for (size_t i = 0; i < m_m2k_analogout->getNbChannels(); i++) { + for(size_t i = 0; i < m_m2k_analogout->getNbChannels(); i++) { unsigned long dev_sample_rate = m_m2k_analogout->getMaximumSamplerate(i); - if (dev_sample_rate > sample_rate) { + if(dev_sample_rate > sample_rate) { sample_rate = dev_sample_rate; } } @@ -164,136 +167,82 @@ SignalGenerator::SignalGenerator(struct iio_context *_ctx, Filter *filt, max_sample_rate = sample_rate; /* Create waveform control widgets */ - phase = new PhaseSpinButton({ - {tr("deg"),1}, - {tr("Ï€ rad"),180}, - {tr("ns"),1e-9}, - {tr("μs"),1e-6}, - {tr("ms"),1e-3}, - {tr("s"),1e0} - }, tr("Phase"), 0, 360, true, true, this); - - amplitude = new ScaleSpinButton({ - {tr("μVolts p-p"),1e-6}, - {tr("mVolts p-p"),1e-3}, - {tr("Volts p-p"),1e0} - }, tr("Amplitude"), 0.000001, 10, true, true, this); - - offset = new PositionSpinButton({ - {tr("μVolts"),1e-6}, - {tr("mVolts"),1e-3}, - {tr("Volts"),1e0} - }, tr("Offset"), -5, 5, true, true, this); - - frequency = new ScaleSpinButton({ - {tr("mHz"),1e-3}, - {tr("Hz"),1e0}, - {tr("kHz"),1e3}, - {tr("MHz"),1e6} - },tr("Frequency"), 0.001, 0.0, true, false, this); + phase = new PhaseSpinButton({{tr("deg"), 1}, + {tr("Ï€ rad"), 180}, + {tr("ns"), 1e-9}, + {tr("μs"), 1e-6}, + {tr("ms"), 1e-3}, + {tr("s"), 1e0}}, + tr("Phase"), 0, 360, true, true, this); + + amplitude = new ScaleSpinButton({{tr("μVolts p-p"), 1e-6}, {tr("mVolts p-p"), 1e-3}, {tr("Volts p-p"), 1e0}}, + tr("Amplitude"), 0.000001, 10, true, true, this); + + offset = new PositionSpinButton({{tr("μVolts"), 1e-6}, {tr("mVolts"), 1e-3}, {tr("Volts"), 1e0}}, tr("Offset"), + -5, 5, true, true, this); + + frequency = new ScaleSpinButton({{tr("mHz"), 1e-3}, {tr("Hz"), 1e0}, {tr("kHz"), 1e3}, {tr("MHz"), 1e6}}, + tr("Frequency"), 0.001, 0.0, true, false, this); /* Create stairstep waveform control widgets*/ - stepsUp = new PositionSpinButton({ - {"steps",1e0}, - }, tr("Rising"),1,1024,true,false,this); + stepsUp = new PositionSpinButton( + { + {"steps", 1e0}, + }, + tr("Rising"), 1, 1024, true, false, this); - stepsDown = new PositionSpinButton({ - {"steps",1e0}, - }, tr("Falling"),1,1024,true,false,this); + stepsDown = new PositionSpinButton( + { + {"steps", 1e0}, + }, + tr("Falling"), 1, 1024, true, false, this); - stairPhase = new PositionSpinButton({ - {"samples",1e0} - }, tr("Phase"), 0, 1024, true, false, this); + stairPhase = new PositionSpinButton({{"samples", 1e0}}, tr("Phase"), 0, 1024, true, false, this); stairPhase->setFineModeAvailable(false); + /* Create trapezoidal waveform control widgets */ + riseTime = new ScaleSpinButton({{tr("ns"), 1e-9}, {tr("μs"), 1e-6}, {tr("ms"), 1e-3}, {tr("s"), 1e0}}, + tr("Rise Time"), 0, 10, true, false, this); + fallTime = new ScaleSpinButton({{tr("ns"), 1e-9}, {tr("μs"), 1e-6}, {tr("ms"), 1e-3}, {tr("s"), 1e0}}, + tr("Fall Time"), 0, 10, true, false, this); - /* Create trapezoidal waveform control widgets */ - riseTime = new ScaleSpinButton({ - {tr("ns"),1e-9}, - {tr("μs"),1e-6}, - {tr("ms"),1e-3}, - {tr("s"),1e0} - },tr("Rise Time"), 0, 10, true, false, this); - - fallTime = new ScaleSpinButton({ - {tr("ns"),1e-9}, - {tr("μs"),1e-6}, - {tr("ms"),1e-3}, - {tr("s"),1e0} - },tr("Fall Time"), 0, 10, true, false, this); - - holdHighTime = new ScaleSpinButton({ - {tr("ns"),1e-9}, - {tr("μs"),1e-6}, - {tr("ms"),1e-3}, - {tr("s"),1e0} - },tr("High Time"), 0, 10, true, false, this); - - holdLowTime = new ScaleSpinButton({ - {tr("ns"),1e-9}, - {tr("μs"),1e-6}, - {tr("ms"),1e-3}, - {tr("s"),1e0} - },tr("Low Time"), 0, 10, true, false, this); + holdHighTime = new ScaleSpinButton({{tr("ns"), 1e-9}, {tr("μs"), 1e-6}, {tr("ms"), 1e-3}, {tr("s"), 1e0}}, + tr("High Time"), 0, 10, true, false, this); + + holdLowTime = new ScaleSpinButton({{tr("ns"), 1e-9}, {tr("μs"), 1e-6}, {tr("ms"), 1e-3}, {tr("s"), 1e0}}, + tr("Low Time"), 0, 10, true, false, this); /* Create file control widgets */ - filePhase = new PositionSpinButton({ - {"samples",1e0} - }, tr("Phase"), 0.0, 360.0, true, false, this); + filePhase = new PositionSpinButton({{"samples", 1e0}}, tr("Phase"), 0.0, 360.0, true, false, this); filePhase->setFineModeAvailable(false); - fileOffset = new PositionSpinButton({ - {tr("μVolts"),1e-6}, - {tr("mVolts"),1e-3}, - {tr("Volts"),1e0} - }, tr("Offset"), -5, 5, true, true, this); - - fileSampleRate = new ScaleSpinButton({ - {"msps",1e-3}, - {"sps",1e0}, - {"ksps",1e3}, - {"Msps",1e6} - },tr("SampleRate"), 0.001, 0.0, true, false, this); + fileOffset = new PositionSpinButton({{tr("μVolts"), 1e-6}, {tr("mVolts"), 1e-3}, {tr("Volts"), 1e0}}, + tr("Offset"), -5, 5, true, true, this); + + fileSampleRate = new ScaleSpinButton({{"msps", 1e-3}, {"sps", 1e0}, {"ksps", 1e3}, {"Msps", 1e6}}, + tr("SampleRate"), 0.001, 0.0, true, false, this); fileSampleRate->setIntegerDivider(75000000); - fileAmplitude = new ScaleSpinButton({ - {tr("μVolts"),1e-6}, - {tr("mVolts"),1e-3}, - {tr("Volts"),1e0} - }, tr("Amplitude"), 0.000001, 10, true, true, this); + fileAmplitude = new ScaleSpinButton({{tr("μVolts"), 1e-6}, {tr("mVolts"), 1e-3}, {tr("Volts"), 1e0}}, + tr("Amplitude"), 0.000001, 10, true, true, this); - mathSampleRate = new ScaleSpinButton({ - {"msps",1e-3}, - {"sps",1e0}, - {"ksps",1e3}, - {"Msps",1e6} - },tr("SampleRate"), 0.001, 75000000.0, true, false, this); + mathSampleRate = new ScaleSpinButton({{"msps", 1e-3}, {"sps", 1e0}, {"ksps", 1e3}, {"Msps", 1e6}}, + tr("SampleRate"), 0.001, 75000000.0, true, false, this); mathSampleRate->setIntegerDivider(75000000); - mathRecordLength = new ScaleSpinButton({ - {"ns",1e-9}, - {"μs",1e-6}, - {"ms",1e-3}, - {"s",1} - }, tr("Record Length"), 1e-9, 100.0, true, false, this, {1,2,5}); + mathRecordLength = new ScaleSpinButton({{"ns", 1e-9}, {"μs", 1e-6}, {"ms", 1e-3}, {"s", 1}}, + tr("Record Length"), 1e-9, 100.0, true, false, this, {1, 2, 5}); - noiseAmplitude = new ScaleSpinButton({ - {tr("μVolts"),1e-6}, - {tr("mVolts"),1e-3}, - {tr("Volts"),1e0} - }, tr("Amplitude"), 0.000001, 10, true, true, this); + noiseAmplitude = new ScaleSpinButton({{tr("μVolts"), 1e-6}, {tr("mVolts"), 1e-3}, {tr("Volts"), 1e0}}, + tr("Amplitude"), 0.000001, 10, true, true, this); - constantValue = new PositionSpinButton({ - {tr("mVolts"),1e-3}, - {tr("Volts"),1e0} - }, tr("Value"), -5, 5, true, true, this); + constantValue = new PositionSpinButton({{tr("mVolts"), 1e-3}, {tr("Volts"), 1e0}}, tr("Value"), -5, 5, true, + true, this); - dutycycle = new PositionSpinButton({ - {"%",1e0} - }, tr("Duty Cycle"), -5, 100, true, false, this); + dutycycle = new PositionSpinButton({{"%", 1e0}}, tr("Duty Cycle"), -5, 100, true, false, this); load = ui->externalLoad; @@ -308,9 +257,9 @@ SignalGenerator::SignalGenerator(struct iio_context *_ctx, Filter *filt, ui->gridLayout_2->addWidget(fallTime, 1, 0, 1, 1); ui->gridLayout_2->addWidget(holdLowTime, 1, 1, 1, 1); - ui->waveformGrid->addWidget(stepsUp,2,0,1,1); - ui->waveformGrid->addWidget(stepsDown,2,1,1,1); - ui->waveformGrid->addWidget(stairPhase,1,1,1,1); + ui->waveformGrid->addWidget(stepsUp, 2, 0, 1, 1); + ui->waveformGrid->addWidget(stepsDown, 2, 1, 1, 1); + ui->waveformGrid->addWidget(stairPhase, 1, 1, 1, 1); ui->waveformGrid_2->addWidget(fileAmplitude, 0, 0, 1, 1); ui->waveformGrid_2->addWidget(fileOffset, 0, 1, 1, 1); @@ -321,7 +270,7 @@ SignalGenerator::SignalGenerator(struct iio_context *_ctx, Filter *filt, ui->verticalLayout_3->insertWidget(1, mathSampleRate); ui->horizontalLayout_5->insertWidget(1, noiseAmplitude); - ui->gridLayout->addWidget(constantValue,0,0,1,1); + ui->gridLayout->addWidget(constantValue, 0, 0, 1, 1); /* Max amplitude by default */ amplitude->setValue(amplitude->maxValue()); @@ -377,21 +326,17 @@ SignalGenerator::SignalGenerator(struct iio_context *_ctx, Filter *filt, noiseAmplitude->setMinValue(1e-06); noiseAmplitude->setValue(noiseAmplitude->minValue()); ui->btnNoiseCollapse->setVisible(true); - ui->cbNoiseType->setItemData(SG_NO_NOISE,0); + ui->cbNoiseType->setItemData(SG_NO_NOISE, 0); ui->cbNoiseType->setItemData(SG_UNIFORM_NOISE, analog::GR_UNIFORM); ui->cbNoiseType->setItemData(SG_GAUSSIAN_NOISE, analog::GR_GAUSSIAN); ui->cbNoiseType->setItemData(SG_LAPLACIAN_NOISE, analog::GR_LAPLACIAN); ui->cbNoiseType->setItemData(SG_IMPULSE_NOISE, analog::GR_IMPULSE); - connect(ui->btnNoiseCollapse,&QPushButton::clicked, - [=](bool check) { - ui->wNoise->setVisible(check); - }); + connect(ui->btnNoiseCollapse, &QPushButton::clicked, [=](bool check) { ui->wNoise->setVisible(check); }); unsigned int nb_channels = m_m2k_analogout->getNbChannels(); - for (unsigned int i = 0; i < nb_channels; i++) { - auto ptr = QSharedPointer( - new signal_generator_data); + for(unsigned int i = 0; i < nb_channels; i++) { + auto ptr = QSharedPointer(new signal_generator_data); ptr->amplitude = amplitude->value(); ptr->offset = offset->value(); ptr->frequency = frequency->value(); @@ -410,14 +355,14 @@ SignalGenerator::SignalGenerator(struct iio_context *_ctx, Filter *filt, ptr->math_record_length = mathRecordLength->value(); ptr->math_sr = mathSampleRate->value(); ptr->noiseType = (gr::analog::noise_type_t)0; - ptr->noiseAmplitude=noiseAmplitude->value(); + ptr->noiseAmplitude = noiseAmplitude->value(); ptr->file_sr = fileSampleRate->value(); ptr->file_amplitude = fileAmplitude->value(); ptr->file_offset = fileOffset->value(); ptr->file_phase = filePhase->value(); - ptr->file_type=FORMAT_NO_FILE; - ptr->file_nr_of_channels=0; - ptr->file_channel=0; + ptr->file_type = FORMAT_NO_FILE; + ptr->file_nr_of_channels = 0; + ptr->file_channel = 0; ptr->lineThickness = 1.0; ptr->load = ExternalLoadLineEdit::MAX_EXTERNAL_LOAD; @@ -430,56 +375,45 @@ SignalGenerator::SignalGenerator(struct iio_context *_ctx, Filter *filt, std::string ch_name = m_m2k_analogout->getChannelName(i); - if (ch_name == "") { + if(ch_name == "") { ch_name += "Channel "; ch_name += std::to_string(i + 1); } cw->setFullName(ch_name.c_str()); - cw->setProperty("signal_generator_data", - QVariant::fromValue(ptr)); - cw->setProperty("channel", - QVariant::fromValue(i)); + cw->setProperty("signal_generator_data", QVariant::fromValue(ptr)); + cw->setProperty("channel", QVariant::fromValue(i)); channels.append(cw); ui->channelsList->addWidget(cw); - connect(cw, SIGNAL(enabled(bool)), - SLOT(channelWidgetEnabled(bool))); + connect(cw, SIGNAL(enabled(bool)), SLOT(channelWidgetEnabled(bool))); - connect(cw, SIGNAL(menuToggled(bool)), - SLOT(channelWidgetMenuToggled(bool))); + connect(cw, SIGNAL(menuToggled(bool)), SLOT(channelWidgetMenuToggled(bool))); channels_group->addButton(cw->nameButton()); settings_group->addButton(cw->menuButton()); - connect(cw->nameButton(), &QAbstractButton::toggled, - cw->menuButton(), &QAbstractButton::setChecked); - connect(cw->menuButton(), &QAbstractButton::toggled, - cw->nameButton(), &QAbstractButton::setChecked); - + connect(cw->nameButton(), &QAbstractButton::toggled, cw->menuButton(), &QAbstractButton::setChecked); + connect(cw->menuButton(), &QAbstractButton::toggled, cw->nameButton(), &QAbstractButton::setChecked); } time_block_data->nb_channels = nb_channels; - time_block_data->time_block = scope_sink_f::make( - nb_points, sample_rate, - "Signal Generator", nb_channels, - static_cast(m_plot)); + time_block_data->time_block = scope_sink_f::make(nb_points, sample_rate, "Signal Generator", nb_channels, + static_cast(m_plot)); /* Attach all curves by default */ - m_plot->registerSink(time_block_data->time_block->name(), - nb_channels, nb_points); + m_plot->registerSink(time_block_data->time_block->name(), nb_channels, nb_points); for(size_t i = 0; i < nb_channels; i++) { m_plot->Curve(i)->setPaintAttribute(QwtPlotCurve::ClipPolygons, false); m_plot->Curve(i)->setPaintAttribute(QwtPlotCurve::FilterPointsAggressive, true); } - /* This must be done after attaching the curves; otherwise * plot->getLineColor(i) returns black. */ - for (unsigned int i = 0; i < nb_channels; i++) { + for(unsigned int i = 0; i < nb_channels; i++) { channels[i]->setColor(m_plot->getLineColor(i)); } @@ -488,106 +422,69 @@ SignalGenerator::SignalGenerator(struct iio_context *_ctx, Filter *filt, m_plot->setVertUnitsPerDiv(AMPLITUDE_VOLTS * 2.0 / 10.0); - m_plot->setHorizUnitsPerDiv((double) nb_points / - ((double) sample_rate * 10.0)); - m_plot->setHorizOffset((double) nb_points / - ((double) sample_rate * 2.0)); + m_plot->setHorizUnitsPerDiv((double)nb_points / ((double)sample_rate * 10.0)); + m_plot->setHorizOffset((double)nb_points / ((double)sample_rate * 2.0)); m_plot->zoomBaseUpdate(true); - //ui->plot->insertWidget(0,m_plot, 0, 0); + // ui->plot->insertWidget(0,m_plot, 0, 0); - connect(ui->btnAppearanceCollapse, SIGNAL(toggled(bool)),ui->wAppearance, SLOT(setVisible(bool))); + connect(ui->btnAppearanceCollapse, SIGNAL(toggled(bool)), ui->wAppearance, SLOT(setVisible(bool))); - connect(ui->btnSigGenAutoscale, &QPushButton::toggled, [=](bool checked){ - m_plot->setAutoScale(checked); - }); + connect(ui->btnSigGenAutoscale, &QPushButton::toggled, [=](bool checked) { m_plot->setAutoScale(checked); }); fileManager = new FileManager("Signal Generator"); api->setObjectName(Filter::tool_name(TOOL_SIGNAL_GENERATOR)); ScopyJS::GetInstance()->registerApi(api); - connect(ui->rightMenu, SIGNAL(finished(bool)), this, - SLOT(rightMenuFinished(bool))); - - connect(constantValue, SIGNAL(valueChanged(double)), - SLOT(constantValueChanged(double))); - - connect(amplitude, SIGNAL(valueChanged(double)), - this, SLOT(amplitudeChanged(double))); - - connect(noiseAmplitude,SIGNAL(valueChanged(double)), - this, SLOT(noiseAmplitudeChanged(double))); - connect(fileAmplitude, SIGNAL(valueChanged(double)), - this, SLOT(fileAmplitudeChanged(double))); - connect(fileOffset, SIGNAL(valueChanged(double)), - this, SLOT(fileOffsetChanged(double))); - connect(filePhase, SIGNAL(valueChanged(double)), - this, SLOT(filePhaseChanged(double))); - connect(ui->fileChannel, SIGNAL(currentIndexChanged(int)), - this, SLOT(fileChannelChanged(int))); - connect(fileSampleRate, SIGNAL(valueChanged(double)), - this, SLOT(fileSampleRateChanged(double))); - connect(offset, SIGNAL(valueChanged(double)), - this, SLOT(offsetChanged(double))); - connect(frequency, SIGNAL(valueChanged(double)), - this, SLOT(frequencyChanged(double))); - connect(phase, SIGNAL(valueChanged(double)), - this, SLOT(phaseChanged(double))); - - connect(dutycycle, SIGNAL(valueChanged(double)), - this, SLOT(dutyChanged(double))); - - - connect(fallTime, SIGNAL(valueChanged(double)), - this, SLOT(fallChanged(double))); - connect(holdHighTime, SIGNAL(valueChanged(double)), - this, SLOT(holdHighChanged(double))); - connect(holdLowTime, SIGNAL(valueChanged(double)), - this, SLOT(holdLowChanged(double))); - connect(riseTime, SIGNAL(valueChanged(double)), - this, SLOT(riseChanged(double))); - - connect(stepsUp,SIGNAL(valueChanged(double)), - this,SLOT(stepsUpChanged(double))); - - connect(stepsDown,SIGNAL(valueChanged(double)), - this,SLOT(stepsDownChanged(double))); - - connect(stairPhase,SIGNAL(valueChanged(double)), - this,SLOT(stairPhaseChanged(double))); - - connect(mathRecordLength, SIGNAL(valueChanged(double)), - this, SLOT(mathRecordLengthChanged(double))); - connect(mathSampleRate, SIGNAL(valueChanged(double)), - this, SLOT(mathSampleRateChanged(double))); - - connect(ui->type, SIGNAL(currentIndexChanged(int)), - this, SLOT(waveformTypeChanged(int))); - connect(ui->cbNoiseType, SIGNAL(currentIndexChanged(int)), - this, SLOT(noiseTypeChanged(int))); - - connect(ui->cbLineThickness, SIGNAL(currentIndexChanged(int)), - this, SLOT(lineThicknessChanged(int))); - - connect(load, SIGNAL(valueChanged(double)), - this, SLOT(externalLoadChanged(double))); - - connect(ui->tabWidget, SIGNAL(currentChanged(int)), - this, SLOT(tabChanged(int))); + connect(ui->rightMenu, SIGNAL(finished(bool)), this, SLOT(rightMenuFinished(bool))); + + connect(constantValue, SIGNAL(valueChanged(double)), SLOT(constantValueChanged(double))); + + connect(amplitude, SIGNAL(valueChanged(double)), this, SLOT(amplitudeChanged(double))); + + connect(noiseAmplitude, SIGNAL(valueChanged(double)), this, SLOT(noiseAmplitudeChanged(double))); + connect(fileAmplitude, SIGNAL(valueChanged(double)), this, SLOT(fileAmplitudeChanged(double))); + connect(fileOffset, SIGNAL(valueChanged(double)), this, SLOT(fileOffsetChanged(double))); + connect(filePhase, SIGNAL(valueChanged(double)), this, SLOT(filePhaseChanged(double))); + connect(ui->fileChannel, SIGNAL(currentIndexChanged(int)), this, SLOT(fileChannelChanged(int))); + connect(fileSampleRate, SIGNAL(valueChanged(double)), this, SLOT(fileSampleRateChanged(double))); + connect(offset, SIGNAL(valueChanged(double)), this, SLOT(offsetChanged(double))); + connect(frequency, SIGNAL(valueChanged(double)), this, SLOT(frequencyChanged(double))); + connect(phase, SIGNAL(valueChanged(double)), this, SLOT(phaseChanged(double))); + + connect(dutycycle, SIGNAL(valueChanged(double)), this, SLOT(dutyChanged(double))); + + connect(fallTime, SIGNAL(valueChanged(double)), this, SLOT(fallChanged(double))); + connect(holdHighTime, SIGNAL(valueChanged(double)), this, SLOT(holdHighChanged(double))); + connect(holdLowTime, SIGNAL(valueChanged(double)), this, SLOT(holdLowChanged(double))); + connect(riseTime, SIGNAL(valueChanged(double)), this, SLOT(riseChanged(double))); + + connect(stepsUp, SIGNAL(valueChanged(double)), this, SLOT(stepsUpChanged(double))); + + connect(stepsDown, SIGNAL(valueChanged(double)), this, SLOT(stepsDownChanged(double))); + + connect(stairPhase, SIGNAL(valueChanged(double)), this, SLOT(stairPhaseChanged(double))); + + connect(mathRecordLength, SIGNAL(valueChanged(double)), this, SLOT(mathRecordLengthChanged(double))); + connect(mathSampleRate, SIGNAL(valueChanged(double)), this, SLOT(mathSampleRateChanged(double))); + + connect(ui->type, SIGNAL(currentIndexChanged(int)), this, SLOT(waveformTypeChanged(int))); + connect(ui->cbNoiseType, SIGNAL(currentIndexChanged(int)), this, SLOT(noiseTypeChanged(int))); + + connect(ui->cbLineThickness, SIGNAL(currentIndexChanged(int)), this, SLOT(lineThicknessChanged(int))); + + connect(load, SIGNAL(valueChanged(double)), this, SLOT(externalLoadChanged(double))); + + connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabChanged(int))); connect(ui->load_file, SIGNAL(pressed()), this, SLOT(loadFile())); - connect(ui->mathWidget, SIGNAL(functionValid(const QString&)), - this, SLOT(setFunction(const QString&))); + connect(ui->mathWidget, SIGNAL(functionValid(const QString &)), this, SLOT(setFunction(const QString &))); - connect(ui->run_button, SIGNAL(toggled(bool)), tme, - SLOT(setRunning(bool))); - connect(tme, SIGNAL(runToggled(bool)), ui->run_button, - SLOT(toggle(bool))); - connect(tme, SIGNAL(runToggled(bool)), - this, SLOT(startStop(bool))); + connect(ui->run_button, SIGNAL(toggled(bool)), tme, SLOT(setRunning(bool))); + connect(tme, SIGNAL(runToggled(bool)), ui->run_button, SLOT(toggle(bool))); + connect(tme, SIGNAL(runToggled(bool)), this, SLOT(startStop(bool))); - connect(ui->refreshBtn, SIGNAL(clicked()), - this, SLOT(loadFileCurrentChannelData())); + connect(ui->refreshBtn, SIGNAL(clicked()), this, SLOT(loadFileCurrentChannelData())); m_plot->addZoomer(0); resetZoom(); @@ -598,16 +495,16 @@ SignalGenerator::SignalGenerator(struct iio_context *_ctx, Filter *filt, readPreferences(); ui->btnHelp->setUrl("https://wiki.analog.com/university/tools/m2k/scopy/siggen"); - - m_plot->setOffsetHandleVisible(0,false); - m_plot->setOffsetHandleVisible(1,false); + + m_plot->setOffsetHandleVisible(0, false); + m_plot->setOffsetHandleVisible(1, false); m_plot->setAxisVisible(QwtAxis::YLeft, false); m_plot->setActiveVertAxis(0); m_plot->enableTimeTrigger(false); // plot widget - QWidget* centralWidget = new QWidget(); + QWidget *centralWidget = new QWidget(); QGridLayout *gridLayout = new QGridLayout(); gridLayout->setVerticalSpacing(0); gridLayout->setHorizontalSpacing(0); @@ -620,17 +517,15 @@ SignalGenerator::SignalGenerator(struct iio_context *_ctx, Filter *filt, centralWidget->setLayout(gridLayout); ui->plot->removeWidget(ui->instrumentNotes); - ui->plot->addWidget(centralWidget,0,0); + ui->plot->addWidget(centralWidget, 0, 0); ui->plot->addWidget(ui->instrumentNotes, 1, 0); channels[0]->menuButton()->setChecked(true); - } - SignalGenerator::~SignalGenerator() { - ui->run_button->toggle(false); + ui->run_button->toggle(false); delete fileManager; @@ -639,20 +534,16 @@ SignalGenerator::~SignalGenerator() delete time_block_data; } -void SignalGenerator::settingsLoaded() -{ - updatePreview(); -} +void SignalGenerator::settingsLoaded() { updatePreview(); } void SignalGenerator::readPreferences() { Preferences *p = Preferences::GetInstance(); bool showFps = p->get("general_show_plot_fps").toBool(); m_plot->setVisibleFpsLabel(showFps); - double prefered_periods_nr = 2;//p->get("M2k_siggen_periods").toBool()); + double prefered_periods_nr = 2; // p->get("M2k_siggen_periods").toBool()); - - if (nr_of_periods != prefered_periods_nr) { + if(nr_of_periods != prefered_periods_nr) { nr_of_periods = prefered_periods_nr; resetZoom(); } @@ -662,41 +553,42 @@ void SignalGenerator::readPreferences() void SignalGenerator::resetZoom() { - disconnect(m_plot->getZoomer(),SIGNAL(zoomed(QRectF)),this,SLOT(rescale())); - bool disable_zoom=false; + disconnect(m_plot->getZoomer(), SIGNAL(zoomed(QRectF)), this, SLOT(rescale())); + bool disable_zoom = false; - for (auto it = channels.begin(); it != channels.end(); ++it) { - auto ptr=getData(*it); + for(auto it = channels.begin(); it != channels.end(); ++it) { + auto ptr = getData(*it); - if (ptr->type==SIGNAL_TYPE_BUFFER) { - disable_zoom=true; + if(ptr->type == SIGNAL_TYPE_BUFFER) { + disable_zoom = true; break; } } - if (!disable_zoom) { - connect(m_plot->getZoomer(),SIGNAL(zoomed(QRectF)),this,SLOT(rescale())); + if(!disable_zoom) { + connect(m_plot->getZoomer(), SIGNAL(zoomed(QRectF)), this, SLOT(rescale())); } double period = 0.0; int slowSignalId = -1; - for (auto it = channels.begin(); it != channels.end(); ++it) { - if ((*it)->enableButton()->isChecked()) { + for(auto it = channels.begin(); it != channels.end(); ++it) { + if((*it)->enableButton()->isChecked()) { auto ptr = getData((*it)); - switch (ptr->type) { + switch(ptr->type) { case SIGNAL_TYPE_CONSTANT: break; case SIGNAL_TYPE_BUFFER: - if (ptr->file_type) { + if(ptr->file_type) { double length = 1; - if (ptr->file_nr_of_samples.size() > 0) { - length=(1/ptr->file_sr)*ptr->file_nr_of_samples[ptr->file_channel]; + if(ptr->file_nr_of_samples.size() > 0) { + length = + (1 / ptr->file_sr) * ptr->file_nr_of_samples[ptr->file_channel]; } - if (periodid; } } @@ -704,16 +596,16 @@ void SignalGenerator::resetZoom() break; case SIGNAL_TYPE_WAVEFORM: - if (period< 1.0 / (ptr->frequency)) { - period=(1.0/ptr->frequency); + if(period < 1.0 / (ptr->frequency)) { + period = (1.0 / ptr->frequency); slowSignalId = ptr->id; } break; case SIGNAL_TYPE_MATH: - if (period< (ptr->math_record_length)) { - period=(ptr->math_record_length); + if(period < (ptr->math_record_length)) { + period = (ptr->math_record_length); slowSignalId = ptr->id; } @@ -721,21 +613,20 @@ void SignalGenerator::resetZoom() default: break; - } } } - period*= nr_of_periods; + period *= nr_of_periods; - if (period==0.0) { // prevent empty graph - period=0.1; + if(period == 0.0) { // prevent empty graph + period = 0.1; } m_plot->setVertUnitsPerDiv(1); m_plot->setVertOffset(0); - m_plot->setHorizUnitsPerDiv(period/10); - m_plot->setHorizOffset(period/2); + m_plot->setHorizUnitsPerDiv(period / 10); + m_plot->setHorizOffset(period / 2); m_plot->zoomBaseUpdate(); rescale(); if(slowSignalId != -1) { @@ -747,33 +638,31 @@ void SignalGenerator::resetZoom() void SignalGenerator::rescale() { - auto hOffset=m_plot->HorizOffset(); - auto hUnitsPerDiv=m_plot->HorizUnitsPerDiv(); - auto xDivisions=10; - + auto hOffset = m_plot->HorizOffset(); + auto hUnitsPerDiv = m_plot->HorizUnitsPerDiv(); + auto xDivisions = 10; - zoomT1=hOffset-hUnitsPerDiv*(xDivisions/2); - zoomT2=hOffset+hUnitsPerDiv*(xDivisions/2); + zoomT1 = hOffset - hUnitsPerDiv * (xDivisions / 2); + zoomT2 = hOffset + hUnitsPerDiv * (xDivisions / 2); - zoomT1OnScreen=hOffset-hUnitsPerDiv*(xDivisions/2); - zoomT2OnScreen=hOffset+hUnitsPerDiv*(xDivisions/2); + zoomT1OnScreen = hOffset - hUnitsPerDiv * (xDivisions / 2); + zoomT2OnScreen = hOffset + hUnitsPerDiv * (xDivisions / 2); - auto deltaT= zoomT2-zoomT1; + auto deltaT = zoomT2 - zoomT1; - double max_sample_rate=750000000; - nb_points=NB_POINTS; - sample_rate=(double)nb_points/deltaT; - - if (sample_rate>max_sample_rate) { - nb_points=nb_points / (long)(sample_rate/max_sample_rate); - sample_rate=max_sample_rate; + double max_sample_rate = 750000000; + nb_points = NB_POINTS; + sample_rate = (double)nb_points / deltaT; + if(sample_rate > max_sample_rate) { + nb_points = nb_points / (long)(sample_rate / max_sample_rate); + sample_rate = max_sample_rate; } - long startSample=sample_rate*zoomT1; + long startSample = sample_rate * zoomT1; m_plot->setDataStartingPoint(startSample); - m_plot->setSampleRate(sample_rate,1,"Hz"); - if (nb_points < 16) { + m_plot->setSampleRate(sample_rate, 1, "Hz"); + if(nb_points < 16) { nb_points = 16; } time_block_data->time_block->set_nsamps(nb_points); @@ -786,8 +675,8 @@ void SignalGenerator::constantValueChanged(double value) { auto ptr = getCurrentData(); - if (ptr->constant != (float) value) { - ptr->constant = (float) value; + if(ptr->constant != (float)value) { + ptr->constant = (float)value; resetZoom(); } } @@ -796,7 +685,7 @@ void SignalGenerator::amplitudeChanged(double value) { auto ptr = getCurrentData(); - if (ptr->amplitude != value) { + if(ptr->amplitude != value) { ptr->amplitude = value; resetZoom(); } @@ -806,7 +695,7 @@ void SignalGenerator::fileAmplitudeChanged(double value) { auto ptr = getCurrentData(); - if (ptr->file_amplitude != value) { + if(ptr->file_amplitude != value) { ptr->file_amplitude = value; resetZoom(); } @@ -816,8 +705,8 @@ void SignalGenerator::fileOffsetChanged(double value) { auto ptr = getCurrentData(); - if (ptr->file_offset!= value) { - ptr->file_offset= value; + if(ptr->file_offset != value) { + ptr->file_offset = value; resetZoom(); } } @@ -826,8 +715,8 @@ void SignalGenerator::filePhaseChanged(double value) { auto ptr = getCurrentData(); - if (ptr->file_phase!= value) { - ptr->file_phase= value; + if(ptr->file_phase != value) { + ptr->file_phase = value; resetZoom(); } } @@ -836,8 +725,8 @@ void SignalGenerator::offsetChanged(double value) { auto ptr = getCurrentData(); - if (ptr->offset != (float) value) { - ptr->offset = (float) value; + if(ptr->offset != (float)value) { + ptr->offset = (float)value; resetZoom(); } } @@ -846,11 +735,10 @@ void SignalGenerator::fileChannelChanged(int value) { auto ptr = getCurrentData(); - if (ptr->file_channel != (size_t) value) { - ptr->file_channel = (size_t) value; + if(ptr->file_channel != (size_t)value) { + ptr->file_channel = (size_t)value; loadFileChannelData(currentChannel); - this->ui->label_size->setText(QString::number( - ptr->file_nr_of_samples[ptr->file_channel]) + + this->ui->label_size->setText(QString::number(ptr->file_nr_of_samples[ptr->file_channel]) + tr(" samples")); resetZoom(); @@ -860,18 +748,17 @@ void SignalGenerator::fileSampleRateChanged(double value) { auto ptr = getCurrentData(); - if (ptr->file_sr != value) { + if(ptr->file_sr != value) { ptr->file_sr = value; resetZoom(); } } - void SignalGenerator::frequencyChanged(double value) { auto ptr = getCurrentData(); - if (ptr->frequency != value) { + if(ptr->frequency != value) { phase->setFrequency(value); if(phase->inSeconds()) { ptr->phase = phase->value(); @@ -886,17 +773,16 @@ void SignalGenerator::mathRecordLengthChanged(double value) { auto ptr = getCurrentData(); - if (ptr->math_record_length != value) { + if(ptr->math_record_length != value) { ptr->math_record_length = value; resetZoom(); } } - void SignalGenerator::mathSampleRateChanged(double value) { auto ptr = getCurrentData(); - if (ptr->math_sr != value) { + if(ptr->math_sr != value) { ptr->math_sr = value; resetZoom(); } @@ -908,8 +794,8 @@ void SignalGenerator::noiseTypeChanged(int index) auto ptr = getCurrentData(); gr::analog::noise_type_t value = qvariant_cast(ui->cbNoiseType->itemData(index)); - if (ptr->noiseType != value) { - ptr->noiseType= value; + if(ptr->noiseType != value) { + ptr->noiseType = value; resetZoom(); } } @@ -919,49 +805,49 @@ void SignalGenerator::noiseAmplitudeChanged(double value) auto ptr = getCurrentData(); - if (ptr->noiseAmplitude != value) { + if(ptr->noiseAmplitude != value) { ptr->noiseAmplitude = value; resetZoom(); } } -void SignalGenerator::externalLoadChanged(double value) { +void SignalGenerator::externalLoadChanged(double value) +{ auto ptr = getCurrentData(); - if (ptr->load != value) { + if(ptr->load != value) { ptr->load = value; resetZoom(); } - } void SignalGenerator::lineThicknessChanged(int index) { - auto ptr = getCurrentData(); - int lineThickness = (int)(ptr->lineThickness / 0.5) - 1; - if (lineThickness != index) { - ptr->lineThickness = 0.5 * (index + 1); + auto ptr = getCurrentData(); + int lineThickness = (int)(ptr->lineThickness / 0.5) - 1; + if(lineThickness != index) { + ptr->lineThickness = 0.5 * (index + 1); m_plot->setLineWidth(ptr->id, ptr->lineThickness); m_plot->replot(); - } + } } void SignalGenerator::dutyChanged(double value) { auto ptr = getCurrentData(); - if (ptr->dutycycle != value) { - ptr->dutycycle= value; + if(ptr->dutycycle != value) { + ptr->dutycycle = value; resetZoom(); } } - void SignalGenerator::trapezoidalComputeFrequency() { auto ptr = getCurrentData(); - double value = static_cast((round(1/(ptr->rise+ptr->fall+ptr->holdh+ptr->holdl))*1000)/1000); + double value = + static_cast((round(1 / (ptr->rise + ptr->fall + ptr->holdh + ptr->holdl)) * 1000) / 1000); frequency->setValue(value); } @@ -969,8 +855,8 @@ void SignalGenerator::riseChanged(double value) { auto ptr = getCurrentData(); - if (ptr->rise != value) { - ptr->rise= value; + if(ptr->rise != value) { + ptr->rise = value; trapezoidalComputeFrequency(); } } @@ -979,8 +865,8 @@ void SignalGenerator::fallChanged(double value) { auto ptr = getCurrentData(); - if (ptr->fall != value) { - ptr->fall= value; + if(ptr->fall != value) { + ptr->fall = value; trapezoidalComputeFrequency(); } } @@ -989,8 +875,8 @@ void SignalGenerator::holdHighChanged(double value) { auto ptr = getCurrentData(); - if (ptr->holdh != value) { - ptr->holdh= value; + if(ptr->holdh != value) { + ptr->holdh = value; trapezoidalComputeFrequency(); } } @@ -999,8 +885,8 @@ void SignalGenerator::holdLowChanged(double value) { auto ptr = getCurrentData(); - if (ptr->holdl != value) { - ptr->holdl= value; + if(ptr->holdl != value) { + ptr->holdl = value; trapezoidalComputeFrequency(); } } @@ -1009,7 +895,7 @@ void SignalGenerator::stepsUpChanged(double value) { auto ptr = getCurrentData(); if(ptr->steps_up != (int)value) { - ptr->steps_up =(int) value; + ptr->steps_up = (int)value; stairPhase->setMaxValue(ptr->steps_up + ptr->steps_down); resetZoom(); } @@ -1020,7 +906,7 @@ void SignalGenerator::stepsDownChanged(double value) auto ptr = getCurrentData(); if(ptr->steps_down != (int)value) { - ptr->steps_down =(int) value; + ptr->steps_down = (int)value; stairPhase->setMaxValue(ptr->steps_up + ptr->steps_down); resetZoom(); } @@ -1029,8 +915,8 @@ void SignalGenerator::stairPhaseChanged(double value) { auto ptr = getCurrentData(); - if(ptr->stairphase != (int) value) { - ptr->stairphase = (int) value; + if(ptr->stairphase != (int)value) { + ptr->stairphase = (int)value; resetZoom(); } } @@ -1040,7 +926,7 @@ void SignalGenerator::phaseChanged(double value) auto ptr = getCurrentData(); ptr->indexValue = phase->indexValue(); - if (ptr->phase != value) { + if(ptr->phase != value) { ptr->phase = value; resetZoom(); } @@ -1055,46 +941,35 @@ void SignalGenerator::phaseIndexChanged() void SignalGenerator::waveformUpdateUi(int val) { - frequency->setEnabled(val!=SG_TRA_WAVE); - ui->wtrapezparams->setVisible(val==SG_TRA_WAVE); - stepsUp->setVisible(val==SG_STAIR_WAVE); - stepsDown->setVisible(val==SG_STAIR_WAVE); - stairPhase->setVisible(val==SG_STAIR_WAVE); - phase->setVisible(val!=SG_STAIR_WAVE); - dutycycle->setVisible(val==SG_SQR_WAVE); - if(val==SG_TRA_WAVE) { + frequency->setEnabled(val != SG_TRA_WAVE); + ui->wtrapezparams->setVisible(val == SG_TRA_WAVE); + stepsUp->setVisible(val == SG_STAIR_WAVE); + stepsDown->setVisible(val == SG_STAIR_WAVE); + stairPhase->setVisible(val == SG_STAIR_WAVE); + phase->setVisible(val != SG_STAIR_WAVE); + dutycycle->setVisible(val == SG_SQR_WAVE); + if(val == SG_TRA_WAVE) { trapezoidalComputeFrequency(); } - } void SignalGenerator::waveformTypeChanged(int val) { enum sg_waveform types[] = { - SG_SIN_WAVE, - SG_SQR_WAVE, - SG_TRI_WAVE, - SG_TRA_WAVE, - SG_SAW_WAVE, - SG_INV_SAW_WAVE, - SG_STAIR_WAVE, + SG_SIN_WAVE, SG_SQR_WAVE, SG_TRI_WAVE, SG_TRA_WAVE, SG_SAW_WAVE, SG_INV_SAW_WAVE, SG_STAIR_WAVE, }; auto ptr = getCurrentData(); - if (ptr->waveform != types[val]) { + if(ptr->waveform != types[val]) { ptr->waveform = types[val]; // only show trapezoid parameters for the apropriate waveform waveformUpdateUi(types[val]); resetZoom(); } - } -QSharedPointer SignalGenerator::getCurrentData() -{ - return getData(channels[currentChannel]); -} +QSharedPointer SignalGenerator::getCurrentData() { return getData(channels[currentChannel]); } QSharedPointer SignalGenerator::getData(QWidget *obj) { @@ -1104,9 +979,9 @@ QSharedPointer SignalGenerator::getData(QWidget *obj) void SignalGenerator::resizeTabWidget(int index) { - for(int i=0;itabWidget->count();i++) - if(i!=index) - ui->tabWidget->widget(i)->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); + for(int i = 0; i < ui->tabWidget->count(); i++) + if(i != index) + ui->tabWidget->widget(i)->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); ui->tabWidget->widget(index)->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); ui->tabWidget->widget(index)->resize(ui->tabWidget->widget(index)->minimumSizeHint()); ui->tabWidget->widget(index)->adjustSize(); @@ -1116,10 +991,9 @@ void SignalGenerator::tabChanged(int index) { auto ptr = getCurrentData(); - if (ptr->type != (enum SIGNAL_TYPE) index) { - ptr->type = (enum SIGNAL_TYPE) index; - if(ptr->type == SIGNAL_TYPE_BUFFER) - { + if(ptr->type != (enum SIGNAL_TYPE)index) { + ptr->type = (enum SIGNAL_TYPE)index; + if(ptr->type == SIGNAL_TYPE_BUFFER) { loadFileCurrentChannelData(); } resizeTabWidget(index); // causes small glitch on windows, to be investigated @@ -1138,10 +1012,10 @@ void SignalGenerator::updatePreview() bool enabled = false; time_block_data->time_block->reset(); - for (auto it = channels.begin(); it != channels.end(); ++it) { + for(auto it = channels.begin(); it != channels.end(); ++it) { basic_block_sptr source; - if ((*it)->enableButton()->isChecked()) { + if((*it)->enableButton()->isChecked()) { source = getSource((*it), sample_rate, top, true); enabled = true; @@ -1150,9 +1024,10 @@ void SignalGenerator::updatePreview() } auto head = blocks::head::make(sizeof(float), nb_points + nb_points_correction); - auto clamp = analog::rail_ff::make(MIN_PREVIEW_RANGE, MAX_PREVIEW_RANGE); // prevent plotting infinite values + auto clamp = + analog::rail_ff::make(MIN_PREVIEW_RANGE, MAX_PREVIEW_RANGE); // prevent plotting infinite values top->connect(source, 0, clamp, 0); - top->connect(clamp, 0, head ,0); + top->connect(clamp, 0, head, 0); top->connect(head, 0, time_block_data->time_block, i++); } @@ -1162,8 +1037,8 @@ void SignalGenerator::updatePreview() top->run(); top->disconnect_all(); - if (ui->run_button->runButtonChecked()) { - if (enabled) { + if(ui->run_button->runButtonChecked()) { + if(enabled) { stop(); start(); } else { @@ -1174,65 +1049,61 @@ void SignalGenerator::updatePreview() enum sg_file_format SignalGenerator::getFileFormat(QString filePath) { - if (filePath.isEmpty()) { + if(filePath.isEmpty()) { return FORMAT_NO_FILE; } QFile f; f.setFileName(filePath); - if (!f.open(QIODevice::ReadOnly)) { + if(!f.open(QIODevice::ReadOnly)) { return FORMAT_NO_FILE; } f.close(); - if (filePath.endsWith(".wav")) { + if(filePath.endsWith(".wav")) { return FORMAT_WAVE; } - if (filePath.endsWith(".csv")||filePath.endsWith(".txt")) { + if(filePath.endsWith(".csv") || filePath.endsWith(".txt")) { return FORMAT_CSV; } - if (filePath.endsWith(".mat")) { + if(filePath.endsWith(".mat")) { return FORMAT_MAT; } return FORMAT_BIN_FLOAT; } - - -bool SignalGenerator::loadParametersFromFile( - QSharedPointer ptr,QString filePath) +bool SignalGenerator::loadParametersFromFile(QSharedPointer ptr, QString filePath) { - ptr->file_message=""; - ptr->file=filePath; - ptr->file_type=getFileFormat(ptr->file); + ptr->file_message = ""; + ptr->file = filePath; + ptr->file_type = getFileFormat(ptr->file); auto info = QFileInfo(ptr->file); ptr->file_channel_names.clear(); - ptr->file_nr_of_channels=0; + ptr->file_nr_of_channels = 0; ptr->file_nr_of_samples.clear(); - ptr->file_channel=0; + ptr->file_channel = 0; - if (ptr->file_type==FORMAT_BIN_FLOAT) { + if(ptr->file_type == FORMAT_BIN_FLOAT) { ptr->file_nr_of_samples.push_back(info.size() / sizeof(float)); - ptr->file_nr_of_channels=1; - ptr->file_message="Binary floats file"; + ptr->file_nr_of_channels = 1; + ptr->file_message = "Binary floats file"; } - if (ptr->file_type==FORMAT_WAVE) { + if(ptr->file_type == FORMAT_WAVE) { // read samples per second - bool ok=true; + bool ok = true; try { - auto fs = blocks::wavfile_source::make(ptr->file.toLocal8Bit(),true); - } catch(std::runtime_error& e) - { - ok=false; - ptr->file_message=QString::fromLocal8Bit(e.what()); + auto fs = blocks::wavfile_source::make(ptr->file.toLocal8Bit(), true); + } catch(std::runtime_error &e) { + ok = false; + ptr->file_message = QString::fromLocal8Bit(e.what()); ptr->file_nr_of_samples.push_back(0); - ptr->file_type=FORMAT_NO_FILE; + ptr->file_type = FORMAT_NO_FILE; } if(!ok) return false; @@ -1244,48 +1115,48 @@ bool SignalGenerator::loadParametersFromFile( f.setFileName(ptr->file); f.open(QIODevice::ReadOnly); - f.read(riff.data,12); + f.read(riff.data, 12); - if (!riffCompare(riff,"WAVE")) { + if(!riffCompare(riff, "WAVE")) { return false; } - while (!f.atEnd()) { - f.read(chunk.data,8); + while(!f.atEnd()) { + f.read(chunk.data, 8); - if (chunkCompare(chunk,"fmt ")) { - f.read(ptr->file_wav_hdr.header_data,sizeof(ptr->file_wav_hdr.header_data)); - ptr->file_sr=ptr->file_wav_hdr.SamplesPerSec; - ptr->file_nr_of_channels=ptr->file_wav_hdr.noChan; - ptr->file_channel=0; + if(chunkCompare(chunk, "fmt ")) { + f.read(ptr->file_wav_hdr.header_data, sizeof(ptr->file_wav_hdr.header_data)); + ptr->file_sr = ptr->file_wav_hdr.SamplesPerSec; + ptr->file_nr_of_channels = ptr->file_wav_hdr.noChan; + ptr->file_channel = 0; continue; } - if (chunkCompare(chunk,"data")) { - auto bytesPerSample = (ptr->file_wav_hdr.bitsPerSample/8); - nr_of_samples = riff.size/(bytesPerSample); + if(chunkCompare(chunk, "data")) { + auto bytesPerSample = (ptr->file_wav_hdr.bitsPerSample / 8); + nr_of_samples = riff.size / (bytesPerSample); continue; } - f.seek(f.pos()+chunk.size); + f.seek(f.pos() + chunk.size); } - for (size_t i=0; ifile_nr_of_channels; i++) { + for(size_t i = 0; i < ptr->file_nr_of_channels; i++) { ptr->file_channel_names.push_back("Channel " + QString::number(i)); ptr->file_nr_of_samples.push_back(nr_of_samples); } - ptr->file_message="WAV"; + ptr->file_message = "WAV"; } - if (ptr->file_type==FORMAT_CSV) { + if(ptr->file_type == FORMAT_CSV) { try { fileManager->open(ptr->file, FileManager::IMPORT); } catch(FileManagerException &e) { - ptr->file_message=QString::fromLocal8Bit(e.what()); + ptr->file_message = QString::fromLocal8Bit(e.what()); ptr->file_nr_of_samples.push_back(0); - ptr->file_type=FORMAT_NO_FILE; + ptr->file_type = FORMAT_NO_FILE; return false; } @@ -1295,38 +1166,38 @@ bool SignalGenerator::loadParametersFromFile( if(fileManager->getSampleRate()) ptr->file_sr = fileManager->getSampleRate(); - ptr->file_channel=0; // autoselect channel 0 - for (size_t i=0; ifile_nr_of_channels; i++) { + ptr->file_channel = 0; // autoselect channel 0 + for(size_t i = 0; i < ptr->file_nr_of_channels; i++) { ptr->file_channel_names.push_back("Column " + QString::number(i)); ptr->file_nr_of_samples.push_back(fileManager->getNrOfSamples()); } - ptr->file_message="CSV"; + ptr->file_message = "CSV"; } #ifdef MATLAB_SUPPORT_SIGGEN - if (ptr->file_type==FORMAT_MAT) { + if(ptr->file_type == FORMAT_MAT) { mat_t *matfp; matvar_t *matvar; - matfp = Mat_Open(filePath.toStdString().c_str(),MAT_ACC_RDONLY); + matfp = Mat_Open(filePath.toStdString().c_str(), MAT_ACC_RDONLY); - if (NULL == matfp) { - qDebug(CAT_M2K_SIGNAL_GENERATOR)<<"Error opening MAT file "<file_nr_of_samples.push_back(0); ptr->file_message = "MAT file could not be parsed"; return false; } - while ((matvar = Mat_VarReadNextInfo(matfp)) != NULL) { + while((matvar = Mat_VarReadNextInfo(matfp)) != NULL) { /* must be a vector */ - if (!(matvar->rank !=2 || (matvar->dims[0] > 1 && matvar->dims[1] > 1) - || matvar->class_type != MAT_C_DOUBLE)) { + if(!(matvar->rank != 2 || (matvar->dims[0] > 1 && matvar->dims[1] > 1) || + matvar->class_type != MAT_C_DOUBLE)) { Mat_VarReadDataAll(matfp, matvar); - if (!matvar->isComplex) { - qDebug(CAT_M2K_SIGNAL_GENERATOR)<<"Complex buffers not supported"; - ptr->file_message="Complex buffers not supported"; + if(!matvar->isComplex) { + qDebug(CAT_M2K_SIGNAL_GENERATOR) << "Complex buffers not supported"; + ptr->file_message = "Complex buffers not supported"; ptr->file_channel_names.push_back(QString(matvar->name)); ptr->file_nr_of_samples.push_back(*matvar->dims); ptr->file_nr_of_channels++; @@ -1341,27 +1212,25 @@ bool SignalGenerator::loadParametersFromFile( } #endif - if (ptr->file_nr_of_channels==0) { - ptr->file_message+="File not loaded due to errors"; + if(ptr->file_nr_of_channels == 0) { + ptr->file_message += "File not loaded due to errors"; ptr->file_nr_of_samples.push_back(0); - ptr->file_type=FORMAT_NO_FILE; - return false; + ptr->file_type = FORMAT_NO_FILE; + return false; } ui->fileChannel->setEnabled(ptr->file_nr_of_channels > 1); - for(size_t i = 0; i < ptr->file_nr_of_samples.size(); i++) - { - if(ptr->file_nr_of_samples[i] > m_maxNbOfSamples) - { + for(size_t i = 0; i < ptr->file_nr_of_samples.size(); i++) { + if(ptr->file_nr_of_samples[i] > m_maxNbOfSamples) { ptr->file_nr_of_samples[i] = m_maxNbOfSamples; ptr->file_message = "File truncated. Max 4MS"; } } - ptr->file_amplitude=1.0; - ptr->file_offset=0; - ptr->file_phase=0; + ptr->file_amplitude = 1.0; + ptr->file_offset = 0; + ptr->file_phase = 0; return true; } @@ -1369,69 +1238,69 @@ bool SignalGenerator::loadParametersFromFile( void SignalGenerator::reloadFileFromPath() { auto ptr = getCurrentData(); - if (!ptr->file.isEmpty()) { + if(!ptr->file.isEmpty()) { loadFileFromPath(ptr->file); } } -void SignalGenerator::loadFileFromPath(QString filename){ - auto ptr = getCurrentData(); - - ptr->file = filename; - ui->label_path->setText(ptr->file); - Util::setWidgetNrOfChars(ui->label_path,10,30); - bool loaded = loadParametersFromFile(ptr,ptr->file); - - fileAmplitude->setEnabled(loaded); - fileSampleRate->setEnabled(loaded); - filePhase->setEnabled(loaded); - fileOffset->setEnabled(loaded); - if (!loaded) { - ptr->file_type=FORMAT_NO_FILE; - resetZoom(); - return; - } - fileOffset->setValue(ptr->file_offset); - filePhase->setValue(ptr->file_phase); - filePhase->setMaxValue(ptr->file_nr_of_samples[ptr->file_channel]); - fileSampleRate->setValue(ptr->file_sr); - ui->fileChannel->blockSignals(true); - ui->fileChannel->clear(); - ui->label_format->setText(ptr->file_message); - - if (ptr->file_channel_names.isEmpty()) { - for (size_t i=0; ifile_nr_of_channels; i++) { - ui->fileChannel->addItem(QString::number(i)); - } - } else { - ui->fileChannel->addItems(ptr->file_channel_names); - } - - this->ui->label_size->setText(QString::number( - ptr->file_nr_of_samples[ptr->file_channel]) + - tr(" samples")); - ui->fileChannel->setEnabled(ptr->file_nr_of_channels>1); - ui->fileChannel->setCurrentIndex(ptr->file_channel); - ui->fileChannel->blockSignals(false); - loadFileChannelData(currentChannel); - updateRightMenuForChn(currentChannel); +void SignalGenerator::loadFileFromPath(QString filename) +{ + auto ptr = getCurrentData(); + + ptr->file = filename; + ui->label_path->setText(ptr->file); + Util::setWidgetNrOfChars(ui->label_path, 10, 30); + bool loaded = loadParametersFromFile(ptr, ptr->file); + + fileAmplitude->setEnabled(loaded); + fileSampleRate->setEnabled(loaded); + filePhase->setEnabled(loaded); + fileOffset->setEnabled(loaded); + if(!loaded) { + ptr->file_type = FORMAT_NO_FILE; + resetZoom(); + return; + } + fileOffset->setValue(ptr->file_offset); + filePhase->setValue(ptr->file_phase); + filePhase->setMaxValue(ptr->file_nr_of_samples[ptr->file_channel]); + fileSampleRate->setValue(ptr->file_sr); + ui->fileChannel->blockSignals(true); + ui->fileChannel->clear(); + ui->label_format->setText(ptr->file_message); + + if(ptr->file_channel_names.isEmpty()) { + for(size_t i = 0; i < ptr->file_nr_of_channels; i++) { + ui->fileChannel->addItem(QString::number(i)); + } + } else { + ui->fileChannel->addItems(ptr->file_channel_names); + } + + this->ui->label_size->setText(QString::number(ptr->file_nr_of_samples[ptr->file_channel]) + tr(" samples")); + ui->fileChannel->setEnabled(ptr->file_nr_of_channels > 1); + ui->fileChannel->setCurrentIndex(ptr->file_channel); + ui->fileChannel->blockSignals(false); + loadFileChannelData(currentChannel); + updateRightMenuForChn(currentChannel); } void SignalGenerator::loadFile() { - QString fileName = QFileDialog::getOpenFileName(this, - tr("Open File"), "", tr("Comma-separated values files (*.csv);;" - "Tab-delimited values files (*.txt);;" - "Waveform Audio File Format (*.wav);;" - "Matlab files (*.mat)"), - nullptr, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); + QString fileName = QFileDialog::getOpenFileName( + this, tr("Open File"), "", + tr("Comma-separated values files (*.csv);;" + "Tab-delimited values files (*.txt);;" + "Waveform Audio File Format (*.wav);;" + "Matlab files (*.mat)"), + nullptr, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); if(fileName.isEmpty()) { // user hit cancel return; } - loadFileFromPath(fileName); - updateRightMenuForChn(currentChannel); - resetZoom(); + loadFileFromPath(fileName); + updateRightMenuForChn(currentChannel); + resetZoom(); } void SignalGenerator::start() @@ -1440,15 +1309,15 @@ void SignalGenerator::start() m_running = true; /* Avoid from being started twice */ - if (buffers.size() > 0) { + if(buffers.size() > 0) { return; } - ResourceManager::open("m2k-dac",this); + ResourceManager::open("m2k-dac", this); m_m2k_analogout->cancelBuffer(); - for (auto it = channels.begin(); it != channels.end(); ++it) { - if (!(*it)->enableButton()->isChecked()) { + for(auto it = channels.begin(); it != channels.end(); ++it) { + if(!(*it)->enableButton()->isChecked()) { m_m2k_analogout->enableChannel((*it)->id(), false); continue; } @@ -1456,7 +1325,7 @@ void SignalGenerator::start() m_m2k_analogout->enableChannel((*it)->id(), true); auto chn_data = getData(*it); - if (chn_data->file_type==FORMAT_NO_FILE && chn_data->type==SIGNAL_TYPE_BUFFER) { + if(chn_data->file_type == FORMAT_NO_FILE && chn_data->type == SIGNAL_TYPE_BUFFER) { continue; } } @@ -1464,9 +1333,9 @@ void SignalGenerator::start() unsigned long final_rate; unsigned long oversampling; - for (size_t i = 0; i < m_m2k_analogout->getNbChannels(); i++) { + for(size_t i = 0; i < m_m2k_analogout->getNbChannels(); i++) { buffers.push_back({}); - if (!m_m2k_analogout->isChannelEnabled(i)) { + if(!m_m2k_analogout->isChannelEnabled(i)) { continue; } @@ -1474,15 +1343,14 @@ void SignalGenerator::start() double best_rate = get_best_sample_rate(i); /* Do not generate anything if samplerate can't be determined */ - if (best_rate <= 0) { + if(best_rate <= 0) { continue; } size_t samples_count = get_samples_count(i, best_rate); - calc_sampling_params(i, best_rate, final_rate, - oversampling); + calc_sampling_params(i, best_rate, final_rate, oversampling); - QWidget* w = channels[i]; + QWidget *w = channels[i]; auto source = getSource(w, best_rate, top_block); auto head = blocks::head::make(sizeof(float), samples_count); auto vector = blocks::vector_sink_f::make(); @@ -1494,33 +1362,27 @@ void SignalGenerator::start() auto clamp = analog::rail_ff::make(-AMPLITUDE_VOLTS, AMPLITUDE_VOLTS); top_block->connect(source, 0, load_scaling, 0); - top_block->connect(load_scaling, 0,clamp,0); - top_block->connect(clamp,0, head,0); + top_block->connect(load_scaling, 0, clamp, 0); + top_block->connect(clamp, 0, head, 0); top_block->connect(head, 0, vector, 0); top_block->run(); - const std::vector& f_samples = vector->data(); + const std::vector &f_samples = vector->data(); std::vector samples(f_samples.begin(), f_samples.end()); buffers.at(i) = samples; m_m2k_analogout->setOversamplingRatio(i, oversampling); m_m2k_analogout->setSampleRate(i, final_rate); - } - qDebug(CAT_M2K_SIGNAL_GENERATOR) << "Pushed cyclic buffer"; m_m2k_analogout->setCyclic(true); m_m2k_analogout->push(buffers); } - -void SignalGenerator::run() -{ - start(); -} +void SignalGenerator::run() { start(); } void SignalGenerator::stop() { @@ -1529,7 +1391,7 @@ void SignalGenerator::stop() buffers.clear(); m_running = false; m_m2k_analogout->stop(); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug(CAT_M2K_SIGNAL_GENERATOR) << e.what(); } @@ -1538,7 +1400,7 @@ void SignalGenerator::stop() void SignalGenerator::startStop(bool pressed) { - if (pressed) { + if(pressed) { start(); } else { stop(); @@ -1547,68 +1409,66 @@ void SignalGenerator::startStop(bool pressed) setDynamicProperty(ui->run_button, "running", pressed); } -void SignalGenerator::setFunction(const QString& function) +void SignalGenerator::setFunction(const QString &function) { auto ptr = getCurrentData(); - if (ptr->function != function) { + if(ptr->function != function) { ptr->function = function; resetZoom(); } } -//std::vector stairdata; +// std::vector stairdata; -basic_block_sptr SignalGenerator::getSignalSource(gr::top_block_sptr top, - double samp_rate, struct signal_generator_data& data, - double phase_correction) +basic_block_sptr SignalGenerator::getSignalSource(gr::top_block_sptr top, double samp_rate, + struct signal_generator_data &data, double phase_correction) { double phase; double amplitude; - double rise=0.5,fall=0.5; - double holdh=0.0,holdl=0.0; + double rise = 0.5, fall = 0.5; + double holdh = 0.0, holdl = 0.0; float offset; - int rising_steps=1; - int falling_steps=1; - int stairphase=0; + int rising_steps = 1; + int falling_steps = 1; + int stairphase = 0; amplitude = data.amplitude / 2.0; offset = data.offset; phase = data.phase + phase_correction; - if (data.waveform == SG_TRI_WAVE) { + if(data.waveform == SG_TRI_WAVE) { phase = std::fmod(phase + 90.0, 360.0); - } else if (data.waveform == SG_SQR_WAVE) { + } else if(data.waveform == SG_SQR_WAVE) { phase = std::fmod(phase + 180.0, 360.0); - } else if (phase<0) { - phase=phase+360.0; + } else if(phase < 0) { + phase = phase + 360.0; } - switch(data.waveform) - { + switch(data.waveform) { case SG_SQR_WAVE: - rise=fall=0; - holdh=(data.dutycycle/100.0); - holdl=1.0-(data.dutycycle/100.0); + rise = fall = 0; + holdh = (data.dutycycle / 100.0); + holdl = 1.0 - (data.dutycycle / 100.0); break; case SG_TRI_WAVE: - rise=fall=1; - holdh=0; - holdl=0; + rise = fall = 1; + holdh = 0; + holdl = 0; break; case SG_SAW_WAVE: - fall=holdh=holdl=0; - rise=1; + fall = holdh = holdl = 0; + rise = 1; break; case SG_INV_SAW_WAVE: - rise=holdh=holdl=0; - fall=1; + rise = holdh = holdl = 0; + fall = 1; break; case SG_TRA_WAVE: - rise=data.rise; - fall=data.fall; - holdl=data.holdl; - holdh=data.holdh; + rise = data.rise; + fall = data.fall; + holdl = data.holdl; + holdh = data.holdh; break; case SG_STAIR_WAVE: rising_steps = data.steps_up; @@ -1620,22 +1480,18 @@ basic_block_sptr SignalGenerator::getSignalSource(gr::top_block_sptr top, } basic_block_sptr src = nullptr; - if(data.waveform==SG_SIN_WAVE) - src = analog::sig_source_f::make(samp_rate, analog::GR_SIN_WAVE, - data.frequency, amplitude, offset, phase*0.01745329); - else if(data.waveform==SG_STAIR_WAVE) { - data.stairdata = get_stairstep(rising_steps, falling_steps, - amplitude, offset, stairphase); + if(data.waveform == SG_SIN_WAVE) + src = analog::sig_source_f::make(samp_rate, analog::GR_SIN_WAVE, data.frequency, amplitude, offset, + phase * 0.01745329); + else if(data.waveform == SG_STAIR_WAVE) { + data.stairdata = get_stairstep(rising_steps, falling_steps, amplitude, offset, stairphase); src = blocks::vector_source_f::make(data.stairdata, true); - } - else - src = gr::scopy::trapezoidal::make(samp_rate, data.frequency, amplitude, - rise, holdh, fall, holdl, offset, - phase*0.01745329); + } else + src = gr::scopy::trapezoidal::make(samp_rate, data.frequency, amplitude, rise, holdh, fall, holdl, + offset, phase * 0.01745329); return src; - } void SignalGenerator::loadFileCurrentChannelData() @@ -1643,15 +1499,14 @@ void SignalGenerator::loadFileCurrentChannelData() reloadFileFromPath(); updateRightMenuForChn(currentChannel); resetZoom(); - } void SignalGenerator::loadFileChannelData(int chIdx) { auto ptr = getData(channels[chIdx]); - if (ptr->type!=SIGNAL_TYPE_BUFFER) { - qDebug(CAT_M2K_SIGNAL_GENERATOR)<<"loadFileChannelData called without having SIGNAL_TYPE_BUFFER"; + if(ptr->type != SIGNAL_TYPE_BUFFER) { + qDebug(CAT_M2K_SIGNAL_GENERATOR) << "loadFileChannelData called without having SIGNAL_TYPE_BUFFER"; return; } @@ -1661,35 +1516,34 @@ void SignalGenerator::loadFileChannelData(int chIdx) try { fileManager->open(ptr->file, FileManager::IMPORT); - if (ptr->file_type==FORMAT_CSV) { + if(ptr->file_type == FORMAT_CSV) { - if (ptr->file_channel >= ptr->file_nr_of_channels) { + if(ptr->file_channel >= ptr->file_nr_of_channels) { return; } auto fileChannels = fileManager->read(ptr->file_channel); - for (auto x : qAsConst(fileChannels)) { + for(auto x : qAsConst(fileChannels)) { ptr->file_data.push_back(x); } } #ifdef MATLAB_SUPPORT_SIGGEN - if (ptr->file_type==FORMAT_MAT) { + if(ptr->file_type == FORMAT_MAT) { mat_t *matfp; matvar_t *matvar; - matfp = Mat_Open(ptr->file.toStdString().c_str(),MAT_ACC_RDONLY); + matfp = Mat_Open(ptr->file.toStdString().c_str(), MAT_ACC_RDONLY); - if (NULL == matfp) { - qDebug(CAT_M2K_SIGNAL_GENERATOR)<<"Error opening MAT file "<file; + if(NULL == matfp) { + qDebug(CAT_M2K_SIGNAL_GENERATOR) << "Error opening MAT file " << ptr->file; return; } - matvar=Mat_VarRead(matfp, - ptr->file_channel_names[ptr->file_channel].toStdString().c_str()); - const double *xData = static_cast(matvar->data) ; + matvar = Mat_VarRead(matfp, ptr->file_channel_names[ptr->file_channel].toStdString().c_str()); + const double *xData = static_cast(matvar->data); - for (auto i=0; ifile_nr_of_samples[ptr->file_channel]; ++i) { + for(auto i = 0; i < ptr->file_nr_of_samples[ptr->file_channel]; ++i) { ptr->file_data.push_back(xData[i]); } @@ -1699,232 +1553,213 @@ void SignalGenerator::loadFileChannelData(int chIdx) #endif } catch(FileManagerException &e) { - ptr->file_message=QString::fromLocal8Bit(e.what()); + ptr->file_message = QString::fromLocal8Bit(e.what()); ptr->file_nr_of_samples.push_back(0); - ptr->file_type=FORMAT_NO_FILE; + ptr->file_type = FORMAT_NO_FILE; } } gr::basic_block_sptr SignalGenerator::getNoise(QWidget *obj, gr::top_block_sptr top) { auto ptr = getData(obj); - auto noiseaAmpl = ptr->noiseAmplitude/2; - if((int)ptr->noiseType != 0) - { - long noiseSeed=(rand()); - double noiseDivider=1; - switch(ptr->noiseType) - { + auto noiseaAmpl = ptr->noiseAmplitude / 2; + if((int)ptr->noiseType != 0) { + long noiseSeed = (rand()); + double noiseDivider = 1; + switch(ptr->noiseType) { case analog::GR_IMPULSE: - noiseaAmpl=ptr -> noiseAmplitude; - noiseDivider=15; + noiseaAmpl = ptr->noiseAmplitude; + noiseDivider = 15; break; case analog::GR_GAUSSIAN: - noiseDivider=7; + noiseDivider = 7; break; case analog::GR_UNIFORM: - noiseDivider=2; + noiseDivider = 2; break; case analog::GR_LAPLACIAN: - noiseDivider=14; + noiseDivider = 14; break; default: - noiseDivider=1; + noiseDivider = 1; break; } - auto noise = analog::noise_source_f::make((analog::noise_type_t)ptr->noiseType,ptr->noiseAmplitude/noiseDivider,noiseSeed); + auto noise = analog::noise_source_f::make((analog::noise_type_t)ptr->noiseType, + ptr->noiseAmplitude / noiseDivider, noiseSeed); auto rail = analog::rail_ff::make(-noiseaAmpl, noiseaAmpl); - top->connect(noise,0,rail,0); + top->connect(noise, 0, rail, 0); return rail; - } - else - { + } else { return blocks::null_source::make(sizeof(float)); } } -gr::basic_block_sptr SignalGenerator::displayResampler(double samp_rate, - double freq, - gr::top_block_sptr top, +gr::basic_block_sptr SignalGenerator::displayResampler(double samp_rate, double freq, gr::top_block_sptr top, gr::basic_block_sptr generated_wave, - gr::basic_block_sptr noiseSrc, - gr::basic_block_sptr noiseAdd - ) -{ - auto ratio = samp_rate/freq; - long m,n; - bool ok=false; - for(auto precision = 128;precision > 8 ;precision>>=1) - { - reduceFraction(ratio,&m,&n,precision); - if(m!=0 && n!=0) - { - ok=true; + gr::basic_block_sptr noiseSrc, gr::basic_block_sptr noiseAdd) +{ + auto ratio = samp_rate / freq; + long m, n; + bool ok = false; + for(auto precision = 128; precision > 8; precision >>= 1) { + reduceFraction(ratio, &m, &n, precision); + if(m != 0 && n != 0) { + ok = true; break; } } ok = true; - if(!ok) - { + if(!ok) { return blocks::nop::make(sizeof(float)); } + auto interp = blocks::repeat::make(sizeof(float), m); + auto decim = blocks::keep_one_in_n::make(sizeof(float), n); - auto interp= blocks::repeat::make(sizeof(float),m); - auto decim=blocks::keep_one_in_n::make(sizeof(float),n); - - top->connect(noiseSrc,0,noiseAdd,0); - top->connect(generated_wave,0,noiseAdd,1); - top->connect(noiseAdd,0,interp,0); - top->connect(interp,0,decim,0); + top->connect(noiseSrc, 0, noiseAdd, 0); + top->connect(generated_wave, 0, noiseAdd, 1); + top->connect(noiseAdd, 0, interp, 0); + top->connect(interp, 0, decim, 0); return decim; } -gr::basic_block_sptr SignalGenerator::getSource(QWidget *obj, - double samp_rate, gr::top_block_sptr top, bool preview) +gr::basic_block_sptr SignalGenerator::getSource(QWidget *obj, double samp_rate, gr::top_block_sptr top, bool preview) { auto ptr = getData(obj); enum SIGNAL_TYPE type = ptr->type; - double phase=0.0; + double phase = 0.0; auto noiseSrc = getNoise(obj, top); auto noiseAdd = blocks::add_ff::make(); gr::basic_block_sptr generated_wave; - switch (type) { + switch(type) { case SIGNAL_TYPE_CONSTANT: - generated_wave = analog::sig_source_f::make(samp_rate, - analog::GR_CONST_WAVE, 0, 0, - ptr->constant); + generated_wave = analog::sig_source_f::make(samp_rate, analog::GR_CONST_WAVE, 0, 0, ptr->constant); break; case SIGNAL_TYPE_WAVEFORM: - if (preview) { - int full_periods=(int)((double)zoomT1OnScreen*ptr->frequency); - double phase_in_time = zoomT1OnScreen - full_periods/ptr->frequency; - phase = (phase_in_time*ptr->frequency) * 360.0; + if(preview) { + int full_periods = (int)((double)zoomT1OnScreen * ptr->frequency); + double phase_in_time = zoomT1OnScreen - full_periods / ptr->frequency; + phase = (phase_in_time * ptr->frequency) * 360.0; generated_wave = getSignalSource(top, samp_rate, *ptr, phase); - if(ptr->waveform!=SG_STAIR_WAVE) + if(ptr->waveform != SG_STAIR_WAVE) break; // Only for STAIR wave - return displayResampler(sample_rate, (ptr->frequency * (ptr->steps_up + ptr->steps_down)), - top, generated_wave, noiseSrc, noiseAdd); + return displayResampler(sample_rate, (ptr->frequency * (ptr->steps_up + ptr->steps_down)), top, + generated_wave, noiseSrc, noiseAdd); - - } - else - { + } else { generated_wave = getSignalSource(top, samp_rate, *ptr, phase); } break; case SIGNAL_TYPE_BUFFER: - if (!ptr->file.isNull() && ptr->file_type != FORMAT_NO_FILE) { + if(!ptr->file.isNull() && ptr->file_type != FORMAT_NO_FILE) { auto str = ptr->file.toStdString(); - std::shared_ptr fs; + std::shared_ptr fs; auto null = blocks::null_sink::make(sizeof(float)); - auto buffer=blocks::head::make(sizeof(float),(4*1024*1024)); + auto buffer = blocks::head::make(sizeof(float), (4 * 1024 * 1024)); - switch (ptr->file_type) { + switch(ptr->file_type) { case FORMAT_BIN_FLOAT: fs = blocks::file_source::make(sizeof(float), str.c_str(), true); - top->connect(fs,0,buffer,0); + top->connect(fs, 0, buffer, 0); break; case FORMAT_WAVE: try { - fs = blocks::wavfile_source::make(str.c_str(),true); - } catch(std::runtime_error& e) - { - ptr->file_message=QString::fromLocal8Bit(e.what()); - fs=blocks::null_source::make(sizeof(float)); + fs = blocks::wavfile_source::make(str.c_str(), true); + } catch(std::runtime_error &e) { + ptr->file_message = QString::fromLocal8Bit(e.what()); + fs = blocks::null_source::make(sizeof(float)); } - for (size_t i=0; ifile_nr_of_channels; i++) { - if (i==ptr->file_channel) { - top->connect(fs,i,buffer,0); + for(size_t i = 0; i < ptr->file_nr_of_channels; i++) { + if(i == ptr->file_channel) { + top->connect(fs, i, buffer, 0); } else { - top->connect(fs,i,null,0); + top->connect(fs, i, null, 0); } } break; case FORMAT_CSV: case FORMAT_MAT: - fs = blocks::vector_source_f::make(ptr->file_data,true); - top->connect(fs,0,buffer,0); + fs = blocks::vector_source_f::make(ptr->file_data, true); + top->connect(fs, 0, buffer, 0); break; default: - fs=blocks::null_source::make(sizeof(float)); - noiseSrc=blocks::null_source::make(sizeof(float)); - top->connect(fs,0,buffer,0); + fs = blocks::null_source::make(sizeof(float)); + noiseSrc = blocks::null_source::make(sizeof(float)); + top->connect(fs, 0, buffer, 0); break; } auto mult = blocks::multiply_const_ff::make(ptr->file_amplitude); - top->connect(buffer,0,mult,0); + top->connect(buffer, 0, mult, 0); auto add = blocks::add_const_ff::make(ptr->file_offset); - top->connect(mult,0,add,0); - auto phase_skip = blocks::skiphead::make(sizeof(float),ptr->file_phase); - top->connect(add,0,phase_skip,0); + top->connect(mult, 0, add, 0); + auto phase_skip = blocks::skiphead::make(sizeof(float), ptr->file_phase); + top->connect(add, 0, phase_skip, 0); - if (preview) { - auto resamp = displayResampler(sample_rate, (ptr->file_sr), - top, phase_skip, noiseSrc, noiseAdd); + if(preview) { + auto resamp = displayResampler(sample_rate, (ptr->file_sr), top, phase_skip, noiseSrc, + noiseAdd); double buffer_freq = 1; - if (ptr->file_nr_of_samples.size() > 0) { - buffer_freq = ptr->file_sr/(double) - ptr->file_nr_of_samples[ptr->file_channel]; + if(ptr->file_nr_of_samples.size() > 0) { + buffer_freq = ptr->file_sr / (double)ptr->file_nr_of_samples[ptr->file_channel]; } - int full_periods=(int)((double)zoomT1OnScreen * buffer_freq); - double phase_in_time = zoomT1OnScreen - (full_periods/buffer_freq); + int full_periods = (int)((double)zoomT1OnScreen * buffer_freq); + double phase_in_time = zoomT1OnScreen - (full_periods / buffer_freq); unsigned long samples_to_skip = phase_in_time * samp_rate; - auto skip = blocks::skiphead::make(sizeof(float),samples_to_skip); - top->connect(resamp,0,skip,0); + auto skip = blocks::skiphead::make(sizeof(float), samples_to_skip); + top->connect(resamp, 0, skip, 0); // return before readding the noise. return skip; } else { generated_wave = phase_skip; } - } - else { + } else { generated_wave = blocks::nop::make(sizeof(float)); } break; case SIGNAL_TYPE_MATH: - if (!ptr->function.isEmpty()) { + if(!ptr->function.isEmpty()) { auto str = ptr->function.toStdString(); - double math_record_freq = (1.0/ptr->math_record_length); + double math_record_freq = (1.0 / ptr->math_record_length); - if (preview) { + if(preview) { - int full_periods=(int)((double)zoomT1OnScreen * math_record_freq); - double phase_in_time = zoomT1OnScreen - full_periods/math_record_freq; - phase = (phase_in_time*math_record_freq) * 360.0; + int full_periods = (int)((double)zoomT1OnScreen * math_record_freq); + double phase_in_time = zoomT1OnScreen - full_periods / math_record_freq; + phase = (phase_in_time * math_record_freq) * 360.0; uint64_t to_skip = samp_rate * phase / (math_record_freq * 360.0); - auto skip_head = blocks::skiphead::make(sizeof(float),(uint64_t)to_skip); + auto skip_head = blocks::skiphead::make(sizeof(float), (uint64_t)to_skip); - if(ptr->math_sr < samp_rate) - { - auto src = gr::scopy::iio_math_gen::make(ptr->math_sr, str, (uint64_t)ptr->math_sr * ptr->math_record_length); - auto resamp = displayResampler(samp_rate, ptr->math_sr, top, src, noiseSrc, noiseAdd); + if(ptr->math_sr < samp_rate) { + auto src = gr::scopy::iio_math_gen::make( + ptr->math_sr, str, (uint64_t)ptr->math_sr * ptr->math_record_length); + auto resamp = + displayResampler(samp_rate, ptr->math_sr, top, src, noiseSrc, noiseAdd); top->connect(resamp, 0, skip_head, 0); return skip_head; - } - else - { - auto src = gr::scopy::iio_math_gen::make(samp_rate, str, (uint64_t)samp_rate * ptr->math_record_length); + } else { + auto src = gr::scopy::iio_math_gen::make( + samp_rate, str, (uint64_t)samp_rate * ptr->math_record_length); top->connect(src, 0, skip_head, 0); generated_wave = skip_head; } } else { - generated_wave = gr::scopy::iio_math_gen::make(samp_rate, str, (uint64_t)samp_rate * ptr->math_record_length); + generated_wave = gr::scopy::iio_math_gen::make( + samp_rate, str, (uint64_t)samp_rate * ptr->math_record_length); } break; } @@ -1934,8 +1769,8 @@ gr::basic_block_sptr SignalGenerator::getSource(QWidget *obj, break; } - top->connect(noiseSrc,0,noiseAdd,0); - top->connect(generated_wave,0,noiseAdd,1); + top->connect(noiseSrc, 0, noiseAdd, 0); + top->connect(generated_wave, 0, noiseAdd, 1); return noiseAdd; } @@ -1946,7 +1781,7 @@ void SignalGenerator::channelWidgetEnabled(bool en) m_m2k_analogout->enableChannel(id, en); - if (en) { + if(en) { m_plot->AttachCurve(id); } else { m_plot->DetachCurve(id); @@ -1957,17 +1792,15 @@ void SignalGenerator::channelWidgetEnabled(bool en) bool enable_run = en; - if (!en) { - for (auto it = channels.begin(); - !enable_run && it != channels.end(); ++it) { + if(!en) { + for(auto it = channels.begin(); !enable_run && it != channels.end(); ++it) { enable_run = (*it)->enableButton()->isChecked(); } } - ui->run_button->setEnabled(enable_run); tme->setEnabled(enable_run); -// setDynamicProperty(run_button, "disabled", !enable_run); + // setDynamicProperty(run_button, "disabled", !enable_run); } void SignalGenerator::triggerRightMenuToggle(int chIdx, bool checked) @@ -1975,9 +1808,8 @@ void SignalGenerator::triggerRightMenuToggle(int chIdx, bool checked) // Queue the action, if right menu animation is in progress. This way // the action will be remembered and performed right after the animation // finishes - if (ui->rightMenu->animInProgress()) { - menuButtonActions.enqueue( - QPair(chIdx, checked)); + if(ui->rightMenu->animInProgress()) { + menuButtonActions.enqueue(QPair(chIdx, checked)); } else { phaseIndexChanged(); currentChannel = chIdx; @@ -1994,7 +1826,7 @@ void SignalGenerator::channelWidgetMenuToggled(bool checked) int SignalGenerator::sg_waveform_to_idx(enum sg_waveform wave) { - switch (wave) { + switch(wave) { case SG_SIN_WAVE: default: return 0; @@ -2028,7 +1860,7 @@ void SignalGenerator::updateRightMenuForChn(int chIdx) phase->blockSignals(true); phase->setComboboxIndex(ptr->indexValue); phase->blockSignals(false); - if (ptr->indexValue < 2) { + if(ptr->indexValue < 2) { phase->setInSeconds(false); phase->setValue(ptr->phase); } else { @@ -2044,15 +1876,15 @@ void SignalGenerator::updateRightMenuForChn(int chIdx) ui->fileChannel->blockSignals(true); ui->fileChannel->clear(); - if (ptr->file_channel_names.isEmpty()) { - for (size_t i=0; ifile_nr_of_channels; i++) { + if(ptr->file_channel_names.isEmpty()) { + for(size_t i = 0; i < ptr->file_nr_of_channels; i++) { ui->fileChannel->addItem(QString::number(i)); } } else { ui->fileChannel->addItems(ptr->file_channel_names); } - ui->fileChannel->setEnabled(ptr->file_nr_of_channels>1); + ui->fileChannel->setEnabled(ptr->file_nr_of_channels > 1); ui->fileChannel->setCurrentIndex(ptr->file_channel); ui->fileChannel->blockSignals(false); @@ -2079,8 +1911,7 @@ void SignalGenerator::updateRightMenuForChn(int chIdx) ui->label_path->setText(ptr->file); ui->label_format->setText(ptr->file_message); if(!ptr->file_nr_of_samples.empty()) { - ui->label_size->setText(QString::number(ptr->file_nr_of_samples[ptr->file_channel]) + - tr(" samples")); + ui->label_size->setText(QString::number(ptr->file_nr_of_samples[ptr->file_channel]) + tr(" samples")); } else { ui->label_size->setText(""); } @@ -2094,16 +1925,16 @@ void SignalGenerator::updateRightMenuForChn(int chIdx) ui->type->setCurrentIndex(sg_waveform_to_idx(ptr->waveform)); waveformUpdateUi(ptr->waveform); - ui->tabWidget->setCurrentIndex((int) ptr->type); + ui->tabWidget->setCurrentIndex((int)ptr->type); resizeTabWidget((int)ptr->type); ui->tabWidget->setStyleSheet(QString("QTabBar::tab:selected { border-bottom: 2px solid %1; }") - .arg(m_plot->getLineColor(chIdx).name())); + .arg(m_plot->getLineColor(chIdx).name())); } void SignalGenerator::updateAndToggleMenu(int chIdx, bool open) { - if (open) { + if(open) { updateRightMenuForChn(chIdx); } @@ -2117,7 +1948,7 @@ void SignalGenerator::rightMenuFinished(bool opened) // At the end of each animation, check if there are other button check // actions that might have happened while animating and execute all // these queued actions - while (menuButtonActions.size()) { + while(menuButtonActions.size()) { auto pair = menuButtonActions.dequeue(); int chIdx = pair.first; bool open = pair.second; @@ -2129,18 +1960,18 @@ void SignalGenerator::rightMenuFinished(bool opened) bool SignalGenerator::use_oversampling(unsigned int chnIdx) { - if (!m_m2k_analogout->isChannelEnabled(chnIdx)) { + if(!m_m2k_analogout->isChannelEnabled(chnIdx)) { return false; } QWidget *w = channels.at(chnIdx); auto ptr = getData(w); - switch (ptr->type) { + switch(ptr->type) { case SIGNAL_TYPE_WAVEFORM: /* We only want oversampling for square waveforms */ - if (ptr->waveform == SG_SQR_WAVE || ptr->waveform == SG_STAIR_WAVE) { + if(ptr->waveform == SG_SQR_WAVE || ptr->waveform == SG_STAIR_WAVE) { return true; } @@ -2158,7 +1989,6 @@ bool SignalGenerator::use_oversampling(unsigned int chnIdx) return false; } - double SignalGenerator::get_best_sample_rate(unsigned int chnIdx) { std::vector values = m_m2k_analogout->getAvailableSampleRates(chnIdx); @@ -2168,19 +1998,19 @@ double SignalGenerator::get_best_sample_rate(unsigned int chnIdx) /* When using oversampling, we actually want to generate the * signal with the lowest sample rate possible. */ - if (sample_rate_forced(chnIdx)) { + if(sample_rate_forced(chnIdx)) { return get_forced_sample_rate(chnIdx); } - if (use_oversampling(chnIdx)) { + if(use_oversampling(chnIdx)) { std::sort(values.begin(), values.end(), std::less()); } /* Return the best sample rate that we can create a buffer for */ - for (unsigned long rate : values) { + for(unsigned long rate : values) { size_t buf_size = get_samples_count(chnIdx, rate, true); - if (buf_size) { + if(buf_size) { return rate; } @@ -2188,15 +2018,14 @@ double SignalGenerator::get_best_sample_rate(unsigned int chnIdx) } /* If we can't find a perfect sample rate, use the highest one */ - if (use_oversampling(chnIdx)) { + if(use_oversampling(chnIdx)) { std::sort(values.begin(), values.end(), std::greater()); } - - for (unsigned long rate : values) { + for(unsigned long rate : values) { size_t buf_size = get_samples_count(chnIdx, rate); - if (buf_size) { + if(buf_size) { return rate; } @@ -2208,56 +2037,55 @@ double SignalGenerator::get_best_sample_rate(unsigned int chnIdx) bool SignalGenerator::sample_rate_forced(unsigned int chnIdx) { - if (!m_m2k_analogout->isChannelEnabled(chnIdx)) { + if(!m_m2k_analogout->isChannelEnabled(chnIdx)) { return false; } QWidget *w = channels.at(chnIdx); auto ptr = getData(w); - if (ptr->file_type && ptr->file_sr && ptr->type==SIGNAL_TYPE_BUFFER) { + if(ptr->file_type && ptr->file_sr && ptr->type == SIGNAL_TYPE_BUFFER) { return true; } - if (ptr->type == SIGNAL_TYPE_WAVEFORM && ptr->waveform == SG_STAIR_WAVE) + if(ptr->type == SIGNAL_TYPE_WAVEFORM && ptr->waveform == SG_STAIR_WAVE) return true; - if(ptr->type==SIGNAL_TYPE_MATH) + if(ptr->type == SIGNAL_TYPE_MATH) return true; return false; } double SignalGenerator::get_forced_sample_rate(unsigned int chnIdx) { - if (sample_rate_forced(chnIdx)) { + if(sample_rate_forced(chnIdx)) { QWidget *w = channels.at(chnIdx); auto ptr = getData(w); - if (ptr->file_type && ptr->file_sr && ptr->type==SIGNAL_TYPE_BUFFER) { + if(ptr->file_type && ptr->file_sr && ptr->type == SIGNAL_TYPE_BUFFER) { return ptr->file_sr; } - if (ptr->type == SIGNAL_TYPE_WAVEFORM && ptr->waveform == SG_STAIR_WAVE) + if(ptr->type == SIGNAL_TYPE_WAVEFORM && ptr->waveform == SG_STAIR_WAVE) return (ptr->frequency * (ptr->steps_up + ptr->steps_down)); - if(ptr->type==SIGNAL_TYPE_MATH) { + if(ptr->type == SIGNAL_TYPE_MATH) { return ptr->math_sr; } } return false; } -void SignalGenerator::calc_sampling_params(unsigned int chnIdx, - double rate, unsigned long& out_sample_rate, - unsigned long& out_oversampling_ratio) +void SignalGenerator::calc_sampling_params(unsigned int chnIdx, double rate, unsigned long &out_sample_rate, + unsigned long &out_oversampling_ratio) { - if (use_oversampling(chnIdx)) { + if(use_oversampling(chnIdx)) { /* We assume that the rate requested here will always be a * divider of the max sample rate */ out_oversampling_ratio = max_sample_rate / rate; out_sample_rate = max_sample_rate; - qDebug(CAT_M2K_SIGNAL_GENERATOR) << QString("Using oversampling with a ratio of %1") - .arg(out_oversampling_ratio); + qDebug(CAT_M2K_SIGNAL_GENERATOR) + << QString("Using oversampling with a ratio of %1").arg(out_oversampling_ratio); } else { out_sample_rate = rate; out_oversampling_ratio = 1; @@ -2266,24 +2094,24 @@ void SignalGenerator::calc_sampling_params(unsigned int chnIdx, void SignalGenerator::reduceFraction(double input, long *numerator, long *denominator, long precision) { - double integral = std::floor(input); - double frac = input - integral; - long gcd_ = gcd(round(frac * precision), precision); + double integral = std::floor(input); + double frac = input - integral; + long gcd_ = gcd(round(frac * precision), precision); - *denominator = precision / gcd_; - *numerator = (round(frac * precision) / gcd_) + ((long)integral*(*denominator)); + *denominator = precision / gcd_; + *numerator = (round(frac * precision) / gcd_) + ((long)integral * (*denominator)); } size_t SignalGenerator::gcd(size_t a, size_t b) { - for (;;) { - if (!a) { + for(;;) { + if(!a) { return b; } b %= a; - if (!b) { + if(!b) { return a; } @@ -2304,85 +2132,77 @@ double SignalGenerator::get_best_ratio(double ratio, double max, double *fract) double best_ratio = ratio; double best_fract = 1.0; - for (double i = 1.0; i < max_it; i += 1.0) { + for(double i = 1.0; i < max_it; i += 1.0) { double integral, new_ratio = i * ratio; double new_fract = modf(new_ratio, &integral); - if (new_fract < best_fract) { + if(new_fract < best_fract) { best_fract = new_fract; best_ratio = new_ratio; } - if (new_fract == 0.0) { + if(new_fract == 0.0) { break; } } - if (fract) { + if(fract) { *fract = best_fract; } return best_ratio; } -QPushButton *SignalGenerator::getRunButton() -{ - return ui->run_button->getRunButton(); -} +QPushButton *SignalGenerator::getRunButton() { return ui->run_button->getRunButton(); } -std::vector SignalGenerator::get_stairstep(int rise, int fall, - float amplitude, float offset, int phase) +std::vector SignalGenerator::get_stairstep(int rise, int fall, float amplitude, float offset, int phase) { - std::vector aux,buff,rising_buff,falling_buff,phased,final_buff; + std::vector aux, buff, rising_buff, falling_buff, phased, final_buff; rising_buff.clear(); falling_buff.clear(); aux.clear(); buff.clear(); phased.clear(); - for(float i=-amplitude;i<=amplitude;i+=amplitude/(float)rise*2.0){ + for(float i = -amplitude; i <= amplitude; i += amplitude / (float)rise * 2.0) { rising_buff.push_back(i); } - for(float i=amplitude;i>=-amplitude;i-=amplitude/(float)fall*2.0){ + for(float i = amplitude; i >= -amplitude; i -= amplitude / (float)fall * 2.0) { falling_buff.push_back(i); } - for(int i =0;i<(rise+fall);i++){ - if(i ptr; + QSharedPointer ptr; - if (!m_m2k_analogout->isChannelEnabled(chnIdx)) { + if(!m_m2k_analogout->isChannelEnabled(chnIdx)) { goto out_cleanup; } @@ -2390,55 +2210,51 @@ size_t SignalGenerator::get_samples_count(unsigned int chnIdx, ptr = getData(w); double ratio, fract; - switch (ptr->type) { + switch(ptr->type) { case SIGNAL_TYPE_WAVEFORM: - if(ptr->waveform == SG_STAIR_WAVE) - { - return (ptr->steps_up+ptr->steps_down)*MULTIPLY_CT; + if(ptr->waveform == SG_STAIR_WAVE) { + return (ptr->steps_up + ptr->steps_down) * MULTIPLY_CT; } - ratio = (double) rate / ptr->frequency; + ratio = (double)rate / ptr->frequency; // for less than max sample rates, generate at least 10 samples per period - if (ratio < 10.0 && rate < max_sample_rate) + if(ratio < 10.0 && rate < max_sample_rate) return 0; - if (ratio < 2.0) { - return 0; /* rate too low */ + if(ratio < 2.0) { + return 0; /* rate too low */ } /* The ratio must be even for square waveforms */ - if (perfect && (ptr->type == SIGNAL_TYPE_WAVEFORM) - && (ptr->waveform == SG_SQR_WAVE) - && (fmod(ratio, 2.0) != 0.0)) { + if(perfect && (ptr->type == SIGNAL_TYPE_WAVEFORM) && (ptr->waveform == SG_SQR_WAVE) && + (fmod(ratio, 2.0) != 0.0)) { return 0; } + ratio = get_best_ratio(ratio, (double)(max_buffer_size / 4), &fract); - ratio = get_best_ratio(ratio, - (double)(max_buffer_size / 4), &fract); - - if (perfect && fract != 0.0) { + if(perfect && fract != 0.0) { return 0; } - size = lcm(size, (size_t) ratio); + size = lcm(size, (size_t)ratio); break; case SIGNAL_TYPE_MATH: size = (size_t)ptr->math_sr * ptr->math_record_length; break; case SIGNAL_TYPE_BUFFER: - if (!ptr->file_type) { + if(!ptr->file_type) { return 0; } - if (perfect && rate!=ptr->file_sr) { + if(perfect && rate != ptr->file_sr) { return 0; } - ratio = rate/ptr->file_sr; - if (ptr->file_nr_of_samples.size() > 0) { - size=(ptr->file_nr_of_samples[ptr->file_channel] * ratio); + ratio = rate / ptr->file_sr; + if(ptr->file_nr_of_samples.size() > 0) { + size = (ptr->file_nr_of_samples[ptr->file_channel] * ratio); } break; @@ -2449,26 +2265,22 @@ size_t SignalGenerator::get_samples_count(unsigned int chnIdx, out_cleanup: /* The buffer size must be a multiple of 4 */ - if(ptr->type == SIGNAL_TYPE_BUFFER) - { + if(ptr->type == SIGNAL_TYPE_BUFFER) { size = size + size % 0x04; - } - else - { - while (size & 0x3) { + } else { + while(size & 0x3) { size <<= 1; } } /* The buffer size shouldn't be too small */ - while (size < min_buffer_size) { + while(size < min_buffer_size) { size <<= 1; } - if (size > max_buffer_size) { + if(size > max_buffer_size) { return 0; } return size; } - diff --git a/plugins/m2k/src/old/signal_generator.hpp b/plugins/m2k/src/old/signal_generator.hpp index c3d8ec8268..73585c47ba 100644 --- a/plugins/m2k/src/old/signal_generator.hpp +++ b/plugins/m2k/src/old/signal_generator.hpp @@ -21,35 +21,33 @@ #ifndef M2K_SIGNAL_GENERATOR_H #define M2K_SIGNAL_GENERATOR_H -#include +#include "filemanager.h" +#include "filter.hpp" +#include "gnuradio/analog/noise_type.h" +#include "m2ktool.hpp" +#include "oscilloscope_plot.hpp" +#include "pluginbase/apiobject.h" +#include "scope_sink_f.h" + #include +#include #include #include #include -#include -#include -#include #include #include - -#include "pluginbase/apiobject.h" -#include "filter.hpp" -#include "oscilloscope_plot.hpp" -#include "scope_sink_f.h" -#include "m2ktool.hpp" -#include "filemanager.h" - -#include "gnuradio/analog/noise_type.h" +#include +#include /* libm2k includes */ -#include -#include - #include "externalloadlineedit.h" +#include +#include -extern "C" { +extern "C" +{ struct iio_context; } @@ -65,14 +63,15 @@ class PhaseSpinButton; class PositionSpinButton; class ScaleSpinButton; -} +} // namespace scopy namespace scopy::m2k { struct signal_generator_data; struct time_block_data; class SignalGenerator_API; -enum sg_noise { +enum sg_noise +{ SG_NO_NOISE = 0, SG_UNIFORM_NOISE = 1, SG_GAUSSIAN_NOISE = 2, @@ -80,18 +79,20 @@ enum sg_noise { SG_IMPULSE_NOISE = 4, }; -enum sg_waveform { +enum sg_waveform +{ SG_SIN_WAVE = gr::analog::GR_SIN_WAVE, SG_SQR_WAVE = gr::analog::GR_SQR_WAVE, SG_TRI_WAVE = gr::analog::GR_TRI_WAVE, SG_TRA_WAVE = 109, SG_SAW_WAVE = gr::analog::GR_SAW_WAVE, SG_INV_SAW_WAVE = 108, - SG_STAIR_WAVE =110, + SG_STAIR_WAVE = 110, }; -enum sg_file_format { +enum sg_file_format +{ FORMAT_NO_FILE, FORMAT_BIN_FLOAT, FORMAT_CSV, @@ -99,20 +100,24 @@ enum sg_file_format { FORMAT_MAT }; -typedef union { - struct { - uint16_t format; // Audio format 1=PCM,6=mulaw,7=alaw, 257=IBM Mu-Law, 258=IBM A-Law, 259=ADPCM - uint16_t noChan; // Number of channels 1=Mono 2=Sterio - uint32_t SamplesPerSec; // Sampling Frequency in Hz - uint32_t bytesPerSec; // bytes per second - uint16_t blockAlign; // 2=16-bit mono, 4=16-bit stereo - uint16_t bitsPerSample; // Number of bits per sample +typedef union +{ + struct + { + uint16_t format; // Audio format 1=PCM,6=mulaw,7=alaw, 257=IBM Mu-Law, 258=IBM A-Law, 259=ADPCM + uint16_t noChan; // Number of channels 1=Mono 2=Sterio + uint32_t SamplesPerSec; // Sampling Frequency in Hz + uint32_t bytesPerSec; // bytes per second + uint16_t blockAlign; // 2=16-bit mono, 4=16-bit stereo + uint16_t bitsPerSample; // Number of bits per sample }; char header_data[16]; } wav_header_t; -typedef union { - struct { +typedef union +{ + struct + { uint8_t riff[4]; uint32_t size; uint8_t id[4]; @@ -120,9 +125,11 @@ typedef union { char data[12]; } riff_header_t; -typedef union { - struct { - uint8_t id[4]; +typedef union +{ + struct + { + uint8_t id[4]; uint32_t size; }; char data[8]; @@ -136,9 +143,8 @@ class SignalGenerator : public M2kTool Q_OBJECT public: - explicit SignalGenerator(struct iio_context *ctx, - Filter *filt, ToolMenuEntry *tme, - QJSEngine *engine, QWidget *parent); + explicit SignalGenerator(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, QJSEngine *engine, + QWidget *parent); ~SignalGenerator(); static const size_t min_buffer_size = 1024; @@ -146,13 +152,13 @@ class SignalGenerator : public M2kTool static constexpr float max_frequency = 30000000; static double get_best_ratio(double ratio, double max, double *fract); - QPushButton* getRunButton(); + QPushButton *getRunButton(); void settingsLoaded(); private: const size_t m_maxNbOfSamples; - libm2k::context::M2k* m_m2k_context; - libm2k::analog::M2kAnalogOut* m_m2k_analogout; + libm2k::context::M2k *m_m2k_context; + libm2k::analog::M2kAnalogOut *m_m2k_analogout; Ui::SignalGenerator *ui; CapturePlot *m_plot; @@ -160,7 +166,7 @@ class SignalGenerator : public M2kTool struct time_block_data *time_block_data; PhaseSpinButton *phase; - PositionSpinButton *filePhase, *stairPhase; + PositionSpinButton *filePhase, *stairPhase; PositionSpinButton *offset, *fileOffset; PositionSpinButton *constantValue, *dutycycle; ScaleSpinButton *amplitude, *frequency; @@ -189,7 +195,7 @@ class SignalGenerator : public M2kTool QSharedPointer getData(QWidget *obj); QSharedPointer getCurrentData(); - void start(); + void start(); void resetZoom(); void updatePreview(); @@ -199,33 +205,25 @@ class SignalGenerator : public M2kTool void loadFileFromPath(QString filename); void reloadFileFromPath(); - gr::basic_block_sptr getSignalSource( - gr::top_block_sptr top, - double sample_rate, - struct signal_generator_data& data, double phase_correction=0.0); - - gr::basic_block_sptr getNoise(QWidget *obj,gr::top_block_sptr top); - gr::basic_block_sptr getSource(QWidget *obj, - double sample_rate, - gr::top_block_sptr top, bool phase_correction=false); - gr::basic_block_sptr displayResampler(double samp_rate, - double freq, - gr::top_block_sptr top, - gr::basic_block_sptr generated_wave, - gr::basic_block_sptr noiseSrc, + gr::basic_block_sptr getSignalSource(gr::top_block_sptr top, double sample_rate, + struct signal_generator_data &data, double phase_correction = 0.0); + + gr::basic_block_sptr getNoise(QWidget *obj, gr::top_block_sptr top); + gr::basic_block_sptr getSource(QWidget *obj, double sample_rate, gr::top_block_sptr top, + bool phase_correction = false); + gr::basic_block_sptr displayResampler(double samp_rate, double freq, gr::top_block_sptr top, + gr::basic_block_sptr generated_wave, gr::basic_block_sptr noiseSrc, gr::basic_block_sptr noiseAdd); - static void reduceFraction(double input,long *numerator, long *denominator, long precision=1000000); + static void reduceFraction(double input, long *numerator, long *denominator, long precision = 1000000); static size_t gcd(size_t a, size_t b); static size_t lcm(size_t a, size_t b); static int sg_waveform_to_idx(enum sg_waveform wave); size_t get_samples_count(unsigned int chnIdx, double sample_rate, bool perfect = false); double get_best_sample_rate(unsigned int chnIdx); - void calc_sampling_params(unsigned int chnIdx, - double sample_rate, - unsigned long& out_sample_rate, - unsigned long& out_oversampling_ratio); + void calc_sampling_params(unsigned int chnIdx, double sample_rate, unsigned long &out_sample_rate, + unsigned long &out_oversampling_ratio); bool use_oversampling(unsigned int chnIdx); bool sample_rate_forced(unsigned int chnIdx); @@ -237,14 +235,13 @@ class SignalGenerator : public M2kTool double zoomT1OnScreen; double zoomT2OnScreen; - std::vectorget_stairstep(int rise, int fall, float amplitude, float offset, int phase); + std::vector get_stairstep(int rise, int fall, float amplitude, float offset, int phase); enum sg_file_format getFileFormat(QString filePath); - bool loadParametersFromFile(QSharedPointer ptr, - QString filePath); + bool loadParametersFromFile(QSharedPointer ptr, QString filePath); void loadFileChannelData(int chIdx); - bool riffCompare(riff_header_t& ptr, const char *id2); - bool chunkCompare(chunk_header_t& ptr, const char *id2); + bool riffCompare(riff_header_t &ptr, const char *id2); + bool chunkCompare(chunk_header_t &ptr, const char *id2); public Q_SLOTS: void run() override; @@ -277,7 +274,6 @@ private Q_SLOTS: void stepsDownChanged(double value); void stairPhaseChanged(double value); - void mathRecordLengthChanged(double val); void mathSampleRateChanged(double value); @@ -292,20 +288,22 @@ private Q_SLOTS: void rescale(); void startStop(bool start); - void setFunction(const QString& function); + void setFunction(const QString &function); void readPreferences(); Q_SIGNALS: void showTool(); }; -enum SIGNAL_TYPE { - SIGNAL_TYPE_CONSTANT = 0, - SIGNAL_TYPE_WAVEFORM = 1, - SIGNAL_TYPE_BUFFER = 2, - SIGNAL_TYPE_MATH = 3, +enum SIGNAL_TYPE +{ + SIGNAL_TYPE_CONSTANT = 0, + SIGNAL_TYPE_WAVEFORM = 1, + SIGNAL_TYPE_BUFFER = 2, + SIGNAL_TYPE_MATH = 3, }; -struct signal_generator_data { +struct signal_generator_data +{ enum SIGNAL_TYPE type; unsigned int id; bool enabled; @@ -343,7 +341,7 @@ struct signal_generator_data { QStringList file_channel_names; enum sg_file_format file_type; wav_header_t file_wav_hdr; - //bool file_loaded; + // bool file_loaded; // SIGNAL_TYPE_MATH QString function; double math_record_length; @@ -355,11 +353,12 @@ struct signal_generator_data { double load; }; -struct time_block_data { +struct time_block_data +{ scope_sink_f::sptr time_block; unsigned long nb_channels; }; -} +} // namespace scopy::m2k Q_DECLARE_METATYPE(gr::analog::noise_type_t) #endif /* M2K_SIGNAL_GENERATOR_H */ diff --git a/plugins/m2k/src/old/signal_generator_api.cpp b/plugins/m2k/src/old/signal_generator_api.cpp index 3eaa1d47c1..d1a10c7ba9 100644 --- a/plugins/m2k/src/old/signal_generator_api.cpp +++ b/plugins/m2k/src/old/signal_generator_api.cpp @@ -18,31 +18,24 @@ * along with this program. If not, see . */ #include "signal_generator_api.hpp" -#include "ui_signal_generator.h" + #include "gui/channel_widget.hpp" #include "gui/spinbox_a.hpp" +#include "ui_signal_generator.h" + namespace scopy::m2k { -void SignalGenerator_API::show() -{ - Q_EMIT gen->showTool(); -} +void SignalGenerator_API::show() { Q_EMIT gen->showTool(); } -bool SignalGenerator_API::running() const -{ - return gen->ui->run_button->runButtonChecked(); -} +bool SignalGenerator_API::running() const { return gen->ui->run_button->runButtonChecked(); } -void SignalGenerator_API::run(bool en) -{ - gen->ui->run_button->toggle(en); -} +void SignalGenerator_API::run(bool en) { gen->ui->run_button->toggle(en); } QList SignalGenerator_API::getMode() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(static_cast(ptr->type)); @@ -51,13 +44,13 @@ QList SignalGenerator_API::getMode() const return list; } -void SignalGenerator_API::setMode(const QList& list) +void SignalGenerator_API::setMode(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->type = static_cast(list.at(i)); @@ -66,35 +59,33 @@ void SignalGenerator_API::setMode(const QList& list) gen->ui->tabWidget->setCurrentIndex(gen->getCurrentData()->type); } - QList SignalGenerator_API::enabledChannels() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { list.append(static_cast(gen->channels[i]->enableButton()->isChecked())); } return list; } -void SignalGenerator_API::enableChannels(const QList& list) +void SignalGenerator_API::enableChannels(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { gen->channels[i]->enableButton()->setChecked(list.at(i)); } } - QList SignalGenerator_API::getConstantValue() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(static_cast(ptr->constant)); @@ -103,13 +94,13 @@ QList SignalGenerator_API::getConstantValue() const return list; } -void SignalGenerator_API::setConstantValue(const QList& list) +void SignalGenerator_API::setConstantValue(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->constant = static_cast(list.at(i)); @@ -122,7 +113,7 @@ QList SignalGenerator_API::getWaveformType() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(SignalGenerator::sg_waveform_to_idx(ptr->waveform)); } @@ -130,30 +121,24 @@ QList SignalGenerator_API::getWaveformType() const return list; } -void SignalGenerator_API::setWaveformType(const QList& list) +void SignalGenerator_API::setWaveformType(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } enum sg_waveform types[] = { - SG_SIN_WAVE, - SG_SQR_WAVE, - SG_TRI_WAVE, - SG_TRA_WAVE, - SG_SAW_WAVE, - SG_INV_SAW_WAVE, - SG_STAIR_WAVE, + SG_SIN_WAVE, SG_SQR_WAVE, SG_TRI_WAVE, SG_TRA_WAVE, SG_SAW_WAVE, SG_INV_SAW_WAVE, SG_STAIR_WAVE, }; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->waveform = types[list.at(i)]; - if (i == gen->currentChannel) { + if(i == gen->currentChannel) { gen->ui->type->setCurrentIndex(list.at(i)); gen->updateRightMenuForChn(i); - gen->resetZoom(); + gen->resetZoom(); } } } @@ -162,7 +147,7 @@ QList SignalGenerator_API::getWaveformAmpl() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(ptr->amplitude); @@ -171,13 +156,13 @@ QList SignalGenerator_API::getWaveformAmpl() const return list; } -void SignalGenerator_API::setWaveformAmpl(const QList& list) +void SignalGenerator_API::setWaveformAmpl(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->amplitude = list.at(i); @@ -190,7 +175,7 @@ QList SignalGenerator_API::getWaveformFreq() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(ptr->frequency); @@ -199,13 +184,13 @@ QList SignalGenerator_API::getWaveformFreq() const return list; } -void SignalGenerator_API::setWaveformFreq(const QList& list) +void SignalGenerator_API::setWaveformFreq(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->frequency = list.at(i); @@ -218,7 +203,7 @@ QList SignalGenerator_API::getWaveformOfft() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(static_cast(ptr->offset)); @@ -227,13 +212,13 @@ QList SignalGenerator_API::getWaveformOfft() const return list; } -void SignalGenerator_API::setWaveformOfft(const QList& list) +void SignalGenerator_API::setWaveformOfft(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->offset = static_cast(list.at(i)); @@ -246,7 +231,7 @@ QList SignalGenerator_API::getStairWaveformStepsUp() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(static_cast(ptr->steps_up)); @@ -255,13 +240,13 @@ QList SignalGenerator_API::getStairWaveformStepsUp() const return list; } -void SignalGenerator_API::setStairWaveformStepsUp(const QList& list) +void SignalGenerator_API::setStairWaveformStepsUp(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->steps_up = static_cast(list.at(i)); @@ -274,7 +259,7 @@ QList SignalGenerator_API::getStairWaveformStepsDown() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(static_cast(ptr->steps_down)); @@ -283,13 +268,13 @@ QList SignalGenerator_API::getStairWaveformStepsDown() const return list; } -void SignalGenerator_API::setStairWaveformStepsDown(const QList& list) +void SignalGenerator_API::setStairWaveformStepsDown(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->steps_down = static_cast(list.at(i)); @@ -301,7 +286,7 @@ QList SignalGenerator_API::getStairWaveformPhase() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(static_cast(ptr->stairphase)); @@ -310,13 +295,13 @@ QList SignalGenerator_API::getStairWaveformPhase() const return list; } -void SignalGenerator_API::setStairWaveformPhase(const QList& list) +void SignalGenerator_API::setStairWaveformPhase(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->stairphase = static_cast(list.at(i)); @@ -329,7 +314,7 @@ QList SignalGenerator_API::getWaveformPhase() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(ptr->phase); @@ -338,13 +323,13 @@ QList SignalGenerator_API::getWaveformPhase() const return list; } -void SignalGenerator_API::setWaveformPhase(const QList& list) +void SignalGenerator_API::setWaveformPhase(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->phase = list.at(i); @@ -353,12 +338,11 @@ void SignalGenerator_API::setWaveformPhase(const QList& list) gen->phase->setValue(gen->getCurrentData()->phase); } - QList SignalGenerator_API::getWaveformDuty() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(ptr->dutycycle); @@ -367,13 +351,13 @@ QList SignalGenerator_API::getWaveformDuty() const return list; } -void SignalGenerator_API::setWaveformDuty(const QList& list) +void SignalGenerator_API::setWaveformDuty(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->dutycycle = list.at(i); @@ -386,7 +370,7 @@ QList SignalGenerator_API::getNoiseType() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(ptr->noiseType); } @@ -394,29 +378,28 @@ QList SignalGenerator_API::getNoiseType() const return list; } -void SignalGenerator_API::setNoiseType(const QList& list) +void SignalGenerator_API::setNoiseType(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->noiseType = qvariant_cast(list.at(i)); - if (i == gen->currentChannel) { + if(i == gen->currentChannel) { gen->updateRightMenuForChn(i); } } } - QList SignalGenerator_API::getNoiseAmpl() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(ptr->noiseAmplitude); @@ -425,13 +408,13 @@ QList SignalGenerator_API::getNoiseAmpl() const return list; } -void SignalGenerator_API::setNoiseAmpl(const QList& list) +void SignalGenerator_API::setNoiseAmpl(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->noiseAmplitude = list.at(i); } @@ -440,12 +423,11 @@ void SignalGenerator_API::setNoiseAmpl(const QList& list) gen->resetZoom(); } - QList SignalGenerator_API::getWaveformRise() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(ptr->rise); @@ -454,13 +436,13 @@ QList SignalGenerator_API::getWaveformRise() const return list; } -void SignalGenerator_API::setWaveformRise(const QList& list) +void SignalGenerator_API::setWaveformRise(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->rise = list.at(i); @@ -469,12 +451,11 @@ void SignalGenerator_API::setWaveformRise(const QList& list) gen->riseTime->setValue(gen->getCurrentData()->rise); } - QList SignalGenerator_API::getWaveformFall() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(ptr->fall); @@ -483,13 +464,13 @@ QList SignalGenerator_API::getWaveformFall() const return list; } -void SignalGenerator_API::setWaveformFall(const QList& list) +void SignalGenerator_API::setWaveformFall(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->fall = list.at(i); @@ -498,12 +479,11 @@ void SignalGenerator_API::setWaveformFall(const QList& list) gen->fallTime->setValue(gen->getCurrentData()->fall); } - QList SignalGenerator_API::getWaveformHoldHigh() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(ptr->holdh); @@ -512,13 +492,13 @@ QList SignalGenerator_API::getWaveformHoldHigh() const return list; } -void SignalGenerator_API::setWaveformHoldHigh(const QList& list) +void SignalGenerator_API::setWaveformHoldHigh(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->holdh = list.at(i); @@ -527,12 +507,11 @@ void SignalGenerator_API::setWaveformHoldHigh(const QList& list) gen->holdHighTime->setValue(gen->getCurrentData()->holdh); } - QList SignalGenerator_API::getWaveformHoldLow() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(ptr->holdl); @@ -541,13 +520,13 @@ QList SignalGenerator_API::getWaveformHoldLow() const return list; } -void SignalGenerator_API::setWaveformHoldLow(const QList& list) +void SignalGenerator_API::setWaveformHoldLow(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->holdl = list.at(i); @@ -556,13 +535,11 @@ void SignalGenerator_API::setWaveformHoldLow(const QList& list) gen->holdLowTime->setValue(gen->getCurrentData()->holdl); } - - QList SignalGenerator_API::getMathRecordLength() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(ptr->math_record_length); @@ -571,13 +548,13 @@ QList SignalGenerator_API::getMathRecordLength() const return list; } -void SignalGenerator_API::setMathRecordLength(const QList& list) +void SignalGenerator_API::setMathRecordLength(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->math_record_length = list.at(i); @@ -586,13 +563,11 @@ void SignalGenerator_API::setMathRecordLength(const QList& list) gen->mathRecordLength->setValue(gen->getCurrentData()->math_record_length); } - - QList SignalGenerator_API::getMathSampleRate() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(ptr->math_sr); @@ -601,13 +576,13 @@ QList SignalGenerator_API::getMathSampleRate() const return list; } -void SignalGenerator_API::setMathSampleRate(const QList& list) +void SignalGenerator_API::setMathSampleRate(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->math_sr = list.at(i); @@ -616,12 +591,11 @@ void SignalGenerator_API::setMathSampleRate(const QList& list) gen->mathSampleRate->setValue(gen->getCurrentData()->math_sr); } - QList SignalGenerator_API::getMathFunction() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); list.append(ptr->function); @@ -630,259 +604,247 @@ QList SignalGenerator_API::getMathFunction() const return list; } -void SignalGenerator_API::setMathFunction(const QList& list) +void SignalGenerator_API::setMathFunction(const QList &list) { - if (list.size() != gen->channels.size()) { + if(list.size() != gen->channels.size()) { return; } - for (int i = 0; i < gen->channels.size(); i++) { + for(int i = 0; i < gen->channels.size(); i++) { auto ptr = gen->getData(gen->channels[i]); ptr->function = list.at(i); } - if (gen->getCurrentData()->type == SIGNAL_TYPE_MATH) { - gen->ui->mathWidget->setFunction( - gen->getCurrentData()->function); - gen->resetZoom(); + if(gen->getCurrentData()->type == SIGNAL_TYPE_MATH) { + gen->ui->mathWidget->setFunction(gen->getCurrentData()->function); + gen->resetZoom(); } - } -QList SignalGenerator_API::getBufferFilePath() const{ - QList list; - - for (int i = 0; i < gen->channels.size(); i++) { - auto ptr = gen->getData(gen->channels[i]); +QList SignalGenerator_API::getBufferFilePath() const +{ + QList list; - if(ptr->file!="" && ptr->file_type!=FORMAT_NO_FILE){ - list.append(ptr->file); - } - else{ - list.append(""); - } + for(int i = 0; i < gen->channels.size(); i++) { + auto ptr = gen->getData(gen->channels[i]); - } + if(ptr->file != "" && ptr->file_type != FORMAT_NO_FILE) { + list.append(ptr->file); + } else { + list.append(""); + } + } - return list; + return list; } -void SignalGenerator_API::setBufferFilePath(const QList& list){ - if (list.size() != gen->channels.size()) { - return; - } +void SignalGenerator_API::setBufferFilePath(const QList &list) +{ + if(list.size() != gen->channels.size()) { + return; + } - auto currentChannel = gen->currentChannel; - for (int i = 0; i < gen->channels.size(); i++) { - if(list.at(i) != ""){ - gen->currentChannel = i; - gen->loadFileFromPath(list.at(i)); - } - } - gen->currentChannel = currentChannel; - gen->updateRightMenuForChn(gen->currentChannel); + auto currentChannel = gen->currentChannel; + for(int i = 0; i < gen->channels.size(); i++) { + if(list.at(i) != "") { + gen->currentChannel = i; + gen->loadFileFromPath(list.at(i)); + } + } + gen->currentChannel = currentChannel; + gen->updateRightMenuForChn(gen->currentChannel); } -QList SignalGenerator_API::getBufferAmplitude() const{ - QList list; +QList SignalGenerator_API::getBufferAmplitude() const +{ + QList list; - for (int i = 0; i < gen->channels.size(); i++) { - auto ptr = gen->getData(gen->channels[i]); + for(int i = 0; i < gen->channels.size(); i++) { + auto ptr = gen->getData(gen->channels[i]); - list.append(ptr->file_amplitude); - } + list.append(ptr->file_amplitude); + } - return list; + return list; } -void SignalGenerator_API::setBufferAmplitude(const QList& list){ - if (list.size() != gen->channels.size()) { - return; - } +void SignalGenerator_API::setBufferAmplitude(const QList &list) +{ + if(list.size() != gen->channels.size()) { + return; + } - for (int i = 0; i < gen->channels.size(); i++) { - auto ptr = gen->getData(gen->channels[i]); + for(int i = 0; i < gen->channels.size(); i++) { + auto ptr = gen->getData(gen->channels[i]); - ptr->file_amplitude = list.at(i); - if(i == gen->currentChannel){ - gen->resetZoom(); - } - } + ptr->file_amplitude = list.at(i); + if(i == gen->currentChannel) { + gen->resetZoom(); + } + } - gen->fileAmplitude->setValue(gen->getCurrentData()->file_amplitude); + gen->fileAmplitude->setValue(gen->getCurrentData()->file_amplitude); } -QList SignalGenerator_API::getBufferOffset() const{ - QList list; +QList SignalGenerator_API::getBufferOffset() const +{ + QList list; - for (int i = 0; i < gen->channels.size(); i++) { - auto ptr = gen->getData(gen->channels[i]); + for(int i = 0; i < gen->channels.size(); i++) { + auto ptr = gen->getData(gen->channels[i]); - list.append(ptr->file_offset); - } + list.append(ptr->file_offset); + } - return list; + return list; } -void SignalGenerator_API::setBufferOffset(const QList& list){ - if (list.size() != gen->channels.size()) { - return; - } +void SignalGenerator_API::setBufferOffset(const QList &list) +{ + if(list.size() != gen->channels.size()) { + return; + } - for (int i = 0; i < gen->channels.size(); i++) { - auto ptr = gen->getData(gen->channels[i]); + for(int i = 0; i < gen->channels.size(); i++) { + auto ptr = gen->getData(gen->channels[i]); - ptr->file_offset = list.at(i); - if(i == gen->currentChannel){ - gen->resetZoom(); - } - } - gen->fileOffset->setValue(gen->getCurrentData()->file_offset); + ptr->file_offset = list.at(i); + if(i == gen->currentChannel) { + gen->resetZoom(); + } + } + gen->fileOffset->setValue(gen->getCurrentData()->file_offset); } -QList SignalGenerator_API::getBufferSampleRate() const{ - QList list; +QList SignalGenerator_API::getBufferSampleRate() const +{ + QList list; - for (int i = 0; i < gen->channels.size(); i++) { - auto ptr = gen->getData(gen->channels[i]); + for(int i = 0; i < gen->channels.size(); i++) { + auto ptr = gen->getData(gen->channels[i]); - list.append(ptr->file_sr); - } + list.append(ptr->file_sr); + } - return list; + return list; } -void SignalGenerator_API::setBufferSampleRate(const QList& list){ - if (list.size() != gen->channels.size()) { - return; - } +void SignalGenerator_API::setBufferSampleRate(const QList &list) +{ + if(list.size() != gen->channels.size()) { + return; + } - for (int i = 0; i < gen->channels.size(); i++) { - auto ptr = gen->getData(gen->channels[i]); + for(int i = 0; i < gen->channels.size(); i++) { + auto ptr = gen->getData(gen->channels[i]); - ptr->file_sr = list.at(i); - if(i == gen->currentChannel){ - gen->resetZoom(); + ptr->file_sr = list.at(i); + if(i == gen->currentChannel) { + gen->resetZoom(); + } } - } - gen->fileSampleRate->setValue(gen->getCurrentData()->file_sr); + gen->fileSampleRate->setValue(gen->getCurrentData()->file_sr); } -QList SignalGenerator_API::getBufferPhase() const{ - QList list; +QList SignalGenerator_API::getBufferPhase() const +{ + QList list; - for (int i = 0; i < gen->channels.size(); i++) { - auto ptr = gen->getData(gen->channels[i]); + for(int i = 0; i < gen->channels.size(); i++) { + auto ptr = gen->getData(gen->channels[i]); - list.append(ptr->file_phase); - } + list.append(ptr->file_phase); + } - return list; + return list; } -void SignalGenerator_API::setBufferPhase(const QList& list){ - if (list.size() != gen->channels.size()) { - return; - } - - for (int i = 0; i < gen->channels.size(); i++) { - auto ptr = gen->getData(gen->channels[i]); - - ptr->file_phase = list.at(i); - if(i == gen->currentChannel){ - gen->resetZoom(); - } - } - gen->filePhase->setValue(gen->getCurrentData()->file_phase); -} +void SignalGenerator_API::setBufferPhase(const QList &list) +{ + if(list.size() != gen->channels.size()) { + return; + } + for(int i = 0; i < gen->channels.size(); i++) { + auto ptr = gen->getData(gen->channels[i]); -QString SignalGenerator_API::getNotes() -{ - return gen->ui->instrumentNotes->getNotes(); -} -void SignalGenerator_API::setNotes(QString str) -{ - gen->ui->instrumentNotes->setNotes(str); + ptr->file_phase = list.at(i); + if(i == gen->currentChannel) { + gen->resetZoom(); + } + } + gen->filePhase->setValue(gen->getCurrentData()->file_phase); } +QString SignalGenerator_API::getNotes() { return gen->ui->instrumentNotes->getNotes(); } +void SignalGenerator_API::setNotes(QString str) { gen->ui->instrumentNotes->setNotes(str); } QList SignalGenerator_API::getLineThickness() const { - QList list; + QList list; - for (int i = 0; i < gen->channels.size(); i++) { - auto ptr = gen->getData(gen->channels[i]); - int lineThicknessIndex = (int)(ptr->lineThickness / 0.5) - 1; - list.append(lineThicknessIndex); - } + for(int i = 0; i < gen->channels.size(); i++) { + auto ptr = gen->getData(gen->channels[i]); + int lineThicknessIndex = (int)(ptr->lineThickness / 0.5) - 1; + list.append(lineThicknessIndex); + } - return list; + return list; } -void SignalGenerator_API::setLineThickness(const QList& list) +void SignalGenerator_API::setLineThickness(const QList &list) { - if (list.size() != gen->channels.size()) { - return; - } + if(list.size() != gen->channels.size()) { + return; + } - for (int i = 0; i < gen->channels.size(); i++) { - auto ptr = gen->getData(gen->channels[i]); + for(int i = 0; i < gen->channels.size(); i++) { + auto ptr = gen->getData(gen->channels[i]); - ptr->lineThickness = 0.5 * (list.at(i) + 1); + ptr->lineThickness = 0.5 * (list.at(i) + 1); - if(i == gen->currentChannel){ - gen->updateRightMenuForChn(i); - gen->m_plot->setLineWidth(i, ptr->lineThickness); - gen->m_plot->replot(); - } - } - int index = (int)(gen->getCurrentData()->lineThickness / 0.5) - 1; + if(i == gen->currentChannel) { + gen->updateRightMenuForChn(i); + gen->m_plot->setLineWidth(i, ptr->lineThickness); + gen->m_plot->replot(); + } + } + int index = (int)(gen->getCurrentData()->lineThickness / 0.5) - 1; gen->ui->cbLineThickness->setCurrentIndex(index); } - - QList SignalGenerator_API::getLoad() const { QList list; - for (int i = 0; i < gen->channels.size(); i++) { - auto ptr = gen->getData(gen->channels[i]); + for(int i = 0; i < gen->channels.size(); i++) { + auto ptr = gen->getData(gen->channels[i]); - list.append(ptr->load); + list.append(ptr->load); } return list; } -void SignalGenerator_API::setLoad(const QList& list) +void SignalGenerator_API::setLoad(const QList &list) { - if (list.size() != gen->channels.size()) { - return; + if(list.size() != gen->channels.size()) { + return; } - for (int i = 0; i < gen->channels.size(); i++) { - auto ptr = gen->getData(gen->channels[i]); + for(int i = 0; i < gen->channels.size(); i++) { + auto ptr = gen->getData(gen->channels[i]); - ptr->load = list.at(i); - if(i == gen->currentChannel){ - gen->resetZoom(); - gen->load->setValue(gen->getCurrentData()->load); - } + ptr->load = list.at(i); + if(i == gen->currentChannel) { + gen->resetZoom(); + gen->load->setValue(gen->getCurrentData()->load); + } } - } +bool SignalGenerator_API::getAutoscale() const { return gen->ui->btnSigGenAutoscale->isChecked(); } -bool SignalGenerator_API::getAutoscale() const -{ - return gen->ui->btnSigGenAutoscale->isChecked(); -} +void SignalGenerator_API::setAutoscale(bool checked) { gen->ui->btnSigGenAutoscale->setChecked(checked); } -void SignalGenerator_API::setAutoscale(bool checked) -{ - gen->ui->btnSigGenAutoscale->setChecked(checked); -} - -} +} // namespace scopy::m2k diff --git a/plugins/m2k/src/old/signal_generator_api.hpp b/plugins/m2k/src/old/signal_generator_api.hpp index 3999f48bf2..3f16cb10d4 100644 --- a/plugins/m2k/src/old/signal_generator_api.hpp +++ b/plugins/m2k/src/old/signal_generator_api.hpp @@ -20,8 +20,8 @@ #ifndef SIGNAL_GENERATOR_API_HPP #define SIGNAL_GENERATOR_API_HPP -#include "signal_generator.hpp" #include "pluginbase/apiobject.h" +#include "signal_generator.hpp" namespace scopy::m2k { using namespace scopy; @@ -34,165 +34,135 @@ class SignalGenerator_API : public scopy::ApiObject Q_PROPERTY(bool running READ running WRITE run STORED false); Q_PROPERTY(QList mode READ getMode WRITE setMode); - Q_PROPERTY(QList enabled - READ enabledChannels WRITE enableChannels) - Q_PROPERTY(QList constant_volts - READ getConstantValue WRITE setConstantValue); - Q_PROPERTY(QList waveform_type - READ getWaveformType WRITE setWaveformType); - Q_PROPERTY(QList waveform_amplitude - READ getWaveformAmpl WRITE setWaveformAmpl); - Q_PROPERTY(QList waveform_frequency - READ getWaveformFreq WRITE setWaveformFreq); - Q_PROPERTY(QList waveform_offset - READ getWaveformOfft WRITE setWaveformOfft); - Q_PROPERTY(QList waveform_phase - READ getWaveformPhase WRITE setWaveformPhase); - Q_PROPERTY(QList math_record_length - READ getMathRecordLength WRITE setMathRecordLength); - Q_PROPERTY(QList math_sample_rate - READ getMathSampleRate WRITE setMathSampleRate); - Q_PROPERTY(QList math_function - READ getMathFunction WRITE setMathFunction); - Q_PROPERTY(QList waveform_duty - READ getWaveformDuty WRITE setWaveformDuty); - - Q_PROPERTY(QList steps_up - READ getStairWaveformStepsUp WRITE setStairWaveformStepsUp); - Q_PROPERTY(QList steps_down - READ getStairWaveformStepsDown WRITE setStairWaveformStepsDown); - Q_PROPERTY(QList stairphase - READ getStairWaveformPhase WRITE setStairWaveformPhase); - - - - Q_PROPERTY(QList noise_type - READ getNoiseType WRITE setNoiseType); - Q_PROPERTY(QList noise_amplitude - READ getNoiseAmpl WRITE setNoiseAmpl); - Q_PROPERTY(QList waveform_rise - READ getWaveformRise WRITE setWaveformRise); - Q_PROPERTY(QList waveform_fall - READ getWaveformFall WRITE setWaveformFall); - Q_PROPERTY(QList waveform_holdhigh - READ getWaveformHoldHigh WRITE setWaveformHoldHigh); - Q_PROPERTY(QList waveform_holdlow - READ getWaveformHoldLow WRITE setWaveformHoldLow); - - Q_PROPERTY(QList buffer_file_path - READ getBufferFilePath WRITE setBufferFilePath) - Q_PROPERTY(QList buffer_amplitude - READ getBufferAmplitude WRITE setBufferAmplitude) - Q_PROPERTY(QList buffer_offset - READ getBufferOffset WRITE setBufferOffset) - Q_PROPERTY(QList buffer_sample_rate - READ getBufferSampleRate WRITE setBufferSampleRate) - Q_PROPERTY(QList buffer_phase - READ getBufferPhase WRITE setBufferPhase) + Q_PROPERTY(QList enabled READ enabledChannels WRITE enableChannels) + Q_PROPERTY(QList constant_volts READ getConstantValue WRITE setConstantValue); + Q_PROPERTY(QList waveform_type READ getWaveformType WRITE setWaveformType); + Q_PROPERTY(QList waveform_amplitude READ getWaveformAmpl WRITE setWaveformAmpl); + Q_PROPERTY(QList waveform_frequency READ getWaveformFreq WRITE setWaveformFreq); + Q_PROPERTY(QList waveform_offset READ getWaveformOfft WRITE setWaveformOfft); + Q_PROPERTY(QList waveform_phase READ getWaveformPhase WRITE setWaveformPhase); + Q_PROPERTY(QList math_record_length READ getMathRecordLength WRITE setMathRecordLength); + Q_PROPERTY(QList math_sample_rate READ getMathSampleRate WRITE setMathSampleRate); + Q_PROPERTY(QList math_function READ getMathFunction WRITE setMathFunction); + Q_PROPERTY(QList waveform_duty READ getWaveformDuty WRITE setWaveformDuty); + + Q_PROPERTY(QList steps_up READ getStairWaveformStepsUp WRITE setStairWaveformStepsUp); + Q_PROPERTY(QList steps_down READ getStairWaveformStepsDown WRITE setStairWaveformStepsDown); + Q_PROPERTY(QList stairphase READ getStairWaveformPhase WRITE setStairWaveformPhase); + + Q_PROPERTY(QList noise_type READ getNoiseType WRITE setNoiseType); + Q_PROPERTY(QList noise_amplitude READ getNoiseAmpl WRITE setNoiseAmpl); + Q_PROPERTY(QList waveform_rise READ getWaveformRise WRITE setWaveformRise); + Q_PROPERTY(QList waveform_fall READ getWaveformFall WRITE setWaveformFall); + Q_PROPERTY(QList waveform_holdhigh READ getWaveformHoldHigh WRITE setWaveformHoldHigh); + Q_PROPERTY(QList waveform_holdlow READ getWaveformHoldLow WRITE setWaveformHoldLow); + + Q_PROPERTY(QList buffer_file_path READ getBufferFilePath WRITE setBufferFilePath) + Q_PROPERTY(QList buffer_amplitude READ getBufferAmplitude WRITE setBufferAmplitude) + Q_PROPERTY(QList buffer_offset READ getBufferOffset WRITE setBufferOffset) + Q_PROPERTY(QList buffer_sample_rate READ getBufferSampleRate WRITE setBufferSampleRate) + Q_PROPERTY(QList buffer_phase READ getBufferPhase WRITE setBufferPhase) Q_PROPERTY(QString notes READ getNotes WRITE setNotes) - Q_PROPERTY(QList line_thickness - READ getLineThickness WRITE setLineThickness) + Q_PROPERTY(QList line_thickness READ getLineThickness WRITE setLineThickness) Q_PROPERTY(bool autoscale READ getAutoscale WRITE setAutoscale); Q_PROPERTY(QList load READ getLoad WRITE setLoad); - public: bool running() const; void run(bool en); QList getMode() const; - void setMode(const QList& list); + void setMode(const QList &list); QList enabledChannels() const; - void enableChannels(const QList& list); + void enableChannels(const QList &list); QList getConstantValue() const; - void setConstantValue(const QList& list); + void setConstantValue(const QList &list); QList getWaveformType() const; - void setWaveformType(const QList& list); + void setWaveformType(const QList &list); QList getWaveformAmpl() const; - void setWaveformAmpl(const QList& list); + void setWaveformAmpl(const QList &list); QList getWaveformFreq() const; - void setWaveformFreq(const QList& list); + void setWaveformFreq(const QList &list); QList getWaveformOfft() const; - void setWaveformOfft(const QList& list); + void setWaveformOfft(const QList &list); QList getWaveformPhase() const; - void setWaveformPhase(const QList& list); + void setWaveformPhase(const QList &list); QList getWaveformDuty() const; - void setWaveformDuty(const QList& list); + void setWaveformDuty(const QList &list); QList getNoiseType() const; - void setNoiseType(const QList& list); + void setNoiseType(const QList &list); QList getNoiseAmpl() const; - void setNoiseAmpl(const QList& list); + void setNoiseAmpl(const QList &list); QList getWaveformHoldLow() const; - void setWaveformHoldLow(const QList& list); + void setWaveformHoldLow(const QList &list); QList getWaveformHoldHigh() const; - void setWaveformHoldHigh(const QList& list); + void setWaveformHoldHigh(const QList &list); QList getWaveformFall() const; - void setWaveformFall(const QList& list); + void setWaveformFall(const QList &list); QList getWaveformRise() const; - void setWaveformRise(const QList& list); + void setWaveformRise(const QList &list); QList getStairWaveformStepsUp() const; - void setStairWaveformStepsUp(const QList& list); + void setStairWaveformStepsUp(const QList &list); QList getStairWaveformStepsDown() const; - void setStairWaveformStepsDown(const QList& list); + void setStairWaveformStepsDown(const QList &list); QList getStairWaveformPhase() const; - void setStairWaveformPhase(const QList& list); - + void setStairWaveformPhase(const QList &list); QList getMathRecordLength() const; - void setMathRecordLength(const QList& list); + void setMathRecordLength(const QList &list); QList getMathSampleRate() const; - void setMathSampleRate(const QList& list); + void setMathSampleRate(const QList &list); QList getMathFunction() const; - void setMathFunction(const QList& list); + void setMathFunction(const QList &list); QList getBufferFilePath() const; - void setBufferFilePath(const QList& list); + void setBufferFilePath(const QList &list); QList getBufferAmplitude() const; - void setBufferAmplitude(const QList& list); + void setBufferAmplitude(const QList &list); QList getBufferOffset() const; - void setBufferOffset(const QList& list); + void setBufferOffset(const QList &list); QList getBufferSampleRate() const; - void setBufferSampleRate(const QList& list); + void setBufferSampleRate(const QList &list); QList getBufferPhase() const; - void setBufferPhase(const QList& list); + void setBufferPhase(const QList &list); QString getNotes(); void setNotes(QString str); QList getLineThickness() const; - void setLineThickness(const QList& list); + void setLineThickness(const QList &list); QList getLoad() const; - void setLoad(const QList& list); + void setLoad(const QList &list); bool getAutoscale() const; void setAutoscale(bool checked); + Q_INVOKABLE void show(); - - Q_INVOKABLE void show(); - - explicit SignalGenerator_API(SignalGenerator *gen) : - ApiObject(), gen(gen) {} + explicit SignalGenerator_API(SignalGenerator *gen) + : ApiObject() + , gen(gen) + {} ~SignalGenerator_API() {} private: SignalGenerator *gen; }; -} +} // namespace scopy::m2k #endif // SIGNAL_GENERATOR_API_HPP diff --git a/plugins/m2k/src/old/signal_sample.cpp b/plugins/m2k/src/old/signal_sample.cpp index 230b89b442..22babbe2c8 100644 --- a/plugins/m2k/src/old/signal_sample.cpp +++ b/plugins/m2k/src/old/signal_sample.cpp @@ -22,28 +22,22 @@ using namespace scopy::m2k; -signal_sample::signal_sample() : - gr::sync_block("signal_sample", - gr::io_signature::make(1, -1, sizeof(float)), - gr::io_signature::make(0, 0, 0)), - QObject() +signal_sample::signal_sample() + : gr::sync_block("signal_sample", gr::io_signature::make(1, -1, sizeof(float)), gr::io_signature::make(0, 0, 0)) + , QObject() { qRegisterMetaType>(); set_max_noutput_items(1); } -signal_sample::~signal_sample() -{ -} +signal_sample::~signal_sample() {} -int signal_sample::work(int noutput_items, - gr_vector_const_void_star &input_items, - gr_vector_void_star &output_items) +int signal_sample::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { std::vector values; - for (unsigned int i = 0; i < input_items.size(); i++) { - const float *vect = (const float *) input_items[i]; + for(unsigned int i = 0; i < input_items.size(); i++) { + const float *vect = (const float *)input_items[i]; values.push_back(*vect); } diff --git a/plugins/m2k/src/old/signal_sample.hpp b/plugins/m2k/src/old/signal_sample.hpp index ceeb3076a6..da4840f2a6 100644 --- a/plugins/m2k/src/old/signal_sample.hpp +++ b/plugins/m2k/src/old/signal_sample.hpp @@ -21,30 +21,28 @@ #ifndef SIGNAL_SAMPLE_HPP #define SIGNAL_SAMPLE_HPP -#include +#include #include -#include +#include Q_DECLARE_METATYPE(std::vector); namespace scopy::m2k { - class signal_sample : public QObject, public gr::sync_block - { - Q_OBJECT - - public: - explicit signal_sample(); - ~signal_sample(); - - int work(int noutput_items, - gr_vector_const_void_star &input_items, - gr_vector_void_star &output_items); - - Q_SIGNALS: - void triggered(const std::vector &values); - }; -} +class signal_sample : public QObject, public gr::sync_block +{ + Q_OBJECT + +public: + explicit signal_sample(); + ~signal_sample(); + + int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); + +Q_SIGNALS: + void triggered(const std::vector &values); +}; +} // namespace scopy::m2k #endif diff --git a/plugins/m2k/src/old/spectrum_analyzer.cpp b/plugins/m2k/src/old/spectrum_analyzer.cpp index 465ef8f4e8..a57f257495 100644 --- a/plugins/m2k/src/old/spectrum_analyzer.cpp +++ b/plugins/m2k/src/old/spectrum_analyzer.cpp @@ -19,61 +19,64 @@ */ /* GNU Radio includes */ -#include -#include +#include +#include #include +#include +#include #include -#include -#include /* Qt includes */ -#include -#include #include +#include #include +#include #include -#include +#include +#include #include -#include #include #include /* Local includes */ #include "WaterfallDisplayPlot.h" -#include "spectrum_analyzer.hpp" -#include "filter.hpp" -#include "math.hpp" #include "fft_block.hpp" -#include "gui/dynamicWidget.h" +#include "filemanager.h" +#include "filter.hpp" #include "gui/channel_widget.hpp" #include "gui/db_click_buttons.hpp" -#include "filemanager.h" +#include "gui/dynamicWidget.h" +#include "math.hpp" +#include "spectrum_analyzer.hpp" #include "spectrum_analyzer_api.hpp" #include "stream_to_vector_overlap.h" #ifdef SPECTRAL_MSR #include "gui/measure.h" -#include "measurement_gui.h" #include "gui/measure_settings.h" +#include "measurement_gui.h" #endif /* Generated UI */ -#include "ui_spectrum_analyzer.h" #include "ui_cursors_settings.h" #include "ui_measure_panel.h" #include "ui_measure_settings.h" +#include "ui_spectrum_analyzer.h" #include + #include /* libm2k includes */ +#include "gui/utils.h" +#include "m2kpluginExceptionHandler.h" + +#include + #include #include -#include "m2kpluginExceptionHandler.h" #include -#include -#include "gui/utils.h" -Q_LOGGING_CATEGORY(CAT_M2K_SPECTRUM_ANALYZER,"M2kSpectrumAnalyzer"); +Q_LOGGING_CATEGORY(CAT_M2K_SPECTRUM_ANALYZER, "M2kSpectrumAnalyzer"); #define TIMER_TIMEOUT_MS 100 @@ -85,88 +88,83 @@ using namespace std; using namespace libm2k; using namespace libm2k::context; -void SpectrumAnalyzer::initInstrumentStrings() { +void SpectrumAnalyzer::initInstrumentStrings() +{ mag_types = { - {tr("dBFS"), FftDisplayPlot::DBFS}, - {tr("dBV"), FftDisplayPlot::DBV}, - {tr("dBu"), FftDisplayPlot::DBU}, - {tr("Vpeak"), FftDisplayPlot::VPEAK}, - {tr("Vrms"), FftDisplayPlot::VRMS}, - {tr("V/√Hz"), FftDisplayPlot::VROOTHZ}, + {tr("dBFS"), FftDisplayPlot::DBFS}, {tr("dBV"), FftDisplayPlot::DBV}, + {tr("dBu"), FftDisplayPlot::DBU}, {tr("Vpeak"), FftDisplayPlot::VPEAK}, + {tr("Vrms"), FftDisplayPlot::VRMS}, {tr("V/√Hz"), FftDisplayPlot::VROOTHZ}, }; avg_types = { - {tr("Sample"), FftDisplayPlot::SAMPLE}, - {tr("Peak Hold"), FftDisplayPlot::PEAK_HOLD}, - {tr("Peak Hold Continous"), FftDisplayPlot::PEAK_HOLD_CONTINUOUS}, - {tr("Min Hold"), FftDisplayPlot::MIN_HOLD}, - {tr("Min Hold Continous"), FftDisplayPlot::MIN_HOLD_CONTINUOUS}, - {tr("Linear RMS"), FftDisplayPlot::LINEAR_RMS}, - {tr("Linear dB"), FftDisplayPlot::LINEAR_DB}, - {tr("Exponential RMS"), FftDisplayPlot::EXPONENTIAL_RMS}, - {tr("Exponential dB"), FftDisplayPlot::EXPONENTIAL_DB}, + {tr("Sample"), FftDisplayPlot::SAMPLE}, + {tr("Peak Hold"), FftDisplayPlot::PEAK_HOLD}, + {tr("Peak Hold Continous"), FftDisplayPlot::PEAK_HOLD_CONTINUOUS}, + {tr("Min Hold"), FftDisplayPlot::MIN_HOLD}, + {tr("Min Hold Continous"), FftDisplayPlot::MIN_HOLD_CONTINUOUS}, + {tr("Linear RMS"), FftDisplayPlot::LINEAR_RMS}, + {tr("Linear dB"), FftDisplayPlot::LINEAR_DB}, + {tr("Exponential RMS"), FftDisplayPlot::EXPONENTIAL_RMS}, + {tr("Exponential dB"), FftDisplayPlot::EXPONENTIAL_DB}, }; win_types = { - {tr("Flat top"), FftWinType::FLAT_TOP}, - {tr("Rectangular"), FftWinType::RECTANGULAR}, - {tr("Triangular (Bartlett)"), FftWinType::TRIANGULAR}, - {tr("Hamming"), FftWinType::HAMMING}, - {tr("Hann"), FftWinType::HANN}, - {tr("Blackman-Harris"), FftWinType::BLACKMAN_HARRIS}, - {tr("Kaiser"), FftWinType::KAISER}, + {tr("Flat top"), FftWinType::FLAT_TOP}, + {tr("Rectangular"), FftWinType::RECTANGULAR}, + {tr("Triangular (Bartlett)"), FftWinType::TRIANGULAR}, + {tr("Hamming"), FftWinType::HAMMING}, + {tr("Hann"), FftWinType::HANN}, + {tr("Blackman-Harris"), FftWinType::BLACKMAN_HARRIS}, + {tr("Kaiser"), FftWinType::KAISER}, }; markerTypes = { - tr("Manual"), - tr("Peak"), - tr("Delta"), - tr("Fixed"), + tr("Manual"), + tr("Peak"), + tr("Delta"), + tr("Fixed"), }; } -SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, - ToolMenuEntry *tme, m2k_iio_manager* m2k_man, - QJSEngine *engine, QWidget *parent): - M2kTool(ctx, tme, new SpectrumAnalyzer_API(this), "Spectrum Analyzer", - parent), - ui(new Ui::SpectrumAnalyzer), - m_m2k_context(nullptr), - m_m2k_analogin(nullptr), - m_generic_context(nullptr), - m_generic_analogin(nullptr), - marker_selector(new DbClickButtons(this)), - fft_plot(nullptr), - waterfall_plot(nullptr), - settings_group(new QButtonGroup(this)), - channels_group(new QButtonGroup(this)), - adc_name(ctx ? filt->device_name(TOOL_SPECTRUM_ANALYZER) : ""), - crt_channel_id(0), - crt_peak(0), - max_peak_count(10), - fft_size(32768), - hCursorsEnabled(true), - vCursorsEnabled(true), - searchVisiblePeaks(true), - m_max_sample_rate(100e6), - sample_rate_divider(1), - marker_menu_opened(false), - bin_sizes({ - 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144 - }), nb_ref_channels(0), - selected_ch_settings(-1), - fft_ids(nullptr), - m_nb_overlapping_avg(1), - use_float_sink(true) +SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, ToolMenuEntry *tme, m2k_iio_manager *m2k_man, + QJSEngine *engine, QWidget *parent) + : M2kTool(ctx, tme, new SpectrumAnalyzer_API(this), "Spectrum Analyzer", parent) + , ui(new Ui::SpectrumAnalyzer) + , m_m2k_context(nullptr) + , m_m2k_analogin(nullptr) + , m_generic_context(nullptr) + , m_generic_analogin(nullptr) + , marker_selector(new DbClickButtons(this)) + , fft_plot(nullptr) + , waterfall_plot(nullptr) + , settings_group(new QButtonGroup(this)) + , channels_group(new QButtonGroup(this)) + , adc_name(ctx ? filt->device_name(TOOL_SPECTRUM_ANALYZER) : "") + , crt_channel_id(0) + , crt_peak(0) + , max_peak_count(10) + , fft_size(32768) + , hCursorsEnabled(true) + , vCursorsEnabled(true) + , searchVisiblePeaks(true) + , m_max_sample_rate(100e6) + , sample_rate_divider(1) + , marker_menu_opened(false) + , bin_sizes({256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144}) + , nb_ref_channels(0) + , selected_ch_settings(-1) + , fft_ids(nullptr) + , m_nb_overlapping_avg(1) + , use_float_sink(true) { initInstrumentStrings(); // Get the list of names of the available channels QList channel_names; - if (ctx) { + if(ctx) { auto libm2k_ctx = contextOpen(ctx, ""); - if (libm2k_ctx->toM2k()) { + if(libm2k_ctx->toM2k()) { m_m2k_context = libm2k_ctx->toM2k(); m_m2k_analogin = m_m2k_context->getAnalogIn(); m_adc_nb_channels = m_m2k_analogin->getNbChannels(); @@ -178,9 +176,8 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, } iio = m2k_man->get_instance(ctx, adc_name); - for (unsigned int i = 0; i < m_adc_nb_channels; i++) { - channel_names.push_back( - QString("Channel %1").arg(i + 1)); + for(unsigned int i = 0; i < m_adc_nb_channels; i++) { + channel_names.push_back(QString("Channel %1").arg(i + 1)); } } sample_rate = m_max_sample_rate; @@ -195,7 +192,7 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, ui->cmb_units->blockSignals(true); ui->cmb_units->clear(); - for (auto it = mag_types.begin(); it != mag_types.end(); ++it) { + for(auto it = mag_types.begin(); it != mag_types.end(); ++it) { ui->cmb_units->addItem(it->first); } @@ -204,7 +201,7 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, ui->comboBox_type->blockSignals(true); ui->comboBox_type->clear(); - for (auto it = avg_types.begin(); it != avg_types.end(); ++it) { + for(auto it = avg_types.begin(); it != avg_types.end(); ++it) { ui->comboBox_type->addItem(it->first); } @@ -213,7 +210,7 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, ui->comboBox_window->blockSignals(true); ui->comboBox_window->clear(); - for (auto it = win_types.begin(); it != win_types.end(); ++it) { + for(auto it = win_types.begin(); it != win_types.end(); ++it) { ui->comboBox_window->addItem(it->first); } @@ -243,13 +240,12 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, // Disable mouse interactions with the axes until they are in a working state fft_plot->setXaxisMouseGesturesEnabled(false); - for (uint i = 0; i < m_adc_nb_channels; i++) { -// ui->gridLayout_plot->addWidget(measurePanel, 0, 1, 1, 1); + for(uint i = 0; i < m_adc_nb_channels; i++) { + // ui->gridLayout_plot->addWidget(measurePanel, 0, 1, 1, 1); fft_plot->setYaxisMouseGesturesEnabled(i, false); } #ifdef SPECTRAL_MSR - connect(fft_plot, SIGNAL(channelAdded(int)), this, - SLOT(onChannelAdded(int))); + connect(fft_plot, SIGNAL(channelAdded(int)), this, SLOT(onChannelAdded(int))); /* Measurements Settings */ measure_settings_init(); #endif @@ -272,8 +268,8 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, waterfall_plot->replot(); // plot widget - QWidget* centralWidget = new QWidget(this); - QVBoxLayout* vLayout = new QVBoxLayout(centralWidget); + QWidget *centralWidget = new QWidget(this); + QVBoxLayout *vLayout = new QVBoxLayout(centralWidget); vLayout->setContentsMargins(20, 0, 20, 20); vLayout->setSpacing(10); centralWidget->setLayout(vLayout); @@ -304,7 +300,6 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, DockerUtils::configureTopBar(waterfallDocker); #endif - // init layouts ui->widgetPlotContainer->layout()->removeWidget(ui->topPlotWidget); vLayout->addWidget(ui->topPlotWidget); @@ -329,9 +324,8 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, fft_plot->setBtmHorAxisUnit("Hz"); // Initialize spectrum channels - for (int i = 0 ; i < m_adc_nb_channels; i++) { - channel_sptr channel = std::make_shared(i, - channel_names[i], fft_plot); + for(int i = 0; i < m_adc_nb_channels; i++) { + channel_sptr channel = std::make_shared(i, channel_names[i], fft_plot); channel->setColor(fft_plot->getLineColor(i)); ui->channelsList->addWidget(channel->widget()); channels.push_back(channel); @@ -339,74 +333,67 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, settings_group->addButton(channel->widget()->menuButton()); channels_group->addButton(channel->widget()->nameButton()); - connect(channel.get()->widget(), SIGNAL(menuToggled(bool)), - SLOT(onChannelSettingsToggled(bool))); - connect(channel.get()->widget(), SIGNAL(selected(bool)), - SLOT(onChannelSelected(bool))); - connect(channel.get()->widget(), SIGNAL(enabled(bool)), - SLOT(onChannelEnabled(bool))); + connect(channel.get()->widget(), SIGNAL(menuToggled(bool)), SLOT(onChannelSettingsToggled(bool))); + connect(channel.get()->widget(), SIGNAL(selected(bool)), SLOT(onChannelSelected(bool))); + connect(channel.get()->widget(), SIGNAL(enabled(bool)), SLOT(onChannelEnabled(bool))); connect(channel.get(), SIGNAL(FftWindowChanged(std::vector, int)), SLOT(setWaterfallWindow(std::vector, int))); - ch_api.append(new SpectrumChannel_API(this,channel)); + ch_api.append(new SpectrumChannel_API(this, channel)); } - if (m_adc_nb_channels > 0) - channels[crt_channel_id]->widget()->nameButton()-> - setChecked(true); + if(m_adc_nb_channels > 0) + channels[crt_channel_id]->widget()->nameButton()->setChecked(true); // Initialize Sweep controls - unit_per_div = new PositionSpinButton({ - {" ",1e0}, - }, tr("Scale/Div"), 0.0, 0.0, false, false, this); + unit_per_div = new PositionSpinButton( + { + {" ", 1e0}, + }, + tr("Scale/Div"), 0.0, 0.0, false, false, this); ui->divisionWidget->addWidget(unit_per_div); m_mag_min_max = QPair(-200, 300); - top = new PositionSpinButton({ - {" ",1e0}, - }, tr("Top"), -200.0, 300.0, false, false, this); - top_scale = new ScaleSpinButton({ - {{"pV/√Hz",1e-12}, - {"nV/√Hz",1e-9}, - {"μV/√Hz",1e-6}, - {"mV/√Hz",1e-3}, - {"V/√Hz",1e0}} - }, tr("Top"), 1e-12, 10e1, false, false, this); + top = new PositionSpinButton( + { + {" ", 1e0}, + }, + tr("Top"), -200.0, 300.0, false, false, this); + top_scale = new ScaleSpinButton( + {{{"pV/√Hz", 1e-12}, {"nV/√Hz", 1e-9}, {"μV/√Hz", 1e-6}, {"mV/√Hz", 1e-3}, {"V/√Hz", 1e0}}}, tr("Top"), + 1e-12, 10e1, false, false, this); ui->topWidget->addWidget(top); ui->topWidget->addWidget(top_scale); - bottom = new PositionSpinButton({ - {" ",1e0}, - }, tr("Bottom"), -200.0, 300.0, false, false, this); - bottom_scale = new ScaleSpinButton({ - {{"pV/√Hz",1e-12}, - {"nV/√Hz",1e-9}, - {"μV/√Hz",1e-6}, - {"mV/√Hz",1e-3}, - {"V/√Hz",1e0}} - }, tr("Bottom"), 1e-12, 10e1, false, false, this); + bottom = new PositionSpinButton( + { + {" ", 1e0}, + }, + tr("Bottom"), -200.0, 300.0, false, false, this); + bottom_scale = new ScaleSpinButton( + {{{"pV/√Hz", 1e-12}, {"nV/√Hz", 1e-9}, {"μV/√Hz", 1e-6}, {"mV/√Hz", 1e-3}, {"V/√Hz", 1e0}}}, + tr("Bottom"), 1e-12, 10e1, false, false, this); ui->bottomWidget->addWidget(bottom); ui->bottomWidget->addWidget(bottom_scale); - marker_freq_pos = new PositionSpinButton({ - {tr("Hz"),1e0}, - {tr("kHz"),1e3}, - {tr("MHz"),1e6} - }, tr("Frequency Position"), 0.0, 5e7, true, false, this); + marker_freq_pos = new PositionSpinButton({{tr("Hz"), 1e0}, {tr("kHz"), 1e3}, {tr("MHz"), 1e6}}, + tr("Frequency Position"), 0.0, 5e7, true, false, this); ui->markerFreqPosLayout->addWidget(marker_freq_pos); marker_freq_pos->setFineModeAvailable(false); - waterfall_size = new PositionSpinButton({ - {" ",1e0}, - }, tr("Waterfall Size"), 10, 5000, false, false, this); + waterfall_size = new PositionSpinButton( + { + {" ", 1e0}, + }, + tr("Waterfall Size"), 10, 5000, false, false, this); ui->vLayout_waterfall->addWidget(waterfall_size); sample_timer = new QTimer(); connect(sample_timer, SIGNAL(timeout()), this, SLOT(refreshCurrentSampleLabel())); startStopRange = new StartStopRangeWidget(0); - connect(startStopRange, &StartStopRangeWidget::rangeChanged, [=](double start, double stop){ + connect(startStopRange, &StartStopRangeWidget::rangeChanged, [=](double start, double stop) { fft_plot->setStartStop(start, stop); fft_plot->setAxisScale(QwtAxis::XBottom, start, stop); fft_plot->replot(); @@ -424,59 +411,54 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, ui->cmb_rbw->clear(); int i = 0; - for (; i < bin_sizes.size(); i++) { - ui->cmb_rbw->addItem(freq_formatter.format( - sample_rate / bin_sizes[i], "Hz", 2)); + for(; i < bin_sizes.size(); i++) { + ui->cmb_rbw->addItem(freq_formatter.format(sample_rate / bin_sizes[i], "Hz", 2)); } ui->cmb_rbw->blockSignals(false); ui->cmb_rbw->setCurrentIndex((int)bin_sizes.size() / 2); marker_freq_pos->setMaxValue(stop); - marker_freq_pos->setStep(2 * (stop - - start) / bin_sizes[ui->cmb_rbw->currentIndex()]); + marker_freq_pos->setStep(2 * (stop - start) / bin_sizes[ui->cmb_rbw->currentIndex()]); fft_plot->updateZoomerBase(); waterfall_plot->updateZoomerBase(); - }); - connect(ui->cmb_rbw, QOverload::of(&QComboBox::currentIndexChanged), - [=](int index){ + connect(ui->cmb_rbw, QOverload::of(&QComboBox::currentIndexChanged), [=](int index) { startStopRange->setMinimumSpanValue(10 * sample_rate / bin_sizes[index]); // set waterfall resolutionBW in kHz waterfall_plot->setResolutionBW((sample_rate / bin_sizes[index])); }); - connect(ui->cmbGainMode, QOverload::of(&QComboBox::currentIndexChanged), - [=](int index){ - + connect(ui->cmbGainMode, QOverload::of(&QComboBox::currentIndexChanged), [=](int index) { int crt_channel = channelIdOfOpenedSettings(); - if (crt_channel >= m_adc_nb_channels || crt_channel < 0) { + if(crt_channel >= m_adc_nb_channels || crt_channel < 0) { return; } channels[crt_channel]->setGainMode(index); bool started = isIioManagerStarted(); - if (started) { + if(started) { iio->lock(); } try { - libm2k::analog::ANALOG_IN_CHANNEL chn = static_cast(crt_channel); + libm2k::analog::ANALOG_IN_CHANNEL chn = + static_cast(crt_channel); m_m2k_analogin->setRange(chn, channels[crt_channel]->getGainMode()); bool canConvRawToVolts = m_m2k_analogin ? true : false; - if (canConvRawToVolts) { + if(canConvRawToVolts) { fft_plot->setScaleFactor(crt_channel, m_m2k_analogin->getScalingFactor(chn)); } - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug(CAT_M2K_SPECTRUM_ANALYZER) << e.what(); } - if (started) { + if(started) { iio->unlock(); } }); @@ -485,21 +467,20 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, // Initialize vertical axis controls unit_per_div->setMinValue(0.01); - unit_per_div->setMaxValue(500/10); + unit_per_div->setMaxValue(500 / 10); // Configure plot peak capabilities - for (uint i = 0; i < m_adc_nb_channels; i++) { + for(uint i = 0; i < m_adc_nb_channels; i++) { fft_plot->setPeakCount(i, max_peak_count); } // Configure markers - for (size_t i = 0; i < m_adc_nb_channels; i++) { + for(size_t i = 0; i < m_adc_nb_channels; i++) { fft_plot->setMarkerCount(i, 5); - for (int m = 0; m < 5; m++) { + for(int m = 0; m < 5; m++) { fft_plot->setMarkerEnabled(i, m, false); - marker_api.append(new SpectrumMarker_API(this,i,m)); - + marker_api.append(new SpectrumMarker_API(this, i, m)); } } @@ -509,77 +490,58 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, // Initialize Marker controls ui->hLayout_marker_selector->addWidget(marker_selector); - connect(marker_selector, SIGNAL(buttonToggled(int, bool)), - this, SLOT(onMarkerToggled(int, bool))); - connect(marker_selector, SIGNAL(buttonSelected(int)), - this, SLOT(onMarkerSelected(int))); + connect(marker_selector, SIGNAL(buttonToggled(int, bool)), this, SLOT(onMarkerToggled(int, bool))); + connect(marker_selector, SIGNAL(buttonSelected(int)), this, SLOT(onMarkerSelected(int))); marker_selector->setSelectedButton(0); - connect(fft_plot, SIGNAL(newMarkerData()), - this, SLOT(onPlotNewMarkerData())); - connect(fft_plot, SIGNAL(markerSelected(uint, uint)), - this, SLOT(onPlotMarkerSelected(uint, uint))); - - connect(marker_freq_pos, SIGNAL(valueChanged(double)), - this, SLOT(onMarkerFreqPosChanged(double))); + connect(fft_plot, SIGNAL(newMarkerData()), this, SLOT(onPlotNewMarkerData())); + connect(fft_plot, SIGNAL(markerSelected(uint, uint)), this, SLOT(onPlotMarkerSelected(uint, uint))); - connect(fft_plot, SIGNAL(sampleRateUpdated(double)), - this, SLOT(onPlotSampleRateUpdated(double))); - connect(fft_plot, SIGNAL(sampleCountUpdated(uint)), - this, SLOT(onPlotSampleCountUpdated(uint))); + connect(marker_freq_pos, SIGNAL(valueChanged(double)), this, SLOT(onMarkerFreqPosChanged(double))); + connect(fft_plot, SIGNAL(sampleRateUpdated(double)), this, SLOT(onPlotSampleRateUpdated(double))); + connect(fft_plot, SIGNAL(sampleCountUpdated(uint)), this, SLOT(onPlotSampleCountUpdated(uint))); - connect(this, SIGNAL(selectedChannelChanged(int)), - fft_plot, SLOT(setSelectedChannel(int))); - connect(this, SIGNAL(selectedChannelChanged(int)), - waterfall_plot, SLOT(enableChannel(int))); + connect(this, SIGNAL(selectedChannelChanged(int)), fft_plot, SLOT(setSelectedChannel(int))); + connect(this, SIGNAL(selectedChannelChanged(int)), waterfall_plot, SLOT(enableChannel(int))); connect(this, &SpectrumAnalyzer::selectedChannelChanged, this, - [=](int id){ - setWaterfallWindow(channels.at(id)->getWindow(), id); - }); + [=](int id) { setWaterfallWindow(channels.at(id)->getWindow(), id); }); - if (ctx) { + if(ctx) { build_gnuradio_block_chain(); } else { build_gnuradio_block_chain_no_ctx(); } connect(ui->btnApply, SIGNAL(clicked()), this, SLOT(validateSpinboxAveraging())); - connect(ui->runSingleWidget, &RunSingleWidget::toggled, - [=](bool checked){ - tme->setRunning(checked); - }); - connect(tme, &ToolMenuEntry::runToggled, - ui->runSingleWidget, &RunSingleWidget::toggle); - connect(ui->runSingleWidget, &RunSingleWidget::toggled, - this, &SpectrumAnalyzer::runStopToggled); - connect(this, &SpectrumAnalyzer::started, - ui->runSingleWidget, &RunSingleWidget::toggle); - + connect(ui->runSingleWidget, &RunSingleWidget::toggled, [=](bool checked) { tme->setRunning(checked); }); + connect(tme, &ToolMenuEntry::runToggled, ui->runSingleWidget, &RunSingleWidget::toggle); + connect(ui->runSingleWidget, &RunSingleWidget::toggled, this, &SpectrumAnalyzer::runStopToggled); + connect(this, &SpectrumAnalyzer::started, ui->runSingleWidget, &RunSingleWidget::toggle); - connect(fft_plot, &FftDisplayPlot::newFFTData, this, [=](){ + connect(fft_plot, &FftDisplayPlot::newFFTData, this, [=]() { receivedFFTData = true; - if (receivedWaterfallData || !waterfall_visible) { + if(receivedWaterfallData || !waterfall_visible) { singleCaptureDone(); receivedWaterfallData = false; receivedFFTData = false; - } else if (ui->runSingleWidget->singleButtonChecked()){ - for (size_t i = 0; i < m_adc_nb_channels; i++) { + } else if(ui->runSingleWidget->singleButtonChecked()) { + for(size_t i = 0; i < m_adc_nb_channels; i++) { iio->stop(fft_ids[i]); } } }); - connect(waterfall_plot, &WaterfallDisplayPlot::newWaterfallData, this, [=](){ + connect(waterfall_plot, &WaterfallDisplayPlot::newWaterfallData, this, [=]() { receivedWaterfallData = true; - if (receivedFFTData) { + if(receivedFFTData) { singleCaptureDone(); receivedWaterfallData = false; receivedFFTData = false; - } else if (ui->runSingleWidget->singleButtonChecked()){ - for (size_t i = 0; i < m_adc_nb_channels; i++) { + } else if(ui->runSingleWidget->singleButtonChecked()) { + for(size_t i = 0; i < m_adc_nb_channels; i++) { iio->stop(waterfall_ids[i]); } } @@ -595,51 +557,45 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, /* Apply measurements for every new batch of data */ connect(fft_plot, SIGNAL(newData()), SLOT(onNewDataReceived())); - for (int i = 0; i < m_adc_nb_channels; i++) { + for(int i = 0; i < m_adc_nb_channels; i++) { fft_plot->initChannelMeasurement(i); - } + } #endif - connect(waterfall_size, SIGNAL(valueChanged(double)), - SLOT(onWaterfallSizeChanged(double))); - connect(top, SIGNAL(valueChanged(double)), - SLOT(onTopValueChanged(double))); - connect(unit_per_div, SIGNAL(valueChanged(double)), - SLOT(onScalePerDivValueChanged(double))); - connect(bottom, SIGNAL(valueChanged(double)), - SLOT(onBottomValueChanged(double))); - connect(top_scale, SIGNAL(valueChanged(double)), - SLOT(onTopValueChanged(double))); - connect(bottom_scale, SIGNAL(valueChanged(double)), - SLOT(onBottomValueChanged(double))); + connect(waterfall_size, SIGNAL(valueChanged(double)), SLOT(onWaterfallSizeChanged(double))); + connect(top, SIGNAL(valueChanged(double)), SLOT(onTopValueChanged(double))); + connect(unit_per_div, SIGNAL(valueChanged(double)), SLOT(onScalePerDivValueChanged(double))); + connect(bottom, SIGNAL(valueChanged(double)), SLOT(onBottomValueChanged(double))); + connect(top_scale, SIGNAL(valueChanged(double)), SLOT(onTopValueChanged(double))); + connect(bottom_scale, SIGNAL(valueChanged(double)), SLOT(onBottomValueChanged(double))); cursor_panel_init(); - connect(fft_plot, - SIGNAL(cursorReadoutsChanged(struct cursorReadoutsText)), + connect(fft_plot, SIGNAL(cursorReadoutsChanged(struct cursorReadoutsText)), SLOT(onCursorReadoutsChanged(struct cursorReadoutsText))); - connect(waterfall_plot, - SIGNAL(cursorReadoutsChanged(struct cursorReadoutsText)), + connect(waterfall_plot, SIGNAL(cursorReadoutsChanged(struct cursorReadoutsText)), SLOT(onCursorReadoutsChanged(struct cursorReadoutsText))); // change waterfall direction based on docker position - connect(waterfallDocker, &QDockWidget::topLevelChanged, this, [=](bool floating){ - if (!floating) { - auto flow = waterfallDocker->pos().y() == 0 ? WaterfallFlowDirection::UP : - WaterfallFlowDirection::DOWN; + connect(waterfallDocker, &QDockWidget::topLevelChanged, this, [=](bool floating) { + if(!floating) { + auto flow = waterfallDocker->pos().y() == 0 ? WaterfallFlowDirection::UP + : WaterfallFlowDirection::DOWN; - if (flow != waterfall_plot->getFlowDirection()) waterfall_plot->setFlowDirection(flow); + if(flow != waterfall_plot->getFlowDirection()) + waterfall_plot->setFlowDirection(flow); } updateVisibleCursorHandles(); }); - connect(fftDocker, &QDockWidget::topLevelChanged, this, [=](bool floating){ - if (!floating) { - auto flow = waterfallDocker->pos().y() == 0 ? WaterfallFlowDirection::UP : - WaterfallFlowDirection::DOWN; + connect(fftDocker, &QDockWidget::topLevelChanged, this, [=](bool floating) { + if(!floating) { + auto flow = waterfallDocker->pos().y() == 0 ? WaterfallFlowDirection::UP + : WaterfallFlowDirection::DOWN; - if (flow != waterfall_plot->getFlowDirection()) waterfall_plot->setFlowDirection(flow); + if(flow != waterfall_plot->getFlowDirection()) + waterfall_plot->setFlowDirection(flow); } updateVisibleCursorHandles(); }); @@ -661,35 +617,30 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, marker_freq_pos->setMinValue(1); marker_freq_pos->setMaxValue(startStopRange->getStopValue()); - marker_freq_pos->setStep(2 * (startStopRange->getStopValue() - - startStopRange->getStartValue()) / bin_sizes[ui->cmb_rbw->currentIndex()]); + marker_freq_pos->setStep(2 * (startStopRange->getStopValue() - startStopRange->getStartValue()) / + bin_sizes[ui->cmb_rbw->currentIndex()]); ui->lblMagUnit->setText(ui->cmb_units->currentText()); ui->markerTable->hide(); - - for (auto ch: qAsConst(channels)) { + for(auto ch : qAsConst(channels)) { ch->setFftWindow(FftWinType::HAMMING, fft_size); } #ifdef SPECTRAL_MSR - if (!runButton()->isChecked() && measurementsEnabled()) { - measureUpdateValues(); - } + if(!runButton()->isChecked() && measurementsEnabled()) { + measureUpdateValues(); + } - for (unsigned int i = 0; i < m_adc_nb_channels; i++) { - init_selected_measurements(i, {0, 1, 4, 5}); - } + for(unsigned int i = 0; i < m_adc_nb_channels; i++) { + init_selected_measurements(i, {0, 1, 4, 5}); + } #endif + connect(ui->logBtn, &QPushButton::toggled, fft_plot, &FftDisplayPlot::useLogFreq); + connect(ui->logBtn, &QPushButton::toggled, waterfall_plot, &WaterfallDisplayPlot::useLogFreq); connect(ui->logBtn, &QPushButton::toggled, - fft_plot, &FftDisplayPlot::useLogFreq); - connect(ui->logBtn, &QPushButton::toggled, - waterfall_plot, &WaterfallDisplayPlot::useLogFreq); - connect(ui->logBtn, &QPushButton::toggled, - [=](bool use_log_freq){ - startStopRange->setMinimumValue(use_log_freq); - }); + [=](bool use_log_freq) { startStopRange->setMinimumValue(use_log_freq); }); ui->btnHistory->setEnabled(true); ui->btnHistory->setChecked(true); @@ -701,25 +652,23 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, connect(ui->rightMenu, &MenuHAnim::finished, this, &SpectrumAnalyzer::rightMenuFinished); menuOrder.push_back(ui->btnSweep); + connect(ui->btnPrint, &QPushButton::clicked, + [=]() { fft_plot->printWithNoBackground(api->objectName(), false); }); - connect(ui->btnPrint, &QPushButton::clicked, [=](){ - fft_plot->printWithNoBackground(api->objectName(), false); - }); - - connect(ui->btnSnapshot, &QPushButton::clicked, [=](){ + connect(ui->btnSnapshot, &QPushButton::clicked, [=]() { QwtPlotCurve *curve = fft_plot->Curve(selected_ch_settings); - if (selected_ch_settings < 2) { - if (nb_ref_channels == MAX_REF_CHANNELS) { + if(selected_ch_settings < 2) { + if(nb_ref_channels == MAX_REF_CHANNELS) { return; } - if (!curve->data()->size()) { + if(!curve->data()->size()) { return; } QVector xData; QVector yData; - for (size_t i = 0; i < curve->data()->size(); ++i) { + for(size_t i = 0; i < curve->data()->size(); ++i) { xData.push_back(curve->data()->sample(i).x()); yData.push_back(curve->data()->sample(i).y()); } @@ -729,20 +678,19 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, QStringList channelDetails; auto iterAvg = std::find_if(avg_types.begin(), avg_types.end(), - [&](const std::pair& p) { - return p.second == sc->averageType(); - }); + [&](const std::pair &p) { + return p.second == sc->averageType(); + }); - if (iterAvg != avg_types.end()) { + if(iterAvg != avg_types.end()) { channelDetails.push_back((*iterAvg).first); } - auto iterWin = std::find_if(win_types.begin(), win_types.end(), - [&](const std::pair& p) { - return p.second == sc->fftWindow(); - }); + auto iterWin = std::find_if( + win_types.begin(), win_types.end(), + [&](const std::pair &p) { return p.second == sc->fftWindow(); }); - if (iterWin != win_types.end()) { + if(iterWin != win_types.end()) { channelDetails.push_back((*iterWin).first); } @@ -762,50 +710,57 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, QString selectedFilter = filter[0]; - QString fileName = QFileDialog::getSaveFileName(this, - tr("Export"), "", filter.join(";;"), - &selectedFilter, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); + QString fileName = QFileDialog::getSaveFileName( + this, tr("Export"), "", filter.join(";;"), &selectedFilter, + (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); - if (fileName.split(".").size() <= 1) { + if(fileName.split(".").size() <= 1) { // file name w/o extension. Let's append it QString ext = selectedFilter.split(".")[1].split(")")[0]; fileName += "." + ext; } - if (!fileName.isEmpty()) { + if(!fileName.isEmpty()) { FileManager fm("Spectrum Analyzer"); fm.open(fileName, FileManager::EXPORT); QVector freq_data, mag_data; - for (size_t i = 0; i < curve->data()->size(); ++i) { + for(size_t i = 0; i < curve->data()->size(); ++i) { freq_data.push_back(curve->sample(i).x()); mag_data.push_back(curve->sample(i).y()); } QString unit = ui->lblMagUnit->text(); fm.save(freq_data, "Frequency(Hz)"); - fm.save(mag_data, "REF" + QString::number(selected_ch_settings - m_adc_nb_channels + 1) - + "(" + unit + ")"); + fm.save(mag_data, + "REF" + QString::number(selected_ch_settings - m_adc_nb_channels + 1) + "(" + + unit + ")"); QString channelDetails; - auto iterAvg = std::find_if(avg_types.begin(), avg_types.end(), - [&](const std::pair& p) { - return p.first == importedChannelDetails[selected_ch_settings - m_adc_nb_channels][0]; - }); + auto iterAvg = + std::find_if(avg_types.begin(), avg_types.end(), + [&](const std::pair &p) { + return p.first == + importedChannelDetails[selected_ch_settings - + m_adc_nb_channels][0]; + }); - if (iterAvg != avg_types.end()) { + if(iterAvg != avg_types.end()) { channelDetails += (*iterAvg).first; channelDetails += ","; } - auto iterWin = std::find_if(win_types.begin(), win_types.end(), - [&](const std::pair& p) { - return p.first == importedChannelDetails[selected_ch_settings - m_adc_nb_channels][1]; - }); + auto iterWin = + std::find_if(win_types.begin(), win_types.end(), + [&](const std::pair &p) { + return p.first == + importedChannelDetails[selected_ch_settings - + m_adc_nb_channels][1]; + }); - if (iterWin != win_types.end()) { + if(iterWin != win_types.end()) { channelDetails += (*iterWin).first; channelDetails += ","; } @@ -820,8 +775,7 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, } }); - connect(ui->btnExport, &QPushButton::clicked, - this, &SpectrumAnalyzer::btnExportClicked); + connect(ui->btnExport, &QPushButton::clicked, this, &SpectrumAnalyzer::btnExportClicked); readPreferences(); ui->btnHelp->setUrl("https://wiki.analog.com/university/tools/m2k/scopy/spectrumanalyzer"); @@ -836,7 +790,6 @@ SpectrumAnalyzer::SpectrumAnalyzer(struct iio_context *ctx, Filter *filt, #ifdef __ANDROID__ ui->btnAddRef->setIconSize(QSize(24, 24)); #endif - } SpectrumAnalyzer::~SpectrumAnalyzer() @@ -845,32 +798,32 @@ SpectrumAnalyzer::~SpectrumAnalyzer() delete sample_timer; delete api; - for (auto it = ch_api.begin(); it != ch_api.end(); ++it) { + for(auto it = ch_api.begin(); it != ch_api.end(); ++it) { delete *it; } - for (auto it = marker_api.begin(); it != marker_api.end(); ++it) { + for(auto it = marker_api.begin(); it != marker_api.end(); ++it) { delete *it; } #ifdef SPECTRAL_MSR - for (auto it = d_measureObjs.begin(); it != d_measureObjs.end(); ++it) { + for(auto it = d_measureObjs.begin(); it != d_measureObjs.end(); ++it) { delete *it; - } + } #endif - if (iio) { + if(iio) { bool started = isIioManagerStarted(); - if (started) { + if(started) { iio->lock(); } - for (unsigned int i = 0; i < m_adc_nb_channels; i++) { + for(unsigned int i = 0; i < m_adc_nb_channels; i++) { iio->disconnect(fft_ids[i]); iio->disconnect(waterfall_ids[i]); } - if (started) { + if(started) { iio->unlock(); } @@ -880,10 +833,7 @@ SpectrumAnalyzer::~SpectrumAnalyzer() delete ui; } -QPushButton *SpectrumAnalyzer::getRunButton() -{ - return ui->runSingleWidget->getRunButton(); -} +QPushButton *SpectrumAnalyzer::getRunButton() { return ui->runSingleWidget->getRunButton(); } void SpectrumAnalyzer::setNativeDialogs(bool nativeDialogs) { @@ -892,7 +842,8 @@ void SpectrumAnalyzer::setNativeDialogs(bool nativeDialogs) waterfall_plot->setUseNativeDialog(nativeDialogs); } -void SpectrumAnalyzer::readPreferences() { +void SpectrumAnalyzer::readPreferences() +{ Preferences *p = Preferences::GetInstance(); bool showFps = p->get("general_show_plot_fps").toBool(); bool spectrumVisiblePeakSearch = p->get("M2k_spectrum_visible_peak_search").toBool(); @@ -912,23 +863,23 @@ void SpectrumAnalyzer::btnExportClicked() QString selectedFilter = filter[0]; - QString fileName = QFileDialog::getSaveFileName(this, - tr("Export"), "", filter.join(";;"), - &selectedFilter, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); + QString fileName = QFileDialog::getSaveFileName( + this, tr("Export"), "", filter.join(";;"), &selectedFilter, + (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); - if (fileName.split(".").size() <= 1) { + if(fileName.split(".").size() <= 1) { // file name w/o extension. Let's append it QString ext = selectedFilter.split(".")[1].split(")")[0]; fileName += "." + ext; } - if (!fileName.isEmpty()) { + if(!fileName.isEmpty()) { FileManager fm("Spectrum Analyzer"); fm.open(fileName, FileManager::EXPORT); QVector frequency_data; int nr_samples = fft_plot->Curve(0)->data()->size(); - for (int i = 0; i < nr_samples; ++i) { + for(int i = 0; i < nr_samples; ++i) { frequency_data.push_back(fft_plot->Curve(0)->sample(i).x()); } @@ -936,56 +887,51 @@ void SpectrumAnalyzer::btnExportClicked() QString channelDetails = ""; - for (int i = 0; i < channels.size(); ++i) { + for(int i = 0; i < channels.size(); ++i) { QVector data; - for (int j = 0; j < nr_samples; ++j) { + for(int j = 0; j < nr_samples; ++j) { data.push_back(fft_plot->Curve(i)->sample(j).y()); } QString unit = ui->lblMagUnit->text(); - fm.save(data, "Amplitude CH" + QString::number(i + 1) - + "(" + unit + ")"); + fm.save(data, "Amplitude CH" + QString::number(i + 1) + "(" + unit + ")"); /* Save information about the channels averaging type, window and - * averaging value */ + * averaging value */ channel_sptr sc = channels.at(i); auto iterAvg = std::find_if(avg_types.begin(), avg_types.end(), - [&](const std::pair& p) { - return p.second == sc->averageType(); - }); + [&](const std::pair &p) { + return p.second == sc->averageType(); + }); - if (iterAvg != avg_types.end()) { + if(iterAvg != avg_types.end()) { channelDetails += (*iterAvg).first; channelDetails += ","; } - auto iterWin = std::find_if(win_types.begin(), win_types.end(), - [&](const std::pair& p) { - return p.second == sc->fftWindow(); - }); + auto iterWin = std::find_if( + win_types.begin(), win_types.end(), + [&](const std::pair &p) { return p.second == sc->fftWindow(); }); - if (iterWin != win_types.end()) { + if(iterWin != win_types.end()) { channelDetails += (*iterWin).first; channelDetails += ","; } channelDetails += QString::number(sc->averaging()); channelDetails += ","; - } fm.setAdditionalInformation(channelDetails); fm.performWrite(); } - } void SpectrumAnalyzer::triggerRightMenuToggle(CustomPushButton *btn, bool checked) { - if (ui->rightMenu->animInProgress()) { - menuButtonActions.enqueue( - QPair(btn, checked)); + if(ui->rightMenu->animInProgress()) { + menuButtonActions.enqueue(QPair(btn, checked)); } else { toggleRightMenu(btn, checked); } @@ -997,8 +943,8 @@ void SpectrumAnalyzer::toggleRightMenu(CustomPushButton *btn, bool checked) bool chSettings = false; int id = -1; - if (btn != ui->btnSettings && btn != ui->btnToolSettings) { - if (!menuOrder.contains(btn)) { + if(btn != ui->btnSettings && btn != ui->btnToolSettings) { + if(!menuOrder.contains(btn)) { menuOrder.push_back(btn); } else { menuOrder.removeOne(btn); @@ -1006,8 +952,8 @@ void SpectrumAnalyzer::toggleRightMenu(CustomPushButton *btn, bool checked) } } - for (int i = 0; i < channels.size(); ++i) { - if (channels.at(i).get()->widget()->menuButton() == btn) { + for(int i = 0; i < channels.size(); ++i) { + if(channels.at(i).get()->widget()->menuButton() == btn) { chSettings = true; id = channels.at(i).get()->widget()->id(); } @@ -1015,50 +961,50 @@ void SpectrumAnalyzer::toggleRightMenu(CustomPushButton *btn, bool checked) /* Also check if one of the reference channels settings btn * was toggled */ - for (unsigned int i = 0; i < nb_ref_channels; ++i) { + for(unsigned int i = 0; i < nb_ref_channels; ++i) { ChannelWidget *cw = referenceChannels.at(i); - if (cw->menuButton() == btn) { + if(cw->menuButton() == btn) { chSettings = true; id = cw->id(); } } - if (!chSettings) { - if (btn == ui->btnToolSettings) { + if(!chSettings) { + if(btn == ui->btnToolSettings) { index = 1; - } else if (btn == ui->btnSweep) { + } else if(btn == ui->btnSweep) { index = 2; - } else if (btn == ui->btnMarkers) { + } else if(btn == ui->btnMarkers) { index = 3; - } else if (btn == ui->btnAddRef) { + } else if(btn == ui->btnAddRef) { index = 4; #ifdef SPECTRAL_MSR - } else if (btn == ui->btnMeasure) { + } else if(btn == ui->btnMeasure) { index = 5; - } else if (btn == ui->btnCursors) { + } else if(btn == ui->btnCursors) { index = 6; } #else - } else if (btn == ui->btnCursors) { + } else if(btn == ui->btnCursors) { index = 5; } #endif } - if (id != -1) { + if(id != -1) { updateChannelSettingsPanel(id); } - if (marker_menu_opened) { + if(marker_menu_opened) { updateMarkerMenu(crt_channel_id); } - if (!ui->btnToolSettings->isChecked()) { + if(!ui->btnToolSettings->isChecked()) { ui->btnSettings->setChecked(!!this->settings_group->checkedButton()); } - if (checked) { + if(checked) { ui->stackedWidget->setCurrentIndex(index); } @@ -1077,25 +1023,21 @@ void SpectrumAnalyzer::rightMenuFinished(bool opened) void SpectrumAnalyzer::on_boxCursors_toggled(bool on) { - fft_plot->setHorizCursorsEnabled( - on ? cr_ui->vCursorsEnable->isChecked() : false); - fft_plot->setVertCursorsEnabled( - on ? cr_ui->hCursorsEnable->isChecked() : false); + fft_plot->setHorizCursorsEnabled(on ? cr_ui->vCursorsEnable->isChecked() : false); + fft_plot->setVertCursorsEnabled(on ? cr_ui->hCursorsEnable->isChecked() : false); fft_plot->trackModeEnabled(on ? cr_ui->btnNormalTrack->isChecked() : true); - waterfall_plot->setHorizCursorsEnabled( - on ? cr_ui->vCursorsEnable->isChecked() : false); - waterfall_plot->setVertCursorsEnabled( - on ? cr_ui->hCursorsEnable->isChecked() : false); + waterfall_plot->setHorizCursorsEnabled(on ? cr_ui->vCursorsEnable->isChecked() : false); + waterfall_plot->setVertCursorsEnabled(on ? cr_ui->hCursorsEnable->isChecked() : false); waterfall_plot->trackModeEnabled(on ? cr_ui->btnNormalTrack->isChecked() : true); - if (on) { + if(on) { fft_plot->setCursorReadoutsVisible(on); waterfall_plot->setCursorReadoutsVisible(on); } else { - if (ui->btnCursors->isChecked()) + if(ui->btnCursors->isChecked()) ui->btnCursors->setChecked(false); menuOrder.removeOne(ui->btnCursors); @@ -1107,9 +1049,8 @@ void SpectrumAnalyzer::on_boxCursors_toggled(bool on) void SpectrumAnalyzer::on_btnToolSettings_toggled(bool checked) { - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); - if (checked) { + triggerRightMenuToggle(static_cast(QObject::sender()), checked); + if(checked) { ui->btnSettings->setChecked(!checked); } } @@ -1117,456 +1058,421 @@ void SpectrumAnalyzer::on_btnToolSettings_toggled(bool checked) void SpectrumAnalyzer::on_btnSettings_clicked(bool checked) { CustomPushButton *btn = nullptr; - if (checked && !menuOrder.isEmpty()) { + if(checked && !menuOrder.isEmpty()) { btn = menuOrder.back(); } else { - btn = static_cast( - settings_group->checkedButton()); + btn = static_cast(settings_group->checkedButton()); } - if (btn) { + if(btn) { btn->setChecked(checked); } } void SpectrumAnalyzer::on_btnCursors_toggled(bool checked) { - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); + triggerRightMenuToggle(static_cast(QObject::sender()), checked); } void SpectrumAnalyzer::on_btnSweep_toggled(bool checked) { - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); + triggerRightMenuToggle(static_cast(QObject::sender()), checked); } void SpectrumAnalyzer::on_btnMarkers_toggled(bool checked) { marker_menu_opened = checked; - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); + triggerRightMenuToggle(static_cast(QObject::sender()), checked); } #ifdef SPECTRAL_MSR -void SpectrumAnalyzer::on_btnMeasure_toggled(bool checked) { - triggerRightMenuToggle(static_cast(QObject::sender()), - checked); +void SpectrumAnalyzer::on_btnMeasure_toggled(bool checked) +{ + triggerRightMenuToggle(static_cast(QObject::sender()), checked); } void SpectrumAnalyzer::measure_settings_init() { - measure_settings = new MeasureSettings(&d_measureObjs, this, false); - int measure_panel = ui->stackedWidget->insertWidget(5, measure_settings); - - ui->btnMeasure->setDisabled(true); + measure_settings = new MeasureSettings(&d_measureObjs, this, false); + int measure_panel = ui->stackedWidget->insertWidget(5, measure_settings); - connect(measure_settings, - SIGNAL(measurementActivated(int, int)), - SLOT(onMeasurementActivated(int, int))); + ui->btnMeasure->setDisabled(true); - connect(measure_settings, - SIGNAL(measurementDeactivated(int, int)), - SLOT(onMeasurementDeactivated(int, int))); + connect(measure_settings, SIGNAL(measurementActivated(int, int)), SLOT(onMeasurementActivated(int, int))); - connect(measure_settings, - SIGNAL(measurementSelectionListChanged()), - SLOT(onMeasurementSelectionListChanged())); + connect(measure_settings, SIGNAL(measurementDeactivated(int, int)), SLOT(onMeasurementDeactivated(int, int))); - connect(fft_plot, SIGNAL(channelAdded(int)), - measure_settings, SLOT(onChannelAdded(int))); + connect(measure_settings, SIGNAL(measurementSelectionListChanged()), SLOT(onMeasurementSelectionListChanged())); - connect(this, SIGNAL(selectedChannelChanged(int)), - measure_settings, SLOT(setSelectedChannel(int))); + connect(fft_plot, SIGNAL(channelAdded(int)), measure_settings, SLOT(onChannelAdded(int))); - connect(ui->boxMeasure, SIGNAL(toggled(bool)), - SLOT(setMeasuremensEnabled(bool))); + connect(this, SIGNAL(selectedChannelChanged(int)), measure_settings, SLOT(setSelectedChannel(int))); + connect(ui->boxMeasure, SIGNAL(toggled(bool)), SLOT(setMeasuremensEnabled(bool))); } void SpectrumAnalyzer::onChannelAdded(int chnIdx) { - Measure *measure = nullptr; - - if(fft_plot->isReferenceWaveform(chnIdx)) - { - int idx = chnIdx - fft_plot->getYdata_size(); - size_t curve_size = fft_plot->getCurveSize(chnIdx); - double* data = new double [curve_size](); - measure = new Measure(chnIdx, data, curve_size, - nullptr, false); - } - else - { - int64_t numPoints = fft_plot->getNumPoints() / 2; - std::vector scale_factor = fft_plot->getScaleFactor(); + Measure *measure = nullptr; - //std::vector data = fft_plot->getOrginal_data(); - //int count = fft_plot->countReferenceWaveform(chnIdx); - double* data = new double [numPoints](); - measure = new Measure(chnIdx, data, - numPoints, nullptr, false); - } - measure->setAdcBitCount(12); - d_measureObjs.push_back(measure); + if(fft_plot->isReferenceWaveform(chnIdx)) { + int idx = chnIdx - fft_plot->getYdata_size(); + size_t curve_size = fft_plot->getCurveSize(chnIdx); + double *data = new double[curve_size](); + measure = new Measure(chnIdx, data, curve_size, nullptr, false); + } else { + int64_t numPoints = fft_plot->getNumPoints() / 2; + std::vector scale_factor = fft_plot->getScaleFactor(); + // std::vector data = fft_plot->getOrginal_data(); + // int count = fft_plot->countReferenceWaveform(chnIdx); + double *data = new double[numPoints](); + measure = new Measure(chnIdx, data, numPoints, nullptr, false); + } + measure->setAdcBitCount(12); + d_measureObjs.push_back(measure); } +void SpectrumAnalyzer::update_measure_for_channel(int ch_idx) +{ + ChannelWidget *chn_widget = getChannelWidgetAt(ch_idx); -void SpectrumAnalyzer::update_measure_for_channel(int ch_idx) { - ChannelWidget *chn_widget = getChannelWidgetAt(ch_idx); - - measure_settings->setChannelName(chn_widget->fullName()); - measure_settings->setChannelUnderlineColor(chn_widget->color()); + measure_settings->setChannelName(chn_widget->fullName()); + measure_settings->setChannelUnderlineColor(chn_widget->color()); } +void SpectrumAnalyzer::measure_panel_init() +{ + measurePanel = new QWidget(this); + measure_panel_ui = new Ui::MeasurementsPanel(); + measure_panel_ui->setupUi(measurePanel); -void SpectrumAnalyzer::measure_panel_init() { - measurePanel = new QWidget(this); - measure_panel_ui = new Ui::MeasurementsPanel(); - measure_panel_ui->setupUi(measurePanel); - - connect(measure_panel_ui->scrollArea->horizontalScrollBar(), &QScrollBar::rangeChanged, - measure_panel_ui->scrollArea_2->horizontalScrollBar(), &QScrollBar::setRange); - - connect(measure_panel_ui->scrollArea_2->horizontalScrollBar(), &QScrollBar::valueChanged, - measure_panel_ui->scrollArea->horizontalScrollBar(), &QScrollBar::setValue); - connect(measure_panel_ui->scrollArea->horizontalScrollBar(), &QScrollBar::valueChanged, - measure_panel_ui->scrollArea_2->horizontalScrollBar(), &QScrollBar::setValue); + connect(measure_panel_ui->scrollArea->horizontalScrollBar(), &QScrollBar::rangeChanged, + measure_panel_ui->scrollArea_2->horizontalScrollBar(), &QScrollBar::setRange); - connect(measure_panel_ui->scrollArea->horizontalScrollBar(), &QScrollBar::rangeChanged, - [=](double v1, double v2){ - measure_panel_ui->scrollArea_2->widget()->setFixedWidth(measure_panel_ui->scrollAreaWidgetContents->width()); - }); + connect(measure_panel_ui->scrollArea_2->horizontalScrollBar(), &QScrollBar::valueChanged, + measure_panel_ui->scrollArea->horizontalScrollBar(), &QScrollBar::setValue); + connect(measure_panel_ui->scrollArea->horizontalScrollBar(), &QScrollBar::valueChanged, + measure_panel_ui->scrollArea_2->horizontalScrollBar(), &QScrollBar::setValue); - measurePanel->hide(); + connect(measure_panel_ui->scrollArea->horizontalScrollBar(), &QScrollBar::rangeChanged, + [=](double v1, double v2) { + measure_panel_ui->scrollArea_2->widget()->setFixedWidth( + measure_panel_ui->scrollAreaWidgetContents->width()); + }); - connect(this, SIGNAL(measurementsAvailable()), - SLOT(onMeasuremetsAvailable())); + measurePanel->hide(); + connect(this, SIGNAL(measurementsAvailable()), SLOT(onMeasuremetsAvailable())); } -void SpectrumAnalyzer::init_selected_measurements(int chnIdx, - std::vector measureIdx) +void SpectrumAnalyzer::init_selected_measurements(int chnIdx, std::vector measureIdx) { - auto measurements_val = measurements(chnIdx); - for (int i = 0; i < measureIdx.size(); i++) { - measurements_val[measureIdx[i]]->setEnabled(true); - measure_settings->onMeasurementActivated( - chnIdx, measureIdx[i], true); - } - measure_settings->loadMeasurementStatesFromData(); - onMeasurementSelectionListChanged(); + auto measurements_val = measurements(chnIdx); + for(int i = 0; i < measureIdx.size(); i++) { + measurements_val[measureIdx[i]]->setEnabled(true); + measure_settings->onMeasurementActivated(chnIdx, measureIdx[i], true); + } + measure_settings->loadMeasurementStatesFromData(); + onMeasurementSelectionListChanged(); } std::shared_ptr SpectrumAnalyzer::measurement(int id, int chnIdx) { - Measure *measure = measureOfChannel(chnIdx); - if (measure) - return measure->measurement(id); - else - return std::shared_ptr(); + Measure *measure = measureOfChannel(chnIdx); + if(measure) + return measure->measurement(id); + else + return std::shared_ptr(); } void SpectrumAnalyzer::onMeasurementActivated(int id, int chnIdx) { - int oldActiveMeasCount = activeMeasurementsCount(chnIdx); + int oldActiveMeasCount = activeMeasurementsCount(chnIdx); - auto mList = measurements(chnIdx); - mList[id]->setEnabled(true); - measurements_data.push_back(mList[id]); - measureCreateAndAppendGuiFrom(*mList[id]); + auto mList = measurements(chnIdx); + mList[id]->setEnabled(true); + measurements_data.push_back(mList[id]); + measureCreateAndAppendGuiFrom(*mList[id]); - if (oldActiveMeasCount == 0) { - measure(); - } + if(oldActiveMeasCount == 0) { + measure(); + } - measureLabelsRearrange(); + measureLabelsRearrange(); } void SpectrumAnalyzer::onMeasurementDeactivated(int id, int chnIdx) { - auto mList = measurements(chnIdx); - QString name = mList[id]->name(); + auto mList = measurements(chnIdx); + QString name = mList[id]->name(); - mList[id]->setEnabled(false); + mList[id]->setEnabled(false); - auto it = find_if(measurements_data.begin(), measurements_data.end(), - [&](std::shared_ptr const& p) - { return (p->name() == name) && (p->channel() == chnIdx); }); - if (it != measurements_data.end()) { - int i = it - measurements_data.begin(); - measurements_data.removeAt(i); - measurements_gui.removeAt(i); - measureLabelsRearrange(); - } + auto it = find_if(measurements_data.begin(), measurements_data.end(), + [&](std::shared_ptr const &p) { + return (p->name() == name) && (p->channel() == chnIdx); + }); + if(it != measurements_data.end()) { + int i = it - measurements_data.begin(); + measurements_data.removeAt(i); + measurements_gui.removeAt(i); + measureLabelsRearrange(); + } } void SpectrumAnalyzer::onMeasurementSelectionListChanged() { - // Clear all measurements in list - for (int i = 0; i < measurements_data.size(); i++) { - measurements_data[i]->setEnabled(false); - } - measurements_data.clear(); - measurements_gui.clear(); - - // Use the new list from MeasureSettings - auto newList = measure_settings->measurementSelection(); - for (int i = 0; i < newList.size(); i++) { - auto pMeasurement = measurement(newList[i].id(), - newList[i].channel_id()); - if (pMeasurement) { - pMeasurement->setEnabled(true); - measurements_data.push_back(pMeasurement); - measureCreateAndAppendGuiFrom(*pMeasurement); - } - } - measureLabelsRearrange(); -} - -void SpectrumAnalyzer::measureCreateAndAppendGuiFrom(const MeasurementData& - measurement) -{ - std::shared_ptr p; - - switch(measurement.unitType()) { - - case MeasurementData::DECIBELS: - p = std::make_shared(); - break; - case MeasurementData::DECIBELS_TO_CARRIER: - p = std::make_shared(); - break; - case MeasurementData::DIMENSIONLESS: - p = std::make_shared(); - break; - default: - break; - } - if (p) - measurements_gui.push_back(p); + // Clear all measurements in list + for(int i = 0; i < measurements_data.size(); i++) { + measurements_data[i]->setEnabled(false); + } + measurements_data.clear(); + measurements_gui.clear(); + + // Use the new list from MeasureSettings + auto newList = measure_settings->measurementSelection(); + for(int i = 0; i < newList.size(); i++) { + auto pMeasurement = measurement(newList[i].id(), newList[i].channel_id()); + if(pMeasurement) { + pMeasurement->setEnabled(true); + measurements_data.push_back(pMeasurement); + measureCreateAndAppendGuiFrom(*pMeasurement); + } + } + measureLabelsRearrange(); } -void SpectrumAnalyzer::measureLabelsRearrange() +void SpectrumAnalyzer::measureCreateAndAppendGuiFrom(const MeasurementData &measurement) { - QWidget *container = measure_panel_ui->measurements-> - findChild("container"); + std::shared_ptr p; - if (container) { - measure_panel_ui->measurements->layout()->removeWidget(container); - delete container; - } + switch(measurement.unitType()) { - container = new QWidget(); - container->setObjectName("container"); - if (!measure_panel_ui->measurements->layout()) { - QVBoxLayout *measurementsLayout = new - QVBoxLayout(measure_panel_ui->measurements); - measurementsLayout->addWidget(container); - measurementsLayout->setContentsMargins(0, 0, 0, 0); - } else { - measure_panel_ui->measurements->layout()->addWidget(container); - } - - QGridLayout *gLayout = new QGridLayout(container); - - gLayout->setContentsMargins(0, 0, 0, 0); - gLayout->setVerticalSpacing(5); - gLayout->setHorizontalSpacing(5); - int max_rows = 4; - int nb_meas_added = 0; + case MeasurementData::DECIBELS: + p = std::make_shared(); + break; + case MeasurementData::DECIBELS_TO_CARRIER: + p = std::make_shared(); + break; + case MeasurementData::DIMENSIONLESS: + p = std::make_shared(); + break; + default: + break; + } + if(p) + measurements_gui.push_back(p); +} - for (int i = 0; i < measurements_data.size(); i++) { +void SpectrumAnalyzer::measureLabelsRearrange() +{ + QWidget *container = measure_panel_ui->measurements->findChild("container"); - int channel = measurements_data[i]->channel(); - if (channel >= m_adc_nb_channels + nb_ref_channels) { - continue; + if(container) { + measure_panel_ui->measurements->layout()->removeWidget(container); + delete container; } - ChannelWidget *chn_widget = getChannelWidgetAt(channel); - if (!chn_widget->enableButton()->isChecked()) { - continue; + container = new QWidget(); + container->setObjectName("container"); + if(!measure_panel_ui->measurements->layout()) { + QVBoxLayout *measurementsLayout = new QVBoxLayout(measure_panel_ui->measurements); + measurementsLayout->addWidget(container); + measurementsLayout->setContentsMargins(0, 0, 0, 0); + } else { + measure_panel_ui->measurements->layout()->addWidget(container); } - QLabel *name = new QLabel(); - QLabel *value = new QLabel(); + QGridLayout *gLayout = new QGridLayout(container); + + gLayout->setContentsMargins(0, 0, 0, 0); + gLayout->setVerticalSpacing(5); + gLayout->setHorizontalSpacing(5); + int max_rows = 4; + int nb_meas_added = 0; + + for(int i = 0; i < measurements_data.size(); i++) { + + int channel = measurements_data[i]->channel(); + if(channel >= m_adc_nb_channels + nb_ref_channels) { + continue; + } + + ChannelWidget *chn_widget = getChannelWidgetAt(channel); + if(!chn_widget->enableButton()->isChecked()) { + continue; + } + QLabel *name = new QLabel(); + QLabel *value = new QLabel(); - int row = nb_meas_added % max_rows; - int col = nb_meas_added / max_rows; + int row = nb_meas_added % max_rows; + int col = nb_meas_added / max_rows; - gLayout->addWidget(name, row, 2 * col); + gLayout->addWidget(name, row, 2 * col); - QHBoxLayout *value_layout = new QHBoxLayout(); - value_layout->setContentsMargins(0, 0, 10, 0); - value_layout->addWidget(value); - gLayout->addLayout(value_layout, row, 2 * col + 1); + QHBoxLayout *value_layout = new QHBoxLayout(); + value_layout->setContentsMargins(0, 0, 10, 0); + value_layout->addWidget(value); + gLayout->addLayout(value_layout, row, 2 * col + 1); - measurements_gui[i]->init(name, value); - double pb_atten = 1; - measurements_gui[i]->update(*(measurements_data[i]), - pb_atten); - measurements_gui[i]->setLabelsColor(fft_plot->getLineColor(channel)); + measurements_gui[i]->init(name, value); + double pb_atten = 1; + measurements_gui[i]->update(*(measurements_data[i]), pb_atten); + measurements_gui[i]->setLabelsColor(fft_plot->getLineColor(channel)); - nb_meas_added++; - } + nb_meas_added++; + } } QList> SpectrumAnalyzer::measurements(int chnIdx) { - //POATE O SA POT PUNE DIRECT MEASURE OF CHANNALE, IN LOC DE FCT ASTA?? - Measure *measure = measureOfChannel(chnIdx); + // POATE O SA POT PUNE DIRECT MEASURE OF CHANNALE, IN LOC DE FCT ASTA?? + Measure *measure = measureOfChannel(chnIdx); - if (measure) - return measure->measurments(); - else - return QList>(); + if(measure) + return measure->measurments(); + else + return QList>(); } -Measure* SpectrumAnalyzer::measureOfChannel(int chnIdx) const +Measure *SpectrumAnalyzer::measureOfChannel(int chnIdx) const { - Measure *measure = nullptr; + Measure *measure = nullptr; - auto it = std::find_if(d_measureObjs.begin(), d_measureObjs.end(), - [&](Measure *m) { return m->channel() == chnIdx; }); - if (it != d_measureObjs.end()) - measure = *it; + auto it = std::find_if(d_measureObjs.begin(), d_measureObjs.end(), + [&](Measure *m) { return m->channel() == chnIdx; }); + if(it != d_measureObjs.end()) + measure = *it; - return measure; + return measure; } int SpectrumAnalyzer::activeMeasurementsCount(int chnIdx) { - int count = -1; - Measure *measure = measureOfChannel(chnIdx); + int count = -1; + Measure *measure = measureOfChannel(chnIdx); - if (measure) - count = measure->activeMeasurementsCount(); + if(measure) + count = measure->activeMeasurementsCount(); - return count; + return count; } -bool SpectrumAnalyzer::measurementsEnabled() -{ - return d_measurementsEnabled; -} +bool SpectrumAnalyzer::measurementsEnabled() { return d_measurementsEnabled; } void SpectrumAnalyzer::setMeasuremensEnabled(bool en) { - d_measurementsEnabled = en; + d_measurementsEnabled = en; - if (en) { - ui->btnMeasure->setEnabled(true); - } else { - if (ui->btnMeasure->isChecked()) - ui->btnMeasure->setChecked(false); + if(en) { + ui->btnMeasure->setEnabled(true); + } else { + if(ui->btnMeasure->isChecked()) + ui->btnMeasure->setChecked(false); - ui->btnMeasure->setEnabled(false); + ui->btnMeasure->setEnabled(false); - menuOrder.removeOne(ui->btnMeasure); - } + menuOrder.removeOne(ui->btnMeasure); + } } void SpectrumAnalyzer::computeMeasurementsForChannel(unsigned int chnIdx, unsigned int sampleRate) { - if (chnIdx >= d_measureObjs.size()) { - return; - } + if(chnIdx >= d_measureObjs.size()) { + return; + } - Measure *measure = d_measureObjs[chnIdx]; - measure->setSampleRate(sampleRate); - measure->measure(); + Measure *measure = d_measureObjs[chnIdx]; + measure->setSampleRate(sampleRate); + measure->measure(); - Q_EMIT measurementsAvailable(); + Q_EMIT measurementsAvailable(); } void SpectrumAnalyzer::measure() { - for (int i = 0; i < d_measureObjs.size(); i++) { - Measure *measure = d_measureObjs[i]; - if (measure->activeMeasurementsCount() > 0) { - measure->setSampleRate(fft_plot->sampleRate()); - measure->measure(); + for(int i = 0; i < d_measureObjs.size(); i++) { + Measure *measure = d_measureObjs[i]; + if(measure->activeMeasurementsCount() > 0) { + measure->setSampleRate(fft_plot->sampleRate()); + measure->measure(); + } } - } } void SpectrumAnalyzer::onNewDataReceived() { - int ref_idx = 0; - for (int i = 0; i < d_measureObjs.size(); i++) { - Measure *measure = d_measureObjs[i]; - int chn = measure->channel(); - if (fft_plot->isReferenceWaveform(chn)) { - size_t curve_size = fft_plot->getCurveSize(chn); - measure->setDataSource(fft_plot->getRef_data()[ref_idx], - curve_size / 2); - ref_idx++; - } - else { - int64_t numPoints = fft_plot->getNumPoints() / 2; - std::vector data = fft_plot->getOrginal_data(); - std::vector scale_factor = fft_plot->getScaleFactor(); - - //int count = fft_plot->countReferenceWaveform(chn); - //chn = chn - count; - for (int s = 0; s < numPoints; s++) { - data[chn][s] = sqrt(data[chn][s]) * scale_factor[chn] / numPoints; - } - measure->setDataSource(data[chn], numPoints); - } - measure->setSampleRate(sample_rate); - measure->measure(); - } + int ref_idx = 0; + for(int i = 0; i < d_measureObjs.size(); i++) { + Measure *measure = d_measureObjs[i]; + int chn = measure->channel(); + if(fft_plot->isReferenceWaveform(chn)) { + size_t curve_size = fft_plot->getCurveSize(chn); + measure->setDataSource(fft_plot->getRef_data()[ref_idx], curve_size / 2); + ref_idx++; + } else { + int64_t numPoints = fft_plot->getNumPoints() / 2; + std::vector data = fft_plot->getOrginal_data(); + std::vector scale_factor = fft_plot->getScaleFactor(); + + // int count = fft_plot->countReferenceWaveform(chn); + // chn = chn - count; + for(int s = 0; s < numPoints; s++) { + data[chn][s] = sqrt(data[chn][s]) * scale_factor[chn] / numPoints; + } + measure->setDataSource(data[chn], numPoints); + } + measure->setSampleRate(sample_rate); + measure->measure(); + } - Q_EMIT measurementsAvailable(); + Q_EMIT measurementsAvailable(); } -void SpectrumAnalyzer::onMeasuremetsAvailable() -{ - measureUpdateValues(); -} +void SpectrumAnalyzer::onMeasuremetsAvailable() { measureUpdateValues(); } void SpectrumAnalyzer::measureUpdateValues() { - for (int i = 0; i < measurements_data.size(); i++) { - int channel = measurements_data[i]->channel(); - ChannelWidget *chn_widget = getChannelWidgetAt(channel); - if (!chn_widget->enableButton()->isChecked()) { - continue; + for(int i = 0; i < measurements_data.size(); i++) { + int channel = measurements_data[i]->channel(); + ChannelWidget *chn_widget = getChannelWidgetAt(channel); + if(!chn_widget->enableButton()->isChecked()) { + continue; + } + measurements_gui[i]->update(*(measurements_data[i]), + 1.0f); // de modificat scale-ul } - measurements_gui[i]->update(*(measurements_data[i]), - 1.0f); // de modificat scale-ul - } } -void SpectrumAnalyzer::on_boxMeasure_toggled(bool checked) { - if (checked) { - update_measure_for_channel(crt_channel_id); - } else { - if (ui->btnMeasure->isChecked()) - ui->btnMeasure->setChecked(false); - menuOrder.removeOne(ui->btnMeasure); - } - measurePanel->setVisible(checked); +void SpectrumAnalyzer::on_boxMeasure_toggled(bool checked) +{ + if(checked) { + update_measure_for_channel(crt_channel_id); + } else { + if(ui->btnMeasure->isChecked()) + ui->btnMeasure->setChecked(false); + menuOrder.removeOne(ui->btnMeasure); + } + measurePanel->setVisible(checked); } #endif void SpectrumAnalyzer::on_btnAddRef_toggled(bool checked) { - triggerRightMenuToggle( - static_cast(QObject::sender()), checked); + triggerRightMenuToggle(static_cast(QObject::sender()), checked); } void SpectrumAnalyzer::on_btnBrowseFile_clicked() { - QString fileName = QFileDialog::getOpenFileName(this, - tr("Export"), "", tr("Comma-separated values files (*.csv);;" - "Tab-delimited values files (*.txt)"), - nullptr, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); + QString fileName = QFileDialog::getOpenFileName( + this, tr("Export"), "", + tr("Comma-separated values files (*.csv);;" + "Tab-delimited values files (*.txt)"), + nullptr, (m_useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); FileManager fm("Spectrum Analyzer"); @@ -1576,7 +1482,7 @@ void SpectrumAnalyzer::on_btnBrowseFile_clicked() try { fm.open(fileName, FileManager::IMPORT); - for (int i = 0; i < fm.getNrOfChannels(); ++i) { + for(int i = 0; i < fm.getNrOfChannels(); ++i) { /* Amplitude CHX UNIT => mid(10, 3) strip CHX from column name */ QString chn_name = fm.getColumnName(i).mid(10, 3); chn_name = (chn_name == "") ? "CH" + i : chn_name; @@ -1584,14 +1490,14 @@ void SpectrumAnalyzer::on_btnBrowseFile_clicked() } QVector> data = fm.read(); - for (int i = 0; i < data.size(); ++i) { + for(int i = 0; i < data.size(); ++i) { import_data.push_back(data[i]); } QStringList channelDetails = fm.getAdditionalInformation(); - for (int i = 0; i < channelDetails.size() / 3; ++i) { + for(int i = 0; i < channelDetails.size() / 3; ++i) { QStringList currentChannelDetails; - for (int j = 0; j < 3; ++j) { + for(int j = 0; j < 3; ++j) { currentChannelDetails.push_back(channelDetails[i * 3 + j]); } importedChannelDetails.push_back(currentChannelDetails); @@ -1603,8 +1509,7 @@ void SpectrumAnalyzer::on_btnBrowseFile_clicked() ui->btnImport->setEnabled(true); ui->importSettings->setEnabled(true); - - } catch (FileManagerException &e) { + } catch(FileManagerException &e) { ui->fileLineEdit->setText(e.what()); ui->fileLineEdit->setToolTip(""); ui->btnImport->setDisabled(true); @@ -1617,8 +1522,8 @@ void SpectrumAnalyzer::on_btnImport_clicked() QMap import_map = ui->importSettings->getExportConfig(); auto keys = import_map.keys(); - for (int key : qAsConst(keys)) { - if (import_map[key]) { + for(int key : qAsConst(keys)) { + if(import_map[key]) { add_ref_waveform(key); } } @@ -1631,35 +1536,28 @@ void SpectrumAnalyzer::cursor_panel_init() setDynamicProperty(cr_ui->btnLockHorizontal, "use_icon", true); setDynamicProperty(cr_ui->btnLockVertical, "use_icon", true); - connect(cr_ui->btnLockHorizontal, &QPushButton::toggled, - fft_plot, &FftDisplayPlot::setHorizCursorsLocked); - connect(cr_ui->btnLockVertical, &QPushButton::toggled, - fft_plot, &FftDisplayPlot::setVertCursorsLocked); + connect(cr_ui->btnLockHorizontal, &QPushButton::toggled, fft_plot, &FftDisplayPlot::setHorizCursorsLocked); + connect(cr_ui->btnLockVertical, &QPushButton::toggled, fft_plot, &FftDisplayPlot::setVertCursorsLocked); - connect(cr_ui->btnLockHorizontal, &QPushButton::toggled, - waterfall_plot, &WaterfallDisplayPlot::setHorizCursorsLocked); - connect(cr_ui->btnLockVertical, &QPushButton::toggled, - waterfall_plot, &WaterfallDisplayPlot::setVertCursorsLocked); + connect(cr_ui->btnLockHorizontal, &QPushButton::toggled, waterfall_plot, + &WaterfallDisplayPlot::setHorizCursorsLocked); + connect(cr_ui->btnLockVertical, &QPushButton::toggled, waterfall_plot, + &WaterfallDisplayPlot::setVertCursorsLocked); cursorsPositionButton = new CustomPlotPositionButton(cr_ui->posSelect); - connect(cr_ui->hCursorsEnable, SIGNAL(toggled(bool)), - fft_plot, SLOT(setVertCursorsEnabled(bool))); - connect(cr_ui->vCursorsEnable, SIGNAL(toggled(bool)), - fft_plot, SLOT(setHorizCursorsEnabled(bool))); - connect(cr_ui->hCursorsEnable, SIGNAL(toggled(bool)), - waterfall_plot, SLOT(setVertCursorsEnabled(bool))); - connect(cr_ui->vCursorsEnable, SIGNAL(toggled(bool)), - waterfall_plot, SLOT(setHorizCursorsEnabled(bool))); + connect(cr_ui->hCursorsEnable, SIGNAL(toggled(bool)), fft_plot, SLOT(setVertCursorsEnabled(bool))); + connect(cr_ui->vCursorsEnable, SIGNAL(toggled(bool)), fft_plot, SLOT(setHorizCursorsEnabled(bool))); + connect(cr_ui->hCursorsEnable, SIGNAL(toggled(bool)), waterfall_plot, SLOT(setVertCursorsEnabled(bool))); + connect(cr_ui->vCursorsEnable, SIGNAL(toggled(bool)), waterfall_plot, SLOT(setHorizCursorsEnabled(bool))); - connect(cr_ui->btnNormalTrack, &QPushButton::toggled, - this, &SpectrumAnalyzer::toggleCursorsMode); + connect(cr_ui->btnNormalTrack, &QPushButton::toggled, this, &SpectrumAnalyzer::toggleCursorsMode); cr_ui->horizontalSlider->setMaximum(100); cr_ui->horizontalSlider->setMinimum(0); cr_ui->horizontalSlider->setSingleStep(1); - connect(cr_ui->horizontalSlider, &QSlider::valueChanged, [=](int value){ + connect(cr_ui->horizontalSlider, &QSlider::valueChanged, [=](int value) { cr_ui->transLabel->setText(tr("Transparency ") + QString::number(value) + "%"); fft_plot->setCursorReadoutsTransparency(value); waterfall_plot->setCursorReadoutsTransparency(value); @@ -1667,10 +1565,10 @@ void SpectrumAnalyzer::cursor_panel_init() cr_ui->horizontalSlider->setSliderPosition(0); connect(cursorsPositionButton, &CustomPlotPositionButton::positionChanged, - [=](CustomPlotPositionButton::ReadoutsPosition position){ - fft_plot->moveCursorReadouts(position); - waterfall_plot->moveCursorReadouts(position); - }); + [=](CustomPlotPositionButton::ReadoutsPosition position) { + fft_plot->moveCursorReadouts(position); + waterfall_plot->moveCursorReadouts(position); + }); // add cursor lock botween waterfall and fft plot @@ -1694,7 +1592,7 @@ void SpectrumAnalyzer::cursor_panel_init() cr_ui->verticalLayout_2->addItem(horizontalLockLayout); horizontalLockLayout->addWidget(new QLabel(tr("Sync plots cursors"), cr_ui->scrollAreaWidgetContents)); - horizontalLockLayout->addSpacerItem(new QSpacerItem(0,0, QSizePolicy::Expanding, QSizePolicy::Fixed)); + horizontalLockLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed)); horizontalLockLayout->addWidget(btnSyncPlotCursors); connectCursorHandles(); @@ -1706,15 +1604,16 @@ void SpectrumAnalyzer::connectZoomers() fft_plot->getZoomer()->zoom(0); waterfall_plot->getZoomer()->zoom(0); - connect(fft_plot->getZoomer(), &QwtPlotZoomer::zoomed, this, [=](const QRectF& rect){ + connect(fft_plot->getZoomer(), &QwtPlotZoomer::zoomed, this, [=](const QRectF &rect) { auto waterfall_zoomer = waterfall_plot->getZoomer(); - auto const new_rect = QRectF(rect.left(), waterfall_zoomer->zoomBase().top(), rect.width(), waterfall_zoomer->zoomBase().height()); + auto const new_rect = QRectF(rect.left(), waterfall_zoomer->zoomBase().top(), rect.width(), + waterfall_zoomer->zoomBase().height()); waterfall_zoomer->blockSignals(true); fft_plot->getZoomer()->blockSignals(true); // if fft was zoomed out - if (waterfall_zoomer->zoomRectIndex() > fft_plot->getZoomer()->zoomRectIndex()) { + if(waterfall_zoomer->zoomRectIndex() > fft_plot->getZoomer()->zoomRectIndex()) { auto wf_stack = waterfall_zoomer->zoomStack(); auto fft_stack = fft_plot->getZoomer()->zoomStack(); @@ -1724,7 +1623,7 @@ void SpectrumAnalyzer::connectZoomers() fft_plot->getZoomer()->setZoomStack(fft_stack, fft_plot->getZoomer()->zoomRectIndex()); // if fft was zoomed in - } else if (waterfall_zoomer->zoomRectIndex() < fft_plot->getZoomer()->zoomRectIndex()) { + } else if(waterfall_zoomer->zoomRectIndex() < fft_plot->getZoomer()->zoomRectIndex()) { auto wf_stack = waterfall_zoomer->zoomStack(); wf_stack.push(new_rect); @@ -1735,26 +1634,27 @@ void SpectrumAnalyzer::connectZoomers() fft_plot->getZoomer()->blockSignals(false); }); - connect(waterfall_plot->getZoomer(), &QwtPlotZoomer::zoomed, this, [=](const QRectF& rect){ + connect(waterfall_plot->getZoomer(), &QwtPlotZoomer::zoomed, this, [=](const QRectF &rect) { auto fft_zoomer = fft_plot->getZoomer(); - auto const new_rect = QRectF(rect.left(), fft_zoomer->zoomBase().top(), rect.width(), fft_zoomer->zoomBase().height()); + auto const new_rect = QRectF(rect.left(), fft_zoomer->zoomBase().top(), rect.width(), + fft_zoomer->zoomBase().height()); fft_zoomer->blockSignals(true); waterfall_plot->getZoomer()->blockSignals(true); - // if waterfall was zoomed out - if (fft_zoomer->zoomRectIndex() > waterfall_plot->getZoomer()->zoomRectIndex()) { + if(fft_zoomer->zoomRectIndex() > waterfall_plot->getZoomer()->zoomRectIndex()) { auto fft_stack = fft_zoomer->zoomStack(); auto wf_stack = waterfall_plot->getZoomer()->zoomStack(); fft_stack.pop(); wf_stack.pop(); fft_zoomer->setZoomStack(fft_stack, fft_zoomer->zoomRectIndex() - 1); - waterfall_plot->getZoomer()->setZoomStack(wf_stack, waterfall_plot->getZoomer()->zoomRectIndex()); + waterfall_plot->getZoomer()->setZoomStack(wf_stack, + waterfall_plot->getZoomer()->zoomRectIndex()); // if waterfall was zoomed in - } else if (fft_zoomer->zoomRectIndex() < waterfall_plot->getZoomer()->zoomRectIndex()){ + } else if(fft_zoomer->zoomRectIndex() < waterfall_plot->getZoomer()->zoomRectIndex()) { auto fft_stack = fft_zoomer->zoomStack(); fft_stack.push(new_rect); fft_zoomer->setZoomStack(fft_stack, fft_zoomer->zoomRectIndex() + 1); @@ -1770,14 +1670,14 @@ void SpectrumAnalyzer::waterfallToggled(bool visible) waterfallDocker->setVisible(visible); waterfall_visible = visible; - if (isIioManagerStarted() && isRunning()) { - if (visible) { - for (size_t i = 0; i < m_adc_nb_channels; i++) { + if(isIioManagerStarted() && isRunning()) { + if(visible) { + for(size_t i = 0; i < m_adc_nb_channels; i++) { iio->start(waterfall_ids[i]); Q_EMIT waterfall_plot->resetWaterfallData(); } } else { - for (int i = 0; i < channels.size(); i++) { + for(int i = 0; i < channels.size(); i++) { iio->stop(waterfall_ids[i]); } } @@ -1796,9 +1696,9 @@ void SpectrumAnalyzer::updateVisibleCursorHandles() bool wf_toggle = cursors_enabled; bool fft_toggle = cursors_enabled; - if (wf_pos <= fft_pos && !floatingDockers && waterfall_visible && cursors_enabled) { + if(wf_pos <= fft_pos && !floatingDockers && waterfall_visible && cursors_enabled) { wf_toggle = !sync_toggled; - } else if (fft_pos <= wf_pos && !floatingDockers && waterfall_visible && cursors_enabled) { + } else if(fft_pos <= wf_pos && !floatingDockers && waterfall_visible && cursors_enabled) { fft_toggle = !sync_toggled; } @@ -1810,29 +1710,28 @@ void SpectrumAnalyzer::updateVisibleCursorHandles() void SpectrumAnalyzer::connectCursorHandles() { - if (!btnSyncPlotCursors) return; + if(!btnSyncPlotCursors) + return; - connect(btnSyncPlotCursors, &QPushButton::toggled, this, [=](bool toggled){ - updateVisibleCursorHandles(); - }); + connect(btnSyncPlotCursors, &QPushButton::toggled, this, [=](bool toggled) { updateVisibleCursorHandles(); }); - connect(fft_plot->d_hCursorHandle1, &PlotLineHandleH::positionChanged, this, [=](int pos){ - if (btnSyncPlotCursors->isChecked()) + connect(fft_plot->d_hCursorHandle1, &PlotLineHandleH::positionChanged, this, [=](int pos) { + if(btnSyncPlotCursors->isChecked()) waterfall_plot->d_hCursorHandle1->setPosition(pos); }); - connect(fft_plot->d_hCursorHandle2, &PlotLineHandleH::positionChanged, this, [=](int pos){ - if (btnSyncPlotCursors->isChecked()) + connect(fft_plot->d_hCursorHandle2, &PlotLineHandleH::positionChanged, this, [=](int pos) { + if(btnSyncPlotCursors->isChecked()) waterfall_plot->d_hCursorHandle2->setPosition(pos); }); - connect(waterfall_plot->d_hCursorHandle1, &PlotLineHandleH::positionChanged, this, [=](int pos){ - if (btnSyncPlotCursors->isChecked()) + connect(waterfall_plot->d_hCursorHandle1, &PlotLineHandleH::positionChanged, this, [=](int pos) { + if(btnSyncPlotCursors->isChecked()) fft_plot->d_hCursorHandle1->setPosition(pos); }); - connect(waterfall_plot->d_hCursorHandle2, &PlotLineHandleH::positionChanged, this, [=](int pos){ - if (btnSyncPlotCursors->isChecked()) + connect(waterfall_plot->d_hCursorHandle2, &PlotLineHandleH::positionChanged, this, [=](int pos) { + if(btnSyncPlotCursors->isChecked()) fft_plot->d_hCursorHandle2->setPosition(pos); }); } @@ -1842,32 +1741,29 @@ void SpectrumAnalyzer::toggleCursorsMode(bool toggled) cr_ui->hCursorsEnable->setEnabled(toggled); cr_ui->vCursorsEnable->setEnabled(toggled); - if (toggled) { + if(toggled) { fft_plot->setVertCursorsEnabled(hCursorsEnabled); fft_plot->setHorizCursorsEnabled(vCursorsEnabled); -// cursor_readouts_ui->TimeCursors->setVisible(vCursorsEnabled); -// cursor_readouts_ui->VoltageCursors->setVisible(hCursorsEnabled); + // cursor_readouts_ui->TimeCursors->setVisible(vCursorsEnabled); + // cursor_readouts_ui->VoltageCursors->setVisible(hCursorsEnabled); } else { hCursorsEnabled = cr_ui->hCursorsEnable->isChecked(); vCursorsEnabled = cr_ui->vCursorsEnable->isChecked(); fft_plot->setVertCursorsEnabled(true); fft_plot->setHorizCursorsEnabled(true); -// cursor_readouts_ui->TimeCursors->setVisible(true); -// cursor_readouts_ui->VoltageCursors->setVisible(true); + // cursor_readouts_ui->TimeCursors->setVisible(true); + // cursor_readouts_ui->VoltageCursors->setVisible(true); } cr_ui->btnLockVertical->setEnabled(toggled); fft_plot->trackModeEnabled(toggled); } -void SpectrumAnalyzer::onCursorReadoutsChanged(struct cursorReadoutsText data) -{ - fillCursorReadouts(data); -} +void SpectrumAnalyzer::onCursorReadoutsChanged(struct cursorReadoutsText data) { fillCursorReadouts(data); } -void SpectrumAnalyzer::fillCursorReadouts(const struct cursorReadoutsText& data) +void SpectrumAnalyzer::fillCursorReadouts(const struct cursorReadoutsText &data) { - //needs to be filled when measure ui is added + // needs to be filled when measure ui is added // cursor_readouts_ui->cursorT1->setText(data.t1); // cursor_readouts_ui->cursorT2->setText(data.t2); // cursor_readouts_ui->timeDelta->setText(data.tDelta); @@ -1880,17 +1776,17 @@ void SpectrumAnalyzer::fillCursorReadouts(const struct cursorReadoutsText& data) QString SpectrumAnalyzer::getReferenceChannelName() const { int current = 1; - for (; current <= MAX_REF_CHANNELS; ++current) { + for(; current <= MAX_REF_CHANNELS; ++current) { bool isOk = true; - for (const auto &ref_channel : referenceChannels) { + for(const auto &ref_channel : referenceChannels) { QString shortName = ref_channel->shortName(); int channel_counter = shortName.midRef(shortName.size() - 1).toInt(); - if (current == channel_counter) { + if(current == channel_counter) { isOk = false; break; } } - if (isOk) { + if(isOk) { return QString("REF %1").arg(current); } } @@ -1898,18 +1794,18 @@ QString SpectrumAnalyzer::getReferenceChannelName() const return QString("REF %1").arg(current); } -void SpectrumAnalyzer::setYAxisUnit(const QString& unit) +void SpectrumAnalyzer::setYAxisUnit(const QString &unit) { - if (unit == "dBFS" || unit == "dBu" || unit == "dBV") { + if(unit == "dBFS" || unit == "dBu" || unit == "dBV") { fft_plot->setLeftVertAxisUnit("dB"); - } else if (unit == "Vpeak" || unit == "Vrms" || unit == "V/√Hz") { + } else if(unit == "Vpeak" || unit == "Vrms" || unit == "V/√Hz") { fft_plot->setLeftVertAxisUnit("V"); } } void SpectrumAnalyzer::add_ref_waveform(QVector xData, QVector yData) { - if (nb_ref_channels == MAX_REF_CHANNELS) { + if(nb_ref_channels == MAX_REF_CHANNELS) { return; } @@ -1923,33 +1819,28 @@ void SpectrumAnalyzer::add_ref_waveform(QVector xData, QVector y channelWidget->setShortName(qname); channelWidget->nameButton()->setText(channelWidget->shortName()); channelWidget->setReferenceChannel(true); - channelWidget->deleteButton()->setProperty( - "curve_name", QVariant(qname)); + channelWidget->deleteButton()->setProperty("curve_name", QVariant(qname)); settings_group->addButton(channelWidget->menuButton()); channels_group->addButton(channelWidget->nameButton()); referenceChannels.push_back(channelWidget); - connect(channelWidget, &ChannelWidget::menuToggled, - this, &SpectrumAnalyzer::onChannelSettingsToggled); - connect(channelWidget, &ChannelWidget::selected, - this, &SpectrumAnalyzer::onChannelSelected); - connect(channelWidget, &ChannelWidget::deleteClicked, - this, &SpectrumAnalyzer::onReferenceChannelDeleted); - connect(channelWidget, &ChannelWidget::enabled, - this, &SpectrumAnalyzer::onChannelEnabled); + connect(channelWidget, &ChannelWidget::menuToggled, this, &SpectrumAnalyzer::onChannelSettingsToggled); + connect(channelWidget, &ChannelWidget::selected, this, &SpectrumAnalyzer::onChannelSelected); + connect(channelWidget, &ChannelWidget::deleteClicked, this, &SpectrumAnalyzer::onReferenceChannelDeleted); + connect(channelWidget, &ChannelWidget::enabled, this, &SpectrumAnalyzer::onChannelEnabled); ui->channelsList->addWidget(channelWidget); /* Increase ref channels count */ nb_ref_channels++; - if (!ui->btnMarkers->isEnabled()) { + if(!ui->btnMarkers->isEnabled()) { QSignalBlocker(ui->btnMarkers); ui->btnMarkers->setEnabled(true); } - if (nb_ref_channels == MAX_REF_CHANNELS) { + if(nb_ref_channels == MAX_REF_CHANNELS) { ui->btnAddRef->hide(); } @@ -1965,7 +1856,7 @@ void SpectrumAnalyzer::add_ref_waveform(unsigned int chIdx) QVector xData; QVector yData; - for (int i = 0; i < import_data.size(); ++i) { + for(int i = 0; i < import_data.size(); ++i) { xData.push_back(import_data[i][0]); yData.push_back(import_data[i][chIdx + 1]); } @@ -1976,22 +1867,21 @@ void SpectrumAnalyzer::add_ref_waveform(unsigned int chIdx) #ifdef SPECTRAL_MSR void SpectrumAnalyzer::cleanUpMeasurementsBeforeChannelRemoval(int chnIdx) { - Measure *measure = measureOfChannel(chnIdx); - if (measure) { - int pos = d_measureObjs.indexOf(measure); - for (int i = pos + 1; i < d_measureObjs.size(); i++) { - d_measureObjs[i]->setChannel( - d_measureObjs[i]->channel() - 1); + Measure *measure = measureOfChannel(chnIdx); + if(measure) { + int pos = d_measureObjs.indexOf(measure); + for(int i = pos + 1; i < d_measureObjs.size(); i++) { + d_measureObjs[i]->setChannel(d_measureObjs[i]->channel() - 1); + } + d_measureObjs.removeOne(measure); + delete measure; } - d_measureObjs.removeOne(measure); - delete measure; - } } #endif void SpectrumAnalyzer::onReferenceChannelDeleted() { - if (nb_ref_channels - 1 < MAX_REF_CHANNELS) { + if(nb_ref_channels - 1 < MAX_REF_CHANNELS) { ui->btnAddRef->show(); } @@ -2004,17 +1894,16 @@ void SpectrumAnalyzer::onReferenceChannelDeleted() disable the measurements.*/ bool shouldDisable = true; - for (unsigned int i = 0; i < m_adc_nb_channels + nb_ref_channels; i++) { - ChannelWidget *cw = static_cast( - ui->channelsList->itemAt(i)->widget()); - if (curve_id == cw->id()) - continue; - if (cw->enableButton()->isChecked()) - shouldDisable = false; - } + for(unsigned int i = 0; i < m_adc_nb_channels + nb_ref_channels; i++) { + ChannelWidget *cw = static_cast(ui->channelsList->itemAt(i)->widget()); + if(curve_id == cw->id()) + continue; + if(cw->enableButton()->isChecked()) + shouldDisable = false; + } #ifdef SPECTRAL_MSR - if (shouldDisable) + if(shouldDisable) measure_settings->disableDisplayAll(); measure_settings->onChannelRemoved(channelWidget->id()); @@ -2028,20 +1917,17 @@ void SpectrumAnalyzer::onReferenceChannelDeleted() /* Check if there are other channel widgets that are enabled */ bool channelsEnabled = false; - referenceChannels.erase(std::find(referenceChannels.begin(), - referenceChannels.end(), - channelWidget)); + referenceChannels.erase(std::find(referenceChannels.begin(), referenceChannels.end(), channelWidget)); /* Update the id of the remaining channels */ int id = m_adc_nb_channels; - for (auto iter = referenceChannels.begin(); - iter != referenceChannels.end(); ++iter) { + for(auto iter = referenceChannels.begin(); iter != referenceChannels.end(); ++iter) { (*iter)->setId(id++); } nb_ref_channels--; - if (channelWidget->id() < crt_channel_id) { + if(channelWidget->id() < crt_channel_id) { crt_channel_id--; Q_EMIT selectedChannelChanged(crt_channel_id); @@ -2049,13 +1935,13 @@ void SpectrumAnalyzer::onReferenceChannelDeleted() update_measure_for_channel(crt_channel_id); #endif - } else if (channelWidget->id() == crt_channel_id) { - for (size_t i = 0; i < m_adc_nb_channels + nb_ref_channels; ++i) { + } else if(channelWidget->id() == crt_channel_id) { + for(size_t i = 0; i < m_adc_nb_channels + nb_ref_channels; ++i) { auto cw = getChannelWidgetAt(i); - if (cw == channelWidget) { + if(cw == channelWidget) { continue; } - if (cw->enableButton()->isChecked()) { + if(cw->enableButton()->isChecked()) { channelsEnabled = true; Q_EMIT selectedChannelChanged(0); @@ -2072,26 +1958,25 @@ void SpectrumAnalyzer::onReferenceChannelDeleted() break; } } - if (!channelsEnabled) { - crt_channel_id = 0; - Q_EMIT selectedChannelChanged(0); + if(!channelsEnabled) { + crt_channel_id = 0; + Q_EMIT selectedChannelChanged(0); } } - if (ui->btnMarkers->isChecked() && !channelsEnabled) { + if(ui->btnMarkers->isChecked() && !channelsEnabled) { ui->btnMarkers->setChecked(false); - menuButtonActions.removeAll(QPair - (ui->btnMarkers, true)); + menuButtonActions.removeAll(QPair(ui->btnMarkers, true)); menuOrder.removeAll(ui->btnMarkers); ui->btnMarkers->blockSignals(true); ui->btnMarkers->setDisabled(true); ui->btnMarkers->blockSignals(false); } - if (channelWidget->menuButton()->isChecked()) { + if(channelWidget->menuButton()->isChecked()) { channelWidget->menuButton()->setChecked(false); - menuButtonActions.removeAll(QPair - (static_cast(channelWidget->menuButton()), true)); + menuButtonActions.removeAll(QPair( + static_cast(channelWidget->menuButton()), true)); menuOrder.removeAll(static_cast(channelWidget->menuButton())); } @@ -2115,14 +2000,14 @@ void SpectrumAnalyzer::stop() void SpectrumAnalyzer::runStopToggled(bool checked) { - if (m_running == checked) { + if(m_running == checked) { return; } - if (checked) { - ResourceManager::open("m2k-adc",this); + if(checked) { + ResourceManager::open("m2k-adc", this); - if (iio) { + if(iio) { writeAllSettingsToHardware(); } @@ -2137,7 +2022,7 @@ void SpectrumAnalyzer::runStopToggled(bool checked) ResourceManager::close("m2k-adc"); } - if (!checked) { + if(!checked) { fft_plot->resetAverageHistory(); } fft_plot->startStop(checked); @@ -2150,37 +2035,30 @@ void SpectrumAnalyzer::build_gnuradio_block_chain() waterfall_plot->setPlotPosHalf(use_float_sink); auto window = SpectrumChannel::build_win(FftWinType::HAMMING, fft_size); - waterfall_sink = scopy::waterfall_sink::make(fft_size, - window, - 0, - m_max_sample_rate, - "Waterfall Plot", - m_adc_nb_channels, - waterfall_plot, - !use_float_sink); - - fft_sink = scopy::scope_sink_f::make(fft_size, m_max_sample_rate, - "Osc Frequency", m_adc_nb_channels, - (QObject *)fft_plot); + waterfall_sink = scopy::waterfall_sink::make(fft_size, window, 0, m_max_sample_rate, "Waterfall Plot", + m_adc_nb_channels, waterfall_plot, !use_float_sink); + + fft_sink = scopy::scope_sink_f::make(fft_size, m_max_sample_rate, "Osc Frequency", m_adc_nb_channels, + (QObject *)fft_plot); fft_sink->set_trigger_mode(TRIG_MODE_TAG, 0, "buffer_start"); waterfall_sink->set_trigger_mode(TRIG_MODE_TAG, 0, "buffer_start"); double samplingTime = sample_rate * fft_size; Preferences *p = Preferences::GetInstance(); double targetFps = p->get("general_plot_target_fps").toDouble(); - fft_sink->set_update_time(1.0/targetFps); - waterfall_sink->set_update_time(std::max(1/samplingTime, 1/targetFps)); + fft_sink->set_update_time(1.0 / targetFps); + waterfall_sink->set_update_time(std::max(1 / samplingTime, 1 / targetFps)); bool started = isIioManagerStarted(); - if (started) { + if(started) { iio->lock(); } bool canConvRawToVolts = m_m2k_analogin ? true : false; - if (canConvRawToVolts) { - for (size_t i = 0; i < m_adc_nb_channels; i++) { + if(canConvRawToVolts) { + for(size_t i = 0; i < m_adc_nb_channels; i++) { libm2k::analog::ANALOG_IN_CHANNEL chn = static_cast(i); fft_plot->setScaleFactor(i, m_m2k_analogin->getScalingFactor(chn)); } @@ -2189,9 +2067,8 @@ void SpectrumAnalyzer::build_gnuradio_block_chain() waterfall_ids = new iio_manager::port_id[m_adc_nb_channels]; fft_ids = new iio_manager::port_id[m_adc_nb_channels]; - for (size_t i = 0; i < m_adc_nb_channels; i++) { - auto fft = gnuradio::get_initial_sptr( - new fft_block(!use_float_sink, fft_size)); + for(size_t i = 0; i < m_adc_nb_channels; i++) { + auto fft = gnuradio::get_initial_sptr(new fft_block(!use_float_sink, fft_size)); auto ctm = gr::blocks::complex_to_mag_squared::make(1); // iio(i)->fft->ctm->fft_sink @@ -2199,7 +2076,7 @@ void SpectrumAnalyzer::build_gnuradio_block_chain() iio->connect(fft, 0, ctm, 0); iio->connect(ctm, 0, fft_sink, i); - if (use_float_sink) { + if(use_float_sink) { auto floatToComplex = gr::blocks::float_to_complex::make(); waterfall_ids[i] = iio->connect(floatToComplex, i, 0, true, fft_size); iio->connect(floatToComplex, 0, waterfall_sink, i); @@ -2212,7 +2089,7 @@ void SpectrumAnalyzer::build_gnuradio_block_chain() channels[i]->ctm_block = ctm; } - if (started) { + if(started) { iio->unlock(); } } @@ -2222,42 +2099,34 @@ void SpectrumAnalyzer::build_gnuradio_block_chain_no_ctx() waterfall_plot->setPlotPosHalf(use_float_sink); auto window = SpectrumChannel::build_win(FftWinType::HAMMING, fft_size); - waterfall_sink = scopy::waterfall_sink::make(fft_size, - window, - 0, - m_max_sample_rate, - "Waterfall Plot", - m_adc_nb_channels, - waterfall_plot); - - fft_sink = scopy::scope_sink_f::make(fft_size, m_max_sample_rate, - "Osc Frequency", m_adc_nb_channels, - (QObject *)fft_plot); + waterfall_sink = scopy::waterfall_sink::make(fft_size, window, 0, m_max_sample_rate, "Waterfall Plot", + m_adc_nb_channels, waterfall_plot); + + fft_sink = scopy::scope_sink_f::make(fft_size, m_max_sample_rate, "Osc Frequency", m_adc_nb_channels, + (QObject *)fft_plot); double samplingTime = sample_rate * fft_size; Preferences *p = Preferences::GetInstance(); double targetFps = p->get("general_plot_target_fps").toDouble(); - fft_sink->set_update_time(1.0/targetFps); - waterfall_sink->set_update_time(std::max(1/samplingTime, 1/targetFps)); + fft_sink->set_update_time(1.0 / targetFps); + waterfall_sink->set_update_time(std::max(1 / samplingTime, 1 / targetFps)); top_block = gr::make_top_block("spectrum_analyzer"); - for (size_t i = 0; i < m_adc_nb_channels; i++) { - auto fft = gnuradio::get_initial_sptr( - new fft_block(false, fft_size)); + for(size_t i = 0; i < m_adc_nb_channels; i++) { + auto fft = gnuradio::get_initial_sptr(new fft_block(false, fft_size)); auto ctm = gr::blocks::complex_to_mag_squared::make(1); - auto siggen = gr::analog::sig_source_f::make(m_max_sample_rate, - gr::analog::GR_SIN_WAVE, 5e6 + i * 5e6, 2048); - auto noise = gr::analog::fastnoise_source_f::make( - gr::analog::GR_GAUSSIAN, 1, 0, 8192); + auto siggen = + gr::analog::sig_source_f::make(m_max_sample_rate, gr::analog::GR_SIN_WAVE, 5e6 + i * 5e6, 2048); + auto noise = gr::analog::fastnoise_source_f::make(gr::analog::GR_GAUSSIAN, 1, 0, 8192); auto add = gr::blocks::add_ff::make(); - //siggen->| + // siggen->| // |->add->fft->ctm->fft_sink - //noise-->| + // noise-->| top_block->connect(siggen, 0, add, 0); top_block->connect(noise, 0, add, 1); top_block->connect(add, 0, fft, 0); @@ -2271,11 +2140,11 @@ void SpectrumAnalyzer::build_gnuradio_block_chain_no_ctx() void SpectrumAnalyzer::start_blockchain_flow() { - if (iio) { - for (size_t i = 0; i < m_adc_nb_channels; i++) { + if(iio) { + for(size_t i = 0; i < m_adc_nb_channels; i++) { iio->start(fft_ids[i]); - if (waterfall_visible) { + if(waterfall_visible) { iio->start(waterfall_ids[i]); Q_EMIT waterfall_plot->resetWaterfallData(); } @@ -2289,11 +2158,11 @@ void SpectrumAnalyzer::start_blockchain_flow() void SpectrumAnalyzer::stop_blockchain_flow() { - if (iio) { - for (size_t i = 0; i < m_adc_nb_channels; i++) { + if(iio) { + for(size_t i = 0; i < m_adc_nb_channels; i++) { iio->stop(fft_ids[i]); - if (waterfall_visible) { + if(waterfall_visible) { iio->stop(waterfall_ids[i]); waterfall_sink->reset(); } @@ -2303,19 +2172,17 @@ void SpectrumAnalyzer::stop_blockchain_flow() } } -void SpectrumAnalyzer::on_comboBox_type_currentIndexChanged(const QString& s) +void SpectrumAnalyzer::on_comboBox_type_currentIndexChanged(const QString &s) { auto it = std::find_if(avg_types.begin(), avg_types.end(), - [&](const std::pair& p) { - return p.first == s; - }); + [&](const std::pair &p) { return p.first == s; }); - if (it == avg_types.end()) { + if(it == avg_types.end()) { return; } const bool visible = ((*it).second != FftDisplayPlot::AverageType::SAMPLE); - if (!visible) { + if(!visible) { ui->spinBox_averaging->setValue(1); } ui->spinBox_averaging->setVisible(visible); @@ -2323,7 +2190,7 @@ void SpectrumAnalyzer::on_comboBox_type_currentIndexChanged(const QString& s) int crt_channel = channelIdOfOpenedSettings(); - if (crt_channel < 0) { + if(crt_channel < 0) { qDebug(CAT_M2K_SPECTRUM_ANALYZER) << "invalid channel ID for the opened Settings menu"; return; } @@ -2337,10 +2204,10 @@ void SpectrumAnalyzer::on_comboBox_type_currentIndexChanged(const QString& s) ui->btnApply->setVisible(visible); setCurrentAverageIndexLabel(crt_channel); - if (avg_type != channels[crt_channel]->averageType()) { + if(avg_type != channels[crt_channel]->averageType()) { channels[crt_channel]->setAverageType(avg_type); - if (channels[crt_channel]->canStoreAverageHistory()) { - if (ui->btnHistory->isChecked()) { + if(channels[crt_channel]->canStoreAverageHistory()) { + if(ui->btnHistory->isChecked()) { ui->spinBox_averaging->setMaximum(10000); } else { ui->spinBox_averaging->setMaximum(1000000); @@ -2351,38 +2218,36 @@ void SpectrumAnalyzer::on_comboBox_type_currentIndexChanged(const QString& s) } } -void SpectrumAnalyzer::on_comboBox_window_currentIndexChanged(const QString& s) +void SpectrumAnalyzer::on_comboBox_window_currentIndexChanged(const QString &s) { auto it = std::find_if(win_types.begin(), win_types.end(), - [&](const std::pair& p) { - return p.first == s; - }); + [&](const std::pair &p) { return p.first == s; }); - if (it == win_types.end()) { + if(it == win_types.end()) { return; } int crt_channel = channelIdOfOpenedSettings(); - if (crt_channel < 0) { + if(crt_channel < 0) { qDebug(CAT_M2K_SPECTRUM_ANALYZER) << "invalid channel ID for the opened Settings menu"; return; } - if (!channels[crt_channel]->fft_block) { + if(!channels[crt_channel]->fft_block) { return; } auto win_type = (*it).second; - if (win_type != channels[crt_channel]->fftWindow()) { + if(win_type != channels[crt_channel]->fftWindow()) { channels[crt_channel]->setFftWindow((*it).second, fft_size); } } void SpectrumAnalyzer::setWaterfallWindow(std::vector win, int channel_id) { - if (channel_id == waterfall_plot->getEnabledChannelID()) { + if(channel_id == waterfall_plot->getEnabledChannelID()) { waterfall_sink->set_fft_window(win); } } @@ -2391,14 +2256,14 @@ void SpectrumAnalyzer::on_comboBox_line_thickness_currentIndexChanged(int index) { int crt_channel = channelIdOfOpenedSettings(); - if (crt_channel < 0) { + if(crt_channel < 0) { qDebug(CAT_M2K_SPECTRUM_ANALYZER) << "invalid channel ID for the opened Settings menu"; return; } qreal width = 0.5 * (index + 1); - if (width != channels[crt_channel]->lineWidth()) { + if(width != channels[crt_channel]->lineWidth()) { channels[crt_channel]->setLinewidth(width); fft_plot->setLineWidth(crt_channel, width); fft_plot->replot(); @@ -2409,12 +2274,12 @@ void SpectrumAnalyzer::on_spinBox_averaging_valueChanged(int n) { int crt_channel = channelIdOfOpenedSettings(); - if (crt_channel < 0) { + if(crt_channel < 0) { qDebug(CAT_M2K_SPECTRUM_ANALYZER) << "invalid channel ID for the opened Settings menu"; return; } - if (n != channels[crt_channel]->averaging()) { + if(n != channels[crt_channel]->averaging()) { channels[crt_channel]->setAveraging(n); } } @@ -2423,8 +2288,7 @@ void SpectrumAnalyzer::onChannelSettingsToggled(bool en) { ChannelWidget *cw = static_cast(QObject::sender()); - triggerRightMenuToggle( - static_cast(cw->menuButton()), en); + triggerRightMenuToggle(static_cast(cw->menuButton()), en); } void SpectrumAnalyzer::updateChannelSettingsPanel(unsigned int id) @@ -2433,13 +2297,13 @@ void SpectrumAnalyzer::updateChannelSettingsPanel(unsigned int id) selected_ch_settings = id; - if (cw->isReferenceChannel()) { + if(cw->isReferenceChannel()) { ui->btnSnapshot->setText(tr("Export")); } else { ui->btnSnapshot->setText(tr("Snapshot")); } - if (id < m_adc_nb_channels) { + if(id < m_adc_nb_channels) { channel_sptr sc = channels.at(id); QString style = QString("border: 2px solid %1").arg(cw->color().name()); @@ -2467,9 +2331,9 @@ void SpectrumAnalyzer::updateChannelSettingsPanel(unsigned int id) ui->label_thickness->setVisible(true); auto it = std::find_if(avg_types.begin(), avg_types.end(), - [&](const std::pair& p) { - return p.second == sc->averageType(); - }); + [&](const std::pair &p) { + return p.second == sc->averageType(); + }); const bool visible = (sc->averageType() != FftDisplayPlot::AverageType::SAMPLE); ui->spinBox_averaging->setVisible(visible); @@ -2481,16 +2345,16 @@ void SpectrumAnalyzer::updateChannelSettingsPanel(unsigned int id) ui->btnHistory->setChecked(sc->isAverageHistoryEnabled()); ui->lbl_history->setVisible(history_visible); - if (it != avg_types.end()) { + if(it != avg_types.end()) { ui->comboBox_type->setCurrentText((*it).first); } - auto it2 = std::find_if(win_types.begin(), win_types.end(), - [&](const std::pair& p) { - return p.second == sc->fftWindow(); - }); + auto it2 = + std::find_if(win_types.begin(), win_types.end(), [&](const std::pair &p) { + return p.second == sc->fftWindow(); + }); - if (it2 != win_types.end()) { + if(it2 != win_types.end()) { ui->comboBox_window->setCurrentText((*it2).first); } @@ -2498,16 +2362,15 @@ void SpectrumAnalyzer::updateChannelSettingsPanel(unsigned int id) int gainIdx = (sc->getGainMode() == libm2k::analog::PLUS_MINUS_25V) ? 0 : 1; ui->cmbGainMode->setCurrentIndex(gainIdx); - int thicknessIdx = (int)(sc->lineWidth() / 0.5) - 1; - ui->comboBox_line_thickness->setCurrentIndex(thicknessIdx); + int thicknessIdx = (int)(sc->lineWidth() / 0.5) - 1; + ui->comboBox_line_thickness->setCurrentIndex(thicknessIdx); } else { QString style = QString("border: 2px solid %1").arg(cw->color().name()); ui->lineChannelSettingsTitle->setStyleSheet(style); ui->channelSettingsTitle->setText(cw->nameButton()->text()); - - if ((id - m_adc_nb_channels) < importedChannelDetails.size() && - importedChannelDetails[id - m_adc_nb_channels].size() == 3) { + if((id - m_adc_nb_channels) < importedChannelDetails.size() && + importedChannelDetails[id - m_adc_nb_channels].size() == 3) { ui->comboBox_type->setCurrentText(importedChannelDetails[id - m_adc_nb_channels][0]); ui->comboBox_window->setCurrentText(importedChannelDetails[id - m_adc_nb_channels][1]); ui->spinBox_averaging->setValue(importedChannelDetails[id - m_adc_nb_channels][2].toInt()); @@ -2527,33 +2390,30 @@ void SpectrumAnalyzer::updateChannelSettingsPanel(unsigned int id) ui->lbl_history->setVisible(false); ui->label_type->setVisible(false); - ui->comboBox_line_thickness->setDisabled(false); + ui->comboBox_line_thickness->setDisabled(false); - ui->label_type->setVisible(false); + ui->label_type->setVisible(false); ui->label_window->setVisible(false); ui->label_averaging->setVisible(false); ui->label_thickness->setVisible(false); } } - } -ChannelWidget * SpectrumAnalyzer::getChannelWidgetAt(unsigned int id) +ChannelWidget *SpectrumAnalyzer::getChannelWidgetAt(unsigned int id) { - for (int i = 0; i < channels.size(); ++i) { - if (channels.at(i).get()->widget()->id() == id) + for(int i = 0; i < channels.size(); ++i) { + if(channels.at(i).get()->widget()->id() == id) return channels.at(i).get()->widget(); } /* Also check if the id corresponds to one of the reference * channel widgets and get an iterator pointing to that widget */ - auto cwIter = std::find_if(referenceChannels.begin(), - referenceChannels.end(), - [&id](ChannelWidget *referenceChannelWidget){ - return referenceChannelWidget->id() == id; - }); + auto cwIter = std::find_if( + referenceChannels.begin(), referenceChannels.end(), + [&id](ChannelWidget *referenceChannelWidget) { return referenceChannelWidget->id() == id; }); - if (cwIter != referenceChannels.end()) { + if(cwIter != referenceChannels.end()) { return *cwIter; } @@ -2565,13 +2425,12 @@ void SpectrumAnalyzer::onChannelSelected(bool en) ChannelWidget *cw = static_cast(QObject::sender()); int chIdx = cw->id(); - if(crt_channel_id != chIdx) - { + if(crt_channel_id != chIdx) { crt_channel_id = chIdx; Q_EMIT selectedChannelChanged(chIdx); } - if (!cw->isReferenceChannel()) { + if(!cw->isReferenceChannel()) { const bool visible = (channels[crt_channel_id]->averageType() != FftDisplayPlot::AverageType::SAMPLE); setCurrentAverageIndexLabel(crt_channel_id); } else { @@ -2579,13 +2438,12 @@ void SpectrumAnalyzer::onChannelSelected(bool en) } fft_plot->bringCurveToFront(chIdx); - if (marker_menu_opened) { - triggerRightMenuToggle( - static_cast(ui->btnMarkers), en); + if(marker_menu_opened) { + triggerRightMenuToggle(static_cast(ui->btnMarkers), en); } #ifdef SPECTRAL_MSR - if (measurementsEnabled()) { + if(measurementsEnabled()) { update_measure_for_channel(chIdx); } #endif @@ -2596,23 +2454,20 @@ void SpectrumAnalyzer::updateMarkerMenu(unsigned int id) ChannelWidget *cw = getChannelWidgetAt(id); // Is this if branch required? - if (!ui->runSingleWidget->runButtonChecked()) { + if(!ui->runSingleWidget->runButtonChecked()) { fft_plot->replot(); } // Update markers settings menu based on current channel - if (cw->nameButton()->isChecked()) { + if(cw->nameButton()->isChecked()) { ui->labelMarkerSettingsTitle->setText(cw->fullName()); - QString stylesheet = QString("border: 2px solid %1" - ).arg(cw->color().name()); + QString stylesheet = QString("border: 2px solid %1").arg(cw->color().name()); ui->lineMarkerSettingsTitle->setStyleSheet(stylesheet); - marker_selector->blockSignals(true); - for (size_t i = 0; i < fft_plot->markerCount(id); i++) { - marker_selector->setButtonChecked(i, - fft_plot->markerEnabled(id, i)); + for(size_t i = 0; i < fft_plot->markerCount(id); i++) { + marker_selector->setButtonChecked(i, fft_plot->markerEnabled(id, i)); } marker_selector->blockSignals(false); @@ -2623,44 +2478,44 @@ void SpectrumAnalyzer::updateMarkerMenu(unsigned int id) bool SpectrumAnalyzer::isIioManagerStarted() const { - return iio->started() && (ui->runSingleWidget->singleButtonChecked() - || ui->runSingleWidget->runButtonChecked()); + return iio->started() && + (ui->runSingleWidget->singleButtonChecked() || ui->runSingleWidget->runButtonChecked()); } void SpectrumAnalyzer::onChannelEnabled(bool en) { ChannelWidget *cw = static_cast(QObject::sender()); - if (en) { + if(en) { fft_plot->AttachCurve(cw->id()); - if (!ui->btnMarkers->isEnabled()) { + if(!ui->btnMarkers->isEnabled()) { ui->btnMarkers->blockSignals(true); ui->btnMarkers->setEnabled(true); ui->btnMarkers->blockSignals(false); } bool shouldActivate = true; - if (cw->enableButton()->isChecked()) { - shouldActivate = false; + if(cw->enableButton()->isChecked()) { + shouldActivate = false; } - if (shouldActivate) { - //nu trebe asta - Q_EMIT selectedChannelChanged(cw->id()); + if(shouldActivate) { + // nu trebe asta + Q_EMIT selectedChannelChanged(cw->id()); #ifdef SPECTRAL_MSR - update_measure_for_channel(cw->id()); - measure_settings->activateDisplayAll(); + update_measure_for_channel(cw->id()); + measure_settings->activateDisplayAll(); #endif } } else { bool allDisabled = true; bool shouldDisable = true; - for (size_t i = 0; i < channels.size() + nb_ref_channels; i++) { + for(size_t i = 0; i < channels.size() + nb_ref_channels; i++) { ChannelWidget *cw = getChannelWidgetAt(i); - if (cw->enableButton()->isChecked()) { + if(cw->enableButton()->isChecked()) { cw->nameButton()->setChecked(true); allDisabled = false; shouldDisable = false; @@ -2669,28 +2524,27 @@ void SpectrumAnalyzer::onChannelEnabled(bool en) } #ifdef SPECTRAL_MSR - if (shouldDisable) { - measure_settings->disableDisplayAll(); + if(shouldDisable) { + measure_settings->disableDisplayAll(); } #endif - if (allDisabled) { + if(allDisabled) { QSignalBlocker(ui->btnMarkers); - if (!ui->btnSweep->isChecked()) { + if(!ui->btnSweep->isChecked()) { QSignalBlocker(ui->btnSettings); ui->btnSettings->setChecked(false); } ui->btnMarkers->setChecked(false); ui->btnMarkers->setDisabled(true); - menuButtonActions.removeAll(QPair - (ui->btnMarkers, false)); + menuButtonActions.removeAll(QPair(ui->btnMarkers, false)); menuOrder.removeAll(ui->btnMarkers); } fft_plot->DetachCurve(cw->id()); } - for (size_t i = 0; i < fft_plot->markerCount(cw->id()); i++) { - if (fft_plot->markerEnabled(cw->id(), i)) { + for(size_t i = 0; i < fft_plot->markerCount(cw->id()); i++) { + if(fft_plot->markerEnabled(cw->id(), i)) { fft_plot->setMarkerVisible(cw->id(), i, en); } } @@ -2705,7 +2559,7 @@ void SpectrumAnalyzer::onChannelEnabled(bool en) void SpectrumAnalyzer::updateRunButton(bool ch_en) { - for (unsigned int i = 0; !ch_en && i < m_adc_nb_channels; i++) { + for(unsigned int i = 0; !ch_en && i < m_adc_nb_channels; i++) { QWidget *parent = ui->channelsList->itemAt(i)->widget(); QCheckBox *box = parent->findChild("box"); ch_en = box->isChecked(); @@ -2713,7 +2567,7 @@ void SpectrumAnalyzer::updateRunButton(bool ch_en) ui->runSingleWidget->setEnabled(ch_en); tme->setRunBtnVisible(ch_en); - if (!ch_en) { + if(!ch_en) { tme->setRunning(false); ui->runSingleWidget->toggle(false); } @@ -2722,31 +2576,32 @@ void SpectrumAnalyzer::updateRunButton(bool ch_en) void SpectrumAnalyzer::writeAllSettingsToHardware() { try { - if (m_m2k_analogin) { + if(m_m2k_analogin) { bool canConvRawToVolts = m_m2k_analogin ? true : false; m_m2k_analogin->setSampleRate(m_max_sample_rate); - for (unsigned int i = 0; i < m_adc_nb_channels; i++) { - libm2k::analog::ANALOG_IN_CHANNEL chn = static_cast(i); + for(unsigned int i = 0; i < m_adc_nb_channels; i++) { + libm2k::analog::ANALOG_IN_CHANNEL chn = + static_cast(i); m_m2k_analogin->setVerticalOffset(chn, 0.0); m_m2k_analogin->setRange(chn, channels[i]->getGainMode()); - if (canConvRawToVolts) { + if(canConvRawToVolts) { fft_plot->setScaleFactor(i, m_m2k_analogin->getScalingFactor(chn)); } } m_m2k_analogin->setOversamplingRatio(sample_rate_divider); auto trigger = m_m2k_analogin->getTrigger(); - if (trigger) { - for (unsigned int i = 0; i < m_adc_nb_channels; i++) { + if(trigger) { + for(unsigned int i = 0; i < m_adc_nb_channels; i++) { trigger->setAnalogMode(i, libm2k::ALWAYS); } } } else { - for (unsigned int i = 0; i < m_adc_nb_channels; i++) { + for(unsigned int i = 0; i < m_adc_nb_channels; i++) { m_generic_analogin->setSampleRate(i, m_generic_analogin->getMaximumSamplerate(i)); } } - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug(CAT_M2K_SPECTRUM_ANALYZER) << "Can't write settings to hardware: " << e.what(); } @@ -2756,8 +2611,8 @@ int SpectrumAnalyzer::channelIdOfOpenedSettings() const { int chId = -1; - for (int i = 0; i < channels.size(); i++) { - if (channels[i]->isSettingsOn()) { + for(int i = 0; i < channels.size(); i++) { + if(channels[i]->isSettingsOn()) { chId = channels[i]->id(); break; } @@ -2772,7 +2627,7 @@ void SpectrumAnalyzer::on_btnLeftPeak_clicked() fft_plot->marker_to_next_lower_freq_peak(crt_channel_id, crt_marker); - if (!ui->runSingleWidget->runButtonChecked()) { + if(!ui->runSingleWidget->runButtonChecked()) { fft_plot->updateMarkerUi(crt_channel_id, crt_marker); fft_plot->replot(); } @@ -2786,7 +2641,7 @@ void SpectrumAnalyzer::on_btnRightPeak_clicked() fft_plot->marker_to_next_higher_freq_peak(crt_channel_id, crt_marker); - if (!ui->runSingleWidget->runButtonChecked()) { + if(!ui->runSingleWidget->runButtonChecked()) { fft_plot->updateMarkerUi(crt_channel_id, crt_marker); fft_plot->replot(); } @@ -2800,7 +2655,7 @@ void SpectrumAnalyzer::on_btnMaxPeak_clicked() fft_plot->marker_to_max_peak(crt_channel_id, crt_marker); - if (!ui->runSingleWidget->runButtonChecked()) { + if(!ui->runSingleWidget->runButtonChecked()) { fft_plot->updateMarkerUi(crt_channel_id, crt_marker); fft_plot->replot(); } @@ -2812,26 +2667,26 @@ void SpectrumAnalyzer::on_cmb_rbw_currentIndexChanged(int index) { double samplingTime = sample_rate * fft_size; Preferences *p = Preferences::GetInstance(); - double target_fps = p->get("general_plot_target_fps").toDouble(); - double update_time = 1.0/target_fps; + double target_fps = p->get("general_plot_target_fps").toDouble(); + double update_time = 1.0 / target_fps; switch(bin_sizes[index]) { - case 1<<17: + case 1 << 17: fft_sink->set_update_time(update_time * 2); - waterfall_sink->set_update_time(std::max(1/samplingTime, update_time * 2)); - break; - case 1<<18: + waterfall_sink->set_update_time(std::max(1 / samplingTime, update_time * 2)); + break; + case 1 << 18: fft_sink->set_update_time(update_time * 4); - waterfall_sink->set_update_time(std::max(1/samplingTime, update_time * 4)); - break; + waterfall_sink->set_update_time(std::max(1 / samplingTime, update_time * 4)); + break; default: fft_sink->set_update_time(update_time); - waterfall_sink->set_update_time(std::max(1/samplingTime, update_time)); + waterfall_sink->set_update_time(std::max(1 / samplingTime, update_time)); break; } uint new_fft_size = bin_sizes[index]; - if (new_fft_size != fft_size) { + if(new_fft_size != fft_size) { setFftSize(new_fft_size); fft_plot->updateZoomerBase(); @@ -2840,8 +2695,8 @@ void SpectrumAnalyzer::on_cmb_rbw_currentIndexChanged(int index) marker_freq_pos->setMinValue(startStopRange->getStartValue()); marker_freq_pos->setMaxValue(startStopRange->getStopValue()); - marker_freq_pos->setStep(2 * (startStopRange->getStopValue() - - startStopRange->getStartValue()) / bin_sizes[ui->cmb_rbw->currentIndex()]); + marker_freq_pos->setStep(2 * (startStopRange->getStopValue() - startStopRange->getStartValue()) / + bin_sizes[ui->cmb_rbw->currentIndex()]); } void SpectrumAnalyzer::setSampleRate(double sr) @@ -2851,27 +2706,27 @@ void SpectrumAnalyzer::setSampleRate(double sr) ui->lbl_sampleRate->setText("Sample rate: " + QString::number(new_sr, 'f', 0)); - if (new_sr == sample_rate) { + if(new_sr == sample_rate) { return; } sample_rate = new_sr; - if (isIioManagerStarted()) { + if(isIioManagerStarted()) { stop_blockchain_flow(); - if (m_m2k_analogin) { + if(m_m2k_analogin) { try { m_m2k_analogin->setOversamplingRatio(sample_rate_divider); - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug(CAT_M2K_SPECTRUM_ANALYZER) << "Can't write oversampling ratio: " << e.what(); } } else { try { - for (unsigned int i = 0; i < m_adc_nb_channels; i++) { + for(unsigned int i = 0; i < m_adc_nb_channels; i++) { m_generic_analogin->setSampleRate(i, sr); } - } catch (libm2k::m2k_exception &e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug(CAT_M2K_SPECTRUM_ANALYZER) << "Can't write sampling frequency: " << e.what(); } @@ -2897,7 +2752,7 @@ void SpectrumAnalyzer::setFftSize(uint size) bool started = isIioManagerStarted(); - if (started) { + if(started) { iio->lock(); } @@ -2905,13 +2760,12 @@ void SpectrumAnalyzer::setFftSize(uint size) fft_sink->set_nsamps(size); waterfall_sink->set_fft_size(size); - if (fft_plot->magnitudeType() == FftDisplayPlot::VROOTHZ) { + if(fft_plot->magnitudeType() == FftDisplayPlot::VROOTHZ) { fft_plot->setNbOverlappingAverages(m_nb_overlapping_avg); } - for (int i = 0; i < channels.size(); i++) { - auto fft = gnuradio::get_initial_sptr( - new fft_block(!use_float_sink, size)); + for(int i = 0; i < channels.size(); i++) { + auto fft = gnuradio::get_initial_sptr(new fft_block(!use_float_sink, size)); iio->disconnect(fft_ids[i]); iio->disconnect(waterfall_ids[i]); @@ -2921,18 +2775,19 @@ void SpectrumAnalyzer::setFftSize(uint size) iio->connect(fft, 0, channels[i]->ctm_block, 0); iio->connect(channels[i]->ctm_block, 0, fft_sink, i); - if (use_float_sink) { + if(use_float_sink) { auto floatToComplex = gr::blocks::float_to_complex::make(); waterfall_ids[i] = iio->connect(floatToComplex, i, 0, true, fft_size * m_nb_overlapping_avg); iio->connect(floatToComplex, 0, waterfall_sink, i); } else { - waterfall_ids[i] = iio->connect(waterfall_sink, i, i, use_float_sink, fft_size * m_nb_overlapping_avg); + waterfall_ids[i] = + iio->connect(waterfall_sink, i, i, use_float_sink, fft_size * m_nb_overlapping_avg); } - if (started) { + if(started) { iio->start(fft_ids[i]); - if (waterfall_visible) { + if(waterfall_visible) { iio->start(waterfall_ids[i]); Q_EMIT waterfall_plot->resetWaterfallData(); } @@ -2945,7 +2800,7 @@ void SpectrumAnalyzer::setFftSize(uint size) iio->set_buffer_size(waterfall_ids[i], size * m_nb_overlapping_avg); } - if (started) { + if(started) { iio->unlock(); } @@ -2955,10 +2810,9 @@ void SpectrumAnalyzer::setFftSize(uint size) sample_timer->start(TIMER_TIMEOUT_MS); } - void SpectrumAnalyzer::refreshCurrentSampleLabel() { - if (!isIioManagerStarted()) { + if(!isIioManagerStarted()) { sample_timer->stop(); return; } @@ -2968,22 +2822,19 @@ void SpectrumAnalyzer::refreshCurrentSampleLabel() auto time_now = std::chrono::system_clock::now(); std::chrono::duration elapsed_done = time_now - m_time_start; - if (time_acquisition < elapsed_done.count()) { + if(time_acquisition < elapsed_done.count()) { setCurrentSampleLabel(100); return; } double time_percentage = elapsed_done.count() / time_acquisition * 100; - if (time_percentage > 100) { + if(time_percentage > 100) { time_percentage = 100; sample_timer->stop(); } setCurrentSampleLabel(time_percentage); } -void SpectrumAnalyzer::validateSpinboxAveraging() -{ - on_spinBox_averaging_valueChanged(ui->spinBox_averaging->value()); -} +void SpectrumAnalyzer::validateSpinboxAveraging() { on_spinBox_averaging_valueChanged(ui->spinBox_averaging->value()); } void SpectrumAnalyzer::setCurrentSampleLabel(double percentage) { @@ -2994,7 +2845,7 @@ void SpectrumAnalyzer::setCurrentSampleLabel(double percentage) bool SpectrumAnalyzer::canSwitchAverageHistory(FftDisplayPlot::AverageType avg_type) { - switch (avg_type) { + switch(avg_type) { case FftDisplayPlot::LINEAR_RMS: case FftDisplayPlot::LINEAR_DB: return true; @@ -3009,7 +2860,7 @@ void SpectrumAnalyzer::on_btnDnAmplPeak_clicked() fft_plot->marker_to_next_lower_mag_peak(crt_channel_id, crt_marker); - if (!ui->runSingleWidget->runButtonChecked()) { + if(!ui->runSingleWidget->runButtonChecked()) { fft_plot->updateMarkerUi(crt_channel_id, crt_marker); fft_plot->replot(); } @@ -3023,7 +2874,7 @@ void SpectrumAnalyzer::on_btnUpAmplPeak_clicked() fft_plot->marker_to_next_higher_mag_peak(crt_channel_id, crt_marker); - if (!ui->runSingleWidget->runButtonChecked()) { + if(!ui->runSingleWidget->runButtonChecked()) { fft_plot->updateMarkerUi(crt_channel_id, crt_marker); fft_plot->replot(); } @@ -3036,20 +2887,18 @@ void SpectrumAnalyzer::onMarkerToggled(int id, bool on) setMarkerEnabled(crt_channel_id, id, on); // Add/remove the marker from the marker table - if (on) { + if(on) { int mkType = fft_plot->markerType(crt_channel_id, id); if(mkType < 0) return; bool mkExists = ui->markerTable->isMarker(id, crt_channel_id); - if (!mkExists) { + if(!mkExists) { ui->markerTable->addMarker(id, crt_channel_id, QString("M%1").arg(id + 1), fft_plot->markerFrequency(crt_channel_id, id), - fft_plot->markerMagnitude(crt_channel_id, id), - markerTypes[mkType]); + fft_plot->markerMagnitude(crt_channel_id, id), markerTypes[mkType]); } else { - ui->markerTable->updateMarker(id, crt_channel_id, - fft_plot->markerFrequency(crt_channel_id, id), + ui->markerTable->updateMarker(id, crt_channel_id, fft_plot->markerFrequency(crt_channel_id, id), fft_plot->markerMagnitude(crt_channel_id, id), markerTypes[mkType]); } @@ -3057,8 +2906,8 @@ void SpectrumAnalyzer::onMarkerToggled(int id, bool on) ui->markerTable->removeMarker(id, crt_channel_id); } - if (id == marker_selector->selectedButton()) { - if (on) { + if(id == marker_selector->selectedButton()) { + if(on) { setCurrentMarkerLabelData(crt_channel_id, id); } @@ -3078,7 +2927,7 @@ void SpectrumAnalyzer::setMarkerEnabled(int ch_idx, int mrk_idx, bool en) { fft_plot->setMarkerEnabled(ch_idx, mrk_idx, en); - if (en) { + if(en) { double cf = startStopRange->getCenterValue(); fft_plot->setMarkerAtFreq(ch_idx, mrk_idx, cf); fft_plot->updateMarkerUi(ch_idx, mrk_idx); @@ -3089,7 +2938,7 @@ void SpectrumAnalyzer::setMarkerEnabled(int ch_idx, int mrk_idx, bool en) void SpectrumAnalyzer::updateWidgetsRelatedToMarker(int mrk_idx) { - if (fft_plot->markerEnabled(crt_channel_id, mrk_idx)) { + if(fft_plot->markerEnabled(crt_channel_id, mrk_idx)) { setCurrentMarkerLabelData(crt_channel_id, mrk_idx); } @@ -3099,13 +2948,10 @@ void SpectrumAnalyzer::updateWidgetsRelatedToMarker(int mrk_idx) void SpectrumAnalyzer::setCurrentMarkerLabelData(int chIdx, int mkIdx) { - QString txtFreq = freq_formatter.format( - fft_plot->markerFrequency(chIdx, mkIdx), "Hz", 3); - QString txtMag = QString::number( - fft_plot->markerMagnitude(chIdx, mkIdx), 'f', 3) + - QString(" " + ui->cmb_units->currentText()); - QString txt = QString("Marker %1 -> ").arg(mkIdx + 1) + - txtFreq + QString(" ") + txtMag; + QString txtFreq = freq_formatter.format(fft_plot->markerFrequency(chIdx, mkIdx), "Hz", 3); + QString txtMag = QString::number(fft_plot->markerMagnitude(chIdx, mkIdx), 'f', 3) + + QString(" " + ui->cmb_units->currentText()); + QString txt = QString("Marker %1 -> ").arg(mkIdx + 1) + txtFreq + QString(" ") + txtMag; ui->lbl_crtMarkerReading->setText(txt); } @@ -3113,7 +2959,7 @@ void SpectrumAnalyzer::updateCrtMrkLblVisibility() { int crt = marker_selector->selectedButton(); - if (crt >= 0) { + if(crt >= 0) { bool visible = marker_selector->buttonChecked(crt); ui->lbl_crtMarkerReading->setVisible(visible); } @@ -3124,20 +2970,18 @@ void SpectrumAnalyzer::onPlotNewMarkerData() int crt_marker = marker_selector->selectedButton(); // Update top-right label holding the reading of the active marker - if (fft_plot->markerEnabled(crt_channel_id, crt_marker)) { + if(fft_plot->markerEnabled(crt_channel_id, crt_marker)) { setCurrentMarkerLabelData(crt_channel_id, crt_marker); updateMrkFreqPosSpinBtnValue(); } // Update the markers in the marker table - for (size_t c = 0; c < m_adc_nb_channels; c++) { - for (size_t m = 0; m < fft_plot->markerCount(c); m++) { - if (fft_plot->markerEnabled(c, m)) { + for(size_t c = 0; c < m_adc_nb_channels; c++) { + for(size_t m = 0; m < fft_plot->markerCount(c); m++) { + if(fft_plot->markerEnabled(c, m)) { int mkType = fft_plot->markerType(c, m); - ui->markerTable->updateMarker(m, c, - fft_plot->markerFrequency(c, m), - fft_plot->markerMagnitude(c, m), - markerTypes[mkType]); + ui->markerTable->updateMarker(m, c, fft_plot->markerFrequency(c, m), + fft_plot->markerMagnitude(c, m), markerTypes[mkType]); } } } @@ -3145,11 +2989,11 @@ void SpectrumAnalyzer::onPlotNewMarkerData() void SpectrumAnalyzer::onPlotMarkerSelected(uint chIdx, uint mkIdx) { - if (crt_channel_id != chIdx) { + if(crt_channel_id != chIdx) { channels[chIdx]->widget()->nameButton()->setChecked(true); } - if (marker_selector->selectedButton() != mkIdx) { + if(marker_selector->selectedButton() != mkIdx) { marker_selector->setSelectedButton(mkIdx); updateWidgetsRelatedToMarker(mkIdx); } @@ -3159,14 +3003,13 @@ void SpectrumAnalyzer::onMarkerFreqPosChanged(double freq) { int crt_marker = marker_selector->selectedButton(); - if (!fft_plot->markerEnabled(crt_channel_id, crt_marker)) { + if(!fft_plot->markerEnabled(crt_channel_id, crt_marker)) { return; } fft_plot->setMarkerAtFreq(crt_channel_id, crt_marker, freq); fft_plot->updateMarkerUi(crt_channel_id, crt_marker); - double actual_freq = fft_plot->markerFrequency(crt_channel_id, - crt_marker); + double actual_freq = fft_plot->markerFrequency(crt_channel_id, crt_marker); marker_freq_pos->silentSetValue(actual_freq); @@ -3176,8 +3019,7 @@ void SpectrumAnalyzer::onMarkerFreqPosChanged(double freq) void SpectrumAnalyzer::updateMrkFreqPosSpinBtnLimits() { marker_freq_pos->setMaxValue(startStopRange->getStopValue()); - marker_freq_pos->setStep(2 * startStopRange->getStopValue() / - bin_sizes[ui->cmb_rbw->currentIndex()]); + marker_freq_pos->setStep(2 * startStopRange->getStopValue() / bin_sizes[ui->cmb_rbw->currentIndex()]); updateMrkFreqPosSpinBtnValue(); } @@ -3186,34 +3028,28 @@ void SpectrumAnalyzer::updateMrkFreqPosSpinBtnValue() { int crt_marker = marker_selector->selectedButton(); - if (!fft_plot->markerEnabled(crt_channel_id, crt_marker)) { + if(!fft_plot->markerEnabled(crt_channel_id, crt_marker)) { return; } -// if (!fft_plot->markerType(crt_channel_id, crt_marker) == 0) { -// return; -// } + // if (!fft_plot->markerType(crt_channel_id, crt_marker) == 0) { + // return; + // } double freq = fft_plot->markerFrequency(crt_channel_id, crt_marker); - if (freq != marker_freq_pos->value()) { + if(freq != marker_freq_pos->value()) { marker_freq_pos->silentSetValue(freq); } } -void SpectrumAnalyzer::onPlotSampleRateUpdated(double) -{ - updateMrkFreqPosSpinBtnLimits(); -} +void SpectrumAnalyzer::onPlotSampleRateUpdated(double) { updateMrkFreqPosSpinBtnLimits(); } -void SpectrumAnalyzer::onPlotSampleCountUpdated(uint) -{ - updateMrkFreqPosSpinBtnLimits(); -} +void SpectrumAnalyzer::onPlotSampleCountUpdated(uint) { updateMrkFreqPosSpinBtnLimits(); } void SpectrumAnalyzer::singleCaptureDone() { - if (ui->runSingleWidget->singleButtonChecked()) { + if(ui->runSingleWidget->singleButtonChecked()) { Q_EMIT started(false); } else { sample_timer->stop(); @@ -3222,39 +3058,37 @@ void SpectrumAnalyzer::singleCaptureDone() } } -void SpectrumAnalyzer::on_cmb_units_currentIndexChanged(const QString& unit) +void SpectrumAnalyzer::on_cmb_units_currentIndexChanged(const QString &unit) { - auto it = std::find_if(mag_types.begin(), mag_types.end(), - [&](const std::pair& p) { - return p.first == unit; - }); + auto it = std::find_if( + mag_types.begin(), mag_types.end(), + [&](const std::pair &p) { return p.first == unit; }); - if (it == mag_types.end()) { + if(it == mag_types.end()) { return; } - FftDisplayPlot::MagnitudeType magType = (*it).second; unsigned int stackedWidgetCurrentIdx = 0; bool started = isIioManagerStarted(); - if (started) { + if(started) { iio->lock(); } - for (unsigned int i = 0; i < m_adc_nb_channels; i++) { + for(unsigned int i = 0; i < m_adc_nb_channels; i++) { auto ov_factor = SpectrumChannel::win_overlap_factor(channels[i]->fftWindow()); - if (magType == FftDisplayPlot::VROOTHZ) { + if(magType == FftDisplayPlot::VROOTHZ) { channels[i]->fft_block->set_overlap_factor(ov_factor); } else { channels[i]->fft_block->set_overlap_factor(0.0); } } - if (started) { + if(started) { iio->unlock(); } - switch (magType) { + switch(magType) { case FftDisplayPlot::VPEAK: case FftDisplayPlot::VRMS: ui->divisionWidget->setVisible(true); @@ -3301,8 +3135,8 @@ void SpectrumAnalyzer::on_cmb_units_currentIndexChanged(const QString& unit) // The QwtPlot and ticks are not correctly repainted. // This seems to be a timing issue. // Need more investigation, this is a temporary hack. - QTimer::singleShot(20, [=](){ - switch (magType) { + QTimer::singleShot(20, [=]() { + switch(magType) { case FftDisplayPlot::VPEAK: case FftDisplayPlot::VRMS: bottom->setValue(-10); @@ -3327,15 +3161,15 @@ void SpectrumAnalyzer::on_btnHistory_toggled(bool checked) { int crt_channel = channelIdOfOpenedSettings(); - if (crt_channel < 0) { + if(crt_channel < 0) { qDebug(CAT_M2K_SPECTRUM_ANALYZER) << "invalid channel ID for the opened Settings menu"; return; } channels[crt_channel]->setAverageHistoryEnabled(checked); - if (channels[crt_channel]->canStoreAverageHistory()) { - if (ui->btnHistory->isChecked()) { + if(channels[crt_channel]->canStoreAverageHistory()) { + if(ui->btnHistory->isChecked()) { ui->spinBox_averaging->setMaximum(10000); } else { ui->spinBox_averaging->setMaximum(1000000); @@ -3350,28 +3184,27 @@ void SpectrumAnalyzer::on_btnMarkerTable_toggled(bool checked) ui->markerTable->setVisible(checked); // Set the Plot 3 times taller than the Marker Table (when visible) -// QGridLayout *layout = static_cast( -// ui->widgetPlotContainer->layout()); -// int row1 = getGridLayoutPosFromIndex(layout, -// layout->indexOf(ui->markerTable)).first; -// int row2 = getGridLayoutPosFromIndex(layout, -// layout->indexOf(ui->gridLayout_plot)).first; + // QGridLayout *layout = static_cast( + // ui->widgetPlotContainer->layout()); + // int row1 = getGridLayoutPosFromIndex(layout, + // layout->indexOf(ui->markerTable)).first; + // int row2 = getGridLayoutPosFromIndex(layout, + // layout->indexOf(ui->gridLayout_plot)).first; -// if (checked) { -// layout->setRowStretch(row1, 1); -// layout->setRowStretch(row2, 3); -// } else { -// layout->setRowStretch(row1, 0); -// layout->setRowStretch(row2, 0); -// } + // if (checked) { + // layout->setRowStretch(row1, 1); + // layout->setRowStretch(row2, 3); + // } else { + // layout->setRowStretch(row1, 0); + // layout->setRowStretch(row2, 0); + // } } -QPair SpectrumAnalyzer::getGridLayoutPosFromIndex(QGridLayout *layout, - int index) const +QPair SpectrumAnalyzer::getGridLayoutPosFromIndex(QGridLayout *layout, int index) const { QPair pos = qMakePair(-1, -1); - if (layout && index >= 0) { + if(layout && index >= 0) { int row, col, rowSpan, colSpan; layout->getItemPosition(index, &row, &col, &rowSpan, &colSpan); pos.first = row; @@ -3383,7 +3216,7 @@ QPair SpectrumAnalyzer::getGridLayoutPosFromIndex(QGridLayout *layout, void SpectrumAnalyzer::onWaterfallSizeChanged(double value) { - waterfall_plot->setVisibleSampleCount((int) value); + waterfall_plot->setVisibleSampleCount((int)value); waterfall_plot->replot(); waterfall_plot->updateZoomerBase(); @@ -3395,11 +3228,11 @@ void SpectrumAnalyzer::onTopValueChanged(double top_value) bool isScaleBtn = ui->topWidget->currentIndex(); double bottom_value; - if (!isScaleBtn) { + if(!isScaleBtn) { bottom_value = bottom->value(); unit_per_div->blockSignals(true); - unit_per_div->setValue(abs((top_value - bottom_value)/10)); + unit_per_div->setValue(abs((top_value - bottom_value) / 10)); unit_per_div->blockSignals(false); } else { @@ -3425,7 +3258,7 @@ void SpectrumAnalyzer::onScalePerDivValueChanged(double perDiv) bool isScaleBtn = ui->topWidget->currentIndex(); double topValue, bottomValue; - if (isScaleBtn) { + if(isScaleBtn) { bottomValue = bottom_scale->value(); topValue = bottomValue + perDiv * 10; @@ -3465,11 +3298,11 @@ void SpectrumAnalyzer::onBottomValueChanged(double bottom_value) bool isScaleBtn = ui->topWidget->currentIndex(); double top_value; - if (!isScaleBtn) { + if(!isScaleBtn) { top_value = top->value(); unit_per_div->blockSignals(true); - unit_per_div->setValue(abs((top_value - bottom_value)/10)); + unit_per_div->setValue(abs((top_value - bottom_value) / 10)); unit_per_div->blockSignals(false); } else { @@ -3498,81 +3331,63 @@ void SpectrumAnalyzer::onCurrentAverageIndexChanged(uint chnIdx, uint avgIdx) void SpectrumAnalyzer::setCurrentAverageIndexLabel(uint chnIdx) { - if (chnIdx == crt_channel_id) { - if (channels[chnIdx]->averaging() != 1) { + if(chnIdx == crt_channel_id) { + if(channels[chnIdx]->averaging() != 1) { ui->lbl_crtAvgSample->setVisible(true); - QString txt = QString(tr("Average Sample:")+" %1 / %2 ").arg(channels[chnIdx]->averageIdx()) - .arg(channels[chnIdx]->averaging()); + QString txt = QString(tr("Average Sample:") + " %1 / %2 ") + .arg(channels[chnIdx]->averageIdx()) + .arg(channels[chnIdx]->averaging()); ui->lbl_crtAvgSample->setText(txt); ui->lbl_crtAvgSample->setStyleSheet(QString("QLabel {" "color: %1;" "font-weight: bold;" - "}").arg(fft_plot->getLineColor(chnIdx).name())); + "}") + .arg(fft_plot->getLineColor(chnIdx).name())); } else { ui->lbl_crtAvgSample->setVisible(false); } } } - /* * class SpectrumChannel */ -SpectrumChannel::SpectrumChannel(int id, const QString& name, - FftDisplayPlot *plot): - m_id(id), - m_name(name), - m_line_width(1.0), - m_color(plot->getLineColor(id).name()), - m_averaging(1), - m_average_current_index(0), - m_avg_type(FftDisplayPlot::SAMPLE), - m_fft_win(SpectrumAnalyzer::HAMMING), - m_plot(plot), - m_widget(new ChannelWidget(id, false, false, m_color)), - m_average_history(true), - m_gain_mode(libm2k::analog::PLUS_MINUS_25V) +SpectrumChannel::SpectrumChannel(int id, const QString &name, FftDisplayPlot *plot) + : m_id(id) + , m_name(name) + , m_line_width(1.0) + , m_color(plot->getLineColor(id).name()) + , m_averaging(1) + , m_average_current_index(0) + , m_avg_type(FftDisplayPlot::SAMPLE) + , m_fft_win(SpectrumAnalyzer::HAMMING) + , m_plot(plot) + , m_widget(new ChannelWidget(id, false, false, m_color)) + , m_average_history(true) + , m_gain_mode(libm2k::analog::PLUS_MINUS_25V) { m_widget->setFullName(name); m_widget->setShortName(QString("CH %1").arg(id + 1)); m_widget->nameButton()->setText(m_widget->shortName()); } -bool SpectrumChannel::isSettingsOn() const -{ - return m_widget->menuButton()->isChecked(); -} +bool SpectrumChannel::isSettingsOn() const { return m_widget->menuButton()->isChecked(); } -void SpectrumChannel::setSettingsOn(bool on) -{ - m_widget->enableButton()->setChecked(on); -} +void SpectrumChannel::setSettingsOn(bool on) { m_widget->enableButton()->setChecked(on); } -float SpectrumChannel::lineWidth() const -{ - return m_line_width; -} +float SpectrumChannel::lineWidth() const { return m_line_width; } -void SpectrumChannel::setLinewidth(float width) -{ - m_line_width = width; -} +void SpectrumChannel::setLinewidth(float width) { m_line_width = width; } -QColor SpectrumChannel::color() const -{ - return m_color; -} +QColor SpectrumChannel::color() const { return m_color; } -void SpectrumChannel::setColor(const QColor& color) +void SpectrumChannel::setColor(const QColor &color) { m_widget->setColor(color); m_color = color; } -uint SpectrumChannel::averaging() const -{ - return m_averaging; -} +uint SpectrumChannel::averaging() const { return m_averaging; } void SpectrumChannel::setAveraging(uint averaging) { @@ -3580,24 +3395,15 @@ void SpectrumChannel::setAveraging(uint averaging) m_plot->setAverage(m_id, m_avg_type, averaging, m_average_history); } -uint SpectrumChannel::averageIdx() const -{ - return m_average_current_index; -} +uint SpectrumChannel::averageIdx() const { return m_average_current_index; } -void SpectrumChannel::setAverageIdx(uint avg) -{ - m_average_current_index = avg; -} +void SpectrumChannel::setAverageIdx(uint avg) { m_average_current_index = avg; } -FftDisplayPlot::AverageType SpectrumChannel::averageType() const -{ - return m_avg_type; -} +FftDisplayPlot::AverageType SpectrumChannel::averageType() const { return m_avg_type; } bool SpectrumChannel::canStoreAverageHistory() const { - switch (m_avg_type) { + switch(m_avg_type) { case FftDisplayPlot::LINEAR_RMS: case FftDisplayPlot::LINEAR_DB: case FftDisplayPlot::PEAK_HOLD: @@ -3610,19 +3416,12 @@ bool SpectrumChannel::canStoreAverageHistory() const void SpectrumChannel::setGainMode(int index) { - m_gain_mode = index == 0 ? libm2k::analog::PLUS_MINUS_25V - : libm2k::analog::PLUS_MINUS_2_5V; + m_gain_mode = index == 0 ? libm2k::analog::PLUS_MINUS_25V : libm2k::analog::PLUS_MINUS_2_5V; } -libm2k::analog::M2K_RANGE SpectrumChannel::getGainMode() -{ - return m_gain_mode; -} +libm2k::analog::M2K_RANGE SpectrumChannel::getGainMode() { return m_gain_mode; } -bool SpectrumChannel::isAverageHistoryEnabled() const -{ - return m_average_history; -} +bool SpectrumChannel::isAverageHistoryEnabled() const { return m_average_history; } void SpectrumChannel::setAverageHistoryEnabled(bool enabled) { @@ -3644,13 +3443,12 @@ void SpectrumChannel::setFftWindow(SpectrumAnalyzer::FftWinType win, int taps) std::vector window = build_win(win, taps); float sum = 0; float sqr_sum = 0; - for (auto elem : window) { + for(auto elem : window) { sum += elem; sqr_sum += (elem * elem); } m_plot->setWindowCoefficientSum(m_id, round(sum), round(sqr_sum)); - /* We scale the window coefficients using the * coeff average in order to compensate for the * loss in the FFT. @@ -3664,15 +3462,11 @@ void SpectrumChannel::setFftWindow(SpectrumAnalyzer::FftWinType win, int taps) Q_EMIT FftWindowChanged(window, id()); } -SpectrumAnalyzer::FftWinType SpectrumChannel::fftWindow() const -{ - return m_fft_win; -} +SpectrumAnalyzer::FftWinType SpectrumChannel::fftWindow() const { return m_fft_win; } -std::vector SpectrumChannel::build_win(SpectrumAnalyzer::FftWinType type, - int ntaps) +std::vector SpectrumChannel::build_win(SpectrumAnalyzer::FftWinType type, int ntaps) { - switch (type) { + switch(type) { case SpectrumAnalyzer::FLAT_TOP: return gr::fft::window::flattop(ntaps); @@ -3700,14 +3494,11 @@ std::vector SpectrumChannel::build_win(SpectrumAnalyzer::FftWinType type, } } -std::vector SpectrumChannel::getWindow() -{ - return d_window; -} +std::vector SpectrumChannel::getWindow() { return d_window; } double SpectrumChannel::win_overlap_factor(SpectrumAnalyzer::FftWinType type) { - switch (type) { + switch(type) { case SpectrumAnalyzer::FLAT_TOP: return 0.656; @@ -3730,21 +3521,20 @@ double SpectrumChannel::win_overlap_factor(SpectrumAnalyzer::FftWinType type) } } -float -SpectrumChannel::calcCoherentPowerGain(const std::vector& win) const +float SpectrumChannel::calcCoherentPowerGain(const std::vector &win) const { float sum = 0; - for (size_t i = 0; i < win.size(); i++) { + for(size_t i = 0; i < win.size(); i++) { sum += win[i]; } return sum / win.size(); } -void SpectrumChannel::scaletFftWindow(std::vector& win, float gain) +void SpectrumChannel::scaletFftWindow(std::vector &win, float gain) { - for (size_t i = 0; i < win.size(); i++) { + for(size_t i = 0; i < win.size(); i++) { win[i] *= gain; } } diff --git a/plugins/m2k/src/old/spectrum_analyzer.hpp b/plugins/m2k/src/old/spectrum_analyzer.hpp index b951cd0398..03cb21c885 100644 --- a/plugins/m2k/src/old/spectrum_analyzer.hpp +++ b/plugins/m2k/src/old/spectrum_analyzer.hpp @@ -21,37 +21,39 @@ #ifndef SPECTRUM_ANALYZER_HPP #define SPECTRUM_ANALYZER_HPP -#include -#include -#include - -#include "iio_manager.hpp" -#include "scope_sink_f.h" -#include "waterfall_sink.h" -#include "fft_block.hpp" #include "FftDisplayPlot.h" -#include "m2ktool.hpp" -#include "plot_utils.hpp" #include "WaterfallDisplayPlot.h" -#include "gui/spinbox_a.hpp" +#include "fft_block.hpp" #include "gui/customPushButton.h" +#include "gui/spinbox_a.hpp" #include "gui/startstoprangewidget.h" +#include "iio_manager.hpp" +#include "m2ktool.hpp" +#include "plot_utils.hpp" +#include "scope_sink_f.h" +#include "waterfall_sink.h" + +#include +#include +#include #ifdef SPECTRAL_MSR #include "gui/measure.h" #endif -#include #include +#include /* libm2k includes */ +#include "gui/smallOnOffSwitch.h" + #include #include -#include #include -#include "gui/smallOnOffSwitch.h" +#include -extern "C" { +extern "C" +{ struct iio_buffer; struct iio_channel; struct iio_context; @@ -66,13 +68,13 @@ class CursorsSettings; #ifdef SPECTRAL_MSR class MeasurementsPanel; #endif -} +} // namespace Ui namespace scopy { class DbClickButtons; class ChannelWidget; class ApiObject; -} +} // namespace scopy namespace scopy::m2k { class SpectrumChannel; class Filter; @@ -81,7 +83,7 @@ class Filter; class MeasurementData; class MeasurementGui; #endif -} +} // namespace scopy::m2k class QPushButton; class QButtonGroup; @@ -96,7 +98,7 @@ class SpectrumMarker_API; class MeasureSettings; #endif -class SpectrumAnalyzer: public M2kTool +class SpectrumAnalyzer : public M2kTool { friend class SpectrumChannel_API; friend class SpectrumAnalyzer_API; @@ -106,8 +108,8 @@ class SpectrumAnalyzer: public M2kTool Q_OBJECT public: - - enum FftWinType { + enum FftWinType + { FLAT_TOP = 0, RECTANGULAR = 1, TRIANGULAR = 2, @@ -119,15 +121,14 @@ class SpectrumAnalyzer: public M2kTool typedef std::shared_ptr channel_sptr; - explicit SpectrumAnalyzer(struct iio_context *iio, Filter *filt, - ToolMenuEntry *tme, m2k_iio_manager* m2k_man, + explicit SpectrumAnalyzer(struct iio_context *iio, Filter *filt, ToolMenuEntry *tme, m2k_iio_manager *m2k_man, QJSEngine *engine, QWidget *parent); ~SpectrumAnalyzer(); - QPushButton* getRunButton(); - void setNativeDialogs(bool nativeDialogs) override; + QPushButton *getRunButton(); + void setNativeDialogs(bool nativeDialogs) override; void setCurrentAverageIndexLabel(uint chnIdx); public Q_SLOTS: - void readPreferences(); + void readPreferences(); void run() override; void stop() override; void setWaterfallWindow(std::vector window, int channel_id); @@ -172,10 +173,10 @@ private Q_SLOTS: void onCursorReadoutsChanged(struct cursorReadoutsText); void toggleCursorsMode(bool toggled); - void on_comboBox_type_currentIndexChanged(const QString&); - void on_comboBox_window_currentIndexChanged(const QString&); - void on_comboBox_line_thickness_currentIndexChanged(int index); - void on_spinBox_averaging_valueChanged(int); + void on_comboBox_type_currentIndexChanged(const QString &); + void on_comboBox_window_currentIndexChanged(const QString &); + void on_comboBox_line_thickness_currentIndexChanged(int index); + void on_spinBox_averaging_valueChanged(int); void runStopToggled(bool); void onChannelSettingsToggled(bool); void onChannelSelected(bool); @@ -188,7 +189,7 @@ private Q_SLOTS: void on_btnDnAmplPeak_clicked(); void on_btnMaxPeak_clicked(); void on_cmb_rbw_currentIndexChanged(int index); - void on_cmb_units_currentIndexChanged(const QString&); + void on_cmb_units_currentIndexChanged(const QString &); void onPlotNewMarkerData(); void onPlotMarkerSelected(uint chIdx, uint mkIdx); void onMarkerFreqPosChanged(double); @@ -199,7 +200,7 @@ private Q_SLOTS: void onTopValueChanged(double); void onScalePerDivValueChanged(double); void onBottomValueChanged(double); - void rightMenuFinished(bool opened); + void rightMenuFinished(bool opened); void btnExportClicked(); void updateRunButton(bool); void on_btnAddRef_toggled(bool checked); @@ -210,6 +211,7 @@ private Q_SLOTS: void validateSpinboxAveraging(); void onWaterfallSizeChanged(double); void waterfallToggled(bool visible); + private: void initInstrumentStrings(); void build_gnuradio_block_chain(); @@ -229,13 +231,12 @@ private Q_SLOTS: void add_ref_waveform(QVector xData, QVector yData); void add_ref_waveform(unsigned int chIdx); QString getReferenceChannelName() const; - void setYAxisUnit(const QString& type); + void setYAxisUnit(const QString &type); QList ch_api; QList marker_api; - QPair getGridLayoutPosFromIndex(QGridLayout *layout, - int index) const; + QPair getGridLayoutPosFromIndex(QGridLayout *layout, int index) const; QQueue> menuButtonActions; QList menuOrder; @@ -249,10 +250,10 @@ private Q_SLOTS: bool use_float_sink; private: - libm2k::context::M2k* m_m2k_context; - libm2k::analog::M2kAnalogIn* m_m2k_analogin; - libm2k::context::Generic* m_generic_context; - libm2k::analog::GenericAnalogIn* m_generic_analogin; + libm2k::context::M2k *m_m2k_context; + libm2k::analog::M2kAnalogIn *m_m2k_analogin; + libm2k::context::Generic *m_generic_context; + libm2k::analog::GenericAnalogIn *m_generic_analogin; Ui::SpectrumAnalyzer *ui; scopy::SmallOnOffSwitch *btnSyncPlotCursors; QHBoxLayout *horizontalLockLayout; @@ -294,7 +295,7 @@ private Q_SLOTS: QList channels; QTimer *sample_timer; - std::chrono::time_point m_time_start; + std::chrono::time_point m_time_start; scopy::scope_sink_f::sptr fft_sink; scopy::waterfall_sink::sptr waterfall_sink; @@ -322,10 +323,8 @@ private Q_SLOTS: bool marker_menu_opened; - std::vector> mag_types; - std::vector> avg_types; + std::vector> mag_types; + std::vector> avg_types; std::vector> win_types; std::vector markerTypes; void triggerRightMenuToggle(CustomPushButton *btn, bool checked); @@ -351,18 +350,18 @@ private Q_SLOTS: QDockWidget *waterfallDocker; #ifdef SPECTRAL_MSR - //din capture plot + // din capture plot QList> measurements(int chnIdx); std::shared_ptr measurement(int id, int chnIdx); void measure(); int activeMeasurementsCount(int chnIdx); - Measure* measureOfChannel(int chnIdx) const; + Measure *measureOfChannel(int chnIdx) const; bool measurementsEnabled(); void computeMeasurementsForChannel(unsigned int chnIdx, unsigned int sampleRate); void cleanUpMeasurementsBeforeChannelRemoval(int chnIdx); - //functii normale + // functii normale void settings_panel_update(int id); void settings_panel_size_adjust(); void update_measure_for_channel(int ch_idx); @@ -372,11 +371,11 @@ private Q_SLOTS: void init_selected_measurements(int, std::vector); void measureUpdateValues(); void measureLabelsRearrange(); - void measureCreateAndAppendGuiFrom(const MeasurementData&); + void measureCreateAndAppendGuiFrom(const MeasurementData &); #endif }; -class SpectrumChannel: public QObject +class SpectrumChannel : public QObject { Q_OBJECT friend class SpectrumChannel_API; @@ -385,20 +384,11 @@ class SpectrumChannel: public QObject std::shared_ptr fft_block; gr::blocks::complex_to_mag_squared::sptr ctm_block; - SpectrumChannel(int id, const QString& name, FftDisplayPlot *plot); + SpectrumChannel(int id, const QString &name, FftDisplayPlot *plot); - int id() const - { - return m_id; - } - QString name() const - { - return m_name; - } - ChannelWidget *widget() const - { - return m_widget; - } + int id() const { return m_id; } + QString name() const { return m_name; } + ChannelWidget *widget() const { return m_widget; } bool isSettingsOn() const; void setSettingsOn(bool on); @@ -407,7 +397,7 @@ class SpectrumChannel: public QObject void setLinewidth(float); QColor color() const; - void setColor(const QColor&); + void setColor(const QColor &); uint averaging() const; void setAveraging(uint); @@ -429,8 +419,7 @@ class SpectrumChannel: public QObject libm2k::analog::M2K_RANGE getGainMode(); static double win_overlap_factor(SpectrumAnalyzer::FftWinType type); - static std::vector build_win(SpectrumAnalyzer::FftWinType type, - int ntaps); + static std::vector build_win(SpectrumAnalyzer::FftWinType type, int ntaps); std::vector getWindow(); @@ -452,9 +441,9 @@ class SpectrumChannel: public QObject ChannelWidget *m_widget; std::vector d_window; - float calcCoherentPowerGain(const std::vector& win) const; - void scaletFftWindow(std::vector& win, float gain); + float calcCoherentPowerGain(const std::vector &win) const; + void scaletFftWindow(std::vector &win, float gain); }; -} // namespace scopy +} // namespace scopy::m2k #endif // SPECTRUM_ANALYZER_HPP diff --git a/plugins/m2k/src/old/spectrum_analyzer_api.cpp b/plugins/m2k/src/old/spectrum_analyzer_api.cpp index a195bf3c90..492c565e26 100644 --- a/plugins/m2k/src/old/spectrum_analyzer_api.cpp +++ b/plugins/m2k/src/old/spectrum_analyzer_api.cpp @@ -18,69 +18,44 @@ * along with this program. If not, see . */ #include "spectrum_analyzer_api.hpp" -#include "ui_spectrum_analyzer.h" -#include "ui_cursors_settings.h" + #include "gui/channel_widget.hpp" #include "gui/db_click_buttons.hpp" +#include "ui_cursors_settings.h" +#include "ui_spectrum_analyzer.h" + namespace scopy::m2k { -int SpectrumChannel_API::type() -{ - return spch->averageType(); -} +int SpectrumChannel_API::type() { return spch->averageType(); } -int SpectrumChannel_API::window() -{ - return spch->fftWindow(); -} +int SpectrumChannel_API::window() { return spch->fftWindow(); } -int SpectrumChannel_API::averaging() -{ - return spch->averaging(); -} +int SpectrumChannel_API::averaging() { return spch->averaging(); } -float SpectrumChannel_API::lineThickness() -{ - return spch->lineWidth(); -} +float SpectrumChannel_API::lineThickness() { return spch->lineWidth(); } -bool SpectrumChannel_API::enabled() -{ - return spch->widget()->enableButton()->isChecked(); -} +bool SpectrumChannel_API::enabled() { return spch->widget()->enableButton()->isChecked(); } -void SpectrumChannel_API::enable(bool en) -{ - spch->widget()->enableButton()->setChecked(en); -} +void SpectrumChannel_API::enable(bool en) { spch->widget()->enableButton()->setChecked(en); } -void SpectrumChannel_API::setType(int type) -{ - spch->setAverageType((scopy::FftDisplayPlot::AverageType)type); -} +void SpectrumChannel_API::setType(int type) { spch->setAverageType((scopy::FftDisplayPlot::AverageType)type); } void SpectrumChannel_API::setWindow(int win) { - auto taps=sp->fft_size; - spch->setFftWindow((SpectrumAnalyzer::FftWinType)win,taps); + auto taps = sp->fft_size; + spch->setFftWindow((SpectrumAnalyzer::FftWinType)win, taps); } -void SpectrumChannel_API::setAveraging(int avg) -{ - spch->setAveraging(avg); -} +void SpectrumChannel_API::setAveraging(int avg) { spch->setAveraging(avg); } -void SpectrumChannel_API::setLineThickness(float val) -{ - spch->setLinewidth(val); -} +void SpectrumChannel_API::setLineThickness(float val) { spch->setLinewidth(val); } QList SpectrumChannel_API::data() const { QList list; - int i = sp->ch_api.indexOf(const_cast(this)); + int i = sp->ch_api.indexOf(const_cast(this)); int nr_samples = sp->fft_plot->Curve(0)->data()->size(); - for (int j = 0; j < nr_samples; ++j) { + for(int j = 0; j < nr_samples; ++j) { list.push_back(sp->fft_plot->Curve(i)->sample(j).y()); } return list; @@ -90,58 +65,45 @@ QList SpectrumChannel_API::freq() const { QList frequency_data; int nr_samples = sp->fft_plot->Curve(0)->data()->size(); - for (int i = 0; i < nr_samples; ++i) { + for(int i = 0; i < nr_samples; ++i) { frequency_data.push_back(sp->fft_plot->Curve(0)->sample(i).x()); } return frequency_data; } -int SpectrumMarker_API::chId() -{ - return m_chid; -} +int SpectrumMarker_API::chId() { return m_chid; } -void SpectrumMarker_API::setChId(int val) -{ - m_chid=val; -} +void SpectrumMarker_API::setChId(int val) { m_chid = val; } -int SpectrumMarker_API::mkId() -{ - return m_mkid; -} +int SpectrumMarker_API::mkId() { return m_mkid; } -void SpectrumMarker_API::setMkId(int val) -{ - m_mkid=val; -} +void SpectrumMarker_API::setMkId(int val) { m_mkid = val; } int SpectrumMarker_API::type() { - if (sp->fft_plot->markerEnabled(m_chid,m_mkid)) { - return sp->fft_plot->markerType(m_chid,m_mkid); + if(sp->fft_plot->markerEnabled(m_chid, m_mkid)) { + return sp->fft_plot->markerType(m_chid, m_mkid); } return -1; - } void SpectrumMarker_API::setType(int val) { - if (val > sp->markerTypes.size()) { + if(val > sp->markerTypes.size()) { val = 0; } m_type = val; - if (m_type == 1) { //if type is peak + if(m_type == 1) { // if type is peak sp->fft_plot->marker_to_max_peak(m_chid, m_mkid); } } double SpectrumMarker_API::freq() { - if (sp->fft_plot->markerEnabled(m_chid,m_mkid)) { - return sp->fft_plot->markerFrequency(m_chid,m_mkid); + if(sp->fft_plot->markerEnabled(m_chid, m_mkid)) { + return sp->fft_plot->markerFrequency(m_chid, m_mkid); } else { return 0; } @@ -149,129 +111,92 @@ double SpectrumMarker_API::freq() void SpectrumMarker_API::setFreq(double pos) { - if (sp->fft_plot->markerEnabled(m_chid,m_mkid)) { - if (m_type != 1) { //if type is not peak - sp->fft_plot->setMarkerAtFreq(m_chid,m_mkid,pos); + if(sp->fft_plot->markerEnabled(m_chid, m_mkid)) { + if(m_type != 1) { // if type is not peak + sp->fft_plot->setMarkerAtFreq(m_chid, m_mkid, pos); } - //sp->crt_channel_id=m_chid; + // sp->crt_channel_id=m_chid; sp->updateWidgetsRelatedToMarker(m_mkid); sp->fft_plot->updateMarkerUi(m_chid, m_mkid); - if (sp->crt_channel_id==m_chid) { + if(sp->crt_channel_id == m_chid) { sp->marker_selector->blockSignals(true); sp->marker_selector->setButtonChecked(m_mkid, true); sp->marker_selector->blockSignals(false); } - if (m_type != 1) { //if type is not peak - sp->ui->markerTable->updateMarker(m_mkid, m_chid, - sp->fft_plot->markerFrequency(m_chid, m_mkid), + if(m_type != 1) { // if type is not peak + sp->ui->markerTable->updateMarker(m_mkid, m_chid, sp->fft_plot->markerFrequency(m_chid, m_mkid), sp->fft_plot->markerMagnitude(m_chid, m_mkid), - sp->markerTypes[m_type]); - + sp->markerTypes[m_type]); } } } double SpectrumMarker_API::magnitude() { - if (sp->fft_plot->markerEnabled(m_chid,m_mkid)) { - return sp->fft_plot->markerMagnitude(m_chid,m_mkid); + if(sp->fft_plot->markerEnabled(m_chid, m_mkid)) { + return sp->fft_plot->markerMagnitude(m_chid, m_mkid); } else { return 0; } } -bool SpectrumMarker_API::enabled() -{ - return sp->fft_plot->markerEnabled(m_chid,m_mkid); -} +bool SpectrumMarker_API::enabled() { return sp->fft_plot->markerEnabled(m_chid, m_mkid); } void SpectrumMarker_API::setEnabled(bool en) { bool enabled = sp->channels[m_chid]->widget()->enableButton()->isChecked(); sp->channels[m_chid]->widget()->enableButton()->setChecked(true); sp->channels[m_chid]->widget()->nameButton()->setChecked(true); - sp->fft_plot->setMarkerEnabled(m_chid,m_mkid,en); + sp->fft_plot->setMarkerEnabled(m_chid, m_mkid, en); sp->marker_selector->setButtonChecked(m_mkid, en); sp->updateWidgetsRelatedToMarker(m_mkid); sp->fft_plot->updateMarkerUi(m_chid, m_mkid); sp->channels[m_chid]->widget()->enableButton()->setChecked(enabled); } -bool SpectrumMarker_API::visible() -{ - return sp->fft_plot->markerVisible(m_chid,m_mkid); -} +bool SpectrumMarker_API::visible() { return sp->fft_plot->markerVisible(m_chid, m_mkid); } -void SpectrumMarker_API::setVisible(bool en) -{ - sp->fft_plot->setMarkerVisible(m_chid, m_mkid, en); -} +void SpectrumMarker_API::setVisible(bool en) { sp->fft_plot->setMarkerVisible(m_chid, m_mkid, en); } -void SpectrumAnalyzer_API::show() -{ - Q_EMIT sp->showTool(); -} +void SpectrumAnalyzer_API::show() { Q_EMIT sp->showTool(); } QVariantList SpectrumAnalyzer_API::getMarkers() { QVariantList list; - for (SpectrumMarker_API *each : qAsConst(sp->marker_api)) { + for(SpectrumMarker_API *each : qAsConst(sp->marker_api)) { list.append(QVariant::fromValue(each)); } return list; } +bool SpectrumAnalyzer_API::hasCursors() const { return sp->ui->boxCursors->isChecked(); } -bool SpectrumAnalyzer_API::hasCursors() const -{ - return sp->ui->boxCursors->isChecked(); -} - -void SpectrumAnalyzer_API::setCursors(bool en) -{ - sp->ui->boxCursors->setChecked(en); -} +void SpectrumAnalyzer_API::setCursors(bool en) { sp->ui->boxCursors->setChecked(en); } -bool SpectrumAnalyzer_API::running() -{ - return sp->ui->runSingleWidget->runButtonChecked(); -} +bool SpectrumAnalyzer_API::running() { return sp->ui->runSingleWidget->runButtonChecked(); } -void SpectrumAnalyzer_API::run(bool chk) -{ - sp->ui->runSingleWidget->toggle(chk); -} +void SpectrumAnalyzer_API::run(bool chk) { sp->ui->runSingleWidget->toggle(chk); } -bool SpectrumAnalyzer_API::isSingle() -{ - return sp->ui->runSingleWidget->singleButtonChecked(); -} -void SpectrumAnalyzer_API::single(bool chk) -{ - sp->ui->runSingleWidget->single(); -} +bool SpectrumAnalyzer_API::isSingle() { return sp->ui->runSingleWidget->singleButtonChecked(); } +void SpectrumAnalyzer_API::single(bool chk) { sp->ui->runSingleWidget->single(); } QVariantList SpectrumAnalyzer_API::getChannels() { QVariantList list; - for (SpectrumChannel_API *each : qAsConst(sp->ch_api)) { + for(SpectrumChannel_API *each : qAsConst(sp->ch_api)) { list.append(QVariant::fromValue(each)); } return list; } - -int SpectrumAnalyzer_API::currentChannel() -{ - return (sp->crt_channel_id < 2 ? sp->crt_channel_id : 0); -} +int SpectrumAnalyzer_API::currentChannel() { return (sp->crt_channel_id < 2 ? sp->crt_channel_id : 0); } void SpectrumAnalyzer_API::setCurrentChannel(int ch) { @@ -279,47 +204,22 @@ void SpectrumAnalyzer_API::setCurrentChannel(int ch) Q_EMIT sp->channels[ch]->widget()->selected(true); } -double SpectrumAnalyzer_API::startFreq() -{ - return sp->startStopRange->getStartValue(); -} -void SpectrumAnalyzer_API::setStartFreq(double val) -{ - sp->startStopRange->setStartValue(val); -} +double SpectrumAnalyzer_API::startFreq() { return sp->startStopRange->getStartValue(); } +void SpectrumAnalyzer_API::setStartFreq(double val) { sp->startStopRange->setStartValue(val); } -double SpectrumAnalyzer_API::stopFreq() -{ - return sp->startStopRange->getStopValue(); -} -void SpectrumAnalyzer_API::setStopFreq(double val) -{ - sp->startStopRange->setStopValue(val); -} - -QString SpectrumAnalyzer_API::resBW() -{ - return sp->ui->cmb_rbw->currentText(); -} -void SpectrumAnalyzer_API::setResBW(QString s) -{ - sp->ui->cmb_rbw->setCurrentText(s); -} +double SpectrumAnalyzer_API::stopFreq() { return sp->startStopRange->getStopValue(); } +void SpectrumAnalyzer_API::setStopFreq(double val) { sp->startStopRange->setStopValue(val); } +QString SpectrumAnalyzer_API::resBW() { return sp->ui->cmb_rbw->currentText(); } +void SpectrumAnalyzer_API::setResBW(QString s) { sp->ui->cmb_rbw->setCurrentText(s); } -QString SpectrumAnalyzer_API::units() -{ - return sp->ui->cmb_units->currentText(); -} +QString SpectrumAnalyzer_API::units() { return sp->ui->cmb_units->currentText(); } -void SpectrumAnalyzer_API::setUnits(QString s) -{ - sp->ui->cmb_units->setCurrentText(s); -} +void SpectrumAnalyzer_API::setUnits(QString s) { sp->ui->cmb_units->setCurrentText(s); } double SpectrumAnalyzer_API::topScale() { - if (sp->ui->topWidget->currentIndex() == 0) { + if(sp->ui->topWidget->currentIndex() == 0) { return sp->top->value(); } else { return sp->top_scale->value(); @@ -327,7 +227,7 @@ double SpectrumAnalyzer_API::topScale() } void SpectrumAnalyzer_API::setTopScale(double val) { - if (sp->ui->topWidget->currentIndex() == 0) { + if(sp->ui->topWidget->currentIndex() == 0) { sp->top->setValue(val); } else { sp->top_scale->setValue(val); @@ -336,7 +236,7 @@ void SpectrumAnalyzer_API::setTopScale(double val) double SpectrumAnalyzer_API::bottomScale() { - if (sp->ui->topWidget->currentIndex() == 0) { + if(sp->ui->topWidget->currentIndex() == 0) { return sp->bottom->value(); } else { return sp->bottom_scale->value(); @@ -344,7 +244,7 @@ double SpectrumAnalyzer_API::bottomScale() } void SpectrumAnalyzer_API::setBottomScale(double val) { - if (sp->ui->topWidget->currentIndex() == 0) { + if(sp->ui->topWidget->currentIndex() == 0) { sp->bottom->setValue(val); } else { sp->bottom_scale->setValue(val); @@ -353,60 +253,39 @@ void SpectrumAnalyzer_API::setBottomScale(double val) double SpectrumAnalyzer_API::unitPerDiv() { - if (sp->ui->topWidget->currentIndex() == 0) { + if(sp->ui->topWidget->currentIndex() == 0) { return sp->unit_per_div->value(); } return 0; } void SpectrumAnalyzer_API::setunitPerDiv(double val) { - if (sp->ui->topWidget->currentIndex() == 0) { + if(sp->ui->topWidget->currentIndex() == 0) { sp->unit_per_div->setValue(val); } } -bool SpectrumAnalyzer_API::markerTableVisible() -{ - return sp->ui->btnMarkerTable->isChecked(); -} +bool SpectrumAnalyzer_API::markerTableVisible() { return sp->ui->btnMarkerTable->isChecked(); } -void SpectrumAnalyzer_API::setMarkerTableVisible(bool en) -{ - sp->ui->btnMarkerTable->setChecked(en); -} +void SpectrumAnalyzer_API::setMarkerTableVisible(bool en) { sp->ui->btnMarkerTable->setChecked(en); } -bool SpectrumAnalyzer_API::horizontalCursors() const -{ - return sp->cr_ui->hCursorsEnable->isChecked(); -} +bool SpectrumAnalyzer_API::horizontalCursors() const { return sp->cr_ui->hCursorsEnable->isChecked(); } -void SpectrumAnalyzer_API::setHorizontalCursors(bool en) -{ - sp->cr_ui->hCursorsEnable->setChecked(en); -} +void SpectrumAnalyzer_API::setHorizontalCursors(bool en) { sp->cr_ui->hCursorsEnable->setChecked(en); } -bool SpectrumAnalyzer_API::verticalCursors() const -{ - return sp->cr_ui->vCursorsEnable->isChecked(); -} +bool SpectrumAnalyzer_API::verticalCursors() const { return sp->cr_ui->vCursorsEnable->isChecked(); } -void SpectrumAnalyzer_API::setVerticalCursors(bool en) -{ - sp->cr_ui->vCursorsEnable->setChecked(en); -} +void SpectrumAnalyzer_API::setVerticalCursors(bool en) { sp->cr_ui->vCursorsEnable->setChecked(en); } -bool SpectrumAnalyzer_API::getLogScale() const -{ - return sp->fft_plot->getLogScale(); -} +bool SpectrumAnalyzer_API::getLogScale() const { return sp->fft_plot->getLogScale(); } int SpectrumAnalyzer_API::getCursorsPosition() const { - if (!hasCursors()) { + if(!hasCursors()) { return 0; } auto currentPos = sp->fft_plot->getCursorReadouts()->getCurrentPosition(); - switch (currentPos) { + switch(currentPos) { case CustomPlotPositionButton::ReadoutsPosition::topLeft: default: return 0; @@ -422,22 +301,21 @@ int SpectrumAnalyzer_API::getCursorsPosition() const void SpectrumAnalyzer_API::setCursorsPosition(int val) { - if (!hasCursors()) { + if(!hasCursors()) { return; } enum CustomPlotPositionButton::ReadoutsPosition types[] = { CustomPlotPositionButton::ReadoutsPosition::topLeft, CustomPlotPositionButton::ReadoutsPosition::topRight, CustomPlotPositionButton::ReadoutsPosition::bottomLeft, - CustomPlotPositionButton::ReadoutsPosition::bottomRight - }; + CustomPlotPositionButton::ReadoutsPosition::bottomRight}; sp->cursorsPositionButton->setPosition(types[val]); sp->fft_plot->replot(); } int SpectrumAnalyzer_API::getCursorsTransparency() const { - if (!hasCursors()) { + if(!hasCursors()) { return 0; } return sp->cr_ui->horizontalSlider->value(); @@ -445,33 +323,18 @@ int SpectrumAnalyzer_API::getCursorsTransparency() const void SpectrumAnalyzer_API::setCursorsTransparency(int val) { - if (!hasCursors()) { + if(!hasCursors()) { return; } sp->cr_ui->horizontalSlider->setValue(val); } -void SpectrumAnalyzer_API::setLogScale(bool useLogScale) -{ - sp->ui->logBtn->setChecked(useLogScale); -} +void SpectrumAnalyzer_API::setLogScale(bool useLogScale) { sp->ui->logBtn->setChecked(useLogScale); } -QString SpectrumAnalyzer_API::getNotes() -{ - return sp->ui->instrumentNotes->getNotes(); -} -void SpectrumAnalyzer_API::setNotes(QString str) -{ - sp->ui->instrumentNotes->setNotes(str); -} +QString SpectrumAnalyzer_API::getNotes() { return sp->ui->instrumentNotes->getNotes(); } +void SpectrumAnalyzer_API::setNotes(QString str) { sp->ui->instrumentNotes->setNotes(str); } -bool SpectrumAnalyzer_API::getWaterfallVisible() const -{ - return sp->waterfall_visible; -} +bool SpectrumAnalyzer_API::getWaterfallVisible() const { return sp->waterfall_visible; } -void SpectrumAnalyzer_API::setWaterfallVisible(bool en) -{ - sp->ui->btnToggleWaterfall->setChecked(en); -} -} +void SpectrumAnalyzer_API::setWaterfallVisible(bool en) { sp->ui->btnToggleWaterfall->setChecked(en); } +} // namespace scopy::m2k diff --git a/plugins/m2k/src/old/spectrum_analyzer_api.hpp b/plugins/m2k/src/old/spectrum_analyzer_api.hpp index 06ad40faed..63ba7648ad 100644 --- a/plugins/m2k/src/old/spectrum_analyzer_api.hpp +++ b/plugins/m2k/src/old/spectrum_analyzer_api.hpp @@ -21,6 +21,7 @@ #define SPECTRUM_ANALYZER_API_HPP #include "spectrum_analyzer.hpp" + #include namespace scopy::m2k { @@ -31,7 +32,7 @@ class SpectrumAnalyzer_API : public ApiObject Q_PROPERTY(bool running READ running WRITE run STORED false); Q_PROPERTY(bool single READ isSingle WRITE single STORED false); Q_PROPERTY(double startFreq READ startFreq WRITE setStartFreq); - Q_PROPERTY(double stopFreq READ stopFreq WRITE setStopFreq); + Q_PROPERTY(double stopFreq READ stopFreq WRITE setStopFreq); Q_PROPERTY(QString units READ units WRITE setUnits); Q_PROPERTY(QString resBW READ resBW WRITE setResBW); Q_PROPERTY(double topScale READ topScale WRITE setTopScale); @@ -39,18 +40,13 @@ class SpectrumAnalyzer_API : public ApiObject Q_PROPERTY(double unitPerDiv READ unitPerDiv WRITE setunitPerDiv); Q_PROPERTY(QVariantList channels READ getChannels); Q_PROPERTY(int currentChannel READ currentChannel WRITE setCurrentChannel); - Q_PROPERTY(bool markerTableVisible READ markerTableVisible WRITE - setMarkerTableVisible); + Q_PROPERTY(bool markerTableVisible READ markerTableVisible WRITE setMarkerTableVisible); Q_PROPERTY(QVariantList markers READ getMarkers); - Q_PROPERTY(bool horizontal_cursors READ horizontalCursors - WRITE setHorizontalCursors) - Q_PROPERTY(bool vertical_cursors READ verticalCursors - WRITE setVerticalCursors) - Q_PROPERTY(int cursors_position READ getCursorsPosition - WRITE setCursorsPosition) - Q_PROPERTY(int cursors_transparency READ getCursorsTransparency - WRITE setCursorsTransparency) + Q_PROPERTY(bool horizontal_cursors READ horizontalCursors WRITE setHorizontalCursors) + Q_PROPERTY(bool vertical_cursors READ verticalCursors WRITE setVerticalCursors) + Q_PROPERTY(int cursors_position READ getCursorsPosition WRITE setCursorsPosition) + Q_PROPERTY(int cursors_transparency READ getCursorsTransparency WRITE setCursorsTransparency) Q_PROPERTY(bool logScale READ getLogScale WRITE setLogScale) Q_PROPERTY(QString notes READ getNotes WRITE setNotes) @@ -58,8 +54,10 @@ class SpectrumAnalyzer_API : public ApiObject public: Q_INVOKABLE void show(); - explicit SpectrumAnalyzer_API(SpectrumAnalyzer *sp) : - ApiObject(), sp(sp) {} + explicit SpectrumAnalyzer_API(SpectrumAnalyzer *sp) + : ApiObject() + , sp(sp) + {} ~SpectrumAnalyzer_API() {} private: @@ -124,7 +122,6 @@ class SpectrumAnalyzer_API : public ApiObject bool getWaterfallVisible() const; void setWaterfallVisible(bool en); - }; class SpectrumChannel_API : public ApiObject @@ -134,27 +131,29 @@ class SpectrumChannel_API : public ApiObject Q_PROPERTY(int type READ type WRITE setType); Q_PROPERTY(int window READ window WRITE setWindow); Q_PROPERTY(int averaging READ averaging WRITE setAveraging); - Q_PROPERTY(float line_thickness READ lineThickness WRITE setLineThickness); - Q_PROPERTY(QList data READ data STORED false) + Q_PROPERTY(float line_thickness READ lineThickness WRITE setLineThickness); + Q_PROPERTY(QList data READ data STORED false) Q_PROPERTY(QList freq READ freq STORED false) public: - explicit SpectrumChannel_API(SpectrumAnalyzer *sp, - std::shared_ptr spch) : - ApiObject(), spch(spch),sp(sp) {} + explicit SpectrumChannel_API(SpectrumAnalyzer *sp, std::shared_ptr spch) + : ApiObject() + , spch(spch) + , sp(sp) + {} ~SpectrumChannel_API() {} bool enabled(); int type(); int window(); int averaging(); - float lineThickness(); + float lineThickness(); - void enable(bool); + void enable(bool); void setType(int); void setWindow(int); void setAveraging(int); - void setLineThickness(float val); + void setLineThickness(float val); QList data() const; QList freq() const; @@ -164,7 +163,7 @@ class SpectrumChannel_API : public ApiObject std::shared_ptr spch; }; -class SpectrumMarker_API :public ApiObject +class SpectrumMarker_API : public ApiObject { Q_OBJECT @@ -179,9 +178,15 @@ class SpectrumMarker_API :public ApiObject int m_chid; int m_mkid; int m_type; + public: - explicit SpectrumMarker_API(SpectrumAnalyzer *sp,int chid, int mkid) : - ApiObject(), sp(sp), m_mkid(mkid), m_chid(chid), m_type(0) {} + explicit SpectrumMarker_API(SpectrumAnalyzer *sp, int chid, int mkid) + : ApiObject() + , sp(sp) + , m_mkid(mkid) + , m_chid(chid) + , m_type(0) + {} ~SpectrumMarker_API() {} int chId(); @@ -205,8 +210,7 @@ class SpectrumMarker_API :public ApiObject double magnitude(); SpectrumAnalyzer *sp; - }; -} +} // namespace scopy::m2k #endif // SPECTRUM_ANALYZER_API_HPP diff --git a/plugins/m2k/src/old/state_updater.cpp b/plugins/m2k/src/old/state_updater.cpp index 99c5e05d00..74e3171f22 100644 --- a/plugins/m2k/src/old/state_updater.cpp +++ b/plugins/m2k/src/old/state_updater.cpp @@ -22,14 +22,14 @@ using namespace scopy::m2k; -StateUpdater::StateUpdater(int msecTimeout, QObject *parent): - QObject(parent), - m_enabled(false), - m_off_state(0), - m_idle_state(0), - m_last_input(0), - m_output_state(0), - m_timeout(msecTimeout) +StateUpdater::StateUpdater(int msecTimeout, QObject *parent) + : QObject(parent) + , m_enabled(false) + , m_off_state(0) + , m_idle_state(0) + , m_last_input(0) + , m_output_state(0) + , m_timeout(msecTimeout) { m_timer.setSingleShot(true); @@ -44,20 +44,17 @@ void StateUpdater::onTimerTimeout() Q_EMIT outputChanged(m_output_state); } -bool StateUpdater::enabled() const -{ - return m_enabled; -} +bool StateUpdater::enabled() const { return m_enabled; } void StateUpdater::setEnabled(bool en) { - if (m_enabled != en) { + if(m_enabled != en) { m_enabled = en; - if (en) { + if(en) { m_output_state = m_idle_state; } else { - if (m_timer.isActive()) + if(m_timer.isActive()) m_timer.stop(); m_output_state = m_off_state; } @@ -65,44 +62,23 @@ void StateUpdater::setEnabled(bool en) } } -int StateUpdater::timeout() const -{ - return m_timeout; -} +int StateUpdater::timeout() const { return m_timeout; } -void StateUpdater::setTimeout(int msec) -{ - m_timeout = msec; -} +void StateUpdater::setTimeout(int msec) { m_timeout = msec; } -int StateUpdater::idleState() const -{ - return m_idle_state; -} +int StateUpdater::idleState() const { return m_idle_state; } -void StateUpdater::setIdleState(int state) -{ - m_idle_state = state; -} +void StateUpdater::setIdleState(int state) { m_idle_state = state; } -int StateUpdater::offState() const -{ - return m_off_state; -} +int StateUpdater::offState() const { return m_off_state; } -void StateUpdater::setOffState(int state) -{ - m_off_state = state; -} +void StateUpdater::setOffState(int state) { m_off_state = state; } -int StateUpdater::inputState() const -{ - return m_last_input; -} +int StateUpdater::inputState() const { return m_last_input; } void StateUpdater::setInput(int input) { - if (!m_enabled) + if(!m_enabled) return; int old_output_state = m_output_state; @@ -112,11 +88,8 @@ void StateUpdater::setInput(int input) m_timer.start(m_timeout); - if (old_output_state != input) + if(old_output_state != input) Q_EMIT outputChanged(input); } -int StateUpdater::outputState() const -{ - return m_output_state; -} +int StateUpdater::outputState() const { return m_output_state; } diff --git a/plugins/m2k/src/old/state_updater.h b/plugins/m2k/src/old/state_updater.h index e1d33b6902..051a7a2fcf 100644 --- a/plugins/m2k/src/old/state_updater.h +++ b/plugins/m2k/src/old/state_updater.h @@ -26,7 +26,7 @@ namespace scopy::m2k { -class StateUpdater: public QObject +class StateUpdater : public QObject { Q_OBJECT @@ -64,6 +64,6 @@ private Q_SLOTS: QTimer m_timer; }; -} // namespace scopy +} // namespace scopy::m2k #endif // STATE_UPDATER_H diff --git a/plugins/m2k/src/old/statistic_widget.cpp b/plugins/m2k/src/old/statistic_widget.cpp index 237cdf2c42..5424a79e4d 100644 --- a/plugins/m2k/src/old/statistic_widget.cpp +++ b/plugins/m2k/src/old/statistic_widget.cpp @@ -19,71 +19,54 @@ */ #include "statistic_widget.h" + #include "gui/m2kmeasure.h" #include "plot_utils.hpp" + #include "ui_statistic.h" namespace scopy { class Formatter { public: - Formatter() - { - } + Formatter() {} - virtual ~Formatter() - { - } + virtual ~Formatter() {} virtual QString format(double value) const = 0; }; -class MetricFormatter: public Formatter +class MetricFormatter : public Formatter { public: - MetricFormatter(QString unit = ""): - m_unit(unit) - { - } + MetricFormatter(QString unit = "") + : m_unit(unit) + {} - void setUnit(QString unit) - { - m_unit = unit; - } + void setUnit(QString unit) { m_unit = unit; } - QString format(double value) const - { - return m_formatter.format(value, m_unit, 3); - } + QString format(double value) const { return m_formatter.format(value, m_unit, 3); } private: MetricPrefixFormatter m_formatter; QString m_unit; - }; -class TimeFormatter: public Formatter +class TimeFormatter : public Formatter { public: - TimeFormatter() - { - } + TimeFormatter() {} - QString format(double value) const - { - return m_formatter.format(value, "", 3); - } + QString format(double value) const { return m_formatter.format(value, "", 3); } private: TimePrefixFormatter m_formatter; }; -class PercentageFormatter: public Formatter +class PercentageFormatter : public Formatter { public: - PercentageFormatter() - { - } + PercentageFormatter() {} QString format(double value) const { @@ -96,12 +79,10 @@ class PercentageFormatter: public Formatter } }; -class DimensionlessFormatter: public Formatter +class DimensionlessFormatter : public Formatter { public: - DimensionlessFormatter() - { - } + DimensionlessFormatter() {} QString format(double value) const { @@ -113,18 +94,18 @@ class DimensionlessFormatter: public Formatter } }; -} +} // namespace scopy using namespace scopy; -StatisticWidget::StatisticWidget(QWidget *parent): - QWidget(parent), - m_ui(new Ui::Statistic), - m_title(""), - m_channelId(-1), - m_posIndex(-1), - m_formatter(new DimensionlessFormatter()), - m_valueLabelWidth(0) +StatisticWidget::StatisticWidget(QWidget *parent) + : QWidget(parent) + , m_ui(new Ui::Statistic) + , m_title("") + , m_channelId(-1) + , m_posIndex(-1) + , m_formatter(new DimensionlessFormatter()) + , m_valueLabelWidth(0) { m_ui->setupUi(this); } @@ -135,22 +116,17 @@ StatisticWidget::~StatisticWidget() delete m_ui; } -QString StatisticWidget::title() const -{ - return m_title; -} +QString StatisticWidget::title() const { return m_title; } -int StatisticWidget::channelId() const -{ - return m_channelId; -} +int StatisticWidget::channelId() const { return m_channelId; } -void StatisticWidget::setTitleColor(const QColor& color) +void StatisticWidget::setTitleColor(const QColor &color) { QString stylesheet = QString("" - "font-size: 14px;" - "font-weight: bold;" - "color: %1;").arg(color.name()); + "font-size: 14px;" + "font-weight: bold;" + "color: %1;") + .arg(color.name()); m_ui->label_count->setStyleSheet(stylesheet); m_ui->label_title->setStyleSheet(stylesheet); @@ -158,7 +134,7 @@ void StatisticWidget::setTitleColor(const QColor& color) void StatisticWidget::setPositionIndex(int pos) { - if (m_posIndex != pos) { + if(m_posIndex != pos) { m_posIndex = pos; QString posText; posText.setNum(pos); @@ -216,13 +192,13 @@ void StatisticWidget::initForMeasurement(const M2kMeasurementData &data) delete label; } -void StatisticWidget::updateStatistics(const M2kStatistic& data) +void StatisticWidget::updateStatistics(const M2kStatistic &data) { QString avg_text; QString min_text; QString max_text; - if (data.numPushedData() == 0) { + if(data.numPushedData() == 0) { avg_text = "--"; min_text = "--"; max_text = "--"; diff --git a/plugins/m2k/src/old/statistic_widget.h b/plugins/m2k/src/old/statistic_widget.h index e85c52192e..75ba139d3c 100644 --- a/plugins/m2k/src/old/statistic_widget.h +++ b/plugins/m2k/src/old/statistic_widget.h @@ -24,7 +24,7 @@ #include namespace Ui { - class Statistic; +class Statistic; } namespace scopy { @@ -33,7 +33,7 @@ class M2kMeasurementData; class M2kStatistic; class Formatter; -class StatisticWidget: public QWidget +class StatisticWidget : public QWidget { public: explicit StatisticWidget(QWidget *parent = nullptr); @@ -43,11 +43,11 @@ class StatisticWidget: public QWidget int channelId() const; int positionIndex() const; - void setTitleColor(const QColor& color); + void setTitleColor(const QColor &color); void setPositionIndex(int pos); - - void initForMeasurement(const M2kMeasurementData & data); - void updateStatistics(const M2kStatistic & data); + + void initForMeasurement(const M2kMeasurementData &data); + void updateStatistics(const M2kStatistic &data); private: Ui::Statistic *m_ui; diff --git a/plugins/m2k/src/old/stream_to_vector_overlap.h b/plugins/m2k/src/old/stream_to_vector_overlap.h index 78ac1a6be7..7def295aa0 100644 --- a/plugins/m2k/src/old/stream_to_vector_overlap.h +++ b/plugins/m2k/src/old/stream_to_vector_overlap.h @@ -49,7 +49,7 @@ namespace scopy { class stream_to_vector_overlap : virtual public gr::sync_decimator { public: - typedef std::shared_ptr sptr; + typedef std::shared_ptr sptr; static sptr make(size_t itemsize, size_t nitems_per_block, double overlap_factor); virtual void set_overlap_factor(double) = 0; }; diff --git a/plugins/m2k/src/old/stream_to_vector_overlap_impl.cc b/plugins/m2k/src/old/stream_to_vector_overlap_impl.cc index 09237cf647..6939e86db6 100644 --- a/plugins/m2k/src/old/stream_to_vector_overlap_impl.cc +++ b/plugins/m2k/src/old/stream_to_vector_overlap_impl.cc @@ -40,49 +40,42 @@ */ #include "stream_to_vector_overlap_impl.h" + #include using namespace gr; namespace scopy { -stream_to_vector_overlap::sptr -stream_to_vector_overlap::make(size_t itemsize, - size_t nitems_per_block, - double overlap_factor) +stream_to_vector_overlap::sptr stream_to_vector_overlap::make(size_t itemsize, size_t nitems_per_block, + double overlap_factor) { - return gnuradio::get_initial_sptr(new stream_to_vector_overlap_impl( - itemsize, - nitems_per_block, - overlap_factor)); + return gnuradio::get_initial_sptr( + new stream_to_vector_overlap_impl(itemsize, nitems_per_block, overlap_factor)); } -stream_to_vector_overlap_impl::stream_to_vector_overlap_impl(size_t itemsize, - size_t nitems_per_block, +stream_to_vector_overlap_impl::stream_to_vector_overlap_impl(size_t itemsize, size_t nitems_per_block, double overlap_factor) - : gr::sync_decimator("stream_to_vector_overlap", - io_signature::make(1, 1, itemsize), - io_signature::make(1, 1, itemsize * nitems_per_block), - nitems_per_block), - m_overlap_factor(overlap_factor), - m_itemsize(itemsize), - m_nitems_per_block(nitems_per_block) + : gr::sync_decimator("stream_to_vector_overlap", io_signature::make(1, 1, itemsize), + io_signature::make(1, 1, itemsize * nitems_per_block), nitems_per_block) + , m_overlap_factor(overlap_factor) + , m_itemsize(itemsize) + , m_nitems_per_block(nitems_per_block) { m_nb_overlapped_items = (size_t)(nitems_per_block * m_overlap_factor); } -int stream_to_vector_overlap_impl::work(int noutput_items, - gr_vector_const_void_star& input_items, - gr_vector_void_star& output_items) +int stream_to_vector_overlap_impl::work(int noutput_items, gr_vector_const_void_star &input_items, + gr_vector_void_star &output_items) { size_t block_size = output_signature()->sizeof_stream_item(0); size_t nb_input_items = noutput_items * block_size; size_t nb_total_copied_items = 0; size_t overlap_size = m_nb_overlapped_items * m_itemsize; - const char* in = (const char*)input_items[0]; - char* out = (char*)output_items[0]; + const char *in = (const char *)input_items[0]; + char *out = (char *)output_items[0]; size_t src_index = 0; - while (src_index + block_size <= nb_input_items) { + while(src_index + block_size <= nb_input_items) { memcpy(out + nb_total_copied_items, in + src_index, block_size); nb_total_copied_items += block_size; src_index = src_index + block_size - overlap_size; @@ -96,4 +89,4 @@ void stream_to_vector_overlap_impl::set_overlap_factor(double factor) m_nb_overlapped_items = m_nitems_per_block * m_overlap_factor; } -} +} // namespace scopy diff --git a/plugins/m2k/src/old/stream_to_vector_overlap_impl.h b/plugins/m2k/src/old/stream_to_vector_overlap_impl.h index 6676c89f83..73f6293d63 100644 --- a/plugins/m2k/src/old/stream_to_vector_overlap_impl.h +++ b/plugins/m2k/src/old/stream_to_vector_overlap_impl.h @@ -49,13 +49,9 @@ namespace scopy { class stream_to_vector_overlap_impl : public stream_to_vector_overlap { public: - explicit stream_to_vector_overlap_impl(size_t itemsize, - size_t nitems_per_block, - double overlap_factor); + explicit stream_to_vector_overlap_impl(size_t itemsize, size_t nitems_per_block, double overlap_factor); - int work(int noutput_items, - gr_vector_const_void_star& input_items, - gr_vector_void_star& output_items); + int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); void set_overlap_factor(double); private: diff --git a/plugins/m2k/src/old/timeout_block.cpp b/plugins/m2k/src/old/timeout_block.cpp index 4d069e55ac..06952e0e1b 100644 --- a/plugins/m2k/src/old/timeout_block.cpp +++ b/plugins/m2k/src/old/timeout_block.cpp @@ -22,25 +22,21 @@ using namespace scopy; -timeout_block::timeout_block(const std::string &pmt_name, QObject *parent) : - QObject(parent), gr::block("timeout_block", - gr::io_signature::make(0, 0, 0), - gr::io_signature::make(0, 0, 0)) +timeout_block::timeout_block(const std::string &pmt_name, QObject *parent) + : QObject(parent) + , gr::block("timeout_block", gr::io_signature::make(0, 0, 0), gr::io_signature::make(0, 0, 0)) { pmt::pmt_t port_id = pmt::mp(pmt_name); message_port_register_in(port_id); - set_msg_handler(port_id, std::bind( - &timeout_block::pmt_received, this, std::placeholders::_1)); + set_msg_handler(port_id, std::bind(&timeout_block::pmt_received, this, std::placeholders::_1)); } -timeout_block::~timeout_block() -{ -} +timeout_block::~timeout_block() {} void timeout_block::pmt_received(pmt::pmt_t pmt) { - if (pmt::symbol_to_string(pmt).compare("timeout") == 0) + if(pmt::symbol_to_string(pmt).compare("timeout") == 0) Q_EMIT timeout(); } diff --git a/plugins/m2k/src/old/timeout_block.hpp b/plugins/m2k/src/old/timeout_block.hpp index 35e73e0fc3..c1770d6b2c 100644 --- a/plugins/m2k/src/old/timeout_block.hpp +++ b/plugins/m2k/src/old/timeout_block.hpp @@ -21,26 +21,25 @@ #ifndef TIMEOUT_BLOCK_HPP #define TIMEOUT_BLOCK_HPP -#include - #include +#include + namespace scopy { - class timeout_block : public QObject, public gr::block - { - Q_OBJECT - - private: - void pmt_received(pmt::pmt_t pmt); - - public: - explicit timeout_block(const std::string &pmt_name, - QObject *parent = nullptr); - ~timeout_block(); - - Q_SIGNALS: - void timeout(); - }; -} +class timeout_block : public QObject, public gr::block +{ + Q_OBJECT + +private: + void pmt_received(pmt::pmt_t pmt); + +public: + explicit timeout_block(const std::string &pmt_name, QObject *parent = nullptr); + ~timeout_block(); + +Q_SIGNALS: + void timeout(); +}; +} // namespace scopy #endif diff --git a/plugins/m2k/src/old/trigger_settings.cpp b/plugins/m2k/src/old/trigger_settings.cpp index 435be5df22..06b9e68719 100644 --- a/plugins/m2k/src/old/trigger_settings.cpp +++ b/plugins/m2k/src/old/trigger_settings.cpp @@ -18,24 +18,25 @@ * along with this program. If not, see . */ -#include -#include -#include -#include -#include -#include - #include "trigger_settings.hpp" + #include "gui/spinbox_a.hpp" +#include "m2kpluginExceptionHandler.h" #include "mousewheelwidgetguard.h" #include "ui_trigger_settings.h" #include + #include #include -#include "m2kpluginExceptionHandler.h" +#include +#include +#include +#include +#include +#include using namespace scopy::m2k; using namespace std; @@ -43,7 +44,8 @@ using namespace libm2k; using namespace libm2k::context; using namespace libm2k::analog; -struct TriggerSettings::trigg_channel_config { +struct TriggerSettings::trigg_channel_config +{ double level_min; double level_max; double level_step; @@ -55,57 +57,50 @@ struct TriggerSettings::trigg_channel_config { double dc_level; }; -void TriggerSettings::initInstrumentStrings() { - externalTriggerOutMapping = { - {tr("Forward Trigger In"), libm2k::SELECT_TRIGGER_IN}, - {tr("Oscilloscope"), libm2k::SELECT_ANALOG_IN}, - {tr("Logic Analyzer"), libm2k::SELECT_DIGITAL_IN} - }; -} - -TriggerSettings::TriggerSettings(M2kAnalogIn* libm2k_adc, - QWidget *parent) : - QWidget(parent), ui(new Ui::TriggerSettings), - m_m2k_adc(libm2k_adc), - m_trigger(nullptr), - current_channel(0), - temporarily_disabled(false), - adc_running(false), - trigger_raw_delay(0), - daisyChainCompensation(0), - m_trigger_in(false), - m_has_external_trigger_out(false), - digital_trigger_was_on(false) +void TriggerSettings::initInstrumentStrings() +{ + externalTriggerOutMapping = {{tr("Forward Trigger In"), libm2k::SELECT_TRIGGER_IN}, + {tr("Oscilloscope"), libm2k::SELECT_ANALOG_IN}, + {tr("Logic Analyzer"), libm2k::SELECT_DIGITAL_IN}}; +} + +TriggerSettings::TriggerSettings(M2kAnalogIn *libm2k_adc, QWidget *parent) + : QWidget(parent) + , ui(new Ui::TriggerSettings) + , m_m2k_adc(libm2k_adc) + , m_trigger(nullptr) + , current_channel(0) + , temporarily_disabled(false) + , adc_running(false) + , trigger_raw_delay(0) + , daisyChainCompensation(0) + , m_trigger_in(false) + , m_has_external_trigger_out(false) + , digital_trigger_was_on(false) { initInstrumentStrings(); ui->setupUi(this); m_trigger = (m_m2k_adc) ? m_m2k_adc->getTrigger() : nullptr; - for (uint i = 0; i < m_m2k_adc->getNbChannels(); i++) { + for(uint i = 0; i < m_m2k_adc->getNbChannels(); i++) { struct trigg_channel_config config = {}; trigg_configs.push_back(config); } - trigger_level = new PositionSpinButton({ - {tr("μVolts"),1e-6}, - {tr("mVolts"),1e-3}, - {tr("Volts"),1e0} - }, tr("Level"), 0.0, 0.0, true, false, this); + trigger_level = new PositionSpinButton({{tr("μVolts"), 1e-6}, {tr("mVolts"), 1e-3}, {tr("Volts"), 1e0}}, + tr("Level"), 0.0, 0.0, true, false, this); - trigger_hysteresis = new PositionSpinButton({ - {tr("μVolts"),1e-6}, - {tr("mVolts"),1e-3}, - {tr("Volts"),1e0} - }, tr("Hysteresis"), 0.0, 0.0, true, false, this); + trigger_hysteresis = new PositionSpinButton({{tr("μVolts"), 1e-6}, {tr("mVolts"), 1e-3}, {tr("Volts"), 1e0}}, + tr("Hysteresis"), 0.0, 0.0, true, false, this); ui->controlsLayout->addWidget(trigger_level); ui->controlsLayout->addWidget(trigger_hysteresis); trigger_auto_mode = ui->btnTrigger->isChecked(); - if (m_m2k_adc) { + if(m_m2k_adc) { // Populate UI source comboboxes with the available channels - for (uint i = 0; i < m_m2k_adc->getNbChannels(); i++) { + for(uint i = 0; i < m_m2k_adc->getNbChannels(); i++) { ui->cmb_source->addItem(QString("Channel %1").arg(i + 1)); } @@ -118,13 +113,10 @@ TriggerSettings::TriggerSettings(M2kAnalogIn* libm2k_adc, setTriggerHystRange(currentChannel(), hyst_range_limits); } - connect(trigger_level, SIGNAL(valueChanged(double)), - SLOT(onSpinboxTriggerLevelChanged(double))); - connect(trigger_hysteresis, SIGNAL(valueChanged(double)), - SLOT(onSpinboxTriggerHystChanged(double))); + connect(trigger_level, SIGNAL(valueChanged(double)), SLOT(onSpinboxTriggerLevelChanged(double))); + connect(trigger_hysteresis, SIGNAL(valueChanged(double)), SLOT(onSpinboxTriggerHystChanged(double))); - connect(ui->btnTrigger, SIGNAL(clicked()), this, - SLOT(autoTriggerEnable())); + connect(ui->btnTrigger, SIGNAL(clicked()), this, SLOT(autoTriggerEnable())); // Default GUI settings ui->cmb_source->setCurrentIndex(0); @@ -142,19 +134,18 @@ TriggerSettings::TriggerSettings(M2kAnalogIn* libm2k_adc, ui->label_daisyChain->setVisible(false); ui->spin_daisyChain->setVisible(false); - if (m_trigger->hasExternalTriggerIn()) { + if(m_trigger->hasExternalTriggerIn()) { ui->cmb_extern_src->addItem(tr("External Trigger In")); } - if (m_trigger->hasCrossInstrumentTrigger()) { + if(m_trigger->hasCrossInstrumentTrigger()) { ui->cmb_extern_src->addItem(tr("Logic Analyzer")); } - if (m_trigger->hasExternalTriggerOut()) { + if(m_trigger->hasExternalTriggerOut()) { m_has_external_trigger_out = true; - for (const auto &val : externalTriggerOutMapping) - { + for(const auto &val : externalTriggerOutMapping) { ui->cmb_extern_to_src->addItem(val.first); - connect(ui->extern_to_en,SIGNAL(toggled(bool)),ui->cmb_extern_to_src,SLOT(setEnabled(bool))); + connect(ui->extern_to_en, SIGNAL(toggled(bool)), ui->cmb_extern_to_src, SLOT(setEnabled(bool))); } } else { m_has_external_trigger_out = false; @@ -172,8 +163,8 @@ TriggerSettings::TriggerSettings(M2kAnalogIn* libm2k_adc, ui->mixedSignalLbl->setVisible(false); ui->btnLogicAnalyzerTriggers->setVisible(false); - connect(ui->btnLogicAnalyzerTriggers, &QPushButton::clicked, - this, &TriggerSettings::showLogicAnalyzerTriggerSettings); + connect(ui->btnLogicAnalyzerTriggers, &QPushButton::clicked, this, + &TriggerSettings::showLogicAnalyzerTriggerSettings); } TriggerSettings::~TriggerSettings() @@ -184,46 +175,26 @@ TriggerSettings::~TriggerSettings() delete ui; } -int TriggerSettings::currentChannel() const -{ - return current_channel; -} +int TriggerSettings::currentChannel() const { return current_channel; } -bool TriggerSettings::analogEnabled() const -{ - return ui->intern_en->isChecked(); -} +bool TriggerSettings::analogEnabled() const { return ui->intern_en->isChecked(); } -bool TriggerSettings::digitalEnabled() const -{ - return ui->extern_en->isChecked(); -} +bool TriggerSettings::digitalEnabled() const { return ui->extern_en->isChecked(); } -bool TriggerSettings::externalOutEnabled() const -{ - return ui->extern_to_en->isChecked(); -} +bool TriggerSettings::externalOutEnabled() const { return ui->extern_to_en->isChecked(); } -double TriggerSettings::level() const -{ - return trigger_level->value(); -} +double TriggerSettings::level() const { return trigger_level->value(); } -long long TriggerSettings::triggerDelay() const -{ - return trigger_raw_delay; -} +long long TriggerSettings::triggerDelay() const { return trigger_raw_delay; } -double TriggerSettings::dcLevel() const -{ - return trigg_configs[current_channel].dc_level; -} +double TriggerSettings::dcLevel() const { return trigg_configs[current_channel].dc_level; } void TriggerSettings::setDaisyChainCompensation() { const long long DELAY_PER_DEVICE = 23; - if(ui->extern_en->isChecked() ) - daisyChainCompensation = ui->spin_daisyChain->value() * DELAY_PER_DEVICE; // if not enabled -> compensation 0 + if(ui->extern_en->isChecked()) + daisyChainCompensation = + ui->spin_daisyChain->value() * DELAY_PER_DEVICE; // if not enabled -> compensation 0 else daisyChainCompensation = 0; } @@ -232,7 +203,7 @@ void TriggerSettings::setTriggerDelay(long long raw_delay) { static long long oldCompensation = 0; setDaisyChainCompensation(); - if ((trigger_raw_delay + oldCompensation) != (raw_delay + daisyChainCompensation)) { + if((trigger_raw_delay + oldCompensation) != (raw_delay + daisyChainCompensation)) { trigger_raw_delay = raw_delay; oldCompensation = daisyChainCompensation; writeHwDelay(raw_delay + daisyChainCompensation); @@ -241,7 +212,7 @@ void TriggerSettings::setTriggerDelay(long long raw_delay) void TriggerSettings::setAcCoupled(bool coupled, int chnIdx) { - if (chnIdx == current_channel) { + if(chnIdx == current_channel) { m_ac_coupled = coupled; } } @@ -261,7 +232,7 @@ void TriggerSettings::enableMixedSignalView() ui->btnLogicAnalyzerTriggers->setVisible(true); ui->btnLogicAnalyzerTriggers->setEnabled(true); digital_trigger_was_on = ui->digital_controls->isEnabled(); - if (digital_trigger_was_on) { + if(digital_trigger_was_on) { ui->digital_controls->setDisabled(true); } } @@ -273,14 +244,14 @@ void TriggerSettings::disableMixedSignalView() ui->mixedSignalLbl->setVisible(false); ui->btnLogicAnalyzerTriggers->setVisible(false); ui->btnLogicAnalyzerTriggers->setDisabled(true); - if (digital_trigger_was_on) { + if(digital_trigger_was_on) { ui->digital_controls->setEnabled(true); } } void TriggerSettings::setDcLevelCoupled(double value) { - if (trigg_configs[current_channel].dc_level != value) { + if(trigg_configs[current_channel].dc_level != value) { trigg_configs[current_channel].dc_level = value; } } @@ -288,7 +259,7 @@ void TriggerSettings::setDcLevelCoupled(double value) void TriggerSettings::setTriggerLevel(double level) { double current_level = trigger_level->value(); - if (current_level != level) { + if(current_level != level) { trigger_level->setValue(level); trigg_configs[current_channel].level_val = level; } @@ -298,7 +269,7 @@ void TriggerSettings::setTriggerHysteresis(double hyst) { double current_hyst = trigger_hysteresis->value(); - if (current_hyst != hyst) { + if(current_hyst != hyst) { trigger_hysteresis->setValue(hyst); trigg_configs[currentChannel()].hyst_val = hyst; } @@ -316,7 +287,7 @@ void TriggerSettings::on_cmb_source_currentIndexChanged(int index) trigger_hysteresis->setMaxValue(trigg_configs[index].hyst_max); trigger_hysteresis->setStep(trigg_configs[index].hyst_step); - if (adc_running) + if(adc_running) write_ui_settings_to_hardware(); Q_EMIT sourceChanged(index); @@ -335,15 +306,9 @@ void TriggerSettings::onSpinboxTriggerHystChanged(double value) trigg_configs[currentChannel()].hyst_val = value; } -void TriggerSettings::on_cmb_condition_currentIndexChanged(int index) -{ - writeHwAnalogCondition(index); -} +void TriggerSettings::on_cmb_condition_currentIndexChanged(int index) { writeHwAnalogCondition(index); } -void TriggerSettings::on_cmb_extern_condition_currentIndexChanged(int index) -{ - writeHwDigitalCondition(index); -} +void TriggerSettings::on_cmb_extern_condition_currentIndexChanged(int index) { writeHwDigitalCondition(index); } void TriggerSettings::on_cmb_extern_to_src_currentIndexChanged(int index) { @@ -373,13 +338,12 @@ void TriggerSettings::on_extern_to_en_toggled(bool checked) setTriggerDelay(trigger_raw_delay); } -libm2k::M2K_TRIGGER_MODE TriggerSettings::determineTriggerMode(bool intern_checked, - bool extern_checked) const +libm2k::M2K_TRIGGER_MODE TriggerSettings::determineTriggerMode(bool intern_checked, bool extern_checked) const { libm2k::M2K_TRIGGER_MODE mode; - if (intern_checked) { - if (extern_checked) { + if(intern_checked) { + if(extern_checked) { int start_idx = static_cast(libm2k::EXTERNAL) + 1; int extern_idx = ui->cmb_analog_extern->currentIndex(); mode = static_cast(start_idx + extern_idx); @@ -387,7 +351,7 @@ libm2k::M2K_TRIGGER_MODE TriggerSettings::determineTriggerMode(bool intern_check mode = libm2k::ANALOG; } } else { - if (extern_checked) { + if(extern_checked) { mode = libm2k::EXTERNAL; } else { mode = libm2k::ALWAYS; @@ -402,11 +366,12 @@ void TriggerSettings::enableExternalTriggerOut(bool enabled) if(m_has_external_trigger_out) { try { if(enabled) { - m_trigger->setAnalogExternalOutSelect(externalTriggerOutMapping[ui->cmb_extern_to_src->currentIndex()].second); + m_trigger->setAnalogExternalOutSelect( + externalTriggerOutMapping[ui->cmb_extern_to_src->currentIndex()].second); } else { m_trigger->setAnalogExternalOutSelect(libm2k::SELECT_NONE); } - } catch (libm2k::m2k_exception& e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug() << e.what(); } catch(std::exception e) { @@ -436,13 +401,13 @@ void TriggerSettings::ui_reconf_on_extern_toggled(bool checked) void TriggerSettings::on_cmb_analog_extern_currentIndexChanged(int index) { - if (adc_running) { + if(adc_running) { libm2k::M2K_TRIGGER_MODE mode; int start_idx = static_cast(libm2k::EXTERNAL) + 1; mode = static_cast(start_idx + index); try { m_trigger->setAnalogMode(currentChannel(), mode); - } catch (libm2k::m2k_exception& e){ + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug() << e.what(); } @@ -451,7 +416,7 @@ void TriggerSettings::on_cmb_analog_extern_currentIndexChanged(int index) void TriggerSettings::autoTriggerDisable() { - if (!ui->btnTrigger->isChecked()) { + if(!ui->btnTrigger->isChecked()) { writeHwMode(libm2k::ALWAYS); temporarily_disabled = true; } @@ -459,23 +424,18 @@ void TriggerSettings::autoTriggerDisable() void TriggerSettings::autoTriggerEnable() { - if (!ui->btnTrigger->isChecked()) { - if (temporarily_disabled) { - writeHwMode(determineTriggerMode(ui->intern_en->isChecked(), - ui->extern_en->isChecked())); + if(!ui->btnTrigger->isChecked()) { + if(temporarily_disabled) { + writeHwMode(determineTriggerMode(ui->intern_en->isChecked(), ui->extern_en->isChecked())); temporarily_disabled = false; } } else { - writeHwMode(determineTriggerMode(ui->intern_en->isChecked(), - ui->extern_en->isChecked())); + writeHwMode(determineTriggerMode(ui->intern_en->isChecked(), ui->extern_en->isChecked())); } } -bool TriggerSettings::triggerIsArmed() const -{ - return ui->intern_en->isChecked() || ui->extern_en->isChecked(); -} +bool TriggerSettings::triggerIsArmed() const { return ui->intern_en->isChecked() || ui->extern_en->isChecked(); } void TriggerSettings::on_btnTrigger_toggled(bool checked) { @@ -494,49 +454,47 @@ void TriggerSettings::updateHwVoltLevels(int chnIdx) { try { double level = trigg_configs[chnIdx].level_val; - if (m_ac_coupled) { + if(m_ac_coupled) { level = level + trigg_configs[current_channel].dc_level; } m_trigger->setAnalogLevel(chnIdx, level); m_trigger->setAnalogHysteresis(chnIdx, trigg_configs[chnIdx].hyst_val); - } - catch (libm2k::m2k_exception& e) - { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug() << e.what(); } } -void TriggerSettings::setTriggerLevelRange(int chn, - const std::pair& range) +void TriggerSettings::setTriggerLevelRange(int chn, const std::pair &range) { trigg_configs[chn].level_min = range.first; trigg_configs[chn].level_max = range.second; - if (current_channel == chn) { + if(current_channel == chn) { trigger_level->setMinValue(range.first); trigger_level->setMaxValue(range.second); } } -void TriggerSettings::setTriggerHystRange(int chn, - const std::pair& range) +void TriggerSettings::setTriggerHystRange(int chn, const std::pair &range) { trigg_configs[chn].hyst_min = range.first; trigg_configs[chn].hyst_max = range.second; - if (current_channel == chn) { + if(current_channel == chn) { trigger_hysteresis->setMinValue(range.first); trigger_hysteresis->setMaxValue(range.second); } } -void TriggerSettings::setTriggerEnable(bool en) { +void TriggerSettings::setTriggerEnable(bool en) +{ ui->intern_en->setChecked(en); on_intern_en_toggled(en); } -void TriggerSettings::setTriggerSource(int ch) { +void TriggerSettings::setTriggerSource(int ch) +{ ui->cmb_source->setCurrentIndex(ch); on_cmb_source_currentIndexChanged(ch); } @@ -545,7 +503,7 @@ void TriggerSettings::setTriggerLevelStep(int chn, double step) { trigg_configs[chn].level_step = step; - if (current_channel == chn) { + if(current_channel == chn) { trigger_level->setStep(step); } } @@ -554,7 +512,7 @@ void TriggerSettings::setTriggerHystStep(int chn, double step) { trigg_configs[chn].hyst_step = step; - if (current_channel == chn) { + if(current_channel == chn) { trigger_hysteresis->setStep(step); } } @@ -563,7 +521,7 @@ void TriggerSettings::setAdcRunningState(bool on) { adc_running = on; - if (on) { + if(on) { write_ui_settings_to_hardware(); } } @@ -574,8 +532,7 @@ void TriggerSettings::write_ui_settings_to_hardware() setDaisyChainCompensation(); writeHwSource(ui->cmb_source->currentIndex()); - writeHwMode(determineTriggerMode(ui->intern_en->isChecked(), - ui->extern_en->isChecked())); + writeHwMode(determineTriggerMode(ui->intern_en->isChecked(), ui->extern_en->isChecked())); writeHwAnalogCondition(ui->cmb_condition->currentIndex()); if(ui->cmb_extern_src->currentIndex() == 0) { /* case of External Trigger In */ extern_cnd = ui->cmb_extern_condition->currentIndex(); @@ -591,11 +548,10 @@ void TriggerSettings::write_ui_settings_to_hardware() void TriggerSettings::writeHwDelay(long long raw_delay) { - if (adc_running) { + if(adc_running) { try { m_trigger->setAnalogDelay(raw_delay); - } - catch (libm2k::m2k_exception& e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug() << e.what(); } @@ -604,15 +560,14 @@ void TriggerSettings::writeHwDelay(long long raw_delay) void TriggerSettings::writeHwLevel(double level) { - if (adc_running) { - if (m_ac_coupled) { + if(adc_running) { + if(m_ac_coupled) { level = level + trigg_configs[current_channel].dc_level; } try { m_trigger->setAnalogLevel(currentChannel(), level); - } - catch (libm2k::m2k_exception& e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug() << e.what(); } @@ -621,11 +576,10 @@ void TriggerSettings::writeHwLevel(double level) void TriggerSettings::writeHwHysteresis(double level) { - if (adc_running) { + if(adc_running) { try { m_trigger->setAnalogHysteresis(currentChannel(), level); - } - catch (libm2k::m2k_exception& e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug() << e.what(); } @@ -634,14 +588,12 @@ void TriggerSettings::writeHwHysteresis(double level) void TriggerSettings::writeHwAnalogCondition(int cond) { - if (adc_running) { - libm2k::M2K_TRIGGER_CONDITION_ANALOG t_cond = - static_cast(cond); + if(adc_running) { + libm2k::M2K_TRIGGER_CONDITION_ANALOG t_cond = static_cast(cond); try { m_trigger->setAnalogCondition(currentChannel(), t_cond); - } - catch (libm2k::m2k_exception& e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug() << e.what(); } @@ -650,14 +602,12 @@ void TriggerSettings::writeHwAnalogCondition(int cond) void TriggerSettings::writeHwDigitalCondition(int cond) { - if (adc_running) { - libm2k::M2K_TRIGGER_CONDITION_DIGITAL t_cond = - static_cast(cond); + if(adc_running) { + libm2k::M2K_TRIGGER_CONDITION_DIGITAL t_cond = static_cast(cond); try { m_trigger->setAnalogExternalCondition(currentChannel(), t_cond); - } - catch (libm2k::m2k_exception& e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug() << e.what(); } @@ -666,13 +616,10 @@ void TriggerSettings::writeHwDigitalCondition(int cond) void TriggerSettings::writeHwMode(int mode) { - if (adc_running) { + if(adc_running) { try { - m_trigger->setAnalogMode(currentChannel(), - static_cast(mode)); - } - catch (libm2k::m2k_exception& e) - { + m_trigger->setAnalogMode(currentChannel(), static_cast(mode)); + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug() << e.what(); } @@ -686,50 +633,44 @@ void TriggerSettings::on_cmb_extern_src_currentIndexChanged(int idx) // logic_mode (src) a_OR_trigger_in -> for logic analyzer // set trigger in when both logic analyzer src and extern trig is on setTriggerIn(idx && ui->extern_en->isChecked()); - ui->cmb_extern_condition->setEnabled(idx==0); - if (adc_running) { + ui->cmb_extern_condition->setEnabled(idx == 0); + if(adc_running) { write_ui_settings_to_hardware(); } } -void TriggerSettings::setTriggerIn(bool enable) -{ - m_trigger_in = enable; -} +void TriggerSettings::setTriggerIn(bool enable) { m_trigger_in = enable; } void TriggerSettings::writeHwSource(int source_chn) { - if (adc_running) { + if(adc_running) { try { libm2k::M2K_TRIGGER_SOURCE_ANALOG source = static_cast(source_chn); /* analog trigger on */ bool intern_checked = ui->intern_en->isChecked(); /* extern trigger on & ext digital */ - bool extern_digital_checked = (ui->extern_en->isChecked() && ui->cmb_extern_src->currentIndex() == 1); + bool extern_digital_checked = + (ui->extern_en->isChecked() && ui->cmb_extern_src->currentIndex() == 1); if(m_trigger_in) { - if (!intern_checked) { - if (extern_digital_checked) { - // digital trigger enabled - source = libm2k::SRC_DIGITAL_IN; - } + if(!intern_checked) { + if(extern_digital_checked) { + // digital trigger enabled + source = libm2k::SRC_DIGITAL_IN; + } } else { - if (extern_digital_checked) { - // analog + digital trigger - source = static_cast( - (source_chn + 1) + libm2k::SRC_DIGITAL_IN); - } + if(extern_digital_checked) { + // analog + digital trigger + source = static_cast( + (source_chn + 1) + libm2k::SRC_DIGITAL_IN); + } } } m_trigger->setAnalogSource(source); - } - catch (libm2k::m2k_exception& e) { + } catch(libm2k::m2k_exception &e) { HANDLE_EXCEPTION(e); qDebug() << e.what(); } } } -void TriggerSettings::on_spin_daisyChain_valueChanged(int arg1) -{ - setTriggerDelay(trigger_raw_delay); -} +void TriggerSettings::on_spin_daisyChain_valueChanged(int arg1) { setTriggerDelay(trigger_raw_delay); } diff --git a/plugins/m2k/src/old/trigger_settings.hpp b/plugins/m2k/src/old/trigger_settings.hpp index 011ff13bac..39c23df405 100644 --- a/plugins/m2k/src/old/trigger_settings.hpp +++ b/plugins/m2k/src/old/trigger_settings.hpp @@ -22,151 +22,148 @@ #define TRIGGER_SETTINGS_HPP #include -#include -#include + +#include #include #include -#include +#include +#include namespace Ui { - class TriggerSettings; +class TriggerSettings; } namespace scopy::m2k { - class Oscilloscope_API; +class Oscilloscope_API; } namespace scopy { - class PositionSpinButton; +class PositionSpinButton; } namespace libm2k { - class M2kHardwareTrigger; - namespace analog { - class M2kAnalogIn; - } +class M2kHardwareTrigger; +namespace analog { +class M2kAnalogIn; } +} // namespace libm2k namespace scopy::m2k { - class TriggerSettings : public QWidget +class TriggerSettings : public QWidget +{ + friend class Oscilloscope_API; + + Q_OBJECT + +public: + enum TriggerMode { - friend class Oscilloscope_API; - - Q_OBJECT - - public: - - enum TriggerMode { - NORMAL, - AUTO - }; - - explicit TriggerSettings(libm2k::analog::M2kAnalogIn* libm2k_adc, - QWidget *parent = nullptr); - ~TriggerSettings(); - - int currentChannel() const; - bool analogEnabled() const; - bool digitalEnabled() const; - bool externalOutEnabled() const; - double level() const; - double dcLevel() const; - double hysteresis() const; - bool triggerIsArmed() const; - enum TriggerMode triggerMode() const; - long long triggerDelay() const; - void setDcLevelCoupled(double); - void setAcCoupled(bool, int); - - void setChannelAttenuation(double value); - - void enableMixedSignalView(); - void disableMixedSignalView(); - - Q_SIGNALS: - void sourceChanged(int); - void levelChanged(double); - void analogTriggerEnabled(bool); - void triggerModeChanged(int); - void showLogicAnalyzerTriggerSettings(); - - public Q_SLOTS: - void setTriggerDelay(long long); - void setDaisyChainCompensation(); - void setTriggerLevel(double); - void setTriggerHysteresis(double); - void setTriggerLevelRange(int chn, - const std::pair& range); - void setTriggerHystRange(int chn, - const std::pair& range); - void setTriggerEnable(bool); - void setTriggerSource(int); - void setTriggerLevelStep(int chn, double step); - void setTriggerHystStep(int chn, double step); - void autoTriggerDisable(); - void autoTriggerEnable(); - void updateHwVoltLevels(int chnIdx); - void setAdcRunningState(bool on); - void onSpinboxTriggerLevelChanged(double); - - private Q_SLOTS: - void onSpinboxTriggerHystChanged(double); - void on_cmb_condition_currentIndexChanged(int); - void on_cmb_extern_condition_currentIndexChanged(int); - void on_intern_en_toggled(bool); - void on_cmb_source_currentIndexChanged(int); - void on_extern_en_toggled(bool); - void on_extern_to_en_toggled(bool); - void on_cmb_analog_extern_currentIndexChanged(int); - void on_cmb_extern_to_src_currentIndexChanged(int); - void on_btnTrigger_toggled(bool); - - void on_cmb_extern_src_currentIndexChanged(int idx); - void on_spin_daisyChain_valueChanged(int arg1); - - private: - void initInstrumentStrings(); - void writeHwDelay(long long delay); - void writeHwLevel(double level); - void writeHwHysteresis(double level); - void writeHwAnalogCondition(int cond); - void writeHwDigitalCondition(int cond); - void writeHwMode(int mode); - void writeHwSource(int source); - - void ui_reconf_on_intern_toggled(bool); - void ui_reconf_on_extern_toggled(bool); - void write_ui_settings_to_hardware(); - void trigg_level_write_hardware(int chn, double value); - libm2k::M2K_TRIGGER_MODE determineTriggerMode(bool intern_checked, - bool extern_checked) const; - void enableExternalTriggerOut(bool); - - private: - struct trigg_channel_config; - - Ui::TriggerSettings *ui; - libm2k::analog::M2kAnalogIn* m_m2k_adc; - libm2k::M2kHardwareTrigger* m_trigger; - bool m_trigger_in; - - bool digital_trigger_was_on; - - std::vector> externalTriggerOutMapping; - - QList trigg_configs; - PositionSpinButton *trigger_level; - PositionSpinButton *trigger_hysteresis; - int current_channel; - bool temporarily_disabled; - bool trigger_auto_mode; - long long trigger_raw_delay; - long long daisyChainCompensation; - bool adc_running; - bool m_ac_coupled; - bool m_has_external_trigger_out; - double m_displayScale; - void setTriggerIn(bool bo); + NORMAL, + AUTO }; -} + explicit TriggerSettings(libm2k::analog::M2kAnalogIn *libm2k_adc, QWidget *parent = nullptr); + ~TriggerSettings(); + + int currentChannel() const; + bool analogEnabled() const; + bool digitalEnabled() const; + bool externalOutEnabled() const; + double level() const; + double dcLevel() const; + double hysteresis() const; + bool triggerIsArmed() const; + enum TriggerMode triggerMode() const; + long long triggerDelay() const; + void setDcLevelCoupled(double); + void setAcCoupled(bool, int); + + void setChannelAttenuation(double value); + + void enableMixedSignalView(); + void disableMixedSignalView(); + +Q_SIGNALS: + void sourceChanged(int); + void levelChanged(double); + void analogTriggerEnabled(bool); + void triggerModeChanged(int); + void showLogicAnalyzerTriggerSettings(); + +public Q_SLOTS: + void setTriggerDelay(long long); + void setDaisyChainCompensation(); + void setTriggerLevel(double); + void setTriggerHysteresis(double); + void setTriggerLevelRange(int chn, const std::pair &range); + void setTriggerHystRange(int chn, const std::pair &range); + void setTriggerEnable(bool); + void setTriggerSource(int); + void setTriggerLevelStep(int chn, double step); + void setTriggerHystStep(int chn, double step); + void autoTriggerDisable(); + void autoTriggerEnable(); + void updateHwVoltLevels(int chnIdx); + void setAdcRunningState(bool on); + void onSpinboxTriggerLevelChanged(double); + +private Q_SLOTS: + void onSpinboxTriggerHystChanged(double); + void on_cmb_condition_currentIndexChanged(int); + void on_cmb_extern_condition_currentIndexChanged(int); + void on_intern_en_toggled(bool); + void on_cmb_source_currentIndexChanged(int); + void on_extern_en_toggled(bool); + void on_extern_to_en_toggled(bool); + void on_cmb_analog_extern_currentIndexChanged(int); + void on_cmb_extern_to_src_currentIndexChanged(int); + void on_btnTrigger_toggled(bool); + + void on_cmb_extern_src_currentIndexChanged(int idx); + void on_spin_daisyChain_valueChanged(int arg1); + +private: + void initInstrumentStrings(); + void writeHwDelay(long long delay); + void writeHwLevel(double level); + void writeHwHysteresis(double level); + void writeHwAnalogCondition(int cond); + void writeHwDigitalCondition(int cond); + void writeHwMode(int mode); + void writeHwSource(int source); + + void ui_reconf_on_intern_toggled(bool); + void ui_reconf_on_extern_toggled(bool); + void write_ui_settings_to_hardware(); + void trigg_level_write_hardware(int chn, double value); + libm2k::M2K_TRIGGER_MODE determineTriggerMode(bool intern_checked, bool extern_checked) const; + void enableExternalTriggerOut(bool); + +private: + struct trigg_channel_config; + + Ui::TriggerSettings *ui; + libm2k::analog::M2kAnalogIn *m_m2k_adc; + libm2k::M2kHardwareTrigger *m_trigger; + bool m_trigger_in; + + bool digital_trigger_was_on; + + std::vector> externalTriggerOutMapping; + + QList trigg_configs; + PositionSpinButton *trigger_level; + PositionSpinButton *trigger_hysteresis; + int current_channel; + bool temporarily_disabled; + bool trigger_auto_mode; + long long trigger_raw_delay; + long long daisyChainCompensation; + bool adc_running; + bool m_ac_coupled; + bool m_has_external_trigger_out; + double m_displayScale; + void setTriggerIn(bool bo); +}; + +} // namespace scopy::m2k #endif /* TRIGGER_SETTINGS_HPP */ diff --git a/plugins/m2k/test/CMakeLists.txt b/plugins/m2k/test/CMakeLists.txt index ff0d566e02..646197d6f9 100644 --- a/plugins/m2k/test/CMakeLists.txt +++ b/plugins/m2k/test/CMakeLists.txt @@ -2,7 +2,4 @@ cmake_minimum_required(VERSION 3.5) include(ScopyTest) -SETUP_SCOPY_TESTS( - pluginloader -) - +setup_scopy_tests(pluginloader) diff --git a/plugins/m2k/test/tst_pluginloader.cpp b/plugins/m2k/test/tst_pluginloader.cpp index ee7f90239b..7ef7a8f885 100644 --- a/plugins/m2k/test/tst_pluginloader.cpp +++ b/plugins/m2k/test/tst_pluginloader.cpp @@ -1,6 +1,8 @@ #include "qpluginloader.h" -#include + #include +#include + #include using namespace scopy; @@ -20,72 +22,65 @@ private Q_SLOTS: void name(); void metadata(); void unload(); - }; #define PLUGIN_LOCATION "../../plugins" #define FILENAME PLUGIN_LOCATION "/libscopy-m2kplugin.so" - void TST_M2k::fileExists() { QFile f(FILENAME); bool ret; - qDebug()<(qp.instance()); - QVERIFY(instance != nullptr ); + QPluginLoader qp(FILENAME, this); + auto instance = qobject_cast(qp.instance()); + QVERIFY(instance != nullptr); } - void TST_M2k::clone() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(this); QVERIFY(p1 != nullptr); p2 = original->clone(this); @@ -93,38 +88,37 @@ void TST_M2k::clone() QVERIFY(p1 != p2); } -void TST_M2k::name() { - QPluginLoader qp(FILENAME,this); +void TST_M2k::name() +{ + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(this); - qDebug()<name(); + qDebug() << p1->name(); } void TST_M2k::metadata() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); original->initMetadata(); p1 = original->clone(this); - qDebug()<metadata(); + qDebug() << p1->metadata(); QVERIFY(!p1->metadata().isEmpty()); } void TST_M2k::unload() { - QPluginLoader qp(FILENAME,this); - auto original = qobject_cast(qp.instance()); + QPluginLoader qp(FILENAME, this); + auto original = qobject_cast(qp.instance()); -// qp.unload(); + // qp.unload(); QVERIFY(!qp.isLoaded() == false); - } - QTEST_MAIN(TST_M2k) #include "tst_pluginloader.moc" diff --git a/plugins/regmap/CMakeLists.txt b/plugins/regmap/CMakeLists.txt index dd43afc2f7..5c7ec00e02 100644 --- a/plugins/regmap/CMakeLists.txt +++ b/plugins/regmap/CMakeLists.txt @@ -8,8 +8,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -26,82 +25,88 @@ set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) set(SCOPY_QT_COMPONENTS Widgets Xml Test) -FILE(GLOB SRC_LIST src/*.cpp src/*.cc src/*.hpp - src/register/*.cpp src/register/*.hpp - src/register/bitfield/*.cpp src/register/bitfield/*.hpp - src/readwrite/*.cpp src/readwrite/*.hpp - src/recycerview/*.cpp src/recycerview/*.hpp) -FILE(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) -FILE(GLOB UI_LIST ui/*.ui) +file( + GLOB + SRC_LIST + src/*.cpp + src/*.cc + src/*.hpp + src/register/*.cpp + src/register/*.hpp + src/register/bitfield/*.cpp + src/register/bitfield/*.hpp + src/readwrite/*.cpp + src/readwrite/*.hpp + src/recycerview/*.cpp + src/recycerview/*.hpp +) +file(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) +file(GLOB UI_LIST ui/*.ui) qt_add_resources(PROJECT_RESOURCES resources/resources.qrc) if(ENABLE_TESTING) - add_subdirectory(test) + add_subdirectory(test) endif() -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} -) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS ${SCOPY_QT_COMPONENTS} REQUIRED) find_package(libm2k REQUIRED) if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") - set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY - "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") else() - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) endif() - set(REGMAP_XML_PATH ${CMAKE_INSTALL_FULL_DATADIR}/regmap) set(REGMAP_XML_SYSTEM_PATH ${REGMAP_XML_PATH}/xmls) set(REGMAP_XML_BUILD_PATH ${CMAKE_CURRENT_BINARY_DIR}/xmls) -INSTALL(DIRECTORY xmls DESTINATION ${REGMAP_XML_PATH}) +install(DIRECTORY xmls DESTINATION ${REGMAP_XML_PATH}) -FILE(GLOB XMLS ${CMAKE_CURRENT_SOURCE_DIR}/xmls/*.xml) +file(GLOB XMLS ${CMAKE_CURRENT_SOURCE_DIR}/xmls/*.xml) file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/xmls/regmap-config.json DESTINATION ${REGMAP_XML_BUILD_PATH}) foreach(_xml ${XMLS}) - file(COPY ${_xml} DESTINATION ${REGMAP_XML_BUILD_PATH}) + file(COPY ${_xml} DESTINATION ${REGMAP_XML_BUILD_PATH}) endforeach() message(include/${SCOPY_MODULE}/) -configure_file(include/${SCOPY_MODULE}/scopy-${SCOPY_MODULE}_config.h.cmakein - ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/scopy-${SCOPY_MODULE}_config.h @ONLY) +configure_file( + include/${SCOPY_MODULE}/scopy-${SCOPY_MODULE}_config.h.cmakein + ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/scopy-${SCOPY_MODULE}_config.h @ONLY +) set(SRC_LIST ${SRC_LIST} ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/scopy-${SCOPY_MODULE}_config.h) -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} - ${PROJECT_RESOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES} ${PROJECT_RESOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}) target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) foreach(comp ${SCOPY_QT_COMPONENTS}) - set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) + set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) endforeach() -target_link_libraries(${PROJECT_NAME} PUBLIC - ${SCOPY_QT_LIBRARIES} - scopy-pluginbase - scopy-iioutil - scopy-gui - scopy-core - Qt${QT_VERSION_MAJOR}::Xml - libm2k::libm2k - Qt5::Test) - +target_link_libraries( + ${PROJECT_NAME} + PUBLIC ${SCOPY_QT_LIBRARIES} + scopy-pluginbase + scopy-iioutil + scopy-gui + scopy-core + Qt${QT_VERSION_MAJOR}::Xml + libm2k::libm2k + Qt5::Test +) set(PLUGIN_NAME ${PROJECT_NAME} PARENT_SCOPE) diff --git a/plugins/regmap/include/regmapplugin/regmapplugin.h b/plugins/regmap/include/regmapplugin/regmapplugin.h index 91cbf8a752..985dd87a83 100644 --- a/plugins/regmap/include/regmapplugin/regmapplugin.h +++ b/plugins/regmap/include/regmapplugin/regmapplugin.h @@ -4,16 +4,17 @@ #define SCOPY_PLUGIN_NAME RegmapPlugin #define SCOPY_PLUGIN_PRIO 100 -#include -#include #include "pluginbase/pluginbase.h" #include "scopy-regmapplugin_export.h" -#include + #include -namespace Ui { +#include -} +#include +#include + +namespace Ui {} namespace scopy { namespace regmap { @@ -31,30 +32,26 @@ class SCOPY_REGMAPPLUGIN_EXPORT RegmapPlugin : public QObject, public PluginBase void loadToolList() override; void unload() override; bool compatible(QString uri, QString category) override; - void initPreferences() override; - bool loadPreferencesPage() override; - + void initPreferences() override; + bool loadPreferencesPage() override; void initMetadata() override; QString description() override; - QWidget* getTool(); + QWidget *getTool(); public Q_SLOTS: bool onConnect() override; bool onDisconnect() override; private: - QWidget *m_registerMapWidget = nullptr; - QList *m_deviceList = nullptr; - struct iio_device* getIioDevice(iio_context* ctx, const char *dev_name); - bool isBufferCapable(iio_device *dev); + QWidget *m_registerMapWidget = nullptr; + QList *m_deviceList = nullptr; + struct iio_device *getIioDevice(iio_context *ctx, const char *dev_name); + bool isBufferCapable(iio_device *dev); private Q_SLOTS: - void handlePreferenceChange(QString, QVariant); - - - + void handlePreferenceChange(QString, QVariant); }; -} +} // namespace scopy #endif // REGMAPPLUGIN_H diff --git a/plugins/regmap/src/deviceregistermap.cpp b/plugins/regmap/src/deviceregistermap.cpp index 92f6bf55f6..694f651696 100644 --- a/plugins/regmap/src/deviceregistermap.cpp +++ b/plugins/regmap/src/deviceregistermap.cpp @@ -1,174 +1,185 @@ -#include "registercontroller.hpp" #include "deviceregistermap.hpp" -#include "registermapvalues.hpp" +#include "dynamicWidget.h" +#include "logging_categories.h" +#include "readwrite/iioregisterreadstrategy.hpp" +#include "readwrite/iioregisterwritestrategy.hpp" +#include "register/registerdetailedwidget.hpp" +#include "register/registermodel.hpp" +#include "register/registersimplewidgetfactory.hpp" +#include "registercontroller.hpp" #include "registermaptemplate.hpp" +#include "registermapvalues.hpp" +#include "regmapstylehelper.hpp" #include "search.hpp" #include "utils.hpp" -#include "logging_categories.h" + +#include #include #include -#include #include #include -#include -#include "readwrite/iioregisterreadstrategy.hpp" -#include "readwrite/iioregisterwritestrategy.hpp" -#include "register/registerdetailedwidget.hpp" -#include "register/registermodel.hpp" -#include "register/registersimplewidgetfactory.hpp" + #include #include #include -#include "dynamicWidget.h" -#include "regmapstylehelper.hpp" +#include using namespace scopy; using namespace regmap; -DeviceRegisterMap::DeviceRegisterMap(RegisterMapTemplate *registerMapTemplate, RegisterMapValues *registerMapValues, QWidget *parent) - : QWidget(parent), - registerMapValues(registerMapValues), - registerMapTemplate(registerMapTemplate) +DeviceRegisterMap::DeviceRegisterMap(RegisterMapTemplate *registerMapTemplate, RegisterMapValues *registerMapValues, + QWidget *parent) + : QWidget(parent) + , registerMapValues(registerMapValues) + , registerMapTemplate(registerMapTemplate) { - layout = new QVBoxLayout(this); - Utils::removeLayoutMargins(layout); - setLayout( layout); - - RegmapStyleHelper::RegisterMapStyle(this); - - initSettings(); - - registerController = new RegisterController(this); - - if (registerMapTemplate) { - QWidget *registerMapTable = new QWidget(); - QVBoxLayout *registerMapTableLayout = new QVBoxLayout(registerMapTable); - Utils::removeLayoutMargins(registerMapTableLayout); - registerMapTable->setLayout(registerMapTableLayout); - layout->addWidget(registerMapTable); - - QWidget *tableHeadWidget = new QWidget(); - scopy::regmap::RegmapStyleHelper::FrameWidget(tableHeadWidget); - QHBoxLayout *tableHead = new QHBoxLayout(); - tableHeadWidget->setLayout(tableHead); - - QLabel *empty = new QLabel(""); - empty->setFixedWidth(130); - tableHead->addWidget(empty, 1); - - for (int i = Utils::getBitsPerRow(); i >= 0; i--) { - tableHead->addWidget(new QLabel("Bit"+QString::number(i)),1); - } - registerMapTableLayout->addWidget(tableHeadWidget); - registerMapTableWidget = new RegisterMapTable(registerMapTemplate->getRegisterList(), this); - - QWidget *aux = registerMapTableWidget->getWidget(); - if (aux) { - registerMapTableLayout->addWidget(aux); - } - - QObject::connect(registerMapTableWidget, &RegisterMapTable::registerSelected, this, [=](uint32_t address){ - registerController->blockSignals(true); - registerMapTableWidget->setRegisterSelected(address); - registerChanged(registerMapTemplate->getRegisterTemplate(address)); - registerController->blockSignals(false); - }); - - QObject::connect(registerController, &RegisterController::registerAddressChanged, this , [=](uint32_t address){ - registerChanged(registerMapTemplate->getRegisterTemplate(address)); - registerMapTableWidget->scrollTo(address); - if (autoread) { - Q_EMIT registerMapValues->requestRead(address); - } - }); - layout->addWidget(registerController); - } - - QObject::connect(registerController, &RegisterController::requestRead, registerMapValues, &RegisterMapValues::requestRead); - QObject::connect(registerController, &RegisterController::requestWrite, registerMapValues, &RegisterMapValues::requestWrite); - QObject::connect(registerMapValues, &RegisterMapValues::registerValueChanged, this, [=](uint32_t address, uint32_t value){ - registerController->registerValueChanged(Utils::convertToHexa(value, 8)); - if (registerMapTemplate) { - registerMapTableWidget->valueUpdated(address, value); - registerDetailedWidget->updateBitFieldsValue(value); - registerDetailedWidget->registerValueUpdated(value); - } - }); - - layout->addWidget(registerController); - - if (registerMapTemplate) { - registerChanged(registerMapTemplate->getRegisterList()->first()); - } else { - layout->addItem(new QSpacerItem(10,10,QSizePolicy::Preferred, QSizePolicy::Expanding)); - } + layout = new QVBoxLayout(this); + Utils::removeLayoutMargins(layout); + setLayout(layout); + + RegmapStyleHelper::RegisterMapStyle(this); + + initSettings(); + + registerController = new RegisterController(this); + + if(registerMapTemplate) { + QWidget *registerMapTable = new QWidget(); + QVBoxLayout *registerMapTableLayout = new QVBoxLayout(registerMapTable); + Utils::removeLayoutMargins(registerMapTableLayout); + registerMapTable->setLayout(registerMapTableLayout); + layout->addWidget(registerMapTable); + + QWidget *tableHeadWidget = new QWidget(); + scopy::regmap::RegmapStyleHelper::FrameWidget(tableHeadWidget); + QHBoxLayout *tableHead = new QHBoxLayout(); + tableHeadWidget->setLayout(tableHead); + + QLabel *empty = new QLabel(""); + empty->setFixedWidth(130); + tableHead->addWidget(empty, 1); + + for(int i = Utils::getBitsPerRow(); i >= 0; i--) { + tableHead->addWidget(new QLabel("Bit" + QString::number(i)), 1); + } + registerMapTableLayout->addWidget(tableHeadWidget); + registerMapTableWidget = new RegisterMapTable(registerMapTemplate->getRegisterList(), this); + + QWidget *aux = registerMapTableWidget->getWidget(); + if(aux) { + registerMapTableLayout->addWidget(aux); + } + + QObject::connect(registerMapTableWidget, &RegisterMapTable::registerSelected, this, + [=](uint32_t address) { + registerController->blockSignals(true); + registerMapTableWidget->setRegisterSelected(address); + registerChanged(registerMapTemplate->getRegisterTemplate(address)); + registerController->blockSignals(false); + }); + + QObject::connect(registerController, &RegisterController::registerAddressChanged, this, + [=](uint32_t address) { + registerChanged(registerMapTemplate->getRegisterTemplate(address)); + registerMapTableWidget->scrollTo(address); + if(autoread) { + Q_EMIT registerMapValues->requestRead(address); + } + }); + layout->addWidget(registerController); + } + + QObject::connect(registerController, &RegisterController::requestRead, registerMapValues, + &RegisterMapValues::requestRead); + QObject::connect(registerController, &RegisterController::requestWrite, registerMapValues, + &RegisterMapValues::requestWrite); + QObject::connect(registerMapValues, &RegisterMapValues::registerValueChanged, this, + [=](uint32_t address, uint32_t value) { + registerController->registerValueChanged(Utils::convertToHexa(value, 8)); + if(registerMapTemplate) { + registerMapTableWidget->valueUpdated(address, value); + registerDetailedWidget->updateBitFieldsValue(value); + registerDetailedWidget->registerValueUpdated(value); + } + }); + + layout->addWidget(registerController); + + if(registerMapTemplate) { + registerChanged(registerMapTemplate->getRegisterList()->first()); + } else { + layout->addItem(new QSpacerItem(10, 10, QSizePolicy::Preferred, QSizePolicy::Expanding)); + } } DeviceRegisterMap::~DeviceRegisterMap() { - delete layout; - if (registerController) delete registerController; - if (registerMapTableWidget) delete registerMapTableWidget; - if (docRegisterMapTable) delete docRegisterMapTable; - if (registerDetailedWidget) delete registerDetailedWidget; + delete layout; + if(registerController) + delete registerController; + if(registerMapTableWidget) + delete registerMapTableWidget; + if(docRegisterMapTable) + delete docRegisterMapTable; + if(registerDetailedWidget) + delete registerDetailedWidget; } void DeviceRegisterMap::registerChanged(RegisterModel *regModel) { - registerController->registerChanged(regModel->getAddress()); - registerController->registerValueChanged("N/R"); - registerController->addNameAndDescription(regModel->getName(), regModel->getDescription()); - - if (registerDetailedWidget) { - delete registerDetailedWidget; - } - - registerDetailedWidget = new RegisterDetailedWidget(regModel); - layout->addWidget(registerDetailedWidget); - - if (registerMapValues) { - uint32_t address = regModel->getAddress(); - if (registerMapValues->hasValue(address)) { - uint32_t value = registerMapValues->getValueOfRegister(address); - registerDetailedWidget->updateBitFieldsValue(value); - registerController->registerValueChanged(Utils::convertToHexa(value,regModel->getWidth())); - } - } - - QObject::connect(registerDetailedWidget, &RegisterDetailedWidget::bitFieldValueChanged, registerController, &RegisterController::registerValueChanged); - QObject::connect(registerController, &RegisterController::valueChanged, this, [=](QString val){ - bool ok; - registerDetailedWidget->updateBitFieldsValue(val.toUInt(&ok,16)); - }); + registerController->registerChanged(regModel->getAddress()); + registerController->registerValueChanged("N/R"); + registerController->addNameAndDescription(regModel->getName(), regModel->getDescription()); + + if(registerDetailedWidget) { + delete registerDetailedWidget; + } + + registerDetailedWidget = new RegisterDetailedWidget(regModel); + layout->addWidget(registerDetailedWidget); + + if(registerMapValues) { + uint32_t address = regModel->getAddress(); + if(registerMapValues->hasValue(address)) { + uint32_t value = registerMapValues->getValueOfRegister(address); + registerDetailedWidget->updateBitFieldsValue(value); + registerController->registerValueChanged(Utils::convertToHexa(value, regModel->getWidth())); + } + } + + QObject::connect(registerDetailedWidget, &RegisterDetailedWidget::bitFieldValueChanged, registerController, + &RegisterController::registerValueChanged); + QObject::connect(registerController, &RegisterController::valueChanged, this, [=](QString val) { + bool ok; + registerDetailedWidget->updateBitFieldsValue(val.toUInt(&ok, 16)); + }); } -void DeviceRegisterMap::toggleAutoread(bool toggled) -{ - autoread = toggled; -} +void DeviceRegisterMap::toggleAutoread(bool toggled) { autoread = toggled; } void DeviceRegisterMap::applyFilters(QString filter) { - if (registerMapTemplate) { - registerMapTableWidget->setFilters(Search::searchForRegisters(registerMapTemplate->getRegisterList(),filter)); - } + if(registerMapTemplate) { + registerMapTableWidget->setFilters( + Search::searchForRegisters(registerMapTemplate->getRegisterList(), filter)); + } } bool DeviceRegisterMap::hasTemplate() { - if (registerMapTemplate) { - return true; - } + if(registerMapTemplate) { + return true; + } - return false; + return false; } void DeviceRegisterMap::initSettings() { - QObject::connect(this, &DeviceRegisterMap::requestRead, registerMapValues, &RegisterMapValues::requestRead); - QObject::connect(this, &DeviceRegisterMap::requestRegisterDump, registerMapValues, &RegisterMapValues::registerDump); - QObject::connect(this, &DeviceRegisterMap::requestWrite, registerMapValues, &RegisterMapValues::requestWrite); + QObject::connect(this, &DeviceRegisterMap::requestRead, registerMapValues, &RegisterMapValues::requestRead); + QObject::connect(this, &DeviceRegisterMap::requestRegisterDump, registerMapValues, + &RegisterMapValues::registerDump); + QObject::connect(this, &DeviceRegisterMap::requestWrite, registerMapValues, &RegisterMapValues::requestWrite); } - diff --git a/plugins/regmap/src/deviceregistermap.hpp b/plugins/regmap/src/deviceregistermap.hpp index e77ea9bfe5..d5c308ce21 100644 --- a/plugins/regmap/src/deviceregistermap.hpp +++ b/plugins/regmap/src/deviceregistermap.hpp @@ -1,16 +1,17 @@ #ifndef DEVICEREGISTERMAP_HPP #define DEVICEREGISTERMAP_HPP +#include "scopy-regmapplugin_export.h" + #include #include #include -#include "scopy-regmapplugin_export.h" class QVBoxLayout; class QDockWidget; -namespace scopy::regmap{ +namespace scopy::regmap { class RegisterMapTemplate; class RegisterModel; class RegisterMapValues; @@ -21,36 +22,34 @@ class RegisterMapTable; class SCOPY_REGMAPPLUGIN_EXPORT DeviceRegisterMap : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit DeviceRegisterMap(RegisterMapTemplate *registerMapTemplate = nullptr, RegisterMapValues *registerMapValues = nullptr, QWidget *parent = nullptr); - ~DeviceRegisterMap(); + explicit DeviceRegisterMap(RegisterMapTemplate *registerMapTemplate = nullptr, + RegisterMapValues *registerMapValues = nullptr, QWidget *parent = nullptr); + ~DeviceRegisterMap(); - void registerChanged(RegisterModel *regModel); - void toggleAutoread(bool toggled); - void applyFilters(QString filter); - bool hasTemplate(); + void registerChanged(RegisterModel *regModel); + void toggleAutoread(bool toggled); + void applyFilters(QString filter); + bool hasTemplate(); private: - - bool autoread = false; - QVBoxLayout *layout; - RegisterMapTemplate *registerMapTemplate ; - RegisterMapValues *registerMapValues; - RegisterController *registerController = nullptr; - - RegisterMapTable *registerMapTableWidget = nullptr; - QDockWidget *docRegisterMapTable = nullptr; - - RegisterDetailedWidget *registerDetailedWidget = nullptr; - void initSettings(); - int selectedRegister; + bool autoread = false; + QVBoxLayout *layout; + RegisterMapTemplate *registerMapTemplate; + RegisterMapValues *registerMapValues; + RegisterController *registerController = nullptr; + + RegisterMapTable *registerMapTableWidget = nullptr; + QDockWidget *docRegisterMapTable = nullptr; + + RegisterDetailedWidget *registerDetailedWidget = nullptr; + void initSettings(); + int selectedRegister; Q_SIGNALS: - void requestRead(uint32_t address); - void requestWrite(uint32_t address, uint32_t value); - void requestRegisterDump(QString path); - - + void requestRead(uint32_t address); + void requestWrite(uint32_t address, uint32_t value); + void requestRegisterDump(QString path); }; -} +} // namespace scopy::regmap #endif // DEVICEREGISTERMAP_HPP diff --git a/plugins/regmap/src/jsonformatedelement.cpp b/plugins/regmap/src/jsonformatedelement.cpp index 68adf86608..3adaeb770e 100644 --- a/plugins/regmap/src/jsonformatedelement.cpp +++ b/plugins/regmap/src/jsonformatedelement.cpp @@ -2,50 +2,30 @@ using namespace scopy::regmap; -JsonFormatedElement::JsonFormatedElement(QString fileName, QList *compatibleDevices, bool isAxiCompatible, bool useRegisterDescriptionAsName, bool useBifieldDescriptionAsName) - : fileName(fileName), - compatibleDevices(compatibleDevices), - isAxiCompatible(isAxiCompatible), - useRegisterDescriptionAsName(useRegisterDescriptionAsName), - useBifieldDescriptionAsName(useBifieldDescriptionAsName) -{ +JsonFormatedElement::JsonFormatedElement(QString fileName, QList *compatibleDevices, bool isAxiCompatible, + bool useRegisterDescriptionAsName, bool useBifieldDescriptionAsName) + : fileName(fileName) + , compatibleDevices(compatibleDevices) + , isAxiCompatible(isAxiCompatible) + , useRegisterDescriptionAsName(useRegisterDescriptionAsName) + , useBifieldDescriptionAsName(useBifieldDescriptionAsName) +{} -} +QString JsonFormatedElement::getFileName() const { return fileName; } -QString JsonFormatedElement::getFileName() const -{ - return fileName; -} +QList *JsonFormatedElement::getCompatibleDevices() const { return compatibleDevices; } -QList* JsonFormatedElement::getCompatibleDevices() const -{ - return compatibleDevices; -} +void JsonFormatedElement::addCompatibleDevice(QString device) { compatibleDevices->push_back(device); } -void JsonFormatedElement::addCompatibleDevice(QString device) -{ - compatibleDevices->push_back(device); -} +bool JsonFormatedElement::getIsAxiCompatible() const { return isAxiCompatible; } -bool JsonFormatedElement::getIsAxiCompatible() const -{ - return isAxiCompatible; -} - -bool JsonFormatedElement::getUseBifieldNameAsDescription() const -{ - return useBifieldDescriptionAsName; -} +bool JsonFormatedElement::getUseBifieldNameAsDescription() const { return useBifieldDescriptionAsName; } QString JsonFormatedElement::toString() { - return QString("Filename : " + fileName + " Compatible Dev: " + compatibleDevices->length() + - " isAxiCompatible :" + isAxiCompatible + - " useRegisterDescriptionAsName: " + useRegisterDescriptionAsName + - " useBifieldDescriptionAsName: " + useBifieldDescriptionAsName); + return QString("Filename : " + fileName + " Compatible Dev: " + compatibleDevices->length() + + " isAxiCompatible :" + isAxiCompatible + " useRegisterDescriptionAsName: " + + useRegisterDescriptionAsName + " useBifieldDescriptionAsName: " + useBifieldDescriptionAsName); } -bool JsonFormatedElement::getUseRegisterNameAsDescription() const -{ - return useRegisterDescriptionAsName; -} +bool JsonFormatedElement::getUseRegisterNameAsDescription() const { return useRegisterDescriptionAsName; } diff --git a/plugins/regmap/src/jsonformatedelement.hpp b/plugins/regmap/src/jsonformatedelement.hpp index 7b5f4d6235..af85cf4fac 100644 --- a/plugins/regmap/src/jsonformatedelement.hpp +++ b/plugins/regmap/src/jsonformatedelement.hpp @@ -3,27 +3,28 @@ #include -namespace scopy::regmap{ +namespace scopy::regmap { class JsonFormatedElement { public: - JsonFormatedElement(QString fileName, QList *compatibleDevices = new QList(), bool isAxiCompatible = false, bool useRegisterDescriptionAsName = false, bool useBifieldDescriptionAsName = false); - QString getFileName() const; + JsonFormatedElement(QString fileName, QList *compatibleDevices = new QList(), + bool isAxiCompatible = false, bool useRegisterDescriptionAsName = false, + bool useBifieldDescriptionAsName = false); + QString getFileName() const; - QList *getCompatibleDevices() const; - void addCompatibleDevice(QString device); - bool getIsAxiCompatible() const; - bool getUseRegisterNameAsDescription() const; - bool getUseBifieldNameAsDescription() const; - QString toString(); - -private : - QString fileName; - QList *compatibleDevices; - bool isAxiCompatible = false; - bool useRegisterDescriptionAsName; - bool useBifieldDescriptionAsName; + QList *getCompatibleDevices() const; + void addCompatibleDevice(QString device); + bool getIsAxiCompatible() const; + bool getUseRegisterNameAsDescription() const; + bool getUseBifieldNameAsDescription() const; + QString toString(); +private: + QString fileName; + QList *compatibleDevices; + bool isAxiCompatible = false; + bool useRegisterDescriptionAsName; + bool useBifieldDescriptionAsName; }; -} +} // namespace scopy::regmap #endif // JSONFORMATEDELEMENT_HPP diff --git a/plugins/regmap/src/logging_categories.cpp b/plugins/regmap/src/logging_categories.cpp index 1be2ff75bf..e941def983 100644 --- a/plugins/regmap/src/logging_categories.cpp +++ b/plugins/regmap/src/logging_categories.cpp @@ -38,29 +38,27 @@ Q_LOGGING_CATEGORY(CAT_REGMAP, "REGISTERMAP") Q_LOGGING_CATEGORY(CAT_REGISTER_MAP_TABLE, "RegisterMapTable") #endif -void SetScopyQDebugMessagePattern() { +void SetScopyQDebugMessagePattern() +{ - qSetMessagePattern( - "[ " - #ifdef QDEBUG_LOG_MSG_TYPE - QDEBUG_LOG_MSG_TYPE_STR " " - QDEBUG_CATEGORY_STR " " - #endif - #ifdef QDEBUG_LOG_TIME - QDEBUG_LOG_TIME_STR - #endif - #ifdef QDEBUG_LOG_DATE - QDEBUG_LOG_DATE_STR - #endif - #ifdef QDEBUG_LOG_CATEGORY - QDEBUG_CATEGORY_STR - #endif - " ] " - #ifdef QDEBUG_LOG_FILE - QDEBUG_LOG_FILE_STR - #endif + qSetMessagePattern("[ " +#ifdef QDEBUG_LOG_MSG_TYPE + QDEBUG_LOG_MSG_TYPE_STR " " QDEBUG_CATEGORY_STR " " +#endif +#ifdef QDEBUG_LOG_TIME + QDEBUG_LOG_TIME_STR +#endif +#ifdef QDEBUG_LOG_DATE + QDEBUG_LOG_DATE_STR +#endif +#ifdef QDEBUG_LOG_CATEGORY + QDEBUG_CATEGORY_STR +#endif + " ] " +#ifdef QDEBUG_LOG_FILE + QDEBUG_LOG_FILE_STR +#endif - " - " - "%{message}" - ); + " - " + "%{message}"); } diff --git a/plugins/regmap/src/logging_categories.h b/plugins/regmap/src/logging_categories.h index 3cd1e506ec..71685683c4 100644 --- a/plugins/regmap/src/logging_categories.h +++ b/plugins/regmap/src/logging_categories.h @@ -29,10 +29,10 @@ //#define QDEBUG_CATEGORY //#define QDEBUG_FUNCTION - #define QDEBUG_LOG_TIME_STR "%{time h:mm:ss.zzz}" #define QDEBUG_LOG_DATE_STR "%{time yyyyMMdd }" -#define QDEBUG_LOG_MSG_TYPE_STR "%{if-debug}D%{endif}%{if-info}I%{endif}%{if-warning}W%{endif}%{if-critical}C%{endif}%{if-fatal}F%{endif}" +#define QDEBUG_LOG_MSG_TYPE_STR \ + "%{if-debug}D%{endif}%{if-info}I%{endif}%{if-warning}W%{endif}%{if-critical}C%{endif}%{if-fatal}F%{endif}" #define QDEBUG_LOG_FILE_PREFIX_STR "file://" #define QDEBUG_LOG_FILE_NAME_STR "%{file}:" #define QDEBUG_LOG_LINE_NR_STR "%{line}" @@ -43,7 +43,6 @@ #define QDEBUG_PID_STR "%{pid}" #define QDEBUG_APP_STR "%{appname}" - #ifndef QT_NO_DEBUG_OUTPUT Q_DECLARE_LOGGING_CATEGORY(CAT_IIO_OPERATION) Q_DECLARE_LOGGING_CATEGORY(CAT_OSCILLOSCOPE) diff --git a/plugins/regmap/src/qtextspinbox.cpp b/plugins/regmap/src/qtextspinbox.cpp index ff7f840b10..22c4a776ea 100644 --- a/plugins/regmap/src/qtextspinbox.cpp +++ b/plugins/regmap/src/qtextspinbox.cpp @@ -1,34 +1,28 @@ #include "qtextspinbox.hpp" -QTextSpinBox::QTextSpinBox(QWidget *parent) : QSpinBox(parent) -{ -} +QTextSpinBox::QTextSpinBox(QWidget *parent) + : QSpinBox(parent) +{} void QTextSpinBox::setValues(QList *acceptedValues) { - this->acceptedValues = acceptedValues; - setRange(1, acceptedValues->size()); + this->acceptedValues = acceptedValues; + setRange(1, acceptedValues->size()); } -QString QTextSpinBox::textFromValue(int value) const -{ - return acceptedValues->value(value); -} +QString QTextSpinBox::textFromValue(int value) const { return acceptedValues->value(value); } -int QTextSpinBox::valueFromText(const QString &text) const -{ - return acceptedValues->indexOf(text); -} +int QTextSpinBox::valueFromText(const QString &text) const { return acceptedValues->indexOf(text); } QValidator::State QTextSpinBox::validate(QString &text, int &pos) const { - if(acceptedValues->contains(text)) { - return QValidator::Acceptable; - } + if(acceptedValues->contains(text)) { + return QValidator::Acceptable; + } - if(!text.isNull()) { - return QValidator::Intermediate; - } + if(!text.isNull()) { + return QValidator::Intermediate; + } - return QValidator::Invalid; + return QValidator::Invalid; } diff --git a/plugins/regmap/src/qtextspinbox.hpp b/plugins/regmap/src/qtextspinbox.hpp index 586f78e7e4..7c90c0c847 100644 --- a/plugins/regmap/src/qtextspinbox.hpp +++ b/plugins/regmap/src/qtextspinbox.hpp @@ -1,23 +1,24 @@ #ifndef QTEXTSPINBOX_HPP #define QTEXTSPINBOX_HPP -#include +#include "scopy-regmapplugin_export.h" + #include +#include #include -#include "scopy-regmapplugin_export.h" class SCOPY_REGMAPPLUGIN_EXPORT QTextSpinBox : public QSpinBox { public: - explicit QTextSpinBox(QWidget *parent = 0); + explicit QTextSpinBox(QWidget *parent = 0); - void setValues(QList *acceptedValues); + void setValues(QList *acceptedValues); private: - QString textFromValue(int value) const; - int valueFromText(const QString &text) const; - QValidator::State validate(QString &text, int &pos) const; - QList *acceptedValues; + QString textFromValue(int value) const; + int valueFromText(const QString &text) const; + QValidator::State validate(QString &text, int &pos) const; + QList *acceptedValues; }; #endif // QTEXTSPINBOX_HPP diff --git a/plugins/regmap/src/readwrite/fileregisterreadstrategy.cpp b/plugins/regmap/src/readwrite/fileregisterreadstrategy.cpp index 130a56f39f..e1b440dac3 100644 --- a/plugins/regmap/src/readwrite/fileregisterreadstrategy.cpp +++ b/plugins/regmap/src/readwrite/fileregisterreadstrategy.cpp @@ -1,32 +1,33 @@ #include "fileregisterreadstrategy.hpp" -#include "iregisterreadstrategy.hpp" #include "../logging_categories.h" -#include +#include "iregisterreadstrategy.hpp" + #include +#include #include using namespace scopy::regmap; FileRegisterReadStrategy::FileRegisterReadStrategy(QString path) - :path(path) -{ -} + : path(path) +{} void FileRegisterReadStrategy::read(uint32_t address) { QFile file(path); - if (!file.open(QIODevice::ReadOnly)) { + if(!file.open(QIODevice::ReadOnly)) { qDebug(CAT_IIO_OPERATION) << "device read error " << file.errorString(); Q_EMIT readError("device read error"); } else { - while (!file.atEnd()) { + while(!file.atEnd()) { QString line(file.readLine()); QString addr(line.split(',').first()); - if (addr.contains(QString::number(address,16))) { + if(addr.contains(QString::number(address, 16))) { bool ok; - Q_EMIT readDone(address,line.split(',').at(1).toInt(&ok,16)); - qDebug(CAT_IIO_OPERATION) << "device read success for " << address << " with value " < #include -#include "../logging_categories.h" using namespace scopy; using namespace regmap; FileRegisterWriteStrategy::FileRegisterWriteStrategy(QString path) - :path(path) -{ - -} + : path(path) +{} void FileRegisterWriteStrategy::write(uint32_t address, uint32_t val) { - //TODO HOW SHOULD WE TREAT WRITE ? + // TODO HOW SHOULD WE TREAT WRITE ? QFile file(path); QTextStream exportStream(&file); - if (!file.isOpen()) { + if(!file.isOpen()) { file.open(QIODevice::Append); exportStream << QString::number(address, 16) << "," << QString::number(val, 16) << "\n"; } else { @@ -26,5 +25,6 @@ void FileRegisterWriteStrategy::write(uint32_t address, uint32_t val) Q_EMIT writeError("device write err"); } - if (file.isOpen()) file.close(); + if(file.isOpen()) + file.close(); } diff --git a/plugins/regmap/src/readwrite/fileregisterwritestrategy.hpp b/plugins/regmap/src/readwrite/fileregisterwritestrategy.hpp index da7c8bfea0..08fb897066 100644 --- a/plugins/regmap/src/readwrite/fileregisterwritestrategy.hpp +++ b/plugins/regmap/src/readwrite/fileregisterwritestrategy.hpp @@ -4,18 +4,18 @@ #include "iregisterwritestrategy.hpp" class QString; -namespace scopy::regmap{ -class FileRegisterWriteStrategy: public IRegisterWriteStrategy +namespace scopy::regmap { +class FileRegisterWriteStrategy : public IRegisterWriteStrategy { public: FileRegisterWriteStrategy(QString path); private: - QString path; + QString path; // IRegisterWriteStrategy interface public: void write(uint32_t address, uint32_t val); }; -} +} // namespace scopy::regmap #endif // FILEREGISTERWRITESTRATEGY_HPP diff --git a/plugins/regmap/src/readwrite/iioregisterreadstrategy.cpp b/plugins/regmap/src/readwrite/iioregisterreadstrategy.cpp index 3f3d4b98fd..b91c7415f5 100644 --- a/plugins/regmap/src/readwrite/iioregisterreadstrategy.cpp +++ b/plugins/regmap/src/readwrite/iioregisterreadstrategy.cpp @@ -1,28 +1,28 @@ #include "iioregisterreadstrategy.hpp" -#include "iregisterreadstrategy.hpp" #include "../logging_categories.h" +#include "iregisterreadstrategy.hpp" using namespace scopy; using namespace regmap; IIORegisterReadStrategy::IIORegisterReadStrategy(struct iio_device *dev) - :dev(dev) -{ -} + : dev(dev) +{} void IIORegisterReadStrategy::read(uint32_t address) { - uint32_t reg_val; + uint32_t reg_val; - ssize_t read = iio_device_reg_read(dev, address, ®_val); - if (read < 0) { - char err[1024]; - iio_strerror(-(int)read, err, sizeof(err)); - qDebug(CAT_IIO_OPERATION) << "device read error " << err; - Q_EMIT readError("device read error"); + ssize_t read = iio_device_reg_read(dev, address, ®_val); + if(read < 0) { + char err[1024]; + iio_strerror(-(int)read, err, sizeof(err)); + qDebug(CAT_IIO_OPERATION) << "device read error " << err; + Q_EMIT readError("device read error"); } else { - qDebug(CAT_IIO_OPERATION) << "device read success for register " << address << " with value " < + #include -namespace scopy::regmap{ +namespace scopy::regmap { class IIORegisterReadStrategy : public IRegisterReadStrategy { @@ -17,5 +19,5 @@ class IIORegisterReadStrategy : public IRegisterReadStrategy private: struct iio_device *dev; }; -} +} // namespace scopy::regmap #endif // IIOREGISTERREADSTRATEGY_HPP diff --git a/plugins/regmap/src/readwrite/iioregisterwritestrategy.cpp b/plugins/regmap/src/readwrite/iioregisterwritestrategy.cpp index a61a029366..4f7e62fdd4 100644 --- a/plugins/regmap/src/readwrite/iioregisterwritestrategy.cpp +++ b/plugins/regmap/src/readwrite/iioregisterwritestrategy.cpp @@ -1,23 +1,24 @@ #include "iioregisterwritestrategy.hpp" + #include "../logging_categories.h" using namespace scopy::regmap; IIORegisterWriteStrategy::IIORegisterWriteStrategy(struct iio_device *dev) - :dev(dev) -{ -} + : dev(dev) +{} void IIORegisterWriteStrategy::write(uint32_t address, uint32_t val) { - ssize_t write = iio_device_reg_write(dev, address, val); - if (write < 0) { - char err[1024]; - iio_strerror(-(int)write, err, sizeof(err)); - qDebug(CAT_IIO_OPERATION) << "device write error " << err; - Q_EMIT writeError("device write err"); - } else { - qDebug(CAT_IIO_OPERATION) << "device write successfull for register " << address << " with value " << val; - Q_EMIT writeSuccess(address); - } + ssize_t write = iio_device_reg_write(dev, address, val); + if(write < 0) { + char err[1024]; + iio_strerror(-(int)write, err, sizeof(err)); + qDebug(CAT_IIO_OPERATION) << "device write error " << err; + Q_EMIT writeError("device write err"); + } else { + qDebug(CAT_IIO_OPERATION) + << "device write successfull for register " << address << " with value " << val; + Q_EMIT writeSuccess(address); + } } diff --git a/plugins/regmap/src/readwrite/iioregisterwritestrategy.hpp b/plugins/regmap/src/readwrite/iioregisterwritestrategy.hpp index ca167291d5..5e3fe606bb 100644 --- a/plugins/regmap/src/readwrite/iioregisterwritestrategy.hpp +++ b/plugins/regmap/src/readwrite/iioregisterwritestrategy.hpp @@ -2,20 +2,21 @@ #define IIOREGISTERWRITESTRATEGY_HPP #include "iregisterwritestrategy.hpp" + #include -namespace scopy::regmap{ -class IIORegisterWriteStrategy: public IRegisterWriteStrategy +namespace scopy::regmap { +class IIORegisterWriteStrategy : public IRegisterWriteStrategy { public: - IIORegisterWriteStrategy(struct iio_device *dev); + IIORegisterWriteStrategy(struct iio_device *dev); private: - struct iio_device *dev; + struct iio_device *dev; - // IRegisterWriteStrategy interface + // IRegisterWriteStrategy interface public: - void write(uint32_t address, uint32_t val); + void write(uint32_t address, uint32_t val); }; -} +} // namespace scopy::regmap #endif // IIOREGISTERWRITESTRATEGY_HPP diff --git a/plugins/regmap/src/readwrite/iregisterreadstrategy.hpp b/plugins/regmap/src/readwrite/iregisterreadstrategy.hpp index 58566f33af..a90969b215 100644 --- a/plugins/regmap/src/readwrite/iregisterreadstrategy.hpp +++ b/plugins/regmap/src/readwrite/iregisterreadstrategy.hpp @@ -3,17 +3,16 @@ #include -namespace scopy::regmap{ +namespace scopy::regmap { class IRegisterReadStrategy : public QObject { Q_OBJECT public: - virtual void read(uint32_t address) = 0; Q_SIGNALS: void readDone(uint32_t address, uint32_t value); void readError(const char *err); }; -} +} // namespace scopy::regmap #endif // IREGISTERREADSTRATEGY_HPP diff --git a/plugins/regmap/src/readwrite/iregisterwritestrategy.hpp b/plugins/regmap/src/readwrite/iregisterwritestrategy.hpp index 1ddf5f7745..6cb4833e9e 100644 --- a/plugins/regmap/src/readwrite/iregisterwritestrategy.hpp +++ b/plugins/regmap/src/readwrite/iregisterwritestrategy.hpp @@ -3,7 +3,7 @@ #include -namespace scopy::regmap{ +namespace scopy::regmap { class IRegisterWriteStrategy : public QObject { Q_OBJECT @@ -14,5 +14,5 @@ class IRegisterWriteStrategy : public QObject void writeError(const char *err); void writeSuccess(uint32_t address); }; -} +} // namespace scopy::regmap #endif // IREGISTERWRITESTRATEGY_HPP diff --git a/plugins/regmap/src/recycerview/irecyclerviewadapter.hpp b/plugins/regmap/src/recycerview/irecyclerviewadapter.hpp index 816e2471ba..8c5843cab3 100644 --- a/plugins/regmap/src/recycerview/irecyclerviewadapter.hpp +++ b/plugins/regmap/src/recycerview/irecyclerviewadapter.hpp @@ -3,15 +3,14 @@ #include -namespace scopy::regmap{ +namespace scopy::regmap { class IRecyclerViewAdapter : public QObject { - Q_OBJECT + Q_OBJECT public: - virtual void generateWidget(int index) = 0; + virtual void generateWidget(int index) = 0; Q_SIGNALS: - void widgetGenerated(int index, QWidget *widget); - + void widgetGenerated(int index, QWidget *widget); }; -} +} // namespace scopy::regmap #endif // IRECYCLERVIEWADAPTER_HPP diff --git a/plugins/regmap/src/recycerview/recyclerview.cpp b/plugins/regmap/src/recycerview/recyclerview.cpp index 922987cfd2..4044a79ce3 100644 --- a/plugins/regmap/src/recycerview/recyclerview.cpp +++ b/plugins/regmap/src/recycerview/recyclerview.cpp @@ -1,226 +1,204 @@ #include "recyclerview.hpp" -#include -#include -#include -#include + #include #include +#include +#include #include +#include +#include + #include using namespace scopy::regmap; -RecyclerView::RecyclerView(QList *widgets,QWidget *parent) - : QWidget(parent), - widgets(widgets) -{ - this->installEventFilter(this); - layout = new QHBoxLayout(); - this->setLayout(layout); - layout->setMargin(0); - layout->setSpacing(0); - - - bitFieldsWidgetLayout = new QGridLayout(); - bitFieldsWidgetLayout->setMargin(0); - bitFieldsWidgetLayout->setSpacing(0); - QWidget *bitFieldsWidget = new QWidget(this); - bitFieldsWidget->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Maximum); - bitFieldsWidget->setLayout(bitFieldsWidgetLayout); - - m_scrollArea = new VerticalScrollArea(this); - m_scrollArea->setWidget(bitFieldsWidget); - m_scrollArea->verticalScrollBar()->setVisible(false); - layout->addWidget(m_scrollArea); - - slider = new QSlider(this); - slider->setInvertedAppearance(true); - slider->setInvertedControls(true); - - QObject::connect(m_scrollArea->verticalScrollBar(),&QAbstractSlider::valueChanged, this, [=](int value){ - if (value == m_scrollArea->verticalScrollBar()->minimum()) { - slider->setValue(m_scrollBarCurrentValue - 1); - m_scrollArea->verticalScrollBar()->setValue(value + 1 ); - } - if (value == m_scrollArea->verticalScrollBar()->maximum()){ - slider->setValue(m_scrollBarCurrentValue + 1); - m_scrollArea->verticalScrollBar()->setValue(value - 1 ); - } - - }); - layout->addWidget(slider); - - QObject::connect(this, &RecyclerView::requestInit, this, &RecyclerView::init , Qt::QueuedConnection); +RecyclerView::RecyclerView(QList *widgets, QWidget *parent) + : QWidget(parent) + , widgets(widgets) +{ + this->installEventFilter(this); + layout = new QHBoxLayout(); + this->setLayout(layout); + layout->setMargin(0); + layout->setSpacing(0); + + bitFieldsWidgetLayout = new QGridLayout(); + bitFieldsWidgetLayout->setMargin(0); + bitFieldsWidgetLayout->setSpacing(0); + QWidget *bitFieldsWidget = new QWidget(this); + bitFieldsWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); + bitFieldsWidget->setLayout(bitFieldsWidgetLayout); + + m_scrollArea = new VerticalScrollArea(this); + m_scrollArea->setWidget(bitFieldsWidget); + m_scrollArea->verticalScrollBar()->setVisible(false); + layout->addWidget(m_scrollArea); + + slider = new QSlider(this); + slider->setInvertedAppearance(true); + slider->setInvertedControls(true); + + QObject::connect(m_scrollArea->verticalScrollBar(), &QAbstractSlider::valueChanged, this, [=](int value) { + if(value == m_scrollArea->verticalScrollBar()->minimum()) { + slider->setValue(m_scrollBarCurrentValue - 1); + m_scrollArea->verticalScrollBar()->setValue(value + 1); + } + if(value == m_scrollArea->verticalScrollBar()->maximum()) { + slider->setValue(m_scrollBarCurrentValue + 1); + m_scrollArea->verticalScrollBar()->setValue(value - 1); + } + }); + layout->addWidget(slider); + + QObject::connect(this, &RecyclerView::requestInit, this, &RecyclerView::init, Qt::QueuedConnection); } RecyclerView::~RecyclerView() { - delete bitFieldsWidgetLayout; - delete widgetMap; - delete m_scrollArea; - delete layout; + delete bitFieldsWidgetLayout; + delete widgetMap; + delete m_scrollArea; + delete layout; } void RecyclerView::init() { - widgetMap = new QMap(); - - populateMap(); + widgetMap = new QMap(); - m_scrollBarCurrentValue = slider->value(); + populateMap(); - QObject::connect(slider, &QAbstractSlider::valueChanged, this, [=](int value){ + m_scrollBarCurrentValue = slider->value(); - if(m_scrollBarCurrentValue < value) { - int diff = value - (activeWidgetTop - widgets->begin()); + QObject::connect(slider, &QAbstractSlider::valueChanged, this, [=](int value) { + if(m_scrollBarCurrentValue < value) { + int diff = value - (activeWidgetTop - widgets->begin()); - while (diff > 0 ) { - scrollDown(); - diff--; - } + while(diff > 0) { + scrollDown(); + diff--; + } - } else { - int diff = (activeWidgetTop - widgets->begin()) - value; - while (diff > 0 ) { - scrollUp(); - diff--; - } - } - m_scrollBarCurrentValue = value; - }); + } else { + int diff = (activeWidgetTop - widgets->begin()) - value; + while(diff > 0) { + scrollUp(); + diff--; + } + } + m_scrollBarCurrentValue = value; + }); - Q_EMIT initDone(); + Q_EMIT initDone(); } -QMap *RecyclerView::getWidgetsMap() const -{ - return widgetMap; -} +QMap *RecyclerView::getWidgetsMap() const { return widgetMap; } -void RecyclerView::setWidgetMap(QMap *newWidgets) -{ - widgetMap = newWidgets; -} +void RecyclerView::setWidgetMap(QMap *newWidgets) { widgetMap = newWidgets; } void RecyclerView::addWidget(int index, QWidget *widget) { - widgetMap->insert(index,widget); - bitFieldsWidgetLayout->addWidget(widget, index, 0); + widgetMap->insert(index, widget); + bitFieldsWidgetLayout->addWidget(widget, index, 0); } -QWidget *RecyclerView::getWidgetAtIndex(int index) -{ - return widgetMap->value(index); -} +QWidget *RecyclerView::getWidgetAtIndex(int index) { return widgetMap->value(index); } void RecyclerView::hideAll() { - QMap::iterator mapIterator; - for (mapIterator = widgetMap->begin(); mapIterator != widgetMap->end(); ++mapIterator) { - mapIterator.value()->hide(); - } + QMap::iterator mapIterator; + for(mapIterator = widgetMap->begin(); mapIterator != widgetMap->end(); ++mapIterator) { + mapIterator.value()->hide(); + } } void RecyclerView::showAll() { - QMap::iterator mapIterator; - for (mapIterator = widgetMap->begin(); mapIterator != widgetMap->end(); ++mapIterator) { - mapIterator.value()->show(); - } + QMap::iterator mapIterator; + for(mapIterator = widgetMap->begin(); mapIterator != widgetMap->end(); ++mapIterator) { + mapIterator.value()->show(); + } } -void RecyclerView::setActiveWidgets(QList *widgets) -{ - this->widgets = widgets; -} +void RecyclerView::setActiveWidgets(QList *widgets) { this->widgets = widgets; } void RecyclerView::scrollTo(int index) { - m_scrollArea->verticalScrollBar()->setValue(0); - slider->setValue(index); + m_scrollArea->verticalScrollBar()->setValue(0); + slider->setValue(index); } -void RecyclerView::setMaxrowCount(int maxRowCount) -{ - this->maxRowCount = maxRowCount; -} +void RecyclerView::setMaxrowCount(int maxRowCount) { this->maxRowCount = maxRowCount; } void RecyclerView::scrollDown() { - if (activeWidgetBottom != widgets->end()) { - if (widgetMap->contains(*activeWidgetBottom)) { - widgetMap->value(*activeWidgetBottom)->show(); - } - else { - Q_EMIT requestWidget(*activeWidgetBottom); - } - - if (widgetMap->value(*activeWidgetTop)) { - widgetMap->value(*activeWidgetTop)->hide(); - } - - activeWidgetTop++; - activeWidgetBottom++; - } + if(activeWidgetBottom != widgets->end()) { + if(widgetMap->contains(*activeWidgetBottom)) { + widgetMap->value(*activeWidgetBottom)->show(); + } else { + Q_EMIT requestWidget(*activeWidgetBottom); + } + + if(widgetMap->value(*activeWidgetTop)) { + widgetMap->value(*activeWidgetTop)->hide(); + } + + activeWidgetTop++; + activeWidgetBottom++; + } } void RecyclerView::scrollUp() { - if (activeWidgetTop != widgets->begin()) { - activeWidgetTop--; - activeWidgetBottom--; - - if (widgetMap->contains(*activeWidgetTop)) { - widgetMap->value(*activeWidgetTop)->show(); - } - else { - Q_EMIT requestWidget(*activeWidgetTop); - } - if (widgetMap->value(*activeWidgetBottom)) { - widgetMap->value(*activeWidgetBottom)->hide(); - } - } + if(activeWidgetTop != widgets->begin()) { + activeWidgetTop--; + activeWidgetBottom--; + + if(widgetMap->contains(*activeWidgetTop)) { + widgetMap->value(*activeWidgetTop)->show(); + } else { + Q_EMIT requestWidget(*activeWidgetTop); + } + if(widgetMap->value(*activeWidgetBottom)) { + widgetMap->value(*activeWidgetBottom)->hide(); + } + } } void RecyclerView::populateMap() { - QList::iterator mapIterator = widgets->begin(); - if (widgetMap->isEmpty()) { - Q_EMIT requestWidget(*mapIterator); - ++mapIterator; - } - - //TODO find a way to autocompute max row count - // maxRowCount = 10; - - int i = 0; - while ( i < maxRowCount && mapIterator != widgets->end()) { - if (widgetMap->contains(*mapIterator)) { - widgetMap->value(*mapIterator)->show(); - } - else { - Q_EMIT requestWidget(*mapIterator); - } - ++mapIterator; - ++i; - } - - activeWidgetBottom = mapIterator; - activeWidgetTop = widgets->begin(); - - slider->setMaximum(widgets->length()); - slider->setSingleStep(1); + QList::iterator mapIterator = widgets->begin(); + if(widgetMap->isEmpty()) { + Q_EMIT requestWidget(*mapIterator); + ++mapIterator; + } + + // TODO find a way to autocompute max row count + // maxRowCount = 10; + + int i = 0; + while(i < maxRowCount && mapIterator != widgets->end()) { + if(widgetMap->contains(*mapIterator)) { + widgetMap->value(*mapIterator)->show(); + } else { + Q_EMIT requestWidget(*mapIterator); + } + ++mapIterator; + ++i; + } + + activeWidgetBottom = mapIterator; + activeWidgetTop = widgets->begin(); + + slider->setMaximum(widgets->length()); + slider->setSingleStep(1); } bool RecyclerView::eventFilter(QObject *watched, QEvent *event) { - if( event->type() == QScrollEvent::Scroll ) { - QScrollEvent *scrollEvent = static_cast(event); - slider->setSliderPosition(m_scrollBarCurrentValue + 1); - } + if(event->type() == QScrollEvent::Scroll) { + QScrollEvent *scrollEvent = static_cast(event); + slider->setSliderPosition(m_scrollBarCurrentValue + 1); + } - return QWidget::eventFilter(watched,event); + return QWidget::eventFilter(watched, event); } - - - diff --git a/plugins/regmap/src/recycerview/recyclerview.hpp b/plugins/regmap/src/recycerview/recyclerview.hpp index 027f97e1fb..e540f1ff97 100644 --- a/plugins/regmap/src/recycerview/recyclerview.hpp +++ b/plugins/regmap/src/recycerview/recyclerview.hpp @@ -1,9 +1,9 @@ #ifndef RECYCLERVIEW_H #define RECYCLERVIEW_H +#include #include #include -#include #include @@ -11,54 +11,54 @@ class QSlider; class QGridLayout; class QHBoxLayout; -namespace scopy::regmap{ +namespace scopy::regmap { class RecyclerView : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit RecyclerView(QList *widgets, QWidget *parent = nullptr); - ~RecyclerView(); + explicit RecyclerView(QList *widgets, QWidget *parent = nullptr); + ~RecyclerView(); - QMap *getWidgetsMap() const; - void setWidgetMap(QMap *newWidgets); - void addWidget(int index, QWidget *widget); - QWidget* getWidgetAtIndex(int index); + QMap *getWidgetsMap() const; + void setWidgetMap(QMap *newWidgets); + void addWidget(int index, QWidget *widget); + QWidget *getWidgetAtIndex(int index); - void hideAll(); - void showAll(); - void setActiveWidgets(QList *widgets); - void scrollTo(int index); - void setMaxrowCount(int maxRowCount); + void hideAll(); + void showAll(); + void setActiveWidgets(QList *widgets); + void scrollTo(int index); + void setMaxrowCount(int maxRowCount); - void init(); - void populateMap(); + void init(); + void populateMap(); Q_SIGNALS: - void requestWidget(int index); - void initDone(); - void requestInit(); + void requestWidget(int index); + void initDone(); + void requestInit(); private: - int maxRowCount; - QSlider *slider ; - VerticalScrollArea *m_scrollArea; - int m_scrollBarCurrentValue; + int maxRowCount; + QSlider *slider; + VerticalScrollArea *m_scrollArea; + int m_scrollBarCurrentValue; - QGridLayout *bitFieldsWidgetLayout; - QHBoxLayout *layout; + QGridLayout *bitFieldsWidgetLayout; + QHBoxLayout *layout; - QMap *widgetMap; - QList *widgets; - QList::iterator activeWidgetTop; - QList::iterator activeWidgetBottom; + QMap *widgetMap; + QList *widgets; + QList::iterator activeWidgetTop; + QList::iterator activeWidgetBottom; - void scrollDown(); - void scrollUp(); + void scrollDown(); + void scrollUp(); - // QObject interface + // QObject interface public: - bool eventFilter(QObject *watched, QEvent *event); + bool eventFilter(QObject *watched, QEvent *event); }; -} +} // namespace scopy::regmap #endif // RECYCLERVIEW_H diff --git a/plugins/regmap/src/recycerview/registermaptable.cpp b/plugins/regmap/src/recycerview/registermaptable.cpp index fdbca6b31b..c887839b4e 100644 --- a/plugins/regmap/src/recycerview/registermaptable.cpp +++ b/plugins/regmap/src/recycerview/registermaptable.cpp @@ -1,102 +1,106 @@ -#include "recyclerview.hpp" #include "registermaptable.hpp" -#include #include "../logging_categories.h" +#include "recyclerview.hpp" + +#include + #include #include using namespace scopy; using namespace regmap; -RegisterMapTable::RegisterMapTable(QMap *registerModels, QWidget *parent) - :registerModels(registerModels) +RegisterMapTable::RegisterMapTable(QMap *registerModels, QWidget *parent) + : registerModels(registerModels) { - registersMap = new QMap(); - - QList *widgets = new QList(); - foreach(uint32_t index, registerModels->keys()) { - widgets->push_back((int)index); - } - - recyclerView = new RecyclerView(widgets, parent); - recyclerView->setMaxrowCount(10); - - QObject::connect(recyclerView, &RecyclerView::requestWidget, this, &RegisterMapTable::generateWidget); - QObject::connect(this, &RegisterMapTable::widgetGenerated, recyclerView, &RecyclerView::addWidget); - QObject::connect(recyclerView, &RecyclerView::initDone, this, [=](){ - selectedAddress = 0; - registersMap->value(selectedAddress)->setRegisterSelected(true); - }, Qt::QueuedConnection); - - Q_EMIT recyclerView->requestInit(); + registersMap = new QMap(); + + QList *widgets = new QList(); + foreach(uint32_t index, registerModels->keys()) { + widgets->push_back((int)index); + } + + recyclerView = new RecyclerView(widgets, parent); + recyclerView->setMaxrowCount(10); + + QObject::connect(recyclerView, &RecyclerView::requestWidget, this, &RegisterMapTable::generateWidget); + QObject::connect(this, &RegisterMapTable::widgetGenerated, recyclerView, &RecyclerView::addWidget); + QObject::connect( + recyclerView, &RecyclerView::initDone, this, + [=]() { + selectedAddress = 0; + registersMap->value(selectedAddress)->setRegisterSelected(true); + }, + Qt::QueuedConnection); + + Q_EMIT recyclerView->requestInit(); } -QWidget *RegisterMapTable::getWidget() -{ - return recyclerView; -} +QWidget *RegisterMapTable::getWidget() { return recyclerView; } void RegisterMapTable::setFilters(QList filters) { - qDebug(CAT_REGISTER_MAP_TABLE) << "Apply filters "; - QList *widgets = new QList(); - foreach(uint32_t index, filters) { - widgets->push_back((int)index); - } - - recyclerView->hideAll(); - recyclerView->setActiveWidgets(widgets); - recyclerView->populateMap(); + qDebug(CAT_REGISTER_MAP_TABLE) << "Apply filters "; + QList *widgets = new QList(); + foreach(uint32_t index, filters) { + widgets->push_back((int)index); + } + + recyclerView->hideAll(); + recyclerView->setActiveWidgets(widgets); + recyclerView->populateMap(); } void RegisterMapTable::valueUpdated(uint32_t address, uint32_t value) { - qDebug(CAT_REGISTER_MAP_TABLE) << "Update value for register at address " << address; - if (registersMap->contains(address)) { - registersMap->value(address)->valueUpdated(value); - } else { - qDebug(CAT_REGISTER_MAP_TABLE) << "No register was found for address " << address; - } + qDebug(CAT_REGISTER_MAP_TABLE) << "Update value for register at address " << address; + if(registersMap->contains(address)) { + registersMap->value(address)->valueUpdated(value); + } else { + qDebug(CAT_REGISTER_MAP_TABLE) << "No register was found for address " << address; + } } void RegisterMapTable::scrollTo(uint32_t index) { - if (registerModels->keys().contains(index)) { - - QMap::iterator iterator = registerModels->begin(); - int i = 0; - while (iterator != registerModels->end() ) { - if (iterator.key() == index) { - recyclerView->scrollTo(i); - setRegisterSelected(iterator.key()); - break; - } - i++; - iterator++; - } - } + if(registerModels->keys().contains(index)) { + + QMap::iterator iterator = registerModels->begin(); + int i = 0; + while(iterator != registerModels->end()) { + if(iterator.key() == index) { + recyclerView->scrollTo(i); + setRegisterSelected(iterator.key()); + break; + } + i++; + iterator++; + } + } } void RegisterMapTable::setRegisterSelected(uint32_t address) { - if (registersMap->value(selectedAddress)) { - registersMap->value(selectedAddress)->setRegisterSelected(false); - } - selectedAddress = address; - if (registersMap->value(address)) { - registersMap->value(address)->setRegisterSelected(true); - } + if(registersMap->value(selectedAddress)) { + registersMap->value(selectedAddress)->setRegisterSelected(false); + } + selectedAddress = address; + if(registersMap->value(address)) { + registersMap->value(address)->setRegisterSelected(true); + } } void RegisterMapTable::generateWidget(int index) { - qDebug(CAT_REGISTER_MAP_TABLE) << "Generate new widget"; - RegisterSimpleWidgetFactory registerSimpleWidgetFactory; - RegisterSimpleWidget *registerSimpleWidget = registerSimpleWidgetFactory.buildWidget(registerModels->value(index)); + qDebug(CAT_REGISTER_MAP_TABLE) << "Generate new widget"; + RegisterSimpleWidgetFactory registerSimpleWidgetFactory; + RegisterSimpleWidget *registerSimpleWidget = + registerSimpleWidgetFactory.buildWidget(registerModels->value(index)); - QObject::connect(registerSimpleWidget, &RegisterSimpleWidget::registerSelected, this, &RegisterMapTable::registerSelected); + QObject::connect(registerSimpleWidget, &RegisterSimpleWidget::registerSelected, this, + &RegisterMapTable::registerSelected); - registersMap->insert(index, registerSimpleWidget); - Q_EMIT widgetGenerated(index, registerSimpleWidget); + registersMap->insert(index, registerSimpleWidget); + Q_EMIT widgetGenerated(index, registerSimpleWidget); } diff --git a/plugins/regmap/src/recycerview/registermaptable.hpp b/plugins/regmap/src/recycerview/registermaptable.hpp index a5bde8b801..3a8253cc6b 100644 --- a/plugins/regmap/src/recycerview/registermaptable.hpp +++ b/plugins/regmap/src/recycerview/registermaptable.hpp @@ -6,35 +6,35 @@ #include #include -namespace scopy::regmap{ +namespace scopy::regmap { class RegisterModel; class RegisterSimpleWidget; class RecyclerView; class RegisterMapTable : public IRecyclerViewAdapter { - Q_OBJECT + Q_OBJECT public: - RegisterMapTable(QMap *registerModels, QWidget *parent); + RegisterMapTable(QMap *registerModels, QWidget *parent); - QWidget* getWidget(); - void setFilters(QList filters); - void valueUpdated(uint32_t address, uint32_t value); - void scrollTo(uint32_t index); - void setRegisterSelected(uint32_t address); + QWidget *getWidget(); + void setFilters(QList filters); + void valueUpdated(uint32_t address, uint32_t value); + void scrollTo(uint32_t index); + void setRegisterSelected(uint32_t address); - // IRecyclerViewAdapter interface - void generateWidget(int index); + // IRecyclerViewAdapter interface + void generateWidget(int index); Q_SIGNALS: - void requestWidget(int index); - void registerSelected(uint32_t address); + void requestWidget(int index); + void registerSelected(uint32_t address); private: - RecyclerView * recyclerView = nullptr; - QMap *registerModels; - QMap *registersMap; - uint32_t selectedAddress; + RecyclerView *recyclerView = nullptr; + QMap *registerModels; + QMap *registersMap; + uint32_t selectedAddress; }; -} +} // namespace scopy::regmap #endif // REGISTERMAPTABLE_H diff --git a/plugins/regmap/src/register/bitfield/bitfielddetailedwidget.cpp b/plugins/regmap/src/register/bitfield/bitfielddetailedwidget.cpp index 26a58a3abc..da6d50f995 100644 --- a/plugins/regmap/src/register/bitfield/bitfielddetailedwidget.cpp +++ b/plugins/regmap/src/register/bitfield/bitfielddetailedwidget.cpp @@ -1,228 +1,219 @@ #include "bitfielddetailedwidget.hpp" +#include "dynamicWidget.h" +#include "utils.hpp" + +#include #include #include #include #include #include -#include -#include -#include -#include "dynamicWidget.h" -#include "utils.hpp" +#include +#include using namespace scopy; using namespace regmap; BitFieldDetailedWidget::BitFieldDetailedWidget(QString name, QString access, int defaultValue, QString description, - int width, QString notes, int regOffset, QVector *options, QWidget *parent) - :options(options), - width(width), - description(description), - regOffset(regOffset), - access(access) + int width, QString notes, int regOffset, + QVector *options, QWidget *parent) + : options(options) + , width(width) + , description(description) + , regOffset(regOffset) + , access(access) { - mainFrame = new QFrame(); - layout = new QVBoxLayout(this); - layout->setSpacing(4); + mainFrame = new QFrame(); + layout = new QVBoxLayout(this); + layout->setSpacing(4); - QHBoxLayout *firstLayout = new QHBoxLayout(); - nameLabel = new QLabel(name); - nameLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum); - firstLayout->addWidget(nameLabel); - firstLayout->addWidget(new QLabel(QString::number(regOffset + width - 1) + ":" + QString::number(regOffset))); - firstLayout->itemAt(1)->setAlignment(Qt::AlignRight); + QHBoxLayout *firstLayout = new QHBoxLayout(); + nameLabel = new QLabel(name); + nameLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum); + firstLayout->addWidget(nameLabel); + firstLayout->addWidget(new QLabel(QString::number(regOffset + width - 1) + ":" + QString::number(regOffset))); + firstLayout->itemAt(1)->setAlignment(Qt::AlignRight); - layout->addLayout(firstLayout); + layout->addLayout(firstLayout); - descriptionLabel = new QLabel(description); - layout->addWidget(descriptionLabel); + descriptionLabel = new QLabel(description); + layout->addWidget(descriptionLabel); - QHBoxLayout *secondLayout = new QHBoxLayout(); + QHBoxLayout *secondLayout = new QHBoxLayout(); - lastReadValue = new QLabel("Current : N/R"); - secondLayout->addWidget(lastReadValue); + lastReadValue = new QLabel("Current : N/R"); + secondLayout->addWidget(lastReadValue); - defaultValueLabel = new QLabel("Default : " + scopy::regmap::Utils::convertToHexa(defaultValue, width)); - secondLayout->addWidget(defaultValueLabel, Qt::AlignRight, Qt::AlignRight); + defaultValueLabel = new QLabel("Default : " + scopy::regmap::Utils::convertToHexa(defaultValue, width)); + secondLayout->addWidget(defaultValueLabel, Qt::AlignRight, Qt::AlignRight); - layout->addLayout(secondLayout); + layout->addLayout(secondLayout); - QString defaultValueString = scopy::regmap::Utils::convertToHexa(defaultValue, width); + QString defaultValueString = scopy::regmap::Utils::convertToHexa(defaultValue, width); - toolTip = "Name : " + name + "\n" - + QString::number(regOffset + width - 1) + ":" + QString::number(regOffset) + "\n" - + "Description : " + description + "\n" - + "Notes : " + notes + "\n" - + "Default Value : " + defaultValueString; + toolTip = "Name : " + name + "\n" + QString::number(regOffset + width - 1) + ":" + QString::number(regOffset) + + "\n" + "Description : " + description + "\n" + "Notes : " + notes + "\n" + + "Default Value : " + defaultValueString; - setToolTip(toolTip); + setToolTip(toolTip); - mainFrame->setLayout(layout); + mainFrame->setLayout(layout); - QVBoxLayout *mainLayout = new QVBoxLayout(); - mainLayout->addWidget(mainFrame); - mainLayout->setSpacing(4); - mainLayout->setMargin(4); - setLayout(mainLayout); + QVBoxLayout *mainLayout = new QVBoxLayout(); + mainLayout->addWidget(mainFrame); + mainLayout->setSpacing(4); + mainLayout->setMargin(4); + setLayout(mainLayout); - if (description == "Reserved") { - reserved = true; - } else { - reserved = false; - } + if(description == "Reserved") { + reserved = true; + } else { + reserved = false; + } - updateValue(defaultValueString); + updateValue(defaultValueString); } BitFieldDetailedWidget::~BitFieldDetailedWidget() { - delete defaultValueLabel; - if (value) delete value; - if (valueComboBox) delete valueComboBox; - if (valueCheckBox) delete valueCheckBox; - if (valueLineEdit) delete valueLineEdit; - delete mainFrame; + delete defaultValueLabel; + if(value) + delete value; + if(valueComboBox) + delete valueComboBox; + if(valueCheckBox) + delete valueCheckBox; + if(valueLineEdit) + delete valueLineEdit; + delete mainFrame; } -QString BitFieldDetailedWidget::getToolTip() const -{ - return toolTip; -} +QString BitFieldDetailedWidget::getToolTip() const { return toolTip; } void BitFieldDetailedWidget::firstRead() { - if (description == "Reserved") { - valueLineEdit = new QLineEdit(); - valueLineEdit->setText("0x0"); - valueLineEdit->setReadOnly(true); - layout->addWidget(valueLineEdit); - }else if (access == "R") { - value = new QLabel(); - } else if (options && !options->isEmpty()) { - valueComboBox = new QComboBox(); - - //check if there are enough options to cover all posible cases for the number of bits - if (!(options->count() == qPow(2,width))) { - valueComboBox->setEditable(true); - } - - layout->addWidget(valueComboBox); - - for (int i = 0; i < options->length(); i++) { - valueComboBox->insertItem(i, options->at(i)->getDescription()); - } - - QObject::connect(valueComboBox, &QComboBox::currentTextChanged, this, [=](QString val){ - - for (int i = 0; i < options->length(); i++) { - if (options->at(i)->getDescription() == val) { - Q_EMIT valueUpdated(options->at(i)->getValue()); - break; - } - } - }); - - //if is only one bit we will use a toggle button - } else if (width == 1) { - valueCheckBox = new QCheckBox(); - layout->addWidget(valueCheckBox); - - QObject::connect(valueCheckBox, &QCheckBox::toggled, this, [=](){ - if (valueCheckBox->isChecked() ) { - Q_EMIT valueUpdated("1"); - } else { - Q_EMIT valueUpdated("0"); - } - }); - - } else { - valueLineEdit = new QLineEdit(); - layout->addWidget(valueLineEdit); - - QObject::connect(valueLineEdit, &QLineEdit::textChanged, this, [=](QString val){ - Q_EMIT valueUpdated(val); - }); - } + if(description == "Reserved") { + valueLineEdit = new QLineEdit(); + valueLineEdit->setText("0x0"); + valueLineEdit->setReadOnly(true); + layout->addWidget(valueLineEdit); + } else if(access == "R") { + value = new QLabel(); + } else if(options && !options->isEmpty()) { + valueComboBox = new QComboBox(); + + // check if there are enough options to cover all posible cases for the number of bits + if(!(options->count() == qPow(2, width))) { + valueComboBox->setEditable(true); + } + + layout->addWidget(valueComboBox); + + for(int i = 0; i < options->length(); i++) { + valueComboBox->insertItem(i, options->at(i)->getDescription()); + } + + QObject::connect(valueComboBox, &QComboBox::currentTextChanged, this, [=](QString val) { + for(int i = 0; i < options->length(); i++) { + if(options->at(i)->getDescription() == val) { + Q_EMIT valueUpdated(options->at(i)->getValue()); + break; + } + } + }); + + // if is only one bit we will use a toggle button + } else if(width == 1) { + valueCheckBox = new QCheckBox(); + layout->addWidget(valueCheckBox); + + QObject::connect(valueCheckBox, &QCheckBox::toggled, this, [=]() { + if(valueCheckBox->isChecked()) { + Q_EMIT valueUpdated("1"); + } else { + Q_EMIT valueUpdated("0"); + } + }); + + } else { + valueLineEdit = new QLineEdit(); + layout->addWidget(valueLineEdit); + + QObject::connect(valueLineEdit, &QLineEdit::textChanged, this, + [=](QString val) { Q_EMIT valueUpdated(val); }); + } } void BitFieldDetailedWidget::updateValue(QString newValue) { - if (isFirstRead) { - firstRead(); - isFirstRead = false; - } - - // if bit is reserved or read only - if (description == "Reserved") { - Q_EMIT valueUpdated("0"); - - } else if (access == "R") { - value->setText(newValue); - Q_EMIT valueUpdated(newValue); - } else { - if (valueLineEdit) { - valueLineEdit->setText(newValue); - - } else if (valueCheckBox){ - valueCheckBox->setChecked(newValue == "1"); - } else if (valueComboBox) { - - for (int i = 0; i < options->length(); i++) { - if (options->at(i)->getValue() == newValue) { - valueComboBox->setCurrentText(options->at(i)->getDescription()); - break; - } - } - - - } else { - value->setText(newValue); - } - - Q_EMIT valueUpdated(newValue); - } - + if(isFirstRead) { + firstRead(); + isFirstRead = false; + } + + // if bit is reserved or read only + if(description == "Reserved") { + Q_EMIT valueUpdated("0"); + + } else if(access == "R") { + value->setText(newValue); + Q_EMIT valueUpdated(newValue); + } else { + if(valueLineEdit) { + valueLineEdit->setText(newValue); + + } else if(valueCheckBox) { + valueCheckBox->setChecked(newValue == "1"); + } else if(valueComboBox) { + + for(int i = 0; i < options->length(); i++) { + if(options->at(i)->getValue() == newValue) { + valueComboBox->setCurrentText(options->at(i)->getDescription()); + break; + } + } + + } else { + value->setText(newValue); + } + + Q_EMIT valueUpdated(newValue); + } } void BitFieldDetailedWidget::registerValueUpdated(QString newValue) { - lastReadValue->setText(QString("Current : 0x") +newValue); - updateValue(newValue); + lastReadValue->setText(QString("Current : 0x") + newValue); + updateValue(newValue); } QString BitFieldDetailedWidget::getValue() { - if (valueLineEdit) { - return valueLineEdit->text(); - } - if (valueCheckBox){ - if (valueCheckBox->isChecked() ) { - return "1"; - } else { - return "0"; - } - } - if (valueComboBox) { - for (int i = 0; i < options->length(); i++) { - if (options->at(i)->getDescription() == valueComboBox->currentText()) { - return options->at(i)->getValue(); - } - } - return "0"; - } - - return value->text(); + if(valueLineEdit) { + return valueLineEdit->text(); + } + if(valueCheckBox) { + if(valueCheckBox->isChecked()) { + return "1"; + } else { + return "0"; + } + } + if(valueComboBox) { + for(int i = 0; i < options->length(); i++) { + if(options->at(i)->getDescription() == valueComboBox->currentText()) { + return options->at(i)->getValue(); + } + } + return "0"; + } + + return value->text(); } -int BitFieldDetailedWidget::getWidth() const -{ - return width; -} +int BitFieldDetailedWidget::getWidth() const { return width; } -int BitFieldDetailedWidget::getRegOffset() const -{ - return regOffset; -} +int BitFieldDetailedWidget::getRegOffset() const { return regOffset; } diff --git a/plugins/regmap/src/register/bitfield/bitfielddetailedwidget.hpp b/plugins/regmap/src/register/bitfield/bitfielddetailedwidget.hpp index fad86a4785..7c21edac9b 100644 --- a/plugins/regmap/src/register/bitfield/bitfielddetailedwidget.hpp +++ b/plugins/regmap/src/register/bitfield/bitfielddetailedwidget.hpp @@ -3,8 +3,8 @@ #include "bitfieldoption.hpp" -#include #include +#include class QLabel; class QLineEdit; @@ -13,28 +13,22 @@ class QComboBox; class QVBoxLayout; class QHBoxLayout; -namespace scopy::regmap{ +namespace scopy::regmap { class BitFieldDetailedWidget : public QFrame { - friend class RegmapStyleHelper; + friend class RegmapStyleHelper; Q_OBJECT public: - explicit BitFieldDetailedWidget(QString name, - QString access, - int defaultValue, - QString description, - int width, - QString notes, - int regOffset, - QVector *options, - QWidget *parent = nullptr); - ~BitFieldDetailedWidget(); + explicit BitFieldDetailedWidget(QString name, QString access, int defaultValue, QString description, int width, + QString notes, int regOffset, QVector *options, + QWidget *parent = nullptr); + ~BitFieldDetailedWidget(); QString getToolTip() const; void updateValue(QString newValue); - void registerValueUpdated(QString newValue); + void registerValueUpdated(QString newValue); QString getValue(); int getWidth() const; @@ -42,32 +36,31 @@ class BitFieldDetailedWidget : public QFrame int getRegOffset() const; private: - QFrame *mainFrame; + QFrame *mainFrame; QVBoxLayout *layout; QString toolTip; int width; QString description; bool reserved; int regOffset; - QString access; + QString access; - QVector *options; - QLabel *nameLabel; - QLabel *descriptionLabel; - QLabel *lastReadValue; - QLabel *defaultValueLabel; - QLabel *value = nullptr; + QVector *options; + QLabel *nameLabel; + QLabel *descriptionLabel; + QLabel *lastReadValue; + QLabel *defaultValueLabel; + QLabel *value = nullptr; QComboBox *valueComboBox = nullptr; QCheckBox *valueCheckBox = nullptr; - QLineEdit *valueLineEdit = nullptr; + QLineEdit *valueLineEdit = nullptr; - bool isFirstRead = true; + bool isFirstRead = true; - void firstRead(); + void firstRead(); Q_SIGNALS: - void valueUpdated(QString value); - + void valueUpdated(QString value); }; -} +} // namespace scopy::regmap #endif // BitFieldDetailedWidget_HPP diff --git a/plugins/regmap/src/register/bitfield/bitfielddetailedwidgetfactory.cpp b/plugins/regmap/src/register/bitfield/bitfielddetailedwidgetfactory.cpp index 17c193367b..677b885453 100644 --- a/plugins/regmap/src/register/bitfield/bitfielddetailedwidgetfactory.cpp +++ b/plugins/regmap/src/register/bitfield/bitfielddetailedwidgetfactory.cpp @@ -10,20 +10,13 @@ using namespace regmap; BitFieldDetailedWidgetFactory::BitFieldDetailedWidgetFactory(QObject *parent) : QObject{parent} -{ - -} +{} BitFieldDetailedWidget *BitFieldDetailedWidgetFactory::buildWidget(BitFieldModel *model) { - BitFieldDetailedWidget *bfdw = new BitFieldDetailedWidget(model->getName(), - model->getAccess(), - model->getDefaultValue(), - model->getDescription(), - model->getWidth(), - model->getNotes(), - model->getRegOffset(), - model->getOptions()); - bfdw->setStyleSheet(RegmapStyleHelper::detailedBitFieldStyle(bfdw, "")); - return bfdw; + BitFieldDetailedWidget *bfdw = new BitFieldDetailedWidget( + model->getName(), model->getAccess(), model->getDefaultValue(), model->getDescription(), + model->getWidth(), model->getNotes(), model->getRegOffset(), model->getOptions()); + bfdw->setStyleSheet(RegmapStyleHelper::detailedBitFieldStyle(bfdw, "")); + return bfdw; } diff --git a/plugins/regmap/src/register/bitfield/bitfielddetailedwidgetfactory.hpp b/plugins/regmap/src/register/bitfield/bitfielddetailedwidgetfactory.hpp index f0a5b824a1..c15d48b2cf 100644 --- a/plugins/regmap/src/register/bitfield/bitfielddetailedwidgetfactory.hpp +++ b/plugins/regmap/src/register/bitfield/bitfielddetailedwidgetfactory.hpp @@ -3,7 +3,7 @@ #include -namespace scopy::regmap{ +namespace scopy::regmap { class BitFieldModel; class BitFieldDetailedWidget; @@ -15,7 +15,6 @@ class BitFieldDetailedWidgetFactory : public QObject BitFieldDetailedWidget *buildWidget(BitFieldModel *model); Q_SIGNALS: - }; -} +} // namespace scopy::regmap #endif // BITFIELDDETAILEDWIDGETFACTORY_HPP diff --git a/plugins/regmap/src/register/bitfield/bitfieldmodel.cpp b/plugins/regmap/src/register/bitfield/bitfieldmodel.cpp index b73eeb87bf..3cbeac1a63 100644 --- a/plugins/regmap/src/register/bitfield/bitfieldmodel.cpp +++ b/plugins/regmap/src/register/bitfield/bitfieldmodel.cpp @@ -2,95 +2,61 @@ using namespace scopy::regmap; -BitFieldModel::BitFieldModel(QString name, int width,int regOffset, QString description, QObject *parent) - : name(name), - width(width), - regOffset(regOffset), - description(description), - QObject{parent} -{ - if (description == "Reserved") { - reserved = true; - } - - defaultValue = 0; - -} -BitFieldModel::BitFieldModel( QString name, QString access, int defaultValue, QString description, - QString visibility, int width, QString notes, int bitOffset, int regOffset, - int sliceWidth, QVector *options, QObject *parent): - name(name), - access(access), - defaultValue(defaultValue), - description(description), - visibility(visibility), - width(width), - notes(notes), - bitOffset(bitOffset), - regOffset(regOffset), - sliceWidth(sliceWidth), - options(options), - QObject{parent} -{ - reserved = false; +BitFieldModel::BitFieldModel(QString name, int width, int regOffset, QString description, QObject *parent) + : name(name) + , width(width) + , regOffset(regOffset) + , description(description) + , QObject{parent} +{ + if(description == "Reserved") { + reserved = true; + } + + defaultValue = 0; +} +BitFieldModel::BitFieldModel(QString name, QString access, int defaultValue, QString description, QString visibility, + int width, QString notes, int bitOffset, int regOffset, int sliceWidth, + QVector *options, QObject *parent) + : name(name) + , access(access) + , defaultValue(defaultValue) + , description(description) + , visibility(visibility) + , width(width) + , notes(notes) + , bitOffset(bitOffset) + , regOffset(regOffset) + , sliceWidth(sliceWidth) + , options(options) + , QObject{parent} +{ + reserved = false; } BitFieldModel::~BitFieldModel() { - if (options) delete options; -} -QString BitFieldModel::getName() const -{ - return name; + if(options) + delete options; } +QString BitFieldModel::getName() const { return name; } +QString BitFieldModel::getAccess() const { return access; } -QString BitFieldModel::getAccess() const -{ - return access; -} +int BitFieldModel::getDefaultValue() const { return defaultValue; } -int BitFieldModel::getDefaultValue() const -{ - return defaultValue; -} - -QString BitFieldModel::getDescription() const -{ - return description; -} +QString BitFieldModel::getDescription() const { return description; } -QString BitFieldModel::getVisibility() const -{ - return visibility; -} +QString BitFieldModel::getVisibility() const { return visibility; } -int BitFieldModel::getWidth() const -{ - return width; -} +int BitFieldModel::getWidth() const { return width; } -QString BitFieldModel::getNotes() const -{ - return notes; -} +QString BitFieldModel::getNotes() const { return notes; } -int BitFieldModel::getBitOffset() const -{ - return bitOffset; -} +int BitFieldModel::getBitOffset() const { return bitOffset; } -int BitFieldModel::getRegOffset() const -{ - return regOffset; -} +int BitFieldModel::getRegOffset() const { return regOffset; } -int BitFieldModel::getSliceWidth() const -{ - return sliceWidth; -} +int BitFieldModel::getSliceWidth() const { return sliceWidth; } -QVector* BitFieldModel::getOptions() const -{ - return options; -} +QVector *BitFieldModel::getOptions() const { return options; } diff --git a/plugins/regmap/src/register/bitfield/bitfieldmodel.hpp b/plugins/regmap/src/register/bitfield/bitfieldmodel.hpp index e419ac1d12..a525f0ac2c 100644 --- a/plugins/regmap/src/register/bitfield/bitfieldmodel.hpp +++ b/plugins/regmap/src/register/bitfield/bitfieldmodel.hpp @@ -6,56 +6,46 @@ #include #include -namespace scopy::regmap{ +namespace scopy::regmap { class BitFieldModel : public QObject { - Q_OBJECT + Q_OBJECT public: - BitFieldModel(QString name, int width,int regOffset, QString description, QObject *parent = nullptr); - - BitFieldModel( QString name, - QString access, - int defaultValue, - QString description, - QString visibility, - int width, - QString notes, - int bitOffset, - int regOffset, - int sliceWidth, - QVector *options, - QObject *parent = nullptr); - ~BitFieldModel(); - - QString getName() const; - QString getAccess() const; - int getDefaultValue() const; - QString getDescription() const; - QString getVisibility() const; - int getWidth() const; - QString getNotes() const; - int getBitOffset() const; - int getRegOffset() const; - int getSliceWidth() const; - QVector* getOptions() const; + BitFieldModel(QString name, int width, int regOffset, QString description, QObject *parent = nullptr); + + BitFieldModel(QString name, QString access, int defaultValue, QString description, QString visibility, + int width, QString notes, int bitOffset, int regOffset, int sliceWidth, + QVector *options, QObject *parent = nullptr); + ~BitFieldModel(); + + QString getName() const; + QString getAccess() const; + int getDefaultValue() const; + QString getDescription() const; + QString getVisibility() const; + int getWidth() const; + QString getNotes() const; + int getBitOffset() const; + int getRegOffset() const; + int getSliceWidth() const; + QVector *getOptions() const; private: - QString name; - QString access; - int defaultValue; - QString description; - QString visibility; - int width; - QString notes; - int bitOffset; - int regOffset; - int sliceWidth; - QVector *options = nullptr; - - bool reserved; + QString name; + QString access; + int defaultValue; + QString description; + QString visibility; + int width; + QString notes; + int bitOffset; + int regOffset; + int sliceWidth; + QVector *options = nullptr; + + bool reserved; Q_SIGNALS: - }; -} +} // namespace scopy::regmap #endif // BITFIELDMODEL_HPP diff --git a/plugins/regmap/src/register/bitfield/bitfieldoption.cpp b/plugins/regmap/src/register/bitfield/bitfieldoption.cpp index 1afd995640..97b87c4d1b 100644 --- a/plugins/regmap/src/register/bitfield/bitfieldoption.cpp +++ b/plugins/regmap/src/register/bitfield/bitfieldoption.cpp @@ -1,18 +1,10 @@ #include "bitfieldoption.hpp" BitFieldOption::BitFieldOption(QString value, QString description) - :value(value), - description(description) -{ + : value(value) + , description(description) +{} -} +QString BitFieldOption::getDescription() const { return description; } -QString BitFieldOption::getDescription() const -{ - return description; -} - -QString BitFieldOption::getValue() const -{ - return value; -} +QString BitFieldOption::getValue() const { return value; } diff --git a/plugins/regmap/src/register/bitfield/bitfieldoption.hpp b/plugins/regmap/src/register/bitfield/bitfieldoption.hpp index cc996c1e8c..08c47478af 100644 --- a/plugins/regmap/src/register/bitfield/bitfieldoption.hpp +++ b/plugins/regmap/src/register/bitfield/bitfieldoption.hpp @@ -6,15 +6,15 @@ class BitFieldOption { public: - BitFieldOption(QString value, QString description); + BitFieldOption(QString value, QString description); - QString getDescription() const; + QString getDescription() const; - QString getValue() const; + QString getValue() const; private: - QString value; - QString description; + QString value; + QString description; }; #endif // BITFIELDOPTION_HPP diff --git a/plugins/regmap/src/register/bitfield/bitfieldsimplewidget.cpp b/plugins/regmap/src/register/bitfield/bitfieldsimplewidget.cpp index 5b767d7f99..4f69ac720c 100644 --- a/plugins/regmap/src/register/bitfield/bitfieldsimplewidget.cpp +++ b/plugins/regmap/src/register/bitfield/bitfieldsimplewidget.cpp @@ -1,115 +1,104 @@ #include "bitfieldsimplewidget.hpp" +#include "dynamicWidget.h" + +#include +#include #include #include -#include -#include -#include + +#include #include -#include "dynamicWidget.h" #include -#include +#include using namespace scopy; using namespace regmap; -BitFieldSimpleWidget::BitFieldSimpleWidget(QString name, int defaultValue, QString description, int width, QString notes, int regOffset, int streach, QWidget *parent): - width(width), - description(description), - streach(streach), - QFrame{parent} +BitFieldSimpleWidget::BitFieldSimpleWidget(QString name, int defaultValue, QString description, int width, + QString notes, int regOffset, int streach, QWidget *parent) + : width(width) + , description(description) + , streach(streach) + , QFrame{parent} { - mainFrame = new QFrame; - RegmapStyleHelper::grayBackgroundHoverWidget(mainFrame, ""); - - setMinimumWidth(60); - setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Maximum); - layout = new QHBoxLayout(); - - QVBoxLayout *rightLayout = new QVBoxLayout(); - rightLayout->setAlignment(Qt::AlignRight); - - value = new QLabel("N/R"); - value->setAlignment(Qt::AlignRight); - value->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum); - value->setMinimumWidth(25); - QLabel *bitfieldWidth = new QLabel(QString::number(regOffset + width - 1) + ":" + QString::number(regOffset)); - bitfieldWidth->setAlignment(Qt::AlignRight); - rightLayout->addWidget(bitfieldWidth); - rightLayout->addWidget(value); - - QVBoxLayout *leftLayout = new QVBoxLayout(); - leftLayout->setAlignment(Qt::AlignTop); - QLabel *descriptionLabel = new QLabel(name); - descriptionLabel->setWordWrap(true); - descriptionLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum); - leftLayout->addWidget(descriptionLabel); - - layout->addLayout(leftLayout); - layout->addLayout(rightLayout); - - QString toolTip = "Name : " + name + "\n" - + QString::number(regOffset + width - 1) + ":" + QString::number(regOffset) + "\n" - + "Description : " + description + "\n" - + "Notes : " + notes + "\n" - + "Default Value : " + scopy::regmap::Utils::convertToHexa(defaultValue, width); - - setToolTip(toolTip); - - - mainFrame->setLayout(layout); - QVBoxLayout *mainFrameLayout = new QVBoxLayout(); - mainFrameLayout->setMargin(0); - mainFrameLayout->setSpacing(0); - mainFrameLayout->addWidget(mainFrame); - setLayout(mainFrameLayout); + mainFrame = new QFrame; + RegmapStyleHelper::grayBackgroundHoverWidget(mainFrame, ""); + + setMinimumWidth(60); + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); + layout = new QHBoxLayout(); + + QVBoxLayout *rightLayout = new QVBoxLayout(); + rightLayout->setAlignment(Qt::AlignRight); + + value = new QLabel("N/R"); + value->setAlignment(Qt::AlignRight); + value->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); + value->setMinimumWidth(25); + QLabel *bitfieldWidth = new QLabel(QString::number(regOffset + width - 1) + ":" + QString::number(regOffset)); + bitfieldWidth->setAlignment(Qt::AlignRight); + rightLayout->addWidget(bitfieldWidth); + rightLayout->addWidget(value); + + QVBoxLayout *leftLayout = new QVBoxLayout(); + leftLayout->setAlignment(Qt::AlignTop); + QLabel *descriptionLabel = new QLabel(name); + descriptionLabel->setWordWrap(true); + descriptionLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum); + leftLayout->addWidget(descriptionLabel); + + layout->addLayout(leftLayout); + layout->addLayout(rightLayout); + + QString toolTip = "Name : " + name + "\n" + QString::number(regOffset + width - 1) + ":" + + QString::number(regOffset) + "\n" + "Description : " + description + "\n" + "Notes : " + notes + "\n" + + "Default Value : " + scopy::regmap::Utils::convertToHexa(defaultValue, width); + + setToolTip(toolTip); + + mainFrame->setLayout(layout); + QVBoxLayout *mainFrameLayout = new QVBoxLayout(); + mainFrameLayout->setMargin(0); + mainFrameLayout->setSpacing(0); + mainFrameLayout->addWidget(mainFrame); + setLayout(mainFrameLayout); } BitFieldSimpleWidget::~BitFieldSimpleWidget() { - delete value; - delete layout; + delete value; + delete layout; } void BitFieldSimpleWidget::updateValue(QString newValue) { - value->setText(newValue); - checkPreferences(); + value->setText(newValue); + checkPreferences(); } -int BitFieldSimpleWidget::getWidth() const -{ - return width; -} +int BitFieldSimpleWidget::getWidth() const { return width; } -QString BitFieldSimpleWidget::getDescription() const -{ - return description; -} +QString BitFieldSimpleWidget::getDescription() const { return description; } -int BitFieldSimpleWidget::getStreach() const -{ - return streach; -} +int BitFieldSimpleWidget::getStreach() const { return streach; } void BitFieldSimpleWidget::checkPreferences() { - scopy::Preferences *p = scopy::Preferences::GetInstance(); - QString background = p->get("regmap_color_by_value").toString(); - - if (background.contains("Bitfield background")) { - bool ok; - this->setStyleSheet(QString("background-color: " + Util::getColors().at(value->text().toInt(&ok,16) % 16))); - } - - if (background.contains("Bitfield text")) { - bool ok; - value->setStyleSheet(QString("color: " + Util::getColors().at(value->text().toInt(&ok,16) % 16))); - } + scopy::Preferences *p = scopy::Preferences::GetInstance(); + QString background = p->get("regmap_color_by_value").toString(); + + if(background.contains("Bitfield background")) { + bool ok; + this->setStyleSheet( + QString("background-color: " + Util::getColors().at(value->text().toInt(&ok, 16) % 16))); + } + + if(background.contains("Bitfield text")) { + bool ok; + value->setStyleSheet(QString("color: " + Util::getColors().at(value->text().toInt(&ok, 16) % 16))); + } } -void BitFieldSimpleWidget::setSelected(bool selected) -{ - scopy::setDynamicProperty(mainFrame,"is_selected",selected); -} +void BitFieldSimpleWidget::setSelected(bool selected) { scopy::setDynamicProperty(mainFrame, "is_selected", selected); } diff --git a/plugins/regmap/src/register/bitfield/bitfieldsimplewidget.hpp b/plugins/regmap/src/register/bitfield/bitfieldsimplewidget.hpp index 262ac21fd1..6299c16a2e 100644 --- a/plugins/regmap/src/register/bitfield/bitfieldsimplewidget.hpp +++ b/plugins/regmap/src/register/bitfield/bitfieldsimplewidget.hpp @@ -8,42 +8,34 @@ class QHBoxLayout; class QVBoxLayout; class QLabel; -namespace scopy::regmap{ +namespace scopy::regmap { class BitFieldSimpleWidget : public QFrame { - Q_OBJECT + Q_OBJECT public: - explicit BitFieldSimpleWidget(QString name, - int defaultValue, - QString description, - int width, - QString notes, - int regOffset, - int streach, - QWidget *parent = nullptr); + explicit BitFieldSimpleWidget(QString name, int defaultValue, QString description, int width, QString notes, + int regOffset, int streach, QWidget *parent = nullptr); - ~BitFieldSimpleWidget(); - void updateValue(QString newValue); - int getWidth() const; + ~BitFieldSimpleWidget(); + void updateValue(QString newValue); + int getWidth() const; + QString getDescription() const; - QString getDescription() const; - - int getStreach() const; + int getStreach() const; public Q_SLOTS: - void checkPreferences(); - void setSelected(bool selected); + void checkPreferences(); + void setSelected(bool selected); private: - QHBoxLayout *layout; - QLabel *value; - int width; - int streach; - QString description; - QFrame *mainFrame; + QHBoxLayout *layout; + QLabel *value; + int width; + int streach; + QString description; + QFrame *mainFrame; Q_SIGNALS: - }; -} +} // namespace scopy::regmap #endif // BITFIELDSIMPLEWIDGET_HPP diff --git a/plugins/regmap/src/register/bitfield/bitfieldsimplewidgetfactory.cpp b/plugins/regmap/src/register/bitfield/bitfieldsimplewidgetfactory.cpp index e84331ae78..12335d4104 100644 --- a/plugins/regmap/src/register/bitfield/bitfieldsimplewidgetfactory.cpp +++ b/plugins/regmap/src/register/bitfield/bitfieldsimplewidgetfactory.cpp @@ -1,23 +1,17 @@ +#include "bitfieldsimplewidgetfactory.hpp" + #include "bitfieldmodel.hpp" #include "bitfieldsimplewidget.hpp" -#include "bitfieldsimplewidgetfactory.hpp" using namespace scopy; using namespace regmap; BitFieldSimpleWidgetFactory::BitFieldSimpleWidgetFactory(QObject *parent) : QObject{parent} -{ - -} +{} BitFieldSimpleWidget *BitFieldSimpleWidgetFactory::buildWidget(BitFieldModel *model, int streach) { - return new BitFieldSimpleWidget(model->getName(), - model->getDefaultValue(), - model->getDescription(), - model->getWidth(), - model->getNotes(), - model->getRegOffset(), - streach); + return new BitFieldSimpleWidget(model->getName(), model->getDefaultValue(), model->getDescription(), + model->getWidth(), model->getNotes(), model->getRegOffset(), streach); } diff --git a/plugins/regmap/src/register/bitfield/bitfieldsimplewidgetfactory.hpp b/plugins/regmap/src/register/bitfield/bitfieldsimplewidgetfactory.hpp index 1a45aede5f..049fe86733 100644 --- a/plugins/regmap/src/register/bitfield/bitfieldsimplewidgetfactory.hpp +++ b/plugins/regmap/src/register/bitfield/bitfieldsimplewidgetfactory.hpp @@ -3,7 +3,7 @@ #include -namespace scopy::regmap{ +namespace scopy::regmap { class BitFieldModel; class BitFieldSimpleWidget; @@ -15,7 +15,6 @@ class BitFieldSimpleWidgetFactory : public QObject BitFieldSimpleWidget *buildWidget(BitFieldModel *model, int streach); Q_SIGNALS: - }; -} +} // namespace scopy::regmap #endif // BITFIELDSIMPLEWIDGETFACTORY_HPP diff --git a/plugins/regmap/src/register/registerdetailedwidget.cpp b/plugins/regmap/src/register/registerdetailedwidget.cpp index 448436958d..e0a75977aa 100644 --- a/plugins/regmap/src/register/registerdetailedwidget.cpp +++ b/plugins/regmap/src/register/registerdetailedwidget.cpp @@ -1,115 +1,118 @@ #include "registerdetailedwidget.hpp" + +#include "../verticalscrollarea.hpp" #include "bitfield/bitfielddetailedwidget.hpp" #include "bitfield/bitfielddetailedwidgetfactory.hpp" -#include "../verticalscrollarea.hpp" -#include -#include -#include -#include "registermodel.hpp" #include "qdebug.h" +#include "registermodel.hpp" #include "utils.hpp" + #include +#include +#include using namespace scopy; using namespace regmap; -RegisterDetailedWidget::RegisterDetailedWidget( RegisterModel *regModel, QWidget *parent) - : QWidget{parent} +RegisterDetailedWidget::RegisterDetailedWidget(RegisterModel *regModel, QWidget *parent) + : QWidget{parent} { - QVBoxLayout *layout = new QVBoxLayout(this); - setLayout(layout); - - setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Maximum); - - QGridLayout *bitFieldsWidgetLayout = new QGridLayout(); - bitFieldsWidgetLayout->setMargin(0); - bitFieldsWidgetLayout->setSpacing(0); - - bitFieldList = new QVector(); - BitFieldDetailedWidgetFactory bitFieldDetailedWidgetFactory; - QWidget *bitFieldsWidget = new QWidget(); - bitFieldsWidget->setLayout(bitFieldsWidgetLayout); - VerticalScrollArea *scrollArea = new VerticalScrollArea(); - scrollArea->setWidget(bitFieldsWidget); - layout->addWidget(scrollArea); - int currentBitFieldCount = 0; - int row = 0; - int col = 0; - for (int i = regModel->getBitFields()->size() - 1; i >= 0; --i) { - BitFieldDetailedWidget *bitFieldDetailedWidget = bitFieldDetailedWidgetFactory.buildWidget(regModel->getBitFields()->at(i)); - bitFieldList->push_back(bitFieldDetailedWidget); - - bitFieldsWidgetLayout->addWidget(bitFieldDetailedWidget, row, col); - - bitFieldsWidgetLayout->setColumnStretch(col,1); - col++; - - currentBitFieldCount += bitFieldDetailedWidget->getWidth(); - - if (col > scopy::regmap::Utils::getBitsPerRowDetailed()) { - row++; - col = 0; - } - QObject::connect(bitFieldDetailedWidget, &BitFieldDetailedWidget::valueUpdated, this, [=](){ - Q_EMIT bitFieldValueChanged(getBitFieldsValue()); - }); - } - // add spacers to keep the shape of the detailed bitfileds when the number of bitfields didn't fill a row - if (row == 0) { - while ( col <= scopy::regmap::Utils::getBitsPerRowDetailed()) { - BitFieldDetailedWidget *aux = new BitFieldDetailedWidget("","",0,"",1,"",0,nullptr); - aux->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); - aux->sizePolicy().setRetainSizeWhenHidden(true); - aux->hide(); - bitFieldsWidgetLayout->addWidget(aux, row, col); - bitFieldsWidgetLayout->setColumnStretch(col,1); - col++; - } - bitFieldsWidgetLayout->addItem(new QSpacerItem(10,10,QSizePolicy::Preferred, QSizePolicy::Expanding), row + 1 , col); - } + QVBoxLayout *layout = new QVBoxLayout(this); + setLayout(layout); + + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum); + + QGridLayout *bitFieldsWidgetLayout = new QGridLayout(); + bitFieldsWidgetLayout->setMargin(0); + bitFieldsWidgetLayout->setSpacing(0); + + bitFieldList = new QVector(); + BitFieldDetailedWidgetFactory bitFieldDetailedWidgetFactory; + QWidget *bitFieldsWidget = new QWidget(); + bitFieldsWidget->setLayout(bitFieldsWidgetLayout); + VerticalScrollArea *scrollArea = new VerticalScrollArea(); + scrollArea->setWidget(bitFieldsWidget); + layout->addWidget(scrollArea); + int currentBitFieldCount = 0; + int row = 0; + int col = 0; + for(int i = regModel->getBitFields()->size() - 1; i >= 0; --i) { + BitFieldDetailedWidget *bitFieldDetailedWidget = + bitFieldDetailedWidgetFactory.buildWidget(regModel->getBitFields()->at(i)); + bitFieldList->push_back(bitFieldDetailedWidget); + + bitFieldsWidgetLayout->addWidget(bitFieldDetailedWidget, row, col); + + bitFieldsWidgetLayout->setColumnStretch(col, 1); + col++; + + currentBitFieldCount += bitFieldDetailedWidget->getWidth(); + + if(col > scopy::regmap::Utils::getBitsPerRowDetailed()) { + row++; + col = 0; + } + QObject::connect(bitFieldDetailedWidget, &BitFieldDetailedWidget::valueUpdated, this, + [=]() { Q_EMIT bitFieldValueChanged(getBitFieldsValue()); }); + } + // add spacers to keep the shape of the detailed bitfileds when the number of bitfields didn't fill a row + if(row == 0) { + while(col <= scopy::regmap::Utils::getBitsPerRowDetailed()) { + BitFieldDetailedWidget *aux = new BitFieldDetailedWidget("", "", 0, "", 1, "", 0, nullptr); + aux->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + aux->sizePolicy().setRetainSizeWhenHidden(true); + aux->hide(); + bitFieldsWidgetLayout->addWidget(aux, row, col); + bitFieldsWidgetLayout->setColumnStretch(col, 1); + col++; + } + bitFieldsWidgetLayout->addItem(new QSpacerItem(10, 10, QSizePolicy::Preferred, QSizePolicy::Expanding), + row + 1, col); + } } void RegisterDetailedWidget::updateBitFieldsValue(uint32_t value) { - int regOffset = 0; - for (int i = bitFieldList->length() - 1; i >= 0; --i) { - bitFieldList->at(i)->blockSignals(true); - - int width = bitFieldList->at(i)->getWidth(); - int bfVal = ( ((1 << (regOffset + width) ) - 1 ) & value) >> regOffset; - QString bitFieldValue = QString::number(bfVal,16); - bitFieldList->at(i)->updateValue(bitFieldValue); - regOffset += width; - - bitFieldList->at(i)->blockSignals(false); - } + int regOffset = 0; + for(int i = bitFieldList->length() - 1; i >= 0; --i) { + bitFieldList->at(i)->blockSignals(true); + + int width = bitFieldList->at(i)->getWidth(); + int bfVal = (((1 << (regOffset + width)) - 1) & value) >> regOffset; + QString bitFieldValue = QString::number(bfVal, 16); + bitFieldList->at(i)->updateValue(bitFieldValue); + regOffset += width; + + bitFieldList->at(i)->blockSignals(false); + } } void RegisterDetailedWidget::registerValueUpdated(uint32_t value) { - int regOffset = 0; - for (int i = bitFieldList->length() - 1; i >= 0; --i) { - bitFieldList->at(i)->blockSignals(true); - - int width = bitFieldList->at(i)->getWidth(); - int bfVal = ( ((1 << (regOffset + width) ) - 1 ) & value) >> regOffset; - QString bitFieldValue = QString::number(bfVal,16); - bitFieldList->at(i)->registerValueUpdated(bitFieldValue); - regOffset += width; - - bitFieldList->at(i)->blockSignals(false); - } + int regOffset = 0; + for(int i = bitFieldList->length() - 1; i >= 0; --i) { + bitFieldList->at(i)->blockSignals(true); + + int width = bitFieldList->at(i)->getWidth(); + int bfVal = (((1 << (regOffset + width)) - 1) & value) >> regOffset; + QString bitFieldValue = QString::number(bfVal, 16); + bitFieldList->at(i)->registerValueUpdated(bitFieldValue); + regOffset += width; + + bitFieldList->at(i)->blockSignals(false); + } } QString RegisterDetailedWidget::getBitFieldsValue() { - int result = 0; - for (int i = 0; i < bitFieldList->length(); ++i) { - bool ok; - int aux = bitFieldList->at(i)->getValue().toInt(&ok,16); - int regOffset = bitFieldList->at(i)->getRegOffset(); - result += qPow(2, regOffset) * aux; - qDebug() << "aux = " << aux << " result = " << result; - } - return QString::number(result,16);; + int result = 0; + for(int i = 0; i < bitFieldList->length(); ++i) { + bool ok; + int aux = bitFieldList->at(i)->getValue().toInt(&ok, 16); + int regOffset = bitFieldList->at(i)->getRegOffset(); + result += qPow(2, regOffset) * aux; + qDebug() << "aux = " << aux << " result = " << result; + } + return QString::number(result, 16); + ; } diff --git a/plugins/regmap/src/register/registerdetailedwidget.hpp b/plugins/regmap/src/register/registerdetailedwidget.hpp index 589043e692..1e9882f9e6 100644 --- a/plugins/regmap/src/register/registerdetailedwidget.hpp +++ b/plugins/regmap/src/register/registerdetailedwidget.hpp @@ -4,26 +4,26 @@ #include class QLabel; -namespace scopy::regmap{ +namespace scopy::regmap { class RegisterModel; class BitFieldModel; class BitFieldDetailedWidget; class RegisterDetailedWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit RegisterDetailedWidget(RegisterModel *regModel, QWidget *parent = nullptr); + explicit RegisterDetailedWidget(RegisterModel *regModel, QWidget *parent = nullptr); - void updateBitFieldsValue(uint32_t value); - void registerValueUpdated(uint32_t value); - QString getBitFieldsValue(); + void updateBitFieldsValue(uint32_t value); + void registerValueUpdated(uint32_t value); + QString getBitFieldsValue(); private: - QVector *bitFieldList; + QVector *bitFieldList; Q_SIGNALS: - void bitFieldValueChanged(QString value); + void bitFieldValueChanged(QString value); }; -} +} // namespace scopy::regmap #endif // REGISTERDETAILEDWIDGET_HPP diff --git a/plugins/regmap/src/register/registermodel.cpp b/plugins/regmap/src/register/registermodel.cpp index 32956e2692..0efdcc98c8 100644 --- a/plugins/regmap/src/register/registermodel.cpp +++ b/plugins/regmap/src/register/registermodel.cpp @@ -1,50 +1,30 @@ -#include "bitfield/bitfieldmodel.hpp" #include "registermodel.hpp" +#include "bitfield/bitfieldmodel.hpp" + using namespace scopy::regmap; RegisterModel::RegisterModel(QString name, uint32_t address, QString description, bool exists, int width, QString notes, - QVector *bitFields): - name(name), - address(address), - description(description), - exists(exists), - width(width), - notes(notes), - bitFields(bitFields) + QVector *bitFields) + : name(name) + , address(address) + , description(description) + , exists(exists) + , width(width) + , notes(notes) + , bitFields(bitFields) {} -QString RegisterModel::getName() const -{ - return name; -} - -uint32_t RegisterModel::getAddress() const -{ - return address; -} - -QString RegisterModel::getDescription() const -{ - return description; -} - -bool RegisterModel::getExists() const -{ - return exists; -} - -int RegisterModel::getWidth() const -{ - return width; -} - -QString RegisterModel::getNotes() const -{ - return notes; -} - -QVector *RegisterModel::getBitFields() const -{ - return bitFields; -} +QString RegisterModel::getName() const { return name; } + +uint32_t RegisterModel::getAddress() const { return address; } + +QString RegisterModel::getDescription() const { return description; } + +bool RegisterModel::getExists() const { return exists; } + +int RegisterModel::getWidth() const { return width; } + +QString RegisterModel::getNotes() const { return notes; } + +QVector *RegisterModel::getBitFields() const { return bitFields; } diff --git a/plugins/regmap/src/register/registermodel.hpp b/plugins/regmap/src/register/registermodel.hpp index 3a0375cf83..76571c3280 100644 --- a/plugins/regmap/src/register/registermodel.hpp +++ b/plugins/regmap/src/register/registermodel.hpp @@ -3,20 +3,15 @@ #include -namespace scopy::regmap{ +namespace scopy::regmap { class BitFieldModel; class RegisterModel : public QObject { Q_OBJECT public: - RegisterModel( QString name, - uint32_t address, - QString description, - bool exists, - int width, - QString notes, - QVector *bitFields); + RegisterModel(QString name, uint32_t address, QString description, bool exists, int width, QString notes, + QVector *bitFields); QString getName() const; uint32_t getAddress() const; @@ -33,9 +28,8 @@ class RegisterModel : public QObject bool exists; int width; QString notes; - QVector *bitFields; + QVector *bitFields; Q_SIGNALS: - }; -} +} // namespace scopy::regmap #endif // REGISTERMODEL_HPP diff --git a/plugins/regmap/src/register/registersimplewidget.cpp b/plugins/regmap/src/register/registersimplewidget.cpp index ecea208e40..095972fde8 100644 --- a/plugins/regmap/src/register/registersimplewidget.cpp +++ b/plugins/regmap/src/register/registersimplewidget.cpp @@ -1,154 +1,155 @@ -#include "bitfield/bitfieldsimplewidget.hpp" #include "registersimplewidget.hpp" + +#include "bitfield/bitfieldsimplewidget.hpp" +#include "dynamicWidget.h" + #include #include #include #include -#include -#include -#include "dynamicWidget.h" -#include + #include #include +#include +#include using namespace scopy; using namespace regmap; -RegisterSimpleWidget::RegisterSimpleWidget(QString name, QString address, QString description, - QString notes,int registerWidth, QVector *bitFields, QWidget *parent) - :bitFields(bitFields), - registerWidth(registerWidth), - address(address) +RegisterSimpleWidget::RegisterSimpleWidget(QString name, QString address, QString description, QString notes, + int registerWidth, QVector *bitFields, + QWidget *parent) + : bitFields(bitFields) + , registerWidth(registerWidth) + , address(address) { - installEventFilter(this); - - setMinimumWidth(10); - setFixedHeight(60 * (registerWidth / 8) ); - setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Maximum); - - bool ok; - QHBoxLayout *layout = new QHBoxLayout(); - layout->setMargin(2); - layout->setSpacing(4); - setLayout(layout); - - regBaseInfoWidget = new QFrame(); - - QHBoxLayout *regBaseInfo = new QHBoxLayout(); - QVBoxLayout *rightLayout = new QVBoxLayout(); - rightLayout->setAlignment(Qt::AlignRight); - - QLabel *registerAddressLable = new QLabel(scopy::regmap::Utils::convertToHexa(address.toInt(&ok,16),registerWidth)); - registerAddressLable->setAlignment(Qt::AlignRight); - rightLayout->addWidget(registerAddressLable); - value = new QLabel("N/R"); - rightLayout->addWidget(value); - - QVBoxLayout *leftLayout = new QVBoxLayout(); - leftLayout->setAlignment(Qt::AlignTop); - registerNameLabel = new QLabel(name); - registerNameLabel->setWordWrap(true); - registerNameLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum); - leftLayout->addWidget(registerNameLabel); - - regBaseInfo->addLayout(leftLayout); - regBaseInfo->addLayout(rightLayout); - - regBaseInfoWidget->setLayout(regBaseInfo); - // to make sure table proportions are good we use a fixed size for this - regBaseInfoWidget->setFixedWidth(130); - layout->addWidget(regBaseInfoWidget,1); - - // add bitfield widgets - QGridLayout *bitFieldsWidgetLayout = new QGridLayout(); - bitFieldsWidgetLayout->setSpacing(0); - - int bits = bitFields->length() - 1; - int row = 0; - int col = 0; - while (bits >= 0 ) { - int streach = bitFields->at(bits)->getStreach(); - bitFieldsWidgetLayout->addWidget(bitFields->at(bits), row, col, 1, streach); - col += streach; - if (col > scopy::regmap::Utils::getBitsPerRow()) { - row++; - col = 0; - } - --bits; - } - - for (int i = 0; i < bitFieldsWidgetLayout->columnCount(); i++){ - bitFieldsWidgetLayout->setColumnStretch(i,1); - } - - layout->addLayout(bitFieldsWidgetLayout,8); - - - QString toolTip = "Name : " + name + "\n" - + "Address : " + scopy::regmap::Utils::convertToHexa(address.toInt(&ok,16), registerWidth) + "\n" - + "Description : " + description + "\n" - + "Notes : " + notes + "\n" ; - - setToolTip(toolTip); + installEventFilter(this); + + setMinimumWidth(10); + setFixedHeight(60 * (registerWidth / 8)); + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); + + bool ok; + QHBoxLayout *layout = new QHBoxLayout(); + layout->setMargin(2); + layout->setSpacing(4); + setLayout(layout); + + regBaseInfoWidget = new QFrame(); + + QHBoxLayout *regBaseInfo = new QHBoxLayout(); + QVBoxLayout *rightLayout = new QVBoxLayout(); + rightLayout->setAlignment(Qt::AlignRight); + + QLabel *registerAddressLable = + new QLabel(scopy::regmap::Utils::convertToHexa(address.toInt(&ok, 16), registerWidth)); + registerAddressLable->setAlignment(Qt::AlignRight); + rightLayout->addWidget(registerAddressLable); + value = new QLabel("N/R"); + rightLayout->addWidget(value); + + QVBoxLayout *leftLayout = new QVBoxLayout(); + leftLayout->setAlignment(Qt::AlignTop); + registerNameLabel = new QLabel(name); + registerNameLabel->setWordWrap(true); + registerNameLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum); + leftLayout->addWidget(registerNameLabel); + + regBaseInfo->addLayout(leftLayout); + regBaseInfo->addLayout(rightLayout); + + regBaseInfoWidget->setLayout(regBaseInfo); + // to make sure table proportions are good we use a fixed size for this + regBaseInfoWidget->setFixedWidth(130); + layout->addWidget(regBaseInfoWidget, 1); + + // add bitfield widgets + QGridLayout *bitFieldsWidgetLayout = new QGridLayout(); + bitFieldsWidgetLayout->setSpacing(0); + + int bits = bitFields->length() - 1; + int row = 0; + int col = 0; + while(bits >= 0) { + int streach = bitFields->at(bits)->getStreach(); + bitFieldsWidgetLayout->addWidget(bitFields->at(bits), row, col, 1, streach); + col += streach; + if(col > scopy::regmap::Utils::getBitsPerRow()) { + row++; + col = 0; + } + --bits; + } + + for(int i = 0; i < bitFieldsWidgetLayout->columnCount(); i++) { + bitFieldsWidgetLayout->setColumnStretch(i, 1); + } + + layout->addLayout(bitFieldsWidgetLayout, 8); + + QString toolTip = "Name : " + name + "\n" + + "Address : " + scopy::regmap::Utils::convertToHexa(address.toInt(&ok, 16), registerWidth) + "\n" + + "Description : " + description + "\n" + "Notes : " + notes + "\n"; + + setToolTip(toolTip); } RegisterSimpleWidget::~RegisterSimpleWidget() { - delete registerNameLabel; - delete value; - delete regBaseInfoWidget; - + delete registerNameLabel; + delete value; + delete regBaseInfoWidget; } void RegisterSimpleWidget::valueUpdated(uint32_t value) { - int regOffset = 0; - for (int i = 0; i < bitFields->length(); ++i) { - bitFields->at(i)->blockSignals(true); - - int width = bitFields->at(i)->getWidth(); - int bfVal = ( ((1 << (regOffset + width) ) - 1 ) & value) >> regOffset; - QString bitFieldValue = scopy::regmap::Utils::convertToHexa(bfVal, bitFields->at(i)->getWidth()); - bitFields->at(i)->updateValue(bitFieldValue); - regOffset += width; - - bitFields->at(i)->blockSignals(false); - } - this->value->setText(scopy::regmap::Utils::convertToHexa(value,registerWidth)); - checkPreferences(); + int regOffset = 0; + for(int i = 0; i < bitFields->length(); ++i) { + bitFields->at(i)->blockSignals(true); + + int width = bitFields->at(i)->getWidth(); + int bfVal = (((1 << (regOffset + width)) - 1) & value) >> regOffset; + QString bitFieldValue = scopy::regmap::Utils::convertToHexa(bfVal, bitFields->at(i)->getWidth()); + bitFields->at(i)->updateValue(bitFieldValue); + regOffset += width; + + bitFields->at(i)->blockSignals(false); + } + this->value->setText(scopy::regmap::Utils::convertToHexa(value, registerWidth)); + checkPreferences(); } void RegisterSimpleWidget::setRegisterSelected(bool selected) { - scopy::setDynamicProperty(regBaseInfoWidget,"is_selected",selected); - for (int i = 0; i < bitFields->length(); ++i) { - bitFields->at(i)->setSelected(selected); - } + scopy::setDynamicProperty(regBaseInfoWidget, "is_selected", selected); + for(int i = 0; i < bitFields->length(); ++i) { + bitFields->at(i)->setSelected(selected); + } } void RegisterSimpleWidget::checkPreferences() { - scopy::Preferences *p = scopy::Preferences::GetInstance(); - QString background = p->get("regmap_color_by_value").toString(); - - if (background.contains("Register background")) { - bool ok; - regBaseInfoWidget->setStyleSheet(QString("background-color: " + Util::getColors().at(value->text().toInt(&ok,16) % 16))); - } - - if (background.contains("Register text")) { - bool ok; - value->setStyleSheet(QString("color: " + Util::getColors().at(value->text().toInt(&ok,16) % 16))); - } + scopy::Preferences *p = scopy::Preferences::GetInstance(); + QString background = p->get("regmap_color_by_value").toString(); + + if(background.contains("Register background")) { + bool ok; + regBaseInfoWidget->setStyleSheet( + QString("background-color: " + Util::getColors().at(value->text().toInt(&ok, 16) % 16))); + } + + if(background.contains("Register text")) { + bool ok; + value->setStyleSheet(QString("color: " + Util::getColors().at(value->text().toInt(&ok, 16) % 16))); + } } bool RegisterSimpleWidget::eventFilter(QObject *object, QEvent *event) { - if (event->type() == QEvent::MouseButtonPress) { - bool ok; - Q_EMIT registerSelected(address.toInt(&ok,16)); - } + if(event->type() == QEvent::MouseButtonPress) { + bool ok; + Q_EMIT registerSelected(address.toInt(&ok, 16)); + } - return QWidget::eventFilter(object,event); + return QWidget::eventFilter(object, event); } - diff --git a/plugins/regmap/src/register/registersimplewidget.hpp b/plugins/regmap/src/register/registersimplewidget.hpp index 7924c34c49..11481dc023 100644 --- a/plugins/regmap/src/register/registersimplewidget.hpp +++ b/plugins/regmap/src/register/registersimplewidget.hpp @@ -9,45 +9,40 @@ class QLabel; class QHBoxLayout; -namespace scopy::regmap{ +namespace scopy::regmap { class BitFieldSimpleWidget; class RegisterSimpleWidget : public QFrame { - friend class RegmapStyleHelper; + friend class RegmapStyleHelper; - Q_OBJECT + Q_OBJECT public: - explicit RegisterSimpleWidget(QString name, - QString address, - QString description, - QString notes, - int registerWidth, - QVector *bitFields, - QWidget *parent = nullptr); + explicit RegisterSimpleWidget(QString name, QString address, QString description, QString notes, + int registerWidth, QVector *bitFields, + QWidget *parent = nullptr); - ~RegisterSimpleWidget(); + ~RegisterSimpleWidget(); - - void valueUpdated(uint32_t value); - void setRegisterSelected(bool selected); + void valueUpdated(uint32_t value); + void setRegisterSelected(bool selected); public Q_SLOTS: - void checkPreferences(); + void checkPreferences(); private: - QHBoxLayout *layout; - QLabel *value; - QVector *bitFields; - QString address; - int registerWidth; - QFrame *regBaseInfoWidget = nullptr; - QLabel *registerNameLabel; + QHBoxLayout *layout; + QLabel *value; + QVector *bitFields; + QString address; + int registerWidth; + QFrame *regBaseInfoWidget = nullptr; + QLabel *registerNameLabel; protected: - bool eventFilter(QObject *object, QEvent *event) override; + bool eventFilter(QObject *object, QEvent *event) override; Q_SIGNALS: - void registerSelected(uint32_t address); + void registerSelected(uint32_t address); }; -} +} // namespace scopy::regmap #endif // REGISTERSIMPLEWIDGET_HPP diff --git a/plugins/regmap/src/register/registersimplewidgetfactory.cpp b/plugins/regmap/src/register/registersimplewidgetfactory.cpp index 55d2fe58fa..9b8f8b9a34 100644 --- a/plugins/regmap/src/register/registersimplewidgetfactory.cpp +++ b/plugins/regmap/src/register/registersimplewidgetfactory.cpp @@ -1,9 +1,10 @@ +#include "registersimplewidgetfactory.hpp" + #include "bitfield/bitfieldmodel.hpp" #include "bitfield/bitfieldsimplewidget.hpp" #include "bitfield/bitfieldsimplewidgetfactory.hpp" #include "registermodel.hpp" #include "registersimplewidget.hpp" -#include "registersimplewidgetfactory.hpp" #include @@ -12,38 +13,36 @@ using namespace regmap; RegisterSimpleWidgetFactory::RegisterSimpleWidgetFactory(QObject *parent) : QObject{parent} -{ } +{} RegisterSimpleWidget *RegisterSimpleWidgetFactory::buildWidget(RegisterModel *model) { - QVector *bitFields = new QVector; + QVector *bitFields = new QVector; BitFieldSimpleWidgetFactory bitFieldSimpleWidgetFactory; int remaingSpaceOnRow = 8; - for (int i = 0 ; i < model->getBitFields()->size(); ++i) { + for(int i = 0; i < model->getBitFields()->size(); ++i) { BitFieldModel *modelBitField = model->getBitFields()->at(i); int width = modelBitField->getWidth(); - while (width > remaingSpaceOnRow) { - bitFields->push_back(bitFieldSimpleWidgetFactory.buildWidget(model->getBitFields()->at(i), remaingSpaceOnRow)); + while(width > remaingSpaceOnRow) { + bitFields->push_back(bitFieldSimpleWidgetFactory.buildWidget(model->getBitFields()->at(i), + remaingSpaceOnRow)); width = width - remaingSpaceOnRow; remaingSpaceOnRow = 8; } bitFields->push_back(bitFieldSimpleWidgetFactory.buildWidget(model->getBitFields()->at(i), width)); - remaingSpaceOnRow-= width; - if (remaingSpaceOnRow == 0 ) { + remaingSpaceOnRow -= width; + if(remaingSpaceOnRow == 0) { remaingSpaceOnRow = 8; } } - RegisterSimpleWidget *rsw = new RegisterSimpleWidget(model->getName(), - QString::number(model->getAddress(),16), - model->getDescription(), - model->getNotes(), - model->getWidth(), - bitFields) ; + RegisterSimpleWidget *rsw = + new RegisterSimpleWidget(model->getName(), QString::number(model->getAddress(), 16), + model->getDescription(), model->getNotes(), model->getWidth(), bitFields); - rsw->setStyleSheet(RegmapStyleHelper::simpleRegisterStyle(rsw, "rsw") + RegmapStyleHelper::frameBorderHover(rsw, "rsw") ); - return rsw; + rsw->setStyleSheet(RegmapStyleHelper::simpleRegisterStyle(rsw, "rsw") + + RegmapStyleHelper::frameBorderHover(rsw, "rsw")); + return rsw; } - diff --git a/plugins/regmap/src/register/registersimplewidgetfactory.hpp b/plugins/regmap/src/register/registersimplewidgetfactory.hpp index b5985a6860..26fc36b0b4 100644 --- a/plugins/regmap/src/register/registersimplewidgetfactory.hpp +++ b/plugins/regmap/src/register/registersimplewidgetfactory.hpp @@ -3,7 +3,7 @@ #include -namespace scopy::regmap{ +namespace scopy::regmap { class RegisterModel; class RegisterSimpleWidget; @@ -15,7 +15,6 @@ class RegisterSimpleWidgetFactory : public QObject RegisterSimpleWidget *buildWidget(RegisterModel *model); Q_SIGNALS: - }; -} +} // namespace scopy::regmap #endif // REGISTERSIMPLEWIDGETFACTORY_HPP diff --git a/plugins/regmap/src/registercontroller.cpp b/plugins/regmap/src/registercontroller.cpp index b767a022b8..36fe63ea34 100644 --- a/plugins/regmap/src/registercontroller.cpp +++ b/plugins/regmap/src/registercontroller.cpp @@ -1,135 +1,131 @@ #include "registercontroller.hpp" + #include "qtextspinbox.hpp" +#include "regmapstylehelper.hpp" +#include "utils.hpp" +#include #include #include +#include #include #include -#include -#include #include -#include "utils.hpp" -#include "regmapstylehelper.hpp" - using namespace scopy; using namespace regmap; RegisterController::RegisterController(QWidget *parent) - : QWidget{parent} + : QWidget{parent} { - mainLayout = new QHBoxLayout(this); - setLayout(mainLayout); - - QHBoxLayout *addressValueLayout = new QHBoxLayout(); - - QVBoxLayout *leftLayout = new QVBoxLayout(); - QHBoxLayout *labelLayout = new QHBoxLayout(); - QHBoxLayout *widgetsLayout = new QHBoxLayout(); - - QVBoxLayout *buttonLayout = new QVBoxLayout(); - - leftLayout->addLayout(labelLayout,1); - leftLayout->addLayout(widgetsLayout,1); - addressValueLayout->addLayout(leftLayout); - addressValueLayout->addLayout(buttonLayout); - mainLayout->addLayout(addressValueLayout,1); - - addressLabel = new QLabel("Address: ", this); - valueLabel = new QLabel("Value: ", this); - - labelLayout->addWidget(addressLabel,1); - labelLayout->addWidget(valueLabel,1); - - addressPicker = new QSpinBox(this); - addressPicker->setDisplayIntegerBase(16); - addressPicker->setMinimum(0); - addressPicker->setMaximum(INT_MAX); - addressPicker->setPrefix("0x"); - QObject::connect(addressPicker, &QSpinBox::textChanged, this, [=](QString address){ - bool ok; - Q_EMIT registerAddressChanged(address.toInt(&ok,16)); - }); - - regValue = new QLineEdit(this); - regValue->setText("N/R"); - regValue->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); - QObject::connect(regValue, &QLineEdit::textChanged, this, &RegisterController::valueChanged); - - - - widgetsLayout->addWidget(addressPicker,1); - widgetsLayout->addWidget(regValue,1); - - - readButton = new QPushButton("Read", this); - //request read - QObject::connect( readButton, &QPushButton::clicked, this , [=](){ - bool ok; - Q_EMIT requestRead(addressPicker->text().toInt(&ok,16)); - }); - - - writeButton = new QPushButton("Write", this); - //request write on register - QObject::connect( writeButton, &QPushButton::clicked, this, [=](){ - bool ok; - Q_EMIT requestWrite(addressPicker->value(), regValue->text().toInt(&ok,16)); - }); - - - buttonLayout->addWidget(readButton); - buttonLayout->addWidget(writeButton); - - applyStyle(); + mainLayout = new QHBoxLayout(this); + setLayout(mainLayout); + + QHBoxLayout *addressValueLayout = new QHBoxLayout(); + + QVBoxLayout *leftLayout = new QVBoxLayout(); + QHBoxLayout *labelLayout = new QHBoxLayout(); + QHBoxLayout *widgetsLayout = new QHBoxLayout(); + + QVBoxLayout *buttonLayout = new QVBoxLayout(); + + leftLayout->addLayout(labelLayout, 1); + leftLayout->addLayout(widgetsLayout, 1); + addressValueLayout->addLayout(leftLayout); + addressValueLayout->addLayout(buttonLayout); + mainLayout->addLayout(addressValueLayout, 1); + + addressLabel = new QLabel("Address: ", this); + valueLabel = new QLabel("Value: ", this); + + labelLayout->addWidget(addressLabel, 1); + labelLayout->addWidget(valueLabel, 1); + + addressPicker = new QSpinBox(this); + addressPicker->setDisplayIntegerBase(16); + addressPicker->setMinimum(0); + addressPicker->setMaximum(INT_MAX); + addressPicker->setPrefix("0x"); + QObject::connect(addressPicker, &QSpinBox::textChanged, this, [=](QString address) { + bool ok; + Q_EMIT registerAddressChanged(address.toInt(&ok, 16)); + }); + + regValue = new QLineEdit(this); + regValue->setText("N/R"); + regValue->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); + QObject::connect(regValue, &QLineEdit::textChanged, this, &RegisterController::valueChanged); + + widgetsLayout->addWidget(addressPicker, 1); + widgetsLayout->addWidget(regValue, 1); + + readButton = new QPushButton("Read", this); + // request read + QObject::connect(readButton, &QPushButton::clicked, this, [=]() { + bool ok; + Q_EMIT requestRead(addressPicker->text().toInt(&ok, 16)); + }); + + writeButton = new QPushButton("Write", this); + // request write on register + QObject::connect(writeButton, &QPushButton::clicked, this, [=]() { + bool ok; + Q_EMIT requestWrite(addressPicker->value(), regValue->text().toInt(&ok, 16)); + }); + + buttonLayout->addWidget(readButton); + buttonLayout->addWidget(writeButton); + + applyStyle(); } RegisterController::~RegisterController() { - delete regValue; - delete addressPicker; - if (nameLabel) delete nameLabel; - if (descriptionLabel) delete descriptionLabel; - delete mainLayout; + delete regValue; + delete addressPicker; + if(nameLabel) + delete nameLabel; + if(descriptionLabel) + delete descriptionLabel; + delete mainLayout; } void RegisterController::registerChanged(uint32_t address) { - if (!addressChanged) { - addressPicker->setValue(address); - } else { - addressChanged = false; - } + if(!addressChanged) { + addressPicker->setValue(address); + } else { + addressChanged = false; + } } -void RegisterController::registerValueChanged(QString value) -{ - regValue->setText(value); -} +void RegisterController::registerValueChanged(QString value) { regValue->setText(value); } void RegisterController::addNameAndDescription(QString name, QString description) { - if (nameLabel) { - nameLabel->setText(QString("Name: " + name)); - descriptionLabel->setText(QString("Description: " + description)); - } else { - QVBoxLayout *nameDescriptionLayout = new QVBoxLayout(); - nameLabel = new QLabel("Name: " + name); - descriptionLabel = new QLabel("Description: " + description); - nameDescriptionLayout->addWidget(nameLabel); - nameDescriptionLayout->addWidget(descriptionLabel); - mainLayout->addLayout(nameDescriptionLayout,1); - } + if(nameLabel) { + nameLabel->setText(QString("Name: " + name)); + descriptionLabel->setText(QString("Description: " + description)); + } else { + QVBoxLayout *nameDescriptionLayout = new QVBoxLayout(); + nameLabel = new QLabel("Name: " + name); + descriptionLabel = new QLabel("Description: " + description); + nameDescriptionLayout->addWidget(nameLabel); + nameDescriptionLayout->addWidget(descriptionLabel); + mainLayout->addLayout(nameDescriptionLayout, 1); + } } void RegisterController::applyStyle() { - setMaximumHeight(90); - RegmapStyleHelper::BlueButton(readButton, ""); - RegmapStyleHelper::BlueButton(writeButton, ""); - RegmapStyleHelper::labelStyle(addressLabel, ""); - RegmapStyleHelper::labelStyle(valueLabel, ""); - if (nameLabel) RegmapStyleHelper::labelStyle(nameLabel, ""); - if (descriptionLabel) RegmapStyleHelper::labelStyle(descriptionLabel, ""); + setMaximumHeight(90); + RegmapStyleHelper::BlueButton(readButton, ""); + RegmapStyleHelper::BlueButton(writeButton, ""); + RegmapStyleHelper::labelStyle(addressLabel, ""); + RegmapStyleHelper::labelStyle(valueLabel, ""); + if(nameLabel) + RegmapStyleHelper::labelStyle(nameLabel, ""); + if(descriptionLabel) + RegmapStyleHelper::labelStyle(descriptionLabel, ""); } diff --git a/plugins/regmap/src/registercontroller.hpp b/plugins/regmap/src/registercontroller.hpp index ac086edeff..46185a42a5 100644 --- a/plugins/regmap/src/registercontroller.hpp +++ b/plugins/regmap/src/registercontroller.hpp @@ -1,9 +1,10 @@ #ifndef REGISTERCONTROLLER_HPP #define REGISTERCONTROLLER_HPP -#include #include "scopy-regmapplugin_export.h" +#include + class QHBoxLayout; class QSpinBox; class QTextSpinBox; @@ -12,9 +13,7 @@ class QPushButton; class QLineEdit; class QVBoxLayout; - - -namespace scopy::regmap{ +namespace scopy::regmap { class RegisterModel; class RegisterValueWidget; class AddressPicker; @@ -28,24 +27,23 @@ class SCOPY_REGMAPPLUGIN_EXPORT RegisterController : public QWidget ~RegisterController(); void registerChanged(uint32_t address); - void registerValueChanged(QString value); - void addNameAndDescription(QString name, QString description); + void registerValueChanged(QString value); + void addNameAndDescription(QString name, QString description); private: + QHBoxLayout *mainLayout; - QHBoxLayout *mainLayout; - - QSpinBox *addressPicker; - QPushButton *readButton; - QPushButton *writeButton; - QLineEdit *regValue; - QLabel *addressLabel; - QLabel *valueLabel; + QSpinBox *addressPicker; + QPushButton *readButton; + QPushButton *writeButton; + QLineEdit *regValue; + QLabel *addressLabel; + QLabel *valueLabel; bool addressChanged = false; - QLabel *nameLabel = nullptr; - QLabel *descriptionLabel = nullptr; - void applyStyle(); + QLabel *nameLabel = nullptr; + QLabel *descriptionLabel = nullptr; + void applyStyle(); Q_SIGNALS: void requestRead(uint32_t address); @@ -53,5 +51,5 @@ class SCOPY_REGMAPPLUGIN_EXPORT RegisterController : public QWidget void registerAddressChanged(uint32_t address); void valueChanged(QString value); }; -} +} // namespace scopy::regmap #endif // REGISTERCONTROLLER_HPP diff --git a/plugins/regmap/src/registermapinstrument.cpp b/plugins/regmap/src/registermapinstrument.cpp index 39d58e9bfe..427fdedd0f 100644 --- a/plugins/regmap/src/registermapinstrument.cpp +++ b/plugins/regmap/src/registermapinstrument.cpp @@ -1,187 +1,184 @@ #include "registermapinstrument.hpp" + +#include "deviceregistermap.hpp" +#include "readwrite/fileregisterreadstrategy.hpp" +#include "readwrite/fileregisterwritestrategy.hpp" #include "readwrite/iioregisterreadstrategy.hpp" #include "readwrite/iioregisterwritestrategy.hpp" -#include "readwrite/fileregisterwritestrategy.hpp" -#include "readwrite/fileregisterreadstrategy.hpp" -#include "deviceregistermap.hpp" #include "registermapsettingsmenu.hpp" #include "registermaptemplate.hpp" #include "registermapvalues.hpp" #include "utils.hpp" #include "xmlfilemanager.hpp" + +#include +#include +#include #include #include -#include + #include -#include -#include -#include +#include using namespace scopy; using namespace regmap; RegisterMapInstrument::RegisterMapInstrument(QWidget *parent) - : QWidget{parent} + : QWidget{parent} { - layout = new QVBoxLayout(this); - Utils::removeLayoutMargins(layout); - this->setLayout(layout); - mainWidget = new QWidget(); - mainWidget->setLayout(new QVBoxLayout(mainWidget)); - - scopy::gui::ToolViewRecipe recepie; - recepie.hasChannels = false; - recepie.hasHeader = true; - recepie.hasPairSettingsBtn = true; - recepie.hasHamburgerMenuBtn = false; - - toolView = scopy::gui::ToolViewBuilder(recepie, nullptr, parent).build(); - toolView->addFixedCentralWidget(mainWidget,0,0,0,0); - toolView->getTopExtraWidget()->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - - Utils::removeLayoutMargins(toolView->getCentralWidget()->layout()); - - registerDeviceList = new QComboBox(); - activeRegisterMap = ""; - settings = new scopy::regmap::RegisterMapSettingsMenu(this); - QObject::connect(registerDeviceList, &QComboBox::currentTextChanged, this, &RegisterMapInstrument::updateActiveRegisterMap); - toolView->addTopExtraWidget(registerDeviceList); - - searchBarWidget = new scopy::regmap::SearchBarWidget(); - searchBarWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); - - QObject::connect(searchBarWidget, &scopy::regmap::SearchBarWidget::requestSearch, this, [=](QString searchParam){ - tabs->value(registerDeviceList->currentText())->applyFilters(searchParam); - }); - - toolView->addTopExtraWidget(searchBarWidget); - toolView->getTopExtraWidget()->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); - layout->addWidget(toolView); - - tabs = new QMap(); - tabsInfo = new QMap(); + layout = new QVBoxLayout(this); + Utils::removeLayoutMargins(layout); + this->setLayout(layout); + mainWidget = new QWidget(); + mainWidget->setLayout(new QVBoxLayout(mainWidget)); + + scopy::gui::ToolViewRecipe recepie; + recepie.hasChannels = false; + recepie.hasHeader = true; + recepie.hasPairSettingsBtn = true; + recepie.hasHamburgerMenuBtn = false; + + toolView = scopy::gui::ToolViewBuilder(recepie, nullptr, parent).build(); + toolView->addFixedCentralWidget(mainWidget, 0, 0, 0, 0); + toolView->getTopExtraWidget()->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + + Utils::removeLayoutMargins(toolView->getCentralWidget()->layout()); + + registerDeviceList = new QComboBox(); + activeRegisterMap = ""; + settings = new scopy::regmap::RegisterMapSettingsMenu(this); + QObject::connect(registerDeviceList, &QComboBox::currentTextChanged, this, + &RegisterMapInstrument::updateActiveRegisterMap); + toolView->addTopExtraWidget(registerDeviceList); + + searchBarWidget = new scopy::regmap::SearchBarWidget(); + searchBarWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + + QObject::connect(searchBarWidget, &scopy::regmap::SearchBarWidget::requestSearch, this, + [=](QString searchParam) { + tabs->value(registerDeviceList->currentText())->applyFilters(searchParam); + }); + + toolView->addTopExtraWidget(searchBarWidget); + toolView->getTopExtraWidget()->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + layout->addWidget(toolView); + + tabs = new QMap(); + tabsInfo = new QMap(); } RegisterMapInstrument::~RegisterMapInstrument() { - delete mainWidget; - delete tabs; + delete mainWidget; + delete tabs; } - void RegisterMapInstrument::toggleSettingsMenu(QString registerName, bool toggle) { - if (toggle) { - QObject::connect(settings, &scopy::regmap::RegisterMapSettingsMenu::autoreadToggled, tabs->value(registerName), ®map::DeviceRegisterMap::toggleAutoread); - QObject::connect(settings, &scopy::regmap::RegisterMapSettingsMenu::requestRead, tabs->value(registerName), ®map::DeviceRegisterMap::requestRead); - QObject::connect(settings, &scopy::regmap::RegisterMapSettingsMenu::requestRegisterDump, tabs->value(registerName), ®map::DeviceRegisterMap::requestRegisterDump); - QObject::connect(settings, &scopy::regmap::RegisterMapSettingsMenu::requestWrite, tabs->value(registerName), ®map::DeviceRegisterMap::requestWrite); - } else { - QObject::disconnect(settings, &scopy::regmap::RegisterMapSettingsMenu::autoreadToggled, tabs->value(registerName), ®map::DeviceRegisterMap::toggleAutoread); - QObject::disconnect(settings, &scopy::regmap::RegisterMapSettingsMenu::requestRead, tabs->value(registerName), ®map::DeviceRegisterMap::requestRead); - QObject::disconnect(settings, &scopy::regmap::RegisterMapSettingsMenu::requestRegisterDump, tabs->value(registerName), ®map::DeviceRegisterMap::requestRegisterDump); - QObject::disconnect(settings, &scopy::regmap::RegisterMapSettingsMenu::requestWrite, tabs->value(registerName), ®map::DeviceRegisterMap::requestWrite); - } + if(toggle) { + QObject::connect(settings, &scopy::regmap::RegisterMapSettingsMenu::autoreadToggled, + tabs->value(registerName), ®map::DeviceRegisterMap::toggleAutoread); + QObject::connect(settings, &scopy::regmap::RegisterMapSettingsMenu::requestRead, + tabs->value(registerName), ®map::DeviceRegisterMap::requestRead); + QObject::connect(settings, &scopy::regmap::RegisterMapSettingsMenu::requestRegisterDump, + tabs->value(registerName), ®map::DeviceRegisterMap::requestRegisterDump); + QObject::connect(settings, &scopy::regmap::RegisterMapSettingsMenu::requestWrite, + tabs->value(registerName), ®map::DeviceRegisterMap::requestWrite); + } else { + QObject::disconnect(settings, &scopy::regmap::RegisterMapSettingsMenu::autoreadToggled, + tabs->value(registerName), ®map::DeviceRegisterMap::toggleAutoread); + QObject::disconnect(settings, &scopy::regmap::RegisterMapSettingsMenu::requestRead, + tabs->value(registerName), ®map::DeviceRegisterMap::requestRead); + QObject::disconnect(settings, &scopy::regmap::RegisterMapSettingsMenu::requestRegisterDump, + tabs->value(registerName), ®map::DeviceRegisterMap::requestRegisterDump); + QObject::disconnect(settings, &scopy::regmap::RegisterMapSettingsMenu::requestWrite, + tabs->value(registerName), ®map::DeviceRegisterMap::requestWrite); + } } void RegisterMapInstrument::generateDeviceRegisterMap(TabInfo *tabInfo) { - RegisterMapTemplate *registerMapTemplate = nullptr; - if (!tabInfo->getXmlPath().isEmpty()) { - registerMapTemplate = new RegisterMapTemplate(this); - XmlFileManager xmlFileManager(tabInfo->getDev(), tabInfo->getXmlPath()); - auto aux = xmlFileManager.getAllRegisters(); - if (!aux->isEmpty()){ - registerMapTemplate->setRegisterList(aux); - } - } - RegisterMapValues *registerMapValues = nullptr; - if (tabInfo->getDev()){ - registerMapValues = getRegisterMapValues(tabInfo->getDev()); - } else { - registerMapValues = getRegisterMapValues(tabInfo->getXmlPath()); - } - - DeviceRegisterMap *regMap = new DeviceRegisterMap(registerMapTemplate,registerMapValues, this); - tabs->insert(tabInfo->getDeviceName(), regMap); - mainWidget->layout()->addWidget(regMap); - tabs->value(tabInfo->getDeviceName())->hide(); - + RegisterMapTemplate *registerMapTemplate = nullptr; + if(!tabInfo->getXmlPath().isEmpty()) { + registerMapTemplate = new RegisterMapTemplate(this); + XmlFileManager xmlFileManager(tabInfo->getDev(), tabInfo->getXmlPath()); + auto aux = xmlFileManager.getAllRegisters(); + if(!aux->isEmpty()) { + registerMapTemplate->setRegisterList(aux); + } + } + RegisterMapValues *registerMapValues = nullptr; + if(tabInfo->getDev()) { + registerMapValues = getRegisterMapValues(tabInfo->getDev()); + } else { + registerMapValues = getRegisterMapValues(tabInfo->getXmlPath()); + } + + DeviceRegisterMap *regMap = new DeviceRegisterMap(registerMapTemplate, registerMapValues, this); + tabs->insert(tabInfo->getDeviceName(), regMap); + mainWidget->layout()->addWidget(regMap); + tabs->value(tabInfo->getDeviceName())->hide(); } void RegisterMapInstrument::updateActiveRegisterMap(QString registerName) { - if (activeRegisterMap != "" && registerName != activeRegisterMap) { - tabs->value(activeRegisterMap)->hide(); - toggleSettingsMenu(activeRegisterMap, false); - - if (! tabs->value(registerName) ) { - generateDeviceRegisterMap(tabsInfo->value(registerName)); - } - tabs->value(registerName)->show(); - toggleSettingsMenu(registerName, true); - toggleSearchBarVisible(tabs->value(registerName)->hasTemplate()); - - activeRegisterMap = registerName; - } -} - -void RegisterMapInstrument::toggleSearchBarVisible(bool visible) -{ - searchBarWidget->setVisible(visible); + if(activeRegisterMap != "" && registerName != activeRegisterMap) { + tabs->value(activeRegisterMap)->hide(); + toggleSettingsMenu(activeRegisterMap, false); + + if(!tabs->value(registerName)) { + generateDeviceRegisterMap(tabsInfo->value(registerName)); + } + tabs->value(registerName)->show(); + toggleSettingsMenu(registerName, true); + toggleSearchBarVisible(tabs->value(registerName)->hasTemplate()); + + activeRegisterMap = registerName; + } } +void RegisterMapInstrument::toggleSearchBarVisible(bool visible) { searchBarWidget->setVisible(visible); } RegisterMapValues *RegisterMapInstrument::getRegisterMapValues(struct iio_device *dev) { - IIORegisterReadStrategy *iioReadStrategy = new IIORegisterReadStrategy(dev); - IIORegisterWriteStrategy *iioWriteStrategy = new IIORegisterWriteStrategy(dev); - RegisterMapValues *registerMapValues = new RegisterMapValues(); - registerMapValues->setReadStrategy(iioReadStrategy); - registerMapValues->setWriteStrategy(iioWriteStrategy); + IIORegisterReadStrategy *iioReadStrategy = new IIORegisterReadStrategy(dev); + IIORegisterWriteStrategy *iioWriteStrategy = new IIORegisterWriteStrategy(dev); + RegisterMapValues *registerMapValues = new RegisterMapValues(); + registerMapValues->setReadStrategy(iioReadStrategy); + registerMapValues->setWriteStrategy(iioWriteStrategy); - return registerMapValues; + return registerMapValues; } RegisterMapValues *RegisterMapInstrument::getRegisterMapValues(QString filePath) { - FileRegisterReadStrategy *fileRegisterReadStrategy = new FileRegisterReadStrategy(filePath); - FileRegisterWriteStrategy *fileRegisterWriteStrategy = new FileRegisterWriteStrategy(filePath); - RegisterMapValues *registerMapValues = new RegisterMapValues(); - registerMapValues->setReadStrategy(fileRegisterReadStrategy); - registerMapValues->setWriteStrategy(fileRegisterWriteStrategy); + FileRegisterReadStrategy *fileRegisterReadStrategy = new FileRegisterReadStrategy(filePath); + FileRegisterWriteStrategy *fileRegisterWriteStrategy = new FileRegisterWriteStrategy(filePath); + RegisterMapValues *registerMapValues = new RegisterMapValues(); + registerMapValues->setReadStrategy(fileRegisterReadStrategy); + registerMapValues->setWriteStrategy(fileRegisterWriteStrategy); - return registerMapValues; + return registerMapValues; } -void RegisterMapInstrument::addTab(iio_device *dev, QString title) -{ - addTab(dev,title, ""); -} - -void RegisterMapInstrument::addTab(QString filePath, QString title) -{ - addTab(nullptr,title, filePath); +void RegisterMapInstrument::addTab(iio_device *dev, QString title) { addTab(dev, title, ""); } -} +void RegisterMapInstrument::addTab(QString filePath, QString title) { addTab(nullptr, title, filePath); } void RegisterMapInstrument::addTab(iio_device *dev, QString title, QString xmlPath) { - tabsInfo->insert(title, new TabInfo(dev,title,xmlPath)); - - - registerDeviceList->addItem(title); - + tabsInfo->insert(title, new TabInfo(dev, title, xmlPath)); - if (first) { - // the first regmap is set active - activeRegisterMap = title; - first = false; - generateDeviceRegisterMap(tabsInfo->value(title)); - toolView->setGeneralSettingsMenu(settings, true); - tabs->value(title)->show(); - toggleSettingsMenu(title, true); - } + registerDeviceList->addItem(title); + if(first) { + // the first regmap is set active + activeRegisterMap = title; + first = false; + generateDeviceRegisterMap(tabsInfo->value(title)); + toolView->setGeneralSettingsMenu(settings, true); + tabs->value(title)->show(); + toggleSettingsMenu(title, true); + } } diff --git a/plugins/regmap/src/registermapinstrument.hpp b/plugins/regmap/src/registermapinstrument.hpp index 1a124d2a36..81c3f1d42a 100644 --- a/plugins/regmap/src/registermapinstrument.hpp +++ b/plugins/regmap/src/registermapinstrument.hpp @@ -1,13 +1,15 @@ #ifndef REGISTERMAPINSTRUMENT_HPP #define REGISTERMAPINSTRUMENT_HPP +#include "scopy-regmapplugin_export.h" + #include -#include + #include #include -#include + #include -#include "scopy-regmapplugin_export.h" +#include class QComboBox; class QVBoxLayout; @@ -24,34 +26,34 @@ class SCOPY_REGMAPPLUGIN_EXPORT RegisterMapInstrument : public QWidget Q_OBJECT public: explicit RegisterMapInstrument(QWidget *parent = nullptr); - ~RegisterMapInstrument(); + ~RegisterMapInstrument(); - void addTab(struct iio_device *dev, QString title, QString xmlPath); - void addTab(struct iio_device *dev, QString title); - void addTab(QString filePath, QString title); + void addTab(struct iio_device *dev, QString title, QString xmlPath); + void addTab(struct iio_device *dev, QString title); + void addTab(QString filePath, QString title); signals: private: - QVBoxLayout *layout; - QWidget *mainWidget; - scopy::gui::ToolView *toolView; - - RegisterMapValues* getRegisterMapValues(struct iio_device *dev); - RegisterMapValues* getRegisterMapValues(QString filePath); - - QMap *tabs; - QMap *tabsInfo; - bool first = true; - QString activeRegisterMap; - QComboBox *registerDeviceList; - void toggleSettingsMenu(QString registerName, bool toggle); - scopy::regmap::RegisterMapSettingsMenu *settings; - SearchBarWidget *searchBarWidget; - void generateDeviceRegisterMap(TabInfo *tabInfo); + QVBoxLayout *layout; + QWidget *mainWidget; + scopy::gui::ToolView *toolView; + + RegisterMapValues *getRegisterMapValues(struct iio_device *dev); + RegisterMapValues *getRegisterMapValues(QString filePath); + + QMap *tabs; + QMap *tabsInfo; + bool first = true; + QString activeRegisterMap; + QComboBox *registerDeviceList; + void toggleSettingsMenu(QString registerName, bool toggle); + scopy::regmap::RegisterMapSettingsMenu *settings; + SearchBarWidget *searchBarWidget; + void generateDeviceRegisterMap(TabInfo *tabInfo); private Q_SLOTS: - void updateActiveRegisterMap(QString registerName); - void toggleSearchBarVisible(bool visible); + void updateActiveRegisterMap(QString registerName); + void toggleSearchBarVisible(bool visible); }; -} +} // namespace scopy::regmap #endif // REGISTERMAPINSTRUMENT_HPP diff --git a/plugins/regmap/src/registermapsettingsmenu.cpp b/plugins/regmap/src/registermapsettingsmenu.cpp index 10884a3a39..2195af3bc1 100644 --- a/plugins/regmap/src/registermapsettingsmenu.cpp +++ b/plugins/regmap/src/registermapsettingsmenu.cpp @@ -1,15 +1,16 @@ #include "registermapsettingsmenu.hpp" +#include "regmapstylehelper.hpp" +#include "utils.hpp" + #include +#include +#include +#include #include #include #include #include -#include -#include -#include -#include "utils.hpp" -#include "regmapstylehelper.hpp" #include @@ -17,146 +18,142 @@ using namespace scopy; using namespace regmap; RegisterMapSettingsMenu::RegisterMapSettingsMenu(QWidget *parent) - : GenericMenu{parent} + : GenericMenu{parent} { - initInteractiveMenu(); - const QColor *color = new QColor(RegmapStyleHelper::getColor("ScopyBlue")); - setMenuHeader("Settings", color, false); - - scopy::gui::SubsectionSeparator *menuSection = new scopy::gui::SubsectionSeparator("", false); - menuSection->setLineVisible(false); - insertSection(menuSection); - menuSection->getContentWidget()->layout()->setSpacing(5); - - autoread = new QCheckBox("Autoread"); - - QObject::connect(autoread, &QCheckBox::toggled, this, &RegisterMapSettingsMenu::autoreadToggled); - menuSection->getContentWidget()->layout()->addWidget(autoread); - - QWidget *setIntervalWidget = new QWidget(); - QVBoxLayout *setIntervalWidgetLayout = new QVBoxLayout(setIntervalWidget); - setIntervalWidget->setLayout(setIntervalWidgetLayout); - - QHBoxLayout *startReadIntervalLayout = new QHBoxLayout(); - hexaPrefix1 = new QLabel("0x"); - startReadIntervalLayout->addWidget(hexaPrefix1); - setIntervalWidgetLayout->addLayout(startReadIntervalLayout); - - startReadInterval = new QLineEdit(); - startReadInterval->setPlaceholderText("From register"); - startReadIntervalLayout->addWidget(startReadInterval); - hexaPrefix2 = new QLabel("0x"); - QHBoxLayout *endReadIntervalLayout = new QHBoxLayout(); - endReadIntervalLayout->addWidget(hexaPrefix2); - setIntervalWidgetLayout->addLayout(endReadIntervalLayout); - - endReadInterval = new QLineEdit(); - endReadInterval->setPlaceholderText("To register"); - endReadIntervalLayout->addWidget(endReadInterval); - - readInterval = new QPushButton("Read interval"); - - readInterval->setEnabled(false); - - QObject::connect(readInterval, &QPushButton::clicked, this, [=](){ - bool ok; - int startInterval = startReadInterval->text().toInt(&ok,16); - int endInterval = endReadInterval->text().toInt(&ok,16); - for (int i = startInterval; i <= endInterval; i++) { - Q_EMIT requestRead(i); - } - }); - - QObject::connect(startReadInterval, &QLineEdit::textChanged, this, [=](){ - if ( !startReadInterval->text().isEmpty() && !endReadInterval->text().isEmpty()) { - readInterval->setEnabled(true); - } else { - readInterval->setEnabled(false); - } - }); - - QObject::connect(endReadInterval, &QLineEdit::textChanged, this, [=](){ - if ( !startReadInterval->text().isEmpty() && !endReadInterval->text().isEmpty()) { - readInterval->setEnabled(true); - } else { - readInterval->setEnabled(false); - } - }); - - menuSection->getContentWidget()->layout()->addWidget(setIntervalWidget); - menuSection->getContentWidget()->layout()->addWidget(readInterval); - - QWidget *findPathWidget = new QWidget(); - QHBoxLayout *findPathLayout = new QHBoxLayout(); - Utils::removeLayoutMargins(findPathLayout); - findPathWidget->setLayout(findPathLayout); - - filePath = new QLineEdit(); - filePath->setPlaceholderText("File path"); - pathButton = new QPushButton("Find path"); - - - QObject::connect(pathButton, &QPushButton::clicked, this, [=](){ - filePath->setText(QFileDialog::getOpenFileName(this, ("Open File"), "")); - }); - - findPathLayout->addWidget(filePath); - findPathLayout->addWidget(pathButton); - menuSection->getContentWidget()->layout()->addWidget(findPathWidget); - - - writeListOfValuesButton = new QPushButton("Write values"); - writeListOfValuesButton->setEnabled(false); - - QObject::connect(writeListOfValuesButton, &QPushButton::clicked, this, [=](){ - - bool ok; - int startInterval = startReadInterval->text().toInt(&ok,16); - int endInterval = endReadInterval->text().toInt(&ok,16); - - FileRegisterReadStrategy *fileRead = new FileRegisterReadStrategy(filePath->text()); - - QObject::connect(fileRead, &FileRegisterReadStrategy::readDone, this, &RegisterMapSettingsMenu::requestWrite); - - for (int i = startInterval; i <= endInterval; i++) { - fileRead->read(i); - } - }); - - menuSection->getContentWidget()->layout()->addWidget(writeListOfValuesButton); - - registerDump = new QPushButton("Register dump"); - registerDump->setEnabled(false); - - QObject::connect(registerDump, &QPushButton::clicked, this, [=](){ - if (autoread->isChecked()) { - readInterval->click(); - } - QFile::remove(filePath->text()); - Q_EMIT requestRegisterDump(filePath->text()); - }); - - menuSection->getContentWidget()->layout()->addWidget(registerDump); - - - QObject::connect(filePath, &QLineEdit::textChanged, this, [=](QString text){ - writeListOfValuesButton->setEnabled(!text.isEmpty()); - registerDump->setEnabled(!text.isEmpty()); - }); - - QSpacerItem *spacer = new QSpacerItem(10,10,QSizePolicy::Preferred, QSizePolicy::Expanding); - this->layout()->addItem(spacer); - - applyStyle(); + initInteractiveMenu(); + const QColor *color = new QColor(RegmapStyleHelper::getColor("ScopyBlue")); + setMenuHeader("Settings", color, false); + + scopy::gui::SubsectionSeparator *menuSection = new scopy::gui::SubsectionSeparator("", false); + menuSection->setLineVisible(false); + insertSection(menuSection); + menuSection->getContentWidget()->layout()->setSpacing(5); + + autoread = new QCheckBox("Autoread"); + + QObject::connect(autoread, &QCheckBox::toggled, this, &RegisterMapSettingsMenu::autoreadToggled); + menuSection->getContentWidget()->layout()->addWidget(autoread); + + QWidget *setIntervalWidget = new QWidget(); + QVBoxLayout *setIntervalWidgetLayout = new QVBoxLayout(setIntervalWidget); + setIntervalWidget->setLayout(setIntervalWidgetLayout); + + QHBoxLayout *startReadIntervalLayout = new QHBoxLayout(); + hexaPrefix1 = new QLabel("0x"); + startReadIntervalLayout->addWidget(hexaPrefix1); + setIntervalWidgetLayout->addLayout(startReadIntervalLayout); + + startReadInterval = new QLineEdit(); + startReadInterval->setPlaceholderText("From register"); + startReadIntervalLayout->addWidget(startReadInterval); + hexaPrefix2 = new QLabel("0x"); + QHBoxLayout *endReadIntervalLayout = new QHBoxLayout(); + endReadIntervalLayout->addWidget(hexaPrefix2); + setIntervalWidgetLayout->addLayout(endReadIntervalLayout); + + endReadInterval = new QLineEdit(); + endReadInterval->setPlaceholderText("To register"); + endReadIntervalLayout->addWidget(endReadInterval); + + readInterval = new QPushButton("Read interval"); + + readInterval->setEnabled(false); + + QObject::connect(readInterval, &QPushButton::clicked, this, [=]() { + bool ok; + int startInterval = startReadInterval->text().toInt(&ok, 16); + int endInterval = endReadInterval->text().toInt(&ok, 16); + for(int i = startInterval; i <= endInterval; i++) { + Q_EMIT requestRead(i); + } + }); + + QObject::connect(startReadInterval, &QLineEdit::textChanged, this, [=]() { + if(!startReadInterval->text().isEmpty() && !endReadInterval->text().isEmpty()) { + readInterval->setEnabled(true); + } else { + readInterval->setEnabled(false); + } + }); + + QObject::connect(endReadInterval, &QLineEdit::textChanged, this, [=]() { + if(!startReadInterval->text().isEmpty() && !endReadInterval->text().isEmpty()) { + readInterval->setEnabled(true); + } else { + readInterval->setEnabled(false); + } + }); + + menuSection->getContentWidget()->layout()->addWidget(setIntervalWidget); + menuSection->getContentWidget()->layout()->addWidget(readInterval); + + QWidget *findPathWidget = new QWidget(); + QHBoxLayout *findPathLayout = new QHBoxLayout(); + Utils::removeLayoutMargins(findPathLayout); + findPathWidget->setLayout(findPathLayout); + + filePath = new QLineEdit(); + filePath->setPlaceholderText("File path"); + pathButton = new QPushButton("Find path"); + + QObject::connect(pathButton, &QPushButton::clicked, this, + [=]() { filePath->setText(QFileDialog::getOpenFileName(this, ("Open File"), "")); }); + + findPathLayout->addWidget(filePath); + findPathLayout->addWidget(pathButton); + menuSection->getContentWidget()->layout()->addWidget(findPathWidget); + + writeListOfValuesButton = new QPushButton("Write values"); + writeListOfValuesButton->setEnabled(false); + + QObject::connect(writeListOfValuesButton, &QPushButton::clicked, this, [=]() { + bool ok; + int startInterval = startReadInterval->text().toInt(&ok, 16); + int endInterval = endReadInterval->text().toInt(&ok, 16); + + FileRegisterReadStrategy *fileRead = new FileRegisterReadStrategy(filePath->text()); + + QObject::connect(fileRead, &FileRegisterReadStrategy::readDone, this, + &RegisterMapSettingsMenu::requestWrite); + + for(int i = startInterval; i <= endInterval; i++) { + fileRead->read(i); + } + }); + + menuSection->getContentWidget()->layout()->addWidget(writeListOfValuesButton); + + registerDump = new QPushButton("Register dump"); + registerDump->setEnabled(false); + + QObject::connect(registerDump, &QPushButton::clicked, this, [=]() { + if(autoread->isChecked()) { + readInterval->click(); + } + QFile::remove(filePath->text()); + Q_EMIT requestRegisterDump(filePath->text()); + }); + + menuSection->getContentWidget()->layout()->addWidget(registerDump); + + QObject::connect(filePath, &QLineEdit::textChanged, this, [=](QString text) { + writeListOfValuesButton->setEnabled(!text.isEmpty()); + registerDump->setEnabled(!text.isEmpty()); + }); + + QSpacerItem *spacer = new QSpacerItem(10, 10, QSizePolicy::Preferred, QSizePolicy::Expanding); + this->layout()->addItem(spacer); + + applyStyle(); } void RegisterMapSettingsMenu::applyStyle() { - RegmapStyleHelper::checkboxStyle(autoread, ""); - RegmapStyleHelper::bigTextLabelStyle(hexaPrefix1, ""); - RegmapStyleHelper::bigTextLabelStyle(hexaPrefix2, ""); - RegmapStyleHelper::BlueButton(readInterval, ""); - RegmapStyleHelper::BlueButton(writeListOfValuesButton, ""); - RegmapStyleHelper::BlueButton(registerDump, ""); - RegmapStyleHelper::BlueButton(pathButton, ""); + RegmapStyleHelper::checkboxStyle(autoread, ""); + RegmapStyleHelper::bigTextLabelStyle(hexaPrefix1, ""); + RegmapStyleHelper::bigTextLabelStyle(hexaPrefix2, ""); + RegmapStyleHelper::BlueButton(readInterval, ""); + RegmapStyleHelper::BlueButton(writeListOfValuesButton, ""); + RegmapStyleHelper::BlueButton(registerDump, ""); + RegmapStyleHelper::BlueButton(pathButton, ""); } diff --git a/plugins/regmap/src/registermapsettingsmenu.hpp b/plugins/regmap/src/registermapsettingsmenu.hpp index ed67136a09..ce741d46e6 100644 --- a/plugins/regmap/src/registermapsettingsmenu.hpp +++ b/plugins/regmap/src/registermapsettingsmenu.hpp @@ -3,40 +3,40 @@ #include #include -#include +#include class QCheckBox; class QLineEdit; -namespace scopy { +namespace scopy { namespace regmap { class RegisterMapSettingsMenu : public ::scopy::gui::GenericMenu { - Q_OBJECT + Q_OBJECT public: - explicit RegisterMapSettingsMenu(QWidget *parent = nullptr); + explicit RegisterMapSettingsMenu(QWidget *parent = nullptr); Q_SIGNALS: - void autoreadToggled(bool toggled); - void requestRead(int address); - void requestWrite(uint32_t address, uint32_t value); - void requestRegisterDump(QString path); + void autoreadToggled(bool toggled); + void requestRead(int address); + void requestWrite(uint32_t address, uint32_t value); + void requestRegisterDump(QString path); private: - void applyStyle(); - QCheckBox *autoread; - QLabel *hexaPrefix1; - QLabel *hexaPrefix2; - QLineEdit *startReadInterval; - QLineEdit *endReadInterval; - QPushButton *readInterval; - QLineEdit *filePath; - QPushButton *writeListOfValuesButton; - QPushButton *registerDump; - QPushButton *pathButton; + void applyStyle(); + QCheckBox *autoread; + QLabel *hexaPrefix1; + QLabel *hexaPrefix2; + QLineEdit *startReadInterval; + QLineEdit *endReadInterval; + QPushButton *readInterval; + QLineEdit *filePath; + QPushButton *writeListOfValuesButton; + QPushButton *registerDump; + QPushButton *pathButton; }; -} -} +} // namespace regmap +} // namespace scopy #endif // REGISTERMAPSETTINGSMENU_HPP diff --git a/plugins/regmap/src/registermaptemplate.cpp b/plugins/regmap/src/registermaptemplate.cpp index 1e24b2d3f8..529d5a3ac4 100644 --- a/plugins/regmap/src/registermaptemplate.cpp +++ b/plugins/regmap/src/registermaptemplate.cpp @@ -1,57 +1,46 @@ #include "registermaptemplate.hpp" -#include "xmlfilemanager.hpp" -#include -#include "register/registermodel.hpp" + #include "register/bitfield/bitfieldmodel.hpp" +#include "register/registermodel.hpp" #include "search.hpp" +#include "xmlfilemanager.hpp" + +#include using namespace scopy; using namespace regmap; RegisterMapTemplate::RegisterMapTemplate(QObject *parent) - : QObject{parent} + : QObject{parent} { - registerList = new QMap(); + registerList = new QMap(); } -RegisterMapTemplate::~RegisterMapTemplate() -{ - delete registerList; -} +RegisterMapTemplate::~RegisterMapTemplate() { delete registerList; } -QMap *RegisterMapTemplate::getRegisterList() const -{ - return registerList; -} +QMap *RegisterMapTemplate::getRegisterList() const { return registerList; } RegisterModel *RegisterMapTemplate::getRegisterTemplate(uint32_t address) { - if (registerList->contains(address)) { - return registerList->value(address); - } - return getDefaultTemplate(address); + if(registerList->contains(address)) { + return registerList->value(address); + } + return getDefaultTemplate(address); } void RegisterMapTemplate::setRegisterList(QMap *newRegisterList) { - registerList = newRegisterList; + registerList = newRegisterList; } RegisterModel *RegisterMapTemplate::getDefaultTemplate(uint32_t address) { - QVector *bitFieldsList = new QVector(); - - for (int i = 0 ; i < 8; ++i) { - bitFieldsList->push_back(new BitFieldModel("Bit " + QString::number(i) ,1, 8 - i, "")); - } - - return new RegisterModel( "Register Name", - address, - "Register Description", - true, - 8, - "Reigster Notes", - bitFieldsList - ); -} + QVector *bitFieldsList = new QVector(); + + for(int i = 0; i < 8; ++i) { + bitFieldsList->push_back(new BitFieldModel("Bit " + QString::number(i), 1, 8 - i, "")); + } + return new RegisterModel("Register Name", address, "Register Description", true, 8, "Reigster Notes", + bitFieldsList); +} diff --git a/plugins/regmap/src/registermaptemplate.hpp b/plugins/regmap/src/registermaptemplate.hpp index 6371b8a189..4baf7260c2 100644 --- a/plugins/regmap/src/registermaptemplate.hpp +++ b/plugins/regmap/src/registermaptemplate.hpp @@ -1,27 +1,27 @@ #ifndef REGISTERMAPTEMPLATE_HPP #define REGISTERMAPTEMPLATE_HPP -#include #include "scopy-regmapplugin_export.h" -namespace scopy::regmap{ +#include + +namespace scopy::regmap { class RegisterModel; class SCOPY_REGMAPPLUGIN_EXPORT RegisterMapTemplate : public QObject { - Q_OBJECT + Q_OBJECT public: - explicit RegisterMapTemplate(QObject *parent = nullptr); - ~RegisterMapTemplate(); + explicit RegisterMapTemplate(QObject *parent = nullptr); + ~RegisterMapTemplate(); - QMap *getRegisterList() const; - RegisterModel* getRegisterTemplate(uint32_t address); - void setRegisterList(QMap *newRegisterList); - RegisterModel* getDefaultTemplate(uint32_t address); + QMap *getRegisterList() const; + RegisterModel *getRegisterTemplate(uint32_t address); + void setRegisterList(QMap *newRegisterList); + RegisterModel *getDefaultTemplate(uint32_t address); private: - QMap *registerList; + QMap *registerList; Q_SIGNALS: - }; -} +} // namespace scopy::regmap #endif // REGISTERMAPTEMPLATE_HPP diff --git a/plugins/regmap/src/registermapvalues.cpp b/plugins/regmap/src/registermapvalues.cpp index 42427b7cc8..0af5765f0e 100644 --- a/plugins/regmap/src/registermapvalues.cpp +++ b/plugins/regmap/src/registermapvalues.cpp @@ -1,7 +1,8 @@ #include "registermapvalues.hpp" -#include "regreadwrite.hpp" + #include "readwrite/iregisterreadstrategy.hpp" #include "readwrite/iregisterwritestrategy.hpp" +#include "regreadwrite.hpp" #include #include @@ -11,80 +12,62 @@ using namespace scopy; using namespace regmap; RegisterMapValues::RegisterMapValues(QObject *parent) - : QObject{parent} + : QObject{parent} { - registerReadValues = new QMap(); - - m_readConnection = QObject::connect(this, &RegisterMapValues::requestRead, this, &RegisterMapValues::getValueOfRegister); - writeConnection = QObject::connect(this, &RegisterMapValues::requestWrite, this, &RegisterMapValues::readDone); + registerReadValues = new QMap(); + m_readConnection = + QObject::connect(this, &RegisterMapValues::requestRead, this, &RegisterMapValues::getValueOfRegister); + writeConnection = QObject::connect(this, &RegisterMapValues::requestWrite, this, &RegisterMapValues::readDone); } -RegisterMapValues::~RegisterMapValues() -{ - delete registerReadValues; -} +RegisterMapValues::~RegisterMapValues() { delete registerReadValues; } -QMap *RegisterMapValues::getRegisterReadValues() const -{ - return registerReadValues; -} +QMap *RegisterMapValues::getRegisterReadValues() const { return registerReadValues; } -bool RegisterMapValues::hasValue(uint32_t address) -{ - return registerReadValues->contains(address); -} +bool RegisterMapValues::hasValue(uint32_t address) { return registerReadValues->contains(address); } void RegisterMapValues::readDone(uint32_t address, uint32_t value) { - registerReadValues->insert(address, value); - Q_EMIT registerValueChanged(address, value); + registerReadValues->insert(address, value); + Q_EMIT registerValueChanged(address, value); } -uint32_t RegisterMapValues::getValueOfRegister(uint32_t address) -{ - return registerReadValues->value(address); -} +uint32_t RegisterMapValues::getValueOfRegister(uint32_t address) { return registerReadValues->value(address); } void RegisterMapValues::setReadStrategy(IRegisterReadStrategy *readStrategy) { - this->readStrategy = readStrategy; - QObject::disconnect(m_readConnection); - QObject::connect(this, &RegisterMapValues::requestRead, readStrategy, &IRegisterReadStrategy::read); - QObject::connect(readStrategy, &IRegisterReadStrategy::readDone, this, &RegisterMapValues::readDone); - + this->readStrategy = readStrategy; + QObject::disconnect(m_readConnection); + QObject::connect(this, &RegisterMapValues::requestRead, readStrategy, &IRegisterReadStrategy::read); + QObject::connect(readStrategy, &IRegisterReadStrategy::readDone, this, &RegisterMapValues::readDone); } void RegisterMapValues::setWriteStrategy(IRegisterWriteStrategy *writeStrategy) { - this->writeStrategy = writeStrategy; - QObject::disconnect(writeConnection); - QObject::connect(this, &RegisterMapValues::requestWrite, writeStrategy, &IRegisterWriteStrategy::write); - if (readStrategy) { - QObject::connect(writeStrategy, &IRegisterWriteStrategy::writeSuccess, readStrategy, &IRegisterReadStrategy::read); - } + this->writeStrategy = writeStrategy; + QObject::disconnect(writeConnection); + QObject::connect(this, &RegisterMapValues::requestWrite, writeStrategy, &IRegisterWriteStrategy::write); + if(readStrategy) { + QObject::connect(writeStrategy, &IRegisterWriteStrategy::writeSuccess, readStrategy, + &IRegisterReadStrategy::read); + } } void RegisterMapValues::registerDump(QString path) { - IRegisterWriteStrategy *currentStrategy = getWriteStrategy(); - setWriteStrategy(new FileRegisterWriteStrategy(path)); + IRegisterWriteStrategy *currentStrategy = getWriteStrategy(); + setWriteStrategy(new FileRegisterWriteStrategy(path)); - QMap::iterator mapIterator; + QMap::iterator mapIterator; - for (mapIterator = registerReadValues->begin() ; mapIterator != registerReadValues->end(); mapIterator++ ) { - Q_EMIT requestWrite(mapIterator.key(), mapIterator.value()); - } + for(mapIterator = registerReadValues->begin(); mapIterator != registerReadValues->end(); mapIterator++) { + Q_EMIT requestWrite(mapIterator.key(), mapIterator.value()); + } - setWriteStrategy(currentStrategy); + setWriteStrategy(currentStrategy); } -IRegisterReadStrategy *RegisterMapValues::getReadStrategy() const -{ - return readStrategy; -} +IRegisterReadStrategy *RegisterMapValues::getReadStrategy() const { return readStrategy; } -IRegisterWriteStrategy *RegisterMapValues::getWriteStrategy() const -{ - return writeStrategy; -} +IRegisterWriteStrategy *RegisterMapValues::getWriteStrategy() const { return writeStrategy; } diff --git a/plugins/regmap/src/registermapvalues.hpp b/plugins/regmap/src/registermapvalues.hpp index 1ec5d6117b..084f47a7dc 100644 --- a/plugins/regmap/src/registermapvalues.hpp +++ b/plugins/regmap/src/registermapvalues.hpp @@ -1,11 +1,12 @@ #ifndef REGISTERMAPVALUES_HPP #define REGISTERMAPVALUES_HPP -#include -#include #include "scopy-regmapplugin_export.h" -namespace scopy::regmap{ +#include +#include + +namespace scopy::regmap { class IRegisterWriteStrategy; class IRegisterReadStrategy; class RegReadWrite; @@ -17,14 +18,13 @@ class SCOPY_REGMAPPLUGIN_EXPORT RegisterMapValues : public QObject explicit RegisterMapValues(QObject *parent = nullptr); ~RegisterMapValues(); - QMap *registerReadValues; void readDone(uint32_t address, uint32_t value); uint32_t getValueOfRegister(uint32_t address); void setReadStrategy(IRegisterReadStrategy *readStrategy); void setWriteStrategy(IRegisterWriteStrategy *writeStrategy); - void registerDump(QString path); + void registerDump(QString path); IRegisterReadStrategy *getReadStrategy() const; @@ -44,5 +44,5 @@ class SCOPY_REGMAPPLUGIN_EXPORT RegisterMapValues : public QObject QMetaObject::Connection m_readConnection; QMetaObject::Connection writeConnection; }; -} +} // namespace scopy::regmap #endif // REGISTERMAPVALUES_HPP diff --git a/plugins/regmap/src/regmapplugin.cpp b/plugins/regmap/src/regmapplugin.cpp index 0ac1f31a81..0a9adbfe78 100644 --- a/plugins/regmap/src/regmapplugin.cpp +++ b/plugins/regmap/src/regmapplugin.cpp @@ -1,31 +1,34 @@ +#include "regmapplugin.h" + #include "deviceregistermap.hpp" +#include "iioutil/contextprovider.h" +#include "jsonformatedelement.hpp" +#include "logging_categories.h" #include "registermapinstrument.hpp" #include "registermaptemplate.hpp" #include "registermapvalues.hpp" -#include "regmapplugin.h" +#include "scopy-regmapplugin_config.h" +#include "utils.hpp" #include "xmlfilemanager.hpp" + #include -#include -#include + #include -#include -#include #include +#include #include #include -#include -#include -#include +#include +#include +#include +#include + #include #include +#include +#include #include #include -#include "logging_categories.h" - -#include "iioutil/contextprovider.h" -#include "jsonformatedelement.hpp" -#include "scopy-regmapplugin_config.h" -#include "utils.hpp" #if defined __APPLE__ #include #endif @@ -34,162 +37,165 @@ using namespace scopy; bool RegmapPlugin::loadPage() { - //TODO - m_page = new QWidget(); + // TODO + m_page = new QWidget(); - return true; + return true; } bool RegmapPlugin::loadIcon() { - m_icon = new QLabel(""); - m_icon->setStyleSheet("border-image: url(:/icons/RegMap.svg);"); - return true; + m_icon = new QLabel(""); + m_icon->setStyleSheet("border-image: url(:/icons/RegMap.svg);"); + return true; } void RegmapPlugin::loadToolList() { - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("regmap","Register Map",":/icons/RegMap.svg")); + m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("regmap", "Register Map", ":/icons/RegMap.svg")); } void RegmapPlugin::unload() { - //TODO + // TODO } bool RegmapPlugin::compatible(QString m_param, QString category) { - m_name="REGMAP"; - auto &&cp = ContextProvider::GetInstance(); - iio_context* ctx = cp->open(m_param); - - if (!ctx) { - cp->close(m_param); - return false; - } else { - - auto deviceCount = iio_context_get_devices_count(ctx); - for (int i = 0; i < deviceCount; i++) { - iio_device *dev = iio_context_get_device(ctx, i); - if (iio_device_find_debug_attr(dev,"direct_reg_access")) { - cp->close(m_param); - return true; - } - } - } - cp->close(m_param); - - return false; + m_name = "REGMAP"; + auto &&cp = ContextProvider::GetInstance(); + iio_context *ctx = cp->open(m_param); + + if(!ctx) { + cp->close(m_param); + return false; + } else { + + auto deviceCount = iio_context_get_devices_count(ctx); + for(int i = 0; i < deviceCount; i++) { + iio_device *dev = iio_context_get_device(ctx, i); + if(iio_device_find_debug_attr(dev, "direct_reg_access")) { + cp->close(m_param); + return true; + } + } + } + cp->close(m_param); + + return false; } void RegmapPlugin::initPreferences() { - Preferences *p = Preferences::GetInstance(); - p->init("regmap_color_by_value","Default"); - #if defined __APPLE__ - p->init("additional_regmap_xml_path",QCoreApplication::applicationDirPath() + "/plugins/plugins/xmls"); - #else - p->init("additional_regmap_xml_path",REGMAP_XML_PATH_LOCAL); - #endif + Preferences *p = Preferences::GetInstance(); + p->init("regmap_color_by_value", "Default"); +#if defined __APPLE__ + p->init("additional_regmap_xml_path", QCoreApplication::applicationDirPath() + "/plugins/plugins/xmls"); +#else + p->init("additional_regmap_xml_path", REGMAP_XML_PATH_LOCAL); +#endif } bool RegmapPlugin::loadPreferencesPage() { - Preferences *p = Preferences::GetInstance(); - - m_preferencesPage = new QWidget(); - QVBoxLayout *lay = new QVBoxLayout(m_preferencesPage); - - MenuSectionWidget *generalWidget = new MenuSectionWidget(m_preferencesPage); - MenuCollapseSection *generalSection = new MenuCollapseSection("General",MenuCollapseSection::MHCW_NONE, generalWidget); - generalWidget->contentLayout()->setSpacing(10); - generalWidget->contentLayout()->addWidget(generalSection); - generalSection->contentLayout()->setSpacing(10); - lay->setMargin(0); - lay->addWidget(generalWidget); - lay->addSpacerItem(new QSpacerItem(0,0,QSizePolicy::Minimum,QSizePolicy::Expanding)); - - generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCombo(p,"regmap_color_by_value","Use color to reflect value", - {"Default","Bitfield background","Bitfield text", - "Register background", "Register text", "Register background and Bitfield background", - "Register text and Bitfield text", "Register background and Bitfield text", - "Register text and Bitfield background"}, generalSection)); - return true; + Preferences *p = Preferences::GetInstance(); + + m_preferencesPage = new QWidget(); + QVBoxLayout *lay = new QVBoxLayout(m_preferencesPage); + + MenuSectionWidget *generalWidget = new MenuSectionWidget(m_preferencesPage); + MenuCollapseSection *generalSection = + new MenuCollapseSection("General", MenuCollapseSection::MHCW_NONE, generalWidget); + generalWidget->contentLayout()->setSpacing(10); + generalWidget->contentLayout()->addWidget(generalSection); + generalSection->contentLayout()->setSpacing(10); + lay->setMargin(0); + lay->addWidget(generalWidget); + lay->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); + + generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCombo( + p, "regmap_color_by_value", "Use color to reflect value", + {"Default", "Bitfield background", "Bitfield text", "Register background", "Register text", + "Register background and Bitfield background", "Register text and Bitfield text", + "Register background and Bitfield text", "Register text and Bitfield background"}, + generalSection)); + return true; } bool RegmapPlugin::onConnect() { - auto &&cp = ContextProvider::GetInstance(); - iio_context* ctx = cp->open(m_param); - - m_deviceList = new QList(); + auto &&cp = ContextProvider::GetInstance(); + iio_context *ctx = cp->open(m_param); - auto deviceCount = iio_context_get_devices_count(ctx); + m_deviceList = new QList(); + auto deviceCount = iio_context_get_devices_count(ctx); - for (int i = 0; i < deviceCount; i++) { - iio_device *dev = iio_context_get_device(ctx, i); - if (iio_device_find_debug_attr(dev,"direct_reg_access")) { - qDebug(CAT_REGMAP)<<"DEVICE FOUND " << iio_device_get_name(dev); - m_deviceList->push_back(dev); - } - } - m_registerMapWidget = new QWidget(); - QVBoxLayout *layout = new QVBoxLayout(m_registerMapWidget); - m_registerMapWidget->setLayout(layout); + for(int i = 0; i < deviceCount; i++) { + iio_device *dev = iio_context_get_device(ctx, i); + if(iio_device_find_debug_attr(dev, "direct_reg_access")) { + qDebug(CAT_REGMAP) << "DEVICE FOUND " << iio_device_get_name(dev); + m_deviceList->push_back(dev); + } + } + m_registerMapWidget = new QWidget(); + QVBoxLayout *layout = new QVBoxLayout(m_registerMapWidget); + m_registerMapWidget->setLayout(layout); - scopy::regmap::Utils::applyJsonConfig(); + scopy::regmap::Utils::applyJsonConfig(); - if (m_deviceList && !m_deviceList->isEmpty()) { - QDir xmlsPath = scopy::regmap::Utils::setXmlPath(); - scopy::regmap::RegisterMapInstrument *regMapInstrument = new scopy::regmap::RegisterMapInstrument(); + if(m_deviceList && !m_deviceList->isEmpty()) { + QDir xmlsPath = scopy::regmap::Utils::setXmlPath(); + scopy::regmap::RegisterMapInstrument *regMapInstrument = new scopy::regmap::RegisterMapInstrument(); - layout->addWidget(regMapInstrument); + layout->addWidget(regMapInstrument); - for (int i = 0; i < m_deviceList->size(); ++i) { - iio_device *dev = m_deviceList->at(i); - QString devName = QString::fromStdString(iio_device_get_name(dev)); - qDebug(CAT_REGMAP)<<"CONNECTING TO DEVICE : " << devName; - QString templatePaths = scopy::regmap::Utils::getTemplate(devName); - qDebug(CAT_REGMAP)<<"templatePaths :" << templatePaths ; - if (!templatePaths.isEmpty()) { - qDebug(CAT_REGMAP)<<"TEMPLATE FORUND FOR DEVICE : " << devName; - regMapInstrument->addTab( dev, devName, xmlsPath.absoluteFilePath(templatePaths)); - } else { - regMapInstrument->addTab(dev, iio_device_get_name(dev)); - } + for(int i = 0; i < m_deviceList->size(); ++i) { + iio_device *dev = m_deviceList->at(i); + QString devName = QString::fromStdString(iio_device_get_name(dev)); + qDebug(CAT_REGMAP) << "CONNECTING TO DEVICE : " << devName; + QString templatePaths = scopy::regmap::Utils::getTemplate(devName); + qDebug(CAT_REGMAP) << "templatePaths :" << templatePaths; + if(!templatePaths.isEmpty()) { + qDebug(CAT_REGMAP) << "TEMPLATE FORUND FOR DEVICE : " << devName; + regMapInstrument->addTab(dev, devName, xmlsPath.absoluteFilePath(templatePaths)); + } else { + regMapInstrument->addTab(dev, iio_device_get_name(dev)); + } - qDebug(CAT_REGMAP) << ""; - } + qDebug(CAT_REGMAP) << ""; + } - m_toolList[0]->setEnabled(true); - m_toolList[0]->setTool(m_registerMapWidget); + m_toolList[0]->setEnabled(true); + m_toolList[0]->setTool(m_registerMapWidget); - Preferences *p = Preferences::GetInstance(); - QObject::connect(p, &Preferences::preferenceChanged, this, &RegmapPlugin::handlePreferenceChange); + Preferences *p = Preferences::GetInstance(); + QObject::connect(p, &Preferences::preferenceChanged, this, &RegmapPlugin::handlePreferenceChange); - return true; - } + return true; + } - return false; + return false; } bool RegmapPlugin::onDisconnect() { - //TODO - auto &&cp = ContextProvider::GetInstance(); - cp->close(m_param); + // TODO + auto &&cp = ContextProvider::GetInstance(); + cp->close(m_param); - if (m_registerMapWidget) delete m_registerMapWidget; - if (m_deviceList) delete m_deviceList; + if(m_registerMapWidget) + delete m_registerMapWidget; + if(m_deviceList) + delete m_deviceList; - return true; + return true; } void RegmapPlugin::initMetadata() { - loadMetadata( - R"plugin( + loadMetadata( + R"plugin( { "priority":3, "category":[ @@ -199,47 +205,41 @@ void RegmapPlugin::initMetadata() )plugin"); } -QString RegmapPlugin::description() -{ - return "Register map tool"; -} +QString RegmapPlugin::description() { return "Register map tool"; } -QWidget *RegmapPlugin::getTool() -{ - return m_registerMapWidget; -} +QWidget *RegmapPlugin::getTool() { return m_registerMapWidget; } +struct iio_device *RegmapPlugin::getIioDevice(iio_context *ctx, const char *dev_name) +{ + auto deviceCount = iio_context_get_devices_count(ctx); -struct iio_device* RegmapPlugin::getIioDevice(iio_context* ctx, const char *dev_name){ - auto deviceCount = iio_context_get_devices_count(ctx); - - for (int i = 0; i < deviceCount; i++) { - iio_device *dev = iio_context_get_device(ctx, i); - if (strcasecmp(iio_device_get_name(dev), dev_name) == 0) { - return dev; - } - } - return nullptr; + for(int i = 0; i < deviceCount; i++) { + iio_device *dev = iio_context_get_device(ctx, i); + if(strcasecmp(iio_device_get_name(dev), dev_name) == 0) { + return dev; + } + } + return nullptr; } bool RegmapPlugin::isBufferCapable(iio_device *dev) { - unsigned int i; + unsigned int i; - for (i = 0; i < iio_device_get_channels_count(dev); i++) { - struct iio_channel *chn = iio_device_get_channel(dev, i); + for(i = 0; i < iio_device_get_channels_count(dev); i++) { + struct iio_channel *chn = iio_device_get_channel(dev, i); - if (iio_channel_is_scan_element(chn)){ - return true; - } - } + if(iio_channel_is_scan_element(chn)) { + return true; + } + } - return false; + return false; } -void RegmapPlugin::handlePreferenceChange(QString id , QVariant val) +void RegmapPlugin::handlePreferenceChange(QString id, QVariant val) { - if (id == "regmap_background_color_by_value") { - // TODO set backround color by value - } + if(id == "regmap_background_color_by_value") { + // TODO set backround color by value + } } diff --git a/plugins/regmap/src/regmapstylehelper.cpp b/plugins/regmap/src/regmapstylehelper.cpp index c6ad39adbc..4202964570 100644 --- a/plugins/regmap/src/regmapstylehelper.cpp +++ b/plugins/regmap/src/regmapstylehelper.cpp @@ -1,67 +1,65 @@ #include "regmapstylehelper.hpp" -#include + #include "dynamicWidget.h" + +#include #include using namespace scopy::regmap; -RegmapStyleHelper* RegmapStyleHelper::pinstance_{nullptr}; +RegmapStyleHelper *RegmapStyleHelper::pinstance_{nullptr}; -RegmapStyleHelper::RegmapStyleHelper(QObject *parent) -{ - -} +RegmapStyleHelper::RegmapStyleHelper(QObject *parent) {} RegmapStyleHelper *RegmapStyleHelper::GetInstance() { - if (pinstance_ == nullptr) - { - pinstance_ = new RegmapStyleHelper(QApplication::instance()); // singleton has the app as parent - RegmapStyleHelper::initColorMap(); - } - return pinstance_; + if(pinstance_ == nullptr) { + pinstance_ = new RegmapStyleHelper(QApplication::instance()); // singleton has the app as parent + RegmapStyleHelper::initColorMap(); + } + return pinstance_; } -void RegmapStyleHelper::initColorMap() { - auto sh = RegmapStyleHelper::GetInstance(); - sh->colorMap.insert("ScopyBlue", "#4A64FF"); - sh->colorMap.insert("UIElementBackground", "#272730"); - sh->colorMap.insert("LabelText", "#FFFFFF"); - sh->colorMap.insert("LabelText2", "rgba(255, 255, 255, 150)"); - sh->colorMap.insert("ScopyBackground", "#141416"); - sh->colorMap.insert("WidgetBackground", "#272730"); - sh->colorMap.insert("ButtonPressed", "#2a44df"); - sh->colorMap.insert("ButtonHover", "#4a34ff"); - sh->colorMap.insert("ButtonDisabled", "grey"); - sh->colorMap.insert("Red", "red"); - sh->colorMap.insert("Transparent", "transparent"); - sh->colorMap.insert("CheckBoxTextColor", "rgba(255, 255, 255, 153)"); - sh->colorMap.insert("CheckBoxIndicatorBorderColor", "rgb(74,100,255)"); - sh->colorMap.insert("ScopyOrange", "#FF7200"); - - +void RegmapStyleHelper::initColorMap() +{ + auto sh = RegmapStyleHelper::GetInstance(); + sh->colorMap.insert("ScopyBlue", "#4A64FF"); + sh->colorMap.insert("UIElementBackground", "#272730"); + sh->colorMap.insert("LabelText", "#FFFFFF"); + sh->colorMap.insert("LabelText2", "rgba(255, 255, 255, 150)"); + sh->colorMap.insert("ScopyBackground", "#141416"); + sh->colorMap.insert("WidgetBackground", "#272730"); + sh->colorMap.insert("ButtonPressed", "#2a44df"); + sh->colorMap.insert("ButtonHover", "#4a34ff"); + sh->colorMap.insert("ButtonDisabled", "grey"); + sh->colorMap.insert("Red", "red"); + sh->colorMap.insert("Transparent", "transparent"); + sh->colorMap.insert("CheckBoxTextColor", "rgba(255, 255, 255, 153)"); + sh->colorMap.insert("CheckBoxIndicatorBorderColor", "rgb(74,100,255)"); + sh->colorMap.insert("ScopyOrange", "#FF7200"); } -QString RegmapStyleHelper::getColor(QString id) { - auto sh = RegmapStyleHelper::GetInstance(); - return sh->colorMap[id]; +QString RegmapStyleHelper::getColor(QString id) +{ + auto sh = RegmapStyleHelper::GetInstance(); + return sh->colorMap[id]; } void RegmapStyleHelper::PartialFrameWidget(QWidget *widget) { - QString style = QString(R"css( + QString style = QString(R"css( .QWidget { border-top: 2px solid black; border-right: 2px solid black; border-left: 2px solid black; } )css"); - widget->setStyleSheet(style); + widget->setStyleSheet(style); } void RegmapStyleHelper::FrameWidget(QWidget *widget) { - QString style = QString(R"css( + QString style = QString(R"css( .QWidget { border-top: 2px solid black; border-right: 2px solid black; @@ -70,13 +68,13 @@ void RegmapStyleHelper::FrameWidget(QWidget *widget) background-color: &&background&& ; } )css"); - style.replace("&&background&&", RegmapStyleHelper::getColor("WidgetBackground")); - widget->setStyleSheet(style); + style.replace("&&background&&", RegmapStyleHelper::getColor("WidgetBackground")); + widget->setStyleSheet(style); } void RegmapStyleHelper::SettingsMenu(QWidget *widget) { - QString style = QString(R"css( + QString style = QString(R"css( .QWidget { background-color: &&background&& ; } @@ -87,44 +85,46 @@ void RegmapStyleHelper::SettingsMenu(QWidget *widget) } )css"); - style.replace("&&background&&", RegmapStyleHelper::getColor("ScopyBackground")); - style.replace("&&textColor&&", RegmapStyleHelper::getColor("LabelText")); + style.replace("&&background&&", RegmapStyleHelper::getColor("ScopyBackground")); + style.replace("&&textColor&&", RegmapStyleHelper::getColor("LabelText")); - widget->setStyleSheet(style); + widget->setStyleSheet(style); } void RegmapStyleHelper::RegisterMapStyle(QWidget *widget) { - QString style = QString(R"css( + QString style = QString(R"css( .QWidget { background-color: &&widgetBackground&& ; } )css"); - style.replace("&&widgetBackground&&", RegmapStyleHelper::getColor("ScopyBackground")); - style += RegmapStyleHelper::BlueButton(nullptr); - widget->setStyleSheet(style); + style.replace("&&widgetBackground&&", RegmapStyleHelper::getColor("ScopyBackground")); + style += RegmapStyleHelper::BlueButton(nullptr); + widget->setStyleSheet(style); } void RegmapStyleHelper::bigTextLabelStyle(QLabel *label, QString objectName) { - if (!objectName.isEmpty()) label->setObjectName(objectName); + if(!objectName.isEmpty()) + label->setObjectName(objectName); - QString style = QString(R"css( + QString style = QString(R"css( QLabel { font: normal; font-size: 16px; color: &&labelColor&& ; } )css"); - style.replace("&&labelColor&&", RegmapStyleHelper::getColor("LabelText")); - label->setStyleSheet(style); + style.replace("&&labelColor&&", RegmapStyleHelper::getColor("LabelText")); + label->setStyleSheet(style); } QString RegmapStyleHelper::BlueButton(QPushButton *btn, QString objectName) { - if (!objectName.isEmpty()) btn->setObjectName(objectName); + if(!objectName.isEmpty()) + btn->setObjectName(objectName); - QString style = QString(R"css( + QString style = QString(R"css( QPushButton { background-color: &&buttonBackground&& ; border-radius: 4px; @@ -140,23 +140,24 @@ QString RegmapStyleHelper::BlueButton(QPushButton *btn, QString objectName) )css"); - style.replace("&&buttonBackground&&", RegmapStyleHelper::getColor("ScopyBlue")); - style.replace("&&pressedColor&&", RegmapStyleHelper::getColor("ButtonPressed")); - style.replace("&&hoverColor&&", RegmapStyleHelper::getColor("ButtonHover")); - style.replace("&&diabledColor&&", RegmapStyleHelper::getColor("ButtonDisabled")); + style.replace("&&buttonBackground&&", RegmapStyleHelper::getColor("ScopyBlue")); + style.replace("&&pressedColor&&", RegmapStyleHelper::getColor("ButtonPressed")); + style.replace("&&hoverColor&&", RegmapStyleHelper::getColor("ButtonHover")); + style.replace("&&diabledColor&&", RegmapStyleHelper::getColor("ButtonDisabled")); - if (btn) { - btn->setStyleSheet(style); - } + if(btn) { + btn->setStyleSheet(style); + } - return style; + return style; } QString RegmapStyleHelper::checkboxStyle(QCheckBox *checkbox, QString objectName) { - if (!objectName.isEmpty()) checkbox->setObjectName(objectName); + if(!objectName.isEmpty()) + checkbox->setObjectName(objectName); - QString style = QString(R"css( + QString style = QString(R"css( QCheckBox { spacing: 8px; background-color: &&checkBoxBackgroundColor&& ; @@ -175,22 +176,23 @@ QString RegmapStyleHelper::checkboxStyle(QCheckBox *checkbox, QString objectName QCheckBox::indicator:checked { background-color: rgb(74,100,255); } )css"); - style.replace("&&checkBoxIndicatorUnchecked&&", RegmapStyleHelper::getColor("Transparent")); - style.replace("&&checkBoxBackgroundColor&&", RegmapStyleHelper::getColor("Transparent")); - style.replace("&&checkBoxColor&&", RegmapStyleHelper::getColor("CheckBoxTextColor")); - style.replace("&&checkBoxIndicatorBorderColor&&", RegmapStyleHelper::getColor("CheckBoxIndicatorBorderColor")); + style.replace("&&checkBoxIndicatorUnchecked&&", RegmapStyleHelper::getColor("Transparent")); + style.replace("&&checkBoxBackgroundColor&&", RegmapStyleHelper::getColor("Transparent")); + style.replace("&&checkBoxColor&&", RegmapStyleHelper::getColor("CheckBoxTextColor")); + style.replace("&&checkBoxIndicatorBorderColor&&", RegmapStyleHelper::getColor("CheckBoxIndicatorBorderColor")); - if (checkbox) { - checkbox->setStyleSheet(style); - } - return style; + if(checkbox) { + checkbox->setStyleSheet(style); + } + return style; } void RegmapStyleHelper::labelStyle(QLabel *label, QString objectName) { - if (!objectName.isEmpty()) label->setObjectName(objectName); + if(!objectName.isEmpty()) + label->setObjectName(objectName); - QString style = QString(R"css( + QString style = QString(R"css( QLabel { font-size: 13px; font-style: normal; @@ -199,15 +201,16 @@ void RegmapStyleHelper::labelStyle(QLabel *label, QString objectName) color: &&labelColor&& ; } )css"); - style.replace("&&labelColor&&", RegmapStyleHelper::getColor("LabelText2")); - label->setStyleSheet(style); + style.replace("&&labelColor&&", RegmapStyleHelper::getColor("LabelText2")); + label->setStyleSheet(style); } QString RegmapStyleHelper::grayBackgroundHoverWidget(QWidget *widget, QString objectName) { - if (!objectName.isEmpty() && widget) widget->setObjectName(objectName); + if(!objectName.isEmpty() && widget) + widget->setObjectName(objectName); - QString style = QString(R"css( + QString style = QString(R"css( .QFrame { background-color: &&frameBackground&& ; @@ -230,22 +233,23 @@ QString RegmapStyleHelper::grayBackgroundHoverWidget(QWidget *widget, QString ob )css"); - style.replace("&&frameBackground&&", RegmapStyleHelper::getColor("WidgetBackground")); - style.replace("&&childWidgetBackground&&", RegmapStyleHelper::getColor("Transparent")); - style.replace("&&hoverBackground&&", RegmapStyleHelper::getColor("ButtonHover")); - style.replace("&&selectedBackground&&", RegmapStyleHelper::getColor("ScopyBlue")); + style.replace("&&frameBackground&&", RegmapStyleHelper::getColor("WidgetBackground")); + style.replace("&&childWidgetBackground&&", RegmapStyleHelper::getColor("Transparent")); + style.replace("&&hoverBackground&&", RegmapStyleHelper::getColor("ButtonHover")); + style.replace("&&selectedBackground&&", RegmapStyleHelper::getColor("ScopyBlue")); - if (widget) { - widget->setStyleSheet(style); - } - return style; + if(widget) { + widget->setStyleSheet(style); + } + return style; } QString RegmapStyleHelper::detailedBitFieldStyle(BitFieldDetailedWidget *widget, QString objectName) { - if (!objectName.isEmpty()) widget->setObjectName(objectName); + if(!objectName.isEmpty()) + widget->setObjectName(objectName); - QString style = QString(R"css( + QString style = QString(R"css( .QFrame { background-color: &&frameBackground&& ; @@ -257,26 +261,27 @@ QString RegmapStyleHelper::detailedBitFieldStyle(BitFieldDetailedWidget *widget, )css"); - style.replace("&&frameBackground&&", RegmapStyleHelper::getColor("WidgetBackground")); - style.replace("&&childWidgetBackground&&", RegmapStyleHelper::getColor("Transparent")); + style.replace("&&frameBackground&&", RegmapStyleHelper::getColor("WidgetBackground")); + style.replace("&&childWidgetBackground&&", RegmapStyleHelper::getColor("Transparent")); - widget->setMinimumWidth(10); - widget->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred); + widget->setMinimumWidth(10); + widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - widget->nameLabel->setStyleSheet(whiteSmallTextLable(nullptr)); - if (widget->valueCheckBox) { - widget->valueCheckBox->setStyleSheet(checkboxStyle(nullptr)); - } - widget->setFixedHeight(120); + widget->nameLabel->setStyleSheet(whiteSmallTextLable(nullptr)); + if(widget->valueCheckBox) { + widget->valueCheckBox->setStyleSheet(checkboxStyle(nullptr)); + } + widget->setFixedHeight(120); - return style; + return style; } QString RegmapStyleHelper::simpleRegisterStyle(RegisterSimpleWidget *widget, QString objectName) { - if (!objectName.isEmpty()) widget->setObjectName(objectName); + if(!objectName.isEmpty()) + widget->setObjectName(objectName); - QString style = QString(R"css( + QString style = QString(R"css( .QFrame { background-color: &&frameBackground&& ; @@ -292,22 +297,23 @@ QString RegmapStyleHelper::simpleRegisterStyle(RegisterSimpleWidget *widget, QSt } )css"); - style.replace("&&frameBackground&&", RegmapStyleHelper::getColor("WidgetBackground")); - style.replace("&&childWidgetBackground&&", RegmapStyleHelper::getColor("Transparent")); - style.replace("&&hoverBackground&&", RegmapStyleHelper::getColor("ButtonHover")); - style.replace("&&selectedBackground&&", RegmapStyleHelper::getColor("ScopyBlue")); - widget->setStyleSheet(style); - widget->regBaseInfoWidget->setStyleSheet(grayBackgroundHoverWidget(nullptr)); - widget->registerNameLabel->setStyleSheet(whiteSmallTextLable(nullptr)); + style.replace("&&frameBackground&&", RegmapStyleHelper::getColor("WidgetBackground")); + style.replace("&&childWidgetBackground&&", RegmapStyleHelper::getColor("Transparent")); + style.replace("&&hoverBackground&&", RegmapStyleHelper::getColor("ButtonHover")); + style.replace("&&selectedBackground&&", RegmapStyleHelper::getColor("ScopyBlue")); + widget->setStyleSheet(style); + widget->regBaseInfoWidget->setStyleSheet(grayBackgroundHoverWidget(nullptr)); + widget->registerNameLabel->setStyleSheet(whiteSmallTextLable(nullptr)); - return style; + return style; } QString RegmapStyleHelper::valueLabel(QLabel *label, QString objectName) { - if (!objectName.isEmpty()) label->setObjectName(objectName); + if(!objectName.isEmpty()) + label->setObjectName(objectName); - QString style = QString(R"css( + QString style = QString(R"css( *[value_label=true] { font-size: 12px; @@ -318,16 +324,17 @@ QString RegmapStyleHelper::valueLabel(QLabel *label, QString objectName) } )css"); - style.replace("&&labelColor&&", RegmapStyleHelper::getColor("ScopyOrange")); + style.replace("&&labelColor&&", RegmapStyleHelper::getColor("ScopyOrange")); - return style; + return style; } QString RegmapStyleHelper::grayLabel(QLabel *label, QString objectName) { - if (!objectName.isEmpty()) label->setObjectName(objectName); + if(!objectName.isEmpty()) + label->setObjectName(objectName); - QString style = QString(R"css( + QString style = QString(R"css( QLabel { font-size: 12px; font-style: normal; @@ -336,38 +343,40 @@ QString RegmapStyleHelper::grayLabel(QLabel *label, QString objectName) color: &&labelColor&& ; } )css"); - style.replace("&&labelColor&&", RegmapStyleHelper::getColor("LabelText2")); + style.replace("&&labelColor&&", RegmapStyleHelper::getColor("LabelText2")); - return style; + return style; } QString RegmapStyleHelper::whiteSmallTextLable(QLabel *label, QString objectName) { - if (!objectName.isEmpty()) label->setObjectName(objectName); + if(!objectName.isEmpty()) + label->setObjectName(objectName); - QString style = QString(R"css( + QString style = QString(R"css( QLabel { font: normal; font-size: 12px; color: &&labelColor&& ; } )css"); - style.replace("&&labelColor&&", RegmapStyleHelper::getColor("LabelText")); + style.replace("&&labelColor&&", RegmapStyleHelper::getColor("LabelText")); - return style; + return style; } QString RegmapStyleHelper::frameBorderHover(QFrame *frame, QString objectName) { - if (!objectName.isEmpty() && frame) frame->setObjectName(objectName); + if(!objectName.isEmpty() && frame) + frame->setObjectName(objectName); - QString style = QString(R"css( + QString style = QString(R"css( .scopy--regmap--RegisterSimpleWidget:hover { border: 1px solid &&hoverBackground&& ; border-radius: 4px; } )css"); - style.replace("&&hoverBackground&&", RegmapStyleHelper::getColor("LabelText")); + style.replace("&&hoverBackground&&", RegmapStyleHelper::getColor("LabelText")); - return style; + return style; } diff --git a/plugins/regmap/src/regmapstylehelper.hpp b/plugins/regmap/src/regmapstylehelper.hpp index b26452da0a..a686147703 100644 --- a/plugins/regmap/src/regmapstylehelper.hpp +++ b/plugins/regmap/src/regmapstylehelper.hpp @@ -8,50 +8,45 @@ #include #include - #include - - - - namespace scopy::regmap { class RegmapStyleHelper { protected: - RegmapStyleHelper(QObject *parent = nullptr); - ~RegmapStyleHelper(); + RegmapStyleHelper(QObject *parent = nullptr); + ~RegmapStyleHelper(); public: - // singleton - RegmapStyleHelper(RegmapStyleHelper &other) = delete; - void operator=(const RegmapStyleHelper &) = delete; - static RegmapStyleHelper *GetInstance(); - - static void initColorMap(); - static QString getColor(QString id); - - static void RegisterMapStyle(QWidget *widget); - static void PartialFrameWidget(QWidget *widget); - static void FrameWidget(QWidget *widget); - static void SettingsMenu(QWidget *widget); - static void bigTextLabelStyle(QLabel *label, QString objectName); - static void labelStyle(QLabel *label, QString objectName); - - static QString grayBackgroundHoverWidget(QWidget *widget, QString objectName = ""); - static QString BlueButton(QPushButton *btn, QString objectName = ""); - static QString checkboxStyle(QCheckBox *checkbox, QString objectName = ""); - static QString detailedBitFieldStyle(BitFieldDetailedWidget *widget, QString objectName); - static QString simpleRegisterStyle(RegisterSimpleWidget *widget, QString objectName); - static QString valueLabel(QLabel *label,QString objectName = ""); - static QString grayLabel(QLabel *label, QString objectName = ""); - static QString whiteSmallTextLable(QLabel *label, QString objectName = ""); - static QString frameBorderHover(QFrame *frame, QString objectName = ""); + // singleton + RegmapStyleHelper(RegmapStyleHelper &other) = delete; + void operator=(const RegmapStyleHelper &) = delete; + static RegmapStyleHelper *GetInstance(); + + static void initColorMap(); + static QString getColor(QString id); + + static void RegisterMapStyle(QWidget *widget); + static void PartialFrameWidget(QWidget *widget); + static void FrameWidget(QWidget *widget); + static void SettingsMenu(QWidget *widget); + static void bigTextLabelStyle(QLabel *label, QString objectName); + static void labelStyle(QLabel *label, QString objectName); + + static QString grayBackgroundHoverWidget(QWidget *widget, QString objectName = ""); + static QString BlueButton(QPushButton *btn, QString objectName = ""); + static QString checkboxStyle(QCheckBox *checkbox, QString objectName = ""); + static QString detailedBitFieldStyle(BitFieldDetailedWidget *widget, QString objectName); + static QString simpleRegisterStyle(RegisterSimpleWidget *widget, QString objectName); + static QString valueLabel(QLabel *label, QString objectName = ""); + static QString grayLabel(QLabel *label, QString objectName = ""); + static QString whiteSmallTextLable(QLabel *label, QString objectName = ""); + static QString frameBorderHover(QFrame *frame, QString objectName = ""); private: - QMap colorMap; - static RegmapStyleHelper * pinstance_; + QMap colorMap; + static RegmapStyleHelper *pinstance_; }; -} +} // namespace scopy::regmap #endif // REGMAPSTYLEHELPER_HPP diff --git a/plugins/regmap/src/regreadwrite.cpp b/plugins/regmap/src/regreadwrite.cpp index e41fa349d7..9807487115 100644 --- a/plugins/regmap/src/regreadwrite.cpp +++ b/plugins/regmap/src/regreadwrite.cpp @@ -1,41 +1,43 @@ #include "regreadwrite.hpp" -#include -#include + #include "logging_categories.h" +#include +#include + using namespace scopy; using namespace regmap; RegReadWrite::RegReadWrite(struct iio_device *dev, QObject *parent) - : dev(dev), - QObject{parent} + : dev(dev) + , QObject{parent} {} -RegReadWrite::~RegReadWrite() -{} +RegReadWrite::~RegReadWrite() {} void RegReadWrite::read(uint32_t address) { uint32_t reg_val; ssize_t read = iio_device_reg_read(dev, address, ®_val); - if (read < 0) { + if(read < 0) { qDebug(CAT_IIO_OPERATION) << "device read error " << read; Q_EMIT readError("device read error"); } else { - qDebug(CAT_IIO_OPERATION) << "device read success for " << address << " with value " < -#include #include "scopy-regmapplugin_export.h" +#include + +#include + // TODO set the right buf size #define BUF_SIZE 16384 -namespace scopy::regmap{ +namespace scopy::regmap { class SCOPY_REGMAPPLUGIN_EXPORT RegReadWrite : public QObject { Q_OBJECT public: - explicit RegReadWrite( struct iio_device *dev, QObject *parent = nullptr); + explicit RegReadWrite(struct iio_device *dev, QObject *parent = nullptr); ~RegReadWrite(); @@ -30,5 +32,5 @@ class SCOPY_REGMAPPLUGIN_EXPORT RegReadWrite : public QObject private: struct iio_device *dev; }; -} +} // namespace scopy::regmap #endif // REGREADWRITE_HPP diff --git a/plugins/regmap/src/search.cpp b/plugins/regmap/src/search.cpp index c8fe3f921a..8ba5e8ad29 100644 --- a/plugins/regmap/src/search.cpp +++ b/plugins/regmap/src/search.cpp @@ -1,32 +1,33 @@ #include "search.hpp" -#include "register/registermodel.hpp" #include "register/bitfield/bitfieldmodel.hpp" +#include "register/registermodel.hpp" using namespace scopy; using namespace regmap; Search::Search(QObject *parent) : QObject{parent} -{ -} +{} QList Search::searchForRegisters(QMap *registers, QString searchParam) { - if (searchParam.isEmpty()) { + if(searchParam.isEmpty()) { return registers->keys(); } QList result; - QMap::iterator mapIterator; - for (mapIterator = registers->begin(); mapIterator != registers->end(); ++mapIterator) { - QString address = QString::number(mapIterator.key(),16); - if (address.contains(searchParam) || mapIterator.value()->getName().contains(searchParam) ){ + QMap::iterator mapIterator; + for(mapIterator = registers->begin(); mapIterator != registers->end(); ++mapIterator) { + QString address = QString::number(mapIterator.key(), 16); + if(address.contains(searchParam) || mapIterator.value()->getName().contains(searchParam)) { result.push_back(mapIterator.key()); } else { - for (int i = 0 ; i < mapIterator.value()->getBitFields()->size(); ++i){ - if (mapIterator.value()->getBitFields()->at(i)->getName().toLower().contains(searchParam) || - mapIterator.value()->getBitFields()->at(i)->getDescription().toLower().contains(searchParam) ) { + for(int i = 0; i < mapIterator.value()->getBitFields()->size(); ++i) { + if(mapIterator.value()->getBitFields()->at(i)->getName().toLower().contains( + searchParam) || + mapIterator.value()->getBitFields()->at(i)->getDescription().toLower().contains( + searchParam)) { result.push_back(mapIterator.key()); break; diff --git a/plugins/regmap/src/search.hpp b/plugins/regmap/src/search.hpp index ab113e679d..e6d26d603d 100644 --- a/plugins/regmap/src/search.hpp +++ b/plugins/regmap/src/search.hpp @@ -1,10 +1,11 @@ #ifndef SEARCH_HPP #define SEARCH_HPP -#include #include "scopy-regmapplugin_export.h" -namespace scopy::regmap{ +#include + +namespace scopy::regmap { class RegisterModel; class SCOPY_REGMAPPLUGIN_EXPORT Search : public QObject { @@ -12,9 +13,8 @@ class SCOPY_REGMAPPLUGIN_EXPORT Search : public QObject public: explicit Search(QObject *parent = nullptr); - static QList searchForRegisters(QMap *registers, QString searchParam); + static QList searchForRegisters(QMap *registers, QString searchParam); Q_SIGNALS: - }; -} +} // namespace scopy::regmap #endif // SEARCH_HPP diff --git a/plugins/regmap/src/searchbarwidget.cpp b/plugins/regmap/src/searchbarwidget.cpp index 42e0815e19..5f8863382b 100644 --- a/plugins/regmap/src/searchbarwidget.cpp +++ b/plugins/regmap/src/searchbarwidget.cpp @@ -1,9 +1,10 @@ #include "searchbarwidget.hpp" +#include "regmapstylehelper.hpp" + #include #include #include -#include "regmapstylehelper.hpp" using namespace scopy; using namespace regmap; @@ -11,32 +12,26 @@ using namespace regmap; SearchBarWidget::SearchBarWidget(QWidget *parent) : QWidget{parent} { - layout = new QHBoxLayout(); - setLayout(layout); + layout = new QHBoxLayout(); + setLayout(layout); searchBar = new QLineEdit(); searchBar->setPlaceholderText("Search for regist by address"); - searchButton = new QPushButton("Search"); - + searchButton = new QPushButton("Search"); - QObject::connect(searchButton, &QPushButton::pressed, this, [=](){ - Q_EMIT requestSearch(searchBar->text().toLower()); - }); - layout->addWidget(searchBar,4); - layout->addWidget(searchButton,1); + QObject::connect(searchButton, &QPushButton::pressed, this, + [=]() { Q_EMIT requestSearch(searchBar->text().toLower()); }); + layout->addWidget(searchBar, 4); + layout->addWidget(searchButton, 1); - - applyStyle(); + applyStyle(); } SearchBarWidget::~SearchBarWidget() { delete layout; - delete searchBar; - delete searchButton; + delete searchBar; + delete searchButton; } -void SearchBarWidget::applyStyle() -{ - RegmapStyleHelper::BlueButton(searchButton, ""); -} +void SearchBarWidget::applyStyle() { RegmapStyleHelper::BlueButton(searchButton, ""); } diff --git a/plugins/regmap/src/searchbarwidget.hpp b/plugins/regmap/src/searchbarwidget.hpp index 398ce4d182..003ced8c3c 100644 --- a/plugins/regmap/src/searchbarwidget.hpp +++ b/plugins/regmap/src/searchbarwidget.hpp @@ -1,14 +1,15 @@ #ifndef SEARCHBARWIDGET_HPP #define SEARCHBARWIDGET_HPP -#include #include "scopy-regmapplugin_export.h" +#include + class QHBoxLayout; class QPushButton; class QLineEdit; -namespace scopy::regmap{ -class SCOPY_REGMAPPLUGIN_EXPORT SearchBarWidget : public QWidget +namespace scopy::regmap { +class SCOPY_REGMAPPLUGIN_EXPORT SearchBarWidget : public QWidget { Q_OBJECT public: @@ -17,11 +18,12 @@ class SCOPY_REGMAPPLUGIN_EXPORT SearchBarWidget : public QWidget Q_SIGNALS: void requestSearch(QString searchParam); + private: QLineEdit *searchBar; QPushButton *searchButton; QHBoxLayout *layout; - void applyStyle(); + void applyStyle(); }; -} +} // namespace scopy::regmap #endif // SEARCHBARWIDGET_HPP diff --git a/plugins/regmap/src/tabinfo.cpp b/plugins/regmap/src/tabinfo.cpp index b473a9588c..3d3a718f4b 100644 --- a/plugins/regmap/src/tabinfo.cpp +++ b/plugins/regmap/src/tabinfo.cpp @@ -1,26 +1,14 @@ #include "tabinfo.hpp" - TabInfo::TabInfo(iio_device *dev, QString deviceName, QString xmlPath, QObject *parent) -: QObject{parent}, - dev(dev), - deviceName(deviceName), - xmlPath(xmlPath) -{ - -} + : QObject{parent} + , dev(dev) + , deviceName(deviceName) + , xmlPath(xmlPath) +{} -iio_device *TabInfo::getDev() const -{ - return dev; -} +iio_device *TabInfo::getDev() const { return dev; } -QString TabInfo::getDeviceName() const -{ - return deviceName; -} +QString TabInfo::getDeviceName() const { return deviceName; } -QString TabInfo::getXmlPath() const -{ - return xmlPath; -} +QString TabInfo::getXmlPath() const { return xmlPath; } diff --git a/plugins/regmap/src/tabinfo.hpp b/plugins/regmap/src/tabinfo.hpp index 35ebf7c931..d3bbe8c4a1 100644 --- a/plugins/regmap/src/tabinfo.hpp +++ b/plugins/regmap/src/tabinfo.hpp @@ -1,28 +1,29 @@ #ifndef TABINFO_HPP #define TABINFO_HPP +#include + #include #include -#include class TabInfo : public QObject { - Q_OBJECT + Q_OBJECT public: - explicit TabInfo(struct iio_device *dev, QString deviceName, QString xmlPath,QObject *parent = nullptr); + explicit TabInfo(struct iio_device *dev, QString deviceName, QString xmlPath, QObject *parent = nullptr); - iio_device *getDev() const; + iio_device *getDev() const; - QString getDeviceName() const; + QString getDeviceName() const; - QString getXmlPath() const; + QString getXmlPath() const; signals: private: - struct iio_device *dev; - QString deviceName; - QString xmlPath; + struct iio_device *dev; + QString deviceName; + QString xmlPath; }; #endif // TABINFO_HPP diff --git a/plugins/regmap/src/utils.cpp b/plugins/regmap/src/utils.cpp index d66b785d32..9774aa5236 100644 --- a/plugins/regmap/src/utils.cpp +++ b/plugins/regmap/src/utils.cpp @@ -1,169 +1,166 @@ #include "utils.hpp" -#include "scopy-regmapplugin_config.h" + #include "jsonformatedelement.hpp" -#include +#include "logging_categories.h" +#include "scopy-regmapplugin_config.h" #include +#include +#include #include #include #include -#include -#include -#include "logging_categories.h" +#include using namespace scopy::regmap; -QMap* Utils::spiJson {new QMap()}; -QMap* Utils::axiJson {new QMap()}; +QMap *Utils::spiJson{new QMap()}; +QMap *Utils::axiJson{new QMap()}; Utils::Utils(QObject *parent) - : QObject{parent} -{ -} + : QObject{parent} +{} QString Utils::convertToHexa(uint32_t value, int size) { - return QStringLiteral("0x%1").arg(value, (size / getBitsPerRow()) + 1, 16, QLatin1Char('0')); + return QStringLiteral("0x%1").arg(value, (size / getBitsPerRow()) + 1, 16, QLatin1Char('0')); } void Utils::removeLayoutMargins(QLayout *layout) { - layout->setMargin(0); - layout->setContentsMargins(0,0,0,0); + layout->setMargin(0); + layout->setContentsMargins(0, 0, 0, 0); } QDir Utils::setXmlPath() { - QDir xmlsPath(REGMAP_XML_BUILD_PATH); - if ( xmlsPath.entryList().empty()) { - #ifdef Q_OS_WINDOWS - xmlsPath.setPath("/plugins/regmap/xmls"); - #else - xmlsPath.setPath(REGMAP_XML_SYSTEM_PATH); - #endif - } - - if(!xmlsPath.entryList().empty()) { - return xmlsPath; - } - - qDebug(CAT_REGMAP)<< "No XML folder found"; - return QDir(""); + QDir xmlsPath(REGMAP_XML_BUILD_PATH); + if(xmlsPath.entryList().empty()) { +#ifdef Q_OS_WINDOWS + xmlsPath.setPath("/plugins/regmap/xmls"); +#else + xmlsPath.setPath(REGMAP_XML_SYSTEM_PATH); +#endif + } + + if(!xmlsPath.entryList().empty()) { + return xmlsPath; + } + + qDebug(CAT_REGMAP) << "No XML folder found"; + return QDir(""); } -int Utils::getBitsPerRow() -{ - return bitsPerRow; -} +int Utils::getBitsPerRow() { return bitsPerRow; } -int Utils::getBitsPerRowDetailed() -{ - return bitsPerRowDetailed; -} +int Utils::getBitsPerRowDetailed() { return bitsPerRowDetailed; } JsonFormatedElement *Utils::getJsonTemplate(QString xml) { - if (spiJson->contains(xml)) { - return spiJson->value(xml); - } + if(spiJson->contains(xml)) { + return spiJson->value(xml); + } - if (axiJson->contains(xml)) { - return axiJson->value(xml); - } + if(axiJson->contains(xml)) { + return axiJson->value(xml); + } - return nullptr; + return nullptr; } QString Utils::getTemplate(QString devName) { - // search for SPI template - foreach (QString key, spiJson->keys()) { - for (int i = 0; i < spiJson->value(key)->getCompatibleDevices()->size(); i++) { - if (spiJson->value(key)->getCompatibleDevices()->at(i).contains(devName)) { - return QString(key); - } - } - } - // search for AXI template - foreach (QString key, axiJson->keys()) { - for (int i = 0; i < axiJson->value(key)->getCompatibleDevices()->size(); i++) { - if (axiJson->value(key)->getCompatibleDevices()->at(i).contains(devName)) { - return QString(key); - } - } - } - - return QString(""); + // search for SPI template + foreach(QString key, spiJson->keys()) { + for(int i = 0; i < spiJson->value(key)->getCompatibleDevices()->size(); i++) { + if(spiJson->value(key)->getCompatibleDevices()->at(i).contains(devName)) { + return QString(key); + } + } + } + // search for AXI template + foreach(QString key, axiJson->keys()) { + for(int i = 0; i < axiJson->value(key)->getCompatibleDevices()->size(); i++) { + if(axiJson->value(key)->getCompatibleDevices()->at(i).contains(devName)) { + return QString(key); + } + } + } + + return QString(""); } void Utils::applyJsonConfig() { - QDir xmlsPath = scopy::regmap::Utils::setXmlPath(); - QString filePath = xmlsPath.filePath("regmap-config.json"); - generateJsonTemplate(filePath); + QDir xmlsPath = scopy::regmap::Utils::setXmlPath(); + QString filePath = xmlsPath.filePath("regmap-config.json"); + generateJsonTemplate(filePath); } void Utils::getConfigurationFromJson(QString filePath) { - QString val; - QFile file; - file.setFileName(filePath); - file.open(QIODevice::ReadOnly | QIODevice::Text); - val = file.readAll(); - file.close(); - - QJsonDocument d = QJsonDocument::fromJson(val.toUtf8()); + QString val; + QFile file; + file.setFileName(filePath); + file.open(QIODevice::ReadOnly | QIODevice::Text); + val = file.readAll(); + file.close(); - QJsonObject obj = d.object(); + QJsonDocument d = QJsonDocument::fromJson(val.toUtf8()); - QJsonArray jsonSpiArray = obj.value(QString("spi")).toArray(); - populateJsonTemplateMap(jsonSpiArray,false); - QJsonArray jsonAxiArray = obj.value(QString("axi")).toArray(); - populateJsonTemplateMap(jsonAxiArray,true); + QJsonObject obj = d.object(); + QJsonArray jsonSpiArray = obj.value(QString("spi")).toArray(); + populateJsonTemplateMap(jsonSpiArray, false); + QJsonArray jsonAxiArray = obj.value(QString("axi")).toArray(); + populateJsonTemplateMap(jsonAxiArray, true); } void Utils::populateJsonTemplateMap(QJsonArray jsonArray, bool isAxi) { - for (auto object : jsonArray) { - - QString fileName = object.toObject().value(QString("file_name")).toString(); - bool useRegisterDescriptionAsName = object.toObject().value(QString("use_register_description_as_name")).toBool(); - bool useBifieldDescriptionAsName = object.toObject().value(QString("use_bitfield_description_as_name")).toBool(); - - QList *compatibleDevicesList = new QList(); - QJsonArray compatibleDevices = object.toObject().value(QString("compatible_drivers")).toArray(); - - qDebug(CAT_REGMAP)<< "fileName : " << fileName; - qDebug(CAT_REGMAP)<< "useRegisterDescriptionAsName : " << useRegisterDescriptionAsName; - qDebug(CAT_REGMAP)<< "useBifieldDescriptionAsName : " << useBifieldDescriptionAsName; - - if (!compatibleDevices.isEmpty()) { - for (auto device : compatibleDevices) { - compatibleDevicesList->push_back(device.toString()); - qDebug(CAT_REGMAP)<< "compatible device : " << device.toString(); - } - } - spiJson->insert(fileName , new JsonFormatedElement(fileName, compatibleDevicesList, isAxi, useRegisterDescriptionAsName, useBifieldDescriptionAsName)); - } + for(auto object : jsonArray) { + + QString fileName = object.toObject().value(QString("file_name")).toString(); + bool useRegisterDescriptionAsName = + object.toObject().value(QString("use_register_description_as_name")).toBool(); + bool useBifieldDescriptionAsName = + object.toObject().value(QString("use_bitfield_description_as_name")).toBool(); + + QList *compatibleDevicesList = new QList(); + QJsonArray compatibleDevices = object.toObject().value(QString("compatible_drivers")).toArray(); + + qDebug(CAT_REGMAP) << "fileName : " << fileName; + qDebug(CAT_REGMAP) << "useRegisterDescriptionAsName : " << useRegisterDescriptionAsName; + qDebug(CAT_REGMAP) << "useBifieldDescriptionAsName : " << useBifieldDescriptionAsName; + + if(!compatibleDevices.isEmpty()) { + for(auto device : compatibleDevices) { + compatibleDevicesList->push_back(device.toString()); + qDebug(CAT_REGMAP) << "compatible device : " << device.toString(); + } + } + spiJson->insert(fileName, + new JsonFormatedElement(fileName, compatibleDevicesList, isAxi, + useRegisterDescriptionAsName, useBifieldDescriptionAsName)); + } } void Utils::generateJsonTemplate(QString filePath) { - getConfigurationFromJson(filePath); - - foreach (const QString &xmlName, scopy::regmap::Utils::setXmlPath().entryList()) { - if (xmlName.contains(".xml") ) { - auto deviceName = xmlName.toLower(); - deviceName.chop(4); - if (spiJson->contains(xmlName)) { - spiJson->value(xmlName)->addCompatibleDevice(deviceName); - } else { - JsonFormatedElement *jsonFormatedElement = new JsonFormatedElement(xmlName); - jsonFormatedElement->addCompatibleDevice(deviceName); - spiJson->insert(xmlName,jsonFormatedElement); - } - } - } + getConfigurationFromJson(filePath); + + foreach(const QString &xmlName, scopy::regmap::Utils::setXmlPath().entryList()) { + if(xmlName.contains(".xml")) { + auto deviceName = xmlName.toLower(); + deviceName.chop(4); + if(spiJson->contains(xmlName)) { + spiJson->value(xmlName)->addCompatibleDevice(deviceName); + } else { + JsonFormatedElement *jsonFormatedElement = new JsonFormatedElement(xmlName); + jsonFormatedElement->addCompatibleDevice(deviceName); + spiJson->insert(xmlName, jsonFormatedElement); + } + } + } } diff --git a/plugins/regmap/src/utils.hpp b/plugins/regmap/src/utils.hpp index 851e4cf6a5..af98bb67ff 100644 --- a/plugins/regmap/src/utils.hpp +++ b/plugins/regmap/src/utils.hpp @@ -12,33 +12,32 @@ class JsonFormatedElement; class Utils : public QObject { - Q_OBJECT + Q_OBJECT public: - explicit Utils(QObject *parent = nullptr); + explicit Utils(QObject *parent = nullptr); - static QString convertToHexa(uint32_t value, int size); - static void removeLayoutMargins(QLayout *layout); - static QDir setXmlPath(); + static QString convertToHexa(uint32_t value, int size); + static void removeLayoutMargins(QLayout *layout); + static QDir setXmlPath(); - static int getBitsPerRow(); - static int getBitsPerRowDetailed(); + static int getBitsPerRow(); + static int getBitsPerRowDetailed(); - static JsonFormatedElement* getJsonTemplate(QString xml); + static JsonFormatedElement *getJsonTemplate(QString xml); - static void applyJsonConfig(); - static QString getTemplate(QString devName); + static void applyJsonConfig(); + static QString getTemplate(QString devName); private: - static const int bitsPerRow = 7; - static const int bitsPerRowDetailed = 3; - static QMap* spiJson; - static QMap* axiJson; - static void getConfigurationFromJson(QString filePath); - static void populateJsonTemplateMap(QJsonArray jsonArray, bool isAxi); - static void generateJsonTemplate(QString filePath); + static const int bitsPerRow = 7; + static const int bitsPerRowDetailed = 3; + static QMap *spiJson; + static QMap *axiJson; + static void getConfigurationFromJson(QString filePath); + static void populateJsonTemplateMap(QJsonArray jsonArray, bool isAxi); + static void generateJsonTemplate(QString filePath); signals: - }; -} +} // namespace scopy::regmap #endif // UTILS_HPP diff --git a/plugins/regmap/src/verticalscrollarea.cpp b/plugins/regmap/src/verticalscrollarea.cpp index bb7f3311af..a2051d20a8 100644 --- a/plugins/regmap/src/verticalscrollarea.cpp +++ b/plugins/regmap/src/verticalscrollarea.cpp @@ -2,17 +2,17 @@ #include -VerticalScrollArea::VerticalScrollArea(QWidget *parent): -QScrollArea(parent) +VerticalScrollArea::VerticalScrollArea(QWidget *parent) + : QScrollArea(parent) { - setWidgetResizable(true); - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + setWidgetResizable(true); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); } bool VerticalScrollArea::eventFilter(QObject *o, QEvent *e) { - if (o && o == widget() && e->type() == QEvent::Resize) - setMinimumWidth(widget()->minimumSizeHint().width() ); - return QScrollArea::eventFilter(o,e); + if(o && o == widget() && e->type() == QEvent::Resize) + setMinimumWidth(widget()->minimumSizeHint().width()); + return QScrollArea::eventFilter(o, e); } diff --git a/plugins/regmap/src/verticalscrollarea.hpp b/plugins/regmap/src/verticalscrollarea.hpp index 67e40b8935..3bb13fc959 100644 --- a/plugins/regmap/src/verticalscrollarea.hpp +++ b/plugins/regmap/src/verticalscrollarea.hpp @@ -1,15 +1,16 @@ #ifndef VERTICALSCROLLAREA_HPP #define VERTICALSCROLLAREA_HPP -#include #include "scopy-regmapplugin_export.h" -class SCOPY_REGMAPPLUGIN_EXPORT VerticalScrollArea: public QScrollArea +#include + +class SCOPY_REGMAPPLUGIN_EXPORT VerticalScrollArea : public QScrollArea { - Q_OBJECT + Q_OBJECT public: - explicit VerticalScrollArea(QWidget *parent = 0); - virtual bool eventFilter(QObject *o, QEvent *e); + explicit VerticalScrollArea(QWidget *parent = 0); + virtual bool eventFilter(QObject *o, QEvent *e); }; #endif // VERTICALSCROLLAREA_HPP diff --git a/plugins/regmap/src/xmlfilemanager.cpp b/plugins/regmap/src/xmlfilemanager.cpp index a25dbdc459..28f2a5d632 100644 --- a/plugins/regmap/src/xmlfilemanager.cpp +++ b/plugins/regmap/src/xmlfilemanager.cpp @@ -1,225 +1,223 @@ +#include "xmlfilemanager.hpp" + +#include "jsonformatedelement.hpp" #include "register/bitfield/bitfieldmodel.hpp" #include "register/registermodel.hpp" -#include "jsonformatedelement.hpp" -#include "xmlfilemanager.hpp" #include "utils.hpp" #include -#include -#include #include +#include +#include #include using namespace scopy; using namespace regmap; -XmlFileManager::XmlFileManager(struct iio_device *dev, QString filePath): - dev(dev), - filePath(filePath) +XmlFileManager::XmlFileManager(struct iio_device *dev, QString filePath) + : dev(dev) + , filePath(filePath) {} QList *XmlFileManager::getAllAddresses() { - QList *addressList = new QList(); - QDomDocument xmlBOM; - QFile f(filePath); - if (!f.open(QIODevice::ReadOnly )) - { - // Error while loading file - qDebug() << "Error while loading file"; - } - // Set data into the QDomDocument before processing - xmlBOM.setContent(&f); - QDomElement root=xmlBOM.documentElement(); - QDomElement reg = root.firstChildElement("Register"); - while(!reg.isNull()) - { - QDomElement address = reg.firstChildElement("Address"); - addressList->push_back(address.firstChild().toText().data()); - reg = reg.nextSibling().toElement(); - } - f.close(); - - return addressList; + QList *addressList = new QList(); + QDomDocument xmlBOM; + QFile f(filePath); + if(!f.open(QIODevice::ReadOnly)) { + // Error while loading file + qDebug() << "Error while loading file"; + } + // Set data into the QDomDocument before processing + xmlBOM.setContent(&f); + QDomElement root = xmlBOM.documentElement(); + QDomElement reg = root.firstChildElement("Register"); + while(!reg.isNull()) { + QDomElement address = reg.firstChildElement("Address"); + addressList->push_back(address.firstChild().toText().data()); + reg = reg.nextSibling().toElement(); + } + f.close(); + + return addressList; } -QMap* XmlFileManager::getAllRegisters() +QMap *XmlFileManager::getAllRegisters() { - QMap *regList = new QMap(); - QDomDocument xmlBOM; - QFile f(filePath); - if (!f.open(QIODevice::ReadOnly )) - { - // Error while loading file - qDebug() << "Error while loading file"; - } - // Set data into the QDomDocument before processing - xmlBOM.setContent(&f); - QDomElement root=xmlBOM.documentElement(); - QDomElement reg = root.firstChildElement("Register"); - - while(!reg.isNull()) - { - bool ok; - int address = reg.firstChildElement("Address").firstChild().toText().data().toInt(&ok,16); - regList->insert(address, getRegister(reg)); - reg = reg.nextSibling().toElement(); - } - f.close(); - - return regList; + QMap *regList = new QMap(); + QDomDocument xmlBOM; + QFile f(filePath); + if(!f.open(QIODevice::ReadOnly)) { + // Error while loading file + qDebug() << "Error while loading file"; + } + // Set data into the QDomDocument before processing + xmlBOM.setContent(&f); + QDomElement root = xmlBOM.documentElement(); + QDomElement reg = root.firstChildElement("Register"); + + while(!reg.isNull()) { + bool ok; + int address = reg.firstChildElement("Address").firstChild().toText().data().toInt(&ok, 16); + regList->insert(address, getRegister(reg)); + reg = reg.nextSibling().toElement(); + } + f.close(); + + return regList; } -QVector *XmlFileManager::getBitFields(QString regAddr) +QVector *XmlFileManager::getBitFields(QString regAddr) { - QDomDocument xmlBOM; - QFile f(filePath); - if (!f.open(QIODevice::ReadOnly )) - { - // Error while loading file - qDebug() << "Error while loading file"; - } - // Set data into the QDomDocument before processing - xmlBOM.setContent(&f); - QDomElement root=xmlBOM.documentElement(); - QDomElement reg = root.firstChildElement("Register"); - while(!reg.isNull()) - { - QDomElement address = reg.firstChildElement("Address"); - if (address.firstChild().toText().data() == regAddr) { - return getBitFieldsOfRegister(reg, true); - } - reg = reg.nextSibling().toElement(); - } - f.close(); - - return nullptr; + QDomDocument xmlBOM; + QFile f(filePath); + if(!f.open(QIODevice::ReadOnly)) { + // Error while loading file + qDebug() << "Error while loading file"; + } + // Set data into the QDomDocument before processing + xmlBOM.setContent(&f); + QDomElement root = xmlBOM.documentElement(); + QDomElement reg = root.firstChildElement("Register"); + while(!reg.isNull()) { + QDomElement address = reg.firstChildElement("Address"); + if(address.firstChild().toText().data() == regAddr) { + return getBitFieldsOfRegister(reg, true); + } + reg = reg.nextSibling().toElement(); + } + f.close(); + + return nullptr; } RegisterModel *XmlFileManager::getRegister(QDomElement reg) { - if (!reg.isNull()) { - bool ok; - - QString name = ""; - QString description = ""; - bool isAxiCompatible = false; - QStringList xmlName = filePath.split(QLatin1Char('/')); - - JsonFormatedElement *jsonFormatedElement = scopy::regmap::Utils::getJsonTemplate(xmlName.at(xmlName.length() - 1)); - if (jsonFormatedElement && jsonFormatedElement->getUseRegisterNameAsDescription()) { - name = reg.firstChildElement("Description").firstChild().toText().data(); - description = reg.firstChildElement("Name").firstChild().toText().data(); - isAxiCompatible = jsonFormatedElement->getIsAxiCompatible(); - } else { - name = reg.firstChildElement("Name").firstChild().toText().data(); - description = reg.firstChildElement("Description").firstChild().toText().data(); - } - - return new RegisterModel( name, - reg.firstChildElement("Address").firstChild().toText().data().toInt(&ok,16), - description, - reg.firstChildElement("Exists").toText().data().toUpper() == "TRUE", - reg.firstChildElement("Width").firstChild().toText().data().toInt(), - reg.firstChildElement("Notes").firstChild().toText().data(), - getBitFieldsOfRegister(reg, isAxiCompatible) - ); - } - return nullptr; + if(!reg.isNull()) { + bool ok; + + QString name = ""; + QString description = ""; + bool isAxiCompatible = false; + QStringList xmlName = filePath.split(QLatin1Char('/')); + + JsonFormatedElement *jsonFormatedElement = + scopy::regmap::Utils::getJsonTemplate(xmlName.at(xmlName.length() - 1)); + if(jsonFormatedElement && jsonFormatedElement->getUseRegisterNameAsDescription()) { + name = reg.firstChildElement("Description").firstChild().toText().data(); + description = reg.firstChildElement("Name").firstChild().toText().data(); + isAxiCompatible = jsonFormatedElement->getIsAxiCompatible(); + } else { + name = reg.firstChildElement("Name").firstChild().toText().data(); + description = reg.firstChildElement("Description").firstChild().toText().data(); + } + + return new RegisterModel( + name, reg.firstChildElement("Address").firstChild().toText().data().toInt(&ok, 16), description, + reg.firstChildElement("Exists").toText().data().toUpper() == "TRUE", + reg.firstChildElement("Width").firstChild().toText().data().toInt(), + reg.firstChildElement("Notes").firstChild().toText().data(), + getBitFieldsOfRegister(reg, isAxiCompatible)); + } + return nullptr; } -bool compareRegisters(const BitFieldModel *bf1, const BitFieldModel *bf2) { - return bf1->getRegOffset() < bf2->getRegOffset(); +bool compareRegisters(const BitFieldModel *bf1, const BitFieldModel *bf2) +{ + return bf1->getRegOffset() < bf2->getRegOffset(); } -QVector *XmlFileManager::getBitFieldsOfRegister(QDomElement reg, bool reverseBitOrder) +QVector *XmlFileManager::getBitFieldsOfRegister(QDomElement reg, bool reverseBitOrder) { - if (!reg.isNull()) { - - QVector *bitFieldsList = new QVector(); - QDomElement bitFields = reg.firstChildElement("BitFields"); - QDomElement bf; - bf = bitFields.firstChild().toElement(); - int regWidth = reg.firstChildElement("Width").firstChild().toText().data().toInt(); - int numberOfBits = 0; - while(!bf.isNull()) { - BitFieldModel *bitField = getBitField(bf); - bitFieldsList->push_back(bitField); - numberOfBits += bitField->getWidth(); - bf = bf.nextSibling().toElement(); - } - // after getting all available bitfields sort the list and add all the missing bits as reserved - if (!bitFieldsList->empty()) { - QVector *bitFieldsListWithReserved = new QVector(); - if (regWidth > numberOfBits){ - //sort bitfield list - std::sort(bitFieldsList->begin(), bitFieldsList->end(), compareRegisters); - bitFieldsListWithReserved->push_back(bitFieldsList->at(0)); - for (int i = 1; i < bitFieldsList->length(); i++) { - int bf1 = bitFieldsList->at(i - 1)->getRegOffset() + bitFieldsList->at(i -1)->getWidth(); - int bf2 = bitFieldsList->at(i)->getRegOffset(); - if ( bf1 != bf2) { - BitFieldModel *bitField = new BitFieldModel("Bit " +QString::number(bf2 -1) + ":" + QString::number(bf1), - bf2 - bf1, bf1 , "Reserved" , nullptr); - bitFieldsListWithReserved->push_back(bitField); - numberOfBits += bf2 - bf1; - } - bitFieldsListWithReserved->push_back(bitFieldsList->at(i)); - } - - if (regWidth > numberOfBits){ - BitFieldModel *bitField = new BitFieldModel("Bit " + QString::number(regWidth -1) + ":" + QString::number(numberOfBits) , regWidth - numberOfBits, numberOfBits, "Reserved", nullptr); - bitFieldsListWithReserved->push_back(bitField); - } - return bitFieldsListWithReserved; - } - } - return bitFieldsList; - } - return nullptr; + if(!reg.isNull()) { + + QVector *bitFieldsList = new QVector(); + QDomElement bitFields = reg.firstChildElement("BitFields"); + QDomElement bf; + bf = bitFields.firstChild().toElement(); + int regWidth = reg.firstChildElement("Width").firstChild().toText().data().toInt(); + int numberOfBits = 0; + while(!bf.isNull()) { + BitFieldModel *bitField = getBitField(bf); + bitFieldsList->push_back(bitField); + numberOfBits += bitField->getWidth(); + bf = bf.nextSibling().toElement(); + } + // after getting all available bitfields sort the list and add all the missing bits as reserved + if(!bitFieldsList->empty()) { + QVector *bitFieldsListWithReserved = new QVector(); + if(regWidth > numberOfBits) { + // sort bitfield list + std::sort(bitFieldsList->begin(), bitFieldsList->end(), compareRegisters); + bitFieldsListWithReserved->push_back(bitFieldsList->at(0)); + for(int i = 1; i < bitFieldsList->length(); i++) { + int bf1 = bitFieldsList->at(i - 1)->getRegOffset() + + bitFieldsList->at(i - 1)->getWidth(); + int bf2 = bitFieldsList->at(i)->getRegOffset(); + if(bf1 != bf2) { + BitFieldModel *bitField = new BitFieldModel( + "Bit " + QString::number(bf2 - 1) + ":" + QString::number(bf1), + bf2 - bf1, bf1, "Reserved", nullptr); + bitFieldsListWithReserved->push_back(bitField); + numberOfBits += bf2 - bf1; + } + bitFieldsListWithReserved->push_back(bitFieldsList->at(i)); + } + + if(regWidth > numberOfBits) { + BitFieldModel *bitField = new BitFieldModel( + "Bit " + QString::number(regWidth - 1) + ":" + + QString::number(numberOfBits), + regWidth - numberOfBits, numberOfBits, "Reserved", nullptr); + bitFieldsListWithReserved->push_back(bitField); + } + return bitFieldsListWithReserved; + } + } + return bitFieldsList; + } + return nullptr; } BitFieldModel *XmlFileManager::getBitField(QDomElement bitField) { - if (!bitField.isNull()) { - QVector *options = new QVector(); - QDomElement bitFieldOptions = bitField.firstChildElement("Options"); - QDomElement bfOption = bitFieldOptions.firstChildElement("Option"); - while (!bfOption.isNull()) { - bool ok; - options->push_back(new BitFieldOption( - QString::number(bfOption.firstChildElement("Value").firstChild().toText().data().toInt(&ok,16)), - bfOption.firstChildElement("Description").firstChild().toText().data() )); - bfOption = bfOption.nextSibling().toElement(); - } - - QString name = ""; - QString description = ""; - QStringList xmlName = filePath.split(QLatin1Char('/')); - - JsonFormatedElement *jsonFormatedElement = scopy::regmap::Utils::getJsonTemplate(xmlName.at(xmlName.length() - 1)); - if (jsonFormatedElement && jsonFormatedElement->getUseBifieldNameAsDescription()) { - name = bitField.firstChildElement("Description").firstChild().toText().data(); - description = bitField.firstChildElement("Name").firstChild().toText().data(); - } else { - name = bitField.firstChildElement("Name").firstChild().toText().data(); - description = bitField.firstChildElement("Description").firstChild().toText().data(); - } - - return new BitFieldModel( - name, - bitField.firstChildElement("Access").firstChild().toText().data(), - bitField.firstChildElement("DefaultValue").firstChild().toText().data().toInt(), - description, - bitField.firstChildElement("Visibility").firstChild().toText().data(), - bitField.firstChildElement("Width").firstChild().toText().data().toInt(), - bitField.firstChildElement("Notes").firstChild().toText().data(), - bitField.firstChildElement("BitOffset").firstChild().toText().data().toInt(), - bitField.firstChildElement("RegOffset").firstChild().toText().data().toInt(), - bitField.firstChildElement("SliceWidth").firstChild().toText().data().toInt(), - options - ); - } - return nullptr; + if(!bitField.isNull()) { + QVector *options = new QVector(); + QDomElement bitFieldOptions = bitField.firstChildElement("Options"); + QDomElement bfOption = bitFieldOptions.firstChildElement("Option"); + while(!bfOption.isNull()) { + bool ok; + options->push_back(new BitFieldOption( + QString::number(bfOption.firstChildElement("Value").firstChild().toText().data().toInt( + &ok, 16)), + bfOption.firstChildElement("Description").firstChild().toText().data())); + bfOption = bfOption.nextSibling().toElement(); + } + + QString name = ""; + QString description = ""; + QStringList xmlName = filePath.split(QLatin1Char('/')); + + JsonFormatedElement *jsonFormatedElement = + scopy::regmap::Utils::getJsonTemplate(xmlName.at(xmlName.length() - 1)); + if(jsonFormatedElement && jsonFormatedElement->getUseBifieldNameAsDescription()) { + name = bitField.firstChildElement("Description").firstChild().toText().data(); + description = bitField.firstChildElement("Name").firstChild().toText().data(); + } else { + name = bitField.firstChildElement("Name").firstChild().toText().data(); + description = bitField.firstChildElement("Description").firstChild().toText().data(); + } + + return new BitFieldModel( + name, bitField.firstChildElement("Access").firstChild().toText().data(), + bitField.firstChildElement("DefaultValue").firstChild().toText().data().toInt(), description, + bitField.firstChildElement("Visibility").firstChild().toText().data(), + bitField.firstChildElement("Width").firstChild().toText().data().toInt(), + bitField.firstChildElement("Notes").firstChild().toText().data(), + bitField.firstChildElement("BitOffset").firstChild().toText().data().toInt(), + bitField.firstChildElement("RegOffset").firstChild().toText().data().toInt(), + bitField.firstChildElement("SliceWidth").firstChild().toText().data().toInt(), options); + } + return nullptr; } diff --git a/plugins/regmap/src/xmlfilemanager.hpp b/plugins/regmap/src/xmlfilemanager.hpp index 064a9c618b..3f10c95ad3 100644 --- a/plugins/regmap/src/xmlfilemanager.hpp +++ b/plugins/regmap/src/xmlfilemanager.hpp @@ -1,36 +1,38 @@ #ifndef XMLFILEMANAGER_HPP #define XMLFILEMANAGER_HPP -#include #include "scopy-regmapplugin_export.h" + #include +#include + class QDomElement; class QString; -namespace scopy::regmap{ +namespace scopy::regmap { class RegisterModel; class BitFieldModel; -class SCOPY_REGMAPPLUGIN_EXPORT XmlFileManager: public QObject +class SCOPY_REGMAPPLUGIN_EXPORT XmlFileManager : public QObject { Q_OBJECT public: - XmlFileManager( struct iio_device *dev, QString filePath); + XmlFileManager(struct iio_device *dev, QString filePath); - QList* getAllAddresses(); - QMap *getAllRegisters(); - RegisterModel* getRegAtAddress(QString addr); - RegisterModel* getRegister(QDomElement reg); + QList *getAllAddresses(); + QMap *getAllRegisters(); + RegisterModel *getRegAtAddress(QString addr); + RegisterModel *getRegister(QDomElement reg); void getRegMapData(QString addr); - QVector *getBitFields(QString regAddr); - QVector *getBitFieldsOfRegister(QDomElement reg, bool reverseBitOrder); + QVector *getBitFields(QString regAddr); + QVector *getBitFieldsOfRegister(QDomElement reg, bool reverseBitOrder); BitFieldModel *getBitField(QDomElement bitField); private: QString filePath; struct iio_device *dev; }; -} +} // namespace scopy::regmap #endif // XMLFILEMANAGER_HPP diff --git a/plugins/regmap/test/CMakeLists.txt b/plugins/regmap/test/CMakeLists.txt index 10061d9e18..3f9d9508a3 100644 --- a/plugins/regmap/test/CMakeLists.txt +++ b/plugins/regmap/test/CMakeLists.txt @@ -1,8 +1,6 @@ cmake_minimum_required(VERSION 3.5) -#set(CMAKE_FIND_DEBUG_MODE ON) +# set(CMAKE_FIND_DEBUG_MODE ON) include(ScopyTest) -SETUP_SCOPY_TESTS( - pluginloader -) +setup_scopy_tests(pluginloader) diff --git a/plugins/regmap/test/tst_pluginloader.cpp b/plugins/regmap/test/tst_pluginloader.cpp index e47ae6fffd..96069eec53 100644 --- a/plugins/regmap/test/tst_pluginloader.cpp +++ b/plugins/regmap/test/tst_pluginloader.cpp @@ -1,6 +1,8 @@ #include "qpluginloader.h" -#include + #include +#include + #include using namespace scopy; @@ -24,7 +26,6 @@ private Q_SLOTS: #define PLUGIN_LOCATION "../../plugins" #define FILENAME PLUGIN_LOCATION "/libscopy-regmapplugin.so" - void TST_REGMAPPlugin::fileExists() { QFile f(FILENAME); @@ -35,54 +36,49 @@ void TST_REGMAPPlugin::fileExists() QVERIFY(ret); } -void TST_REGMAPPlugin::isLibrary() -{ - QVERIFY(QLibrary::isLibrary(FILENAME)); -} +void TST_REGMAPPlugin::isLibrary() { QVERIFY(QLibrary::isLibrary(FILENAME)); } void TST_REGMAPPlugin::className() { - QPluginLoader qp(FILENAME,this); - QVERIFY(qp.metaData().value("className") == "RegmapPlugin"); + QPluginLoader qp(FILENAME, this); + QVERIFY(qp.metaData().value("className") == "RegmapPlugin"); } void TST_REGMAPPlugin::loaded() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); qp.load(); - qDebug() << qp.errorString(); + qDebug() << qp.errorString(); QVERIFY(qp.isLoaded()); } void TST_REGMAPPlugin::instanceNotNull() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); QVERIFY(qp.instance() != nullptr); } void TST_REGMAPPlugin::multipleInstances() { - QPluginLoader qp1(FILENAME,this); - QPluginLoader qp2(FILENAME,this); + QPluginLoader qp1(FILENAME, this); + QPluginLoader qp2(FILENAME, this); QVERIFY(qp1.instance() == qp2.instance()); } - void TST_REGMAPPlugin::qobjectcast_to_plugin() { - QPluginLoader qp(FILENAME,this); - auto instance = qobject_cast(qp.instance()); - QVERIFY(instance != nullptr ); + QPluginLoader qp(FILENAME, this); + auto instance = qobject_cast(qp.instance()); + QVERIFY(instance != nullptr); } - void TST_REGMAPPlugin::clone() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(); QVERIFY(p1 != nullptr); p2 = original->clone(); @@ -90,28 +86,28 @@ void TST_REGMAPPlugin::clone() QVERIFY(p1 != p2); } -void TST_REGMAPPlugin::name() { - QPluginLoader qp(FILENAME,this); +void TST_REGMAPPlugin::name() +{ + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(); - qDebug()<name(); + qDebug() << p1->name(); } void TST_REGMAPPlugin::metadata() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); original->initMetadata(); p1 = original->clone(); - qDebug()<metadata(); + qDebug() << p1->metadata(); QVERIFY(!p1->metadata().isEmpty()); } - QTEST_MAIN(TST_REGMAPPlugin) #include "tst_pluginloader.moc" diff --git a/plugins/regmap/test/tst_swiot.cpp b/plugins/regmap/test/tst_swiot.cpp index 836b35c1d4..3b84f786dd 100644 --- a/plugins/regmap/test/tst_swiot.cpp +++ b/plugins/regmap/test/tst_swiot.cpp @@ -7,7 +7,7 @@ private Q_SLOTS: void hello(); }; -void ScopyMainWindowTest::hello() { +void ScopyMainWindowTest::hello(){ }; diff --git a/plugins/swiot/CMakeLists.txt b/plugins/swiot/CMakeLists.txt index c3d22747a7..ee38cc76aa 100644 --- a/plugins/swiot/CMakeLists.txt +++ b/plugins/swiot/CMakeLists.txt @@ -8,8 +8,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -26,70 +25,58 @@ set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) set(SCOPY_QT_COMPONENTS Widgets Concurrent Svg Xml) -FILE(GLOB SRC_LIST +file( + GLOB + SRC_LIST src/config/*.cpp src/config/*.cc - -# some of these will eventually be moved to the core/gui directories + # some of these will eventually be moved to the core/gui directories src/refactoring/maincore/* src/refactoring/maingui/* src/refactoring/tool/* - src/runtime/ad74413r/*.cpp src/runtime/ad74413r/*.cc - src/runtime/max14906/*.cpp src/runtime/max14906/*.cc - src/runtime/faults/*.cpp src/runtime/faults/*.cc - src/runtime/*.cpp - src/*.cpp model/* ) -FILE(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) -FILE(GLOB UI_LIST ui/*.ui) +file(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) +file(GLOB UI_LIST ui/*.ui) if(ENABLE_TESTING) add_subdirectory(test) endif() -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} -) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS ${SCOPY_QT_COMPONENTS} REQUIRED) if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") - set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY - "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") else() - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) endif() - if(ANDROID) find_library(QWT_LIBRARIES REQUIRED NAMES qwt_${ANDROID_ABI}) else() find_library(QWT_LIBRARIES REQUIRED NAMES qwt) endif() - qt_add_resources(PROJECT_RESOURCES resources/resources.qrc ../../resources/resources.qrc) -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} - ${PROJECT_RESOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES} ${PROJECT_RESOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}) @@ -97,15 +84,17 @@ target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/i include_directories(${Qt${QT_VERSION_MAJOR}Concurrent_INCLUDE_DIRS}) foreach(comp ${SCOPY_QT_COMPONENTS}) - set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) + set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) endforeach() -target_link_libraries(${PROJECT_NAME} PUBLIC - ${SCOPY_QT_LIBRARIES} - scopy-pluginbase - scopy-iioutil - scopy-gui - scopy-core - ${QWT_LIBRARIES}) +target_link_libraries( + ${PROJECT_NAME} + PUBLIC ${SCOPY_QT_LIBRARIES} + scopy-pluginbase + scopy-iioutil + scopy-gui + scopy-core + ${QWT_LIBRARIES} +) -set(PLUGIN_NAME ${PROJECT_NAME} PARENT_SCOPE) \ No newline at end of file +set(PLUGIN_NAME ${PROJECT_NAME} PARENT_SCOPE) diff --git a/plugins/swiot/include/swiot/swiotplugin.h b/plugins/swiot/include/swiot/swiotplugin.h index b2a73c67d6..d015b0b353 100644 --- a/plugins/swiot/include/swiot/swiotplugin.h +++ b/plugins/swiot/include/swiot/swiotplugin.h @@ -18,7 +18,6 @@ * along with this program. If not, see . */ - #ifndef SWIOTPLUGIN_H #define SWIOTPLUGIN_H #define SCOPY_PLUGIN_NAME SWIOTPlugin @@ -27,17 +26,18 @@ #define FAULTS_TME_ID "swiotfaults" #define MAX14906_TME_ID "swiotmax14906" -#include -#include +#include "QLabel" #include "scopy-swiot_export.h" +#include "src/externalpsreaderthread.h" #include "src/runtime/swiotruntime.h" -#include "QLabel" #include "src/swiotcontroller.h" #include "src/swiotinfopage.h" -#include -#include + #include -#include "src/externalpsreaderthread.h" +#include +#include +#include +#include namespace scopy::swiot { class SCOPY_SWIOT_EXPORT SWIOTPlugin : public QObject, public PluginBase @@ -93,6 +93,6 @@ public Q_SLOTS: bool m_isRuntime; }; -} +} // namespace scopy::swiot #endif // SWIOTPLUGIN_H diff --git a/plugins/swiot/src/config/configchannelview.cpp b/plugins/swiot/src/config/configchannelview.cpp index 5d90da1020..e067557ece 100644 --- a/plugins/swiot/src/config/configchannelview.cpp +++ b/plugins/swiot/src/config/configchannelview.cpp @@ -18,17 +18,17 @@ * along with this program. If not, see . */ - #include "configchannelview.h" + #include "src/swiot_logging_categories.h" using namespace scopy::swiot; -ConfigChannelView::ConfigChannelView(int channelIndex, QWidget *parent) : - QFrame(parent), - ui(new Ui::ConfigChannelView()), - m_channelEnabled(false), - m_channelIndex(channelIndex) +ConfigChannelView::ConfigChannelView(int channelIndex, QWidget *parent) + : QFrame(parent) + , ui(new Ui::ConfigChannelView()) + , m_channelEnabled(false) + , m_channelIndex(channelIndex) { this->installEventFilter(this); this->ui->setupUi(this); @@ -42,14 +42,13 @@ ConfigChannelView::ConfigChannelView(int channelIndex, QWidget *parent) : this->initTutorialProperties(); } -ConfigChannelView::~ConfigChannelView() { - delete ui; -} +ConfigChannelView::~ConfigChannelView() { delete ui; } -void ConfigChannelView::connectSignalsAndSlots() { - QObject::connect(this->ui->enabledCheckBox, &QCheckBox::stateChanged, this, [=, this] (int state) { +void ConfigChannelView::connectSignalsAndSlots() +{ + QObject::connect(this->ui->enabledCheckBox, &QCheckBox::stateChanged, this, [=, this](int state) { this->setChannelEnabled(state); - if (m_channelEnabled) { + if(m_channelEnabled) { Q_EMIT showPath(m_channelIndex, m_selectedDevice); } else { Q_EMIT hidePaths(); @@ -57,25 +56,24 @@ void ConfigChannelView::connectSignalsAndSlots() { Q_EMIT enabledChanged(m_channelIndex, state); }); - QObject::connect(this->ui->deviceOptions, &QComboBox::textActivated, this, [this] (const QString& text) { + QObject::connect(this->ui->deviceOptions, &QComboBox::textActivated, this, [this](const QString &text) { m_selectedDevice = text; Q_EMIT deviceChanged(m_channelIndex, this->ui->deviceOptions->currentText()); }); - QObject::connect(this->ui->functionOptions, &QComboBox::textActivated, this, [=, this] (const QString& text) { + QObject::connect(this->ui->functionOptions, &QComboBox::textActivated, this, [=, this](const QString &text) { m_selectedFunction = text; Q_EMIT functionChanged(m_channelIndex, this->ui->functionOptions->currentText()); }); } -bool ConfigChannelView::isChannelEnabled() const { - return m_channelEnabled; -} +bool ConfigChannelView::isChannelEnabled() const { return m_channelEnabled; } -void ConfigChannelView::setChannelEnabled(bool mChannelEnabled) { +void ConfigChannelView::setChannelEnabled(bool mChannelEnabled) +{ m_channelEnabled = mChannelEnabled; - if (m_channelEnabled) { + if(m_channelEnabled) { this->ui->enabledCheckBox->setChecked(true); this->ui->deviceOptions->setEnabled(true); this->ui->functionOptions->setEnabled(true); @@ -86,66 +84,63 @@ void ConfigChannelView::setChannelEnabled(bool mChannelEnabled) { } } -const QString &ConfigChannelView::getSelectedDevice() const { - return m_selectedDevice; -} +const QString &ConfigChannelView::getSelectedDevice() const { return m_selectedDevice; } -void ConfigChannelView::setSelectedDevice(const QString &mSelectedDevice) { +void ConfigChannelView::setSelectedDevice(const QString &mSelectedDevice) +{ m_selectedDevice = mSelectedDevice; int index = this->ui->deviceOptions->findText(m_selectedDevice); this->ui->deviceOptions->setCurrentIndex(index); } -const QStringList &ConfigChannelView::getDeviceAvailable() const { - return m_deviceAvailable; -} +const QStringList &ConfigChannelView::getDeviceAvailable() const { return m_deviceAvailable; } -void ConfigChannelView::setDeviceAvailable(const QStringList &mDeviceAvailable) { +void ConfigChannelView::setDeviceAvailable(const QStringList &mDeviceAvailable) +{ m_deviceAvailable = mDeviceAvailable; this->ui->deviceOptions->clear(); - for (const QString &device: qAsConst(m_deviceAvailable)) { + for(const QString &device : qAsConst(m_deviceAvailable)) { this->ui->deviceOptions->addItem(device); } } -const QString &ConfigChannelView::getSelectedFunction() const { - return m_selectedFunction; -} +const QString &ConfigChannelView::getSelectedFunction() const { return m_selectedFunction; } -void ConfigChannelView::setSelectedFunction(const QString &mSelectedFunction) { +void ConfigChannelView::setSelectedFunction(const QString &mSelectedFunction) +{ m_selectedFunction = mSelectedFunction; - if (mSelectedFunction.isEmpty()) { + if(mSelectedFunction.isEmpty()) { this->ui->functionOptions->setCurrentIndex(0); } else { int index = this->ui->functionOptions->findText(m_selectedFunction); - if (index >= 0) { + if(index >= 0) { this->ui->functionOptions->setCurrentIndex(index); } } } -const QStringList &ConfigChannelView::getFunctionAvailable() const { - return m_functionAvailable; -} +const QStringList &ConfigChannelView::getFunctionAvailable() const { return m_functionAvailable; } -void ConfigChannelView::setFunctionAvailable(const QStringList &mFunctionAvailable) { +void ConfigChannelView::setFunctionAvailable(const QStringList &mFunctionAvailable) +{ m_functionAvailable = mFunctionAvailable; this->ui->functionOptions->clear(); - for (const QString &device: qAsConst(m_functionAvailable)) { + for(const QString &device : qAsConst(m_functionAvailable)) { this->ui->functionOptions->addItem(device); } } -bool ConfigChannelView::eventFilter(QObject* object, QEvent *event) { - if (event->type() == QEvent::Enter) { +bool ConfigChannelView::eventFilter(QObject *object, QEvent *event) +{ + if(event->type() == QEvent::Enter) { this->setStyleSheet("background-color: #272730;"); this->ensurePolished(); - if (m_channelEnabled) { + if(m_channelEnabled) { Q_EMIT showPath(m_channelIndex, m_selectedDevice); } } - if (event->type() == QEvent::Leave) { + if(event->type() == QEvent::Leave) { this->setStyleSheet(""); this->ensurePolished(); Q_EMIT hidePaths(); @@ -154,8 +149,9 @@ bool ConfigChannelView::eventFilter(QObject* object, QEvent *event) { return QFrame::event(event); } -void ConfigChannelView::initTutorialProperties() { - if (m_channelIndex == 0) { +void ConfigChannelView::initTutorialProperties() +{ + if(m_channelIndex == 0) { this->setProperty("tutorial_name", "CHANNEL_WIDGET_1"); this->ui->enabledCheckBox->setProperty("tutorial_name", "CHANNEL_ENABLE_1"); this->ui->deviceOptions->setProperty("tutorial_name", "CHANNEL_DEVICE_1"); diff --git a/plugins/swiot/src/config/configchannelview.h b/plugins/swiot/src/config/configchannelview.h index 6283e3815e..e720af5616 100644 --- a/plugins/swiot/src/config/configchannelview.h +++ b/plugins/swiot/src/config/configchannelview.h @@ -18,21 +18,21 @@ * along with this program. If not, see . */ - #ifndef CONFIGCHANNELVIEW_H #define CONFIGCHANNELVIEW_H #include "qwidget.h" + #include "ui_configchannelview.h" +#include +#include +#include #include #include -#include -#include -#include namespace scopy::swiot { -class ConfigChannelView: public QFrame +class ConfigChannelView : public QFrame { Q_OBJECT public: @@ -46,7 +46,7 @@ class ConfigChannelView: public QFrame void setSelectedDevice(const QString &selectedDevice); protected: - bool eventFilter(QObject* object, QEvent *event) override; + bool eventFilter(QObject *object, QEvent *event) override; public: const QStringList &getDeviceAvailable() const; @@ -62,10 +62,10 @@ class ConfigChannelView: public QFrame Q_SIGNALS: void enabledChanged(int channelIndex, bool enabled); - void deviceChanged(int channelIndex, const QString& device); - void functionChanged(int channelIndex, const QString& function); + void deviceChanged(int channelIndex, const QString &device); + void functionChanged(int channelIndex, const QString &function); - void showPath(int channelIndex, const QString& device); + void showPath(int channelIndex, const QString &device); void hidePaths(); private: @@ -82,6 +82,6 @@ class ConfigChannelView: public QFrame void initTutorialProperties(); }; -} +} // namespace scopy::swiot #endif // CONFIGCHANNELVIEW_H diff --git a/plugins/swiot/src/config/configcontroller.cpp b/plugins/swiot/src/config/configcontroller.cpp index 309ff2a0a3..8208972882 100644 --- a/plugins/swiot/src/config/configcontroller.cpp +++ b/plugins/swiot/src/config/configcontroller.cpp @@ -18,18 +18,16 @@ * along with this program. If not, see . */ - #include "configcontroller.h" -#include -#include #include "src/swiot_logging_categories.h" +#include +#include + using namespace scopy::swiot; -ConfigController::ConfigController(ConfigChannelView *channelView, - ConfigModel *model, - int channelId) +ConfigController::ConfigController(ConfigChannelView *channelView, ConfigModel *model, int channelId) : m_channelsView(channelView) , m_model(model) , m_channelId(channelId) @@ -38,13 +36,14 @@ ConfigController::ConfigController(ConfigChannelView *channelView, this->initChannelView(); } -ConfigController::~ConfigController() { - if (m_channelsView) { +ConfigController::~ConfigController() +{ + if(m_channelsView) { delete m_channelsView; m_channelsView = nullptr; } - if (m_model) { + if(m_model) { delete m_model; m_model = nullptr; } @@ -52,38 +51,34 @@ ConfigController::~ConfigController() { void ConfigController::connectSignalsAndSlots() { - connect(m_model, &ConfigModel::readConfigChannelEnabled, this, [=, this] (bool enabled) { - m_channelsView->setChannelEnabled(enabled); - }); - connect(m_model, &ConfigModel::readConfigChannelDevice, this, [=, this] (QString device) { + connect(m_model, &ConfigModel::readConfigChannelEnabled, this, + [=, this](bool enabled) { m_channelsView->setChannelEnabled(enabled); }); + connect(m_model, &ConfigModel::readConfigChannelDevice, this, [=, this](QString device) { m_channelsView->setSelectedDevice(device); Q_EMIT deviceReadingComplete(); }); - connect(m_model, &ConfigModel::readConfigChannelFunction, this, [=, this] (QString function) { - m_channelsView->setSelectedFunction(function); - }); - connect(m_model, &ConfigModel::readConfigChannelDeviceAvailable, this, [=, this] (QStringList devicesAvailable) { - m_channelsView->setDeviceAvailable(devicesAvailable); - }); - connect(m_model, &ConfigModel::readConfigChannelFunctionAvailable, this, [=, this] (QStringList functionsAvailable) { - m_channelsView->setFunctionAvailable(functionsAvailable); - Q_EMIT functionAvailableReadingComplete(); - }); - connect(m_model, &ConfigModel::configChannelDevice, this, [=, this] () { + connect(m_model, &ConfigModel::readConfigChannelFunction, this, + [=, this](QString function) { m_channelsView->setSelectedFunction(function); }); + connect(m_model, &ConfigModel::readConfigChannelDeviceAvailable, this, + [=, this](QStringList devicesAvailable) { m_channelsView->setDeviceAvailable(devicesAvailable); }); + connect(m_model, &ConfigModel::readConfigChannelFunctionAvailable, this, + [=, this](QStringList functionsAvailable) { + m_channelsView->setFunctionAvailable(functionsAvailable); + Q_EMIT functionAvailableReadingComplete(); + }); + connect(m_model, &ConfigModel::configChannelDevice, this, [=, this]() { Q_EMIT deviceReadingComplete(); // stop and wait for readConfigChannelDevice to finish in order to continue }); - connect(this, &ConfigController::deviceReadingComplete, this, [this] () { + connect(this, &ConfigController::deviceReadingComplete, this, [this]() { m_model->readFunctionAvailable(); // stop and wait for readConfigChannelFunctionAvailable to finish in order to continue }); - connect(this, &ConfigController::functionAvailableReadingComplete, this, [this] () { - m_model->readFunction(); - }); + connect(this, &ConfigController::functionAvailableReadingComplete, this, [this]() { m_model->readFunction(); }); - QObject::connect(m_channelsView, &ConfigChannelView::enabledChanged, this, [this] (int index, bool value) { - if (m_channelId == index) { - if (value) { + QObject::connect(m_channelsView, &ConfigChannelView::enabledChanged, this, [this](int index, bool value) { + if(m_channelId == index) { + if(value) { m_model->writeEnabled("1"); } else { m_model->writeEnabled("0"); @@ -91,18 +86,20 @@ void ConfigController::connectSignalsAndSlots() } }); - QObject::connect(m_channelsView, &ConfigChannelView::deviceChanged, this, [this] (int index, const QString& device) { - if (m_channelId == index) { - m_model->writeDevice(device); - Q_EMIT clearDrawArea(); - } - }); + QObject::connect(m_channelsView, &ConfigChannelView::deviceChanged, this, + [this](int index, const QString &device) { + if(m_channelId == index) { + m_model->writeDevice(device); + Q_EMIT clearDrawArea(); + } + }); - QObject::connect(m_channelsView, &ConfigChannelView::functionChanged, this, [this] (int index, const QString& function) { - if (m_channelId == index) { - m_model->writeFunction(function); - } - }); + QObject::connect(m_channelsView, &ConfigChannelView::functionChanged, this, + [this](int index, const QString &function) { + if(m_channelId == index) { + m_model->writeFunction(function); + } + }); } void ConfigController::initChannelView() @@ -110,5 +107,6 @@ void ConfigController::initChannelView() m_model->readEnabled(); m_model->readDeviceAvailable(); m_model->readDevice(); - // the read device function activates a sequence that also reads the "function_available" and "function" attributes + // the read device function activates a sequence that also reads the "function_available" and "function" + // attributes } diff --git a/plugins/swiot/src/config/configcontroller.h b/plugins/swiot/src/config/configcontroller.h index a939e699c9..b212edf49a 100644 --- a/plugins/swiot/src/config/configcontroller.h +++ b/plugins/swiot/src/config/configcontroller.h @@ -18,22 +18,20 @@ * along with this program. If not, see . */ - #ifndef CONFIGCONTROLLER_H #define CONFIGCONTROLLER_H #include "QObject" -#include "src/config/configchannelview.h" #include "configmodel.h" +#include "src/config/configchannelview.h" namespace scopy::swiot { -class ConfigController : public QObject { -Q_OBJECT +class ConfigController : public QObject +{ + Q_OBJECT public: - explicit ConfigController(ConfigChannelView *channelView, - ConfigModel *model, - int channelId); + explicit ConfigController(ConfigChannelView *channelView, ConfigModel *model, int channelId); ~ConfigController(); @@ -51,7 +49,6 @@ Q_OBJECT int m_channelId; }; -} - +} // namespace scopy::swiot #endif // CONFIGCONTROLLER_H diff --git a/plugins/swiot/src/config/configmodel.cpp b/plugins/swiot/src/config/configmodel.cpp index a4a38719f6..f2743201ba 100644 --- a/plugins/swiot/src/config/configmodel.cpp +++ b/plugins/swiot/src/config/configmodel.cpp @@ -18,20 +18,23 @@ * along with this program. If not, see . */ - #include "configmodel.h" + +#include "src/swiot_logging_categories.h" + #include + #include -#include "src/swiot_logging_categories.h" + #include #include using namespace scopy::swiot; -ConfigModel::ConfigModel(struct iio_device* device, int channelId, CommandQueue *commandQueue) : - m_device(device), - m_channelId(channelId), - m_commandQueue(commandQueue) +ConfigModel::ConfigModel(struct iio_device *device, int channelId, CommandQueue *commandQueue) + : m_device(device) + , m_channelId(channelId) + , m_commandQueue(commandQueue) { std::string attributePrefix = "ch" + std::to_string(m_channelId); @@ -42,160 +45,199 @@ ConfigModel::ConfigModel(struct iio_device* device, int channelId, CommandQueue m_deviceAvailableAttribute = attributePrefix + "_device_available"; } -ConfigModel::~ConfigModel() -{} +ConfigModel::~ConfigModel() {} void ConfigModel::readEnabled() { Command *enabledChnCmd = new IioDeviceAttributeRead(m_device, m_enableAttribute.c_str(), nullptr); - connect(enabledChnCmd, &scopy::Command::finished, this, [=, this] (scopy::Command* cmd) { - IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { return; } - - if (tcmd->getReturnCode() >= 0) { - char *result = tcmd->getResult(); - bool ok = false; - bool enabled = QString(result).toInt(&ok); - if (!ok) { return; } - Q_EMIT readConfigChannelEnabled(enabled); - } else { - qCritical(CAT_SWIOT_CONFIG) << "Error: could not read attribute \"enable\" on channel" << m_channelId - << "error id ->" << tcmd->getReturnCode() ; - } - }, Qt::QueuedConnection); + connect( + enabledChnCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + + if(tcmd->getReturnCode() >= 0) { + char *result = tcmd->getResult(); + bool ok = false; + bool enabled = QString(result).toInt(&ok); + if(!ok) { + return; + } + Q_EMIT readConfigChannelEnabled(enabled); + } else { + qCritical(CAT_SWIOT_CONFIG) << "Error: could not read attribute \"enable\" on channel" + << m_channelId << "error id ->" << tcmd->getReturnCode(); + } + }, + Qt::QueuedConnection); m_commandQueue->enqueue(enabledChnCmd); } -void ConfigModel::writeEnabled(const QString& enabled) +void ConfigModel::writeEnabled(const QString &enabled) { - Command *enabledChnCmd = new IioDeviceAttributeWrite(m_device, m_enableAttribute.c_str(), enabled.toStdString().c_str(), nullptr); - connect(enabledChnCmd, &scopy::Command::finished, this, [=, this](scopy::Command *cmd) { - IioDeviceAttributeWrite *tcmd = dynamic_cast(cmd); - if (!tcmd) { - return; - } - if (tcmd->getReturnCode() < 0) { - qCritical(CAT_SWIOT_CONFIG) << "Error: could not write attribute \"enable\", (" - << enabled << ") on channel" - << m_channelId << "error id ->" << tcmd->getReturnCode(); - } else { - Q_EMIT configChannelEnabled(); - } - }, Qt::QueuedConnection); + Command *enabledChnCmd = new IioDeviceAttributeWrite(m_device, m_enableAttribute.c_str(), + enabled.toStdString().c_str(), nullptr); + connect( + enabledChnCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioDeviceAttributeWrite *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + if(tcmd->getReturnCode() < 0) { + qCritical(CAT_SWIOT_CONFIG) + << "Error: could not write attribute \"enable\", (" << enabled << ") on channel" + << m_channelId << "error id ->" << tcmd->getReturnCode(); + } else { + Q_EMIT configChannelEnabled(); + } + }, + Qt::QueuedConnection); m_commandQueue->enqueue(enabledChnCmd); } void ConfigModel::readDevice() { Command *deviceChnCmd = new IioDeviceAttributeRead(m_device, m_deviceAttribute.c_str(), nullptr); - connect(deviceChnCmd, &scopy::Command::finished, this, [=, this] (scopy::Command* cmd) { - IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { return; } - - if (tcmd->getReturnCode() >= 0) { - char *result = tcmd->getResult(); - Q_EMIT readConfigChannelDevice(result); - } else { - qDebug(CAT_SWIOT_CONFIG) << "Can't read value from device on channel" << m_channelId - << "error id ->" << tcmd->getReturnCode() ; - } - }, Qt::QueuedConnection); + connect( + deviceChnCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + + if(tcmd->getReturnCode() >= 0) { + char *result = tcmd->getResult(); + Q_EMIT readConfigChannelDevice(result); + } else { + qDebug(CAT_SWIOT_CONFIG) << "Can't read value from device on channel" << m_channelId + << "error id ->" << tcmd->getReturnCode(); + } + }, + Qt::QueuedConnection); m_commandQueue->enqueue(deviceChnCmd); } -void ConfigModel::writeDevice(const QString& device) +void ConfigModel::writeDevice(const QString &device) { - Command *deviceChnCmd = new IioDeviceAttributeWrite(m_device, m_deviceAttribute.c_str(), device.toStdString().c_str(), nullptr); - connect(deviceChnCmd, &scopy::Command::finished, this, [=, this](scopy::Command *cmd) { - IioDeviceAttributeWrite *tcmd = dynamic_cast(cmd); - if (!tcmd) { - return; - } - if (tcmd->getReturnCode() < 0) { - qCritical(CAT_SWIOT_CONFIG) << "Error: could not write attribute \"device\", (" - << device << ") on channel" - << m_channelId << "error id ->" << tcmd->getReturnCode(); - } else { - Q_EMIT configChannelDevice(); - } - }, Qt::QueuedConnection); + Command *deviceChnCmd = + new IioDeviceAttributeWrite(m_device, m_deviceAttribute.c_str(), device.toStdString().c_str(), nullptr); + connect( + deviceChnCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioDeviceAttributeWrite *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + if(tcmd->getReturnCode() < 0) { + qCritical(CAT_SWIOT_CONFIG) + << "Error: could not write attribute \"device\", (" << device << ") on channel" + << m_channelId << "error id ->" << tcmd->getReturnCode(); + } else { + Q_EMIT configChannelDevice(); + } + }, + Qt::QueuedConnection); m_commandQueue->enqueue(deviceChnCmd); } void ConfigModel::readFunction() { Command *functionChnCmd = new IioDeviceAttributeRead(m_device, m_functionAttribute.c_str(), nullptr); - connect(functionChnCmd, &scopy::Command::finished, this, [=, this] (scopy::Command* cmd) { - IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { return; } - - if (tcmd->getReturnCode() >= 0) { - char *result = tcmd->getResult(); - Q_EMIT readConfigChannelFunction(result); - } else { - qCritical(CAT_SWIOT_CONFIG) << "Error: could not read attribute \"function\" on channel" - << m_channelId << "error id ->" << tcmd->getReturnCode() ; - } - }, Qt::QueuedConnection); + connect( + functionChnCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + + if(tcmd->getReturnCode() >= 0) { + char *result = tcmd->getResult(); + Q_EMIT readConfigChannelFunction(result); + } else { + qCritical(CAT_SWIOT_CONFIG) << "Error: could not read attribute \"function\" on channel" + << m_channelId << "error id ->" << tcmd->getReturnCode(); + } + }, + Qt::QueuedConnection); m_commandQueue->enqueue(functionChnCmd); } -void ConfigModel::writeFunction(const QString& function) +void ConfigModel::writeFunction(const QString &function) { - Command *functionChnCmd = new IioDeviceAttributeWrite(m_device, m_functionAttribute.c_str(), function.toStdString().c_str(), nullptr); - connect(functionChnCmd, &scopy::Command::finished, this, [=, this](scopy::Command *cmd) { - IioDeviceAttributeWrite *tcmd = dynamic_cast(cmd); - if (!tcmd) { - return; - } - if (tcmd->getReturnCode() < 0) { - qCritical(CAT_SWIOT_CONFIG) << "Error: could not write attribute \"function\", (" - << function << ") on channel" - << m_channelId << "error id ->" << tcmd->getReturnCode(); - } else { - Q_EMIT configChannelFunction(); - } - }, Qt::QueuedConnection); + Command *functionChnCmd = new IioDeviceAttributeWrite(m_device, m_functionAttribute.c_str(), + function.toStdString().c_str(), nullptr); + connect( + functionChnCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioDeviceAttributeWrite *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + if(tcmd->getReturnCode() < 0) { + qCritical(CAT_SWIOT_CONFIG) + << "Error: could not write attribute \"function\", (" << function + << ") on channel" << m_channelId << "error id ->" << tcmd->getReturnCode(); + } else { + Q_EMIT configChannelFunction(); + } + }, + Qt::QueuedConnection); m_commandQueue->enqueue(functionChnCmd); } void ConfigModel::readDeviceAvailable() { - Command *deviceAvailableChnCmd = new IioDeviceAttributeRead(m_device, m_deviceAvailableAttribute.c_str(), nullptr); - connect(deviceAvailableChnCmd, &scopy::Command::finished, this, [=, this] (scopy::Command* cmd) { - IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { return; } - - if (tcmd->getReturnCode() >= 0) { - char *result = tcmd->getResult(); - QStringList resultList = QStringList(QString(result).split(" ")); - Q_EMIT readConfigChannelDeviceAvailable(resultList); - } else { - qCritical(CAT_SWIOT_CONFIG) << "Error: could not read attribute \"function available\" on channel" - << m_channelId << "error id ->" << tcmd->getReturnCode(); - } - }, Qt::QueuedConnection); + Command *deviceAvailableChnCmd = + new IioDeviceAttributeRead(m_device, m_deviceAvailableAttribute.c_str(), nullptr); + connect( + deviceAvailableChnCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + + if(tcmd->getReturnCode() >= 0) { + char *result = tcmd->getResult(); + QStringList resultList = QStringList(QString(result).split(" ")); + Q_EMIT readConfigChannelDeviceAvailable(resultList); + } else { + qCritical(CAT_SWIOT_CONFIG) + << "Error: could not read attribute \"function available\" on channel" + << m_channelId << "error id ->" << tcmd->getReturnCode(); + } + }, + Qt::QueuedConnection); m_commandQueue->enqueue(deviceAvailableChnCmd); } void ConfigModel::readFunctionAvailable() { - Command *functionAvailableChnCmd = new IioDeviceAttributeRead(m_device, m_functionAvailableAttribute.c_str(), nullptr); - connect(functionAvailableChnCmd, &scopy::Command::finished, this, [=, this] (scopy::Command* cmd) { - IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { return; } - - if (tcmd->getReturnCode() >= 0) { - char *result = tcmd->getResult(); - QStringList resultList = QStringList(QString(result).split(" ")); - Q_EMIT readConfigChannelFunctionAvailable(resultList); - } else { - qCritical(CAT_SWIOT_CONFIG) << "Error: could not read attribute \"device available\" on channel" - << m_channelId << "error id ->" << tcmd->getReturnCode(); - } - }, Qt::QueuedConnection); + Command *functionAvailableChnCmd = + new IioDeviceAttributeRead(m_device, m_functionAvailableAttribute.c_str(), nullptr); + connect( + functionAvailableChnCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + + if(tcmd->getReturnCode() >= 0) { + char *result = tcmd->getResult(); + QStringList resultList = QStringList(QString(result).split(" ")); + Q_EMIT readConfigChannelFunctionAvailable(resultList); + } else { + qCritical(CAT_SWIOT_CONFIG) + << "Error: could not read attribute \"device available\" on channel" + << m_channelId << "error id ->" << tcmd->getReturnCode(); + } + }, + Qt::QueuedConnection); m_commandQueue->enqueue(functionAvailableChnCmd); } - - - diff --git a/plugins/swiot/src/config/configmodel.h b/plugins/swiot/src/config/configmodel.h index 66ed74eafd..5014b18c47 100644 --- a/plugins/swiot/src/config/configmodel.h +++ b/plugins/swiot/src/config/configmodel.h @@ -18,35 +18,38 @@ * along with this program. If not, see . */ - #ifndef CONFIGMODEL_H #define CONFIGMODEL_H #include "qobject.h" + #include -#include + #include +#include -extern "C"{ -struct iio_channel; -struct iio_device; +extern "C" +{ + struct iio_channel; + struct iio_device; } namespace scopy::swiot { -class ConfigModel : public QObject { +class ConfigModel : public QObject +{ Q_OBJECT public: - explicit ConfigModel(struct iio_device* device, int channelId, CommandQueue *m_commandQueue); + explicit ConfigModel(struct iio_device *device, int channelId, CommandQueue *m_commandQueue); ~ConfigModel(); void readEnabled(); - void writeEnabled(const QString& enabled); + void writeEnabled(const QString &enabled); void readDevice(); - void writeDevice(const QString& device); + void writeDevice(const QString &device); void readFunction(); - void writeFunction(const QString& function); + void writeFunction(const QString &function); void readDeviceAvailable(); void readFunctionAvailable(); @@ -62,7 +65,7 @@ class ConfigModel : public QObject { void configChannelFunction(); private: - struct iio_device* m_device; + struct iio_device *m_device; int m_channelId; std::string m_enableAttribute; @@ -76,5 +79,5 @@ class ConfigModel : public QObject { QStringList m_availableFunctions; CommandQueue *m_commandQueue; }; -} +} // namespace scopy::swiot #endif // CONFIGMODEL_H diff --git a/plugins/swiot/src/config/drawarea.cpp b/plugins/swiot/src/config/drawarea.cpp index c836c0f057..cf88d9af78 100644 --- a/plugins/swiot/src/config/drawarea.cpp +++ b/plugins/swiot/src/config/drawarea.cpp @@ -18,32 +18,32 @@ * along with this program. If not, see . */ - #include "drawarea.h" + +#include "src/swiot_logging_categories.h" + +#include +#include +#include #include #include -#include -#include -#include #include -#include - -#include "src/swiot_logging_categories.h" +#include using namespace scopy::swiot; -DrawArea::DrawArea(QWidget *parent) : - QWidget(parent), - m_filePath(":/swiot/swiot_board.svg"), - m_drawLabel(new QLabel(this)), - m_baseImage(new QImage(m_filePath)), - m_connectionsMap(new QMap, QPixmap *>()) +DrawArea::DrawArea(QWidget *parent) + : QWidget(parent) + , m_filePath(":/swiot/swiot_board.svg") + , m_drawLabel(new QLabel(this)) + , m_baseImage(new QImage(m_filePath)) + , m_connectionsMap(new QMap, QPixmap *>()) { this->setLayout(new QVBoxLayout(this)); this->setStyleSheet("background-color: black;"); // insert, for each channel, the 2 PixMaps, one for ad74413r and one for max14906 - for (int i = 1; i <= 4; ++i) { + for(int i = 1; i <= 4; ++i) { m_connectionsMap->insert({i, AD74413R}, new QPixmap(":/swiot/ad74413r_channel" + QString::number(i) + ".png")); m_connectionsMap->insert({i, MAX14906}, @@ -56,17 +56,17 @@ DrawArea::DrawArea(QWidget *parent) : this->layout()->addWidget(m_drawLabel); } -DrawArea::~DrawArea() { - delete m_connectionsMap; -} +DrawArea::~DrawArea() { delete m_connectionsMap; } -void DrawArea::activateConnection(int channelIndex, DrawArea::ChannelName channelName) { +void DrawArea::activateConnection(int channelIndex, DrawArea::ChannelName channelName) +{ QPainter painter(m_boardImage); painter.drawPixmap(0, 0, *m_connectionsMap->value(qMakePair(channelIndex, channelName))); m_drawLabel->setPixmap(QPixmap::fromImage(*m_boardImage)); } -void DrawArea::deactivateConnections() { +void DrawArea::deactivateConnections() +{ m_boardImage = new QImage(*m_baseImage); m_drawLabel->setPixmap(QPixmap::fromImage(*m_baseImage)); } diff --git a/plugins/swiot/src/config/drawarea.h b/plugins/swiot/src/config/drawarea.h index 29c45870b0..c761cfce09 100644 --- a/plugins/swiot/src/config/drawarea.h +++ b/plugins/swiot/src/config/drawarea.h @@ -18,24 +18,25 @@ * along with this program. If not, see . */ - #ifndef TOOL_LAUNCHER_DRAWAREA_H #define TOOL_LAUNCHER_DRAWAREA_H -#include #include #include +#include namespace scopy::swiot { -class DrawArea : public QWidget { -Q_OBJECT +class DrawArea : public QWidget +{ + Q_OBJECT public: explicit DrawArea(QWidget *parent = nullptr); ~DrawArea() override; - enum ChannelName : int { + enum ChannelName : int + { AD74413R = 0, MAX14906 = 1 }; @@ -53,6 +54,6 @@ Q_OBJECT // channel-device pairs QMap, QPixmap *> *m_connectionsMap; }; -} +} // namespace scopy::swiot -#endif //TOOL_LAUNCHER_DRAWAREA_H +#endif // TOOL_LAUNCHER_DRAWAREA_H diff --git a/plugins/swiot/src/config/swiotconfig.cpp b/plugins/swiot/src/config/swiotconfig.cpp index 66976a4f64..2bc0a4f9c0 100644 --- a/plugins/swiot/src/config/swiotconfig.cpp +++ b/plugins/swiot/src/config/swiotconfig.cpp @@ -18,33 +18,36 @@ * along with this program. If not, see . */ - #include "swiotconfig.h" -#include + #include "configcontroller.h" #include "configmodel.h" -#include -#include #include "src/swiot_logging_categories.h" -#include + +#include + #include +#include + +#include +#include using namespace scopy::swiot; -SwiotConfig::SwiotConfig(struct iio_context *ctx, QWidget *parent) : - QWidget(parent), - m_context(ctx), - m_drawArea(nullptr), - m_scrollArea(nullptr), - m_toolView(nullptr), - m_mainView(new QWidget(this)), - m_statusLabel(new QLabel(this)), - m_statusContainer(new QWidget(this)), - m_commandQueue(CommandQueueProvider::GetInstance()->open(ctx)), - ui(new Ui::ConfigMenu) +SwiotConfig::SwiotConfig(struct iio_context *ctx, QWidget *parent) + : QWidget(parent) + , m_context(ctx) + , m_drawArea(nullptr) + , m_scrollArea(nullptr) + , m_toolView(nullptr) + , m_mainView(new QWidget(this)) + , m_statusLabel(new QLabel(this)) + , m_statusContainer(new QWidget(this)) + , m_commandQueue(CommandQueueProvider::GetInstance()->open(ctx)) + , ui(new Ui::ConfigMenu) { m_swiotDevice = iio_context_find_device(ctx, "swiot"); - if (m_swiotDevice == nullptr) { + if(m_swiotDevice == nullptr) { qCritical(CAT_SWIOT_CONFIG) << "Critical error: the \"swiot\" device was not found."; } @@ -62,15 +65,16 @@ SwiotConfig::SwiotConfig(struct iio_context *ctx, QWidget *parent) : SwiotConfig::~SwiotConfig() { - if (m_commandQueue) { + if(m_commandQueue) { CommandQueueProvider::GetInstance()->close(m_context); m_commandQueue = nullptr; m_context = nullptr; } } -void SwiotConfig::init() { - for (int i = 0; i < 4; i++) { // there can only be 4 channels +void SwiotConfig::init() +{ + for(int i = 0; i < 4; i++) { // there can only be 4 channels auto *channelView = new ConfigChannelView(i); auto *configModel = new ConfigModel(m_swiotDevice, i, m_commandQueue); auto *configController = new ConfigController(channelView, configModel, i); @@ -79,36 +83,36 @@ void SwiotConfig::init() { QObject::connect(channelView, &ConfigChannelView::showPath, this, [this, i](int channelIndex, const QString &deviceName) { - if (channelIndex == i) { + if(channelIndex == i) { m_drawArea->activateConnection(channelIndex + 1, (deviceName == "ad74413r") - ? DrawArea::AD74413R - : DrawArea::MAX14906); + ? DrawArea::AD74413R + : DrawArea::MAX14906); } }); - QObject::connect(channelView, &ConfigChannelView::hidePaths, this, [this]() { - m_drawArea->deactivateConnections(); - }); + QObject::connect(channelView, &ConfigChannelView::hidePaths, this, + [this]() { m_drawArea->deactivateConnections(); }); - QObject::connect(configController, &ConfigController::clearDrawArea, this, [this]() { - m_drawArea->deactivateConnections(); - }); + QObject::connect(configController, &ConfigController::clearDrawArea, this, + [this]() { m_drawArea->deactivateConnections(); }); } } -void SwiotConfig::setDevices(iio_context *ctx) { +void SwiotConfig::setDevices(iio_context *ctx) +{ ssize_t devicesNumber = iio_context_get_devices_count(ctx); - for (int i = 0; i < devicesNumber; i++) { + for(int i = 0; i < devicesNumber; i++) { struct iio_device *iioDev = iio_context_get_device(ctx, i); - if (iioDev) { + if(iioDev) { QString deviceName = QString(iio_device_get_name(iioDev)); m_iioDevices[deviceName] = iioDev; } } } -QPushButton *SwiotConfig::createConfigBtn() { +QPushButton *SwiotConfig::createConfigBtn() +{ auto *configBtn = new QPushButton(); configBtn->setObjectName(QString::fromUtf8("configBtn")); configBtn->setLayoutDirection(Qt::RightToLeft); @@ -129,18 +133,17 @@ QPushButton *SwiotConfig::createConfigBtn() { return configBtn; } -void SwiotConfig::onConfigBtnPressed() { - Q_EMIT writeModeAttribute("runtime"); -} +void SwiotConfig::onConfigBtnPressed() { Q_EMIT writeModeAttribute("runtime"); } void SwiotConfig::modeAttributeChanged(std::string mode) { - if (mode == "runtime") { + if(mode == "runtime") { Q_EMIT configBtnPressed(); } } -void SwiotConfig::setupToolView(QWidget *parent) { +void SwiotConfig::setupToolView(QWidget *parent) +{ scopy::gui::ToolViewRecipe recipe; recipe.helpBtnUrl = ""; recipe.hasRunBtn = false; @@ -156,7 +159,8 @@ void SwiotConfig::setupToolView(QWidget *parent) { m_scrollArea = new QScrollArea(this); } -void SwiotConfig::createPageLayout() { +void SwiotConfig::createPageLayout() +{ auto scrollWidget = new QWidget(this); m_scrollArea->setStyleSheet("background-color: black;"); scrollWidget->setLayout(new QHBoxLayout(this)); @@ -171,8 +175,8 @@ void SwiotConfig::createPageLayout() { m_statusContainer->setLayout(new QHBoxLayout(m_statusContainer)); m_statusContainer->layout()->setSpacing(0); m_statusContainer->layout()->setContentsMargins(0, 0, 0, 0); - m_statusContainer->setStyleSheet( - "QWidget{color: #ffc904; background-color: rgba(0, 0, 0, 60); border: 1px solid rgba(0, 0, 0, 30); font-size: 11pt}"); + m_statusContainer->setStyleSheet("QWidget{color: #ffc904; background-color: rgba(0, 0, 0, 60); border: 1px " + "solid rgba(0, 0, 0, 30); font-size: 11pt}"); auto exclamationButton = new QPushButton(m_statusContainer); exclamationButton->setIcon(QIcon::fromTheme(":/swiot/warning.svg")); @@ -183,7 +187,7 @@ void SwiotConfig::createPageLayout() { m_statusContainer->layout()->addWidget(m_statusLabel); m_mainView->setLayout(new QVBoxLayout(m_mainView)); - m_mainView->layout()->setContentsMargins(0,0,0,0); + m_mainView->layout()->setContentsMargins(0, 0, 0, 0); m_mainView->layout()->addWidget(m_scrollArea); m_toolView->addPlotInfoWidget(m_statusContainer); @@ -192,8 +196,9 @@ void SwiotConfig::createPageLayout() { this->layout()->addWidget(m_toolView); } -void SwiotConfig::externalPowerSupply(bool ps) { - if (ps) { +void SwiotConfig::externalPowerSupply(bool ps) +{ + if(ps) { m_statusContainer->hide(); } else { m_statusContainer->show(); @@ -201,7 +206,8 @@ void SwiotConfig::externalPowerSupply(bool ps) { } } -void SwiotConfig::initTutorialProperties() { +void SwiotConfig::initTutorialProperties() +{ m_configBtn->setProperty("tutorial_name", "APPLY_BUTTON"); m_drawArea->setProperty("tutorial_name", "DRAW_AREA"); } diff --git a/plugins/swiot/src/config/swiotconfig.h b/plugins/swiot/src/config/swiotconfig.h index bb2e58802a..d3f4f8309d 100644 --- a/plugins/swiot/src/config/swiotconfig.h +++ b/plugins/swiot/src/config/swiotconfig.h @@ -18,32 +18,34 @@ * along with this program. If not, see . */ - #ifndef SWIOTCONFIG_H #define SWIOTCONFIG_H #define AD_NAME "ad74413r" #define MAX_NAME "max14906" -#include #include "configcontroller.h" +#include "src/config/drawarea.h" + #include "ui_swiotconfig.h" -#include -#include + #include +#include #include -#include "src/config/drawarea.h" +#include +#include -extern "C"{ -struct iio_context; -struct iio_device; -struct iio_channel; +extern "C" +{ + struct iio_context; + struct iio_device; + struct iio_channel; } namespace scopy::swiot { -class SwiotConfig: public QWidget +class SwiotConfig : public QWidget { Q_OBJECT public: @@ -60,30 +62,30 @@ public Q_SLOTS: void configBtnPressed(); private: - QMap m_iioDevices; - struct iio_context* m_context; - struct iio_device* m_swiotDevice; - - QVector m_controllers; - QVector m_funcAvailable; - QPushButton* m_configBtn; - scopy::gui::ToolView* m_toolView; + QMap m_iioDevices; + struct iio_context *m_context; + struct iio_device *m_swiotDevice; + + QVector m_controllers; + QVector m_funcAvailable; + QPushButton *m_configBtn; + scopy::gui::ToolView *m_toolView; CommandQueue *m_commandQueue; - DrawArea* m_drawArea; - QScrollArea* m_scrollArea; - QWidget* m_mainView; - QLabel* m_statusLabel; - QWidget* m_statusContainer; - Ui::ConfigMenu* ui; + DrawArea *m_drawArea; + QScrollArea *m_scrollArea; + QWidget *m_mainView; + QLabel *m_statusLabel; + QWidget *m_statusContainer; + Ui::ConfigMenu *ui; void initTutorialProperties(); - void setupToolView(QWidget* parent); + void setupToolView(QWidget *parent); void init(); - void createPageLayout(); - void setDevices(struct iio_context* ctx); - static QPushButton* createConfigBtn(); + void createPageLayout(); + void setDevices(struct iio_context *ctx); + static QPushButton *createConfigBtn(); }; -} +} // namespace scopy::swiot #endif // SWIOTCONFIG_H diff --git a/plugins/swiot/src/externalpsreaderthread.cpp b/plugins/swiot/src/externalpsreaderthread.cpp index 7d6d0a70a7..0fab230ad4 100644 --- a/plugins/swiot/src/externalpsreaderthread.cpp +++ b/plugins/swiot/src/externalpsreaderthread.cpp @@ -18,62 +18,69 @@ * along with this program. If not, see . */ - #include "externalpsreaderthread.h" -#include + +#include "src/swiot_logging_categories.h" + #include +#include #include -#include "src/swiot_logging_categories.h" #include using namespace scopy::swiot; -ExternalPsReaderThread::ExternalPsReaderThread(QString uri, QString attr, QObject* parent) +ExternalPsReaderThread::ExternalPsReaderThread(QString uri, QString attr, QObject *parent) : QThread(parent) , m_uri(uri) , m_attribute(attr) -{ -} +{} -void ExternalPsReaderThread::run() { +void ExternalPsReaderThread::run() +{ iio_context *ctx = ContextProvider::GetInstance()->open(m_uri); - if (!ctx) { + if(!ctx) { return; } - if (isInterruptionRequested()) { + if(isInterruptionRequested()) { ContextProvider::GetInstance()->close(m_uri); return; } CommandQueue *commandQueue = CommandQueueProvider::GetInstance()->open(ctx); - if (!commandQueue) { + if(!commandQueue) { ContextProvider::GetInstance()->close(m_uri); return; } iio_device *swiotDevice = iio_context_find_device(ctx, "swiot"); - if (swiotDevice) { - IioDeviceAttributeRead *iioAttrRead = new IioDeviceAttributeRead(swiotDevice, m_attribute.toStdString().c_str(), nullptr, true); + if(swiotDevice) { + IioDeviceAttributeRead *iioAttrRead = + new IioDeviceAttributeRead(swiotDevice, m_attribute.toStdString().c_str(), nullptr, true); - connect(iioAttrRead, &scopy::Command::finished, this, [=, this](scopy::Command *cmd) { - IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { + connect( + iioAttrRead, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + CommandQueueProvider::GetInstance()->close(ctx); + ContextProvider::GetInstance()->close(m_uri); + return; + } + if(tcmd->getReturnCode() >= 0) { + char *extPsu = tcmd->getResult(); + bool ok = false; + bool extPsuValue = QString(extPsu).toInt(&ok); + if(ok) { + Q_EMIT hasConnectedPowerSupply(extPsuValue); + } + } else { + qCritical(CAT_SWIOT) << "Error, could not read ext_psu attribute from swiot " + "device, error code" + << tcmd->getReturnCode(); + } CommandQueueProvider::GetInstance()->close(ctx); ContextProvider::GetInstance()->close(m_uri); - return; - } - if (tcmd->getReturnCode() >= 0) { - char *extPsu = tcmd->getResult(); - bool ok = false; - bool extPsuValue = QString(extPsu).toInt(&ok); - if (ok) { - Q_EMIT hasConnectedPowerSupply(extPsuValue); - } - } else { - qCritical(CAT_SWIOT) << "Error, could not read ext_psu attribute from swiot device, error code" << tcmd->getReturnCode(); - } - CommandQueueProvider::GetInstance()->close(ctx); - ContextProvider::GetInstance()->close(m_uri); - }, Qt::QueuedConnection); + }, + Qt::QueuedConnection); commandQueue->enqueue(iioAttrRead); } else { diff --git a/plugins/swiot/src/externalpsreaderthread.h b/plugins/swiot/src/externalpsreaderthread.h index 163f292b17..c2c44ec467 100644 --- a/plugins/swiot/src/externalpsreaderthread.h +++ b/plugins/swiot/src/externalpsreaderthread.h @@ -18,17 +18,17 @@ * along with this program. If not, see . */ - #ifndef SCOPY_EXTERNALPSREADERTHREAD_H #define SCOPY_EXTERNALPSREADERTHREAD_H #include namespace scopy::swiot { -class ExternalPsReaderThread : public QThread { +class ExternalPsReaderThread : public QThread +{ Q_OBJECT public: - explicit ExternalPsReaderThread(QString uri, QString attr, QObject* parent = nullptr); + explicit ExternalPsReaderThread(QString uri, QString attr, QObject *parent = nullptr); void run() override; Q_SIGNALS: @@ -37,8 +37,7 @@ class ExternalPsReaderThread : public QThread { private: QString m_uri; QString m_attribute; - }; -} // scopy::swiot +} // namespace scopy::swiot -#endif //SCOPY_EXTERNALPSREADERTHREAD_H +#endif // SCOPY_EXTERNALPSREADERTHREAD_H diff --git a/plugins/swiot/src/runtime/ad74413r/ad74413r.cpp b/plugins/swiot/src/runtime/ad74413r/ad74413r.cpp index fc6f3bf931..8dccff0924 100644 --- a/plugins/swiot/src/runtime/ad74413r/ad74413r.cpp +++ b/plugins/swiot/src/runtime/ad74413r/ad74413r.cpp @@ -18,33 +18,38 @@ * along with this program. If not, see . */ - #include "ad74413r.h" -#include -#include -#include "buffermenuview.h" + #include "buffermenumodel.h" -#include -#include +#include "buffermenuview.h" #include "src/swiot_logging_categories.h" +#include + +#include +#include +#include + using namespace scopy; using namespace scopy::swiot; -Ad74413r::Ad74413r(iio_context *ctx, ToolMenuEntry *tme, QWidget* parent): - QWidget(parent) - , m_tme(tme), m_statusLabel(new QLabel(this)) - , m_swiotAdLogic(nullptr), m_widget(this) - , m_readerThread(nullptr), m_statusContainer(new QWidget(this)) - , m_ctx(ctx) - , m_cmdQueue(CommandQueueProvider::GetInstance()->open(ctx)) - , m_currentChannelSelected(0) +Ad74413r::Ad74413r(iio_context *ctx, ToolMenuEntry *tme, QWidget *parent) + : QWidget(parent) + , m_tme(tme) + , m_statusLabel(new QLabel(this)) + , m_swiotAdLogic(nullptr) + , m_widget(this) + , m_readerThread(nullptr) + , m_statusContainer(new QWidget(this)) + , m_ctx(ctx) + , m_cmdQueue(CommandQueueProvider::GetInstance()->open(ctx)) + , m_currentChannelSelected(0) { createDevicesMap(m_ctx); - if (m_iioDevicesMap.contains(AD_NAME) && m_iioDevicesMap.contains(SWIOT_DEVICE_NAME)) { + if(m_iioDevicesMap.contains(AD_NAME) && m_iioDevicesMap.contains(SWIOT_DEVICE_NAME)) { char mode[64]; ssize_t result = iio_device_attr_read(m_iioDevicesMap[SWIOT_DEVICE_NAME], "mode", mode, 64); - if ((result >= 0) && (strcmp(mode, "runtime") == 0)) { + if((result >= 0) && (strcmp(mode, "runtime") == 0)) { m_backBtn = createBackBtn(); m_enabledChannels = std::vector(MAX_CURVES_NUMBER, false); @@ -59,7 +64,8 @@ Ad74413r::Ad74413r(iio_context *ctx, ToolMenuEntry *tme, QWidget* parent): QMap chnlsId = m_swiotAdLogic->getPlotChnlsId(); m_plotHandler->setHandlesName(chnlsId); - gui::GenericMenu *settingsMenu = createSettingsMenu("General settings", new QColor(0x4a, 0x64, 0xff)); + gui::GenericMenu *settingsMenu = + createSettingsMenu("General settings", new QColor(0x4a, 0x64, 0xff)); setupToolView(settingsMenu); setupConnections(); m_swiotAdLogic->readChnlsSamplingFreqAvailableAttr(); @@ -73,14 +79,14 @@ Ad74413r::Ad74413r(iio_context *ctx, ToolMenuEntry *tme, QWidget* parent): Ad74413r::~Ad74413r() { - if (m_readerThread) { + if(m_readerThread) { m_readerThread->forcedStop(); delete m_readerThread; } - if (m_controllers.size() > 0) { + if(m_controllers.size() > 0) { m_controllers.clear(); } - if (m_cmdQueue) { + if(m_cmdQueue) { CommandQueueProvider::GetInstance()->close(m_ctx); m_cmdQueue = nullptr; m_ctx = nullptr; @@ -111,8 +117,9 @@ void Ad74413r::setupToolView(gui::GenericMenu *settingsMenu) m_statusContainer->setLayout(new QHBoxLayout(m_statusContainer)); m_statusContainer->layout()->setSpacing(0); - m_statusContainer->layout()->setContentsMargins(0,0,0,0); - m_statusContainer->setStyleSheet("QWidget{color: #ffc904; background-color: rgba(0, 0, 0, 60); border: 1px solid rgba(0, 0, 0, 30); font-size: 11pt}"); + m_statusContainer->layout()->setContentsMargins(0, 0, 0, 0); + m_statusContainer->setStyleSheet("QWidget{color: #ffc904; background-color: rgba(0, 0, 0, 60); border: 1px " + "solid rgba(0, 0, 0, 30); font-size: 11pt}"); auto exclamationButton = new QPushButton(m_statusContainer); exclamationButton->setIcon(QIcon::fromTheme(":/swiot/warning.svg")); @@ -135,36 +142,42 @@ void Ad74413r::setupConnections() connect(m_swiotAdLogic, &BufferLogic::chnlsChanged, m_readerThread, &ReaderThread::onChnlsChange); connect(this, &Ad74413r::activateRunBtns, this, &Ad74413r::onActivateRunBtns); - connect(m_monitorChannelManager, &scopy::gui::ChannelManager::enabledChannel, this, &Ad74413r::onChannelWidgetEnabled); + connect(m_monitorChannelManager, &scopy::gui::ChannelManager::enabledChannel, this, + &Ad74413r::onChannelWidgetEnabled); connect(this, &Ad74413r::channelWidgetEnabled, m_plotHandler, &BufferPlotHandler::onChannelWidgetEnabled); - connect(m_readerThread, &ReaderThread::bufferRefilled, m_plotHandler, &BufferPlotHandler::onBufferRefilled, Qt::QueuedConnection); - connect(m_readerThread, &ReaderThread::readerThreadFinished, this, &Ad74413r::onReaderThreadFinished, Qt::QueuedConnection); + connect(m_readerThread, &ReaderThread::bufferRefilled, m_plotHandler, &BufferPlotHandler::onBufferRefilled, + Qt::QueuedConnection); + connect(m_readerThread, &ReaderThread::readerThreadFinished, this, &Ad74413r::onReaderThreadFinished, + Qt::QueuedConnection); connect(m_toolView->getSingleBtn(), &QPushButton::toggled, this, &Ad74413r::onSingleBtnPressed); connect(m_plotHandler, &BufferPlotHandler::singleCaptureFinished, this, &Ad74413r::onSingleCaptureFinished); - connect(m_swiotAdLogic, &BufferLogic::samplingFreqRead, m_plotHandler, &BufferPlotHandler::onSamplingFreqWritten); + connect(m_swiotAdLogic, &BufferLogic::samplingFreqRead, m_plotHandler, + &BufferPlotHandler::onSamplingFreqWritten); connect(m_swiotAdLogic, &BufferLogic::samplingFreqRead, m_readerThread, &ReaderThread::onSamplingFreqWritten); connect(m_swiotAdLogic, &BufferLogic::channelFunctionDetermined, this, &Ad74413r::initChannelToolView); - connect(m_swiotAdLogic, &BufferLogic::samplingFreqRead, this, [=, this] (int sampFreq) { - if (m_samplingFreqOptions->currentText() != QString::number(sampFreq)) { + connect(m_swiotAdLogic, &BufferLogic::samplingFreqRead, this, [=, this](int sampFreq) { + if(m_samplingFreqOptions->currentText() != QString::number(sampFreq)) { m_samplingFreqOptions->setCurrentText(QString::number(sampFreq)); } }); - connect(m_swiotAdLogic, &BufferLogic::samplingFreqAvailableRead, this, [=, this] (QStringList availableFreq) { - m_samplingFreqOptions->addItems(availableFreq); - }); + connect(m_swiotAdLogic, &BufferLogic::samplingFreqAvailableRead, this, + [=, this](QStringList availableFreq) { m_samplingFreqOptions->addItems(availableFreq); }); connect(m_swiotAdLogic, &BufferLogic::instantValueChanged, m_plotHandler, &BufferPlotHandler::setInstantValue); - connect(m_timespanSpin, &PositionSpinButton::valueChanged, m_plotHandler, &BufferPlotHandler::onTimespanChanged); - connect(m_samplingFreqOptions, QOverload::of(&QComboBox::currentIndexChanged), m_swiotAdLogic, &BufferLogic::onSamplingFreqChanged); + connect(m_timespanSpin, &PositionSpinButton::valueChanged, m_plotHandler, + &BufferPlotHandler::onTimespanChanged); + connect(m_samplingFreqOptions, QOverload::of(&QComboBox::currentIndexChanged), m_swiotAdLogic, + &BufferLogic::onSamplingFreqChanged); connect(m_tme, &ToolMenuEntry::runToggled, m_toolView->getRunBtn(), &QPushButton::setChecked); connect(m_plotHandler, &BufferPlotHandler::offsetHandleSelected, this, &Ad74413r::onOffsetHdlSelected); - connect(m_monitorChannelManager, &scopy::gui::ChannelManager::selectedChannel, this, &Ad74413r::onChannelWidgetSelected); + connect(m_monitorChannelManager, &scopy::gui::ChannelManager::selectedChannel, this, + &Ad74413r::onChannelWidgetSelected); connect(this, &Ad74413r::channelWidgetSelected, m_plotHandler, &BufferPlotHandler::onChannelWidgetSelected); connect(m_toolView->getPrintBtn(), &QPushButton::clicked, m_plotHandler, &BufferPlotHandler::onPrintBtnClicked); @@ -172,56 +185,62 @@ void Ad74413r::setupConnections() void Ad74413r::initChannelToolView(unsigned int i, QString function) { - if (function.compare("no_config") != 0) { + if(function.compare("no_config") != 0) { bool enabled = (function.compare("diagnostic") != 0); int nextColorId = m_monitorChannelManager->getChannelsCount(); - QString menuTitle(((QString(AD_NAME).toUpper() + " - Channel ") + QString::number(i+1)) + (": " + function)); + QString menuTitle(((QString(AD_NAME).toUpper() + " - Channel ") + QString::number(i + 1)) + + (": " + function)); BufferMenuView *menu = new BufferMenuView(this); - //the curves id is in the range (0, chnlsNumber - 1) and the chnlsWidgets id is in the range (1, chnlsNumber) - //that's why we have to decrease by 1 + // the curves id is in the range (0, chnlsNumber - 1) and the chnlsWidgets id is in the range (1, + // chnlsNumber) that's why we have to decrease by 1 QString unit = m_swiotAdLogic->getPlotChnlUnitOfMeasure(i); auto yRange = m_swiotAdLogic->getPlotChnlRangeValues(i); m_plotHandler->addChannelScale(i, m_plotHandler->getCurveColor(nextColorId), unit, enabled); - menu->init(menuTitle, function, new QColor(m_plotHandler->getCurveColor(nextColorId)), - unit, yRange.first, yRange.second); + menu->init(menuTitle, function, new QColor(m_plotHandler->getCurveColor(nextColorId)), unit, + yRange.first, yRange.second); m_plotHandler->mapChannelCurveId(nextColorId, i); - QMap chnlsMap = m_swiotAdLogic->getIioChnl(i); - BufferMenuModel* swiotModel = new BufferMenuModel(chnlsMap, m_cmdQueue); - BufferMenuController* controller = new BufferMenuController(menu, swiotModel, i); + QMap chnlsMap = m_swiotAdLogic->getIioChnl(i); + BufferMenuModel *swiotModel = new BufferMenuModel(chnlsMap, m_cmdQueue); + BufferMenuController *controller = new BufferMenuController(menu, swiotModel, i); - if (controller) { + if(controller) { m_controllers.push_back(controller); } - QString chnlWidgetName(function + " " + QString::number(i+1)); - //the curves id is in the range (0, chnlsNumber - 1) and the chnlsWidgets id is in the range (1, chnlsNumber) - //that's why we have to decrease by 1 - ChannelWidget *chWidget = - m_toolView->buildNewChannel(m_monitorChannelManager, menu, false, -1, false, false, - m_plotHandler->getCurveColor(nextColorId), chnlWidgetName, chnlWidgetName); + QString chnlWidgetName(function + " " + QString::number(i + 1)); + // the curves id is in the range (0, chnlsNumber - 1) and the chnlsWidgets id is in the range (1, + // chnlsNumber) that's why we have to decrease by 1 + ChannelWidget *chWidget = m_toolView->buildNewChannel(m_monitorChannelManager, menu, false, -1, false, + false, m_plotHandler->getCurveColor(nextColorId), + chnlWidgetName, chnlWidgetName); chWidget->setIsPhysicalChannel(true); controller->createConnections(); m_channelWidgetList.push_back(chWidget); - if (!enabled) { + if(!enabled) { chWidget->enableButton()->setChecked(false); } - connect(controller, &BufferMenuController::setUnitPerDivision, m_plotHandler, &BufferPlotHandler::setUnitPerDivision); - connect(m_plotHandler, &BufferPlotHandler::unitPerDivisionChanged, controller, &BufferMenuController::unitPerDivisionChanged); - - connect(controller, &BufferMenuController::diagnosticFunctionUpdated, this, &Ad74413r::onDiagnosticFunctionUpdated); - connect(controller, SIGNAL(broadcastThresholdReadForward(QString)), this, SIGNAL(broadcastReadThreshold(QString))); - connect(this, SIGNAL(broadcastReadThreshold(QString)), controller, SIGNAL(broadcastThresholdReadBackward(QString))); - connect(this, &Ad74413r::thresholdControlEnable, controller, &BufferMenuController::thresholdControlEnable); + connect(controller, &BufferMenuController::setUnitPerDivision, m_plotHandler, + &BufferPlotHandler::setUnitPerDivision); + connect(m_plotHandler, &BufferPlotHandler::unitPerDivisionChanged, controller, + &BufferMenuController::unitPerDivisionChanged); + + connect(controller, &BufferMenuController::diagnosticFunctionUpdated, this, + &Ad74413r::onDiagnosticFunctionUpdated); + connect(controller, SIGNAL(broadcastThresholdReadForward(QString)), this, + SIGNAL(broadcastReadThreshold(QString))); + connect(this, SIGNAL(broadcastReadThreshold(QString)), controller, + SIGNAL(broadcastThresholdReadBackward(QString))); + connect(this, &Ad74413r::thresholdControlEnable, controller, + &BufferMenuController::thresholdControlEnable); } m_currentChannelSelected++; - if (m_currentChannelSelected == 4) { + if(m_currentChannelSelected == 4) { m_swiotAdLogic->initDiagnosticChannels(); - } - if (m_currentChannelSelected == MAX_INPUT_CHNLS_NO) { + if(m_currentChannelSelected == MAX_INPUT_CHNLS_NO) { m_monitorChannelManager->getChannelAt(0)->nameButton()->click(); } } @@ -232,50 +251,42 @@ void Ad74413r::initExportSettings(QWidget *parent) m_exportSettings = new ExportSettings(parent); m_exportSettings->enableExportButton(false); - for (int i = 0; i < plotChnlsNo; i++){ - m_exportSettings->addChannel(i, QString("Channel") + - QString::number(i+1)); + for(int i = 0; i < plotChnlsNo; i++) { + m_exportSettings->addChannel(i, QString("Channel") + QString::number(i + 1)); } - connect(m_exportSettings->getExportButton(), &QPushButton::clicked, this, [=, this](){ - Q_EMIT exportBtnClicked(m_exportSettings->getExportConfig()); - }); + connect(m_exportSettings->getExportButton(), &QPushButton::clicked, this, + [=, this]() { Q_EMIT exportBtnClicked(m_exportSettings->getExportConfig()); }); connect(this, &Ad74413r::exportBtnClicked, m_plotHandler, &BufferPlotHandler::onBtnExportClicked); - connect(this, &Ad74413r::activateExportButton, - [=, this](){ - m_exportSettings->enableExportButton(true); - }); + connect(this, &Ad74413r::activateExportButton, [=, this]() { m_exportSettings->enableExportButton(true); }); } -scopy::gui::GenericMenu* Ad74413r::createSettingsMenu(QString title, QColor* color) +scopy::gui::GenericMenu *Ad74413r::createSettingsMenu(QString title, QColor *color) { scopy::gui::GenericMenu *menu = new scopy::gui::GenericMenu(this); menu->initInteractiveMenu(); - menu->setMenuHeader(title,color,false); + menu->setMenuHeader(title, color, false); auto *generalSubsection = new scopy::gui::SubsectionSeparator("ACQUISITION SETTINGS", false, this); generalSubsection->getLabel()->setStyleSheet("color:gray;"); generalSubsection->layout()->setSpacing(10); generalSubsection->getContentWidget()->layout()->setSpacing(10); - //channels sampling freq + // channels sampling freq auto *samplingFreqLayout = new QHBoxLayout(); m_samplingFreqOptions = new QComboBox(generalSubsection->getContentWidget()); - samplingFreqLayout->addWidget(new QLabel("Sampling frequency",generalSubsection->getContentWidget())); + samplingFreqLayout->addWidget(new QLabel("Sampling frequency", generalSubsection->getContentWidget())); samplingFreqLayout->addWidget(m_samplingFreqOptions); - //plot timespan + // plot timespan auto *timespanLayout = new QHBoxLayout(); - m_timespanSpin = new PositionSpinButton({ - {"ms",1E-3}, - {"s", 1E0}}, - "Timespan",0.1,10, - true, false, generalSubsection->getContentWidget()); + m_timespanSpin = new PositionSpinButton({{"ms", 1E-3}, {"s", 1E0}}, "Timespan", 0.1, 10, true, false, + generalSubsection->getContentWidget()); m_timespanSpin->setStep(0.1); m_timespanSpin->setValue(1); timespanLayout->addWidget(m_timespanSpin); - //export section + // export section auto *exportLayout = new QHBoxLayout(); initExportSettings(generalSubsection->getContentWidget()); @@ -294,16 +305,15 @@ void Ad74413r::onChannelWidgetEnabled(int chnWidgetId, bool en) int id = chnWidgetId; int chnlIdx = m_controllers[id]->getChnlIdx(); - if (en) { + if(en) { m_enabledChannels[chnlIdx] = true; verifyChnlsChanges(); - } - else { + } else { m_enabledChannels[chnlIdx] = false; verifyChnlsChanges(); } - if (std::find(m_enabledChannels.begin(), m_enabledChannels.end(), true) == m_enabledChannels.end()) { + if(std::find(m_enabledChannels.begin(), m_enabledChannels.end(), true) == m_enabledChannels.end()) { Q_EMIT activateRunBtns(false); } else { @@ -315,7 +325,9 @@ void Ad74413r::onChannelWidgetEnabled(int chnWidgetId, bool en) void Ad74413r::onChannelWidgetSelected(int chnWidgetId, bool en) { - if (!en) { return; } + if(!en) { + return; + } int id = chnWidgetId; Q_EMIT channelWidgetSelected(id); @@ -323,8 +335,8 @@ void Ad74413r::onChannelWidgetSelected(int chnWidgetId, bool en) void Ad74413r::onOffsetHdlSelected(int hdlIdx, bool selected) { - for (int i = 0; i < m_channelWidgetList.size(); i++) { - if (m_channelWidgetList[i] != nullptr) { + for(int i = 0; i < m_channelWidgetList.size(); i++) { + if(m_channelWidgetList[i] != nullptr) { m_channelWidgetList[i]->nameButton()->setChecked(i == hdlIdx); } } @@ -332,11 +344,11 @@ void Ad74413r::onOffsetHdlSelected(int hdlIdx, bool selected) void Ad74413r::onActivateRunBtns(bool enable) { - if (!enable) { - if (m_toolView->getRunBtn()->isChecked()) { + if(!enable) { + if(m_toolView->getRunBtn()->isChecked()) { m_toolView->getRunBtn()->setChecked(false); } - if (m_toolView->getSingleBtn()->isChecked()) { + if(m_toolView->getSingleBtn()->isChecked()) { m_toolView->getSingleBtn()->setChecked(false); } m_toolView->getRunBtn()->setEnabled(false); @@ -353,24 +365,24 @@ void Ad74413r::onRunBtnPressed(bool toggled) { Q_EMIT activateExportButton(); Q_EMIT thresholdControlEnable(!toggled); - if (toggled) { + if(toggled) { m_toolView->getSingleBtn()->setChecked(false); m_toolView->getSingleBtn()->setEnabled(false); m_samplingFreqOptions->setEnabled(false); verifyChnlsChanges(); - if (!m_readerThread->isRunning()) { + if(!m_readerThread->isRunning()) { m_plotHandler->setSingleCapture(false); m_plotHandler->resetPlotParameters(); m_readerThread->startCapture(); } - if (!m_tme->running()) { + if(!m_tme->running()) { m_tme->setRunning(toggled); } } else { m_toolView->getSingleBtn()->setEnabled(true); m_samplingFreqOptions->setEnabled(true); m_readerThread->requestStop(); - if (m_tme->running()) { + if(m_tme->running()) { m_tme->setRunning(toggled); } } @@ -379,15 +391,15 @@ void Ad74413r::onRunBtnPressed(bool toggled) void Ad74413r::onSingleBtnPressed(bool toggled) { bool runBtnChecked = m_toolView->getRunBtn()->isChecked(); - if (toggled) { + if(toggled) { Q_EMIT activateExportButton(); Q_EMIT thresholdControlEnable(toggled); verifyChnlsChanges(); - if (runBtnChecked) { + if(runBtnChecked) { m_toolView->getRunBtn()->setChecked(false); } m_plotHandler->setSingleCapture(true); - if (!m_readerThread->isRunning()) { + if(!m_readerThread->isRunning()) { m_plotHandler->resetPlotParameters(); int bufNumber = m_plotHandler->getRequiredBuffersNumber(); m_readerThread->startCapture(bufNumber); @@ -399,8 +411,8 @@ void Ad74413r::onSingleBtnPressed(bool toggled) void Ad74413r::onSingleCaptureFinished() { bool runBtnChecked = m_toolView->getRunBtn()->isChecked(); - if (!runBtnChecked) { - if (m_tme->running()) { + if(!runBtnChecked) { + if(m_tme->running()) { m_tme->setRunning(false); } Q_EMIT thresholdControlEnable(true); @@ -414,7 +426,7 @@ void Ad74413r::onSingleCaptureFinished() void Ad74413r::verifyChnlsChanges() { bool changes = m_swiotAdLogic->verifyChannelsEnabledChanges(m_enabledChannels); - if (changes) { + if(changes) { m_readerThread->requestStop(); m_swiotAdLogic->applyChannelsEnabledChanges(m_enabledChannels); } @@ -423,21 +435,20 @@ void Ad74413r::verifyChnlsChanges() void Ad74413r::createDevicesMap(iio_context *ctx) { int devicesCount = iio_context_get_devices_count(ctx); - for (int i = 0; i < devicesCount; i++) { - struct iio_device* iioDev = iio_context_get_device(ctx, i); - if (iioDev) { + for(int i = 0; i < devicesCount; i++) { + struct iio_device *iioDev = iio_context_get_device(ctx, i); + if(iioDev) { QString deviceName = QString(iio_device_get_name(iioDev)); - if ((deviceName.compare(AD_NAME) && deviceName.compare(SWIOT_DEVICE_NAME)) == 0) - { + if((deviceName.compare(AD_NAME) && deviceName.compare(SWIOT_DEVICE_NAME)) == 0) { m_iioDevicesMap[deviceName] = iioDev; } } } } -QPushButton* Ad74413r::createBackBtn() +QPushButton *Ad74413r::createBackBtn() { - QPushButton* backBtn = new QPushButton(this); + QPushButton *backBtn = new QPushButton(this); backBtn->setObjectName(QString::fromUtf8("backBtn")); backBtn->setLayoutDirection(Qt::RightToLeft); backBtn->setStyleSheet(QString::fromUtf8("QPushButton{\n" @@ -461,13 +472,13 @@ QPushButton* Ad74413r::createBackBtn() void Ad74413r::onReaderThreadFinished() { bool singleCaptureOn = m_plotHandler->singleCapture(); - if (singleCaptureOn) { + if(singleCaptureOn) { m_plotHandler->setSingleCapture(false); } int nbRequiredBuffers = 0; - if (m_toolView->getRunBtn()->isChecked() || !m_toolView->getSingleBtn()->isEnabled()) { + if(m_toolView->getRunBtn()->isChecked() || !m_toolView->getSingleBtn()->isEnabled()) { m_plotHandler->resetPlotParameters(); - if (m_toolView->getSingleBtn()->isChecked()) { + if(m_toolView->getSingleBtn()->isChecked()) { m_plotHandler->setSingleCapture(true); nbRequiredBuffers = m_plotHandler->getRequiredBuffersNumber(); } @@ -475,8 +486,9 @@ void Ad74413r::onReaderThreadFinished() } } -void Ad74413r::externalPowerSupply(bool ps) { - if (ps) { +void Ad74413r::externalPowerSupply(bool ps) +{ + if(ps) { m_statusContainer->hide(); } else { m_statusContainer->show(); @@ -496,7 +508,8 @@ void Ad74413r::onBackBtnPressed() Q_EMIT backBtnPressed(); } -void Ad74413r::initTutorialProperties() { +void Ad74413r::initTutorialProperties() +{ // initialize components that might be used for the AD74413R tutorial m_plotHandler->getPlotWidget()->setProperty("tutorial_name", "AD74413R_PLOT"); m_toolView->getSingleBtn()->setProperty("tutorial_name", "SINGLE_BUTTON"); diff --git a/plugins/swiot/src/runtime/ad74413r/ad74413r.h b/plugins/swiot/src/runtime/ad74413r/ad74413r.h index f5097f9c84..2645bc4a51 100644 --- a/plugins/swiot/src/runtime/ad74413r/ad74413r.h +++ b/plugins/swiot/src/runtime/ad74413r/ad74413r.h @@ -18,30 +18,33 @@ * along with this program. If not, see . */ - #ifndef AD74413R_H #define AD74413R_H -#include -#include #include "bufferlogic.h" +#include "buffermenucontroller.h" +#include "bufferplothandler.h" #include "pluginbase/toolmenuentry.h" #include "src/runtime/readerthread.h" -#include "buffermenucontroller.h" + +#include + +#include +#include + #include #include -#include -#include "bufferplothandler.h" -#include +#include #define MAX_CURVES_NUMBER 8 #define AD_NAME "ad74413r" #define SWIOT_DEVICE_NAME "swiot" -extern "C"{ -struct iio_device; -struct iio_channel; -struct iio_buffer; +extern "C" +{ + struct iio_device; + struct iio_channel; + struct iio_buffer; } namespace scopy { @@ -50,11 +53,11 @@ class GenericMenu; } namespace swiot { -class Ad74413r : public QWidget { +class Ad74413r : public QWidget +{ Q_OBJECT public: - explicit Ad74413r(iio_context *ctx = nullptr, ToolMenuEntry *tme = 0, - QWidget *parent = nullptr); + explicit Ad74413r(iio_context *ctx = nullptr, ToolMenuEntry *tme = 0, QWidget *parent = nullptr); ~Ad74413r(); @@ -98,6 +101,7 @@ public Q_SLOTS: void backBtnPressed(); private Q_SLOTS: void onBackBtnPressed(); + private: void setupToolView(gui::GenericMenu *settingsMenu); @@ -105,12 +109,12 @@ private Q_SLOTS: void setupConnections(); - QPushButton* createBackBtn(); + QPushButton *createBackBtn(); void initTutorialProperties(); private: - QMap m_iioDevicesMap; + QMap m_iioDevicesMap; int m_enabledChnlsNo = 0; int m_currentChannelSelected; @@ -118,14 +122,14 @@ private Q_SLOTS: scopy::gui::ToolView *m_toolView; QWidget *m_widget; QPushButton *m_backBtn; - QLabel* m_statusLabel; - QWidget* m_statusContainer; + QLabel *m_statusLabel; + QWidget *m_statusContainer; ToolMenuEntry *m_tme; QVector m_controllers; std::vector m_enabledChannels; - std::vector m_channelWidgetList; + std::vector m_channelWidgetList; BufferLogic *m_swiotAdLogic; ReaderThread *m_readerThread; @@ -138,6 +142,6 @@ private Q_SLOTS: struct iio_context *m_ctx; }; -} -} +} // namespace swiot +} // namespace scopy #endif // AD74413R_H diff --git a/plugins/swiot/src/runtime/ad74413r/bufferlogic.cpp b/plugins/swiot/src/runtime/ad74413r/bufferlogic.cpp index 6541f87c09..89961e9ead 100644 --- a/plugins/swiot/src/runtime/ad74413r/bufferlogic.cpp +++ b/plugins/swiot/src/runtime/ad74413r/bufferlogic.cpp @@ -18,30 +18,31 @@ * along with this program. If not, see . */ - #include "bufferlogic.h" + +#include "chnlinfobuilder.h" #include "src/runtime/ad74413r/ad74413r.h" #include "src/swiot_logging_categories.h" -#include "chnlinfobuilder.h" -#include + #include +#include #include using namespace scopy::swiot; -BufferLogic::BufferLogic(QMap devicesMap, CommandQueue *commandQueue) +BufferLogic::BufferLogic(QMap devicesMap, CommandQueue *commandQueue) : m_plotChnlsNo(0) , m_iioDevicesMap(devicesMap) , m_commandQueue(commandQueue) { - if (m_iioDevicesMap.contains(AD_NAME) && m_iioDevicesMap.contains(SWIOT_DEVICE_NAME)) { + if(m_iioDevicesMap.contains(AD_NAME) && m_iioDevicesMap.contains(SWIOT_DEVICE_NAME)) { createChannels(); } } BufferLogic::~BufferLogic() { - if (m_chnlsInfo.size() > 0) { + if(m_chnlsInfo.size() > 0) { qDeleteAll(m_chnlsInfo); m_chnlsInfo.clear(); } @@ -54,37 +55,36 @@ void BufferLogic::createChannels() int plotChnlsNo = 0; int chnlIdx = -1; const QRegExp rx("[^0-9]+"); - for (int i = 0; i < chnlsNumber; i++) { - struct iio_channel* iioChnl = iio_device_get_channel(m_iioDevicesMap[AD_NAME], i); + for(int i = 0; i < chnlsNumber; i++) { + struct iio_channel *iioChnl = iio_device_get_channel(m_iioDevicesMap[AD_NAME], i); QString chnlId(iio_channel_get_id(iioChnl)); QString chnlName(iio_channel_get_name(iioChnl)); ChnlInfo *channelInfo = ChnlInfoBuilder::build(iioChnl, chnlId[0].toLower(), m_commandQueue); - const auto&& parts = chnlId.split(rx); + const auto &&parts = chnlId.split(rx); chnlIdx = -1; - plotChnlsNo = (!channelInfo->isOutput() && channelInfo->isScanElement()) ? (plotChnlsNo + 1) : plotChnlsNo; - if (parts.size() <= 1) { + plotChnlsNo = (!channelInfo->isOutput() && channelInfo->isScanElement()) ? (plotChnlsNo + 1) + : plotChnlsNo; + if(parts.size() <= 1) { continue; } - if(parts[1].compare("")){ + if(parts[1].compare("")) { chnlIdx = parts[1].toInt(); chnlIdx = (channelInfo->isOutput()) ? (chnlIdx + MAX_INPUT_CHNLS_NO) : chnlIdx; } m_chnlsInfo[chnlIdx] = channelInfo; - connect(channelInfo, &ChnlInfo::instantValueChanged, this, [=, this](double value) { - Q_EMIT instantValueChanged(chnlIdx, value); - }); + connect(channelInfo, &ChnlInfo::instantValueChanged, this, + [=, this](double value) { Q_EMIT instantValueChanged(chnlIdx, value); }); } m_plotChnlsNo = plotChnlsNo; } - } bool BufferLogic::verifyChannelsEnabledChanges(std::vector enabledChnls) { bool changes = false; - for (int i = 0; i < enabledChnls.size(); i++) { - if (m_chnlsInfo.contains(i)) { - if (enabledChnls[i] != m_chnlsInfo[i]->isEnabled()) { + for(int i = 0; i < enabledChnls.size(); i++) { + if(m_chnlsInfo.contains(i)) { + if(enabledChnls[i] != m_chnlsInfo[i]->isEnabled()) { changes = true; break; } @@ -95,9 +95,9 @@ bool BufferLogic::verifyChannelsEnabledChanges(std::vector enabledChnls) void BufferLogic::applyChannelsEnabledChanges(std::vector enabledChnls) { - for (int i = 0; i < enabledChnls.size(); i++) { - if (m_chnlsInfo.contains(i)) { - if (enabledChnls[i] != m_chnlsInfo[i]->isEnabled()) { + for(int i = 0; i < enabledChnls.size(); i++) { + if(m_chnlsInfo.contains(i)) { + if(enabledChnls[i] != m_chnlsInfo[i]->isEnabled()) { m_chnlsInfo[i]->setIsEnabled(enabledChnls[i]); } } @@ -109,22 +109,26 @@ void BufferLogic::onSamplingFreqChanged(int idx) { std::string newSamplingFreq = m_samplingFreqAvailable[idx].toStdString(); - if (!m_chnlsInfo.size()) { + if(!m_chnlsInfo.size()) { return; } Command *writeSrCmd = new IioChannelAttributeWrite(m_chnlsInfo.first()->iioChnl(), SAMPLING_FREQ_ATTR_NAME, - newSamplingFreq.c_str(), nullptr); - connect(writeSrCmd, &scopy::Command::finished, this, [=, this](scopy::Command *cmd) { - IioChannelAttributeWrite *tcmd = dynamic_cast(cmd); - if (!tcmd) { - return; - } - if (tcmd->getReturnCode() < 0) { - qDebug(CAT_SWIOT_AD74413R) << "Chnl attribute write error " + QString::number(tcmd->getReturnCode()); - } else { - readChnlsSamplingFreqAttr(); - } - }, Qt::QueuedConnection); + newSamplingFreq.c_str(), nullptr); + connect( + writeSrCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioChannelAttributeWrite *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + if(tcmd->getReturnCode() < 0) { + qDebug(CAT_SWIOT_AD74413R) + << "Chnl attribute write error " + QString::number(tcmd->getReturnCode()); + } else { + readChnlsSamplingFreqAttr(); + } + }, + Qt::QueuedConnection); m_commandQueue->enqueue(writeSrCmd); } @@ -132,28 +136,32 @@ void BufferLogic::readChnlsSamplingFreqAvailableAttr() { std::string s_attrName = "sampling_frequency_available"; - if (!m_chnlsInfo.size()) { + if(!m_chnlsInfo.size()) { return; } - Command *readSrCommand = new IioChannelAttributeRead(m_chnlsInfo.first()->iioChnl(), s_attrName.c_str(), nullptr); - connect(readSrCommand, &scopy::Command::finished, - this, [=, this](scopy::Command* cmd) { - IioChannelAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { - return; - } - QStringList attrValues; - char *sr_available = tcmd->getResult(); - - if (tcmd->getReturnCode() < 0) { - qDebug(CAT_SWIOT_AD74413R) << "Chnl attribute read error " + QString::number(tcmd->getReturnCode()); - } else { - QString bufferValues(sr_available); - m_samplingFreqAvailable = bufferValues.split(" "); - m_samplingFreqAvailable.removeAll(""); - Q_EMIT samplingFreqAvailableRead(m_samplingFreqAvailable); - } - }, Qt::QueuedConnection); + Command *readSrCommand = + new IioChannelAttributeRead(m_chnlsInfo.first()->iioChnl(), s_attrName.c_str(), nullptr); + connect( + readSrCommand, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioChannelAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + QStringList attrValues; + char *sr_available = tcmd->getResult(); + + if(tcmd->getReturnCode() < 0) { + qDebug(CAT_SWIOT_AD74413R) + << "Chnl attribute read error " + QString::number(tcmd->getReturnCode()); + } else { + QString bufferValues(sr_available); + m_samplingFreqAvailable = bufferValues.split(" "); + m_samplingFreqAvailable.removeAll(""); + Q_EMIT samplingFreqAvailableRead(m_samplingFreqAvailable); + } + }, + Qt::QueuedConnection); m_commandQueue->enqueue(readSrCommand); } @@ -161,44 +169,46 @@ void BufferLogic::readChnlsSamplingFreqAttr() { std::string s_attrName = "sampling_frequency"; - if (!m_chnlsInfo.size()) { + if(!m_chnlsInfo.size()) { return; } - Command *readSrCommand = new IioChannelAttributeRead(m_chnlsInfo.first()->iioChnl(), s_attrName.c_str(), nullptr); - connect(readSrCommand, &scopy::Command::finished, - this, [=, this](scopy::Command* cmd) { - IioChannelAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { - return; - } - QStringList attrValues; - char *srAttrValueStr = tcmd->getResult(); - - if (tcmd->getReturnCode() < 0) { - qDebug(CAT_SWIOT_AD74413R) << "Chnl attribute read error " + QString::number(tcmd->getReturnCode()); - } else { - try { - int samplingFreq = std::stoi(srAttrValueStr); - Q_EMIT samplingFreqRead(samplingFreq); - } catch (std::invalid_argument& exception) { - qDebug(CAT_SWIOT_AD74413R) << "Chnl attribute read error conversion: " + QString(srAttrValueStr); + Command *readSrCommand = + new IioChannelAttributeRead(m_chnlsInfo.first()->iioChnl(), s_attrName.c_str(), nullptr); + connect( + readSrCommand, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioChannelAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; } - } - }, Qt::QueuedConnection); + QStringList attrValues; + char *srAttrValueStr = tcmd->getResult(); + + if(tcmd->getReturnCode() < 0) { + qDebug(CAT_SWIOT_AD74413R) + << "Chnl attribute read error " + QString::number(tcmd->getReturnCode()); + } else { + try { + int samplingFreq = std::stoi(srAttrValueStr); + Q_EMIT samplingFreqRead(samplingFreq); + } catch(std::invalid_argument &exception) { + qDebug(CAT_SWIOT_AD74413R) + << "Chnl attribute read error conversion: " + QString(srAttrValueStr); + } + } + }, + Qt::QueuedConnection); m_commandQueue->enqueue(readSrCommand); } -int BufferLogic::getPlotChnlsNo() -{ - return m_plotChnlsNo; -} +int BufferLogic::getPlotChnlsNo() { return m_plotChnlsNo; } QString BufferLogic::getPlotChnlUnitOfMeasure(int channel) { QString unit = ""; ChnlInfo *chnlInfo = m_chnlsInfo[channel]; - if (chnlInfo) { - if (chnlInfo->isScanElement() && !chnlInfo->isOutput()) { + if(chnlInfo) { + if(chnlInfo->isScanElement() && !chnlInfo->isOutput()) { unit = chnlInfo->unitOfMeasure(); } } @@ -209,8 +219,8 @@ QVector BufferLogic::getPlotChnlsUnitOfMeasure() { QVector chnlsUnitOfMeasure; - for (ChnlInfo* chnl : qAsConst(m_chnlsInfo)) { - if (chnl->isScanElement() && !chnl->isOutput()) { + for(ChnlInfo *chnl : qAsConst(m_chnlsInfo)) { + if(chnl->isScanElement() && !chnl->isOutput()) { QString unitOfMeasure = chnl->unitOfMeasure(); chnlsUnitOfMeasure.push_back(unitOfMeasure); } @@ -222,8 +232,8 @@ std::pair BufferLogic::getPlotChnlRangeValues(int channel) { std::pair range = {0, 0}; ChnlInfo *chnlInfo = m_chnlsInfo[channel]; - if (chnlInfo) { - if (chnlInfo->isScanElement() && !chnlInfo->isOutput()) { + if(chnlInfo) { + if(chnlInfo->isScanElement() && !chnlInfo->isOutput()) { range = chnlInfo->rangeValues(); } } @@ -233,8 +243,8 @@ std::pair BufferLogic::getPlotChnlRangeValues(int channel) QVector> BufferLogic::getPlotChnlsRangeValues() { QVector> chnlsRangeValues; - for (ChnlInfo* chnl : qAsConst(m_chnlsInfo)) { - if (chnl->isScanElement() && !chnl->isOutput()) { + for(ChnlInfo *chnl : qAsConst(m_chnlsInfo)) { + if(chnl->isScanElement() && !chnl->isOutput()) { std::pair rangeValues = chnl->rangeValues(); chnlsRangeValues.push_back(rangeValues); } @@ -246,8 +256,8 @@ QMap BufferLogic::getPlotChnlsId() { QMap chnlsId; auto keys = m_chnlsInfo.keys(); - for (int key : keys){ - if (m_chnlsInfo[key]->isScanElement() && !m_chnlsInfo[key]->isOutput()) { + for(int key : keys) { + if(m_chnlsInfo[key]->isScanElement() && !m_chnlsInfo[key]->isOutput()) { QString chnlId = m_chnlsInfo[key]->chnlId(); chnlsId[key] = chnlId; } @@ -258,8 +268,8 @@ QMap BufferLogic::getPlotChnlsId() void BufferLogic::initAd74413rChnlsFunctions() { -// on the SWIOT board we have only 4 channels - for (int i = 0; i < 4; ++i) { + // on the SWIOT board we have only 4 channels + for(int i = 0; i < 4; ++i) { initChannelFunction(i); } } @@ -268,7 +278,7 @@ void BufferLogic::initDiagnosticChannels() { // The last 4 channels from context are always the diagnostic channels // (they are not physically on the board) - for (int i = 4; i < MAX_INPUT_CHNLS_NO; i++) { + for(int i = 4; i < MAX_INPUT_CHNLS_NO; i++) { Q_EMIT channelFunctionDetermined(i, "diagnostic"); } } @@ -276,31 +286,36 @@ void BufferLogic::initDiagnosticChannels() void BufferLogic::initChannelFunction(unsigned int i) { std::string chnlEnableAttribute = "ch" + std::to_string(i) + "_enable"; - Command *enabledChnCmd = new IioDeviceAttributeRead(m_iioDevicesMap[SWIOT_DEVICE_NAME], - chnlEnableAttribute.c_str(), nullptr); - connect(enabledChnCmd, &scopy::Command::finished, this, [=, this] (scopy::Command* cmd) { - enabledChnCmdFinished(i, cmd); - }, Qt::QueuedConnection); + Command *enabledChnCmd = + new IioDeviceAttributeRead(m_iioDevicesMap[SWIOT_DEVICE_NAME], chnlEnableAttribute.c_str(), nullptr); + connect( + enabledChnCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { enabledChnCmdFinished(i, cmd); }, Qt::QueuedConnection); m_commandQueue->enqueue(enabledChnCmd); } void BufferLogic::enabledChnCmdFinished(unsigned int i, scopy::Command *cmd) { - IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { return; } + IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } - if (tcmd->getReturnCode() >= 0) { + if(tcmd->getReturnCode() >= 0) { char *result = tcmd->getResult(); bool ok = false; bool enabled = QString(result).toInt(&ok); - if (!ok) { return; } - if (enabled) { + if(!ok) { + return; + } + if(enabled) { std::string deviceAttributeName = "ch" + std::to_string(i) + "_device"; Command *configuredDevCmd = new IioDeviceAttributeRead(m_iioDevicesMap[SWIOT_DEVICE_NAME], deviceAttributeName.c_str(), nullptr); - connect(configuredDevCmd, &scopy::Command::finished, this, [=, this] (scopy::Command* cmd) { - configuredDevCmdFinished(i, cmd); - }, Qt::QueuedConnection); + connect( + configuredDevCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { configuredDevCmdFinished(i, cmd); }, + Qt::QueuedConnection); m_commandQueue->enqueue(configuredDevCmd); } else { @@ -311,19 +326,22 @@ void BufferLogic::enabledChnCmdFinished(unsigned int i, scopy::Command *cmd) void BufferLogic::configuredDevCmdFinished(unsigned int i, scopy::Command *cmd) { - IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { return; } + IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } - if (tcmd->getReturnCode() >= 0) { + if(tcmd->getReturnCode() >= 0) { char *result = tcmd->getResult(); std::string device = std::string(result); - if (device == "ad74413r") { + if(device == "ad74413r") { std::string functionAttributeName = "ch" + std::to_string(i) + "_function"; Command *chnFunctionCmd = new IioDeviceAttributeRead(m_iioDevicesMap[SWIOT_DEVICE_NAME], functionAttributeName.c_str(), nullptr); - connect(chnFunctionCmd, &scopy::Command::finished, this, [=, this] (scopy::Command* cmd) { - chnFunctionCmdFinished(i, cmd); - }, Qt::QueuedConnection); + connect( + chnFunctionCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { chnFunctionCmdFinished(i, cmd); }, + Qt::QueuedConnection); m_commandQueue->enqueue(chnFunctionCmd); } else { @@ -334,30 +352,30 @@ void BufferLogic::configuredDevCmdFinished(unsigned int i, scopy::Command *cmd) void BufferLogic::chnFunctionCmdFinished(unsigned int i, scopy::Command *cmd) { - IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { return; } + IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } - if (tcmd->getReturnCode() >= 0) { + if(tcmd->getReturnCode() >= 0) { char *result = tcmd->getResult(); QString function = QString(result); Q_EMIT channelFunctionDetermined(i, function); } } -QMap BufferLogic::getIioChnl(int chnlIdx) +QMap BufferLogic::getIioChnl(int chnlIdx) { - QMap chnlsMap; + QMap chnlsMap; int outputChblIdx = chnlIdx + MAX_INPUT_CHNLS_NO; - if (m_chnlsInfo.contains(chnlIdx) && !m_chnlsInfo[chnlIdx]->isOutput()) { + if(m_chnlsInfo.contains(chnlIdx) && !m_chnlsInfo[chnlIdx]->isOutput()) { chnlsMap["input"] = m_chnlsInfo[chnlIdx]->iioChnl(); } - if (m_chnlsInfo.contains(outputChblIdx) && m_chnlsInfo[outputChblIdx]->isOutput()) { + if(m_chnlsInfo.contains(outputChblIdx) && m_chnlsInfo[outputChblIdx]->isOutput()) { chnlsMap["output"] = m_chnlsInfo[outputChblIdx]->iioChnl(); } return chnlsMap; } - - diff --git a/plugins/swiot/src/runtime/ad74413r/bufferlogic.h b/plugins/swiot/src/runtime/ad74413r/bufferlogic.h index 429e6d8d94..075dc52be2 100644 --- a/plugins/swiot/src/runtime/ad74413r/bufferlogic.h +++ b/plugins/swiot/src/runtime/ad74413r/bufferlogic.h @@ -18,25 +18,27 @@ * along with this program. If not, see . */ - #ifndef BUFFERLOGIC_H #define BUFFERLOGIC_H #include "chnlinfo.h" -#include -#include #include + +#include +#include + +#include #include #include -#include -extern "C" { -struct iio_context; -struct iio_device; -struct iio_channel; +extern "C" +{ + struct iio_context; + struct iio_device; + struct iio_channel; } -Q_DECLARE_OPAQUE_POINTER(struct iio_buffer*) +Q_DECLARE_OPAQUE_POINTER(struct iio_buffer *) namespace scopy::swiot { #define MAX_BUFFER_SIZE 160 @@ -44,14 +46,15 @@ namespace scopy::swiot { #define SAMPLING_FREQ_ATTR_NAME "sampling_frequency" #define MAX_INPUT_CHNLS_NO 8 -class BufferLogic : public QObject { +class BufferLogic : public QObject +{ Q_OBJECT public: - explicit BufferLogic(QMap devicesMap, CommandQueue *commandQueue); + explicit BufferLogic(QMap devicesMap, CommandQueue *commandQueue); ~BufferLogic(); - QMap getIioChnl(int chnlIdx); + QMap getIioChnl(int chnlIdx); bool verifyChannelsEnabledChanges(std::vector enabledChnls); void applyChannelsEnabledChanges(std::vector enabledChnls); @@ -72,7 +75,7 @@ public Q_SLOTS: void onSamplingFreqChanged(int idx); Q_SIGNALS: - void chnlsChanged(QMap chnlsInfo); + void chnlsChanged(QMap chnlsInfo); void samplingFreqWritten(int samplingFreq); void samplingFreqRead(int samplingFreq); void channelFunctionDetermined(unsigned int i, QString function); @@ -83,19 +86,19 @@ private Q_SLOTS: void enabledChnCmdFinished(unsigned int i, scopy::Command *cmd); void configuredDevCmdFinished(unsigned int i, scopy::Command *cmd); void chnFunctionCmdFinished(unsigned int i, scopy::Command *cmd); + private: void createChannels(); void initChannelFunction(unsigned int i); private: int m_plotChnlsNo; - QMap m_iioDevicesMap; + QMap m_iioDevicesMap; QStringList m_samplingFreqAvailable; QMap m_chnlsInfo; CommandQueue *m_commandQueue; }; -} - +} // namespace scopy::swiot #endif // BUFFERLOGIC_H diff --git a/plugins/swiot/src/runtime/ad74413r/buffermenu.cpp b/plugins/swiot/src/runtime/ad74413r/buffermenu.cpp index 6600f80e0e..26b6b55dc8 100644 --- a/plugins/swiot/src/runtime/ad74413r/buffermenu.cpp +++ b/plugins/swiot/src/runtime/ad74413r/buffermenu.cpp @@ -18,22 +18,20 @@ * along with this program. If not, see . */ - #include "buffermenu.h" + #include "qdebug.h" #include "qlineedit.h" using namespace scopy::swiot; BufferMenu::BufferMenu(QWidget *parent, QString chnlFunction) - : QWidget(parent), - m_widget(parent), - m_chnlFunction(chnlFunction) -{ -} - -BufferMenu::~BufferMenu() + : QWidget(parent) + , m_widget(parent) + , m_chnlFunction(chnlFunction) {} +BufferMenu::~BufferMenu() {} + void BufferMenu::init() { m_unitPerDivision->setValue(1); @@ -43,16 +41,12 @@ void BufferMenu::init() QString BufferMenu::getInfoMessage() { QString defaultMessage = "\"" + m_chnlFunction + "\" configuration generates\n" + - "a buffer capable channel which is directly\n" + - "related to the plot. The channel attributes\n" + - "can be changed through this menu."; + "a buffer capable channel which is directly\n" + "related to the plot. The channel attributes\n" + + "can be changed through this menu."; return defaultMessage; } -void BufferMenu::addMenuLayout(QBoxLayout *layout) -{ - m_menuLayers.push_back(layout); -} +void BufferMenu::addMenuLayout(QBoxLayout *layout) { m_menuLayers.push_back(layout); } void BufferMenu::setupVerticalSettingsMenu(QWidget *settingsWidget, QString unit, double yMin, double yMax) { @@ -63,42 +57,32 @@ void BufferMenu::setupVerticalSettingsMenu(QWidget *settingsWidget, QString unit m_unitPerDivision = new PositionSpinButton( { - {unit, 1e0}, - },"Unit/Div",0.1,yMax,false,false,settingsWidget); - + {unit, 1e0}, + }, + "Unit/Div", 0.1, yMax, false, false, settingsWidget); yMinMaxLayout->addWidget(m_unitPerDivision); settingsWidget->layout()->addItem(yMinMaxLayout); // Connects connect(m_unitPerDivision, &PositionSpinButton::valueChanged, this, &BufferMenu::setUnitPerDivision); - connect(this, &BufferMenu::unitPerDivisionChanged, this, [=, this] (double unitPerDiv) { + connect(this, &BufferMenu::unitPerDivisionChanged, this, [=, this](double unitPerDiv) { QSignalBlocker block(m_unitPerDivision); m_unitPerDivision->setValue(unitPerDiv); }); } -void BufferMenu::setAttrValues(QMap> values) -{ - m_attrValues=values; -} +void BufferMenu::setAttrValues(QMap> values) { m_attrValues = values; } -QMap> BufferMenu::getAttrValues() -{ - return m_attrValues; -} +QMap> BufferMenu::getAttrValues() { return m_attrValues; } -QVector BufferMenu::getMenuLayers() -{ - return m_menuLayers; -} +QVector BufferMenu::getMenuLayers() { return m_menuLayers; } double BufferMenu::convertFromRaw(int rawValue, QString chnlType) { - double value=0.0; - if (m_attrValues.contains(chnlType) - && m_attrValues[chnlType].contains("offset") - && m_attrValues[chnlType].contains("scale")) { + double value = 0.0; + if(m_attrValues.contains(chnlType) && m_attrValues[chnlType].contains("offset") && + m_attrValues[chnlType].contains("scale")) { double offset = m_attrValues[chnlType]["offset"].first().toDouble(); double scale = m_attrValues[chnlType]["scale"].first().toDouble(); value = (rawValue + offset) * scale; @@ -106,26 +90,21 @@ double BufferMenu::convertFromRaw(int rawValue, QString chnlType) return value; } -void BufferMenu::onAttrWritten(QMap > values) +void BufferMenu::onAttrWritten(QMap> values) { m_attrValues = values; Q_EMIT mapUpdated(); } -CurrentInLoopMenu::CurrentInLoopMenu(QWidget* parent, QString chnlFunction) +CurrentInLoopMenu::CurrentInLoopMenu(QWidget *parent, QString chnlFunction) : BufferMenu(parent, chnlFunction) { - //dac code + // dac code QHBoxLayout *dacCodeLayout = new QHBoxLayout(); - m_dacCodeSpinButton = new PositionSpinButton({ - {"value", 1E0} - }, - "DAC Code", 0, - 8191, - true, false, m_widget); + m_dacCodeSpinButton = new PositionSpinButton({{"value", 1E0}}, "DAC Code", 0, 8191, true, false, m_widget); dacCodeLayout->addWidget(m_dacCodeSpinButton); addMenuLayout(dacCodeLayout); - //dac label + // dac label QHBoxLayout *m_dacLabelLayout = new QHBoxLayout(); m_dacLabel = new QLabel("mA", m_widget); m_dacLabelLayout->addWidget(m_dacLabel); @@ -135,15 +114,14 @@ CurrentInLoopMenu::CurrentInLoopMenu(QWidget* parent, QString chnlFunction) connectSignalsToSlots(); } -CurrentInLoopMenu::~CurrentInLoopMenu() -{} +CurrentInLoopMenu::~CurrentInLoopMenu() {} void CurrentInLoopMenu::init() { BufferMenu::init(); (m_attrValues[OUTPUT_CHNL].contains("raw") && !m_attrValues[OUTPUT_CHNL]["raw"].isEmpty()) - ? m_dacCodeSpinButton->setValue(m_attrValues[OUTPUT_CHNL]["raw"].first().toDouble()) - : m_dacCodeSpinButton->setValue(0); + ? m_dacCodeSpinButton->setValue(m_attrValues[OUTPUT_CHNL]["raw"].first().toDouble()) + : m_dacCodeSpinButton->setValue(0); } void CurrentInLoopMenu::connectSignalsToSlots() @@ -155,50 +133,49 @@ void CurrentInLoopMenu::connectSignalsToSlots() QString CurrentInLoopMenu::getInfoMessage() { QString infoMessage = "\"" + m_chnlFunction + "\" configuration generates 2 context channels.\n" + - "One of them is an input buffer capable channel (current_in)\n" + - "which is related to the plot and the other one is an output\n" + - "channel (current_out) whose attributes can be changed from\n" + - "this menu."; + "One of them is an input buffer capable channel (current_in)\n" + + "which is related to the plot and the other one is an output\n" + + "channel (current_out) whose attributes can be changed from\n" + "this menu."; return infoMessage; } void CurrentInLoopMenu::dacCodeChanged(double value) { QString attrName("raw"); - if (!m_attrValues.contains(OUTPUT_CHNL)) { + if(!m_attrValues.contains(OUTPUT_CHNL)) { qWarning() << "There is no output channel available for this function!"; return; } m_attrValues[OUTPUT_CHNL][attrName].clear(); m_attrValues[OUTPUT_CHNL][attrName].push_back(QString::number(value)); - double val = convertFromRaw(value) ; + double val = convertFromRaw(value); m_dacLabel->clear(); - m_dacLabel->setText(QString::number(val)+" mA"); + m_dacLabel->setText(QString::number(val) + " mA"); Q_EMIT attrValuesChanged(attrName, OUTPUT_CHNL); - } void CurrentInLoopMenu::onMapUpdated() { m_dacCodeSpinButton->blockSignals(true); (m_attrValues[OUTPUT_CHNL].contains("raw") && !m_attrValues[OUTPUT_CHNL]["raw"].isEmpty()) - ? m_dacCodeSpinButton->setValue(m_attrValues[OUTPUT_CHNL]["raw"].first().toDouble()) - : m_dacCodeSpinButton->setValue(0); + ? m_dacCodeSpinButton->setValue(m_attrValues[OUTPUT_CHNL]["raw"].first().toDouble()) + : m_dacCodeSpinButton->setValue(0); m_dacCodeSpinButton->blockSignals(false); } -DigitalInLoopMenu::DigitalInLoopMenu(QWidget* parent, QString chnlFunction) +DigitalInLoopMenu::DigitalInLoopMenu(QWidget *parent, QString chnlFunction) : BufferMenu(parent, chnlFunction) { - //threshold + // threshold QVBoxLayout *thresholdLayout = new QVBoxLayout(); QRegExp regExp("([0-9]|[1-9][0-9]{1,3}|1[0-5][0-9]{3}|16000)"); QRegExpValidator *validator = new QRegExpValidator(regExp, this); m_titleLabel = new QLabel("Threshold (0 - 16000 mV)", m_widget); m_titleLabel->setStyleSheet("font-size: 14px;"); m_thresholdLineEdit = new QLineEdit(m_widget); - m_thresholdLineEdit->setStyleSheet("background: transparent; height: 20px; width: 75px; font-size: 18px; border: 0px; bottom: 10px;"); + m_thresholdLineEdit->setStyleSheet( + "background: transparent; height: 20px; width: 75px; font-size: 18px; border: 0px; bottom: 10px;"); m_thresholdLineEdit->setValidator(validator); QFrame *frame = new QFrame(m_widget); @@ -208,18 +185,13 @@ DigitalInLoopMenu::DigitalInLoopMenu(QWidget* parent, QString chnlFunction) thresholdLayout->addWidget(m_thresholdLineEdit); thresholdLayout->addWidget(frame); addMenuLayout(thresholdLayout); - //dac code + // dac code QHBoxLayout *dacCodeLayout = new QHBoxLayout(); - m_dacCodeSpinButton = new PositionSpinButton({ - {"value", 1E0} - }, - "DAC Code", 0, - 8191, - true, false, m_widget); + m_dacCodeSpinButton = new PositionSpinButton({{"value", 1E0}}, "DAC Code", 0, 8191, true, false, m_widget); dacCodeLayout->addWidget(m_dacCodeSpinButton); addMenuLayout(dacCodeLayout); - //dac label + // dac label QHBoxLayout *m_dacLabelLayout = new QHBoxLayout(); m_dacLabel = new QLabel("mA", m_widget); m_dacLabelLayout->addWidget(m_dacLabel); @@ -229,21 +201,20 @@ DigitalInLoopMenu::DigitalInLoopMenu(QWidget* parent, QString chnlFunction) connectSignalsToSlots(); } -DigitalInLoopMenu::~DigitalInLoopMenu() -{} +DigitalInLoopMenu::~DigitalInLoopMenu() {} void DigitalInLoopMenu::init() { BufferMenu::init(); (m_attrValues[INPUT_CHNL].contains("threshold") && !m_attrValues[INPUT_CHNL]["threshold"].isEmpty()) - ? m_thresholdLineEdit->setText(m_attrValues[INPUT_CHNL]["threshold"].first()), - m_thresholdLineEdit->setPlaceholderText(m_attrValues[INPUT_CHNL]["threshold"].first()) - : m_thresholdLineEdit->setText("0"), - m_thresholdLineEdit->setPlaceholderText("0"); + ? m_thresholdLineEdit->setText(m_attrValues[INPUT_CHNL]["threshold"].first()), + m_thresholdLineEdit->setPlaceholderText(m_attrValues[INPUT_CHNL]["threshold"].first()) + : m_thresholdLineEdit->setText("0"), + m_thresholdLineEdit->setPlaceholderText("0"); (m_attrValues[OUTPUT_CHNL].contains("raw") && !m_attrValues[OUTPUT_CHNL]["raw"].isEmpty()) - ? m_dacCodeSpinButton->setValue(m_attrValues[OUTPUT_CHNL]["raw"].first().toDouble()) - : m_dacCodeSpinButton->setValue(0); + ? m_dacCodeSpinButton->setValue(m_attrValues[OUTPUT_CHNL]["raw"].first().toDouble()) + : m_dacCodeSpinButton->setValue(0); } void DigitalInLoopMenu::connectSignalsToSlots() @@ -258,17 +229,17 @@ void DigitalInLoopMenu::connectSignalsToSlots() QString DigitalInLoopMenu::getInfoMessage() { QString infoMessage = "\"" + m_chnlFunction + "\" configuration generates 2 context channels.\n" + - "One of them is an input buffer capable channel (voltage_in)\n" + - "which is related to the plot and the other one is an output\n" + - "channel (current_out). The threshold is set for the\n" + - "input channel and the DAC Code for the output channel."; + "One of them is an input buffer capable channel (voltage_in)\n" + + "which is related to the plot and the other one is an output\n" + + "channel (current_out). The threshold is set for the\n" + + "input channel and the DAC Code for the output channel."; return infoMessage; } void DigitalInLoopMenu::dacCodeChanged(double value) { QString attrName("raw"); - if (!m_attrValues.contains(OUTPUT_CHNL)) { + if(!m_attrValues.contains(OUTPUT_CHNL)) { qWarning() << "There is no output channel available for this function!"; return; } @@ -279,17 +250,16 @@ void DigitalInLoopMenu::dacCodeChanged(double value) m_dacLabel->setText(QString::number(val) + " mA"); Q_EMIT attrValuesChanged(attrName, OUTPUT_CHNL); - } void DigitalInLoopMenu::thresholdChanged() { QString attrName("threshold"); - if (!m_attrValues.contains(INPUT_CHNL)) { + if(!m_attrValues.contains(INPUT_CHNL)) { qWarning() << "There is no input channel available for this function!"; return; } - if (m_attrValues[INPUT_CHNL].contains(attrName)) { + if(m_attrValues[INPUT_CHNL].contains(attrName)) { m_attrValues[INPUT_CHNL][attrName].clear(); m_attrValues[INPUT_CHNL][attrName].push_back(m_thresholdLineEdit->text()); Q_EMIT attrValuesChanged(attrName, INPUT_CHNL); @@ -301,8 +271,8 @@ void DigitalInLoopMenu::thresholdChanged() void DigitalInLoopMenu::onMapUpdated() { m_thresholdLineEdit->blockSignals(true); - if (m_attrValues[INPUT_CHNL].contains("threshold") && !m_attrValues[INPUT_CHNL]["threshold"].isEmpty()) { - if (m_attrValues[INPUT_CHNL]["threshold"].first().compare(m_thresholdLineEdit->text()) != 0 ) { + if(m_attrValues[INPUT_CHNL].contains("threshold") && !m_attrValues[INPUT_CHNL]["threshold"].isEmpty()) { + if(m_attrValues[INPUT_CHNL]["threshold"].first().compare(m_thresholdLineEdit->text()) != 0) { Q_EMIT broadcastThresholdReadForward(m_attrValues[INPUT_CHNL]["threshold"].first()); } m_thresholdLineEdit->setText(m_attrValues[INPUT_CHNL]["threshold"].first()); @@ -313,15 +283,15 @@ void DigitalInLoopMenu::onMapUpdated() m_thresholdLineEdit->blockSignals(false); m_dacCodeSpinButton->blockSignals(true); (m_attrValues[OUTPUT_CHNL].contains("raw") && !m_attrValues[OUTPUT_CHNL]["raw"].isEmpty()) - ? m_dacCodeSpinButton->setValue(m_attrValues[OUTPUT_CHNL]["raw"].first().toDouble()) - : m_dacCodeSpinButton->setValue(0); + ? m_dacCodeSpinButton->setValue(m_attrValues[OUTPUT_CHNL]["raw"].first().toDouble()) + : m_dacCodeSpinButton->setValue(0); m_dacCodeSpinButton->blockSignals(false); } void DigitalInLoopMenu::onBroadcastThresholdRead(QString value) { m_thresholdLineEdit->blockSignals(true); - if (value.compare(m_thresholdLineEdit->text()) != 0 ) { + if(value.compare(m_thresholdLineEdit->text()) != 0) { m_thresholdLineEdit->setText(value); m_thresholdLineEdit->setPlaceholderText(value); m_attrValues[INPUT_CHNL]["threshold"].first() = value; @@ -329,31 +299,23 @@ void DigitalInLoopMenu::onBroadcastThresholdRead(QString value) m_thresholdLineEdit->blockSignals(false); } -void DigitalInLoopMenu::onThresholdControlEnable(bool enabled) -{ - m_thresholdLineEdit->setEnabled(enabled); -} +void DigitalInLoopMenu::onThresholdControlEnable(bool enabled) { m_thresholdLineEdit->setEnabled(enabled); } -VoltageOutMenu::VoltageOutMenu(QWidget* parent, QString chnlFunction) +VoltageOutMenu::VoltageOutMenu(QWidget *parent, QString chnlFunction) : BufferMenu(parent, chnlFunction) { - //dac code + // dac code QHBoxLayout *dacCodeLayout = new QHBoxLayout(); - m_dacCodeSpinButton = new PositionSpinButton({ - {"value", 1E0} - }, - "DAC Code", 0, - 8191, - true, false, m_widget); + m_dacCodeSpinButton = new PositionSpinButton({{"value", 1E0}}, "DAC Code", 0, 8191, true, false, m_widget); dacCodeLayout->addWidget(m_dacCodeSpinButton); addMenuLayout(dacCodeLayout); - //dac label + // dac label QHBoxLayout *m_dacLabelLayout = new QHBoxLayout(); m_dacLabel = new QLabel("V", m_widget); m_dacLabelLayout->addWidget(m_dacLabel); m_dacLabelLayout->setAlignment(Qt::AlignRight); addMenuLayout(m_dacLabelLayout); - //slew + // slew QHBoxLayout *slewLayout = new QHBoxLayout(); m_slewOptions = new QComboBox(m_widget); m_slewOptions->addItem(QString("Disable")); @@ -362,14 +324,14 @@ VoltageOutMenu::VoltageOutMenu(QWidget* parent, QString chnlFunction) slewLayout->addWidget(new QLabel("Slew", m_widget), 1); slewLayout->addWidget(m_slewOptions, 1); addMenuLayout(slewLayout); - //slew step + // slew step QHBoxLayout *slewStepLayout = new QHBoxLayout(); m_slewStepOptions = new QComboBox(m_widget); slewStepLayout->addWidget(new QLabel("Slew Step Size", m_widget), 1); slewStepLayout->addWidget(m_slewStepOptions, 1); addMenuLayout(slewStepLayout); - //slew rate + // slew rate QHBoxLayout *slewRateLayout = new QHBoxLayout(); m_slewRateOptions = new QComboBox(m_widget); @@ -380,8 +342,7 @@ VoltageOutMenu::VoltageOutMenu(QWidget* parent, QString chnlFunction) connectSignalsToSlots(); } -VoltageOutMenu::~VoltageOutMenu() -{} +VoltageOutMenu::~VoltageOutMenu() {} void VoltageOutMenu::init() { @@ -390,51 +351,53 @@ void VoltageOutMenu::init() setAvailableOptions(m_slewRateOptions, "slew_rate_available"); (m_attrValues[OUTPUT_CHNL].contains("raw") && !m_attrValues[OUTPUT_CHNL]["raw"].isEmpty()) - ? m_dacCodeSpinButton->setValue(m_attrValues[OUTPUT_CHNL]["raw"].first().toDouble()) - : m_dacCodeSpinButton->setValue(0); + ? m_dacCodeSpinButton->setValue(m_attrValues[OUTPUT_CHNL]["raw"].first().toDouble()) + : m_dacCodeSpinButton->setValue(0); - if (m_attrValues[OUTPUT_CHNL].contains("slew_en") && !m_attrValues[OUTPUT_CHNL]["slew_en"].isEmpty()) { + if(m_attrValues[OUTPUT_CHNL].contains("slew_en") && !m_attrValues[OUTPUT_CHNL]["slew_en"].isEmpty()) { (m_attrValues[OUTPUT_CHNL]["slew_en"].first().compare("0") == 0) - ? m_slewOptions->setCurrentText("Disable") - : m_slewOptions->setCurrentText("Enable"); + ? m_slewOptions->setCurrentText("Disable") + : m_slewOptions->setCurrentText("Enable"); } (m_attrValues[OUTPUT_CHNL].contains("slew_step") && !m_attrValues[OUTPUT_CHNL]["slew_step"].isEmpty()) - ? m_slewStepOptions->setCurrentText(m_attrValues[OUTPUT_CHNL]["slew_step"].first()) - : m_slewStepOptions->setCurrentText("ERROR"); + ? m_slewStepOptions->setCurrentText(m_attrValues[OUTPUT_CHNL]["slew_step"].first()) + : m_slewStepOptions->setCurrentText("ERROR"); (m_attrValues[OUTPUT_CHNL].contains("slew_rate") && !m_attrValues[OUTPUT_CHNL]["slew_rate"].isEmpty()) - ? m_slewRateOptions->setCurrentText(m_attrValues[OUTPUT_CHNL]["slew_rate"].first()) - : m_slewRateOptions->setCurrentText("ERROR"); + ? m_slewRateOptions->setCurrentText(m_attrValues[OUTPUT_CHNL]["slew_rate"].first()) + : m_slewRateOptions->setCurrentText("ERROR"); } void VoltageOutMenu::connectSignalsToSlots() { connect(m_dacCodeSpinButton, &PositionSpinButton::valueChanged, this, &VoltageOutMenu::dacCodeChanged); - connect(m_slewStepOptions, QOverload::of(&QComboBox::currentIndexChanged), this, &VoltageOutMenu::slewStepIndexChanged); - connect(m_slewRateOptions, QOverload::of(&QComboBox::currentIndexChanged), this, &VoltageOutMenu::slewRateIndexChanged); - connect(m_slewOptions, QOverload::of(&QComboBox::currentIndexChanged), this, &VoltageOutMenu::slewIndexChanged); + connect(m_slewStepOptions, QOverload::of(&QComboBox::currentIndexChanged), this, + &VoltageOutMenu::slewStepIndexChanged); + connect(m_slewRateOptions, QOverload::of(&QComboBox::currentIndexChanged), this, + &VoltageOutMenu::slewRateIndexChanged); + connect(m_slewOptions, QOverload::of(&QComboBox::currentIndexChanged), this, + &VoltageOutMenu::slewIndexChanged); connect(this, SIGNAL(mapUpdated()), this, SLOT(onMapUpdated())); } QString VoltageOutMenu::getInfoMessage() { QString infoMessage = "\"" + m_chnlFunction + "\" configuration generates 2 context channels.\n" + - "One of them is an input buffer capable channel (current_in)\n" + - "which is related to the plot and the other one is an\n" + - "output channel whose attributes can be changed from\n" + - "this menu."; + "One of them is an input buffer capable channel (current_in)\n" + + "which is related to the plot and the other one is an\n" + + "output channel whose attributes can be changed from\n" + "this menu."; return infoMessage; } void VoltageOutMenu::setAvailableOptions(QComboBox *list, QString attrName) { - if (!m_attrValues.contains(OUTPUT_CHNL)) { + if(!m_attrValues.contains(OUTPUT_CHNL)) { qWarning() << "There is no output channel available for this function!"; return; } QStringList availableValues = m_attrValues[OUTPUT_CHNL][attrName]; - for (const auto& slewValue : qAsConst(availableValues)) { + for(const auto &slewValue : qAsConst(availableValues)) { list->addItem(slewValue); } } @@ -442,118 +405,106 @@ void VoltageOutMenu::setAvailableOptions(QComboBox *list, QString attrName) void VoltageOutMenu::dacCodeChanged(double value) { QString attrName("raw"); - if (!m_attrValues.contains(OUTPUT_CHNL)) { + if(!m_attrValues.contains(OUTPUT_CHNL)) { qWarning() << "There is no output channel available for this function!"; return; } m_attrValues[OUTPUT_CHNL][attrName].clear(); m_attrValues[OUTPUT_CHNL][attrName].push_back(QString::number((int)value)); - //the convertFromRaw return value is in mV that's why we multiply by 10^(-3) + // the convertFromRaw return value is in mV that's why we multiply by 10^(-3) double val = convertFromRaw(value) * 0.001; m_dacLabel->clear(); m_dacLabel->setText(QString::number(val) + " V"); Q_EMIT attrValuesChanged(attrName, OUTPUT_CHNL); - } void VoltageOutMenu::slewStepIndexChanged(int idx) { QString attrName = "slew_step"; - if (!m_attrValues.contains(OUTPUT_CHNL)) { + if(!m_attrValues.contains(OUTPUT_CHNL)) { qWarning() << "There is no output channel available for this function!"; return; } - const auto& slewStep = m_attrValues[OUTPUT_CHNL]["slew_step_available"][idx]; + const auto &slewStep = m_attrValues[OUTPUT_CHNL]["slew_step_available"][idx]; m_attrValues[OUTPUT_CHNL][attrName].clear(); m_attrValues[OUTPUT_CHNL][attrName].push_back(slewStep); Q_EMIT attrValuesChanged(attrName, OUTPUT_CHNL); - } void VoltageOutMenu::slewRateIndexChanged(int idx) { QString attrName = "slew_rate"; - if (!m_attrValues.contains(OUTPUT_CHNL)) { + if(!m_attrValues.contains(OUTPUT_CHNL)) { qWarning() << "There is no output channel available for this function!"; return; } - const auto& slewStep = m_attrValues[OUTPUT_CHNL]["slew_rate_available"][idx]; + const auto &slewStep = m_attrValues[OUTPUT_CHNL]["slew_rate_available"][idx]; m_attrValues[OUTPUT_CHNL][attrName].clear(); m_attrValues[OUTPUT_CHNL][attrName].push_back(slewStep); Q_EMIT attrValuesChanged(attrName, OUTPUT_CHNL); - } void VoltageOutMenu::slewIndexChanged(int idx) { QString attrName = "slew_en"; - if (!m_attrValues.contains(OUTPUT_CHNL) ) { + if(!m_attrValues.contains(OUTPUT_CHNL)) { qWarning() << "There is no output channel available for this function!"; return; } m_attrValues[OUTPUT_CHNL][attrName].clear(); - if (idx == SLEW_DISABLE_IDX) { + if(idx == SLEW_DISABLE_IDX) { m_attrValues[OUTPUT_CHNL][attrName].push_back(QString("0")); - } - else { + } else { m_attrValues[OUTPUT_CHNL][attrName].push_back(QString("1")); } Q_EMIT attrValuesChanged(attrName, OUTPUT_CHNL); - } void VoltageOutMenu::onMapUpdated() { m_dacCodeSpinButton->blockSignals(true); (m_attrValues[OUTPUT_CHNL].contains("raw") && !m_attrValues[OUTPUT_CHNL]["raw"].isEmpty()) - ? m_dacCodeSpinButton->setValue(m_attrValues[OUTPUT_CHNL]["raw"].first().toDouble()) - : m_dacCodeSpinButton->setValue(0); + ? m_dacCodeSpinButton->setValue(m_attrValues[OUTPUT_CHNL]["raw"].first().toDouble()) + : m_dacCodeSpinButton->setValue(0); m_dacCodeSpinButton->blockSignals(false); m_slewOptions->blockSignals(true); - (m_attrValues[OUTPUT_CHNL]["slew_en"].first().compare("0") == 0) - ? m_slewOptions->setCurrentText("Disable") - : m_slewOptions->setCurrentText("Enable"); + (m_attrValues[OUTPUT_CHNL]["slew_en"].first().compare("0") == 0) ? m_slewOptions->setCurrentText("Disable") + : m_slewOptions->setCurrentText("Enable"); m_slewOptions->blockSignals(false); m_slewStepOptions->blockSignals(true); (m_attrValues[OUTPUT_CHNL].contains("slew_step") && !m_attrValues[OUTPUT_CHNL]["slew_step"].isEmpty()) - ? m_slewStepOptions->setCurrentText(m_attrValues[OUTPUT_CHNL]["slew_step"].first()) - : m_slewStepOptions->setCurrentText("ERROR"); + ? m_slewStepOptions->setCurrentText(m_attrValues[OUTPUT_CHNL]["slew_step"].first()) + : m_slewStepOptions->setCurrentText("ERROR"); m_slewStepOptions->blockSignals(false); m_slewRateOptions->blockSignals(true); (m_attrValues[OUTPUT_CHNL].contains("slew_rate") && !m_attrValues[OUTPUT_CHNL]["slew_rate"].isEmpty()) - ? m_slewRateOptions->setCurrentText(m_attrValues[OUTPUT_CHNL]["slew_rate"].first()) - : m_slewRateOptions->setCurrentText("ERROR"); + ? m_slewRateOptions->setCurrentText(m_attrValues[OUTPUT_CHNL]["slew_rate"].first()) + : m_slewRateOptions->setCurrentText("ERROR"); m_slewRateOptions->blockSignals(false); - } -CurrentOutMenu::CurrentOutMenu(QWidget* parent, QString chnlFunction) +CurrentOutMenu::CurrentOutMenu(QWidget *parent, QString chnlFunction) : BufferMenu(parent, chnlFunction) { - //dac code + // dac code QHBoxLayout *dacCodeLayout = new QHBoxLayout(); - m_dacCodeSpinButton = new PositionSpinButton({ - {"value", 1E0} - }, - "DAC Code", 0, - 8196, - true, false, m_widget); + m_dacCodeSpinButton = new PositionSpinButton({{"value", 1E0}}, "DAC Code", 0, 8196, true, false, m_widget); dacCodeLayout->addWidget(m_dacCodeSpinButton); addMenuLayout(dacCodeLayout); - //dac label + // dac label QHBoxLayout *m_dacLabelLayout = new QHBoxLayout(); m_dacLabel = new QLabel("mA", m_widget); m_dacLabelLayout->addWidget(m_dacLabel); m_dacLabelLayout->setAlignment(Qt::AlignRight); addMenuLayout(m_dacLabelLayout); - //slew + // slew QHBoxLayout *slewLayout = new QHBoxLayout(); m_slewOptions = new QComboBox(m_widget); m_slewOptions->addItem(QString("Disable")); @@ -562,27 +513,25 @@ CurrentOutMenu::CurrentOutMenu(QWidget* parent, QString chnlFunction) slewLayout->addWidget(new QLabel("Slew", m_widget), 1); slewLayout->addWidget(m_slewOptions, 1); addMenuLayout(slewLayout); - //slew step + // slew step QHBoxLayout *slewStepLayout = new QHBoxLayout(); m_slewStepOptions = new QComboBox(m_widget); slewStepLayout->addWidget(new QLabel("Slew Step Size", m_widget), 1); slewStepLayout->addWidget(m_slewStepOptions, 1); addMenuLayout(slewStepLayout); - //slew rate + // slew rate QHBoxLayout *slewRateLayout = new QHBoxLayout(); m_slewRateOptions = new QComboBox(m_widget); - slewRateLayout->addWidget(new QLabel("Slew Rate (kHz)",m_widget),1); + slewRateLayout->addWidget(new QLabel("Slew Rate (kHz)", m_widget), 1); slewRateLayout->addWidget(m_slewRateOptions, 1); addMenuLayout(slewRateLayout); connectSignalsToSlots(); } -CurrentOutMenu::~CurrentOutMenu() -{ -} +CurrentOutMenu::~CurrentOutMenu() {} void CurrentOutMenu::init() { @@ -591,51 +540,53 @@ void CurrentOutMenu::init() setAvailableOptions(m_slewRateOptions, "slew_rate_available"); (m_attrValues[OUTPUT_CHNL].contains("raw") && !m_attrValues[OUTPUT_CHNL]["raw"].isEmpty()) - ? m_dacCodeSpinButton->setValue(m_attrValues[OUTPUT_CHNL]["raw"].first().toDouble()) - : m_dacCodeSpinButton->setValue(0); + ? m_dacCodeSpinButton->setValue(m_attrValues[OUTPUT_CHNL]["raw"].first().toDouble()) + : m_dacCodeSpinButton->setValue(0); - if (m_attrValues[OUTPUT_CHNL].contains("slew_en") && !m_attrValues[OUTPUT_CHNL]["slew_en"].isEmpty()) { + if(m_attrValues[OUTPUT_CHNL].contains("slew_en") && !m_attrValues[OUTPUT_CHNL]["slew_en"].isEmpty()) { (m_attrValues[OUTPUT_CHNL]["slew_en"].first().compare("0") == 0) - ? m_slewOptions->setCurrentText("Disable") - : m_slewOptions->setCurrentText("Enable"); + ? m_slewOptions->setCurrentText("Disable") + : m_slewOptions->setCurrentText("Enable"); } (m_attrValues[OUTPUT_CHNL].contains("slew_step") && !m_attrValues[OUTPUT_CHNL]["slew_step"].isEmpty()) - ? m_slewStepOptions->setCurrentText(m_attrValues[OUTPUT_CHNL]["slew_step"].first()) - : m_slewStepOptions->setCurrentText("ERROR"); + ? m_slewStepOptions->setCurrentText(m_attrValues[OUTPUT_CHNL]["slew_step"].first()) + : m_slewStepOptions->setCurrentText("ERROR"); (m_attrValues[OUTPUT_CHNL].contains("slew_rate") && !m_attrValues[OUTPUT_CHNL]["slew_rate"].isEmpty()) - ? m_slewRateOptions->setCurrentText(m_attrValues[OUTPUT_CHNL]["slew_rate"].first()) - : m_slewRateOptions->setCurrentText("ERROR"); + ? m_slewRateOptions->setCurrentText(m_attrValues[OUTPUT_CHNL]["slew_rate"].first()) + : m_slewRateOptions->setCurrentText("ERROR"); } void CurrentOutMenu::connectSignalsToSlots() { connect(m_dacCodeSpinButton, &PositionSpinButton::valueChanged, this, &CurrentOutMenu::dacCodeChanged); - connect(m_slewStepOptions, QOverload::of(&QComboBox::currentIndexChanged), this, &CurrentOutMenu::slewStepIndexChanged); - connect(m_slewRateOptions, QOverload::of(&QComboBox::currentIndexChanged), this, &CurrentOutMenu::slewRateIndexChanged); - connect(m_slewOptions, QOverload::of(&QComboBox::currentIndexChanged), this, &CurrentOutMenu::slewIndexChanged); + connect(m_slewStepOptions, QOverload::of(&QComboBox::currentIndexChanged), this, + &CurrentOutMenu::slewStepIndexChanged); + connect(m_slewRateOptions, QOverload::of(&QComboBox::currentIndexChanged), this, + &CurrentOutMenu::slewRateIndexChanged); + connect(m_slewOptions, QOverload::of(&QComboBox::currentIndexChanged), this, + &CurrentOutMenu::slewIndexChanged); connect(this, SIGNAL(mapUpdated()), this, SLOT(onMapUpdated())); } QString CurrentOutMenu::getInfoMessage() { QString infoMessage = "\"" + m_chnlFunction + "\" configuration generates 2 context channels.\n" + - "One of them is an input buffer capable channel (voltage_in)\n" + - "which is related to the plot and the other one is an\n" + - "output channel whose attributes can be changed from\n" + - "this menu."; + "One of them is an input buffer capable channel (voltage_in)\n" + + "which is related to the plot and the other one is an\n" + + "output channel whose attributes can be changed from\n" + "this menu."; return infoMessage; } void CurrentOutMenu::setAvailableOptions(QComboBox *list, QString attrName) { - if (!m_attrValues.contains(OUTPUT_CHNL)) { + if(!m_attrValues.contains(OUTPUT_CHNL)) { qWarning() << "There is no output channel available for this function!"; return; } QStringList availableValues = m_attrValues[OUTPUT_CHNL][attrName]; - for (const auto& slewValue : availableValues) { + for(const auto &slewValue : availableValues) { list->addItem(slewValue); } } @@ -643,16 +594,16 @@ void CurrentOutMenu::setAvailableOptions(QComboBox *list, QString attrName) void CurrentOutMenu::dacCodeChanged(double value) { QString attrName("raw"); - if (!m_attrValues.contains(OUTPUT_CHNL)) { + if(!m_attrValues.contains(OUTPUT_CHNL)) { qWarning() << "There is no output channel available for this function!"; return; } - if (m_attrValues.contains(OUTPUT_CHNL)) { + if(m_attrValues.contains(OUTPUT_CHNL)) { m_attrValues[OUTPUT_CHNL][attrName].clear(); m_attrValues[OUTPUT_CHNL][attrName].push_back(QString::number((int)value)); double val = convertFromRaw(value); m_dacLabel->clear(); - m_dacLabel->setText(QString::number(val)+" mA"); + m_dacLabel->setText(QString::number(val) + " mA"); Q_EMIT attrValuesChanged(attrName, OUTPUT_CHNL); } @@ -661,11 +612,11 @@ void CurrentOutMenu::dacCodeChanged(double value) void CurrentOutMenu::slewStepIndexChanged(int idx) { QString attrName = "slew_step"; - if (!m_attrValues.contains(OUTPUT_CHNL)) { + if(!m_attrValues.contains(OUTPUT_CHNL)) { qWarning() << "There is no output channel available for this function!"; return; } - const auto& slewStep = m_attrValues[OUTPUT_CHNL]["slew_step_available"][idx]; + const auto &slewStep = m_attrValues[OUTPUT_CHNL]["slew_step_available"][idx]; m_attrValues[OUTPUT_CHNL][attrName].clear(); m_attrValues[OUTPUT_CHNL][attrName].push_back(slewStep); @@ -675,11 +626,11 @@ void CurrentOutMenu::slewStepIndexChanged(int idx) void CurrentOutMenu::slewRateIndexChanged(int idx) { QString attrName = "slew_rate"; - if (!m_attrValues.contains(OUTPUT_CHNL)) { + if(!m_attrValues.contains(OUTPUT_CHNL)) { qWarning() << "There is no output channel available for this function!"; return; } - const auto& slewStep = m_attrValues[OUTPUT_CHNL]["slew_rate_available"][idx]; + const auto &slewStep = m_attrValues[OUTPUT_CHNL]["slew_rate_available"][idx]; m_attrValues[OUTPUT_CHNL][attrName].clear(); m_attrValues[OUTPUT_CHNL][attrName].push_back(slewStep); @@ -689,15 +640,14 @@ void CurrentOutMenu::slewRateIndexChanged(int idx) void CurrentOutMenu::slewIndexChanged(int idx) { QString attrName = "slew_en"; - if (!m_attrValues.contains(OUTPUT_CHNL)) { + if(!m_attrValues.contains(OUTPUT_CHNL)) { qWarning() << "There is no output channel available for this function!"; return; } m_attrValues[OUTPUT_CHNL][attrName].clear(); - if (idx == SLEW_DISABLE_IDX) { + if(idx == SLEW_DISABLE_IDX) { m_attrValues[OUTPUT_CHNL][attrName].push_back(QString("0")); - } - else { + } else { m_attrValues[OUTPUT_CHNL][attrName].push_back(QString("1")); } @@ -708,30 +658,29 @@ void CurrentOutMenu::onMapUpdated() { m_dacCodeSpinButton->blockSignals(true); (m_attrValues[OUTPUT_CHNL].contains("raw") && !m_attrValues[OUTPUT_CHNL]["raw"].isEmpty()) - ? m_dacCodeSpinButton->setValue(m_attrValues[OUTPUT_CHNL]["raw"].first().toDouble()) - : m_dacCodeSpinButton->setValue(0); + ? m_dacCodeSpinButton->setValue(m_attrValues[OUTPUT_CHNL]["raw"].first().toDouble()) + : m_dacCodeSpinButton->setValue(0); m_dacCodeSpinButton->blockSignals(false); m_slewOptions->blockSignals(true); - (m_attrValues[OUTPUT_CHNL]["slew_en"].first().compare("0") == 0) - ? m_slewOptions->setCurrentText("Disable") - : m_slewOptions->setCurrentText("Enable"); + (m_attrValues[OUTPUT_CHNL]["slew_en"].first().compare("0") == 0) ? m_slewOptions->setCurrentText("Disable") + : m_slewOptions->setCurrentText("Enable"); m_slewOptions->blockSignals(false); m_slewStepOptions->blockSignals(true); (m_attrValues[OUTPUT_CHNL].contains("slew_step") && !m_attrValues[OUTPUT_CHNL]["slew_step"].isEmpty()) - ? m_slewStepOptions->setCurrentText(m_attrValues[OUTPUT_CHNL]["slew_step"].first()) - : m_slewStepOptions->setCurrentText("ERROR"); + ? m_slewStepOptions->setCurrentText(m_attrValues[OUTPUT_CHNL]["slew_step"].first()) + : m_slewStepOptions->setCurrentText("ERROR"); m_slewStepOptions->blockSignals(false); m_slewRateOptions->blockSignals(true); (m_attrValues[OUTPUT_CHNL].contains("slew_rate") && !m_attrValues[OUTPUT_CHNL]["slew_rate"].isEmpty()) - ? m_slewRateOptions->setCurrentText(m_attrValues[OUTPUT_CHNL]["slew_rate"].first()) - : m_slewRateOptions->setCurrentText("ERROR"); + ? m_slewRateOptions->setCurrentText(m_attrValues[OUTPUT_CHNL]["slew_rate"].first()) + : m_slewRateOptions->setCurrentText("ERROR"); m_slewRateOptions->blockSignals(false); } -DiagnosticMenu::DiagnosticMenu(QWidget* parent, QString chnlFunction) +DiagnosticMenu::DiagnosticMenu(QWidget *parent, QString chnlFunction) : BufferMenu(parent, chnlFunction) { QHBoxLayout *diagLayout = new QHBoxLayout(); @@ -743,32 +692,32 @@ DiagnosticMenu::DiagnosticMenu(QWidget* parent, QString chnlFunction) connectSignalsToSlots(); } -DiagnosticMenu::~DiagnosticMenu() -{} +DiagnosticMenu::~DiagnosticMenu() {} void DiagnosticMenu::init() { BufferMenu::init(); setAvailableOptions(m_diagOptions, "diag_function_available"); (m_attrValues[INPUT_CHNL].contains("diag_function") && !m_attrValues[INPUT_CHNL]["diag_function"].isEmpty()) - ? m_diagOptions->setCurrentText(m_attrValues[INPUT_CHNL]["diag_function"].first()) - : m_diagOptions->setCurrentText("ERROR"); + ? m_diagOptions->setCurrentText(m_attrValues[INPUT_CHNL]["diag_function"].first()) + : m_diagOptions->setCurrentText("ERROR"); } void DiagnosticMenu::connectSignalsToSlots() { - connect(m_diagOptions, QOverload::of(&QComboBox::currentIndexChanged), this, &DiagnosticMenu::diagIndexChanged); + connect(m_diagOptions, QOverload::of(&QComboBox::currentIndexChanged), this, + &DiagnosticMenu::diagIndexChanged); connect(this, SIGNAL(mapUpdated()), this, SLOT(onMapUpdated())); } void DiagnosticMenu::setAvailableOptions(QComboBox *list, QString attrName) { - if (!m_attrValues.contains(INPUT_CHNL)) { + if(!m_attrValues.contains(INPUT_CHNL)) { qWarning() << "There is no input channel available for this function!"; return; } QStringList availableValues = m_attrValues[INPUT_CHNL][attrName]; - for (const auto& slewValue : qAsConst(availableValues)) { + for(const auto &slewValue : qAsConst(availableValues)) { list->addItem(slewValue); } } @@ -776,11 +725,11 @@ void DiagnosticMenu::setAvailableOptions(QComboBox *list, QString attrName) void DiagnosticMenu::diagIndexChanged(int idx) { QString attrName = "diag_function"; - if (!m_attrValues.contains(INPUT_CHNL)) { + if(!m_attrValues.contains(INPUT_CHNL)) { qWarning() << "There is no input channel available for this function!"; return; } - const auto& diagFunc = m_attrValues[INPUT_CHNL]["diag_function_available"][idx]; + const auto &diagFunc = m_attrValues[INPUT_CHNL]["diag_function_available"][idx]; m_attrValues[INPUT_CHNL][attrName].clear(); m_attrValues[INPUT_CHNL][attrName].push_back(diagFunc); @@ -791,13 +740,13 @@ void DiagnosticMenu::onMapUpdated() { m_diagOptions->blockSignals(true); (m_attrValues[INPUT_CHNL].contains("diag_function") && !m_attrValues[INPUT_CHNL]["diag_function"].isEmpty()) - ? m_diagOptions->setCurrentText(m_attrValues[INPUT_CHNL]["diag_function"].first()) - : m_diagOptions->setCurrentText("ERROR"); + ? m_diagOptions->setCurrentText(m_attrValues[INPUT_CHNL]["diag_function"].first()) + : m_diagOptions->setCurrentText("ERROR"); m_diagOptions->blockSignals(false); Q_EMIT diagnosticFunctionUpdated(); } -WithoutAdvSettings::WithoutAdvSettings(QWidget* parent, QString chnlFunction) +WithoutAdvSettings::WithoutAdvSettings(QWidget *parent, QString chnlFunction) : BufferMenu(parent, chnlFunction) { QHBoxLayout *msgLayout = new QHBoxLayout(); @@ -805,18 +754,13 @@ WithoutAdvSettings::WithoutAdvSettings(QWidget* parent, QString chnlFunction) addMenuLayout(msgLayout); } -WithoutAdvSettings::~WithoutAdvSettings() -{} +WithoutAdvSettings::~WithoutAdvSettings() {} -void WithoutAdvSettings::init() -{ - BufferMenu::init(); -} +void WithoutAdvSettings::init() { BufferMenu::init(); } -void WithoutAdvSettings::connectSignalsToSlots() -{} +void WithoutAdvSettings::connectSignalsToSlots() {} -DigitalInMenu::DigitalInMenu(QWidget* parent, QString chnlFunction) +DigitalInMenu::DigitalInMenu(QWidget *parent, QString chnlFunction) : BufferMenu(parent, chnlFunction) { QVBoxLayout *thresholdLayout = new QVBoxLayout(); @@ -826,7 +770,8 @@ DigitalInMenu::DigitalInMenu(QWidget* parent, QString chnlFunction) m_titleLabel = new QLabel("Threshold (0 - 16000 mV)", m_widget); m_titleLabel->setStyleSheet("font-size: 14px;"); m_thresholdLineEdit = new QLineEdit(m_widget); - m_thresholdLineEdit->setStyleSheet("background: transparent; height: 20px; width: 75px; font-size: 18px; border: 0px; bottom: 10px;"); + m_thresholdLineEdit->setStyleSheet( + "background: transparent; height: 20px; width: 75px; font-size: 18px; border: 0px; bottom: 10px;"); m_thresholdLineEdit->setValidator(validator); QFrame *frame = new QFrame(m_widget); frame->setFrameShape(QFrame::HLine); @@ -839,18 +784,17 @@ DigitalInMenu::DigitalInMenu(QWidget* parent, QString chnlFunction) connectSignalsToSlots(); } -DigitalInMenu::~DigitalInMenu() -{} +DigitalInMenu::~DigitalInMenu() {} void DigitalInMenu::init() { BufferMenu::init(); - //threshold + // threshold (m_attrValues[INPUT_CHNL].contains("threshold") && !m_attrValues[INPUT_CHNL]["threshold"].isEmpty()) - ? m_thresholdLineEdit->setText(m_attrValues[INPUT_CHNL]["threshold"].first()), - m_thresholdLineEdit->setPlaceholderText(m_attrValues[INPUT_CHNL]["threshold"].first()) - : m_thresholdLineEdit->setText("0"), - m_thresholdLineEdit->setPlaceholderText("0"); + ? m_thresholdLineEdit->setText(m_attrValues[INPUT_CHNL]["threshold"].first()), + m_thresholdLineEdit->setPlaceholderText(m_attrValues[INPUT_CHNL]["threshold"].first()) + : m_thresholdLineEdit->setText("0"), + m_thresholdLineEdit->setPlaceholderText("0"); } void DigitalInMenu::connectSignalsToSlots() @@ -864,11 +808,11 @@ void DigitalInMenu::connectSignalsToSlots() void DigitalInMenu::thresholdChanged() { QString attrName("threshold"); - if (!m_attrValues.contains(INPUT_CHNL)) { + if(!m_attrValues.contains(INPUT_CHNL)) { qWarning() << "There is no input channel available for this function!"; return; } - if (m_attrValues[INPUT_CHNL].contains(attrName)) { + if(m_attrValues[INPUT_CHNL].contains(attrName)) { m_attrValues[INPUT_CHNL][attrName].clear(); m_attrValues[INPUT_CHNL][attrName].push_back(m_thresholdLineEdit->text()); Q_EMIT attrValuesChanged(attrName, INPUT_CHNL); @@ -880,8 +824,8 @@ void DigitalInMenu::thresholdChanged() void DigitalInMenu::onMapUpdated() { m_thresholdLineEdit->blockSignals(true); - if (m_attrValues[INPUT_CHNL].contains("threshold") && !m_attrValues[INPUT_CHNL]["threshold"].isEmpty()) { - if (m_attrValues[INPUT_CHNL]["threshold"].first().compare(m_thresholdLineEdit->text()) != 0 ) { + if(m_attrValues[INPUT_CHNL].contains("threshold") && !m_attrValues[INPUT_CHNL]["threshold"].isEmpty()) { + if(m_attrValues[INPUT_CHNL]["threshold"].first().compare(m_thresholdLineEdit->text()) != 0) { Q_EMIT broadcastThresholdReadForward(m_attrValues[INPUT_CHNL]["threshold"].first()); } m_thresholdLineEdit->setText(m_attrValues[INPUT_CHNL]["threshold"].first()); @@ -895,7 +839,7 @@ void DigitalInMenu::onMapUpdated() void DigitalInMenu::onBroadcastThresholdRead(QString value) { m_thresholdLineEdit->blockSignals(true); - if (value.compare(m_thresholdLineEdit->text()) != 0 ) { + if(value.compare(m_thresholdLineEdit->text()) != 0) { m_thresholdLineEdit->setText(value); m_thresholdLineEdit->setPlaceholderText(value); m_attrValues[INPUT_CHNL]["threshold"].first() = value; @@ -903,10 +847,4 @@ void DigitalInMenu::onBroadcastThresholdRead(QString value) m_thresholdLineEdit->blockSignals(false); } -void DigitalInMenu::onThresholdControlEnable(bool enabled) -{ - m_thresholdLineEdit->setEnabled(enabled); -} - - - +void DigitalInMenu::onThresholdControlEnable(bool enabled) { m_thresholdLineEdit->setEnabled(enabled); } diff --git a/plugins/swiot/src/runtime/ad74413r/buffermenu.h b/plugins/swiot/src/runtime/ad74413r/buffermenu.h index 11a5c3e305..0391ba33ee 100644 --- a/plugins/swiot/src/runtime/ad74413r/buffermenu.h +++ b/plugins/swiot/src/runtime/ad74413r/buffermenu.h @@ -18,7 +18,6 @@ * along with this program. If not, see . */ - #ifndef SWIOTADVMENU_H #define SWIOTADVMENU_H @@ -26,8 +25,9 @@ #include "qcombobox.h" #include "qlabel.h" -#include #include + +#include #include namespace scopy { @@ -39,11 +39,11 @@ namespace swiot { #define OUTPUT_CHNL "output" #define INPUT_CHNL "input" -class BufferMenu: public QWidget +class BufferMenu : public QWidget { Q_OBJECT public: - explicit BufferMenu(QWidget* parent = nullptr, QString chnlFunction = ""); + explicit BufferMenu(QWidget *parent = nullptr, QString chnlFunction = ""); ~BufferMenu(); virtual void init(); @@ -55,8 +55,8 @@ class BufferMenu: public QWidget void setupVerticalSettingsMenu(QWidget *settingsWidget, QString unit, double yMin, double yMax); void setAttrValues(QMap> values); double convertFromRaw(int rawValue, QString chnlType = OUTPUT_CHNL); -public Q_SLOT: - void onAttrWritten(QMap> values); +public + Q_SLOT : void onAttrWritten(QMap> values); Q_SIGNALS: void attrValuesChanged(QString attrName, QString chnlType); void mapUpdated(); @@ -72,15 +72,16 @@ public Q_SLOT: QString m_chnlFunction; QMap> m_attrValues; PositionSpinButton *m_unitPerDivision; + private: QVector m_menuLayers; }; -class CurrentInLoopMenu: public BufferMenu +class CurrentInLoopMenu : public BufferMenu { Q_OBJECT public: - explicit CurrentInLoopMenu(QWidget* parent = nullptr, QString chnlFunction = ""); + explicit CurrentInLoopMenu(QWidget *parent = nullptr, QString chnlFunction = ""); ~CurrentInLoopMenu(); void init(); void connectSignalsToSlots(); @@ -88,16 +89,17 @@ class CurrentInLoopMenu: public BufferMenu public Q_SLOTS: void dacCodeChanged(double value); void onMapUpdated(); + private: PositionSpinButton *m_dacCodeSpinButton; QLabel *m_dacLabel; }; -class DigitalInLoopMenu: public BufferMenu +class DigitalInLoopMenu : public BufferMenu { Q_OBJECT public: - explicit DigitalInLoopMenu(QWidget* parent = nullptr, QString chnlFunction = ""); + explicit DigitalInLoopMenu(QWidget *parent = nullptr, QString chnlFunction = ""); ~DigitalInLoopMenu(); void init(); void connectSignalsToSlots(); @@ -108,6 +110,7 @@ public Q_SLOTS: void onMapUpdated(); void onBroadcastThresholdRead(QString value); void onThresholdControlEnable(bool enabled); + private: QLabel *m_titleLabel; QLineEdit *m_thresholdLineEdit; @@ -115,11 +118,11 @@ public Q_SLOTS: QLabel *m_dacLabel; }; -class VoltageOutMenu: public BufferMenu +class VoltageOutMenu : public BufferMenu { Q_OBJECT public: - explicit VoltageOutMenu(QWidget* parent = nullptr, QString chnlFunction = ""); + explicit VoltageOutMenu(QWidget *parent = nullptr, QString chnlFunction = ""); ~VoltageOutMenu(); void init(); void connectSignalsToSlots(); @@ -130,6 +133,7 @@ public Q_SLOTS: void slewIndexChanged(int idx); void dacCodeChanged(double value); void onMapUpdated(); + private: PositionSpinButton *m_dacCodeSpinButton; QLabel *m_dacLabel; @@ -140,11 +144,11 @@ public Q_SLOTS: void setAvailableOptions(QComboBox *list, QString attrName); }; -class CurrentOutMenu: public BufferMenu +class CurrentOutMenu : public BufferMenu { Q_OBJECT public: - explicit CurrentOutMenu(QWidget* parent = nullptr, QString chnlFunction = ""); + explicit CurrentOutMenu(QWidget *parent = nullptr, QString chnlFunction = ""); ~CurrentOutMenu(); void init(); void connectSignalsToSlots(); @@ -156,7 +160,8 @@ public Q_SLOTS: void slewIndexChanged(int idx); void dacCodeChanged(double value); void onMapUpdated(); -private: + +private: PositionSpinButton *m_dacCodeSpinButton; QComboBox *m_slewOptions; QComboBox *m_slewStepOptions; @@ -166,17 +171,18 @@ public Q_SLOTS: void setAvailableOptions(QComboBox *list, QString attrName); }; -class DiagnosticMenu: public BufferMenu +class DiagnosticMenu : public BufferMenu { Q_OBJECT public: - explicit DiagnosticMenu(QWidget* parent = nullptr, QString chnlFunction = ""); + explicit DiagnosticMenu(QWidget *parent = nullptr, QString chnlFunction = ""); ~DiagnosticMenu(); void init(); void connectSignalsToSlots(); public Q_SLOTS: void diagIndexChanged(int idx); void onMapUpdated(); + private: QComboBox *m_diagOptions; @@ -187,7 +193,7 @@ class DigitalInMenu : public BufferMenu { Q_OBJECT public: - explicit DigitalInMenu(QWidget* parent = nullptr, QString chnlFunction = ""); + explicit DigitalInMenu(QWidget *parent = nullptr, QString chnlFunction = ""); ~DigitalInMenu(); void init(); void connectSignalsToSlots(); @@ -196,16 +202,17 @@ public Q_SLOTS: void onMapUpdated(); void onBroadcastThresholdRead(QString value); void onThresholdControlEnable(bool enabled); + private: QLabel *m_titleLabel; QLineEdit *m_thresholdLineEdit; }; -class WithoutAdvSettings: public BufferMenu +class WithoutAdvSettings : public BufferMenu { Q_OBJECT public: - explicit WithoutAdvSettings(QWidget* parent = nullptr, QString chnlFunction = ""); + explicit WithoutAdvSettings(QWidget *parent = nullptr, QString chnlFunction = ""); ~WithoutAdvSettings(); void init(); void connectSignalsToSlots(); @@ -215,57 +222,57 @@ class BufferMenuBuilder { public: - - enum MenuType { - CURRENT_IN_LOOP = 0, - DIGITAL_IN = 1, - DIGITAL_IN_LOOP = 2, - VOLTAGE_OUT = 3, - CURRENT_OUT = 4, - VOLTAGE_IN = 5, - CURRENT_IN_EXT = 6, - CURRENT_IN_LOOP_HART = 7, - CURRENT_IN_EXT_HART = 8, - RESISTANCE = 9, - DIAGNOSTIC = 10, - HIGH_Z = 11 + enum MenuType + { + CURRENT_IN_LOOP = 0, + DIGITAL_IN = 1, + DIGITAL_IN_LOOP = 2, + VOLTAGE_OUT = 3, + CURRENT_OUT = 4, + VOLTAGE_IN = 5, + CURRENT_IN_EXT = 6, + CURRENT_IN_LOOP_HART = 7, + CURRENT_IN_EXT_HART = 8, + RESISTANCE = 9, + DIAGNOSTIC = 10, + HIGH_Z = 11 }; static int decodeFunctionName(QString function) { - if (function.compare("voltage_in") == 0) { + if(function.compare("voltage_in") == 0) { return VOLTAGE_IN; - } else if (function.compare("current_in_ext") == 0) { + } else if(function.compare("current_in_ext") == 0) { return CURRENT_IN_EXT; - } else if (function.compare("current_in_loop_hart") == 0) { + } else if(function.compare("current_in_loop_hart") == 0) { return CURRENT_IN_LOOP_HART; - } else if (function.compare("current_in_ext_hart") == 0) { + } else if(function.compare("current_in_ext_hart") == 0) { return CURRENT_IN_EXT_HART; - } else if (function.compare("resistance") == 0) { + } else if(function.compare("resistance") == 0) { return RESISTANCE; - } else if (function.compare("current_in_loop") == 0) { + } else if(function.compare("current_in_loop") == 0) { return CURRENT_IN_LOOP; - } else if (function.compare("digital_input") == 0) { + } else if(function.compare("digital_input") == 0) { return DIGITAL_IN; - } else if (function.compare("digital_input_loop") == 0) { + } else if(function.compare("digital_input_loop") == 0) { return DIGITAL_IN_LOOP; - } else if (function.compare("voltage_out") == 0) { + } else if(function.compare("voltage_out") == 0) { return VOLTAGE_OUT; - } else if (function.compare("current_out") == 0) { + } else if(function.compare("current_out") == 0) { return CURRENT_OUT; - } else if (function.compare("diagnostic") == 0) { + } else if(function.compare("diagnostic") == 0) { return DIAGNOSTIC; - } else if (function.compare("high_z") == 0) { + } else if(function.compare("high_z") == 0) { return HIGH_Z; } else { return -1; } } - static BufferMenu* newAdvMenu(QWidget *widget, QString function) + static BufferMenu *newAdvMenu(QWidget *widget, QString function) { int menu_type = decodeFunctionName(function); - switch (menu_type) { + switch(menu_type) { case CURRENT_IN_LOOP: return new CurrentInLoopMenu(widget, function); case CURRENT_IN_LOOP_HART: @@ -284,11 +291,9 @@ class BufferMenuBuilder return new WithoutAdvSettings(widget, function); } } - }; -} -} - +} // namespace swiot +} // namespace scopy #endif // SWIOTADVMENU_H diff --git a/plugins/swiot/src/runtime/ad74413r/buffermenucontroller.cpp b/plugins/swiot/src/runtime/ad74413r/buffermenucontroller.cpp index 93788238cb..4b86e3004a 100644 --- a/plugins/swiot/src/runtime/ad74413r/buffermenucontroller.cpp +++ b/plugins/swiot/src/runtime/ad74413r/buffermenucontroller.cpp @@ -18,15 +18,14 @@ * along with this program. If not, see . */ - #include "buffermenucontroller.h" using namespace scopy::swiot; -BufferMenuController::BufferMenuController(BufferMenuView* genericMenu, BufferMenuModel* model, int chnlIdx): - m_chnlIdx(chnlIdx) - ,m_genericMenu(genericMenu) - ,m_model(model) +BufferMenuController::BufferMenuController(BufferMenuView *genericMenu, BufferMenuModel *model, int chnlIdx) + : m_chnlIdx(chnlIdx) + , m_genericMenu(genericMenu) + , m_model(model) {} BufferMenuController::~BufferMenuController() @@ -35,44 +34,42 @@ BufferMenuController::~BufferMenuController() delete m_genericMenu; } -void BufferMenuController::addMenuAttrValues(QMap > values) +void BufferMenuController::addMenuAttrValues(QMap> values) { - if (!values.empty()) { + if(!values.empty()) { m_genericMenu->initAdvMenu(values); } } void BufferMenuController::createConnections() { - BufferMenu* advMenu = m_genericMenu->getAdvMenu(); + BufferMenu *advMenu = m_genericMenu->getAdvMenu(); connect(advMenu, &BufferMenu::attrValuesChanged, this, &BufferMenuController::attributesChanged); connect(m_model, &BufferMenuModel::attrWritten, advMenu, &BufferMenu::onAttrWritten); connect(m_model, &BufferMenuModel::menuModelInitDone, this, &BufferMenuController::addMenuAttrValues); - connect(advMenu, &BufferMenu::setUnitPerDivision, this, [=, this] (double unitPerDiv) { - Q_EMIT setUnitPerDivision(m_chnlIdx, unitPerDiv); - }); - connect(this, &BufferMenuController::unitPerDivisionChanged, this, [=, this] (int chnl, double unitPerDiv) { - if (m_chnlIdx == chnl) { + connect(advMenu, &BufferMenu::setUnitPerDivision, this, + [=, this](double unitPerDiv) { Q_EMIT setUnitPerDivision(m_chnlIdx, unitPerDiv); }); + connect(this, &BufferMenuController::unitPerDivisionChanged, this, [=, this](int chnl, double unitPerDiv) { + if(m_chnlIdx == chnl) { Q_EMIT advMenu->unitPerDivisionChanged(unitPerDiv); } }); - connect(advMenu, &BufferMenu::diagnosticFunctionUpdated, this, &BufferMenuController::diagnosticFunctionUpdated); - connect(advMenu, SIGNAL(broadcastThresholdReadForward(QString)), this, SIGNAL(broadcastThresholdReadForward(QString))); - connect(this, SIGNAL(broadcastThresholdReadBackward(QString)), advMenu, SIGNAL(broadcastThresholdReadBackward(QString))); + connect(advMenu, &BufferMenu::diagnosticFunctionUpdated, this, + &BufferMenuController::diagnosticFunctionUpdated); + connect(advMenu, SIGNAL(broadcastThresholdReadForward(QString)), this, + SIGNAL(broadcastThresholdReadForward(QString))); + connect(this, SIGNAL(broadcastThresholdReadBackward(QString)), advMenu, + SIGNAL(broadcastThresholdReadBackward(QString))); connect(this, &BufferMenuController::thresholdControlEnable, advMenu, &BufferMenu::thresholdControlEnable); } void BufferMenuController::attributesChanged(QString attrName, QString chnlType) { - BufferMenu* menu=m_genericMenu->getAdvMenu(); + BufferMenu *menu = m_genericMenu->getAdvMenu(); QMap> attributes = menu->getAttrValues(); m_model->updateChnlAttributes(attributes, attrName, chnlType); } -int BufferMenuController::getChnlIdx() -{ - return m_chnlIdx; -} - +int BufferMenuController::getChnlIdx() { return m_chnlIdx; } diff --git a/plugins/swiot/src/runtime/ad74413r/buffermenucontroller.h b/plugins/swiot/src/runtime/ad74413r/buffermenucontroller.h index bab165e490..9f451a1182 100644 --- a/plugins/swiot/src/runtime/ad74413r/buffermenucontroller.h +++ b/plugins/swiot/src/runtime/ad74413r/buffermenucontroller.h @@ -18,20 +18,20 @@ * along with this program. If not, see . */ - #ifndef BUFFERMENUCONTROLLER_H #define BUFFERMENUCONTROLLER_H -#include "qobject.h" -#include "buffermenuview.h" #include "buffermenumodel.h" +#include "buffermenuview.h" +#include "qobject.h" namespace scopy::swiot { -class BufferMenuController : public QObject { +class BufferMenuController : public QObject +{ Q_OBJECT public: - explicit BufferMenuController(BufferMenuView *genericMenu = nullptr, - BufferMenuModel *model = nullptr, int chnlIdx = -1); + explicit BufferMenuController(BufferMenuView *genericMenu = nullptr, BufferMenuModel *model = nullptr, + int chnlIdx = -1); ~BufferMenuController(); @@ -42,7 +42,7 @@ class BufferMenuController : public QObject { public Q_SLOTS: void attributesChanged(QString attrName, QString chnlType); - void addMenuAttrValues(QMap > values); + void addMenuAttrValues(QMap> values); Q_SIGNALS: void broadcastThresholdReadForward(QString value); void broadcastThresholdReadBackward(QString value); @@ -55,9 +55,7 @@ public Q_SLOTS: int m_chnlIdx; BufferMenuView *m_genericMenu; BufferMenuModel *m_model; - }; -} - +} // namespace scopy::swiot #endif // BUFFERMENUCONTROLLER_H diff --git a/plugins/swiot/src/runtime/ad74413r/buffermenumodel.cpp b/plugins/swiot/src/runtime/ad74413r/buffermenumodel.cpp index ac99c3587f..c8d5ee4cfa 100644 --- a/plugins/swiot/src/runtime/ad74413r/buffermenumodel.cpp +++ b/plugins/swiot/src/runtime/ad74413r/buffermenumodel.cpp @@ -18,16 +18,18 @@ * along with this program. If not, see . */ +#include "buffermenumodel.h" -#include #include "qdebug.h" -#include "buffermenumodel.h" + +#include + #include #include using namespace scopy::swiot; -BufferMenuModel::BufferMenuModel(QMap chnlsMap, CommandQueue *cmdQueue) +BufferMenuModel::BufferMenuModel(QMap chnlsMap, CommandQueue *cmdQueue) : m_chnlsMap(chnlsMap) , m_commandQueue(cmdQueue) , m_initialized(false) @@ -37,46 +39,41 @@ BufferMenuModel::BufferMenuModel(QMap chnlsMap, CommandQu init(); } -BufferMenuModel::~BufferMenuModel() -{} +BufferMenuModel::~BufferMenuModel() {} void BufferMenuModel::init() { - if (m_chnlsMap.size() > 0) { + if(m_chnlsMap.size() > 0) { auto keys = m_chnlsMap.keys(); - for (const QString &key : keys) { + for(const QString &key : keys) { int chnlAttrNumber = iio_channel_get_attrs_count(m_chnlsMap[key]); QStringList attrValues; - for (int i = 0; i < chnlAttrNumber; i++) { + for(int i = 0; i < chnlAttrNumber; i++) { QString attrName(iio_channel_get_attr(m_chnlsMap[key], i)); readChnlAttr(key, attrName); } } auto key = m_chnlsMap.lastKey(); int chnlAttrNumber = iio_channel_get_attrs_count(m_chnlsMap[key]); - connect(this, &BufferMenuModel::attrRead, this, [=, this] - (QMap> chnlAttributes){ - if (!m_initialized && (chnlAttributes.size() == m_chnlsMap.size()) - && (chnlAttributes[key].size() == chnlAttrNumber)) { - m_initialized = true; - Q_EMIT menuModelInitDone(chnlAttributes); - } - }); + connect(this, &BufferMenuModel::attrRead, this, + [=, this](QMap> chnlAttributes) { + if(!m_initialized && (chnlAttributes.size() == m_chnlsMap.size()) && + (chnlAttributes[key].size() == chnlAttrNumber)) { + m_initialized = true; + Q_EMIT menuModelInitDone(chnlAttributes); + } + }); } } -QMap> BufferMenuModel::getChnlAttrValues() -{ - return m_chnlAttributes; -} - +QMap> BufferMenuModel::getChnlAttrValues() { return m_chnlAttributes; } -void BufferMenuModel::onChannelAttributeRead(QString iioChannelKey, QString attrName, - QStringList attrValues, bool readback) +void BufferMenuModel::onChannelAttributeRead(QString iioChannelKey, QString attrName, QStringList attrValues, + bool readback) { m_chnlAttributes[iioChannelKey][attrName] = attrValues; Q_EMIT attrRead(m_chnlAttributes); - if (readback) { + if(readback) { Q_EMIT attrWritten(m_chnlAttributes); } } @@ -90,52 +87,61 @@ void BufferMenuModel::onChannelAttributeWritten(QString iioChannelKey, QString a void BufferMenuModel::readChnlAttr(QString iioChannelKey, QString attrName, bool readback) { - Command *channelAttrReadCommand = new IioChannelAttributeRead(m_chnlsMap[iioChannelKey], attrName.toStdString().c_str(), nullptr); - connect(channelAttrReadCommand, &scopy::Command::finished, this, [=, this] (scopy::Command* cmd) { - IioChannelAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { return; } - - if (tcmd->getReturnCode() >= 0) { - char *result = tcmd->getResult(); - QString bufferValues(result); - QStringList attrValues = bufferValues.trimmed().split(" "); - //threshold should have a default value in the driver - // attrValues.removeAll(QString("")); - Q_EMIT channelAttributeRead(iioChannelKey, attrName, attrValues, readback); - } - }, Qt::QueuedConnection); + Command *channelAttrReadCommand = + new IioChannelAttributeRead(m_chnlsMap[iioChannelKey], attrName.toStdString().c_str(), nullptr); + connect( + channelAttrReadCommand, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioChannelAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + + if(tcmd->getReturnCode() >= 0) { + char *result = tcmd->getResult(); + QString bufferValues(result); + QStringList attrValues = bufferValues.trimmed().split(" "); + // threshold should have a default value in the driver + // attrValues.removeAll(QString("")); + Q_EMIT channelAttributeRead(iioChannelKey, attrName, attrValues, readback); + } + }, + Qt::QueuedConnection); m_commandQueue->enqueue(channelAttrReadCommand); } void BufferMenuModel::writeChnlAttr(QString iioChannelKey, QString attrName, QString attrVal, - QMap> newValues) + QMap> newValues) { - Command *channelAttrWriteCommand = new IioChannelAttributeWrite(m_chnlsMap[iioChannelKey], attrName.toStdString().c_str(), - attrVal.toStdString().c_str(), nullptr); - connect(channelAttrWriteCommand, &scopy::Command::finished, this, [=, this] (scopy::Command* cmd) { - IioChannelAttributeWrite *tcmd = dynamic_cast(cmd); - if (!tcmd) { return; } - - if (tcmd->getReturnCode() >= 0) { - m_chnlAttributes = newValues; - Q_EMIT channelAttributeWritten(iioChannelKey, attrName); - } - }, Qt::QueuedConnection); + Command *channelAttrWriteCommand = new IioChannelAttributeWrite( + m_chnlsMap[iioChannelKey], attrName.toStdString().c_str(), attrVal.toStdString().c_str(), nullptr); + connect( + channelAttrWriteCommand, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioChannelAttributeWrite *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + + if(tcmd->getReturnCode() >= 0) { + m_chnlAttributes = newValues; + Q_EMIT channelAttributeWritten(iioChannelKey, attrName); + } + }, + Qt::QueuedConnection); m_commandQueue->enqueue(channelAttrWriteCommand); } -void BufferMenuModel::updateChnlAttributes(QMap> newValues, - QString attrName, QString chnlType) +void BufferMenuModel::updateChnlAttributes(QMap> newValues, QString attrName, + QString chnlType) { QStringList value = newValues[chnlType].value(attrName); - if (value.size() == 1) { + if(value.size() == 1) { QString attrVal = value.first(); std::string s_attrValue = attrVal.toStdString(); std::string s_attrName = attrName.toStdString(); - if (m_chnlsMap.contains(chnlType) && m_chnlsMap[chnlType] != nullptr) { + if(m_chnlsMap.contains(chnlType) && m_chnlsMap[chnlType] != nullptr) { writeChnlAttr(chnlType, s_attrName.c_str(), s_attrValue.c_str(), newValues); } } - } - diff --git a/plugins/swiot/src/runtime/ad74413r/buffermenumodel.h b/plugins/swiot/src/runtime/ad74413r/buffermenumodel.h index 3562e32633..360c875316 100644 --- a/plugins/swiot/src/runtime/ad74413r/buffermenumodel.h +++ b/plugins/swiot/src/runtime/ad74413r/buffermenumodel.h @@ -18,30 +18,34 @@ * along with this program. If not, see . */ - #ifndef BUFFERMENUMODEL_H #define BUFFERMENUMODEL_H #include "qobject.h" + #include + #include -extern "C"{ -struct iio_channel; +extern "C" +{ + struct iio_channel; } namespace scopy::swiot { -class BufferMenuModel: public QObject{ +class BufferMenuModel : public QObject +{ Q_OBJECT public: - explicit BufferMenuModel(QMap chnlsMap, CommandQueue *cmdQueue); + explicit BufferMenuModel(QMap chnlsMap, CommandQueue *cmdQueue); ~BufferMenuModel(); QMap> getChnlAttrValues(); void readChnlAttr(QString iioChannelKey, QString attrName, bool readback = false); void writeChnlAttr(QString iioChannelKey, QString attrName, QString attrVal, - QMap> newValues); - void updateChnlAttributes(QMap> newValues, QString attrName, QString chnlType); + QMap> newValues); + void updateChnlAttributes(QMap> newValues, QString attrName, + QString chnlType); public Q_SLOTS: void onChannelAttributeRead(QString iioChannelKey, QString attrName, QStringList, bool readback); void onChannelAttributeWritten(QString iioChannelKey, QString attrName); @@ -51,13 +55,14 @@ public Q_SLOTS: void attrWritten(QMap> chnlAttributes); void channelAttributeRead(QString iioChannelKey, QString attrName, QStringList attrValues, bool readback); void channelAttributeWritten(QString iioChannelKey, QString attrName); + private: - QMap m_chnlsMap; + QMap m_chnlsMap; QMap> m_chnlAttributes; CommandQueue *m_commandQueue; bool m_initialized; void init(); }; -} +} // namespace scopy::swiot #endif // BUFFERMENUMODEL_H diff --git a/plugins/swiot/src/runtime/ad74413r/buffermenuview.cpp b/plugins/swiot/src/runtime/ad74413r/buffermenuview.cpp index b0d3df9e20..b17f56698e 100644 --- a/plugins/swiot/src/runtime/ad74413r/buffermenuview.cpp +++ b/plugins/swiot/src/runtime/ad74413r/buffermenuview.cpp @@ -18,26 +18,25 @@ * along with this program. If not, see . */ - #include "buffermenuview.h" + #include using namespace scopy; -swiot::BufferMenuView::BufferMenuView(QWidget *parent): - GenericMenu(parent) - ,m_swiotAdvMenu(nullptr) +swiot::BufferMenuView::BufferMenuView(QWidget *parent) + : GenericMenu(parent) + , m_swiotAdvMenu(nullptr) {} -swiot::BufferMenuView::~BufferMenuView() -{} +swiot::BufferMenuView::~BufferMenuView() {} -void swiot::BufferMenuView::init(QString title, QString function, QColor* color, QString unit, - double yMin, double yMax) +void swiot::BufferMenuView::init(QString title, QString function, QColor *color, QString unit, double yMin, double yMax) { initInteractiveMenu(); - setMenuHeader(title,color,false); - createHeaderWidget(title);; + setMenuHeader(title, color, false); + createHeaderWidget(title); + ; m_advanceSettingsSection = new gui::SubsectionSeparator("SETTINGS", false); m_advanceSettingsSection->getLabel()->setStyleSheet("color:gray;"); @@ -54,10 +53,9 @@ void swiot::BufferMenuView::init(QString title, QString function, QColor* color, m_swiotAdvMenu = swiot::BufferMenuBuilder::newAdvMenu(m_advanceSettingsSection->getContentWidget(), function); m_swiotAdvMenu->setupVerticalSettingsMenu(m_verticalSettingsSection->getContentWidget(), unit, yMin, yMax); QVector layers = m_swiotAdvMenu->getMenuLayers(); - for (int i = 0; i < layers.size(); i++) { + for(int i = 0; i < layers.size(); i++) { m_advanceSettingsSection->getContentWidget()->layout()->addItem(layers[i]); } - } void swiot::BufferMenuView::initAdvMenu(QMap> values) @@ -72,7 +70,7 @@ void swiot::BufferMenuView::createHeaderWidget(const QString title) headerWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); QHBoxLayout *headerLayout = new QHBoxLayout(headerWidget); - headerLayout->setContentsMargins(0,0,0,0); + headerLayout->setContentsMargins(0, 0, 0, 0); headerLayout->setSpacing(0); m_btnInfoStatus = new scopy::LinkedButton(); m_btnInfoStatus->installEventFilter(this); @@ -80,8 +78,8 @@ void swiot::BufferMenuView::createHeaderWidget(const QString title) m_btnInfoStatus->setCheckable(false); m_btnInfoStatus->setText(QString()); m_btnInfoStatus->setToolTip("For each output channel, a buffered\n" - "input channel is generated which is\n" - "displayed on the plot"); + "input channel is generated which is\n" + "displayed on the plot"); headerLayout->insertWidget(headerLayout->count(), new QLabel(title)); headerLayout->insertWidget(headerLayout->count(), m_btnInfoStatus); addNewHeaderWidget(headerWidget); @@ -89,9 +87,8 @@ void swiot::BufferMenuView::createHeaderWidget(const QString title) bool swiot::BufferMenuView::eventFilter(QObject *obj, QEvent *event) { - if (obj == (QObject*)m_btnInfoStatus) { - if (event->type() == QEvent::Enter) - { + if(obj == (QObject *)m_btnInfoStatus) { + if(event->type() == QEvent::Enter) { m_btnInfoStatus->setToolTip(m_swiotAdvMenu->getInfoMessage()); } return false; @@ -100,7 +97,4 @@ bool swiot::BufferMenuView::eventFilter(QObject *obj, QEvent *event) } } -swiot::BufferMenu* swiot::BufferMenuView::getAdvMenu() -{ - return m_swiotAdvMenu; -} +swiot::BufferMenu *swiot::BufferMenuView::getAdvMenu() { return m_swiotAdvMenu; } diff --git a/plugins/swiot/src/runtime/ad74413r/buffermenuview.h b/plugins/swiot/src/runtime/ad74413r/buffermenuview.h index a738e68577..09445f2705 100644 --- a/plugins/swiot/src/runtime/ad74413r/buffermenuview.h +++ b/plugins/swiot/src/runtime/ad74413r/buffermenuview.h @@ -18,23 +18,25 @@ * along with this program. If not, see . */ - #ifndef SWIOTGENERICMENU_H #define SWIOTGENERICMENU_H -#include -#include #include "buffermenu.h" #include "linked_button.hpp" + #include #include +#include + +#include namespace scopy { class CustomSwitch; class GenericMenu; namespace swiot { -class BufferMenuView : public gui::GenericMenu { +class BufferMenuView : public gui::GenericMenu +{ Q_OBJECT public: explicit BufferMenuView(QWidget *parent = nullptr); @@ -55,7 +57,7 @@ class BufferMenuView : public gui::GenericMenu { scopy::gui::SubsectionSeparator *m_verticalSettingsSection; scopy::LinkedButton *m_btnInfoStatus; }; -} -} +} // namespace swiot +} // namespace scopy #endif // SWIOTGENERICMENU_H diff --git a/plugins/swiot/src/runtime/ad74413r/bufferplothandler.cpp b/plugins/swiot/src/runtime/ad74413r/bufferplothandler.cpp index a0214e8616..0759a464ae 100644 --- a/plugins/swiot/src/runtime/ad74413r/bufferplothandler.cpp +++ b/plugins/swiot/src/runtime/ad74413r/bufferplothandler.cpp @@ -18,49 +18,52 @@ * along with this program. If not, see . */ - #include "bufferplothandler.h" -#include -#include + #include "linked_button.hpp" #include "pluginbase/preferences.h" #include "qlabel.h" #include "src/runtime/ad74413r/ad74413r.h" #include "src/swiot_logging_categories.h" + #include +#include + +#include #include using namespace scopy::swiot; -BufferPlotHandler::BufferPlotHandler(QWidget *parent, int plotChnlsNo) : - QWidget(parent) +BufferPlotHandler::BufferPlotHandler(QWidget *parent, int plotChnlsNo) + : QWidget(parent) { m_lock = new QMutex(); m_plotChnlsNo = plotChnlsNo; - m_plot = new CapturePlot(parent, false, 16, 10, new TimePrefixFormatter, new MetricPrefixFormatter, QwtAxis::YRight); + m_plot = new CapturePlot(parent, false, 16, 10, new TimePrefixFormatter, new MetricPrefixFormatter, + QwtAxis::YRight); m_plotScalesController = new ChannelPlotScalesController(this); initPlot(plotChnlsNo); readPreferences(); } BufferPlotHandler::~BufferPlotHandler() { - if (m_dataPoints.size() > 0) { - for (int i = 0; i < m_dataPoints.size(); i++) { + if(m_dataPoints.size() > 0) { + for(int i = 0; i < m_dataPoints.size(); i++) { delete[] m_dataPoints[i]; m_dataPoints[i] = nullptr; } } - if (m_plot) { + if(m_plot) { delete m_plot; } - if (m_plotScalesController) { + if(m_plotScalesController) { delete m_plotScalesController; } } void BufferPlotHandler::initPlot(int plotChnlsNo) { - //the last 4 channels are for diagnostic + // the last 4 channels are for diagnostic int configuredChnlsNo = plotChnlsNo - DIAG_CHNLS_NUMBER; m_enabledPlots = std::vector(plotChnlsNo, false); @@ -79,8 +82,7 @@ void BufferPlotHandler::initPlot(int plotChnlsNo) m_plotWidget->setStyleSheet("background-color:black;"); m_plotWidget->setLayout(gridPlot); - QSpacerItem *plotSpacer = new QSpacerItem(0, 5, - QSizePolicy::Fixed, QSizePolicy::Fixed); + QSpacerItem *plotSpacer = new QSpacerItem(0, 5, QSizePolicy::Fixed, QSizePolicy::Fixed); gridPlot->addWidget(m_plot->topArea(), 1, 0, 1, 4); gridPlot->addWidget(m_plot->topHandlesArea(), 2, 0, 1, 4); @@ -99,14 +101,12 @@ void BufferPlotHandler::initPlot(int plotChnlsNo) m_plot->enableColoredLabels(true); updatePlotTimespan(); - for (unsigned int i = 0; i < plotChnlsNo; i++) { - m_plot->Curve(i)->setAxes( - QwtAxisId(QwtAxis::XBottom, 0), - QwtAxisId(QwtAxis::YRight, i)); - if (i < configuredChnlsNo) { - m_plot->Curve(i)->setTitle("CH " + QString::number(i+1)); + for(unsigned int i = 0; i < plotChnlsNo; i++) { + m_plot->Curve(i)->setAxes(QwtAxisId(QwtAxis::XBottom, 0), QwtAxisId(QwtAxis::YRight, i)); + if(i < configuredChnlsNo) { + m_plot->Curve(i)->setTitle("CH " + QString::number(i + 1)); } else { - m_plot->Curve(i)->setTitle("DIAG " + QString::number(i+1)); + m_plot->Curve(i)->setTitle("DIAG " + QString::number(i + 1)); } m_plot->DetachCurve(i); m_plot->setOffsetHandleVisible(i, false); @@ -141,27 +141,23 @@ void BufferPlotHandler::initStatusWidget() m_plot->setStatusWidget(statusWidget); } -void BufferPlotHandler::setYAxisVisible(bool visible) -{ - m_plot->setAxisVisible(QwtAxis::YRight, visible); -} +void BufferPlotHandler::setYAxisVisible(bool visible) { m_plot->setAxisVisible(QwtAxis::YRight, visible); } void BufferPlotHandler::setHandlesName(QMap chnlsId) { - connect(m_plot, &CapturePlot::channelOffsetChanged, this, [=, this] (int chn, double offset) { + connect(m_plot, &CapturePlot::channelOffsetChanged, this, [=, this](int chn, double offset) { double unitPerDiv = m_plot->VertUnitsPerDiv(chn); int curveId = m_channelCurveId[chn]; setUnitPerDivision(curveId, unitPerDiv); - }); QList offsetHandles = m_plot->getOffsetHandles(); - int offsetHandlesSize =offsetHandles.size(); + int offsetHandlesSize = offsetHandles.size(); int mapSize = chnlsId.size(); int activeChnlsIndex = 0; - if (mapSize == offsetHandlesSize) { + if(mapSize == offsetHandlesSize) { auto keys = chnlsId.keys(); - for (int key : keys) { - if (activeChnlsIndex < (m_plotChnlsNo - DIAG_CHNLS_NUMBER)) { + for(int key : keys) { + if(activeChnlsIndex < (m_plotChnlsNo - DIAG_CHNLS_NUMBER)) { QString chId = QString::number(key + 1); offsetHandles[activeChnlsIndex]->setName(chnlsId[key][0].toUpper() + chId); } else { @@ -171,10 +167,9 @@ void BufferPlotHandler::setHandlesName(QMap chnlsId) activeChnlsIndex++; } } - } -//bufferCounter is used only for debug +// bufferCounter is used only for debug void BufferPlotHandler::onBufferRefilled(QVector> bufferData, int bufferCounter) { int plotSampleNumber = m_plotSampleRate * m_timespan; @@ -183,21 +178,21 @@ void BufferPlotHandler::onBufferRefilled(QVector> bufferData, in bool rolling = false; m_lock->lock(); resetDataPoints(); - if (!(m_singleCapture && (m_bufferIndex == m_buffersNumber))) { - if (bufferDataSize > 0) { + if(!(m_singleCapture && (m_bufferIndex == m_buffersNumber))) { + if(bufferDataSize > 0) { int currentPlotDataSamplesNumber = 0; - for (int i = 0; i < m_dataPointsDeque.size(); i++) { - if (m_bufferIndex == m_buffersNumber) - { + for(int i = 0; i < m_dataPointsDeque.size(); i++) { + if(m_bufferIndex == m_buffersNumber) { int dequeSize = m_dataPointsDeque[i].size(); - if (dequeSize > 0) { + if(dequeSize > 0) { m_dataPointsDeque[i].pop_front(); rolling = true; } } else { int lastBuffer = plotSampleNumber % m_bufferSize; - if ((m_bufferIndex == (m_buffersNumber - 1)) && lastBuffer != 0 ) { - currentPlotDataSamplesNumber = (m_bufferIndex * m_bufferSize) + lastBuffer; + if((m_bufferIndex == (m_buffersNumber - 1)) && lastBuffer != 0) { + currentPlotDataSamplesNumber = + (m_bufferIndex * m_bufferSize) + lastBuffer; } else { currentPlotDataSamplesNumber = (m_bufferIndex + 1) * m_bufferSize; } @@ -207,7 +202,7 @@ void BufferPlotHandler::onBufferRefilled(QVector> bufferData, in m_plot->resetXaxisOnNextReceivedData(); m_samplesAquiredLabel->setText(QString::number(currentPlotDataSamplesNumber)); } - if (m_enabledPlots[i] && (enPlotIndex < bufferDataSize)) { + if(m_enabledPlots[i] && (enPlotIndex < bufferDataSize)) { m_dataPointsDeque[i].push_back(bufferData[enPlotIndex]); enPlotIndex++; } @@ -216,34 +211,34 @@ void BufferPlotHandler::onBufferRefilled(QVector> bufferData, in drawPlot(); } } - if (m_singleCapture && (m_bufferIndex == m_buffersNumber)) { + if(m_singleCapture && (m_bufferIndex == m_buffersNumber)) { Q_EMIT singleCaptureFinished(); } m_lock->unlock(); } -int BufferPlotHandler::getRequiredBuffersNumber() -{ - return m_buffersNumber; -} +int BufferPlotHandler::getRequiredBuffersNumber() { return m_buffersNumber; } void BufferPlotHandler::drawPlot() { int plotSampleNumber = m_plotSampleRate * m_timespan; int dataPointsNumber = m_bufferIndex * m_bufferSize; int lastBufferData = plotSampleNumber % m_bufferSize; - if ((m_bufferIndex == m_buffersNumber) && (lastBufferData != 0)) { + if((m_bufferIndex == m_buffersNumber) && (lastBufferData != 0)) { dataPointsNumber = (dataPointsNumber - m_bufferSize) + lastBufferData; } - for (int i = 0; i < m_dataPointsDeque.size(); i++) { + for(int i = 0; i < m_dataPointsDeque.size(); i++) { m_dataPoints.push_back(new double[dataPointsNumber]()); int dequeSize = m_dataPointsDeque[i].size(); - if (dequeSize > 0) { - for (int j = 0; j < dequeSize; j++) { - if (j == (m_buffersNumber - 1) && (lastBufferData != 0)) { - std::copy(m_dataPointsDeque[i][j].begin(), m_dataPointsDeque[i][j].begin() + lastBufferData, m_dataPoints[i] + (j * m_bufferSize)); + if(dequeSize > 0) { + for(int j = 0; j < dequeSize; j++) { + if(j == (m_buffersNumber - 1) && (lastBufferData != 0)) { + std::copy(m_dataPointsDeque[i][j].begin(), + m_dataPointsDeque[i][j].begin() + lastBufferData, + m_dataPoints[i] + (j * m_bufferSize)); } else { - std::copy(m_dataPointsDeque[i][j].begin(), m_dataPointsDeque[i][j].end(), m_dataPoints[i] + (j * m_bufferSize)); + std::copy(m_dataPointsDeque[i][j].begin(), m_dataPointsDeque[i][j].end(), + m_dataPoints[i] + (j * m_bufferSize)); } } } @@ -253,7 +248,7 @@ void BufferPlotHandler::drawPlot() void BufferPlotHandler::setChnlsUnitOfMeasure(QVector unitsOfMeasure) { - for (int i = 0; i < m_plot->leftVertAxesCount(); i++) { + for(int i = 0; i < m_plot->leftVertAxesCount(); i++) { m_plot->setYaxisUnit(unitsOfMeasure[i], i); } m_plot->replot(); @@ -276,10 +271,7 @@ void BufferPlotHandler::addChannelScale(int index, QColor color, QString unit, b m_plotScalesController->addChannel(index, color, unit, enabled); } -void BufferPlotHandler::mapChannelCurveId(int curveId, int channelId) -{ - m_channelCurveId.insert(curveId, channelId); -} +void BufferPlotHandler::mapChannelCurveId(int curveId, int channelId) { m_channelCurveId.insert(curveId, channelId); } void BufferPlotHandler::updateScale(int channel) { @@ -299,11 +291,11 @@ void BufferPlotHandler::onBtnExportClicked(QMap exportConfig) QString selectedFilter = filter[0]; - QString fileName = QFileDialog::getSaveFileName(this, - tr("Export"), "", filter.join(";;"), - &selectedFilter, (useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); + QString fileName = QFileDialog::getSaveFileName( + this, tr("Export"), "", filter.join(";;"), &selectedFilter, + (useNativeDialogs ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog)); - if (fileName.split(".").size() <= 1) { + if(fileName.split(".").size() <= 1) { // file name w/o extension. Let's append it QString ext = selectedFilter.split(".")[1].split(")")[0]; fileName += "." + ext; @@ -311,35 +303,35 @@ void BufferPlotHandler::onBtnExportClicked(QMap exportConfig) bool atleastOneChannelEnabled = false; auto keys = exportConfig.keys(); - for (auto x : qAsConst(keys)) - if (exportConfig[x]){ + for(auto x : qAsConst(keys)) + if(exportConfig[x]) { atleastOneChannelEnabled = true; break; } - if (!atleastOneChannelEnabled){ + if(!atleastOneChannelEnabled) { return; } - if (!fileName.isEmpty()){ + if(!fileName.isEmpty()) { FileManager fm("SWIOTad74413rRuntime"); fm.open(fileName, FileManager::EXPORT); QVector time_data; - for (size_t i = 0; i < m_plot->Curve(0)->data()->size(); ++i) { + for(size_t i = 0; i < m_plot->Curve(0)->data()->size(); ++i) { time_data.push_back(m_plot->Curve(0)->sample(i).x()); } fm.save(time_data, "Time(S)"); - for (int i = 0; i < m_plotChnlsNo; ++i){ - if (exportConfig[i]){ + for(int i = 0; i < m_plotChnlsNo; ++i) { + if(exportConfig[i]) { QVector data; int samples = m_plot->Curve(i)->data()->size(); - for (int j = 0; j < samples; ++j) + for(int j = 0; j < samples; ++j) data.push_back(m_plot->Curve(i)->data()->sample(j).y()); QString chNo = QString::number(i + 1); - QString chType = (i < (m_plotChnlsNo - DIAG_CHNLS_NUMBER)) - ? QString("CH") : QString("DIAG"); + QString chType = + (i < (m_plotChnlsNo - DIAG_CHNLS_NUMBER)) ? QString("CH") : QString("DIAG"); fm.save(data, chType + chNo + "(" + m_plot->yAxisUnit(i) + ")"); } } @@ -361,27 +353,18 @@ void BufferPlotHandler::onSamplingFreqWritten(int samplingFreq) resetPlotParameters(); } -void BufferPlotHandler::setSingleCapture(bool en) -{ - m_singleCapture = en; -} +void BufferPlotHandler::setSingleCapture(bool en) { m_singleCapture = en; } -QColor BufferPlotHandler::getCurveColor(int id) const -{ - return m_plot->getLineColor(id); -} +QColor BufferPlotHandler::getCurveColor(int id) const { return m_plot->getLineColor(id); } -QWidget *BufferPlotHandler::getPlotWidget() const -{ - return m_plotWidget; -} +QWidget *BufferPlotHandler::getPlotWidget() const { return m_plotWidget; } void BufferPlotHandler::onChannelWidgetEnabled(int curveId, bool en) { m_enabledPlots[curveId] = en; m_plot->setOffsetHandleVisible(curveId, en); m_plotScalesController->setChannelEnabled(m_channelCurveId.value(curveId), en); - if (en) { + if(en) { m_plot->AttachCurve(curveId); } else { m_plot->DetachCurve(curveId); @@ -395,21 +378,18 @@ void BufferPlotHandler::onChannelWidgetSelected(int curveId) m_plot->setAllAxes(curveId); } -void BufferPlotHandler::onPrintBtnClicked() -{ - m_plot->printWithNoBackground(AD_NAME); -} +void BufferPlotHandler::onPrintBtnClicked() { m_plot->printWithNoBackground(AD_NAME); } void BufferPlotHandler::resetPlotParameters() { m_lock->lock(); - int enabledPlotsNo = std::count(m_enabledPlots.begin(), m_enabledPlots.end(), true); - m_plotSampleRate = (enabledPlotsNo > 0) ? ( m_samplingFreq / enabledPlotsNo ) : m_samplingFreq; + int enabledPlotsNo = std::count(m_enabledPlots.begin(), m_enabledPlots.end(), true); + m_plotSampleRate = (enabledPlotsNo > 0) ? (m_samplingFreq / enabledPlotsNo) : m_samplingFreq; auto plotSampleNumber = m_plotSampleRate * m_timespan; m_bufferSize = (m_samplingFreq > MAX_BUFFER_SIZE) ? MAX_BUFFER_SIZE : MIN_BUFFER_SIZE; - m_buffersNumber = (((int)plotSampleNumber % m_bufferSize) == 0) ? - (plotSampleNumber / m_bufferSize) : ((plotSampleNumber / m_bufferSize) + 1); + m_buffersNumber = (((int)plotSampleNumber % m_bufferSize) == 0) ? (plotSampleNumber / m_bufferSize) + : ((plotSampleNumber / m_bufferSize) + 1); m_bufferIndex = 0; resetDeque(); @@ -419,14 +399,15 @@ void BufferPlotHandler::resetPlotParameters() m_plot->setSampleRate(m_plotSampleRate - 1, 1, ""); m_plot->replot(); - qDebug(CAT_SWIOT_AD74413R) << "Plot samples number: " << QString::number(plotSampleNumber) <<" "<unlock(); } void BufferPlotHandler::resetDataPoints() { - for (int i = 0; i < m_dataPoints.size(); i++) { + for(int i = 0; i < m_dataPoints.size(); i++) { delete[] m_dataPoints[i]; m_dataPoints[i] = nullptr; } @@ -440,7 +421,7 @@ void BufferPlotHandler::resetDeque() m_dataPointsDeque[i].clear(); } m_dataPointsDeque.clear(); - for (int i = 0; i < m_plotChnlsNo; i++) { + for(int i = 0; i < m_plotChnlsNo; i++) { m_dataPointsDeque.push_back(std::deque>()); } } @@ -456,9 +437,9 @@ void BufferPlotHandler::updatePlotTimespan() { double unitsPerDiv = m_timespan / m_plot->xAxisNumDiv(); m_plot->setHorizUnitsPerDiv(unitsPerDiv); - //the offset is calculated so that the 0 moment of time to be on the right side of the x axis - //we divide by 2 the number of x divisions because the moment - //0 of time is by default in the middle of the x Axis + // the offset is calculated so that the 0 moment of time to be on the right side of the x axis + // we divide by 2 the number of x divisions because the moment + // 0 of time is by default in the middle of the x Axis double offset = unitsPerDiv * (m_plot->xAxisNumDiv() / 2); m_plot->setHorizOffset(-offset); m_plot->resetXaxisOnNextReceivedData(); @@ -466,15 +447,15 @@ void BufferPlotHandler::updatePlotTimespan() bool BufferPlotHandler::eventFilter(QObject *obj, QEvent *event) { - if (obj == (QObject*)m_btnInfoStatus) { - if (event->type() == QEvent::Enter) - { + if(obj == (QObject *)m_btnInfoStatus) { + if(event->type() == QEvent::Enter) { auto enabledPlotsNo = std::count(m_enabledPlots.begin(), m_enabledPlots.end(), true); m_btnInfoStatus->setToolTip("sps = samples per second \n" - "sps = sampling_frequency / enabled_channels \n" - "Enabled channels = " + QString::number(enabledPlotsNo) + "\n" + - "Samples per channel = " + m_samplesAquiredLabel->text() + "\n" + - "Sampling frequency = " + QString::number(m_samplingFreq)); + "sps = sampling_frequency / enabled_channels \n" + "Enabled channels = " + + QString::number(enabledPlotsNo) + "\n" + + "Samples per channel = " + m_samplesAquiredLabel->text() + "\n" + + "Sampling frequency = " + QString::number(m_samplingFreq)); } return false; } else { @@ -482,7 +463,4 @@ bool BufferPlotHandler::eventFilter(QObject *obj, QEvent *event) } } -bool BufferPlotHandler::singleCapture() const -{ - return m_singleCapture; -} +bool BufferPlotHandler::singleCapture() const { return m_singleCapture; } diff --git a/plugins/swiot/src/runtime/ad74413r/bufferplothandler.h b/plugins/swiot/src/runtime/ad74413r/bufferplothandler.h index 44b6c57cdd..b2f6dfba8a 100644 --- a/plugins/swiot/src/runtime/ad74413r/bufferplothandler.h +++ b/plugins/swiot/src/runtime/ad74413r/bufferplothandler.h @@ -18,18 +18,19 @@ * along with this program. If not, see . */ - #ifndef BUFFERPLOTHANDLER_H #define BUFFERPLOTHANDLER_H -#include -#include #include "bufferlogic.h" -#include "linked_button.hpp" #include "channelplotscalescontroller.h" -#include +#include "linked_button.hpp" + #include +#include +#include + #include +#include namespace scopy::swiot { #define DIAG_CHNLS_NUMBER 4 @@ -69,6 +70,7 @@ public Q_SLOTS: void singleCaptureFinished(); void offsetHandleSelected(int hdlIdx, bool selected); void unitPerDivisionChanged(int i, double val); + private: void initPlot(int plotChnlsNo); void initStatusWidget(); @@ -84,15 +86,15 @@ public Q_SLOTS: QWidget *m_plotWidget; QLabel *m_samplesAquiredLabel; QLabel *m_plotSamplesNumberLabel; - LinkedButton* m_btnInfoStatus; + LinkedButton *m_btnInfoStatus; ChannelPlotScalesController *m_plotScalesController; int m_samplingFreq = 4800; double m_timespan = 1; int m_plotChnlsNo; - //all of these will be calculated in functions; for example we will have a spinbox for timespan, - //and in a slot we will set its value and we will calculate plotSampleRate and the number of necessary buffers + // all of these will be calculated in functions; for example we will have a spinbox for timespan, + // and in a slot we will set its value and we will calculate plotSampleRate and the number of necessary buffers int m_buffersNumber = 0; int m_bufferIndex = 0; int m_bufferSize = 0; @@ -101,13 +103,13 @@ public Q_SLOTS: bool m_singleCapture = false; std::vector>> m_dataPointsDeque; - std::vector m_dataPoints; + std::vector m_dataPoints; std::vector m_enabledPlots; QMutex *m_lock; QMap m_unitPerDivision; QMap m_channelCurveId; }; -} +} // namespace scopy::swiot #endif // BUFFERPLOTHANDLER_H diff --git a/plugins/swiot/src/runtime/ad74413r/channelplotscale.cpp b/plugins/swiot/src/runtime/ad74413r/channelplotscale.cpp index ed516f8c26..741b6854a0 100644 --- a/plugins/swiot/src/runtime/ad74413r/channelplotscale.cpp +++ b/plugins/swiot/src/runtime/ad74413r/channelplotscale.cpp @@ -19,6 +19,7 @@ */ #include "channelplotscale.h" + #include using namespace scopy::swiot; @@ -43,28 +44,26 @@ ChannelPlotScale::ChannelPlotScale(int channel, QString unit, QColor color, QWid layout->addWidget(m_unitPerDivisionLbl); layout->addWidget(m_instantValueLbl); - connect(this, &ChannelPlotScale::requestUpdate, this, &ChannelPlotScale::update); m_unitPerDivisionLbl->setStyleSheet(QString("QLabel {" "color: %1;" "font-weight: bold;" - "}").arg(m_channelColor.name())); + "}") + .arg(m_channelColor.name())); m_instantValueLbl->setStyleSheet(QString("QLabel {" - "color: %1;" - "font-weight: bold;" - "}").arg(m_channelColor.name())); + "color: %1;" + "font-weight: bold;" + "}") + .arg(m_channelColor.name())); setInstantValue(0); setUnitPerDivision(0); } -ChannelPlotScale::~ChannelPlotScale() -{ - delete m_formatter; -} +ChannelPlotScale::~ChannelPlotScale() { delete m_formatter; } void ChannelPlotScale::setInstantValue(double value) { - if (qFuzzyCompare(m_instantValue, value)) + if(qFuzzyCompare(m_instantValue, value)) return; m_instantValue = value; Q_EMIT requestUpdate(); @@ -72,7 +71,7 @@ void ChannelPlotScale::setInstantValue(double value) void ChannelPlotScale::setUnitPerDivision(double value) { - if (qFuzzyCompare(m_unitPerDivision, value)) + if(qFuzzyCompare(m_unitPerDivision, value)) return; m_unitPerDivision = value; Q_EMIT requestUpdate(); @@ -80,23 +79,12 @@ void ChannelPlotScale::setUnitPerDivision(double value) void ChannelPlotScale::update() { - m_unitPerDivisionLbl->setText(m_formatter->format( - m_unitPerDivision, m_unit + "/div", 2)); - m_instantValueLbl->setText(m_formatter->format( - m_instantValue, m_unit, 2)); + m_unitPerDivisionLbl->setText(m_formatter->format(m_unitPerDivision, m_unit + "/div", 2)); + m_instantValueLbl->setText(m_formatter->format(m_instantValue, m_unit, 2)); } -int ChannelPlotScale::getChannelId() -{ - return m_channel; -} +int ChannelPlotScale::getChannelId() { return m_channel; } -bool ChannelPlotScale::getEnabled() -{ - return m_enabled; -} +bool ChannelPlotScale::getEnabled() { return m_enabled; } -void ChannelPlotScale::setEnabled(bool en) -{ - m_enabled = en; -} +void ChannelPlotScale::setEnabled(bool en) { m_enabled = en; } diff --git a/plugins/swiot/src/runtime/ad74413r/channelplotscale.h b/plugins/swiot/src/runtime/ad74413r/channelplotscale.h index 1152bf6646..1d5b000cfb 100644 --- a/plugins/swiot/src/runtime/ad74413r/channelplotscale.h +++ b/plugins/swiot/src/runtime/ad74413r/channelplotscale.h @@ -18,12 +18,12 @@ * along with this program. If not, see . */ - #ifndef CHANNELPLOTSCALE_H #define CHANNELPLOTSCALE_H -#include #include +#include + #include namespace scopy::swiot { @@ -44,6 +44,7 @@ class ChannelPlotScale : public QWidget private Q_SLOTS: void update(); + private: QString m_unit; QLabel *m_unitPerDivisionLbl; @@ -54,9 +55,7 @@ private Q_SLOTS: double m_instantValue; bool m_enabled; MetricPrefixFormatter *m_formatter; - }; -} - +} // namespace scopy::swiot -#endif //CHANNELPLOTSCALE_H +#endif // CHANNELPLOTSCALE_H diff --git a/plugins/swiot/src/runtime/ad74413r/channelplotscalescontroller.cpp b/plugins/swiot/src/runtime/ad74413r/channelplotscalescontroller.cpp index a8dc3240a8..aacc9508b5 100644 --- a/plugins/swiot/src/runtime/ad74413r/channelplotscalescontroller.cpp +++ b/plugins/swiot/src/runtime/ad74413r/channelplotscalescontroller.cpp @@ -19,6 +19,7 @@ */ #include "channelplotscalescontroller.h" + #include #include using namespace scopy::swiot; @@ -30,15 +31,15 @@ ChannelPlotScalesController::ChannelPlotScalesController(QWidget *parent) auto layout = new QHBoxLayout(this); layout->setMargin(0); layout->setSpacing(10); - layout->addSpacerItem(new QSpacerItem(0,0, QSizePolicy::Expanding)); + layout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding)); this->setLayout(m_layout); } ChannelPlotScalesController::~ChannelPlotScalesController() { - if (m_layout) { + if(m_layout) { QLayoutItem *child; - while ((child = m_layout->takeAt(0)) != nullptr) { + while((child = m_layout->takeAt(0)) != nullptr) { delete child->widget(); delete child; } @@ -57,10 +58,10 @@ void ChannelPlotScalesController::addChannel(int index, QColor color, QString un void ChannelPlotScalesController::updateLayout() { - QHBoxLayout* mainLayout = (QHBoxLayout* )this->layout(); - if (m_layout) { + QHBoxLayout *mainLayout = (QHBoxLayout *)this->layout(); + if(m_layout) { QLayoutItem *child; - while ((child = m_layout->takeAt(0)) != nullptr) { + while((child = m_layout->takeAt(0)) != nullptr) { delete child; } mainLayout->removeItem(m_layout); @@ -69,7 +70,7 @@ void ChannelPlotScalesController::updateLayout() m_layout = new QHBoxLayout(this); m_layout->setMargin(0); m_layout->setSpacing(20); - for (auto chnPlotScale : qAsConst(m_channelPlotScales)) { + for(auto chnPlotScale : qAsConst(m_channelPlotScales)) { m_layout->addWidget(chnPlotScale); } mainLayout->insertLayout(0, m_layout); @@ -77,8 +78,8 @@ void ChannelPlotScalesController::updateLayout() void ChannelPlotScalesController::setChannelEnabled(int channel, bool enable) { - for (auto chn : qAsConst(m_channelPlotScales)) { - if (chn->getChannelId() == channel) { + for(auto chn : qAsConst(m_channelPlotScales)) { + if(chn->getChannelId() == channel) { chn->setEnabled(enable); chn->setVisible(enable); break; @@ -89,8 +90,8 @@ void ChannelPlotScalesController::setChannelEnabled(int channel, bool enable) void ChannelPlotScalesController::setUnitPerDivision(int channel, double unitPerDivision) { - for (auto chn : qAsConst(m_channelPlotScales)) { - if (chn->getChannelId() == channel) { + for(auto chn : qAsConst(m_channelPlotScales)) { + if(chn->getChannelId() == channel) { chn->setUnitPerDivision(unitPerDivision); break; } @@ -99,8 +100,8 @@ void ChannelPlotScalesController::setUnitPerDivision(int channel, double unitPer void ChannelPlotScalesController::setInstantValue(int channel, double value) { - for (auto chn : qAsConst(m_channelPlotScales)) { - if (chn->getChannelId() == channel) { + for(auto chn : qAsConst(m_channelPlotScales)) { + if(chn->getChannelId() == channel) { chn->setInstantValue(value); break; } diff --git a/plugins/swiot/src/runtime/ad74413r/channelplotscalescontroller.h b/plugins/swiot/src/runtime/ad74413r/channelplotscalescontroller.h index 2e3de51a97..9270fdb44a 100644 --- a/plugins/swiot/src/runtime/ad74413r/channelplotscalescontroller.h +++ b/plugins/swiot/src/runtime/ad74413r/channelplotscalescontroller.h @@ -21,11 +21,13 @@ #ifndef CHANNELPLOTSCALESCONTROLLER_H #define CHANNELPLOTSCALESCONTROLLER_H -#include -#include +#include "channelplotscale.h" + #include +#include +#include + #include -#include "channelplotscale.h" namespace scopy::swiot { class ChannelPlotScalesController : public QWidget @@ -39,15 +41,16 @@ class ChannelPlotScalesController : public QWidget void setChannelEnabled(int channel, bool enabled); void setUnitPerDivision(int channel, double unitPerDivision); void setInstantValue(int channel, double value); + private: void updateLayout(); + private: QString m_unit; QColor *m_channelColor; QVector m_channelPlotScales; QHBoxLayout *m_layout; }; -} - +} // namespace scopy::swiot -#endif //CHANNELPLOTSCALESCONTROLLER_H +#endif // CHANNELPLOTSCALESCONTROLLER_H diff --git a/plugins/swiot/src/runtime/ad74413r/chnlinfo.cpp b/plugins/swiot/src/runtime/ad74413r/chnlinfo.cpp index a42a0c1184..0b583a8a5e 100644 --- a/plugins/swiot/src/runtime/ad74413r/chnlinfo.cpp +++ b/plugins/swiot/src/runtime/ad74413r/chnlinfo.cpp @@ -1,17 +1,18 @@ #include "chnlinfo.h" -#include + #include +#include using namespace scopy::swiot; -ChnlInfo::ChnlInfo(QString plotUm, QString hwUm, iio_channel *iioChnl, CommandQueue *cmdQueue) : - m_iioChnl(iioChnl), - m_plotUm(plotUm), - m_hwUm(hwUm), - m_commandQueue(cmdQueue) +ChnlInfo::ChnlInfo(QString plotUm, QString hwUm, iio_channel *iioChnl, CommandQueue *cmdQueue) + : m_iioChnl(iioChnl) + , m_plotUm(plotUm) + , m_hwUm(hwUm) + , m_commandQueue(cmdQueue) { m_offsetScalePair = {0, 1}; - if (m_iioChnl) { + if(m_iioChnl) { iio_channel_disable(iioChnl); m_chnlId = QString(iio_channel_get_id(m_iioChnl)); double offset = 0.0; @@ -31,7 +32,7 @@ ChnlInfo::ChnlInfo(QString plotUm, QString hwUm, iio_channel *iioChnl, CommandQu ChnlInfo::~ChnlInfo() { - if (m_commandQueue) { + if(m_commandQueue) { m_commandQueue = nullptr; } } @@ -39,100 +40,72 @@ ChnlInfo::~ChnlInfo() void ChnlInfo::addReadScaleCommand() { Command *attrReadScale = new IioChannelAttributeRead(m_iioChnl, "scale", nullptr); - connect(attrReadScale, &scopy::Command::finished, this, - &ChnlInfo::readScaleCommandFinished, Qt::QueuedConnection); + connect(attrReadScale, &scopy::Command::finished, this, &ChnlInfo::readScaleCommandFinished, + Qt::QueuedConnection); m_commandQueue->enqueue(attrReadScale); } void ChnlInfo::addReadOffsetCommand() { Command *attrReadOffset = new IioChannelAttributeRead(m_iioChnl, "offset", nullptr); - connect(attrReadOffset, &scopy::Command::finished, this, - &ChnlInfo::readOffsetCommandFinished, Qt::QueuedConnection); + connect(attrReadOffset, &scopy::Command::finished, this, &ChnlInfo::readOffsetCommandFinished, + Qt::QueuedConnection); m_commandQueue->enqueue(attrReadOffset); } void ChnlInfo::readScaleCommandFinished(Command *cmd) { - IioChannelAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { + IioChannelAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { return; } - if (tcmd->getReturnCode() >= 0) { + if(tcmd->getReturnCode() >= 0) { char *res = tcmd->getResult(); bool ok = false; double scale = QString(res).toDouble(&ok); - if (ok) { + if(ok) { m_offsetScalePair.second = scale; } } else { -// qDebug(CAT_SWIOT) << "Error, could not read \"scale\" attribute for channel."; + // qDebug(CAT_SWIOT) << "Error, could not read \"scale\" attribute for channel."; } } void ChnlInfo::readOffsetCommandFinished(Command *cmd) { - IioChannelAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { + IioChannelAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { return; } - if (tcmd->getReturnCode() >= 0) { + if(tcmd->getReturnCode() >= 0) { char *res = tcmd->getResult(); bool ok = false; double offset = QString(res).toDouble(&ok); - if (ok) { + if(ok) { m_offsetScalePair.first = offset; } } else { -// qDebug(CAT_SWIOT) << "Error, could not read \"offset\" attribute from channel"; + // qDebug(CAT_SWIOT) << "Error, could not read \"offset\" attribute from channel"; } } +iio_channel *ChnlInfo::iioChnl() const { return m_iioChnl; } -iio_channel *ChnlInfo::iioChnl() const -{ - return m_iioChnl; -} +bool ChnlInfo::isOutput() const { return m_isOutput; } -bool ChnlInfo::isOutput() const -{ - return m_isOutput; -} +bool ChnlInfo::isScanElement() const { return m_isScanElement; } -bool ChnlInfo::isScanElement() const -{ - return m_isScanElement; -} - -QString ChnlInfo::chnlId() const -{ - return m_chnlId; -} +QString ChnlInfo::chnlId() const { return m_chnlId; } -std::pair ChnlInfo::rangeValues() const -{ - return m_rangeValues; -} +std::pair ChnlInfo::rangeValues() const { return m_rangeValues; } -std::pair ChnlInfo::offsetScalePair() const -{ - return m_offsetScalePair; -} +std::pair ChnlInfo::offsetScalePair() const { return m_offsetScalePair; } -bool ChnlInfo::isEnabled() const -{ - return m_isEnabled; -} +bool ChnlInfo::isEnabled() const { return m_isEnabled; } -void ChnlInfo::setIsEnabled(bool newIsEnabled) -{ - m_isEnabled = newIsEnabled; -} +void ChnlInfo::setIsEnabled(bool newIsEnabled) { m_isEnabled = newIsEnabled; } -QString ChnlInfo::unitOfMeasure() const -{ - return m_plotUm; -} +QString ChnlInfo::unitOfMeasure() const { return m_plotUm; } void ChnlInfo::initUnitOfMeasureFactor() { diff --git a/plugins/swiot/src/runtime/ad74413r/chnlinfo.h b/plugins/swiot/src/runtime/ad74413r/chnlinfo.h index 1e158d6cb8..862b103171 100644 --- a/plugins/swiot/src/runtime/ad74413r/chnlinfo.h +++ b/plugins/swiot/src/runtime/ad74413r/chnlinfo.h @@ -2,21 +2,22 @@ #define CHNLINFO_H #include "plot_utils.hpp" -#include + #include + +#include +#include + #include #include -#include -#define SWAP_UINT32(x) (((x) >> 24) | (((x) & 0x00FF0000) >> 8) | (((x) & 0x0000FF00) << 8) | ((x) << 24)) +#define SWAP_UINT32(x) (((x) >> 24) | (((x)&0x00FF0000) >> 8) | (((x)&0x0000FF00) << 8) | ((x) << 24)) namespace scopy::swiot { class ChnlInfo : public QObject { Q_OBJECT public: - explicit ChnlInfo(QString plotUm, QString hwUm, - iio_channel *iioChnl, - CommandQueue *cmdQueue); + explicit ChnlInfo(QString plotUm, QString hwUm, iio_channel *iioChnl, CommandQueue *cmdQueue); ~ChnlInfo(); virtual double convertData(unsigned int data) = 0; @@ -62,6 +63,6 @@ private Q_SLOTS: void initUnitOfMeasureFactor(); struct iio_channel *m_iioChnl; }; -} +} // namespace scopy::swiot #endif // CHNLINFO_H diff --git a/plugins/swiot/src/runtime/ad74413r/chnlinfobuilder.cpp b/plugins/swiot/src/runtime/ad74413r/chnlinfobuilder.cpp index 16b790e5cf..0715950c8e 100644 --- a/plugins/swiot/src/runtime/ad74413r/chnlinfobuilder.cpp +++ b/plugins/swiot/src/runtime/ad74413r/chnlinfobuilder.cpp @@ -1,14 +1,15 @@ #include "chnlinfobuilder.h" -#include "src/runtime/ad74413r/currentchnlinfo.h" + #include "resistancechnlinfo.h" +#include "src/runtime/ad74413r/currentchnlinfo.h" #include "voltagechnlinfo.h" using namespace scopy::swiot; -ChnlInfo* ChnlInfoBuilder::build(iio_channel *iioChnl, QString id, CommandQueue *cmdQueue) +ChnlInfo *ChnlInfoBuilder::build(iio_channel *iioChnl, QString id, CommandQueue *cmdQueue) { int chnl_type = decodeId(id); - switch (chnl_type) { + switch(chnl_type) { case VOLTAGE: return new VoltageChnlInfo("V", "mV", iioChnl, cmdQueue); case CURRENT: diff --git a/plugins/swiot/src/runtime/ad74413r/chnlinfobuilder.h b/plugins/swiot/src/runtime/ad74413r/chnlinfobuilder.h index aa439b8f57..1e739a5b94 100644 --- a/plugins/swiot/src/runtime/ad74413r/chnlinfobuilder.h +++ b/plugins/swiot/src/runtime/ad74413r/chnlinfobuilder.h @@ -7,27 +7,27 @@ namespace scopy::swiot { class ChnlInfoBuilder { public: - enum ChnlInfoType { - VOLTAGE = 0, - CURRENT = 1, - RESISTANCE = 2 + enum ChnlInfoType + { + VOLTAGE = 0, + CURRENT = 1, + RESISTANCE = 2 }; static int decodeId(QString function) { - if (function.compare("v") == 0) { + if(function.compare("v") == 0) { return VOLTAGE; - } else if (function.compare("c") == 0) { + } else if(function.compare("c") == 0) { return CURRENT; - } else if (function.compare("r") == 0) { + } else if(function.compare("r") == 0) { return RESISTANCE; } else { return -1; } } - static ChnlInfo* build(iio_channel *iioChnl, QString id, CommandQueue *cmdQueue); - + static ChnlInfo *build(iio_channel *iioChnl, QString id, CommandQueue *cmdQueue); }; -} +} // namespace scopy::swiot #endif // CHNLINFOBUILDER_H diff --git a/plugins/swiot/src/runtime/ad74413r/currentchnlinfo.cpp b/plugins/swiot/src/runtime/ad74413r/currentchnlinfo.cpp index cb4226bbeb..b639c2e6e6 100644 --- a/plugins/swiot/src/runtime/ad74413r/currentchnlinfo.cpp +++ b/plugins/swiot/src/runtime/ad74413r/currentchnlinfo.cpp @@ -1,23 +1,19 @@ #include "currentchnlinfo.h" using namespace scopy::swiot; -CurrentChnlInfo::CurrentChnlInfo(QString plotUm, QString hwUm, - iio_channel *iioChnl, CommandQueue *cmdQueue) +CurrentChnlInfo::CurrentChnlInfo(QString plotUm, QString hwUm, iio_channel *iioChnl, CommandQueue *cmdQueue) : ChnlInfo(plotUm, hwUm, iioChnl, cmdQueue) { m_rangeValues = {MIN_CURRENT_VALUE, MAX_CURRENT_VALUE}; } -CurrentChnlInfo::~CurrentChnlInfo() -{} +CurrentChnlInfo::~CurrentChnlInfo() {} double CurrentChnlInfo::convertData(unsigned int data) { double convertedData = 0.0; - double defaultFactor = m_unitOfMeasureFactor.contains(m_hwUm.at(0)) - ? m_unitOfMeasureFactor[m_hwUm.at(0)] : 1; - double newFactor = m_unitOfMeasureFactor.contains(m_plotUm.at(0)) - ? m_unitOfMeasureFactor[m_plotUm.at(0)] : 1; + double defaultFactor = m_unitOfMeasureFactor.contains(m_hwUm.at(0)) ? m_unitOfMeasureFactor[m_hwUm.at(0)] : 1; + double newFactor = m_unitOfMeasureFactor.contains(m_plotUm.at(0)) ? m_unitOfMeasureFactor[m_plotUm.at(0)] : 1; double factor = defaultFactor / newFactor; data <<= 8; data = SWAP_UINT32(data); diff --git a/plugins/swiot/src/runtime/ad74413r/currentchnlinfo.h b/plugins/swiot/src/runtime/ad74413r/currentchnlinfo.h index 191ac3b1cd..78c3dc5be8 100644 --- a/plugins/swiot/src/runtime/ad74413r/currentchnlinfo.h +++ b/plugins/swiot/src/runtime/ad74413r/currentchnlinfo.h @@ -4,17 +4,17 @@ #include "chnlinfo.h" #define MIN_CURRENT_VALUE 0 #define MAX_CURRENT_VALUE 25 -namespace scopy::swiot{ +namespace scopy::swiot { class CurrentChnlInfo : public ChnlInfo { Q_OBJECT public: - explicit CurrentChnlInfo(QString plotUm = "mA", QString hwUm = "mA", - iio_channel *iioChnl = nullptr, CommandQueue *cmdQueue = nullptr); + explicit CurrentChnlInfo(QString plotUm = "mA", QString hwUm = "mA", iio_channel *iioChnl = nullptr, + CommandQueue *cmdQueue = nullptr); ~CurrentChnlInfo(); double convertData(unsigned int data) override; }; -} +} // namespace scopy::swiot #endif // CURRENTCHNLINFO_H diff --git a/plugins/swiot/src/runtime/ad74413r/resistancechnlinfo.cpp b/plugins/swiot/src/runtime/ad74413r/resistancechnlinfo.cpp index 9e5adb5e99..3ecf0c6072 100644 --- a/plugins/swiot/src/runtime/ad74413r/resistancechnlinfo.cpp +++ b/plugins/swiot/src/runtime/ad74413r/resistancechnlinfo.cpp @@ -2,15 +2,13 @@ using namespace scopy::swiot; -ResistanceChnlInfo::ResistanceChnlInfo(QString plotUm, QString hwUm, - iio_channel *iioChnl, CommandQueue *cmdQueue) +ResistanceChnlInfo::ResistanceChnlInfo(QString plotUm, QString hwUm, iio_channel *iioChnl, CommandQueue *cmdQueue) : ChnlInfo(plotUm, hwUm, iioChnl, cmdQueue) { m_rangeValues = {MIN_RESISTANCE_VALUE, MAX_RESISTANCE_VALUE}; } -ResistanceChnlInfo::~ResistanceChnlInfo() -{} +ResistanceChnlInfo::~ResistanceChnlInfo() {} double ResistanceChnlInfo::convertData(unsigned int data) { @@ -18,8 +16,8 @@ double ResistanceChnlInfo::convertData(unsigned int data) data <<= 8; data = SWAP_UINT32(data); data &= 0x0000FFFF; - convertedData = ((ADC_MAX_VALUE - data) != 0) - ? ((data * RPULL_UP) / (ADC_MAX_VALUE - data)) : MAX_RESISTANCE_VALUE; + convertedData = + ((ADC_MAX_VALUE - data) != 0) ? ((data * RPULL_UP) / (ADC_MAX_VALUE - data)) : MAX_RESISTANCE_VALUE; Q_EMIT instantValueChanged(convertedData); return convertedData; } diff --git a/plugins/swiot/src/runtime/ad74413r/resistancechnlinfo.h b/plugins/swiot/src/runtime/ad74413r/resistancechnlinfo.h index 8a8bd33d29..76cc3364f4 100644 --- a/plugins/swiot/src/runtime/ad74413r/resistancechnlinfo.h +++ b/plugins/swiot/src/runtime/ad74413r/resistancechnlinfo.h @@ -6,16 +6,16 @@ #define ADC_MAX_VALUE 65535 #define MIN_RESISTANCE_VALUE 0 #define MAX_RESISTANCE_VALUE 1000000000 -namespace scopy::swiot{ +namespace scopy::swiot { class ResistanceChnlInfo : public ChnlInfo { Q_OBJECT public: - explicit ResistanceChnlInfo(QString plotUm = "Ω", QString hwUm = "Ω", - iio_channel *iioChnl = nullptr, CommandQueue *cmdQueue = nullptr); + explicit ResistanceChnlInfo(QString plotUm = "Ω", QString hwUm = "Ω", iio_channel *iioChnl = nullptr, + CommandQueue *cmdQueue = nullptr); ~ResistanceChnlInfo(); double convertData(unsigned int data) override; }; -} +} // namespace scopy::swiot #endif // RESISTANCECHNLINFO_H diff --git a/plugins/swiot/src/runtime/ad74413r/voltagechnlinfo.cpp b/plugins/swiot/src/runtime/ad74413r/voltagechnlinfo.cpp index c0c99abd8f..be1450a348 100644 --- a/plugins/swiot/src/runtime/ad74413r/voltagechnlinfo.cpp +++ b/plugins/swiot/src/runtime/ad74413r/voltagechnlinfo.cpp @@ -2,23 +2,18 @@ using namespace scopy::swiot; -VoltageChnlInfo::VoltageChnlInfo(QString plotUm, QString hwUm, - iio_channel *iioChnl, CommandQueue *cmdQueue) +VoltageChnlInfo::VoltageChnlInfo(QString plotUm, QString hwUm, iio_channel *iioChnl, CommandQueue *cmdQueue) : ChnlInfo(plotUm, hwUm, iioChnl, cmdQueue) { m_rangeValues = {MIN_VOLTAGE_VALUE, MAX_VOLTAGE_VALUE}; } -VoltageChnlInfo::~VoltageChnlInfo() -{} - +VoltageChnlInfo::~VoltageChnlInfo() {} double VoltageChnlInfo::convertData(unsigned int data) { - double defaultFactor = m_unitOfMeasureFactor.contains(m_hwUm.at(0)) - ? m_unitOfMeasureFactor[m_hwUm.at(0)] : 1; - double newFactor = m_unitOfMeasureFactor.contains(m_plotUm.at(0)) - ? m_unitOfMeasureFactor[m_plotUm.at(0)] : 1; + double defaultFactor = m_unitOfMeasureFactor.contains(m_hwUm.at(0)) ? m_unitOfMeasureFactor[m_hwUm.at(0)] : 1; + double newFactor = m_unitOfMeasureFactor.contains(m_plotUm.at(0)) ? m_unitOfMeasureFactor[m_plotUm.at(0)] : 1; double factor = defaultFactor / newFactor; double convertedData = 0.0; data <<= 8; diff --git a/plugins/swiot/src/runtime/ad74413r/voltagechnlinfo.h b/plugins/swiot/src/runtime/ad74413r/voltagechnlinfo.h index 163ea5eb8c..cb7cc7a0fa 100644 --- a/plugins/swiot/src/runtime/ad74413r/voltagechnlinfo.h +++ b/plugins/swiot/src/runtime/ad74413r/voltagechnlinfo.h @@ -4,17 +4,17 @@ #include "chnlinfo.h" #define MIN_VOLTAGE_VALUE 0 #define MAX_VOLTAGE_VALUE 10 -namespace scopy::swiot{ +namespace scopy::swiot { class VoltageChnlInfo : public ChnlInfo { Q_OBJECT public: - explicit VoltageChnlInfo(QString plotUm = "V", QString hwUm = "mV", - iio_channel *iioChnl = nullptr, CommandQueue *cmdQueue = nullptr); + explicit VoltageChnlInfo(QString plotUm = "V", QString hwUm = "mV", iio_channel *iioChnl = nullptr, + CommandQueue *cmdQueue = nullptr); ~VoltageChnlInfo(); double convertData(unsigned int data) override; }; -} +} // namespace scopy::swiot #endif // VOLTAGECHNLINFO_H diff --git a/plugins/swiot/src/runtime/faults/faults.cpp b/plugins/swiot/src/runtime/faults/faults.cpp index 9d288a15f9..90fd08580c 100644 --- a/plugins/swiot/src/runtime/faults/faults.cpp +++ b/plugins/swiot/src/runtime/faults/faults.cpp @@ -18,34 +18,34 @@ * along with this program. If not, see . */ - #include "faults.h" -#include - -#include -#include #include "src/runtime/max14906/max14906.h" #include "src/swiot_logging_categories.h" + +#include +#include + #include +#include using namespace scopy::swiot; #define POLLING_INTERVAL 1000 -Faults::Faults(struct iio_context *ctx, ToolMenuEntry *tme, QWidget *parent) : - QWidget(parent), - ctx(ctx), - ui(new Ui::Faults), - m_faultsPage(new FaultsPage(ctx, this)), - m_statusLabel(new QLabel(this)), - m_statusContainer(new QWidget(this)), - timer(new QTimer()), - ad74413r_numeric(0), - max14906_numeric(0), - m_backButton(Faults::createBackButton()), - thread(new QThread(this)), - m_tme(tme) +Faults::Faults(struct iio_context *ctx, ToolMenuEntry *tme, QWidget *parent) + : QWidget(parent) + , ctx(ctx) + , ui(new Ui::Faults) + , m_faultsPage(new FaultsPage(ctx, this)) + , m_statusLabel(new QLabel(this)) + , m_statusContainer(new QWidget(this)) + , timer(new QTimer()) + , ad74413r_numeric(0) + , max14906_numeric(0) + , m_backButton(Faults::createBackButton()) + , thread(new QThread(this)) + , m_tme(tme) { qInfo(CAT_SWIOT_FAULTS) << "Initialising SWIOT faults page."; @@ -57,8 +57,9 @@ Faults::Faults(struct iio_context *ctx, ToolMenuEntry *tme, QWidget *parent) : this->initTutorialProperties(); } -Faults::~Faults() { - if (thread) { +Faults::~Faults() +{ + if(thread) { thread->quit(); thread->wait(); delete thread; @@ -66,7 +67,8 @@ Faults::~Faults() { delete ui; } -void Faults::setupDynamicUi(QWidget *parent) { +void Faults::setupDynamicUi(QWidget *parent) +{ scopy::gui::ToolViewRecipe recipe; recipe.helpBtnUrl = ""; recipe.hasRunBtn = true; @@ -80,10 +82,11 @@ void Faults::setupDynamicUi(QWidget *parent) { m_statusContainer->setLayout(new QHBoxLayout(m_statusContainer)); m_statusContainer->layout()->setSpacing(0); - m_statusContainer->layout()->setContentsMargins(0,0,0,0); + m_statusContainer->layout()->setContentsMargins(0, 0, 0, 0); m_statusLabel->setText("The system is powered at limited capacity."); m_statusLabel->setWordWrap(true); - m_statusContainer->setStyleSheet("QWidget{color: #ffc904; background-color: rgba(0, 0, 0, 60); border: 1px solid rgba(0, 0, 0, 30); font-size: 11pt}"); + m_statusContainer->setStyleSheet("QWidget{color: #ffc904; background-color: rgba(0, 0, 0, 60); border: 1px " + "solid rgba(0, 0, 0, 30); font-size: 11pt}"); auto exclamationLabel = new QPushButton(m_statusContainer); exclamationLabel->setIcon(QIcon::fromTheme(":/swiot/warning.svg")); @@ -105,11 +108,10 @@ void Faults::setupDynamicUi(QWidget *parent) { this->setMinimumSize(800, 500); } -void Faults::connectSignalsAndSlots() { - QObject::connect(this->m_toolView->getRunBtn(), &QPushButton::toggled, this, - &Faults::runButtonClicked); - QObject::connect(this->m_toolView->getSingleBtn(), &QPushButton::clicked, this, - &Faults::singleButtonClicked); +void Faults::connectSignalsAndSlots() +{ + QObject::connect(this->m_toolView->getRunBtn(), &QPushButton::toggled, this, &Faults::runButtonClicked); + QObject::connect(this->m_toolView->getSingleBtn(), &QPushButton::clicked, this, &Faults::singleButtonClicked); QObject::connect(m_backButton, &QPushButton::clicked, this, &Faults::onBackBtnPressed); QObject::connect(this->timer, &QTimer::timeout, this, &Faults::pollFaults); @@ -130,26 +132,28 @@ void Faults::onBackBtnPressed() Q_EMIT backBtnPressed(); } -void Faults::runButtonClicked(bool toggled) { +void Faults::runButtonClicked(bool toggled) +{ this->m_toolView->getSingleBtn()->setChecked(false); - if (toggled) { + if(toggled) { this->thread->start(); - if (!this->m_tme->running()) { + if(!this->m_tme->running()) { this->m_tme->setRunning(true); } } else { - if (this->thread->isRunning()) { + if(this->thread->isRunning()) { this->thread->quit(); -// this->thread->wait(); + // this->thread->wait(); } - if (this->m_tme->running()) { + if(this->m_tme->running()) { this->m_tme->setRunning(false); } this->timer->stop(); } } -void Faults::singleButtonClicked() { +void Faults::singleButtonClicked() +{ qDebug(CAT_SWIOT_FAULTS) << "Single button clicked"; this->m_toolView->getRunBtn()->setChecked(false); this->timer->stop(); @@ -157,12 +161,14 @@ void Faults::singleButtonClicked() { this->m_toolView->getSingleBtn()->setChecked(false); } -void Faults::pollFaults() { +void Faults::pollFaults() +{ qDebug(CAT_SWIOT_FAULTS) << "Polling faults..."; this->m_faultsPage->update(); } -QPushButton *Faults::createBackButton() { +QPushButton *Faults::createBackButton() +{ auto *backButton = new QPushButton(); backButton->setObjectName(QString::fromUtf8("backButton")); backButton->setLayoutDirection(Qt::RightToLeft); @@ -184,8 +190,9 @@ QPushButton *Faults::createBackButton() { return backButton; } -void Faults::externalPowerSupply(bool ps) { - if (ps) { +void Faults::externalPowerSupply(bool ps) +{ + if(ps) { m_statusContainer->hide(); } else { m_statusContainer->show(); @@ -193,7 +200,8 @@ void Faults::externalPowerSupply(bool ps) { } } -void Faults::initTutorialProperties() { +void Faults::initTutorialProperties() +{ // initialize components that might be used for the Faults tutorial m_toolView->getSingleBtn()->setProperty("tutorial_name", "SINGLE_BUTTON"); m_toolView->getRunBtn()->setProperty("tutorial_name", "RUN_BUTTON"); diff --git a/plugins/swiot/src/runtime/faults/faults.h b/plugins/swiot/src/runtime/faults/faults.h index 2638ab20ef..635e1584bf 100644 --- a/plugins/swiot/src/runtime/faults/faults.h +++ b/plugins/swiot/src/runtime/faults/faults.h @@ -18,22 +18,23 @@ * along with this program. If not, see . */ - #ifndef FAULTS_H #define FAULTS_H +#include "faultspage.h" #include "pluginbase/toolmenuentry.h" -#include "ui_swiotfaults.h" -#include "faultspage.h" -#include -#include -#include +#include "ui_swiotfaults.h" #include +#include +#include +#include + namespace scopy::swiot { -class Faults : public QWidget { +class Faults : public QWidget +{ Q_OBJECT public: explicit Faults(struct iio_context *ctx, ToolMenuEntry *tme, QWidget *parent = nullptr); @@ -42,7 +43,7 @@ class Faults : public QWidget { void pollFaults(); Q_SIGNALS: - void backBtnPressed(); + void backBtnPressed(); public Q_SLOTS: void runButtonClicked(bool toggled); @@ -52,18 +53,19 @@ public Q_SLOTS: private Q_SLOTS: void onBackBtnPressed(); + private: - void connectSignalsAndSlots(); - void setupDynamicUi(QWidget *parent); + void connectSignalsAndSlots(); + void setupDynamicUi(QWidget *parent); void initTutorialProperties(); - static QPushButton* createBackButton(); + static QPushButton *createBackButton(); - struct iio_context* ctx; + struct iio_context *ctx; Ui::Faults *ui; - QPushButton *m_backButton; - QLabel* m_statusLabel; - QWidget* m_statusContainer; + QPushButton *m_backButton; + QLabel *m_statusLabel; + QWidget *m_statusContainer; QTimer *timer; QThread *thread; @@ -76,5 +78,5 @@ private Q_SLOTS: ToolMenuEntry *m_tme; }; -} +} // namespace scopy::swiot #endif // FAULTS_H diff --git a/plugins/swiot/src/runtime/faults/faultsdevice.cpp b/plugins/swiot/src/runtime/faults/faultsdevice.cpp index ee0e910d99..1440f026c9 100644 --- a/plugins/swiot/src/runtime/faults/faultsdevice.cpp +++ b/plugins/swiot/src/runtime/faults/faultsdevice.cpp @@ -18,36 +18,36 @@ * along with this program. If not, see . */ - #include "faultsdevice.h" -#include + #include "faultsgroup.h" #include "src/swiot_logging_categories.h" + +#include #include #include -#include #include +#include #define FAULT_CHANNEL_NAME "voltage" #define SWIOT_NB_CHANNELS 4 using namespace scopy::swiot; -FaultsDevice::FaultsDevice(const QString& name, QString path, struct iio_device* device, - struct iio_device* swiot, struct iio_context *context, - QVector ®isters, QWidget *parent) - : ui(new Ui::FaultsDevice), - QWidget(parent), - m_faults_explanation(new QWidget(this)), - m_subsectionSeparator(new scopy::gui::SubsectionSeparator("Faults Explanation", true, this)), - m_name(name.toUpper()), - m_path(std::move(path)), - m_device(device), - m_swiot(swiot), - m_context(context), - m_cmdQueue(nullptr), - m_faultNumeric(0), - m_registers(registers) +FaultsDevice::FaultsDevice(const QString &name, QString path, struct iio_device *device, struct iio_device *swiot, + struct iio_context *context, QVector ®isters, QWidget *parent) + : ui(new Ui::FaultsDevice) + , QWidget(parent) + , m_faults_explanation(new QWidget(this)) + , m_subsectionSeparator(new scopy::gui::SubsectionSeparator("Faults Explanation", true, this)) + , m_name(name.toUpper()) + , m_path(std::move(path)) + , m_device(device) + , m_swiot(swiot) + , m_context(context) + , m_cmdQueue(nullptr) + , m_faultNumeric(0) + , m_registers(registers) { ui->setupUi(this); ui->reset_button->setProperty("blue_button", QVariant(true)); @@ -57,10 +57,11 @@ FaultsDevice::FaultsDevice(const QString& name, QString path, struct iio_device* m_faultsGroup = new FaultsGroup(name, m_path, this); connect(this, &FaultsDevice::specialFaultsUpdated, m_faultsGroup, &FaultsGroup::specialFaultsUpdated); connect(m_faultsGroup, &FaultsGroup::specialFaultExplanationChanged, this, &FaultsDevice::updateExplanation); - connect(this, &FaultsDevice::faultNumericUpdated, this, &FaultsDevice::onFaultNumericUpdated, Qt::QueuedConnection); + connect(this, &FaultsDevice::faultNumericUpdated, this, &FaultsDevice::onFaultNumericUpdated, + Qt::QueuedConnection); connect(this, &FaultsDevice::faultRegisterRead, this, &FaultsDevice::onFaultRegisterRead, Qt::QueuedConnection); - if (m_device == nullptr) { + if(m_device == nullptr) { qCritical(CAT_SWIOT_FAULTS) << "No device was found"; } @@ -71,7 +72,7 @@ FaultsDevice::FaultsDevice(const QString& name, QString path, struct iio_device* this->ui->lineEdit_numeric->setFocusPolicy(Qt::NoFocus); // initialize components that might be used for the Faults tutorial - if (m_name == "AD74413R") { + if(m_name == "AD74413R") { this->initTutorialProperties(); } @@ -86,56 +87,57 @@ FaultsDevice::FaultsDevice(const QString& name, QString path, struct iio_device* onFaultNumericUpdated(); } -FaultsDevice::~FaultsDevice() { - if (m_cmdQueue) { +FaultsDevice::~FaultsDevice() +{ + if(m_cmdQueue) { CommandQueueProvider::GetInstance()->close(m_context); } delete ui; } -void FaultsDevice::resetStored() { - for (auto fault: this->m_faultsGroup->getFaults()) { +void FaultsDevice::resetStored() +{ + for(auto fault : this->m_faultsGroup->getFaults()) { fault->setStored(false); } this->updateExplanations(); } -void FaultsDevice::update() { - readRegister(); -} +void FaultsDevice::update() { readRegister(); } void FaultsDevice::updateExplanation(int index) { - QLabel *lbl = dynamic_cast(m_faultExplanationWidgets[index]); - if (lbl) { + QLabel *lbl = dynamic_cast(m_faultExplanationWidgets[index]); + if(lbl) { QString updatedText = m_faultsGroup->getExplanation(index); lbl->setText(updatedText); } m_faults_explanation->ensurePolished(); } -void FaultsDevice::updateExplanations() { +void FaultsDevice::updateExplanations() +{ std::set selected = m_faultsGroup->getSelectedIndexes(); std::set actives = m_faultsGroup->getActiveIndexes(); - if (selected.empty()) { - for (int i = 0; i < m_faultExplanationWidgets.size(); ++i) { + if(selected.empty()) { + for(int i = 0; i < m_faultExplanationWidgets.size(); ++i) { m_faultExplanationWidgets[i]->show(); - if (actives.contains(i)) { + if(actives.contains(i)) { setDynamicProperty(m_faultExplanationWidgets[i], "highlighted", true); } else { setDynamicProperty(m_faultExplanationWidgets[i], "highlighted", false); } } } else { - for (int i = 0; i < m_faultExplanationWidgets.size(); ++i) { - if (selected.contains(i)) { + for(int i = 0; i < m_faultExplanationWidgets.size(); ++i) { + if(selected.contains(i)) { m_faultExplanationWidgets[i]->show(); } else { m_faultExplanationWidgets[i]->hide(); } - if (actives.contains(i)) { + if(actives.contains(i)) { setDynamicProperty(m_faultExplanationWidgets[i], "highlighted", true); } else { setDynamicProperty(m_faultExplanationWidgets[i], "highlighted", false); @@ -146,13 +148,15 @@ void FaultsDevice::updateExplanations() { m_faults_explanation->ensurePolished(); } -void FaultsDevice::updateMinimumHeight() { +void FaultsDevice::updateMinimumHeight() +{ this->ensurePolished(); this->m_faults_explanation->ensurePolished(); this->m_faultsGroup->ensurePolished(); } -void FaultsDevice::initFaultExplanations() { +void FaultsDevice::initFaultExplanations() +{ m_faults_explanation->setLayout(new QVBoxLayout(m_faults_explanation)); m_faults_explanation->layout()->setContentsMargins(0, 0, 0, 0); m_faults_explanation->layout()->setSpacing(0); @@ -160,7 +164,7 @@ void FaultsDevice::initFaultExplanations() { m_faults_explanation->layout()->setSizeConstraint(QLayout::SetMinimumSize); QStringList l = this->m_faultsGroup->getExplanations(); - for (const auto &item: l) { + for(const auto &item : l) { auto widget = new QLabel(item, m_faults_explanation); widget->setTextFormat(Qt::PlainText); widget->setStyleSheet("QWidget[highlighted=true]{color:white;} QWidget{color:#5c5c5c;}"); @@ -172,7 +176,8 @@ void FaultsDevice::initFaultExplanations() { m_faults_explanation->ensurePolished(); } -void FaultsDevice::connectSignalsAndSlots() { +void FaultsDevice::connectSignalsAndSlots() +{ connect(this->ui->clear_selection_button, &QPushButton::clicked, this->m_faultsGroup, &FaultsGroup::clearSelection); connect(this->ui->reset_button, &QPushButton::clicked, this, &FaultsDevice::resetStored); @@ -190,9 +195,9 @@ void FaultsDevice::onFaultNumericUpdated() void FaultsDevice::onFaultRegisterRead(int iReg, uint32_t value) { m_registerValues.insert(iReg, value); - if (m_registerValues.size() == m_registers.size()) { + if(m_registerValues.size() == m_registers.size()) { uint32_t faultRegisterValue = 0; - for (int i = 0; i < m_registerValues.size(); i++) { + for(int i = 0; i < m_registerValues.size(); i++) { faultRegisterValue |= (m_registerValues.at(i) << (i * 8)); } m_faultNumeric = faultRegisterValue; @@ -203,43 +208,46 @@ void FaultsDevice::onFaultRegisterRead(int iReg, uint32_t value) void FaultsDevice::readRegister() { - for (int i = 0; i < m_registers.size(); i++) { + for(int i = 0; i < m_registers.size(); i++) { uint32_t reg_val; uint32_t address = m_registers.at(i); Command *readRegisterCommand = new IioRegisterRead(m_device, address, nullptr); - connect(readRegisterCommand, &scopy::Command::finished, - this, [=, this](scopy::Command* cmd) { - IioRegisterRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { - qCritical(CAT_SWIOT_FAULTS) << m_name << "faults register could not be read."; - return; - } - uint32_t reg = tcmd->getResult(); + connect( + readRegisterCommand, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioRegisterRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + qCritical(CAT_SWIOT_FAULTS) << m_name << "faults register could not be read."; + return; + } + uint32_t reg = tcmd->getResult(); - if (tcmd->getReturnCode() < 0) { - qCritical(CAT_SWIOT_FAULTS) << m_name << "faults register could not be read."; - } else { - qDebug(CAT_SWIOT_FAULTS) << m_name << "faults register read val:" << reg; - try { - Q_EMIT faultRegisterRead(i, reg); - } catch (std::invalid_argument& exception) { + if(tcmd->getReturnCode() < 0) { qCritical(CAT_SWIOT_FAULTS) << m_name << "faults register could not be read."; + } else { + qDebug(CAT_SWIOT_FAULTS) << m_name << "faults register read val:" << reg; + try { + Q_EMIT faultRegisterRead(i, reg); + } catch(std::invalid_argument &exception) { + qCritical(CAT_SWIOT_FAULTS) + << m_name << "faults register could not be read."; + } } - } - }, Qt::QueuedConnection); + }, + Qt::QueuedConnection); m_cmdQueue->enqueue(readRegisterCommand); } } void FaultsDevice::functionConfigCmdFinished(scopy::Command *cmd) { - IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { + IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { qCritical(CAT_SWIOT_FAULTS) << "Error: cannot read swiot special fault property"; return; } - if (tcmd->getReturnCode() < 0) { + if(tcmd->getReturnCode() < 0) { qCritical(CAT_SWIOT_FAULTS) << "Error: cannot read swiot special fault property"; } else { int cmdIndex = m_functionConfigCmds.indexOf(cmd); @@ -251,21 +259,22 @@ void FaultsDevice::functionConfigCmdFinished(scopy::Command *cmd) void FaultsDevice::deviceConfigCmdFinished(scopy::Command *cmd) { - IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { + IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { qCritical(CAT_SWIOT_FAULTS) << "Error: cannot read swiot special fault config property"; return; } - if (tcmd->getReturnCode() < 0) { + if(tcmd->getReturnCode() < 0) { qCritical(CAT_SWIOT_FAULTS) << "Error: cannot read swiot special fault config property"; } else { char *readDevice = tcmd->getResult(); int cmdIndex = m_deviceConfigCmds.indexOf(cmd); - if (std::string(readDevice) == "ad74413r") { + if(std::string(readDevice) == "ad74413r") { QString function = "ch" + QString::number(cmdIndex) + "_function"; - m_functionConfigCmds[cmdIndex] = new IioDeviceAttributeRead(m_swiot, function.toStdString().c_str(), m_cmdQueue); + m_functionConfigCmds[cmdIndex] = + new IioDeviceAttributeRead(m_swiot, function.toStdString().c_str(), m_cmdQueue); connect(m_functionConfigCmds.at(cmdIndex), &scopy::Command::finished, this, &FaultsDevice::functionConfigCmdFinished, Qt::QueuedConnection); disconnect(cmd, &scopy::Command::finished, this, &FaultsDevice::deviceConfigCmdFinished); @@ -276,8 +285,8 @@ void FaultsDevice::deviceConfigCmdFinished(scopy::Command *cmd) void FaultsDevice::initSpecialFaults() { - if (!m_name.contains("MAX")) { - for (int i = 0; i < SWIOT_NB_CHANNELS; ++i) { + if(!m_name.contains("MAX")) { + for(int i = 0; i < SWIOT_NB_CHANNELS; ++i) { std::string device = "ch" + std::to_string(i) + "_device"; m_deviceConfigCmds.push_back(new IioDeviceAttributeRead(m_swiot, device.c_str(), m_cmdQueue)); connect(m_deviceConfigCmds.at(i), &scopy::Command::finished, this, @@ -288,7 +297,8 @@ void FaultsDevice::initSpecialFaults() } } -void FaultsDevice::initTutorialProperties() { +void FaultsDevice::initTutorialProperties() +{ ui->lineEdit_numeric->setProperty("tutorial_name", "AD74413R_NUMERIC"); ui->reset_button->setProperty("tutorial_name", "AD74413R_RESET_STORED"); ui->clear_selection_button->setProperty("tutorial_name", "AD74413R_CLEAR_SELECTION"); diff --git a/plugins/swiot/src/runtime/faults/faultsdevice.h b/plugins/swiot/src/runtime/faults/faultsdevice.h index 601f9124ac..d967659d94 100644 --- a/plugins/swiot/src/runtime/faults/faultsdevice.h +++ b/plugins/swiot/src/runtime/faults/faultsdevice.h @@ -18,28 +18,30 @@ * along with this program. If not, see . */ - #ifndef FAULTSDEVICE_H #define FAULTSDEVICE_H -#include -#include -#include "ui_faultsdevice.h" #include "faultsgroup.h" -#include + +#include "ui_faultsdevice.h" + #include + +#include +#include + +#include #include namespace scopy::swiot { class FaultsGroup; -class FaultsDevice : public QWidget { +class FaultsDevice : public QWidget +{ Q_OBJECT public: - explicit FaultsDevice(const QString& name, QString path, struct iio_device* device, - struct iio_device* swiot, struct iio_context *context, - QVector ®isters, - QWidget* parent = nullptr); + explicit FaultsDevice(const QString &name, QString path, struct iio_device *device, struct iio_device *swiot, + struct iio_context *context, QVector ®isters, QWidget *parent = nullptr); ~FaultsDevice(); void update(); @@ -74,23 +76,23 @@ private Q_SLOTS: CommandQueue *m_cmdQueue; - FaultsGroup* m_faultsGroup; - QVector m_faultExplanationWidgets; + FaultsGroup *m_faultsGroup; + QVector m_faultExplanationWidgets; QString m_name; QString m_path; - struct iio_device* m_device; - struct iio_device* m_swiot; - struct iio_context* m_context; + struct iio_device *m_device; + struct iio_device *m_swiot; + struct iio_context *m_context; uint32_t m_faultNumeric; QVector m_registers; QVector m_registerValues; - QVector m_deviceConfigCmds; - QVector m_functionConfigCmds; + QVector m_deviceConfigCmds; + QVector m_functionConfigCmds; }; -} // scopy::swiot +} // namespace scopy::swiot -#endif //FAULTSDEVICE_H +#endif // FAULTSDEVICE_H diff --git a/plugins/swiot/src/runtime/faults/faultsgroup.cpp b/plugins/swiot/src/runtime/faults/faultsgroup.cpp index 95dbd1282f..f8256574fc 100644 --- a/plugins/swiot/src/runtime/faults/faultsgroup.cpp +++ b/plugins/swiot/src/runtime/faults/faultsgroup.cpp @@ -18,39 +18,39 @@ * along with this program. If not, see . */ +#include "faultsgroup.h" + +#include "src/swiot_logging_categories.h" -#include #include +#include #include #include -#include +#include #include -#include "faultsgroup.h" -#include "src/swiot_logging_categories.h" - - using namespace scopy::swiot; #define MAX_COLS_IN_GRID 100 -FaultsGroup::FaultsGroup(QString name, const QString &path, QWidget *parent) : - QWidget(parent), - ui(new Ui::FaultsGroup), - m_name(std::move(name)), - m_customColGrid(new FlexGridLayout(MAX_COLS_IN_GRID, this)) +FaultsGroup::FaultsGroup(QString name, const QString &path, QWidget *parent) + : QWidget(parent) + , ui(new Ui::FaultsGroup) + , m_name(std::move(name)) + , m_customColGrid(new FlexGridLayout(MAX_COLS_IN_GRID, this)) { ui->setupUi(this); connect(m_customColGrid, &FlexGridLayout::reqestLayoutUpdate, this, [this]() { - if (this->ui->activeStoredLayout->count() != m_customColGrid->rows()) { - while (this->ui->activeStoredLayout->count() < m_customColGrid->rows()) { + if(this->ui->activeStoredLayout->count() != m_customColGrid->rows()) { + while(this->ui->activeStoredLayout->count() < m_customColGrid->rows()) { this->ui->activeStoredLayout->addWidget(this->buildActiveStoredWidget()); } - while (this->ui->activeStoredLayout->count() > m_customColGrid->rows()) { - QWidget *widgetToDelete = this->ui->activeStoredLayout->itemAt( - this->ui->activeStoredLayout->count() - 1)->widget(); + while(this->ui->activeStoredLayout->count() > m_customColGrid->rows()) { + QWidget *widgetToDelete = + this->ui->activeStoredLayout->itemAt(this->ui->activeStoredLayout->count() - 1) + ->widget(); this->ui->activeStoredLayout->removeWidget(widgetToDelete); delete widgetToDelete; } @@ -66,24 +66,26 @@ FaultsGroup::FaultsGroup(QString name, const QString &path, QWidget *parent) : m_max_faults = faults_obj->size(); this->setupDynamicUi(); - for (int i = 0; i < m_max_faults; ++i) { + for(int i = 0; i < m_max_faults; ++i) { QJsonObject fault_object = faults_obj->at(i).toObject(); QString fault_name = fault_object.value("name").toString(); QString fault_description = fault_object.value("description").toString(); auto fault_widget = new FaultWidget(i, fault_name, fault_description, this); - if (fault_object.contains("condition")) { + if(fault_object.contains("condition")) { QJsonObject condition = fault_object["condition"].toObject(); fault_widget->setFaultExplanationOptions(condition); - connect(this, &FaultsGroup::specialFaultsUpdated, fault_widget, &FaultWidget::specialFaultUpdated); - connect(fault_widget, &FaultWidget::specialFaultExplanationChanged, this, &FaultsGroup::specialFaultExplanationChanged); + connect(this, &FaultsGroup::specialFaultsUpdated, fault_widget, + &FaultWidget::specialFaultUpdated); + connect(fault_widget, &FaultWidget::specialFaultExplanationChanged, this, + &FaultsGroup::specialFaultExplanationChanged); } connect(fault_widget, &FaultWidget::faultSelected, this, [this](unsigned int id_) { bool added = m_currentlySelected.insert(id_).second; - if (!added) { + if(!added) { m_currentlySelected.erase(id_); - m_faults.at((int) (id_))->setPressed(false); + m_faults.at((int)(id_))->setPressed(false); } Q_EMIT selectionUpdated(); }); @@ -97,45 +99,40 @@ FaultsGroup::FaultsGroup(QString name, const QString &path, QWidget *parent) : m_customColGrid->itemSizeChanged(); } -FaultsGroup::~FaultsGroup() { - delete ui; -} +FaultsGroup::~FaultsGroup() { delete ui; } -const QVector &FaultsGroup::getFaults() const { - return m_faults; -} +const QVector &FaultsGroup::getFaults() const { return m_faults; } -const QString &FaultsGroup::getName() const { - return m_name; -} +const QString &FaultsGroup::getName() const { return m_name; } -void FaultsGroup::setName(const QString &name_) { - FaultsGroup::m_name = name_; -} +void FaultsGroup::setName(const QString &name_) { FaultsGroup::m_name = name_; } -void FaultsGroup::setupDynamicUi() { +void FaultsGroup::setupDynamicUi() +{ m_customColGrid->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); this->ui->horizontalLayout->addWidget(m_customColGrid); } -void FaultsGroup::clearSelection() { - for (unsigned int i: m_currentlySelected) { - m_faults[(int) (i)]->setPressed(false); +void FaultsGroup::clearSelection() +{ + for(unsigned int i : m_currentlySelected) { + m_faults[(int)(i)]->setPressed(false); } m_currentlySelected.clear(); Q_EMIT selectionUpdated(); } -void FaultsGroup::update(uint32_t faults_numeric) { - for (int i = 0; i < m_faults.size(); i++) { - bool bit = (bool) ((faults_numeric >> i) & 0b1); - if (m_faults.at(i)->isActive() && bit) { // if we get 2 active signals, we set the stored to 1 +void FaultsGroup::update(uint32_t faults_numeric) +{ + for(int i = 0; i < m_faults.size(); i++) { + bool bit = (bool)((faults_numeric >> i) & 0b1); + if(m_faults.at(i)->isActive() && bit) { // if we get 2 active signals, we set the stored to 1 m_faults.at(i)->setStored(true); } m_faults.at(i)->setActive(bit); - if (bit) { + if(bit) { m_actives.insert(i); } else { m_actives.erase(i); @@ -143,28 +140,30 @@ void FaultsGroup::update(uint32_t faults_numeric) { } } -QStringList FaultsGroup::getExplanations() { +QStringList FaultsGroup::getExplanations() +{ QStringList res; - for (auto fault: m_faults) { + for(auto fault : m_faults) { res += getExplanation(fault->getId()); } return res; } -QString FaultsGroup::getExplanation(unsigned int id) { +QString FaultsGroup::getExplanation(unsigned int id) +{ QString res = ""; auto fault = m_faults.at(id); - if (fault) { - res += QString("Bit%1 (%2): %3").arg(QString::number(fault->getId()), - fault->getName(), - fault->getFaultExplanation()); + if(fault) { + res += QString("Bit%1 (%2): %3") + .arg(QString::number(fault->getId()), fault->getName(), fault->getFaultExplanation()); } return res; } -QWidget *FaultsGroup::buildActiveStoredWidget() { +QWidget *FaultsGroup::buildActiveStoredWidget() +{ auto widget = new QWidget(this); auto storedLabel = new QLabel(this); storedLabel->setText("Stored"); @@ -186,12 +185,13 @@ QWidget *FaultsGroup::buildActiveStoredWidget() { return widget; } -QJsonArray *FaultsGroup::getJsonArray(const QString &path) { +QJsonArray *FaultsGroup::getJsonArray(const QString &path) +{ QString contents; QFile file; file.setFileName(path); file.open(QIODevice::ReadOnly | QIODevice::Text); - if (!file.isOpen()) { + if(!file.isOpen()) { qCritical(CAT_SWIOT_FAULTS) << "File could not be opened (read): " << path; } else { qDebug(CAT_SWIOT_FAULTS) << "File opened (read): " << path; @@ -201,11 +201,13 @@ QJsonArray *FaultsGroup::getJsonArray(const QString &path) { QJsonParseError parse_error{}; QJsonDocument document = QJsonDocument::fromJson(contents.toUtf8(), &parse_error); - if (document.isNull()) { qCritical(CAT_SWIOT_FAULTS) << "Invalid json: " << parse_error.errorString(); } + if(document.isNull()) { + qCritical(CAT_SWIOT_FAULTS) << "Invalid json: " << parse_error.errorString(); + } QJsonObject document_object = document.object(); QJsonValue device_value = document_object.value(m_name); - if (device_value == QJsonValue::Undefined) { + if(device_value == QJsonValue::Undefined) { qCritical(CAT_SWIOT_FAULTS) << "Invalid json: Could not extract value " << m_name; } @@ -221,10 +223,6 @@ QJsonArray *FaultsGroup::getJsonArray(const QString &path) { return array; } -std::set FaultsGroup::getSelectedIndexes() { - return this->m_currentlySelected; -} +std::set FaultsGroup::getSelectedIndexes() { return this->m_currentlySelected; } -std::set FaultsGroup::getActiveIndexes() { - return m_actives; -} +std::set FaultsGroup::getActiveIndexes() { return m_actives; } diff --git a/plugins/swiot/src/runtime/faults/faultsgroup.h b/plugins/swiot/src/runtime/faults/faultsgroup.h index 8256c5d48c..9d5f066a94 100644 --- a/plugins/swiot/src/runtime/faults/faultsgroup.h +++ b/plugins/swiot/src/runtime/faults/faultsgroup.h @@ -18,27 +18,30 @@ * along with this program. If not, see . */ - #ifndef FAULTSGROUP_H #define FAULTSGROUP_H -#include +#include "faultwidget.h" + +#include "ui_faultsgroup.h" #include -#include "faultwidget.h" #include -#include "ui_faultsgroup.h" +#include QT_BEGIN_NAMESPACE -namespace Ui { class FaultsGroup; } +namespace Ui { +class FaultsGroup; +} QT_END_NAMESPACE namespace scopy::swiot { -class FaultsGroup : public QWidget { +class FaultsGroup : public QWidget +{ Q_OBJECT public: - explicit FaultsGroup(QString name, const QString& path, QWidget *parent = nullptr); + explicit FaultsGroup(QString name, const QString &path, QWidget *parent = nullptr); ~FaultsGroup() override; const QVector &getFaults() const; @@ -58,6 +61,7 @@ class FaultsGroup : public QWidget { void minimumSizeChanged(); void specialFaultsUpdated(unsigned int index, QString channelFunction); void specialFaultExplanationChanged(unsigned int, QString); + private: Ui::FaultsGroup *ui; QString m_name; @@ -65,13 +69,13 @@ class FaultsGroup : public QWidget { std::set m_currentlySelected; std::set m_actives; int m_max_faults; - FlexGridLayout* m_customColGrid; + FlexGridLayout *m_customColGrid; protected: void setupDynamicUi(); - QWidget* buildActiveStoredWidget(); - QJsonArray* getJsonArray(const QString& path); + QWidget *buildActiveStoredWidget(); + QJsonArray *getJsonArray(const QString &path); }; -} +} // namespace scopy::swiot #endif // FAULTSGROUP_H diff --git a/plugins/swiot/src/runtime/faults/faultspage.cpp b/plugins/swiot/src/runtime/faults/faultspage.cpp index 0d55148466..fc4048990d 100644 --- a/plugins/swiot/src/runtime/faults/faultspage.cpp +++ b/plugins/swiot/src/runtime/faults/faultspage.cpp @@ -18,19 +18,20 @@ * along with this program. If not, see . */ - #include "faultspage.h" -#include "ui_faultspage.h" + #include "src/swiot_logging_categories.h" +#include "ui_faultspage.h" + using namespace scopy::swiot; -FaultsPage::FaultsPage(struct iio_context* context, QWidget *parent) : - QWidget(parent), - m_context(context), - ui(new Ui::FaultsPage), - m_ad74413rFaultsDevice(nullptr), - m_max14906FaultsDevice(nullptr) +FaultsPage::FaultsPage(struct iio_context *context, QWidget *parent) + : QWidget(parent) + , m_context(context) + , ui(new Ui::FaultsPage) + , m_ad74413rFaultsDevice(nullptr) + , m_max14906FaultsDevice(nullptr) { ui->setupUi(this); this->setupDevices(); @@ -41,38 +42,38 @@ FaultsPage::FaultsPage(struct iio_context* context, QWidget *parent) : this->ui->mainVerticalLayout->addWidget(this->m_ad74413rFaultsDevice); this->ui->mainVerticalLayout->addWidget(this->m_max14906FaultsDevice); - this->ui->mainVerticalLayout->addItem(new QSpacerItem(0 ,0, QSizePolicy::Preferred, QSizePolicy::Expanding)); + this->ui->mainVerticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Preferred, QSizePolicy::Expanding)); this->ui->frame->setStyleSheet("QFrame#frame{background-color:#1C1C20;}"); } -FaultsPage::~FaultsPage() { - delete ui; -} +FaultsPage::~FaultsPage() { delete ui; } -void FaultsPage::update() { +void FaultsPage::update() +{ this->m_ad74413rFaultsDevice->update(); this->m_max14906FaultsDevice->update(); } -void FaultsPage::setupDevices() { - struct iio_device* ad74413r = iio_context_find_device(m_context, "ad74413r"); - struct iio_device* max14906 = iio_context_find_device(m_context, "max14906"); - struct iio_device* swiot = iio_context_find_device(m_context, "swiot"); +void FaultsPage::setupDevices() +{ + struct iio_device *ad74413r = iio_context_find_device(m_context, "ad74413r"); + struct iio_device *max14906 = iio_context_find_device(m_context, "max14906"); + struct iio_device *swiot = iio_context_find_device(m_context, "swiot"); - if (swiot) { - if (ad74413r) { + if(swiot) { + if(ad74413r) { QVector faultRegistersAddr = {0x02e}; - m_ad74413rFaultsDevice = new FaultsDevice("ad74413r", ":/swiot/swiot_faults.json", - ad74413r, swiot, m_context, faultRegistersAddr, this); + m_ad74413rFaultsDevice = new FaultsDevice("ad74413r", ":/swiot/swiot_faults.json", ad74413r, + swiot, m_context, faultRegistersAddr, this); } else { qCritical(CAT_SWIOT_FAULTS) << "Error: did not find ad74413r device."; } - if (max14906) { + if(max14906) { QVector faultRegistersAddr = {0x04, 0x05, 0x06, 0x07}; - m_max14906FaultsDevice = new FaultsDevice("max14906", ":/swiot/swiot_faults.json", - max14906, swiot, m_context, faultRegistersAddr, this); + m_max14906FaultsDevice = new FaultsDevice("max14906", ":/swiot/swiot_faults.json", max14906, + swiot, m_context, faultRegistersAddr, this); } else { qCritical(CAT_SWIOT_FAULTS) << "Error: did not find max14906 device."; } diff --git a/plugins/swiot/src/runtime/faults/faultspage.h b/plugins/swiot/src/runtime/faults/faultspage.h index f7136b74e0..7a3013448b 100644 --- a/plugins/swiot/src/runtime/faults/faultspage.h +++ b/plugins/swiot/src/runtime/faults/faultspage.h @@ -18,41 +18,43 @@ * along with this program. If not, see . */ - #ifndef FAULTSPAGE_H #define FAULTSPAGE_H -#include -#include -#include +#include "faultsdevice.h" +#include "faultsgroup.h" #include -#include "faultsgroup.h" -#include "faultsdevice.h" +#include +#include +#include -namespace Ui { class FaultsPage; } +namespace Ui { +class FaultsPage; +} namespace scopy::swiot { class FaultsDevice; -class FaultsPage : public QWidget { +class FaultsPage : public QWidget +{ Q_OBJECT public: - explicit FaultsPage(struct iio_context* context, QWidget *parent = nullptr); + explicit FaultsPage(struct iio_context *context, QWidget *parent = nullptr); ~FaultsPage(); void update(); private: - struct iio_context* m_context; + struct iio_context *m_context; Ui::FaultsPage *ui; - FaultsDevice* m_ad74413rFaultsDevice; - FaultsDevice* m_max14906FaultsDevice; + FaultsDevice *m_ad74413rFaultsDevice; + FaultsDevice *m_max14906FaultsDevice; void setupDevices(); }; -} +} // namespace scopy::swiot #endif // FAULTSPAGE_H diff --git a/plugins/swiot/src/runtime/faults/faultwidget.cpp b/plugins/swiot/src/runtime/faults/faultwidget.cpp index 12493c6b8d..1eed8b586c 100644 --- a/plugins/swiot/src/runtime/faults/faultwidget.cpp +++ b/plugins/swiot/src/runtime/faults/faultwidget.cpp @@ -18,24 +18,25 @@ * along with this program. If not, see . */ - #include "faultwidget.h" -#include -#include "ui_faultwidget.h" #include "core/logging_categories.h" +#include "ui_faultwidget.h" + +#include + using namespace scopy::swiot; -FaultWidget::FaultWidget(unsigned int id, QString name, QString faultExplanation, QWidget *parent) : - QWidget(parent), - ui(new Ui::FaultWidget), - m_stored(false), - m_active(false), - m_pressed(false), - m_id(id), - m_name(std::move(name)), - m_faultExplanation(std::move(faultExplanation)) +FaultWidget::FaultWidget(unsigned int id, QString name, QString faultExplanation, QWidget *parent) + : QWidget(parent) + , ui(new Ui::FaultWidget) + , m_stored(false) + , m_active(false) + , m_pressed(false) + , m_id(id) + , m_name(std::move(name)) + , m_faultExplanation(std::move(faultExplanation)) { ui->setupUi(this); @@ -46,73 +47,56 @@ FaultWidget::FaultWidget(unsigned int id, QString name, QString faultExplanation this->ui->mainFrame->setMinimumSize(70, 90); } -FaultWidget::~FaultWidget() { - delete ui; -} +FaultWidget::~FaultWidget() { delete ui; } -bool FaultWidget::isStored() const { - return m_stored; -} +bool FaultWidget::isStored() const { return m_stored; } -void FaultWidget::setStored(bool stored) { +void FaultWidget::setStored(bool stored) +{ FaultWidget::m_stored = stored; this->ui->stored->setProperty("high", this->m_stored); this->ui->stored->setStyle(this->ui->stored->style()); } -bool FaultWidget::isActive() const { - return m_active; -} +bool FaultWidget::isActive() const { return m_active; } -void FaultWidget::setActive(bool active) { +void FaultWidget::setActive(bool active) +{ FaultWidget::m_active = active; this->ui->active->setProperty("high", m_active); this->ui->active->setStyle(this->ui->active->style()); } -const QString &FaultWidget::getName() const { - return m_name; -} +const QString &FaultWidget::getName() const { return m_name; } -void FaultWidget::setName(const QString &name) { - FaultWidget::m_name = name; -} +void FaultWidget::setName(const QString &name) { FaultWidget::m_name = name; } -const QString &FaultWidget::getFaultExplanation() const { - return m_faultExplanation; -} +const QString &FaultWidget::getFaultExplanation() const { return m_faultExplanation; } -void FaultWidget::setFaultExplanation(const QString &faultExplanation) { +void FaultWidget::setFaultExplanation(const QString &faultExplanation) +{ FaultWidget::m_faultExplanation = faultExplanation; } -void FaultWidget::setFaultExplanationOptions(QJsonObject options) -{ - m_faultExplanationOptions = options; -} +void FaultWidget::setFaultExplanationOptions(QJsonObject options) { m_faultExplanationOptions = options; } -unsigned int FaultWidget::getId() const { - return m_id; -} +unsigned int FaultWidget::getId() const { return m_id; } -void FaultWidget::setId(unsigned int id) { - FaultWidget::m_id = id; -} +void FaultWidget::setId(unsigned int id) { FaultWidget::m_id = id; } -bool FaultWidget::isPressed() const { - return m_pressed; -} +bool FaultWidget::isPressed() const { return m_pressed; } -void FaultWidget::setPressed(bool pressed) { +void FaultWidget::setPressed(bool pressed) +{ FaultWidget::m_pressed = pressed; scopy::setDynamicProperty(this->ui->mainFrame, "pressed", pressed); } void FaultWidget::specialFaultUpdated(int index, QString channelFunction) { - if (index == m_id) { + if(index == m_id) { QString option = m_faultExplanationOptions[channelFunction].toString(); - if (option.isEmpty()) { + if(option.isEmpty()) { option = "channel configured as: " + channelFunction; } setFaultExplanation(option); @@ -120,14 +104,15 @@ void FaultWidget::specialFaultUpdated(int index, QString channelFunction) } } -bool FaultWidget::eventFilter(QObject *object, QEvent *event) { - if (event->type() == QEvent::MouseButtonPress) { - this->setPressed( !scopy::getDynamicProperty(this->ui->mainFrame, "pressed") ); +bool FaultWidget::eventFilter(QObject *object, QEvent *event) +{ + if(event->type() == QEvent::MouseButtonPress) { + this->setPressed(!scopy::getDynamicProperty(this->ui->mainFrame, "pressed")); Q_EMIT faultSelected(this->m_id); } - if (event->type() == QEvent::ToolTip) { + if(event->type() == QEvent::ToolTip) { this->setToolTip(this->m_name); } diff --git a/plugins/swiot/src/runtime/faults/faultwidget.h b/plugins/swiot/src/runtime/faults/faultwidget.h index 128054225f..e350dedffe 100644 --- a/plugins/swiot/src/runtime/faults/faultwidget.h +++ b/plugins/swiot/src/runtime/faults/faultwidget.h @@ -18,23 +18,26 @@ * along with this program. If not, see . */ - #ifndef SCOPY_FAULTWIDGET_H #define SCOPY_FAULTWIDGET_H -#include -#include -#include "ui_faultwidget.h" #include "gui/dynamicWidget.h" -#include +#include "ui_faultwidget.h" + +#include +#include +#include QT_BEGIN_NAMESPACE -namespace Ui { class FaultWidget; } +namespace Ui { +class FaultWidget; +} QT_END_NAMESPACE namespace scopy::swiot { -class FaultWidget : public QWidget { +class FaultWidget : public QWidget +{ Q_OBJECT public: @@ -82,6 +85,6 @@ public Q_SLOTS: QString m_faultExplanation; QJsonObject m_faultExplanationOptions; }; -} +} // namespace scopy::swiot -#endif //SCOPY_FAULTWIDGET_H +#endif // SCOPY_FAULTWIDGET_H diff --git a/plugins/swiot/src/runtime/max14906/diocontroller.cpp b/plugins/swiot/src/runtime/max14906/diocontroller.cpp index c9574c9c1c..9d50155d1e 100644 --- a/plugins/swiot/src/runtime/max14906/diocontroller.cpp +++ b/plugins/swiot/src/runtime/max14906/diocontroller.cpp @@ -18,33 +18,35 @@ * along with this program. If not, see . */ - #include "diocontroller.h" -#include "src/swiot_logging_categories.h" + #include "max14906.h" +#include "src/swiot_logging_categories.h" using namespace scopy::swiot; -DioController::DioController(struct iio_context* context_, QString deviceName) : - m_deviceName(std::move(deviceName)), - m_context(context_) { - struct iio_device* dev = iio_context_find_device(this->m_context, MAX_NAME); +DioController::DioController(struct iio_context *context_, QString deviceName) + : m_deviceName(std::move(deviceName)) + , m_context(context_) +{ + struct iio_device *dev = iio_context_find_device(this->m_context, MAX_NAME); this->m_device = dev; } -DioController::~DioController() { +DioController::~DioController() {} -} - -int DioController::getChannelCount() { +int DioController::getChannelCount() +{ unsigned int dev_count = iio_device_get_channels_count(this->m_device); return (int)(dev_count); } -QString DioController::getChannelName(unsigned int index) { +QString DioController::getChannelName(unsigned int index) +{ iio_channel *channel = iio_device_get_channel(this->m_device, index); - if (channel == nullptr) { - qCritical(CAT_SWIOT_MAX14906) << "Error when selecting channel with index" << index << ", returning empty string."; + if(channel == nullptr) { + qCritical(CAT_SWIOT_MAX14906) + << "Error when selecting channel with index" << index << ", returning empty string."; return ""; } QString name = iio_channel_get_id(channel); @@ -52,10 +54,12 @@ QString DioController::getChannelName(unsigned int index) { return name; } -QString DioController::getChannelType(unsigned int index) { - iio_channel* channel = iio_device_get_channel(this->m_device, index); - if (channel == nullptr) { - qCritical(CAT_SWIOT_MAX14906) << "Error when selecting channel with index" << index << ", returning empty string."; +QString DioController::getChannelType(unsigned int index) +{ + iio_channel *channel = iio_device_get_channel(this->m_device, index); + if(channel == nullptr) { + qCritical(CAT_SWIOT_MAX14906) + << "Error when selecting channel with index" << index << ", returning empty string."; return ""; } bool output = iio_channel_is_output(channel); @@ -63,6 +67,4 @@ QString DioController::getChannelType(unsigned int index) { return output ? "OUTPUT" : "INPUT"; } -iio_device *DioController::getDevice() const { - return DioController::m_device; -} +iio_device *DioController::getDevice() const { return DioController::m_device; } diff --git a/plugins/swiot/src/runtime/max14906/diocontroller.h b/plugins/swiot/src/runtime/max14906/diocontroller.h index fed08e4f2c..2b67aac16c 100644 --- a/plugins/swiot/src/runtime/max14906/diocontroller.h +++ b/plugins/swiot/src/runtime/max14906/diocontroller.h @@ -18,21 +18,23 @@ * along with this program. If not, see . */ - #ifndef SCOPY_DIOCONTROLLER_H #define SCOPY_DIOCONTROLLER_H -#include -#include #include + +#include #include #include +#include + namespace scopy::swiot { -class DioController : public QObject { +class DioController : public QObject +{ Q_OBJECT public: - explicit DioController(struct iio_context* context_, QString deviceName = "max14906"); + explicit DioController(struct iio_context *context_, QString deviceName = "max14906"); ~DioController() override; int getChannelCount(); @@ -41,11 +43,12 @@ class DioController : public QObject { QString getChannelName(unsigned int index); QString getChannelType(unsigned int index); + private: QString m_deviceName; - struct iio_context* m_context; - struct iio_device* m_device; + struct iio_context *m_context; + struct iio_device *m_device; }; -} +} // namespace scopy::swiot -#endif //SCOPY_DIOCONTROLLER_H +#endif // SCOPY_DIOCONTROLLER_H diff --git a/plugins/swiot/src/runtime/max14906/diodigitalchannel.cpp b/plugins/swiot/src/runtime/max14906/diodigitalchannel.cpp index 0c9e637bc5..b73288fb62 100644 --- a/plugins/swiot/src/runtime/max14906/diodigitalchannel.cpp +++ b/plugins/swiot/src/runtime/max14906/diodigitalchannel.cpp @@ -18,20 +18,21 @@ * along with this program. If not, see . */ - #include "diodigitalchannel.h" + #include "src/swiot_logging_categories.h" + #include using namespace scopy::swiot; #define SISMOGRAPH_INITIAL_SIZE 10 -DioDigitalChannel::DioDigitalChannel(const QString &deviceName, const QString &deviceType, QWidget *parent) : - QWidget(parent), - ui(new Ui::DioDigitalChannel()), - m_deviceName(deviceName), - m_deviceType(deviceType) +DioDigitalChannel::DioDigitalChannel(const QString &deviceName, const QString &deviceType, QWidget *parent) + : QWidget(parent) + , ui(new Ui::DioDigitalChannel()) + , m_deviceName(deviceName) + , m_deviceType(deviceType) { this->ui->setupUi(this); this->connectSignalsAndSlots(); @@ -44,7 +45,7 @@ DioDigitalChannel::DioDigitalChannel(const QString &deviceName, const QString &d this->ui->channelTitleLineEdit->setPlaceholderText("Enter title here..."); - if (deviceType == "INPUT") { + if(deviceType == "INPUT") { this->ui->customSwitch->setVisible(false); this->ui->currentLimitValues->hide(); this->ui->currentLimitLabel->hide(); @@ -53,18 +54,19 @@ DioDigitalChannel::DioDigitalChannel(const QString &deviceName, const QString &d this->ui->customSwitch->setChecked(false); } - this->ui->sismograph->setAxisTitle(QwtAxis::YLeft, ""); // clear title - this->ui->sismograph->setAxisTitle(QwtAxis::XBottom, ""); // clear title - this->ui->sismograph->setAxisScale(0, 0, 1, 1); // y axis + this->ui->sismograph->setAxisTitle(QwtAxis::YLeft, ""); // clear title + this->ui->sismograph->setAxisTitle(QwtAxis::XBottom, ""); // clear title + this->ui->sismograph->setAxisScale(0, 0, 1, 1); // y axis this->ui->sismograph->setPlotDirection(Sismograph::RIGHT_TO_LEFT); // plot from right to left - this->ui->sismograph->setColor(QColor(0xff, 0x72, 0x00)); // #ff7200 + this->ui->sismograph->setColor(QColor(0xff, 0x72, 0x00)); // #ff7200 this->ui->sismograph->setContentsMargins(9, 9, 9, 9); this->ui->sismograph->setUpdatesEnabled(true); this->ui->sismograph->setAutoscale(false); this->ui->sismograph->setAxisScale(QwtAxis::YRight, 0.0, 1.0); this->ui->sismograph->setNumSamples(10); this->ui->sismograph->setSampleRate(1); - this->ui->sismograph->updateYScale(SISMOGRAPH_INITIAL_SIZE, 0); // FIXME: sismograph typo, actually updates XBottom axis + this->ui->sismograph->updateYScale(SISMOGRAPH_INITIAL_SIZE, + 0); // FIXME: sismograph typo, actually updates XBottom axis this->ui->sismograph->replot(); this->ui->lcdNumber->setPrecision(0); @@ -74,11 +76,10 @@ DioDigitalChannel::DioDigitalChannel(const QString &deviceName, const QString &d this->ui->modeLabel->setText(modeLabel + " mode"); } -DioDigitalChannel::~DioDigitalChannel() { - delete ui; -} +DioDigitalChannel::~DioDigitalChannel() { delete ui; } -void DioDigitalChannel::connectSignalsAndSlots() { +void DioDigitalChannel::connectSignalsAndSlots() +{ connect(this->ui->customSwitch, &CustomSwitch::toggled, this, [this]() { bool isChecked = this->ui->customSwitch->isChecked(); @@ -86,37 +87,37 @@ void DioDigitalChannel::connectSignalsAndSlots() { }); } -void DioDigitalChannel::updateTimeScale(double newMax) { +void DioDigitalChannel::updateTimeScale(double newMax) +{ this->ui->sismograph->updateYScale(newMax, 0); // in this case, data always comes towards index 0 this->ui->sismograph->setNumSamples((int)(newMax)); this->ui->sismograph->reset(); // apply changes by plotting again } -void DioDigitalChannel::addDataSample(double value) { +void DioDigitalChannel::addDataSample(double value) +{ this->ui->sismograph->plot(value); this->ui->lcdNumber->display(value); } -const std::vector DioDigitalChannel::getConfigModes() const { - return m_configModes; -} +const std::vector DioDigitalChannel::getConfigModes() const { return m_configModes; } -void DioDigitalChannel::setConfigModes(std::vector &configModes) { +void DioDigitalChannel::setConfigModes(std::vector &configModes) +{ m_configModes = configModes; this->ui->configModes->clear(); - for (const std::string &item: m_configModes) { + for(const std::string &item : m_configModes) { this->ui->configModes->addItem(QString::fromStdString(item)); } } -const QString &DioDigitalChannel::getSelectedConfigMode() const { - return m_selectedConfigMode; -} +const QString &DioDigitalChannel::getSelectedConfigMode() const { return m_selectedConfigMode; } -void DioDigitalChannel::setSelectedConfigMode(const QString &selectedConfigMode) { +void DioDigitalChannel::setSelectedConfigMode(const QString &selectedConfigMode) +{ m_selectedConfigMode = selectedConfigMode; int index = this->ui->configModes->findText(selectedConfigMode); @@ -124,8 +125,6 @@ void DioDigitalChannel::setSelectedConfigMode(const QString &selectedConfigMode) qDebug() << "The channel " << this->m_deviceName << " read selected config mode " << selectedConfigMode; } -void DioDigitalChannel::resetSismograph() { - this->ui->sismograph->reset(); -} +void DioDigitalChannel::resetSismograph() { this->ui->sismograph->reset(); } #include "moc_diodigitalchannel.cpp" diff --git a/plugins/swiot/src/runtime/max14906/diodigitalchannel.h b/plugins/swiot/src/runtime/max14906/diodigitalchannel.h index b5c0d70812..dfe0669b3d 100644 --- a/plugins/swiot/src/runtime/max14906/diodigitalchannel.h +++ b/plugins/swiot/src/runtime/max14906/diodigitalchannel.h @@ -18,17 +18,19 @@ * along with this program. If not, see . */ - #ifndef SCOPY_DIODIGITALCHANNEL_H #define SCOPY_DIODIGITALCHANNEL_H -#include #include "ui_diodigitalchannel.h" -#include + #include +#include + +#include namespace scopy::swiot { -class DioDigitalChannel : public QWidget { +class DioDigitalChannel : public QWidget +{ Q_OBJECT public: explicit DioDigitalChannel(const QString &deviceName, const QString &deviceType, QWidget *parent = nullptr); @@ -57,6 +59,6 @@ class DioDigitalChannel : public QWidget { Q_SIGNALS: void outputValueChanged(bool value); }; -} +} // namespace scopy::swiot -#endif //SCOPY_DIODIGITALCHANNEL_H +#endif // SCOPY_DIODIGITALCHANNEL_H diff --git a/plugins/swiot/src/runtime/max14906/diodigitalchannelcontroller.cpp b/plugins/swiot/src/runtime/max14906/diodigitalchannelcontroller.cpp index 2b12044469..3d6c90cdf4 100644 --- a/plugins/swiot/src/runtime/max14906/diodigitalchannelcontroller.cpp +++ b/plugins/swiot/src/runtime/max14906/diodigitalchannelcontroller.cpp @@ -18,201 +18,228 @@ * along with this program. If not, see . */ - #include "diodigitalchannelcontroller.h" + #include "src/swiot_logging_categories.h" + #include #include #include using namespace scopy::swiot; -DioDigitalChannelController::DioDigitalChannelController(struct iio_channel* channel, - const QString &deviceName, - const QString &deviceType, - CommandQueue *cmdQueue, - QWidget *parent) : - QWidget(parent), - m_digitalChannel(new DioDigitalChannel(deviceName, deviceType, this)), - m_channelName(deviceName), - m_channelType(deviceType), - m_cmdQueue(cmdQueue), - m_channel(channel) +DioDigitalChannelController::DioDigitalChannelController(struct iio_channel *channel, const QString &deviceName, + const QString &deviceType, CommandQueue *cmdQueue, + QWidget *parent) + : QWidget(parent) + , m_digitalChannel(new DioDigitalChannel(deviceName, deviceType, this)) + , m_channelName(deviceName) + , m_channelType(deviceType) + , m_cmdQueue(cmdQueue) + , m_channel(channel) { m_iioAttrAvailableTypes = (m_channelType == "INPUT") ? "IEC_type_available" : "do_mode_available"; m_iioAttrType = (m_channelType == "INPUT") ? "IEC_type" : "do_mode"; - - Command *readAvailableTypeCmd = new IioChannelAttributeRead(m_channel, m_iioAttrAvailableTypes.c_str(), nullptr); + Command *readAvailableTypeCmd = + new IioChannelAttributeRead(m_channel, m_iioAttrAvailableTypes.c_str(), nullptr); Command *readTypeCmd = new IioChannelAttributeRead(m_channel, m_iioAttrType.c_str(), nullptr); - connect(readAvailableTypeCmd, &scopy::Command::finished, this, [=, this](scopy::Command *cmd) { - IioChannelAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { - return; - } - if (tcmd->getReturnCode() >= 0) { - char *result = tcmd->getResult(); - std::stringstream ss(result); - std::string aux; - while (std::getline(ss, aux, ' ')) { - m_availableTypes.push_back(aux); - } - this->m_digitalChannel->setConfigModes(m_availableTypes); - } else { - qCritical(CAT_SWIOT_MAX14906) << "Could not read the available types, error code: " << tcmd->getReturnCode(); - } - }, Qt::QueuedConnection); - - connect(readTypeCmd, &scopy::Command::finished, this, [=, this](scopy::Command *cmd) { - IioChannelAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { - return; - } - if (tcmd->getReturnCode() >= 0) { - char *result = tcmd->getResult(); - m_type = std::string(result); - m_digitalChannel->setSelectedConfigMode(QString::fromStdString(m_type)); - } else { - qCritical(CAT_SWIOT_MAX14906) << "Could not read the type, error code: " << tcmd->getReturnCode(); - } - }, Qt::QueuedConnection); - - m_cmdQueue->enqueue(readAvailableTypeCmd); - m_cmdQueue->enqueue(readTypeCmd); - - if (m_channelType == "OUTPUT") { - Command *readRawCmd = new IioChannelAttributeRead(m_channel, "raw", nullptr); - Command *readCurrentLimitAvailableCmd = new IioChannelAttributeRead(m_channel, "current_limit_available", nullptr); - - connect(readRawCmd, &scopy::Command::finished, this, [=, this](scopy::Command *cmd) { - IioChannelAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { + connect( + readAvailableTypeCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioChannelAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { return; } - if (tcmd->getReturnCode() >= 0) { + if(tcmd->getReturnCode() >= 0) { char *result = tcmd->getResult(); - bool ok = false; - bool rawValue = QString(result).toInt(&ok); - if (ok) { - m_digitalChannel->ui->customSwitch->setChecked(rawValue); + std::stringstream ss(result); + std::string aux; + while(std::getline(ss, aux, ' ')) { + m_availableTypes.push_back(aux); } + this->m_digitalChannel->setConfigModes(m_availableTypes); } else { - qCritical(CAT_SWIOT_MAX14906) <<"Could not read initial channel raw value, error code: " << tcmd->getReturnCode(); + qCritical(CAT_SWIOT_MAX14906) + << "Could not read the available types, error code: " << tcmd->getReturnCode(); } - }, Qt::QueuedConnection); - - connect(readCurrentLimitAvailableCmd, &scopy::Command::finished, this, [=, this](scopy::Command *cmd) { - IioChannelAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { + }, + Qt::QueuedConnection); + + connect( + readTypeCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioChannelAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { return; } - if (tcmd->getReturnCode() >= 0) { + if(tcmd->getReturnCode() >= 0) { char *result = tcmd->getResult(); - QStringList limitAvailable = QString(result).trimmed().split(" "); - for (const auto& item : limitAvailable) { - this->m_digitalChannel->ui->currentLimitValues->addItem(item); - } + m_type = std::string(result); + m_digitalChannel->setSelectedConfigMode(QString::fromStdString(m_type)); + } else { + qCritical(CAT_SWIOT_MAX14906) + << "Could not read the type, error code: " << tcmd->getReturnCode(); + } + }, + Qt::QueuedConnection); + + m_cmdQueue->enqueue(readAvailableTypeCmd); + m_cmdQueue->enqueue(readTypeCmd); - IioChannelAttributeRead *readCurrentLimitCmd = new IioChannelAttributeRead(m_channel, "current_limit", nullptr); - connect(readCurrentLimitCmd, &scopy::Command::finished, this, [=, this](scopy::Command *cmd) { - IioChannelAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { - return; + if(m_channelType == "OUTPUT") { + Command *readRawCmd = new IioChannelAttributeRead(m_channel, "raw", nullptr); + Command *readCurrentLimitAvailableCmd = + new IioChannelAttributeRead(m_channel, "current_limit_available", nullptr); + + connect( + readRawCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioChannelAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + if(tcmd->getReturnCode() >= 0) { + char *result = tcmd->getResult(); + bool ok = false; + bool rawValue = QString(result).toInt(&ok); + if(ok) { + m_digitalChannel->ui->customSwitch->setChecked(rawValue); } - if (tcmd->getReturnCode() >= 0) { - char *result = tcmd->getResult(); - m_digitalChannel->ui->currentLimitValues->setCurrentIndex(m_digitalChannel->ui->currentLimitValues->findText(result)); - } else { - qCritical(CAT_SWIOT_MAX14906) << "Could not read current_limit, error code: " << tcmd->getReturnCode(); + } else { + qCritical(CAT_SWIOT_MAX14906) + << "Could not read initial channel raw value, error code: " + << tcmd->getReturnCode(); + } + }, + Qt::QueuedConnection); + + connect( + readCurrentLimitAvailableCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioChannelAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + if(tcmd->getReturnCode() >= 0) { + char *result = tcmd->getResult(); + QStringList limitAvailable = QString(result).trimmed().split(" "); + for(const auto &item : limitAvailable) { + this->m_digitalChannel->ui->currentLimitValues->addItem(item); } - }, Qt::QueuedConnection); - m_cmdQueue->enqueue(readCurrentLimitCmd); - } else { - qCritical(CAT_SWIOT_MAX14906) << "Could not read current_limit_available, error code: " << tcmd->getReturnCode(); - } - }, Qt::QueuedConnection); + + IioChannelAttributeRead *readCurrentLimitCmd = + new IioChannelAttributeRead(m_channel, "current_limit", nullptr); + connect( + readCurrentLimitCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioChannelAttributeRead *tcmd = + dynamic_cast(cmd); + if(!tcmd) { + return; + } + if(tcmd->getReturnCode() >= 0) { + char *result = tcmd->getResult(); + m_digitalChannel->ui->currentLimitValues + ->setCurrentIndex( + m_digitalChannel->ui->currentLimitValues + ->findText(result)); + } else { + qCritical(CAT_SWIOT_MAX14906) + << "Could not read current_limit, error code: " + << tcmd->getReturnCode(); + } + }, + Qt::QueuedConnection); + m_cmdQueue->enqueue(readCurrentLimitCmd); + } else { + qCritical(CAT_SWIOT_MAX14906) + << "Could not read current_limit_available, error code: " + << tcmd->getReturnCode(); + } + }, + Qt::QueuedConnection); m_cmdQueue->enqueue(readRawCmd); m_cmdQueue->enqueue(readCurrentLimitAvailableCmd); } - QObject::connect(m_digitalChannel->ui->configModes, QOverload::of(&QComboBox::currentIndexChanged), - [=, this](int index){ - createWriteTypeCommand(index); - }); + [=, this](int index) { createWriteTypeCommand(index); }); QObject::connect(m_digitalChannel, &DioDigitalChannel::outputValueChanged, this, - [=, this] (bool value) { - createWriteRawCommand(value); - }); + [=, this](bool value) { createWriteRawCommand(value); }); QObject::connect(m_digitalChannel->ui->currentLimitValues, QOverload::of(&QComboBox::currentIndexChanged), - [=, this] (int index) { - createWriteCurrentLimitCommand(index); - }); + [=, this](int index) { createWriteCurrentLimitCommand(index); }); } -DioDigitalChannelController::~DioDigitalChannelController() -{ +DioDigitalChannelController::~DioDigitalChannelController() {} -} - -DioDigitalChannel *DioDigitalChannelController::getDigitalChannel() const { - return m_digitalChannel; -} +DioDigitalChannel *DioDigitalChannelController::getDigitalChannel() const { return m_digitalChannel; } void DioDigitalChannelController::createWriteRawCommand(bool value) { - Command *writeRawCmd = new IioChannelAttributeWrite(m_channel, "raw", QString::number(value).toStdString().c_str(), nullptr); - connect(writeRawCmd, &scopy::Command::finished, this, [=, this](scopy::Command *cmd) { - IioChannelAttributeWrite *tcmd = dynamic_cast(cmd); - if (!tcmd) { - return; - } - if (tcmd->getReturnCode() < 0) { - qCritical(CAT_SWIOT_MAX14906) << "Could not write value " << value << - " to channel " << m_channelName << - " error code" << tcmd->getReturnCode(); - } - }, Qt::QueuedConnection); + Command *writeRawCmd = + new IioChannelAttributeWrite(m_channel, "raw", QString::number(value).toStdString().c_str(), nullptr); + connect( + writeRawCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioChannelAttributeWrite *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + if(tcmd->getReturnCode() < 0) { + qCritical(CAT_SWIOT_MAX14906) + << "Could not write value " << value << " to channel " << m_channelName + << " error code" << tcmd->getReturnCode(); + } + }, + Qt::QueuedConnection); m_cmdQueue->enqueue(writeRawCmd); } void DioDigitalChannelController::createWriteCurrentLimitCommand(int index) { QString text = m_digitalChannel->ui->currentLimitValues->currentText(); - Command *writeCurrentLimitCmd = new IioChannelAttributeWrite(m_channel, "current_limit", text.toStdString().c_str(), nullptr); - connect(writeCurrentLimitCmd, &scopy::Command::finished, this, [=, this](scopy::Command *cmd) { - IioChannelAttributeWrite *tcmd = dynamic_cast(cmd); - if (!tcmd) { - return; - } - if (tcmd->getReturnCode() < 0) { - qCritical(CAT_SWIOT_MAX14906) << "Could not write value " << text << - " to channel " << m_channelName << - " error code " << tcmd->getReturnCode(); - } - }, Qt::QueuedConnection); + Command *writeCurrentLimitCmd = + new IioChannelAttributeWrite(m_channel, "current_limit", text.toStdString().c_str(), nullptr); + connect( + writeCurrentLimitCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioChannelAttributeWrite *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + if(tcmd->getReturnCode() < 0) { + qCritical(CAT_SWIOT_MAX14906) + << "Could not write value " << text << " to channel " << m_channelName + << " error code " << tcmd->getReturnCode(); + } + }, + Qt::QueuedConnection); m_cmdQueue->enqueue(writeCurrentLimitCmd); - } void DioDigitalChannelController::createWriteTypeCommand(int index) { QString text = m_digitalChannel->ui->configModes->currentText(); m_type = text.toStdString(); - Command *writeTypeCmd = new IioChannelAttributeWrite(m_channel, m_iioAttrType.c_str(), text.toStdString().c_str(), nullptr); - connect(writeTypeCmd, &scopy::Command::finished, this, [=, this](scopy::Command *cmd) { - IioChannelAttributeWrite *tcmd = dynamic_cast(cmd); - if (!tcmd) { - return; - } - if (tcmd->getReturnCode() < 0) { - qCritical(CAT_SWIOT_MAX14906) << "Could not write attr to channel " << m_channelName << - " error code " << tcmd->getReturnCode(); - } - }, Qt::QueuedConnection); + Command *writeTypeCmd = + new IioChannelAttributeWrite(m_channel, m_iioAttrType.c_str(), text.toStdString().c_str(), nullptr); + connect( + writeTypeCmd, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioChannelAttributeWrite *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } + if(tcmd->getReturnCode() < 0) { + qCritical(CAT_SWIOT_MAX14906) << "Could not write attr to channel " << m_channelName + << " error code " << tcmd->getReturnCode(); + } + }, + Qt::QueuedConnection); m_cmdQueue->enqueue(writeTypeCmd); } diff --git a/plugins/swiot/src/runtime/max14906/diodigitalchannelcontroller.h b/plugins/swiot/src/runtime/max14906/diodigitalchannelcontroller.h index 6e50b006c0..75f3cd8962 100644 --- a/plugins/swiot/src/runtime/max14906/diodigitalchannelcontroller.h +++ b/plugins/swiot/src/runtime/max14906/diodigitalchannelcontroller.h @@ -18,25 +18,25 @@ * along with this program. If not, see . */ - #ifndef SCOPY_DIODIGITALCHANNELCONTROLLER_H #define SCOPY_DIODIGITALCHANNELCONTROLLER_H #include "diodigitalchannel.h" -#include -#include #include +#include +#include + #define ATTR_BUFFER_LEN 200 namespace scopy::swiot { -class DioDigitalChannelController : public QWidget { +class DioDigitalChannelController : public QWidget +{ Q_OBJECT public: - - explicit DioDigitalChannelController(struct iio_channel* channel, const QString& deviceName, - const QString& deviceType, CommandQueue *cmdQueue, QWidget *parent); + explicit DioDigitalChannelController(struct iio_channel *channel, const QString &deviceName, + const QString &deviceType, CommandQueue *cmdQueue, QWidget *parent); ~DioDigitalChannelController() override; DioDigitalChannel *getDigitalChannel() const; @@ -44,6 +44,7 @@ private Q_SLOTS: void createWriteCurrentLimitCommand(int index); void createWriteRawCommand(bool value); void createWriteTypeCommand(int index); + private: DioDigitalChannel *m_digitalChannel; @@ -58,9 +59,9 @@ private Q_SLOTS: CommandQueue *m_cmdQueue; - struct iio_channel* m_channel; + struct iio_channel *m_channel; }; -} // scopy +} // namespace scopy::swiot -#endif //SCOPY_DIODIGITALCHANNELCONTROLLER_H +#endif // SCOPY_DIODIGITALCHANNELCONTROLLER_H diff --git a/plugins/swiot/src/runtime/max14906/diosettingstab.cpp b/plugins/swiot/src/runtime/max14906/diosettingstab.cpp index 66129de9f1..a224381f0c 100644 --- a/plugins/swiot/src/runtime/max14906/diosettingstab.cpp +++ b/plugins/swiot/src/runtime/max14906/diosettingstab.cpp @@ -18,32 +18,26 @@ * along with this program. If not, see . */ - #include "diosettingstab.h" + #include "ui_swiotmax14906settingstab.h" using namespace scopy::swiot; -DioSettingsTab::DioSettingsTab(QWidget *parent) : - QWidget(parent), - ui(new Ui::DioSettingsTab) { +DioSettingsTab::DioSettingsTab(QWidget *parent) + : QWidget(parent) + , ui(new Ui::DioSettingsTab) +{ ui->setupUi(this); - this->m_max_spin_button = new PositionSpinButton({ - {tr("s"), 1} - }, tr("Timespan"), 1, 300, true, false, this); + this->m_max_spin_button = new PositionSpinButton({{tr("s"), 1}}, tr("Timespan"), 1, 300, true, false, this); this->m_max_spin_button->setValue(10); // default value this->ui->verticalLayout_maxTimer->addWidget(this->m_max_spin_button); - QObject::connect(m_max_spin_button, &PositionSpinButton::valueChanged, [this]() { - Q_EMIT timeValueChanged(this->m_max_spin_button->value()); - }); + QObject::connect(m_max_spin_button, &PositionSpinButton::valueChanged, + [this]() { Q_EMIT timeValueChanged(this->m_max_spin_button->value()); }); } -DioSettingsTab::~DioSettingsTab() { - delete ui; -} +DioSettingsTab::~DioSettingsTab() { delete ui; } -double DioSettingsTab::getTimeValue() const { - return m_max_spin_button->value(); -} +double DioSettingsTab::getTimeValue() const { return m_max_spin_button->value(); } diff --git a/plugins/swiot/src/runtime/max14906/diosettingstab.h b/plugins/swiot/src/runtime/max14906/diosettingstab.h index 7098afea3e..d6a6eb36e4 100644 --- a/plugins/swiot/src/runtime/max14906/diosettingstab.h +++ b/plugins/swiot/src/runtime/max14906/diosettingstab.h @@ -18,11 +18,11 @@ * along with this program. If not, see . */ - #ifndef DIOSETTINGSTAB_H #define DIOSETTINGSTAB_H #include + #include namespace Ui { @@ -30,7 +30,8 @@ class DioSettingsTab; } namespace scopy::swiot { -class DioSettingsTab : public QWidget { +class DioSettingsTab : public QWidget +{ Q_OBJECT public: explicit DioSettingsTab(QWidget *parent = nullptr); @@ -47,5 +48,5 @@ class DioSettingsTab : public QWidget { Ui::DioSettingsTab *ui; PositionSpinButton *m_max_spin_button; }; -} +} // namespace scopy::swiot #endif // DIOSETTINGSTAB_H diff --git a/plugins/swiot/src/runtime/max14906/max14906.cpp b/plugins/swiot/src/runtime/max14906/max14906.cpp index d170077447..97ca23d8ac 100644 --- a/plugins/swiot/src/runtime/max14906/max14906.cpp +++ b/plugins/swiot/src/runtime/max14906/max14906.cpp @@ -18,37 +18,38 @@ * along with this program. If not, see . */ - #include "max14906.h" -#include -#include + #include "src/swiot_logging_categories.h" #include "utils.h" -#include #include #include +#include + +#include +#include #define MAX14906_POLLING_TIME 1000 using namespace scopy::swiot; -Max14906::Max14906(struct iio_context *ctx, ToolMenuEntry *tme, QWidget *parent) : - QWidget(parent), - max14906ToolController(new DioController(ctx)), - ui(new Ui::Max14906), - m_backButton(Max14906::createBackButton()), - m_qTimer(new QTimer(this)), - m_toolView(nullptr), - m_tme(tme), - m_max14906SettingsTab(nullptr), - m_generalSettingsMenu(), - settingsWidgetSeparator(), - m_statusLabel(new QLabel(this)), - m_statusContainer(new QWidget(this)), - m_ctx(ctx), - m_cmdQueue(CommandQueueProvider::GetInstance()->open(m_ctx)), - m_readerThread(new ReaderThread(false, m_cmdQueue)) +Max14906::Max14906(struct iio_context *ctx, ToolMenuEntry *tme, QWidget *parent) + : QWidget(parent) + , max14906ToolController(new DioController(ctx)) + , ui(new Ui::Max14906) + , m_backButton(Max14906::createBackButton()) + , m_qTimer(new QTimer(this)) + , m_toolView(nullptr) + , m_tme(tme) + , m_max14906SettingsTab(nullptr) + , m_generalSettingsMenu() + , settingsWidgetSeparator() + , m_statusLabel(new QLabel(this)) + , m_statusContainer(new QWidget(this)) + , m_ctx(ctx) + , m_cmdQueue(CommandQueueProvider::GetInstance()->open(m_ctx)) + , m_readerThread(new ReaderThread(false, m_cmdQueue)) { this->ui->setupUi(this); m_nbDioChannels = max14906ToolController->getChannelCount(); @@ -64,7 +65,8 @@ Max14906::Max14906(struct iio_context *ctx, ToolMenuEntry *tme, QWidget *parent) this->ui->mainLayout->addWidget(m_toolView); } -void Max14906::setupDynamicUi(QWidget *parent) { +void Max14906::setupDynamicUi(QWidget *parent) +{ scopy::gui::ToolViewRecipe recipe; recipe.helpBtnUrl = ""; recipe.hasRunBtn = true; @@ -77,8 +79,8 @@ void Max14906::setupDynamicUi(QWidget *parent) { m_toolView = scopy::gui::ToolViewBuilder(recipe, nullptr, parent).build(); - this->m_generalSettingsMenu = this->createGeneralSettings("General settings", - new QColor(0x4a, 0x64, 0xff)); // "#4a64ff" + this->m_generalSettingsMenu = + this->createGeneralSettings("General settings", new QColor(0x4a, 0x64, 0xff)); // "#4a64ff" this->m_generalSettingsMenu->setProperty("tutorial_name", "GENERAL_SETTINGS"); this->m_toolView->setGeneralSettingsMenu(this->m_generalSettingsMenu, true); @@ -87,8 +89,9 @@ void Max14906::setupDynamicUi(QWidget *parent) { m_statusContainer->setLayout(new QHBoxLayout(m_statusContainer)); m_statusContainer->layout()->setSpacing(0); - m_statusContainer->layout()->setContentsMargins(0,0,0,0); - m_statusContainer->setStyleSheet("QWidget{color: #ffc904; background-color: rgba(0, 0, 0, 60); border: 1px solid rgba(0, 0, 0, 30); font-size: 11pt}"); + m_statusContainer->layout()->setContentsMargins(0, 0, 0, 0); + m_statusContainer->setStyleSheet("QWidget{color: #ffc904; background-color: rgba(0, 0, 0, 60); border: 1px " + "solid rgba(0, 0, 0, 30); font-size: 11pt}"); auto exclamationLabel = new QPushButton(m_statusContainer); exclamationLabel->setIcon(QIcon::fromTheme(":/swiot/warning.svg")); @@ -112,7 +115,8 @@ void Max14906::setupDynamicUi(QWidget *parent) { m_backButton->setProperty("tutorial_name", "CONFIG_BUTTON"); } -scopy::gui::GenericMenu *Max14906::createGeneralSettings(const QString &title, QColor *color) { +scopy::gui::GenericMenu *Max14906::createGeneralSettings(const QString &title, QColor *color) +{ auto generalSettingsMenu = new scopy::gui::GenericMenu(this); generalSettingsMenu->initInteractiveMenu(); generalSettingsMenu->setMenuHeader(title, color, false); @@ -122,22 +126,18 @@ scopy::gui::GenericMenu *Max14906::createGeneralSettings(const QString &title, Q settingsWidgetSeparator->setContent(this->m_max14906SettingsTab); generalSettingsMenu->insertSection(settingsWidgetSeparator); - return generalSettingsMenu; } -void Max14906::connectSignalsAndSlots() { +void Max14906::connectSignalsAndSlots() +{ connect(this->m_toolView->getRunBtn(), &QPushButton::toggled, this, &Max14906::runButtonToggled); -// connect(this->m_toolView->getSingleBtn(), &QPushButton::clicked, this, &Max14906::singleButtonToggled); + // connect(this->m_toolView->getSingleBtn(), &QPushButton::clicked, this, &Max14906::singleButtonToggled); QObject::connect(m_backButton, &QPushButton::clicked, this, &Max14906::onBackBtnPressed); connect(this->m_max14906SettingsTab, &DioSettingsTab::timeValueChanged, this, &Max14906::timerChanged); - connect(this->m_qTimer, &QTimer::timeout, this, [&]() { - this->m_readerThread->start(); - }); - connect(m_readerThread, &ReaderThread::started, this, [&]() { - this->m_qTimer->start(1000); - }); + connect(this->m_qTimer, &QTimer::timeout, this, [&]() { this->m_readerThread->start(); }); + connect(m_readerThread, &ReaderThread::started, this, [&]() { this->m_qTimer->start(1000); }); connect(m_tme, &ToolMenuEntry::runToggled, this->m_toolView->getRunBtn(), &QPushButton::setChecked); } @@ -147,23 +147,28 @@ void Max14906::onBackBtnPressed() bool runBtnChecked = m_toolView->getRunBtn()->isChecked(); bool singleBtnChecked = m_toolView->getSingleBtn()->isChecked(); - if (runBtnChecked) { m_toolView->getRunBtn()->setChecked(false); } - if (singleBtnChecked) { m_toolView->getSingleBtn()->setChecked(false); } + if(runBtnChecked) { + m_toolView->getRunBtn()->setChecked(false); + } + if(singleBtnChecked) { + m_toolView->getSingleBtn()->setChecked(false); + } Q_EMIT backBtnPressed(); } -Max14906::~Max14906() { - if (this->m_toolView) { - if (this->m_toolView->getRunBtn()->isChecked()) { +Max14906::~Max14906() +{ + if(this->m_toolView) { + if(this->m_toolView->getRunBtn()->isChecked()) { this->m_toolView->getRunBtn()->setChecked(false); } - if (this->m_readerThread->isRunning()) { + if(this->m_readerThread->isRunning()) { this->m_readerThread->forcedStop(); this->m_readerThread->wait(); } delete m_readerThread; } - if (m_cmdQueue) { + if(m_cmdQueue) { CommandQueueProvider::GetInstance()->close(m_ctx); m_cmdQueue = nullptr; m_ctx = nullptr; @@ -172,107 +177,110 @@ Max14906::~Max14906() { delete ui; } -void Max14906::runButtonToggled() { +void Max14906::runButtonToggled() +{ qDebug(CAT_SWIOT_MAX14906) << "Run button clicked"; this->m_toolView->getSingleBtn()->setChecked(false); - if (this->m_toolView->getRunBtn()->isChecked()) { - for (auto &channel: this->m_channelControls) { + if(this->m_toolView->getRunBtn()->isChecked()) { + for(auto &channel : this->m_channelControls) { channel->getDigitalChannel()->resetSismograph(); } qDebug(CAT_SWIOT_MAX14906) << "Reader thread started"; this->m_readerThread->start(); - if (!this->m_tme->running()) { + if(!this->m_tme->running()) { m_tme->setRunning(true); } } else { - if (this->m_readerThread->isRunning()) { + if(this->m_readerThread->isRunning()) { qDebug(CAT_SWIOT_MAX14906) << "Reader thread stopped"; this->m_readerThread->forcedStop(); this->m_readerThread->wait(); } - if (this->m_tme->running()) { + if(this->m_tme->running()) { m_tme->setRunning(false); } this->m_qTimer->stop(); } } -void Max14906::timerChanged(double value) { - for (auto &channelControl: this->m_channelControls) { +void Max14906::timerChanged(double value) +{ + for(auto &channelControl : this->m_channelControls) { channelControl->getDigitalChannel()->updateTimeScale(value); } } -void Max14906::initMonitorToolView() { +void Max14906::initMonitorToolView() +{ this->ui->grid->setProperty("tutorial_name", "DIO_DIGITAL_CHANNEL_SPACE"); int nbChannels = m_channelControls.size(); int lineSpan; - if (nbChannels > 2) { + if(nbChannels > 2) { lineSpan = 3; this->ui->gridLayout->addWidget(scopy::swiot::Max14906::createVLine(this->ui->grid), 1, 0, 1, lineSpan); this->ui->gridLayout->addWidget(scopy::swiot::Max14906::createHLine(this->ui->grid), 0, 1, lineSpan, 1); - } else if (nbChannels == 2) { + } else if(nbChannels == 2) { lineSpan = 1; this->ui->gridLayout->addWidget(scopy::swiot::Max14906::createVLine(this->ui->grid), 1, 0, 1, lineSpan); } // there can only be 4 channels, so we position them accordingly - switch (m_channelControls.size()) { - case 4: { - DioDigitalChannel *digitalChannel = m_channelControls[3]->getDigitalChannel(); - auto mainWindow = createDockableMainWindow("", digitalChannel, this); + switch(m_channelControls.size()) { + case 4: { + DioDigitalChannel *digitalChannel = m_channelControls[3]->getDigitalChannel(); + auto mainWindow = createDockableMainWindow("", digitalChannel, this); - this->ui->gridLayout->addWidget(mainWindow, 2, 2); - } - case 3: { - DioDigitalChannel *digitalChannel = m_channelControls[2]->getDigitalChannel(); - auto mainWindow = createDockableMainWindow("", digitalChannel, this); + this->ui->gridLayout->addWidget(mainWindow, 2, 2); + } + case 3: { + DioDigitalChannel *digitalChannel = m_channelControls[2]->getDigitalChannel(); + auto mainWindow = createDockableMainWindow("", digitalChannel, this); - this->ui->gridLayout->addWidget(mainWindow, 0, 2); - } - case 2: { - DioDigitalChannel *digitalChannel = m_channelControls[1]->getDigitalChannel(); - auto mainWindow = createDockableMainWindow("", digitalChannel, this); + this->ui->gridLayout->addWidget(mainWindow, 0, 2); + } + case 2: { + DioDigitalChannel *digitalChannel = m_channelControls[1]->getDigitalChannel(); + auto mainWindow = createDockableMainWindow("", digitalChannel, this); - this->ui->gridLayout->addWidget(mainWindow, 2, 0); - } - case 1: { - DioDigitalChannel *digitalChannel = m_channelControls[0]->getDigitalChannel(); - auto mainWindow = createDockableMainWindow("", digitalChannel, this); + this->ui->gridLayout->addWidget(mainWindow, 2, 0); + } + case 1: { + DioDigitalChannel *digitalChannel = m_channelControls[0]->getDigitalChannel(); + auto mainWindow = createDockableMainWindow("", digitalChannel, this); - this->ui->gridLayout->addWidget(mainWindow, 0, 0); - } - default: { - break; - } + this->ui->gridLayout->addWidget(mainWindow, 0, 0); + } + default: { + break; + } } this->ui->gridLayout->addItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding), 2, 0); setUpdatesEnabled(true); } -void Max14906::initChannels() { - for (int i = 0; i < m_nbDioChannels; ++i) { +void Max14906::initChannels() +{ + for(int i = 0; i < m_nbDioChannels; ++i) { struct iio_channel *channel = iio_device_get_channel(this->max14906ToolController->getDevice(), i); DioDigitalChannelController *channel_control = new DioDigitalChannelController( - channel, - this->max14906ToolController->getChannelName(i), - this->max14906ToolController->getChannelType(i), - m_cmdQueue, this); + channel, this->max14906ToolController->getChannelName(i), + this->max14906ToolController->getChannelType(i), m_cmdQueue, this); this->m_channelControls.insert(i, channel_control); this->m_readerThread->addDioChannel(i, channel); connect(this->m_readerThread, &ReaderThread::channelDataChanged, channel_control, [this, i](int index, double value) { - if (i == index) { + if(i == index) { this->m_channelControls.value(index)->getDigitalChannel()->addDataSample(value); } }); } } -QPushButton *Max14906::createBackButton() { +QPushButton *Max14906::createBackButton() +{ auto *backButton = new QPushButton(); backButton->setObjectName(QString::fromUtf8("backButton")); backButton->setLayoutDirection(Qt::RightToLeft); @@ -294,7 +302,8 @@ QPushButton *Max14906::createBackButton() { return backButton; } -QFrame *Max14906::createVLine(QWidget *parent) { +QFrame *Max14906::createVLine(QWidget *parent) +{ auto *frame = new QFrame(parent); frame->setFrameShape(QFrame::VLine); frame->setFrameShadow(QFrame::Sunken); @@ -305,7 +314,8 @@ QFrame *Max14906::createVLine(QWidget *parent) { return frame; } -QFrame *Max14906::createHLine(QWidget *parent) { +QFrame *Max14906::createHLine(QWidget *parent) +{ auto *frame = new QFrame(parent); frame->setFrameShape(QFrame::HLine); frame->setFrameShadow(QFrame::Sunken); @@ -316,8 +326,9 @@ QFrame *Max14906::createHLine(QWidget *parent) { return frame; } -QMainWindow * -Max14906::createDockableMainWindow(const QString &title, DioDigitalChannel *digitalChannel, QWidget *parent) { +QMainWindow *Max14906::createDockableMainWindow(const QString &title, DioDigitalChannel *digitalChannel, + QWidget *parent) +{ auto mainWindow = new QMainWindow(parent); mainWindow->setCentralWidget(nullptr); mainWindow->setWindowFlags(Qt::Widget); @@ -328,8 +339,9 @@ Max14906::createDockableMainWindow(const QString &title, DioDigitalChannel *digi return mainWindow; } -void Max14906::externalPowerSupply(bool ps) { - if (ps) { +void Max14906::externalPowerSupply(bool ps) +{ + if(ps) { m_statusContainer->hide(); } else { m_statusContainer->show(); diff --git a/plugins/swiot/src/runtime/max14906/max14906.h b/plugins/swiot/src/runtime/max14906/max14906.h index 75011cab70..dc072a6a22 100644 --- a/plugins/swiot/src/runtime/max14906/max14906.h +++ b/plugins/swiot/src/runtime/max14906/max14906.h @@ -18,32 +18,34 @@ * along with this program. If not, see . */ - #ifndef MAX14906TOOL_H #define MAX14906TOOL_H -#include "pluginbase/toolmenuentry.h" -#include "ui_max14906.h" #include "diocontroller.h" #include "diodigitalchannelcontroller.h" -#include "src/runtime/readerthread.h" #include "diosettingstab.h" -#include +#include "pluginbase/toolmenuentry.h" +#include "src/runtime/readerthread.h" + +#include "ui_max14906.h" + #include +#include namespace scopy::swiot { #define MAX_NAME "max14906" class DioDigitalChannel; class DioController; -class Max14906 : public QWidget { +class Max14906 : public QWidget +{ Q_OBJECT public: explicit Max14906(struct iio_context *ctx, ToolMenuEntry *tme, QWidget *parent = nullptr); ~Max14906() override; Q_SIGNALS: - void backBtnPressed(); + void backBtnPressed(); public Q_SLOTS: void externalPowerSupply(bool ps); @@ -54,38 +56,40 @@ private Q_SLOTS: void timerChanged(double value); void onBackBtnPressed(); + private: - static QPushButton* createBackButton(); + static QPushButton *createBackButton(); void initChannels(); void setupDynamicUi(QWidget *parent); void initMonitorToolView(); - scopy::gui::GenericMenu* createGeneralSettings(const QString& title, QColor* color); + scopy::gui::GenericMenu *createGeneralSettings(const QString &title, QColor *color); void connectSignalsAndSlots(); - static QFrame* createVLine(QWidget* parent); - static QFrame* createHLine(QWidget* parent); - static QMainWindow* createDockableMainWindow(const QString& title, DioDigitalChannel* digitalChannel, QWidget* parent); + static QFrame *createVLine(QWidget *parent); + static QFrame *createHLine(QWidget *parent); + static QMainWindow *createDockableMainWindow(const QString &title, DioDigitalChannel *digitalChannel, + QWidget *parent); struct iio_context *m_ctx; - QPushButton *m_backButton; - QWidget* m_statusContainer; - QLabel* m_statusLabel; + QPushButton *m_backButton; + QWidget *m_statusContainer; + QLabel *m_statusLabel; int m_nbDioChannels; DioController *max14906ToolController; Ui::Max14906 *ui; DioSettingsTab *m_max14906SettingsTab; scopy::gui::ToolView *m_toolView; - scopy::gui::GenericMenu* m_generalSettingsMenu; + scopy::gui::GenericMenu *m_generalSettingsMenu; scopy::gui::SubsectionSeparator *settingsWidgetSeparator; QTimer *m_qTimer; CommandQueue *m_cmdQueue; ReaderThread *m_readerThread; - QMap m_channelControls; + QMap m_channelControls; ToolMenuEntry *m_tme; }; -} +} // namespace scopy::swiot #endif // MAX14906TOOL_H diff --git a/plugins/swiot/src/runtime/readerthread.cpp b/plugins/swiot/src/runtime/readerthread.cpp index bc99dd3195..860efa087e 100644 --- a/plugins/swiot/src/runtime/readerthread.cpp +++ b/plugins/swiot/src/runtime/readerthread.cpp @@ -18,24 +18,25 @@ * along with this program. If not, see . */ - #include "readerthread.h" -#include "src/swiot_logging_categories.h" + #include "src/runtime/ad74413r/bufferlogic.h" +#include "src/swiot_logging_categories.h" + +#include + +#include +#include +#include #include #include #include -#include -#include -#include - -#include using namespace scopy::swiot; ReaderThread::ReaderThread(bool isBuffered, CommandQueue *cmdQueue, QObject *parent) : QThread{parent} - , isBuffered(isBuffered) + , isBuffered(isBuffered) , m_enabledChnlsNo(0) , m_iioBuff(nullptr) , m_iioDev(nullptr) @@ -44,65 +45,63 @@ ReaderThread::ReaderThread(bool isBuffered, CommandQueue *cmdQueue, QObject *par , bufferCounter(0) , m_running(false) , m_bufferInvalid(false) -{ -} +{} -ReaderThread::~ReaderThread() -{ - forcedStop(); -} +ReaderThread::~ReaderThread() { forcedStop(); } -void ReaderThread::addDioChannel(int index, struct iio_channel *channel) { - m_dioChannels.insert(index, channel); -} +void ReaderThread::addDioChannel(int index, struct iio_channel *channel) { m_dioChannels.insert(index, channel); } void ReaderThread::createDioChannelCommand(int index) { Command *dioChannelReadCommand = new IioChannelAttributeRead(m_dioChannels[index], "raw", nullptr); - connect(dioChannelReadCommand, &scopy::Command::finished, this, [=, this] (scopy::Command *cmd) { - IioChannelAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { - return; - } + connect( + dioChannelReadCommand, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioChannelAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + return; + } - auto channel = tcmd->getChannel(); - if (!channel) { - return; - } - int channelIndex = m_dioChannels.key(channel); - if (tcmd->getReturnCode() >= 0) { - char *res = tcmd->getResult(); - bool ok = false; - double raw = QString(res).toDouble(&ok); - if (ok) { - Q_EMIT channelDataChanged(channelIndex, raw); + auto channel = tcmd->getChannel(); + if(!channel) { + return; } - qDebug(CAT_SWIOT_MAX14906) << "Channel with index " << channelIndex << " read raw value: " << raw; - } else { - qCritical(CAT_SWIOT_MAX14906) << "Failed to acquire data on DioReaderThread " << tcmd->getReturnCode(); - } - }, Qt::QueuedConnection); + int channelIndex = m_dioChannels.key(channel); + if(tcmd->getReturnCode() >= 0) { + char *res = tcmd->getResult(); + bool ok = false; + double raw = QString(res).toDouble(&ok); + if(ok) { + Q_EMIT channelDataChanged(channelIndex, raw); + } + qDebug(CAT_SWIOT_MAX14906) + << "Channel with index " << channelIndex << " read raw value: " << raw; + } else { + qCritical(CAT_SWIOT_MAX14906) + << "Failed to acquire data on DioReaderThread " << tcmd->getReturnCode(); + } + }, + Qt::QueuedConnection); m_cmdQueue->enqueue(dioChannelReadCommand); } -void ReaderThread::runDio() { +void ReaderThread::runDio() +{ qDebug(CAT_SWIOT_MAX14906) << "DioReaderThread started"; try { - if (!this->m_dioChannels.empty()) { + if(!this->m_dioChannels.empty()) { auto keys = this->m_dioChannels.keys(); - for (int index : keys) { + for(int index : keys) { createDioChannelCommand(index); } } - } catch (...) { + } catch(...) { qCritical(CAT_SWIOT_MAX14906) << "Failed to acquire data on DioReaderThread"; } } -void ReaderThread::addBufferedDevice(iio_device *device) { - m_iioDev = device; -} +void ReaderThread::addBufferedDevice(iio_device *device) { m_iioDev = device; } void ReaderThread::initIioChannels() { @@ -115,75 +114,75 @@ void ReaderThread::initIioChannels() void ReaderThread::enableIioChnls() { - if (m_iioDev) { + if(m_iioDev) { auto keys = m_chnlsInfo.keys(); for(const auto &key : keys) { - struct iio_channel* iioChnl = m_chnlsInfo[key]->iioChnl(); - bool isEnabled = iio_channel_is_enabled(iioChnl); - if (m_chnlsInfo[key]->isEnabled()) { - if (!isEnabled) { - iio_channel_enable(iioChnl); - } + struct iio_channel *iioChnl = m_chnlsInfo[key]->iioChnl(); + bool isEnabled = iio_channel_is_enabled(iioChnl); + if(m_chnlsInfo[key]->isEnabled()) { + if(!isEnabled) { + iio_channel_enable(iioChnl); + } qDebug(CAT_SWIOT_AD74413R) << "Chanel en " << key; - } else { - if (isEnabled) { - iio_channel_disable(iioChnl); - } + } else { + if(isEnabled) { + iio_channel_disable(iioChnl); + } qDebug(CAT_SWIOT_AD74413R) << "Chanel dis " << key; - } - } - } + } + } + } } int ReaderThread::getEnabledChnls() { int enChnls = 0; auto keys = m_chnlsInfo.keys(); - for (const auto &key : keys) { - if (iio_channel_is_enabled(m_chnlsInfo[key]->iioChnl())) { - enChnls++; - } - } + for(const auto &key : keys) { + if(iio_channel_is_enabled(m_chnlsInfo[key]->iioChnl())) { + enChnls++; + } + } return enChnls; } QVector ReaderThread::getEnabledBufferedChnls() { - QVector enabledBufferedChnls= {}; + QVector enabledBufferedChnls = {}; auto keys = m_chnlsInfo.keys(); - for (const auto &key : keys) { - if (m_chnlsInfo[key]->isScanElement() && m_chnlsInfo[key]->isEnabled() - && !m_chnlsInfo[key]->isOutput()) { + for(const auto &key : keys) { + if(m_chnlsInfo[key]->isScanElement() && m_chnlsInfo[key]->isEnabled() && + !m_chnlsInfo[key]->isOutput()) { enabledBufferedChnls.push_back(m_chnlsInfo[key]); } } return enabledBufferedChnls; } -void ReaderThread::bufferRefillCommandFinished(scopy::Command* cmd) +void ReaderThread::bufferRefillCommandFinished(scopy::Command *cmd) { std::unique_lock lock(m_mutex); - IioBufferRefill *tcmd = dynamic_cast(cmd); - if (!tcmd) { + IioBufferRefill *tcmd = dynamic_cast(cmd); + if(!tcmd) { return; } - if (m_bufferInvalid) { + if(m_bufferInvalid) { return; } - if (tcmd->getReturnCode() > 0) { + if(tcmd->getReturnCode() > 0) { int i = 0; int idx = 0; double data = 0.0; - uint32_t* startAdr = (uint32_t*)iio_buffer_start(m_iioBuff); - uint32_t* endAdr = (uint32_t*)iio_buffer_end(m_iioBuff); + uint32_t *startAdr = (uint32_t *)iio_buffer_start(m_iioBuff); + uint32_t *endAdr = (uint32_t *)iio_buffer_end(m_iioBuff); m_bufferData.clear(); - for (int i=0; i < m_enabledChnlsNo; i++){ + for(int i = 0; i < m_enabledChnlsNo; i++) { m_bufferData.push_back({}); } - for (uint32_t* ptr = startAdr; ptr != endAdr; ptr++) { + for(uint32_t *ptr = startAdr; ptr != endAdr; ptr++) { idx = i % m_enabledChnlsNo; uint32_t d_ptr = (uint32_t)*ptr; data = m_bufferedChnls[idx]->convertData(d_ptr); @@ -200,11 +199,11 @@ void ReaderThread::bufferRefillCommandFinished(scopy::Command* cmd) void ReaderThread::bufferCreateCommandFinished(scopy::Command *cmd) { std::unique_lock lock(m_mutex); - IioDeviceCreateBuffer *tcmd = dynamic_cast(cmd); - if (!tcmd) { + IioDeviceCreateBuffer *tcmd = dynamic_cast(cmd); + if(!tcmd) { return; } - if (tcmd->getReturnCode() < 0) { + if(tcmd->getReturnCode() < 0) { qDebug(CAT_SWIOT_AD74413R) << "Buffer wasn't created: " + QString(strerror(-tcmd->getReturnCode())); } else { m_iioBuff = tcmd->getResult(); @@ -216,22 +215,21 @@ void ReaderThread::bufferCreateCommandFinished(scopy::Command *cmd) void ReaderThread::bufferCancelCommandFinished(scopy::Command *cmd) { std::unique_lock lock(m_mutex); - IioBufferCancel *tcmd = dynamic_cast(cmd); - if (!tcmd) { + IioBufferCancel *tcmd = dynamic_cast(cmd); + if(!tcmd) { return; } - if (tcmd->getReturnCode() < 0) { + if(tcmd->getReturnCode() < 0) { qDebug(CAT_SWIOT_AD74413R) << "Buffer wasn't canceled: " + QString(strerror(-tcmd->getReturnCode())); } lock.unlock(); destroyIioBuffer(); } - void ReaderThread::bufferDestroyCommandStarted(scopy::Command *cmd) { - IioBufferDestroy *tcmd = dynamic_cast(cmd); - if (!tcmd) { + IioBufferDestroy *tcmd = dynamic_cast(cmd); + if(!tcmd) { return; } m_bufferInvalid = true; @@ -240,12 +238,12 @@ void ReaderThread::bufferDestroyCommandStarted(scopy::Command *cmd) void ReaderThread::bufferDestroyCommandFinished(scopy::Command *cmd) { std::unique_lock lock(m_mutex); - IioBufferDestroy *tcmd = dynamic_cast(cmd); - if (!tcmd) { + IioBufferDestroy *tcmd = dynamic_cast(cmd); + if(!tcmd) { Q_EMIT readerThreadFinished(); return; } - if (tcmd->getReturnCode() < 0) { + if(tcmd->getReturnCode() < 0) { qDebug(CAT_SWIOT_AD74413R) << "Buffer wasn't destroyed: " + QString(strerror(-tcmd->getReturnCode())); } else { m_iioBuff = nullptr; @@ -260,14 +258,15 @@ void ReaderThread::createIioBuffer() m_enabledChnlsNo = getEnabledChnls(); m_bufferedChnls = getEnabledBufferedChnls(); qInfo(CAT_SWIOT_AD74413R) << "Enabled channels number: " + QString::number(m_enabledChnlsNo); - if (m_iioDev) { - Command *createBufferCommand ; + if(m_iioDev) { + Command *createBufferCommand; if(m_samplingFreq >= MAX_BUFFER_SIZE) { createBufferCommand = new IioDeviceCreateBuffer(m_iioDev, MAX_BUFFER_SIZE, false, nullptr); } else { createBufferCommand = new IioDeviceCreateBuffer(m_iioDev, MIN_BUFFER_SIZE, false, nullptr); } - connect(createBufferCommand, &scopy::Command::finished, this, &ReaderThread::bufferCreateCommandFinished, Qt::QueuedConnection); + connect(createBufferCommand, &scopy::Command::finished, this, + &ReaderThread::bufferCreateCommandFinished, Qt::QueuedConnection); m_cmdQueue->enqueue(createBufferCommand); } } @@ -275,9 +274,10 @@ void ReaderThread::createIioBuffer() void ReaderThread::cancelIioBuffer() { std::unique_lock lock(m_mutex); - if (m_iioBuff) { + if(m_iioBuff) { Command *cancelBufferCommand = new IioBufferCancel(m_iioBuff, nullptr); - connect(cancelBufferCommand, &scopy::Command::finished, this, &ReaderThread::bufferCancelCommandFinished, Qt::QueuedConnection); + connect(cancelBufferCommand, &scopy::Command::finished, this, + &ReaderThread::bufferCancelCommandFinished, Qt::QueuedConnection); m_cmdQueue->enqueue(cancelBufferCommand); } } @@ -285,39 +285,36 @@ void ReaderThread::cancelIioBuffer() void ReaderThread::destroyIioBuffer() { std::unique_lock lock(m_mutex); - if (m_iioBuff) { + if(m_iioBuff) { Command *destroyBufferCommand = new IioBufferDestroy(m_iioBuff, nullptr); - connect(destroyBufferCommand, &scopy::Command::finished, this, &ReaderThread::bufferDestroyCommandFinished, Qt::QueuedConnection); + connect(destroyBufferCommand, &scopy::Command::finished, this, + &ReaderThread::bufferDestroyCommandFinished, Qt::QueuedConnection); m_bufferInvalid = true; m_cmdQueue->enqueue(destroyBufferCommand); - } + } } -void ReaderThread::onChnlsChange(QMap chnlsInfo) -{ - m_chnlsInfo = chnlsInfo; -} +void ReaderThread::onChnlsChange(QMap chnlsInfo) { m_chnlsInfo = chnlsInfo; } -void ReaderThread::onSamplingFreqWritten(int samplingFreq) -{ - m_samplingFreq = samplingFreq; -} +void ReaderThread::onSamplingFreqWritten(int samplingFreq) { m_samplingFreq = samplingFreq; } -void ReaderThread::runBuffered(int requiredBuffersNumber) { +void ReaderThread::runBuffered(int requiredBuffersNumber) +{ std::unique_lock lock(m_mutex); - if (!m_iioBuff || !m_running) { + if(!m_iioBuff || !m_running) { m_running = false; return; } - if ((m_requiredBuffersNumber != 0) && (bufferCounter >= m_requiredBuffersNumber)) { + if((m_requiredBuffersNumber != 0) && (bufferCounter >= m_requiredBuffersNumber)) { return; } - if (m_bufferInvalid) { + if(m_bufferInvalid) { return; } - if (m_iioBuff) { + if(m_iioBuff) { Command *refillBufferCommand = new IioBufferRefill(m_iioBuff, nullptr); - connect(refillBufferCommand, &scopy::Command::finished, this, &ReaderThread::bufferRefillCommandFinished, Qt::QueuedConnection); + connect(refillBufferCommand, &scopy::Command::finished, this, + &ReaderThread::bufferRefillCommandFinished, Qt::QueuedConnection); m_cmdQueue->enqueue(refillBufferCommand); bufferCounter++; } @@ -326,24 +323,25 @@ void ReaderThread::runBuffered(int requiredBuffersNumber) { void ReaderThread::requestStop() { requestInterruption(); - if (isBuffered && m_running) { + if(isBuffered && m_running) { m_running = false; destroyIioBuffer(); } wait(); } -void ReaderThread::run() { - if (isBuffered) { +void ReaderThread::run() +{ + if(isBuffered) { this->runBuffered(m_requiredBuffersNumber); - } else { - this->runDio(); - } + } else { + this->runDio(); + } } void ReaderThread::startCapture(int requiredBuffersNumber) { - if (isBuffered) { + if(isBuffered) { bufferCounter = 0; m_requiredBuffersNumber = requiredBuffersNumber; enableIioChnls(); @@ -355,14 +353,12 @@ void ReaderThread::startCapture(int requiredBuffersNumber) } } -void ReaderThread::singleDio() { - this->runDio(); -} +void ReaderThread::singleDio() { this->runDio(); } void ReaderThread::forcedStop() { requestInterruption(); - if (isBuffered && m_running) { + if(isBuffered && m_running) { m_running = false; cancelIioBuffer(); } diff --git a/plugins/swiot/src/runtime/readerthread.h b/plugins/swiot/src/runtime/readerthread.h index 42df494728..08ca6a7471 100644 --- a/plugins/swiot/src/runtime/readerthread.h +++ b/plugins/swiot/src/runtime/readerthread.h @@ -18,20 +18,23 @@ * along with this program. If not, see . */ - #ifndef READERTHREAD_H #define READERTHREAD_H #include "src/runtime/ad74413r/chnlinfo.h" -#include + +#include + #include #include +#include + #include -#include #include namespace scopy::swiot { -class ReaderThread : public QThread { +class ReaderThread : public QThread +{ Q_OBJECT public: explicit ReaderThread(bool isBuffered, CommandQueue *cmdQueue, QObject *parent = nullptr); @@ -44,7 +47,7 @@ class ReaderThread : public QThread { void addBufferedDevice(iio_device *device); void runDio(); - void singleDio(); + void singleDio(); void runBuffered(int requiredBuffersNumber = 0); @@ -96,12 +99,12 @@ private Q_SLOTS: struct iio_device *m_iioDev; struct iio_buffer *m_iioBuff; - QMap m_chnlsInfo; + QMap m_chnlsInfo; QVector m_bufferedChnls; QVector> m_bufferData; std::atomic m_running, m_bufferInvalid; std::mutex m_mutex; }; -} +} // namespace scopy::swiot #endif // READERTHREAD_H diff --git a/plugins/swiot/src/runtime/swiotruntime.cpp b/plugins/swiot/src/runtime/swiotruntime.cpp index 0f3407a76e..5d70034af8 100644 --- a/plugins/swiot/src/runtime/swiotruntime.cpp +++ b/plugins/swiot/src/runtime/swiotruntime.cpp @@ -18,12 +18,13 @@ * along with this program. If not, see . */ - #include "swiotruntime.h" -#include + #include "src/swiot_logging_categories.h" + #include #include +#include using namespace scopy::swiot; @@ -32,7 +33,7 @@ SwiotRuntime::SwiotRuntime(struct iio_context *ctx, QObject *parent) , m_iioCtx(ctx) , m_cmdQueue(nullptr) { - if (m_iioCtx) { + if(m_iioCtx) { m_cmdQueue = CommandQueueProvider::GetInstance()->open(m_iioCtx); } createDevicesMap(); @@ -40,7 +41,7 @@ SwiotRuntime::SwiotRuntime(struct iio_context *ctx, QObject *parent) SwiotRuntime::~SwiotRuntime() { - if (m_cmdQueue) { + if(m_cmdQueue) { CommandQueueProvider::GetInstance()->close(m_iioCtx); m_cmdQueue = nullptr; m_iioCtx = nullptr; @@ -49,18 +50,18 @@ SwiotRuntime::~SwiotRuntime() void SwiotRuntime::onIsRuntimeCtxChanged(bool isRuntimeCtx) { - if (isRuntimeCtx) { + if(isRuntimeCtx) { writeTriggerDevice(); } } void SwiotRuntime::writeTriggerDevice() { - if (m_iioDevices.contains(AD_TRIGGER_NAME)) { - Command *setTriggerCommand = new IioDeviceSetTrigger(m_iioDevices[AD_NAME], - m_iioDevices[AD_TRIGGER_NAME], nullptr); - connect(setTriggerCommand, &scopy::Command::finished, this, - &SwiotRuntime::setTriggerCommandFinished, Qt::QueuedConnection); + if(m_iioDevices.contains(AD_TRIGGER_NAME)) { + Command *setTriggerCommand = + new IioDeviceSetTrigger(m_iioDevices[AD_NAME], m_iioDevices[AD_TRIGGER_NAME], nullptr); + connect(setTriggerCommand, &scopy::Command::finished, this, &SwiotRuntime::setTriggerCommandFinished, + Qt::QueuedConnection); m_cmdQueue->enqueue(setTriggerCommand); } else { qDebug(CAT_SWIOT) << "Isn't runtime context"; @@ -69,11 +70,11 @@ void SwiotRuntime::writeTriggerDevice() void SwiotRuntime::setTriggerCommandFinished(scopy::Command *cmd) { - IioDeviceSetTrigger *tcmd = dynamic_cast(cmd); - if (!tcmd) { + IioDeviceSetTrigger *tcmd = dynamic_cast(cmd); + if(!tcmd) { return; } - if (tcmd->getReturnCode() >= 0) { + if(tcmd->getReturnCode() >= 0) { qDebug(CAT_SWIOT) << "Trigger has been set: " + QString::number(tcmd->getReturnCode()); } else { qDebug(CAT_SWIOT) << "Can't set trigger, not in runtime context"; @@ -82,12 +83,12 @@ void SwiotRuntime::setTriggerCommandFinished(scopy::Command *cmd) void SwiotRuntime::createDevicesMap() { - if (m_iioCtx) { + if(m_iioCtx) { int devicesNumber = iio_context_get_devices_count(m_iioCtx); m_iioDevices.clear(); - for (int i = 0; i < devicesNumber; i++) { - struct iio_device* iioDev = iio_context_get_device(m_iioCtx, i); - if (iioDev) { + for(int i = 0; i < devicesNumber; i++) { + struct iio_device *iioDev = iio_context_get_device(m_iioCtx, i); + if(iioDev) { QString deviceName = QString(iio_device_get_name(iioDev)); m_iioDevices[deviceName] = iioDev; } @@ -95,14 +96,11 @@ void SwiotRuntime::createDevicesMap() } } -void SwiotRuntime::onBackBtnPressed() -{ - Q_EMIT writeModeAttribute("config"); -} +void SwiotRuntime::onBackBtnPressed() { Q_EMIT writeModeAttribute("config"); } void SwiotRuntime::modeAttributeChanged(std::string mode) { - if (mode == "config") { + if(mode == "config") { Q_EMIT backBtnPressed(); } } diff --git a/plugins/swiot/src/runtime/swiotruntime.h b/plugins/swiot/src/runtime/swiotruntime.h index 0b1416448f..542438ea9c 100644 --- a/plugins/swiot/src/runtime/swiotruntime.h +++ b/plugins/swiot/src/runtime/swiotruntime.h @@ -18,7 +18,6 @@ * along with this program. If not, see . */ - #ifndef SWIOTRUNTIME_H #define SWIOTRUNTIME_H @@ -28,7 +27,7 @@ namespace scopy { namespace gui { class GenericMenu; class ChannelManager; -} +} // namespace gui namespace swiot { #define AD_NAME "ad74413r" @@ -47,18 +46,20 @@ public Q_SLOTS: void writeTriggerDevice(); void onIsRuntimeCtxChanged(bool isRuntimeCtx); private Q_SLOTS: - void setTriggerCommandFinished(scopy::Command*); + void setTriggerCommandFinished(scopy::Command *); Q_SIGNALS: void writeModeAttribute(std::string mode); void backBtnPressed(); + private: void createDevicesMap(); + private: iio_context *m_iioCtx; - QMap m_iioDevices; + QMap m_iioDevices; CommandQueue *m_cmdQueue; }; -} -} +} // namespace swiot +} // namespace scopy #endif // SWIOTRUNTIME_H diff --git a/plugins/swiot/src/swiot_logging_categories.cpp b/plugins/swiot/src/swiot_logging_categories.cpp index abeb330011..d9baee813a 100644 --- a/plugins/swiot/src/swiot_logging_categories.cpp +++ b/plugins/swiot/src/swiot_logging_categories.cpp @@ -18,7 +18,6 @@ * along with this program. If not, see . */ - #include "swiot_logging_categories.h" #ifndef QT_NO_DEBUG_OUTPUT diff --git a/plugins/swiot/src/swiot_logging_categories.h b/plugins/swiot/src/swiot_logging_categories.h index 6574ed9b2f..dfa45fea44 100644 --- a/plugins/swiot/src/swiot_logging_categories.h +++ b/plugins/swiot/src/swiot_logging_categories.h @@ -18,7 +18,6 @@ * along with this program. If not, see . */ - #ifndef SCOPY_SWIOT_LOGGING_CATEGORIES_H #define SCOPY_SWIOT_LOGGING_CATEGORIES_H @@ -38,4 +37,4 @@ Q_DECLARE_LOGGING_CATEGORY(CAT_SWIOT_MAX14906) #define CAT_SWIOT_MAX14906 #endif -#endif //SCOPY_SWIOT_LOGGING_CATEGORIES_H +#endif // SCOPY_SWIOT_LOGGING_CATEGORIES_H diff --git a/plugins/swiot/src/swiotcontroller.cpp b/plugins/swiot/src/swiotcontroller.cpp index af46a1486a..19adeb8a09 100644 --- a/plugins/swiot/src/swiotcontroller.cpp +++ b/plugins/swiot/src/swiotcontroller.cpp @@ -18,12 +18,13 @@ * along with this program. If not, see . */ - #include "swiotcontroller.h" + #include "src/swiot_logging_categories.h" + #include -#include #include +#include using namespace scopy; using namespace scopy::swiot; @@ -44,15 +45,14 @@ SwiotController::SwiotController(QString uri, QObject *parent) m_cmdQueue = nullptr; } -SwiotController::~SwiotController() -{} +SwiotController::~SwiotController() {} void SwiotController::startPingTask() { pingTask = new SwiotPingTask(m_iioCtx); pingTimer = new CyclicalTask(pingTask); - connect(pingTask,SIGNAL(pingSuccess()),this,SIGNAL(pingSuccess())); - connect(pingTask,SIGNAL(pingFailed()),this,SIGNAL(pingFailed())); + connect(pingTask, SIGNAL(pingSuccess()), this, SIGNAL(pingSuccess())); + connect(pingTask, SIGNAL(pingFailed()), this, SIGNAL(pingFailed())); pingTimer->start(2000); } @@ -81,7 +81,7 @@ void SwiotController::stopSwitchContextTask() void SwiotController::connectSwiot(iio_context *ctx) { m_iioCtx = ctx; - if (m_iioCtx) { + if(m_iioCtx) { m_cmdQueue = CommandQueueProvider::GetInstance()->open(m_iioCtx); readModeAttribute(); } @@ -89,7 +89,7 @@ void SwiotController::connectSwiot(iio_context *ctx) void SwiotController::disconnectSwiot() { - if (m_cmdQueue) { + if(m_cmdQueue) { CommandQueueProvider::GetInstance()->close(m_iioCtx); m_cmdQueue = nullptr; } @@ -100,7 +100,8 @@ void SwiotController::startPowerSupplyTask(QString attribute) { extPsTask = new ExternalPsReaderThread(uri, attribute, this); powerSupplyTimer = new CyclicalTask(extPsTask); - connect(extPsTask, &ExternalPsReaderThread::hasConnectedPowerSupply, this, &SwiotController::hasConnectedPowerSupply); + connect(extPsTask, &ExternalPsReaderThread::hasConnectedPowerSupply, this, + &SwiotController::hasConnectedPowerSupply); powerSupplyTimer->start(5000); } @@ -108,13 +109,15 @@ void SwiotController::stopPowerSupplyTask() { powerSupplyTimer->stop(); extPsTask->requestInterruption(); - disconnect(extPsTask, &ExternalPsReaderThread::hasConnectedPowerSupply, this, &SwiotController::hasConnectedPowerSupply); + disconnect(extPsTask, &ExternalPsReaderThread::hasConnectedPowerSupply, this, + &SwiotController::hasConnectedPowerSupply); powerSupplyTimer->deleteLater(); extPsTask->deleteLater(); } -void SwiotController::startTemperatureTask() { - if (!m_isRuntimeCtx || m_temperatureReadEn) { +void SwiotController::startTemperatureTask() +{ + if(!m_isRuntimeCtx || m_temperatureReadEn) { return; } temperatureTask = new SwiotReadTemperatureTask(uri, this); @@ -124,8 +127,9 @@ void SwiotController::startTemperatureTask() { m_temperatureReadEn = true; } -void SwiotController::stopTemperatureTask() { - if (!m_isRuntimeCtx || !m_temperatureReadEn) { +void SwiotController::stopTemperatureTask() +{ + if(!m_isRuntimeCtx || !m_temperatureReadEn) { return; } temperatureTask->requestInterruption(); @@ -141,7 +145,7 @@ void SwiotController::identify() if(!identifyTask) { identifyTask = new SwiotIdentifyTask(uri); identifyTask->start(); - connect(identifyTask,&QThread::finished,this,[=, this](){ + connect(identifyTask, &QThread::finished, this, [=, this]() { delete identifyTask; identifyTask = nullptr; }); @@ -150,14 +154,14 @@ void SwiotController::identify() void SwiotController::writeModeAttribute(std::string mode) { - if (!m_iioCtx || !m_cmdQueue) { + if(!m_iioCtx || !m_cmdQueue) { return; } struct iio_device *swiot = iio_context_find_device(m_iioCtx, "swiot"); - if (swiot) { + if(swiot) { Command *writeModeCommand = new IioDeviceAttributeWrite(swiot, "mode", mode.c_str(), nullptr); - connect(writeModeCommand, &scopy::Command::finished, this, - &SwiotController::writeModeCommandFinished, Qt::QueuedConnection); + connect(writeModeCommand, &scopy::Command::finished, this, &SwiotController::writeModeCommandFinished, + Qt::QueuedConnection); m_cmdQueue->enqueue(writeModeCommand); } else { qDebug(CAT_SWIOT) << "Can't find swiot iio_device"; @@ -166,11 +170,11 @@ void SwiotController::writeModeAttribute(std::string mode) void SwiotController::writeModeCommandFinished(scopy::Command *cmd) { - IioDeviceAttributeWrite *tcmd = dynamic_cast(cmd); - if (!tcmd) { + IioDeviceAttributeWrite *tcmd = dynamic_cast(cmd); + if(!tcmd) { return; } - if (tcmd->getReturnCode() >= 0) { + if(tcmd->getReturnCode() >= 0) { Q_EMIT modeAttributeChanged(tcmd->getAttributeValue()); qInfo(CAT_SWIOT) << R"(Successfully changed the swiot mode)"; } else { @@ -180,14 +184,14 @@ void SwiotController::writeModeCommandFinished(scopy::Command *cmd) void SwiotController::readModeAttribute() { - if (!m_iioCtx || !m_cmdQueue) { + if(!m_iioCtx || !m_cmdQueue) { return; } struct iio_device *swiot = iio_context_find_device(m_iioCtx, "swiot"); - if (swiot) { + if(swiot) { Command *readModeCommand = new IioDeviceAttributeRead(swiot, "mode", nullptr); - connect(readModeCommand, &scopy::Command::finished, this, - &SwiotController::readModeCommandFinished, Qt::QueuedConnection); + connect(readModeCommand, &scopy::Command::finished, this, &SwiotController::readModeCommandFinished, + Qt::QueuedConnection); m_cmdQueue->enqueue(readModeCommand); } else { qDebug(CAT_SWIOT) << "Can't find swiot iio_device"; @@ -196,16 +200,17 @@ void SwiotController::readModeAttribute() void SwiotController::readModeCommandFinished(scopy::Command *cmd) { - IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { + IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { return; } - if (tcmd->getReturnCode() >= 0) { - char* mode = tcmd->getResult(); + if(tcmd->getReturnCode() >= 0) { + char *mode = tcmd->getResult(); bool runtime = (strcmp(mode, "runtime") == 0); setIsRuntimeCtx(runtime); } else { - qDebug(CAT_SWIOT) << R"(Critical error: could not read mode attribute, error code:)" << tcmd->getReturnCode(); + qDebug(CAT_SWIOT) << R"(Critical error: could not read mode attribute, error code:)" + << tcmd->getReturnCode(); } } diff --git a/plugins/swiot/src/swiotcontroller.h b/plugins/swiot/src/swiotcontroller.h index 3b46bc3995..d5cbed9f10 100644 --- a/plugins/swiot/src/swiotcontroller.h +++ b/plugins/swiot/src/swiotcontroller.h @@ -18,20 +18,20 @@ * along with this program. If not, see . */ - #ifndef SWIOTCONTROLLER_H #define SWIOTCONTROLLER_H -#include -#include -#include "iioutil/iiopingtask.h" #include "iioutil/cyclicaltask.h" +#include "iioutil/iiopingtask.h" #include "src/externalpsreaderthread.h" -#include "src/swiotswitchctxtask.h" -#include "src/swiotreadtemperaturetask.h" #include "src/swiotidentifytask.h" #include "src/swiotpingtask.h" +#include "src/swiotreadtemperaturetask.h" +#include "src/swiotswitchctxtask.h" + +#include +#include namespace scopy::swiot { class SwiotController : public QObject @@ -92,7 +92,6 @@ private Q_SLOTS: CyclicalTask *powerSupplyTimer; CyclicalTask *temperatureTimer; }; -} - +} // namespace scopy::swiot #endif // SWIOTCONTROLLER_H diff --git a/plugins/swiot/src/swiotidentifytask.cpp b/plugins/swiot/src/swiotidentifytask.cpp index be383639ea..ccceb33d0f 100644 --- a/plugins/swiot/src/swiotidentifytask.cpp +++ b/plugins/swiot/src/swiotidentifytask.cpp @@ -1,48 +1,60 @@ #include "swiotidentifytask.h" + +#include "src/swiot_logging_categories.h" + #include -#include + #include +#include #include -#include "src/swiot_logging_categories.h" using namespace scopy::swiot; -SwiotIdentifyTask::SwiotIdentifyTask(QString uri, QObject *parent) : QThread(parent), m_uri(uri) {} +SwiotIdentifyTask::SwiotIdentifyTask(QString uri, QObject *parent) + : QThread(parent) + , m_uri(uri) +{} SwiotIdentifyTask::~SwiotIdentifyTask() {} -void SwiotIdentifyTask::run() { +void SwiotIdentifyTask::run() +{ iio_context *ctx = ContextProvider::GetInstance()->open(m_uri); - if (!ctx) { + if(!ctx) { return; } - if (isInterruptionRequested()) { + if(isInterruptionRequested()) { ContextProvider::GetInstance()->close(m_uri); return; } CommandQueue *commandQueue = CommandQueueProvider::GetInstance()->open(ctx); - if (!commandQueue) { + if(!commandQueue) { ContextProvider::GetInstance()->close(m_uri); return; } iio_device *swiotDevice = iio_context_find_device(ctx, "swiot"); - if (swiotDevice) { - IioDeviceAttributeWrite *iioAttrWrite = new IioDeviceAttributeWrite(swiotDevice, "identify", "1", nullptr, true); + if(swiotDevice) { + IioDeviceAttributeWrite *iioAttrWrite = + new IioDeviceAttributeWrite(swiotDevice, "identify", "1", nullptr, true); - connect(iioAttrWrite, &scopy::Command::finished, this, [=, this](scopy::Command *cmd) { - IioDeviceAttributeWrite *tcmd = dynamic_cast(cmd); - if (!tcmd) { + connect( + iioAttrWrite, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioDeviceAttributeWrite *tcmd = dynamic_cast(cmd); + if(!tcmd) { + CommandQueueProvider::GetInstance()->close(ctx); + ContextProvider::GetInstance()->close(m_uri); + return; + } + if(tcmd->getReturnCode() < 0) { + qCritical(CAT_SWIOT) << "Error, could not identify swiot, error code" + << tcmd->getReturnCode(); + } CommandQueueProvider::GetInstance()->close(ctx); ContextProvider::GetInstance()->close(m_uri); - return; - } - if (tcmd->getReturnCode() < 0) { - qCritical(CAT_SWIOT) << "Error, could not identify swiot, error code" << tcmd->getReturnCode(); - } - CommandQueueProvider::GetInstance()->close(ctx); - ContextProvider::GetInstance()->close(m_uri); - }, Qt::QueuedConnection); + }, + Qt::QueuedConnection); commandQueue->enqueue(iioAttrWrite); } else { diff --git a/plugins/swiot/src/swiotidentifytask.h b/plugins/swiot/src/swiotidentifytask.h index 91bfddcfab..b94b6882a1 100644 --- a/plugins/swiot/src/swiotidentifytask.h +++ b/plugins/swiot/src/swiotidentifytask.h @@ -3,13 +3,15 @@ #include namespace scopy::swiot { -class SwiotIdentifyTask : public QThread { +class SwiotIdentifyTask : public QThread +{ public: SwiotIdentifyTask(QString uri, QObject *parent = nullptr); ~SwiotIdentifyTask(); void run() override; + private: QString m_uri; }; -} +} // namespace scopy::swiot #endif // SWIOTIDENTIFYTASK_H diff --git a/plugins/swiot/src/swiotinfopage.cpp b/plugins/swiot/src/swiotinfopage.cpp index 88f3a076e9..4aa4af81e4 100644 --- a/plugins/swiot/src/swiotinfopage.cpp +++ b/plugins/swiot/src/swiotinfopage.cpp @@ -18,14 +18,16 @@ * along with this program. If not, see . */ - #include "swiotinfopage.h" + #include "smallOnOffSwitch.h" + #include using namespace scopy::swiot; -SwiotInfoPage::SwiotInfoPage(QWidget* parent) : InfoPage(parent) +SwiotInfoPage::SwiotInfoPage(QWidget *parent) + : InfoPage(parent) { // not enough attributes for correct display with normal size policies, there is too much spacing without this this->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); @@ -39,11 +41,11 @@ void SwiotInfoPage::enableTemperatureReadBtn(bool enable) m_enTempReadCheckBox->setVisible(enable); } -void SwiotInfoPage::initTempCheckBox() { +void SwiotInfoPage::initTempCheckBox() +{ m_enTempReadCheckBox = new QCheckBox("Enable temperature read"); m_enTempReadCheckBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - connect(m_enTempReadCheckBox, &QCheckBox::toggled, - this, &SwiotInfoPage::temperatureReadEnabled); + connect(m_enTempReadCheckBox, &QCheckBox::toggled, this, &SwiotInfoPage::temperatureReadEnabled); m_enTempReadCheckBox->setEnabled(false); m_enTempReadCheckBox->setVisible(true); m_enTempReadCheckBox->setChecked(true); diff --git a/plugins/swiot/src/swiotinfopage.h b/plugins/swiot/src/swiotinfopage.h index f20ebd84f0..9bd2a49b2f 100644 --- a/plugins/swiot/src/swiotinfopage.h +++ b/plugins/swiot/src/swiotinfopage.h @@ -18,20 +18,21 @@ * along with this program. If not, see . */ - #ifndef SCOPY_SWIOTINFOPAGE_H #define SCOPY_SWIOTINFOPAGE_H -#include -#include #include +#include +#include + #include namespace scopy::swiot { -class SwiotInfoPage : public InfoPage { +class SwiotInfoPage : public InfoPage +{ Q_OBJECT public: - explicit SwiotInfoPage(QWidget* parent = nullptr); + explicit SwiotInfoPage(QWidget *parent = nullptr); void enableTemperatureReadBtn(bool enable); Q_SIGNALS: @@ -42,6 +43,6 @@ class SwiotInfoPage : public InfoPage { QCheckBox *m_enTempReadCheckBox; }; -} +} // namespace scopy::swiot -#endif //SCOPY_SWIOTINFOPAGE_H +#endif // SCOPY_SWIOTINFOPAGE_H diff --git a/plugins/swiot/src/swiotpingtask.cpp b/plugins/swiot/src/swiotpingtask.cpp index af49c8c7b9..d59c76e93c 100644 --- a/plugins/swiot/src/swiotpingtask.cpp +++ b/plugins/swiot/src/swiotpingtask.cpp @@ -1,29 +1,37 @@ #include "swiotpingtask.h" -#include + #include "src/swiot_logging_categories.h" + +#include + #include #include using namespace scopy; using namespace scopy::swiot; -SwiotPingTask::SwiotPingTask(iio_context *c ,QObject *parent) : QThread(parent), c(c) {} +SwiotPingTask::SwiotPingTask(iio_context *c, QObject *parent) + : QThread(parent) + , c(c) +{} SwiotPingTask::~SwiotPingTask() {} -void SwiotPingTask::run() { +void SwiotPingTask::run() +{ enabled = true; CommandQueue *commandQueue = CommandQueueProvider::GetInstance()->open(c); - if (!commandQueue || !c) { + if(!commandQueue || !c) { Q_EMIT pingFailed(); return; } auto dev = iio_context_find_device(c, "sw_trig"); - if (dev) { + if(dev) { Command *getTriggerCommand = new IioDeviceGetTrigger(dev, nullptr); - connect(getTriggerCommand, &scopy::Command::finished, this, &SwiotPingTask::getTriggerCommandFinished, Qt::QueuedConnection); + connect(getTriggerCommand, &scopy::Command::finished, this, &SwiotPingTask::getTriggerCommandFinished, + Qt::QueuedConnection); commandQueue->enqueue(getTriggerCommand); } else { CommandQueueProvider::GetInstance()->close(c); @@ -32,13 +40,13 @@ void SwiotPingTask::run() { void SwiotPingTask::getTriggerCommandFinished(scopy::Command *cmd) { - IioDeviceGetTrigger *tcmd = dynamic_cast(cmd); - if (!tcmd) { + IioDeviceGetTrigger *tcmd = dynamic_cast(cmd); + if(!tcmd) { CommandQueueProvider::GetInstance()->close(c); return; } int ret = tcmd->getReturnCode(); - if (ret>= 0 || ret == -ENOENT) { + if(ret >= 0 || ret == -ENOENT) { Q_EMIT pingSuccess(); } else { Q_EMIT pingFailed(); diff --git a/plugins/swiot/src/swiotpingtask.h b/plugins/swiot/src/swiotpingtask.h index 8251aa6a94..57ce920f0d 100644 --- a/plugins/swiot/src/swiotpingtask.h +++ b/plugins/swiot/src/swiotpingtask.h @@ -1,13 +1,17 @@ #ifndef SWIOTPINGTASK_H #define SWIOTPINGTASK_H -#include -#include #include "scopy-swiot_export.h" + +#include + +#include + #include namespace scopy::swiot { -class SwiotPingTask : public QThread { +class SwiotPingTask : public QThread +{ Q_OBJECT public: SwiotPingTask(iio_context *c, QObject *parent = nullptr); @@ -16,6 +20,7 @@ class SwiotPingTask : public QThread { Q_SIGNALS: void pingSuccess(); void pingFailed(); + protected: iio_context *c; bool enabled; @@ -23,5 +28,5 @@ class SwiotPingTask : public QThread { private Q_SLOTS: void getTriggerCommandFinished(scopy::Command *cmd); }; -} +} // namespace scopy::swiot #endif // SWIOTPINGTASK_H diff --git a/plugins/swiot/src/swiotplugin.cpp b/plugins/swiot/src/swiotplugin.cpp index f0638610f4..be44a56d38 100644 --- a/plugins/swiot/src/swiotplugin.cpp +++ b/plugins/swiot/src/swiotplugin.cpp @@ -18,22 +18,23 @@ * along with this program. If not, see . */ - #include "swiotplugin.h" -#include -#include -#include -#include +#include "src/config/swiotconfig.h" #include "src/runtime/faults/faults.h" #include "src/runtime/max14906/max14906.h" -#include "src/config/swiotconfig.h" #include "src/runtime/swiotruntime.h" #include "src/swiot_logging_categories.h" #include "swiotinfopage.h" #include "utils.h" -#include +#include + +#include +#include +#include + +#include using namespace scopy::swiot; @@ -41,7 +42,8 @@ void SWIOTPlugin::preload() { m_displayName = "SWIOT1L"; m_swiotController = new SwiotController(m_param, this); - connect(m_swiotController, &SwiotController::contextSwitched, this, &SWIOTPlugin::onCtxSwitched, Qt::QueuedConnection); + connect(m_swiotController, &SwiotController::contextSwitched, this, &SWIOTPlugin::onCtxSwitched, + Qt::QueuedConnection); connect(m_swiotController, &SwiotController::isRuntimeCtxChanged, this, &SWIOTPlugin::onIsRuntimeCtxChanged); } @@ -54,14 +56,13 @@ bool SWIOTPlugin::loadPage() m_page->layout()->addWidget(m_infoPage); m_page->layout()->addItem(new QSpacerItem(0, 0, QSizePolicy::Preferred, QSizePolicy::Expanding)); - connect(m_swiotController, &SwiotController::readTemperature, this, [=, this] (double temperature) { - if (m_isRuntime) { + connect(m_swiotController, &SwiotController::readTemperature, this, [=, this](double temperature) { + if(m_isRuntime) { m_infoPage->update("Temperature", QString::number(temperature)); } }); - connect(m_infoPage, &SwiotInfoPage::temperatureReadEnabled, - this, [=, this](bool toggled) { - if (toggled) { + connect(m_infoPage, &SwiotInfoPage::temperatureReadEnabled, this, [=, this](bool toggled) { + if(toggled) { m_swiotController->startTemperatureTask(); } else { m_swiotController->stopTemperatureTask(); @@ -70,14 +71,14 @@ bool SWIOTPlugin::loadPage() connect(m_btnTutorial, &QPushButton::clicked, this, &SWIOTPlugin::startTutorial); auto cp = ContextProvider::GetInstance(); - struct iio_context* context = cp->open(m_param); + struct iio_context *context = cp->open(m_param); ssize_t attributeCount = iio_context_get_attrs_count(context); - for (int i = 0; i < attributeCount; ++i) { + for(int i = 0; i < attributeCount; ++i) { const char *name; const char *value; int ret = iio_context_get_attr(context, i, &name, &value); - if (ret < 0) { + if(ret < 0) { qWarning(CAT_SWIOT) << "Could not read attribute with index:" << i; continue; } @@ -93,11 +94,13 @@ bool SWIOTPlugin::loadPage() bool SWIOTPlugin::loadExtraButtons() { - m_btnIdentify = new QPushButton("Identify"); m_extraButtons.append(m_btnIdentify); + m_btnIdentify = new QPushButton("Identify"); + m_extraButtons.append(m_btnIdentify); connect(m_btnIdentify, SIGNAL(clicked()), m_swiotController, SLOT(identify())); // The tutorial button will only be clickable when the user connects to the device - m_btnTutorial = new QPushButton(tr("Tutorial")); m_extraButtons.append(m_btnTutorial); + m_btnTutorial = new QPushButton(tr("Tutorial")); + m_extraButtons.append(m_btnTutorial); m_btnTutorial->setEnabled(false); m_btnTutorial->setToolTip("The tutorial will be available once the device is connected."); @@ -111,17 +114,18 @@ bool SWIOTPlugin::loadIcon() return true; } -void SWIOTPlugin::showPageCallback() { -} +void SWIOTPlugin::showPageCallback() {} -void SWIOTPlugin::hidePageCallback() { -} +void SWIOTPlugin::hidePageCallback() {} void SWIOTPlugin::loadToolList() { - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY(CONFIG_TME_ID, "Config", ":/gui/icons/scopy-default/icons/tool_debugger.svg")); - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY(AD74413R_TME_ID, "AD74413R",":/gui/icons/scopy-default/icons/tool_oscilloscope.svg")); - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY(MAX14906_TME_ID, "MAX14906", ":/gui/icons/scopy-default/icons/tool_io.svg")); + m_toolList.append( + SCOPY_NEW_TOOLMENUENTRY(CONFIG_TME_ID, "Config", ":/gui/icons/scopy-default/icons/tool_debugger.svg")); + m_toolList.append(SCOPY_NEW_TOOLMENUENTRY(AD74413R_TME_ID, "AD74413R", + ":/gui/icons/scopy-default/icons/tool_oscilloscope.svg")); + m_toolList.append( + SCOPY_NEW_TOOLMENUENTRY(MAX14906_TME_ID, "MAX14906", ":/gui/icons/scopy-default/icons/tool_io.svg")); m_toolList.append(SCOPY_NEW_TOOLMENUENTRY(FAULTS_TME_ID, "Faults", ":/swiot/tool_faults.svg")); } @@ -139,15 +143,15 @@ bool SWIOTPlugin::compatible(QString m_param, QString category) bool ret = false; auto &&cp = ContextProvider::GetInstance(); - iio_context* ctx = cp->open(m_param); + iio_context *ctx = cp->open(m_param); if(!ctx) { qWarning(CAT_SWIOT) << "No context available for swiot"; return false; } - iio_device* swiotDevice = iio_context_find_device(ctx, "swiot"); - if (swiotDevice) { + iio_device *swiotDevice = iio_context_find_device(ctx, "swiot"); + if(swiotDevice) { ret = true; } @@ -159,7 +163,7 @@ bool SWIOTPlugin::compatible(QString m_param, QString category) void SWIOTPlugin::setupToolList() { auto &&cp = ContextProvider::GetInstance(); - iio_context* ctx = cp->open(m_param); + iio_context *ctx = cp->open(m_param); m_infoPage->enableTemperatureReadBtn(m_isRuntime); m_swiotController->startTemperatureTask(); @@ -172,12 +176,12 @@ void SWIOTPlugin::setupToolList() for(ToolMenuEntry *tme : qAsConst(m_toolList)) { tme->setEnabled(true); tme->setVisible(true); - if (!m_isRuntime) { - if (tme->id().compare(CONFIG_TME_ID)) { + if(!m_isRuntime) { + if(tme->id().compare(CONFIG_TME_ID)) { tme->setVisible(false); } } else { - if (tme->id().compare(CONFIG_TME_ID)) { + if(tme->id().compare(CONFIG_TME_ID)) { tme->setRunBtnVisible(true); tme->setRunning(false); } else { @@ -186,7 +190,7 @@ void SWIOTPlugin::setupToolList() } } - if (m_isRuntime) { + if(m_isRuntime) { ad74413rTme->setTool(new swiot::Ad74413r(ctx, ad74413rTme)); max14906Tme->setTool(new swiot::Max14906(ctx, max14906Tme)); faultsTme->setTool(new swiot::Faults(ctx, faultsTme)); @@ -194,21 +198,30 @@ void SWIOTPlugin::setupToolList() configTme->setTool(new swiot::SwiotConfig(ctx)); } - connect(dynamic_cast(configTme->tool()), &SwiotConfig::writeModeAttribute, m_swiotController, &SwiotController::writeModeAttribute); - connect(m_swiotController, &SwiotController::modeAttributeChanged, dynamic_cast(configTme->tool()), &SwiotConfig::modeAttributeChanged); - connect(dynamic_cast(configTme->tool()), &SwiotConfig::configBtnPressed, this, &SWIOTPlugin::startCtxSwitch); - connect(dynamic_cast (ad74413rTme->tool()), &Ad74413r::backBtnPressed, m_runtime, &SwiotRuntime::onBackBtnPressed); - connect(dynamic_cast (max14906Tme->tool()), &Max14906::backBtnPressed, m_runtime, &SwiotRuntime::onBackBtnPressed); - connect(dynamic_cast (faultsTme->tool()), &Faults::backBtnPressed, m_runtime, &SwiotRuntime::onBackBtnPressed); - - - connect(m_swiotController, &SwiotController::hasConnectedPowerSupply, dynamic_cast (faultsTme->tool()), &Faults::externalPowerSupply); - connect(m_swiotController, &SwiotController::hasConnectedPowerSupply, dynamic_cast (max14906Tme->tool()), &Max14906::externalPowerSupply); - connect(m_swiotController, &SwiotController::hasConnectedPowerSupply, dynamic_cast (ad74413rTme->tool()), &Ad74413r::externalPowerSupply); - connect(m_swiotController, &SwiotController::hasConnectedPowerSupply, dynamic_cast (configTme->tool()), &SwiotConfig::externalPowerSupply); + connect(dynamic_cast(configTme->tool()), &SwiotConfig::writeModeAttribute, m_swiotController, + &SwiotController::writeModeAttribute); + connect(m_swiotController, &SwiotController::modeAttributeChanged, + dynamic_cast(configTme->tool()), &SwiotConfig::modeAttributeChanged); + connect(dynamic_cast(configTme->tool()), &SwiotConfig::configBtnPressed, this, + &SWIOTPlugin::startCtxSwitch); + connect(dynamic_cast(ad74413rTme->tool()), &Ad74413r::backBtnPressed, m_runtime, + &SwiotRuntime::onBackBtnPressed); + connect(dynamic_cast(max14906Tme->tool()), &Max14906::backBtnPressed, m_runtime, + &SwiotRuntime::onBackBtnPressed); + connect(dynamic_cast(faultsTme->tool()), &Faults::backBtnPressed, m_runtime, + &SwiotRuntime::onBackBtnPressed); + + connect(m_swiotController, &SwiotController::hasConnectedPowerSupply, dynamic_cast(faultsTme->tool()), + &Faults::externalPowerSupply); + connect(m_swiotController, &SwiotController::hasConnectedPowerSupply, + dynamic_cast(max14906Tme->tool()), &Max14906::externalPowerSupply); + connect(m_swiotController, &SwiotController::hasConnectedPowerSupply, + dynamic_cast(ad74413rTme->tool()), &Ad74413r::externalPowerSupply); + connect(m_swiotController, &SwiotController::hasConnectedPowerSupply, + dynamic_cast(configTme->tool()), &SwiotConfig::externalPowerSupply); connect(m_swiotController, &SwiotController::pingFailed, this, &SWIOTPlugin::disconnectDevice); - if (!m_isRuntime) { + if(!m_isRuntime) { requestTool(configTme->id()); } else { requestTool(ad74413rTme->id()); @@ -225,13 +238,15 @@ void SWIOTPlugin::onIsRuntimeCtxChanged(bool isRuntimeCtx) bool SWIOTPlugin::onConnect() { auto &&cp = ContextProvider::GetInstance(); - iio_context* ctx = cp->open(m_param); + iio_context *ctx = cp->open(m_param); m_runtime = new SwiotRuntime(ctx, this); connect(m_runtime, &SwiotRuntime::writeModeAttribute, m_swiotController, &SwiotController::writeModeAttribute); - connect(m_swiotController, &SwiotController::modeAttributeChanged, m_runtime, &SwiotRuntime::modeAttributeChanged); + connect(m_swiotController, &SwiotController::modeAttributeChanged, m_runtime, + &SwiotRuntime::modeAttributeChanged); connect(m_runtime, &SwiotRuntime::backBtnPressed, this, &SWIOTPlugin::startCtxSwitch); - connect(m_swiotController, &SwiotController::isRuntimeCtxChanged, m_runtime, &SwiotRuntime::onIsRuntimeCtxChanged); + connect(m_swiotController, &SwiotController::isRuntimeCtxChanged, m_runtime, + &SwiotRuntime::onIsRuntimeCtxChanged); m_swiotController->connectSwiot(ctx); m_swiotController->startPingTask(); @@ -257,24 +272,37 @@ bool SWIOTPlugin::onDisconnect() tme->setTool(nullptr); } - disconnect(dynamic_cast(configTme->tool()), &SwiotConfig::configBtnPressed, this, &SWIOTPlugin::startCtxSwitch); - disconnect(m_swiotController, &SwiotController::modeAttributeChanged, dynamic_cast(configTme->tool()), &SwiotConfig::modeAttributeChanged); - disconnect(dynamic_cast(configTme->tool()), &SwiotConfig::writeModeAttribute, m_swiotController, &SwiotController::writeModeAttribute); - disconnect(dynamic_cast (ad74413rTme->tool()), &Ad74413r::backBtnPressed, m_runtime, &SwiotRuntime::onBackBtnPressed); - disconnect(dynamic_cast (max14906Tme->tool()), &Max14906::backBtnPressed, m_runtime, &SwiotRuntime::onBackBtnPressed); - disconnect(dynamic_cast (faultsTme->tool()), &Faults::backBtnPressed, m_runtime, &SwiotRuntime::onBackBtnPressed); - - disconnect(m_swiotController, &SwiotController::hasConnectedPowerSupply, dynamic_cast (faultsTme->tool()), &Faults::externalPowerSupply); - disconnect(m_swiotController, &SwiotController::hasConnectedPowerSupply, dynamic_cast (max14906Tme->tool()), &Max14906::externalPowerSupply); - disconnect(m_swiotController, &SwiotController::hasConnectedPowerSupply, dynamic_cast (ad74413rTme->tool()), &Ad74413r::externalPowerSupply); - disconnect(m_swiotController, &SwiotController::hasConnectedPowerSupply, dynamic_cast (configTme->tool()), &SwiotConfig::externalPowerSupply); + disconnect(dynamic_cast(configTme->tool()), &SwiotConfig::configBtnPressed, this, + &SWIOTPlugin::startCtxSwitch); + disconnect(m_swiotController, &SwiotController::modeAttributeChanged, + dynamic_cast(configTme->tool()), &SwiotConfig::modeAttributeChanged); + disconnect(dynamic_cast(configTme->tool()), &SwiotConfig::writeModeAttribute, m_swiotController, + &SwiotController::writeModeAttribute); + disconnect(dynamic_cast(ad74413rTme->tool()), &Ad74413r::backBtnPressed, m_runtime, + &SwiotRuntime::onBackBtnPressed); + disconnect(dynamic_cast(max14906Tme->tool()), &Max14906::backBtnPressed, m_runtime, + &SwiotRuntime::onBackBtnPressed); + disconnect(dynamic_cast(faultsTme->tool()), &Faults::backBtnPressed, m_runtime, + &SwiotRuntime::onBackBtnPressed); + + disconnect(m_swiotController, &SwiotController::hasConnectedPowerSupply, + dynamic_cast(faultsTme->tool()), &Faults::externalPowerSupply); + disconnect(m_swiotController, &SwiotController::hasConnectedPowerSupply, + dynamic_cast(max14906Tme->tool()), &Max14906::externalPowerSupply); + disconnect(m_swiotController, &SwiotController::hasConnectedPowerSupply, + dynamic_cast(ad74413rTme->tool()), &Ad74413r::externalPowerSupply); + disconnect(m_swiotController, &SwiotController::hasConnectedPowerSupply, + dynamic_cast(configTme->tool()), &SwiotConfig::externalPowerSupply); disconnect(m_swiotController, &SwiotController::pingFailed, this, &SWIOTPlugin::disconnectDevice); - disconnect(m_swiotController, &SwiotController::isRuntimeCtxChanged, m_runtime, &SwiotRuntime::onIsRuntimeCtxChanged); + disconnect(m_swiotController, &SwiotController::isRuntimeCtxChanged, m_runtime, + &SwiotRuntime::onIsRuntimeCtxChanged); disconnect(m_runtime, &SwiotRuntime::backBtnPressed, this, &SWIOTPlugin::startCtxSwitch); - disconnect(m_swiotController, &SwiotController::modeAttributeChanged, m_runtime, &SwiotRuntime::modeAttributeChanged); - disconnect(m_runtime, &SwiotRuntime::writeModeAttribute, m_swiotController, &SwiotController::writeModeAttribute); + disconnect(m_swiotController, &SwiotController::modeAttributeChanged, m_runtime, + &SwiotRuntime::modeAttributeChanged); + disconnect(m_runtime, &SwiotRuntime::writeModeAttribute, m_swiotController, + &SwiotController::writeModeAttribute); m_swiotController->stopPingTask(); m_swiotController->stopPowerSupplyTask(); @@ -283,7 +311,7 @@ bool SWIOTPlugin::onDisconnect() m_btnTutorial->setEnabled(false); - if (m_runtime) { + if(m_runtime) { delete m_runtime; m_runtime = nullptr; } @@ -297,9 +325,9 @@ void SWIOTPlugin::startCtxSwitch() { m_swiotController->stopPingTask(); m_swiotController->stopPowerSupplyTask(); -// if (m_isRuntime) { -// m_swiotController->stopTemperatureTask(); -// } + // if (m_isRuntime) { + // m_swiotController->stopTemperatureTask(); + // } m_swiotController->disconnectSwiot(); Q_EMIT disconnectDevice(); @@ -312,24 +340,28 @@ void SWIOTPlugin::onCtxSwitched() Q_EMIT connectDevice(); } -void SWIOTPlugin::startTutorial() { - if (m_isRuntime) { +void SWIOTPlugin::startTutorial() +{ + if(m_isRuntime) { qInfo(CAT_SWIOT) << "Starting SWIOT runtime tutorial."; // The tutorial builder is responsible for deleting itself after the tutorial is finished, so creating // a new one each time the tutorial is started will not create memory leaks. - ToolMenuEntry* ad74413rTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, AD74413R_TME_ID); - ToolMenuEntry* max14906Tme = ToolMenuEntry::findToolMenuEntryById(m_toolList, MAX14906_TME_ID); - ToolMenuEntry* faultsTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, FAULTS_TME_ID); - - QWidget* ad74413rTool = ad74413rTme->tool(); - QWidget* max14906Tool = max14906Tme->tool(); - QWidget* faultsTool = faultsTme->tool(); - QWidget* parent = Util::findContainingWindow(ad74413rTool); - - m_ad74413rTutorial = new gui::TutorialBuilder(ad74413rTool, ":/swiot/tutorial_chapters.json", "ad74413r", parent); - m_max14906Tutorial = new gui::TutorialBuilder(max14906Tool, ":/swiot/tutorial_chapters.json", "max14906", parent); - m_faultsTutorial = new gui::TutorialBuilder(faultsTool, ":/swiot/tutorial_chapters.json", "faults", parent); + ToolMenuEntry *ad74413rTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, AD74413R_TME_ID); + ToolMenuEntry *max14906Tme = ToolMenuEntry::findToolMenuEntryById(m_toolList, MAX14906_TME_ID); + ToolMenuEntry *faultsTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, FAULTS_TME_ID); + + QWidget *ad74413rTool = ad74413rTme->tool(); + QWidget *max14906Tool = max14906Tme->tool(); + QWidget *faultsTool = faultsTme->tool(); + QWidget *parent = Util::findContainingWindow(ad74413rTool); + + m_ad74413rTutorial = + new gui::TutorialBuilder(ad74413rTool, ":/swiot/tutorial_chapters.json", "ad74413r", parent); + m_max14906Tutorial = + new gui::TutorialBuilder(max14906Tool, ":/swiot/tutorial_chapters.json", "max14906", parent); + m_faultsTutorial = + new gui::TutorialBuilder(faultsTool, ":/swiot/tutorial_chapters.json", "faults", parent); connect(m_ad74413rTutorial, &gui::TutorialBuilder::finished, this, &SWIOTPlugin::startMax14906Tutorial); connect(m_max14906Tutorial, &gui::TutorialBuilder::finished, this, &SWIOTPlugin::startFaultsTutorial); @@ -350,45 +382,45 @@ void SWIOTPlugin::startTutorial() { } } -void SWIOTPlugin::startAd74413rTutorial() { +void SWIOTPlugin::startAd74413rTutorial() +{ qInfo(CAT_SWIOT) << "Starting ad74413r tutorial."; - ToolMenuEntry* ad74413rTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, AD74413R_TME_ID); + ToolMenuEntry *ad74413rTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, AD74413R_TME_ID); this->requestTool(ad74413rTme->id()); m_ad74413rTutorial->setTitle("AD74413R"); m_ad74413rTutorial->start(); } -void SWIOTPlugin::startMax14906Tutorial() { +void SWIOTPlugin::startMax14906Tutorial() +{ qInfo(CAT_SWIOT) << "Starting max14906 tutorial."; - ToolMenuEntry* max14906Tme = ToolMenuEntry::findToolMenuEntryById(m_toolList, MAX14906_TME_ID); + ToolMenuEntry *max14906Tme = ToolMenuEntry::findToolMenuEntryById(m_toolList, MAX14906_TME_ID); this->requestTool(max14906Tme->id()); m_max14906Tutorial->setTitle("MAX14906"); m_max14906Tutorial->start(); } -void SWIOTPlugin::startFaultsTutorial() { +void SWIOTPlugin::startFaultsTutorial() +{ qInfo(CAT_SWIOT) << "Starting faults tutorial."; - ToolMenuEntry* faultsTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, FAULTS_TME_ID); + ToolMenuEntry *faultsTme = ToolMenuEntry::findToolMenuEntryById(m_toolList, FAULTS_TME_ID); this->requestTool(faultsTme->id()); m_faultsTutorial->setTitle("FAULTS"); m_faultsTutorial->start(); } -void SWIOTPlugin::abortTutorial() { +void SWIOTPlugin::abortTutorial() +{ disconnect(m_ad74413rTutorial, &gui::TutorialBuilder::finished, this, &SWIOTPlugin::startMax14906Tutorial); disconnect(m_max14906Tutorial, &gui::TutorialBuilder::finished, this, &SWIOTPlugin::startFaultsTutorial); } - -QString SWIOTPlugin::description() -{ - return "Adds functionality specific to SWIOT1L board"; -} +QString SWIOTPlugin::description() { return "Adds functionality specific to SWIOT1L board"; } void SWIOTPlugin::initMetadata() { loadMetadata( - R"plugin( + R"plugin( { "priority":100, "category":[ diff --git a/plugins/swiot/src/swiotreadtemperaturetask.cpp b/plugins/swiot/src/swiotreadtemperaturetask.cpp index 562be54119..becef41164 100644 --- a/plugins/swiot/src/swiotreadtemperaturetask.cpp +++ b/plugins/swiot/src/swiotreadtemperaturetask.cpp @@ -18,13 +18,13 @@ * along with this program. If not, see . */ - #include "swiotreadtemperaturetask.h" + +#include "src/swiot_logging_categories.h" + #include #include #include -#include "src/swiot_logging_categories.h" - #include #define DEVICE_NAME "adt75" @@ -32,102 +32,100 @@ using namespace scopy::swiot; - -SwiotReadTemperatureTask::SwiotReadTemperatureTask(QString uri, QObject* parent) : - QThread(parent), - m_uri(std::move(uri)), - m_context(nullptr), - m_channel(nullptr), - m_device(nullptr), - m_commandQueue(nullptr), - m_raw(0.0), - m_scale(0.0), - m_offset(0.0) +SwiotReadTemperatureTask::SwiotReadTemperatureTask(QString uri, QObject *parent) + : QThread(parent) + , m_uri(std::move(uri)) + , m_context(nullptr) + , m_channel(nullptr) + , m_device(nullptr) + , m_commandQueue(nullptr) + , m_raw(0.0) + , m_scale(0.0) + , m_offset(0.0) { m_context = ContextProvider::GetInstance()->open(m_uri); - if (!m_context) { + if(!m_context) { qDebug(CAT_SWIOT) << "Error, empty context received by temperature task."; return; } m_device = iio_context_find_device(m_context, DEVICE_NAME); - if (!m_device) { - qDebug(CAT_SWIOT) << "Error, could not find" << DEVICE_NAME << - "from the given context. Temperature not available."; + if(!m_device) { + qDebug(CAT_SWIOT) << "Error, could not find" << DEVICE_NAME + << "from the given context. Temperature not available."; ContextProvider::GetInstance()->close(m_uri); return; } - if (isInterruptionRequested()) { + if(isInterruptionRequested()) { return; } m_commandQueue = CommandQueueProvider::GetInstance()->open(m_context); - if (!m_commandQueue) { + if(!m_commandQueue) { ContextProvider::GetInstance()->close(m_uri); return; } m_channel = iio_device_find_channel(m_device, CHANNEL_NAME, false); - if (!m_channel) { - qDebug(CAT_SWIOT) << "Error, could not find channel " << CHANNEL_NAME << - "from device" << DEVICE_NAME << ". Temperature not available."; + if(!m_channel) { + qDebug(CAT_SWIOT) << "Error, could not find channel " << CHANNEL_NAME << "from device" << DEVICE_NAME + << ". Temperature not available."; ContextProvider::GetInstance()->close(m_uri); return; } Command *attrReadScale = new IioChannelAttributeRead(m_channel, "scale", nullptr, true); Command *attrReadOffset = new IioChannelAttributeRead(m_channel, "offset", nullptr, true); - connect(attrReadScale, &scopy::Command::finished, this, - &SwiotReadTemperatureTask::readScaleCommandFinished, Qt::QueuedConnection); - connect(attrReadOffset, &scopy::Command::finished, this, - &SwiotReadTemperatureTask::readOffsetCommandFinished, Qt::QueuedConnection); + connect(attrReadScale, &scopy::Command::finished, this, &SwiotReadTemperatureTask::readScaleCommandFinished, + Qt::QueuedConnection); + connect(attrReadOffset, &scopy::Command::finished, this, &SwiotReadTemperatureTask::readOffsetCommandFinished, + Qt::QueuedConnection); m_commandQueue->enqueue(attrReadScale); m_commandQueue->enqueue(attrReadOffset); } -SwiotReadTemperatureTask::~SwiotReadTemperatureTask() -{ - m_commandQueue = nullptr; -} +SwiotReadTemperatureTask::~SwiotReadTemperatureTask() { m_commandQueue = nullptr; } -void SwiotReadTemperatureTask::run() { - if (isInterruptionRequested()) { +void SwiotReadTemperatureTask::run() +{ + if(isInterruptionRequested()) { return; } Command *attrReadRaw = new IioChannelAttributeRead(m_channel, "raw", nullptr); - connect(attrReadRaw, &scopy::Command::finished, this, - &SwiotReadTemperatureTask::readRawCommandFinished, Qt::QueuedConnection); + connect(attrReadRaw, &scopy::Command::finished, this, &SwiotReadTemperatureTask::readRawCommandFinished, + Qt::QueuedConnection); m_commandQueue->enqueue(attrReadRaw); } void SwiotReadTemperatureTask::readRawCommandFinished(Command *cmd) { - if (isInterruptionRequested()) { + if(isInterruptionRequested()) { ContextProvider::GetInstance()->close(m_uri); return; } - IioChannelAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { + IioChannelAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { CommandQueueProvider::GetInstance()->close(m_context); ContextProvider::GetInstance()->close(m_uri); return; } - if (tcmd->getReturnCode() >= 0) { + if(tcmd->getReturnCode() >= 0) { char *res = tcmd->getResult(); bool ok = false; double raw = QString(res).toDouble(&ok); - if (ok) { + if(ok) { m_raw = raw; double temperature = (m_raw + m_offset) * m_scale / 1000; qDebug(CAT_SWIOT) << "Read temperature value of" << temperature; Q_EMIT newTemperature(temperature); } } else { - qDebug(CAT_SWIOT) << "Error, could not read \"raw\" attribute from " << DEVICE_NAME << ". Temperature not available."; + qDebug(CAT_SWIOT) << "Error, could not read \"raw\" attribute from " << DEVICE_NAME + << ". Temperature not available."; CommandQueueProvider::GetInstance()->close(m_context); ContextProvider::GetInstance()->close(m_uri); } @@ -135,21 +133,22 @@ void SwiotReadTemperatureTask::readRawCommandFinished(Command *cmd) void SwiotReadTemperatureTask::readScaleCommandFinished(Command *cmd) { - IioChannelAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { + IioChannelAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { CommandQueueProvider::GetInstance()->close(m_context); ContextProvider::GetInstance()->close(m_uri); return; } - if (tcmd->getReturnCode() >= 0) { + if(tcmd->getReturnCode() >= 0) { char *res = tcmd->getResult(); bool ok = false; double scale = QString(res).toDouble(&ok); - if (ok) { + if(ok) { m_scale = scale; } } else { - qDebug(CAT_SWIOT) << "Error, could not read \"scale\" attribute from " << DEVICE_NAME << ". Temperature not available."; + qDebug(CAT_SWIOT) << "Error, could not read \"scale\" attribute from " << DEVICE_NAME + << ". Temperature not available."; CommandQueueProvider::GetInstance()->close(m_context); ContextProvider::GetInstance()->close(m_uri); } @@ -157,26 +156,25 @@ void SwiotReadTemperatureTask::readScaleCommandFinished(Command *cmd) void SwiotReadTemperatureTask::readOffsetCommandFinished(Command *cmd) { - IioChannelAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { + IioChannelAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { CommandQueueProvider::GetInstance()->close(m_context); ContextProvider::GetInstance()->close(m_uri); return; } - if (tcmd->getReturnCode() >= 0) { + if(tcmd->getReturnCode() >= 0) { char *res = tcmd->getResult(); bool ok = false; double offset = QString(res).toDouble(&ok); - if (ok) { + if(ok) { m_offset = offset; } } else { - qDebug(CAT_SWIOT) << "Error, could not read \"offset\" attribute from " << DEVICE_NAME << ". Temperature not available."; + qDebug(CAT_SWIOT) << "Error, could not read \"offset\" attribute from " << DEVICE_NAME + << ". Temperature not available."; } CommandQueueProvider::GetInstance()->close(m_context); ContextProvider::GetInstance()->close(m_uri); } - - #include "moc_swiotreadtemperaturetask.cpp" diff --git a/plugins/swiot/src/swiotreadtemperaturetask.h b/plugins/swiot/src/swiotreadtemperaturetask.h index e658d5435b..7cb44701e2 100644 --- a/plugins/swiot/src/swiotreadtemperaturetask.h +++ b/plugins/swiot/src/swiotreadtemperaturetask.h @@ -18,20 +18,22 @@ * along with this program. If not, see . */ - #ifndef SCOPY_SWIOTREADTEMPERATURETASK_H #define SCOPY_SWIOTREADTEMPERATURETASK_H -#include #include + +#include + #include #include namespace scopy::swiot { -class SwiotReadTemperatureTask : public QThread { +class SwiotReadTemperatureTask : public QThread +{ Q_OBJECT public: - explicit SwiotReadTemperatureTask(QString uri, QObject* parent = nullptr); + explicit SwiotReadTemperatureTask(QString uri, QObject *parent = nullptr); ~SwiotReadTemperatureTask(); void run() override; @@ -50,8 +52,7 @@ private Q_SLOTS: struct iio_device *m_device; CommandQueue *m_commandQueue; double m_raw, m_scale, m_offset; - }; -} // scopy::swiot +} // namespace scopy::swiot -#endif //SCOPY_SWIOTREADTEMPERATURETASK_H +#endif // SCOPY_SWIOTREADTEMPERATURETASK_H diff --git a/plugins/swiot/src/swiotswitchctxtask.cpp b/plugins/swiot/src/swiotswitchctxtask.cpp index 06a02db85a..03599530e1 100644 --- a/plugins/swiot/src/swiotswitchctxtask.cpp +++ b/plugins/swiot/src/swiotswitchctxtask.cpp @@ -18,12 +18,13 @@ * along with this program. If not, see . */ - #include "swiotswitchctxtask.h" -#include + +#include "src/swiot_logging_categories.h" + #include +#include #include -#include "src/swiot_logging_categories.h" using namespace scopy::swiot; @@ -36,42 +37,45 @@ SwiotSwitchCtxTask::SwiotSwitchCtxTask(QString uri, bool wasRuntime) void SwiotSwitchCtxTask::run() { iio_context *ctx = ContextProvider::GetInstance()->open(m_uri); - if (!ctx) { + if(!ctx) { return; } - if (isInterruptionRequested()) { + if(isInterruptionRequested()) { ContextProvider::GetInstance()->close(m_uri); return; } CommandQueue *commandQueue = CommandQueueProvider::GetInstance()->open(ctx); - if (!commandQueue) { + if(!commandQueue) { ContextProvider::GetInstance()->close(m_uri); return; } iio_device *swiotDevice = iio_context_find_device(ctx, "swiot"); - if (swiotDevice) { + if(swiotDevice) { IioDeviceAttributeRead *iioAttrRead = new IioDeviceAttributeRead(swiotDevice, "mode", nullptr, true); - connect(iioAttrRead, &scopy::Command::finished, this, [=, this] (scopy::Command *cmd) { - IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); - if (!tcmd) { + connect( + iioAttrRead, &scopy::Command::finished, this, + [=, this](scopy::Command *cmd) { + IioDeviceAttributeRead *tcmd = dynamic_cast(cmd); + if(!tcmd) { + CommandQueueProvider::GetInstance()->close(ctx); + ContextProvider::GetInstance()->close(m_uri); + return; + } + char *readMode = tcmd->getResult(); + if(tcmd->getReturnCode() >= 0) { + if((m_wasRuntime && (strcmp(readMode, "config") == 0)) || + (!m_wasRuntime && (strcmp(readMode, "runtime") == 0))) { + qDebug(CAT_SWIOT) << "Context has been changed"; + Q_EMIT contextSwitched(); + } + } CommandQueueProvider::GetInstance()->close(ctx); ContextProvider::GetInstance()->close(m_uri); - return; - } - char *readMode = tcmd->getResult(); - if (tcmd->getReturnCode() >= 0) { - if ((m_wasRuntime && (strcmp(readMode, "config") == 0)) || - (!m_wasRuntime && (strcmp(readMode, "runtime") == 0))) { - qDebug(CAT_SWIOT)<<"Context has been changed"; - Q_EMIT contextSwitched(); - } - } - CommandQueueProvider::GetInstance()->close(ctx); - ContextProvider::GetInstance()->close(m_uri); - }, Qt::QueuedConnection); + }, + Qt::QueuedConnection); commandQueue->enqueue(iioAttrRead); } else { @@ -79,4 +83,3 @@ void SwiotSwitchCtxTask::run() ContextProvider::GetInstance()->close(m_uri); } } - diff --git a/plugins/swiot/src/swiotswitchctxtask.h b/plugins/swiot/src/swiotswitchctxtask.h index 1dec167ffc..2885cc7a9a 100644 --- a/plugins/swiot/src/swiotswitchctxtask.h +++ b/plugins/swiot/src/swiotswitchctxtask.h @@ -18,12 +18,11 @@ * along with this program. If not, see . */ - #ifndef SWIOTSWITCHCTXTASK_H #define SWIOTSWITCHCTXTASK_H -#include #include +#include namespace scopy::swiot { class SwiotSwitchCtxTask : public QThread @@ -35,11 +34,11 @@ class SwiotSwitchCtxTask : public QThread Q_SIGNALS: void contextSwitched(); + private: QString m_uri; bool m_wasRuntime; }; -} - +} // namespace scopy::swiot #endif // SWIOTSWITCHCTXTASK_H diff --git a/plugins/swiot/test/CMakeLists.txt b/plugins/swiot/test/CMakeLists.txt index 10061d9e18..3f9d9508a3 100644 --- a/plugins/swiot/test/CMakeLists.txt +++ b/plugins/swiot/test/CMakeLists.txt @@ -1,8 +1,6 @@ cmake_minimum_required(VERSION 3.5) -#set(CMAKE_FIND_DEBUG_MODE ON) +# set(CMAKE_FIND_DEBUG_MODE ON) include(ScopyTest) -SETUP_SCOPY_TESTS( - pluginloader -) +setup_scopy_tests(pluginloader) diff --git a/plugins/swiot/test/tst_pluginloader.cpp b/plugins/swiot/test/tst_pluginloader.cpp index 15116e5530..2e46138a09 100644 --- a/plugins/swiot/test/tst_pluginloader.cpp +++ b/plugins/swiot/test/tst_pluginloader.cpp @@ -18,10 +18,11 @@ * along with this program. If not, see . */ - #include "qpluginloader.h" -#include + #include +#include + #include using namespace scopy; @@ -45,7 +46,6 @@ private Q_SLOTS: #define PLUGIN_LOCATION "../../plugins" #define FILENAME PLUGIN_LOCATION "/libscopy-swiot.so" - void TST_SWIOTPlugin::fileExists() { QFile f(FILENAME); @@ -56,53 +56,48 @@ void TST_SWIOTPlugin::fileExists() QVERIFY(ret); } -void TST_SWIOTPlugin::isLibrary() -{ - QVERIFY(QLibrary::isLibrary(FILENAME)); -} +void TST_SWIOTPlugin::isLibrary() { QVERIFY(QLibrary::isLibrary(FILENAME)); } void TST_SWIOTPlugin::className() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); QVERIFY(qp.metaData().value("className") == "SWIOTPlugin"); } void TST_SWIOTPlugin::loaded() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); qp.load(); QVERIFY(qp.isLoaded()); } void TST_SWIOTPlugin::instanceNotNull() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); QVERIFY(qp.instance() != nullptr); } void TST_SWIOTPlugin::multipleInstances() { - QPluginLoader qp1(FILENAME,this); - QPluginLoader qp2(FILENAME,this); + QPluginLoader qp1(FILENAME, this); + QPluginLoader qp2(FILENAME, this); QVERIFY(qp1.instance() == qp2.instance()); } - void TST_SWIOTPlugin::qobjectcast_to_plugin() { - QPluginLoader qp(FILENAME,this); - auto instance = qobject_cast(qp.instance()); - QVERIFY(instance != nullptr ); + QPluginLoader qp(FILENAME, this); + auto instance = qobject_cast(qp.instance()); + QVERIFY(instance != nullptr); } - void TST_SWIOTPlugin::clone() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(); QVERIFY(p1 != nullptr); p2 = original->clone(); @@ -110,28 +105,28 @@ void TST_SWIOTPlugin::clone() QVERIFY(p1 != p2); } -void TST_SWIOTPlugin::name() { - QPluginLoader qp(FILENAME,this); +void TST_SWIOTPlugin::name() +{ + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(); - qDebug()<name(); + qDebug() << p1->name(); } void TST_SWIOTPlugin::metadata() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); original->initMetadata(); p1 = original->clone(); - qDebug()<metadata(); + qDebug() << p1->metadata(); QVERIFY(!p1->metadata().isEmpty()); } - QTEST_MAIN(TST_SWIOTPlugin) #include "tst_pluginloader.moc" diff --git a/plugins/swiot/test/tst_swiot.cpp b/plugins/swiot/test/tst_swiot.cpp index 4e13281457..e5af22e682 100644 --- a/plugins/swiot/test/tst_swiot.cpp +++ b/plugins/swiot/test/tst_swiot.cpp @@ -18,7 +18,6 @@ * along with this program. If not, see . */ - #include class ScopyMainWindowTest : public QObject @@ -28,7 +27,7 @@ private Q_SLOTS: void hello(); }; -void ScopyMainWindowTest::hello() { +void ScopyMainWindowTest::hello(){ }; diff --git a/plugins/testplugin/CMakeLists.txt b/plugins/testplugin/CMakeLists.txt index c8f7da45fb..dfc45b9575 100644 --- a/plugins/testplugin/CMakeLists.txt +++ b/plugins/testplugin/CMakeLists.txt @@ -8,8 +8,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -26,56 +25,43 @@ set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) set(SCOPY_QT_COMPONENTS Widgets Core) -FILE(GLOB SRC_LIST src/*.cpp src/*.cc) -FILE(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) -FILE(GLOB UI_LIST ui/*.ui) +file(GLOB SRC_LIST src/*.cpp src/*.cc) +file(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) +file(GLOB UI_LIST ui/*.ui) set(ENABLE_TESTING ON) if(ENABLE_TESTING) - add_subdirectory(test) + add_subdirectory(test) endif() -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} -) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS ${SCOPY_QT_COMPONENTS} REQUIRED) if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") - set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY - "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") else() - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) endif() qt_add_resources(PROJECT_RESOURCES res/resources.qrc) -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} - ${PROJECT_RESOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES} ${PROJECT_RESOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) -target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE} -scopy-gui -) +target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE} scopy-gui) target_include_directories(${PROJECT_NAME} PUBLIC scopy-pluginbase scopy-gui) foreach(comp ${SCOPY_QT_COMPONENTS}) - set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) + set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) endforeach() - -target_link_libraries(${PROJECT_NAME} PUBLIC - ${SCOPY_QT_LIBRARIES} - scopy-pluginbase - scopy-gui) - +target_link_libraries(${PROJECT_NAME} PUBLIC ${SCOPY_QT_LIBRARIES} scopy-pluginbase scopy-gui) set(PLUGIN_NAME ${PROJECT_NAME} PARENT_SCOPE) diff --git a/plugins/testplugin/include/testplugin/testplugin.h b/plugins/testplugin/include/testplugin/testplugin.h index 90a00e2428..8b834fc936 100644 --- a/plugins/testplugin/include/testplugin/testplugin.h +++ b/plugins/testplugin/include/testplugin/testplugin.h @@ -3,14 +3,16 @@ #define SCOPY_PLUGIN_NAME TestPlugin -#include -#include -#include #include "scopy-testplugin_export.h" -#include + #include +#include +#include #include +#include +#include + namespace scopy { class SCOPY_TESTPLUGIN_EXPORT TestPlugin : public QObject, public PluginBase @@ -34,7 +36,7 @@ class SCOPY_TESTPLUGIN_EXPORT TestPlugin : public QObject, public PluginBase QString version() override; bool onConnect() override; bool onDisconnect() override; - void cloneExtra(Plugin*) override; + void cloneExtra(Plugin *) override; void saveSettings(QSettings &) override; void loadSettings(QSettings &) override; @@ -47,11 +49,10 @@ public Q_SLOTS: QWidget *tool2; QLineEdit *edit; int renameCnt; - ApiObject* m_pluginApi; + ApiObject *m_pluginApi; void startTutorial(); void initHoverWidgetTests(); - QLabel *lbl; QLabel *pic; QLabel *lbl2; @@ -61,21 +62,25 @@ public Q_SLOTS: QPushButton *btn4; }; -class SCOPY_TESTPLUGIN_EXPORT TestPlugin_API : public ApiObject { +class SCOPY_TESTPLUGIN_EXPORT TestPlugin_API : public ApiObject +{ Q_OBJECT public: - explicit TestPlugin_API(TestPlugin *p) : ApiObject(p),p(p) {} + explicit TestPlugin_API(TestPlugin *p) + : ApiObject(p) + , p(p) + {} ~TestPlugin_API() {} - TestPlugin* p; + TestPlugin *p; Q_PROPERTY(QString testText READ testText WRITE setTestText); QString testText() const; void setTestText(const QString &newTestText); + private: QString m_testText; }; -} - +} // namespace scopy #endif // TESTPLUGIN_H diff --git a/plugins/testplugin/src/testplugin.cpp b/plugins/testplugin/src/testplugin.cpp index 793094dba2..69e5b6296d 100644 --- a/plugins/testplugin/src/testplugin.cpp +++ b/plugins/testplugin/src/testplugin.cpp @@ -1,40 +1,44 @@ #include "testplugin.h" + +#include "testtool.h" +#include "tutorialoverlay.h" + #include +#include +#include +#include #include #include -#include #include -#include -#include -#include -#include -#include -#include #include -#include +#include +#include + #include -#include "tutorialoverlay.h" #include #include +#include +#include +#include #include #include -#include "testtool.h" -Q_LOGGING_CATEGORY(CAT_TESTPLUGIN,"TestPlugin"); +Q_LOGGING_CATEGORY(CAT_TESTPLUGIN, "TestPlugin"); using namespace scopy; -bool TestPlugin::compatible(QString m_param, QString category) { - qDebug(CAT_TESTPLUGIN)<<"compatible"; +bool TestPlugin::compatible(QString m_param, QString category) +{ + qDebug(CAT_TESTPLUGIN) << "compatible"; return true; } void TestPlugin::initPreferences() { Preferences *p = Preferences::GetInstance(); - p->init("pref1",false); - p->init("pref2",true); - p->init("prefstr","this is a string"); - p->init("pref4","english"); + p->init("pref1", false); + p->init("pref2", true); + p->init("prefstr", "this is a string"); + p->init("pref4", "english"); } bool TestPlugin::loadPreferencesPage() @@ -46,18 +50,23 @@ bool TestPlugin::loadPreferencesPage() QVBoxLayout *lay = new QVBoxLayout(m_preferencesPage); MenuSectionWidget *generalWidget = new MenuSectionWidget(m_preferencesPage); - MenuCollapseSection *generalSection = new MenuCollapseSection("General",MenuCollapseSection::MHCW_NONE, generalWidget); + MenuCollapseSection *generalSection = + new MenuCollapseSection("General", MenuCollapseSection::MHCW_NONE, generalWidget); generalWidget->contentLayout()->setSpacing(10); generalWidget->contentLayout()->addWidget(generalSection); generalSection->contentLayout()->setSpacing(10); lay->setMargin(0); lay->addWidget(generalWidget); - lay->addSpacerItem(new QSpacerItem(0,0,QSizePolicy::Minimum,QSizePolicy::Expanding)); + lay->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); - generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"pref1","First Option",generalSection)); - generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCheckBox(p,"pref2","Second Option",generalSection)); - generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceEdit(p,"prefstr","PreferenceString",generalSection)); - generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCombo(p,"pref4","languages",{"english","french","italian"},generalSection)); + generalSection->contentLayout()->addWidget( + PreferencesHelper::addPreferenceCheckBox(p, "pref1", "First Option", generalSection)); + generalSection->contentLayout()->addWidget( + PreferencesHelper::addPreferenceCheckBox(p, "pref2", "Second Option", generalSection)); + generalSection->contentLayout()->addWidget( + PreferencesHelper::addPreferenceEdit(p, "prefstr", "PreferenceString", generalSection)); + generalSection->contentLayout()->addWidget(PreferencesHelper::addPreferenceCombo( + p, "pref4", "languages", {"english", "french", "italian"}, generalSection)); return true; } @@ -72,37 +81,39 @@ bool TestPlugin::loadPage() { m_page = new QWidget(); QVBoxLayout *lay = new QVBoxLayout(m_page); - lay->addWidget(new QLabel("TestPage",m_page)); - QPushButton* restartBtn = new QPushButton("restartPlugin",m_page); + lay->addWidget(new QLabel("TestPage", m_page)); + QPushButton *restartBtn = new QPushButton("restartPlugin", m_page); lay->addWidget(restartBtn); - connect(restartBtn,SIGNAL(clicked()),this,SIGNAL(restartDevice())); + connect(restartBtn, SIGNAL(clicked()), this, SIGNAL(restartDevice())); return true; - } void TestPlugin::loadToolList() { renameCnt = 0; - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("test1first","FirstPlugin",":/gui/icons/scopy-default/icons/tool_home.svg")); - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("test1second","Second Plugin",":/gui/icons/scopy-default/icons/tool_io.svg")); + m_toolList.append( + SCOPY_NEW_TOOLMENUENTRY("test1first", "FirstPlugin", ":/gui/icons/scopy-default/icons/tool_home.svg")); + m_toolList.append( + SCOPY_NEW_TOOLMENUENTRY("test1second", "Second Plugin", ":/gui/icons/scopy-default/icons/tool_io.svg")); } bool TestPlugin::loadExtraButtons() { m_extraButtons.append(new QPushButton("Calibrate")); m_extraButtons.append(new QPushButton("Register")); - connect(m_extraButtons[0],&QAbstractButton::clicked,this,[=](){edit->setText("Calibrating");}); - connect(m_extraButtons[1],&QAbstractButton::clicked,this,[=](){edit->setText("Registering");}); + connect(m_extraButtons[0], &QAbstractButton::clicked, this, [=]() { edit->setText("Calibrating"); }); + connect(m_extraButtons[1], &QAbstractButton::clicked, this, [=]() { edit->setText("Registering"); }); return true; } -void TestPlugin::startTutorial() { +void TestPlugin::startTutorial() +{ QWidget *window = Util::findContainingWindow(m_toolList[0]->tool()); gui::TutorialOverlay *tut = new gui::TutorialOverlay(window); - tut->addChapter({btn,lbl}, -R"story( + tut->addChapter({btn, lbl}, + R"story( # First Button Two highlights with default **description** location. @@ -112,7 +123,7 @@ Two highlights with default **description** location. One button, but tutorial *moved* )story"); -tut->addChapter(pic, R"story( + tut->addChapter(pic, R"story( # Picture Text overlayed on picture @@ -120,20 +131,19 @@ Text overlayed on picture You can even put a picture on top ![ADALM2000 pic!](:/gui/icons/adalm.svg "svgg") )story"); -tut->addChapter(lbl, R"story( + tut->addChapter(lbl, R"story( # Cristi's Label This label is cool )story"); -tut->addChapter(nullptr,R"story( + tut->addChapter(nullptr, R"story( # Link For more info, visit [wiki](https://wiki.analog.com/) ![ADI](:/gui/icons/scopy-default/icons/logo.svg "ADI") )story"); - tut->setTitle("Welcome to TestPlugin ! "); tut->start(); } @@ -141,8 +151,8 @@ For more info, visit [wiki](https://wiki.analog.com/) bool TestPlugin::onConnect() { MessageBroker::GetInstance()->subscribe(this, "TestPlugin"); - qDebug(CAT_TESTPLUGIN)<<"connect"; - qDebug(CAT_TESTPLUGIN)<id()<name(); + qDebug(CAT_TESTPLUGIN) << "connect"; + qDebug(CAT_TESTPLUGIN) << m_toolList[0]->id() << m_toolList[0]->name(); m_toolList[0]->setEnabled(true); m_toolList[0]->setName("TestPlugin"); @@ -156,22 +166,23 @@ bool TestPlugin::onConnect() lay->addLayout(hlay); lbl = new QLabel("TestPlugin", tool); - lbl->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Maximum); + lbl->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); hlay->addWidget(lbl); - hlay->addSpacerItem(new QSpacerItem(0,0,QSizePolicy::Expanding,QSizePolicy::Fixed)); + hlay->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed)); - pic = new QLabel("Picture",tool); - lbl2 = new QLabel("m_initText->"+m_initText,tool); + pic = new QLabel("Picture", tool); + lbl2 = new QLabel("m_initText->" + m_initText, tool); - btn = new QPushButton("detach",tool); - btn2 = new QPushButton("renameTool",tool); - btn3 = new QPushButton("tutorial",tool); - btn4 = new QPushButton("show hoverwidget",tool); + btn = new QPushButton("detach", tool); + btn2 = new QPushButton("renameTool", tool); + btn3 = new QPushButton("tutorial", tool); + btn4 = new QPushButton("show hoverwidget", tool); btn4->setCheckable(true); - connect(btn,&QPushButton::clicked,this,[=](){m_toolList[0]->setAttached(!m_toolList[0]->attached());}); - connect(btn2,&QPushButton::clicked,this,[=](){m_toolList[0]->setName("TestPlugin"+QString::number(renameCnt++));}); - connect(btn3,&QPushButton::clicked,this,[=](){startTutorial();}); + connect(btn, &QPushButton::clicked, this, [=]() { m_toolList[0]->setAttached(!m_toolList[0]->attached()); }); + connect(btn2, &QPushButton::clicked, this, + [=]() { m_toolList[0]->setName("TestPlugin" + QString::number(renameCnt++)); }); + connect(btn3, &QPushButton::clicked, this, [=]() { startTutorial(); }); edit = new QLineEdit(tool); pic->setStyleSheet("border-image: url(\":/testplugin/testImage.png\") "); @@ -201,7 +212,7 @@ void TestPlugin::initHoverWidgetTests() { CursorSettings *cursorMenu = new CursorSettings(); - HoverWidget* hover = new HoverWidget(cursorMenu, btn4, tool); + HoverWidget *hover = new HoverWidget(cursorMenu, btn4, tool); hover->setAnchorPos(HoverPosition::HP_TOPLEFT); hover->setContentPos(HoverPosition::HP_TOPRIGHT); connect(btn4, &QPushButton::toggled, this, [=](bool b) { @@ -211,71 +222,67 @@ void TestPlugin::initHoverWidgetTests() QWidget *hoverTest = new QWidget(tool); QHBoxLayout *hoverTestLayout = new QHBoxLayout(hoverTest); - QPushButton *testBtn = new QPushButton(hoverTest); + QPushButton *testBtn = new QPushButton(hoverTest); testBtn->setText("change content"); hoverTestLayout->addWidget(testBtn); QLabel *testLabel = new QLabel("--HOVER TEST--"); testLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - connect(testBtn, &QPushButton::clicked, this, [=](){hover->setContent(testLabel);}); + connect(testBtn, &QPushButton::clicked, this, [=]() { hover->setContent(testLabel); }); - testBtn = new QPushButton(hoverTest); + testBtn = new QPushButton(hoverTest); testBtn->setText("reset content"); hoverTestLayout->addWidget(testBtn); - connect(testBtn, &QPushButton::clicked, this, [=](){hover->setContent(cursorMenu);}); + connect(testBtn, &QPushButton::clicked, this, [=]() { hover->setContent(cursorMenu); }); - testBtn = new QPushButton(hoverTest); + testBtn = new QPushButton(hoverTest); testBtn->setText("change anchor"); hoverTestLayout->addWidget(testBtn); - connect(testBtn, &QPushButton::clicked, this, [=](){hover->setAnchor(edit);}); + connect(testBtn, &QPushButton::clicked, this, [=]() { hover->setAnchor(edit); }); - testBtn = new QPushButton(hoverTest); + testBtn = new QPushButton(hoverTest); testBtn->setText("reset anchor"); hoverTestLayout->addWidget(testBtn); - connect(testBtn, &QPushButton::clicked, this, [=](){hover->setAnchor(btn4);}); + connect(testBtn, &QPushButton::clicked, this, [=]() { hover->setAnchor(btn4); }); - testBtn = new QPushButton(hoverTest); + testBtn = new QPushButton(hoverTest); testBtn->setText("change parent"); hoverTestLayout->addWidget(testBtn); - connect(testBtn, &QPushButton::clicked, this, [=](){hover->setParent(lbl2);}); + connect(testBtn, &QPushButton::clicked, this, [=]() { hover->setParent(lbl2); }); - testBtn = new QPushButton(hoverTest); + testBtn = new QPushButton(hoverTest); testBtn->setText("reset parent"); hoverTestLayout->addWidget(testBtn); - connect(testBtn, &QPushButton::clicked, this, [=](){hover->setParent(tool);}); + connect(testBtn, &QPushButton::clicked, this, [=]() { hover->setParent(tool); }); - testBtn = new QPushButton(hoverTest); + testBtn = new QPushButton(hoverTest); testBtn->setText("change position"); hoverTestLayout->addWidget(testBtn); - connect(testBtn, &QPushButton::clicked, this, [=](){ + connect(testBtn, &QPushButton::clicked, this, [=]() { hover->setAnchorPos(HoverPosition::HP_TOPRIGHT); hover->setContentPos(HoverPosition::HP_TOPLEFT); }); - testBtn = new QPushButton(hoverTest); + testBtn = new QPushButton(hoverTest); testBtn->setText("reset position"); hoverTestLayout->addWidget(testBtn); - connect(testBtn, &QPushButton::clicked, this, [=](){ + connect(testBtn, &QPushButton::clicked, this, [=]() { hover->setAnchorPos(HoverPosition::HP_TOPLEFT); hover->setContentPos(HoverPosition::HP_TOPRIGHT); }); - testBtn = new QPushButton(hoverTest); + testBtn = new QPushButton(hoverTest); testBtn->setText("set draggable"); testBtn->setCheckable(true); hoverTestLayout->addWidget(testBtn); - connect(testBtn, &QPushButton::toggled, this, [=](bool toggled){ - hover->setDraggable(toggled); - }); + connect(testBtn, &QPushButton::toggled, this, [=](bool toggled) { hover->setDraggable(toggled); }); testBtn->setStyleSheet("QPushButton::checked{background-color: grey;}"); - testBtn = new QPushButton(hoverTest); + testBtn = new QPushButton(hoverTest); testBtn->setText("set relative"); testBtn->setCheckable(true); hoverTestLayout->addWidget(testBtn); - connect(testBtn, &QPushButton::toggled, this, [=](bool toggled){ - hover->setRelative(toggled); - }); + connect(testBtn, &QPushButton::toggled, this, [=](bool toggled) { hover->setRelative(toggled); }); testBtn->setStyleSheet("QPushButton::checked{background-color: grey;}"); tool->layout()->addWidget(hoverTest); @@ -283,7 +290,7 @@ void TestPlugin::initHoverWidgetTests() bool TestPlugin::onDisconnect() { - qDebug(CAT_TESTPLUGIN)<<"disconnect"; + qDebug(CAT_TESTPLUGIN) << "disconnect"; for(auto &tool : m_toolList) { tool->setEnabled(false); tool->setRunBtnVisible(false); @@ -300,26 +307,17 @@ void TestPlugin::cloneExtra(Plugin *p) { static int i = 0; - m_initText = dynamic_cast(p)->m_initText; + m_initText = dynamic_cast(p)->m_initText; - m_initText += " Cloned from original " +QString::number(i)+" times"; + m_initText += " Cloned from original " + QString::number(i) + " times"; i++; } -void TestPlugin::messageCallback(QString topic, QString message) -{ - qInfo(CAT_TESTPLUGIN) << topic <<": "<save(s); -} +void TestPlugin::saveSettings(QSettings &s) { m_pluginApi->save(s); } -void TestPlugin::loadSettings(QSettings &s) -{ - m_pluginApi->load(s); -} +void TestPlugin::loadSettings(QSettings &s) { m_pluginApi->load(s); } QString TestPlugin::about() { @@ -330,7 +328,7 @@ QString TestPlugin::about() void TestPlugin::initMetadata() { loadMetadata( -R"plugin( + R"plugin( { "priority":2, "category":[ @@ -340,25 +338,14 @@ R"plugin( )plugin"); } -void TestPlugin::init() -{ - m_initText = "This text was initialized"; -} +void TestPlugin::init() { m_initText = "This text was initialized"; } -QString TestPlugin::version() { - return "0.1"; -} +QString TestPlugin::version() { return "0.1"; } // -------------------- -QString TestPlugin_API::testText() const -{ - return p->edit->text(); -} +QString TestPlugin_API::testText() const { return p->edit->text(); } -void TestPlugin_API::setTestText(const QString &newTestText) -{ - p->edit->setText(newTestText); -} +void TestPlugin_API::setTestText(const QString &newTestText) { p->edit->setText(newTestText); } #include "moc_testplugin.cpp" diff --git a/plugins/testplugin/src/testtool.cpp b/plugins/testplugin/src/testtool.cpp index 512dd7a5fd..39db4252d0 100644 --- a/plugins/testplugin/src/testtool.cpp +++ b/plugins/testplugin/src/testtool.cpp @@ -1,27 +1,28 @@ #include "testtool.h" + +#include "plotaxis.h" +#include "plotwidget.h" +#include "spinbox_a.hpp" + +#include +#include #include + +#include #include -#include #include -#include -#include -#include "plotwidget.h" -#include "plotaxis.h" -#include "spinbox_a.hpp" #include +#include +#include +#include #include -#include #include -#include -#include -#include -#include -#include -#include #include +#include +#include +#include #include -#include -#include +#include using namespace scopy; @@ -42,7 +43,7 @@ TestTool::TestTool(QWidget *parent) lay->addWidget(tool); StyleHelper::GetInstance()->initColorMap(); - btn3 = new OpenLastMenuBtn(dynamic_cast(tool->rightContainer()),false,this); + btn3 = new OpenLastMenuBtn(dynamic_cast(tool->rightContainer()), false, this); tool->setLeftContainerWidth(200); tool->setRightContainerWidth(300); tool->openLeftContainerHelper(false); @@ -50,7 +51,7 @@ TestTool::TestTool(QWidget *parent) PlotWidget *plot = new PlotWidget(this); tool->addWidgetToCentralContainerHelper(plot); - plot->xAxis()->setInterval(0,1); + plot->xAxis()->setInterval(0, 1); plot->replot(); GearBtn *btn5 = new GearBtn(this); @@ -61,20 +62,20 @@ TestTool::TestTool(QWidget *parent) QTimer *dataRefreshTimer = new QTimer(this); dataRefreshTimer->setInterval(10); - connect(runBtn,&QPushButton::toggled, this, [=](bool b) { + connect(runBtn, &QPushButton::toggled, this, [=](bool b) { if(b) { dataRefreshTimer->start(); } else { dataRefreshTimer->stop(); } }); - connect(dataRefreshTimer,&QTimer::timeout, this, &TestTool::acquireData); - connect(dataRefreshTimer,&QTimer::timeout, plot, &PlotWidget::replot); + connect(dataRefreshTimer, &QTimer::timeout, this, &TestTool::acquireData); + connect(dataRefreshTimer, &QTimer::timeout, plot, &PlotWidget::replot); MenuControlButton *channels = new MenuControlButton(this); channels->setCheckBoxStyle(MenuControlButton::CS_CIRCLE); channels->setName("Channels"); -// ch0->setColor(StyleHelper::getColor("CH0")); + // ch0->setColor(StyleHelper::getColor("CH0")); channels->checkBox()->setVisible(false); channels->setChecked(false); @@ -92,14 +93,13 @@ TestTool::TestTool(QWidget *parent) QPen ch1pen = QPen(QColor(StyleHelper::getColor("CH1")), 1); auto *ch1PlotAxis = new PlotAxis(QwtAxis::YLeft, plot, ch1pen); PlotChannel *ch1_plotch = new PlotChannel("Channel1", ch1pen, plot, plot->xAxis(), ch1PlotAxis, this); - ch1_plotch->setHandle(new PlotAxisHandle(ch1pen ,ch1PlotAxis,plot, QwtAxis::YLeft, this)); + ch1_plotch->setHandle(new PlotAxisHandle(ch1pen, ch1PlotAxis, plot, QwtAxis::YLeft, this)); plot->addPlotAxisHandle(ch1_plotch->handle()); - connect(ch1->checkBox(),&QCheckBox::toggled, ch1_plotch, &PlotChannel::setEnabled); - connect(ch1->checkBox(),&QCheckBox::toggled, this, [=](){plot->replot();}); - connect(ch1, &QAbstractButton::toggled, this, [=](){plot->selectChannel(ch1_plotch);}); - ch1_plotch->curve()->setRawSamples(xTime.data(),y1Volt.data(),xTime.size()); - + connect(ch1->checkBox(), &QCheckBox::toggled, ch1_plotch, &PlotChannel::setEnabled); + connect(ch1->checkBox(), &QCheckBox::toggled, this, [=]() { plot->replot(); }); + connect(ch1, &QAbstractButton::toggled, this, [=]() { plot->selectChannel(ch1_plotch); }); + ch1_plotch->curve()->setRawSamples(xTime.data(), y1Volt.data(), xTime.size()); MenuControlButton *ch2 = new MenuControlButton(this); ch2->setCheckBoxStyle(MenuControlButton::CS_CIRCLE); @@ -110,12 +110,12 @@ TestTool::TestTool(QWidget *parent) QPen ch2pen = QPen(QColor(StyleHelper::getColor("CH2")), 1); auto *ch2PlotAxis = new PlotAxis(QwtAxis::YLeft, plot, ch2pen); PlotChannel *ch2_plotch = new PlotChannel("Channel2", ch2pen, plot, plot->xAxis(), ch2PlotAxis, this); - ch2_plotch->setHandle(new PlotAxisHandle(ch2pen,ch2PlotAxis, plot, QwtAxis::YRight, this)); + ch2_plotch->setHandle(new PlotAxisHandle(ch2pen, ch2PlotAxis, plot, QwtAxis::YRight, this)); plot->addPlotAxisHandle(ch2_plotch->handle()); - connect(ch2->checkBox(),&QCheckBox::toggled, ch2_plotch, &PlotChannel::setEnabled); - connect(ch2->checkBox(),&QCheckBox::toggled, this, [=](){plot->replot();}); - connect(ch2, &QAbstractButton::toggled, this, [=](){plot->selectChannel(ch2_plotch);}); - ch2_plotch->curve()->setRawSamples(xTime.data(),y2Volt.data(),xTime.size()); + connect(ch2->checkBox(), &QCheckBox::toggled, ch2_plotch, &PlotChannel::setEnabled); + connect(ch2->checkBox(), &QCheckBox::toggled, this, [=]() { plot->replot(); }); + connect(ch2, &QAbstractButton::toggled, this, [=]() { plot->selectChannel(ch2_plotch); }); + ch2_plotch->curve()->setRawSamples(xTime.data(), y2Volt.data(), xTime.size()); MenuControlButton *cursor = new MenuControlButton(this); cursor->setName("Cursors"); @@ -140,14 +140,14 @@ TestTool::TestTool(QWidget *parent) connect(cursor->button(), &QAbstractButton::toggled, hoverSettings, &HoverWidget::setVisible); connect(cursor, &QAbstractButton::toggled, cursorController, &CursorController::setVisible); - tool->addWidgetToTopContainerMenuControlHelper(btn3,TTA_RIGHT); - tool->addWidgetToTopContainerMenuControlHelper(btn5,TTA_LEFT); + tool->addWidgetToTopContainerMenuControlHelper(btn3, TTA_RIGHT); + tool->addWidgetToTopContainerMenuControlHelper(btn5, TTA_LEFT); - tool->addWidgetToTopContainerHelper(runBtn,TTA_RIGHT); - tool->addWidgetToTopContainerHelper(singleBtn,TTA_RIGHT); + tool->addWidgetToTopContainerHelper(runBtn, TTA_RIGHT); + tool->addWidgetToTopContainerHelper(singleBtn, TTA_RIGHT); - tool->addWidgetToTopContainerHelper(infoBtn,TTA_LEFT); - tool->addWidgetToTopContainerHelper(printBtn,TTA_LEFT); + tool->addWidgetToTopContainerHelper(infoBtn, TTA_LEFT); + tool->addWidgetToTopContainerHelper(printBtn, TTA_LEFT); tool->addWidgetToBottomContainerHelper(channels, TTA_LEFT); tool->addWidgetToBottomContainerHelper(ch1, TTA_LEFT); @@ -160,15 +160,15 @@ TestTool::TestTool(QWidget *parent) QLabel *wch1 = new QLabel("Channel1Label"); QLabel *wch2 = new QLabel("Channel2Label"); - tool->rightStack()->add("ch0",wch0); - tool->rightStack()->add("ch1",wch1); - tool->rightStack()->add("ch2",wch2); + tool->rightStack()->add("ch0", wch0); + tool->rightStack()->add("ch1", wch1); + tool->rightStack()->add("ch2", wch2); - connect(channels->button(),&QAbstractButton::pressed,this,[=](){tool->requestMenu("ch0");}); - connect(ch1->button(),&QAbstractButton::pressed,this,[=](){tool->requestMenu("ch1");}); - connect(ch2->button(),&QAbstractButton::pressed,this,[=](){tool->requestMenu("ch2");}); + connect(channels->button(), &QAbstractButton::pressed, this, [=]() { tool->requestMenu("ch0"); }); + connect(ch1->button(), &QAbstractButton::pressed, this, [=]() { tool->requestMenu("ch1"); }); + connect(ch2->button(), &QAbstractButton::pressed, this, [=]() { tool->requestMenu("ch2"); }); - auto grp = static_cast(btn3)->getButtonGroup(); + auto grp = static_cast(btn3)->getButtonGroup(); grp->addButton(channels->button()); grp->addButton(ch1->button()); grp->addButton(ch2->button()); @@ -198,11 +198,11 @@ TestTool::TestTool(QWidget *parent) vcm->add(dev1); vcm->add(fileChannel); - vcm->setFixedSize(260,350); + vcm->setFixedSize(260, 350); HoverWidget *hv = new HoverWidget(nullptr, channels, tool); hv->setContent(vcm); - hv->setAnchorOffset(QPoint(0,-10)); + hv->setAnchorOffset(QPoint(0, -10)); hv->setAnchorPos(HoverPosition::HP_TOPLEFT); hv->setContentPos(HoverPosition::HP_TOPRIGHT); @@ -212,15 +212,14 @@ TestTool::TestTool(QWidget *parent) plot->topHandlesArea()->setVisible(true); connect(channels, &QAbstractButton::toggled, this, [=](bool b) { - qInfo()<<"setVisible: "<setVisible(b); hv->raise(); - }); } - -QWidget* TestTool::createMenu(QWidget* parent) { +QWidget *TestTool::createMenu(QWidget *parent) +{ QWidget *w = new QWidget(parent); QVBoxLayout *lay = new QVBoxLayout(w); lay->setMargin(0); @@ -231,22 +230,18 @@ QWidget* TestTool::createMenu(QWidget* parent) { MenuComboWidget *yscale = new MenuComboWidget(tr("Y-Axis"), w); MenuSectionWidget *vdiv = new MenuSectionWidget(w); - QLabel *txt = new QLabel("VDiv",vdiv); - StyleHelper::MenuSmallLabel(txt,"vdivLabel"); + QLabel *txt = new QLabel("VDiv", vdiv); + StyleHelper::MenuSmallLabel(txt, "vdivLabel"); QComboBox *cbb = new QComboBox(vdiv); cbb->addItem("Lorem"); cbb->addItem("Ipsum"); cbb->addItem("Corectipsum"); - StyleHelper::MenuComboBox(cbb,"vdivCombo"); - - PositionSpinButton *ssb = new PositionSpinButton( - { - {"Hz",1e0}, - {"kHz",1e3}, - {"MHz",1e6} - },"Volts",0,1000,true,false,vdiv); + StyleHelper::MenuComboBox(cbb, "vdivCombo"); + + PositionSpinButton *ssb = + new PositionSpinButton({{"Hz", 1e0}, {"kHz", 1e3}, {"MHz", 1e6}}, "Volts", 0, 1000, true, false, vdiv); ssb->setMaxValue(1000); - StyleHelper::MenuSpinBox(ssb,"vdivSpin"); + StyleHelper::MenuSpinBox(ssb, "vdivSpin"); MenuOnOffSwitch *autoscale = new MenuOnOffSwitch(tr("AUTOSCALE"), vdiv, false); @@ -259,7 +254,7 @@ QWidget* TestTool::createMenu(QWidget* parent) { // MenuBigSwitch *bigsw = new MenuBigSwitch("Yes", "No", vdiv); QLabel *lbl = new QLabel("AUTOSCALE"); - StyleHelper::MenuSmallLabel(lbl,"edit"); + StyleHelper::MenuSmallLabel(lbl, "edit"); MenuLineEdit *edit = new MenuLineEdit(vdiv); vdiv->contentLayout()->addWidget(section1); @@ -274,33 +269,32 @@ QWidget* TestTool::createMenu(QWidget* parent) { lay->addWidget(header); lay->addWidget(yscale); lay->addWidget(vdiv); - lay->addSpacerItem(new QSpacerItem(40,40,QSizePolicy::Minimum,QSizePolicy::Expanding)); + lay->addSpacerItem(new QSpacerItem(40, 40, QSizePolicy::Minimum, QSizePolicy::Expanding)); QPushButton *btn = new QPushButton("TESTBtn"); - StyleHelper::BlueButton(btn,"TestBtn"); + StyleHelper::BlueButton(btn, "TestBtn"); vdiv->contentLayout()->addWidget(btn); vdiv->contentLayout()->setSpacing(4); - return w; } - void TestTool::initData() { - for(int i = 0; i < testDataSize ; i++){ - xTime.push_back( (i / (double)testDataSize)); - y1Volt.push_back(amplitude*sin(2 * 10 * 3.1416 * i / (double)testDataSize)); - y2Volt.push_back(amplitude*sin(2 * 20 * 3.1416 * i / (double)testDataSize)); + for(int i = 0; i < testDataSize; i++) { + xTime.push_back((i / (double)testDataSize)); + y1Volt.push_back(amplitude * sin(2 * 10 * 3.1416 * i / (double)testDataSize)); + y2Volt.push_back(amplitude * sin(2 * 20 * 3.1416 * i / (double)testDataSize)); } } -void TestTool::acquireData() { +void TestTool::acquireData() +{ y1Volt.clear(); y2Volt.clear(); - for(int i = 0; i < testDataSize ; i++){ - y1Volt.push_back(amplitude*sin(2 * 10 * 3.1416 * i / (double)testDataSize + phase)); - y2Volt.push_back(amplitude*sin(2 * 17 * 3.1416 * i / (double)testDataSize + 2*phase)); + for(int i = 0; i < testDataSize; i++) { + y1Volt.push_back(amplitude * sin(2 * 10 * 3.1416 * i / (double)testDataSize + phase)); + y2Volt.push_back(amplitude * sin(2 * 17 * 3.1416 * i / (double)testDataSize + 2 * phase)); } phase++; } diff --git a/plugins/testplugin/src/testtool.h b/plugins/testplugin/src/testtool.h index c42168eec9..799e66cc58 100644 --- a/plugins/testplugin/src/testtool.h +++ b/plugins/testplugin/src/testtool.h @@ -1,13 +1,15 @@ #ifndef TESTTOOL_H #define TESTTOOL_H -#include +#include "gui/mapstackedwidget.h" #include "gui/tooltemplate.h" -#include + #include #include +#include +#include + #include -#include "gui/mapstackedwidget.h" using namespace scopy; @@ -18,6 +20,7 @@ class SCOPY_TESTPLUGIN_EXPORT TestTool : public QWidget void initData(); public Q_SLOTS: void acquireData(); + private: int testDataSize = 128; double amplitude = 0.5; @@ -26,10 +29,9 @@ public Q_SLOTS: std::vector y1Volt; std::vector xTime; - ToolTemplate *tool; QPushButton *btn1, *btn2, *btn3; - QWidget* createMenu(QWidget* parent); + QWidget *createMenu(QWidget *parent); }; //}; #endif // TESTTOOL_H diff --git a/plugins/testplugin/test/CMakeLists.txt b/plugins/testplugin/test/CMakeLists.txt index ff0d566e02..646197d6f9 100644 --- a/plugins/testplugin/test/CMakeLists.txt +++ b/plugins/testplugin/test/CMakeLists.txt @@ -2,7 +2,4 @@ cmake_minimum_required(VERSION 3.5) include(ScopyTest) -SETUP_SCOPY_TESTS( - pluginloader -) - +setup_scopy_tests(pluginloader) diff --git a/plugins/testplugin/test/tst_pluginloader.cpp b/plugins/testplugin/test/tst_pluginloader.cpp index bf9ce7d324..7da966ea11 100644 --- a/plugins/testplugin/test/tst_pluginloader.cpp +++ b/plugins/testplugin/test/tst_pluginloader.cpp @@ -1,6 +1,8 @@ #include "qpluginloader.h" -#include + #include +#include + #include using namespace scopy; @@ -19,71 +21,64 @@ private Q_SLOTS: void clone(); void name(); void metadata(); - }; #define PLUGIN_LOCATION "../../plugins" #define FILENAME PLUGIN_LOCATION "/libscopy-testplugin.so" - void TST_TestPlugin::fileExists() { QFile f(FILENAME); bool ret; - qDebug()<(qp.instance()); - QVERIFY(instance != nullptr ); + QPluginLoader qp(FILENAME, this); + auto instance = qobject_cast(qp.instance()); + QVERIFY(instance != nullptr); } - void TST_TestPlugin::clone() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(); QVERIFY(p1 != nullptr); p2 = original->clone(); @@ -91,28 +86,28 @@ void TST_TestPlugin::clone() QVERIFY(p1 != p2); } -void TST_TestPlugin::name() { - QPluginLoader qp(FILENAME,this); +void TST_TestPlugin::name() +{ + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(); - qDebug()<name(); + qDebug() << p1->name(); } void TST_TestPlugin::metadata() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); original->initMetadata(); p1 = original->clone(); - qDebug()<metadata(); + qDebug() << p1->metadata(); QVERIFY(!p1->metadata().isEmpty()); } - QTEST_MAIN(TST_TestPlugin) #include "tst_pluginloader.moc" diff --git a/plugins/testplugin2/CMakeLists.txt b/plugins/testplugin2/CMakeLists.txt index 4435c53ad5..1f178939aa 100644 --- a/plugins/testplugin2/CMakeLists.txt +++ b/plugins/testplugin2/CMakeLists.txt @@ -7,8 +7,7 @@ project(scopy-${SCOPY_MODULE} VERSION 0.1 LANGUAGES CXX) include(GenerateExportHeader) -# TODO: split stylesheet/resources and add here -# TODO: export header files correctly +# TODO: split stylesheet/resources and add here TODO: export header files correctly set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -25,47 +24,39 @@ set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) set(SCOPY_QT_COMPONENTS Widgets Core) -FILE(GLOB SRC_LIST src/*.cpp src/*.cc) -FILE(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) -FILE(GLOB UI_LIST ui/*.ui) +file(GLOB SRC_LIST src/*.cpp src/*.cc) +file(GLOB HEADER_LIST include/${SCOPY_MODULE}/*.h include/${SCOPY_MODULE}/*.hpp) +file(GLOB UI_LIST ui/*.ui) if(ENABLE_TESTING) - add_subdirectory(test) + add_subdirectory(test) endif() -set(PROJECT_SOURCES - ${SRC_LIST} - ${HEADER_LIST} - ${UI_LIST} -) +set(PROJECT_SOURCES ${SRC_LIST} ${HEADER_LIST} ${UI_LIST}) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS ${SCOPY_QT_COMPONENTS} REQUIRED) if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") - set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY - "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/Scopy.app/Contents/MacOS/plugins/plugins") else() - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${SCOPY_PLUGIN_BUILD_PATH}) endif() -add_library(${PROJECT_NAME} SHARED - ${PROJECT_SOURCES} -) +add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES}) -generate_export_header(${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h) +generate_export_header( + ${PROJECT_NAME} EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}/${PROJECT_NAME}_export.h +) target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/${SCOPY_MODULE}) foreach(comp ${SCOPY_QT_COMPONENTS}) - set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) + set(SCOPY_QT_LIBRARIES ${SCOPY_QT_LIBRARIES} Qt${QT_VERSION_MAJOR}::${comp}) endforeach() -target_link_libraries(${PROJECT_NAME} PUBLIC - ${SCOPY_QT_LIBRARIES} - scopy-pluginbase) - +target_link_libraries(${PROJECT_NAME} PUBLIC ${SCOPY_QT_LIBRARIES} scopy-pluginbase) -set(PLUGIN_NAME ${PROJECT_NAME} PARENT_SCOPE) \ No newline at end of file +set(PLUGIN_NAME ${PROJECT_NAME} PARENT_SCOPE) diff --git a/plugins/testplugin2/include/testplugin2/testpluginip.h b/plugins/testplugin2/include/testplugin2/testpluginip.h index 29ce4e7960..4b9dc51439 100644 --- a/plugins/testplugin2/include/testplugin2/testpluginip.h +++ b/plugins/testplugin2/include/testplugin2/testpluginip.h @@ -1,21 +1,22 @@ #ifndef TESTPLUGINIP_H #define TESTPLUGINIP_H - #define SCOPY_PLUGIN_NAME TestPluginIp -#include -#include #include "pluginbase/pluginbase.h" #include "scopy-testplugin2_export.h" +#include + +#include + namespace scopy { class SCOPY_TESTPLUGIN2_EXPORT TestPluginIp : public QObject, public PluginBase { Q_OBJECT SCOPY_PLUGIN -// Plugin interface + // Plugin interface public: void postload() override; bool loadIcon() override; @@ -31,9 +32,6 @@ class SCOPY_TESTPLUGIN2_EXPORT TestPluginIp : public QObject, public PluginBase private: QWidget *m_tool; - - - }; -} +} // namespace scopy #endif // TESTPLUGINIP_H diff --git a/plugins/testplugin2/src/testpluginip.cpp b/plugins/testplugin2/src/testpluginip.cpp index 43f41e64a2..86401fca50 100644 --- a/plugins/testplugin2/src/testpluginip.cpp +++ b/plugins/testplugin2/src/testpluginip.cpp @@ -1,35 +1,39 @@ #include "testpluginip.h" + #include "qlabel.h" #include "qpushbutton.h" -#include + #include +#include + #include -Q_LOGGING_CATEGORY(CAT_TESTPLUGINIP,"TestPluginIp"); +Q_LOGGING_CATEGORY(CAT_TESTPLUGINIP, "TestPluginIp"); using namespace scopy; -bool TestPluginIp::compatible(QString m_param, QString category) { - qDebug(CAT_TESTPLUGINIP)<<"compatible"; +bool TestPluginIp::compatible(QString m_param, QString category) +{ + qDebug(CAT_TESTPLUGINIP) << "compatible"; return m_param.startsWith("ip:"); } -void TestPluginIp::unload() { +void TestPluginIp::unload() +{ for(auto &tool : m_toolList) { delete tool; } - } bool TestPluginIp::onConnect() { - qDebug(CAT_TESTPLUGINIP)<<"connect"; - qDebug(CAT_TESTPLUGINIP)<id()<name(); + qDebug(CAT_TESTPLUGINIP) << "connect"; + qDebug(CAT_TESTPLUGINIP) << m_toolList[0]->id() << m_toolList[0]->name(); m_toolList[0]->setEnabled(true); m_toolList[0]->setName("IP tool1"); m_toolList[0]->setRunBtnVisible(true); m_toolList[0]->setTool(new QLabel("TestPage IP Renamed")); - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("IP tool2","IP tool2", "")); + m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("IP tool2", "IP tool2", "")); m_toolList[1]->setEnabled(true); m_tool = new QWidget(); QVBoxLayout *lay = new QVBoxLayout(m_tool); @@ -41,13 +45,13 @@ bool TestPluginIp::onConnect() QPushButton *sendMessage = new QPushButton("SendMessage"); lay->addWidget(sendMessage); - connect(btn,&QPushButton::clicked,this,[=]() { requestTool(m_toolList[0]->id());}); - connect(sendMessage,&QPushButton::clicked,this,[=]() { - MessageBroker::GetInstance()->publish("TestPlugin","testMessage"); - MessageBroker::GetInstance()->publish("broadcast","testMessage"); - MessageBroker::GetInstance()->publish("TestPlugin2","testMessage"); + connect(btn, &QPushButton::clicked, this, [=]() { requestTool(m_toolList[0]->id()); }); + connect(sendMessage, &QPushButton::clicked, this, [=]() { + MessageBroker::GetInstance()->publish("TestPlugin", "testMessage"); + MessageBroker::GetInstance()->publish("broadcast", "testMessage"); + MessageBroker::GetInstance()->publish("TestPlugin2", "testMessage"); }); - connect(disc,&QPushButton::clicked,this,[=]() { Q_EMIT disconnectDevice();}); + connect(disc, &QPushButton::clicked, this, [=]() { Q_EMIT disconnectDevice(); }); Q_EMIT toolListChanged(); m_toolList[1]->setTool(m_tool); @@ -69,14 +73,11 @@ bool TestPluginIp::onDisconnect() m_toolList.removeLast(); m_toolList[0]->setName("IP"); - qDebug(CAT_TESTPLUGINIP)<<"disconnect"; + qDebug(CAT_TESTPLUGINIP) << "disconnect"; return true; } -void TestPluginIp::postload() -{ - -} +void TestPluginIp::postload() {} bool TestPluginIp::loadIcon() { @@ -93,15 +94,12 @@ bool TestPluginIp::loadPage() return true; } -void TestPluginIp::loadToolList() -{ - m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("test2","SecondPlugin","")); -} +void TestPluginIp::loadToolList() { m_toolList.append(SCOPY_NEW_TOOLMENUENTRY("test2", "SecondPlugin", "")); } void TestPluginIp::initMetadata() { loadMetadata( -R"plugin( + R"plugin( { "priority":2, "category":[ @@ -111,14 +109,8 @@ R"plugin( )plugin"); } -void TestPluginIp::saveSettings(QSettings &s) -{ - s.setValue("ip",m_param); -} +void TestPluginIp::saveSettings(QSettings &s) { s.setValue("ip", m_param); } -void TestPluginIp::loadSettings(QSettings &s) -{ - qInfo(CAT_TESTPLUGINIP)< + #include +#include + #include using namespace scopy; @@ -25,7 +27,6 @@ private Q_SLOTS: #define PLUGIN_LOCATION "../../plugins" #define FILENAME PLUGIN_LOCATION "/libscopy-testplugin2.so" - void TST_TestPluginIp::fileExists() { QFile f(FILENAME); @@ -36,53 +37,48 @@ void TST_TestPluginIp::fileExists() QVERIFY(ret); } -void TST_TestPluginIp::isLibrary() -{ - QVERIFY(QLibrary::isLibrary(FILENAME)); -} +void TST_TestPluginIp::isLibrary() { QVERIFY(QLibrary::isLibrary(FILENAME)); } void TST_TestPluginIp::className() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); QVERIFY(qp.metaData().value("className") == "TestPluginIp"); } void TST_TestPluginIp::loaded() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); qp.load(); QVERIFY(qp.isLoaded()); } void TST_TestPluginIp::instanceNotNull() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); QVERIFY(qp.instance() != nullptr); } void TST_TestPluginIp::multipleInstances() { - QPluginLoader qp1(FILENAME,this); - QPluginLoader qp2(FILENAME,this); + QPluginLoader qp1(FILENAME, this); + QPluginLoader qp2(FILENAME, this); QVERIFY(qp1.instance() == qp2.instance()); } - void TST_TestPluginIp::qobjectcast_to_plugin() { - QPluginLoader qp(FILENAME,this); - auto instance = qobject_cast(qp.instance()); - QVERIFY(instance != nullptr ); + QPluginLoader qp(FILENAME, this); + auto instance = qobject_cast(qp.instance()); + QVERIFY(instance != nullptr); } - void TST_TestPluginIp::clone() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(); QVERIFY(p1 != nullptr); p2 = original->clone(); @@ -90,24 +86,25 @@ void TST_TestPluginIp::clone() QVERIFY(p1 != p2); } -void TST_TestPluginIp::name() { - QPluginLoader qp(FILENAME,this); +void TST_TestPluginIp::name() +{ + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); p1 = original->clone(); - qDebug()<name(); + qDebug() << p1->name(); } void TST_TestPluginIp::metadata() { - QPluginLoader qp(FILENAME,this); + QPluginLoader qp(FILENAME, this); Plugin *p1 = nullptr, *p2 = nullptr; - auto original = qobject_cast(qp.instance()); + auto original = qobject_cast(qp.instance()); original->initMetadata(); p1 = original->clone(); - qDebug()<metadata(); + qDebug() << p1->metadata(); QVERIFY(!p1->metadata().isEmpty()); } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index a0e0e109b5..b5caf61376 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,2 +1 @@ cmake_minimum_required(VERSION 3.5) - diff --git a/tools/format.sh b/tools/format.sh index 3604cc2108..a5a5b8c34e 100755 --- a/tools/format.sh +++ b/tools/format.sh @@ -13,6 +13,7 @@ find $SCOPY_REPO -type f -name "*.cc" | xargs $CLANG_FORMAT $VERBOSE $IN_PLACE find $SCOPY_REPO -type f -name "*.hpp" | xargs $CLANG_FORMAT $VERBOSE $IN_PLACE find $SCOPY_REPO -type f -name "*.h" | xargs $CLANG_FORMAT $VERBOSE $IN_PLACE find $SCOPY_REPO -type f -name "CMakeLists.txt" | xargs $CMAKE_FORMAT $IN_PLACE +find $SCOPY_REPO -type f -name "*.cmake" | xargs $CMAKE_FORMAT $IN_PLACE pushd $SCOPY_REPO/tools ./includemocs.sh popd