diff --git a/.clang-format b/.clang-format index 41a4a7234..e2f0bb93b 100644 --- a/.clang-format +++ b/.clang-format @@ -15,7 +15,7 @@ BreakBeforeBinaryOperators: false BreakBeforeTernaryOperators: false BreakConstructorInitializersBeforeComma: true BinPackParameters: true -ColumnLimit: 120 +ColumnLimit: 90 ConstructorInitializerAllOnOneLineOrOnePerLine: true DerivePointerBinding: false PointerBindsToType: true diff --git a/plotjuggler_app/cheatsheet/cheatsheet_dialog.cpp b/plotjuggler_app/cheatsheet/cheatsheet_dialog.cpp index e67adb325..2523b94b9 100644 --- a/plotjuggler_app/cheatsheet/cheatsheet_dialog.cpp +++ b/plotjuggler_app/cheatsheet/cheatsheet_dialog.cpp @@ -1,9 +1,8 @@ #include "cheatsheet_dialog.h" #include "ui_cheatsheet_dialog.h" -CheatsheetDialog::CheatsheetDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::CheatsheetDialog) +CheatsheetDialog::CheatsheetDialog(QWidget* parent) + : QDialog(parent), ui(new Ui::CheatsheetDialog) { ui->setupUi(this); diff --git a/plotjuggler_app/cheatsheet/cheatsheet_dialog.h b/plotjuggler_app/cheatsheet/cheatsheet_dialog.h index 17cc4919d..2a6970afb 100644 --- a/plotjuggler_app/cheatsheet/cheatsheet_dialog.h +++ b/plotjuggler_app/cheatsheet/cheatsheet_dialog.h @@ -3,7 +3,8 @@ #include -namespace Ui { +namespace Ui +{ class CheatsheetDialog; } @@ -12,14 +13,14 @@ class CheatsheetDialog : public QDialog Q_OBJECT public: - explicit CheatsheetDialog(QWidget *parent = nullptr); + explicit CheatsheetDialog(QWidget* parent = nullptr); ~CheatsheetDialog(); private slots: void on_listWidget_currentRowChanged(int currentRow); private: - Ui::CheatsheetDialog *ui; + Ui::CheatsheetDialog* ui; }; -#endif // CHEATSHEET_DIALOG_H +#endif // CHEATSHEET_DIALOG_H diff --git a/plotjuggler_app/curvelist_panel.cpp b/plotjuggler_app/curvelist_panel.cpp index 3e4d26720..b3dedf658 100644 --- a/plotjuggler_app/curvelist_panel.cpp +++ b/plotjuggler_app/curvelist_panel.cpp @@ -24,15 +24,14 @@ //------------------------------------------------- CurveListPanel::CurveListPanel(PlotDataMapRef& mapped_plot_data, - const TransformsMap &mapped_math_plots, - QWidget* parent) + const TransformsMap& mapped_math_plots, QWidget* parent) : QWidget(parent) , ui(new Ui::CurveListPanel) - , _plot_data( mapped_plot_data ) + , _plot_data(mapped_plot_data) , _custom_view(new CurveTableView(this)) , _tree_view(new CurveTreeView(this)) , _transforms_map(mapped_math_plots) - , _column_width_dirty (true) + , _column_width_dirty(true) { ui->setupUi(this); @@ -59,12 +58,14 @@ CurveListPanel::CurveListPanel(PlotDataMapRef& mapped_plot_data, ui->splitter->setStretchFactor(0, 5); ui->splitter->setStretchFactor(1, 1); - connect(_custom_view->selectionModel(), &QItemSelectionModel::selectionChanged, - this, &CurveListPanel::onCustomSelectionChanged); + connect(_custom_view->selectionModel(), &QItemSelectionModel::selectionChanged, this, + &CurveListPanel::onCustomSelectionChanged); - connect(_custom_view->verticalScrollBar(), &QScrollBar::valueChanged, this, &CurveListPanel::refreshValues); + connect(_custom_view->verticalScrollBar(), &QScrollBar::valueChanged, this, + &CurveListPanel::refreshValues); - connect(_tree_view->verticalScrollBar(), &QScrollBar::valueChanged, this, &CurveListPanel::refreshValues); + connect(_tree_view->verticalScrollBar(), &QScrollBar::valueChanged, this, + &CurveListPanel::refreshValues); connect(_tree_view, &QTreeWidget::itemExpanded, this, &CurveListPanel::refreshValues); } @@ -81,33 +82,34 @@ void CurveListPanel::clear() ui->labelNumberDisplayed->setText("0 of 0"); } -void CurveListPanel::addCurve(const std::string &plot_name) +void CurveListPanel::addCurve(const std::string& plot_name) { QString group_name; - auto FindInPlotData = [&](auto& plot_data, const std::string &plot_name) - { - auto it = plot_data.find( plot_name ); - if( it != plot_data.end() ){ + auto FindInPlotData = [&](auto& plot_data, const std::string& plot_name) { + auto it = plot_data.find(plot_name); + if (it != plot_data.end()) + { auto& plot = it->second; - if( plot.group() ){ - group_name = QString::fromStdString( plot.group()->name() ); + if (plot.group()) + { + group_name = QString::fromStdString(plot.group()->name()); } return true; } return false; }; - bool found = - FindInPlotData( _plot_data.numeric, plot_name ) || - FindInPlotData( _plot_data.strings, plot_name ); + bool found = FindInPlotData(_plot_data.numeric, plot_name) || + FindInPlotData(_plot_data.strings, plot_name); - if( !found ) { + if (!found) + { return; } - QString plot_id = QString::fromStdString( plot_name ); - _tree_view->addItem(group_name, getTreeName( plot_id ), plot_id ); + QString plot_id = QString::fromStdString(plot_name); + _tree_view->addItem(group_name, getTreeName(plot_id), plot_id); _column_width_dirty = true; } @@ -120,51 +122,47 @@ void CurveListPanel::addCustom(const QString& item_name) void CurveListPanel::updateColors() { - QColor default_color = _tree_view->palette().color( QPalette::Text ); + QColor default_color = _tree_view->palette().color(QPalette::Text); //------------------------------------------ // Propagate change in color and style to the children of a group - std::function ChangeColorAndStyle; - ChangeColorAndStyle = [&](QTreeWidgetItem* cell, QColor color, bool italic) - { + std::function ChangeColorAndStyle; + ChangeColorAndStyle = [&](QTreeWidgetItem* cell, QColor color, bool italic) { cell->setForeground(0, color); auto font = cell->font(0); - font.setItalic( italic ); + font.setItalic(italic); cell->setFont(0, font); for (int c = 0; c < cell->childCount(); c++) { - ChangeColorAndStyle(cell->child(c), color, italic); + ChangeColorAndStyle(cell->child(c), color, italic); }; }; // set everything to default first for (int c = 0; c < _tree_view->invisibleRootItem()->childCount(); c++) { - ChangeColorAndStyle(_tree_view->invisibleRootItem()->child(c), - default_color, - false); + ChangeColorAndStyle(_tree_view->invisibleRootItem()->child(c), default_color, false); } //------------- Change groups first --------------------- - auto ChangeGroupVisitor = [&](QTreeWidgetItem* cell) - { - if( cell->data(0, CustomRoles::IsGroupName).toBool() ) + auto ChangeGroupVisitor = [&](QTreeWidgetItem* cell) { + if (cell->data(0, CustomRoles::IsGroupName).toBool()) { auto group_name = cell->data(0, CustomRoles::Name).toString(); - auto it = _plot_data.groups.find( group_name.toStdString() ); - if ( it != _plot_data.groups.end() ) + auto it = _plot_data.groups.find(group_name.toStdString()); + if (it != _plot_data.groups.end()) { QVariant color_var = it->second->attribute(PJ::TEXT_COLOR); - QColor text_color = color_var.isValid() ? - color_var.value() : default_color; + QColor text_color = + color_var.isValid() ? color_var.value() : default_color; QVariant style_var = it->second->attribute(PJ::ITALIC_FONTS); - bool italic =( style_var.isValid() && style_var.value() ); + bool italic = (style_var.isValid() && style_var.value()); ChangeColorAndStyle(cell, text_color, italic); // tooltip doesn't propagate QVariant tooltip = it->second->attribute("ToolTip"); - cell->setData(0, CustomRoles::ToolTip, tooltip ); + cell->setData(0, CustomRoles::ToolTip, tooltip); } } }; @@ -173,30 +171,30 @@ void CurveListPanel::updateColors() //------------- Change leaves --------------------- - auto ChangeLeavesVisitor = [&](QTreeWidgetItem* cell) - { - if( cell->childCount() == 0 ) + auto ChangeLeavesVisitor = [&](QTreeWidgetItem* cell) { + if (cell->childCount() == 0) { - const std::string& curve_name = cell->data(0, CustomRoles::Name).toString().toStdString(); + const std::string& curve_name = + cell->data(0, CustomRoles::Name).toString().toStdString(); QVariant text_color; - auto GetTextColor = [&](auto& plot_data, const std::string& curve_name){ + auto GetTextColor = [&](auto& plot_data, const std::string& curve_name) { auto it = plot_data.find(curve_name); - if ( it != plot_data.end() ) + if (it != plot_data.end()) { QVariant color_var = it->second.attribute(PJ::TEXT_COLOR); - if( color_var.isValid() ) + if (color_var.isValid()) { - cell->setForeground(0, color_var.value() ); + cell->setForeground(0, color_var.value()); } QVariant tooltip_var = it->second.attribute(PJ::TOOL_TIP); - cell->setData(0, CustomRoles::ToolTip, tooltip_var ); + cell->setData(0, CustomRoles::ToolTip, tooltip_var); QVariant style_var = it->second.attribute(PJ::ITALIC_FONTS); - bool italic = ( style_var.isValid() && style_var.value() ); - if( italic ) + bool italic = (style_var.isValid() && style_var.value()); + if (italic) { QFont font = cell->font(0); font.setItalic(italic); @@ -207,8 +205,8 @@ void CurveListPanel::updateColors() return false; }; - bool valid = ( GetTextColor( _plot_data.numeric, curve_name ) || - GetTextColor( _plot_data.strings, curve_name )); + bool valid = (GetTextColor(_plot_data.numeric, curve_name) || + GetTextColor(_plot_data.strings, curve_name)); } }; @@ -287,7 +285,8 @@ void CurveListPanel::refreshValues() { auto& plot_data = it->second; auto val = plot_data.getYfromX(_tracker_time); - if( val ) { + if (val) + { return FormattedNumber(val.value()); } } @@ -299,14 +298,17 @@ void CurveListPanel::refreshValues() { auto& plot_data = it->second; auto val = plot_data.getYfromX(_tracker_time); - if( val ) { + if (val) + { auto str_view = val.value(); - char last_byte = str_view.data()[ str_view.size()-1 ]; - if( last_byte == '\0') { - return QString::fromLocal8Bit( str_view.data(), str_view.size() - 1 ); + char last_byte = str_view.data()[str_view.size() - 1]; + if (last_byte == '\0') + { + return QString::fromLocal8Bit(str_view.data(), str_view.size() - 1); } - else{ - return QString::fromLocal8Bit( str_view.data(), str_view.size() ); + else + { + return QString::fromLocal8Bit(str_view.data(), str_view.size()); } } } @@ -332,21 +334,21 @@ void CurveListPanel::refreshValues() break; } - if ( !is2ndColumnHidden() ) + if (!is2ndColumnHidden()) { const std::string& name = table->item(row, 0)->text().toStdString(); QString str_value = GetValue(name); - table->item(row, 1)->setText( str_value ); + table->item(row, 1)->setText(str_value); } } - if(_column_width_dirty) + if (_column_width_dirty) { _column_width_dirty = false; table->setViewResizeEnabled(true); } } //------------------------------------ - for (CurveTreeView* tree_view : {_tree_view}) + for (CurveTreeView* tree_view : { _tree_view }) { const int vertical_height = tree_view->visibleRegion().boundingRect().height(); @@ -366,10 +368,10 @@ void CurveListPanel::refreshValues() return; } - if ( !is2ndColumnHidden() ) + if (!is2ndColumnHidden()) { QString str_value = GetValue(curve_name.toStdString()); - cell->setText(1, str_value ); + cell->setText(1, str_value); } } }; @@ -384,16 +386,17 @@ QString StringifyArray(QString str) { static const QRegExp rx("(\\[\\d+\\])"); int pos = 0; - std::vector> index_positions; + std::vector> index_positions; - while ((pos = rx.indexIn(str, pos)) != -1) { + while ((pos = rx.indexIn(str, pos)) != -1) + { QString array_index = rx.cap(1); - std::pair index = {pos+1, array_index.size()-2}; + std::pair index = { pos + 1, array_index.size() - 2 }; index_positions.push_back(index); pos += rx.matchedLength(); } - if( index_positions.empty() ) + if (index_positions.empty()) { return str; } @@ -401,10 +404,10 @@ QString StringifyArray(QString str) QStringList out_list; out_list.push_back(str); - for(int i = index_positions.size()-1; i >= 0; i--) + for (int i = index_positions.size() - 1; i >= 0; i--) { - std::pair index = index_positions[i]; - str.remove( index.first, index.second ); + std::pair index = index_positions[i]; + str.remove(index.first, index.second); out_list.push_front(str); } @@ -416,10 +419,10 @@ QString CurveListPanel::getTreeName(QString name) auto parts = name.split('/', QString::SplitBehavior::SkipEmptyParts); QString out; - for(int i=0; i < parts.size(); i++) + for (int i = 0; i < parts.size(); i++) { out += StringifyArray(parts[i]); - if( i+1 < parts.size() ) + if (i + 1 < parts.size()) { out += "/"; } @@ -439,7 +442,8 @@ void CurveListPanel::on_lineEditFilter_textChanged(const QString& search_string) int item_count = h_c.second; int visible_count = item_count - h_c.first; - ui->labelNumberDisplayed->setText(QString::number(visible_count) + QString(" of ") + QString::number(item_count)); + ui->labelNumberDisplayed->setText(QString::number(visible_count) + QString(" of ") + + QString::number(item_count)); if (updated) { emit hiddenItemsChanged(); @@ -449,7 +453,8 @@ void CurveListPanel::on_lineEditFilter_textChanged(const QString& search_string) void CurveListPanel::removeSelectedCurves() { QMessageBox::StandardButton reply; - reply = QMessageBox::question(nullptr, tr("Warning"), tr("Do you really want to remove these data?\n"), + reply = QMessageBox::question(nullptr, tr("Warning"), + tr("Do you really want to remove these data?\n"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (reply == QMessageBox::Yes) @@ -487,14 +492,16 @@ void CurveListPanel::on_buttonAddCustom_clicked() on_lineEditFilter_textChanged(ui->lineEditFilter->text()); } -void CurveListPanel::onCustomSelectionChanged(const QItemSelection&, const QItemSelection&) +void CurveListPanel::onCustomSelectionChanged(const QItemSelection&, + const QItemSelection&) { - auto selected = _custom_view->getSelectedNames(); + auto selected = _custom_view->getSelectedNames(); bool enabled = (selected.size() == 1); ui->buttonEditCustom->setEnabled(enabled); ui->buttonEditCustom->setToolTip(enabled ? "Edit the selected custom timeserie" : - "Select a single custom Timeserie to Edit it"); + "Select a single custom Timeserie to Edit " + "it"); } void CurveListPanel::on_buttonEditCustom_clicked() @@ -508,10 +515,10 @@ void CurveListPanel::on_buttonEditCustom_clicked() std::vector CurveListPanel::getSelectedNames() const { - auto selected = _tree_view->getSelectedNames(); - auto custom_select = _custom_view->getSelectedNames(); - selected.insert( selected.end(), custom_select.begin(), custom_select.end() ); - return selected; + auto selected = _tree_view->getSelectedNames(); + auto custom_select = _custom_view->getSelectedNames(); + selected.insert(selected.end(), custom_select.begin(), custom_select.end()); + return selected; } void CurveListPanel::clearSelections() @@ -535,14 +542,14 @@ void CurveListPanel::on_checkBoxShowValues_toggled(bool show) emit hiddenItemsChanged(); } -void CurveListPanel::on_pushButtonTrash_clicked(bool ) +void CurveListPanel::on_pushButtonTrash_clicked(bool) { QMessageBox msgBox(this); msgBox.setWindowTitle("Warning. Can't be undone."); msgBox.setText(tr("Delete data:\n\n" "[Delete All]: remove timeseries and plots.\n" - "[Delete Points]: reset data points, but keep plots and timeseries.\n" - )); + "[Delete Points]: reset data points, but keep plots and " + "timeseries.\n")); QPushButton* buttonAll = msgBox.addButton(tr("Delete All"), QMessageBox::NoRole); QPushButton* buttonPoints = msgBox.addButton(tr("Delete Points"), QMessageBox::NoRole); msgBox.addButton(QMessageBox::Cancel); @@ -554,7 +561,8 @@ void CurveListPanel::on_pushButtonTrash_clicked(bool ) { requestDeleteAll(1); } - else if (msgBox.clickedButton() == buttonPoints) { + else if (msgBox.clickedButton() == buttonPoints) + { requestDeleteAll(2); } } diff --git a/plotjuggler_app/curvelist_panel.h b/plotjuggler_app/curvelist_panel.h index a995cfaad..5a90f7b59 100644 --- a/plotjuggler_app/curvelist_panel.h +++ b/plotjuggler_app/curvelist_panel.h @@ -25,14 +25,13 @@ class CurveListPanel : public QWidget public: explicit CurveListPanel(PlotDataMapRef& mapped_plot_data, - const TransformsMap& mapped_math_plots, - QWidget* parent); + const TransformsMap& mapped_math_plots, QWidget* parent); ~CurveListPanel() override; void clear(); - void addCurve(const std::string &plot_name); + void addCurve(const std::string& plot_name); void addCustom(const QString& item_name); @@ -53,7 +52,7 @@ class CurveListPanel : public QWidget virtual void keyPressEvent(QKeyEvent* event) override; void updateColors(); - + private slots: void on_lineEditFilter_textChanged(const QString& search_string); @@ -64,7 +63,8 @@ private slots: void on_buttonEditCustom_clicked(); - void onCustomSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); + void onCustomSelectionChanged(const QItemSelection& selected, + const QItemSelection& deselected); void on_checkBoxShowValues_toggled(bool show); @@ -81,7 +81,6 @@ public slots: void refreshValues(); protected: - private: Ui::CurveListPanel* ui; diff --git a/plotjuggler_app/curvelist_view.cpp b/plotjuggler_app/curvelist_view.cpp index 9a7af3129..4ff4e9017 100644 --- a/plotjuggler_app/curvelist_view.cpp +++ b/plotjuggler_app/curvelist_view.cpp @@ -7,7 +7,8 @@ #include #include "curvelist_panel.h" -CurveTableView::CurveTableView(CurveListPanel* parent) : QTableWidget(parent), CurvesView(parent) +CurveTableView::CurveTableView(CurveListPanel* parent) + : QTableWidget(parent), CurvesView(parent) { setColumnCount(2); setEditTriggers(NoEditTriggers); @@ -35,7 +36,8 @@ CurveTableView::CurveTableView(CurveListPanel* parent) : QTableWidget(parent), C setShowGrid(false); } -void CurveTableView::addItem(const QString &prefix, const QString& plot_name, const QString &plot_ID) +void CurveTableView::addItem(const QString& prefix, const QString& plot_name, + const QString& plot_ID) { if (_inserted_curves.contains(plot_ID)) { @@ -43,7 +45,7 @@ void CurveTableView::addItem(const QString &prefix, const QString& plot_name, co } QString row_name = prefix; - if( !prefix.isEmpty() && !prefix.endsWith('/')) + if (!prefix.isEmpty() && !prefix.endsWith('/')) { row_name += "/"; } @@ -104,7 +106,7 @@ void CurveTableView::refreshFontSize() cell = item(row, 1); font = QFontDatabase::systemFont(QFontDatabase::FixedFont); - font.setPointSize(_point_size - 2 ); + font.setPointSize(_point_size - 2); cell->setFont(font); } setViewResizeEnabled(true); @@ -194,7 +196,7 @@ void CurveTableView::hideValuesColumn(bool hide) } } -CurvesView::CurvesView(CurveListPanel *parent) : _parent_panel(parent) +CurvesView::CurvesView(CurveListPanel* parent) : _parent_panel(parent) { } @@ -214,7 +216,8 @@ bool CurvesView::eventFilterBase(QObject* object, QEvent* event) table_widget = qobject_cast(obj); } - bool ctrl_modifier_pressed = (QGuiApplication::keyboardModifiers() == Qt::ControlModifier); + bool ctrl_modifier_pressed = + (QGuiApplication::keyboardModifiers() == Qt::ControlModifier); if (event->type() == QEvent::MouseButtonPress) { @@ -242,7 +245,8 @@ bool CurvesView::eventFilterBase(QObject* object, QEvent* event) QMouseEvent* mouse_event = static_cast(event); double distance_from_click = (mouse_event->pos() - _drag_start_pos).manhattanLength(); - if ((mouse_event->buttons() == Qt::LeftButton || mouse_event->buttons() == Qt::RightButton) && + if ((mouse_event->buttons() == Qt::LeftButton || + mouse_event->buttons() == Qt::RightButton) && distance_from_click >= QApplication::startDragDistance() && !_dragging) { _dragging = true; @@ -312,11 +316,11 @@ bool CurvesView::eventFilterBase(QObject* object, QEvent* event) int prev_size = _point_size; if (wheel_event->delta() < 0) { - _point_size = std::max(8, prev_size-1); + _point_size = std::max(8, prev_size - 1); } else if (wheel_event->delta() > 0) { - _point_size = std::min(14, prev_size+1); + _point_size = std::min(14, prev_size + 1); } if (_point_size != prev_size) { diff --git a/plotjuggler_app/curvelist_view.h b/plotjuggler_app/curvelist_view.h index 0065c358a..052488166 100644 --- a/plotjuggler_app/curvelist_view.h +++ b/plotjuggler_app/curvelist_view.h @@ -35,7 +35,8 @@ class SortedTableItem : public Item std::string str; }; -enum CustomRoles{ +enum CustomRoles +{ Name = Qt::UserRole, IsGroupName = Qt::UserRole + 1, ToolTip = Qt::UserRole + 2 @@ -44,12 +45,12 @@ enum CustomRoles{ class CurvesView { public: - CurvesView(CurveListPanel* parent); virtual void clear() = 0; - virtual void addItem(const QString& prefix, const QString& tree_name, const QString &plot_ID) = 0; + virtual void addItem(const QString& prefix, const QString& tree_name, + const QString& plot_ID) = 0; virtual std::vector getSelectedNames() = 0; @@ -94,7 +95,8 @@ class CurveTableView : public QTableWidget, public CurvesView _inserted_curves.clear(); } - void addItem(const QString& prefix, const QString& tree_name, const QString &plot_ID) override; + void addItem(const QString& prefix, const QString& tree_name, + const QString& plot_ID) override; void refreshColumns() override; diff --git a/plotjuggler_app/curvetree_view.cpp b/plotjuggler_app/curvetree_view.cpp index 3716ae36c..683b05350 100644 --- a/plotjuggler_app/curvetree_view.cpp +++ b/plotjuggler_app/curvetree_view.cpp @@ -14,11 +14,13 @@ class TreeWidgetItem : public QTreeWidgetItem bool operator<(const QTreeWidgetItem& other) const { - return doj::alphanum_impl(this->text(0).toLocal8Bit(), other.text(0).toLocal8Bit()) < 0; + return doj::alphanum_impl(this->text(0).toLocal8Bit(), other.text(0).toLocal8Bit()) < + 0; } }; -CurveTreeView::CurveTreeView(CurveListPanel* parent) : QTreeWidget(parent), CurvesView(parent) +CurveTreeView::CurveTreeView(CurveListPanel* parent) + : QTreeWidget(parent), CurvesView(parent) { setColumnCount(2); setEditTriggers(NoEditTriggers); @@ -37,39 +39,42 @@ CurveTreeView::CurveTreeView(CurveListPanel* parent) : QTreeWidget(parent), Curv header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); - connect(this, &QTreeWidget::itemDoubleClicked, this, [this](QTreeWidgetItem *item, int column) - { - if( column == 0){ + connect(this, &QTreeWidget::itemDoubleClicked, this, + [this](QTreeWidgetItem* item, int column) { + if (column == 0) + { expandChildren(item); } }); - connect(selectionModel(), &QItemSelectionModel::selectionChanged, this, [this]() - { + connect(selectionModel(), &QItemSelectionModel::selectionChanged, this, [this]() { if (getSelectedNames().empty()) { // this looks nicer clearFocus(); setFocusPolicy(Qt::NoFocus); } - else { + else + { // this focus policy is needed to allow CurveListPanel::keyPressEvent to be called setFocusPolicy(Qt::ClickFocus); } }); } -void CurveTreeView::addItem(const QString &group_name, const QString& tree_name, const QString& plot_ID) +void CurveTreeView::addItem(const QString& group_name, const QString& tree_name, + const QString& plot_ID) { QSettings settings; bool use_separator = settings.value("Preferences::use_separator", true).toBool(); QStringList parts; - if( use_separator ) + if (use_separator) { parts = tree_name.split('/', QString::SplitBehavior::SkipEmptyParts); } - else{ + else + { parts.push_back(tree_name); } @@ -78,16 +83,15 @@ void CurveTreeView::addItem(const QString &group_name, const QString& tree_name, return; } - bool prefix_is_group = tree_name.startsWith( group_name ); + bool prefix_is_group = tree_name.startsWith(group_name); bool hasGroup = !group_name.isEmpty(); auto group_parts = group_name.split('/', QString::SplitBehavior::SkipEmptyParts); - if( hasGroup && !prefix_is_group ) + if (hasGroup && !prefix_is_group) { parts = group_parts + parts; } - QTreeWidgetItem* tree_parent = this->invisibleRootItem(); for (int i = 0; i < parts.size(); i++) @@ -117,11 +121,11 @@ void CurveTreeView::addItem(const QString &group_name, const QString& tree_name, child_item->setText(0, part); child_item->setText(1, is_leaf ? "-" : ""); - bool isGroupCell = ( i < group_parts.size() ); + bool isGroupCell = (i < group_parts.size()); QFont font = QFontDatabase::systemFont(QFontDatabase::GeneralFont); font.setPointSize(_point_size); - //font.setBold(isGroupCell); + // font.setBold(isGroupCell); child_item->setFont(0, font); font = QFontDatabase::systemFont(QFontDatabase::FixedFont); @@ -133,9 +137,10 @@ void CurveTreeView::addItem(const QString &group_name, const QString& tree_name, auto current_flag = child_item->flags(); - if( isGroupCell ){ + if (isGroupCell) + { child_item->setData(0, Name, group_name); - child_item->setData(0, IsGroupName, (i+1) == group_parts.size()); + child_item->setData(0, IsGroupName, (i + 1) == group_parts.size()); } if (is_leaf) @@ -259,19 +264,21 @@ bool CurveTreeView::applyVisibilityFilter(const QString& search_string) return updated; } -bool CurveTreeView::eventFilter(QObject *object, QEvent *event) +bool CurveTreeView::eventFilter(QObject* object, QEvent* event) { - if(event->type() == QEvent::MouseMove) + if (event->type() == QEvent::MouseMove) { - auto mouse_event = static_cast(event); - auto *item = itemAt(mouse_event->pos()); - if( item ){ + auto mouse_event = static_cast(event); + auto* item = itemAt(mouse_event->pos()); + if (item) + { auto tooltip = item->data(0, CustomRoles::ToolTip); - if( tooltip.isValid() ) + if (tooltip.isValid()) { - QToolTip::showText( mapToGlobal(mouse_event->pos()), tooltip.toString() ); + QToolTip::showText(mapToGlobal(mouse_event->pos()), tooltip.toString()); } - else{ + else + { QToolTip::hideText(); } } @@ -321,7 +328,7 @@ void CurveTreeView::removeCurve(const QString& to_be_deleted) void CurveTreeView::hideValuesColumn(bool hide) { setViewResizeEnabled(true); - setColumnHidden(1,hide); + setColumnHidden(1, hide); } void CurveTreeView::treeVisitor(std::function visitor) @@ -341,13 +348,15 @@ void CurveTreeView::treeVisitor(std::function visitor) } } -void CurveTreeView::expandChildren(QTreeWidgetItem *item) +void CurveTreeView::expandChildren(QTreeWidgetItem* item) { int childCount = item->childCount(); - for (int i = 0; i < childCount; i++) { + for (int i = 0; i < childCount; i++) + { const auto child = item->child(i); // Recursively call the function for each child node. - if( !child->isExpanded() && child->childCount() > 0 ){ + if (!child->isExpanded() && child->childCount() > 0) + { child->setExpanded(true); expandChildren(child); } diff --git a/plotjuggler_app/curvetree_view.h b/plotjuggler_app/curvetree_view.h index 5dbf8ab38..10a059365 100644 --- a/plotjuggler_app/curvetree_view.h +++ b/plotjuggler_app/curvetree_view.h @@ -17,7 +17,8 @@ class CurveTreeView : public QTreeWidget, public CurvesView _hidden_count = 0; } - void addItem(const QString& prefix, const QString& tree_name, const QString &plot_ID) override; + void addItem(const QString& prefix, const QString& tree_name, + const QString& plot_ID) override; void refreshColumns() override; @@ -37,19 +38,18 @@ class CurveTreeView : public QTreeWidget, public CurvesView } void setViewResizeEnabled(bool) override - { } + { + } virtual void hideValuesColumn(bool hide) override; void treeVisitor(std::function visitor); private: - - void expandChildren(QTreeWidgetItem *item); + void expandChildren(QTreeWidgetItem* item); int _hidden_count = 0; int _leaf_count = 0; - }; #endif // CURVETREE_VIEW_H diff --git a/plotjuggler_app/customtracker.cpp b/plotjuggler_app/customtracker.cpp index dcafcf2c7..5c9e2b7c0 100644 --- a/plotjuggler_app/customtracker.cpp +++ b/plotjuggler_app/customtracker.cpp @@ -117,7 +117,8 @@ void CurveTracker::setPosition(const QPointF& position) if (!_marker[i]->symbol() || _marker[i]->symbol()->brush().color() != color) { - QwtSymbol* sym = new QwtSymbol(QwtSymbol::Ellipse, color, QPen(Qt::black), QSize(5, 5)); + QwtSymbol* sym = + new QwtSymbol(QwtSymbol::Ellipse, color, QPen(Qt::black), QSize(5, 5)); _marker[i]->setSymbol(sym); } @@ -159,7 +160,10 @@ void CurveTracker::setPosition(const QPointF& position) while (whitespaces-- > 0) value.prepend(" "); - line = QString("%2 : %3").arg(color.name()).arg(value).arg(curve->title().text()); + line = QString("%2 : %3") + .arg(color.name()) + .arg(value) + .arg(curve->title().text()); } text_lines.insert(std::make_pair(val, line)); diff --git a/plotjuggler_app/dummy_data.cpp b/plotjuggler_app/dummy_data.cpp index 8d3a69354..32dc01dd1 100644 --- a/plotjuggler_app/dummy_data.cpp +++ b/plotjuggler_app/dummy_data.cpp @@ -45,21 +45,21 @@ void BuildDummyData(PlotDataMapRef& datamap) //------------------------------- auto tcGroup = datamap.getOrCreateGroup("myGroup/subGroup"); - tcGroup->setAttribute(PJ::TEXT_COLOR, QColor(Qt::blue) ); - tcGroup->setAttribute(PJ::TOOL_TIP, QString("This is a group") ); + tcGroup->setAttribute(PJ::TEXT_COLOR, QColor(Qt::blue)); + tcGroup->setAttribute(PJ::TOOL_TIP, QString("This is a group")); auto& tc_default = datamap.addNumeric("color/default", tcGroup)->second; auto& tc_red = datamap.addNumeric("color/red", tcGroup)->second; - tc_red.setAttribute(PJ::TEXT_COLOR, QColor(Qt::red) ); + tc_red.setAttribute(PJ::TEXT_COLOR, QColor(Qt::red)); PlotData& sin_plot = datamap.addNumeric("_sin")->second; PlotData& cos_plot = datamap.addNumeric("_cos")->second; StringSeries& str_plot = datamap.addStringSeries("str_value")->second; - sin_plot.setAttribute(PJ::TOOL_TIP, QString("sine") ); - cos_plot.setAttribute(PJ::TOOL_TIP, QString("cosine") ); - str_plot.setAttribute(PJ::TOOL_TIP, QString("this is a string") ); + sin_plot.setAttribute(PJ::TOOL_TIP, QString("sine")); + cos_plot.setAttribute(PJ::TOOL_TIP, QString("cosine")); + str_plot.setAttribute(PJ::TOOL_TIP, QString("this is a string")); sin_plot.setAttribute(PJ::ITALIC_FONTS, true); @@ -73,10 +73,17 @@ void BuildDummyData(PlotDataMapRef& datamap) tc_default.pushBack(PlotData::Point(t + 20, indx)); tc_default.pushBack(PlotData::Point(t + 20, indx)); - switch( indx%3 ){ - case 0: str_plot.pushBack( {t + 20, "Blue"} ); break; - case 1: str_plot.pushBack( {t + 20, "Red"} ); break; - case 2: str_plot.pushBack( {t + 20, "Green"} ); break; + switch (indx % 3) + { + case 0: + str_plot.pushBack({ t + 20, "Blue" }); + break; + case 1: + str_plot.pushBack({ t + 20, "Red" }); + break; + case 2: + str_plot.pushBack({ t + 20, "Green" }); + break; } } } diff --git a/plotjuggler_app/dummy_data.h b/plotjuggler_app/dummy_data.h index ccc5216f0..4e7933b06 100644 --- a/plotjuggler_app/dummy_data.h +++ b/plotjuggler_app/dummy_data.h @@ -5,4 +5,4 @@ void BuildDummyData(PJ::PlotDataMapRef& datamap); -#endif // DUMMY_DATA_H +#endif // DUMMY_DATA_H diff --git a/plotjuggler_app/main.cpp b/plotjuggler_app/main.cpp index 95d65c58d..9f68b5b6a 100644 --- a/plotjuggler_app/main.cpp +++ b/plotjuggler_app/main.cpp @@ -23,12 +23,13 @@ #include "nlohmann_parsers.h" #include "new_release_dialog.h" -static QString VERSION_STRING = QString("%1.%2.%3").arg(PJ_MAJOR_VERSION).arg(PJ_MINOR_VERSION).arg(PJ_PATCH_VERSION); +static QString VERSION_STRING = + QString("%1.%2.%3").arg(PJ_MAJOR_VERSION).arg(PJ_MINOR_VERSION).arg(PJ_PATCH_VERSION); inline int GetVersionNumber(QString str) { QStringList online_version = str.split('.'); - if( online_version.size() != 3 ) + if (online_version.size() != 3) { return 0; } @@ -52,7 +53,8 @@ void OpenNewReleaseDialog(QNetworkReply* reply) QString tag_name = data["tag_name"].toString(); QSettings settings; int online_number = GetVersionNumber(tag_name); - QString dont_show = settings.value("NewRelease/dontShowThisVersion", VERSION_STRING).toString(); + QString dont_show = + settings.value("NewRelease/dontShowThisVersion", VERSION_STRING).toString(); int dontshow_number = GetVersionNumber(dont_show); int current_number = GetVersionNumber(VERSION_STRING); @@ -66,7 +68,7 @@ void OpenNewReleaseDialog(QNetworkReply* reply) QPixmap getFunnySplashscreen() { QSettings settings; - srand (time(nullptr)); + srand(time(nullptr)); auto getNum = []() { const int last_image_num = 60; @@ -88,13 +90,13 @@ QPixmap getFunnySplashscreen() return QPixmap(filename); } - -std::pair MergeArguments(int argc, char* argv[]) +std::pair MergeArguments(int argc, char* argv[]) { - #ifdef PJ_DEFAULT_ARGS - auto default_cmdline_args = QString( PJ_DEFAULT_ARGS ).split(" ", QString::SkipEmptyParts); +#ifdef PJ_DEFAULT_ARGS + auto default_cmdline_args = + QString(PJ_DEFAULT_ARGS).split(" ", QString::SkipEmptyParts); int new_argc = argc + default_cmdline_args.size(); - static char *new_argv[100]; + static char* new_argv[100]; // preserve arg[0] => executable path new_argv[0] = argv[0]; @@ -105,28 +107,29 @@ std::pair MergeArguments(int argc, char* argv[]) // _0x20_ --> ' ' (space) // _0x3b_ --> ';' (semicolon) int index = 1; - for ( auto cmdline_arg : default_cmdline_args ) + for (auto cmdline_arg : default_cmdline_args) { - // replace(const QString &before, const QString &after, Qt::CaseSensitivity cs = Qt::CaseSensitive) + // replace(const QString &before, const QString &after, Qt::CaseSensitivity cs = + // Qt::CaseSensitive) cmdline_arg = cmdline_arg.replace("_0x20_", " ", Qt::CaseSensitive); cmdline_arg = cmdline_arg.replace("_0x3b_", ";", Qt::CaseSensitive); new_argv[index++] = strdup(cmdline_arg.toLocal8Bit().data()); } - // If an argument appears repeated, the second value overrides previous one. + // If an argument appears repeated, the second value overrides previous one. // Do this after adding default_cmdline_args so the command-line overide default - for (int i=1; i< argc; ++i ) { + for (int i = 1; i < argc; ++i) + { new_argv[index++] = argv[i]; } - return {new_argc, new_argv}; + return { new_argc, new_argv }; #else - return {argc, argv}; + return { argc, argv }; #endif } - int main(int argc, char* argv[]) { auto arg = MergeArguments(argc, argv); @@ -138,11 +141,12 @@ int main(int argc, char* argv[]) QSettings settings; - if( !settings.isWritable() ) + if (!settings.isWritable()) { - qDebug() << "ERROR: the file [" << settings.fileName() << - "] is not writable. This may happen when you run PlotJuggler with sudo. " - "Change the permissions of the file (\"sudo chmod 666 \"on linux)"; + qDebug() << "ERROR: the file [" << settings.fileName() + << "] is not writable. This may happen when you run PlotJuggler with sudo. " + "Change the permissions of the file (\"sudo chmod 666 \"on " + "linux)"; } app.setApplicationVersion(VERSION_STRING); @@ -157,7 +161,8 @@ int main(int argc, char* argv[]) //--------------------------- QCommandLineParser parser; - parser.setApplicationDescription("PlotJuggler: the time series visualization tool that you deserve "); + parser.setApplicationDescription("PlotJuggler: the time series visualization tool that " + "you deserve "); parser.addVersionOption(); parser.addHelpOption(); @@ -178,48 +183,68 @@ int main(int argc, char* argv[]) QCommandLineOption layout_option(QStringList() << "l" << "layout", - "Load a file containing the layout configuration", "file_path"); + "Load a file containing the layout configuration", + "file_path"); parser.addOption(layout_option); QCommandLineOption publish_option(QStringList() << "p" << "publish", - "Automatically start publisher when loading the layout file"); + "Automatically start publisher when loading the " + "layout file"); parser.addOption(publish_option); QCommandLineOption folder_option(QStringList() << "plugin_folders", - "Add semicolon-separated list of folders where you should look " + "Add semicolon-separated list of folders where you " + "should look " "for additional plugins.", "directory_paths"); parser.addOption(folder_option); - QCommandLineOption buffersize_option( - QStringList() << "buffer_size", - QCoreApplication::translate("main", "Change the maximum size of the streaming " - "buffer (minimum: 10 default: 60)"), - QCoreApplication::translate("main", "seconds")); + QCommandLineOption buffersize_option(QStringList() << "buffer_size", + QCoreApplication::translate("main", "Change the " + "maximum size " + "of the " + "streaming " + "buffer " + "(minimum: 10 " + "default: " + "60)"), + QCoreApplication::translate("main", "seconds")); parser.addOption(buffersize_option); - QCommandLineOption nogl_option(QStringList() << "disable_opengl", - "Disable OpenGL display before starting the application. " - "You can enable it again in the 'Preferences' menu."); + QCommandLineOption nogl_option(QStringList() << "disable_opengl", "Disable OpenGL " + "display before " + "starting the " + "application. " + "You can enable it " + "again in the " + "'Preferences' " + "menu."); parser.addOption(nogl_option); QCommandLineOption enabled_plugins_option(QStringList() << "enabled_plugins", - "Limit the loaded plugins to ones in the semicolon-separated list", "name_list"); + "Limit the loaded plugins to ones in the " + "semicolon-separated list", + "name_list"); parser.addOption(enabled_plugins_option); QCommandLineOption disabled_plugins_option(QStringList() << "disabled_plugins", - "Do not load any of the plugins in the semicolon separated list", "name_list"); + "Do not load any of the plugins in the " + "semicolon separated list", + "name_list"); parser.addOption(disabled_plugins_option); QCommandLineOption skin_path_option(QStringList() << "skin_path", - "New \"skin\". Refer to the sample in [plotjuggler_app/resources/skin]", "path to folder"); + "New \"skin\". Refer to the sample in " + "[plotjuggler_app/resources/skin]", + "path to folder"); parser.addOption(skin_path_option); QCommandLineOption start_streamer(QStringList() << "start_streamer", - "Automatically start a Streaming Plugin with the give filename", + "Automatically start a Streaming Plugin with the " + "give filename", "file_name (no extension)"); parser.addOption(start_streamer); @@ -227,14 +252,18 @@ int main(int argc, char* argv[]) if (parser.isSet(publish_option) && !parser.isSet(layout_option)) { - std::cerr << "Option [ -p / --publish ] is invalid unless [ -l / --layout ] is used too." << std::endl; + std::cerr << "Option [ -p / --publish ] is invalid unless [ -l / --layout ] is used " + "too." + << std::endl; return -1; } if (parser.isSet(enabled_plugins_option) && parser.isSet(disabled_plugins_option)) { - std::cerr << "Option [ --enabled_plugins ] and [ --disabled_plugins ] can't be used together." << std::endl; - return -1; + std::cerr << "Option [ --enabled_plugins ] and [ --disabled_plugins ] can't be used " + "together." + << std::endl; + return -1; } if (parser.isSet(nogl_option)) @@ -244,9 +273,10 @@ int main(int argc, char* argv[]) if (parser.isSet(skin_path_option)) { - QDir path( parser.value(skin_path_option ) ); - if( !path.exists() ) { - qDebug() << "Skin path [" << parser.value(skin_path_option) << "] not found"; + QDir path(parser.value(skin_path_option)); + if (!path.exists()) + { + qDebug() << "Skin path [" << parser.value(skin_path_option) << "] not found"; return -1; } } @@ -258,10 +288,10 @@ int main(int argc, char* argv[]) QObject::connect(&manager, &QNetworkAccessManager::finished, OpenNewReleaseDialog); QNetworkRequest request; - request.setUrl(QUrl("https://api.github.com/repos/facontidavide/PlotJuggler/releases/latest")); + request.setUrl(QUrl("https://api.github.com/repos/facontidavide/PlotJuggler/releases/" + "latest")); manager.get(request); - MainWindow* w = nullptr; /* @@ -273,26 +303,28 @@ int main(int argc, char* argv[]) * The splashscreen is the connection between me and my users, the glue that keeps * together our invisible relationship. * Now, it is up to you to decide: you can block the splashscreen forever or not, - * reject a message that brings a little of happiness into your day, spent analyzing data. - * Please don't do it. + * reject a message that brings a little of happiness into your day, spent analyzing + * data. Please don't do it. */ if (!parser.isSet(nosplash_option) && - !(parser.isSet(loadfile_option) || parser.isSet(layout_option)) ) + !(parser.isSet(loadfile_option) || parser.isSet(layout_option))) // if(false) // if you uncomment this line, a kitten will die somewhere in the world. { QPixmap main_pixmap; if (parser.isSet(skin_path_option)) { - QDir path( parser.value(skin_path_option ) ); - QFile splash = path.filePath( "pj_splashscreen.png"); - if( splash.exists() ){ - main_pixmap = QPixmap( splash.fileName() ); + QDir path(parser.value(skin_path_option)); + QFile splash = path.filePath("pj_splashscreen.png"); + if (splash.exists()) + { + main_pixmap = QPixmap(splash.fileName()); } } - if( main_pixmap.isNull() ){ + if (main_pixmap.isNull()) + { main_pixmap = getFunnySplashscreen(); } QSplashScreen splash(main_pixmap, Qt::WindowStaysOnTopHint); @@ -318,15 +350,16 @@ int main(int argc, char* argv[]) app.processEvents(); } } - else{ + else + { w = new MainWindow(parser); } w->show(); - if ( parser.isSet(start_streamer)) + if (parser.isSet(start_streamer)) { - w->on_buttonStreamingStart_clicked(); + w->on_buttonStreamingStart_clicked(); } return app.exec(); diff --git a/plotjuggler_app/mainwindow.cpp b/plotjuggler_app/mainwindow.cpp index b4fe05a00..47ffcf705 100644 --- a/plotjuggler_app/mainwindow.cpp +++ b/plotjuggler_app/mainwindow.cpp @@ -58,8 +58,6 @@ #include #endif - - MainWindow::MainWindow(const QCommandLineParser& commandline_parser, QWidget* parent) : QMainWindow(parent) , ui(new Ui::MainWindow) @@ -69,32 +67,35 @@ MainWindow::MainWindow(const QCommandLineParser& commandline_parser, QWidget* pa , _streaming_shortcut(QKeySequence(Qt::CTRL + Qt::Key_Space), this) , _playback_shotcut(Qt::Key_Space, this) , _minimized(false) - , _message_parser_factory( new MessageParserFactory ) + , _message_parser_factory(new MessageParserFactory) , _active_streamer_plugin(nullptr) , _disable_undo_logging(false) , _tracker_time(0) , _tracker_param(CurveTracker::VALUE) , _labels_status(LabelStatus::RIGHT) , _recent_data_files(new QMenu()) - ,_recent_layout_files(new QMenu()) + , _recent_layout_files(new QMenu()) { QLocale::setDefault(QLocale::c()); // set as default _test_option = commandline_parser.isSet("test"); _autostart_publishers = commandline_parser.isSet("publish"); - if ( commandline_parser.isSet("enabled_plugins")) + if (commandline_parser.isSet("enabled_plugins")) { - _enabled_plugins = commandline_parser.value("enabled_plugins").split(";", QString::SkipEmptyParts); - // Treat the command-line parameter '--enabled_plugins *' to mean all plugings are enabled - if ( (_enabled_plugins.size() == 1) && (_enabled_plugins.contains("*")) ) + _enabled_plugins = + commandline_parser.value("enabled_plugins").split(";", QString::SkipEmptyParts); + // Treat the command-line parameter '--enabled_plugins *' to mean all plugings are + // enabled + if ((_enabled_plugins.size() == 1) && (_enabled_plugins.contains("*"))) { _enabled_plugins.clear(); } } - if ( commandline_parser.isSet("disabled_plugins")) + if (commandline_parser.isSet("disabled_plugins")) { - _disabled_plugins = commandline_parser.value("disabled_plugins").split(";", QString::SkipEmptyParts); + _disabled_plugins = + commandline_parser.value("disabled_plugins").split(";", QString::SkipEmptyParts); } _curvelist_widget = new CurveListPanel(_mapped_plot_data, _transform_functions, this); @@ -102,17 +103,18 @@ MainWindow::MainWindow(const QCommandLineParser& commandline_parser, QWidget* pa ui->setupUi(this); // setupUi() sets the windowTitle so the skin-based setting must be done after - _skin_path ="://resources/skin"; - if( commandline_parser.isSet("skin_path") ) + _skin_path = "://resources/skin"; + if (commandline_parser.isSet("skin_path")) { - QDir path( commandline_parser.value("skin_path") ); - if( path.exists() ) + QDir path(commandline_parser.value("skin_path")); + if (path.exists()) { _skin_path = path.absolutePath(); } } - QFile fileTitle( _skin_path + "/mainwindow_title.txt"); - if(fileTitle.open(QIODevice::ReadOnly)) { + QFile fileTitle(_skin_path + "/mainwindow_title.txt"); + if (fileTitle.open(QIODevice::ReadOnly)) + { QString title = fileTitle.readAll().trimmed(); setWindowTitle(title); } @@ -139,24 +141,20 @@ MainWindow::MainWindow(const QCommandLineParser& commandline_parser, QWidget* pa _animated_streaming_movie = new QMovie(":/resources/animated_radio.gif"); _animated_streaming_movie->setScaledSize(ui->labelStreamingAnimation->size()); - _animated_streaming_movie->jumpToFrame( 0 ); + _animated_streaming_movie->jumpToFrame(0); _animated_streaming_timer = new QTimer(); _animated_streaming_timer->setSingleShot(true); - connect( _animated_streaming_timer, &QTimer::timeout, - this, [this]() - { + connect(_animated_streaming_timer, &QTimer::timeout, this, [this]() { _animated_streaming_movie->stop(); - _animated_streaming_movie->jumpToFrame( 0 ); + _animated_streaming_movie->jumpToFrame(0); }); _tracker_delaty_timer = new QTimer(); _tracker_delaty_timer->setSingleShot(true); - connect( _tracker_delaty_timer, &QTimer::timeout, - this, [this]() - { + connect(_tracker_delaty_timer, &QTimer::timeout, this, [this]() { updatedDisplayTime(); onUpdateLeftTableValues(); }); @@ -164,69 +162,70 @@ MainWindow::MainWindow(const QCommandLineParser& commandline_parser, QWidget* pa ui->labelStreamingAnimation->setMovie(_animated_streaming_movie); ui->labelStreamingAnimation->setHidden(true); - connect(this, &MainWindow::stylesheetChanged, - this, &MainWindow::on_stylesheetChanged); + connect(this, &MainWindow::stylesheetChanged, this, &MainWindow::on_stylesheetChanged); - connect(this, &MainWindow::stylesheetChanged, - _curvelist_widget, &CurveListPanel::on_stylesheetChanged); + connect(this, &MainWindow::stylesheetChanged, _curvelist_widget, + &CurveListPanel::on_stylesheetChanged); - connect(_curvelist_widget, &CurveListPanel::hiddenItemsChanged, - this, &MainWindow::onUpdateLeftTableValues); + connect(_curvelist_widget, &CurveListPanel::hiddenItemsChanged, this, + &MainWindow::onUpdateLeftTableValues); - connect(_curvelist_widget, &CurveListPanel::deleteCurves, - this, &MainWindow::onDeleteMultipleCurves); + connect(_curvelist_widget, &CurveListPanel::deleteCurves, this, + &MainWindow::onDeleteMultipleCurves); - connect(_curvelist_widget, &CurveListPanel::createMathPlot, - this, &MainWindow::onAddCustomPlot); + connect(_curvelist_widget, &CurveListPanel::createMathPlot, this, + &MainWindow::onAddCustomPlot); - connect(_curvelist_widget, &CurveListPanel::editMathPlot, - this, &MainWindow::onEditCustomPlot); + connect(_curvelist_widget, &CurveListPanel::editMathPlot, this, + &MainWindow::onEditCustomPlot); - connect(_curvelist_widget, &CurveListPanel::refreshMathPlot, - this, &MainWindow::onRefreshCustomPlot); + connect(_curvelist_widget, &CurveListPanel::refreshMathPlot, this, + &MainWindow::onRefreshCustomPlot); - connect(ui->timeSlider, &RealSlider::realValueChanged, - this, &MainWindow::onTimeSlider_valueChanged); + connect(ui->timeSlider, &RealSlider::realValueChanged, this, + &MainWindow::onTimeSlider_valueChanged); - connect(ui->playbackRate, &QDoubleSpinBox::editingFinished, - this, [this]() { ui->playbackRate->clearFocus(); }); + connect(ui->playbackRate, &QDoubleSpinBox::editingFinished, this, + [this]() { ui->playbackRate->clearFocus(); }); - connect(ui->playbackStep, &QDoubleSpinBox::editingFinished, - this, [this]() { ui->playbackStep->clearFocus(); }); + connect(ui->playbackStep, &QDoubleSpinBox::editingFinished, this, + [this]() { ui->playbackStep->clearFocus(); }); - connect(_curvelist_widget, &CurveListPanel::requestDeleteAll, - this, [this](int option) - { - if( option == 1) { + connect(_curvelist_widget, &CurveListPanel::requestDeleteAll, this, [this](int option) { + if (option == 1) + { deleteAllData(); } - else if( option == 2) { + else if (option == 2) + { on_actionClearBuffer_triggered(); } }); - _main_tabbed_widget = new TabbedPlotWidget("Main Window", - this, _mapped_plot_data, this); + _main_tabbed_widget = + new TabbedPlotWidget("Main Window", this, _mapped_plot_data, this); connect(this, &MainWindow::stylesheetChanged, _main_tabbed_widget, &TabbedPlotWidget::on_stylesheetChanged); ui->plottingLayout->insertWidget(0, _main_tabbed_widget, 1); - ui->leftLayout->addWidget(_curvelist_widget,1); + ui->leftLayout->addWidget(_curvelist_widget, 1); ui->mainSplitter->setCollapsible(0, true); ui->mainSplitter->setStretchFactor(0, 2); ui->mainSplitter->setStretchFactor(1, 6); - ui->layoutTimescale->removeWidget( ui->widgetButtons ); - _main_tabbed_widget->tabWidget()->setCornerWidget( ui->widgetButtons ); + ui->layoutTimescale->removeWidget(ui->widgetButtons); + _main_tabbed_widget->tabWidget()->setCornerWidget(ui->widgetButtons); - connect(ui->mainSplitter, SIGNAL(splitterMoved(int, int)), SLOT(on_splitterMoved(int, int))); + connect(ui->mainSplitter, SIGNAL(splitterMoved(int, int)), + SLOT(on_splitterMoved(int, int))); initializeActions(); //------------ Load plugins ------------- - auto plugin_extra_folders = commandline_parser.value("plugin_folders").split(";", QString::SkipEmptyParts); + auto plugin_extra_folders = + commandline_parser.value("plugin_folders").split(";", QString::SkipEmptyParts); _default_streamer = commandline_parser.value("start_streamer"); @@ -240,7 +239,8 @@ MainWindow::MainWindow(const QCommandLineParser& commandline_parser, QWidget* pa onUndoableChange(); _replot_timer = new QTimer(this); - connect(_replot_timer, &QTimer::timeout, this, [this]() { updateDataAndReplot(false); }); + connect(_replot_timer, &QTimer::timeout, this, + [this]() { updateDataAndReplot(false); }); _publish_timer = new QTimer(this); _publish_timer->setInterval(20); @@ -270,18 +270,19 @@ MainWindow::MainWindow(const QCommandLineParser& commandline_parser, QWidget* pa restoreGeometry(settings.value("MainWindow.geometry").toByteArray()); restoreState(settings.value("MainWindow.state").toByteArray()); - //qDebug() << "restoreGeometry"; + // qDebug() << "restoreGeometry"; bool activate_grid = settings.value("MainWindow.activateGrid", false).toBool(); ui->pushButtonActivateGrid->setChecked(activate_grid); - bool zoom_link_active = settings.value("MainWindow.buttonLink",true).toBool(); + bool zoom_link_active = settings.value("MainWindow.buttonLink", true).toBool(); ui->pushButtonLink->setChecked(zoom_link_active); - bool ration_active = settings.value("MainWindow.buttonRatio",true).toBool(); + bool ration_active = settings.value("MainWindow.buttonRatio", true).toBool(); ui->pushButtonRatio->setChecked(ration_active); - int streaming_buffer_value = settings.value("MainWindow.streamingBufferValue", 5).toInt(); + int streaming_buffer_value = + settings.value("MainWindow.streamingBufferValue", 5).toInt(); ui->streamingSpinBox->setValue(streaming_buffer_value); bool datetime_display = settings.value("MainWindow.dateTimeDisplay", false).toBool(); @@ -292,17 +293,17 @@ MainWindow::MainWindow(const QCommandLineParser& commandline_parser, QWidget* pa // ui->widgetOptions->setVisible(ui->pushButtonOptions->isChecked()); - if( settings.value("MainWindow.hiddenFileFrame", false).toBool() ) + if (settings.value("MainWindow.hiddenFileFrame", false).toBool()) { ui->buttonHideFileFrame->setText("+"); ui->frameFile->setHidden(true); } - if( settings.value("MainWindow.hiddenStreamingFrame", false).toBool() ) + if (settings.value("MainWindow.hiddenStreamingFrame", false).toBool()) { ui->buttonHideStreamingFrame->setText("+"); ui->frameStreaming->setHidden(true); } - if( settings.value("MainWindow.hiddenPublishersFrame", false).toBool() ) + if (settings.value("MainWindow.hiddenPublishersFrame", false).toBool()) { ui->buttonHidePublishersFrame->setText("+"); ui->framePublishers->setHidden(true); @@ -319,7 +320,8 @@ MainWindow::MainWindow(const QCommandLineParser& commandline_parser, QWidget* pa _tracker_button_icons[CurveTracker::VALUE] = trackerIconB; _tracker_button_icons[CurveTracker::VALUE_NAME] = trackerIconC; - int tracker_setting = settings.value("MainWindow.timeTrackerSetting", (int)CurveTracker::VALUE).toInt(); + int tracker_setting = + settings.value("MainWindow.timeTrackerSetting", (int)CurveTracker::VALUE).toInt(); _tracker_param = static_cast(tracker_setting); ui->pushButtonTimeTracker->setIcon(_tracker_button_icons[_tracker_param]); @@ -329,39 +331,40 @@ MainWindow::MainWindow(const QCommandLineParser& commandline_parser, QWidget* pa auto editor_layout = new QVBoxLayout(); editor_layout->setMargin(0); ui->formulaPage->setLayout(editor_layout); - _function_editor = new FunctionEditorWidget( _mapped_plot_data, _transform_functions, this); + _function_editor = + new FunctionEditorWidget(_mapped_plot_data, _transform_functions, this); editor_layout->addWidget(_function_editor); - connect(_function_editor, &FunctionEditorWidget::closed, - this, [this]() { - ui->widgetStack->setCurrentIndex(0); - }); + connect(_function_editor, &FunctionEditorWidget::closed, this, + [this]() { ui->widgetStack->setCurrentIndex(0); }); - connect(this, &MainWindow::stylesheetChanged, - _function_editor, &FunctionEditorWidget::on_stylesheetChanged); + connect(this, &MainWindow::stylesheetChanged, _function_editor, + &FunctionEditorWidget::on_stylesheetChanged); - connect(_function_editor, &FunctionEditorWidget::accept, - this, &MainWindow::onCustomPlotCreated); + connect(_function_editor, &FunctionEditorWidget::accept, this, + &MainWindow::onCustomPlotCreated); QString theme = settings.value("Preferences::theme", "light").toString(); - if( theme != "dark") { + if (theme != "dark") + { theme = "light"; } loadStyleSheet(tr(":/resources/stylesheet_%1.qss").arg(theme)); // builtin messageParsers - _message_parser_factory->insert( {"JSON", std::make_shared() }); - _message_parser_factory->insert( {"CBOR", std::make_shared() }); - _message_parser_factory->insert( {"BSON", std::make_shared() }); - _message_parser_factory->insert( {"MessagePack", std::make_shared() }); + _message_parser_factory->insert({ "JSON", std::make_shared() }); + _message_parser_factory->insert({ "CBOR", std::make_shared() }); + _message_parser_factory->insert({ "BSON", std::make_shared() }); + _message_parser_factory->insert( + { "MessagePack", std::make_shared() }); - if( !_default_streamer.isEmpty() ) + if (!_default_streamer.isEmpty()) { - auto index = ui->comboStreaming->findText( _default_streamer ); - if( index != -1) + auto index = ui->comboStreaming->findText(_default_streamer); + if (index != -1) { - ui->comboStreaming->setCurrentIndex( index ); - settings.setValue("MainWindow.previousStreamingPlugin", _default_streamer ); + ui->comboStreaming->setCurrentIndex(index); + settings.setValue("MainWindow.previousStreamingPlugin", _default_streamer); } } } @@ -392,7 +395,7 @@ void MainWindow::onUndoableChange() _undo_states.pop_front(); _undo_states.push_back(xmlSaveState()); _redo_states.clear(); - //qDebug() << "undo " << _undo_states.size(); + // qDebug() << "undo " << _undo_states.size(); } void MainWindow::onRedoInvoked() @@ -408,7 +411,7 @@ void MainWindow::onRedoInvoked() xmlLoadState(state_document); } - //qDebug() << "undo " << _undo_states.size(); + // qDebug() << "undo " << _undo_states.size(); _disable_undo_logging = false; } @@ -426,7 +429,7 @@ void MainWindow::onUndoInvoked() xmlLoadState(state_document); } - //qDebug() << "undo " << _undo_states.size(); + // qDebug() << "undo " << _undo_states.size(); _disable_undo_logging = false; } @@ -453,10 +456,10 @@ void MainWindow::onTimeSlider_valueChanged(double abs_time) } void MainWindow::onTrackerTimeUpdated(double absolute_time, bool do_replot) -{ - if( !_tracker_delaty_timer->isActive() ) +{ + if (!_tracker_delaty_timer->isActive()) { - _tracker_delaty_timer->start( 100 ); // 10 Hz at most + _tracker_delaty_timer->start(100); // 10 Hz at most } for (auto& it : _state_publisher) @@ -481,9 +484,12 @@ void MainWindow::initializeActions() connect(&_undo_shortcut, &QShortcut::activated, this, &MainWindow::onUndoInvoked); connect(&_redo_shortcut, &QShortcut::activated, this, &MainWindow::onRedoInvoked); - connect(&_streaming_shortcut, &QShortcut::activated, this, &MainWindow::on_streamingToggled); - connect(&_playback_shotcut, &QShortcut::activated, ui->pushButtonPlay, &QPushButton::toggle); - connect(&_fullscreen_shortcut, &QShortcut::activated, this, &MainWindow::onActionFullscreenTriggered); + connect(&_streaming_shortcut, &QShortcut::activated, this, + &MainWindow::on_streamingToggled); + connect(&_playback_shotcut, &QShortcut::activated, ui->pushButtonPlay, + &QPushButton::toggle); + connect(&_fullscreen_shortcut, &QShortcut::activated, this, + &MainWindow::onActionFullscreenTriggered); QShortcut* open_menu_shortcut = new QShortcut(QKeySequence(Qt::ALT + Qt::Key_F), this); connect(open_menu_shortcut, &QShortcut::activated, @@ -496,8 +502,10 @@ void MainWindow::initializeActions() //--------------------------------------------- QSettings settings; - updateRecentDataMenu(settings.value("MainWindow.recentlyLoadedDatafile").toStringList()); - updateRecentLayoutMenu(settings.value("MainWindow.recentlyLoadedLayout").toStringList()); + updateRecentDataMenu( + settings.value("MainWindow.recentlyLoadedDatafile").toStringList()); + updateRecentLayoutMenu( + settings.value("MainWindow.recentlyLoadedLayout").toStringList()); } void MainWindow::loadAllPlugins(QStringList command_line_plugin_folders) @@ -508,46 +516,55 @@ void MainWindow::loadAllPlugins(QStringList command_line_plugin_folders) QStringList builtin_folders; plugin_folders += command_line_plugin_folders; - plugin_folders += settings.value("Preferences::plugin_folders", QStringList()).toStringList(); + plugin_folders += + settings.value("Preferences::plugin_folders", QStringList()).toStringList(); builtin_folders += QCoreApplication::applicationDirPath(); - try { + try + { #ifdef COMPILED_WITH_CATKIN builtin_folders += QCoreApplication::applicationDirPath() + "_ros"; - const char * env = std::getenv("CMAKE_PREFIX_PATH"); - if (env) { - QString env_catkin_paths = QString::fromStdString( env ); - env_catkin_paths.replace(";",":"); // for windows + const char* env = std::getenv("CMAKE_PREFIX_PATH"); + if (env) + { + QString env_catkin_paths = QString::fromStdString(env); + env_catkin_paths.replace(";", ":"); // for windows auto catkin_paths = env_catkin_paths.split(":"); - for(const auto& path: catkin_paths) + for (const auto& path : catkin_paths) { builtin_folders += path + "/lib/plotjuggler_ros"; } } #endif #ifdef COMPILED_WITH_AMENT - auto ros2_path = QString::fromStdString(ament_index_cpp::get_package_prefix("plotjuggler_ros")); + auto ros2_path = QString::fromStdString(ament_index_cpp::get_package_prefix("plotjugg" + "ler_" + "ros")); ros2_path += "/lib/plotjuggler_ros"; loaded += initializePlugins(ros2_path); #endif - } catch (...) { - + } + catch (...) + { QMessageBox::warning(nullptr, "Missing package [plotjuggler-ros]", - "If you just upgraded from PlotJuggler 2.x to 3.x , try installing this package:\n\n" + "If you just upgraded from PlotJuggler 2.x to 3.x , try " + "installing this package:\n\n" "sudo apt install ros-${ROS_DISTRO}-plotjuggler-ros", QMessageBox::Cancel, QMessageBox::Cancel); } - builtin_folders += QStandardPaths::writableLocation( QStandardPaths::GenericDataLocation) + "/PlotJuggler"; + builtin_folders += + QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/PlotJuggl" + "er"; builtin_folders.removeDuplicates(); plugin_folders += builtin_folders; plugin_folders.removeDuplicates(); - for(const auto& folder: plugin_folders) + for (const auto& folder : plugin_folders) { loaded += initializePlugins(folder); } @@ -568,7 +585,8 @@ QStringList MainWindow::initializePlugins(QString directory_name) for (const QString& filename : pluginsDir.entryList(QDir::Files)) { QFileInfo fileinfo(filename); - if (fileinfo.suffix() != "so" && fileinfo.suffix() != "dll" && fileinfo.suffix() != "dylib") + if (fileinfo.suffix() != "so" && fileinfo.suffix() != "dll" && + fileinfo.suffix() != "dylib") { continue; } @@ -584,52 +602,59 @@ QStringList MainWindow::initializePlugins(QString directory_name) if (plugin) { auto class_name = pluginLoader.metaData().value("className").toString(); - loaded_out.push_back( class_name ); + loaded_out.push_back(class_name); DataLoader* loader = qobject_cast(plugin); StatePublisher* publisher = qobject_cast(plugin); DataStreamer* streamer = qobject_cast(plugin); - MessageParserCreator* message_parser = qobject_cast(plugin); + MessageParserCreator* message_parser = qobject_cast(plugin); ToolboxPlugin* toolbox = qobject_cast(plugin); QString plugin_name; QString plugin_type; bool is_debug_plugin = dynamic_cast(plugin)->isDebugPlugin(); - if (loader){ + if (loader) + { plugin_name = loader->name(); plugin_type = "DataLoader"; } - else if (publisher){ + else if (publisher) + { plugin_name = publisher->name(); plugin_type = "StatePublisher"; } - else if (streamer){ + else if (streamer) + { plugin_name = streamer->name(); plugin_type = "DataStreamer"; } - else if (message_parser){ + else if (message_parser) + { plugin_name = message_parser->name(); plugin_type = "MessageParser"; } - else if (toolbox){ + else if (toolbox) + { plugin_name = toolbox->name(); plugin_type = "MessageParser"; } QString message = QString("%1 is a %2 plugin").arg(filename).arg(plugin_type); - if ( (_enabled_plugins.size() > 0) && (_enabled_plugins.contains(fileinfo.baseName()) == false) ) + if ((_enabled_plugins.size() > 0) && + (_enabled_plugins.contains(fileinfo.baseName()) == false)) { qDebug() << message << " ...skipping, because it is not explicitly enabled"; continue; } - if ( (_disabled_plugins.size() > 0) && (_disabled_plugins.contains(fileinfo.baseName()) == true) ) + if ((_disabled_plugins.size() > 0) && + (_disabled_plugins.contains(fileinfo.baseName()) == true)) { qDebug() << message << " ...skipping, because it is explicitly disabled"; continue; } - if ( !_test_option && is_debug_plugin ) + if (!_test_option && is_debug_plugin) { qDebug() << message << " ...disabled, unless option -t is used"; continue; @@ -662,119 +687,109 @@ QStringList MainWindow::initializePlugins(QString directory_name) auto start_checkbox = new QCheckBox(ui->framePublishers); ui->layoutPublishers->addWidget(start_checkbox, row, 1); - start_checkbox->setFocusPolicy( Qt::FocusPolicy::NoFocus ); + start_checkbox->setFocusPolicy(Qt::FocusPolicy::NoFocus); connect(start_checkbox, &QCheckBox::toggled, this, [=](bool enable) { publisher->setEnabled(enable); }); - connect(publisher, &StatePublisher::closed, - start_checkbox, [=]() {start_checkbox->setChecked(false);} ); + connect(publisher, &StatePublisher::closed, start_checkbox, + [=]() { start_checkbox->setChecked(false); }); - if( publisher->availableActions().empty() ) + if (publisher->availableActions().empty()) { QFrame* empty = new QFrame(ui->framePublishers); - empty->setFixedSize({22,22}); + empty->setFixedSize({ 22, 22 }); ui->layoutPublishers->addWidget(empty, row, 2); } - else{ + else + { auto options_button = new QPushButton(ui->framePublishers); options_button->setFlat(true); - options_button->setFixedSize({24,24}); + options_button->setFixedSize({ 24, 24 }); ui->layoutPublishers->addWidget(options_button, row, 2); - options_button->setIcon( LoadSvg(":/resources/svg/settings_cog.svg", "light")); - options_button->setIconSize( {16,16} ); + options_button->setIcon(LoadSvg(":/resources/svg/settings_cog.svg", "light")); + options_button->setIconSize({ 16, 16 }); - auto optionsMenu = [=]() - { + auto optionsMenu = [=]() { PopupMenu* menu = new PopupMenu(options_button, this); - for(auto action: publisher->availableActions()) { + for (auto action : publisher->availableActions()) + { menu->addAction(action); } menu->exec(); }; - connect( options_button, &QPushButton::clicked, - options_button, optionsMenu); + connect(options_button, &QPushButton::clicked, options_button, optionsMenu); - connect( this, &MainWindow::stylesheetChanged, - options_button, [=](QString style) - { - options_button->setIcon( LoadSvg(":/resources/svg/settings_cog.svg", style)); + connect(this, &MainWindow::stylesheetChanged, options_button, + [=](QString style) { + options_button->setIcon( + LoadSvg(":/resources/svg/settings_cog.svg", style)); }); } } else if (message_parser) { - _message_parser_factory->insert( std::make_pair(plugin_name, message_parser ) ); + _message_parser_factory->insert(std::make_pair(plugin_name, message_parser)); } else if (streamer) { - if( _default_streamer == fileinfo.baseName() ) + if (_default_streamer == fileinfo.baseName()) { _default_streamer = plugin_name; } _data_streamer.insert(std::make_pair(plugin_name, streamer)); - streamer->setAvailableParsers( _message_parser_factory ); + streamer->setAvailableParsers(_message_parser_factory); connect(streamer, &DataStreamer::closed, this, - [this]() { this->stopStreamingPlugin(); } ); + [this]() { this->stopStreamingPlugin(); }); - connect(streamer, &DataStreamer::clearBuffers, - this, &MainWindow::on_actionClearBuffer_triggered); + connect(streamer, &DataStreamer::clearBuffers, this, + &MainWindow::on_actionClearBuffer_triggered); - connect(streamer, &DataStreamer::dataReceived, - _animated_streaming_movie, [this]() - { + connect(streamer, &DataStreamer::dataReceived, _animated_streaming_movie, + [this]() { _animated_streaming_movie->start(); _animated_streaming_timer->start(500); }); - connect(streamer, &DataStreamer::removeGroup, - this, &MainWindow::on_deleteSerieFromGroup ); - - connect(streamer, &DataStreamer::dataReceived, - this, [this]() - { - if( isStreamingActive() && !_replot_timer->isActive() ) - { - _replot_timer->setSingleShot(true); - _replot_timer->start( 40 ); - } - }); + connect(streamer, &DataStreamer::removeGroup, this, + &MainWindow::on_deleteSerieFromGroup); - connect(streamer, &DataStreamer::notificationsChanged, - this, &MainWindow::on_streamingNotificationsChanged ); + connect(streamer, &DataStreamer::dataReceived, this, [this]() { + if (isStreamingActive() && !_replot_timer->isActive()) + { + _replot_timer->setSingleShot(true); + _replot_timer->start(40); + } + }); + + connect(streamer, &DataStreamer::notificationsChanged, this, + &MainWindow::on_streamingNotificationsChanged); } - else if(toolbox) + else if (toolbox) { - toolbox->init( _mapped_plot_data, _transform_functions ); + toolbox->init(_mapped_plot_data, _transform_functions); - auto action = ui->menuTools->addAction( toolbox->name() ); + auto action = ui->menuTools->addAction(toolbox->name()); int new_index = ui->widgetStack->count(); - auto provided = toolbox->providedWidget(); - auto widget = provided.first; - ui->widgetStack->addWidget( widget ); + auto provided = toolbox->providedWidget(); + auto widget = provided.first; + ui->widgetStack->addWidget(widget); - connect( action, &QAction::triggered, - toolbox, &ToolboxPlugin::onShowWidget ); + connect(action, &QAction::triggered, toolbox, &ToolboxPlugin::onShowWidget); - connect( action, &QAction::triggered, - this, [=]() { - ui->widgetStack->setCurrentIndex(new_index); - }); + connect(action, &QAction::triggered, this, + [=]() { ui->widgetStack->setCurrentIndex(new_index); }); - connect( toolbox, &ToolboxPlugin::closed, - this, [=]() { - ui->widgetStack->setCurrentIndex(0); - }); + connect(toolbox, &ToolboxPlugin::closed, this, + [=]() { ui->widgetStack->setCurrentIndex(0); }); - connect( toolbox, &ToolboxPlugin::plotCreated, - this, [=](std::string name) { - _curvelist_widget->addCurve( name ); - }); + connect(toolbox, &ToolboxPlugin::plotCreated, this, + [=](std::string name) { _curvelist_widget->addCurve(name); }); } } else @@ -785,26 +800,29 @@ QStringList MainWindow::initializePlugins(QString directory_name) } } } - if( !_data_streamer.empty() ) + if (!_data_streamer.empty()) { QSignalBlocker block(ui->comboStreaming); ui->comboStreaming->setEnabled(true); ui->buttonStreamingStart->setEnabled(true); - for(const auto& it: _data_streamer) + for (const auto& it : _data_streamer) { - if( ui->comboStreaming->findText(it.first) == -1){ + if (ui->comboStreaming->findText(it.first) == -1) + { ui->comboStreaming->addItem(it.first); } } // remember the previous one QSettings settings; - QString streaming_name = settings.value("MainWindow.previousStreamingPlugin", - ui->comboStreaming->itemText(0)).toString(); + QString streaming_name = + settings + .value("MainWindow.previousStreamingPlugin", ui->comboStreaming->itemText(0)) + .toString(); auto streamer_it = _data_streamer.find(streaming_name); - if( streamer_it == _data_streamer.end() ) + if (streamer_it == _data_streamer.end()) { streamer_it = _data_streamer.begin(); streaming_name = streamer_it->first; @@ -866,7 +884,8 @@ void MainWindow::onPlotAdded(PlotWidget* plot) connect(plot, &PlotWidget::trackerMoved, this, &MainWindow::onTrackerMovedFromWidget); - // TODO connect(plot, &PlotWidget::swapWidgetsRequested, this, &MainWindow::onSwapPlots); + // TODO connect(plot, &PlotWidget::swapWidgetsRequested, this, + // &MainWindow::onSwapPlots); connect(this, &MainWindow::dataSourceRemoved, plot, &PlotWidget::onSourceDataRemoved); @@ -875,22 +894,24 @@ void MainWindow::onPlotAdded(PlotWidget* plot) updateTimeSlider(); }); - connect(&_time_offset, SIGNAL(valueChanged(double)), plot, SLOT(on_changeTimeOffset(double))); + connect(&_time_offset, SIGNAL(valueChanged(double)), plot, + SLOT(on_changeTimeOffset(double))); - connect(ui->pushButtonUseDateTime, &QPushButton::toggled, plot, &PlotWidget::on_changeDateTimeScale); + connect(ui->pushButtonUseDateTime, &QPushButton::toggled, plot, + &PlotWidget::on_changeDateTimeScale); - connect(plot, &PlotWidget::curvesDropped, _curvelist_widget, &CurveListPanel::clearSelections); + connect(plot, &PlotWidget::curvesDropped, _curvelist_widget, + &CurveListPanel::clearSelections); - connect(plot, &PlotWidget::legendSizeChanged, this, [=](int point_size) - { - auto visitor = [=](PlotWidget* p){ - if(plot != p) p->setLegendSize(point_size); + connect(plot, &PlotWidget::legendSizeChanged, this, [=](int point_size) { + auto visitor = [=](PlotWidget* p) { + if (plot != p) + p->setLegendSize(point_size); }; this->forEachWidget(visitor); }); - connect(plot, &PlotWidget::rectChanged, - this, &MainWindow::onPlotZoomChanged); + connect(plot, &PlotWidget::rectChanged, this, &MainWindow::onPlotZoomChanged); plot->on_changeTimeOffset(_time_offset.get()); plot->on_changeDateTimeScale(ui->pushButtonUseDateTime->isChecked()); @@ -904,11 +925,9 @@ void MainWindow::onPlotZoomChanged(PlotWidget* modified_plot, QRectF new_range) { if (ui->pushButtonLink->isChecked()) { - auto visitor = [=](PlotWidget* plot){ - if(plot != modified_plot && - !plot->isEmpty() && - !plot->isXYPlot() && - plot->isZoomLinkEnabled() ) + auto visitor = [=](PlotWidget* plot) { + if (plot != modified_plot && !plot->isEmpty() && !plot->isXYPlot() && + plot->isZoomLinkEnabled()) { QRectF bound_act = plot->canvasBoundingRect(); bound_act.setLeft(new_range.left()); @@ -928,15 +947,19 @@ void MainWindow::onPlotTabAdded(PlotDocker* docker) { connect(docker, &PlotDocker::plotWidgetAdded, this, &MainWindow::onPlotAdded); - connect( this, &MainWindow::stylesheetChanged, docker, &PlotDocker::on_stylesheetChanged); + connect(this, &MainWindow::stylesheetChanged, docker, + &PlotDocker::on_stylesheetChanged); - // TODO connect(matrix, &PlotMatrix::undoableChange, this, &MainWindow::onUndoableChange); + // TODO connect(matrix, &PlotMatrix::undoableChange, this, + // &MainWindow::onUndoableChange); } QDomDocument MainWindow::xmlSaveState() const { QDomDocument doc; - QDomProcessingInstruction instr = doc.createProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); + QDomProcessingInstruction instr = doc.createProcessingInstruction("xml", "version='1.0'" + " encoding='" + "UTF-8'"); doc.appendChild(instr); @@ -961,18 +984,22 @@ void MainWindow::checkAllCurvesFromLayout(const QDomElement& root) { std::set curves; - for (QDomElement tw = root.firstChildElement("tabbed_widget"); !tw.isNull(); tw = tw.nextSiblingElement("tabbed_" - "widget")) + for (QDomElement tw = root.firstChildElement("tabbed_widget"); !tw.isNull(); + tw = tw.nextSiblingElement("tabbed_" + "widget")) { - for (QDomElement pm = tw.firstChildElement("plotmatrix"); !pm.isNull(); pm = pm.nextSiblingElement("plotmatrix")) + for (QDomElement pm = tw.firstChildElement("plotmatrix"); !pm.isNull(); + pm = pm.nextSiblingElement("plotmatrix")) { - for (QDomElement pl = pm.firstChildElement("plot"); !pl.isNull(); pl = pl.nextSiblingElement("plot")) + for (QDomElement pl = pm.firstChildElement("plot"); !pl.isNull(); + pl = pl.nextSiblingElement("plot")) { QDomElement tran_elem = pl.firstChildElement("transform"); std::string trans = tran_elem.attribute("value").toStdString(); bool is_XY_plot = (trans == "XYPlot"); - for (QDomElement cv = pl.firstChildElement("curve"); !cv.isNull(); cv = cv.nextSiblingElement("curve")) + for (QDomElement cv = pl.firstChildElement("curve"); !cv.isNull(); + cv = cv.nextSiblingElement("curve")) { if (is_XY_plot) { @@ -1008,8 +1035,10 @@ void MainWindow::checkAllCurvesFromLayout(const QDomElement& root) msgBox.setText(tr("One or more timeseries in the layout haven't been loaded yet\n" "What do you want to do?")); - QPushButton* buttonRemove = msgBox.addButton(tr("Remove curves from plots"), QMessageBox::RejectRole); - QPushButton* buttonPlaceholder = msgBox.addButton(tr("Create empty placeholders"), QMessageBox::YesRole); + QPushButton* buttonRemove = + msgBox.addButton(tr("Remove curves from plots"), QMessageBox::RejectRole); + QPushButton* buttonPlaceholder = + msgBox.addButton(tr("Create empty placeholders"), QMessageBox::YesRole); msgBox.setDefaultButton(buttonPlaceholder); msgBox.exec(); if (msgBox.clickedButton() == buttonPlaceholder) @@ -1017,7 +1046,7 @@ void MainWindow::checkAllCurvesFromLayout(const QDomElement& root) for (auto& name : missing_curves) { auto plot_it = _mapped_plot_data.addNumeric(name); - _curvelist_widget->addCurve( name ); + _curvelist_widget->addCurve(name); } _curvelist_widget->refreshColumns(); } @@ -1036,9 +1065,11 @@ bool MainWindow::xmlLoadState(QDomDocument state_document) size_t num_floating = 0; std::map tabbed_widgets_with_name; - for (QDomElement tw = root.firstChildElement("tabbed_widget"); - tw.isNull() == false; - tw = tw.nextSiblingElement("tabbed_widget")) + for (QDomElement tw = root.firstChildElement("tabbed_widget"); tw.isNull() == false; + tw = tw.nextSiblingElement("tabb" + "ed_" + "widg" + "et")) { if (tw.attribute("parent") != ("main_window")) { @@ -1069,9 +1100,11 @@ bool MainWindow::xmlLoadState(QDomDocument state_document) checkAllCurvesFromLayout(root); //----------------------------------------------------- - for (QDomElement tw = root.firstChildElement("tabbed_widget"); - tw.isNull() == false; - tw = tw.nextSiblingElement("tabbed_widget")) + for (QDomElement tw = root.firstChildElement("tabbed_widget"); tw.isNull() == false; + tw = tw.nextSiblingElement("tabb" + "ed_" + "widg" + "et")) { TabbedPlotWidget* tabwidget = TabbedPlotWidget::instance(tw.attribute("name")); tabwidget->xmlLoadState(tw); @@ -1127,7 +1160,8 @@ void MainWindow::updateRecentDataMenu(QStringList new_filenames) for (const auto& filename : new_filenames) { QAction* action = new QAction(filename, nullptr); - connect(action, &QAction::triggered, this, [this, filename] { loadDataFromFiles({ filename }); }); + connect(action, &QAction::triggered, this, + [this, filename] { loadDataFromFiles({ filename }); }); menu->insertAction(separator, action); } @@ -1192,13 +1226,15 @@ void MainWindow::deleteAllData() bool stopped = false; - for(int idx = 0; idx < ui->layoutPublishers->count(); idx++) + for (int idx = 0; idx < ui->layoutPublishers->count(); idx++) { - QLayoutItem * item = ui->layoutPublishers->itemAt(idx); - if(dynamic_cast(item)) + QLayoutItem* item = ui->layoutPublishers->itemAt(idx); + if (dynamic_cast(item)) { - if( auto checkbox = dynamic_cast(item->widget())) { - if( checkbox->isChecked() ) { + if (auto checkbox = dynamic_cast(item->widget())) + { + if (checkbox->isChecked()) + { checkbox->setChecked(false); stopped = true; } @@ -1209,19 +1245,19 @@ void MainWindow::deleteAllData() if (stopped) { QMessageBox::warning(this, "State publishers stopped", - "All the state publishers have been stopped because old data has been deleted."); + "All the state publishers have been stopped because old data " + "has been deleted."); } } - void MainWindow::importPlotDataMap(PlotDataMapRef& new_data, bool remove_old) { if (remove_old) { std::vector old_plots_to_delete; - auto AddToDeleteList = [&old_plots_to_delete](auto& prev_plot_data, auto& new_plot_data) - { + auto AddToDeleteList = [&old_plots_to_delete](auto& prev_plot_data, + auto& new_plot_data) { for (auto& it : prev_plot_data) { // timeseries in old but not in new @@ -1232,8 +1268,8 @@ void MainWindow::importPlotDataMap(PlotDataMapRef& new_data, bool remove_old) } }; - AddToDeleteList( _mapped_plot_data.numeric, new_data.numeric ); - AddToDeleteList( _mapped_plot_data.strings, new_data.strings ); + AddToDeleteList(_mapped_plot_data.numeric, new_data.numeric); + AddToDeleteList(_mapped_plot_data.strings, new_data.strings); if (!old_plots_to_delete.empty()) { @@ -1241,25 +1277,23 @@ void MainWindow::importPlotDataMap(PlotDataMapRef& new_data, bool remove_old) } } - auto [ added_curves, curve_updated, data_pushed ] = - MoveData ( new_data, _mapped_plot_data, remove_old ); + auto [added_curves, curve_updated, data_pushed] = + MoveData(new_data, _mapped_plot_data, remove_old); - for(const auto& added_curve: added_curves ) + for (const auto& added_curve : added_curves) { - _curvelist_widget->addCurve( added_curve ); + _curvelist_widget->addCurve(added_curve); } if (curve_updated) { _curvelist_widget->refreshColumns(); } - } bool MainWindow::isStreamingActive() const { - return !ui->buttonStreamingPause->isChecked() && - _active_streamer_plugin; + return !ui->buttonStreamingPause->isChecked() && _active_streamer_plugin; } bool MainWindow::loadDataFromFiles(QStringList filenames) @@ -1269,32 +1303,35 @@ bool MainWindow::loadDataFromFiles(QStringList filenames) { QMessageBox msgbox; msgbox.setWindowTitle("Loading multiple files"); - msgbox.setText("You are loading multiple files at once. A prefix will be automatically added to the name of the " + msgbox.setText("You are loading multiple files at once. A prefix will be " + "automatically added to the name of the " "timeseries.\n\n" - "This is an experimental feature. Publishers will not work as you may expect."); + "This is an experimental feature. Publishers will not work as you may " + "expect."); msgbox.addButton(QMessageBox::Ok); - QCheckBox *cb = new QCheckBox("Don't show this again"); + QCheckBox* cb = new QCheckBox("Don't show this again"); cb->setChecked(!show_me); msgbox.setCheckBox(cb); - connect(cb, &QCheckBox::stateChanged, this, [&]() { show_me = !cb->isChecked(); } ); + connect(cb, &QCheckBox::stateChanged, this, [&]() { show_me = !cb->isChecked(); }); msgbox.exec(); } - if( _mapped_plot_data.numeric.size() > 0 || - _mapped_plot_data.strings.size() > 0 || - _mapped_plot_data.user_defined.size() > 0 ) + if (_mapped_plot_data.numeric.size() > 0 || _mapped_plot_data.strings.size() > 0 || + _mapped_plot_data.user_defined.size() > 0) { QMessageBox::StandardButton reply; - reply = QMessageBox::question(this, tr("Warning"), tr("Do you want to remove the previously loaded data?\n"), - QMessageBox::Yes | QMessageBox::No, QMessageBox::NoButton); + reply = QMessageBox::question( + this, tr("Warning"), tr("Do you want to remove the previously loaded data?\n"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::NoButton); if (reply == QMessageBox::Yes) { deleteAllData(); } - if(reply == QMessageBox::NoButton) + if (reply == QMessageBox::NoButton) { - QMessageBox::information(this, tr("Closed"), "File loading interrupted by the user"); + QMessageBox::information(this, tr("Closed"), + "File loading interrupted by the user"); return false; } } @@ -1305,7 +1342,7 @@ bool MainWindow::loadDataFromFiles(QStringList filenames) { FileLoadInfo info; info.filename = filenames[i]; - info.prefix = QFileInfo( info.filename ).baseName(); + info.prefix = QFileInfo(info.filename).baseName(); if (loadDataFromFile(info)) { @@ -1371,8 +1408,9 @@ bool MainWindow::loadDataFromFile(const FileLoadInfo& info) } bool ok; - QString plugin_name = QInputDialog::getItem(this, tr("QInputDialog::getItem()"), tr("Select the loader to use:"), - names, 0, false, &ok); + QString plugin_name = + QInputDialog::getItem(this, tr("QInputDialog::getItem()"), + tr("Select the loader to use:"), names, 0, false, &ok); if (ok && !plugin_name.isEmpty()) { dataloader = _data_loader[plugin_name]; @@ -1386,8 +1424,9 @@ bool MainWindow::loadDataFromFile(const FileLoadInfo& info) if (!file.open(QFile::ReadOnly | QFile::Text)) { - QMessageBox::warning(this, tr("Datafile"), - tr("Cannot read file %1:\n%2.").arg(info.filename).arg(file.errorString())); + QMessageBox::warning( + this, tr("Datafile"), + tr("Cannot read file %1:\n%2.").arg(info.filename).arg(file.errorString())); return false; } file.close(); @@ -1412,7 +1451,8 @@ bool MainWindow::loadDataFromFile(const FileLoadInfo& info) // substitute an old item of _loaded_datafiles or push_back another item. for (auto& prev_loaded : _loaded_datafiles) { - if (prev_loaded.filename == new_info.filename && prev_loaded.prefix == new_info.prefix) + if (prev_loaded.filename == new_info.filename && + prev_loaded.prefix == new_info.prefix) { prev_loaded = new_info; duplicate = true; @@ -1428,23 +1468,26 @@ bool MainWindow::loadDataFromFile(const FileLoadInfo& info) } catch (std::exception& ex) { - QMessageBox::warning( - this, tr("Exception from the plugin"), - tr("The plugin [%1] thrown the following exception: \n\n %3\n").arg(dataloader->name()).arg(ex.what())); + QMessageBox::warning(this, tr("Exception from the plugin"), + tr("The plugin [%1] thrown the following exception: \n\n %3\n") + .arg(dataloader->name()) + .arg(ex.what())); return false; } } else { QMessageBox::warning(this, tr("Error"), - tr("Cannot read files with extension %1.\n No plugin can handle that!\n").arg(info.filename)); + tr("Cannot read files with extension %1.\n No plugin can handle " + "that!\n") + .arg(info.filename)); } _curvelist_widget->updateFilter(); // clean the custom plot. Function updateDataAndReplot will update them for (auto& custom_it : _transform_functions) { - auto dst_data_it = _mapped_plot_data.numeric.find( custom_it.first ); + auto dst_data_it = _mapped_plot_data.numeric.find(custom_it.first); if (dst_data_it != _mapped_plot_data.numeric.end()) { dst_data_it->second.clear(); @@ -1460,15 +1503,14 @@ bool MainWindow::loadDataFromFile(const FileLoadInfo& info) void MainWindow::on_buttonStreamingNotifications_clicked() { - auto streamer = _data_streamer.at( ui->comboStreaming->currentText() ); + auto streamer = _data_streamer.at(ui->comboStreaming->currentText()); QAction* notification_button_action = streamer->notificationAction().first; - if (notification_button_action != nullptr) + if (notification_button_action != nullptr) { notification_button_action->trigger(); } } - void MainWindow::on_buttonStreamingPause_toggled(bool paused) { if (!_active_streamer_plugin) @@ -1508,7 +1550,6 @@ void MainWindow::on_streamingToggled() } } - void MainWindow::stopStreamingPlugin() { ui->comboStreaming->setEnabled(true); @@ -1517,19 +1558,20 @@ void MainWindow::stopStreamingPlugin() ui->labelStreamingAnimation->setHidden(true); enableStreamingNotificationsButton(false); - // force the cleanups typically done in on_buttonStreamingPause_toggled - if( ui->buttonStreamingPause->isChecked() ) + if (ui->buttonStreamingPause->isChecked()) { // Will call on_buttonStreamingPause_toggled ui->buttonStreamingPause->setChecked(false); } - else{ + else + { // call it manually on_buttonStreamingPause_toggled(true); } - if( _active_streamer_plugin ) { + if (_active_streamer_plugin) + { _active_streamer_plugin->shutdown(); _active_streamer_plugin = nullptr; } @@ -1540,8 +1582,7 @@ void MainWindow::stopStreamingPlugin() } // reset max range. - _mapped_plot_data.setMaximumRangeX( std::numeric_limits::max() ); - + _mapped_plot_data.setMaximumRangeX(std::numeric_limits::max()); } void MainWindow::startStreamingPlugin(QString streamer_name) @@ -1578,8 +1619,9 @@ void MainWindow::startStreamingPlugin(QString streamer_name) } catch (std::runtime_error& err) { - QMessageBox::warning(this, tr("Exception from the plugin"), - tr("The plugin thrown the following exception: \n\n %1\n").arg(err.what())); + QMessageBox::warning( + this, tr("Exception from the plugin"), + tr("The plugin thrown the following exception: \n\n %1\n").arg(err.what())); _active_streamer_plugin = nullptr; return; } @@ -1608,7 +1650,7 @@ void MainWindow::startStreamingPlugin(QString streamer_name) } else { - QSignalBlocker block( ui->buttonStreamingStart ); + QSignalBlocker block(ui->buttonStreamingStart); ui->buttonStreamingStart->setChecked(false); qDebug() << "Failed to launch the streamer"; _active_streamer_plugin = nullptr; @@ -1622,12 +1664,15 @@ void MainWindow::enableStreamingNotificationsButton(bool enabled) QSettings settings; QString theme = settings.value("Preferences::theme", "light").toString(); - if( enabled ) + if (enabled) { - ui->buttonStreamingNotifications->setIcon(LoadSvg(":/resources/svg/alarm-bell-active.svg", theme)); + ui->buttonStreamingNotifications->setIcon( + LoadSvg(":/resources/svg/alarm-bell-active.svg", theme)); } - else{ - ui->buttonStreamingNotifications->setIcon(LoadSvg(":/resources/svg/alarm-bell.svg", theme)); + else + { + ui->buttonStreamingNotifications->setIcon( + LoadSvg(":/resources/svg/alarm-bell.svg", theme)); } } @@ -1635,34 +1680,34 @@ void MainWindow::loadStyleSheet(QString file_path) { QFile styleFile(file_path); styleFile.open(QFile::ReadOnly); - try{ - QString theme = SetApplicationStyleSheet( styleFile.readAll() ); + try + { + QString theme = SetApplicationStyleSheet(styleFile.readAll()); - forEachWidget([&](PlotWidget* plot) { - plot->replot(); - }); + forEachWidget([&](PlotWidget* plot) { plot->replot(); }); _curvelist_widget->updateColors(); emit stylesheetChanged(theme); } - catch( std::runtime_error& err ) + catch (std::runtime_error& err) { QMessageBox::warning(this, tr("Error loading StyleSheet"), tr(err.what())); } } - void MainWindow::on_stylesheetChanged(QString theme) { ui->pushButtonLoadDatafile->setIcon(LoadSvg(":/resources/svg/import.svg", theme)); ui->buttonStreamingPause->setIcon(LoadSvg(":/resources/svg/pause.svg", theme)); - if ( ui->buttonStreamingNotifications->isEnabled() ) + if (ui->buttonStreamingNotifications->isEnabled()) { - ui->buttonStreamingNotifications->setIcon(LoadSvg(":/resources/svg/alarm-bell-active.svg", theme)); + ui->buttonStreamingNotifications->setIcon( + LoadSvg(":/resources/svg/alarm-bell-active.svg", theme)); } - else + else { - ui->buttonStreamingNotifications->setIcon(LoadSvg(":/resources/svg/alarm-bell.svg", theme)); + ui->buttonStreamingNotifications->setIcon( + LoadSvg(":/resources/svg/alarm-bell.svg", theme)); } ui->buttonRecentData->setIcon(LoadSvg(":/resources/svg/right-arrow.svg", theme)); ui->buttonRecentLayout->setIcon(LoadSvg(":/resources/svg/right-arrow.svg", theme)); @@ -1688,15 +1733,16 @@ void MainWindow::loadPluginState(const QDomElement& root) { QDomElement plugins = root.firstChildElement("Plugins"); - for (QDomElement plugin_elem = plugins.firstChildElement(); plugin_elem.isNull() == false; - plugin_elem = plugin_elem.nextSiblingElement()) + for (QDomElement plugin_elem = plugins.firstChildElement(); + plugin_elem.isNull() == false; plugin_elem = plugin_elem.nextSiblingElement()) { const QString plugin_name = plugin_elem.attribute("ID"); if (plugin_elem.nodeName() != "plugin" || plugin_name.isEmpty()) { QMessageBox::warning(this, tr("Error loading Plugin State from Layout"), - tr("The method xmlSaveState() must return a node like this \ninstead of\n") - .arg(elem.attribute("ID")) - .arg(expected_name)); + tr("The method xmlSaveState() returned\n\ninstead of\n") + .arg(elem.attribute("ID")) + .arg(expected_name)); } }; @@ -1836,11 +1883,12 @@ bool MainWindow::loadLayoutFromFile(QString filename) QFile file(filename); if (!file.open(QFile::ReadOnly | QFile::Text)) { - QMessageBox::warning(this, tr("Layout"), tr("Cannot read file %1:\n%2.").arg(filename).arg(file.errorString())); + QMessageBox::warning( + this, tr("Layout"), + tr("Cannot read file %1:\n%2.").arg(filename).arg(file.errorString())); return false; } - QString errorStr; int errorLine, errorColumn; @@ -1848,8 +1896,9 @@ bool MainWindow::loadLayoutFromFile(QString filename) if (!domDocument.setContent(&file, true, &errorStr, &errorLine, &errorColumn)) { - QMessageBox::information(window(), tr("XML Layout"), - tr("Parse error at line %1:\n%2").arg(errorLine).arg(errorStr)); + QMessageBox::information( + window(), tr("XML Layout"), + tr("Parse error at line %1:\n%2").arg(errorLine).arg(errorStr)); return false; } @@ -1861,12 +1910,14 @@ bool MainWindow::loadLayoutFromFile(QString filename) { QMessageBox msgBox(this); msgBox.setWindowTitle("Obsolate Layout version"); - msgBox.setText(tr("This Layout ID is not supported [%1].\nThis version of PlotJuggler use Layout ID [%2]") - .arg(root.attribute("version")) - .arg(LAYOUT_VERSION)); + msgBox.setText(tr("This Layout ID is not supported [%1].\nThis version of " + "PlotJuggler use Layout ID [%2]") + .arg(root.attribute("version")) + .arg(LAYOUT_VERSION)); msgBox.setStandardButtons(QMessageBox::Abort); - QPushButton* continueButton = msgBox.addButton(tr("Continue anyway"), QMessageBox::ActionRole); + QPushButton* continueButton = + msgBox.addButton(tr("Continue anyway"), QMessageBox::ActionRole); msgBox.setDefaultButton(continueButton); int ret = msgBox.exec(); @@ -1878,7 +1929,8 @@ bool MainWindow::loadLayoutFromFile(QString filename) loadPluginState(root); //------------------------------------------------- - QDomElement previously_loaded_datafile = root.firstChildElement("previouslyLoaded_Datafiles"); + QDomElement previously_loaded_datafile = root.firstChildElement("previouslyLoaded_" + "Datafiles"); QDomElement datafile_elem = previously_loaded_datafile.firstChildElement("fileInfo"); while (!datafile_elem.isNull()) @@ -1887,7 +1939,8 @@ bool MainWindow::loadLayoutFromFile(QString filename) info.filename = datafile_elem.attribute("filename"); info.prefix = datafile_elem.attribute("prefix"); - QDomElement datasources_elem = datafile_elem.firstChildElement("selected_datasources"); + QDomElement datasources_elem = datafile_elem.firstChildElement("selected_" + "datasources"); QString topics_list = datasources_elem.attribute("value"); info.selected_datasources = topics_list.split(";", QString::SkipEmptyParts); @@ -1905,7 +1958,8 @@ bool MainWindow::loadLayoutFromFile(QString filename) QMessageBox msgBox(this); msgBox.setWindowTitle("Start Streaming?"); - msgBox.setText(tr("Start the previously used streaming plugin?\n\n %1 \n\n").arg(streamer_name)); + msgBox.setText( + tr("Start the previously used streaming plugin?\n\n %1 \n\n").arg(streamer_name)); QPushButton* yes = msgBox.addButton(tr("Yes"), QMessageBox::YesRole); QPushButton* no = msgBox.addButton(tr("No"), QMessageBox::RejectRole); msgBox.setDefaultButton(yes); @@ -1915,14 +1969,15 @@ bool MainWindow::loadLayoutFromFile(QString filename) { if (_data_streamer.count(streamer_name) != 0) { - auto allCurves = readAllCurvesFromXML( root ); + auto allCurves = readAllCurvesFromXML(root); // create placeholders, if necessary - for(auto curve_name: allCurves) { + for (auto curve_name : allCurves) + { std::string curve_str = curve_name.toStdString(); - if( _mapped_plot_data.numeric.count( curve_str ) == 0 ) + if (_mapped_plot_data.numeric.count(curve_str) == 0) { - _mapped_plot_data.addNumeric( curve_str ); + _mapped_plot_data.addNumeric(curve_str); } } @@ -1930,8 +1985,9 @@ bool MainWindow::loadLayoutFromFile(QString filename) } else { - QMessageBox::warning(this, tr("Error Loading Streamer"), - tr("The streamer named %1 can not be loaded.").arg(streamer_name)); + QMessageBox::warning( + this, tr("Error Loading Streamer"), + tr("The streamer named %1 can not be loaded.").arg(streamer_name)); } } } @@ -1941,8 +1997,8 @@ bool MainWindow::loadLayoutFromFile(QString filename) if (!plugins.isNull() && _autostart_publishers) { - for (QDomElement plugin_elem = plugins.firstChildElement(); plugin_elem.isNull() == false; - plugin_elem = plugin_elem.nextSiblingElement()) + for (QDomElement plugin_elem = plugins.firstChildElement(); + plugin_elem.isNull() == false; plugin_elem = plugin_elem.nextSiblingElement()) { const QString plugin_name = plugin_elem.nodeName(); if (_state_publisher.find(plugin_name) != _state_publisher.end()) @@ -1964,29 +2020,31 @@ bool MainWindow::loadLayoutFromFile(QString filename) if (!custom_equations.isNull()) { for (QDomElement custom_eq = custom_equations.firstChildElement("snippet"); - custom_eq.isNull() == false; - custom_eq = custom_eq.nextSiblingElement("snippet")) + custom_eq.isNull() == false; custom_eq = custom_eq.nextSiblingElement("snippe" + "t")) { auto snippet = GetSnippetFromXML(custom_eq); CustomPlotPtr new_custom_plot = std::make_shared(snippet); - new_custom_plot->xmlLoadState( custom_eq ); + new_custom_plot->xmlLoadState(custom_eq); new_custom_plot->calculateAndAdd(_mapped_plot_data); const auto& alias_name = new_custom_plot->aliasName(); _curvelist_widget->addCustom(alias_name); - _transform_functions.insert( {alias_name.toStdString(), new_custom_plot } ); + _transform_functions.insert({ alias_name.toStdString(), new_custom_plot }); } _curvelist_widget->refreshColumns(); } } catch (std::runtime_error& err) { - QMessageBox::warning(this, tr("Exception"), - tr("Failed to refresh a customMathEquation \n\n %1\n").arg(err.what())); + QMessageBox::warning( + this, tr("Exception"), + tr("Failed to refresh a customMathEquation \n\n %1\n").arg(err.what())); } - QByteArray snippets_saved_xml = settings.value("AddCustomPlotDialog.savedXML", QByteArray()).toByteArray(); + QByteArray snippets_saved_xml = + settings.value("AddCustomPlotDialog.savedXML", QByteArray()).toByteArray(); auto snippets_element = root.firstChildElement("snippets"); if (!snippets_element.isNull()) @@ -2012,7 +2070,8 @@ bool MainWindow::loadLayoutFromFile(QString filename) { QMessageBox msgBox(this); msgBox.setWindowTitle("Overwrite custom transforms?"); - msgBox.setText("Your layout file contains a set of custom transforms different from " + msgBox.setText("Your layout file contains a set of custom transforms different " + "from " "the last one you used.\nWant to load these transformations?"); msgBox.addButton(QMessageBox::No); msgBox.addButton(QMessageBox::Yes); @@ -2048,14 +2107,15 @@ void MainWindow::on_tabbedAreaDestroyed(QObject* object) this->setFocus(); } - -void MainWindow::forEachWidget(std::function operation) +void MainWindow::forEachWidget( + std::function operation) { auto func = [&](QTabWidget* tabs) { for (int t = 0; t < tabs->count(); t++) { PlotDocker* matrix = dynamic_cast(tabs->widget(t)); - if(!matrix){ + if (!matrix) + { continue; } @@ -2114,9 +2174,7 @@ void MainWindow::updateDataAndReplot(bool replot_hidden_tabs) { { std::lock_guard lock(_active_streamer_plugin->mutex()); - move_ret = MoveData(_active_streamer_plugin->dataMap(), - _mapped_plot_data, - false); + move_ret = MoveData(_active_streamer_plugin->dataMap(), _mapped_plot_data, false); } for (const auto& str : move_ret.added_curves) @@ -2124,12 +2182,12 @@ void MainWindow::updateDataAndReplot(bool replot_hidden_tabs) _curvelist_widget->addCurve(str); } - if ( move_ret.curves_updated ) + if (move_ret.curves_updated) { _curvelist_widget->refreshColumns(); } - _mapped_plot_data.setMaximumRangeX( ui->streamingSpinBox->value() ); + _mapped_plot_data.setMaximumRangeX(ui->streamingSpinBox->value()); } const bool is_streaming_active = isStreamingActive(); @@ -2140,9 +2198,7 @@ void MainWindow::updateDataAndReplot(bool replot_hidden_tabs) function->calculate(); } - forEachWidget([](PlotWidget* plot) { - plot->updateCurves(); - }); + forEachWidget([](PlotWidget* plot) { plot->updateCurves(); }); //-------------------------------- // trigger again the execution of this callback if steaming == true @@ -2159,7 +2215,7 @@ void MainWindow::updateDataAndReplot(bool replot_hidden_tabs) updateTimeSlider(); } //-------------------------------- - if( move_ret.data_pushed ) + if (move_ret.data_pushed) { for (const auto& it : TabbedPlotWidget::instances()) { @@ -2179,10 +2235,9 @@ void MainWindow::updateDataAndReplot(bool replot_hidden_tabs) } } } - else{ - forEachWidget([](PlotWidget* plot) { - plot->replot(); - }); + else + { + forEachWidget([](PlotWidget* plot) { plot->replot(); }); } } @@ -2195,7 +2250,7 @@ void MainWindow::on_streamingSpinBox_valueChanged(int value) return; } - _mapped_plot_data.setMaximumRangeX( real_value ); + _mapped_plot_data.setMaximumRangeX(real_value); if (_active_streamer_plugin) { @@ -2203,8 +2258,6 @@ void MainWindow::on_streamingSpinBox_valueChanged(int value) } } - - void MainWindow::on_actionExit_triggered() { this->close(); @@ -2217,7 +2270,8 @@ void MainWindow::on_pushButtonRemoveTimeOffset_toggled(bool) forEachWidget([](PlotWidget* plot) { plot->replot(); }); - if (this->signalsBlocked() == false){ + if (this->signalsBlocked() == false) + { onUndoableChange(); } } @@ -2235,7 +2289,8 @@ void MainWindow::updatedDisplayTime() } else { - QDateTime datetime = QDateTime::fromMSecsSinceEpoch(std::round(_tracker_time * 1000.0)); + QDateTime datetime = + QDateTime::fromMSecsSinceEpoch(std::round(_tracker_time * 1000.0)); timeLine->setText(datetime.toString("[yyyy MMM dd] HH:mm::ss.zzz")); } } @@ -2306,41 +2361,40 @@ void MainWindow::on_actionClearBuffer_triggered() }); } -void MainWindow::on_deleteSerieFromGroup(std::string group_name ) +void MainWindow::on_deleteSerieFromGroup(std::string group_name) { std::vector names; - auto AddFromGroup = [&]( auto& series ) - { + auto AddFromGroup = [&](auto& series) { for (auto& it : series) { const auto& group = it.second.group(); - if( group && group->name() == group_name) + if (group && group->name() == group_name) { - names.push_back( it.first ); + names.push_back(it.first); } } }; - AddFromGroup( _mapped_plot_data.numeric ); - AddFromGroup( _mapped_plot_data.strings ); - AddFromGroup( _mapped_plot_data.user_defined ); + AddFromGroup(_mapped_plot_data.numeric); + AddFromGroup(_mapped_plot_data.strings); + AddFromGroup(_mapped_plot_data.user_defined); onDeleteMultipleCurves(names); } void MainWindow::on_streamingNotificationsChanged(int active_count) { - if ( active_count > 0 && _active_streamer_plugin ) + if (active_count > 0 && _active_streamer_plugin) { enableStreamingNotificationsButton(true); QString tooltipText = QString("%1 has %2 outstanding notitication%3") .arg(_active_streamer_plugin->name()) .arg(active_count) - .arg( active_count > 1 ? "s":""); + .arg(active_count > 1 ? "s" : ""); ui->buttonStreamingNotifications->setToolTip(tooltipText); } - else + else { enableStreamingNotificationsButton(false); ui->buttonStreamingNotifications->setToolTip("View streaming alerts"); @@ -2350,16 +2404,18 @@ void MainWindow::on_streamingNotificationsChanged(int active_count) void MainWindow::on_pushButtonUseDateTime_toggled(bool checked) { static bool first = true; - if( checked && ui->pushButtonRemoveTimeOffset->isChecked() ) + if (checked && ui->pushButtonRemoveTimeOffset->isChecked()) { - if( first ){ + if (first) + { QMessageBox::information(this, tr("Note"), - tr("When \"Use Date Time\" is checked, the option \"Remove Time Offset\" " + tr("When \"Use Date Time\" is checked, the option " + "\"Remove Time Offset\" " "is automatically disabled.\n" "This message will be shown only once.")); first = false; } - ui->pushButtonRemoveTimeOffset->setChecked( false ); + ui->pushButtonRemoveTimeOffset->setChecked(false); } updatedDisplayTime(); } @@ -2401,7 +2457,8 @@ void MainWindow::closeEvent(QCloseEvent* event) settings.setValue("MainWindow.state", saveState()); settings.setValue("MainWindow.activateGrid", ui->pushButtonActivateGrid->isChecked()); - settings.setValue("MainWindow.removeTimeOffset", ui->pushButtonRemoveTimeOffset->isChecked()); + settings.setValue("MainWindow.removeTimeOffset", + ui->pushButtonRemoveTimeOffset->isChecked()); settings.setValue("MainWindow.dateTimeDisplay", ui->pushButtonUseDateTime->isChecked()); settings.setValue("MainWindow.buttonLink", ui->pushButtonLink->isChecked()); settings.setValue("MainWindow.buttonRatio", ui->pushButtonRatio->isChecked()); @@ -2428,8 +2485,7 @@ void MainWindow::onEditCustomPlot(const std::string& plot_name) return; } _function_editor->editExistingPlot( - std::dynamic_pointer_cast(custom_it->second) - ); + std::dynamic_pointer_cast(custom_it->second)); } void MainWindow::onRefreshCustomPlot(const std::string& plot_name) @@ -2450,14 +2506,15 @@ void MainWindow::onRefreshCustomPlot(const std::string& plot_name) } catch (const std::runtime_error& e) { - QMessageBox::critical(this, "error", "Failed to refresh data : " + QString::fromStdString(e.what())); + QMessageBox::critical(this, "error", + "Failed to refresh data : " + QString::fromStdString(e.what())); } } - void MainWindow::onPlaybackLoop() { - qint64 delta_ms = (QDateTime::currentMSecsSinceEpoch() - _prev_publish_time.toMSecsSinceEpoch()); + qint64 delta_ms = + (QDateTime::currentMSecsSinceEpoch() - _prev_publish_time.toMSecsSinceEpoch()); _prev_publish_time = QDateTime::currentDateTime(); delta_ms = std::max((qint64)_publish_timer->interval(), delta_ms); @@ -2509,7 +2566,8 @@ void MainWindow::onCustomPlotCreated(CustomPlotPtr custom_plot) { QMessageBox::warning(this, tr("Warning"), tr("Failed to create the custom timeseries. " - "Error:\n\n%1").arg(ex.what())); + "Error:\n\n%1") + .arg(ex.what())); return; } @@ -2521,10 +2579,11 @@ void MainWindow::onCustomPlotCreated(CustomPlotPtr custom_plot) if (custom_it == _transform_functions.end()) { _transform_functions.insert({ curve_name, custom_plot }); - _curvelist_widget->addCustom( QString::fromStdString(curve_name) ); + _curvelist_widget->addCustom(QString::fromStdString(curve_name)); onUpdateLeftTableValues(); } - else{ + else + { custom_it->second = custom_plot; } @@ -2532,9 +2591,8 @@ void MainWindow::onCustomPlotCreated(CustomPlotPtr custom_plot) // update plots forEachWidget([&](PlotWidget* plot) { - - PlotWidgetBase::CurveInfo* info = plot->curveFromTitle( - QString::fromStdString( curve_name ) ); + PlotWidgetBase::CurveInfo* info = + plot->curveFromTitle(QString::fromStdString(curve_name)); if (info) { @@ -2551,7 +2609,8 @@ void MainWindow::on_actionReportBug_triggered() void MainWindow::on_actionShare_the_love_triggered() { - QDesktopServices::openUrl(QUrl("https://twitter.com/intent/tweet?hashtags=PlotJuggler")); + QDesktopServices::openUrl(QUrl("https://twitter.com/intent/" + "tweet?hashtags=PlotJuggler")); } void MainWindow::on_actionAbout_triggered() @@ -2563,14 +2622,16 @@ void MainWindow::on_actionAbout_triggered() ui->label_version->setText(QString("version: ") + QApplication::applicationVersion()); dialog->setAttribute(Qt::WA_DeleteOnClose); - QFile fileTitle( _skin_path + "/about_window_title.html"); - if(fileTitle.open(QIODevice::ReadOnly)) { - ui->titleTextBrowser->setHtml( fileTitle.readAll() ); + QFile fileTitle(_skin_path + "/about_window_title.html"); + if (fileTitle.open(QIODevice::ReadOnly)) + { + ui->titleTextBrowser->setHtml(fileTitle.readAll()); } - QFile fileBody( _skin_path + "/about_window_body.html"); - if(fileBody.open(QIODevice::ReadOnly)) { - ui->bodyTextBrowser->setHtml( fileBody.readAll() ); + QFile fileBody(_skin_path + "/about_window_body.html"); + if (fileBody.open(QIODevice::ReadOnly)) + { + ui->bodyTextBrowser->setHtml(fileBody.readAll()); } dialog->setAttribute(Qt::WA_DeleteOnClose); @@ -2581,7 +2642,7 @@ void MainWindow::on_actionCheatsheet_triggered() { QSettings settings; - CheatsheetDialog *dialog = new CheatsheetDialog(this); + CheatsheetDialog* dialog = new CheatsheetDialog(this); dialog->restoreGeometry(settings.value("Cheatsheet.geometry").toByteArray()); dialog->exec(); settings.setValue("Cheatsheet.geometry", dialog->saveGeometry()); @@ -2603,7 +2664,8 @@ void MainWindow::on_actionSupportPlotJuggler_triggered() void MainWindow::on_actionSaveAllPlotTabs_triggered() { QSettings settings; - QString directory_path = settings.value("MainWindow.saveAllPlotTabs", QDir::currentPath()).toString(); + QString directory_path = settings.value("MainWindow.saveAllPlotTabs", +QDir::currentPath()).toString(); // Get destination folder QFileDialog saveDialog(this); saveDialog.setDirectory(directory_path); @@ -2681,7 +2743,8 @@ void MainWindow::on_pushButtonLoadDatafile_clicked() { if (_data_loader.empty()) { - QMessageBox::warning(this, tr("Warning"), tr("No plugin was loaded to process a data file\n")); + QMessageBox::warning(this, tr("Warning"), + tr("No plugin was loaded to process a data file\n")); return; } @@ -2705,7 +2768,8 @@ void MainWindow::on_pushButtonLoadDatafile_clicked() file_extension_filter.append(QString(" *.") + it); } - QString directory_path = settings.value("MainWindow.lastDatafileDirectory", QDir::currentPath()).toString(); + QString directory_path = + settings.value("MainWindow.lastDatafileDirectory", QDir::currentPath()).toString(); QFileDialog loadDialog(this); loadDialog.setFileMode(QFileDialog::ExistingFiles); @@ -2737,8 +2801,10 @@ void MainWindow::on_pushButtonLoadLayout_clicked() { QSettings settings; - QString directory_path = settings.value("MainWindow.lastLayoutDirectory", QDir::currentPath()).toString(); - QString filename = QFileDialog::getOpenFileName(this, "Open Layout", directory_path, "*.xml"); + QString directory_path = + settings.value("MainWindow.lastLayoutDirectory", QDir::currentPath()).toString(); + QString filename = + QFileDialog::getOpenFileName(this, "Open Layout", directory_path, "*.xml"); if (filename.isEmpty()) { return; @@ -2759,7 +2825,8 @@ void MainWindow::on_pushButtonSaveLayout_clicked() QSettings settings; - QString directory_path = settings.value("MainWindow.lastLayoutDirectory", QDir::currentPath()).toString(); + QString directory_path = + settings.value("MainWindow.lastLayoutDirectory", QDir::currentPath()).toString(); QFileDialog saveDialog(this); saveDialog.setOption(QFileDialog::DontUseNativeDialog, true); @@ -2777,14 +2844,18 @@ void MainWindow::on_pushButtonSaveLayout_clicked() auto checkbox_datasource = new QCheckBox("Save data source"); checkbox_datasource->setToolTip("ant the layout to remember the source of your data,\n" - "i.e. the Datafile used or the Streaming Plugin loaded ?"); + "i.e. the Datafile used or the Streaming Plugin loaded " + "?"); checkbox_datasource->setFocusPolicy(Qt::NoFocus); - checkbox_datasource->setChecked(settings.value("MainWindow.saveLayoutDataSource", true).toBool()); + checkbox_datasource->setChecked( + settings.value("MainWindow.saveLayoutDataSource", true).toBool()); auto checkbox_snippets = new QCheckBox("Save custom transformations"); - checkbox_snippets->setToolTip("Do you want the layout to save the custom transformations?"); + checkbox_snippets->setToolTip("Do you want the layout to save the custom " + "transformations?"); checkbox_snippets->setFocusPolicy(Qt::NoFocus); - checkbox_snippets->setChecked(settings.value("MainWindow.saveLayoutSnippets", true).toBool()); + checkbox_snippets->setChecked( + settings.value("MainWindow.saveLayoutSnippets", true).toBool()); vbox->addWidget(title); vbox->addWidget(separator); @@ -2870,7 +2941,8 @@ void MainWindow::on_pushButtonSaveLayout_clicked() } root.appendChild(custom_equations); - QByteArray snippets_xml_text = settings.value("AddCustomPlotDialog.savedXML", QByteArray()).toByteArray(); + QByteArray snippets_xml_text = + settings.value("AddCustomPlotDialog.savedXML", QByteArray()).toByteArray(); auto snipped_saved = GetSnippetsFromXML(snippets_xml_text); auto snippets_root = ExportSnippets(snipped_saved, doc); root.appendChild(snippets_root); @@ -2891,7 +2963,8 @@ void MainWindow::onActionFullscreenTriggered() if (first_call && !_minimized) { first_call = false; - QMessageBox::information(this, "Remember!", "Press F10 to switch back to the normal view"); + QMessageBox::information(this, "Remember!", + "Press F10 to switch back to the normal view"); } _minimized = !_minimized; @@ -2982,9 +3055,12 @@ void MainWindow::on_playbackStep_valueChanged(double step) void MainWindow::on_actionLoadStyleSheet_triggered() { QSettings settings; - QString directory_path = settings.value("MainWindow.loadStyleSheetDirectory", QDir::currentPath()).toString(); + QString directory_path = + settings.value("MainWindow.loadStyleSheetDirectory", QDir::currentPath()) + .toString(); - QString fileName = QFileDialog::getOpenFileName(this, tr("Load StyleSheet"), directory_path, tr("(*.qss)")); + QString fileName = QFileDialog::getOpenFileName(this, tr("Load StyleSheet"), + directory_path, tr("(*.qss)")); if (fileName.isEmpty()) { return; @@ -3000,19 +3076,18 @@ void MainWindow::on_pushButtonLegend_clicked() { switch (_labels_status) { - case LabelStatus::LEFT: - _labels_status = LabelStatus::HIDDEN; - break; - case LabelStatus::RIGHT: - _labels_status = LabelStatus::LEFT; - break; - case LabelStatus::HIDDEN: - _labels_status = LabelStatus::RIGHT; - break; + case LabelStatus::LEFT: + _labels_status = LabelStatus::HIDDEN; + break; + case LabelStatus::RIGHT: + _labels_status = LabelStatus::LEFT; + break; + case LabelStatus::HIDDEN: + _labels_status = LabelStatus::RIGHT; + break; } - auto visitor = [=](PlotWidget* plot) - { + auto visitor = [=](PlotWidget* plot) { plot->activateLegend(_labels_status != LabelStatus::HIDDEN); if (_labels_status == LabelStatus::LEFT) @@ -3031,27 +3106,24 @@ void MainWindow::on_pushButtonLegend_clicked() void MainWindow::on_pushButtonZoomOut_clicked() { - auto visitor = [=](PlotWidget* plot) - { - plot->zoomOut(false); - }; + auto visitor = [=](PlotWidget* plot) { plot->zoomOut(false); }; this->forEachWidget(visitor); onUndoableChange(); } -void MainWindow::on_comboStreaming_currentIndexChanged(const QString ¤t_text) +void MainWindow::on_comboStreaming_currentIndexChanged(const QString& current_text) { QSettings settings; - settings.setValue("MainWindow.previousStreamingPlugin", current_text ); - auto streamer = _data_streamer.at( current_text ); - ui->buttonStreamingOptions->setEnabled( !streamer->availableActions().empty() ); + settings.setValue("MainWindow.previousStreamingPlugin", current_text); + auto streamer = _data_streamer.at(current_text); + ui->buttonStreamingOptions->setEnabled(!streamer->availableActions().empty()); std::pair notifications_pair = streamer->notificationAction(); if (notifications_pair.first == nullptr) { ui->buttonStreamingNotifications->setEnabled(false); } - else + else { on_streamingNotificationsChanged(notifications_pair.second); } @@ -3060,35 +3132,35 @@ void MainWindow::on_comboStreaming_currentIndexChanged(const QString ¤t_te void MainWindow::on_buttonStreamingStart_clicked() { ui->buttonStreamingStart->setEnabled(false); - if( ui->buttonStreamingStart->text() == "Start") + if (ui->buttonStreamingStart->text() == "Start") { - startStreamingPlugin( ui->comboStreaming->currentText() ); + startStreamingPlugin(ui->comboStreaming->currentText()); } - else { + else + { stopStreamingPlugin(); } ui->buttonStreamingStart->setEnabled(true); } - -PopupMenu::PopupMenu(QWidget *relative_widget, QWidget *parent): - QMenu(parent), _w(relative_widget) +PopupMenu::PopupMenu(QWidget* relative_widget, QWidget* parent) + : QMenu(parent), _w(relative_widget) { } -void PopupMenu::showEvent(QShowEvent *) +void PopupMenu::showEvent(QShowEvent*) { - QPoint p = _w->mapToGlobal( {} ); + QPoint p = _w->mapToGlobal({}); QRect geo = _w->geometry(); - this->move( p.x() + geo.width(), p.y() ); + this->move(p.x() + geo.width(), p.y()); } -void PopupMenu::leaveEvent(QEvent *) +void PopupMenu::leaveEvent(QEvent*) { close(); } -void PopupMenu::closeEvent(QCloseEvent *) +void PopupMenu::closeEvent(QCloseEvent*) { _w->setAttribute(Qt::WA_UnderMouse, false); } @@ -3097,7 +3169,8 @@ void MainWindow::on_buttonRecentData_clicked() { PopupMenu* menu = new PopupMenu(ui->buttonRecentData, this); - for(auto action: _recent_data_files->actions()) { + for (auto action : _recent_data_files->actions()) + { menu->addAction(action); } menu->exec(); @@ -3105,21 +3178,21 @@ void MainWindow::on_buttonRecentData_clicked() void MainWindow::on_buttonStreamingOptions_clicked() { - auto streamer = _data_streamer.at( ui->comboStreaming->currentText() ); + auto streamer = _data_streamer.at(ui->comboStreaming->currentText()); PopupMenu* menu = new PopupMenu(ui->buttonStreamingOptions, this); - for( auto action: streamer->availableActions() ) { + for (auto action : streamer->availableActions()) + { menu->addAction(action); } menu->show(); } - void MainWindow::on_buttonHideFileFrame_clicked() { bool hidden = !ui->frameFile->isHidden(); - ui->buttonHideFileFrame->setText( hidden ? "+" : " -"); - ui->frameFile->setHidden( hidden ); + ui->buttonHideFileFrame->setText(hidden ? "+" : " -"); + ui->frameFile->setHidden(hidden); QSettings settings; settings.setValue("MainWindow.hiddenFileFrame", hidden); @@ -3128,8 +3201,8 @@ void MainWindow::on_buttonHideFileFrame_clicked() void MainWindow::on_buttonHideStreamingFrame_clicked() { bool hidden = !ui->frameStreaming->isHidden(); - ui->buttonHideStreamingFrame->setText( hidden ? "+" : " -"); - ui->frameStreaming->setHidden( hidden ); + ui->buttonHideStreamingFrame->setText(hidden ? "+" : " -"); + ui->frameStreaming->setHidden(hidden); QSettings settings; settings.setValue("MainWindow.hiddenStreamingFrame", hidden); @@ -3138,8 +3211,8 @@ void MainWindow::on_buttonHideStreamingFrame_clicked() void MainWindow::on_buttonHidePublishersFrame_clicked() { bool hidden = !ui->framePublishers->isHidden(); - ui->buttonHidePublishersFrame->setText( hidden ? "+" : " -"); - ui->framePublishers->setHidden( hidden ); + ui->buttonHidePublishersFrame->setText(hidden ? "+" : " -"); + ui->framePublishers->setHidden(hidden); QSettings settings; settings.setValue("MainWindow.hiddenPublishersFrame", hidden); @@ -3149,33 +3222,33 @@ void MainWindow::on_buttonRecentLayout_clicked() { PopupMenu* menu = new PopupMenu(ui->buttonRecentLayout, this); - for(auto action: _recent_layout_files->actions()) { + for (auto action : _recent_layout_files->actions()) + { menu->addAction(action); } menu->exec(); } - QStringList MainWindow::readAllCurvesFromXML(QDomElement root_node) { QStringList curves; - QStringList level_names = - {"tabbed_widget", "Tab", "Container", - "DockSplitter", "DockArea", "plot", "curve" }; + QStringList level_names = { "tabbed_widget", "Tab", "Container", "DockSplitter", + "DockArea", "plot", "curve" }; - std::function recursiveXmlStream; - recursiveXmlStream = [&](int level, QDomElement parent_elem) - { - QString level_name = level_names[level]; - for ( auto elem = parent_elem.firstChildElement(level_name); - elem.isNull() == false; - elem = elem.nextSiblingElement(level_name)) { - if( level_name == "curve" ){ - curves.push_back( elem.attribute("name") ); + std::function recursiveXmlStream; + recursiveXmlStream = [&](int level, QDomElement parent_elem) { + QString level_name = level_names[level]; + for (auto elem = parent_elem.firstChildElement(level_name); elem.isNull() == false; + elem = elem.nextSiblingElement(level_name)) + { + if (level_name == "curve") + { + curves.push_back(elem.attribute("name")); } - else{ - recursiveXmlStream(level+1, elem); + else + { + recursiveXmlStream(level + 1, elem); } } }; @@ -3185,6 +3258,3 @@ QStringList MainWindow::readAllCurvesFromXML(QDomElement root_node) return curves; } - - - diff --git a/plotjuggler_app/mainwindow.h b/plotjuggler_app/mainwindow.h index 78bcd8365..ac91d00cd 100644 --- a/plotjuggler_app/mainwindow.h +++ b/plotjuggler_app/mainwindow.h @@ -32,7 +32,8 @@ class MainWindow : public QMainWindow Q_OBJECT public: - explicit MainWindow(const QCommandLineParser& commandline_parser, QWidget* parent = nullptr); + explicit MainWindow(const QCommandLineParser& commandline_parser, + QWidget* parent = nullptr); ~MainWindow(); @@ -40,7 +41,6 @@ class MainWindow : public QMainWindow bool loadDataFromFiles(QStringList filenames); bool loadDataFromFile(const FileLoadInfo& info); - void stopStreamingPlugin(); void startStreamingPlugin(QString streamer_name); void enableStreamingNotificationsButton(bool enabled); @@ -61,7 +61,7 @@ public slots: void on_streamingSpinBox_valueChanged(int value); - void on_comboStreaming_currentIndexChanged(const QString ¤t_text); + void on_comboStreaming_currentIndexChanged(const QString& current_text); void on_splitterMoved(int, int); @@ -171,7 +171,7 @@ public slots: void initializeActions(); QStringList initializePlugins(QString subdir_name); - void forEachWidget(std::function op); + void forEachWidget(std::function op); void forEachWidget(std::function op); void rearrangeGridLayout(); @@ -219,7 +219,7 @@ public slots: void on_actionDeleteAllData_triggered(); void on_actionClearBuffer_triggered(); - void on_deleteSerieFromGroup(std::string group_name ); + void on_deleteSerieFromGroup(std::string group_name); void on_streamingNotificationsChanged(int active_notifications_count); @@ -228,7 +228,7 @@ public slots: void on_actionReportBug_triggered(); void on_actionCheatsheet_triggered(); void on_actionSupportPlotJuggler_triggered(); -// TODO ? void on_actionSaveAllPlotTabs_triggered(); + // TODO ? void on_actionSaveAllPlotTabs_triggered(); void on_actionAbout_triggered(); void on_actionExit_triggered(); @@ -276,9 +276,9 @@ class PopupMenu : public QMenu void showEvent(QShowEvent*) override; void leaveEvent(QEvent*) override; void closeEvent(QCloseEvent*) override; + private: QWidget* _w; }; - #endif // MAINWINDOW_H diff --git a/plotjuggler_app/menubar.cpp b/plotjuggler_app/menubar.cpp index 639f4e2c6..789e7bdc4 100644 --- a/plotjuggler_app/menubar.cpp +++ b/plotjuggler_app/menubar.cpp @@ -7,7 +7,8 @@ MenuBar::MenuBar(QWidget* parent) : QMenuBar(parent) { - int font_id = QFontDatabase::addApplicationFont("://resources/DejaVuSans-ExtraLight.ttf"); + int font_id = QFontDatabase::addApplicationFont("://resources/" + "DejaVuSans-ExtraLight.ttf"); QString family = QFontDatabase::applicationFontFamilies(font_id).at(0); _font.setFamily(family); @@ -19,7 +20,7 @@ MenuBar::MenuBar(QWidget* parent) : QMenuBar(parent) _width_juggler = fm.width("Juggler"); } -//void MenuBar::paintEvent(QPaintEvent* event) +// void MenuBar::paintEvent(QPaintEvent* event) //{ // QMenuBar::paintEvent(event); // QPainter painter(this); @@ -30,12 +31,14 @@ MenuBar::MenuBar(QWidget* parent) : QMenuBar(parent) // QPoint topleft(this->rect().width() - text_width - 12, 0); // QSize rect_size(_width_plot, this->rect().height()); // painter.setPen(QColor("#dd22dd")); -// painter.drawText(QRect(topleft, rect_size), Qt::AlignHCenter | Qt::AlignVCenter, "Plot"); +// painter.drawText(QRect(topleft, rect_size), Qt::AlignHCenter | Qt::AlignVCenter, +// "Plot"); // } // { // QPoint topleft(this->rect().width() - _width_juggler - 10, 0); // QSize rect_size(_width_juggler, this->rect().height()); // painter.setPen(QColor("#2288ff")); -// painter.drawText(QRect(topleft, rect_size), Qt::AlignHCenter | Qt::AlignVCenter, "Juggler"); +// painter.drawText(QRect(topleft, rect_size), Qt::AlignHCenter | Qt::AlignVCenter, +// "Juggler"); // } //} diff --git a/plotjuggler_app/menubar.h b/plotjuggler_app/menubar.h index 9a7024a2c..48ea45e81 100644 --- a/plotjuggler_app/menubar.h +++ b/plotjuggler_app/menubar.h @@ -9,7 +9,7 @@ class MenuBar : public QMenuBar { public: MenuBar(QWidget* parent); - // void paintEvent(QPaintEvent* event); + // void paintEvent(QPaintEvent* event); private: QFont _font; diff --git a/plotjuggler_app/messageparser_base.cpp b/plotjuggler_app/messageparser_base.cpp index a0de4978f..2b1aded0c 100644 --- a/plotjuggler_app/messageparser_base.cpp +++ b/plotjuggler_app/messageparser_base.cpp @@ -1,7 +1 @@ #include "PlotJuggler/messageparser_base.h" - - - - - - diff --git a/plotjuggler_app/new_release_dialog.cpp b/plotjuggler_app/new_release_dialog.cpp index f191db521..7836ff8e3 100644 --- a/plotjuggler_app/new_release_dialog.cpp +++ b/plotjuggler_app/new_release_dialog.cpp @@ -5,13 +5,15 @@ #include #include -NewReleaseDialog::NewReleaseDialog(QWidget* parent, QString release, QString title, QString url) +NewReleaseDialog::NewReleaseDialog(QWidget* parent, QString release, QString title, + QString url) : QDialog(parent), ui(new Ui::NewReleaseDialog) { ui->setupUi(this); setWindowFlags(Qt::WindowStaysOnTopHint); - connect(ui->pushButtonWeb, &QPushButton::clicked, this, [=] { QDesktopServices::openUrl(QUrl(url)); }); + connect(ui->pushButtonWeb, &QPushButton::clicked, this, + [=] { QDesktopServices::openUrl(QUrl(url)); }); connect(ui->buttonBox, &QDialogButtonBox::rejected, this, [=] { if (ui->dontShowAgain->isChecked()) diff --git a/plotjuggler_app/nlohmann_parsers.cpp b/plotjuggler_app/nlohmann_parsers.cpp index 695f8c000..ca366e0aa 100644 --- a/plotjuggler_app/nlohmann_parsers.cpp +++ b/plotjuggler_app/nlohmann_parsers.cpp @@ -2,96 +2,92 @@ #include "PlotJuggler/fmt/format.h" -bool NlohmannParser::parseMessageImpl(double ×tamp) +bool NlohmannParser::parseMessageImpl(double& timestamp) { - if (_use_message_stamp){ - - auto ts = _json.find("timestamp"); - if( ts != _json.end() && ts.value().is_number()) - { - timestamp = ts.value().get(); - } + if (_use_message_stamp) + { + auto ts = _json.find("timestamp"); + if (ts != _json.end() && ts.value().is_number()) + { + timestamp = ts.value().get(); } + } - std::function flatten; + std::function flatten; - flatten =[&](const std::string& prefix, - const nlohmann::json& value) + flatten = [&](const std::string& prefix, const nlohmann::json& value) { + if (value.empty()) { - if (value.empty()){ - return; - } + return; + } - switch (value.type()) + switch (value.type()) + { + case nlohmann::detail::value_t::array: { + // iterate array and use index as reference string + for (std::size_t i = 0; i < value.size(); ++i) { - case nlohmann::detail::value_t::array:{ - // iterate array and use index as reference string - for (std::size_t i = 0; i < value.size(); ++i) { - flatten( fmt::format("{}[{}]", prefix, i), value[i]); - } - break; + flatten(fmt::format("{}[{}]", prefix, i), value[i]); } + break; + } - case nlohmann::detail::value_t::object:{ - // iterate object and use keys as reference string - for(const auto& element: value.items()) { - flatten( fmt::format("{}/{}", prefix, element.key()), element.value()); - } - break; + case nlohmann::detail::value_t::object: { + // iterate object and use keys as reference string + for (const auto& element : value.items()) + { + flatten(fmt::format("{}/{}", prefix, element.key()), element.value()); } + break; + } - default:{ - double numeric_value = 0; - if( value.is_boolean()) { - numeric_value = value.get(); - } - else if( value.is_number()) { - numeric_value = value.get(); - } - else{ - return; - } + default: { + double numeric_value = 0; + if (value.is_boolean()) + { + numeric_value = value.get(); + } + else if (value.is_number()) + { + numeric_value = value.get(); + } + else + { + return; + } - auto plot_data = &(getSeries(prefix)); - plot_data->pushBack( {timestamp, numeric_value} ); + auto plot_data = &(getSeries(prefix)); + plot_data->pushBack({ timestamp, numeric_value }); - break; - } - } // end switch - }; + break; + } + } // end switch + }; - flatten(_topic_name, _json); - return true; + flatten(_topic_name, _json); + return true; } -bool MessagePack_Parser::parseMessage(const MessageRef msg, - double& timestamp) +bool MessagePack_Parser::parseMessage(const MessageRef msg, double& timestamp) { - _json = nlohmann::json::from_msgpack( msg.data(), - msg.data() + msg.size() ); - return parseMessageImpl(timestamp); + _json = nlohmann::json::from_msgpack(msg.data(), msg.data() + msg.size()); + return parseMessageImpl(timestamp); } -bool JSON_Parser::parseMessage(const MessageRef msg, - double& timestamp) +bool JSON_Parser::parseMessage(const MessageRef msg, double& timestamp) { - _json = nlohmann::json::parse( msg.data(), - msg.data()+ msg.size()); - return parseMessageImpl(timestamp); + _json = nlohmann::json::parse(msg.data(), msg.data() + msg.size()); + return parseMessageImpl(timestamp); } -bool CBOR_Parser::parseMessage(const MessageRef msg, - double& timestamp) +bool CBOR_Parser::parseMessage(const MessageRef msg, double& timestamp) { - _json = nlohmann::json::from_cbor( msg.data(), - msg.data()+ msg.size() ); - return parseMessageImpl(timestamp); + _json = nlohmann::json::from_cbor(msg.data(), msg.data() + msg.size()); + return parseMessageImpl(timestamp); } -bool BSON_Parser::parseMessage(const MessageRef msg, - double& timestamp) +bool BSON_Parser::parseMessage(const MessageRef msg, double& timestamp) { - _json = nlohmann::json::from_bson( msg.data(), - msg.data()+ msg.size() ); - return parseMessageImpl(timestamp); + _json = nlohmann::json::from_bson(msg.data(), msg.data() + msg.size()); + return parseMessageImpl(timestamp); } diff --git a/plotjuggler_app/nlohmann_parsers.h b/plotjuggler_app/nlohmann_parsers.h index dc05acb9b..0939dbf6b 100644 --- a/plotjuggler_app/nlohmann_parsers.h +++ b/plotjuggler_app/nlohmann_parsers.h @@ -8,77 +8,81 @@ using namespace PJ; - -class NlohmannParser: public MessageParser +class NlohmannParser : public MessageParser { public: - - NlohmannParser(const std::string& topic_name, PlotDataMapRef& data, bool use_msg_stamp): - MessageParser(topic_name, data), - _use_message_stamp(use_msg_stamp) {} + NlohmannParser(const std::string& topic_name, PlotDataMapRef& data, bool use_msg_stamp) + : MessageParser(topic_name, data), _use_message_stamp(use_msg_stamp) + { + } protected: - bool parseMessageImpl(double& timestamp); nlohmann::json _json; bool _use_message_stamp; }; - -class JSON_Parser: public NlohmannParser +class JSON_Parser : public NlohmannParser { public: - JSON_Parser(const std::string& topic_name, PlotDataMapRef& data, bool use_msg_stamp): - NlohmannParser(topic_name, data,use_msg_stamp) - {} + JSON_Parser(const std::string& topic_name, PlotDataMapRef& data, bool use_msg_stamp) + : NlohmannParser(topic_name, data, use_msg_stamp) + { + } - bool parseMessage(const MessageRef msg, double ×tamp) override; + bool parseMessage(const MessageRef msg, double& timestamp) override; }; -class CBOR_Parser: public NlohmannParser +class CBOR_Parser : public NlohmannParser { public: - CBOR_Parser(const std::string& topic_name, PlotDataMapRef& data, bool use_msg_stamp): - NlohmannParser(topic_name, data,use_msg_stamp) - {} + CBOR_Parser(const std::string& topic_name, PlotDataMapRef& data, bool use_msg_stamp) + : NlohmannParser(topic_name, data, use_msg_stamp) + { + } - bool parseMessage(const MessageRef msg, double ×tamp) override; + bool parseMessage(const MessageRef msg, double& timestamp) override; }; -class BSON_Parser: public NlohmannParser +class BSON_Parser : public NlohmannParser { public: - BSON_Parser(const std::string& topic_name, PlotDataMapRef& data, bool use_msg_stamp): - NlohmannParser(topic_name, data,use_msg_stamp) - {} + BSON_Parser(const std::string& topic_name, PlotDataMapRef& data, bool use_msg_stamp) + : NlohmannParser(topic_name, data, use_msg_stamp) + { + } - bool parseMessage(const MessageRef msg, double ×tamp) override; + bool parseMessage(const MessageRef msg, double& timestamp) override; }; -class MessagePack_Parser: public NlohmannParser +class MessagePack_Parser : public NlohmannParser { public: - MessagePack_Parser(const std::string& topic_name, PlotDataMapRef& data, bool use_msg_stamp): - NlohmannParser(topic_name, data,use_msg_stamp) - {} + MessagePack_Parser(const std::string& topic_name, PlotDataMapRef& data, + bool use_msg_stamp) + : NlohmannParser(topic_name, data, use_msg_stamp) + { + } - bool parseMessage(const MessageRef msg, double ×tamp) override; + bool parseMessage(const MessageRef msg, double& timestamp) override; }; //------------------------------------------ -class QCheckBoxClose: public QCheckBox +class QCheckBoxClose : public QCheckBox { public: - QCheckBoxClose(QString text): QCheckBox(text) {} + QCheckBoxClose(QString text) : QCheckBox(text) + { + } ~QCheckBoxClose() override { qDebug() << "Destroying QCheckBoxClose"; } }; -class NlohmannParserCreator: public MessageParserCreator +class NlohmannParserCreator : public MessageParserCreator { public: NlohmannParserCreator() @@ -98,42 +102,61 @@ class NlohmannParserCreator: public MessageParserCreator class JSON_ParserCreator : public NlohmannParserCreator { public: - - MessageParserPtr createInstance(const std::string& topic_name, PlotDataMapRef& data) override { - return std::make_shared(topic_name, data, _checkbox_use_timestamp->isChecked()); + MessageParserPtr createInstance(const std::string& topic_name, + PlotDataMapRef& data) override + { + return std::make_shared(topic_name, data, + _checkbox_use_timestamp->isChecked()); + } + const char* name() const override + { + return "JSON"; } - const char* name() const override { return "JSON"; } }; class CBOR_ParserCreator : public NlohmannParserCreator { public: - - MessageParserPtr createInstance(const std::string& topic_name, PlotDataMapRef& data) override { - return std::make_shared(topic_name, data, _checkbox_use_timestamp->isChecked()); + MessageParserPtr createInstance(const std::string& topic_name, + PlotDataMapRef& data) override + { + return std::make_shared(topic_name, data, + _checkbox_use_timestamp->isChecked()); + } + const char* name() const override + { + return "CBOR"; } - const char* name() const override { return "CBOR"; } }; class BSON_ParserCreator : public NlohmannParserCreator { public: - - MessageParserPtr createInstance(const std::string& topic_name, PlotDataMapRef& data) override { - return std::make_shared(topic_name, data, _checkbox_use_timestamp->isChecked()); + MessageParserPtr createInstance(const std::string& topic_name, + PlotDataMapRef& data) override + { + return std::make_shared(topic_name, data, + _checkbox_use_timestamp->isChecked()); + } + const char* name() const override + { + return "BSON"; } - const char* name() const override { return "BSON"; } }; class MessagePack_ParserCreator : public NlohmannParserCreator { public: - - MessageParserPtr createInstance(const std::string& topic_name, PlotDataMapRef& data) override { - return std::make_shared(topic_name, data, _checkbox_use_timestamp->isChecked()); + MessageParserPtr createInstance(const std::string& topic_name, + PlotDataMapRef& data) override + { + return std::make_shared(topic_name, data, + _checkbox_use_timestamp->isChecked()); + } + const char* name() const override + { + return "MessagePack"; } - const char* name() const override { return "MessagePack"; } }; - -#endif // NLOHMANN_PARSERS_H +#endif // NLOHMANN_PARSERS_H diff --git a/plotjuggler_app/plot_docker.cpp b/plotjuggler_app/plot_docker.cpp index 29c60d058..f4fdf4b82 100644 --- a/plotjuggler_app/plot_docker.cpp +++ b/plotjuggler_app/plot_docker.cpp @@ -13,30 +13,29 @@ class SplittableComponentsFactory : public ads::CDockComponentsFactory { public: - ads::CDockAreaTitleBar* createDockAreaTitleBar(ads::CDockAreaWidget* dock_area) const override + ads::CDockAreaTitleBar* + createDockAreaTitleBar(ads::CDockAreaWidget* dock_area) const override { - auto title_bar = new ads::CDockAreaTitleBar(dock_area); + auto title_bar = new ads::CDockAreaTitleBar(dock_area); title_bar->setVisible(false); return title_bar; } }; - -PlotDocker::PlotDocker(QString name, PlotDataMapRef& datamap, QWidget *parent): - ads::CDockManager(parent), _name(name), _datamap(datamap) +PlotDocker::PlotDocker(QString name, PlotDataMapRef& datamap, QWidget* parent) + : ads::CDockManager(parent), _name(name), _datamap(datamap) { ads::CDockComponentsFactory::setFactory(new SplittableComponentsFactory()); - auto CreateFirstWidget = [&]() - { - if( dockAreaCount() == 0) + auto CreateFirstWidget = [&]() { + if (dockAreaCount() == 0) { DockWidget* widget = new DockWidget(datamap, this); auto area = addDockWidget(ads::TopDockWidgetArea, widget); area->setAllowedAreas(ads::OuterDockAreas); - this->plotWidgetAdded( widget->plotWidget() ); + this->plotWidgetAdded(widget->plotWidget()); connect(widget, &DockWidget::undoableChange, this, &PlotDocker::undoableChange); } @@ -49,7 +48,8 @@ PlotDocker::PlotDocker(QString name, PlotDataMapRef& datamap, QWidget *parent): CreateFirstWidget(); } -QString PlotDocker::name() const{ +QString PlotDocker::name() const +{ return _name; } @@ -58,59 +58,60 @@ void PlotDocker::setName(QString name) _name = name; } - -QDomElement saveChildNodesState(QDomDocument &doc, QWidget* widget) +QDomElement saveChildNodesState(QDomDocument& doc, QWidget* widget) { - QSplitter* splitter = qobject_cast(widget); - if (splitter) + QSplitter* splitter = qobject_cast(widget); + if (splitter) + { + QDomElement splitter_elem = doc.createElement("DockSplitter"); + splitter_elem.setAttribute("orientation", + (splitter->orientation() == Qt::Horizontal) ? "|" : "-"); + splitter_elem.setAttribute("count", QString::number(splitter->count())); + + QString sizes_str; + int total_size = 0; + for (int size : splitter->sizes()) { - QDomElement splitter_elem = doc.createElement("DockSplitter"); - splitter_elem.setAttribute("orientation", (splitter->orientation() == Qt::Horizontal) ? "|" : "-"); - splitter_elem.setAttribute("count", QString::number(splitter->count())); - - QString sizes_str; - int total_size = 0; - for(int size : splitter->sizes() ) - { - total_size += size; - } - for(int size : splitter->sizes() ) - { - sizes_str += QString::number( double(size)/double(total_size) ); - sizes_str += ";"; - } - sizes_str.resize( sizes_str.size()-1 ); - splitter_elem.setAttribute("sizes", sizes_str); + total_size += size; + } + for (int size : splitter->sizes()) + { + sizes_str += QString::number(double(size) / double(total_size)); + sizes_str += ";"; + } + sizes_str.resize(sizes_str.size() - 1); + splitter_elem.setAttribute("sizes", sizes_str); - for (int i = 0; i < splitter->count(); ++i) - { - auto child = saveChildNodesState(doc, splitter->widget(i)); - splitter_elem.appendChild( child ); - } - return splitter_elem; + for (int i = 0; i < splitter->count(); ++i) + { + auto child = saveChildNodesState(doc, splitter->widget(i)); + splitter_elem.appendChild(child); } - else{ - ads::CDockAreaWidget* dockArea = qobject_cast(widget); - if (dockArea) + return splitter_elem; + } + else + { + ads::CDockAreaWidget* dockArea = qobject_cast(widget); + if (dockArea) + { + QDomElement area_elem = doc.createElement("DockArea"); + for (int i = 0; i < dockArea->dockWidgetsCount(); ++i) { - QDomElement area_elem = doc.createElement("DockArea"); - for (int i = 0; i < dockArea->dockWidgetsCount(); ++i) + auto dock_widget = dynamic_cast(dockArea->dockWidget(i)); + if (dock_widget) { - auto dock_widget = dynamic_cast( dockArea->dockWidget(i) ); - if( dock_widget ) - { - auto plotwidget_elem = dock_widget->plotWidget()->xmlSaveState(doc); - area_elem.appendChild( plotwidget_elem ); - area_elem.setAttribute("name", dock_widget->toolBar()->label()->text()); - } + auto plotwidget_elem = dock_widget->plotWidget()->xmlSaveState(doc); + area_elem.appendChild(plotwidget_elem); + area_elem.setAttribute("name", dock_widget->toolBar()->label()->text()); } - return area_elem; } + return area_elem; } - return {}; + } + return {}; } -QDomElement PlotDocker::xmlSaveState(QDomDocument &doc) const +QDomElement PlotDocker::xmlSaveState(QDomDocument& doc) const { QDomElement containers_elem = doc.createElement("Tab"); @@ -137,31 +138,33 @@ void PlotDocker::restoreSplitter(QDomElement elem, DockWidget* widget) return; } - Qt::Orientation orientation = orientation_str.startsWith("|") ? Qt::Horizontal : Qt::Vertical; + Qt::Orientation orientation = + orientation_str.startsWith("|") ? Qt::Horizontal : Qt::Vertical; std::vector widgets(splitter_count); widgets[0] = widget; - for (int i=1; isplitHorizontal() : widget->splitVertical(); + widget = (orientation == Qt::Horizontal) ? widget->splitHorizontal() : + widget->splitVertical(); widgets[i] = widget; } int tot_size = 0; - for (int i=0; iwidth() : widgets[i]->height(); + tot_size += + (orientation == Qt::Horizontal) ? widgets[i]->width() : widgets[i]->height(); } auto sizes_str = elem.attribute("sizes").splitRef(";", QString::SkipEmptyParts); QList sizes; - for (int i=0; i(sizes_str[i].toDouble() * tot_size) ); + sizes.push_back(static_cast(sizes_str[i].toDouble() * tot_size)); } auto splitter = ads::internal::findParent(widget); @@ -172,22 +175,23 @@ void PlotDocker::restoreSplitter(QDomElement elem, DockWidget* widget) QDomElement child_elem = elem.firstChildElement(); while (child_elem.isNull() == false) { - if( child_elem.tagName() == "DockArea" ) + if (child_elem.tagName() == "DockArea") { auto plot_elem = child_elem.firstChildElement("plot"); widgets[index]->plotWidget()->xmlLoadState(plot_elem); - if( child_elem.hasAttribute("name") ) + if (child_elem.hasAttribute("name")) { QString area_name = child_elem.attribute("name"); widgets[index]->toolBar()->label()->setText(area_name); } index++; } - else if( child_elem.tagName() == "DockSplitter" ) + else if (child_elem.tagName() == "DockSplitter") { - restoreSplitter(child_elem, widgets[index++]); + restoreSplitter(child_elem, widgets[index++]); } - else{ + else + { return; } @@ -195,7 +199,7 @@ void PlotDocker::restoreSplitter(QDomElement elem, DockWidget* widget) } }; -bool PlotDocker::xmlLoadState(QDomElement &tab_element) +bool PlotDocker::xmlLoadState(QDomElement& tab_element) { if (!isHidden()) { @@ -203,14 +207,15 @@ bool PlotDocker::xmlLoadState(QDomElement &tab_element) } for (auto container_elem = tab_element.firstChildElement("Container"); - !container_elem.isNull(); - container_elem = container_elem.nextSiblingElement("Container")) + !container_elem.isNull(); container_elem = container_elem.nextSiblingElement("Cont" + "aine" + "r")) { auto splitter_elem = container_elem.firstChildElement("DockSplitter"); - if( !splitter_elem.isNull()) + if (!splitter_elem.isNull()) { - auto widget = dynamic_cast( dockArea(0)->currentDockWidget()); - restoreSplitter(splitter_elem, widget ); + auto widget = dynamic_cast(dockArea(0)->currentDockWidget()); + restoreSplitter(splitter_elem, widget); } } @@ -223,13 +228,14 @@ bool PlotDocker::xmlLoadState(QDomElement &tab_element) int PlotDocker::plotCount() const { - return dockAreaCount(); + return dockAreaCount(); } -PlotWidget *PlotDocker::plotAt(int index) +PlotWidget* PlotDocker::plotAt(int index) { - DockWidget* dock_widget = dynamic_cast( dockArea(index)->currentDockWidget() ); - return static_cast(dock_widget->plotWidget() ); + DockWidget* dock_widget = + dynamic_cast(dockArea(index)->currentDockWidget()); + return static_cast(dock_widget->plotWidget()); } void PlotDocker::setHorizontalLink(bool enabled) @@ -241,7 +247,7 @@ void PlotDocker::zoomOut() { for (int index = 0; index < plotCount(); index++) { - plotAt(index)->zoomOut(false); // TODO is it false? + plotAt(index)->zoomOut(false); // TODO is it false? } } @@ -257,20 +263,20 @@ void PlotDocker::on_stylesheetChanged(QString theme) { for (int index = 0; index < plotCount(); index++) { - auto dock_widget = static_cast( dockArea(index)->currentDockWidget()); + auto dock_widget = static_cast(dockArea(index)->currentDockWidget()); dock_widget->toolBar()->on_stylesheetChanged(theme); } } -DockWidget::DockWidget(PlotDataMapRef& datamap, QWidget *parent): - ads::CDockWidget("Plot", parent), _datamap(datamap) +DockWidget::DockWidget(PlotDataMapRef& datamap, QWidget* parent) + : ads::CDockWidget("Plot", parent), _datamap(datamap) { setFrameShape(QFrame::NoFrame); static int plot_count = 0; QString plot_name = QString("_plot_%1_").arg(plot_count++); _plot_widget = new PlotWidget(datamap, this); - setWidget( _plot_widget->widget() ); + setWidget(_plot_widget->widget()); setFeature(ads::CDockWidget::DockWidgetFloatable, false); setFeature(ads::CDockWidget::DockWidgetDeleteOnClose, true); @@ -278,25 +284,23 @@ DockWidget::DockWidget(PlotDataMapRef& datamap, QWidget *parent): _toolbar->label()->setText("..."); qobject_cast(layout())->insertWidget(0, _toolbar); - connect(_toolbar->buttonSplitHorizontal(), &QPushButton::clicked, - this, &DockWidget::splitHorizontal); + connect(_toolbar->buttonSplitHorizontal(), &QPushButton::clicked, this, + &DockWidget::splitHorizontal); - connect(_toolbar->buttonSplitVertical(), &QPushButton::clicked, - this, &DockWidget::splitVertical); + connect(_toolbar->buttonSplitVertical(), &QPushButton::clicked, this, + &DockWidget::splitVertical); - connect(_plot_widget, &PlotWidget::splitHorizontal, - this, &DockWidget::splitHorizontal); + connect(_plot_widget, &PlotWidget::splitHorizontal, this, &DockWidget::splitHorizontal); - connect(_plot_widget, &PlotWidget::splitVertical, - this, &DockWidget::splitVertical); + connect(_plot_widget, &PlotWidget::splitVertical, this, &DockWidget::splitVertical); auto FullscreenAction = [=]() { - PlotDocker* parent_docker = static_cast( dockManager() ); + PlotDocker* parent_docker = static_cast(dockManager()); this->toolBar()->toggleFullscreen(); - bool fullscreen = this->toolBar()->isFullscreen(); + bool fullscreen = this->toolBar()->isFullscreen(); - for(int i = 0; i < parent_docker->dockAreaCount(); i++ ) + for (int i = 0; i < parent_docker->dockAreaCount(); i++) { auto area = parent_docker->dockArea(i); if (area != dockAreaWidget()) @@ -307,20 +311,18 @@ DockWidget::DockWidget(PlotDataMapRef& datamap, QWidget *parent): } }; - QObject::connect(_toolbar->buttonFullscreen(), &QPushButton::clicked, FullscreenAction ); + QObject::connect(_toolbar->buttonFullscreen(), &QPushButton::clicked, FullscreenAction); - QObject::connect(_toolbar->buttonClose(), &QPushButton::pressed, [=]() - { - dockAreaWidget()->closeArea(); - this->undoableChange(); - } ); + QObject::connect(_toolbar->buttonClose(), &QPushButton::pressed, [=]() { + dockAreaWidget()->closeArea(); + this->undoableChange(); + }); this->layout()->setMargin(10); } DockWidget::~DockWidget() { - } DockWidget* DockWidget::splitHorizontal() @@ -328,13 +330,13 @@ DockWidget* DockWidget::splitHorizontal() // create a sibling (same parent) auto new_widget = new DockWidget(_datamap, qobject_cast(parent())); - PlotDocker* parent_docker = static_cast( dockManager() ); - auto area = parent_docker->addDockWidget(ads::RightDockWidgetArea, - new_widget, dockAreaWidget()); + PlotDocker* parent_docker = static_cast(dockManager()); + auto area = parent_docker->addDockWidget(ads::RightDockWidgetArea, new_widget, + dockAreaWidget()); area->setAllowedAreas(ads::OuterDockAreas); - parent_docker->plotWidgetAdded( new_widget->plotWidget() ); + parent_docker->plotWidgetAdded(new_widget->plotWidget()); connect(this, &DockWidget::undoableChange, parent_docker, &PlotDocker::undoableChange); @@ -347,13 +349,13 @@ DockWidget* DockWidget::splitVertical() { auto new_widget = new DockWidget(_datamap, qobject_cast(parent())); - PlotDocker* parent_docker = static_cast( dockManager() ); + PlotDocker* parent_docker = static_cast(dockManager()); - auto area = parent_docker->addDockWidget(ads::BottomDockWidgetArea, - new_widget, dockAreaWidget()); + auto area = parent_docker->addDockWidget(ads::BottomDockWidgetArea, new_widget, + dockAreaWidget()); area->setAllowedAreas(ads::OuterDockAreas); - parent_docker->plotWidgetAdded( new_widget->plotWidget() ); + parent_docker->plotWidgetAdded(new_widget->plotWidget()); connect(this, &DockWidget::undoableChange, parent_docker, &PlotDocker::undoableChange); @@ -362,12 +364,12 @@ DockWidget* DockWidget::splitVertical() return new_widget; } -PlotWidget *DockWidget::plotWidget() +PlotWidget* DockWidget::plotWidget() { return _plot_widget; } -DraggableToolbar *DockWidget::toolBar() +DraggableToolbar* DockWidget::toolBar() { return _toolbar; } @@ -378,11 +380,11 @@ static void setButtonIcon(QPushButton* button, QIcon icon) button->setText(""); } -DraggableToolbar::DraggableToolbar(ads::CDockWidget* parent) : - QWidget(parent), - _parent(parent), - ui(new Ui::DraggableToolbar), - _fullscreen_mode(false) +DraggableToolbar::DraggableToolbar(ads::CDockWidget* parent) + : QWidget(parent) + , _parent(parent) + , ui(new Ui::DraggableToolbar) + , _fullscreen_mode(false) { ui->setupUi(this); @@ -390,9 +392,9 @@ DraggableToolbar::DraggableToolbar(ads::CDockWidget* parent) : QString theme = settings.value("StyleSheet::theme", "light").toString(); on_stylesheetChanged(theme); - ui->buttonFullscreen->setVisible( false ); - ui->buttonSplitHorizontal->setVisible( false ); - ui->buttonSplitVertical->setVisible( false ); + ui->buttonFullscreen->setVisible(false); + ui->buttonSplitHorizontal->setVisible(false); + ui->buttonSplitVertical->setVisible(false); setMouseTracking(true); ui->widgetButtons->setMouseTracking(true); @@ -409,61 +411,64 @@ void DraggableToolbar::toggleFullscreen() { _fullscreen_mode = !_fullscreen_mode; - setButtonIcon(ui->buttonFullscreen, _fullscreen_mode ? _collapse_icon : _expand_icon ); + setButtonIcon(ui->buttonFullscreen, _fullscreen_mode ? _collapse_icon : _expand_icon); ui->buttonClose->setHidden(_fullscreen_mode); - if( _fullscreen_mode ){ - ui->buttonSplitHorizontal->setVisible( false ); - ui->buttonSplitVertical->setVisible( false ); + if (_fullscreen_mode) + { + ui->buttonSplitHorizontal->setVisible(false); + ui->buttonSplitVertical->setVisible(false); } } -void DraggableToolbar::mousePressEvent(QMouseEvent *ev) +void DraggableToolbar::mousePressEvent(QMouseEvent* ev) { _parent->dockAreaWidget()->titleBar()->mousePressEvent(ev); } -void DraggableToolbar::mouseReleaseEvent(QMouseEvent *ev) +void DraggableToolbar::mouseReleaseEvent(QMouseEvent* ev) { _parent->dockAreaWidget()->titleBar()->mouseReleaseEvent(ev); } -void DraggableToolbar::mouseMoveEvent(QMouseEvent *ev) +void DraggableToolbar::mouseMoveEvent(QMouseEvent* ev) { - ui->buttonFullscreen->setVisible( true ); - ui->buttonSplitHorizontal->setVisible( !_fullscreen_mode ); - ui->buttonSplitVertical->setVisible( !_fullscreen_mode ); + ui->buttonFullscreen->setVisible(true); + ui->buttonSplitHorizontal->setVisible(!_fullscreen_mode); + ui->buttonSplitVertical->setVisible(!_fullscreen_mode); _parent->dockAreaWidget()->titleBar()->mouseMoveEvent(ev); ev->accept(); QWidget::mouseMoveEvent(ev); } -void DraggableToolbar::enterEvent(QEvent *ev) +void DraggableToolbar::enterEvent(QEvent* ev) { - ui->buttonFullscreen->setVisible( true ); - ui->buttonSplitHorizontal->setVisible( !_fullscreen_mode ); - ui->buttonSplitVertical->setVisible( !_fullscreen_mode ); + ui->buttonFullscreen->setVisible(true); + ui->buttonSplitHorizontal->setVisible(!_fullscreen_mode); + ui->buttonSplitVertical->setVisible(!_fullscreen_mode); ev->accept(); QWidget::enterEvent(ev); } -bool DraggableToolbar::eventFilter(QObject *object, QEvent *event) +bool DraggableToolbar::eventFilter(QObject* object, QEvent* event) { - if(event->type() == QEvent::MouseButtonDblClick) + if (event->type() == QEvent::MouseButtonDblClick) { bool ok = true; - QString newName = QInputDialog::getText(this, tr("Change name of the Area"), tr("New name:"), - QLineEdit::Normal, ui->label->text(), &ok); + QString newName = + QInputDialog::getText(this, tr("Change name of the Area"), tr("New name:"), + QLineEdit::Normal, ui->label->text(), &ok); if (ok) { ui->label->setText(newName); } return true; } - else{ - return QObject::eventFilter(object,event); + else + { + return QObject::eventFilter(object, event); } } @@ -471,18 +476,17 @@ void DraggableToolbar::on_stylesheetChanged(QString theme) { _expand_icon = LoadSvg(":/resources/svg/expand.svg", theme); _collapse_icon = LoadSvg(":/resources/svg/collapse.svg", theme); - setButtonIcon(ui->buttonFullscreen, _fullscreen_mode ? _collapse_icon : _expand_icon ); - setButtonIcon(ui->buttonClose, LoadSvg( ":/resources/svg/close-button.svg", theme)); - setButtonIcon(ui->buttonSplitHorizontal, LoadSvg(":/resources/svg/add_column.svg", theme)); - setButtonIcon(ui->buttonSplitVertical, LoadSvg(":/resources/svg/add_row.svg", theme)); + setButtonIcon(ui->buttonFullscreen, _fullscreen_mode ? _collapse_icon : _expand_icon); + setButtonIcon(ui->buttonClose, LoadSvg(":/resources/svg/close-button.svg", theme)); + setButtonIcon(ui->buttonSplitHorizontal, + LoadSvg(":/resources/svg/add_column.svg", theme)); + setButtonIcon(ui->buttonSplitVertical, LoadSvg(":/resources/svg/add_row.svg", theme)); } -void DraggableToolbar::leaveEvent(QEvent *ev) +void DraggableToolbar::leaveEvent(QEvent* ev) { - ui->buttonFullscreen->setVisible( _fullscreen_mode ); - ui->buttonSplitHorizontal->setVisible( false ); - ui->buttonSplitVertical->setVisible( false ); + ui->buttonFullscreen->setVisible(_fullscreen_mode); + ui->buttonSplitHorizontal->setVisible(false); + ui->buttonSplitVertical->setVisible(false); QWidget::leaveEvent(ev); } - - diff --git a/plotjuggler_app/plot_docker.h b/plotjuggler_app/plot_docker.h index 40770f52f..c0ed0e2d8 100644 --- a/plotjuggler_app/plot_docker.h +++ b/plotjuggler_app/plot_docker.h @@ -22,19 +22,35 @@ class DraggableToolbar : public QWidget explicit DraggableToolbar(ads::CDockWidget* parent); ~DraggableToolbar() override; - QLabel* label(){ return ui->label;} - QPushButton* buttonFullscreen() { return ui->buttonFullscreen; } - QPushButton* buttonClose() { return ui->buttonClose; } - QPushButton* buttonSplitHorizontal() { return ui->buttonSplitHorizontal; } - QPushButton* buttonSplitVertical() { return ui->buttonSplitVertical; } + QLabel* label() + { + return ui->label; + } + QPushButton* buttonFullscreen() + { + return ui->buttonFullscreen; + } + QPushButton* buttonClose() + { + return ui->buttonClose; + } + QPushButton* buttonSplitHorizontal() + { + return ui->buttonSplitHorizontal; + } + QPushButton* buttonSplitVertical() + { + return ui->buttonSplitVertical; + } void toggleFullscreen(); - bool isFullscreen() const{ + bool isFullscreen() const + { return _fullscreen_mode; } - bool eventFilter(QObject* object,QEvent* event) override; + bool eventFilter(QObject* object, QEvent* event) override; public slots: @@ -44,18 +60,18 @@ public slots: void mousePressEvent(QMouseEvent* ev) override; void mouseReleaseEvent(QMouseEvent* ev) override; void mouseMoveEvent(QMouseEvent* ev) override; - void enterEvent(QEvent *) override; - void leaveEvent(QEvent *) override; + void enterEvent(QEvent*) override; + void leaveEvent(QEvent*) override; ads::CDockWidget* _parent; - Ui::DraggableToolbar *ui; + Ui::DraggableToolbar* ui; bool _fullscreen_mode; QIcon _expand_icon; QIcon _collapse_icon; }; -class DockWidget: public ads::CDockWidget +class DockWidget : public ads::CDockWidget { Q_OBJECT @@ -84,13 +100,12 @@ public slots: void undoableChange(); }; -class PlotDocker: public ads::CDockManager +class PlotDocker : public ads::CDockManager { - -Q_OBJECT + Q_OBJECT public: - PlotDocker(QString name, PlotDataMapRef &datamap, QWidget* parent = nullptr); + PlotDocker(QString name, PlotDataMapRef& datamap, QWidget* parent = nullptr); QString name() const; @@ -115,7 +130,6 @@ public slots: void on_stylesheetChanged(QString theme); private: - void restoreSplitter(QDomElement elem, DockWidget* widget); QString _name; @@ -127,8 +141,6 @@ public slots: void plotWidgetAdded(PlotWidget*); void undoableChange(); - }; - -#endif // PLOT_DOCKER_H +#endif // PLOT_DOCKER_H diff --git a/plotjuggler_app/plotwidget.cpp b/plotjuggler_app/plotwidget.cpp index 025300245..84feda402 100644 --- a/plotjuggler_app/plotwidget.cpp +++ b/plotjuggler_app/plotwidget.cpp @@ -46,7 +46,6 @@ #include "PlotJuggler/svg_util.h" #include "point_series_xy.h" - class TimeScaleDraw : public QwtScaleDraw { virtual QwtText label(double v) const @@ -72,10 +71,10 @@ PlotWidget::PlotWidget(PlotDataMapRef& datamap, QWidget* parent) , _dragging({ DragInfo::NONE, {}, nullptr }) , _time_offset(0.0) , _transform_select_dialog(nullptr) - ,_context_menu_enabled(true) + , _context_menu_enabled(true) { - connect(this, &PlotWidget::curveListChanged, - this, [this]() { this->updateMaximumZoomArea(); }); + connect(this, &PlotWidget::curveListChanged, this, + [this]() { this->updateMaximumZoomArea(); }); qwtPlot()->setAcceptDrops(true); @@ -85,14 +84,11 @@ PlotWidget::PlotWidget(PlotDataMapRef& datamap, QWidget* parent) _grid = new QwtPlotGrid(); _grid->setPen(QPen(Qt::gray, 0.0, Qt::DotLine)); - connect( this, &PlotWidgetBase::viewResized, - this, &PlotWidget::on_externallyResized); + connect(this, &PlotWidgetBase::viewResized, this, &PlotWidget::on_externallyResized); - connect( this, &PlotWidgetBase::dragEnterSignal, - this, &PlotWidget::onDragEnterEvent); + connect(this, &PlotWidgetBase::dragEnterSignal, this, &PlotWidget::onDragEnterEvent); - connect( this, &PlotWidgetBase::dropSignal, - this, &PlotWidget::onDropEvent); + connect(this, &PlotWidgetBase::dropSignal, this, &PlotWidget::onDropEvent); //------------------------- @@ -101,12 +97,12 @@ PlotWidget::PlotWidget(PlotDataMapRef& datamap, QWidget* parent) _custom_Y_limits.min = (-MAX_DOUBLE); _custom_Y_limits.max = (MAX_DOUBLE); -// QwtScaleWidget* bottomAxis = qwtPlot()->axisWidget( QwtPlot::xBottom ); -// QwtScaleWidget* leftAxis = qwtPlot()->axisWidget( QwtPlot::yLeft ); + // QwtScaleWidget* bottomAxis = qwtPlot()->axisWidget( QwtPlot::xBottom ); + // QwtScaleWidget* leftAxis = qwtPlot()->axisWidget( QwtPlot::yLeft ); -// bottomAxis->installEventFilter(this); -// leftAxis->installEventFilter(this); -// qwtPlot()->canvas()->installEventFilter(this); + // bottomAxis->installEventFilter(this); + // leftAxis->installEventFilter(this); + // qwtPlot()->canvas()->installEventFilter(this); } PlotWidget::~PlotWidget() @@ -132,36 +128,36 @@ void PlotWidget::buildActions() { QIcon iconDeleteList; - _action_edit = new QAction("&Edit curves...", this); - connect(_action_edit, &QAction::triggered, this, - [=]() - { - auto editor_dialog = new PlotwidgetEditor(this, qwtPlot()); - editor_dialog->exec(); - editor_dialog->deleteLater(); - } ); - - _action_formula = new QAction("&Apply filter to data...", this); - connect(_action_formula, &QAction::triggered, this, - [=]() - { - auto editor_dialog = new DialogTransformEditor(this); - int res = editor_dialog->exec(); - editor_dialog->deleteLater(); - if( res == QDialog::Accepted){ - emit undoableChange(); - } - } ); - - _action_split_horizontal = new QAction("&Split Horizontally", this); - connect( _action_split_horizontal, &QAction::triggered, this, &PlotWidget::splitHorizontal); - - _action_split_vertical = new QAction("&Split Vertically", this); - connect( _action_split_vertical, &QAction::triggered, this, &PlotWidget::splitVertical); + _action_edit = new QAction("&Edit curves...", this); + connect(_action_edit, &QAction::triggered, this, [=]() { + auto editor_dialog = new PlotwidgetEditor(this, qwtPlot()); + editor_dialog->exec(); + editor_dialog->deleteLater(); + }); + + _action_formula = new QAction("&Apply filter to data...", this); + connect(_action_formula, &QAction::triggered, this, [=]() { + auto editor_dialog = new DialogTransformEditor(this); + int res = editor_dialog->exec(); + editor_dialog->deleteLater(); + if (res == QDialog::Accepted) + { + emit undoableChange(); + } + }); + + _action_split_horizontal = new QAction("&Split Horizontally", this); + connect(_action_split_horizontal, &QAction::triggered, this, + &PlotWidget::splitHorizontal); + + _action_split_vertical = new QAction("&Split Vertically", this); + connect(_action_split_vertical, &QAction::triggered, this, &PlotWidget::splitVertical); _action_removeAllCurves = new QAction("&Remove ALL curves", this); - connect(_action_removeAllCurves, &QAction::triggered, this, &PlotWidget::removeAllCurves); - connect(_action_removeAllCurves, &QAction::triggered, this, &PlotWidget::undoableChange); + connect(_action_removeAllCurves, &QAction::triggered, this, + &PlotWidget::removeAllCurves); + connect(_action_removeAllCurves, &QAction::triggered, this, + &PlotWidget::undoableChange); _action_zoomOutMaximum = new QAction("&Zoom Out", this); connect(_action_zoomOutMaximum, &QAction::triggered, this, [this]() { @@ -194,16 +190,17 @@ void PlotWidget::buildActions() connect(_action_copy, &QAction::triggered, this, &PlotWidget::on_copyAction_triggered); _action_paste = new QAction("&Paste", this); - connect(_action_paste, &QAction::triggered, this, &PlotWidget::on_pasteAction_triggered); + connect(_action_paste, &QAction::triggered, this, + &PlotWidget::on_pasteAction_triggered); _action_image_to_clipboard = new QAction("&Copy image to clipboard", this); - connect(_action_image_to_clipboard, &QAction::triggered, this, &PlotWidget::on_copyToClipboard); - + connect(_action_image_to_clipboard, &QAction::triggered, this, + &PlotWidget::on_copyToClipboard); } void PlotWidget::canvasContextMenuTriggered(const QPoint& pos) { - if( _context_menu_enabled == false ) + if (_context_menu_enabled == false) { return; } @@ -211,18 +208,19 @@ void PlotWidget::canvasContextMenuTriggered(const QPoint& pos) QSettings settings; QString theme = settings.value("StyleSheet::theme", "light").toString(); - _action_removeAllCurves->setIcon( LoadSvg(":/resources/svg/trash.svg", theme) ); - _action_edit->setIcon( LoadSvg(":/resources/svg/pencil-edit.svg", theme) ); - _action_formula->setIcon( LoadSvg(":/resources/svg/Fx.svg", theme) ); - _action_split_horizontal->setIcon( LoadSvg(":/resources/svg/add_column.svg", theme) ); - _action_split_vertical->setIcon( LoadSvg(":/resources/svg/add_row.svg", theme) ); - _action_zoomOutMaximum->setIcon( LoadSvg(":/resources/svg/zoom_max.svg", theme) ); - _action_zoomOutHorizontally->setIcon( LoadSvg(":/resources/svg/zoom_horizontal.svg", theme) ); - _action_zoomOutVertically->setIcon( LoadSvg(":/resources/svg/zoom_vertical.svg", theme) ); - _action_copy->setIcon( LoadSvg(":/resources/svg/copy.svg", theme) ); - _action_paste->setIcon( LoadSvg(":/resources/svg/paste.svg", theme) ); - _action_saveToFile->setIcon( LoadSvg(":/resources/svg/save.svg", theme) ); - _action_image_to_clipboard->setIcon( LoadSvg(":/resources/svg/plot_image.svg", theme) ); + _action_removeAllCurves->setIcon(LoadSvg(":/resources/svg/trash.svg", theme)); + _action_edit->setIcon(LoadSvg(":/resources/svg/pencil-edit.svg", theme)); + _action_formula->setIcon(LoadSvg(":/resources/svg/Fx.svg", theme)); + _action_split_horizontal->setIcon(LoadSvg(":/resources/svg/add_column.svg", theme)); + _action_split_vertical->setIcon(LoadSvg(":/resources/svg/add_row.svg", theme)); + _action_zoomOutMaximum->setIcon(LoadSvg(":/resources/svg/zoom_max.svg", theme)); + _action_zoomOutHorizontally->setIcon( + LoadSvg(":/resources/svg/zoom_horizontal.svg", theme)); + _action_zoomOutVertically->setIcon(LoadSvg(":/resources/svg/zoom_vertical.svg", theme)); + _action_copy->setIcon(LoadSvg(":/resources/svg/copy.svg", theme)); + _action_paste->setIcon(LoadSvg(":/resources/svg/paste.svg", theme)); + _action_saveToFile->setIcon(LoadSvg(":/resources/svg/save.svg", theme)); + _action_image_to_clipboard->setIcon(LoadSvg(":/resources/svg/plot_image.svg", theme)); QMenu menu(qwtPlot()); @@ -244,25 +242,23 @@ void PlotWidget::canvasContextMenuTriggered(const QPoint& pos) menu.addAction(_action_saveToFile); // check the clipboard - QClipboard *clipboard = QGuiApplication::clipboard(); + QClipboard* clipboard = QGuiApplication::clipboard(); QString clipboard_text = clipboard->text(); QDomDocument doc; - bool valid_clipbaord = - ( !clipboard_text.isEmpty() && // not empty - doc.setContent(clipboard_text) && // valid xml - doc.firstChildElement().tagName() == "PlotWidgetClipBoard"); + bool valid_clipbaord = (!clipboard_text.isEmpty() && // not empty + doc.setContent(clipboard_text) && // valid xml + doc.firstChildElement().tagName() == "PlotWidgetClipBoard"); _action_paste->setEnabled(valid_clipbaord); _action_removeAllCurves->setEnabled(!curveList().empty()); _action_formula->setEnabled(!curveList().empty() && !isXYPlot()); - menu.exec( qwtPlot()->canvas()->mapToGlobal(pos)); + menu.exec(qwtPlot()->canvas()->mapToGlobal(pos)); } - - -PlotWidget::CurveInfo *PlotWidget::addCurveXY(std::string name_x, std::string name_y, QString curve_name) +PlotWidget::CurveInfo* PlotWidget::addCurveXY(std::string name_x, std::string name_y, + QString curve_name) { std::string name = curve_name.toStdString(); @@ -283,11 +279,13 @@ PlotWidget::CurveInfo *PlotWidget::addCurveXY(std::string name_x, std::string na auto curve_it = curveFromTitle(curve_name); - if (name.empty() || curve_it ) + if (name.empty() || curve_it) { int ret = QMessageBox::warning(qwtPlot(), "Missing name", - "The name of the curve is missing or exist already. Try again or abort.", - QMessageBox::Abort | QMessageBox::Retry, QMessageBox::NoButton); + "The name of the curve is missing or exist already. " + "Try again or abort.", + QMessageBox::Abort | QMessageBox::Retry, + QMessageBox::NoButton); if (ret == QMessageBox::Abort || ret == QMessageBox::NoButton) { return nullptr; @@ -335,7 +333,7 @@ PlotWidget::CurveInfo *PlotWidget::addCurveXY(std::string name_x, std::string na QColor color = getColorHint(nullptr); curve->setPen(color); - setStyle( curve, curveStyle() ); + setStyle(curve, curveStyle()); curve->setRenderHint(QwtPlotItem::RenderAntialiased, true); @@ -351,25 +349,24 @@ PlotWidget::CurveInfo *PlotWidget::addCurveXY(std::string name_x, std::string na curve_info.curve = curve; curve_info.marker = marker; curve_info.src_name = name; - curveList().push_back( curve_info ); + curveList().push_back(curve_info); return &(curveList().back()); } -PlotWidgetBase::CurveInfo *PlotWidget::addCurve(const std::string &name, - QColor color) +PlotWidgetBase::CurveInfo* PlotWidget::addCurve(const std::string& name, QColor color) { auto it = _mapped_data.numeric.find(name); if (it == _mapped_data.numeric.end()) { return nullptr; } - return PlotWidgetBase::addCurve( name, it->second, color); + return PlotWidgetBase::addCurve(name, it->second, color); } -void PlotWidget::removeCurve(const QString &title) +void PlotWidget::removeCurve(const QString& title) { - PlotWidgetBase::removeCurve( title ); + PlotWidgetBase::removeCurve(title); _tracker->redraw(); } @@ -380,9 +377,8 @@ void PlotWidget::onSourceDataRemoved(const std::string& src_name) for (auto it = curveList().begin(); it != curveList().end();) { PointSeriesXY* curve_xy = dynamic_cast(it->curve->data()); - bool remove_curve_xy = - curve_xy && (curve_xy->dataX()->plotName() == src_name || - curve_xy->dataY()->plotName() == src_name); + bool remove_curve_xy = curve_xy && (curve_xy->dataX()->plotName() == src_name || + curve_xy->dataY()->plotName() == src_name); if (it->src_name == src_name || remove_curve_xy) { @@ -393,7 +389,8 @@ void PlotWidget::onSourceDataRemoved(const std::string& src_name) it = curveList().erase(it); } - else { + else + { it++; } } @@ -407,9 +404,9 @@ void PlotWidget::onSourceDataRemoved(const std::string& src_name) void PlotWidget::removeAllCurves() { - PlotWidgetBase::removeAllCurves(); - setModeXY(false); - _tracker->redraw(); + PlotWidgetBase::removeAllCurves(); + setModeXY(false); + _tracker->redraw(); } void PlotWidget::onDragEnterEvent(QDragEnterEvent* event) @@ -446,36 +443,36 @@ void PlotWidget::onDragEnterEvent(QDragEnterEvent* event) qDebug() << "FATAL: Dragging " << _dragging.curves.size() << " curves"; return; } - if( curveList().empty() || isXYPlot()) + if (curveList().empty() || isXYPlot()) { _dragging.mode = DragInfo::NEW_XY; event->acceptProposedAction(); } - else{ + else + { event->ignore(); } } } } - void PlotWidget::onDropEvent(QDropEvent*) { bool curves_changed = false; if (_dragging.mode == DragInfo::CURVES) - { - if ( isXYPlot() && !curveList().empty()) + { + if (isXYPlot() && !curveList().empty()) { _dragging.mode = DragInfo::NONE; _dragging.curves.clear(); - QMessageBox::warning( - qwtPlot(), "Warning", - tr("This is a XY plot, you can not drop normal time series here.\n" - "Clear all curves to reset it to normal mode.")); + QMessageBox::warning(qwtPlot(), "Warning", + tr("This is a XY plot, you can not drop normal time series " + "here.\n" + "Clear all curves to reset it to normal mode.")); return; } - else if ( isXYPlot() && curveList().empty()) + else if (isXYPlot() && curveList().empty()) { setModeXY(false); } @@ -492,16 +489,14 @@ void PlotWidget::onDropEvent(QDropEvent*) { _dragging.mode = DragInfo::NONE; _dragging.curves.clear(); - QMessageBox::warning( - qwtPlot(), "Warning", - tr("To convert this widget into a XY plot, " - "you must first remove all the time series.")); + QMessageBox::warning(qwtPlot(), "Warning", + tr("To convert this widget into a XY plot, " + "you must first remove all the time series.")); return; } setModeXY(true); - addCurveXY(_dragging.curves[0].toStdString(), - _dragging.curves[1].toStdString()); + addCurveXY(_dragging.curves[0].toStdString(), _dragging.curves[1].toStdString()); curves_changed = true; } @@ -574,16 +569,19 @@ QDomElement PlotWidget::xmlSaveState(QDomDocument& doc) const if (isXYPlot()) { PointSeriesXY* curve_xy = dynamic_cast(curve->data()); - curve_el.setAttribute("curve_x", QString::fromStdString(curve_xy->dataX()->plotName())); - curve_el.setAttribute("curve_y", QString::fromStdString(curve_xy->dataY()->plotName())); + curve_el.setAttribute("curve_x", + QString::fromStdString(curve_xy->dataX()->plotName())); + curve_el.setAttribute("curve_y", + QString::fromStdString(curve_xy->dataY()->plotName())); } - else{ + else + { auto ts = dynamic_cast(curve->data()); - if(ts && ts->transform()) + if (ts && ts->transform()) { QDomElement transform_el = doc.createElement("transform"); - transform_el.setAttribute("name", ts->transformName() ); - transform_el.setAttribute("alias", ts->alias() ); + transform_el.setAttribute("name", ts->transformName()); + transform_el.setAttribute("alias", ts->alias()); ts->transform()->xmlSaveState(doc, transform_el); curve_el.appendChild(transform_el); } @@ -630,12 +628,12 @@ bool PlotWidget::xmlLoadState(QDomElement& plot_widget) curveList().clear(); // insert curves - for (QDomElement curve_element = plot_widget.firstChildElement("curve"); !curve_element.isNull(); - curve_element = curve_element.nextSiblingElement("curve")) + for (QDomElement curve_element = plot_widget.firstChildElement("curve"); + !curve_element.isNull(); curve_element = curve_element.nextSiblingElement("curve")) { QString curve_name = curve_element.attribute("name"); std::string curve_name_std = curve_name.toStdString(); - QColor color( curve_element.attribute("color")); + QColor color(curve_element.attribute("color")); bool error = false; if (!isXYPlot()) @@ -647,24 +645,24 @@ bool PlotWidget::xmlLoadState(QDomElement& plot_widget) else { auto curve_it = addCurve(curve_name_std, color); - if( ! curve_it ) + if (!curve_it) { continue; } - auto &curve = curve_it->curve; + auto& curve = curve_it->curve; curve->setPen(color, 1.3); added_curve_names.insert(curve_name_std); auto ts = dynamic_cast(curve->data()); QDomElement transform_el = curve_element.firstChildElement("transform"); - if( transform_el.isNull() == false ) + if (transform_el.isNull() == false) { - ts->setTransform( transform_el.attribute("name") ); + ts->setTransform(transform_el.attribute("name")); ts->transform()->xmlLoadState(transform_el); ts->updateCache(true); auto alias = transform_el.attribute("alias"); - ts->setAlias( alias ); - curve->setTitle( alias ); + ts->setAlias(alias); + curve->setTitle(alias); } } } @@ -681,19 +679,20 @@ bool PlotWidget::xmlLoadState(QDomElement& plot_widget) else { auto curve_it = addCurveXY(curve_x, curve_y, curve_name); - if( ! curve_it ) + if (!curve_it) { continue; } curve_it->curve->setPen(color, 1.3); - curve_it->marker->setSymbol(new QwtSymbol(QwtSymbol::Ellipse, color, QPen(Qt::black), QSize(8, 8))); + curve_it->marker->setSymbol( + new QwtSymbol(QwtSymbol::Ellipse, color, QPen(Qt::black), QSize(8, 8))); added_curve_names.insert(curve_name_std); } } if (error && !warning_message_shown) { - QMessageBox::warning( qwtPlot(), "Warning", + QMessageBox::warning(qwtPlot(), "Warning", tr("Can't find one or more curves.\n" "This message will be shown only once.")); warning_message_shown = true; @@ -721,19 +720,19 @@ bool PlotWidget::xmlLoadState(QDomElement& plot_widget) QString style = plot_widget.attribute("style"); if (style == "Lines") { - changeCurvesStyle( PlotWidgetBase::LINES ); + changeCurvesStyle(PlotWidgetBase::LINES); } else if (style == "LinesAndDots") { - changeCurvesStyle( PlotWidgetBase::LINES_AND_DOTS ); + changeCurvesStyle(PlotWidgetBase::LINES_AND_DOTS); } else if (style == "Dots") { - changeCurvesStyle( PlotWidgetBase::DOTS ); + changeCurvesStyle(PlotWidgetBase::DOTS); } - else if (style == "Sticks" ) + else if (style == "Sticks") { - changeCurvesStyle( PlotWidgetBase::STICKS ); + changeCurvesStyle(PlotWidgetBase::STICKS); } } @@ -778,11 +777,9 @@ void PlotWidget::rescaleEqualAxisScaling() rect = maxZoomRect(); } - qwtPlot()->setAxisScale(QwtPlot::yLeft, - std::min(rect.bottom(), rect.top()), + qwtPlot()->setAxisScale(QwtPlot::yLeft, std::min(rect.bottom(), rect.top()), std::max(rect.bottom(), rect.top())); - qwtPlot()->setAxisScale(QwtPlot::xBottom, - std::min(rect.left(), rect.right()), + qwtPlot()->setAxisScale(QwtPlot::xBottom, std::min(rect.left(), rect.right()), std::max(rect.left(), rect.right())); qwtPlot()->updateAxes(); } @@ -794,12 +791,10 @@ void PlotWidget::setZoomRectangle(QRectF rect, bool emit_signal) { return; } - qwtPlot()->setAxisScale(QwtPlot::yLeft, - std::min(rect.bottom(), rect.top()), - std::max(rect.bottom(), rect.top())); - qwtPlot()->setAxisScale(QwtPlot::xBottom, - std::min(rect.left(), rect.right()), - std::max(rect.left(), rect.right())); + qwtPlot()->setAxisScale(QwtPlot::yLeft, std::min(rect.bottom(), rect.top()), + std::max(rect.bottom(), rect.top())); + qwtPlot()->setAxisScale(QwtPlot::xBottom, std::min(rect.left(), rect.right()), + std::max(rect.left(), rect.right())); qwtPlot()->updateAxes(); if (isXYPlot() && keepRatioXY()) @@ -828,7 +823,8 @@ void PlotWidget::reloadPlotData() for (auto& it : curveList()) { - if (it.curve->isVisible()){ + if (it.curve->isVisible()) + { visible++; } @@ -838,7 +834,7 @@ void PlotWidget::reloadPlotData() if (data_it != _mapped_data.numeric.end()) { auto ts = dynamic_cast(it.curve->data()); - if( ts ) + if (ts) { ts->updateCache(true); } @@ -853,17 +849,16 @@ void PlotWidget::reloadPlotData() void PlotWidget::activateLegend(bool activate) { - legend()->setVisible(activate); + legend()->setVisible(activate); } - void PlotWidget::activateGrid(bool activate) { _grid->enableX(activate); _grid->enableXMin(activate); _grid->enableY(activate); _grid->enableYMin(activate); - _grid->attach( qwtPlot() ); + _grid->attach(qwtPlot()); } void PlotWidget::configureTracker(CurveTracker::Parameter val) @@ -927,8 +922,8 @@ void PlotWidget::on_changeTimeOffset(double offset) void PlotWidget::on_changeDateTimeScale(bool enable) { _use_date_time_scale = enable; - bool is_timescale = dynamic_cast( - qwtPlot()->axisScaleDraw(QwtPlot::xBottom)) != nullptr; + bool is_timescale = + dynamic_cast(qwtPlot()->axisScaleDraw(QwtPlot::xBottom)) != nullptr; if (enable && !isXYPlot()) { @@ -959,7 +954,8 @@ Range PlotWidget::getVisualizationRangeY(Range range_X) const if (lower_limit) { bottom = _custom_Y_limits.min; - if (top < bottom){ + if (top < bottom) + { top = bottom; } } @@ -967,7 +963,8 @@ Range PlotWidget::getVisualizationRangeY(Range range_X) const if (upper_limit) { top = _custom_Y_limits.max; - if (top < bottom){ + if (top < bottom) + { bottom = top; } } @@ -986,10 +983,9 @@ void PlotWidget::updateCurves() updateMaximumZoomArea(); } - void PlotWidget::on_changeCurveColor(const QString& curve_name, QColor new_color) { - for(auto& it: curveList()) + for (auto& it : curveList()) { if (it.curve->title() == curve_name) { @@ -1004,7 +1000,6 @@ void PlotWidget::on_changeCurveColor(const QString& curve_name, QColor new_color } } - void PlotWidget::on_externallyResized(const QRectF& rect) { QRectF current_rect = canvasBoundingRect(); @@ -1015,12 +1010,13 @@ void PlotWidget::on_externallyResized(const QRectF& rect) if (isXYPlot()) { - if( keepRatioXY() ) { + if (keepRatioXY()) + { rescaleEqualAxisScaling(); } emit undoableChange(); } - else if( isZoomLinkEnabled() ) + else if (isZoomLinkEnabled()) { emit rectChanged(this, rect); } @@ -1035,7 +1031,7 @@ void PlotWidget::zoomOut(bool emit_signal) return; } updateMaximumZoomArea(); - setZoomRectangle( maxZoomRect(), emit_signal); + setZoomRectangle(maxZoomRect(), emit_signal); replot(); } @@ -1063,22 +1059,24 @@ void PlotWidget::on_zoomOutVertical_triggered(bool emit_signal) void PlotWidget::setModeXY(bool enable) { - if( enable == isXYPlot() ) + if (enable == isXYPlot()) { return; } - PlotWidgetBase::setModeXY( enable ); + PlotWidgetBase::setModeXY(enable); enableTracker(!enable); - if( enable ){ + if (enable) + { QFont font_footer; font_footer.setPointSize(10); QwtText text("XY Plot"); text.setFont(font_footer); qwtPlot()->setFooter(text); } - else{ + else + { qwtPlot()->setFooter(""); } @@ -1098,7 +1096,6 @@ void PlotWidget::updateAvailableTransformers() } } - void PlotWidget::on_savePlotToFile() { QString fileName; @@ -1225,26 +1222,28 @@ void PlotWidget::on_copyAction_triggered() doc.appendChild(root); root.appendChild(el); - QClipboard *clipboard = QGuiApplication::clipboard(); - clipboard->setText( doc.toString() ); + QClipboard* clipboard = QGuiApplication::clipboard(); + clipboard->setText(doc.toString()); } void PlotWidget::on_pasteAction_triggered() { - QClipboard *clipboard = QGuiApplication::clipboard(); + QClipboard* clipboard = QGuiApplication::clipboard(); QString clipboard_text = clipboard->text(); QDomDocument doc; bool valid = doc.setContent(clipboard_text); - if( !valid ){ + if (!valid) + { return; } auto root = doc.firstChildElement(); - if( root.tagName() != "PlotWidgetClipBoard") + if (root.tagName() != "PlotWidgetClipBoard") { return; } - else{ + else + { auto el = root.firstChildElement(); xmlLoadState(el); clipboard->setText(""); @@ -1254,12 +1253,12 @@ void PlotWidget::on_pasteAction_triggered() bool PlotWidget::eventFilter(QObject* obj, QEvent* event) { - if( PlotWidgetBase::eventFilter(obj, event) ) + if (PlotWidgetBase::eventFilter(obj, event)) { return true; } - if( event->type() == QEvent::Destroy ) + if (event->type() == QEvent::Destroy) { return false; } @@ -1281,10 +1280,10 @@ void PlotWidget::overrideCursonMove() bool PlotWidget::isZoomLinkEnabled() const { - for(const auto& it: curveList() ) + for (const auto& it : curveList()) { auto series = dynamic_cast(it.curve->data()); - if( series->plotData()->attribute( PJ::DISABLE_LINKED_ZOOM).toBool() ) + if (series->plotData()->attribute(PJ::DISABLE_LINKED_ZOOM).toBool()) { return false; } @@ -1309,9 +1308,8 @@ bool PlotWidget::canvasEventFilter(QEvent* event) const QPoint press_point = mouse_event->pos(); if (mouse_event->modifiers() == Qt::ShiftModifier) // time tracker { - QPointF pointF( - qwtPlot()->invTransform(QwtPlot::xBottom, press_point.x()), - qwtPlot()->invTransform(QwtPlot::yLeft, press_point.y())); + QPointF pointF(qwtPlot()->invTransform(QwtPlot::xBottom, press_point.x()), + qwtPlot()->invTransform(QwtPlot::yLeft, press_point.y())); emit trackerMoved(pointF); return true; // don't pass to canvas(). } @@ -1350,9 +1348,8 @@ bool PlotWidget::canvasEventFilter(QEvent* event) mouse_event->modifiers() == Qt::ShiftModifier) { const QPoint point = mouse_event->pos(); - QPointF pointF( - qwtPlot()->invTransform( QwtPlot::xBottom, point.x()), - qwtPlot()->invTransform( QwtPlot::yLeft, point.y())); + QPointF pointF(qwtPlot()->invTransform(QwtPlot::xBottom, point.x()), + qwtPlot()->invTransform(QwtPlot::yLeft, point.y())); emit trackerMoved(pointF); return true; } @@ -1395,16 +1392,16 @@ void PlotWidget::setDefaultRangeX() max = std::max(B, max); } } - qwtPlot()->setAxisScale(QwtPlot::xBottom, - min - _time_offset, - max - _time_offset); + qwtPlot()->setAxisScale(QwtPlot::xBottom, min - _time_offset, max - _time_offset); } - else{ + else + { qwtPlot()->setAxisScale(QwtPlot::xBottom, 0.0, 1.0); } } -QwtSeriesWrapper* PlotWidget::createCurveXY(const PlotData* data_x, const PlotData* data_y) +QwtSeriesWrapper* PlotWidget::createCurveXY(const PlotData* data_x, + const PlotData* data_y) { QwtSeriesWrapper* output = nullptr; @@ -1418,7 +1415,9 @@ QwtSeriesWrapper* PlotWidget::createCurveXY(const PlotData* data_x, const PlotDa { QMessageBox msgBox(qwtPlot()); msgBox.setWindowTitle("Warnings"); - msgBox.setText(tr("The creation of the XY plot failed with the following message:\n %1").arg(ex.what())); + msgBox.setText(tr("The creation of the XY plot failed with the following " + "message:\n %1") + .arg(ex.what())); msgBox.addButton("Continue", QMessageBox::AcceptRole); msgBox.exec(); } @@ -1447,5 +1446,3 @@ void PlotWidget::changeBackgroundColor(QColor color) replot(); } } - - diff --git a/plotjuggler_app/plotwidget.h b/plotjuggler_app/plotwidget.h index d91cdbca7..27579103d 100644 --- a/plotjuggler_app/plotwidget.h +++ b/plotjuggler_app/plotwidget.h @@ -29,7 +29,6 @@ class PlotWidget : public PlotWidgetBase Q_OBJECT public: - PlotWidget(PlotDataMapRef& datamap, QWidget* parent = nullptr); void setContextMenuEnabled(bool enabled); @@ -58,12 +57,9 @@ class PlotWidget : public PlotWidgetBase return _mapped_data; } - CurveInfo* addCurveXY(std::string name_x, - std::string name_y, - QString curve_name = ""); + CurveInfo* addCurveXY(std::string name_x, std::string name_y, QString curve_name = ""); - CurveInfo* addCurve(const std::string& name, - QColor color = Qt::transparent); + CurveInfo* addCurve(const std::string& name, QColor color = Qt::transparent); void setCustomAxisLimits(Range range); @@ -96,7 +92,7 @@ public slots: void updateCurves(); - void onSourceDataRemoved(const std::string &src_name); + void onSourceDataRemoved(const std::string& src_name); void removeAllCurves() override; @@ -124,11 +120,11 @@ public slots: void on_changeDateTimeScale(bool enable); - void on_changeCurveColor(const QString &curve_name, QColor new_color); + void on_changeCurveColor(const QString& curve_name, QColor new_color); private slots: - //void on_changeToBuiltinTransforms(QString new_transform); + // void on_changeToBuiltinTransforms(QString new_transform); void setModeXY(bool enable) override; @@ -147,7 +143,6 @@ private slots: void on_externallyResized(const QRectF& new_rect); private: - QAction* _action_removeAllCurves; QAction* _action_edit; QAction* _action_formula; @@ -181,7 +176,6 @@ private slots: DragInfo _dragging; - void buildActions(); void updateAvailableTransformers(); @@ -203,10 +197,9 @@ private slots: bool _context_menu_enabled; - //void updateMaximumZoomArea(); + // void updateMaximumZoomArea(); void rescaleEqualAxisScaling(); void overrideCursonMove(); - }; #endif diff --git a/plotjuggler_app/plotwidget_editor.cpp b/plotjuggler_app/plotwidget_editor.cpp index b3eb00b68..7bc5bc3d3 100644 --- a/plotjuggler_app/plotwidget_editor.cpp +++ b/plotjuggler_app/plotwidget_editor.cpp @@ -13,16 +13,14 @@ const double MAX_DOUBLE = std::numeric_limits::max() / 2; -PlotwidgetEditor::PlotwidgetEditor(PlotWidget *plotwidget, QWidget *parent) : - QDialog(parent), - ui(new Ui::PlotWidgetEditor), - _plotwidget_origin(plotwidget) +PlotwidgetEditor::PlotwidgetEditor(PlotWidget* plotwidget, QWidget* parent) + : QDialog(parent), ui(new Ui::PlotWidgetEditor), _plotwidget_origin(plotwidget) { ui->setupUi(this); installEventFilter(this); -// setWindowFlags(windowFlags() | Qt::FramelessWindowHint); + // setWindowFlags(windowFlags() | Qt::FramelessWindowHint); setupColorWidget(); @@ -31,7 +29,7 @@ PlotwidgetEditor::PlotwidgetEditor(PlotWidget *plotwidget, QWidget *parent) : _plotwidget = new PlotWidget(plotwidget->datamap()); _plotwidget->xmlLoadState(saved_state); - _plotwidget->on_changeTimeOffset( plotwidget->timeOffset() ); + _plotwidget->on_changeTimeOffset(plotwidget->timeOffset()); _plotwidget->setContextMenuEnabled(false); _bounding_rect_original = _plotwidget_origin->canvasBoundingRect(); @@ -48,19 +46,20 @@ PlotwidgetEditor::PlotwidgetEditor(PlotWidget *plotwidget, QWidget *parent) : QSettings settings; restoreGeometry(settings.value("PlotwidgetEditor.geometry").toByteArray()); - if( _plotwidget->curveStyle() == PlotWidgetBase::LINES) + if (_plotwidget->curveStyle() == PlotWidgetBase::LINES) { ui->radioLines->setChecked(true); } - else if( _plotwidget->curveStyle() == PlotWidgetBase::DOTS) + else if (_plotwidget->curveStyle() == PlotWidgetBase::DOTS) { ui->radioPoints->setChecked(true); } - else if( _plotwidget->curveStyle() == PlotWidgetBase::STICKS) + else if (_plotwidget->curveStyle() == PlotWidgetBase::STICKS) { ui->radioSticks->setChecked(true); } - else { + else + { ui->radioBoth->setChecked(true); } @@ -71,27 +70,31 @@ PlotwidgetEditor::PlotwidgetEditor(PlotWidget *plotwidget, QWidget *parent) : auto range_x = _plotwidget->getVisualizationRangeX(); Range suggested_limits = _plotwidget->getVisualizationRangeY(range_x); - if( ylimits.min != -MAX_DOUBLE) + if (ylimits.min != -MAX_DOUBLE) { ui->checkBoxMin->setChecked(true); ui->lineLimitMin->setText(QString::number(ylimits.min)); } - else{ + else + { ui->lineLimitMin->setText(QString::number(suggested_limits.min)); } - if( ylimits.max != MAX_DOUBLE) + if (ylimits.max != MAX_DOUBLE) { ui->checkBoxMax->setChecked(true); ui->lineLimitMax->setText(QString::number(ylimits.max)); } - else{ + else + { ui->lineLimitMax->setText(QString::number(suggested_limits.max)); } - //ui->listWidget->widget_background_disabled("QListView::item:selected { background: #ddeeff; }"); + // ui->listWidget->widget_background_disabled("QListView::item:selected { background: + // #ddeeff; }"); - if( ui->listWidget->count() != 0 ){ + if (ui->listWidget->count() != 0) + { ui->listWidget->item(0)->setSelected(true); } } @@ -105,24 +108,24 @@ PlotwidgetEditor::~PlotwidgetEditor() delete ui; } - void PlotwidgetEditor::onColorChanged(QColor c) { auto selected = ui->listWidget->selectedItems(); - if( selected.size() != 1) + if (selected.size() != 1) { return; } - auto item = selected.front(); - if( item ){ - auto row_widget = dynamic_cast( ui->listWidget->itemWidget(item) ); + auto item = selected.front(); + if (item) + { + auto row_widget = dynamic_cast(ui->listWidget->itemWidget(item)); auto name = row_widget->text(); - if( row_widget->color() != c) + if (row_widget->color() != c) { - row_widget->setColor( c ); + row_widget->setColor(c); } - _plotwidget->on_changeCurveColor( item->data(Qt::UserRole).toString(), c ); + _plotwidget->on_changeCurveColor(item->data(Qt::UserRole).toString(), c); } } @@ -131,7 +134,7 @@ void PlotwidgetEditor::setupColorWidget() auto wheel_layout = new QVBoxLayout(); wheel_layout->setMargin(0); wheel_layout->setSpacing(5); - ui->widgetWheel->setLayout( wheel_layout ); + ui->widgetWheel->setLayout(wheel_layout); _color_wheel = new color_widgets::ColorWheel(this); wheel_layout->addWidget(_color_wheel); @@ -140,18 +143,17 @@ void PlotwidgetEditor::setupColorWidget() wheel_layout->addWidget(_color_preview); - connect(_color_wheel, &color_widgets::ColorWheel::colorChanged, - this, &PlotwidgetEditor::onColorChanged); + connect(_color_wheel, &color_widgets::ColorWheel::colorChanged, this, + &PlotwidgetEditor::onColorChanged); - connect(_color_wheel, &color_widgets::ColorWheel::colorChanged, - _color_preview, &color_widgets::ColorPreview::setColor ); + connect(_color_wheel, &color_widgets::ColorWheel::colorChanged, _color_preview, + &color_widgets::ColorPreview::setColor); - connect(_color_wheel, &color_widgets::ColorWheel::colorChanged, - this, [this](QColor col) - { - QSignalBlocker block( ui->editColotText ); - ui->editColotText->setText( col.name() ); - }); + connect(_color_wheel, &color_widgets::ColorWheel::colorChanged, this, + [this](QColor col) { + QSignalBlocker block(ui->editColotText); + ui->editColotText->setText(col.name()); + }); _color_wheel->setColor(Qt::blue); } @@ -159,11 +161,11 @@ void PlotwidgetEditor::setupColorWidget() void PlotwidgetEditor::onDeleteRow(QWidget* w) { int row_count = ui->listWidget->count(); - for(int row = 0; row < row_count; row++ ) + for (int row = 0; row < row_count; row++) { auto item = ui->listWidget->item(row); auto widget = ui->listWidget->itemWidget(item); - if( widget == w ) + if (widget == w) { QString curve = dynamic_cast(w)->text(); @@ -174,7 +176,7 @@ void PlotwidgetEditor::onDeleteRow(QWidget* w) break; } } - if( row_count == 0) + if (row_count == 0) { disableWidgets(); } @@ -202,17 +204,18 @@ void PlotwidgetEditor::setupTable() auto color = it.second; auto item = new QListWidgetItem(); // even if it is not visible, we store here the original name (not alias) - item->setData(Qt::UserRole, it.first ); + item->setData(Qt::UserRole, it.first); - ui->listWidget->addItem( item ); - auto plot_row = new EditorRowWidget(alias, color) ; - item->setSizeHint( plot_row->sizeHint() ); - ui->listWidget->setItemWidget(item, plot_row ); + ui->listWidget->addItem(item); + auto plot_row = new EditorRowWidget(alias, color); + item->setSizeHint(plot_row->sizeHint()); + ui->listWidget->setItemWidget(item, plot_row); - connect(plot_row, &EditorRowWidget::deleteRow, this, [this](QWidget* w) { onDeleteRow(w); }); + connect(plot_row, &EditorRowWidget::deleteRow, this, + [this](QWidget* w) { onDeleteRow(w); }); row++; } - if( row == 0 ) + if (row == 0) { disableWidgets(); } @@ -227,14 +230,20 @@ void PlotwidgetEditor::updateLimits() { bool ok = false; double val = ui->lineLimitMax->text().toDouble(&ok); - if(ok) { ymax = val; } + if (ok) + { + ymax = val; + } } if (ui->checkBoxMin->isChecked() && !ui->lineLimitMin->text().isEmpty()) { bool ok = false; double val = ui->lineLimitMin->text().toDouble(&ok); - if(ok) { ymin = val; } + if (ok) + { + ymin = val; + } } if (ymin > ymax) @@ -251,50 +260,48 @@ void PlotwidgetEditor::updateLimits() _plotwidget->setCustomAxisLimits(range); } -void PlotwidgetEditor::on_editColotText_textChanged(const QString &text) +void PlotwidgetEditor::on_editColotText_textChanged(const QString& text) { - if( text.size() == 7 && text[0] == '#' && QColor::isValidColor(text)) + if (text.size() == 7 && text[0] == '#' && QColor::isValidColor(text)) { QColor col(text); - _color_wheel->setColor( col ); - _color_preview->setColor( col ); + _color_wheel->setColor(col); + _color_preview->setColor(col); } } void PlotwidgetEditor::on_radioLines_toggled(bool checked) { - if(checked) + if (checked) { - _plotwidget->changeCurvesStyle( PlotWidgetBase::LINES ); + _plotwidget->changeCurvesStyle(PlotWidgetBase::LINES); } } - void PlotwidgetEditor::on_radioPoints_toggled(bool checked) { - if(checked) + if (checked) { - _plotwidget->changeCurvesStyle( PlotWidgetBase::DOTS ); + _plotwidget->changeCurvesStyle(PlotWidgetBase::DOTS); } } void PlotwidgetEditor::on_radioBoth_toggled(bool checked) { - if(checked) + if (checked) { - _plotwidget->changeCurvesStyle( PlotWidgetBase::LINES_AND_DOTS ); + _plotwidget->changeCurvesStyle(PlotWidgetBase::LINES_AND_DOTS); } } void PlotwidgetEditor::on_radioSticks_toggled(bool checked) { - if(checked) + if (checked) { - _plotwidget->changeCurvesStyle( PlotWidgetBase::STICKS ); + _plotwidget->changeCurvesStyle(PlotWidgetBase::STICKS); } } - void PlotwidgetEditor::on_checkBoxMax_toggled(bool checked) { ui->lineLimitMax->setEnabled(checked); @@ -322,14 +329,14 @@ void PlotwidgetEditor::on_pushButtonReset_clicked() ui->lineLimitMax->setText(QString::number(limits.max)); } -void PlotwidgetEditor::on_lineLimitMax_textChanged(const QString &) +void PlotwidgetEditor::on_lineLimitMax_textChanged(const QString&) { - updateLimits(); + updateLimits(); } -void PlotwidgetEditor::on_lineLimitMin_textChanged(const QString &) +void PlotwidgetEditor::on_lineLimitMin_textChanged(const QString&) { - updateLimits(); + updateLimits(); } void PlotwidgetEditor::on_pushButtonCancel_pressed() @@ -342,31 +349,31 @@ void PlotwidgetEditor::on_pushButtonSave_pressed() QDomDocument doc; _plotwidget->setZoomRectangle(_bounding_rect_original, false); auto elem = _plotwidget->xmlSaveState(doc); - _plotwidget_origin->xmlLoadState( elem ); + _plotwidget_origin->xmlLoadState(elem); this->accept(); } -EditorRowWidget::EditorRowWidget(QString text, QColor color): QWidget() +EditorRowWidget::EditorRowWidget(QString text, QColor color) : QWidget() { setMouseTracking(true); - const QSize button_size(20,20); + const QSize button_size(20, 20); auto layout = new QHBoxLayout(); - setLayout( layout ); + setLayout(layout); _text = new QLabel(text, this); _empty_spacer = new QWidget(); - _empty_spacer->setFixedSize( button_size ); + _empty_spacer->setFixedSize(button_size); setColor(color); _delete_button = new QPushButton(this); _delete_button->setFlat(true); - _delete_button->setFixedSize( button_size ); + _delete_button->setFixedSize(button_size); auto icon = QIcon(":/resources/svg/trash.svg"); _delete_button->setStyleSheet("QPushButton:hover{ border: 0px;}"); - _delete_button->setIcon( icon) ; - _delete_button->setIconSize( button_size ); + _delete_button->setIcon(icon); + _delete_button->setIconSize(button_size); layout->addWidget(_empty_spacer); layout->addWidget(_delete_button); @@ -374,16 +381,17 @@ EditorRowWidget::EditorRowWidget(QString text, QColor color): QWidget() _delete_button->setHidden(true); - connect( _delete_button, &QPushButton::clicked, this, [this](){ emit deleteRow(this); }); + connect(_delete_button, &QPushButton::clicked, this, + [this]() { emit deleteRow(this); }); } -void EditorRowWidget::enterEvent(QEvent *ev) +void EditorRowWidget::enterEvent(QEvent* ev) { _delete_button->setHidden(false); _empty_spacer->setHidden(true); } -void EditorRowWidget::leaveEvent(QEvent *ev) +void EditorRowWidget::leaveEvent(QEvent* ev) { _delete_button->setHidden(true); _empty_spacer->setHidden(false); @@ -396,7 +404,7 @@ QString EditorRowWidget::text() const void EditorRowWidget::setColor(QColor color) { - setStyleSheet( QString("color: %1;").arg(color.name())); + setStyleSheet(QString("color: %1;").arg(color.name())); _color = color; } @@ -408,24 +416,24 @@ QColor EditorRowWidget::color() const void PlotwidgetEditor::on_listWidget_itemSelectionChanged() { auto selected = ui->listWidget->selectedItems(); - if( selected.size() == 0 || ui->listWidget->count() == 0) + if (selected.size() == 0 || ui->listWidget->count() == 0) { ui->widgetColor->setEnabled(false); - ui->editColotText->setText( "#000000" ); + ui->editColotText->setText("#000000"); return; } ui->widgetColor->setEnabled(true); - if( selected.size() != 1) + if (selected.size() != 1) { return; } auto item = selected.front(); - auto row_widget = dynamic_cast( ui->listWidget->itemWidget(item) ); - if( row_widget ) + auto row_widget = dynamic_cast(ui->listWidget->itemWidget(item)); + if (row_widget) { - ui->editColotText->setText( row_widget->color().name() ); + ui->editColotText->setText(row_widget->color().name()); } } diff --git a/plotjuggler_app/plotwidget_editor.h b/plotjuggler_app/plotwidget_editor.h index 831e7211e..8fb6ed83e 100644 --- a/plotjuggler_app/plotwidget_editor.h +++ b/plotjuggler_app/plotwidget_editor.h @@ -8,19 +8,20 @@ #include "color_preview.hpp" #include "PlotJuggler/transform_function.h" -namespace Ui { +namespace Ui +{ class PlotWidgetEditor; } -class EditorRowWidget: public QWidget +class EditorRowWidget : public QWidget { Q_OBJECT public: EditorRowWidget(QString text, QColor color); - void enterEvent(QEvent *ev) override; - void leaveEvent(QEvent *ev) override; + void enterEvent(QEvent* ev) override; + void leaveEvent(QEvent* ev) override; QString text() const; @@ -43,7 +44,7 @@ class PlotwidgetEditor : public QDialog Q_OBJECT public: - explicit PlotwidgetEditor(PlotWidget* plotwidget, QWidget *parent = nullptr); + explicit PlotwidgetEditor(PlotWidget* plotwidget, QWidget* parent = nullptr); ~PlotwidgetEditor(); public slots: @@ -51,7 +52,7 @@ public slots: private slots: - void on_editColotText_textChanged(const QString &arg1); + void on_editColotText_textChanged(const QString& arg1); void on_radioLines_toggled(bool checked); @@ -71,14 +72,14 @@ private slots: void on_listWidget_itemSelectionChanged(); - void on_lineLimitMin_textChanged(const QString &text); + void on_lineLimitMin_textChanged(const QString& text); - void on_lineLimitMax_textChanged(const QString &text); + void on_lineLimitMax_textChanged(const QString& text); void on_radioSticks_toggled(bool checked); private: - Ui::PlotWidgetEditor *ui; + Ui::PlotWidgetEditor* ui; color_widgets::ColorWheel* _color_wheel; color_widgets::ColorPreview* _color_preview; @@ -91,10 +92,10 @@ private slots: void setupColorWidget(); void setupTable(); void updateLimits(); - void onDeleteRow(QWidget *w); + void onDeleteRow(QWidget* w); void disableWidgets(); std::unordered_map> _transforms; }; -#endif // PLOTWIDGET_EDITOR_H +#endif // PLOTWIDGET_EDITOR_H diff --git a/plotjuggler_app/plotwidget_transforms.cpp b/plotjuggler_app/plotwidget_transforms.cpp index 07da1f803..f97dcdeaa 100644 --- a/plotjuggler_app/plotwidget_transforms.cpp +++ b/plotjuggler_app/plotwidget_transforms.cpp @@ -11,17 +11,17 @@ #include #include -DialogTransformEditor::DialogTransformEditor(PlotWidget* plotwidget) : - QDialog(plotwidget->widget()), - ui(new Ui::plotwidget_transforms), - _plotwidget_origin(plotwidget) +DialogTransformEditor::DialogTransformEditor(PlotWidget* plotwidget) + : QDialog(plotwidget->widget()) + , ui(new Ui::plotwidget_transforms) + , _plotwidget_origin(plotwidget) { ui->setupUi(this); QDomDocument doc; auto saved_state = plotwidget->xmlSaveState(doc); _plotwidget = new PlotWidget(plotwidget->datamap()); - _plotwidget->on_changeTimeOffset( plotwidget->timeOffset() ); + _plotwidget->on_changeTimeOffset(plotwidget->timeOffset()); _plotwidget->xmlLoadState(saved_state); auto layout = new QVBoxLayout(); @@ -41,12 +41,13 @@ DialogTransformEditor::DialogTransformEditor(PlotWidget* plotwidget) : auto names = TransformFactory::registeredTransforms(); - for(const auto& name: names) + for (const auto& name : names) { - ui->listTransforms->addItem( QString::fromStdString(name) ); + ui->listTransforms->addItem(QString::fromStdString(name)); } - if( ui->listCurves->count() != 0 ){ + if (ui->listCurves->count() != 0) + { ui->listCurves->item(0)->setSelected(true); } } @@ -63,10 +64,10 @@ void DialogTransformEditor::setupTable() auto color = it.second; auto item = new QListWidgetItem(); // item->setForeground(color); - ui->listCurves->addItem( item ); - auto plot_row = new RowWidget(name, color) ; - item->setSizeHint( plot_row->sizeHint() ); - ui->listCurves->setItemWidget(item, plot_row ); + ui->listCurves->addItem(item); + auto plot_row = new RowWidget(name, color); + item->setSizeHint(plot_row->sizeHint()); + ui->listCurves->setItemWidget(item, plot_row); row++; } @@ -83,42 +84,45 @@ DialogTransformEditor::~DialogTransformEditor() DialogTransformEditor::RowWidget::RowWidget(QString text, QColor color) { auto layout = new QHBoxLayout(); - setLayout( layout ); + setLayout(layout); _text = new QLabel(text, this); - setStyleSheet( QString("color: %1;").arg(color.name())); + setStyleSheet(QString("color: %1;").arg(color.name())); _color = color; layout->addWidget(_text); } -QString DialogTransformEditor::RowWidget::text() const{ +QString DialogTransformEditor::RowWidget::text() const +{ return _text->text(); } -QColor DialogTransformEditor::RowWidget::color() const{ +QColor DialogTransformEditor::RowWidget::color() const +{ return _color; } void DialogTransformEditor::on_listCurves_itemSelectionChanged() { auto selected = ui->listCurves->selectedItems(); - if( selected.size() != 1){ + if (selected.size() != 1) + { return; } auto item = selected.front(); - auto row_widget = dynamic_cast( ui->listCurves->itemWidget(item) ); + auto row_widget = dynamic_cast(ui->listCurves->itemWidget(item)); auto curve_name = row_widget->text(); auto curve_it = _plotwidget->curveFromTitle(curve_name); - auto ts = dynamic_cast( curve_it->curve->data() ); + auto ts = dynamic_cast(curve_it->curve->data()); int transform_row = 0; - if( ts->transform() ) + if (ts->transform()) { - for( int row = 1; row < ui->listTransforms->count(); row++) + for (int row = 1; row < ui->listTransforms->count(); row++) { - if( ui->listTransforms->item(row)->text() == ts->transformName() ) + if (ui->listTransforms->item(row)->text() == ts->transformName()) { transform_row = row; break; @@ -128,16 +132,18 @@ void DialogTransformEditor::on_listCurves_itemSelectionChanged() int selected_row = -1; auto selected_transforms = ui->listTransforms->selectedItems(); - if( selected_transforms.size() == 1) + if (selected_transforms.size() == 1) { selected_row = ui->listTransforms->row(selected_transforms.front()); } - if( selected_row == transform_row){ + if (selected_row == transform_row) + { // force callback on_listTransforms_itemSelectionChanged(); } - else{ + else + { ui->listTransforms->item(transform_row)->setSelected(true); } } @@ -145,27 +151,29 @@ void DialogTransformEditor::on_listCurves_itemSelectionChanged() void DialogTransformEditor::on_listTransforms_itemSelectionChanged() { auto selected_curves = ui->listCurves->selectedItems(); - if( selected_curves.size() != 1){ + if (selected_curves.size() != 1) + { return; } - auto row_widget = dynamic_cast( - ui->listCurves->itemWidget(selected_curves.front()) ); + auto row_widget = + dynamic_cast(ui->listCurves->itemWidget(selected_curves.front())); QString curve_name = row_widget->text(); auto selected_transforms = ui->listTransforms->selectedItems(); - if( selected_transforms.size() != 1){ + if (selected_transforms.size() != 1) + { return; } QString transform_ID = selected_transforms.front()->text(); auto curve_info = _plotwidget->curveFromTitle(curve_name); auto qwt_curve = curve_info->curve; - auto ts = dynamic_cast( curve_info->curve->data() ); + auto ts = dynamic_cast(curve_info->curve->data()); QSignalBlocker block(ui->lineEditAlias); - if( transform_ID.isEmpty() || transform_ID == ui->listTransforms->item(0)->text() ) + if (transform_ID.isEmpty() || transform_ID == ui->listTransforms->item(0)->text()) { ts->setTransform({}); ts->updateCache(true); @@ -173,40 +181,40 @@ void DialogTransformEditor::on_listTransforms_itemSelectionChanged() ui->lineEditAlias->setText(""); ui->lineEditAlias->setEnabled(false); - qwt_curve->setTitle( curve_name ); + qwt_curve->setTitle(curve_name); } - else{ + else + { ts->setTransform(transform_ID); ts->updateCache(true); ui->lineEditAlias->setEnabled(true); QString curve_title = qwt_curve->title().text(); - if( ts->alias().isEmpty()) + if (ts->alias().isEmpty()) { auto src_name = QString::fromStdString(curve_info->src_name); auto new_title = QString("%1[%2]").arg(src_name).arg(transform_ID); ts->setAlias(new_title); } - ui->lineEditAlias->setText( ts->alias() ); - qwt_curve->setTitle( ts->alias() ); + ui->lineEditAlias->setText(ts->alias()); + qwt_curve->setTitle(ts->alias()); auto widget = ts->transform()->optionsWidget(); int index = ui->stackedWidgetArguments->indexOf(widget); - if( index == -1) + if (index == -1) { index = ui->stackedWidgetArguments->addWidget(widget); } ui->stackedWidgetArguments->setCurrentIndex(index); - if( _connected_transform_widgets.count(widget) == 0) + if (_connected_transform_widgets.count(widget) == 0) { - connect( ts->transform().get(), &TransformFunction::parametersChanged, - this, [=]() { - ts->updateCache(true); - _plotwidget->zoomOut(false); - }); + connect(ts->transform().get(), &TransformFunction::parametersChanged, this, [=]() { + ts->updateCache(true); + _plotwidget->zoomOut(false); + }); _connected_transform_widgets.insert(widget); } } @@ -225,7 +233,7 @@ void DialogTransformEditor::on_pushButtonSave_clicked() QDomDocument doc; auto elem = _plotwidget->xmlSaveState(doc); - _plotwidget_origin->xmlLoadState( elem ); + _plotwidget_origin->xmlLoadState(elem); _plotwidget_origin->zoomOut(false); this->accept(); @@ -234,20 +242,21 @@ void DialogTransformEditor::on_pushButtonSave_clicked() void DialogTransformEditor::on_lineEditAlias_editingFinished() { auto selected_curves = ui->listCurves->selectedItems(); - if( selected_curves.size() != 1){ + if (selected_curves.size() != 1) + { return; } - auto row_widget = dynamic_cast( - ui->listCurves->itemWidget(selected_curves.front()) ); + auto row_widget = + dynamic_cast(ui->listCurves->itemWidget(selected_curves.front())); QString curve_name = row_widget->text(); auto curve_it = _plotwidget->curveFromTitle(curve_name); - auto ts = dynamic_cast( curve_it->curve->data() ); + auto ts = dynamic_cast(curve_it->curve->data()); - curve_it->curve->setTitle( ui->lineEditAlias->text() ); + curve_it->curve->setTitle(ui->lineEditAlias->text()); - if( ts && ts->transform() ) + if (ts && ts->transform()) { ts->setAlias(ui->lineEditAlias->text()); } diff --git a/plotjuggler_app/plotwidget_transforms.h b/plotjuggler_app/plotwidget_transforms.h index 946472160..0418558da 100644 --- a/plotjuggler_app/plotwidget_transforms.h +++ b/plotjuggler_app/plotwidget_transforms.h @@ -4,7 +4,8 @@ #include #include "plotwidget.h" -namespace Ui { +namespace Ui +{ class plotwidget_transforms; } @@ -29,7 +30,7 @@ private slots: void on_lineEditAlias_editingFinished(); private: - Ui::plotwidget_transforms *ui; + Ui::plotwidget_transforms* ui; PlotWidget* _plotwidget; PlotWidget* _plotwidget_origin; @@ -38,7 +39,7 @@ private slots: void setupTable(); - class RowWidget: public QWidget + class RowWidget : public QWidget { public: RowWidget(QString text, QColor color); @@ -50,7 +51,6 @@ private slots: QLabel* _text; QColor _color; }; - }; -#endif // PLOTWIDGET_TRANSFORMS_H +#endif // PLOTWIDGET_TRANSFORMS_H diff --git a/plotjuggler_app/point_series_xy.cpp b/plotjuggler_app/point_series_xy.cpp index 35356ef56..42a50f914 100644 --- a/plotjuggler_app/point_series_xy.cpp +++ b/plotjuggler_app/point_series_xy.cpp @@ -3,10 +3,10 @@ #include PointSeriesXY::PointSeriesXY(const PlotData* x_axis, const PlotData* y_axis) - : QwtSeriesWrapper(&_cached_curve), - _x_axis(x_axis), - _y_axis(y_axis), - _cached_curve("", x_axis->group()) + : QwtSeriesWrapper(&_cached_curve) + , _x_axis(x_axis) + , _y_axis(y_axis) + , _cached_curve("", x_axis->group()) { updateCache(true); } @@ -65,7 +65,7 @@ bool PointSeriesXY::updateCache(bool reset_old_data) } const QPointF p(_x_axis->at(i).y, _y_axis->at(i).y); - _cached_curve.pushBack( { p.x(), p.y() } ); + _cached_curve.pushBack({ p.x(), p.y() }); } return true; } diff --git a/plotjuggler_app/preferences_dialog.cpp b/plotjuggler_app/preferences_dialog.cpp index 93b846908..ab198b59a 100644 --- a/plotjuggler_app/preferences_dialog.cpp +++ b/plotjuggler_app/preferences_dialog.cpp @@ -5,7 +5,8 @@ #include #include "PlotJuggler/svg_util.h" -PreferencesDialog::PreferencesDialog(QWidget* parent) : QDialog(parent), ui(new Ui::PreferencesDialog) +PreferencesDialog::PreferencesDialog(QWidget* parent) + : QDialog(parent), ui(new Ui::PreferencesDialog) { ui->setupUi(this); QSettings settings; @@ -19,16 +20,16 @@ PreferencesDialog::PreferencesDialog(QWidget* parent) : QDialog(parent), ui(new ui->comboBoxTheme->setCurrentIndex(0); } - bool use_plot_color_index = settings.value("Preferences::use_plot_color_index", false).toBool(); + bool use_plot_color_index = + settings.value("Preferences::use_plot_color_index", false).toBool(); bool remember_color = settings.value("Preferences::remember_color", true).toBool(); ui->checkBoxRememberColor->setChecked(remember_color); ui->radioLocalColorIndex->setChecked(use_plot_color_index); ui->radioGlobalColorIndex->setChecked(!use_plot_color_index); - ui->pushButtonAdd->setIcon( LoadSvg(":/resources/svg/add_tab.svg", theme)); - ui->pushButtonRemove->setIcon( LoadSvg(":/resources/svg/trash.svg", theme)); - + ui->pushButtonAdd->setIcon(LoadSvg(":/resources/svg/add_tab.svg", theme)); + ui->pushButtonRemove->setIcon(LoadSvg(":/resources/svg/trash.svg", theme)); bool use_separator = settings.value("Preferences::use_separator", true).toBool(); ui->checkBoxSeparator->setChecked(use_separator); @@ -37,21 +38,23 @@ PreferencesDialog::PreferencesDialog(QWidget* parent) : QDialog(parent), ui(new ui->checkBoxOpenGL->setChecked(use_opengl); //--------------- - auto custom_plugin_folders = settings.value("Preferences::plugin_folders", true).toStringList(); - for (const auto& folder: custom_plugin_folders) + auto custom_plugin_folders = + settings.value("Preferences::plugin_folders", true).toStringList(); + for (const auto& folder : custom_plugin_folders) { QDir dir(folder); auto item = new QListWidgetItem(folder); - if( !dir.exists() ) + if (!dir.exists()) { item->setForeground(Qt::red); } ui->listWidgetCustom->addItem(item); }; - ui->pushButtonRemove->setEnabled( !ui->listWidgetCustom->selectedItems().isEmpty() ); + ui->pushButtonRemove->setEnabled(!ui->listWidgetCustom->selectedItems().isEmpty()); //--------------- - auto builtin_plugin_folders = settings.value("Preferences::builtin_plugin_folders", true).toStringList(); - for (const auto& folder: builtin_plugin_folders) + auto builtin_plugin_folders = + settings.value("Preferences::builtin_plugin_folders", true).toStringList(); + for (const auto& folder : builtin_plugin_folders) { ui->listWidgetBuiltin->addItem(new QListWidgetItem(folder)); }; @@ -65,16 +68,19 @@ PreferencesDialog::~PreferencesDialog() void PreferencesDialog::on_buttonBox_accepted() { QSettings settings; - settings.setValue("Preferences::theme", ui->comboBoxTheme->currentIndex() == 1 ? "dark" : "light"); - settings.setValue("Preferences::remember_color", ui->checkBoxRememberColor->isChecked()); - settings.setValue("Preferences::use_plot_color_index", ui->radioLocalColorIndex->isChecked()); + settings.setValue("Preferences::theme", + ui->comboBoxTheme->currentIndex() == 1 ? "dark" : "light"); + settings.setValue("Preferences::remember_color", + ui->checkBoxRememberColor->isChecked()); + settings.setValue("Preferences::use_plot_color_index", + ui->radioLocalColorIndex->isChecked()); settings.setValue("Preferences::use_separator", ui->checkBoxSeparator->isChecked()); settings.setValue("Preferences::use_opengl", ui->checkBoxOpenGL->isChecked()); QStringList plugin_folders; - for(int row=0; row< ui->listWidgetCustom->count(); row++) + for (int row = 0; row < ui->listWidgetCustom->count(); row++) { - plugin_folders.push_back( ui->listWidgetCustom->item(row)->text()); + plugin_folders.push_back(ui->listWidgetCustom->item(row)->text()); } settings.setValue("Preferences::plugin_folders", plugin_folders); @@ -83,9 +89,9 @@ void PreferencesDialog::on_buttonBox_accepted() void PreferencesDialog::on_pushButtonAdd_clicked() { - QString dir = QFileDialog::getExistingDirectory(this, tr("Select a Directory"), - QDir::homePath(), - QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + QString dir = QFileDialog::getExistingDirectory( + this, tr("Select a Directory"), QDir::homePath(), + QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); auto item = new QListWidgetItem(dir); ui->listWidgetCustom->addItem(item); } @@ -94,13 +100,14 @@ void PreferencesDialog::on_pushButtonRemove_clicked() { auto selected = ui->listWidgetCustom->selectedItems(); - for(QListWidgetItem* item: selected){ - ui->listWidgetCustom->removeItemWidget(item); - delete item; + for (QListWidgetItem* item : selected) + { + ui->listWidgetCustom->removeItemWidget(item); + delete item; } } void PreferencesDialog::on_listWidgetCustom_itemSelectionChanged() { - ui->pushButtonRemove->setEnabled( !ui->listWidgetCustom->selectedItems().isEmpty() ); + ui->pushButtonRemove->setEnabled(!ui->listWidgetCustom->selectedItems().isEmpty()); } diff --git a/plotjuggler_app/series_data.h b/plotjuggler_app/series_data.h index f4d925afa..844bbb19d 100644 --- a/plotjuggler_app/series_data.h +++ b/plotjuggler_app/series_data.h @@ -4,6 +4,4 @@ #include "PlotJuggler/plotdata.h" #include "qwt_series_data.h" - - #endif // SERIES_DATA_H diff --git a/plotjuggler_app/stylesheet.h b/plotjuggler_app/stylesheet.h index ec30d87ce..9cf77cc6f 100644 --- a/plotjuggler_app/stylesheet.h +++ b/plotjuggler_app/stylesheet.h @@ -16,45 +16,44 @@ inline QString SetApplicationStyleSheet(QString style) int i = 0; - while( i < lines.size() ) + while (i < lines.size()) { - if( lines[i++].contains("PALETTE START") ) + if (lines[i++].contains("PALETTE START")) { break; } } - while( i < lines.size() ) + while (i < lines.size()) { auto parts = lines[i].split(":"); - if( parts.size() == 2 ) + if (parts.size() == 2) { - QString value = parts[1].remove(" "); - value.remove("\r"); - palette.insert( {parts[0].remove(" ") ,value } ); + QString value = parts[1].remove(" "); + value.remove("\r"); + palette.insert({ parts[0].remove(" "), value }); } - if( lines[i++].contains("PALETTE END") ) + if (lines[i++].contains("PALETTE END")) { break; } } - - while( i < lines.size() ) + while (i < lines.size()) { QString line = lines[i]; - int pos_start = line.indexOf("${", 0 ); - if( pos_start != -1 ) + int pos_start = line.indexOf("${", 0); + if (pos_start != -1) { - int pos_end = line.indexOf("}",pos_start ); - if( pos_end == -1 ) + int pos_end = line.indexOf("}", pos_start); + if (pos_end == -1) { throw std::runtime_error("problem loading stylesheet. Unclosed ${}"); } - int mid_length = pos_end -( pos_start+2 ); - QString id = line.mid(pos_start+2, mid_length); + int mid_length = pos_end - (pos_start + 2); + QString id = line.mid(pos_start + 2, mid_length); if (palette.count(id) == 0) { @@ -63,7 +62,7 @@ inline QString SetApplicationStyleSheet(QString style) throw std::runtime_error(msg); } QString color = palette[id]; - line = line.left(pos_start) + color + line.right(line.size() - pos_end -1); + line = line.left(pos_start) + color + line.right(line.size() - pos_end - 1); } out += line + "\n"; @@ -78,4 +77,4 @@ inline QString SetApplicationStyleSheet(QString style) return palette["theme"]; } -#endif // STYLESHEET_H +#endif // STYLESHEET_H diff --git a/plotjuggler_app/suggest_dialog.cpp b/plotjuggler_app/suggest_dialog.cpp index a7e4249f8..b8d935e86 100644 --- a/plotjuggler_app/suggest_dialog.cpp +++ b/plotjuggler_app/suggest_dialog.cpp @@ -2,7 +2,8 @@ #include "suggest_dialog.h" #include "ui_suggest_dialog.h" -SuggestDialog::SuggestDialog(const std::string& name_x, const std::string& name_y, QWidget* parent) +SuggestDialog::SuggestDialog(const std::string& name_x, const std::string& name_y, + QWidget* parent) : QDialog(parent), ui(new Ui::SuggestDialog) { ui->setupUi(this); @@ -47,7 +48,8 @@ void SuggestDialog::updateSuggestion() { std::swap(name_x, name_y); } - common_prefix = std::string(name_x.begin(), std::mismatch(name_x.begin(), name_x.end(), name_y.begin()).first); + common_prefix = std::string( + name_x.begin(), std::mismatch(name_x.begin(), name_x.end(), name_y.begin()).first); std::string suffix_x = name_x.substr(common_prefix.size()); std::string suffix_y = name_y.substr(common_prefix.size()); diff --git a/plotjuggler_app/suggest_dialog.h b/plotjuggler_app/suggest_dialog.h index 89937dfee..16f74d285 100644 --- a/plotjuggler_app/suggest_dialog.h +++ b/plotjuggler_app/suggest_dialog.h @@ -13,7 +13,8 @@ class SuggestDialog : public QDialog Q_OBJECT public: - explicit SuggestDialog(const std::string& name_x, const std::string& name_y, QWidget* parent = nullptr); + explicit SuggestDialog(const std::string& name_x, const std::string& name_y, + QWidget* parent = nullptr); ~SuggestDialog(); QString nameX() const; diff --git a/plotjuggler_app/tabbedplotwidget.cpp b/plotjuggler_app/tabbedplotwidget.cpp index 53eaa92b0..cab401e93 100644 --- a/plotjuggler_app/tabbedplotwidget.cpp +++ b/plotjuggler_app/tabbedplotwidget.cpp @@ -21,14 +21,11 @@ std::map TabbedPlotWidget::_instances; TabbedPlotWidget::TabbedPlotWidget(QString name, QMainWindow* mainwindow, PlotDataMapRef& mapped_data, QMainWindow* parent) - : QWidget(parent) - , _mapped_data(mapped_data) - , _name(name) - , _main_window(mainwindow) + : QWidget(parent), _mapped_data(mapped_data), _name(name), _main_window(mainwindow) { MainWindow* main_window = dynamic_cast(_main_window); - setContentsMargins(0,0,0,0); + setContentsMargins(0, 0, 0, 0); if (main_window == parent) { @@ -55,50 +52,53 @@ TabbedPlotWidget::TabbedPlotWidget(QString name, QMainWindow* mainwindow, _tabWidget->setTabsClosable(true); _tabWidget->setMovable(true); - connect(_tabWidget->tabBar(), &QTabBar::tabBarDoubleClicked, - this, &TabbedPlotWidget::on_renameCurrentTab); + connect(_tabWidget->tabBar(), &QTabBar::tabBarDoubleClicked, this, + &TabbedPlotWidget::on_renameCurrentTab); main_layout->addWidget(_tabWidget); - connect(_tabWidget, &QTabWidget::currentChanged, - this, &TabbedPlotWidget::on_tabWidget_currentChanged); + connect(_tabWidget, &QTabWidget::currentChanged, this, + &TabbedPlotWidget::on_tabWidget_currentChanged); tabWidget()->tabBar()->installEventFilter(this); - // TODO _action_savePlots = new QAction(tr("&Save plots to file"), this); - // TODO connect(_action_savePlots, &QAction::triggered, this, &TabbedPlotWidget::on_savePlotsToFile); + // TODO connect(_action_savePlots, &QAction::triggered, this, + // &TabbedPlotWidget::on_savePlotsToFile); -// _tab_menu = new QMenu(this); -// _tab_menu->addSeparator(); -// //_tab_menu->addAction(_action_savePlots); -// _tab_menu->addSeparator(); + // _tab_menu = new QMenu(this); + // _tab_menu->addSeparator(); + // //_tab_menu->addAction(_action_savePlots); + // _tab_menu->addSeparator(); - connect(this, &TabbedPlotWidget::destroyed, main_window, &MainWindow::on_tabbedAreaDestroyed); + connect(this, &TabbedPlotWidget::destroyed, main_window, + &MainWindow::on_tabbedAreaDestroyed); connect(this, &TabbedPlotWidget::tabAdded, main_window, &MainWindow::onPlotTabAdded); - connect(this, &TabbedPlotWidget::undoableChange, main_window, &MainWindow::onUndoableChange); + connect(this, &TabbedPlotWidget::undoableChange, main_window, + &MainWindow::onUndoableChange); - // TODO connect(_tabWidget, &TabWidget::movingPlotWidgetToTab, this, &TabbedPlotWidget::onMoveWidgetIntoNewTab); + // TODO connect(_tabWidget, &TabWidget::movingPlotWidgetToTab, this, + // &TabbedPlotWidget::onMoveWidgetIntoNewTab); this->addTab({}); - _buttonAddTab = new QPushButton("",this); + _buttonAddTab = new QPushButton("", this); _buttonAddTab->setFlat(true); - _buttonAddTab->setFixedSize( QSize(32,32)); + _buttonAddTab->setFixedSize(QSize(32, 32)); _buttonAddTab->setFocusPolicy(Qt::NoFocus); - connect(_buttonAddTab, &QPushButton::pressed, this, &TabbedPlotWidget::on_addTabButton_pressed); + connect(_buttonAddTab, &QPushButton::pressed, this, + &TabbedPlotWidget::on_addTabButton_pressed); } -void TabbedPlotWidget::paintEvent(QPaintEvent *event) +void TabbedPlotWidget::paintEvent(QPaintEvent* event) { QWidget::paintEvent(event); auto size = tabWidget()->tabBar()->size(); - _buttonAddTab->move( QPoint( size.width()+ 5, 0) ); + _buttonAddTab->move(QPoint(size.width() + 5, 0)); } - PlotDocker* TabbedPlotWidget::currentTab() { return static_cast(tabWidget()->currentWidget()); @@ -125,19 +125,19 @@ PlotDocker* TabbedPlotWidget::addTab(QString tab_name) ads::CDockManager::setConfigFlag(ads::CDockManager::EqualSplitOnInsertion, true); ads::CDockManager::setConfigFlag(ads::CDockManager::OpaqueSplitterResize, true); - if( tab_name.isEmpty() ) + if (tab_name.isEmpty()) { tab_name = QString("tab%1").arg(tab_suffix_count++); } auto docker = new PlotDocker(tab_name, _mapped_data, this); - connect( docker, &PlotDocker::undoableChange, this, &TabbedPlotWidget::undoableChange ); + connect(docker, &PlotDocker::undoableChange, this, &TabbedPlotWidget::undoableChange); tabWidget()->addTab(docker, tab_name); emit tabAdded(docker); // we need to send the signal for the very first widget - emit docker->plotWidgetAdded( docker->plotAt(0) ); + emit docker->plotWidgetAdded(docker->plotAt(0)); int index = tabWidget()->count() - 1; @@ -152,10 +152,11 @@ PlotDocker* TabbedPlotWidget::addTab(QString tab_name) QString theme = settings.value("StyleSheet::theme", "light").toString(); close_button->setIcon(LoadSvg(":/resources/svg/close-button.svg", theme)); - close_button->setFixedSize( QSize(16,16)); + close_button->setFixedSize(QSize(16, 16)); close_button->setFlat(true); - connect(close_button, &QPushButton::pressed, - this, [this](){ on_tabWidget_tabCloseRequested(tabWidget()->tabBar()->currentIndex());} ); + connect(close_button, &QPushButton::pressed, this, [this]() { + on_tabWidget_tabCloseRequested(tabWidget()->tabBar()->currentIndex()); + }); layout->addWidget(close_button); tabWidget()->tabBar()->setTabButton(index, QTabBar::RightSide, button_widget); @@ -194,12 +195,11 @@ bool TabbedPlotWidget::xmlLoadState(QDomElement& tabbed_area) { int prev_count = tabWidget()->count(); - for (auto docker_elem = tabbed_area.firstChildElement("Tab"); - !docker_elem.isNull(); + for (auto docker_elem = tabbed_area.firstChildElement("Tab"); !docker_elem.isNull(); docker_elem = docker_elem.nextSiblingElement("Tab")) { QString tab_name = docker_elem.attribute("tab_name"); - PlotDocker* docker = addTab( tab_name ); + PlotDocker* docker = addTab(tab_name); bool success = docker->xmlLoadState(docker_elem); @@ -210,7 +210,7 @@ bool TabbedPlotWidget::xmlLoadState(QDomElement& tabbed_area) } // remove old ones - for(int i=0; iremoveTab(0); } @@ -229,12 +229,10 @@ bool TabbedPlotWidget::xmlLoadState(QDomElement& tabbed_area) void TabbedPlotWidget::setStreamingMode(bool streaming_mode) { - } TabbedPlotWidget::~TabbedPlotWidget() { - } void TabbedPlotWidget::on_renameCurrentTab() @@ -242,8 +240,9 @@ void TabbedPlotWidget::on_renameCurrentTab() int idx = tabWidget()->tabBar()->currentIndex(); bool ok = true; - QString newName = QInputDialog::getText(this, tr("Change the tab name"), tr("New name:"), - QLineEdit::Normal, tabWidget()->tabText(idx), &ok); + QString newName = + QInputDialog::getText(this, tr("Change the tab name"), tr("New name:"), + QLineEdit::Normal, tabWidget()->tabText(idx), &ok); if (ok) { tabWidget()->setTabText(idx, newName); @@ -251,13 +250,11 @@ void TabbedPlotWidget::on_renameCurrentTab() } } - void TabbedPlotWidget::on_stylesheetChanged(QString theme) { _buttonAddTab->setIcon(LoadSvg(":/resources/svg/add_tab.svg", theme)); } - void TabbedPlotWidget::on_addTabButton_pressed() { addTab(nullptr); @@ -283,18 +280,19 @@ void TabbedPlotWidget::on_tabWidget_currentChanged(int index) { tab->replot(); } - for (int i=0; icount(); i++ ) + for (int i = 0; i < tabWidget()->count(); i++) { auto button = _tabWidget->tabBar()->tabButton(i, QTabBar::RightSide); - if( button ){ - button->setHidden( i!=index ); + if (button) + { + button->setHidden(i != index); } } } void TabbedPlotWidget::on_tabWidget_tabCloseRequested(int index) { - PlotDocker* tab = dynamic_cast( tabWidget()->widget(index) ); + PlotDocker* tab = dynamic_cast(tabWidget()->widget(index)); // first add then delete. // Otherwise currentPlotGrid might be empty @@ -315,7 +313,6 @@ void TabbedPlotWidget::on_tabWidget_tabCloseRequested(int index) tabWidget()->removeTab(index); emit undoableChange(); - } void TabbedPlotWidget::on_buttonLinkHorizontalScale_toggled(bool checked) @@ -362,43 +359,45 @@ bool TabbedPlotWidget::eventFilter(QObject* obj, QEvent* event) if (mouse_event->button() == Qt::RightButton) { - //QMenu* submenu = new QMenu("Move tab to..."); - // _tab_menu->addMenu(submenu); + // QMenu* submenu = new QMenu("Move tab to..."); + // _tab_menu->addMenu(submenu); - // QSignalMapper* signalMapper = new QSignalMapper(submenu); + // QSignalMapper* signalMapper = new QSignalMapper(submenu); //----------------------------------- -// QAction* action_new_window = submenu->addAction("New Window"); -// submenu->addSeparator(); -// connect(action_new_window, &QAction::triggered, this, &TabbedPlotWidget::on_moveTabIntoNewWindow); - -// //----------------------------------- -// for (auto& it : TabbedPlotWidget::_instances) -// { -// QString name = it.first; -// TabbedPlotWidget* tabbed_menu = it.second; -// if (tabbed_menu != this) -// { -// QAction* action = submenu->addAction(name); -// connect(action, SIGNAL(triggered()), signalMapper, SLOT(map())); -// signalMapper->setMapping(action, name); -// } -// } - -// connect(signalMapper, SIGNAL(mapped(QString)), this, SLOT(on_requestTabMovement(QString))); - -// //------------------------------- -//// QIcon iconSave; -//// iconSave.addFile(tr(":/%1/save.png").arg(theme), QSize(26, 26)); -//// _action_savePlots->setIcon(iconSave); - -//// QIcon iconNewWin; -//// iconNewWin.addFile(tr(":/%1/stacks.png").arg(theme), QSize(16, 16)); -//// action_new_window->setIcon(iconNewWin); - -// _tab_menu->exec(mouse_event->globalPos()); -// //------------------------------- -// submenu->deleteLater(); + // QAction* action_new_window = submenu->addAction("New Window"); + // submenu->addSeparator(); + // connect(action_new_window, &QAction::triggered, this, + // &TabbedPlotWidget::on_moveTabIntoNewWindow); + + // //----------------------------------- + // for (auto& it : TabbedPlotWidget::_instances) + // { + // QString name = it.first; + // TabbedPlotWidget* tabbed_menu = it.second; + // if (tabbed_menu != this) + // { + // QAction* action = submenu->addAction(name); + // connect(action, SIGNAL(triggered()), signalMapper, SLOT(map())); + // signalMapper->setMapping(action, name); + // } + // } + + // connect(signalMapper, SIGNAL(mapped(QString)), this, + // SLOT(on_requestTabMovement(QString))); + + // //------------------------------- + //// QIcon iconSave; + //// iconSave.addFile(tr(":/%1/save.png").arg(theme), QSize(26, 26)); + //// _action_savePlots->setIcon(iconSave); + + //// QIcon iconNewWin; + //// iconNewWin.addFile(tr(":/%1/stacks.png").arg(theme), QSize(16, 16)); + //// action_new_window->setIcon(iconNewWin); + + // _tab_menu->exec(mouse_event->globalPos()); + // //------------------------------- + // submenu->deleteLater(); } } } diff --git a/plotjuggler_app/tabbedplotwidget.h b/plotjuggler_app/tabbedplotwidget.h index 79ebf6e73..1f9ac55cc 100644 --- a/plotjuggler_app/tabbedplotwidget.h +++ b/plotjuggler_app/tabbedplotwidget.h @@ -16,10 +16,8 @@ class TabbedPlotWidget : public QWidget { } MainWindowArea; - explicit TabbedPlotWidget(QString name, - QMainWindow* main_window, - PlotDataMapRef& mapped_data, - QMainWindow* parent); + explicit TabbedPlotWidget(QString name, QMainWindow* main_window, + PlotDataMapRef& mapped_data, QMainWindow* parent); PlotDocker* currentTab(); @@ -50,7 +48,7 @@ public slots: void setStreamingMode(bool streaming_mode); - //static void saveTabImage(QString fileName, PlotDocker* matrix); + // static void saveTabImage(QString fileName, PlotDocker* matrix); void on_stylesheetChanged(QString style_dir); @@ -58,7 +56,7 @@ private slots: void on_renameCurrentTab(); - //void on_savePlotsToFile(); + // void on_savePlotsToFile(); void on_addTabButton_pressed(); @@ -77,7 +75,6 @@ private slots: void paintEvent(QPaintEvent* event) override; private: - QTabWidget* _tabWidget; QPushButton* _buttonHorizontalLink; @@ -86,7 +83,7 @@ private slots: // TODO QAction* _action_savePlots; - // QMenu* _tab_menu; + // QMenu* _tab_menu; const QString _name; @@ -100,7 +97,7 @@ private slots: virtual void closeEvent(QCloseEvent* event) override; - // void printPlotsNames(); + // void printPlotsNames(); protected: virtual bool eventFilter(QObject* obj, QEvent* event) override; diff --git a/plotjuggler_app/transforms/custom_function.cpp b/plotjuggler_app/transforms/custom_function.cpp index 39afb7788..fb254783f 100644 --- a/plotjuggler_app/transforms/custom_function.cpp +++ b/plotjuggler_app/transforms/custom_function.cpp @@ -11,15 +11,16 @@ CustomFunction::CustomFunction(SnippetData snippet) setSnippet(snippet); } -void CustomFunction::setSnippet(const SnippetData &snippet) +void CustomFunction::setSnippet(const SnippetData& snippet) { _snippet = snippet; _linked_plot_name = snippet.linked_source.toStdString(); _plot_name = snippet.alias_name.toStdString(); _used_channels.clear(); - for( QString source: snippet.additional_sources){ - _used_channels.push_back( source.toStdString() ); + for (QString source : snippet.additional_sources) + { + _used_channels.push_back(source.toStdString()); } } @@ -44,7 +45,7 @@ void CustomFunction::calculateAndAdd(PlotDataMapRef& src_data) std::vector dst_vector = { &dst_data }; dst_data.clear(); - setData( &src_data, {}, dst_vector ); + setData(&src_data, {}, dst_vector); try { @@ -60,7 +61,7 @@ void CustomFunction::calculateAndAdd(PlotDataMapRef& src_data) } } -const SnippetData &CustomFunction::snippet() const +const SnippetData& CustomFunction::snippet() const { return _snippet; } @@ -70,13 +71,13 @@ void CustomFunction::calculate() auto dst_data = _dst_vector.front(); auto data_it = plotData()->numeric.find(_linked_plot_name); - if ( data_it == plotData()->numeric.end()) + if (data_it == plotData()->numeric.end()) { // failed! keep it empty return; } _src_vector.clear(); - _src_vector.push_back( &data_it->second ); + _src_vector.push_back(&data_it->second); for (const auto& channel : _used_channels) { @@ -92,7 +93,7 @@ void CustomFunction::calculate() const PlotData* main_data_source = _src_vector.front(); // clean up old data - dst_data->setMaximumRangeX( main_data_source->maximumRangeX() ); + dst_data->setMaximumRangeX(main_data_source->maximumRangeX()); double last_updated_stamp = -std::numeric_limits::max(); if (dst_data->size() != 0) @@ -106,9 +107,10 @@ void CustomFunction::calculate() if (main_data_source->at(i).x > last_updated_stamp) { points.clear(); - calculatePoints( _src_vector, i, points); + calculatePoints(_src_vector, i, points); - for (PlotData::Point const &point : points) { + for (PlotData::Point const& point : points) + { dst_data->pushBack(point); } } @@ -117,19 +119,20 @@ void CustomFunction::calculate() bool CustomFunction::xmlSaveState(QDomDocument& doc, QDomElement& parent_element) const { - parent_element.appendChild( ExportSnippetToXML(_snippet, doc) ); + parent_element.appendChild(ExportSnippetToXML(_snippet, doc)); return true; } -bool CustomFunction::xmlLoadState(const QDomElement &parent_element) +bool CustomFunction::xmlLoadState(const QDomElement& parent_element) { - setSnippet ( GetSnippetFromXML(parent_element) ); + setSnippet(GetSnippetFromXML(parent_element)); return true; } SnippetsMap GetSnippetsFromXML(const QString& xml_text) { - if (xml_text.isEmpty()){ + if (xml_text.isEmpty()) + { return {}; } @@ -138,9 +141,10 @@ SnippetsMap GetSnippetsFromXML(const QString& xml_text) int parseErrorLine; if (!doc.setContent(xml_text, &parseErrorMsg, &parseErrorLine)) { - QMessageBox::critical( - nullptr, "Error", - QString("Failed to parse snippets (xml), error %1 at line %2").arg(parseErrorMsg).arg(parseErrorLine)); + QMessageBox::critical(nullptr, "Error", + QString("Failed to parse snippets (xml), error %1 at line %2") + .arg(parseErrorMsg) + .arg(parseErrorLine)); return {}; } else @@ -154,9 +158,9 @@ SnippetsMap GetSnippetsFromXML(const QDomElement& snippets_element) { SnippetsMap snippets; - for (auto elem = snippets_element.firstChildElement("snippet"); - !elem.isNull(); - elem = elem.nextSiblingElement("snippet") ) + for (auto elem = snippets_element.firstChildElement("snippet"); !elem.isNull(); + elem = elem.nextSiblingElement("snipp" + "et")) { SnippetData snippet = GetSnippetFromXML(elem); snippets.insert({ snippet.alias_name, snippet }); @@ -164,7 +168,6 @@ SnippetsMap GetSnippetsFromXML(const QDomElement& snippets_element) return snippets; } - QDomElement ExportSnippets(const SnippetsMap& snippets, QDomDocument& doc) { auto snippets_root = doc.createElement("snippets"); @@ -178,7 +181,7 @@ QDomElement ExportSnippets(const SnippetsMap& snippets, QDomDocument& doc) return snippets_root; } -SnippetData GetSnippetFromXML(const QDomElement &element) +SnippetData GetSnippetFromXML(const QDomElement& element) { SnippetData snippet; snippet.linked_source = element.firstChildElement("linked_source").text().trimmed(); @@ -187,23 +190,22 @@ SnippetData GetSnippetFromXML(const QDomElement &element) snippet.function = element.firstChildElement("function").text().trimmed(); auto additional_el = element.firstChildElement("additional_sources"); - if( !additional_el.isNull() ) + if (!additional_el.isNull()) { int count = 1; auto tag_name = QString("v%1").arg(count); - auto source_el = additional_el.firstChildElement( tag_name ); - while( !source_el.isNull() ) + auto source_el = additional_el.firstChildElement(tag_name); + while (!source_el.isNull()) { - snippet.additional_sources.push_back( source_el.text() ); + snippet.additional_sources.push_back(source_el.text()); tag_name = QString("v%1").arg(++count); - source_el = additional_el.firstChildElement( tag_name ); + source_el = additional_el.firstChildElement(tag_name); } } return snippet; } - -QDomElement ExportSnippetToXML(const SnippetData &snippet, QDomDocument &doc) +QDomElement ExportSnippetToXML(const SnippetData& snippet, QDomDocument& doc) { auto element = doc.createElement("snippet"); @@ -221,12 +223,12 @@ QDomElement ExportSnippetToXML(const SnippetData &snippet, QDomDocument &doc) linked_el.appendChild(doc.createTextNode(snippet.linked_source)); element.appendChild(linked_el); - if( snippet.additional_sources.size() > 0) + if (snippet.additional_sources.size() > 0) { auto sources_el = doc.createElement("additional_sources"); int count = 1; - for(QString curve_name: snippet.additional_sources) + for (QString curve_name : snippet.additional_sources) { auto tag_name = QString("v%1").arg(count++); auto source_el = doc.createElement(tag_name); diff --git a/plotjuggler_app/transforms/custom_function.h b/plotjuggler_app/transforms/custom_function.h index d42bfb4e2..a668d34e8 100644 --- a/plotjuggler_app/transforms/custom_function.h +++ b/plotjuggler_app/transforms/custom_function.h @@ -40,22 +40,24 @@ QDomElement ExportSnippets(const SnippetsMap& snippets, QDomDocument& destinatio class CustomFunction : public PJ::TransformFunction { public: - CustomFunction(SnippetData snippet = {}); void setSnippet(const SnippetData& snippet); void reset() override; - int numInputs() const override { + int numInputs() const override + { return -1; } - int numOutputs() const override { + int numOutputs() const override + { return 1; } - QString aliasName() const { + QString aliasName() const + { return _snippet.alias_name; } @@ -71,12 +73,11 @@ class CustomFunction : public PJ::TransformFunction virtual void initEngine() = 0; - void calculateAndAdd(PlotDataMapRef &src_data); + void calculateAndAdd(PlotDataMapRef& src_data); - virtual void calculatePoints( - const std::vector& src_data, - size_t point_index, - std::vector &new_points) = 0; + virtual void calculatePoints(const std::vector& src_data, + size_t point_index, + std::vector& new_points) = 0; protected: SnippetData _snippet; diff --git a/plotjuggler_app/transforms/custom_timeseries.cpp b/plotjuggler_app/transforms/custom_timeseries.cpp index c50d764c0..256dda96d 100644 --- a/plotjuggler_app/transforms/custom_timeseries.cpp +++ b/plotjuggler_app/transforms/custom_timeseries.cpp @@ -2,7 +2,8 @@ #include #include "lua_custom_function.h" -//CustomTimeseries::CustomTimeseries(const Timeseries* source_data, const SnippetData& snippet, PlotDataMapRef& mapped_data) +// CustomTimeseries::CustomTimeseries(const Timeseries* source_data, const SnippetData& +// snippet, PlotDataMapRef& mapped_data) // : TimeseriesQwt(source_data, &_cached_data), _mapped_data(mapped_data) //{ // if (snippet.language == "LUA") @@ -17,7 +18,7 @@ // updateCache(); //} -//bool CustomTimeseries::updateCache() +// bool CustomTimeseries::updateCache() //{ // if (_source_data->size() == 0) // { diff --git a/plotjuggler_app/transforms/custom_timeseries.h b/plotjuggler_app/transforms/custom_timeseries.h index 2a92c6857..cea69650e 100644 --- a/plotjuggler_app/transforms/custom_timeseries.h +++ b/plotjuggler_app/transforms/custom_timeseries.h @@ -9,8 +9,7 @@ class CustomTimeseries : public TransformedTimeseries { public: - CustomTimeseries(const PlotData* source_data, - const SnippetData& snippet, + CustomTimeseries(const PlotData* source_data, const SnippetData& snippet, PlotDataMapRef& mapped_data); bool updateCache(bool reset_old_data) override; diff --git a/plotjuggler_app/transforms/first_derivative.cpp b/plotjuggler_app/transforms/first_derivative.cpp index af2ac08de..120c08cc6 100644 --- a/plotjuggler_app/transforms/first_derivative.cpp +++ b/plotjuggler_app/transforms/first_derivative.cpp @@ -2,38 +2,36 @@ #include #include -FirstDerivative::FirstDerivative(): - _widget(new QWidget()), - ui(new Ui::FirstDerivariveForm), - _dT(0.0) +FirstDerivative::FirstDerivative() + : _widget(new QWidget()), ui(new Ui::FirstDerivariveForm), _dT(0.0) { ui->setupUi(_widget); - ui->lineEditCustom->setValidator( new QDoubleValidator(0.0001, 1000, 4, ui->lineEditCustom) ); - - connect(ui->buttonCompute, &QPushButton::clicked, - this, &FirstDerivative::on_buttonCompute_clicked ); - - connect(ui->lineEditCustom, &QLineEdit::editingFinished, - this, [=](){ - _dT = ui->lineEditCustom->text().toDouble(); - emit parametersChanged(); - } ); - - connect(ui->radioActual, &QRadioButton::toggled, - this, [=](bool toggled){ - if( toggled) { - _dT = 0.0; - emit parametersChanged(); - } - } ); - - connect(ui->radioCustom, &QRadioButton::toggled, - this, [=](bool toggled){ - if( toggled) { - _dT = ui->lineEditCustom->text().toDouble(); - emit parametersChanged(); - } - } ); + ui->lineEditCustom->setValidator( + new QDoubleValidator(0.0001, 1000, 4, ui->lineEditCustom)); + + connect(ui->buttonCompute, &QPushButton::clicked, this, + &FirstDerivative::on_buttonCompute_clicked); + + connect(ui->lineEditCustom, &QLineEdit::editingFinished, this, [=]() { + _dT = ui->lineEditCustom->text().toDouble(); + emit parametersChanged(); + }); + + connect(ui->radioActual, &QRadioButton::toggled, this, [=](bool toggled) { + if (toggled) + { + _dT = 0.0; + emit parametersChanged(); + } + }); + + connect(ui->radioCustom, &QRadioButton::toggled, this, [=](bool toggled) { + if (toggled) + { + _dT = ui->lineEditCustom->text().toDouble(); + emit parametersChanged(); + } + }); } FirstDerivative::~FirstDerivative() @@ -42,68 +40,69 @@ FirstDerivative::~FirstDerivative() delete _widget; } -std::optional -FirstDerivative::calculateNextPoint(size_t index) +std::optional FirstDerivative::calculateNextPoint(size_t index) { - if( index == 0) + if (index == 0) { return {}; } - const auto& prev = dataSource()->at(index-1); + const auto& prev = dataSource()->at(index - 1); const auto& p = dataSource()->at(index); double dt = (_dT == 0.0) ? (p.x - prev.x) : _dT; - if( dt <= 0 ) + if (dt <= 0) { return {}; } double der = (p.y - prev.y) / dt; - PlotData::Point out = {prev.x, der}; + PlotData::Point out = { prev.x, der }; return out; } -QWidget *FirstDerivative::optionsWidget() +QWidget* FirstDerivative::optionsWidget() { const size_t data_size = dataSource()->size(); - if(!dataSource() || data_size < 2) + if (!dataSource() || data_size < 2) { _widget->setEnabled(false); } return _widget; } -bool FirstDerivative::xmlSaveState(QDomDocument &doc, QDomElement &parent_element) const +bool FirstDerivative::xmlSaveState(QDomDocument& doc, QDomElement& parent_element) const { QDomElement widget_el = doc.createElement("options"); - if( ui->radioActual->isChecked() ) + if (ui->radioActual->isChecked()) { widget_el.setAttribute("radioChecked", "radioActual"); } - else{ + else + { widget_el.setAttribute("radioChecked", "radioCustom"); } - widget_el.setAttribute("lineEdit", ui->lineEditCustom->text() ); + widget_el.setAttribute("lineEdit", ui->lineEditCustom->text()); - parent_element.appendChild( widget_el ); + parent_element.appendChild(widget_el); return true; } -bool FirstDerivative::xmlLoadState(const QDomElement &parent_element) +bool FirstDerivative::xmlLoadState(const QDomElement& parent_element) { QDomElement widget_el = parent_element.firstChildElement("options"); - ui->lineEditCustom->setText( widget_el.attribute("lineEdit") ); + ui->lineEditCustom->setText(widget_el.attribute("lineEdit")); - if( widget_el.attribute("radioChecked") == "radioActual") + if (widget_el.attribute("radioChecked") == "radioActual") { ui->radioActual->setChecked(true); } - else{ + else + { ui->radioCustom->setChecked(true); } return true; @@ -111,7 +110,7 @@ bool FirstDerivative::xmlLoadState(const QDomElement &parent_element) void FirstDerivative::on_buttonCompute_clicked() { - if(!dataSource() || dataSource()->size() < 2) + if (!dataSource() || dataSource()->size() < 2) { return; } @@ -120,9 +119,9 @@ void FirstDerivative::on_buttonCompute_clicked() // calculate automatic diff std::vector diff; - diff.reserve(data_size-1); + diff.reserve(data_size - 1); double prev_t = dataSource()->at(0).x; - for(size_t i=1; iat(i).x; double delta = t - prev_t; @@ -132,20 +131,21 @@ void FirstDerivative::on_buttonCompute_clicked() size_t first = 0; size_t last = diff.size(); - if( data_size > 10 ) + if (data_size > 10) { std::sort(diff.begin(), diff.end()); first = last / 5; - last = (last*4)/5; + last = (last * 4) / 5; } double total = 0; - for(size_t i=first; i(last-first); + double estimated_dt = total / static_cast(last - first); ui->lineEditCustom->setText(QString::number(estimated_dt, 'g', 4)); - if( ui->radioCustom->isChecked() ) + if (ui->radioCustom->isChecked()) { _dT = estimated_dt; emit parametersChanged(); diff --git a/plotjuggler_app/transforms/first_derivative.h b/plotjuggler_app/transforms/first_derivative.h index 6ec5696a7..cec2cb68d 100644 --- a/plotjuggler_app/transforms/first_derivative.h +++ b/plotjuggler_app/transforms/first_derivative.h @@ -7,14 +7,17 @@ using namespace PJ; -class FirstDerivative: public TransformFunction_SISO +class FirstDerivative : public TransformFunction_SISO { public: FirstDerivative(); ~FirstDerivative() override; - const char* name() const override { return "Derivative"; } + const char* name() const override + { + return "Derivative"; + } QWidget* optionsWidget() override; @@ -25,13 +28,11 @@ class FirstDerivative: public TransformFunction_SISO void on_buttonCompute_clicked(); private: - std::optional - calculateNextPoint(size_t index) override; + std::optional calculateNextPoint(size_t index) override; - QWidget *_widget; + QWidget* _widget; Ui::FirstDerivariveForm* ui; double _dT; - }; -#endif // FIRST_DERIVATIVE_H +#endif // FIRST_DERIVATIVE_H diff --git a/plotjuggler_app/transforms/function_editor.cpp b/plotjuggler_app/transforms/function_editor.cpp index a4191a704..01b95faca 100644 --- a/plotjuggler_app/transforms/function_editor.cpp +++ b/plotjuggler_app/transforms/function_editor.cpp @@ -38,7 +38,7 @@ void FunctionEditorWidget::on_stylesheetChanged(QString theme) } FunctionEditorWidget::FunctionEditorWidget(PlotDataMapRef& plotMapData, - const TransformsMap &mapped_custom_plots, + const TransformsMap& mapped_custom_plots, QWidget* parent) : QWidget(parent) , _plot_map_data(plotMapData) @@ -76,7 +76,8 @@ FunctionEditorWidget::FunctionEditorWidget(PlotDataMapRef& plotMapData, } numericPlotNames.sort(Qt::CaseInsensitive); - QByteArray saved_xml = settings.value("AddCustomPlotDialog.recentSnippetsXML", QByteArray()).toByteArray(); + QByteArray saved_xml = + settings.value("AddCustomPlotDialog.recentSnippetsXML", QByteArray()).toByteArray(); restoreGeometry(settings.value("AddCustomPlotDialog.geometry").toByteArray()); if (saved_xml.isEmpty()) @@ -96,14 +97,16 @@ FunctionEditorWidget::FunctionEditorWidget(PlotDataMapRef& plotMapData, connect(ui->snippetsListSaved, &QListWidget::customContextMenuRequested, this, &FunctionEditorWidget::savedContextMenu); - ui->globalVarsTextField->setPlainText(settings.value("AddCustomPlotDialog.previousGlobals", "").toString()); + ui->globalVarsTextField->setPlainText( + settings.value("AddCustomPlotDialog.previousGlobals", "").toString()); - ui->mathEquation->setPlainText(settings.value("AddCustomPlotDialog.previousFunction", "return value").toString()); + ui->mathEquation->setPlainText( + settings.value("AddCustomPlotDialog.previousFunction", "return value").toString()); ui->lineEditSource->installEventFilter(this); ui->listAdditionalSources->installEventFilter(this); - auto preview_layout = new QHBoxLayout( ui->framePlotPreview); + auto preview_layout = new QHBoxLayout(ui->framePlotPreview); preview_layout->setMargin(6); preview_layout->addWidget(_preview_widget->widget()); @@ -111,8 +114,8 @@ FunctionEditorWidget::FunctionEditorWidget(PlotDataMapRef& plotMapData, _update_preview_timer.setSingleShot(true); - connect(&_update_preview_timer, &QTimer::timeout, - this, &FunctionEditorWidget::on_updatePreview); + connect(&_update_preview_timer, &QTimer::timeout, this, + &FunctionEditorWidget::on_updatePreview); updatePreview(); } @@ -124,8 +127,10 @@ FunctionEditorWidget::~FunctionEditorWidget() QSettings settings; settings.setValue("AddCustomPlotDialog.recentSnippetsXML", exportSnippets()); settings.setValue("AddCustomPlotDialog.geometry", saveGeometry()); - settings.setValue("AddCustomPlotDialog.previousGlobals", ui->globalVarsTextField->toPlainText()); - settings.setValue("AddCustomPlotDialog.previousFunction", ui->mathEquation->toPlainText()); + settings.setValue("AddCustomPlotDialog.previousGlobals", + ui->globalVarsTextField->toPlainText()); + settings.setValue("AddCustomPlotDialog.previousFunction", + ui->mathEquation->toPlainText()); delete ui; } @@ -142,7 +147,6 @@ void FunctionEditorWidget::clear() ui->listAdditionalSources->setRowCount(0); } - QString FunctionEditorWidget::getLinkedData() const { return ui->lineEditSource->text(); @@ -170,13 +174,12 @@ void FunctionEditorWidget::createNewPlot() _editor_mode = CREATE; } - void FunctionEditorWidget::editExistingPlot(CustomPlotPtr data) { ui->globalVarsTextField->setPlainText(data->snippet().global_vars); ui->mathEquation->setPlainText(data->snippet().function); - setLinkedPlotName( data->snippet().linked_source ); - ui->nameLineEdit->setText( data->aliasName() ); + setLinkedPlotName(data->snippet().linked_source); + ui->nameLineEdit->setText(data->aliasName()); ui->nameLineEdit->setEnabled(false); _editor_mode = MODIFY; @@ -184,33 +187,34 @@ void FunctionEditorWidget::editExistingPlot(CustomPlotPtr data) auto list_widget = ui->listAdditionalSources; list_widget->setRowCount(0); - for (QString curve_name: data->snippet().additional_sources) { - if( list_widget->findItems(curve_name, Qt::MatchExactly).isEmpty() && - curve_name != ui->lineEditSource->text() ) + for (QString curve_name : data->snippet().additional_sources) + { + if (list_widget->findItems(curve_name, Qt::MatchExactly).isEmpty() && + curve_name != ui->lineEditSource->text()) { int row = list_widget->rowCount(); - list_widget->setRowCount(row+1); - list_widget->setItem(row,0, new QTableWidgetItem( QString("v%1").arg(row+1))); - list_widget->setItem(row,1, new QTableWidgetItem(curve_name)); + list_widget->setRowCount(row + 1); + list_widget->setItem(row, 0, new QTableWidgetItem(QString("v%1").arg(row + 1))); + list_widget->setItem(row, 1, new QTableWidgetItem(curve_name)); } } on_listSourcesChanged(); } -//CustomPlotPtr FunctionEditorWidget::getCustomPlotData() const +// CustomPlotPtr FunctionEditorWidget::getCustomPlotData() const //{ // return _plot; //} -bool FunctionEditorWidget::eventFilter(QObject *obj, QEvent *ev) +bool FunctionEditorWidget::eventFilter(QObject* obj, QEvent* ev) { - if( ev->type() == QEvent::DragEnter ) + if (ev->type() == QEvent::DragEnter) { auto event = static_cast(ev); const QMimeData* mimeData = event->mimeData(); QStringList mimeFormats = mimeData->formats(); - for(const QString& format : mimeFormats) + for (const QString& format : mimeFormats) { QByteArray encoded = mimeData->data(format); QDataStream stream(&encoded, QIODevice::ReadOnly); @@ -231,32 +235,34 @@ bool FunctionEditorWidget::eventFilter(QObject *obj, QEvent *ev) _dragging_curves.push_back(curve_name); } } - if( (obj == ui->lineEditSource && _dragging_curves.size() == 1) - || (obj == ui->listAdditionalSources && _dragging_curves.size() > 0) ) + if ((obj == ui->lineEditSource && _dragging_curves.size() == 1) || + (obj == ui->listAdditionalSources && _dragging_curves.size() > 0)) { event->acceptProposedAction(); return true; } } } - else if ( ev->type() == QEvent::Drop ) { - if( obj == ui->lineEditSource ) + else if (ev->type() == QEvent::Drop) + { + if (obj == ui->lineEditSource) { - ui->lineEditSource->setText( _dragging_curves.front() ); + ui->lineEditSource->setText(_dragging_curves.front()); } - else if ( obj == ui->listAdditionalSources ) + else if (obj == ui->listAdditionalSources) { auto list_widget = ui->listAdditionalSources; - for (QString curve_name: _dragging_curves) { - if( list_widget->findItems(curve_name, Qt::MatchExactly).isEmpty() && - curve_name != ui->lineEditSource->text() ) + for (QString curve_name : _dragging_curves) + { + if (list_widget->findItems(curve_name, Qt::MatchExactly).isEmpty() && + curve_name != ui->lineEditSource->text()) { int row = list_widget->rowCount(); - list_widget->setRowCount(row+1); - list_widget->setItem(row,0, new QTableWidgetItem( QString("v%1").arg(row+1))); - list_widget->setItem(row,1, new QTableWidgetItem(curve_name)); + list_widget->setRowCount(row + 1); + list_widget->setItem(row, 0, new QTableWidgetItem(QString("v%1").arg(row + 1))); + list_widget->setItem(row, 1, new QTableWidgetItem(curve_name)); } - } + } on_listSourcesChanged(); } } @@ -277,8 +283,9 @@ void FunctionEditorWidget::importSnippets(const QByteArray& xml_text) for (const auto& custom_it : _transform_maps) { - auto math_plot = dynamic_cast( custom_it.second.get() ); - if ( !math_plot ){ + auto math_plot = dynamic_cast(custom_it.second.get()); + if (!math_plot) + { continue; } SnippetData snippet; @@ -315,22 +322,22 @@ void FunctionEditorWidget::on_snippetsListSaved_currentRowChanged(int current_ro QString preview; - if( !snippet.global_vars.isEmpty() ) + if (!snippet.global_vars.isEmpty()) { - preview += snippet.global_vars + "\n\n"; + preview += snippet.global_vars + "\n\n"; } preview += "function calc(time, value"; - for (int i=1; i<= snippet.additional_sources.size(); i++) + for (int i = 1; i <= snippet.additional_sources.size(); i++) { preview += QString(", v%1").arg(i); } preview += ")\n"; auto function_lines = snippet.function.split("\n"); - for (const auto& line: function_lines) + for (const auto& line : function_lines) { - preview += " " + line + "\n"; + preview += " " + line + "\n"; } preview += "end"; ui->snippetPreview->setPlainText(preview); @@ -389,12 +396,11 @@ void FunctionEditorWidget::on_nameLineEdit_textChanged(const QString& name) void FunctionEditorWidget::on_buttonLoadFunctions_clicked() { QSettings settings; - QString directory_path = settings.value("AddCustomPlotDialog.loadDirectory", QDir::currentPath()).toString(); + QString directory_path = + settings.value("AddCustomPlotDialog.loadDirectory", QDir::currentPath()).toString(); - QString fileName = - QFileDialog::getOpenFileName(this, tr("Open Snippet Library"), - directory_path, - tr("Snippets (*.snippets.xml)")); + QString fileName = QFileDialog::getOpenFileName( + this, tr("Open Snippet Library"), directory_path, tr("Snippets (*.snippets.xml)")); if (fileName.isEmpty()) { return; @@ -404,7 +410,8 @@ void FunctionEditorWidget::on_buttonLoadFunctions_clicked() if (!file.open(QIODevice::ReadOnly)) { - QMessageBox::critical(this, "Error", QString("Failed to open the file [%1]").arg(fileName)); + QMessageBox::critical(this, "Error", + QString("Failed to open the file [%1]").arg(fileName)); return; } @@ -417,13 +424,11 @@ void FunctionEditorWidget::on_buttonLoadFunctions_clicked() void FunctionEditorWidget::on_buttonSaveFunctions_clicked() { QSettings settings; - QString directory_path = settings.value("AddCustomPlotDialog.loadDirectory", - QDir::currentPath()).toString(); + QString directory_path = + settings.value("AddCustomPlotDialog.loadDirectory", QDir::currentPath()).toString(); - QString fileName = - QFileDialog::getSaveFileName(this, tr("Open Snippet Library"), - directory_path, - tr("Snippets (*.snippets.xml)")); + QString fileName = QFileDialog::getSaveFileName( + this, tr("Open Snippet Library"), directory_path, tr("Snippets (*.snippets.xml)")); if (fileName.isEmpty()) { @@ -437,7 +442,8 @@ void FunctionEditorWidget::on_buttonSaveFunctions_clicked() QFile file(fileName); if (!file.open(QIODevice::WriteOnly)) { - QMessageBox::critical(this, "Error", QString("Failed to open the file [%1]").arg(fileName)); + QMessageBox::critical(this, "Error", + QString("Failed to open the file [%1]").arg(fileName)); return; } auto data = exportSnippets(); @@ -454,16 +460,16 @@ void FunctionEditorWidget::on_buttonSaveCurrent_clicked() QString name; auto selected_snippets = ui->snippetsListSaved->selectedItems(); - if( selected_snippets.size() >= 1 ) + if (selected_snippets.size() >= 1) { name = selected_snippets.front()->text(); } bool ok = false; - name = QInputDialog::getText(this, tr("Name of the Function"), - tr("Name:"), QLineEdit::Normal, - name, &ok); + name = QInputDialog::getText(this, tr("Name of the Function"), tr("Name:"), + QLineEdit::Normal, name, &ok); - if (!ok || name.isEmpty()) { + if (!ok || name.isEmpty()) + { return; } @@ -483,7 +489,8 @@ bool FunctionEditorWidget::addToSaved(const QString& name, const SnippetData& sn { QMessageBox msgBox(this); msgBox.setWindowTitle("Warning"); - msgBox.setText(tr("A function with the same name exists already in the list of saved functions.\n")); + msgBox.setText(tr("A function with the same name exists already in the list of saved " + "functions.\n")); msgBox.addButton(QMessageBox::Cancel); QPushButton* button = msgBox.addButton(tr("Overwrite"), QMessageBox::YesRole); msgBox.setDefaultButton(button); @@ -511,8 +518,8 @@ void FunctionEditorWidget::onRenameSaved() const auto& name = item->text(); bool ok; - QString new_name = - QInputDialog::getText(this, tr("Change the name of the function"), tr("New name:"), QLineEdit::Normal, name, &ok); + QString new_name = QInputDialog::getText(this, tr("Change the name of the function"), + tr("New name:"), QLineEdit::Normal, name, &ok); if (!ok || new_name.isEmpty() || new_name == name) { @@ -557,9 +564,10 @@ void FunctionEditorWidget::on_pushButtonCreate_clicked() snippet.global_vars = getglobal_vars(); snippet.alias_name = getName(); snippet.linked_source = getLinkedData(); - for(int row = 0; row < ui->listAdditionalSources->rowCount(); row++) + for (int row = 0; row < ui->listAdditionalSources->rowCount(); row++) { - snippet.additional_sources.push_back( ui->listAdditionalSources->item(row,1)->text()); + snippet.additional_sources.push_back( + ui->listAdditionalSources->item(row, 1)->text()); } CustomPlotPtr plot = std::make_unique(snippet); @@ -567,28 +575,28 @@ void FunctionEditorWidget::on_pushButtonCreate_clicked() } catch (const std::runtime_error& e) { - QMessageBox::critical(this, "Error", "Failed to create math plot : " + QString::fromStdString(e.what())); + QMessageBox::critical(this, "Error", + "Failed to create math plot : " + + QString::fromStdString(e.what())); } } - void FunctionEditorWidget::on_pushButtonCancel_pressed() { - if( _editor_mode == MODIFY ) + if (_editor_mode == MODIFY) { clear(); } closed(); } - void FunctionEditorWidget::on_listSourcesChanged() { QString function_text("function( time, value"); - for(int row = 0; row < ui->listAdditionalSources->rowCount(); row++) + for (int row = 0; row < ui->listAdditionalSources->rowCount(); row++) { function_text += ", "; - function_text += ui->listAdditionalSources->item(row,0)->text(); + function_text += ui->listAdditionalSources->item(row, 0)->text(); } function_text += " )"; ui->labelFunction->setText(function_text); @@ -598,29 +606,29 @@ void FunctionEditorWidget::on_listSourcesChanged() void FunctionEditorWidget::on_listAdditionalSources_itemSelectionChanged() { - bool any_selected = !ui->listAdditionalSources->selectedItems().isEmpty(); - ui->pushButtonDeleteCurves->setEnabled(any_selected); + bool any_selected = !ui->listAdditionalSources->selectedItems().isEmpty(); + ui->pushButtonDeleteCurves->setEnabled(any_selected); } void FunctionEditorWidget::on_pushButtonDeleteCurves_clicked() { auto list_sources = ui->listAdditionalSources; QModelIndexList selected = list_sources->selectionModel()->selectedRows(); - while( selected.size() > 0 ) + while (selected.size() > 0) { - list_sources->removeRow( selected.first().row() ); + list_sources->removeRow(selected.first().row()); selected = list_sources->selectionModel()->selectedRows(); } - for( int row = 0; row < list_sources->rowCount(); row++ ) + for (int row = 0; row < list_sources->rowCount(); row++) { - list_sources->item(row,0)->setText( QString("v%1").arg(row+1) ); + list_sources->item(row, 0)->setText(QString("v%1").arg(row + 1)); } on_listAdditionalSources_itemSelectionChanged(); on_listSourcesChanged(); } -void FunctionEditorWidget::on_lineEditSource_textChanged(const QString &text) +void FunctionEditorWidget::on_lineEditSource_textChanged(const QString& text) { updatePreview(); } @@ -632,7 +640,7 @@ void FunctionEditorWidget::on_mathEquation_textChanged() void FunctionEditorWidget::updatePreview() { - _update_preview_timer.start(250); + _update_preview_timer.start(250); } void FunctionEditorWidget::on_updatePreview() @@ -640,29 +648,34 @@ void FunctionEditorWidget::on_updatePreview() QString errors; std::string new_plot_name = ui->nameLineEdit->text().toStdString(); - if ( _transform_maps.count(new_plot_name) != 0 ) + if (_transform_maps.count(new_plot_name) != 0) { - if( ui->lineEditSource->text().toStdString() == new_plot_name || - ui->listAdditionalSources->findItems(getName(), Qt::MatchExactly).isEmpty() == false ) + if (ui->lineEditSource->text().toStdString() == new_plot_name || + ui->listAdditionalSources->findItems(getName(), Qt::MatchExactly).isEmpty() == + false) { - errors += "- The name of the new timeseries is the same of one of its dependencies.\n"; + errors += "- The name of the new timeseries is the same of one of its " + "dependencies.\n"; } } - if( new_plot_name.empty() ) { - errors+= "- Missing name of the new time series.\n"; + if (new_plot_name.empty()) + { + errors += "- Missing name of the new time series.\n"; } - else{ + else + { // check if name is unique (except if is custom_plot) - if (_plot_map_data.numeric.count(new_plot_name) != 0 && _transform_maps.count(new_plot_name) == 0) + if (_plot_map_data.numeric.count(new_plot_name) != 0 && + _transform_maps.count(new_plot_name) == 0) { - errors+= "- Plot name already exists and can't be modified.\n"; + errors += "- Plot name already exists and can't be modified.\n"; } } - if( ui->lineEditSource->text().isEmpty() ) + if (ui->lineEditSource->text().isEmpty()) { - errors+= "- Missing source time series.\n"; + errors += "- Missing source time series.\n"; } SnippetData snippet; @@ -670,51 +683,57 @@ void FunctionEditorWidget::on_updatePreview() snippet.global_vars = getglobal_vars(); snippet.alias_name = getName(); snippet.linked_source = getLinkedData(); - for(int row = 0; row < ui->listAdditionalSources->rowCount(); row++) + for (int row = 0; row < ui->listAdditionalSources->rowCount(); row++) { - snippet.additional_sources.push_back( ui->listAdditionalSources->item(row,1)->text()); + snippet.additional_sources.push_back(ui->listAdditionalSources->item(row, 1)->text()); } CustomPlotPtr lua_function; - try { + try + { lua_function = std::make_unique(snippet); ui->buttonSaveCurrent->setEnabled(true); - } catch (...) + } + catch (...) { - errors+= "- The Lua function is not valid.\n"; + errors += "- The Lua function is not valid.\n"; ui->buttonSaveCurrent->setEnabled(false); } - if( lua_function ) + if (lua_function) { - try { + try + { std::string name = new_plot_name.empty() ? "no_name" : new_plot_name; PlotData& out_data = _local_plot_data.getOrCreateNumeric(name); out_data.clear(); - std::vector out_vector = {&out_data}; - lua_function->setData( &_plot_map_data, {}, out_vector ); + std::vector out_vector = { &out_data }; + lua_function->setData(&_plot_map_data, {}, out_vector); lua_function->calculate(); _preview_widget->removeAllCurves(); _preview_widget->addCurve(name, Qt::blue); _preview_widget->zoomOut(false); - } catch (...) { - errors+= "- The Lua function can not compute the result.\n"; + } + catch (...) + { + errors += "- The Lua function can not compute the result.\n"; } } //---------------------------------- QFile file(":/resources/svg/red_circle.svg"); - if( errors.isEmpty() ) + if (errors.isEmpty()) { errors = "Everything is fine :)"; file.setFileName(":/resources/svg/green_circle.svg"); ui->pushButtonCreate->setEnabled(true); } - else{ - errors = errors.left( errors.size()-1 ); + else + { + errors = errors.left(errors.size() - 1); ui->pushButtonCreate->setEnabled(false); } @@ -725,12 +744,12 @@ void FunctionEditorWidget::on_updatePreview() auto svg_data = file.readAll(); file.close(); QByteArray content(svg_data); - QSvgRenderer rr( content ); + QSvgRenderer rr(content); QImage image(26, 26, QImage::Format_ARGB32); QPainter painter(&image); image.fill(Qt::transparent); rr.render(&painter); - ui->labelSemaphore->setPixmap( QPixmap::fromImage(image) ); + ui->labelSemaphore->setPixmap(QPixmap::fromImage(image)); } void FunctionEditorWidget::on_globalVarsTextField_textChanged() diff --git a/plotjuggler_app/transforms/function_editor.h b/plotjuggler_app/transforms/function_editor.h index 649a30e28..1f8a76661 100644 --- a/plotjuggler_app/transforms/function_editor.h +++ b/plotjuggler_app/transforms/function_editor.h @@ -43,11 +43,11 @@ class FunctionEditorWidget : public QWidget void editExistingPlot(CustomPlotPtr data); - bool eventFilter(QObject *obj, QEvent *event) override; + bool eventFilter(QObject* obj, QEvent* event) override; public slots: void on_stylesheetChanged(QString theme); - + private slots: void on_snippetsListSaved_currentRowChanged(int currentRow); @@ -75,8 +75,8 @@ private slots: void on_pushButtonDeleteCurves_clicked(); void on_listSourcesChanged(); - - void on_lineEditSource_textChanged(const QString &text); + + void on_lineEditSource_textChanged(const QString& text); void on_mathEquation_textChanged(); diff --git a/plotjuggler_app/transforms/integral_transform.cpp b/plotjuggler_app/transforms/integral_transform.cpp index 3024c9b57..30f02d671 100644 --- a/plotjuggler_app/transforms/integral_transform.cpp +++ b/plotjuggler_app/transforms/integral_transform.cpp @@ -2,38 +2,36 @@ #include #include -IntegralTransform::IntegralTransform(): - _widget(new QWidget()), - ui(new Ui::IntegralTransform), - _dT(0.0) +IntegralTransform::IntegralTransform() + : _widget(new QWidget()), ui(new Ui::IntegralTransform), _dT(0.0) { ui->setupUi(_widget); - ui->lineEditCustom->setValidator( new QDoubleValidator(0.0001, 1000, 4, ui->lineEditCustom) ); - - connect(ui->buttonCompute, &QPushButton::clicked, - this, &IntegralTransform::on_buttonCompute_clicked ); - - connect(ui->lineEditCustom, &QLineEdit::editingFinished, - this, [=](){ - _dT = ui->lineEditCustom->text().toDouble(); - emit parametersChanged(); - } ); - - connect(ui->radioActual, &QRadioButton::toggled, - this, [=](bool toggled){ - if( toggled) { - _dT = 0.0; - emit parametersChanged(); - } - } ); - - connect(ui->radioCustom, &QRadioButton::toggled, - this, [=](bool toggled){ - if( toggled) { - _dT = ui->lineEditCustom->text().toDouble(); - emit parametersChanged(); - } - } ); + ui->lineEditCustom->setValidator( + new QDoubleValidator(0.0001, 1000, 4, ui->lineEditCustom)); + + connect(ui->buttonCompute, &QPushButton::clicked, this, + &IntegralTransform::on_buttonCompute_clicked); + + connect(ui->lineEditCustom, &QLineEdit::editingFinished, this, [=]() { + _dT = ui->lineEditCustom->text().toDouble(); + emit parametersChanged(); + }); + + connect(ui->radioActual, &QRadioButton::toggled, this, [=](bool toggled) { + if (toggled) + { + _dT = 0.0; + emit parametersChanged(); + } + }); + + connect(ui->radioCustom, &QRadioButton::toggled, this, [=](bool toggled) { + if (toggled) + { + _dT = ui->lineEditCustom->text().toDouble(); + emit parametersChanged(); + } + }); } IntegralTransform::~IntegralTransform() @@ -42,35 +40,34 @@ IntegralTransform::~IntegralTransform() delete _widget; } -std::optional -IntegralTransform::calculateNextPoint(size_t index) +std::optional IntegralTransform::calculateNextPoint(size_t index) { - if( index == 0) + if (index == 0) { return {}; } - const auto& prev = dataSource()->at(index-1); + const auto& prev = dataSource()->at(index - 1); const auto& p = dataSource()->at(index); double dt = (_dT == 0.0) ? (p.x - prev.x) : _dT; - if( dt <= 0 ) + if (dt <= 0) { return {}; } double val = (p.y + prev.y) * dt / (2.0); _accumulated_value += val; - PlotData::Point out = {p.x, _accumulated_value}; + PlotData::Point out = { p.x, _accumulated_value }; return out; } -QWidget *IntegralTransform::optionsWidget() +QWidget* IntegralTransform::optionsWidget() { const size_t data_size = dataSource()->size(); - if(!dataSource() || data_size < 2) + if (!dataSource() || data_size < 2) { _widget->setEnabled(false); } @@ -83,34 +80,36 @@ void IntegralTransform::reset() TransformFunction_SISO::reset(); } -bool IntegralTransform::xmlSaveState(QDomDocument &doc, QDomElement &parent_element) const +bool IntegralTransform::xmlSaveState(QDomDocument& doc, QDomElement& parent_element) const { QDomElement widget_el = doc.createElement("options"); - if( ui->radioActual->isChecked() ) + if (ui->radioActual->isChecked()) { widget_el.setAttribute("radioChecked", "radioActual"); } - else{ + else + { widget_el.setAttribute("radioChecked", "radioCustom"); } - widget_el.setAttribute("lineEdit", ui->lineEditCustom->text() ); + widget_el.setAttribute("lineEdit", ui->lineEditCustom->text()); - parent_element.appendChild( widget_el ); + parent_element.appendChild(widget_el); return true; } -bool IntegralTransform::xmlLoadState(const QDomElement &parent_element) +bool IntegralTransform::xmlLoadState(const QDomElement& parent_element) { QDomElement widget_el = parent_element.firstChildElement("options"); - ui->lineEditCustom->setText( widget_el.attribute("lineEdit") ); + ui->lineEditCustom->setText(widget_el.attribute("lineEdit")); - if( widget_el.attribute("radioChecked") == "radioActual") + if (widget_el.attribute("radioChecked") == "radioActual") { ui->radioActual->setChecked(true); } - else{ + else + { ui->radioCustom->setChecked(true); } return true; @@ -118,7 +117,7 @@ bool IntegralTransform::xmlLoadState(const QDomElement &parent_element) void IntegralTransform::on_buttonCompute_clicked() { - if(!dataSource() || dataSource()->size() < 2) + if (!dataSource() || dataSource()->size() < 2) { return; } @@ -127,9 +126,9 @@ void IntegralTransform::on_buttonCompute_clicked() // calculate automatic diff std::vector diff; - diff.reserve(data_size-1); + diff.reserve(data_size - 1); double prev_t = dataSource()->at(0).x; - for(size_t i=1; iat(i).x; double delta = t - prev_t; @@ -139,20 +138,21 @@ void IntegralTransform::on_buttonCompute_clicked() size_t first = 0; size_t last = diff.size(); - if( data_size > 10 ) + if (data_size > 10) { std::sort(diff.begin(), diff.end()); first = last / 5; - last = (last*4)/5; + last = (last * 4) / 5; } double total = 0; - for(size_t i=first; i(last-first); + double estimated_dt = total / static_cast(last - first); ui->lineEditCustom->setText(QString::number(estimated_dt, 'g', 4)); - if( ui->radioCustom->isChecked() ) + if (ui->radioCustom->isChecked()) { _dT = estimated_dt; emit parametersChanged(); diff --git a/plotjuggler_app/transforms/integral_transform.h b/plotjuggler_app/transforms/integral_transform.h index 222eaf7f2..4637c1484 100644 --- a/plotjuggler_app/transforms/integral_transform.h +++ b/plotjuggler_app/transforms/integral_transform.h @@ -7,14 +7,17 @@ using namespace PJ; -class IntegralTransform: public TransformFunction_SISO +class IntegralTransform : public TransformFunction_SISO { public: IntegralTransform(); ~IntegralTransform() override; - const char* name() const override { return "Integral"; } + const char* name() const override + { + return "Integral"; + } QWidget* optionsWidget() override; @@ -27,14 +30,13 @@ class IntegralTransform: public TransformFunction_SISO void on_buttonCompute_clicked(); private: - std::optional - calculateNextPoint(size_t index) override; + std::optional calculateNextPoint(size_t index) override; - QWidget *_widget; + QWidget* _widget; Ui::IntegralTransform* ui; double _dT; double _accumulated_value; }; -#endif // INTEGRAL_TRANSFORM_H +#endif // INTEGRAL_TRANSFORM_H diff --git a/plotjuggler_app/transforms/lua_custom_function.cpp b/plotjuggler_app/transforms/lua_custom_function.cpp index f96cb9b10..bb3ed2610 100644 --- a/plotjuggler_app/transforms/lua_custom_function.cpp +++ b/plotjuggler_app/transforms/lua_custom_function.cpp @@ -1,7 +1,6 @@ #include "lua_custom_function.h" -LuaCustomFunction::LuaCustomFunction(SnippetData snippet) - : CustomFunction(snippet) +LuaCustomFunction::LuaCustomFunction(SnippetData snippet) : CustomFunction(snippet) { initEngine(); } @@ -15,7 +14,7 @@ void LuaCustomFunction::initEngine() _lua_engine->script(_snippet.global_vars.toStdString()); auto calcMethodStr = QString("function calc(time, value"); - for(int index = 1; index <= _snippet.additional_sources.size(); index++ ) + for (int index = 1; index <= _snippet.additional_sources.size(); index++) { calcMethodStr += QString(", v%1").arg(index); } @@ -26,13 +25,13 @@ void LuaCustomFunction::initEngine() _lua_function = (*_lua_engine)["calc"]; } -void LuaCustomFunction::calculatePoints(const std::vector &src_data, +void LuaCustomFunction::calculatePoints(const std::vector& src_data, size_t point_index, - std::vector &points) + std::vector& points) { std::unique_lock lk(mutex_); - _chan_values.resize( src_data.size() ); + _chan_values.resize(src_data.size()); const PlotData::Point& old_point = src_data.front()->at(point_index); @@ -55,31 +54,41 @@ void LuaCustomFunction::calculatePoints(const std::vector &src sol::safe_function_result result; const auto& v = _chan_values; // ugly code, sorry - switch( _snippet.additional_sources.size() ) + switch (_snippet.additional_sources.size()) { - case 0: result = _lua_function(old_point.x, v[0]); - break; - case 1: result = _lua_function(old_point.x, v[0], v[1]); - break; - case 2: result = _lua_function(old_point.x,v[0], v[1], v[2]); - break; - case 3: result = _lua_function(old_point.x, v[0], v[1], v[2], v[3]); - break; - case 4: result = _lua_function(old_point.x, v[0], v[1], v[2], v[3], v[4]); - break; - case 5: result = _lua_function(old_point.x, v[0], v[1], v[2], v[3], v[4], v[5]); - break; - case 6: result = _lua_function(old_point.x, v[0], v[1], v[2], v[3], v[4], v[5], v[6]); - break; - case 7: result = _lua_function(old_point.x, v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]); - break; - case 8: result = _lua_function(old_point.x, v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8]); - break; - default: - throw std::runtime_error("Lua Engine : maximum number of additional source is 8"); + case 0: + result = _lua_function(old_point.x, v[0]); + break; + case 1: + result = _lua_function(old_point.x, v[0], v[1]); + break; + case 2: + result = _lua_function(old_point.x, v[0], v[1], v[2]); + break; + case 3: + result = _lua_function(old_point.x, v[0], v[1], v[2], v[3]); + break; + case 4: + result = _lua_function(old_point.x, v[0], v[1], v[2], v[3], v[4]); + break; + case 5: + result = _lua_function(old_point.x, v[0], v[1], v[2], v[3], v[4], v[5]); + break; + case 6: + result = _lua_function(old_point.x, v[0], v[1], v[2], v[3], v[4], v[5], v[6]); + break; + case 7: + result = _lua_function(old_point.x, v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]); + break; + case 8: + result = _lua_function(old_point.x, v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], + v[8]); + break; + default: + throw std::runtime_error("Lua Engine : maximum number of additional source is 8"); } - if( !result.valid() ) + if (!result.valid()) { throw std::runtime_error("Lua Engine : invalid function (missing variable?)"); } @@ -115,12 +124,13 @@ void LuaCustomFunction::calculatePoints(const std::vector &src } else { - throw std::runtime_error("Lua Engine : return either a single value, two values (time, value) " + throw std::runtime_error("Lua Engine : return either a single value, two values " + "(time, value) " "or an array of two-sized arrays (time, value)"); } } -bool LuaCustomFunction::xmlLoadState(const QDomElement &parent_element) +bool LuaCustomFunction::xmlLoadState(const QDomElement& parent_element) { bool ret = CustomFunction::xmlLoadState(parent_element); initEngine(); diff --git a/plotjuggler_app/transforms/lua_custom_function.h b/plotjuggler_app/transforms/lua_custom_function.h index 627ae37f3..62c68ade1 100644 --- a/plotjuggler_app/transforms/lua_custom_function.h +++ b/plotjuggler_app/transforms/lua_custom_function.h @@ -7,14 +7,12 @@ class LuaCustomFunction : public CustomFunction { public: - LuaCustomFunction(SnippetData snippet = {}); void initEngine() override; void calculatePoints(const std::vector& channels_data, - size_t point_index, - std::vector &points) override; + size_t point_index, std::vector& points) override; QString language() const override { diff --git a/plotjuggler_app/transforms/moving_average_filter.cpp b/plotjuggler_app/transforms/moving_average_filter.cpp index 4c5876e5c..11df3cd4d 100644 --- a/plotjuggler_app/transforms/moving_average_filter.cpp +++ b/plotjuggler_app/transforms/moving_average_filter.cpp @@ -3,19 +3,19 @@ #include #include -MovingAverageFilter::MovingAverageFilter() : - ui(new Ui::MovingAverageFilter), - _widget(new QWidget()), - _buffer(1), - _ring_view( _buffer.begin(), _buffer.end() ) +MovingAverageFilter::MovingAverageFilter() + : ui(new Ui::MovingAverageFilter) + , _widget(new QWidget()) + , _buffer(1) + , _ring_view(_buffer.begin(), _buffer.end()) { ui->setupUi(_widget); - connect(ui->spinBoxSamples, qOverload(&QSpinBox::valueChanged), - this, [=](int){ emit parametersChanged(); } ); + connect(ui->spinBoxSamples, qOverload(&QSpinBox::valueChanged), this, + [=](int) { emit parametersChanged(); }); - connect(ui->checkBoxTimeOffset, &QCheckBox::toggled, - this, [=](){ emit parametersChanged(); } ); + connect(ui->checkBoxTimeOffset, &QCheckBox::toggled, this, + [=]() { emit parametersChanged(); }); } MovingAverageFilter::~MovingAverageFilter() @@ -30,60 +30,62 @@ void MovingAverageFilter::reset() TransformFunction_SISO::reset(); } -std::optional -MovingAverageFilter::calculateNextPoint(size_t index) +std::optional MovingAverageFilter::calculateNextPoint(size_t index) { - size_t buffer_size = std::min( size_t(ui->spinBoxSamples->value()), - size_t(dataSource()->size())); - if( buffer_size != _buffer.size() ) { - _buffer.resize( buffer_size ); + size_t buffer_size = + std::min(size_t(ui->spinBoxSamples->value()), size_t(dataSource()->size())); + if (buffer_size != _buffer.size()) + { + _buffer.resize(buffer_size); _ring_view = nonstd::ring_span(_buffer.begin(), _buffer.end()); } const auto& p = dataSource()->at(index); _ring_view.push_back(p); - while( _ring_view.size() < buffer_size ) + while (_ring_view.size() < buffer_size) { _ring_view.push_back(p); } double total = 0; - for(size_t i=0; i < buffer_size; i++) + for (size_t i = 0; i < buffer_size; i++) { total += _ring_view[i].y; } double time = p.x; - if( ui->checkBoxTimeOffset->isChecked()) + if (ui->checkBoxTimeOffset->isChecked()) { time = (_ring_view.back().x + _ring_view.front().x) / 2.0; } - PlotData::Point out = {time, total / _ring_view.size() }; + PlotData::Point out = { time, total / _ring_view.size() }; return out; } -QWidget *MovingAverageFilter::optionsWidget() +QWidget* MovingAverageFilter::optionsWidget() { return _widget; } -bool MovingAverageFilter::xmlSaveState(QDomDocument &doc, QDomElement &parent_element) const +bool MovingAverageFilter::xmlSaveState(QDomDocument& doc, + QDomElement& parent_element) const { QDomElement widget_el = doc.createElement("options"); widget_el.setAttribute("value", ui->spinBoxSamples->value()); - widget_el.setAttribute("compensate_offset", ui->checkBoxTimeOffset->isChecked() ? "true" : "false"); - parent_element.appendChild( widget_el ); + widget_el.setAttribute("compensate_offset", + ui->checkBoxTimeOffset->isChecked() ? "true" : "false"); + parent_element.appendChild(widget_el); return true; } -bool MovingAverageFilter::xmlLoadState(const QDomElement &parent_element) +bool MovingAverageFilter::xmlLoadState(const QDomElement& parent_element) { QDomElement widget_el = parent_element.firstChildElement("options"); - ui->spinBoxSamples->setValue( widget_el.attribute("value").toInt() ); + ui->spinBoxSamples->setValue(widget_el.attribute("value").toInt()); bool checked = widget_el.attribute("compensate_offset") == "true"; - ui->checkBoxTimeOffset->setChecked( checked ); + ui->checkBoxTimeOffset->setChecked(checked); return true; } diff --git a/plotjuggler_app/transforms/moving_average_filter.h b/plotjuggler_app/transforms/moving_average_filter.h index 901ee0a23..f7f853d20 100644 --- a/plotjuggler_app/transforms/moving_average_filter.h +++ b/plotjuggler_app/transforms/moving_average_filter.h @@ -9,12 +9,12 @@ using namespace PJ; - -namespace Ui { +namespace Ui +{ class MovingAverageFilter; } -class MovingAverageFilter: public TransformFunction_SISO +class MovingAverageFilter : public TransformFunction_SISO { public: explicit MovingAverageFilter(); @@ -23,7 +23,10 @@ class MovingAverageFilter: public TransformFunction_SISO void reset() override; - const char* name() const override { return "Moving Average"; } + const char* name() const override + { + return "Moving Average"; + } QWidget* optionsWidget() override; @@ -32,12 +35,10 @@ class MovingAverageFilter: public TransformFunction_SISO bool xmlLoadState(const QDomElement& parent_element) override; private: - Ui::MovingAverageFilter *ui; - QWidget *_widget; + Ui::MovingAverageFilter* ui; + QWidget* _widget; std::vector _buffer; nonstd::ring_span_lite::ring_span _ring_view; - std::optional - calculateNextPoint(size_t index) override; + std::optional calculateNextPoint(size_t index) override; }; - diff --git a/plotjuggler_app/transforms/moving_rms.cpp b/plotjuggler_app/transforms/moving_rms.cpp index dd4945109..359664c7b 100644 --- a/plotjuggler_app/transforms/moving_rms.cpp +++ b/plotjuggler_app/transforms/moving_rms.cpp @@ -1,16 +1,16 @@ #include "moving_rms.h" #include "ui_moving_rms.h" -MovingRMS::MovingRMS() : - ui(new Ui::MovingRMS), - _widget(new QWidget()), - _buffer(1), - _ring_view( _buffer.begin(), _buffer.end() ) +MovingRMS::MovingRMS() + : ui(new Ui::MovingRMS) + , _widget(new QWidget()) + , _buffer(1) + , _ring_view(_buffer.begin(), _buffer.end()) { ui->setupUi(_widget); - connect(ui->spinBoxSamples, qOverload(&QSpinBox::valueChanged), - this, [=](int){ emit parametersChanged(); } ); + connect(ui->spinBoxSamples, qOverload(&QSpinBox::valueChanged), this, + [=](int) { emit parametersChanged(); }); } MovingRMS::~MovingRMS() @@ -25,55 +25,54 @@ void MovingRMS::reset() TransformFunction_SISO::reset(); } -QWidget *MovingRMS::optionsWidget() +QWidget* MovingRMS::optionsWidget() { return _widget; } -bool MovingRMS::xmlSaveState(QDomDocument &doc, QDomElement &parent_element) const +bool MovingRMS::xmlSaveState(QDomDocument& doc, QDomElement& parent_element) const { QDomElement widget_el = doc.createElement("options"); widget_el.setAttribute("value", ui->spinBoxSamples->value()); - parent_element.appendChild( widget_el ); + parent_element.appendChild(widget_el); return true; } -bool MovingRMS::xmlLoadState(const QDomElement &parent_element) +bool MovingRMS::xmlLoadState(const QDomElement& parent_element) { QDomElement widget_el = parent_element.firstChildElement("options"); - ui->spinBoxSamples->setValue( widget_el.attribute("value").toInt() ); + ui->spinBoxSamples->setValue(widget_el.attribute("value").toInt()); return true; } -std::optional -MovingRMS::calculateNextPoint(size_t index) +std::optional MovingRMS::calculateNextPoint(size_t index) { - size_t buffer_size = std::min( size_t(ui->spinBoxSamples->value()), - size_t(dataSource()->size()) ); - if( buffer_size != _buffer.size() ) { - _buffer.resize( buffer_size ); - _ring_view = nonstd::ring_span( - _buffer.begin(), _buffer.end()); + size_t buffer_size = + std::min(size_t(ui->spinBoxSamples->value()), size_t(dataSource()->size())); + if (buffer_size != _buffer.size()) + { + _buffer.resize(buffer_size); + _ring_view = nonstd::ring_span(_buffer.begin(), _buffer.end()); } const auto& p = dataSource()->at(index); _ring_view.push_back(p); - while( _ring_view.size() < buffer_size ) + while (_ring_view.size() < buffer_size) { _ring_view.push_back(p); } double total_sqr = 0; - for(size_t i=0; i < buffer_size; i++) + for (size_t i = 0; i < buffer_size; i++) { double val = _ring_view[i].y; - total_sqr += val*val; + total_sqr += val * val; } double time = p.x; - PJ::PlotData::Point out = {time, sqrt(total_sqr / _ring_view.size()) }; + PJ::PlotData::Point out = { time, sqrt(total_sqr / _ring_view.size()) }; return out; } diff --git a/plotjuggler_app/transforms/moving_rms.h b/plotjuggler_app/transforms/moving_rms.h index 45ba0e8ab..c28019bad 100644 --- a/plotjuggler_app/transforms/moving_rms.h +++ b/plotjuggler_app/transforms/moving_rms.h @@ -6,11 +6,12 @@ #include "PlotJuggler/transform_function.h" #include "PlotJuggler/ring_span.hpp" -namespace Ui { +namespace Ui +{ class MovingRMS; } -class MovingRMS: public PJ::TransformFunction_SISO +class MovingRMS : public PJ::TransformFunction_SISO { Q_OBJECT @@ -21,7 +22,10 @@ class MovingRMS: public PJ::TransformFunction_SISO void reset() override; - const char* name() const override { return "Moving Root Mean Squared"; } + const char* name() const override + { + return "Moving Root Mean Squared"; + } QWidget* optionsWidget() override; @@ -30,14 +34,13 @@ class MovingRMS: public PJ::TransformFunction_SISO bool xmlLoadState(const QDomElement& parent_element) override; private: - Ui::MovingRMS *ui; + Ui::MovingRMS* ui; - QWidget *_widget; + QWidget* _widget; std::vector _buffer; nonstd::ring_span_lite::ring_span _ring_view; - std::optional - calculateNextPoint(size_t index) override; + std::optional calculateNextPoint(size_t index) override; }; -#endif // MOVING_RMS_H +#endif // MOVING_RMS_H diff --git a/plotjuggler_app/transforms/outlier_removal.cpp b/plotjuggler_app/transforms/outlier_removal.cpp index 0383aaa36..37abbc7f4 100644 --- a/plotjuggler_app/transforms/outlier_removal.cpp +++ b/plotjuggler_app/transforms/outlier_removal.cpp @@ -1,16 +1,16 @@ #include "outlier_removal.h" #include "ui_outlier_removal.h" -OutlierRemovalFilter::OutlierRemovalFilter(): - ui(new Ui::OutlierRemovalFilter), - _widget(new QWidget()), - _buffer(4), - _ring_view( _buffer.begin(), _buffer.end() ) +OutlierRemovalFilter::OutlierRemovalFilter() + : ui(new Ui::OutlierRemovalFilter) + , _widget(new QWidget()) + , _buffer(4) + , _ring_view(_buffer.begin(), _buffer.end()) { ui->setupUi(_widget); - connect(ui->spinBoxFactor, qOverload(&QDoubleSpinBox::valueChanged), - this, [=](int){ emit parametersChanged(); } ); + connect(ui->spinBoxFactor, qOverload(&QDoubleSpinBox::valueChanged), this, + [=](int) { emit parametersChanged(); }); } OutlierRemovalFilter::~OutlierRemovalFilter() @@ -19,50 +19,49 @@ OutlierRemovalFilter::~OutlierRemovalFilter() delete _widget; } - -QWidget *OutlierRemovalFilter::optionsWidget() +QWidget* OutlierRemovalFilter::optionsWidget() { return _widget; } -bool OutlierRemovalFilter::xmlSaveState(QDomDocument &doc, QDomElement &parent_element) const +bool OutlierRemovalFilter::xmlSaveState(QDomDocument& doc, + QDomElement& parent_element) const { QDomElement widget_el = doc.createElement("options"); - widget_el.setAttribute("value", ui->spinBoxFactor->value() ); - parent_element.appendChild( widget_el ); + widget_el.setAttribute("value", ui->spinBoxFactor->value()); + parent_element.appendChild(widget_el); return true; } -bool OutlierRemovalFilter::xmlLoadState(const QDomElement &parent_element) +bool OutlierRemovalFilter::xmlLoadState(const QDomElement& parent_element) { QDomElement widget_el = parent_element.firstChildElement("options"); - ui->spinBoxFactor->setValue( widget_el.attribute("value", "100.0").toDouble() ); + ui->spinBoxFactor->setValue(widget_el.attribute("value", "100.0").toDouble()); return true; } -std::optional -OutlierRemovalFilter::calculateNextPoint(size_t index) +std::optional OutlierRemovalFilter::calculateNextPoint(size_t index) { const auto& p = dataSource()->at(index); _ring_view.push_back(p.y); - if( index < 3 ) + if (index < 3) { return p; } - double d1 = (_ring_view[1] - _ring_view[2]); - double d2 = (_ring_view[2] - _ring_view[3]); - if( d1*d2 < 0 ) // spike + double d1 = (_ring_view[1] - _ring_view[2]); + double d2 = (_ring_view[2] - _ring_view[3]); + if (d1 * d2 < 0) // spike { - double d0 = (_ring_view[0] - _ring_view[1]); + double d0 = (_ring_view[0] - _ring_view[1]); double thresh = ui->spinBoxFactor->value(); double jump = std::max(std::abs(d1), std::abs(d2)); - if( jump / std::abs(d0) > thresh ) + if (jump / std::abs(d0) > thresh) { return {}; } } - return dataSource()->at(index-1); + return dataSource()->at(index - 1); } diff --git a/plotjuggler_app/transforms/outlier_removal.h b/plotjuggler_app/transforms/outlier_removal.h index 972662c1b..f85d56116 100644 --- a/plotjuggler_app/transforms/outlier_removal.h +++ b/plotjuggler_app/transforms/outlier_removal.h @@ -8,19 +8,22 @@ using namespace PJ; - -namespace Ui { +namespace Ui +{ class OutlierRemovalFilter; } -class OutlierRemovalFilter: public TransformFunction_SISO +class OutlierRemovalFilter : public TransformFunction_SISO { public: explicit OutlierRemovalFilter(); ~OutlierRemovalFilter() override; - const char* name() const override { return "Outlier Removal"; } + const char* name() const override + { + return "Outlier Removal"; + } QWidget* optionsWidget() override; @@ -29,11 +32,10 @@ class OutlierRemovalFilter: public TransformFunction_SISO bool xmlLoadState(const QDomElement& parent_element) override; private: - Ui::OutlierRemovalFilter *ui; - QWidget *_widget; + Ui::OutlierRemovalFilter* ui; + QWidget* _widget; std::vector _buffer; nonstd::ring_span_lite::ring_span _ring_view; - std::optional - calculateNextPoint(size_t index) override; + std::optional calculateNextPoint(size_t index) override; }; diff --git a/plotjuggler_app/transforms/scale_transform.cpp b/plotjuggler_app/transforms/scale_transform.cpp index 8f46c08b4..a821f87e5 100644 --- a/plotjuggler_app/transforms/scale_transform.cpp +++ b/plotjuggler_app/transforms/scale_transform.cpp @@ -1,34 +1,30 @@ #include "scale_transform.h" #include "ui_scale_transform.h" -ScaleTransform::ScaleTransform() : - _widget(new QWidget()), - ui(new Ui::ScaleTransform) +ScaleTransform::ScaleTransform() : _widget(new QWidget()), ui(new Ui::ScaleTransform) { ui->setupUi(_widget); -// ui->lineEditValue->setValidator( new QDoubleValidator() ); + // ui->lineEditValue->setValidator( new QDoubleValidator() ); - connect(ui->buttonDegRad, &QPushButton::clicked, - this, [=](){ - const double deg_rad = 3.14159265359 / 180; - ui->lineEditValueScale->setText( QString::number(deg_rad, 'g', 5)); - emit parametersChanged(); - } ); + connect(ui->buttonDegRad, &QPushButton::clicked, this, [=]() { + const double deg_rad = 3.14159265359 / 180; + ui->lineEditValueScale->setText(QString::number(deg_rad, 'g', 5)); + emit parametersChanged(); + }); - connect(ui->buttonRadDeg, &QPushButton::clicked, - this, [=](){ - const double rad_deg = 180.0 / 3.14159265359; - ui->lineEditValueScale->setText( QString::number(rad_deg, 'g', 5)); - emit parametersChanged(); - } ); + connect(ui->buttonRadDeg, &QPushButton::clicked, this, [=]() { + const double rad_deg = 180.0 / 3.14159265359; + ui->lineEditValueScale->setText(QString::number(rad_deg, 'g', 5)); + emit parametersChanged(); + }); - connect(ui->lineEditTimeOffset, &QLineEdit::editingFinished, - this, [=](){ emit parametersChanged(); } ); - connect(ui->lineEditValueOffset, &QLineEdit::editingFinished, - this, [=](){ emit parametersChanged(); } ); - connect(ui->lineEditValueScale, &QLineEdit::editingFinished, - this, [=](){ emit parametersChanged(); } ); + connect(ui->lineEditTimeOffset, &QLineEdit::editingFinished, this, + [=]() { emit parametersChanged(); }); + connect(ui->lineEditValueOffset, &QLineEdit::editingFinished, this, + [=]() { emit parametersChanged(); }); + connect(ui->lineEditValueScale, &QLineEdit::editingFinished, this, + [=]() { emit parametersChanged(); }); } ScaleTransform::~ScaleTransform() @@ -37,32 +33,33 @@ ScaleTransform::~ScaleTransform() delete _widget; } -const char *ScaleTransform::name() const { +const char* ScaleTransform::name() const +{ return "Scale/Offset"; } -QWidget *ScaleTransform::optionsWidget() +QWidget* ScaleTransform::optionsWidget() { return _widget; } -bool ScaleTransform::xmlSaveState(QDomDocument &doc, QDomElement &parent_element) const +bool ScaleTransform::xmlSaveState(QDomDocument& doc, QDomElement& parent_element) const { QDomElement widget_el = doc.createElement("options"); - widget_el.setAttribute("time_offset", ui->lineEditTimeOffset->text() ); - widget_el.setAttribute("value_offset", ui->lineEditValueOffset->text() ); - widget_el.setAttribute("value_scale", ui->lineEditValueScale->text() ); - parent_element.appendChild( widget_el ); + widget_el.setAttribute("time_offset", ui->lineEditTimeOffset->text()); + widget_el.setAttribute("value_offset", ui->lineEditValueOffset->text()); + widget_el.setAttribute("value_scale", ui->lineEditValueScale->text()); + parent_element.appendChild(widget_el); return true; } -bool ScaleTransform::xmlLoadState(const QDomElement &parent_element) +bool ScaleTransform::xmlLoadState(const QDomElement& parent_element) { QDomElement widget_el = parent_element.firstChildElement("options"); - ui->lineEditTimeOffset->setText( widget_el.attribute("time_offset") ); - ui->lineEditValueOffset->setText( widget_el.attribute("value_offset") ); - ui->lineEditValueScale->setText( widget_el.attribute("value_scale") ); + ui->lineEditTimeOffset->setText(widget_el.attribute("time_offset")); + ui->lineEditValueOffset->setText(widget_el.attribute("value_offset")); + ui->lineEditValueScale->setText(widget_el.attribute("value_scale")); return true; } @@ -73,6 +70,6 @@ std::optional ScaleTransform::calculateNextPoint(size_t index) double scale = ui->lineEditValueScale->text().toDouble(); const auto& p = dataSource()->at(index); - PlotData::Point out = {p.x + off_x, scale * p.y + off_y}; + PlotData::Point out = { p.x + off_x, scale * p.y + off_y }; return out; } diff --git a/plotjuggler_app/transforms/scale_transform.h b/plotjuggler_app/transforms/scale_transform.h index 781459dfd..7fed34c3b 100644 --- a/plotjuggler_app/transforms/scale_transform.h +++ b/plotjuggler_app/transforms/scale_transform.h @@ -6,13 +6,13 @@ using namespace PJ; -namespace Ui { +namespace Ui +{ class ScaleTransform; } class ScaleTransform : public TransformFunction_SISO { - public: explicit ScaleTransform(); @@ -27,11 +27,10 @@ class ScaleTransform : public TransformFunction_SISO bool xmlLoadState(const QDomElement& parent_element) override; private: - QWidget *_widget; - Ui::ScaleTransform *ui; + QWidget* _widget; + Ui::ScaleTransform* ui; - std::optional - calculateNextPoint(size_t index) override; + std::optional calculateNextPoint(size_t index) override; }; -#endif // SCALE_TRANSFORM_H +#endif // SCALE_TRANSFORM_H diff --git a/plotjuggler_app/transforms/transform_selector.cpp b/plotjuggler_app/transforms/transform_selector.cpp index c58aa67fc..f9793a2ba 100644 --- a/plotjuggler_app/transforms/transform_selector.cpp +++ b/plotjuggler_app/transforms/transform_selector.cpp @@ -6,10 +6,15 @@ #include #include -TransformSelector::TransformSelector(QStringList builtin_transform, QStringList available_transforms, - QString* default_tansform, std::map* curve_transforms, +TransformSelector::TransformSelector(QStringList builtin_transform, + QStringList available_transforms, + QString* default_tansform, + std::map* curve_transforms, QWidget* parent) - : QDialog(parent), ui(new Ui::transform_selector), _curves_trans(curve_transforms), _default_trans(default_tansform) + : QDialog(parent) + , ui(new Ui::transform_selector) + , _curves_trans(curve_transforms) + , _default_trans(default_tansform) { ui->setupUi(this); diff --git a/plotjuggler_app/transforms/transform_selector.h b/plotjuggler_app/transforms/transform_selector.h index 097f8df2c..58c97fc05 100644 --- a/plotjuggler_app/transforms/transform_selector.h +++ b/plotjuggler_app/transforms/transform_selector.h @@ -13,8 +13,10 @@ class TransformSelector : public QDialog Q_OBJECT public: - TransformSelector(QStringList builtin_transform, QStringList available_transforms, QString* default_tansform, - std::map* curve_transforms, QWidget* parent = nullptr); + TransformSelector(QStringList builtin_transform, QStringList available_transforms, + QString* default_tansform, + std::map* curve_transforms, + QWidget* parent = nullptr); ~TransformSelector(); private slots: diff --git a/plotjuggler_app/utils.cpp b/plotjuggler_app/utils.cpp index cec55649b..d5d050973 100644 --- a/plotjuggler_app/utils.cpp +++ b/plotjuggler_app/utils.cpp @@ -1,16 +1,12 @@ #include "utils.h" #include - -MoveDataRet MoveData(PlotDataMapRef &source, - PlotDataMapRef &destination, - bool remove_older ) +MoveDataRet MoveData(PlotDataMapRef& source, PlotDataMapRef& destination, + bool remove_older) { - MoveDataRet ret; - auto moveDataImpl = [&](auto& source_series, auto& destination_series) - { + auto moveDataImpl = [&](auto& source_series, auto& destination_series) { for (auto& it : source_series) { const std::string& ID = it.first; @@ -23,16 +19,14 @@ MoveDataRet MoveData(PlotDataMapRef &source, ret.added_curves.push_back(ID); PlotGroup::Ptr group; - if( source_plot.group() ) + if (source_plot.group()) { - destination.getOrCreateGroup( source_plot.group()->name() ); + destination.getOrCreateGroup(source_plot.group()->name()); } - dest_plot_it = - destination_series - .emplace(std::piecewise_construct, - std::forward_as_tuple(ID), - std::forward_as_tuple(plot_name, group)) - .first; + dest_plot_it = destination_series + .emplace(std::piecewise_construct, std::forward_as_tuple(ID), + std::forward_as_tuple(plot_name, group)) + .first; ret.curves_updated = true; } @@ -40,44 +34,47 @@ MoveDataRet MoveData(PlotDataMapRef &source, PlotGroup::Ptr destination_group = destination_plot.group(); // copy plot attributes - for (const auto& [name, attr]: source_plot.attributes() ) + for (const auto& [name, attr] : source_plot.attributes()) { - if( destination_plot.attribute(name) != attr ){ - destination_plot.setAttribute( name, attr ); + if (destination_plot.attribute(name) != attr) + { + destination_plot.setAttribute(name, attr); ret.curves_updated = true; } } // Copy the group name and attributes - if( source_plot.group() ) + if (source_plot.group()) { - if( !destination_group || destination_group->name() != source_plot.group()->name() ) + if (!destination_group || + destination_group->name() != source_plot.group()->name()) { - destination_group = destination.getOrCreateGroup( source_plot.group()->name() ); - destination_plot.changeGroup( destination_group ); + destination_group = destination.getOrCreateGroup(source_plot.group()->name()); + destination_plot.changeGroup(destination_group); } - for (const auto& [name, attr]: source_plot.group()->attributes() ) + for (const auto& [name, attr] : source_plot.group()->attributes()) { - if( destination_group->attribute(name) != attr ) + if (destination_group->attribute(name) != attr) { - destination_group->setAttribute( name, attr ); + destination_group->setAttribute(name, attr); ret.curves_updated = true; } } } - if( remove_older ) { + if (remove_older) + { destination_plot.clear(); } - if( source_plot.size() > 0 ) + if (source_plot.size() > 0) { ret.data_pushed = true; } for (size_t i = 0; i < source_plot.size(); i++) { - destination_plot.pushBack( source_plot.at(i) ); + destination_plot.pushBack(source_plot.at(i)); } double max_range_x = source_plot.maximumRangeX(); @@ -88,9 +85,9 @@ MoveDataRet MoveData(PlotDataMapRef &source, }; //-------------------------------------------- - moveDataImpl( source.numeric, destination.numeric ); - moveDataImpl( source.strings, destination.strings ); - moveDataImpl( source.user_defined, destination.user_defined ); + moveDataImpl(source.numeric, destination.numeric); + moveDataImpl(source.strings, destination.strings); + moveDataImpl(source.user_defined, destination.user_defined); return ret; } diff --git a/plotjuggler_app/utils.h b/plotjuggler_app/utils.h index 67b7090ca..d3b40ed12 100644 --- a/plotjuggler_app/utils.h +++ b/plotjuggler_app/utils.h @@ -35,7 +35,6 @@ class MonitoredValue : public QObject double _value; }; - struct MoveDataRet { std::vector added_curves; @@ -43,10 +42,7 @@ struct MoveDataRet bool data_pushed = false; }; - -MoveDataRet MoveData(PlotDataMapRef& source, - PlotDataMapRef& destination, - bool remove_older); - +MoveDataRet MoveData(PlotDataMapRef& source, PlotDataMapRef& destination, + bool remove_older); #endif // UTILS_H diff --git a/plotjuggler_base/include/PlotJuggler/dataloader_base.h b/plotjuggler_base/include/PlotJuggler/dataloader_base.h index f8193d598..9e87e8748 100644 --- a/plotjuggler_base/include/PlotJuggler/dataloader_base.h +++ b/plotjuggler_base/include/PlotJuggler/dataloader_base.h @@ -8,8 +8,8 @@ #include "PlotJuggler/pj_plugin.h" #include "PlotJuggler/messageparser_base.h" -namespace PJ { - +namespace PJ +{ struct FileLoadInfo { /// name of the file to open @@ -38,12 +38,13 @@ class DataLoader : public PlotJugglerPlugin /// Provide a list of file extensions that this plugin can open virtual const std::vector& compatibleFileExtensions() const = 0; - virtual bool readDataFromFile(FileLoadInfo* fileload_info, PlotDataMapRef& destination) = 0; + virtual bool readDataFromFile(FileLoadInfo* fileload_info, + PlotDataMapRef& destination) = 0; }; using DataLoaderPtr = std::shared_ptr; -} +} // namespace PJ QT_BEGIN_NAMESPACE #define DataRead_iid "facontidavide.PlotJuggler3.DataLoader" diff --git a/plotjuggler_base/include/PlotJuggler/datastreamer_base.h b/plotjuggler_base/include/PlotJuggler/datastreamer_base.h index 49d9e4194..4898c04af 100644 --- a/plotjuggler_base/include/PlotJuggler/datastreamer_base.h +++ b/plotjuggler_base/include/PlotJuggler/datastreamer_base.h @@ -7,8 +7,8 @@ #include "PlotJuggler/pj_plugin.h" #include "PlotJuggler/messageparser_base.h" -namespace PJ { - +namespace PJ +{ /** * @brief The DataStreamer base classm used to read streaming of data. * @@ -20,7 +20,6 @@ class DataStreamer : public PlotJugglerPlugin { Q_OBJECT public: - DataStreamer() = default; virtual ~DataStreamer() = default; @@ -49,22 +48,25 @@ class DataStreamer : public PlotJugglerPlugin * @brief Gets the action to execute when clicking the 'notifications' button and * the current number of outstanding notifications. */ - virtual std::pair notificationAction() + virtual std::pair notificationAction() { - return {nullptr, 0}; - } + return { nullptr, 0 }; + } - std::mutex& mutex() { + std::mutex& mutex() + { return _mutex; } void setMaximumRangeX(double range); - PlotDataMapRef& dataMap() { + PlotDataMapRef& dataMap() + { return _data_map; } - const PlotDataMapRef& dataMap() const { + const PlotDataMapRef& dataMap() const + { return _data_map; } @@ -74,7 +76,7 @@ class DataStreamer : public PlotJugglerPlugin * * @param parsers */ - void setAvailableParsers(std::shared_ptr parsers_factory ); + void setAvailableParsers(std::shared_ptr parsers_factory); std::shared_ptr availableParsers(); @@ -107,7 +109,7 @@ class DataStreamer : public PlotJugglerPlugin using DataStreamerPtr = std::shared_ptr; -} +} // namespace PJ QT_BEGIN_NAMESPACE #define DataStream_iid "facontidavide.PlotJuggler3.DataStreamer" diff --git a/plotjuggler_base/include/PlotJuggler/messageparser_base.h b/plotjuggler_base/include/PlotJuggler/messageparser_base.h index 14965e8a4..b0a1b9b89 100644 --- a/plotjuggler_base/include/PlotJuggler/messageparser_base.h +++ b/plotjuggler_base/include/PlotJuggler/messageparser_base.h @@ -11,8 +11,8 @@ #include "PlotJuggler/plotdata.h" #include "PlotJuggler/pj_plugin.h" -namespace PJ { - +namespace PJ +{ /* * A messgaeParser is a clas that is able to convert a message received by * a DataStreamer plugin into data in PlotDataMapRef. @@ -27,23 +27,28 @@ namespace PJ { class MessageRef { public: - explicit MessageRef(uint8_t* first_ptr, size_t size) : - _first_ptr(first_ptr), _size(size) - { } + explicit MessageRef(uint8_t* first_ptr, size_t size) + : _first_ptr(first_ptr), _size(size) + { + } - explicit MessageRef(std::vector& vect) : - _first_ptr(vect.data()), _size(vect.size()) - { } + explicit MessageRef(std::vector& vect) + : _first_ptr(vect.data()), _size(vect.size()) + { + } - const uint8_t* data() const { + const uint8_t* data() const + { return _first_ptr; } - uint8_t* data() { + uint8_t* data() + { return _first_ptr; } - size_t size() const { + size_t size() const + { return _size; } @@ -53,10 +58,9 @@ class MessageRef }; /** - * @brief The MessageParser is the base class to create plugins that are able to parse one or - * multiple Message types. - * Each message type is uniquely identified by a MessageKey (128 bits, sufficiently large to - * hold a MD5Sum identifier). + * @brief The MessageParser is the base class to create plugins that are able to parse one + * or multiple Message types. Each message type is uniquely identified by a MessageKey + * (128 bits, sufficiently large to hold a MD5Sum identifier). * * You push one or more raw messages using the method pushMessageRef() * Once you have done, the result can be copied using plotData() @@ -64,26 +68,26 @@ class MessageRef class MessageParser { public: - MessageParser(const std::string& topic_name, - PlotDataMapRef& plot_data): _plot_data(plot_data), _topic_name(topic_name) - { } + MessageParser(const std::string& topic_name, PlotDataMapRef& plot_data) + : _plot_data(plot_data), _topic_name(topic_name) + { + } virtual ~MessageParser() = default; - virtual bool parseMessage(const MessageRef serialized_msg, - double& timestamp) = 0; -protected: + virtual bool parseMessage(const MessageRef serialized_msg, double& timestamp) = 0; +protected: PlotDataMapRef& _plot_data; std::string _topic_name; PlotData& getSeries(const std::string& key) { - return _plot_data.getOrCreateNumeric( key ); + return _plot_data.getOrCreateNumeric(key); } StringSeries& getStringSeries(const std::string& key) { - return _plot_data.getOrCreateStringSeries( key ); + return _plot_data.getOrCreateStringSeries(key); } }; @@ -93,15 +97,14 @@ using MessageParserPtr = std::shared_ptr; class MessageParserCreator : public PlotJugglerPlugin { public: - - virtual MessageParserPtr createInstance(const std::string& topic_name, PlotDataMapRef& data) = 0; + virtual MessageParserPtr createInstance(const std::string& topic_name, + PlotDataMapRef& data) = 0; }; //---------------------------------------------------------------- using MessageParserFactory = std::map>; -} // end namespace - +} // namespace PJ QT_BEGIN_NAMESPACE #define MessageParserCreator_iid "facontidavide.PlotJuggler3.MessageParserCreator" diff --git a/plotjuggler_base/include/PlotJuggler/pj_plugin.h b/plotjuggler_base/include/PlotJuggler/pj_plugin.h index 9bc402a5f..cfb9d9b7f 100644 --- a/plotjuggler_base/include/PlotJuggler/pj_plugin.h +++ b/plotjuggler_base/include/PlotJuggler/pj_plugin.h @@ -7,8 +7,8 @@ #include #include "PlotJuggler/plotdata.h" -namespace PJ { - +namespace PJ +{ /** * @brief The PlotJugglerPlugin is the base class of all the plugins. */ @@ -22,7 +22,8 @@ class PlotJugglerPlugin : public QObject /// Override this to return true, if you want this plugin to be loaded only when /// the command line option [-t] is used. - virtual bool isDebugPlugin() { + virtual bool isDebugPlugin() + { return false; } @@ -30,33 +31,38 @@ class PlotJugglerPlugin : public QObject * @brief optionsWidget pointer to a persistent widget used to * set the plugin options . */ - virtual QWidget* optionsWidget() { + virtual QWidget* optionsWidget() + { return nullptr; } /// Override this method to save the status of the plugin to XML - virtual bool xmlSaveState(QDomDocument& doc, QDomElement& parent_element) const { + virtual bool xmlSaveState(QDomDocument& doc, QDomElement& parent_element) const + { return false; } /// Override this method to load the status of the plugin from XML - virtual bool xmlLoadState(const QDomElement& parent_element) { + virtual bool xmlLoadState(const QDomElement& parent_element) + { return false; } - QDomElement xmlSaveState(QDomDocument& doc) const { + QDomElement xmlSaveState(QDomDocument& doc) const + { QDomElement plugin_elem = doc.createElement("plugin"); plugin_elem.setAttribute("ID", this->name()); xmlSaveState(doc, plugin_elem); return plugin_elem; } - virtual const std::vector& availableActions() { + virtual const std::vector& availableActions() + { static std::vector empty; return empty; } }; -} +} // namespace PJ #endif // PJ_PLUGIN_H diff --git a/plotjuggler_base/include/PlotJuggler/plotdata.h b/plotjuggler_base/include/PlotJuggler/plotdata.h index 1da763fc5..77b2eb640 100644 --- a/plotjuggler_base/include/PlotJuggler/plotdata.h +++ b/plotjuggler_base/include/PlotJuggler/plotdata.h @@ -5,8 +5,8 @@ #include "timeseries.h" #include "stringseries.h" -namespace PJ { - +namespace PJ +{ using PlotDataXY = PlotDataBase; using PlotData = TimeseriesBase; using PlotDataAny = TimeseriesBase; @@ -38,9 +38,7 @@ struct PlotDataMapRef */ std::unordered_map groups; - - PlotDataMap::iterator addNumeric(const std::string& name, - PlotGroup::Ptr group = {}); + PlotDataMap::iterator addNumeric(const std::string& name, PlotGroup::Ptr group = {}); AnySeriesMap::iterator addUserDefined(const std::string& name, PlotGroup::Ptr group = {}); @@ -48,62 +46,60 @@ struct PlotDataMapRef StringSeriesMap::iterator addStringSeries(const std::string& name, PlotGroup::Ptr group = {}); - PlotData& getOrCreateNumeric(const std::string& name, - PlotGroup::Ptr group = {}); + PlotData& getOrCreateNumeric(const std::string& name, PlotGroup::Ptr group = {}); StringSeries& getOrCreateStringSeries(const std::string& name, PlotGroup::Ptr group = {}); - PlotDataAny& getOrCreateUserDefined(const std::string& name, - PlotGroup::Ptr group = {}); + PlotDataAny& getOrCreateUserDefined(const std::string& name, PlotGroup::Ptr group = {}); PlotGroup::Ptr getOrCreateGroup(const std::string& name); void clear(); - void setMaximumRangeX( double range ); - - bool erase(const std::string& name ); + void setMaximumRangeX(double range); + bool erase(const std::string& name); }; template inline void AddPrefixToPlotData(const std::string& prefix, std::unordered_map& data) { - if (prefix.empty()){ + if (prefix.empty()) + { return; } std::vector temp_key; - temp_key.reserve( data.size() ); + temp_key.reserve(data.size()); std::vector temp_value; - temp_value.reserve( data.size() ); + temp_value.reserve(data.size()); for (auto& it : data) { std::string key; key.reserve(prefix.size() + 2 + it.first.size()); - key = (it.first.front() == '/') ? (prefix + it.first) : (prefix + "/" + it.first); + key = (it.first.front() == '/') ? (prefix + it.first) : (prefix + "/" + it.first); - temp_key.emplace_back( key ); - temp_value.emplace_back( std::move(it.second) ); + temp_key.emplace_back(key); + temp_value.emplace_back(std::move(it.second)); } data.clear(); - for (size_t i=0; i < temp_key.size(); i++) + for (size_t i = 0; i < temp_key.size(); i++) { const std::string& key = temp_key[i]; - auto it = data.emplace(std::piecewise_construct, - std::forward_as_tuple(key), - std::forward_as_tuple(key, PlotGroup::Ptr()) ).first; + auto it = data.emplace(std::piecewise_construct, std::forward_as_tuple(key), + std::forward_as_tuple(key, PlotGroup::Ptr())) + .first; it->second = std::move(temp_value[i]); } } -} +} // namespace PJ -#endif // PJ_PLOTDATA_H +#endif // PJ_PLOTDATA_H diff --git a/plotjuggler_base/include/PlotJuggler/plotdatabase.h b/plotjuggler_base/include/PlotJuggler/plotdatabase.h index fe204251a..3a86c8369 100644 --- a/plotjuggler_base/include/PlotJuggler/plotdatabase.h +++ b/plotjuggler_base/include/PlotJuggler/plotdatabase.h @@ -18,19 +18,20 @@ #include #include -namespace PJ { - +namespace PJ +{ struct Range { - double min; - double max; + double min; + double max; }; typedef std::optional RangeOpt; using Attributes = std::map; // Attributes supported by the GUI. -enum PlotAttribute { +enum PlotAttribute +{ // color to be displayed on the curve list. Type: QColor TEXT_COLOR, // font style to be displayed on the curve list. @@ -44,12 +45,18 @@ enum PlotAttribute { DISABLE_LINKED_ZOOM }; -inline const char* ToStr(const PlotAttribute& attr){ - switch(attr) { - case TEXT_COLOR: return "TextColor"; - case ITALIC_FONTS: return "Italic"; - case TOOL_TIP: return "ToolTip"; - case DISABLE_LINKED_ZOOM: return "DisableLinkedZoom"; +inline const char* ToStr(const PlotAttribute& attr) +{ + switch (attr) + { + case TEXT_COLOR: + return "TextColor"; + case ITALIC_FONTS: + return "Italic"; + case TOOL_TIP: + return "ToolTip"; + case DISABLE_LINKED_ZOOM: + return "DisableLinkedZoom"; } return ""; } @@ -62,392 +69,401 @@ inline const char* ToStr(const PlotAttribute& attr){ class PlotGroup { public: - using Ptr = std::shared_ptr; - PlotGroup(const std::string& name): - _name( name ) - { } + PlotGroup(const std::string& name) : _name(name) + { + } - const std::string& name() const { + const std::string& name() const + { return _name; } void setAttribute(const std::string& name, const QVariant& value) { - _attributes[ name ] = value; + _attributes[name] = value; } - const Attributes& attributes() const{ + const Attributes& attributes() const + { return _attributes; } - Attributes& attributes() { + Attributes& attributes() + { return _attributes; } QVariant attribute(const std::string& name) const { - auto it = _attributes.find( name ); + auto it = _attributes.find(name); - if( it == _attributes.end() ) { - return {}; - } - else { - return it->second; - } + if (it == _attributes.end()) + { + return {}; + } + else + { + return it->second; + } } void setAttribute(const PlotAttribute& id, const QVariant& value) { - _attributes[ ToStr(id) ] = value; + _attributes[ToStr(id)] = value; } QVariant attribute(const PlotAttribute& id) const { - return attribute( ToStr(id) ); + return attribute(ToStr(id)); } - private: const std::string _name; Attributes _attributes; }; // A Generic series of points -template +template class PlotDataBase { - public: - - class Point - { - public: - TypeX x; - Value y; - Point(TypeX _x, Value _y) : x(_x), y(_y) - { } - Point() = default; - }; - - enum + class Point + { + public: + TypeX x; + Value y; + Point(TypeX _x, Value _y) : x(_x), y(_y) { - MAX_CAPACITY = 1024 * 1024, - ASYNC_BUFFER_CAPACITY = 1024 - }; + } + Point() = default; + }; - typedef typename std::deque::iterator Iterator; - typedef typename std::deque::const_iterator ConstIterator; + enum + { + MAX_CAPACITY = 1024 * 1024, + ASYNC_BUFFER_CAPACITY = 1024 + }; - PlotDataBase(const std::string& name, PlotGroup::Ptr group ): - _name(name), - _range_x_dirty(true), - _range_y_dirty(true), - _group(group) - {} + typedef typename std::deque::iterator Iterator; + typedef typename std::deque::const_iterator ConstIterator; - PlotDataBase(const PlotDataBase& other) = delete; - PlotDataBase(PlotDataBase&& other) = default; + PlotDataBase(const std::string& name, PlotGroup::Ptr group) + : _name(name), _range_x_dirty(true), _range_y_dirty(true), _group(group) + { + } - PlotDataBase& operator=(const PlotDataBase& other) = delete; - PlotDataBase& operator=(PlotDataBase&& other) = default; + PlotDataBase(const PlotDataBase& other) = delete; + PlotDataBase(PlotDataBase&& other) = default; - virtual ~PlotDataBase() = default; + PlotDataBase& operator=(const PlotDataBase& other) = delete; + PlotDataBase& operator=(PlotDataBase&& other) = default; - const std::string& plotName() const - { - return _name; - } + virtual ~PlotDataBase() = default; - const PlotGroup::Ptr& group() const - { - return _group; - } + const std::string& plotName() const + { + return _name; + } - void changeGroup(PlotGroup::Ptr group) - { - _group = group; - } + const PlotGroup::Ptr& group() const + { + return _group; + } - virtual size_t size() const - { - return _points.size(); - } + void changeGroup(PlotGroup::Ptr group) + { + _group = group; + } - const Point& at(size_t index) const - { - return _points[index]; - } + virtual size_t size() const + { + return _points.size(); + } - Point& at(size_t index) - { - return _points[index]; - } + const Point& at(size_t index) const + { + return _points[index]; + } - const Point& operator[](size_t index) const - { - return at(index); - } + Point& at(size_t index) + { + return _points[index]; + } - Point& operator[](size_t index) - { - return at(index); - } + const Point& operator[](size_t index) const + { + return at(index); + } - virtual void clear() - { - _points.clear(); - _range_x_dirty = true; - _range_y_dirty = true; - } + Point& operator[](size_t index) + { + return at(index); + } - void setAttribute(const std::string& name, const QVariant& value) - { - _attributes[ name ] = value; - } + virtual void clear() + { + _points.clear(); + _range_x_dirty = true; + _range_y_dirty = true; + } - const Attributes& attributes() const{ - return _attributes; - } + void setAttribute(const std::string& name, const QVariant& value) + { + _attributes[name] = value; + } - Attributes& attributes() { - return _attributes; - } + const Attributes& attributes() const + { + return _attributes; + } - QVariant attribute(const std::string& name) const - { - auto it = _attributes.find( name ); + Attributes& attributes() + { + return _attributes; + } - if( it == _attributes.end() ) { - return {}; - } - else { - return it->second; - } - } + QVariant attribute(const std::string& name) const + { + auto it = _attributes.find(name); - void setAttribute(const PlotAttribute& id, const QVariant& value) + if (it == _attributes.end()) { - _attributes[ ToStr(id) ] = value; + return {}; } - - QVariant attribute(const PlotAttribute& id) const + else { - return attribute( ToStr(id) ); + return it->second; } + } - const Point& front() const - { - return _points.front(); - } + void setAttribute(const PlotAttribute& id, const QVariant& value) + { + _attributes[ToStr(id)] = value; + } - const Point& back() const + QVariant attribute(const PlotAttribute& id) const + { + return attribute(ToStr(id)); + } + + const Point& front() const + { + return _points.front(); + } + + const Point& back() const + { + return _points.back(); + } + + ConstIterator begin() const + { + return _points.begin(); + } + + ConstIterator end() const + { + return _points.end(); + } + + Iterator begin() + { + return _points.begin(); + } + + Iterator end() + { + return _points.end(); + } + + // template specialization for types that support compare operator + virtual RangeOpt rangeX() const + { + if constexpr (std::is_arithmetic_v) { - return _points.back(); + if (_points.empty()) + { + return std::nullopt; + } + if (_range_x_dirty) + { + _range_x.min = front().x; + _range_x.max = _range_x.min; + for (const auto& p : _points) + { + _range_x.min = std::min(_range_x.min, p.x); + _range_x.max = std::max(_range_x.max, p.x); + } + _range_x_dirty = false; + } + return _range_x; } + return std::nullopt; + } - ConstIterator begin() const + // template specialization for types that support compare operator + virtual RangeOpt rangeY() const + { + if constexpr (std::is_arithmetic_v) { - return _points.begin(); + if (_points.empty()) + { + return std::nullopt; + } + if (_range_y_dirty) + { + _range_y.min = front().y; + _range_y.max = _range_y.min; + for (const auto& p : _points) + { + _range_y.min = std::min(_range_y.min, p.y); + _range_y.max = std::max(_range_y.max, p.y); + } + _range_y_dirty = false; + } + return _range_y; } + return std::nullopt; + } - ConstIterator end() const + virtual void pushBack(const Point& p) + { + auto temp = p; + pushBack(std::move(temp)); + } + + virtual void pushBack(Point&& p) + { + if constexpr (std::is_arithmetic_v) { - return _points.end(); + if (std::isinf(p.x) || std::isnan(p.x)) + { + return; // skip + } + pushUpdateRangeX(p); } - - Iterator begin() + if constexpr (std::is_arithmetic_v) { - return _points.begin(); + if (std::isinf(p.y) || std::isnan(p.y)) + { + return; // skip + } + pushUpdateRangeY(p); } - Iterator end() + _points.emplace_back(p); + } + + virtual void insert(Iterator it, Point&& p) + { + if constexpr (std::is_arithmetic_v) { - return _points.end(); + if (std::isinf(p.x) || std::isnan(p.x)) + { + return; // skip + } + pushUpdateRangeX(p); } - - // template specialization for types that support compare operator - virtual RangeOpt rangeX() const + if constexpr (std::is_arithmetic_v) { - if constexpr ( std::is_arithmetic_v ) - { - if( _points.empty() ) - { - return std::nullopt; - } - if( _range_x_dirty ) - { - _range_x.min = front().x; - _range_x.max = _range_x.min; - for(const auto& p: _points) - { - _range_x.min = std::min(_range_x.min, p.x); - _range_x.max = std::max(_range_x.max, p.x); - } - _range_x_dirty = false; - } - return _range_x; - } - return std::nullopt; + if (std::isinf(p.y) || std::isnan(p.y)) + { + return; // skip + } + pushUpdateRangeY(p); } - // template specialization for types that support compare operator - virtual RangeOpt rangeY() const + _points.insert(it, p); + } + + virtual void popFront() + { + const auto& p = _points.front(); + + if constexpr (std::is_arithmetic_v) { - if constexpr ( std::is_arithmetic_v ) - { - if( _points.empty() ) - { - return std::nullopt; - } - if( _range_y_dirty ) - { - _range_y.min = front().y; - _range_y.max = _range_y.min; - for(const auto& p: _points) - { - _range_y.min = std::min(_range_y.min, p.y); - _range_y.max = std::max(_range_y.max, p.y); - } - _range_y_dirty = false; - } - return _range_y; - } - return std::nullopt; + if (!_range_x_dirty && (p.x == _range_x.max || p.x == _range_x.min)) + { + _range_x_dirty = true; + } } - virtual void pushBack(const Point &p) + if constexpr (std::is_arithmetic_v) { - auto temp = p; - pushBack(std::move(temp)); + if (!_range_y_dirty && (p.y == _range_y.max || p.y == _range_y.min)) + { + _range_y_dirty = true; + } } + _points.pop_front(); + } - virtual void pushBack(Point&& p) - { - if constexpr ( std::is_arithmetic_v ) - { - if (std::isinf(p.x) || std::isnan(p.x)) - { - return; // skip - } - pushUpdateRangeX(p); - } - if constexpr ( std::is_arithmetic_v ) - { - if (std::isinf(p.y) || std::isnan(p.y)) - { - return; // skip - } - pushUpdateRangeY(p); - } +protected: + std::string _name; + Attributes _attributes; + std::deque _points; - _points.emplace_back(p); - } + mutable Range _range_x; + mutable Range _range_y; + mutable bool _range_x_dirty; + mutable bool _range_y_dirty; + mutable std::shared_ptr _group; - virtual void insert(Iterator it, Point&& p) + // template specialization for types that support compare operator + virtual void pushUpdateRangeX(const Point& p) + { + if constexpr (std::is_arithmetic_v) { - if constexpr ( std::is_arithmetic_v ) - { - if (std::isinf(p.x) || std::isnan(p.x)) - { - return; // skip - } - pushUpdateRangeX(p); - } - if constexpr ( std::is_arithmetic_v ) + if (_points.empty()) + { + _range_x_dirty = false; + _range_x.min = p.x; + _range_x.max = p.x; + } + if (!_range_x_dirty) + { + if (p.x > _range_x.max) { - if (std::isinf(p.y) || std::isnan(p.y)) - { - return; // skip - } - pushUpdateRangeY(p); + _range_x.max = p.x; } - - _points.insert(it, p); - } - - virtual void popFront() - { - const auto& p = _points.front(); - - if constexpr ( std::is_arithmetic_v ) + else if (p.x < _range_x.min) { - if( !_range_x_dirty && (p.x == _range_x.max || p.x == _range_x.min) ) - { - _range_x_dirty = true; - } + _range_x.min = p.x; } - - if constexpr ( std::is_arithmetic_v ) + else { - if( !_range_y_dirty && (p.y == _range_y.max || p.y == _range_y.min) ) - { - _range_y_dirty = true; - } + _range_x_dirty = true; } - _points.pop_front(); + } } + } -protected: - std::string _name; - Attributes _attributes; - std::deque _points; - - mutable Range _range_x; - mutable Range _range_y; - mutable bool _range_x_dirty; - mutable bool _range_y_dirty; - mutable std::shared_ptr _group; - - // template specialization for types that support compare operator - virtual void pushUpdateRangeX(const Point& p) + // template specialization for types that support compare operator + virtual void pushUpdateRangeY(const Point& p) + { + if constexpr (std::is_arithmetic_v) { - if constexpr ( std::is_arithmetic_v ) + if (!_range_y_dirty) + { + if (p.y > _range_y.max) { - if( _points.empty() ) - { - _range_x_dirty = false; - _range_x.min = p.x; - _range_x.max = p.x; - } - if( !_range_x_dirty ) - { - if( p.x > _range_x.max ){ - _range_x.max = p.x; - } - else if( p.x < _range_x.min ){ - _range_x.min = p.x; - } - else{ - _range_x_dirty = true; - } - } + _range_y.max = p.y; } - } - - // template specialization for types that support compare operator - virtual void pushUpdateRangeY(const Point& p) - { - if constexpr ( std::is_arithmetic_v ) + else if (p.y < _range_y.min) { - if( !_range_y_dirty ) - { - if( p.y > _range_y.max ){ - _range_y.max = p.y; - } - else if( p.y < _range_y.min ){ - _range_y.min = p.y; - } - else{ - _range_y_dirty = true; - } - } + _range_y.min = p.y; } + else + { + _range_y_dirty = true; + } + } } + } }; - -} // end namespace +} // namespace PJ #endif diff --git a/plotjuggler_base/include/PlotJuggler/plotwidget_base.h b/plotjuggler_base/include/PlotJuggler/plotwidget_base.h index e07a8f3ce..aa01eb0cd 100644 --- a/plotjuggler_base/include/PlotJuggler/plotwidget_base.h +++ b/plotjuggler_base/include/PlotJuggler/plotwidget_base.h @@ -16,14 +16,13 @@ class PlotLegend; namespace PJ { - -class PlotWidgetBase: public QObject +class PlotWidgetBase : public QObject { Q_OBJECT public: - - enum CurveStyle { + enum CurveStyle + { LINES, DOTS, LINES_AND_DOTS, @@ -41,13 +40,12 @@ class PlotWidgetBase: public QObject ~PlotWidgetBase(); - virtual CurveInfo* addCurve(const std::string& name, - PlotData &src_data, + virtual CurveInfo* addCurve(const std::string& name, PlotData& src_data, QColor color = Qt::transparent); virtual void removeCurve(const QString& title); - const std::list &curveList() const; + const std::list& curveList() const; bool isEmpty() const; @@ -55,11 +53,10 @@ class PlotWidgetBase: public QObject std::map getCurveColors() const; - CurveInfo* curveFromTitle(const QString &title); + CurveInfo* curveFromTitle(const QString& title); - virtual QwtSeriesWrapper* createTimeSeries( - const QString& transform_ID, - const PlotData* data); + virtual QwtSeriesWrapper* createTimeSeries(const QString& transform_ID, + const PlotData* data); virtual void resetZoom(); @@ -116,16 +113,15 @@ public slots: void legendSizeChanged(int new_size); protected: - class QwtPlotPimpl; QwtPlotPimpl* p = nullptr; - static void setStyle( QwtPlotCurve* curve, CurveStyle style ); + static void setStyle(QwtPlotCurve* curve, CurveStyle style); QwtPlot* qwtPlot(); const QwtPlot* qwtPlot() const; - std::list &curveList(); + std::list& curveList(); PlotLegend* legend(); PlotZoomer* zoomer(); @@ -143,8 +139,6 @@ public slots: bool _keep_aspect_ratio; }; -} - - +} // namespace PJ -#endif // PLOTWIDGET_PROXY_H +#endif // PLOTWIDGET_PROXY_H diff --git a/plotjuggler_base/include/PlotJuggler/statepublisher_base.h b/plotjuggler_base/include/PlotJuggler/statepublisher_base.h index f716089fd..b75893196 100644 --- a/plotjuggler_base/include/PlotJuggler/statepublisher_base.h +++ b/plotjuggler_base/include/PlotJuggler/statepublisher_base.h @@ -9,15 +9,13 @@ #include "PlotJuggler/plotdata.h" #include "PlotJuggler/pj_plugin.h" -namespace PJ { - +namespace PJ +{ class StatePublisher : public PlotJugglerPlugin { - Q_OBJECT public: - /// True if started virtual bool enabled() const = 0; @@ -30,7 +28,8 @@ class StatePublisher : public PlotJugglerPlugin virtual ~StatePublisher() = default; - void setDataMap(const PlotDataMapRef* datamap) { + void setDataMap(const PlotDataMapRef* datamap) + { _datamap = datamap; } @@ -49,7 +48,7 @@ public slots: using StatePublisherPtr = std::shared_ptr; -} +} // namespace PJ QT_BEGIN_NAMESPACE #define StatePublisher_iid "facontidavide.PlotJuggler3.StatePublisher" diff --git a/plotjuggler_base/include/PlotJuggler/string_ref_sso.h b/plotjuggler_base/include/PlotJuggler/string_ref_sso.h index 1a940b5f8..50ecae640 100644 --- a/plotjuggler_base/include/PlotJuggler/string_ref_sso.h +++ b/plotjuggler_base/include/PlotJuggler/string_ref_sso.h @@ -6,7 +6,6 @@ namespace PJ { - /** * @brief Super simple, unmutable, string_view with * small string optimization. @@ -16,8 +15,7 @@ namespace PJ class StringRef { private: - - static const uint64_t TYPE_BIT = uint64_t(1) << (sizeof(size_t)*8 -1 ); + static const uint64_t TYPE_BIT = uint64_t(1) << (sizeof(size_t) * 8 - 1); struct noSSO { @@ -32,42 +30,42 @@ class StringRef char data[sizeof(noSSO)]; }; - union { + union + { noSSO no_sso; SSO sso; } _storage; public: - - bool isSSO() const { return !(_storage.no_sso.size & TYPE_BIT); } - StringRef() - : StringRef( nullptr, 0 ) - {} + StringRef() : StringRef(nullptr, 0) + { + } - StringRef(const std::string& str) - : StringRef( str.data(), str.size() ) - {} + StringRef(const std::string& str) : StringRef(str.data(), str.size()) + { + } - StringRef(const char* str) - : StringRef( str, strlen(str) ) - {} + StringRef(const char* str) : StringRef(str, strlen(str)) + { + } explicit StringRef(const char* data_ptr, size_t length) { _storage.no_sso.data = nullptr; _storage.no_sso.size = 0; - if( length <= SSO_SIZE ) + if (length <= SSO_SIZE) { - memcpy( _storage.sso.data, data_ptr, length ); + memcpy(_storage.sso.data, data_ptr, length); _storage.sso.data[SSO_SIZE] = SSO_SIZE - length; } - else{ + else + { _storage.no_sso.data = data_ptr; _storage.no_sso.size = length; _storage.no_sso.size |= TYPE_BIT; @@ -76,17 +74,16 @@ class StringRef const char* data() const { - return isSSO() ? _storage.sso.data : - _storage.no_sso.data; + return isSSO() ? _storage.sso.data : _storage.no_sso.data; } size_t size() const { return isSSO() ? (SSO_SIZE - _storage.sso.data[SSO_SIZE]) : - _storage.no_sso.size & ~TYPE_BIT; + _storage.no_sso.size & ~TYPE_BIT; } }; -} +} // namespace PJ -#endif // STRING_REF_SSO_H +#endif // STRING_REF_SSO_H diff --git a/plotjuggler_base/include/PlotJuggler/stringseries.h b/plotjuggler_base/include/PlotJuggler/stringseries.h index b98cd403c..d2674a84c 100644 --- a/plotjuggler_base/include/PlotJuggler/stringseries.h +++ b/plotjuggler_base/include/PlotJuggler/stringseries.h @@ -6,68 +6,69 @@ #include #include -namespace PJ { - -class StringSeries: public TimeseriesBase +namespace PJ +{ +class StringSeries : public TimeseriesBase { public: - using TimeseriesBase::_points; + using TimeseriesBase::_points; + + StringSeries(const std::string& name, PlotGroup::Ptr group) + : TimeseriesBase(name, group) + { + } + + StringSeries(const StringSeries& other) = delete; + StringSeries(StringSeries&& other) = default; - StringSeries(const std::string& name, PlotGroup::Ptr group): - TimeseriesBase(name, group) - { } + StringSeries& operator=(const StringSeries& other) = delete; + StringSeries& operator=(StringSeries&& other) = default; - StringSeries(const StringSeries& other) = delete; - StringSeries(StringSeries&& other) = default; + virtual void clear() override + { + _storage.clear(); + TimeseriesBase::clear(); + } - StringSeries& operator=(const StringSeries& other) = delete; - StringSeries& operator=(StringSeries&& other) = default; + void pushBack(const Point& p) override + { + auto temp = p; + pushBack(std::move(temp)); + } - virtual void clear() override + virtual void pushBack(Point&& p) override + { + const auto& str = p.y; + // do not add empty strings + if (str.data() == nullptr || str.size() == 0) { - _storage.clear(); - TimeseriesBase::clear(); + return; } - - void pushBack(const Point &p) override + if (str.isSSO()) { - auto temp = p; - pushBack(std::move(temp)); + // the object stroed the string already, just push it + TimeseriesBase::pushBack(std::move(p)); } - - virtual void pushBack(Point&& p) override + else { - const auto& str = p.y; - // do not add empty strings - if ( str.data() == nullptr || str.size() == 0) - { - return; - } - if( str.isSSO() ) - { - // the object stroed the string already, just push it - TimeseriesBase::pushBack( std::move(p) ); - } - else - { - // save a copy of the string in the flywheel structure _storage - // create a reference to that cached value. - _tmp_str.assign( str.data(), str.size() ); + // save a copy of the string in the flywheel structure _storage + // create a reference to that cached value. + _tmp_str.assign(str.data(), str.size()); - auto it = _storage.find( _tmp_str ); - if( it == _storage.end() ) { - it = _storage.insert( _tmp_str ).first; - } - TimeseriesBase::pushBack( { p.x, StringRef( *it ) } ); - } + auto it = _storage.find(_tmp_str); + if (it == _storage.end()) + { + it = _storage.insert(_tmp_str).first; + } + TimeseriesBase::pushBack({ p.x, StringRef(*it) }); } + } private: - std::string _tmp_str; - std::unordered_set _storage; + std::string _tmp_str; + std::unordered_set _storage; }; - -} // end namespace +} // namespace PJ #endif diff --git a/plotjuggler_base/include/PlotJuggler/svg_util.h b/plotjuggler_base/include/PlotJuggler/svg_util.h index 197642fd2..68750d362 100644 --- a/plotjuggler_base/include/PlotJuggler/svg_util.h +++ b/plotjuggler_base/include/PlotJuggler/svg_util.h @@ -2,7 +2,7 @@ #define PJ_SVG_UTIL_H #ifdef QT_NO_SVGRENDERER - #error "QT_NO_SVGRENDERER defined" +#error "QT_NO_SVGRENDERER defined" #endif #include @@ -24,19 +24,20 @@ inline QPixmap LoadSvg(QString filename, QString style_name = "light") auto svg_data = file.readAll(); file.close(); - if( style_name.contains("light") ) + if (style_name.contains("light")) { svg_data.replace("#000000", "#111111"); svg_data.replace("#ffffff", "#dddddd"); } - else{ + else + { svg_data.replace("#000000", "#dddddd"); svg_data.replace("#ffffff", "#111111"); } QByteArray content(svg_data); - QSvgRenderer rr( content ); + QSvgRenderer rr(content); QImage image(64, 64, QImage::Format_ARGB32); QPainter painter(&image); image.fill(Qt::transparent); @@ -45,5 +46,4 @@ inline QPixmap LoadSvg(QString filename, QString style_name = "light") return QPixmap::fromImage(image); } - -#endif // PJ_SVG_UTIL_H +#endif // PJ_SVG_UTIL_H diff --git a/plotjuggler_base/include/PlotJuggler/timeseries.h b/plotjuggler_base/include/PlotJuggler/timeseries.h index 98bba8729..dbe51577e 100644 --- a/plotjuggler_base/include/PlotJuggler/timeseries.h +++ b/plotjuggler_base/include/PlotJuggler/timeseries.h @@ -4,84 +4,90 @@ #include "plotdatabase.h" #include -namespace PJ { - +namespace PJ +{ template -class TimeseriesBase: public PlotDataBase +class TimeseriesBase : public PlotDataBase { protected: - double _max_range_x; - using PlotDataBase::_points; + double _max_range_x; + using PlotDataBase::_points; public: - using Point = typename PlotDataBase::Point; + using Point = typename PlotDataBase::Point; - TimeseriesBase(const std::string& name, PlotGroup::Ptr group): - PlotDataBase(name, group), - _max_range_x( std::numeric_limits::max() ) - { } + TimeseriesBase(const std::string& name, PlotGroup::Ptr group) + : PlotDataBase(name, group) + , _max_range_x(std::numeric_limits::max()) + { + } - TimeseriesBase(const TimeseriesBase& other) = delete; - TimeseriesBase(TimeseriesBase&& other) = default; + TimeseriesBase(const TimeseriesBase& other) = delete; + TimeseriesBase(TimeseriesBase&& other) = default; - TimeseriesBase& operator=(const TimeseriesBase& other) = delete; - TimeseriesBase& operator=(TimeseriesBase&& other) = default; + TimeseriesBase& operator=(const TimeseriesBase& other) = delete; + TimeseriesBase& operator=(TimeseriesBase&& other) = default; - void clone(const TimeseriesBase& other) - { - _max_range_x = other._max_range_x; - _points = other._points; - } + void clone(const TimeseriesBase& other) + { + _max_range_x = other._max_range_x; + _points = other._points; + } - void setMaximumRangeX(double max_range) - { - _max_range_x = max_range; - trimRange(); - } + void setMaximumRangeX(double max_range) + { + _max_range_x = max_range; + trimRange(); + } - double maximumRangeX() const - { - return _max_range_x; - } + double maximumRangeX() const + { + return _max_range_x; + } - int getIndexFromX(double x) const; + int getIndexFromX(double x) const; - std::optional getYfromX(double x) const - { - int index = getIndexFromX(x); - return ( index < 0 ) ? std::nullopt : std::optional( _points[index].y ); - } + std::optional getYfromX(double x) const + { + int index = getIndexFromX(x); + return (index < 0) ? std::nullopt : std::optional(_points[index].y); + } - void pushBack(const Point &p) override + void pushBack(const Point& p) override + { + auto temp = p; + pushBack(std::move(temp)); + } + + void pushBack(Point&& p) override + { + bool need_sorting = (!_points.empty() && p.x < this->back().x); + + if (need_sorting) { - auto temp = p; - pushBack(std::move(temp)); + auto it = std::upper_bound(_points.begin(), _points.end(), p, TimeCompare); + PlotDataBase::insert(it, std::move(p)); } - - void pushBack(Point&& p) override + else { - bool need_sorting = ( !_points.empty() && p.x < this->back().x ); - - if( need_sorting ) { - auto it = std::upper_bound(_points.begin(), _points.end(), p, TimeCompare ); - PlotDataBase::insert( it, std::move(p) ); - } - else{ - PlotDataBase::pushBack( std::move(p) ); - } - trimRange(); + PlotDataBase::pushBack(std::move(p)); } + trimRange(); + } private: - void trimRange() + void trimRange() + { + while (_points.size() > 2 && (_points.back().x - _points.front().x) > _max_range_x) { - while (_points.size() > 2 && (_points.back().x - _points.front().x) > _max_range_x) - { - this->popFront(); - } + this->popFront(); } + } - static bool TimeCompare(const Point& a, const Point& b) { return a.x < b.x; } + static bool TimeCompare(const Point& a, const Point& b) + { + return a.x < b.x; + } }; //-------------------- @@ -93,7 +99,8 @@ inline int TimeseriesBase::getIndexFromX(double x) const { return -1; } - auto lower = std::lower_bound(_points.begin(), _points.end(), Point(x, {}), TimeCompare ); + auto lower = + std::lower_bound(_points.begin(), _points.end(), Point(x, {}), TimeCompare); auto index = std::distance(_points.begin(), lower); if (index >= _points.size()) @@ -105,13 +112,13 @@ inline int TimeseriesBase::getIndexFromX(double x) const return 0; } - if (index > 0 && (abs(_points[index - 1].x - x) < abs(_points[index].x - x) ) ) + if (index > 0 && (abs(_points[index - 1].x - x) < abs(_points[index].x - x))) { - index = index - 1; + index = index - 1; } return index; } -} // end namespace +} // namespace PJ #endif diff --git a/plotjuggler_base/include/PlotJuggler/toolbox_base.h b/plotjuggler_base/include/PlotJuggler/toolbox_base.h index bf86237ef..e6b882908 100644 --- a/plotjuggler_base/include/PlotJuggler/toolbox_base.h +++ b/plotjuggler_base/include/PlotJuggler/toolbox_base.h @@ -8,22 +8,21 @@ #include "PlotJuggler/pj_plugin.h" #include "PlotJuggler/transform_function.h" -namespace PJ { - +namespace PJ +{ class ToolboxPlugin : public PlotJugglerPlugin { Q_OBJECT public: - ToolboxPlugin() = default; - virtual void init( PlotDataMapRef& src_data, - TransformsMap& transform_map) = 0; + virtual void init(PlotDataMapRef& src_data, TransformsMap& transform_map) = 0; virtual ~ToolboxPlugin() = default; - enum WidgetType { + enum WidgetType + { FLOATING, FIXED }; @@ -39,12 +38,11 @@ public slots: void plotCreated(std::string plot_name); void closed(); - }; using ToolboxPluginPtr = std::shared_ptr; -} +} // namespace PJ QT_BEGIN_NAMESPACE #define Toolbox_iid "facontidavide.PlotJuggler3.Toolbox" diff --git a/plotjuggler_base/include/PlotJuggler/transform_function.h b/plotjuggler_base/include/PlotJuggler/transform_function.h index fab804c6b..09d824511 100644 --- a/plotjuggler_base/include/PlotJuggler/transform_function.h +++ b/plotjuggler_base/include/PlotJuggler/transform_function.h @@ -6,8 +6,8 @@ #include "PlotJuggler/plotdata.h" #include "PlotJuggler/pj_plugin.h" -namespace PJ { - +namespace PJ +{ /** @brief Generic interface for a multi input - multi output transformation function. * Contrariwise to other plugins, multiple instances of the this class might be created. * For this reason, a TransformFactory is also defined @@ -26,15 +26,15 @@ class TransformFunction : public PlotJugglerPlugin virtual const char* name() const = 0; /** Number of inputs. Return -1 if it is not a constant. - * - * When numInputs() > 0, then the data will be initialized using - * the method: - * setDataSource(const std::vector& src_data) - * - * When numInputs() == -1, then the number of inputs is undefined and the - * data will be initialized using the method_ - * setDataSource( PlotDataMapRef* data ) - */ + * + * When numInputs() > 0, then the data will be initialized using + * the method: + * setDataSource(const std::vector& src_data) + * + * When numInputs() == -1, then the number of inputs is undefined and the + * data will be initialized using the method_ + * setDataSource( PlotDataMapRef* data ) + */ virtual int numInputs() const = 0; /** Number of outputs. Define the size of the vector used in: @@ -43,18 +43,19 @@ class TransformFunction : public PlotJugglerPlugin virtual int numOutputs() const = 0; /** Clear the cache, state and any stored data */ - virtual void reset() {} + virtual void reset() + { + } - PlotDataMapRef* plotData() { + PlotDataMapRef* plotData() + { return _data; } std::vector& dataSources(); - virtual void setData( - PlotDataMapRef* data, - const std::vector& src_vect, - std::vector& dst_vect); + virtual void setData(PlotDataMapRef* data, const std::vector& src_vect, + std::vector& dst_vect); virtual void calculate() = 0; @@ -65,7 +66,6 @@ class TransformFunction : public PlotJugglerPlugin std::vector _src_vector; std::vector _dst_vector; PlotDataMapRef* _data; - }; using TransformsMap = std::unordered_map>; @@ -75,16 +75,17 @@ class TransformFunction_SISO : public TransformFunction { Q_OBJECT public: - TransformFunction_SISO() = default; void reset() override; - int numInputs() const override { + int numInputs() const override + { return 1; } - int numOutputs() const override { + int numOutputs() const override + { return 1; } @@ -97,16 +98,17 @@ class TransformFunction_SISO : public TransformFunction const PlotData* dataSource() const; protected: - - double _last_timestamp = - std::numeric_limits::max(); + double _last_timestamp = -std::numeric_limits::max(); }; ///------ The factory to create instances of a SeriesTransform ------------- -class TransformFactory: public QObject +class TransformFactory : public QObject { public: - TransformFactory() {} + TransformFactory() + { + } private: TransformFactory(const TransformFactory&) = delete; @@ -118,27 +120,26 @@ class TransformFactory: public QObject static TransformFactory* instance(); public: - static const std::set& registeredTransforms(); - template static void registerTransform() + template + static void registerTransform() { T temp; std::string name = temp.name(); instance()->names_.insert(name); - instance()->creators_[name] = [](){ return std::make_shared(); }; + instance()->creators_[name] = []() { return std::make_shared(); }; } static TransformFunction::Ptr create(const std::string& name); }; -} // end namespace +} // namespace PJ -Q_DECLARE_OPAQUE_POINTER(PJ::TransformFactory *) -Q_DECLARE_METATYPE(PJ::TransformFactory *) +Q_DECLARE_OPAQUE_POINTER(PJ::TransformFactory*) +Q_DECLARE_METATYPE(PJ::TransformFactory*) Q_GLOBAL_STATIC(PJ::TransformFactory, _transform_factory_ptr_from_macro) - QT_BEGIN_NAMESPACE #define TransformFunction_iid "facontidavide.PlotJuggler3.TransformFunction" @@ -148,4 +149,3 @@ Q_DECLARE_INTERFACE(PJ::TransformFunction, TransformFunction_iid) Q_DECLARE_INTERFACE(PJ::TransformFunction_SISO, TransformFunctionSISO_iid) QT_END_NAMESPACE - diff --git a/plotjuggler_base/src/datastreamer_base.cpp b/plotjuggler_base/src/datastreamer_base.cpp index f868af251..69933b38e 100644 --- a/plotjuggler_base/src/datastreamer_base.cpp +++ b/plotjuggler_base/src/datastreamer_base.cpp @@ -2,14 +2,16 @@ namespace PJ { - -void DataStreamer::setAvailableParsers(std::shared_ptr parsers_factory) { +void DataStreamer::setAvailableParsers( + std::shared_ptr parsers_factory) +{ _available_parsers = parsers_factory; } std::shared_ptr DataStreamer::availableParsers() { - if( _available_parsers && _available_parsers->empty() ) { + if (_available_parsers && _available_parsers->empty()) + { return {}; } return _available_parsers; @@ -32,5 +34,4 @@ void PJ::DataStreamer::setMaximumRangeX(double range) } } - -} +} // namespace PJ diff --git a/plotjuggler_base/src/plotdata.cpp b/plotjuggler_base/src/plotdata.cpp index 81cdaa192..fa4fcb389 100644 --- a/plotjuggler_base/src/plotdata.cpp +++ b/plotjuggler_base/src/plotdata.cpp @@ -2,16 +2,13 @@ namespace PJ { - - template -typename std::unordered_map::iterator addImpl( - std::unordered_map& series, - const std::string& name, - PlotGroup::Ptr group ) +typename std::unordered_map::iterator +addImpl(std::unordered_map& series, const std::string& name, + PlotGroup::Ptr group) { std::string ID; - if( group ) + if (group) { ID = group->name(); if (ID.back() != '/') @@ -21,68 +18,69 @@ typename std::unordered_map::iterator addImpl( } ID += name; - return series.emplace( - std::piecewise_construct, - std::forward_as_tuple(name), - std::forward_as_tuple(name, group)).first; + return series + .emplace(std::piecewise_construct, std::forward_as_tuple(name), + std::forward_as_tuple(name, group)) + .first; } template -T& getOrCreateImpl(std::unordered_map& series, - const std::string& name, +T& getOrCreateImpl(std::unordered_map& series, const std::string& name, const PlotGroup::Ptr& group) { - auto it = series.find( name ); - if( it == series.end() ) { + auto it = series.find(name); + if (it == series.end()) + { it = addImpl(series, name, group); } return it->second; } -PlotDataMap::iterator -PlotDataMapRef::addNumeric(const std::string &name, - PlotGroup::Ptr group) +PlotDataMap::iterator PlotDataMapRef::addNumeric(const std::string& name, + PlotGroup::Ptr group) { return addImpl(numeric, name, group); } -AnySeriesMap::iterator PlotDataMapRef::addUserDefined(const std::string &name, +AnySeriesMap::iterator PlotDataMapRef::addUserDefined(const std::string& name, PlotGroup::Ptr group) { return addImpl(user_defined, name, group); } -StringSeriesMap::iterator PlotDataMapRef::addStringSeries(const std::string &name, +StringSeriesMap::iterator PlotDataMapRef::addStringSeries(const std::string& name, PlotGroup::Ptr group) { return addImpl(strings, name, group); } -PlotData &PlotDataMapRef::getOrCreateNumeric(const std::string &name, +PlotData& PlotDataMapRef::getOrCreateNumeric(const std::string& name, PlotGroup::Ptr group) { - return getOrCreateImpl( numeric, name, group ); + return getOrCreateImpl(numeric, name, group); } -StringSeries &PlotDataMapRef::getOrCreateStringSeries(const std::string &name, +StringSeries& PlotDataMapRef::getOrCreateStringSeries(const std::string& name, PlotGroup::Ptr group) { - return getOrCreateImpl( strings, name, group ); + return getOrCreateImpl(strings, name, group); } -PlotDataAny &PlotDataMapRef::getOrCreateUserDefined(const std::string &name, +PlotDataAny& PlotDataMapRef::getOrCreateUserDefined(const std::string& name, PlotGroup::Ptr group) { - return getOrCreateImpl( user_defined, name, group ); + return getOrCreateImpl(user_defined, name, group); } -PlotGroup::Ptr PlotDataMapRef::getOrCreateGroup(const std::string &name) +PlotGroup::Ptr PlotDataMapRef::getOrCreateGroup(const std::string& name) { - if( name.empty() ) { - throw std::runtime_error( "Group name can not be empty" ); + if (name.empty()) + { + throw std::runtime_error("Group name can not be empty"); } - auto& group = groups[ name ]; - if( !group ) { + auto& group = groups[name]; + if (!group) + { group = std::make_shared(name); } return group; @@ -99,43 +97,42 @@ void PlotDataMapRef::setMaximumRangeX(double range) { for (auto& it : numeric) { - it.second.setMaximumRangeX( range ); + it.second.setMaximumRangeX(range); } for (auto& it : strings) { - it.second.setMaximumRangeX( range ); + it.second.setMaximumRangeX(range); } for (auto& it : user_defined) { - it.second.setMaximumRangeX( range ); + it.second.setMaximumRangeX(range); } } -bool PlotDataMapRef::erase(const std::string &name) +bool PlotDataMapRef::erase(const std::string& name) { bool erased = false; auto num_it = numeric.find(name); if (num_it != numeric.end()) { - numeric.erase( num_it ); + numeric.erase(num_it); erased = true; } auto str_it = strings.find(name); if (str_it != strings.end()) { - strings.erase( str_it ); + strings.erase(str_it); erased = true; } auto any_it = user_defined.find(name); if (any_it != user_defined.end()) { - user_defined.erase( any_it ); + user_defined.erase(any_it); erased = true; } return erased; } - -} +} // namespace PJ diff --git a/plotjuggler_base/src/plotlegend.cpp b/plotjuggler_base/src/plotlegend.cpp index 5bc5e2ec3..0f65b4a83 100644 --- a/plotjuggler_base/src/plotlegend.cpp +++ b/plotjuggler_base/src/plotlegend.cpp @@ -14,7 +14,8 @@ PlotLegend::PlotLegend(QwtPlot* parent) : _parent_plot(parent), _collapsed(false setMaxColumns(1); setAlignmentInCanvas(Qt::Alignment(Qt::AlignTop | Qt::AlignRight)); - setBackgroundMode(QwtPlotLegendItem::BackgroundMode::LegendBackground);; + setBackgroundMode(QwtPlotLegendItem::BackgroundMode::LegendBackground); + ; setBorderRadius(0); setMargin(2); @@ -35,12 +36,13 @@ QRectF PlotLegend::hideButtonRect() const auto canvas_rect = _parent_plot->canvas()->rect(); if (alignmentInCanvas() & Qt::AlignRight) { - return QRectF(geometry(canvas_rect).topRight() + QPoint(-s, -s) , QSize(s*2, s*2)); + return QRectF(geometry(canvas_rect).topRight() + QPoint(-s, -s), QSize(s * 2, s * 2)); } - return QRectF(geometry(canvas_rect).topLeft() + QPoint(-s, -s), QSize(s*2, s*2)); + return QRectF(geometry(canvas_rect).topLeft() + QPoint(-s, -s), QSize(s * 2, s * 2)); } -void PlotLegend::draw(QPainter* painter, const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QRectF& rect) const +void PlotLegend::draw(QPainter* painter, const QwtScaleMap& xMap, const QwtScaleMap& yMap, + const QRectF& rect) const { if (!_collapsed) { @@ -58,8 +60,9 @@ void PlotLegend::draw(QPainter* painter, const QwtScaleMap& xMap, const QwtScale painter->setBrush(QBrush(Qt::white, Qt::SolidPattern)); painter->drawEllipse(iconRect); - if( _collapsed ){ - iconRect -= QMarginsF(3,3,3,3); + if (_collapsed) + { + iconRect -= QMarginsF(3, 3, 3, 3); painter->setBrush(QBrush(col, Qt::SolidPattern)); painter->drawEllipse(iconRect); } @@ -68,8 +71,8 @@ void PlotLegend::draw(QPainter* painter, const QwtScaleMap& xMap, const QwtScale } } -void PlotLegend::drawLegendData(QPainter* painter, const QwtPlotItem* plotItem, const QwtLegendData& data, - const QRectF& rect) const +void PlotLegend::drawLegendData(QPainter* painter, const QwtPlotItem* plotItem, + const QwtLegendData& data, const QRectF& rect) const { Q_UNUSED(plotItem); @@ -137,7 +140,7 @@ const QwtPlotItem* PlotLegend::processMousePressEvent(QMouseEvent* mouse_event) if (isVisible() && mouse_event->modifiers() == Qt::NoModifier) { - if ( (hideButtonRect() + QMargins(2,2,2,2) ).contains(press_point)) + if ((hideButtonRect() + QMargins(2, 2, 2, 2)).contains(press_point)) { _collapsed = !_collapsed; _parent_plot->replot(); diff --git a/plotjuggler_base/src/plotlegend.h b/plotjuggler_base/src/plotlegend.h index 992e3c1e6..4688a22bc 100644 --- a/plotjuggler_base/src/plotlegend.h +++ b/plotjuggler_base/src/plotlegend.h @@ -16,7 +16,8 @@ class PlotLegend : public QObject, public QwtPlotLegendItem const QwtPlotItem* processMousePressEvent(QMouseEvent* mouse_event); private: - virtual void draw(QPainter* p, const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QRectF& rect) const override; + virtual void draw(QPainter* p, const QwtScaleMap& xMap, const QwtScaleMap& yMap, + const QRectF& rect) const override; virtual void drawLegendData(QPainter* painter, const QwtPlotItem*, const QwtLegendData&, const QRectF&) const override; @@ -25,7 +26,6 @@ class PlotLegend : public QObject, public QwtPlotLegendItem QwtPlot* _parent_plot; bool _collapsed; - }; #endif // PLOTLEGEND_H diff --git a/plotjuggler_base/src/plotmagnifier.cpp b/plotjuggler_base/src/plotmagnifier.cpp index b23912ea8..58e491079 100644 --- a/plotjuggler_base/src/plotmagnifier.cpp +++ b/plotjuggler_base/src/plotmagnifier.cpp @@ -7,7 +7,8 @@ #include "qwt_plot.h" #include "qwt_scale_map.h" -PlotMagnifier::PlotMagnifier(QWidget* canvas) : QwtPlotMagnifier(canvas), _default_mode(BOTH_AXES) +PlotMagnifier::PlotMagnifier(QWidget* canvas) + : QwtPlotMagnifier(canvas), _default_mode(BOTH_AXES) { for (int axisId = 0; axisId < QwtPlot::axisCnt; axisId++) { diff --git a/plotjuggler_base/src/plotwidget_base.cpp b/plotjuggler_base/src/plotwidget_base.cpp index 9c59b2b53..86394c9bf 100644 --- a/plotjuggler_base/src/plotwidget_base.cpp +++ b/plotjuggler_base/src/plotwidget_base.cpp @@ -34,7 +34,7 @@ static int _global_color_index_ = 0; -class PlotWidgetBase::QwtPlotPimpl: public QwtPlot +class PlotWidgetBase::QwtPlotPimpl : public QwtPlot { public: PlotLegend* legend; @@ -44,18 +44,17 @@ class PlotWidgetBase::QwtPlotPimpl: public QwtPlot PlotZoomer* zoomer; std::function resized_callback; std::function event_callback; - PlotWidgetBase *parent; + PlotWidgetBase* parent; - QwtPlotPimpl(PlotWidgetBase *parentObject, - QWidget* canvas, + QwtPlotPimpl(PlotWidgetBase* parentObject, QWidget* canvas, std::function resizedViewCallback, - std::function eventCallback): - QwtPlot(nullptr), - resized_callback(resizedViewCallback), - event_callback(eventCallback), - parent( parentObject ) + std::function eventCallback) + : QwtPlot(nullptr) + , resized_callback(resizedViewCallback) + , event_callback(eventCallback) + , parent(parentObject) { - this->setCanvas( canvas ); + this->setCanvas(canvas); legend = new PlotLegend(this); magnifier = new PlotMagnifier(this->canvas()); @@ -65,8 +64,7 @@ class PlotWidgetBase::QwtPlotPimpl: public QwtPlot zoomer->setRubberBandPen(QColor(Qt::red, 1, Qt::DotLine)); zoomer->setTrackerPen(QColor(Qt::green, 1, Qt::DotLine)); - zoomer->setMousePattern(QwtEventPattern::MouseSelect1, - Qt::LeftButton, + zoomer->setMousePattern(QwtEventPattern::MouseSelect1, Qt::LeftButton, Qt::NoModifier); magnifier->setAxisEnabled(QwtPlot::xTop, false); @@ -81,25 +79,22 @@ class PlotWidgetBase::QwtPlotPimpl: public QwtPlot panner1->setMouseButton(Qt::LeftButton, Qt::ControlModifier); panner2->setMouseButton(Qt::MiddleButton, Qt::NoModifier); - connect(zoomer, &PlotZoomer::zoomed, - this, [this](const QRectF& r) { resized_callback(r); } ); + connect(zoomer, &PlotZoomer::zoomed, this, + [this](const QRectF& r) { resized_callback(r); }); - connect(magnifier, &PlotMagnifier::rescaled, - this, [this](const QRectF& r) { + connect(magnifier, &PlotMagnifier::rescaled, this, [this](const QRectF& r) { resized_callback(r); replot(); - } ); + }); - connect(panner1, &QwtPlotPanner::panned, - this, [this]() { - resized_callback(canvasBoundingRect()); } ); + connect(panner1, &QwtPlotPanner::panned, this, + [this]() { resized_callback(canvasBoundingRect()); }); - connect(panner2, &QwtPlotPanner::panned, - this, [this]() { - resized_callback(canvasBoundingRect()); } ); + connect(panner2, &QwtPlotPanner::panned, this, + [this]() { resized_callback(canvasBoundingRect()); }); - QwtScaleWidget* bottomAxis = axisWidget( QwtPlot::xBottom ); - QwtScaleWidget* leftAxis = axisWidget( QwtPlot::yLeft ); + QwtScaleWidget* bottomAxis = axisWidget(QwtPlot::xBottom); + QwtScaleWidget* leftAxis = axisWidget(QwtPlot::yLeft); bottomAxis->installEventFilter(parent); leftAxis->installEventFilter(parent); @@ -108,12 +103,12 @@ class PlotWidgetBase::QwtPlotPimpl: public QwtPlot ~QwtPlotPimpl() override { - QwtScaleWidget* bottomAxis = axisWidget( QwtPlot::xBottom ); - QwtScaleWidget* leftAxis = axisWidget( QwtPlot::yLeft ); + QwtScaleWidget* bottomAxis = axisWidget(QwtPlot::xBottom); + QwtScaleWidget* leftAxis = axisWidget(QwtPlot::yLeft); bottomAxis->installEventFilter(parent); leftAxis->removeEventFilter(parent); - canvas()->removeEventFilter( parent ); + canvas()->removeEventFilter(parent); setCanvas(nullptr); } @@ -147,20 +142,18 @@ class PlotWidgetBase::QwtPlotPimpl: public QwtPlot void dropEvent(QDropEvent* event) override { - event_callback(event); + event_callback(event); } - }; namespace PJ { - -QwtPlot *PlotWidgetBase::qwtPlot() +QwtPlot* PlotWidgetBase::qwtPlot() { return p; } -const QwtPlot *PlotWidgetBase::qwtPlot() const +const QwtPlot* PlotWidgetBase::qwtPlot() const { return p; } @@ -180,11 +173,9 @@ void PlotWidgetBase::resetZoom() updateMaximumZoomArea(); QRectF rect = maxZoomRect(); - qwtPlot()->setAxisScale(QwtPlot::yLeft, - std::min(rect.bottom(), rect.top()), + qwtPlot()->setAxisScale(QwtPlot::yLeft, std::min(rect.bottom(), rect.top()), std::max(rect.bottom(), rect.top())); - qwtPlot()->setAxisScale(QwtPlot::xBottom, - std::min(rect.left(), rect.right()), + qwtPlot()->setAxisScale(QwtPlot::xBottom, std::min(rect.left(), rect.right()), std::max(rect.left(), rect.right())); qwtPlot()->updateAxes(); @@ -203,7 +194,8 @@ Range PlotWidgetBase::getVisualizationRangeX() const auto series = dynamic_cast(it.curve->data()); const auto max_range_X = series->getVisualizationRangeX(); - if (!max_range_X){ + if (!max_range_X) + { continue; } @@ -241,7 +233,8 @@ Range PlotWidgetBase::getVisualizationRangeY(Range range_X) const auto series = dynamic_cast(it.curve->data()); const auto max_range_X = series->plotData()->rangeX(); - if (!max_range_X){ + if (!max_range_X) + { continue; } @@ -256,10 +249,12 @@ Range PlotWidgetBase::getVisualizationRangeY(Range range_X) const qDebug() << " invalid range_Y in PlotWidget::maximumRangeY"; continue; } - if (top < range_Y->max){ + if (top < range_Y->max) + { top = range_Y->max; } - if (bottom > range_Y->min){ + if (bottom > range_Y->min) + { bottom = range_Y->min; } } @@ -303,22 +298,17 @@ void PlotWidgetBase::setModeXY(bool enable) _xy_mode = enable; } - -PlotWidgetBase::PlotWidgetBase(QWidget *parent): - _xy_mode(false), - _keep_aspect_ratio(false) +PlotWidgetBase::PlotWidgetBase(QWidget* parent) + : _xy_mode(false), _keep_aspect_ratio(false) { - auto onViewResized = [this](const QRectF& r) { - emit viewResized(r); - }; + auto onViewResized = [this](const QRectF& r) { emit viewResized(r); }; - auto onEvent = [this](QEvent* event) - { - if( auto ev = dynamic_cast(event) ) + auto onEvent = [this](QEvent* event) { + if (auto ev = dynamic_cast(event)) { emit dragEnterSignal(ev); } - else if( auto ev = dynamic_cast(event) ) + else if (auto ev = dynamic_cast(event)) { emit dropSignal(ev); } @@ -328,21 +318,22 @@ PlotWidgetBase::PlotWidgetBase(QWidget *parent): bool use_opengl = settings.value("Preferences::use_opengl", true).toBool(); QWidget* abs_canvas; - if( use_opengl ) + if (use_opengl) { auto canvas = new QwtPlotOpenGLCanvas(); canvas->setFrameStyle(QFrame::NoFrame); - canvas->setFrameStyle( QFrame::Box | QFrame::Plain ); - canvas->setLineWidth( 1 ); - canvas->setPalette( Qt::white ); + canvas->setFrameStyle(QFrame::Box | QFrame::Plain); + canvas->setLineWidth(1); + canvas->setPalette(Qt::white); abs_canvas = canvas; } - else{ + else + { auto canvas = new QwtPlotCanvas(); canvas->setFrameStyle(QFrame::NoFrame); - canvas->setFrameStyle( QFrame::Box | QFrame::Plain ); - canvas->setLineWidth( 1 ); - canvas->setPalette( Qt::white ); + canvas->setFrameStyle(QFrame::Box | QFrame::Plain); + canvas->setLineWidth(1); + canvas->setPalette(Qt::white); canvas->setPaintAttribute(QwtPlotCanvas::BackingStore, true); abs_canvas = canvas; } @@ -362,7 +353,9 @@ PlotWidgetBase::PlotWidgetBase(QWidget *parent): qwtPlot()->setAxisAutoScale(QwtPlot::yLeft, true); qwtPlot()->setAxisAutoScale(QwtPlot::xBottom, true); - qwtPlot()->axisScaleEngine(QwtPlot::xBottom)->setAttribute(QwtScaleEngine::Floating, true); + qwtPlot() + ->axisScaleEngine(QwtPlot::xBottom) + ->setAttribute(QwtScaleEngine::Floating, true); qwtPlot()->plotLayout()->setAlignCanvasToScales(true); qwtPlot()->setAxisScale(QwtPlot::xBottom, 0.0, 1.0); @@ -371,16 +364,15 @@ PlotWidgetBase::PlotWidgetBase(QWidget *parent): PlotWidgetBase::~PlotWidgetBase() { - if( p ){ + if (p) + { delete p; p = nullptr; } } -PlotWidgetBase::CurveInfo *PlotWidgetBase::addCurve( - const std::string &name, - PlotData& data, - QColor color) +PlotWidgetBase::CurveInfo* PlotWidgetBase::addCurve(const std::string& name, + PlotData& data, QColor color) { const auto qname = QString::fromStdString(name); @@ -388,7 +380,7 @@ PlotWidgetBase::CurveInfo *PlotWidgetBase::addCurve( auto curve_it = curveFromTitle(qname); if (curve_it) { - return nullptr; //TODO FIXME + return nullptr; // TODO FIXME } auto curve = new QwtPlotCurve(qname); @@ -402,29 +394,28 @@ PlotWidgetBase::CurveInfo *PlotWidgetBase::addCurve( } catch (std::exception& ex) { - QMessageBox::warning( qwtPlot(), "Exception!", ex.what()); + QMessageBox::warning(qwtPlot(), "Exception!", ex.what()); return nullptr; } - if( color == Qt::transparent ){ + if (color == Qt::transparent) + { color = getColorHint(&data); } curve->setPen(color); - setStyle( curve, p->curve_style ); + setStyle(curve, p->curve_style); curve->setRenderHint(QwtPlotItem::RenderAntialiased, true); - curve->attach( qwtPlot() ); + curve->attach(qwtPlot()); auto marker = new QwtPlotMarker; - marker->attach( qwtPlot() ); + marker->attach(qwtPlot()); marker->setVisible(false); - QwtSymbol* sym = new QwtSymbol(QwtSymbol::Ellipse, - Qt::red, - QPen(Qt::black), - QSize(8, 8)); + QwtSymbol* sym = + new QwtSymbol(QwtSymbol::Ellipse, Qt::red, QPen(Qt::black), QSize(8, 8)); marker->setSymbol(sym); CurveInfo curve_info; @@ -432,7 +423,7 @@ PlotWidgetBase::CurveInfo *PlotWidgetBase::addCurve( curve_info.marker = marker; curve_info.src_name = name; - p->curve_list.push_back( curve_info ); + p->curve_list.push_back(curve_info); return &(p->curve_list.back()); } @@ -442,13 +433,12 @@ bool PlotWidgetBase::isEmpty() const return p->curve_list.empty(); } -void PlotWidgetBase::removeCurve(const QString &title) +void PlotWidgetBase::removeCurve(const QString& title) { auto it = std::find_if(p->curve_list.begin(), p->curve_list.end(), - [&title](const PlotWidgetBase::CurveInfo& info) - { - return info.curve->title() == title; - }); + [&title](const PlotWidgetBase::CurveInfo& info) { + return info.curve->title() == title; + }); if (it != p->curve_list.end()) { @@ -460,18 +450,18 @@ void PlotWidgetBase::removeCurve(const QString &title) } } -const std::list &PlotWidgetBase::curveList() const +const std::list& PlotWidgetBase::curveList() const { return p->curve_list; } -std::list &PlotWidgetBase::curveList() +std::list& PlotWidgetBase::curveList() { return p->curve_list; } QwtSeriesWrapper* PlotWidgetBase::createTimeSeries(const QString& transform_ID, - const PlotData* data) + const PlotData* data) { TransformedTimeseries* output = new TransformedTimeseries(data); output->setTransform(transform_ID); @@ -479,7 +469,6 @@ QwtSeriesWrapper* PlotWidgetBase::createTimeSeries(const QString& transform_ID, return output; } - PlotWidgetBase::CurveStyle PlotWidgetBase::curveStyle() const { return p->curve_style; @@ -510,7 +499,7 @@ void PlotWidgetBase::setAcceptDrops(bool accept) bool PlotWidgetBase::eventFilter(QObject* obj, QEvent* event) { - if( event->type() == QEvent::Destroy ) + if (event->type() == QEvent::Destroy) { return false; } @@ -518,10 +507,8 @@ bool PlotWidgetBase::eventFilter(QObject* obj, QEvent* event) QwtScaleWidget* bottomAxis = qwtPlot()->axisWidget(QwtPlot::xBottom); QwtScaleWidget* leftAxis = qwtPlot()->axisWidget(QwtPlot::yLeft); - if (magnifier() && - (obj == bottomAxis || obj == leftAxis) - && !(isXYPlot() - && keepRatioXY())) + if (magnifier() && (obj == bottomAxis || obj == leftAxis) && + !(isXYPlot() && keepRatioXY())) { if (event->type() == QEvent::Wheel) { @@ -549,7 +536,7 @@ bool PlotWidgetBase::eventFilter(QObject* obj, QEvent* event) auto mouse_event = dynamic_cast(event); bool ctrl_modifier = mouse_event->modifiers() == Qt::ControlModifier; - auto legend_rect = legend()->geometry( qwtPlot()->canvas()->rect()); + auto legend_rect = legend()->geometry(qwtPlot()->canvas()->rect()); if (ctrl_modifier) { @@ -559,13 +546,13 @@ bool PlotWidgetBase::eventFilter(QObject* obj, QEvent* event) int new_size = prev_size; if (mouse_event->angleDelta().y() > 0) { - new_size = std::min(13, prev_size+1); + new_size = std::min(13, prev_size + 1); } if (mouse_event->angleDelta().y() < 0) { - new_size = std::max(7, prev_size-1); + new_size = std::max(7, prev_size - 1); } - if( new_size != prev_size) + if (new_size != prev_size) { setLegendSize(new_size); emit legendSizeChanged(new_size); @@ -606,19 +593,19 @@ bool PlotWidgetBase::eventFilter(QObject* obj, QEvent* event) QColor PlotWidgetBase::getColorHint(PlotData* data) { QSettings settings; - bool remember_color = - settings.value("Preferences::remember_color", true).toBool(); + bool remember_color = settings.value("Preferences::remember_color", true).toBool(); - if (data ) + if (data) { auto colorHint = data->attribute("ColorHint"); - if( remember_color && colorHint.isValid()) + if (remember_color && colorHint.isValid()) { return colorHint.value(); } } QColor color; - bool use_plot_color_index = settings.value("Preferences::use_plot_color_index", false).toBool(); + bool use_plot_color_index = + settings.value("Preferences::use_plot_color_index", false).toBool(); int index = p->curve_list.size(); if (!use_plot_color_index) @@ -657,7 +644,7 @@ QColor PlotWidgetBase::getColorHint(PlotData* data) } if (data) { - data->setAttribute( "ColorHint", color ); + data->setAttribute("ColorHint", color); } return color; @@ -669,48 +656,50 @@ std::map PlotWidgetBase::getCurveColors() const for (auto& it : p->curve_list) { - color_by_name.insert( {it.curve->title().text(), it.curve->pen().color()} ); + color_by_name.insert({ it.curve->title().text(), it.curve->pen().color() }); } return color_by_name; } - -void PlotWidgetBase::setStyle( QwtPlotCurve* curve, CurveStyle style ) +void PlotWidgetBase::setStyle(QwtPlotCurve* curve, CurveStyle style) { - curve->setPen(curve->pen().color(), - (style == DOTS) ? 4.0 : 1.3); + curve->setPen(curve->pen().color(), (style == DOTS) ? 4.0 : 1.3); - switch (style) { - case LINES: curve->setStyle( QwtPlotCurve::Lines ); - break; - case LINES_AND_DOTS: curve->setStyle( QwtPlotCurve::LinesAndDots ); - break; - case DOTS: curve->setStyle( QwtPlotCurve::Dots ); - break; - case STICKS: curve->setStyle( QwtPlotCurve::Sticks ); + switch (style) + { + case LINES: + curve->setStyle(QwtPlotCurve::Lines); + break; + case LINES_AND_DOTS: + curve->setStyle(QwtPlotCurve::LinesAndDots); + break; + case DOTS: + curve->setStyle(QwtPlotCurve::Dots); + break; + case STICKS: + curve->setStyle(QwtPlotCurve::Sticks); } } - void PlotWidgetBase::changeCurvesStyle(CurveStyle style) { p->curve_style = style; for (auto& it : p->curve_list) { - setStyle( it.curve, style ); + setStyle(it.curve, style); } replot(); } -PlotWidgetBase::CurveInfo *PlotWidgetBase::curveFromTitle(const QString &title) +PlotWidgetBase::CurveInfo* PlotWidgetBase::curveFromTitle(const QString& title) { - for(auto& info: p->curve_list ) + for (auto& info : p->curve_list) { - if( info.curve->title() == title ) + if (info.curve->title() == title) { return &info; } - if( info.src_name == title.toStdString() ) + if (info.src_name == title.toStdString()) { return &info; } @@ -726,7 +715,6 @@ void PlotWidgetBase::setLegendSize(int size) replot(); } - void PlotWidgetBase::setLegendAlignment(Qt::Alignment alignment) { p->legend->setAlignmentInCanvas(Qt::Alignment(Qt::AlignTop | alignment)); @@ -748,7 +736,8 @@ bool PlotWidgetBase::isZoomEnabled() const void PlotWidgetBase::replot() { - if( p->zoomer ){ + if (p->zoomer) + { p->zoomer->setZoomBase(false); } qwtPlot()->replot(); @@ -828,4 +817,4 @@ void PlotWidgetBase::updateMaximumZoomArea() _max_zoom_rect = max_rect; } -} +} // namespace PJ diff --git a/plotjuggler_base/src/plotzoomer.cpp b/plotjuggler_base/src/plotzoomer.cpp index 315c457fb..4bdc21b62 100644 --- a/plotjuggler_base/src/plotzoomer.cpp +++ b/plotjuggler_base/src/plotzoomer.cpp @@ -44,7 +44,8 @@ void PlotZoomer::widgetMouseMoveEvent(QMouseEvent* me) QRect rect(me->pos(), _initial_pos); QRectF zoomRect = invTransform(rect.normalized()); - if (zoomRect.width() > minZoomSize().width() && zoomRect.height() > minZoomSize().height()) + if (zoomRect.width() > minZoomSize().width() && + zoomRect.height() > minZoomSize().height()) { if (!_zoom_enabled) { @@ -91,7 +92,8 @@ bool PlotZoomer::accept(QPolygon& pa) const QRect rect = QRect(pa[0], pa[int(pa.count()) - 1]); QRectF zoomRect = invTransform(rect.normalized()); - if (zoomRect.width() < minZoomSize().width() && zoomRect.height() < minZoomSize().height()) + if (zoomRect.width() < minZoomSize().width() && + zoomRect.height() < minZoomSize().height()) { return false; } diff --git a/plotjuggler_base/src/timeseries_qwt.cpp b/plotjuggler_base/src/timeseries_qwt.cpp index 99f2b56f2..ddbbf0429 100644 --- a/plotjuggler_base/src/timeseries_qwt.cpp +++ b/plotjuggler_base/src/timeseries_qwt.cpp @@ -8,7 +8,7 @@ RangeOpt QwtTimeseries::getVisualizationRangeY(Range range_X) { int first_index = _ts_data->getIndexFromX(range_X.min); - int last_index = _ts_data->getIndexFromX(range_X.max); + int last_index = _ts_data->getIndexFromX(range_X.max); if (first_index > last_index || first_index < 0 || last_index < 0) { @@ -43,16 +43,13 @@ std::optional QwtTimeseries::sampleFromTime(double t) return QPointF(p.x, p.y); } - TransformedTimeseries::TransformedTimeseries(const PlotData* source_data) : QwtTimeseries(&_dst_data) - ,_dst_data(source_data->plotName(), {} ) - ,_src_data( source_data ) + , _dst_data(source_data->plotName(), {}) + , _src_data(source_data) { - } - TransformFunction::Ptr TransformedTimeseries::transform() { return _transform; @@ -60,40 +57,42 @@ TransformFunction::Ptr TransformedTimeseries::transform() void TransformedTimeseries::setTransform(QString transform_ID) { - if( transformName() == transform_ID) + if (transformName() == transform_ID) { return; } - if( transform_ID.isEmpty() ) + if (transform_ID.isEmpty()) { _transform.reset(); } - else{ + else + { _dst_data.clear(); _transform = TransformFactory::create(transform_ID.toStdString()); - std::vector dest = {&_dst_data}; - _transform->setData( nullptr, {_src_data}, dest ); + std::vector dest = { &_dst_data }; + _transform->setData(nullptr, { _src_data }, dest); } } bool TransformedTimeseries::updateCache(bool reset_old_data) { - if( _transform ) + if (_transform) { - if( reset_old_data ) + if (reset_old_data) { _dst_data.clear(); _transform->reset(); } - std::vector dest = {&_dst_data}; - _transform->calculate( ); + std::vector dest = { &_dst_data }; + _transform->calculate(); } - else{ + else + { // TODO: optimize ?? _dst_data.clear(); - for(size_t i=0; i < _src_data->size(); i++) + for (size_t i = 0; i < _src_data->size(); i++) { - _dst_data.pushBack( _src_data->at(i) ); + _dst_data.pushBack(_src_data->at(i)); } } return true; @@ -101,7 +100,7 @@ bool TransformedTimeseries::updateCache(bool reset_old_data) QString TransformedTimeseries::transformName() { - return ( !_transform ) ? QString() : _transform->name(); + return (!_transform) ? QString() : _transform->name(); } QString TransformedTimeseries::alias() const @@ -116,7 +115,7 @@ void TransformedTimeseries::setAlias(QString alias) QRectF QwtSeriesWrapper::boundingRect() const { - if( size() == 0 ) + if (size() == 0) { return {}; } @@ -131,7 +130,6 @@ QRectF QwtSeriesWrapper::boundingRect() const return box; } - QPointF QwtSeriesWrapper::sample(size_t i) const { const auto& p = _data->at(i); @@ -150,18 +148,18 @@ void QwtSeriesWrapper::setTimeOffset(double offset) RangeOpt QwtSeriesWrapper::getVisualizationRangeX() { - if (this->size() < 2){ + if (this->size() < 2) + { return {}; } else { auto range = _data->rangeX().value(); - return RangeOpt({ range.min - _time_offset, - range.max - _time_offset }); + return RangeOpt({ range.min - _time_offset, range.max - _time_offset }); } } -const PlotDataBase *QwtSeriesWrapper::plotData() const +const PlotDataBase* QwtSeriesWrapper::plotData() const { return _data; } diff --git a/plotjuggler_base/src/timeseries_qwt.h b/plotjuggler_base/src/timeseries_qwt.h index 8e991c7c2..1c82e6821 100644 --- a/plotjuggler_base/src/timeseries_qwt.h +++ b/plotjuggler_base/src/timeseries_qwt.h @@ -7,16 +7,17 @@ using namespace PJ; - // wrapper to Timeseries inclduing a time offset -class QwtSeriesWrapper: public QwtSeriesData +class QwtSeriesWrapper : public QwtSeriesData { private: const PlotDataXY* _data; double _time_offset; public: - QwtSeriesWrapper(const PlotDataXY* data): _data(data), _time_offset(0.0) {} + QwtSeriesWrapper(const PlotDataXY* data) : _data(data), _time_offset(0.0) + { + } QPointF sample(size_t i) const override; @@ -35,16 +36,12 @@ class QwtSeriesWrapper: public QwtSeriesData virtual RangeOpt getVisualizationRangeY(Range range_X) = 0; virtual std::optional sampleFromTime(double t) = 0; - }; - class QwtTimeseries : public QwtSeriesWrapper { public: - QwtTimeseries(const PlotData* data): - QwtSeriesWrapper(data), - _ts_data(data) + QwtTimeseries(const PlotData* data) : QwtSeriesWrapper(data), _ts_data(data) { } @@ -76,7 +73,6 @@ class TransformedTimeseries : public QwtTimeseries void setAlias(QString alias); protected: - QString _alias; PlotData _dst_data; const PlotData* _src_data; @@ -85,6 +81,4 @@ class TransformedTimeseries : public QwtTimeseries //--------------------------------------------------------- - - #endif // PLOTDATA_H diff --git a/plotjuggler_base/src/transform_function.cpp b/plotjuggler_base/src/transform_function.cpp index db3a7a1ce..bc4076a68 100644 --- a/plotjuggler_base/src/transform_function.cpp +++ b/plotjuggler_base/src/transform_function.cpp @@ -1,29 +1,26 @@ #include "PlotJuggler/transform_function.h" -namespace PJ { - -TransformFunction::TransformFunction(): - _data(nullptr) +namespace PJ +{ +TransformFunction::TransformFunction() : _data(nullptr) { - } -std::vector &TransformFunction::dataSources() +std::vector& TransformFunction::dataSources() { return _src_vector; } -void TransformFunction::setData( - PlotDataMapRef *data, - const std::vector &src_vect, - std::vector& dst_vect) +void TransformFunction::setData(PlotDataMapRef* data, + const std::vector& src_vect, + std::vector& dst_vect) { - if( numInputs() >= 0 && src_vect.size() != numInputs() ) + if (numInputs() >= 0 && src_vect.size() != numInputs()) { throw std::runtime_error("Wrong number of input data sources " "in setDataSource"); } - if( dst_vect.size() != numOutputs() ) + if (dst_vect.size() != numOutputs()) { throw std::runtime_error("Wrong number of output data destinations"); } @@ -32,8 +29,9 @@ void TransformFunction::setData( _dst_vector = dst_vect; } -void TransformFunction_SISO::reset() { - _last_timestamp = - std::numeric_limits::max(); +void TransformFunction_SISO::reset() +{ + _last_timestamp = -std::numeric_limits::max(); } void TransformFunction_SISO::calculate() @@ -44,16 +42,16 @@ void TransformFunction_SISO::calculate() { return; } - dst_data->setMaximumRangeX( src_data->maximumRangeX() ); + dst_data->setMaximumRangeX(src_data->maximumRangeX()); if (dst_data->size() != 0) { _last_timestamp = dst_data->back().x; } - int pos = src_data->getIndexFromX( _last_timestamp ); + int pos = src_data->getIndexFromX(_last_timestamp); size_t index = pos < 0 ? 0 : static_cast(pos); - while(index < src_data->size()) + while (index < src_data->size()) { const auto& in_point = src_data->at(index); @@ -62,7 +60,7 @@ void TransformFunction_SISO::calculate() auto out_point = calculateNextPoint(index); if (out_point) { - dst_data->pushBack( std::move(out_point.value()) ); + dst_data->pushBack(std::move(out_point.value())); } _last_timestamp = in_point.x; } @@ -70,49 +68,47 @@ void TransformFunction_SISO::calculate() } } - -TransformFunction::Ptr TransformFactory::create(const std::string &name) +TransformFunction::Ptr TransformFactory::create(const std::string& name) { auto it = instance()->creators_.find(name); - if( it == instance()->creators_.end()) + if (it == instance()->creators_.end()) { return {}; } return it->second(); } -TransformFactory *PJ::TransformFactory::instance() +TransformFactory* PJ::TransformFactory::instance() { - static TransformFactory * _ptr(nullptr); - if (!qApp->property("TransformFactory").isValid() && !_ptr) { + static TransformFactory* _ptr(nullptr); + if (!qApp->property("TransformFactory").isValid() && !_ptr) + { _ptr = _transform_factory_ptr_from_macro; qApp->setProperty("TransformFactory", QVariant::fromValue(_ptr)); } - else if (!_ptr) { - _ptr = qvariant_cast(qApp->property("TransformFactory")); + else if (!_ptr) + { + _ptr = qvariant_cast(qApp->property("TransformFactory")); } - else if (!qApp->property("TransformFactory").isValid()) { + else if (!qApp->property("TransformFactory").isValid()) + { qApp->setProperty("TransformFactory", QVariant::fromValue(_ptr)); } return _ptr; } -const std::set &TransformFactory::registeredTransforms() +const std::set& TransformFactory::registeredTransforms() { return instance()->names_; } -const PlotData *TransformFunction_SISO::dataSource() const +const PlotData* TransformFunction_SISO::dataSource() const { - if( _src_vector.empty() ) + if (_src_vector.empty()) { return nullptr; } return _src_vector.front(); } - -} - - - +} // namespace PJ diff --git a/plotjuggler_plugins/DataLoadCSV/dataload_csv.cpp b/plotjuggler_plugins/DataLoadCSV/dataload_csv.cpp index 492954bee..a9da9ba8b 100644 --- a/plotjuggler_plugins/DataLoadCSV/dataload_csv.cpp +++ b/plotjuggler_plugins/DataLoadCSV/dataload_csv.cpp @@ -11,7 +11,6 @@ const int TIME_INDEX_NOT_DEFINED = -2; const int TIME_INDEX_GENERATED = -1; - QStringList SplitLine(const QString& line, QChar separator) { QStringList parts; @@ -22,17 +21,18 @@ QStringList SplitLine(const QString& line, QChar separator) int quote_start = 0; int quote_end = 0; - for( int pos = 0; pos < line.size(); pos++ ) + for (int pos = 0; pos < line.size(); pos++) { - if( line[pos] == '"' ) + if (line[pos] == '"') { - if( inside_quotes ) + if (inside_quotes) { quoted_word = true; - quote_end = pos-1; + quote_end = pos - 1; } - else{ - quote_start = pos+1; + else + { + quote_start = pos + 1; } inside_quotes = !inside_quotes; } @@ -41,40 +41,42 @@ QStringList SplitLine(const QString& line, QChar separator) bool add_empty = false; int end_pos = pos; - if( (!inside_quotes && line[pos] == separator) ) + if ((!inside_quotes && line[pos] == separator)) { part_completed = true; } - if( pos+1 == line.size() ) + if (pos + 1 == line.size()) { part_completed = true; - end_pos = pos+1; + end_pos = pos + 1; // special case - if( line[pos] == separator ) + if (line[pos] == separator) { end_pos = pos; add_empty = true; } } - if( part_completed ) + if (part_completed) { QString part; - if ( quoted_word ) { - part = line.mid(quote_start, quote_end - quote_start + 1 ); + if (quoted_word) + { + part = line.mid(quote_start, quote_end - quote_start + 1); } - else{ - part = line.mid(start_pos, end_pos - start_pos ); + else + { + part = line.mid(start_pos, end_pos - start_pos); } - parts.push_back( part.trimmed() ); - start_pos = pos+1; + parts.push_back(part.trimmed()); + start_pos = pos + 1; quoted_word = false; inside_quotes = false; } - if( add_empty ) + if (add_empty) { - parts.push_back( QString() ); + parts.push_back(QString()); } } @@ -91,36 +93,28 @@ DataLoadCSV::DataLoadCSV() _ui = new Ui::DialogCSV(); _ui->setupUi(_dialog); - connect ( _ui->radioButtonSelect, &QRadioButton::toggled, - this, [this]( bool checked ) { - _ui->listWidgetSeries->setEnabled( checked ); - auto selected = _ui->listWidgetSeries->selectionModel()->selectedIndexes(); - bool box_enabled = !checked || selected.size() == 1; - _ui->buttonBox->setEnabled( box_enabled ); - }); - connect ( _ui->listWidgetSeries, &QListWidget::itemSelectionChanged, - this, [this]() { - auto selected = _ui->listWidgetSeries->selectionModel()->selectedIndexes(); - bool box_enabled = _ui->radioButtonIndex->isChecked() || selected.size() == 1; - _ui->buttonBox->setEnabled( box_enabled ); - }); - - connect ( _ui->listWidgetSeries, &QListWidget::itemDoubleClicked, - this, [this]() { - emit _ui->buttonBox->accepted(); - }); - - connect(_ui->checkBoxDateFormat, &QCheckBox::toggled, - this, [this](bool checked) { - _ui->lineEditDateFormat->setEnabled( checked ); - }); + connect(_ui->radioButtonSelect, &QRadioButton::toggled, this, [this](bool checked) { + _ui->listWidgetSeries->setEnabled(checked); + auto selected = _ui->listWidgetSeries->selectionModel()->selectedIndexes(); + bool box_enabled = !checked || selected.size() == 1; + _ui->buttonBox->setEnabled(box_enabled); + }); + connect(_ui->listWidgetSeries, &QListWidget::itemSelectionChanged, this, [this]() { + auto selected = _ui->listWidgetSeries->selectionModel()->selectedIndexes(); + bool box_enabled = _ui->radioButtonIndex->isChecked() || selected.size() == 1; + _ui->buttonBox->setEnabled(box_enabled); + }); + + connect(_ui->listWidgetSeries, &QListWidget::itemDoubleClicked, this, + [this]() { emit _ui->buttonBox->accepted(); }); + connect(_ui->checkBoxDateFormat, &QCheckBox::toggled, this, + [this](bool checked) { _ui->lineEditDateFormat->setEnabled(checked); }); _ui->splitter->setStretchFactor(0, 1); _ui->splitter->setStretchFactor(1, 2); } - DataLoadCSV::~DataLoadCSV() { delete _ui; @@ -132,8 +126,7 @@ const std::vector& DataLoadCSV::compatibleFileExtensions() const return _extensions; } -void DataLoadCSV::parseHeader(QFile& file, - std::vector& column_names ) +void DataLoadCSV::parseHeader(QFile& file, std::vector& column_names) { file.open(QFile::ReadOnly); @@ -147,7 +140,7 @@ void DataLoadCSV::parseHeader(QFile& file, QString preview_lines = first_line + "\n"; - QStringList firstline_items = SplitLine( first_line, _separator ); + QStringList firstline_items = SplitLine(first_line, _separator); int is_number_count = 0; @@ -158,13 +151,13 @@ void DataLoadCSV::parseHeader(QFile& file, { bool isNum; firstline_items[i].trimmed().toDouble(&isNum); - if( isNum ) + if (isNum) { is_number_count++; } } - if( is_number_count == firstline_items.size() ) + if (is_number_count == firstline_items.size()) { for (int i = 0; i < firstline_items.size(); i++) { @@ -191,9 +184,9 @@ void DataLoadCSV::parseHeader(QFile& file, } } - if( different_columns.size() < column_names.size() ) + if (different_columns.size() < column_names.size()) { - if( multiple_columns_warning_ ) + if (multiple_columns_warning_) { QMessageBox::warning(nullptr, "Duplicate Column Name", "Multiple Columns have the same name.\n" @@ -202,20 +195,21 @@ void DataLoadCSV::parseHeader(QFile& file, } std::vector repeated_columns; - for (size_t i=0; i 1) { - for (size_t index: repeated_columns) + for (size_t index : repeated_columns) { QString suffix = "_"; suffix += QString::number(index).rightJustified(2, '0'); @@ -225,20 +219,21 @@ void DataLoadCSV::parseHeader(QFile& file, } } - for(const auto& name: column_names) + for (const auto& name : column_names) { - _ui->listWidgetSeries->addItem( QString::fromStdString(name) ); + _ui->listWidgetSeries->addItem(QString::fromStdString(name)); } int linecount = 1; while (!inA.atEnd()) { auto line = inA.readLine(); - if( linecount++ < 100 ) + if (linecount++ < 100) { preview_lines += line + "\n"; } - else{ + else + { break; } } @@ -247,16 +242,19 @@ void DataLoadCSV::parseHeader(QFile& file, file.close(); } -int DataLoadCSV::launchDialog(QFile &file, std::vector *column_names) +int DataLoadCSV::launchDialog(QFile& file, std::vector* column_names) { column_names->clear(); QSettings settings; _dialog->restoreGeometry(settings.value("DataLoadCSV.geometry").toByteArray()); - _ui->radioButtonIndex->setChecked( settings.value("DataLoadCSV.useIndex", false).toBool() ); - _ui->checkBoxDateFormat->setChecked( settings.value("DataLoadCSV.useDateFormat", false).toBool() ); - _ui->lineEditDateFormat->setText( settings.value("DataLoadCSV.dateFormat","yyyy-MM-dd hh:mm:ss").toString() ); + _ui->radioButtonIndex->setChecked( + settings.value("DataLoadCSV.useIndex", false).toBool()); + _ui->checkBoxDateFormat->setChecked( + settings.value("DataLoadCSV.useDateFormat", false).toBool()); + _ui->lineEditDateFormat->setText( + settings.value("DataLoadCSV.dateFormat", "yyyy-MM-dd hh:mm:ss").toString()); // suggest separator { @@ -268,38 +266,43 @@ int DataLoadCSV::launchDialog(QFile &file, std::vector *column_name int semicolon_count = first_line.count(QLatin1Char(';')); int space_count = first_line.count(QLatin1Char(' ')); - if( comma_count > 3 && comma_count > semicolon_count ) + if (comma_count > 3 && comma_count > semicolon_count) { - _ui->comboBox->setCurrentIndex( 0 ); + _ui->comboBox->setCurrentIndex(0); _separator = ','; } - if( semicolon_count > 3 && semicolon_count > comma_count ) + if (semicolon_count > 3 && semicolon_count > comma_count) { - _ui->comboBox->setCurrentIndex( 1 ); + _ui->comboBox->setCurrentIndex(1); _separator = ';'; } - if( space_count > 3 && comma_count == 0 && semicolon_count == 0 ) + if (space_count > 3 && comma_count == 0 && semicolon_count == 0) { - _ui->comboBox->setCurrentIndex( 2 ); + _ui->comboBox->setCurrentIndex(2); _separator = ' '; } file.close(); } // temporaryy connection - std::unique_ptr pcontext (new QObject); - QObject *context = pcontext.get(); - QObject::connect( _ui->comboBox, qOverload( &QComboBox::currentIndexChanged ), - context, [&](int index) - { - switch( index ) - { - case 0: _separator = ','; break; - case 1: _separator = ';'; break; - case 2: _separator = ' '; break; - } - parseHeader( file, *column_names ); - }); + std::unique_ptr pcontext(new QObject); + QObject* context = pcontext.get(); + QObject::connect(_ui->comboBox, qOverload(&QComboBox::currentIndexChanged), + context, [&](int index) { + switch (index) + { + case 0: + _separator = ','; + break; + case 1: + _separator = ';'; + break; + case 2: + _separator = ' '; + break; + } + parseHeader(file, *column_names); + }); // parse the header once and launch the dialog parseHeader(file, *column_names); @@ -307,22 +310,22 @@ int DataLoadCSV::launchDialog(QFile &file, std::vector *column_name int res = _dialog->exec(); settings.setValue("DataLoadCSV.geometry", _dialog->saveGeometry()); - settings.setValue("DataLoadCSV.useIndex", _ui->radioButtonIndex->isChecked() ); - settings.setValue("DataLoadCSV.useDateFormat", _ui->checkBoxDateFormat->isChecked() ); - settings.setValue("DataLoadCSV.dateFormat", _ui->lineEditDateFormat->text() ); + settings.setValue("DataLoadCSV.useIndex", _ui->radioButtonIndex->isChecked()); + settings.setValue("DataLoadCSV.useDateFormat", _ui->checkBoxDateFormat->isChecked()); + settings.setValue("DataLoadCSV.dateFormat", _ui->lineEditDateFormat->text()); if (res == QDialog::Rejected) { return TIME_INDEX_NOT_DEFINED; } - if( _ui->radioButtonIndex->isChecked() ) + if (_ui->radioButtonIndex->isChecked()) { return TIME_INDEX_GENERATED; } QModelIndexList indexes = _ui->listWidgetSeries->selectionModel()->selectedIndexes(); - if( indexes.size() == 1) + if (indexes.size() == 1) { return indexes.front().row(); } @@ -343,26 +346,27 @@ bool DataLoadCSV::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data xmlLoadState(info->plugin_config.firstChildElement()); } - QFile file( info->filename); + QFile file(info->filename); std::vector column_names; int time_index = TIME_INDEX_NOT_DEFINED; - if( !use_provided_configuration ) + if (!use_provided_configuration) { - time_index = launchDialog( file, &column_names ); + time_index = launchDialog(file, &column_names); } else { - parseHeader(file, column_names ); + parseHeader(file, column_names); if (_default_time_axis == "__TIME_INDEX_GENERATED__") { time_index = TIME_INDEX_GENERATED; } - else{ - for( size_t i=0; icheckBoxDateFormat->isChecked(); QString format_string = _ui->lineEditDateFormat->text(); - auto ParseNumber = [&](QString str, bool& is_number) - { + auto ParseNumber = [&](QString str, bool& is_number) { double val = str.trimmed().toDouble(&is_number); - if( !is_number && parse_date_format && !format_string.isEmpty() ) { + if (!is_number && parse_date_format && !format_string.isEmpty()) + { QDateTime ts = QDateTime::fromString(str, format_string); is_number = ts.isValid(); - if( is_number ) + if (is_number) { - val = ts.toMSecsSinceEpoch()/1000.0; + val = ts.toMSecsSinceEpoch() / 1000.0; } } return val; @@ -443,18 +447,18 @@ bool DataLoadCSV::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data while (!in.atEnd()) { QString line = in.readLine(); - QStringList string_items = SplitLine( line, _separator ); + QStringList string_items = SplitLine(line, _separator); if (string_items.size() != column_names.size()) { auto err_msg = QString("The number of values at line %1 is %2,\n" "but the expected number of columns is %3.\n" "Aborting...") - .arg(linecount+1) - .arg(string_items.size()) - .arg(column_names.size()); + .arg(linecount + 1) + .arg(string_items.size()) + .arg(column_names.size()); - QMessageBox::warning(nullptr, "Error reading file", err_msg ); + QMessageBox::warning(nullptr, "Error reading file", err_msg); return false; } @@ -464,14 +468,15 @@ bool DataLoadCSV::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data { bool is_number = false; QString str = string_items[time_index]; - t = ParseNumber ( str, is_number ); + t = ParseNumber(str, is_number); if (!is_number) { - QMessageBox::StandardButton reply; - reply = QMessageBox::warning(nullptr, tr("Error reading file"), - tr("Couldn't parse timestamp with string \"%1\" . Aborting.\n").arg(str) ); - return false; + QMessageBox::StandardButton reply; + reply = QMessageBox::warning( + nullptr, tr("Error reading file"), + tr("Couldn't parse timestamp with string \"%1\" . Aborting.\n").arg(str)); + return false; } if (prev_time > t) @@ -490,13 +495,14 @@ bool DataLoadCSV::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data { bool is_number = false; const auto& str = string_items[i]; - double y = ParseNumber( str, is_number); + double y = ParseNumber(str, is_number); if (is_number) { - plots_vector[i]->pushBack( {t, y} ); + plots_vector[i]->pushBack({ t, y }); } - else{ - string_vector[i]->pushBack( {t, str.toStdString()} ); + else + { + string_vector[i]->pushBack({ t, str.toStdString() }); } } @@ -518,8 +524,9 @@ bool DataLoadCSV::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data plot_data.clear(); } - if( time_index >= 0){ - _default_time_axis = column_names[ time_index ]; + if (time_index >= 0) + { + _default_time_axis = column_names[time_index]; } // cleanups @@ -527,30 +534,30 @@ bool DataLoadCSV::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data { const auto& name = column_names[i]; bool is_numeric = true; - if( plots_vector[i]->size() == 0 && string_vector[i]->size() > 0 ) + if (plots_vector[i]->size() == 0 && string_vector[i]->size() > 0) { is_numeric = false; } - if( is_numeric ) + if (is_numeric) { - plot_data.strings.erase( plot_data.strings.find(name) ); + plot_data.strings.erase(plot_data.strings.find(name)); } - else{ - plot_data.numeric.erase( plot_data.numeric.find(name) ); + else + { + plot_data.numeric.erase(plot_data.numeric.find(name)); } } return true; } - bool DataLoadCSV::xmlSaveState(QDomDocument& doc, QDomElement& parent_element) const { QDomElement elem = doc.createElement("default"); elem.setAttribute("time_axis", _default_time_axis.c_str()); QString date_format; - if( _ui->checkBoxDateFormat->isChecked() ) + if (_ui->checkBoxDateFormat->isChecked()) { - elem.setAttribute("date_format", _ui->lineEditDateFormat->text() ); + elem.setAttribute("date_format", _ui->lineEditDateFormat->text()); } parent_element.appendChild(elem); @@ -568,8 +575,8 @@ bool DataLoadCSV::xmlLoadState(const QDomElement& parent_element) } if (elem.hasAttribute("date_format")) { - _ui->checkBoxDateFormat->setChecked( true ); - _ui->lineEditDateFormat->setText( elem.attribute("date_format") ); + _ui->checkBoxDateFormat->setChecked(true); + _ui->lineEditDateFormat->setText(elem.attribute("date_format")); } } return true; diff --git a/plotjuggler_plugins/DataLoadCSV/dataload_csv.h b/plotjuggler_plugins/DataLoadCSV/dataload_csv.h index cc90c04b7..2650fe2dd 100644 --- a/plotjuggler_plugins/DataLoadCSV/dataload_csv.h +++ b/plotjuggler_plugins/DataLoadCSV/dataload_csv.h @@ -27,16 +27,15 @@ class DataLoadCSV : public DataLoader return "DataLoad CSV"; } - virtual bool xmlSaveState(QDomDocument& doc, QDomElement& parent_element) const override; + virtual bool xmlSaveState(QDomDocument& doc, + QDomElement& parent_element) const override; virtual bool xmlLoadState(const QDomElement& parent_element) override; protected: - void parseHeader(QFile &file, - std::vector &ordered_names); + void parseHeader(QFile& file, std::vector& ordered_names); - int launchDialog(QFile &file, - std::vector *ordered_names); + int launchDialog(QFile& file, std::vector* ordered_names); private: std::vector _extensions; @@ -50,5 +49,3 @@ class DataLoadCSV : public DataLoader bool multiple_columns_warning_ = true; }; - - diff --git a/plotjuggler_plugins/DataLoadULog/dataload_ulog.cpp b/plotjuggler_plugins/DataLoadULog/dataload_ulog.cpp index b657eebcc..d1ed02964 100644 --- a/plotjuggler_plugins/DataLoadULog/dataload_ulog.cpp +++ b/plotjuggler_plugins/DataLoadULog/dataload_ulog.cpp @@ -29,7 +29,8 @@ const std::vector& DataLoadULog::compatibleFileExtensions() const return extensions; } -bool DataLoadULog::readDataFromFile(FileLoadInfo* fileload_info, PlotDataMapRef& plot_data) +bool DataLoadULog::readDataFromFile(FileLoadInfo* fileload_info, + PlotDataMapRef& plot_data) { const auto& filename = fileload_info->filename; @@ -40,7 +41,7 @@ bool DataLoadULog::readDataFromFile(FileLoadInfo* fileload_info, PlotDataMapRef& throw std::runtime_error("ULog: Failed to open file"); } QByteArray file_array = file.readAll(); - ULogParser::DataStream datastream( file_array.data(), file_array.size() ); + ULogParser::DataStream datastream(file_array.data(), file_array.size()); ULogParser parser(datastream); diff --git a/plotjuggler_plugins/DataLoadULog/dataload_ulog.h b/plotjuggler_plugins/DataLoadULog/dataload_ulog.h index 06a05f255..6c3382d8d 100644 --- a/plotjuggler_plugins/DataLoadULog/dataload_ulog.h +++ b/plotjuggler_plugins/DataLoadULog/dataload_ulog.h @@ -36,4 +36,3 @@ class DataLoadULog : public PJ::DataLoader std::string _default_time_axis; QWidget* _main_win; }; - diff --git a/plotjuggler_plugins/DataLoadULog/ulog_messages.h b/plotjuggler_plugins/DataLoadULog/ulog_messages.h index 0373d7a09..afde3d11f 100644 --- a/plotjuggler_plugins/DataLoadULog/ulog_messages.h +++ b/plotjuggler_plugins/DataLoadULog/ulog_messages.h @@ -35,157 +35,176 @@ #include -enum class ULogMessageType : uint8_t { - FORMAT = 'F', - DATA = 'D', - INFO = 'I', - INFO_MULTIPLE = 'M', - PARAMETER = 'P', - PARAMETER_DEFAULT = 'Q', - ADD_LOGGED_MSG = 'A', - REMOVE_LOGGED_MSG = 'R', - SYNC = 'S', - DROPOUT = 'O', - LOGGING = 'L', - LOGGING_TAGGED = 'C', - FLAG_BITS = 'B', +enum class ULogMessageType : uint8_t +{ + FORMAT = 'F', + DATA = 'D', + INFO = 'I', + INFO_MULTIPLE = 'M', + PARAMETER = 'P', + PARAMETER_DEFAULT = 'Q', + ADD_LOGGED_MSG = 'A', + REMOVE_LOGGED_MSG = 'R', + SYNC = 'S', + DROPOUT = 'O', + LOGGING = 'L', + LOGGING_TAGGED = 'C', + FLAG_BITS = 'B', }; - /* declare message data structs with byte alignment (no padding) */ #pragma pack(push, 1) /** first bytes of the file */ -struct ulog_file_header_s { - uint8_t magic[8]; - uint64_t timestamp; +struct ulog_file_header_s +{ + uint8_t magic[8]; + uint64_t timestamp; }; -#define ULOG_MSG_HEADER_LEN 3 //accounts for msg_size and msg_type -struct ulog_message_header_s { - uint16_t msg_size; - uint8_t msg_type; +#define ULOG_MSG_HEADER_LEN 3 // accounts for msg_size and msg_type +struct ulog_message_header_s +{ + uint16_t msg_size; + uint8_t msg_type; }; -struct ulog_message_format_s { - uint16_t msg_size; //size of message - ULOG_MSG_HEADER_LEN - uint8_t msg_type = static_cast(ULogMessageType::FORMAT); +struct ulog_message_format_s +{ + uint16_t msg_size; // size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::FORMAT); - char format[1500]; + char format[1500]; }; -struct ulog_message_add_logged_s { - uint16_t msg_size; //size of message - ULOG_MSG_HEADER_LEN - uint8_t msg_type = static_cast(ULogMessageType::ADD_LOGGED_MSG); +struct ulog_message_add_logged_s +{ + uint16_t msg_size; // size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::ADD_LOGGED_MSG); - uint8_t multi_id; - uint16_t msg_id; - char message_name[255]; + uint8_t multi_id; + uint16_t msg_id; + char message_name[255]; }; -struct ulog_message_remove_logged_s { - uint16_t msg_size; //size of message - ULOG_MSG_HEADER_LEN - uint8_t msg_type = static_cast(ULogMessageType::REMOVE_LOGGED_MSG); +struct ulog_message_remove_logged_s +{ + uint16_t msg_size; // size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::REMOVE_LOGGED_MSG); - uint16_t msg_id; + uint16_t msg_id; }; -struct ulog_message_sync_s { - uint16_t msg_size; //size of message - ULOG_MSG_HEADER_LEN - uint8_t msg_type = static_cast(ULogMessageType::SYNC); +struct ulog_message_sync_s +{ + uint16_t msg_size; // size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::SYNC); - uint8_t sync_magic[8]; + uint8_t sync_magic[8]; }; -struct ulog_message_dropout_s { - uint16_t msg_size = sizeof(uint16_t); //size of message - ULOG_MSG_HEADER_LEN - uint8_t msg_type = static_cast(ULogMessageType::DROPOUT); +struct ulog_message_dropout_s +{ + uint16_t msg_size = sizeof(uint16_t); // size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::DROPOUT); - uint16_t duration; //in ms + uint16_t duration; // in ms }; -struct ulog_message_data_header_s { - uint16_t msg_size; //size of message - ULOG_MSG_HEADER_LEN - uint8_t msg_type = static_cast(ULogMessageType::DATA); +struct ulog_message_data_header_s +{ + uint16_t msg_size; // size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::DATA); - uint16_t msg_id; + uint16_t msg_id; }; -struct ulog_message_info_header_s { - uint16_t msg_size; //size of message - ULOG_MSG_HEADER_LEN - uint8_t msg_type = static_cast(ULogMessageType::INFO); +struct ulog_message_info_header_s +{ + uint16_t msg_size; // size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::INFO); - uint8_t key_len; - char key[255]; + uint8_t key_len; + char key[255]; }; -struct ulog_message_info_multiple_header_s { - uint16_t msg_size; //size of message - ULOG_MSG_HEADER_LEN - uint8_t msg_type = static_cast(ULogMessageType::INFO_MULTIPLE); +struct ulog_message_info_multiple_header_s +{ + uint16_t msg_size; // size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::INFO_MULTIPLE); - uint8_t is_continued; ///< can be used for arrays: set to 1, if this message is part of the previous with the same key - uint8_t key_len; - char key[255]; + uint8_t is_continued; ///< can be used for arrays: set to 1, if this message is part of + ///< the previous with the same key + uint8_t key_len; + char key[255]; }; -struct ulog_message_logging_s { - uint16_t msg_size; //size of message - ULOG_MSG_HEADER_LEN - uint8_t msg_type = static_cast(ULogMessageType::LOGGING); +struct ulog_message_logging_s +{ + uint16_t msg_size; // size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::LOGGING); - uint8_t log_level; //same levels as in the linux kernel - uint64_t timestamp; - char message[128]; //defines the maximum length of a logged message string + uint8_t log_level; // same levels as in the linux kernel + uint64_t timestamp; + char message[128]; // defines the maximum length of a logged message string }; -struct ulog_message_logging_tagged_s { - uint16_t msg_size; //size of message - ULOG_MSG_HEADER_LEN - uint8_t msg_type = static_cast(ULogMessageType::LOGGING_TAGGED); +struct ulog_message_logging_tagged_s +{ + uint16_t msg_size; // size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::LOGGING_TAGGED); - uint8_t log_level; //same levels as in the linux kernel - uint16_t tag; - uint64_t timestamp; - char message[128]; //defines the maximum length of a logged message string + uint8_t log_level; // same levels as in the linux kernel + uint16_t tag; + uint64_t timestamp; + char message[128]; // defines the maximum length of a logged message string }; -struct ulog_message_parameter_header_s { - uint16_t msg_size; - uint8_t msg_type = static_cast(ULogMessageType::PARAMETER); +struct ulog_message_parameter_header_s +{ + uint16_t msg_size; + uint8_t msg_type = static_cast(ULogMessageType::PARAMETER); - uint8_t key_len; - char key[255]; + uint8_t key_len; + char key[255]; }; -enum class ulog_parameter_default_type_t : uint8_t { - system = (1<<0), - current_setup = (1<<1) //airframe default +enum class ulog_parameter_default_type_t : uint8_t +{ + system = (1 << 0), + current_setup = (1 << 1) // airframe default }; -inline ulog_parameter_default_type_t operator|(ulog_parameter_default_type_t a, ulog_parameter_default_type_t b) +inline ulog_parameter_default_type_t operator|(ulog_parameter_default_type_t a, + ulog_parameter_default_type_t b) { - return static_cast(static_cast(a) | static_cast(b)); + return static_cast(static_cast(a) | + static_cast(b)); } -struct ulog_message_parameter_default_header_s { - uint16_t msg_size; - uint8_t msg_type = static_cast(ULogMessageType::PARAMETER_DEFAULT); +struct ulog_message_parameter_default_header_s +{ + uint16_t msg_size; + uint8_t msg_type = static_cast(ULogMessageType::PARAMETER_DEFAULT); - ulog_parameter_default_type_t default_types; - uint8_t key_len; - char key[255]; + ulog_parameter_default_type_t default_types; + uint8_t key_len; + char key[255]; }; +#define ULOG_INCOMPAT_FLAG0_DATA_APPENDED_MASK (1 << 0) -#define ULOG_INCOMPAT_FLAG0_DATA_APPENDED_MASK (1<<0) +#define ULOG_COMPAT_FLAG0_DEFAULT_PARAMETERS_MASK (1 << 0) -#define ULOG_COMPAT_FLAG0_DEFAULT_PARAMETERS_MASK (1<<0) - -struct ulog_message_flag_bits_s { - uint16_t msg_size; - uint8_t msg_type = static_cast(ULogMessageType::FLAG_BITS); +struct ulog_message_flag_bits_s +{ + uint16_t msg_size; + uint8_t msg_type = static_cast(ULogMessageType::FLAG_BITS); - uint8_t compat_flags[8]; - uint8_t incompat_flags[8]; ///< @see ULOG_INCOMPAT_FLAG_* - uint64_t appended_offsets[3]; ///< file offset(s) for appended data if ULOG_INCOMPAT_FLAG0_DATA_APPENDED_MASK is set + uint8_t compat_flags[8]; + uint8_t incompat_flags[8]; ///< @see ULOG_INCOMPAT_FLAG_* + uint64_t appended_offsets[3]; ///< file offset(s) for appended data if + ///< ULOG_INCOMPAT_FLAG0_DATA_APPENDED_MASK is set }; #pragma pack(pop) diff --git a/plotjuggler_plugins/DataLoadULog/ulog_parameters_dialog.cpp b/plotjuggler_plugins/DataLoadULog/ulog_parameters_dialog.cpp index 89d8f232f..b730d9a87 100644 --- a/plotjuggler_plugins/DataLoadULog/ulog_parameters_dialog.cpp +++ b/plotjuggler_plugins/DataLoadULog/ulog_parameters_dialog.cpp @@ -27,14 +27,17 @@ ULogParametersDialog::ULogParametersDialog(const ULogParser& parser, QWidget* pa row = 0; for (const auto& param : parser.getParameters()) { - table_params->setItem(row, 0, new QTableWidgetItem(QString::fromStdString(param.name))); + table_params->setItem(row, 0, + new QTableWidgetItem(QString::fromStdString(param.name))); if (param.val_type == ULogParser::FLOAT) { - table_params->setItem(row, 1, new QTableWidgetItem(QString::number(param.value.val_real))); + table_params->setItem(row, 1, + new QTableWidgetItem(QString::number(param.value.val_real))); } else { - table_params->setItem(row, 1, new QTableWidgetItem(QString::number(param.value.val_int))); + table_params->setItem(row, 1, + new QTableWidgetItem(QString::number(param.value.val_int))); } row++; } @@ -76,7 +79,8 @@ ULogParametersDialog::ULogParametersDialog(const ULogParser& parser, QWidget* pa default: table_logs->setItem(row, 1, new QTableWidgetItem(QString::number(log_msg.level))); } - table_logs->setItem(row, 2, new QTableWidgetItem(QString::fromStdString(log_msg.msg))); + table_logs->setItem(row, 2, + new QTableWidgetItem(QString::fromStdString(log_msg.msg))); row++; } } @@ -88,8 +92,10 @@ void ULogParametersDialog::restoreSettings() QSettings settings; restoreGeometry(settings.value("ULogParametersDialog/geometry").toByteArray()); - table_info->horizontalHeader()->restoreState(settings.value("ULogParametersDialog/info/state").toByteArray()); - table_params->horizontalHeader()->restoreState(settings.value("ULogParametersDialog/params/state").toByteArray()); + table_info->horizontalHeader()->restoreState( + settings.value("ULogParametersDialog/info/state").toByteArray()); + table_params->horizontalHeader()->restoreState( + settings.value("ULogParametersDialog/params/state").toByteArray()); table_info->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Interactive); table_info->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Interactive); @@ -105,8 +111,10 @@ ULogParametersDialog::~ULogParametersDialog() QSettings settings; settings.setValue("ULogParametersDialog/geometry", this->saveGeometry()); - settings.setValue("ULogParametersDialog/info/state", table_info->horizontalHeader()->saveState()); - settings.setValue("ULogParametersDialog/params/state", table_params->horizontalHeader()->saveState()); + settings.setValue("ULogParametersDialog/info/state", + table_info->horizontalHeader()->saveState()); + settings.setValue("ULogParametersDialog/params/state", + table_params->horizontalHeader()->saveState()); delete ui; } diff --git a/plotjuggler_plugins/DataLoadULog/ulog_parameters_dialog.h b/plotjuggler_plugins/DataLoadULog/ulog_parameters_dialog.h index d81bba9a0..7a8ce0074 100644 --- a/plotjuggler_plugins/DataLoadULog/ulog_parameters_dialog.h +++ b/plotjuggler_plugins/DataLoadULog/ulog_parameters_dialog.h @@ -23,4 +23,3 @@ class ULogParametersDialog : public QDialog private: Ui::ULogParametersDialog* ui; }; - diff --git a/plotjuggler_plugins/DataLoadULog/ulog_parser.cpp b/plotjuggler_plugins/DataLoadULog/ulog_parser.cpp index 25dc39de4..a7cdd9f34 100644 --- a/plotjuggler_plugins/DataLoadULog/ulog_parser.cpp +++ b/plotjuggler_plugins/DataLoadULog/ulog_parser.cpp @@ -10,7 +10,7 @@ using ios = std::ios; -ULogParser::ULogParser(DataStream &datastream) : _file_start_time(0) +ULogParser::ULogParser(DataStream& datastream) : _file_start_time(0) { bool ret = readFileHeader(datastream); @@ -58,8 +58,8 @@ ULogParser::ULogParser(DataStream &datastream) : _file_start_time(0) _message_name_with_multi_id.insert(sub.message_name); } - // printf("ADD_LOGGED_MSG: %d %d %s\n", sub.msg_id, sub.multi_id, sub.message_name.c_str() ); - // std::cout << std::endl; + // printf("ADD_LOGGED_MSG: %d %d %s\n", sub.msg_id, sub.multi_id, + // sub.message_name.c_str() ); std::cout << std::endl; } break; case (int)ULogMessageType::REMOVE_LOGGED_MSG: @@ -148,7 +148,8 @@ void ULogParser::parseDataMessage(const ULogParser::Subscription& sub, char* mes parseSimpleDataMessage(timeseries, sub.format, message, &index); } -char* ULogParser::parseSimpleDataMessage(Timeseries& timeseries, const Format* format, char* message, size_t* index) +char* ULogParser::parseSimpleDataMessage(Timeseries& timeseries, const Format* format, + char* message, size_t* index) { for (const auto& field : format->fields) { @@ -297,7 +298,8 @@ size_t ULogParser::fieldsCount(const ULogParser::Format& format) const return count; } -std::vector ULogParser::splitString(const StringView& strToSplit, char delimeter) +std::vector ULogParser::splitString(const StringView& strToSplit, + char delimeter) { std::vector splitted_strings; splitted_strings.reserve(4); @@ -347,11 +349,11 @@ bool ULogParser::readFileDefinitions(DataStream& datastream) while (true) { -// qDebug() <<"\noffset before" << datastream.offset; + // qDebug() <<"\noffset before" << datastream.offset; datastream.read((char*)&message_header, ULOG_MSG_HEADER_LEN); -// qDebug() <<"msg_size" << message_header.msg_size; -// qDebug() <<"type" << char(message_header.msg_type); -// qDebug() <<"offset after" << datastream.offset; + // qDebug() <<"msg_size" << message_header.msg_size; + // qDebug() <<"type" << char(message_header.msg_type); + // qDebug() <<"offset after" << datastream.offset; if (!datastream) { @@ -395,15 +397,14 @@ bool ULogParser::readFileDefinitions(DataStream& datastream) } } break; - case (int)ULogMessageType::INFO_MULTIPLE: // skip + case (int)ULogMessageType::INFO_MULTIPLE: // skip case (int)ULogMessageType::PARAMETER_DEFAULT: // skip datastream.offset += message_header.msg_size; break; default: printf("unknown log definition type %i, size %i (offset %i)\n", - (int)message_header.msg_type, - (int)message_header.msg_size, + (int)message_header.msg_type, (int)message_header.msg_size, (int)datastream.offset); datastream.offset += message_header.msg_size; break; @@ -428,7 +429,8 @@ bool ULogParser::readFlagBits(DataStream& datastream, uint16_t msg_size) uint8_t* incompat_flags = message + 8; // handle & validate the flags - bool contains_appended_data = incompat_flags[0] & ULOG_INCOMPAT_FLAG0_DATA_APPENDED_MASK; + bool contains_appended_data = + incompat_flags[0] & ULOG_INCOMPAT_FLAG0_DATA_APPENDED_MASK; bool has_unknown_incompat_bits = false; if (incompat_flags[0] & ~0x1) @@ -457,7 +459,8 @@ bool ULogParser::readFlagBits(DataStream& datastream, uint16_t msg_size) if (appended_offsets[0] > 0) { - // the appended data is currently only used for hardfault dumps, so it's safe to ignore it. + // the appended data is currently only used for hardfault dumps, so it's safe to + // ignore it. // LOG_INFO("Log contains appended data. Replay will ignore this data" ); _read_until_file_position = appended_offsets[0]; } @@ -767,7 +770,8 @@ ULogParser::Timeseries ULogParser::createTimeseries(const ULogParser::Format* fo Timeseries timeseries; - appendVector = [&appendVector, this, ×eries](const Format& format, const std::string& prefix) { + appendVector = [&appendVector, this, ×eries](const Format& format, + const std::string& prefix) { for (const auto& field : format.fields) { // skip padding messages diff --git a/plotjuggler_plugins/DataLoadULog/ulog_parser.h b/plotjuggler_plugins/DataLoadULog/ulog_parser.h index b38ca5ae6..8fa0e3701 100644 --- a/plotjuggler_plugins/DataLoadULog/ulog_parser.h +++ b/plotjuggler_plugins/DataLoadULog/ulog_parser.h @@ -19,10 +19,9 @@ class ULogParser const size_t _length; size_t offset; - DataStream(char* data, int len): - _data(data), - _length(len), - offset(0) {} + DataStream(char* data, int len) : _data(data), _length(len), offset(0) + { + } void read(char* dst, int len) { @@ -30,7 +29,8 @@ class ULogParser offset += len; } - operator bool() { + operator bool() + { return offset < _length; } }; @@ -110,7 +110,7 @@ class ULogParser }; public: - ULogParser(DataStream &datastream); + ULogParser(DataStream& datastream); const std::map& getTimeseriesMap() const; @@ -121,7 +121,6 @@ class ULogParser const std::vector& getLogs() const; private: - bool readFileHeader(DataStream& datastream); bool readFileDefinitions(DataStream& datastream); @@ -148,7 +147,8 @@ class ULogParser std::streampos _data_section_start; ///< first ADD_LOGGED_MSG message - int64_t _read_until_file_position = 1ULL << 60; ///< read limit if log contains appended data + int64_t _read_until_file_position = + 1ULL << 60; ///< read limit if log contains appended data std::set _overridden_params; @@ -168,6 +168,6 @@ class ULogParser void parseDataMessage(const Subscription& sub, char* message); - char* parseSimpleDataMessage(Timeseries& timeseries, const Format* format, char* message, size_t* index); + char* parseSimpleDataMessage(Timeseries& timeseries, const Format* format, + char* message, size_t* index); }; - diff --git a/plotjuggler_plugins/DataStreamSample/datastream_sample.cpp b/plotjuggler_plugins/DataStreamSample/datastream_sample.cpp index 4738d85f4..b0202debb 100644 --- a/plotjuggler_plugins/DataStreamSample/datastream_sample.cpp +++ b/plotjuggler_plugins/DataStreamSample/datastream_sample.cpp @@ -15,20 +15,17 @@ DataStreamSample::DataStreamSample() { _dummy_notification = new QAction(this); - connect( _dummy_notification, &QAction::triggered, - this, [this]() - { - QMessageBox::warning( - nullptr, "Dummy Notifications", - QString("%1 notifications").arg(_notifications_count), - QMessageBox::Ok); - - if( _notifications_count > 0 ) - { - _notifications_count = 0; - emit notificationsChanged(_notifications_count); - } - }); + connect(_dummy_notification, &QAction::triggered, this, [this]() { + QMessageBox::warning(nullptr, "Dummy Notifications", + QString("%1 notifications").arg(_notifications_count), + QMessageBox::Ok); + + if (_notifications_count > 0) + { + _notifications_count = 0; + emit notificationsChanged(_notifications_count); + } + }); _notifications_count = 0; for (int i = 0; i < 150; i++) @@ -39,10 +36,11 @@ DataStreamSample::DataStreamSample() param.B = 3 * ((double)rand() / (double)RAND_MAX); param.C = 3 * ((double)rand() / (double)RAND_MAX); param.D = 20 * ((double)rand() / (double)RAND_MAX); - _parameters.insert({str, param}); + _parameters.insert({ str, param }); auto& plotdata = dataMap().addNumeric(str)->second; - if( i%5 == 0 ) { + if (i % 5 == 0) + { plotdata.setAttribute("label_color", "red"); } } @@ -51,13 +49,12 @@ DataStreamSample::DataStreamSample() //------------ auto tcGroup = std::make_shared("tc"); - tcGroup->setAttribute("text_color", QColor(Qt::blue) ); + tcGroup->setAttribute("text_color", QColor(Qt::blue)); auto& tc_default = dataMap().addNumeric("tc/default")->second; auto& tc_red = dataMap().addNumeric("tc/red")->second; - tc_red.setAttribute("text_color", QColor(Qt::red) ); - + tc_red.setAttribute("text_color", QColor(Qt::red)); } bool DataStreamSample::start(QStringList*) @@ -71,7 +68,8 @@ bool DataStreamSample::start(QStringList*) void DataStreamSample::shutdown() { _running = false; - if (_thread.joinable()){ + if (_thread.joinable()) + { _thread.join(); } } @@ -103,30 +101,32 @@ void DataStreamSample::pushSingleCycle() using namespace std::chrono; static auto initial_time = high_resolution_clock::now(); - const double offset = duration_cast>(initial_time.time_since_epoch()).count(); + const double offset = + duration_cast>(initial_time.time_since_epoch()).count(); auto now = high_resolution_clock::now(); - std::string colors[]= { "RED", "BLUE", "GREEN" }; + std::string colors[] = { "RED", "BLUE", "GREEN" }; - const double stamp = duration_cast>(now - initial_time).count() + offset; + const double stamp = + duration_cast>(now - initial_time).count() + offset; for (auto& it : _parameters) { auto& plot = dataMap().numeric.find(it.first)->second; const DataStreamSample::Parameters& param = it.second; - double val = param.A*sin( param.B*stamp + param.C ) + param.D; - plot.pushBack( PlotData::Point(stamp, val) ); + double val = param.A * sin(param.B * stamp + param.C) + param.D; + plot.pushBack(PlotData::Point(stamp, val)); } auto& col_series = dataMap().strings.find("color")->second; - col_series.pushBack( { stamp, colors[ (count/10) % 3]}); + col_series.pushBack({ stamp, colors[(count / 10) % 3] }); auto& tc_default = dataMap().numeric.find("tc/default")->second; - tc_default.pushBack( { stamp, double(count) }); + tc_default.pushBack({ stamp, double(count) }); auto& tc_red = dataMap().numeric.find("tc/red")->second; - tc_red.pushBack( { stamp, double(count) }); + tc_red.pushBack({ stamp, double(count) }); count++; } @@ -140,7 +140,7 @@ void DataStreamSample::loop() auto prev = std::chrono::high_resolution_clock::now(); pushSingleCycle(); emit dataReceived(); - if( count++ % 200 == 0 ) + if (count++ % 200 == 0) { _notifications_count++; emit notificationsChanged(_notifications_count); diff --git a/plotjuggler_plugins/DataStreamSample/datastream_sample.h b/plotjuggler_plugins/DataStreamSample/datastream_sample.h index 9cd1fe463..45d621143 100644 --- a/plotjuggler_plugins/DataStreamSample/datastream_sample.h +++ b/plotjuggler_plugins/DataStreamSample/datastream_sample.h @@ -31,17 +31,17 @@ class DataStreamSample : public PJ::DataStreamer return true; } - virtual bool xmlSaveState(QDomDocument& doc, QDomElement& parent_element) const override; + virtual bool xmlSaveState(QDomDocument& doc, + QDomElement& parent_element) const override; virtual bool xmlLoadState(const QDomElement& parent_element) override; std::pair notificationAction() override { - return {_dummy_notification, _notifications_count}; + return { _dummy_notification, _notifications_count }; } private: - struct Parameters { double A, B, C, D; @@ -61,4 +61,3 @@ class DataStreamSample : public PJ::DataStreamer int _notifications_count; }; - diff --git a/plotjuggler_plugins/DataStreamUDP/udp_server.cpp b/plotjuggler_plugins/DataStreamUDP/udp_server.cpp index 730b3c8e7..af4e1b016 100644 --- a/plotjuggler_plugins/DataStreamUDP/udp_server.cpp +++ b/plotjuggler_plugins/DataStreamUDP/udp_server.cpp @@ -2,15 +2,18 @@ Copyright(C) 2018 Philippe Gauthier - ISIR - UPMC Copyright(C) 2020 Davide Faconti -Permission is hereby granted to any person obtaining a copy of this software and associated documentation files(the -"Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, -merge, publish, distribute, sublicense, and / or sell copies("Use") of the Software, and to permit persons to whom the -Software is furnished to do so. The above copyright notice and this permission notice shall be included in all copies or -substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE -OR OTHER DEALINGS IN THE SOFTWARE. +Permission is hereby granted to any person obtaining a copy of this software and +associated documentation files(the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and / or sell copies("Use") of the Software, and to permit persons +to whom the Software is furnished to do so. The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. THE +SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. */ #include "udp_server.h" #include @@ -28,25 +31,21 @@ OR OTHER DEALINGS IN THE SOFTWARE. #include "ui_udp_server.h" -class UdpServerDialog: public QDialog +class UdpServerDialog : public QDialog { public: - UdpServerDialog(): - QDialog(nullptr), - ui(new Ui::UDPServerDialog) + UdpServerDialog() : QDialog(nullptr), ui(new Ui::UDPServerDialog) { ui->setupUi(this); - ui->lineEditPort->setValidator( new QIntValidator() ); + ui->lineEditPort->setValidator(new QIntValidator()); setWindowTitle("UDP Server"); - connect( ui->buttonBox, &QDialogButtonBox::accepted, - this, &QDialog::accept ); - connect( ui->buttonBox, &QDialogButtonBox::rejected, - this, &QDialog::reject ); + connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); } ~UdpServerDialog() { - while( ui->layoutOptions->count() > 0) + while (ui->layoutOptions->count() > 0) { auto item = ui->layoutOptions->takeAt(0); item->widget()->setParent(nullptr); @@ -56,8 +55,7 @@ class UdpServerDialog: public QDialog Ui::UDPServerDialog* ui; }; -UDP_Server::UDP_Server() : - _running(false) +UDP_Server::UDP_Server() : _running(false) { } @@ -73,9 +71,10 @@ bool UDP_Server::start(QStringList*) return _running; } - if( !availableParsers() ) + if (!availableParsers()) { - QMessageBox::warning(nullptr,tr("UDP Server"), tr("No available MessageParsers"), QMessageBox::Ok); + QMessageBox::warning(nullptr, tr("UDP Server"), tr("No available MessageParsers"), + QMessageBox::Ok); _running = false; return false; } @@ -84,14 +83,14 @@ bool UDP_Server::start(QStringList*) UdpServerDialog dialog; - for( const auto& it: *availableParsers()) + for (const auto& it : *availableParsers()) { - dialog.ui->comboBoxProtocol->addItem( it.first ); + dialog.ui->comboBoxProtocol->addItem(it.first); - if(auto widget = it.second->optionsWidget() ) + if (auto widget = it.second->optionsWidget()) { widget->setVisible(false); - dialog.ui->layoutOptions->addWidget( widget ); + dialog.ui->layoutOptions->addWidget(widget); } } @@ -100,28 +99,29 @@ bool UDP_Server::start(QStringList*) QString protocol = settings.value("UDP_Server::protocol", "JSON").toString(); int port = settings.value("UDP_Server::port", 9870).toInt(); - dialog.ui->lineEditPort->setText( QString::number(port) ); + dialog.ui->lineEditPort->setText(QString::number(port)); std::shared_ptr parser_creator; - connect(dialog.ui->comboBoxProtocol, qOverload( &QComboBox::currentIndexChanged), this, - [&](int) - { - if( parser_creator ){ - QWidget* prev_widget = parser_creator->optionsWidget(); - prev_widget->setVisible(false); - } - parser_creator = availableParsers()->at( protocol ); - - if(auto widget = parser_creator->optionsWidget() ){ - widget->setVisible(true); - } - }); + connect(dialog.ui->comboBoxProtocol, qOverload(&QComboBox::currentIndexChanged), + this, [&](int) { + if (parser_creator) + { + QWidget* prev_widget = parser_creator->optionsWidget(); + prev_widget->setVisible(false); + } + parser_creator = availableParsers()->at(protocol); + + if (auto widget = parser_creator->optionsWidget()) + { + widget->setVisible(true); + } + }); dialog.ui->comboBoxProtocol->setCurrentText(protocol); int res = dialog.exec(); - if( res == QDialog::Rejected ) + if (res == QDialog::Rejected) { _running = false; return false; @@ -139,19 +139,17 @@ bool UDP_Server::start(QStringList*) _udp_socket = new QUdpSocket(); _udp_socket->bind(QHostAddress::Any, port); - connect(_udp_socket, &QUdpSocket::readyRead, - this, &UDP_Server::processMessage); + connect(_udp_socket, &QUdpSocket::readyRead, this, &UDP_Server::processMessage); - if ( _udp_socket ) + if (_udp_socket) { qDebug() << "UDP listening on port" << port; _running = true; } else { - QMessageBox::warning(nullptr,tr("UDP Server"), - tr("Couldn't bind UDP port %1").arg(port), - QMessageBox::Ok); + QMessageBox::warning(nullptr, tr("UDP Server"), + tr("Couldn't bind UDP port %1").arg(port), QMessageBox::Ok); _running = false; } @@ -169,27 +167,29 @@ void UDP_Server::shutdown() void UDP_Server::processMessage() { - while (_udp_socket->hasPendingDatagrams()) { - + while (_udp_socket->hasPendingDatagrams()) + { QNetworkDatagram datagram = _udp_socket->receiveDatagram(); - using namespace std::chrono; auto ts = high_resolution_clock::now().time_since_epoch(); - double timestamp = 1e-6* double( duration_cast(ts).count() ); + double timestamp = 1e-6 * double(duration_cast(ts).count()); QByteArray m = datagram.data(); - MessageRef msg ( reinterpret_cast(m.data()), m.count() ); + MessageRef msg(reinterpret_cast(m.data()), m.count()); - try { + try + { std::lock_guard lock(mutex()); // important use the mutex to protect any access to the data _parser->parseMessage(msg, timestamp); - } catch (std::exception& err) + } + catch (std::exception& err) { - QMessageBox::warning(nullptr, - tr("UDP Server"), - tr("Problem parsing the message. UDP Server will be stopped.\n%1").arg(err.what()), + QMessageBox::warning(nullptr, tr("UDP Server"), + tr("Problem parsing the message. UDP Server will be " + "stopped.\n%1") + .arg(err.what()), QMessageBox::Ok); shutdown(); // notify the GUI @@ -201,4 +201,3 @@ void UDP_Server::processMessage() emit dataReceived(); return; } - diff --git a/plotjuggler_plugins/DataStreamUDP/udp_server.h b/plotjuggler_plugins/DataStreamUDP/udp_server.h index 2b5a78c2a..0a3046d1d 100644 --- a/plotjuggler_plugins/DataStreamUDP/udp_server.h +++ b/plotjuggler_plugins/DataStreamUDP/udp_server.h @@ -1,15 +1,18 @@ /*DataStreamServer PlotJuggler Plugin license(Faircode) Copyright(C) 2018 Philippe Gauthier - ISIR - UPMC -Permission is hereby granted to any person obtaining a copy of this software and associated documentation files(the -"Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, -merge, publish, distribute, sublicense, and / or sell copies("Use") of the Software, and to permit persons to whom the -Software is furnished to do so. The above copyright notice and this permission notice shall be included in all copies or -substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE -OR OTHER DEALINGS IN THE SOFTWARE. +Permission is hereby granted to any person obtaining a copy of this software and +associated documentation files(the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and / or sell copies("Use") of the Software, and to permit persons +to whom the Software is furnished to do so. The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. THE +SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. */ #pragma once @@ -60,5 +63,3 @@ private slots: void processMessage(); }; - - diff --git a/plotjuggler_plugins/DataStreamWebsocket/websocket_server.cpp b/plotjuggler_plugins/DataStreamWebsocket/websocket_server.cpp index ef7be613d..2bce22df4 100644 --- a/plotjuggler_plugins/DataStreamWebsocket/websocket_server.cpp +++ b/plotjuggler_plugins/DataStreamWebsocket/websocket_server.cpp @@ -2,15 +2,18 @@ Copyright(C) 2018 Philippe Gauthier - ISIR - UPMC Copyright(C) 2020 Davide Faconti -Permission is hereby granted to any person obtaining a copy of this software and associated documentation files(the -"Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, -merge, publish, distribute, sublicense, and / or sell copies("Use") of the Software, and to permit persons to whom the -Software is furnished to do so. The above copyright notice and this permission notice shall be included in all copies or -substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE -OR OTHER DEALINGS IN THE SOFTWARE. +Permission is hereby granted to any person obtaining a copy of this software and +associated documentation files(the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and / or sell copies("Use") of the Software, and to permit persons +to whom the Software is furnished to do so. The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. THE +SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. */ #include "websocket_server.h" #include @@ -27,25 +30,21 @@ OR OTHER DEALINGS IN THE SOFTWARE. #include "ui_websocket_server.h" -class WebsocketDialog: public QDialog +class WebsocketDialog : public QDialog { public: - WebsocketDialog(): - QDialog(nullptr), - ui(new Ui::WebSocketDialog) + WebsocketDialog() : QDialog(nullptr), ui(new Ui::WebSocketDialog) { ui->setupUi(this); - ui->lineEditPort->setValidator( new QIntValidator() ); + ui->lineEditPort->setValidator(new QIntValidator()); setWindowTitle("WebSocket Server"); - connect( ui->buttonBox, &QDialogButtonBox::accepted, - this, &QDialog::accept ); - connect( ui->buttonBox, &QDialogButtonBox::rejected, - this, &QDialog::reject ); + connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); } ~WebsocketDialog() { - while( ui->layoutOptions->count() > 0) + while (ui->layoutOptions->count() > 0) { auto item = ui->layoutOptions->takeAt(0); item->widget()->setParent(nullptr); @@ -55,12 +54,11 @@ class WebsocketDialog: public QDialog Ui::WebSocketDialog* ui; }; -WebsocketServer::WebsocketServer() : - _running(false), - _server("plotJuggler", QWebSocketServer::NonSecureMode) +WebsocketServer::WebsocketServer() + : _running(false), _server("plotJuggler", QWebSocketServer::NonSecureMode) { - connect(&_server, &QWebSocketServer::newConnection, - this, &WebsocketServer::onNewConnection); + connect(&_server, &QWebSocketServer::newConnection, this, + &WebsocketServer::onNewConnection); } WebsocketServer::~WebsocketServer() @@ -75,9 +73,10 @@ bool WebsocketServer::start(QStringList*) return _running; } - if( !availableParsers() ) + if (!availableParsers()) { - QMessageBox::warning(nullptr,tr("Websocket Server"), tr("No available MessageParsers"), QMessageBox::Ok); + QMessageBox::warning(nullptr, tr("Websocket Server"), + tr("No available MessageParsers"), QMessageBox::Ok); _running = false; return false; } @@ -86,14 +85,14 @@ bool WebsocketServer::start(QStringList*) WebsocketDialog* dialog = new WebsocketDialog(); - for( const auto& it: *availableParsers()) + for (const auto& it : *availableParsers()) { - dialog->ui->comboBoxProtocol->addItem( it.first ); + dialog->ui->comboBoxProtocol->addItem(it.first); - if(auto widget = it.second->optionsWidget() ) + if (auto widget = it.second->optionsWidget()) { widget->setVisible(false); - dialog->ui->layoutOptions->addWidget( widget ); + dialog->ui->layoutOptions->addWidget(widget); } } @@ -102,29 +101,30 @@ bool WebsocketServer::start(QStringList*) QString protocol = settings.value("WebsocketServer::protocol", "JSON").toString(); int port = settings.value("WebsocketServer::port", 9871).toInt(); - dialog->ui->lineEditPort->setText( QString::number(port) ); + dialog->ui->lineEditPort->setText(QString::number(port)); std::shared_ptr parser_creator; - connect(dialog->ui->comboBoxProtocol, qOverload( &QComboBox::currentIndexChanged), this, - [&](int index) - { - if( parser_creator ){ - QWidget* prev_widget = parser_creator->optionsWidget(); - prev_widget->setVisible(false); - } - QString protocol = dialog->ui->comboBoxProtocol->itemText(index); - parser_creator = availableParsers()->at( protocol ); - - if(auto widget = parser_creator->optionsWidget() ){ - widget->setVisible(true); - } - }); + connect(dialog->ui->comboBoxProtocol, qOverload(&QComboBox::currentIndexChanged), + this, [&](int index) { + if (parser_creator) + { + QWidget* prev_widget = parser_creator->optionsWidget(); + prev_widget->setVisible(false); + } + QString protocol = dialog->ui->comboBoxProtocol->itemText(index); + parser_creator = availableParsers()->at(protocol); + + if (auto widget = parser_creator->optionsWidget()) + { + widget->setVisible(true); + } + }); dialog->ui->comboBoxProtocol->setCurrentText(protocol); int res = dialog->exec(); - if( res == QDialog::Rejected ) + if (res == QDialog::Rejected) { _running = false; return false; @@ -140,14 +140,14 @@ bool WebsocketServer::start(QStringList*) settings.setValue("WebsocketServer::protocol", protocol); settings.setValue("WebsocketServer::port", port); - if ( _server.listen(QHostAddress::Any, port)) + if (_server.listen(QHostAddress::Any, port)) { qDebug() << "Websocket listening on port" << port; _running = true; } else { - QMessageBox::warning(nullptr,tr("Websocket Server"), + QMessageBox::warning(nullptr, tr("Websocket Server"), tr("Couldn't open websocket on port %1").arg(port), QMessageBox::Ok); _running = false; @@ -169,7 +169,8 @@ void WebsocketServer::shutdown() void WebsocketServer::onNewConnection() { QWebSocket* pSocket = _server.nextPendingConnection(); - connect(pSocket, &QWebSocket::textMessageReceived, this, &WebsocketServer::processMessage); + connect(pSocket, &QWebSocket::textMessageReceived, this, + &WebsocketServer::processMessage); connect(pSocket, &QWebSocket::disconnected, this, &WebsocketServer::socketDisconnected); _clients << pSocket; } @@ -180,18 +181,21 @@ void WebsocketServer::processMessage(QString message) using namespace std::chrono; auto ts = high_resolution_clock::now().time_since_epoch(); - double timestamp = 1e-6* double( duration_cast(ts).count() ); + double timestamp = 1e-6 * double(duration_cast(ts).count()); QByteArray bmsg = message.toLocal8Bit(); - MessageRef msg ( reinterpret_cast(bmsg.data()), bmsg.size() ); + MessageRef msg(reinterpret_cast(bmsg.data()), bmsg.size()); - try { + try + { _parser->parseMessage(msg, timestamp); - } catch (std::exception& err) + } + catch (std::exception& err) { - QMessageBox::warning(nullptr, - tr("Websocket Server"), - tr("Problem parsing the message. Websocket Server will be stopped.\n%1").arg(err.what()), + QMessageBox::warning(nullptr, tr("Websocket Server"), + tr("Problem parsing the message. Websocket Server will be " + "stopped.\n%1") + .arg(err.what()), QMessageBox::Ok); shutdown(); emit closed(); @@ -206,8 +210,10 @@ void WebsocketServer::socketDisconnected() QWebSocket* pClient = qobject_cast(sender()); if (pClient) { - disconnect(pClient, &QWebSocket::textMessageReceived, this, &WebsocketServer::processMessage); - disconnect(pClient, &QWebSocket::disconnected, this, &WebsocketServer::socketDisconnected); + disconnect(pClient, &QWebSocket::textMessageReceived, this, + &WebsocketServer::processMessage); + disconnect(pClient, &QWebSocket::disconnected, this, + &WebsocketServer::socketDisconnected); _clients.removeAll(pClient); pClient->deleteLater(); } diff --git a/plotjuggler_plugins/DataStreamWebsocket/websocket_server.h b/plotjuggler_plugins/DataStreamWebsocket/websocket_server.h index d402959b3..0a7575d98 100644 --- a/plotjuggler_plugins/DataStreamWebsocket/websocket_server.h +++ b/plotjuggler_plugins/DataStreamWebsocket/websocket_server.h @@ -1,15 +1,18 @@ /*DataStreamServer PlotJuggler Plugin license(Faircode) Copyright(C) 2018 Philippe Gauthier - ISIR - UPMC -Permission is hereby granted to any person obtaining a copy of this software and associated documentation files(the -"Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, -merge, publish, distribute, sublicense, and / or sell copies("Use") of the Software, and to permit persons to whom the -Software is furnished to do so. The above copyright notice and this permission notice shall be included in all copies or -substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE -OR OTHER DEALINGS IN THE SOFTWARE. +Permission is hereby granted to any person obtaining a copy of this software and +associated documentation files(the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and / or sell copies("Use") of the Software, and to permit persons +to whom the Software is furnished to do so. The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. THE +SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. */ #pragma once @@ -60,11 +63,8 @@ class WebsocketServer : public PJ::DataStreamer QWebSocketServer _server; PJ::MessageParserPtr _parser; - private slots: void onNewConnection(); void processMessage(QString message); void socketDisconnected(); }; - - diff --git a/plotjuggler_plugins/DataStreamZMQ/datastream_zmq.cpp b/plotjuggler_plugins/DataStreamZMQ/datastream_zmq.cpp index 6c27b0ecb..26ef63775 100644 --- a/plotjuggler_plugins/DataStreamZMQ/datastream_zmq.cpp +++ b/plotjuggler_plugins/DataStreamZMQ/datastream_zmq.cpp @@ -8,17 +8,16 @@ #include #include -StreamZMQDialog::StreamZMQDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::DataStreamZMQ) +StreamZMQDialog::StreamZMQDialog(QWidget* parent) + : QDialog(parent), ui(new Ui::DataStreamZMQ) { ui->setupUi(this); - ui->lineEditPort->setValidator( new QIntValidator() ); + ui->lineEditPort->setValidator(new QIntValidator()); } StreamZMQDialog::~StreamZMQDialog() { - while( ui->layoutOptions->count() > 0) + while (ui->layoutOptions->count() > 0) { auto item = ui->layoutOptions->takeAt(0); item->widget()->setParent(nullptr); @@ -26,10 +25,8 @@ StreamZMQDialog::~StreamZMQDialog() delete ui; } -DataStreamZMQ::DataStreamZMQ(): - _running(false), - _zmq_context(), - _zmq_socket(_zmq_context, zmq::socket_type::sub) +DataStreamZMQ::DataStreamZMQ() + : _running(false), _zmq_context(), _zmq_socket(_zmq_context, zmq::socket_type::sub) { } @@ -45,9 +42,10 @@ bool DataStreamZMQ::start(QStringList*) return _running; } - if( !availableParsers() ) + if (!availableParsers()) { - QMessageBox::warning(nullptr,tr("UDP Server"), tr("No available MessageParsers"), QMessageBox::Ok); + QMessageBox::warning(nullptr, tr("UDP Server"), tr("No available MessageParsers"), + QMessageBox::Ok); _running = false; return false; } @@ -56,14 +54,14 @@ bool DataStreamZMQ::start(QStringList*) StreamZMQDialog* dialog = new StreamZMQDialog(); - for( const auto& it: *availableParsers()) + for (const auto& it : *availableParsers()) { - dialog->ui->comboBoxProtocol->addItem( it.first ); + dialog->ui->comboBoxProtocol->addItem(it.first); - if(auto widget = it.second->optionsWidget() ) + if (auto widget = it.second->optionsWidget()) { widget->setVisible(false); - dialog->ui->layoutOptions->addWidget( widget ); + dialog->ui->layoutOptions->addWidget(widget); } } @@ -73,31 +71,31 @@ bool DataStreamZMQ::start(QStringList*) QString protocol = settings.value("ZMQ_Subscriber::protocol", "JSON").toString(); int port = settings.value("ZMQ_Subscriber::port", 9872).toInt(); - - dialog->ui->lineEditAddress->setText( address ); - dialog->ui->lineEditPort->setText( QString::number(port) ); + dialog->ui->lineEditAddress->setText(address); + dialog->ui->lineEditPort->setText(QString::number(port)); std::shared_ptr parser_creator; - connect(dialog->ui->comboBoxProtocol, qOverload( &QComboBox::currentIndexChanged), this, - [&](int index) - { - if( parser_creator ){ - QWidget* prev_widget = parser_creator->optionsWidget(); - prev_widget->setVisible(false); - } - QString protocol = dialog->ui->comboBoxProtocol->itemText(index); - parser_creator = availableParsers()->at( protocol ); - - if(auto widget = parser_creator->optionsWidget() ){ - widget->setVisible(true); - } - }); + connect(dialog->ui->comboBoxProtocol, qOverload(&QComboBox::currentIndexChanged), + this, [&](int index) { + if (parser_creator) + { + QWidget* prev_widget = parser_creator->optionsWidget(); + prev_widget->setVisible(false); + } + QString protocol = dialog->ui->comboBoxProtocol->itemText(index); + parser_creator = availableParsers()->at(protocol); + + if (auto widget = parser_creator->optionsWidget()) + { + widget->setVisible(true); + } + }); dialog->ui->comboBoxProtocol->setCurrentText(protocol); int res = dialog->exec(); - if( res == QDialog::Rejected ) + if (res == QDialog::Rejected) { _running = false; return false; @@ -115,15 +113,15 @@ bool DataStreamZMQ::start(QStringList*) settings.setValue("ZMQ_Subscriber::port", port); _socket_address = - (dialog->ui->comboBox->currentText()+ - address+ ":" + QString::number(port)).toStdString(); + (dialog->ui->comboBox->currentText() + address + ":" + QString::number(port)) + .toStdString(); - _zmq_socket.connect( _socket_address.c_str() ); + _zmq_socket.connect(_socket_address.c_str()); // subscribe to everything _zmq_socket.set(zmq::sockopt::subscribe, ""); _zmq_socket.set(zmq::sockopt::rcvtimeo, 100); - qDebug() << "ZMQ listening on address" << QString::fromStdString( _socket_address ); + qDebug() << "ZMQ listening on address" << QString::fromStdString(_socket_address); _running = true; _receive_thread = std::thread(&DataStreamZMQ::receiveLoop, this); @@ -134,46 +132,48 @@ bool DataStreamZMQ::start(QStringList*) void DataStreamZMQ::shutdown() { - if( _running ) + if (_running) { _running = false; - if( _receive_thread.joinable() ) + if (_receive_thread.joinable()) { _receive_thread.join(); } - _zmq_socket.disconnect( _socket_address.c_str() ); + _zmq_socket.disconnect(_socket_address.c_str()); _running = false; } } void DataStreamZMQ::receiveLoop() { - while( _running ) + while (_running) { zmq::message_t recv_msg; zmq::recv_result_t result = _zmq_socket.recv(recv_msg); - if( recv_msg.size() > 0 ) + if (recv_msg.size() > 0) { using namespace std::chrono; auto ts = high_resolution_clock::now().time_since_epoch(); - double timestamp = 1e-6* double( duration_cast(ts).count() ); + double timestamp = 1e-6 * double(duration_cast(ts).count()); - PJ::MessageRef msg ( reinterpret_cast(recv_msg.data()), recv_msg.size() ); + PJ::MessageRef msg(reinterpret_cast(recv_msg.data()), recv_msg.size()); - try { + try + { std::lock_guard lock(mutex()); _parser->parseMessage(msg, timestamp); emit this->dataReceived(); } catch (std::exception& err) { - QMessageBox::warning(nullptr, - tr("ZMQ Subscriber"), - tr("Problem parsing the message. ZMQ Subscriber will be stopped.\n%1").arg(err.what()), + QMessageBox::warning(nullptr, tr("ZMQ Subscriber"), + tr("Problem parsing the message. ZMQ Subscriber will be " + "stopped.\n%1") + .arg(err.what()), QMessageBox::Ok); - _zmq_socket.disconnect( _socket_address.c_str() ); + _zmq_socket.disconnect(_socket_address.c_str()); _running = false; // notify the GUI emit closed(); @@ -182,5 +182,3 @@ void DataStreamZMQ::receiveLoop() } } } - - diff --git a/plotjuggler_plugins/DataStreamZMQ/datastream_zmq.h b/plotjuggler_plugins/DataStreamZMQ/datastream_zmq.h index f860d08e6..1e459e55b 100644 --- a/plotjuggler_plugins/DataStreamZMQ/datastream_zmq.h +++ b/plotjuggler_plugins/DataStreamZMQ/datastream_zmq.h @@ -13,14 +13,12 @@ class StreamZMQDialog : public QDialog Q_OBJECT public: - explicit StreamZMQDialog(QWidget *parent = nullptr); + explicit StreamZMQDialog(QWidget* parent = nullptr); ~StreamZMQDialog(); - Ui::DataStreamZMQ *ui; - + Ui::DataStreamZMQ* ui; }; - class DataStreamZMQ : public PJ::DataStreamer { Q_OBJECT diff --git a/plotjuggler_plugins/StatePublisherCSV/publisher_csv.cpp b/plotjuggler_plugins/StatePublisherCSV/publisher_csv.cpp index d1c822357..f695c60f7 100644 --- a/plotjuggler_plugins/StatePublisherCSV/publisher_csv.cpp +++ b/plotjuggler_plugins/StatePublisherCSV/publisher_csv.cpp @@ -23,7 +23,7 @@ void StatePublisherCSV::setEnabled(bool enabled) { _enabled = enabled; - if( _enabled ) + if (_enabled) { _dialog = new QDialog(); _notification_timer = new QTimer(_dialog); @@ -41,92 +41,73 @@ void StatePublisherCSV::setEnabled(bool enabled) updateButtonsState(); //-------------------- - connect(_notification_timer, &QTimer::timeout, - this, [this](){ - _ui->labelNotification->setText(""); - }); + connect(_notification_timer, &QTimer::timeout, this, + [this]() { _ui->labelNotification->setText(""); }); //-------------------- - connect(_dialog, &QDialog::finished, - this, &StatePublisherCSV::onWindowClosed); + connect(_dialog, &QDialog::finished, this, &StatePublisherCSV::onWindowClosed); //-------------------- - connect(_ui->buttonGetStart, &QPushButton::clicked, - this, [this]() - { + connect(_ui->buttonGetStart, &QPushButton::clicked, this, [this]() { _start_time = _previous_time; - _ui->lineEditStart->setText( QString::number(_previous_time, 'f', 3) ); + _ui->lineEditStart->setText(QString::number(_previous_time, 'f', 3)); updateButtonsState(); }); //-------------------- - connect(_ui->buttonGetEnd, &QPushButton::clicked, - this, [this](){ + connect(_ui->buttonGetEnd, &QPushButton::clicked, this, [this]() { _end_time = _previous_time; - _ui->lineEditEnd->setText( QString::number(_previous_time, 'f', 3) ); + _ui->lineEditEnd->setText(QString::number(_previous_time, 'f', 3)); updateButtonsState(); }); //-------------------- - connect(_ui->checkBoxFirst, &QCheckBox::toggled, - this, [this](bool checked) - { - _ui->lineEditStart->setEnabled( !checked ); - _start_time = (checked) ? -std::numeric_limits::max() : - _previous_time; + connect(_ui->checkBoxFirst, &QCheckBox::toggled, this, [this](bool checked) { + _ui->lineEditStart->setEnabled(!checked); + _start_time = (checked) ? -std::numeric_limits::max() : _previous_time; updateButtonsState(); }); //-------------------- - connect(_ui->checkBoxLast, &QCheckBox::toggled, - this, [this](bool checked) - { - _ui->lineEditEnd->setEnabled( !checked ); - _end_time = (checked) ? std::numeric_limits::max() : - _previous_time; + connect(_ui->checkBoxLast, &QCheckBox::toggled, this, [this](bool checked) { + _ui->lineEditEnd->setEnabled(!checked); + _end_time = (checked) ? std::numeric_limits::max() : _previous_time; updateButtonsState(); }); //-------------------- - connect(_ui->buttonStatisticsClip, &QPushButton::clicked, - this, [this]() - { + connect(_ui->buttonStatisticsClip, &QPushButton::clicked, this, [this]() { auto csv_string = generateStatisticsCSV(_start_time, _end_time); - QClipboard *clipboard = QGuiApplication::clipboard(); + QClipboard* clipboard = QGuiApplication::clipboard(); clipboard->setText(csv_string); _ui->labelNotification->setText("Statistics copied to Clipboard"); _notification_timer->start(2000); }); //-------------------- - connect(_ui->buttonRangeClip, &QPushButton::clicked, - this, [this]() - { + connect(_ui->buttonRangeClip, &QPushButton::clicked, this, [this]() { auto csv_string = generateRangeCSV(_start_time, _end_time); - QClipboard *clipboard = QGuiApplication::clipboard(); + QClipboard* clipboard = QGuiApplication::clipboard(); clipboard->setText(csv_string); _ui->labelNotification->setText("Range data copied to Clipboard"); _notification_timer->start(2000); }); //-------------------- - connect(_ui->buttonStatisticsFile, &QPushButton::clicked, - this, [this]() - { + connect(_ui->buttonStatisticsFile, &QPushButton::clicked, this, [this]() { auto csv_string = generateStatisticsCSV(_start_time, _end_time); - this->saveFile( csv_string ); + this->saveFile(csv_string); }); //-------------------- - connect(_ui->buttonRangeFile, &QPushButton::clicked, - this, [this]() - { + connect(_ui->buttonRangeFile, &QPushButton::clicked, this, [this]() { auto csv_string = generateRangeCSV(_start_time, _end_time); - this->saveFile( csv_string ); + this->saveFile(csv_string); }); //-------------------- _dialog->setWindowFlag(Qt::WindowStaysOnTopHint); _dialog->show(); } - else{ - if( _dialog ) + else + { + if (_dialog) { _dialog->done(0); } @@ -139,14 +120,12 @@ void StatePublisherCSV::onWindowClosed() emit closed(); } - - QString StatePublisherCSV::generateStatisticsCSV(double time_start, double time_end) { std::map ordered_map; - for(const auto& it: _datamap->numeric) + for (const auto& it : _datamap->numeric) { - ordered_map.insert( {it.first, &it.second} ); + ordered_map.insert({ it.first, &it.second }); } std::stringstream out; @@ -155,25 +134,25 @@ QString StatePublisherCSV::generateStatisticsCSV(double time_start, double time_ out << "End Time," << time_end << "\n"; out << "Current Time," << _previous_time << "\n"; - for(const auto& it: ordered_map) + for (const auto& it : ordered_map) { const auto& name = it.first; const auto& plot = *(it.second); int index = plot.getIndexFromX(time_start); if (index < 0) { - continue; //skip this + continue; // skip this } - auto current_value = plot.getYfromX( _previous_time ); + auto current_value = plot.getYfromX(_previous_time); auto point = plot.at(index); - if( point.x > time_end) // out of range + if (point.x > time_end) // out of range { continue; } - if( index+1 == plot.size() ) // out of range + if (index + 1 == plot.size()) // out of range { continue; } @@ -184,10 +163,10 @@ QString StatePublisherCSV::generateStatisticsCSV(double time_start, double time_ int count = 1; index++; - while ( index < plot.size() ) + while (index < plot.size()) { point = plot.at(index); - if( point.x > time_end) + if (point.x > time_end) { break; } @@ -205,18 +184,20 @@ QString StatePublisherCSV::generateStatisticsCSV(double time_start, double time_ out << std::to_string(max_value) << ','; out << std::to_string(total / double(count)) << '\n'; } - return QString::fromStdString( out.str() ); + return QString::fromStdString(out.str()); } -bool StatePublisherCSV::getTimeRanges(double *first, double *last) +bool StatePublisherCSV::getTimeRanges(double* first, double* last) { bool ok; *first = _ui->lineEditStart->text().toDouble(&ok); - if (!ok) { + if (!ok) + { return false; } *last = _ui->lineEditEnd->text().toDouble(&ok); - if (!ok) { + if (!ok) + { return false; } return true; @@ -224,7 +205,7 @@ bool StatePublisherCSV::getTimeRanges(double *first, double *last) void StatePublisherCSV::updateButtonsState() { - bool enable = (_start_time <= _end_time ); + bool enable = (_start_time <= _end_time); _ui->buttonRangeClip->setEnabled(enable); _ui->buttonRangeFile->setEnabled(enable); _ui->buttonStatisticsClip->setEnabled(enable); @@ -233,16 +214,14 @@ void StatePublisherCSV::updateButtonsState() void StatePublisherCSV::saveFile(QString text) { - //QFileDialog::getSaveFileName(nullptr, "Save as CSV file", ); + // QFileDialog::getSaveFileName(nullptr, "Save as CSV file", ); QSettings settings; - QString directory_path = settings.value("StatePublisherCSV.saveDirectory", - QDir::currentPath()).toString(); + QString directory_path = + settings.value("StatePublisherCSV.saveDirectory", QDir::currentPath()).toString(); - QString fileName = - QFileDialog::getSaveFileName(nullptr, tr("Save as CSV file"), - directory_path, - tr("CSV files (*.csv)")); + QString fileName = QFileDialog::getSaveFileName( + nullptr, tr("Save as CSV file"), directory_path, tr("CSV files (*.csv)")); if (fileName.isEmpty()) { @@ -256,11 +235,12 @@ void StatePublisherCSV::saveFile(QString text) QFile file(fileName); if (!file.open(QIODevice::WriteOnly)) { - QMessageBox::warning(nullptr, "Error", QString("Failed to open the file [%1]").arg(fileName)); + QMessageBox::warning(nullptr, "Error", + QString("Failed to open the file [%1]").arg(fileName)); return; } - file.write( text.toUtf8() ); + file.write(text.toUtf8()); file.close(); directory_path = QFileInfo(fileName).absolutePath(); @@ -269,42 +249,40 @@ void StatePublisherCSV::saveFile(QString text) QString StatePublisherCSV::generateRangeCSV(double time_start, double time_end) { - using PlotPair = std::pair; + using PlotPair = std::pair; std::vector ordered_plotdata; - for(const auto& it: _datamap->numeric) + for (const auto& it : _datamap->numeric) { - if( it.second.size() == 0 || - it.second.front().x > time_end || - it.second.back().x < time_start ) + if (it.second.size() == 0 || it.second.front().x > time_end || + it.second.back().x < time_start) { continue; } - ordered_plotdata.push_back( {it.first, &it.second} ); + ordered_plotdata.push_back({ it.first, &it.second }); } const size_t plot_count = ordered_plotdata.size(); std::sort(ordered_plotdata.begin(), ordered_plotdata.end(), - [](const PlotPair& a, const PlotPair& b) { return a.first < b.first; } ) ; + [](const PlotPair& a, const PlotPair& b) { return a.first < b.first; }); // current index per plordata std::vector indices(plot_count, 0); const auto NaN = std::numeric_limits::quiet_NaN(); - std::vector row_values(plot_count, NaN ); - + std::vector row_values(plot_count, NaN); QString labels; labels += "__time,"; - for( size_t i=0; i < plot_count; i++) + for (size_t i = 0; i < plot_count; i++) { - labels += QString::fromStdString( ordered_plotdata[i].first ); - labels += ( i+1 < plot_count) ? "," : "\n"; + labels += QString::fromStdString(ordered_plotdata[i].first); + labels += (i + 1 < plot_count) ? "," : "\n"; const PJ::PlotData* plotdata = (ordered_plotdata[i].second); int index = plotdata->getIndexFromX(time_start); - if( index < 0 ) + if (index < 0) { index = plotdata->size(); } @@ -312,7 +290,7 @@ QString StatePublisherCSV::generateRangeCSV(double time_start, double time_end) } bool done = false; - QStringList rows = {labels}; + QStringList rows = { labels }; while (!done) { @@ -320,38 +298,38 @@ QString StatePublisherCSV::generateRangeCSV(double time_start, double time_end) done = true; double min_time = std::numeric_limits::max(); - for( size_t i=0; i < plot_count; i++) + for (size_t i = 0; i < plot_count; i++) { size_t index = indices[i]; const PJ::PlotData* plotdata = (ordered_plotdata[i].second); row_values[i] = NaN; - if( index >= plotdata->size() ) + if (index >= plotdata->size()) { continue; } const auto& point = plotdata->at(index); - if( point.x > time_end ) + if (point.x > time_end) { continue; } done = false; - if( min_time > point.x ) + if (min_time > point.x) { - min_time = point.x; // new min_time + min_time = point.x; // new min_time // reset previous flags - std::fill( row_values.begin(), row_values.begin() + i, NaN); + std::fill(row_values.begin(), row_values.begin() + i, NaN); row_values[i] = point.y; } - else if( std::abs( min_time - point.x) < std::numeric_limits::epsilon() ) + else if (std::abs(min_time - point.x) < std::numeric_limits::epsilon()) { row_values[i] = point.y; } } - if( min_time > time_end || done ) + if (min_time > time_end || done) { break; } @@ -359,17 +337,17 @@ QString StatePublisherCSV::generateRangeCSV(double time_start, double time_end) // the row to append to the CSV file QString row_str = QString::number(min_time, 'f', 6) + ","; - for( size_t i=0; i < plot_count; i++) + for (size_t i = 0; i < plot_count; i++) { - if( !std::isnan(row_values[i]) ) + if (!std::isnan(row_values[i])) { row_str += QString::number(row_values[i], 'f'); // value used, move to the nex index indices[i]++; } - row_str += ( i+1 < plot_count) ? "," : "\n"; + row_str += (i + 1 < plot_count) ? "," : "\n"; } - rows.push_back( row_str ); + rows.push_back(row_str); } return rows.join(""); } diff --git a/plotjuggler_plugins/StatePublisherCSV/publisher_csv.h b/plotjuggler_plugins/StatePublisherCSV/publisher_csv.h index b70969acf..88a2b138c 100644 --- a/plotjuggler_plugins/StatePublisherCSV/publisher_csv.h +++ b/plotjuggler_plugins/StatePublisherCSV/publisher_csv.h @@ -26,16 +26,19 @@ class StatePublisherCSV : public PJ::StatePublisher virtual ~StatePublisherCSV() override; - virtual bool enabled() const override { + virtual bool enabled() const override + { return _enabled; } - virtual void updateState(double current_time) override { + virtual void updateState(double current_time) override + { _previous_time = current_time; } virtual void play(double) override - {} + { + } public slots: virtual void setEnabled(bool enabled) override; @@ -44,7 +47,6 @@ private slots: void onWindowClosed(); private: - std::mutex _mutex; bool _enabled = false; diff --git a/plotjuggler_plugins/StatePublisherZMQ/statepublisher_zmq.cpp b/plotjuggler_plugins/StatePublisherZMQ/statepublisher_zmq.cpp index 0e9340582..f27ae0d96 100644 --- a/plotjuggler_plugins/StatePublisherZMQ/statepublisher_zmq.cpp +++ b/plotjuggler_plugins/StatePublisherZMQ/statepublisher_zmq.cpp @@ -6,7 +6,9 @@ #include StatePublisherZMQ::StatePublisherZMQ() - : _prev_dataplot(0), _thread(std::bind(&StatePublisherZMQ::run_thread, this)), _prev_time(0) + : _prev_dataplot(0) + , _thread(std::bind(&StatePublisherZMQ::run_thread, this)) + , _prev_time(0) { } diff --git a/plotjuggler_plugins/ToolboxFFT/toolbox_FFT.cpp b/plotjuggler_plugins/ToolboxFFT/toolbox_FFT.cpp index 70bf4e220..d06c0b23b 100644 --- a/plotjuggler_plugins/ToolboxFFT/toolbox_FFT.cpp +++ b/plotjuggler_plugins/ToolboxFFT/toolbox_FFT.cpp @@ -19,17 +19,14 @@ ToolboxFFT::ToolboxFFT() ui->setupUi(_widget); - connect( ui->buttonBox, &QDialogButtonBox::rejected, - this, &ToolboxPlugin::closed ); + connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &ToolboxPlugin::closed); - connect( ui->pushButtonCalculate, &QPushButton::clicked, - this, &ToolboxFFT::calculateCurveFFT ); + connect(ui->pushButtonCalculate, &QPushButton::clicked, this, + &ToolboxFFT::calculateCurveFFT); - connect( ui->pushButtonSave, &QPushButton::clicked, - this, &ToolboxFFT::onSaveCurve ); + connect(ui->pushButtonSave, &QPushButton::clicked, this, &ToolboxFFT::onSaveCurve); - connect( ui->pushButtonClear, &QPushButton::clicked, - this, &ToolboxFFT::onClearCurves ); + connect(ui->pushButtonClear, &QPushButton::clicked, this, &ToolboxFFT::onClearCurves); } ToolboxFFT::~ToolboxFFT() @@ -37,8 +34,7 @@ ToolboxFFT::~ToolboxFFT() delete ui; } -void ToolboxFFT::init(PJ::PlotDataMapRef &src_data, - PJ::TransformsMap &transform_map) +void ToolboxFFT::init(PJ::PlotDataMapRef& src_data, PJ::TransformsMap& transform_map) { _plot_data = &src_data; _transforms = &transform_map; @@ -46,28 +42,25 @@ void ToolboxFFT::init(PJ::PlotDataMapRef &src_data, _plot_widget_A = new PJ::PlotWidgetBase(ui->framePlotPreviewA); _plot_widget_B = new PJ::PlotWidgetBase(ui->framePlotPreviewB); - auto preview_layout_A = new QHBoxLayout( ui->framePlotPreviewA ); + auto preview_layout_A = new QHBoxLayout(ui->framePlotPreviewA); preview_layout_A->setMargin(6); - preview_layout_A->addWidget( _plot_widget_A->widget() ); + preview_layout_A->addWidget(_plot_widget_A->widget()); - auto preview_layout_B = new QHBoxLayout( ui->framePlotPreviewB ); + auto preview_layout_B = new QHBoxLayout(ui->framePlotPreviewB); preview_layout_B->setMargin(6); - preview_layout_B->addWidget( _plot_widget_B->widget() ); + preview_layout_B->addWidget(_plot_widget_B->widget()); _plot_widget_A->setAcceptDrops(true); - connect( _plot_widget_A, &PlotWidgetBase::dragEnterSignal, - this, &ToolboxFFT::onDragEnterEvent); + connect(_plot_widget_A, &PlotWidgetBase::dragEnterSignal, this, + &ToolboxFFT::onDragEnterEvent); - connect( _plot_widget_A, &PlotWidgetBase::dropSignal, - this, &ToolboxFFT::onDropEvent); + connect(_plot_widget_A, &PlotWidgetBase::dropSignal, this, &ToolboxFFT::onDropEvent); - connect( _plot_widget_A, &PlotWidgetBase::viewResized, - this, &ToolboxFFT::onViewResized ); + connect(_plot_widget_A, &PlotWidgetBase::viewResized, this, &ToolboxFFT::onViewResized); } -std::pair -ToolboxFFT::providedWidget() const +std::pair ToolboxFFT::providedWidget() const { return { _widget, PJ::ToolboxPlugin::FIXED }; } @@ -85,10 +78,11 @@ void ToolboxFFT::calculateCurveFFT() { _plot_widget_B->removeAllCurves(); - for( const auto& curve_id: _curve_names) + for (const auto& curve_id : _curve_names) { - auto it = _plot_data->numeric.find( curve_id ); - if( it == _plot_data->numeric.end() ) { + auto it = _plot_data->numeric.find(curve_id); + if (it == _plot_data->numeric.end()) + { return; } PlotData& curve_data = it->second; @@ -96,10 +90,10 @@ void ToolboxFFT::calculateCurveFFT() int min_index = 0; int max_index = curve_data.size() - 1; - if( ui->radioZoomed->isChecked() ) + if (ui->radioZoomed->isChecked()) { - min_index = curve_data.getIndexFromX( _zoom_range.min ); - max_index = curve_data.getIndexFromX( _zoom_range.max ); + min_index = curve_data.getIndexFromX(_zoom_range.min); + max_index = curve_data.getIndexFromX(_zoom_range.max); } double min_t = curve_data.at(min_index).x; @@ -107,67 +101,68 @@ void ToolboxFFT::calculateCurveFFT() int N = 1 + max_index - min_index; - if( N & 1 ) { // if not even, make it even + if (N & 1) + { // if not even, make it even N--; max_index--; } - if( N < 8 || min_index < 0 || max_index < 0 ) { + if (N < 8 || min_index < 0 || max_index < 0) + { return; } - double dT = (curve_data.at(max_index).x - - curve_data.at(min_index).x ) / - double(N-1); + double dT = (curve_data.at(max_index).x - curve_data.at(min_index).x) / double(N - 1); std::vector input; - input.reserve( curve_data.size() ); + input.reserve(curve_data.size()); - //double std_dev = 0.0; + // double std_dev = 0.0; - for(size_t i=0; i(p.y) ); + input.push_back(static_cast(p.y)); - if( i != 0) { - double dTi = ( p.x - curve_data[i-1].x ); + if (i != 0) + { + double dTi = (p.x - curve_data[i - 1].x); double diff = dTi - dT; - //std_dev += diff*diff; + // std_dev += diff*diff; } } - //std_dev = sqrt(std_dev / double(N-1) ); + // std_dev = sqrt(std_dev / double(N-1) ); - std::vector out( N/2+1 ); + std::vector out(N / 2 + 1); auto config = kiss_fftr_alloc(N, false, nullptr, nullptr); QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - kiss_fftr( config, input.data(), out.data() ); + kiss_fftr(config, input.data(), out.data()); QApplication::restoreOverrideCursor(); - auto& curver_fft = _local_data.getOrCreateNumeric( curve_id ); + auto& curver_fft = _local_data.getOrCreateNumeric(curve_id); curver_fft.clear(); - for ( int i=0; i(); } - _plot_widget_B->addCurve( curve_id + "_FFT", curver_fft, color ); + _plot_widget_B->addCurve(curve_id + "_FFT", curver_fft, color); free(config); } _plot_widget_B->resetZoom(); - } void ToolboxFFT::onClearCurves() @@ -182,22 +177,23 @@ void ToolboxFFT::onClearCurves() ui->pushButtonCalculate->setEnabled(false); ui->lineEditSuffix->setEnabled(false); - ui->lineEditSuffix->setText( "_FFT" ); + ui->lineEditSuffix->setText("_FFT"); _curve_names.clear(); } -void ToolboxFFT::onDragEnterEvent(QDragEnterEvent *event) +void ToolboxFFT::onDragEnterEvent(QDragEnterEvent* event) { const QMimeData* mimeData = event->mimeData(); QStringList mimeFormats = mimeData->formats(); - for(const QString& format : mimeFormats) + for (const QString& format : mimeFormats) { QByteArray encoded = mimeData->data(format); QDataStream stream(&encoded, QIODevice::ReadOnly); - if (format != "curveslist/add_curve") { + if (format != "curveslist/add_curve") + { return; } @@ -216,20 +212,20 @@ void ToolboxFFT::onDragEnterEvent(QDragEnterEvent *event) } } -void ToolboxFFT::onDropEvent(QDropEvent *) +void ToolboxFFT::onDropEvent(QDropEvent*) { _zoom_range.min = -std::numeric_limits::max(); _zoom_range.max = std::numeric_limits::max(); - for( auto& curve: _dragging_curves ) + for (auto& curve : _dragging_curves) { std::string curve_id = curve.toStdString(); PlotData& curve_data = _plot_data->getOrCreateNumeric(curve_id); - _plot_widget_A->addCurve( curve_id, curve_data ); - _curve_names.push_back( curve_id ); - _zoom_range.min = std::min( _zoom_range.min, curve_data.front().x ); - _zoom_range.max = std::max( _zoom_range.max, curve_data.back().x ); + _plot_widget_A->addCurve(curve_id, curve_data); + _curve_names.push_back(curve_id); + _zoom_range.min = std::min(_zoom_range.min, curve_data.front().x); + _zoom_range.max = std::max(_zoom_range.max, curve_data.back().x); } ui->pushButtonSave->setEnabled(true); @@ -240,7 +236,7 @@ void ToolboxFFT::onDropEvent(QDropEvent *) _plot_widget_A->resetZoom(); } -void ToolboxFFT::onViewResized(const QRectF &rect) +void ToolboxFFT::onViewResized(const QRectF& rect) { _zoom_range.min = rect.left(); _zoom_range.max = rect.right(); @@ -249,22 +245,23 @@ void ToolboxFFT::onViewResized(const QRectF &rect) void ToolboxFFT::onSaveCurve() { auto suffix = ui->lineEditSuffix->text().toStdString(); - if( suffix.empty() ) + if (suffix.empty()) { ui->lineEditSuffix->setText("_FFT"); suffix = "_FFT"; } - for(const auto& curve_id: _curve_names) + for (const auto& curve_id : _curve_names) { - auto it = _local_data.numeric.find( curve_id ); - if( it == _local_data.numeric.end() ) { + auto it = _local_data.numeric.find(curve_id); + if (it == _local_data.numeric.end()) + { continue; } - auto& out_data = _plot_data->getOrCreateNumeric( curve_id + suffix ); - out_data.clone( it->second ); + auto& out_data = _plot_data->getOrCreateNumeric(curve_id + suffix); + out_data.clone(it->second); - out_data.setAttribute( PJ::DISABLE_LINKED_ZOOM, true ); - emit plotCreated( curve_id + suffix ); + out_data.setAttribute(PJ::DISABLE_LINKED_ZOOM, true); + emit plotCreated(curve_id + suffix); } emit closed(); diff --git a/plotjuggler_plugins/ToolboxFFT/toolbox_FFT.h b/plotjuggler_plugins/ToolboxFFT/toolbox_FFT.h index 88a17a876..70bbf2aa8 100644 --- a/plotjuggler_plugins/ToolboxFFT/toolbox_FFT.h +++ b/plotjuggler_plugins/ToolboxFFT/toolbox_FFT.h @@ -5,7 +5,8 @@ #include "PlotJuggler/toolbox_base.h" #include "PlotJuggler/plotwidget_base.h" -namespace Ui { +namespace Ui +{ class toolbox_fft; } @@ -25,8 +26,7 @@ class ToolboxFFT : public PJ::ToolboxPlugin return "Fast Fourier Transform"; } - void init( PJ::PlotDataMapRef& src_data, - PJ::TransformsMap& transform_map) override; + void init(PJ::PlotDataMapRef& src_data, PJ::TransformsMap& transform_map) override; std::pair providedWidget() const override; @@ -36,9 +36,9 @@ public slots: private: QWidget* _widget; - Ui::toolbox_fft *ui; + Ui::toolbox_fft* ui; - //bool eventFilter(QObject *obj, QEvent *event) override; + // bool eventFilter(QObject *obj, QEvent *event) override; QStringList _dragging_curves; @@ -63,4 +63,3 @@ private slots: void calculateCurveFFT(); void onClearCurves(); }; - diff --git a/plotjuggler_plugins/ToolboxQuaternion/quaternion_to_rpy.cpp b/plotjuggler_plugins/ToolboxQuaternion/quaternion_to_rpy.cpp index 4a6a60a30..e2549de25 100644 --- a/plotjuggler_plugins/ToolboxQuaternion/quaternion_to_rpy.cpp +++ b/plotjuggler_plugins/ToolboxQuaternion/quaternion_to_rpy.cpp @@ -1,6 +1,5 @@ #include "quaternion_to_rpy.h" - QuaternionToRollPitchYaw::QuaternionToRollPitchYaw() { reset(); @@ -14,7 +13,7 @@ void QuaternionToRollPitchYaw::reset() _roll_offset = 0; _pitch_offset = 0; _yaw_offset = 0; - _last_timestamp = - std::numeric_limits::max(); + _last_timestamp = -std::numeric_limits::max(); } void QuaternionToRollPitchYaw::calculate() @@ -24,30 +23,28 @@ void QuaternionToRollPitchYaw::calculate() auto& data_z = *_src_vector[2]; auto& data_w = *_src_vector[3]; - auto& data_roll = *_dst_vector[0]; + auto& data_roll = *_dst_vector[0]; auto& data_pitch = *_dst_vector[1]; - auto& data_yaw = *_dst_vector[2]; + auto& data_yaw = *_dst_vector[2]; - data_roll.setMaximumRangeX( data_x.maximumRangeX() ); - data_pitch.setMaximumRangeX( data_x.maximumRangeX() ); - data_yaw.setMaximumRangeX( data_x.maximumRangeX() ); + data_roll.setMaximumRangeX(data_x.maximumRangeX()); + data_pitch.setMaximumRangeX(data_x.maximumRangeX()); + data_yaw.setMaximumRangeX(data_x.maximumRangeX()); data_roll.clear(); data_pitch.clear(); data_yaw.clear(); - if( data_x.size() == 0 || - data_x.size() != data_y.size() || - data_y.size() != data_z.size() || - data_z.size() != data_w.size() ) + if (data_x.size() == 0 || data_x.size() != data_y.size() || + data_y.size() != data_z.size() || data_z.size() != data_w.size()) { return; } - int pos = data_x.getIndexFromX( _last_timestamp ); + int pos = data_x.getIndexFromX(_last_timestamp); size_t index = pos < 0 ? 0 : static_cast(pos); - while(index < data_x.size()) + while (index < data_x.size()) { auto& point_x = data_x.at(index); double timestamp = point_x.x; @@ -58,12 +55,12 @@ void QuaternionToRollPitchYaw::calculate() if (timestamp >= _last_timestamp) { - std::array RPY; - calculateNextPoint(index, {q_x, q_y, q_z, q_w}, RPY ); + std::array RPY; + calculateNextPoint(index, { q_x, q_y, q_z, q_w }, RPY); - data_roll.pushBack({ timestamp, _scale * (RPY[0] + _roll_offset)}); + data_roll.pushBack({ timestamp, _scale * (RPY[0] + _roll_offset) }); data_pitch.pushBack({ timestamp, _scale * (RPY[1] + _pitch_offset) }); - data_yaw.pushBack({ timestamp, _scale * (RPY[2] + _yaw_offset)}); + data_yaw.pushBack({ timestamp, _scale * (RPY[2] + _yaw_offset) }); _last_timestamp = timestamp; } @@ -71,10 +68,9 @@ void QuaternionToRollPitchYaw::calculate() } } -void QuaternionToRollPitchYaw::calculateNextPoint( - size_t index, - const std::array &quat, - std::array &rpy) +void QuaternionToRollPitchYaw::calculateNextPoint(size_t index, + const std::array& quat, + std::array& rpy) { double q_x = quat[0]; double q_y = quat[1]; @@ -111,30 +107,36 @@ void QuaternionToRollPitchYaw::calculateNextPoint( double cosy_cosp = 1 - 2 * (q_y * q_y + q_z * q_z); yaw = std::atan2(siny_cosp, cosy_cosp); - const double WRAP_ANGLE = M_PI*2.0; - const double WRAP_THRESHOLD = M_PI*1.95; + const double WRAP_ANGLE = M_PI * 2.0; + const double WRAP_THRESHOLD = M_PI * 1.95; //--------- wrap ------ - if( index != 0 && _wrap) + if (index != 0 && _wrap) { - if( (roll -_prev_roll) > WRAP_THRESHOLD ) { + if ((roll - _prev_roll) > WRAP_THRESHOLD) + { _roll_offset -= WRAP_ANGLE; } - else if( (_prev_roll - roll) > WRAP_THRESHOLD ) { + else if ((_prev_roll - roll) > WRAP_THRESHOLD) + { _roll_offset += WRAP_ANGLE; } - if( (pitch -_prev_pitch) > WRAP_THRESHOLD ) { + if ((pitch - _prev_pitch) > WRAP_THRESHOLD) + { _pitch_offset -= WRAP_ANGLE; } - else if( (_prev_pitch - pitch) > WRAP_THRESHOLD ) { + else if ((_prev_pitch - pitch) > WRAP_THRESHOLD) + { _pitch_offset += WRAP_ANGLE; } - if( (yaw -_prev_yaw) > WRAP_THRESHOLD ) { + if ((yaw - _prev_yaw) > WRAP_THRESHOLD) + { _yaw_offset -= WRAP_ANGLE; } - else if( (_prev_yaw - yaw) > WRAP_THRESHOLD ) { + else if ((_prev_yaw - yaw) > WRAP_THRESHOLD) + { _yaw_offset += WRAP_ANGLE; } } diff --git a/plotjuggler_plugins/ToolboxQuaternion/quaternion_to_rpy.h b/plotjuggler_plugins/ToolboxQuaternion/quaternion_to_rpy.h index d844829e9..a955c391a 100644 --- a/plotjuggler_plugins/ToolboxQuaternion/quaternion_to_rpy.h +++ b/plotjuggler_plugins/ToolboxQuaternion/quaternion_to_rpy.h @@ -1,42 +1,44 @@ #ifndef QUATERNION_TO_RPY_H #define QUATERNION_TO_RPY_H - #include "PlotJuggler/transform_function.h" -class QuaternionToRollPitchYaw: public PJ::TransformFunction +class QuaternionToRollPitchYaw : public PJ::TransformFunction { public: - QuaternionToRollPitchYaw(); - const char* name() const override { + const char* name() const override + { return "quaternion_to_RPY"; } void reset() override; - int numInputs() const override { + int numInputs() const override + { return 4; } - int numOutputs() const override { + int numOutputs() const override + { return 3; } - void setScale(double scale) { + void setScale(double scale) + { _scale = scale; } - void setWarp(bool wrap) { + void setWarp(bool wrap) + { _wrap = wrap; } void calculate() override; - void calculateNextPoint(size_t index, - const std::array& quat, - std::array& rpy); + void calculateNextPoint(size_t index, const std::array& quat, + std::array& rpy); private: double _prev_roll = 0; @@ -47,8 +49,7 @@ class QuaternionToRollPitchYaw: public PJ::TransformFunction double _yaw_offset = 0; double _scale = 1.0; bool _wrap = true; - double _last_timestamp = - std::numeric_limits::max(); + double _last_timestamp = -std::numeric_limits::max(); }; - -#endif // QUATERNION_TO_RPY_H +#endif // QUATERNION_TO_RPY_H diff --git a/plotjuggler_plugins/ToolboxQuaternion/toolbox_quaternion.cpp b/plotjuggler_plugins/ToolboxQuaternion/toolbox_quaternion.cpp index d296ae17c..92450e592 100644 --- a/plotjuggler_plugins/ToolboxQuaternion/toolbox_quaternion.cpp +++ b/plotjuggler_plugins/ToolboxQuaternion/toolbox_quaternion.cpp @@ -19,36 +19,33 @@ ToolboxQuaternion::ToolboxQuaternion() ui->lineEditZ->installEventFilter(this); ui->lineEditW->installEventFilter(this); - connect( ui->buttonBox, &QDialogButtonBox::rejected, - this, &ToolboxQuaternion::onClosed ); + connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &ToolboxQuaternion::onClosed); - connect( ui->checkBoxUnwrap, &QCheckBox::toggled, - this, &ToolboxQuaternion::onParametersChanged ); + connect(ui->checkBoxUnwrap, &QCheckBox::toggled, this, + &ToolboxQuaternion::onParametersChanged); - connect( ui->radioButtonDegrees, &QRadioButton::toggled, - this, &ToolboxQuaternion::onParametersChanged ); + connect(ui->radioButtonDegrees, &QRadioButton::toggled, this, + &ToolboxQuaternion::onParametersChanged); - connect( ui->pushButtonSave, &QPushButton::clicked, - this, &ToolboxQuaternion::on_pushButtonSave_clicked ); + connect(ui->pushButtonSave, &QPushButton::clicked, this, + &ToolboxQuaternion::on_pushButtonSave_clicked); } ToolboxQuaternion::~ToolboxQuaternion() { - } -void ToolboxQuaternion::init(PJ::PlotDataMapRef &src_data, - PJ::TransformsMap &transform_map) +void ToolboxQuaternion::init(PJ::PlotDataMapRef& src_data, + PJ::TransformsMap& transform_map) { _plot_data = &src_data; _transforms = &transform_map; _plot_widget = new PJ::PlotWidgetBase(ui->frame); - auto preview_layout = new QHBoxLayout( ui->framePlotPreview ); + auto preview_layout = new QHBoxLayout(ui->framePlotPreview); preview_layout->setMargin(6); - preview_layout->addWidget( _plot_widget->widget() ); - + preview_layout->addWidget(_plot_widget->widget()); } std::pair @@ -62,20 +59,21 @@ bool ToolboxQuaternion::onShowWidget() return true; } -bool ToolboxQuaternion::eventFilter(QObject *obj, QEvent *ev) +bool ToolboxQuaternion::eventFilter(QObject* obj, QEvent* ev) { - if( ev->type() == QEvent::DragEnter ) + if (ev->type() == QEvent::DragEnter) { auto event = static_cast(ev); const QMimeData* mimeData = event->mimeData(); QStringList mimeFormats = mimeData->formats(); - for(const QString& format : mimeFormats) + for (const QString& format : mimeFormats) { QByteArray encoded = mimeData->data(format); QDataStream stream(&encoded, QIODevice::ReadOnly); - if (format != "curveslist/add_curve") { + if (format != "curveslist/add_curve") + { return false; } @@ -89,38 +87,37 @@ bool ToolboxQuaternion::eventFilter(QObject *obj, QEvent *ev) curves.push_back(curve_name); } } - if( curves.size() != 1 ) + if (curves.size() != 1) { return false; } _dragging_curve = curves.front(); - if( obj == ui->lineEditX || - obj == ui->lineEditY || - obj == ui->lineEditZ || - obj == ui->lineEditW ) + if (obj == ui->lineEditX || obj == ui->lineEditY || obj == ui->lineEditZ || + obj == ui->lineEditW) { event->acceptProposedAction(); return true; } } } - else if ( ev->type() == QEvent::Drop ) { - auto lineEdit = qobject_cast( obj ); + else if (ev->type() == QEvent::Drop) + { + auto lineEdit = qobject_cast(obj); - if ( !lineEdit ) + if (!lineEdit) { return false; } - lineEdit->setText( _dragging_curve ); + lineEdit->setText(_dragging_curve); - if( (obj == ui->lineEditX && _dragging_curve.endsWith("x") ) || - (obj == ui->lineEditY && _dragging_curve.endsWith("y") ) || - (obj == ui->lineEditZ && _dragging_curve.endsWith("z") ) || - (obj == ui->lineEditW && _dragging_curve.endsWith("w") ) ) + if ((obj == ui->lineEditX && _dragging_curve.endsWith("x")) || + (obj == ui->lineEditY && _dragging_curve.endsWith("y")) || + (obj == ui->lineEditZ && _dragging_curve.endsWith("z")) || + (obj == ui->lineEditW && _dragging_curve.endsWith("w"))) { - autoFill( _dragging_curve.left( _dragging_curve.size() - 1 ) ); + autoFill(_dragging_curve.left(_dragging_curve.size() - 1)); } } @@ -129,30 +126,28 @@ bool ToolboxQuaternion::eventFilter(QObject *obj, QEvent *ev) void ToolboxQuaternion::autoFill(QString prefix) { - QStringList suffix = {"x", "y", "z", "w"}; - std::array lineEdits = {ui->lineEditX, - ui->lineEditY, - ui->lineEditZ, - ui->lineEditW }; + QStringList suffix = { "x", "y", "z", "w" }; + std::array lineEdits = { ui->lineEditX, ui->lineEditY, ui->lineEditZ, + ui->lineEditW }; QStringList names; - for( int i=0; i<4; i++ ) + for (int i = 0; i < 4; i++) { QString name = prefix + suffix[i]; - auto it = _plot_data->numeric.find( name.toStdString() ); - if( it != _plot_data->numeric.end() ) + auto it = _plot_data->numeric.find(name.toStdString()); + if (it != _plot_data->numeric.end()) { - names.push_back( name ); + names.push_back(name); } } - if( names.size() == 4 ) + if (names.size() == 4) { - for( int i=0; i<4; i++ ) + for (int i = 0; i < 4; i++) { - lineEdits[i]->setText( names[i] ); + lineEdits[i]->setText(names[i]); } - ui->lineEditOut->setText( prefix ); - ui->pushButtonSave->setEnabled( true ); + ui->lineEditOut->setText(prefix); + ui->pushButtonSave->setEnabled(true); generateRPY(PREVIEW); } @@ -170,85 +165,78 @@ void ToolboxQuaternion::generateRPY(GenerateType type) std::string prefix = ui->lineEditOut->text().toStdString(); - PlotData data_roll( prefix + "roll", {} ); - PlotData data_pitch( prefix + "pitch", {} ); - PlotData data_yaw( prefix + "yaw", {} ); + PlotData data_roll(prefix + "roll", {}); + PlotData data_pitch(prefix + "pitch", {}); + PlotData data_yaw(prefix + "yaw", {}); std::vector dst_vector = { &data_roll, &data_pitch, &data_yaw }; - if( type == SAVE ) + if (type == SAVE) { - dst_vector[0] = &_plot_data->getOrCreateNumeric( prefix + "roll", {} ); - dst_vector[1] = &_plot_data->getOrCreateNumeric( prefix + "pitch", {} ); - dst_vector[2] = &_plot_data->getOrCreateNumeric( prefix + "yaw", {} ); + dst_vector[0] = &_plot_data->getOrCreateNumeric(prefix + "roll", {}); + dst_vector[1] = &_plot_data->getOrCreateNumeric(prefix + "pitch", {}); + dst_vector[2] = &_plot_data->getOrCreateNumeric(prefix + "yaw", {}); } - transform->setData( _plot_data, src_data, dst_vector ); - transform->setWarp( wrap ); - transform->setScale( unit_scale ); + transform->setData(_plot_data, src_data, dst_vector); + transform->setWarp(wrap); + transform->setScale(unit_scale); transform->calculate(); - if( type == PREVIEW ) + if (type == PREVIEW) { _plot_widget->removeAllCurves(); for (const auto& dst_data : dst_vector) { - _plot_widget->addCurve( dst_data->plotName(), *dst_data ); + _plot_widget->addCurve(dst_data->plotName(), *dst_data); } _plot_widget->resetZoom(); } - if( type == SAVE ) + if (type == SAVE) { - _transforms->insert( { prefix + "RPY", transform} ); + _transforms->insert({ prefix + "RPY", transform }); - emit plotCreated( prefix + "roll" ); - emit plotCreated( prefix + "pitch" ); - emit plotCreated( prefix + "yaw" ); + emit plotCreated(prefix + "roll"); + emit plotCreated(prefix + "pitch"); + emit plotCreated(prefix + "yaw"); } } std::vector ToolboxQuaternion::getSrcData() { - PlotData& data_x = _plot_data->getOrCreateNumeric( - ui->lineEditX->text().toStdString() ); - PlotData& data_y = _plot_data->getOrCreateNumeric( - ui->lineEditY->text().toStdString() ); - PlotData& data_z = _plot_data->getOrCreateNumeric( - ui->lineEditZ->text().toStdString() ); - PlotData& data_w = _plot_data->getOrCreateNumeric( - ui->lineEditW->text().toStdString() ); + PlotData& data_x = _plot_data->getOrCreateNumeric(ui->lineEditX->text().toStdString()); + PlotData& data_y = _plot_data->getOrCreateNumeric(ui->lineEditY->text().toStdString()); + PlotData& data_z = _plot_data->getOrCreateNumeric(ui->lineEditZ->text().toStdString()); + PlotData& data_w = _plot_data->getOrCreateNumeric(ui->lineEditW->text().toStdString()); return { &data_x, &data_y, &data_z, &data_w }; } void ToolboxQuaternion::on_pushButtonSave_clicked() { - generateRPY( SAVE ); - - ui->pushButtonSave->setEnabled( false ); - ui->lineEditX->setText( {} ); - ui->lineEditY->setText( {} ); - ui->lineEditZ->setText( {} ); - ui->lineEditW->setText( {} ); - ui->lineEditOut->setText( {} ); + generateRPY(SAVE); + + ui->pushButtonSave->setEnabled(false); + ui->lineEditX->setText({}); + ui->lineEditY->setText({}); + ui->lineEditZ->setText({}); + ui->lineEditW->setText({}); + ui->lineEditOut->setText({}); _plot_widget->removeAllCurves(); emit this->closed(); } - void ToolboxQuaternion::onParametersChanged() { - if( ui->lineEditX->text().isEmpty() || - ui->lineEditY->text().isEmpty() || - ui->lineEditZ->text().isEmpty() || - ui->lineEditW->text().isEmpty() || - ui->lineEditOut->text().isEmpty() ) - { - return; - } - generateRPY(PREVIEW); + if (ui->lineEditX->text().isEmpty() || ui->lineEditY->text().isEmpty() || + ui->lineEditZ->text().isEmpty() || ui->lineEditW->text().isEmpty() || + ui->lineEditOut->text().isEmpty()) + { + return; + } + generateRPY(PREVIEW); } void ToolboxQuaternion::onClosed() diff --git a/plotjuggler_plugins/ToolboxQuaternion/toolbox_quaternion.h b/plotjuggler_plugins/ToolboxQuaternion/toolbox_quaternion.h index 092799683..88bd51afe 100644 --- a/plotjuggler_plugins/ToolboxQuaternion/toolbox_quaternion.h +++ b/plotjuggler_plugins/ToolboxQuaternion/toolbox_quaternion.h @@ -6,7 +6,8 @@ #include "PlotJuggler/plotwidget_base.h" #include "quaternion_to_rpy.h" -namespace Ui { +namespace Ui +{ class quaternion_to_RPY; } @@ -26,8 +27,7 @@ class ToolboxQuaternion : public PJ::ToolboxPlugin return "Quaternion to RPY"; } - void init( PJ::PlotDataMapRef& src_data, - PJ::TransformsMap& transform_map) override; + void init(PJ::PlotDataMapRef& src_data, PJ::TransformsMap& transform_map) override; std::pair providedWidget() const override; @@ -45,9 +45,9 @@ private slots: private: QWidget* _widget; - Ui::quaternion_to_RPY *ui; + Ui::quaternion_to_RPY* ui; - bool eventFilter(QObject *obj, QEvent *event) override; + bool eventFilter(QObject* obj, QEvent* event) override; QString _dragging_curve; @@ -59,7 +59,8 @@ private slots: PJ::TransformsMap* _transforms = nullptr; - enum GenerateType{ + enum GenerateType + { PREVIEW, SAVE }; @@ -68,4 +69,3 @@ private slots: std::vector getSrcData(); }; - diff --git a/plotjuggler_plugins/selectlistdialog.h b/plotjuggler_plugins/selectlistdialog.h index 94dad7b52..7c5dbb634 100644 --- a/plotjuggler_plugins/selectlistdialog.h +++ b/plotjuggler_plugins/selectlistdialog.h @@ -15,8 +15,8 @@ class SelectFromListDialog : public QDialog Q_OBJECT public: - explicit SelectFromListDialog(const std::deque& fields, bool single_selection = true, - QWidget* parent = 0); + explicit SelectFromListDialog(const std::deque& fields, + bool single_selection = true, QWidget* parent = 0); ~SelectFromListDialog(); std::vector getSelectedRowNumber() const; @@ -39,8 +39,8 @@ private slots: }; //----------------------------------------------- -inline SelectFromListDialog::SelectFromListDialog(const std::deque& fields, bool single_selection, - QWidget* parent) +inline SelectFromListDialog::SelectFromListDialog(const std::deque& fields, + bool single_selection, QWidget* parent) : QDialog(parent), ui(new Ui::SelectXAxisDialog), _single_selection(single_selection) { auto flags = this->windowFlags();