forked from IQ.Lvbs/IQ.Pilot
IQ.Pilot Release Commit @ f2a861c
This commit is contained in:
770
iqpilot/tools/cabana/chart/chart.cc
Normal file
770
iqpilot/tools/cabana/chart/chart.cc
Normal file
@@ -0,0 +1,770 @@
|
||||
#include "tools/cabana/chart/chart.h"
|
||||
#include "tools/cabana/dbc/dbcqt.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <random>
|
||||
|
||||
#include <QActionGroup>
|
||||
#include <QContextMenuEvent>
|
||||
#include <QMouseEvent>
|
||||
#include <QPainterPath>
|
||||
|
||||
#include "tools/cabana/chart/chartswidget.h"
|
||||
|
||||
const int AXIS_X_TOP_MARGIN = 4;
|
||||
const int X_TICK_COUNT = 5;
|
||||
const double MIN_ZOOM_SECONDS = 0.01; // 10ms
|
||||
// Define a small value of epsilon to compare double values
|
||||
const float EPSILON = 0.000001;
|
||||
static inline bool xLessThan(const QPointF &p, float x) { return p.x() < (x - EPSILON); }
|
||||
|
||||
static QMargins layoutMargins(const QStyle *style) {
|
||||
return {
|
||||
style->pixelMetric(QStyle::PM_LayoutLeftMargin),
|
||||
style->pixelMetric(QStyle::PM_LayoutTopMargin),
|
||||
style->pixelMetric(QStyle::PM_LayoutRightMargin),
|
||||
style->pixelMetric(QStyle::PM_LayoutBottomMargin),
|
||||
};
|
||||
}
|
||||
|
||||
ChartView::ChartView(const std::pair<double, double> &x_range, ChartsWidget *parent)
|
||||
: x_min(x_range.first), x_max(x_range.second), charts_widget(parent), QWidget(parent) {
|
||||
series_type = (SeriesType)settings.chart_series_type;
|
||||
align_to = 50;
|
||||
setMouseTracking(true);
|
||||
tip_label = new TipLabel(this);
|
||||
createToolButtons();
|
||||
signal_value_font.setPointSize(9);
|
||||
|
||||
QObject::connect(dbcNotifier(), &QtDBCNotifier::signalRemoved, this, &ChartView::signalRemoved);
|
||||
QObject::connect(dbcNotifier(), &QtDBCNotifier::signalUpdated, this, &ChartView::signalUpdated);
|
||||
QObject::connect(dbcNotifier(), &QtDBCNotifier::msgRemoved, this, &ChartView::msgRemoved);
|
||||
QObject::connect(dbcNotifier(), &QtDBCNotifier::msgUpdated, this, &ChartView::msgUpdated);
|
||||
}
|
||||
|
||||
void ChartView::createToolButtons() {
|
||||
close_btn = new ToolButton("x", tr("Remove Chart"), this);
|
||||
|
||||
menu = new QMenu(this);
|
||||
// series types
|
||||
auto change_series_group = new QActionGroup(menu);
|
||||
change_series_group->setExclusive(true);
|
||||
QStringList types{tr("Line"), tr("Step Line"), tr("Scatter")};
|
||||
for (int i = 0; i < types.size(); ++i) {
|
||||
QAction *act = new QAction(types[i], change_series_group);
|
||||
act->setData(i);
|
||||
act->setCheckable(true);
|
||||
act->setChecked(i == (int)series_type);
|
||||
menu->addAction(act);
|
||||
}
|
||||
menu->addSeparator();
|
||||
menu->addAction(tr("Manage Signals"), this, &ChartView::manageSignals);
|
||||
split_chart_act = menu->addAction(tr("Split Chart"), [this]() { charts_widget->splitChart(this); });
|
||||
|
||||
manage_btn = new ToolButton("list", "", this);
|
||||
manage_btn->setMenu(menu);
|
||||
manage_btn->setPopupMode(QToolButton::InstantPopup);
|
||||
manage_btn->setStyleSheet("QToolButton::menu-indicator { image: none; }");
|
||||
|
||||
close_act = new QAction(tr("Close"), this);
|
||||
QObject::connect(close_act, &QAction::triggered, [this] () { charts_widget->removeChart(this); });
|
||||
QObject::connect(close_btn, &QToolButton::clicked, close_act, &QAction::triggered);
|
||||
QObject::connect(change_series_group, &QActionGroup::triggered, [this](QAction *action) {
|
||||
setSeriesType((SeriesType)action->data().toInt());
|
||||
});
|
||||
}
|
||||
|
||||
QSize ChartView::sizeHint() const {
|
||||
return {CHART_MIN_WIDTH, settings.chart_height};
|
||||
}
|
||||
|
||||
void ChartView::addSignal(const MessageId &msg_id, const cabana::Signal *sig) {
|
||||
if (hasSignal(msg_id, sig)) return;
|
||||
|
||||
sigs.push_back({.msg_id = msg_id, .sig = sig, .color = uniqueColor(toQColor(sig->color))});
|
||||
updateSeries(sig);
|
||||
updateTitle();
|
||||
emit charts_widget->seriesChanged();
|
||||
}
|
||||
|
||||
bool ChartView::hasSignal(const MessageId &msg_id, const cabana::Signal *sig) const {
|
||||
return std::any_of(sigs.cbegin(), sigs.cend(), [&](auto &s) { return s.msg_id == msg_id && s.sig == sig; });
|
||||
}
|
||||
|
||||
void ChartView::removeIf(std::function<bool(const SigItem &s)> predicate) {
|
||||
int prev_size = sigs.size();
|
||||
sigs.erase(std::remove_if(sigs.begin(), sigs.end(), predicate), sigs.end());
|
||||
if (sigs.empty()) {
|
||||
charts_widget->removeChart(this);
|
||||
} else if (sigs.size() != prev_size) {
|
||||
emit charts_widget->seriesChanged();
|
||||
updateAxisY();
|
||||
updateTitle();
|
||||
}
|
||||
}
|
||||
|
||||
void ChartView::signalUpdated(const cabana::Signal *sig) {
|
||||
auto it = std::find_if(sigs.begin(), sigs.end(), [sig](auto &s) { return s.sig == sig; });
|
||||
if (it != sigs.end()) {
|
||||
if (it->color != toQColor(sig->color)) {
|
||||
it->color = uniqueColor(toQColor(sig->color), sig);
|
||||
}
|
||||
updateTitle();
|
||||
updateSeries(sig);
|
||||
}
|
||||
}
|
||||
|
||||
void ChartView::msgUpdated(MessageId id) {
|
||||
if (std::any_of(sigs.cbegin(), sigs.cend(), [=](auto &s) { return s.msg_id.address == id.address; })) {
|
||||
updateTitle();
|
||||
}
|
||||
}
|
||||
|
||||
void ChartView::manageSignals() {
|
||||
SignalSelector dlg(tr("Manage Chart"), this);
|
||||
for (auto &s : sigs) {
|
||||
dlg.addSelected(s.msg_id, s.sig);
|
||||
}
|
||||
if (dlg.exec() == QDialog::Accepted) {
|
||||
auto items = dlg.seletedItems();
|
||||
for (auto s : items) {
|
||||
addSignal(s->msg_id, s->sig);
|
||||
}
|
||||
removeIf([&](auto &s) {
|
||||
return std::none_of(items.cbegin(), items.cend(), [&](auto &it) { return s.msg_id == it->msg_id && s.sig == it->sig; });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void ChartView::resizeEvent(QResizeEvent *event) {
|
||||
QWidget::resizeEvent(event);
|
||||
const auto margins = layoutMargins(style());
|
||||
QPixmap grip = utils::icon("grip-horizontal");
|
||||
move_icon_rect = QRect(QPoint(margins.left(), margins.top()), grip.size() / grip.devicePixelRatio());
|
||||
close_btn->resize(close_btn->sizeHint());
|
||||
manage_btn->resize(manage_btn->sizeHint());
|
||||
close_btn->move(rect().right() - margins.right() - close_btn->width(), margins.top());
|
||||
manage_btn->move(close_btn->x() - manage_btn->width() - style()->pixelMetric(QStyle::PM_LayoutHorizontalSpacing), margins.top());
|
||||
updatePlotArea(align_to, true);
|
||||
}
|
||||
|
||||
void ChartView::updatePlotArea(int left_pos, bool force) {
|
||||
if (align_to != left_pos || force) {
|
||||
align_to = left_pos;
|
||||
|
||||
const auto margins = layoutMargins(style());
|
||||
QFont bold_font = font();
|
||||
bold_font.setBold(true);
|
||||
QFontMetrics fm(font()), bfm(bold_font);
|
||||
const int marker_size = fm.height() - 4;
|
||||
const int row_height = std::max(marker_size, fm.height()) + QFontMetrics(signal_value_font).height() + 3;
|
||||
const int legend_left = move_icon_rect.right() + margins.left();
|
||||
const int legend_right = std::max(manage_btn->x() - margins.right(), legend_left + 10);
|
||||
|
||||
// layout legend entries left-to-right, wrapping between the move icon and the buttons
|
||||
legend_rects.clear();
|
||||
int x = legend_left, y = margins.top();
|
||||
for (auto &s : sigs) {
|
||||
int w = marker_size + 5 + bfm.horizontalAdvance(QString::fromStdString(s.sig->name)) +
|
||||
fm.horizontalAdvance(QString::fromStdString(" " + msgName(s.msg_id) + " " + s.msg_id.toString()));
|
||||
w = std::min(w, legend_right - legend_left); // keep oversized entries clear of the header buttons
|
||||
if (x + w > legend_right && x > legend_left) {
|
||||
x = legend_left;
|
||||
y += row_height;
|
||||
}
|
||||
legend_rects.emplace_back(x, y, w, std::max(marker_size, fm.height()));
|
||||
x += w + 12;
|
||||
}
|
||||
|
||||
// add top space for the legend and signal values
|
||||
int adjust_top = (y + row_height) - margins.top();
|
||||
adjust_top = std::max(adjust_top, manage_btn->geometry().bottom() + style()->pixelMetric(QStyle::PM_LayoutTopMargin));
|
||||
// add right space for x-axis label
|
||||
QSizeF x_label_size = fm.size(Qt::TextSingleLine, QString::number(x_max, 'f', xAxisPrecision())) + QSizeF{5, 5};
|
||||
plot_area = rect().adjusted(align_to + margins.left(), adjust_top + margins.top(),
|
||||
-x_label_size.width() / 2 - margins.right(),
|
||||
-x_label_size.height() - margins.bottom());
|
||||
resetChartCache();
|
||||
}
|
||||
}
|
||||
|
||||
void ChartView::updateTitle() {
|
||||
split_chart_act->setEnabled(sigs.size() > 1);
|
||||
updatePlotArea(align_to, true);
|
||||
}
|
||||
|
||||
void ChartView::updatePlot(double cur, double min, double max) {
|
||||
cur_sec = cur;
|
||||
if (min != x_min || max != x_max) {
|
||||
x_min = min;
|
||||
x_max = max;
|
||||
updateAxisY();
|
||||
// update tooltip
|
||||
if (tooltip_x >= 0) {
|
||||
showTip(secondsAtPoint({tooltip_x, 0}));
|
||||
}
|
||||
resetChartCache();
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
void ChartView::appendCanEvents(const cabana::Signal *sig, const std::vector<const CanEvent *> &events,
|
||||
std::vector<QPointF> &vals, std::vector<QPointF> &step_vals) {
|
||||
vals.reserve(vals.size() + events.capacity());
|
||||
step_vals.reserve(step_vals.size() + events.capacity() * 2);
|
||||
|
||||
double value = 0;
|
||||
for (const CanEvent *e : events) {
|
||||
if (sig->getValue(e->dat, e->size, &value)) {
|
||||
const double ts = can->toSeconds(e->mono_time);
|
||||
vals.emplace_back(ts, value);
|
||||
if (!step_vals.empty())
|
||||
step_vals.emplace_back(ts, step_vals.back().y());
|
||||
step_vals.emplace_back(ts, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ChartView::updateSeries(const cabana::Signal *sig, const MessageEventsMap *msg_new_events) {
|
||||
for (auto &s : sigs) {
|
||||
if (!sig || s.sig == sig) {
|
||||
if (!msg_new_events) {
|
||||
s.vals.clear();
|
||||
s.step_vals.clear();
|
||||
}
|
||||
auto events = msg_new_events ? msg_new_events : &can->eventsMap();
|
||||
auto it = events->find(s.msg_id);
|
||||
if (it == events->end() || it->second.empty()) continue;
|
||||
|
||||
if (s.vals.empty() || can->toSeconds(it->second.back()->mono_time) > s.vals.back().x()) {
|
||||
appendCanEvents(s.sig, it->second, s.vals, s.step_vals);
|
||||
} else {
|
||||
std::vector<QPointF> vals, step_vals;
|
||||
appendCanEvents(s.sig, it->second, vals, step_vals);
|
||||
s.vals.insert(std::lower_bound(s.vals.begin(), s.vals.end(), vals.front().x(), xLessThan),
|
||||
vals.begin(), vals.end());
|
||||
s.step_vals.insert(std::lower_bound(s.step_vals.begin(), s.step_vals.end(), step_vals.front().x(), xLessThan),
|
||||
step_vals.begin(), step_vals.end());
|
||||
}
|
||||
|
||||
if (!can->liveStreaming()) {
|
||||
s.segment_tree.build(s.vals);
|
||||
}
|
||||
}
|
||||
}
|
||||
updateAxisY();
|
||||
// invoke resetChartCache in ui thread
|
||||
QMetaObject::invokeMethod(this, &ChartView::resetChartCache, Qt::QueuedConnection);
|
||||
}
|
||||
|
||||
// auto zoom on yaxis
|
||||
void ChartView::updateAxisY() {
|
||||
if (sigs.empty()) return;
|
||||
|
||||
double min = std::numeric_limits<double>::max();
|
||||
double max = std::numeric_limits<double>::lowest();
|
||||
QString unit = QString::fromStdString(sigs[0].sig->unit);
|
||||
|
||||
for (auto &s : sigs) {
|
||||
if (!s.visible) continue;
|
||||
|
||||
// Only show unit when all signals have the same unit
|
||||
if (unit != QString::fromStdString(s.sig->unit)) {
|
||||
unit.clear();
|
||||
}
|
||||
|
||||
auto first = std::lower_bound(s.vals.cbegin(), s.vals.cend(), x_min, xLessThan);
|
||||
auto last = std::lower_bound(first, s.vals.cend(), x_max, xLessThan);
|
||||
s.min = std::numeric_limits<double>::max();
|
||||
s.max = std::numeric_limits<double>::lowest();
|
||||
if (can->liveStreaming()) {
|
||||
for (auto it = first; it != last; ++it) {
|
||||
if (it->y() < s.min) s.min = it->y();
|
||||
if (it->y() > s.max) s.max = it->y();
|
||||
}
|
||||
} else {
|
||||
std::tie(s.min, s.max) = s.segment_tree.minmax(std::distance(s.vals.cbegin(), first), std::distance(s.vals.cbegin(), last));
|
||||
}
|
||||
min = std::min(min, s.min);
|
||||
max = std::max(max, s.max);
|
||||
}
|
||||
if (min == std::numeric_limits<double>::max()) min = 0;
|
||||
if (max == std::numeric_limits<double>::lowest()) max = 0;
|
||||
|
||||
if (y_unit != unit) {
|
||||
y_unit = unit;
|
||||
y_label_width = 0; // recalc width
|
||||
}
|
||||
|
||||
double delta = std::abs(max - min) < 1e-3 ? 1 : (max - min) * 0.05;
|
||||
auto [min_y, max_y, tick_count] = getNiceAxisNumbers(min - delta, max + delta, 3);
|
||||
if (min_y != y_min || max_y != y_max || y_label_width == 0) {
|
||||
y_min = min_y;
|
||||
y_max = max_y;
|
||||
y_tick_count = tick_count;
|
||||
y_precision = std::max(int(-std::floor(std::log10((max_y - min_y) / (tick_count - 1)))), 0);
|
||||
|
||||
QFontMetrics fm(font());
|
||||
int max_label_width = 0;
|
||||
for (int i = 0; i < tick_count; i++) {
|
||||
qreal value = min_y + (i * (max_y - min_y) / (tick_count - 1));
|
||||
max_label_width = std::max(max_label_width, fm.horizontalAdvance(QString::number(value, 'f', y_precision)));
|
||||
}
|
||||
|
||||
int title_spacing = y_unit.isEmpty() ? 0 : fm.size(Qt::TextSingleLine, y_unit).height();
|
||||
y_label_width = title_spacing + max_label_width + 15;
|
||||
emit axisYLabelWidthChanged(y_label_width);
|
||||
}
|
||||
}
|
||||
|
||||
std::tuple<double, double, int> ChartView::getNiceAxisNumbers(qreal min, qreal max, int tick_count) {
|
||||
qreal range = niceNumber((max - min), true); // range with ceiling
|
||||
qreal step = niceNumber(range / (tick_count - 1), false);
|
||||
min = std::floor(min / step);
|
||||
max = std::ceil(max / step);
|
||||
tick_count = int(max - min) + 1;
|
||||
return {min * step, max * step, tick_count};
|
||||
}
|
||||
|
||||
int ChartView::xAxisPrecision() const {
|
||||
return std::max(int(-std::floor(std::log10((x_max - x_min) / (X_TICK_COUNT - 1)))), 2);
|
||||
}
|
||||
|
||||
// nice numbers can be expressed as form of 1*10^n, 2* 10^n or 5*10^n
|
||||
qreal ChartView::niceNumber(qreal x, bool ceiling) {
|
||||
qreal z = std::pow(10, std::floor(std::log10(x))); //find corresponding number of the form of 10^n than is smaller than x
|
||||
qreal q = x / z; //q<10 && q>=1;
|
||||
if (ceiling) {
|
||||
if (q <= 1.0) q = 1;
|
||||
else if (q <= 2.0) q = 2;
|
||||
else if (q <= 5.0) q = 5;
|
||||
else q = 10;
|
||||
} else {
|
||||
if (q < 1.5) q = 1;
|
||||
else if (q < 3.0) q = 2;
|
||||
else if (q < 7.0) q = 5;
|
||||
else q = 10;
|
||||
}
|
||||
return q * z;
|
||||
}
|
||||
|
||||
void ChartView::contextMenuEvent(QContextMenuEvent *event) {
|
||||
QMenu context_menu(this);
|
||||
context_menu.addActions(menu->actions());
|
||||
context_menu.addSeparator();
|
||||
context_menu.addAction(charts_widget->undo_zoom_action);
|
||||
context_menu.addAction(charts_widget->redo_zoom_action);
|
||||
context_menu.addSeparator();
|
||||
context_menu.addAction(close_act);
|
||||
context_menu.exec(event->globalPos());
|
||||
}
|
||||
|
||||
void ChartView::mousePressEvent(QMouseEvent *event) {
|
||||
press_pos = event->pos();
|
||||
if (event->button() == Qt::LeftButton && move_icon_rect.contains(event->pos())) {
|
||||
charts_widget->startChartDrag(this, event->globalPos());
|
||||
} else if (event->button() == Qt::LeftButton && event->modifiers().testFlag(Qt::ShiftModifier)) {
|
||||
// Save current playback state when scrubbing
|
||||
resume_after_scrub = !can->isPaused();
|
||||
if (resume_after_scrub) {
|
||||
can->pause(true);
|
||||
}
|
||||
mouse_mode = MouseMode::Scrub;
|
||||
} else if (event->button() == Qt::LeftButton && plot_area.contains(event->pos())) {
|
||||
mouse_mode = MouseMode::Rubber;
|
||||
rubber_rect = QRect();
|
||||
} else {
|
||||
QWidget::mousePressEvent(event);
|
||||
}
|
||||
}
|
||||
|
||||
void ChartView::mouseMoveEvent(QMouseEvent *ev) {
|
||||
// Scrubbing
|
||||
if (mouse_mode == MouseMode::Scrub && ev->modifiers().testFlag(Qt::ShiftModifier)) {
|
||||
if (plot_area.contains(ev->pos())) {
|
||||
can->seekTo(std::clamp(secondsAtPoint(ev->pos()), can->minSeconds(), can->maxSeconds()));
|
||||
}
|
||||
}
|
||||
|
||||
if (mouse_mode == MouseMode::Rubber) {
|
||||
// horizontal selection, clamped to the plot area
|
||||
int left = std::clamp(std::min(press_pos.x(), ev->pos().x()), plot_area.left(), plot_area.right());
|
||||
int right = std::clamp(std::max(press_pos.x(), ev->pos().x()), plot_area.left(), plot_area.right());
|
||||
rubber_rect = QRect(left, plot_area.top(), right - left, plot_area.height());
|
||||
update();
|
||||
}
|
||||
|
||||
clearTrackPoints();
|
||||
if (mouse_mode != MouseMode::Rubber && plot_area.contains(ev->pos()) && isActiveWindow()) {
|
||||
charts_widget->showValueTip(secondsAtPoint(ev->pos()));
|
||||
} else if (tip_label->isVisible()) {
|
||||
charts_widget->showValueTip(-1);
|
||||
}
|
||||
QWidget::mouseMoveEvent(ev);
|
||||
}
|
||||
|
||||
void ChartView::mouseReleaseEvent(QMouseEvent *event) {
|
||||
if (event->button() == Qt::LeftButton && mouse_mode == MouseMode::Rubber) {
|
||||
mouse_mode = MouseMode::None;
|
||||
// Prevent zooming/seeking past the end of the route
|
||||
double min = std::clamp(secondsAtPoint(rubber_rect.topLeft()), can->minSeconds(), can->maxSeconds());
|
||||
double max = std::clamp(secondsAtPoint(rubber_rect.bottomRight()), can->minSeconds(), can->maxSeconds());
|
||||
if (rubber_rect.width() <= 0) {
|
||||
// no rubber dragged, seek to mouse position
|
||||
can->seekTo(std::clamp(secondsAtPoint(press_pos), can->minSeconds(), can->maxSeconds()));
|
||||
} else if (rubber_rect.width() > 10 && (max - min) > MIN_ZOOM_SECONDS) {
|
||||
charts_widget->zoom_undo_stack.push(new ZoomCommand({min, max}));
|
||||
}
|
||||
rubber_rect = QRect();
|
||||
update();
|
||||
} else if (event->button() == Qt::LeftButton && mouse_mode == MouseMode::None && sigs.size() > 1) {
|
||||
// toggle series visibility by clicking its legend entry
|
||||
for (int i = 0; i < sigs.size() && i < legend_rects.size(); ++i) {
|
||||
if (legend_rects[i].contains(press_pos) && legend_rects[i].contains(event->pos())) {
|
||||
sigs[i].visible = !sigs[i].visible;
|
||||
updateAxisY();
|
||||
updateTitle();
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (event->button() == Qt::RightButton) {
|
||||
charts_widget->zoom_undo_stack.undo();
|
||||
} else {
|
||||
QWidget::mouseReleaseEvent(event);
|
||||
}
|
||||
|
||||
// Resume playback if we were scrubbing
|
||||
if (mouse_mode == MouseMode::Scrub) {
|
||||
mouse_mode = MouseMode::None;
|
||||
if (resume_after_scrub) {
|
||||
can->pause(false);
|
||||
resume_after_scrub = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ChartView::takeSignalsFrom(ChartView *source) {
|
||||
for (auto &s : source->sigs) {
|
||||
sigs.push_back(std::move(s));
|
||||
sigs.back().color = uniqueColor(sigs.back().color, sigs.back().sig);
|
||||
}
|
||||
source->sigs.clear();
|
||||
updateAxisY();
|
||||
updateTitle();
|
||||
charts_widget->removeChart(source);
|
||||
}
|
||||
|
||||
void ChartView::showTip(double sec) {
|
||||
QRect tip_area(0, plot_area.top(), rect().width(), plot_area.height());
|
||||
QRect visible_rect = charts_widget->chartVisibleRect(this).intersected(tip_area);
|
||||
if (visible_rect.isEmpty()) {
|
||||
tip_label->hide();
|
||||
return;
|
||||
}
|
||||
|
||||
tooltip_x = xPos(sec);
|
||||
qreal x = -1;
|
||||
QStringList text_list;
|
||||
for (auto &s : sigs) {
|
||||
if (s.visible) {
|
||||
QString value = "--";
|
||||
// use reverse iterator to find last item <= sec.
|
||||
auto it = std::lower_bound(s.vals.crbegin(), s.vals.crend(), sec, [](auto &p, double v) { return p.x() > v; });
|
||||
if (it != s.vals.crend() && it->x() >= x_min) {
|
||||
value = QString::fromStdString(s.sig->formatValue(it->y(), false));
|
||||
s.track_pt = *it;
|
||||
x = std::max(x, xPos(it->x()));
|
||||
}
|
||||
QString name = sigs.size() > 1 ? QString::fromStdString(s.sig->name) + ": " : "";
|
||||
QString min = s.min == std::numeric_limits<double>::max() ? "--" : QString::number(s.min);
|
||||
QString max = s.max == std::numeric_limits<double>::lowest() ? "--" : QString::number(s.max);
|
||||
text_list << QString("<span style=\"color:%1;\">■ </span>%2<b>%3</b> (%4, %5)")
|
||||
.arg(s.color.name(), name, value, min, max);
|
||||
}
|
||||
}
|
||||
if (x < 0) {
|
||||
x = tooltip_x;
|
||||
}
|
||||
QPoint pt(x, plot_area.top());
|
||||
text_list.push_front(QString::number(secondsAtPoint({x, 0}), 'f', 3));
|
||||
QString text = "<p style='white-space:pre'>" % text_list.join("<br />") % "</p>";
|
||||
tip_label->showText(pt, text, this, visible_rect);
|
||||
update();
|
||||
}
|
||||
|
||||
void ChartView::hideTip() {
|
||||
clearTrackPoints();
|
||||
tooltip_x = -1;
|
||||
tip_label->hide();
|
||||
update();
|
||||
}
|
||||
|
||||
void ChartView::resetChartCache() {
|
||||
chart_pixmap = QPixmap();
|
||||
update();
|
||||
}
|
||||
|
||||
void ChartView::paintEvent(QPaintEvent *event) {
|
||||
QPainter painter(this);
|
||||
painter.setRenderHints(QPainter::Antialiasing);
|
||||
|
||||
// the static layer is invalidated on x-range change and data merge, so cache it in live mode too
|
||||
const qreal dpr = devicePixelRatioF();
|
||||
if (chart_pixmap.isNull() || chart_pixmap.size() != size() * dpr) {
|
||||
chart_pixmap = QPixmap(size() * dpr);
|
||||
chart_pixmap.setDevicePixelRatio(dpr);
|
||||
QPainter p(&chart_pixmap);
|
||||
p.setRenderHints(QPainter::Antialiasing);
|
||||
p.setFont(font());
|
||||
drawStaticLayer(&p);
|
||||
}
|
||||
painter.drawPixmap(QPoint(), chart_pixmap);
|
||||
|
||||
if (can_drop) {
|
||||
painter.setPen(QPen(palette().color(QPalette::Highlight), 4));
|
||||
painter.drawRect(rect());
|
||||
}
|
||||
drawForeground(&painter);
|
||||
}
|
||||
|
||||
void ChartView::drawStaticLayer(QPainter *painter) {
|
||||
painter->fillRect(rect(), palette().color(QPalette::Base));
|
||||
painter->drawPixmap(move_icon_rect.topLeft(), utils::icon("grip-horizontal"));
|
||||
drawAxes(painter);
|
||||
drawLegend(painter);
|
||||
drawSeries(painter);
|
||||
}
|
||||
|
||||
void ChartView::drawAxes(QPainter *painter) {
|
||||
const QColor text_color = palette().color(QPalette::Text);
|
||||
QColor grid_color = text_color;
|
||||
grid_color.setAlpha(50);
|
||||
QFontMetrics fm(font());
|
||||
painter->setFont(font());
|
||||
|
||||
// y grid lines and tick labels
|
||||
for (int i = 0; i < y_tick_count; ++i) {
|
||||
double value = y_min + i * (y_max - y_min) / (y_tick_count - 1);
|
||||
qreal y = yPos(value);
|
||||
painter->setPen(grid_color);
|
||||
painter->drawLine(QPointF(plot_area.left(), y), QPointF(plot_area.right(), y));
|
||||
painter->setPen(text_color);
|
||||
QRectF label_rect(0, y - fm.height() / 2.0, plot_area.left() - 6, fm.height());
|
||||
painter->drawText(label_rect, Qt::AlignRight | Qt::AlignVCenter, QString::number(value, 'f', y_precision));
|
||||
}
|
||||
|
||||
// rotated y axis title (unit)
|
||||
if (!y_unit.isEmpty()) {
|
||||
painter->save();
|
||||
painter->translate(plot_area.left() - y_label_width + fm.height() / 2.0, plot_area.center().y());
|
||||
painter->rotate(-90);
|
||||
painter->drawText(QRectF(-plot_area.height() / 2.0, -fm.height() / 2.0, plot_area.height(), fm.height()),
|
||||
Qt::AlignCenter, y_unit);
|
||||
painter->restore();
|
||||
}
|
||||
|
||||
// x grid lines and tick labels
|
||||
const int x_precision = xAxisPrecision();
|
||||
for (int i = 0; i < X_TICK_COUNT; ++i) {
|
||||
double sec = x_min + i * (x_max - x_min) / (X_TICK_COUNT - 1);
|
||||
qreal x = xPos(sec);
|
||||
painter->setPen(grid_color);
|
||||
painter->drawLine(QPointF(x, plot_area.top()), QPointF(x, plot_area.bottom()));
|
||||
painter->setPen(text_color);
|
||||
QString label = QString::number(sec, 'f', x_precision);
|
||||
QRectF label_rect(x - 100, plot_area.bottom() + AXIS_X_TOP_MARGIN, 200, fm.height());
|
||||
painter->drawText(label_rect, Qt::AlignHCenter | Qt::AlignTop, label);
|
||||
}
|
||||
}
|
||||
|
||||
void ChartView::drawLegend(QPainter *painter) {
|
||||
QColor title_color = palette().color(QPalette::WindowText);
|
||||
// Draw message details in similar color, but slightly fade it to the background
|
||||
QColor msg_color = title_color;
|
||||
msg_color.setAlpha(180);
|
||||
QFont bold_font = font();
|
||||
bold_font.setBold(true);
|
||||
const int marker_size = QFontMetrics(font()).height() - 4;
|
||||
|
||||
for (int i = 0; i < sigs.size() && i < legend_rects.size(); ++i) {
|
||||
const auto &s = sigs[i];
|
||||
const QRect &r = legend_rects[i];
|
||||
painter->setPen(Qt::NoPen);
|
||||
painter->setBrush(s.color);
|
||||
QRectF marker_rect(r.left(), r.center().y() - marker_size / 2.0, marker_size, marker_size);
|
||||
series_type == SeriesType::Scatter ? painter->drawEllipse(marker_rect) : painter->drawRect(marker_rect);
|
||||
|
||||
bold_font.setStrikeOut(!s.visible);
|
||||
QFont normal_font = font();
|
||||
normal_font.setStrikeOut(!s.visible);
|
||||
|
||||
qreal x = r.left() + marker_size + 5;
|
||||
painter->setFont(bold_font);
|
||||
painter->setPen(title_color);
|
||||
QString name = QFontMetrics(bold_font).elidedText(QString::fromStdString(s.sig->name), Qt::ElideRight, r.right() - x);
|
||||
painter->drawText(QRectF(x, r.top(), r.right() - x, r.height()), Qt::AlignLeft | Qt::AlignVCenter, name);
|
||||
x += QFontMetrics(bold_font).horizontalAdvance(name);
|
||||
painter->setFont(normal_font);
|
||||
painter->setPen(msg_color);
|
||||
QString msg = QFontMetrics(normal_font).elidedText(QString::fromStdString(" " + msgName(s.msg_id) + " " + s.msg_id.toString()),
|
||||
Qt::ElideRight, r.right() - x);
|
||||
painter->drawText(QRectF(x, r.top(), r.right() - x, r.height()), Qt::AlignLeft | Qt::AlignVCenter, msg);
|
||||
}
|
||||
}
|
||||
|
||||
void ChartView::drawSeries(QPainter *painter) {
|
||||
painter->save();
|
||||
painter->setClipRect(plot_area);
|
||||
for (auto &s : sigs) {
|
||||
if (!s.visible) continue;
|
||||
|
||||
// visible points in vals to compute point density
|
||||
auto first = std::lower_bound(s.vals.cbegin(), s.vals.cend(), x_min, xLessThan);
|
||||
auto last = std::lower_bound(first, s.vals.cend(), x_max, xLessThan);
|
||||
int num_points = std::max<int>(last - first, 1);
|
||||
double pixels_per_point = 0;
|
||||
if (first != last) {
|
||||
const QPointF &right_pt = last == s.vals.cend() ? s.vals.back() : *last;
|
||||
pixels_per_point = (xPos(right_pt.x()) - xPos(first->x())) / num_points;
|
||||
}
|
||||
|
||||
if (series_type == SeriesType::Scatter) {
|
||||
qreal radius = std::clamp(pixels_per_point / 2.0, 2.0, 8.0) / 2.0;
|
||||
painter->setPen(Qt::NoPen);
|
||||
painter->setBrush(s.color);
|
||||
for (auto it = first; it != last; ++it) {
|
||||
painter->drawEllipse(QPointF(xPos(it->x()), yPos(it->y())), radius, radius);
|
||||
}
|
||||
} else {
|
||||
const auto &points = series_type == SeriesType::StepLine ? s.step_vals : s.vals;
|
||||
auto begin = std::lower_bound(points.cbegin(), points.cend(), x_min, xLessThan);
|
||||
if (begin != points.cbegin()) --begin;
|
||||
auto end = std::lower_bound(begin, points.cend(), x_max, xLessThan);
|
||||
if (end != points.cend()) ++end;
|
||||
if (begin == end) continue;
|
||||
|
||||
std::vector<QPointF> polyline;
|
||||
polyline.reserve(end - begin);
|
||||
for (auto it = begin; it != end; ++it) {
|
||||
polyline.emplace_back(xPos(it->x()), yPos(it->y()));
|
||||
}
|
||||
painter->setPen(QPen(s.color, 2));
|
||||
painter->setBrush(Qt::NoBrush);
|
||||
painter->drawPolyline(polyline.data(), polyline.size());
|
||||
|
||||
// show points when zoomed in enough
|
||||
if (num_points == 1 || pixels_per_point > 20) {
|
||||
painter->setPen(Qt::NoPen);
|
||||
painter->setBrush(s.color);
|
||||
for (auto it = first; it != last; ++it) {
|
||||
painter->drawEllipse(QPointF(xPos(it->x()), yPos(it->y())), 4, 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
painter->restore();
|
||||
}
|
||||
|
||||
void ChartView::drawForeground(QPainter *painter) {
|
||||
drawTimeline(painter);
|
||||
drawSignalValue(painter);
|
||||
// draw track points
|
||||
painter->setPen(Qt::NoPen);
|
||||
qreal track_line_x = -1;
|
||||
for (auto &s : sigs) {
|
||||
if (!s.track_pt.isNull() && s.visible) {
|
||||
painter->setBrush(s.color.darker(125));
|
||||
QPointF pos(xPos(s.track_pt.x()), yPos(s.track_pt.y()));
|
||||
painter->drawEllipse(pos, 5.5, 5.5);
|
||||
track_line_x = std::max(track_line_x, pos.x());
|
||||
}
|
||||
}
|
||||
if (track_line_x > 0) {
|
||||
painter->setPen(QPen(Qt::darkGray, 1, Qt::DashLine));
|
||||
painter->drawLine(QPointF{track_line_x, (qreal)plot_area.top()}, QPointF{track_line_x, (qreal)plot_area.bottom()});
|
||||
}
|
||||
|
||||
drawRubberBandTimeRange(painter);
|
||||
}
|
||||
|
||||
void ChartView::drawRubberBandTimeRange(QPainter *painter) {
|
||||
if (rubber_rect.width() <= 1) return;
|
||||
|
||||
// selection rect
|
||||
QColor highlight = palette().color(QPalette::Highlight);
|
||||
QColor fill = highlight;
|
||||
fill.setAlpha(50);
|
||||
painter->fillRect(rubber_rect, fill);
|
||||
painter->setPen(highlight);
|
||||
painter->setBrush(Qt::NoBrush);
|
||||
painter->drawRect(rubber_rect);
|
||||
|
||||
// time labels at the bottom corners
|
||||
painter->setPen(Qt::white);
|
||||
painter->setFont(font());
|
||||
for (const auto &pt : {rubber_rect.bottomLeft(), rubber_rect.bottomRight()}) {
|
||||
QString sec = QString::number(secondsAtPoint(pt), 'f', 2);
|
||||
auto r = painter->fontMetrics().boundingRect(sec).adjusted(-6, -AXIS_X_TOP_MARGIN, 6, AXIS_X_TOP_MARGIN);
|
||||
pt == rubber_rect.bottomLeft() ? r.moveTopRight(pt + QPoint{0, 2}) : r.moveTopLeft(pt + QPoint{0, 2});
|
||||
painter->fillRect(r, Qt::gray);
|
||||
painter->drawText(r, Qt::AlignCenter, sec);
|
||||
}
|
||||
}
|
||||
|
||||
void ChartView::drawTimeline(QPainter *painter) {
|
||||
// draw vertical time line
|
||||
qreal x = std::clamp(xPos(cur_sec), (qreal)plot_area.left(), (qreal)plot_area.right());
|
||||
painter->setPen(QPen(palette().color(QPalette::Text), 1));
|
||||
painter->drawLine(QPointF{x, plot_area.top() - 1.0}, QPointF{x, plot_area.bottom() + 1.0});
|
||||
|
||||
// draw current time under the axis-x
|
||||
QString time_str = QString::number(cur_sec, 'f', 2);
|
||||
QSize time_str_size = QFontMetrics(font()).size(Qt::TextSingleLine, time_str) + QSize(8, 2);
|
||||
QRectF time_str_rect(QPointF(x - time_str_size.width() / 2.0, plot_area.bottom() + AXIS_X_TOP_MARGIN), time_str_size);
|
||||
QPainterPath path;
|
||||
path.addRoundedRect(time_str_rect, 3, 3);
|
||||
painter->fillPath(path, utils::isDarkTheme() ? Qt::darkGray : Qt::gray);
|
||||
painter->setPen(palette().color(QPalette::BrightText));
|
||||
painter->setFont(font());
|
||||
painter->drawText(time_str_rect, Qt::AlignCenter, time_str);
|
||||
}
|
||||
|
||||
void ChartView::drawSignalValue(QPainter *painter) {
|
||||
painter->setFont(signal_value_font);
|
||||
painter->setPen(palette().color(QPalette::Text));
|
||||
for (int i = 0; i < sigs.size() && i < legend_rects.size(); ++i) {
|
||||
const auto &s = sigs[i];
|
||||
auto it = std::lower_bound(s.vals.crbegin(), s.vals.crend(), cur_sec,
|
||||
[](auto &p, double x) { return p.x() > x + EPSILON; });
|
||||
QString value = (it != s.vals.crend() && it->x() >= x_min) ? QString::fromStdString(s.sig->formatValue(it->y())) : "--";
|
||||
QRectF value_rect(legend_rects[i].bottomLeft() - QPoint(0, 1), legend_rects[i].size());
|
||||
QString elided_val = painter->fontMetrics().elidedText(value, Qt::ElideRight, value_rect.width());
|
||||
painter->drawText(value_rect, Qt::AlignHCenter | Qt::AlignTop, elided_val);
|
||||
}
|
||||
}
|
||||
|
||||
QColor ChartView::uniqueColor(QColor color, const cabana::Signal *exclude) const {
|
||||
for (auto &s : sigs) {
|
||||
if (s.sig != exclude && std::abs(color.hueF() - s.color.hueF()) < 0.1) {
|
||||
// use different color to distinguish it from others.
|
||||
auto last_color = sigs.back().color;
|
||||
static thread_local std::mt19937 rng{std::random_device{}()};
|
||||
std::uniform_int_distribution<int> sat(35, 99);
|
||||
std::uniform_int_distribution<int> val(85, 99);
|
||||
color.setHsvF(std::fmod(last_color.hueF() + 60 / 360.0, 1.0),
|
||||
sat(rng) / 100.0,
|
||||
val(rng) / 100.0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return color;
|
||||
}
|
||||
|
||||
void ChartView::setSeriesType(SeriesType type) {
|
||||
if (type != series_type) {
|
||||
series_type = type;
|
||||
menu->actions()[(int)type]->setChecked(true);
|
||||
updateTitle();
|
||||
}
|
||||
}
|
||||
130
iqpilot/tools/cabana/chart/chart.h
Normal file
130
iqpilot/tools/cabana/chart/chart.h
Normal file
@@ -0,0 +1,130 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
#include <tuple>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include <QMenu>
|
||||
|
||||
#include "tools/cabana/chart/tiplabel.h"
|
||||
#include "tools/cabana/dbc/dbcmanager.h"
|
||||
#include "tools/cabana/streams/abstractstream.h"
|
||||
|
||||
enum class SeriesType {
|
||||
Line = 0,
|
||||
StepLine,
|
||||
Scatter
|
||||
};
|
||||
|
||||
class ChartsWidget;
|
||||
class ChartView : public QWidget {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
ChartView(const std::pair<double, double> &x_range, ChartsWidget *parent = nullptr);
|
||||
void addSignal(const MessageId &msg_id, const cabana::Signal *sig);
|
||||
bool hasSignal(const MessageId &msg_id, const cabana::Signal *sig) const;
|
||||
void updateSeries(const cabana::Signal *sig = nullptr, const MessageEventsMap *msg_new_events = nullptr);
|
||||
void updatePlot(double cur, double min, double max);
|
||||
void setSeriesType(SeriesType type);
|
||||
void updatePlotArea(int left, bool force = false);
|
||||
void showTip(double sec);
|
||||
void hideTip();
|
||||
double secondsAtPoint(const QPointF &pt) const {
|
||||
return x_min + (pt.x() - plot_area.left()) * (x_max - x_min) / std::max(plot_area.width(), 1);
|
||||
}
|
||||
|
||||
struct SigItem {
|
||||
MessageId msg_id;
|
||||
const cabana::Signal *sig = nullptr;
|
||||
QColor color;
|
||||
bool visible = true;
|
||||
std::vector<QPointF> vals;
|
||||
std::vector<QPointF> step_vals;
|
||||
QPointF track_pt{};
|
||||
SegmentTree segment_tree;
|
||||
double min = 0;
|
||||
double max = 0;
|
||||
};
|
||||
|
||||
signals:
|
||||
void axisYLabelWidthChanged(int w);
|
||||
|
||||
private slots:
|
||||
void signalUpdated(const cabana::Signal *sig);
|
||||
void manageSignals();
|
||||
void msgUpdated(MessageId id);
|
||||
void msgRemoved(MessageId id) { removeIf([=](auto &s) { return s.msg_id.address == id.address && !dbc()->msg(id); }); }
|
||||
void signalRemoved(const cabana::Signal *sig) { removeIf([=](auto &s) { return s.sig == sig; }); }
|
||||
|
||||
private:
|
||||
void appendCanEvents(const cabana::Signal *sig, const std::vector<const CanEvent *> &events,
|
||||
std::vector<QPointF> &vals, std::vector<QPointF> &step_vals);
|
||||
void createToolButtons();
|
||||
void contextMenuEvent(QContextMenuEvent *event) override;
|
||||
void mousePressEvent(QMouseEvent *event) override;
|
||||
void mouseMoveEvent(QMouseEvent *event) override;
|
||||
void mouseReleaseEvent(QMouseEvent *event) override;
|
||||
void resizeEvent(QResizeEvent *event) override;
|
||||
QSize sizeHint() const override;
|
||||
void updateAxisY();
|
||||
void updateTitle();
|
||||
void resetChartCache();
|
||||
void paintEvent(QPaintEvent *event) override;
|
||||
void drawStaticLayer(QPainter *painter);
|
||||
void drawAxes(QPainter *painter);
|
||||
void drawLegend(QPainter *painter);
|
||||
void drawSeries(QPainter *painter);
|
||||
void drawForeground(QPainter *painter);
|
||||
void drawSignalValue(QPainter *painter);
|
||||
void drawTimeline(QPainter *painter);
|
||||
void drawRubberBandTimeRange(QPainter *painter);
|
||||
int xAxisPrecision() const;
|
||||
std::tuple<double, double, int> getNiceAxisNumbers(qreal min, qreal max, int tick_count);
|
||||
qreal niceNumber(qreal x, bool ceiling);
|
||||
QColor uniqueColor(QColor color, const cabana::Signal *exclude = nullptr) const;
|
||||
void removeIf(std::function<bool(const SigItem &)> predicate);
|
||||
void takeSignalsFrom(ChartView *source);
|
||||
void setDropHighlight(bool highlight) { if (std::exchange(can_drop, highlight) != highlight) update(); }
|
||||
inline void clearTrackPoints() { for (auto &s : sigs) s.track_pt = {}; }
|
||||
inline qreal xPos(double sec) const { return plot_area.left() + (sec - x_min) / (x_max - x_min) * plot_area.width(); }
|
||||
inline qreal yPos(double val) const { return plot_area.bottom() - (val - y_min) / (y_max - y_min) * plot_area.height(); }
|
||||
|
||||
// layout
|
||||
QRect plot_area;
|
||||
QRect move_icon_rect;
|
||||
std::vector<QRect> legend_rects;
|
||||
// axes
|
||||
double x_min;
|
||||
double x_max;
|
||||
double y_min = 0;
|
||||
double y_max = 1;
|
||||
int y_tick_count = 3;
|
||||
int y_precision = 0;
|
||||
QString y_unit;
|
||||
int y_label_width = 0;
|
||||
int align_to = 0;
|
||||
// interaction
|
||||
enum class MouseMode { None, Rubber, Scrub };
|
||||
MouseMode mouse_mode = MouseMode::None;
|
||||
QPoint press_pos;
|
||||
QRect rubber_rect;
|
||||
bool resume_after_scrub = false;
|
||||
|
||||
QMenu *menu;
|
||||
QAction *split_chart_act;
|
||||
QAction *close_act;
|
||||
ToolButton *manage_btn;
|
||||
ToolButton *close_btn;
|
||||
TipLabel *tip_label;
|
||||
std::vector<SigItem> sigs;
|
||||
double cur_sec = 0;
|
||||
SeriesType series_type = SeriesType::Line;
|
||||
QPixmap chart_pixmap;
|
||||
bool can_drop = false;
|
||||
double tooltip_x = -1;
|
||||
QFont signal_value_font;
|
||||
ChartsWidget *charts_widget;
|
||||
friend class ChartsWidget;
|
||||
};
|
||||
661
iqpilot/tools/cabana/chart/chartswidget.cc
Normal file
661
iqpilot/tools/cabana/chart/chartswidget.cc
Normal file
@@ -0,0 +1,661 @@
|
||||
#include "tools/cabana/chart/chartswidget.h"
|
||||
#include "tools/cabana/dbc/dbcqt.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <future>
|
||||
|
||||
#include <QApplication>
|
||||
#include <QMenu>
|
||||
#include <QMouseEvent>
|
||||
#include <QScrollBar>
|
||||
#include <QToolBar>
|
||||
|
||||
#include "tools/cabana/chart/chart.h"
|
||||
|
||||
const int MAX_COLUMN_COUNT = 4;
|
||||
const int CHART_SPACING = 4;
|
||||
|
||||
ChartsWidget::ChartsWidget(QWidget *parent) : QFrame(parent) {
|
||||
align_timer = new QTimer(this);
|
||||
auto_scroll_timer = new QTimer(this);
|
||||
setFrameStyle(QFrame::StyledPanel | QFrame::Plain);
|
||||
QVBoxLayout *main_layout = new QVBoxLayout(this);
|
||||
main_layout->setContentsMargins(0, 0, 0, 0);
|
||||
main_layout->setSpacing(0);
|
||||
|
||||
// toolbar
|
||||
toolbar = new QToolBar(tr("Charts"), this);
|
||||
int icon_size = style()->pixelMetric(QStyle::PM_SmallIconSize);
|
||||
toolbar->setIconSize({icon_size, icon_size});
|
||||
|
||||
auto new_plot_btn = new ToolButton("file-plus", tr("New Chart"));
|
||||
auto new_tab_btn = new ToolButton("window-stack", tr("New Tab"));
|
||||
toolbar->addWidget(new_plot_btn);
|
||||
toolbar->addWidget(new_tab_btn);
|
||||
toolbar->addWidget(title_label = new QLabel());
|
||||
title_label->setContentsMargins(0, 0, style()->pixelMetric(QStyle::PM_LayoutHorizontalSpacing), 0);
|
||||
|
||||
auto chart_type_action = toolbar->addAction("");
|
||||
QMenu *chart_type_menu = new QMenu(this);
|
||||
auto types = std::array{tr("Line"), tr("Step"), tr("Scatter")};
|
||||
for (int i = 0; i < types.size(); ++i) {
|
||||
QString type_text = types[i];
|
||||
chart_type_menu->addAction(type_text, this, [=]() {
|
||||
settings.chart_series_type = i;
|
||||
chart_type_action->setText("Type: " + type_text);
|
||||
settingChanged();
|
||||
});
|
||||
}
|
||||
chart_type_action->setText("Type: " + types[settings.chart_series_type]);
|
||||
chart_type_action->setMenu(chart_type_menu);
|
||||
qobject_cast<QToolButton *>(toolbar->widgetForAction(chart_type_action))->setPopupMode(QToolButton::InstantPopup);
|
||||
|
||||
QMenu *menu = new QMenu(this);
|
||||
for (int i = 0; i < MAX_COLUMN_COUNT; ++i) {
|
||||
menu->addAction(tr("%1").arg(i + 1), [=]() { setColumnCount(i + 1); });
|
||||
}
|
||||
columns_action = toolbar->addAction("");
|
||||
columns_action->setMenu(menu);
|
||||
qobject_cast<QToolButton*>(toolbar->widgetForAction(columns_action))->setPopupMode(QToolButton::InstantPopup);
|
||||
|
||||
QWidget *spacer = new QWidget(this);
|
||||
spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
|
||||
toolbar->addWidget(spacer);
|
||||
|
||||
range_lb_action = toolbar->addWidget(range_lb = new QLabel(this));
|
||||
range_slider = new LogSlider(1000, Qt::Horizontal, this);
|
||||
range_slider->setFixedWidth(150 * qApp->devicePixelRatio());
|
||||
range_slider->setToolTip(tr("Set the chart range"));
|
||||
range_slider->setRange(1, settings.max_cached_minutes * 60);
|
||||
range_slider->setSingleStep(1);
|
||||
range_slider->setPageStep(60); // 1 min
|
||||
range_slider_action = toolbar->addWidget(range_slider);
|
||||
|
||||
// zoom controls
|
||||
undo_zoom_action = toolbar->addAction(utils::icon("arrow-counterclockwise"), tr("Undo Zoom"), [this]() { zoom_undo_stack.undo(); });
|
||||
redo_zoom_action = toolbar->addAction(utils::icon("arrow-clockwise"), tr("Redo Zoom"), [this]() { zoom_undo_stack.redo(); });
|
||||
undo_zoom_action->setEnabled(false);
|
||||
redo_zoom_action->setEnabled(false);
|
||||
zoom_undo_stack.setCallbacks({.index_changed = [this]() {
|
||||
undo_zoom_action->setEnabled(zoom_undo_stack.canUndo());
|
||||
redo_zoom_action->setEnabled(zoom_undo_stack.canRedo());
|
||||
}});
|
||||
reset_zoom_action = toolbar->addWidget(reset_zoom_btn = new ToolButton("zoom-out", tr("Reset Zoom")));
|
||||
reset_zoom_btn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
|
||||
|
||||
toolbar->addWidget(remove_all_btn = new ToolButton("x-square", tr("Remove all charts")));
|
||||
toolbar->addWidget(dock_btn = new ToolButton(""));
|
||||
main_layout->addWidget(toolbar);
|
||||
|
||||
// tabbar
|
||||
tabbar = new TabBar(this);
|
||||
tabbar->setAutoHide(true);
|
||||
tabbar->setExpanding(false);
|
||||
tabbar->setDrawBase(true);
|
||||
tabbar->setUsesScrollButtons(true);
|
||||
main_layout->addWidget(tabbar);
|
||||
|
||||
// charts
|
||||
charts_container = new ChartsContainer(this);
|
||||
charts_container->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
|
||||
charts_scroll = new QScrollArea(this);
|
||||
charts_scroll->viewport()->setBackgroundRole(QPalette::Base);
|
||||
charts_scroll->setFrameStyle(QFrame::NoFrame);
|
||||
charts_scroll->setWidgetResizable(true);
|
||||
charts_scroll->setWidget(charts_container);
|
||||
charts_scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
|
||||
main_layout->addWidget(charts_scroll);
|
||||
|
||||
// chart drag preview
|
||||
drag_preview = new QLabel(this);
|
||||
drag_preview->setAttribute(Qt::WA_TransparentForMouseEvents);
|
||||
drag_preview->hide();
|
||||
|
||||
// init settings
|
||||
current_theme = settings.theme;
|
||||
column_count = std::clamp(settings.chart_column_count, 1, MAX_COLUMN_COUNT);
|
||||
max_chart_range = std::clamp(settings.chart_range, 1, settings.max_cached_minutes * 60);
|
||||
display_range = std::make_pair(can->minSeconds(), can->minSeconds() + max_chart_range);
|
||||
range_slider->setValue(max_chart_range);
|
||||
updateToolBar();
|
||||
|
||||
align_timer->setSingleShot(true);
|
||||
QObject::connect(align_timer, &QTimer::timeout, this, &ChartsWidget::alignCharts);
|
||||
QObject::connect(auto_scroll_timer, &QTimer::timeout, this, &ChartsWidget::doAutoScroll);
|
||||
QObject::connect(dbcNotifier(), &QtDBCNotifier::DBCFileChanged, this, &ChartsWidget::removeAll);
|
||||
QObject::connect(can, &AbstractStream::eventsMerged, this, &ChartsWidget::eventsMerged);
|
||||
QObject::connect(can, &AbstractStream::msgsReceived, this, &ChartsWidget::updateState);
|
||||
QObject::connect(can, &AbstractStream::seeking, this, &ChartsWidget::updateState);
|
||||
QObject::connect(can, &AbstractStream::timeRangeChanged, this, &ChartsWidget::timeRangeChanged);
|
||||
QObject::connect(range_slider, &QSlider::valueChanged, this, &ChartsWidget::setMaxChartRange);
|
||||
QObject::connect(new_plot_btn, &QToolButton::clicked, this, &ChartsWidget::newChart);
|
||||
QObject::connect(remove_all_btn, &QToolButton::clicked, this, &ChartsWidget::removeAll);
|
||||
QObject::connect(reset_zoom_btn, &QToolButton::clicked, this, &ChartsWidget::zoomReset);
|
||||
QObject::connect(&settings, &Settings::changed, this, &ChartsWidget::settingChanged);
|
||||
QObject::connect(new_tab_btn, &QToolButton::clicked, this, &ChartsWidget::newTab);
|
||||
QObject::connect(this, &ChartsWidget::seriesChanged, this, &ChartsWidget::updateTabBar);
|
||||
QObject::connect(tabbar, &QTabBar::tabCloseRequested, this, &ChartsWidget::removeTab);
|
||||
QObject::connect(tabbar, &QTabBar::currentChanged, [this](int index) {
|
||||
if (index != -1) updateLayout(true);
|
||||
});
|
||||
QObject::connect(dock_btn, &QToolButton::clicked, this, &ChartsWidget::toggleChartsDocking);
|
||||
|
||||
setIsDocked(true);
|
||||
newTab();
|
||||
qApp->installEventFilter(this);
|
||||
setWhatsThis(tr(R"(
|
||||
<b>Chart View</b><br />
|
||||
<b>Click</b>: Click to seek to a corresponding time.<br />
|
||||
<b>Drag</b>: Zoom into the chart.<br />
|
||||
<b>Shift + Drag</b>: Scrub through the chart to view values.<br />
|
||||
<b>Right Mouse</b>: Open the context menu.<br />
|
||||
)"));
|
||||
}
|
||||
|
||||
void ChartsWidget::newTab() {
|
||||
static int tab_unique_id = 0;
|
||||
int idx = tabbar->addTab("");
|
||||
tabbar->setTabData(idx, tab_unique_id++);
|
||||
tabbar->setCurrentIndex(idx);
|
||||
updateTabBar();
|
||||
}
|
||||
|
||||
void ChartsWidget::removeTab(int index) {
|
||||
int id = tabbar->tabData(index).toInt();
|
||||
for (auto &c : tab_charts[id]) {
|
||||
removeChart(c);
|
||||
}
|
||||
tab_charts.erase(id);
|
||||
tabbar->removeTab(index);
|
||||
updateTabBar();
|
||||
}
|
||||
|
||||
void ChartsWidget::updateTabBar() {
|
||||
for (int i = 0; i < tabbar->count(); ++i) {
|
||||
const auto &charts_in_tab = tab_charts[tabbar->tabData(i).toInt()];
|
||||
tabbar->setTabText(i, QString("Tab %1 (%2)").arg(i + 1).arg((int)charts_in_tab.size()));
|
||||
}
|
||||
}
|
||||
|
||||
void ChartsWidget::eventsMerged(const MessageEventsMap &new_events) {
|
||||
std::vector<std::future<void>> futures;
|
||||
for (auto c : charts) {
|
||||
futures.push_back(std::async(std::launch::async, &ChartView::updateSeries, c, nullptr, &new_events));
|
||||
}
|
||||
for (auto &f : futures) f.get();
|
||||
}
|
||||
|
||||
void ChartsWidget::timeRangeChanged(const std::optional<std::pair<double, double>> &time_range) {
|
||||
updateToolBar();
|
||||
updateState();
|
||||
}
|
||||
|
||||
void ChartsWidget::zoomReset() {
|
||||
can->setTimeRange(std::nullopt);
|
||||
zoom_undo_stack.clear();
|
||||
}
|
||||
|
||||
QRect ChartsWidget::chartVisibleRect(ChartView *chart) {
|
||||
const QRect visible_rect(-charts_container->pos(), charts_scroll->viewport()->size());
|
||||
return chart->rect().intersected(QRect(chart->mapFrom(charts_container, visible_rect.topLeft()), visible_rect.size()));
|
||||
}
|
||||
|
||||
void ChartsWidget::showValueTip(double sec) {
|
||||
emit showTip(sec);
|
||||
if (sec < 0 && !value_tip_visible_) return;
|
||||
|
||||
value_tip_visible_ = sec >= 0;
|
||||
for (auto c : currentCharts()) {
|
||||
value_tip_visible_ ? c->showTip(sec) : c->hideTip();
|
||||
}
|
||||
}
|
||||
|
||||
void ChartsWidget::updateState() {
|
||||
if (charts.empty()) return;
|
||||
|
||||
const auto &time_range = can->timeRange();
|
||||
const double cur_sec = can->currentSec();
|
||||
if (!time_range.has_value()) {
|
||||
double pos = (cur_sec - display_range.first) / std::max<float>(1.0, max_chart_range);
|
||||
if (pos < 0 || pos > 0.8) {
|
||||
display_range.first = std::max(can->minSeconds(), cur_sec - max_chart_range * 0.1);
|
||||
}
|
||||
double max_sec = std::min(display_range.first + max_chart_range, can->maxSeconds());
|
||||
display_range.first = std::max(can->minSeconds(), max_sec - max_chart_range);
|
||||
display_range.second = display_range.first + max_chart_range;
|
||||
}
|
||||
|
||||
const auto &range = time_range ? *time_range : display_range;
|
||||
for (auto c : charts) {
|
||||
c->updatePlot(cur_sec, range.first, range.second);
|
||||
}
|
||||
}
|
||||
|
||||
void ChartsWidget::setMaxChartRange(int value) {
|
||||
max_chart_range = settings.chart_range = range_slider->value();
|
||||
updateToolBar();
|
||||
updateState();
|
||||
}
|
||||
|
||||
void ChartsWidget::setIsDocked(bool docked) {
|
||||
is_docked = docked;
|
||||
dock_btn->setIcon(is_docked ? "arrow-up-right-square" : "arrow-down-left-square");
|
||||
dock_btn->setToolTip(is_docked ? tr("Float the charts window") : tr("Dock the charts window"));
|
||||
}
|
||||
|
||||
void ChartsWidget::updateToolBar() {
|
||||
title_label->setText(tr("Charts: %1").arg(charts.size()));
|
||||
columns_action->setText(tr("Columns: %1").arg(column_count));
|
||||
range_lb->setText(utils::formatSeconds(max_chart_range));
|
||||
|
||||
bool is_zoomed = can->timeRange().has_value();
|
||||
range_lb_action->setVisible(!is_zoomed);
|
||||
range_slider_action->setVisible(!is_zoomed);
|
||||
undo_zoom_action->setVisible(is_zoomed);
|
||||
redo_zoom_action->setVisible(is_zoomed);
|
||||
reset_zoom_action->setVisible(is_zoomed);
|
||||
reset_zoom_btn->setText(is_zoomed ? tr("%1-%2").arg(can->timeRange()->first, 0, 'f', 2).arg(can->timeRange()->second, 0, 'f', 2) : "");
|
||||
remove_all_btn->setEnabled(!charts.empty());
|
||||
}
|
||||
|
||||
void ChartsWidget::settingChanged() {
|
||||
if (std::exchange(current_theme, settings.theme) != current_theme) {
|
||||
undo_zoom_action->setIcon(utils::icon("arrow-counterclockwise"));
|
||||
redo_zoom_action->setIcon(utils::icon("arrow-clockwise"));
|
||||
}
|
||||
if (range_slider->maximum() != settings.max_cached_minutes * 60) {
|
||||
range_slider->setRange(1, settings.max_cached_minutes * 60);
|
||||
}
|
||||
for (auto c : charts) {
|
||||
c->setFixedHeight(settings.chart_height);
|
||||
c->setSeriesType((SeriesType)settings.chart_series_type);
|
||||
c->resetChartCache();
|
||||
}
|
||||
}
|
||||
|
||||
ChartView *ChartsWidget::findChart(const MessageId &id, const cabana::Signal *sig) {
|
||||
for (auto c : charts)
|
||||
if (c->hasSignal(id, sig)) return c;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
ChartView *ChartsWidget::createChart(int pos) {
|
||||
auto chart = new ChartView(can->timeRange().value_or(display_range), this);
|
||||
chart->setFixedHeight(settings.chart_height);
|
||||
chart->setMinimumWidth(CHART_MIN_WIDTH);
|
||||
chart->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
|
||||
QObject::connect(chart, &ChartView::axisYLabelWidthChanged, align_timer, qOverload<>(&QTimer::start));
|
||||
pos = std::clamp(pos, 0, (int)charts.size());
|
||||
charts.insert(charts.begin() + pos, chart);
|
||||
currentCharts().insert(currentCharts().begin() + pos, chart);
|
||||
updateLayout(true);
|
||||
updateToolBar();
|
||||
return chart;
|
||||
}
|
||||
|
||||
void ChartsWidget::showChart(const MessageId &id, const cabana::Signal *sig, bool show, bool merge) {
|
||||
ChartView *chart = findChart(id, sig);
|
||||
if (show && !chart) {
|
||||
chart = merge && currentCharts().size() > 0 ? currentCharts().front() : createChart();
|
||||
chart->addSignal(id, sig);
|
||||
updateState();
|
||||
} else if (!show && chart) {
|
||||
chart->removeIf([&](auto &s) { return s.msg_id == id && s.sig == sig; });
|
||||
}
|
||||
}
|
||||
|
||||
void ChartsWidget::splitChart(ChartView *src_chart) {
|
||||
if (src_chart->sigs.size() > 1) {
|
||||
int pos = std::find(charts.begin(), charts.end(), src_chart) - charts.begin() + 1;
|
||||
for (auto it = src_chart->sigs.begin() + 1; it != src_chart->sigs.end(); /**/) {
|
||||
auto c = createChart(pos);
|
||||
// Restore to the original color
|
||||
it->color = toQColor(it->sig->color);
|
||||
c->sigs.emplace_back(std::move(*it));
|
||||
c->updateAxisY();
|
||||
c->updateTitle();
|
||||
it = src_chart->sigs.erase(it);
|
||||
}
|
||||
src_chart->updateAxisY();
|
||||
src_chart->updateTitle();
|
||||
updateState();
|
||||
QTimer::singleShot(0, src_chart, &ChartView::resetChartCache);
|
||||
}
|
||||
}
|
||||
|
||||
QStringList ChartsWidget::serializeChartIds() const {
|
||||
QStringList chart_ids;
|
||||
for (auto c : charts) {
|
||||
QStringList ids;
|
||||
for (const auto& s : c->sigs)
|
||||
ids += QString("%1|%2").arg(QString::fromStdString(s.msg_id.toString()), QString::fromStdString(s.sig->name));
|
||||
chart_ids += ids.join(',');
|
||||
}
|
||||
std::reverse(chart_ids.begin(), chart_ids.end());
|
||||
return chart_ids;
|
||||
}
|
||||
|
||||
void ChartsWidget::restoreChartsFromIds(const QStringList& chart_ids) {
|
||||
for (const auto& chart_id : chart_ids) {
|
||||
int index = 0;
|
||||
for (const auto& part : chart_id.split(',')) {
|
||||
const auto sig_parts = part.split('|');
|
||||
if (sig_parts.size() != 2) continue;
|
||||
MessageId msg_id = MessageId::fromString(sig_parts[0].toStdString());
|
||||
if (auto* msg = dbc()->msg(msg_id))
|
||||
if (auto* sig = msg->sig(sig_parts[1].toStdString()))
|
||||
showChart(msg_id, sig, true, index++ > 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ChartsWidget::setColumnCount(int n) {
|
||||
n = std::clamp(n, 1, MAX_COLUMN_COUNT);
|
||||
if (column_count != n) {
|
||||
column_count = settings.chart_column_count = n;
|
||||
updateToolBar();
|
||||
updateLayout();
|
||||
}
|
||||
}
|
||||
|
||||
void ChartsWidget::updateLayout(bool force) {
|
||||
auto charts_layout = charts_container->charts_layout;
|
||||
int n = MAX_COLUMN_COUNT;
|
||||
for (; n > 1; --n) {
|
||||
if ((n * CHART_MIN_WIDTH + (n - 1) * charts_layout->horizontalSpacing()) < charts_layout->geometry().width()) break;
|
||||
}
|
||||
|
||||
bool show_column_cb = n > 1;
|
||||
columns_action->setVisible(show_column_cb);
|
||||
|
||||
n = std::min(column_count, n);
|
||||
auto ¤t_charts = currentCharts();
|
||||
if ((current_charts.size() != charts_layout->count() || n != current_column_count) || force) {
|
||||
current_column_count = n;
|
||||
charts_container->setUpdatesEnabled(false);
|
||||
for (auto c : charts) {
|
||||
c->setVisible(false);
|
||||
}
|
||||
for (int i = 0; i < current_charts.size(); ++i) {
|
||||
charts_layout->addWidget(current_charts[i], i / n, i % n);
|
||||
if (current_charts[i]->sigs.empty()) {
|
||||
// the chart will be resized after add signal. delay setVisible to reduce flicker.
|
||||
QTimer::singleShot(0, current_charts[i], [c = current_charts[i]]() { c->setVisible(true); });
|
||||
} else {
|
||||
current_charts[i]->setVisible(true);
|
||||
}
|
||||
}
|
||||
charts_container->setUpdatesEnabled(true);
|
||||
}
|
||||
}
|
||||
|
||||
void ChartsWidget::startChartDrag(ChartView *chart, const QPoint &global_pos) {
|
||||
stopAutoScroll();
|
||||
drag = {.source = chart, .press_pos = global_pos};
|
||||
QPixmap px = chart->grab().scaledToWidth(CHART_MIN_WIDTH * chart->devicePixelRatio(), Qt::SmoothTransformation);
|
||||
drag_preview->setPixmap(px);
|
||||
drag_preview->resize(px.size() / px.devicePixelRatio());
|
||||
}
|
||||
|
||||
void ChartsWidget::dragChartMove(const QPoint &global_pos) {
|
||||
if (!drag.active) {
|
||||
if ((global_pos - drag.press_pos).manhattanLength() < QApplication::startDragDistance()) return;
|
||||
drag.active = true;
|
||||
drag_preview->show();
|
||||
drag_preview->raise();
|
||||
}
|
||||
drag_preview->move(mapFromGlobal(global_pos) + QPoint(5, 5));
|
||||
|
||||
// hovering a tab switches to it so the chart can be dropped into another tab
|
||||
int tab = tabbar->tabAt(tabbar->mapFromGlobal(global_pos));
|
||||
if (tab >= 0 && tab != tabbar->currentIndex()) {
|
||||
tabbar->setCurrentIndex(tab);
|
||||
}
|
||||
|
||||
const QPoint container_pos = charts_container->mapFromGlobal(global_pos);
|
||||
ChartView *target = nullptr;
|
||||
for (auto c : currentCharts()) {
|
||||
if (c != drag.source && c->isVisible() && c->geometry().contains(container_pos)) {
|
||||
target = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (std::exchange(drop_target, target) != target) {
|
||||
for (auto c : charts) c->setDropHighlight(c == target);
|
||||
}
|
||||
bool in_viewport = charts_scroll->viewport()->rect().contains(charts_scroll->viewport()->mapFromGlobal(global_pos));
|
||||
bool on_background = !target && in_viewport && !charts_container->childAt(container_pos);
|
||||
charts_container->drawDropIndicator(on_background ? container_pos : QPoint());
|
||||
|
||||
if (in_viewport) {
|
||||
startAutoScroll(global_pos);
|
||||
}
|
||||
}
|
||||
|
||||
void ChartsWidget::cancelChartDrag() {
|
||||
drag = {};
|
||||
stopAutoScroll();
|
||||
drag_preview->hide();
|
||||
charts_container->drawDropIndicator({});
|
||||
if (auto target = std::exchange(drop_target, nullptr)) target->setDropHighlight(false);
|
||||
}
|
||||
|
||||
void ChartsWidget::dragChartRelease(const QPoint &global_pos) {
|
||||
ChartView *source = drag.source;
|
||||
bool active = drag.active;
|
||||
ChartView *target = drop_target;
|
||||
cancelChartDrag();
|
||||
if (!active) return;
|
||||
|
||||
const QPoint container_pos = charts_container->mapFromGlobal(global_pos);
|
||||
bool in_viewport = charts_scroll->viewport()->rect().contains(charts_scroll->viewport()->mapFromGlobal(global_pos));
|
||||
if (target) {
|
||||
// merge source into target
|
||||
target->takeSignalsFrom(source);
|
||||
} else if (in_viewport && !charts_container->childAt(container_pos)) {
|
||||
// reorder within the current tab
|
||||
auto w = charts_container->getDropAfter(container_pos);
|
||||
if (w != source) {
|
||||
for (auto &[_, list] : tab_charts) {
|
||||
list.erase(std::remove(list.begin(), list.end(), source), list.end());
|
||||
}
|
||||
auto &cur = currentCharts();
|
||||
int to = w ? std::find(cur.begin(), cur.end(), w) - cur.begin() + 1 : 0;
|
||||
cur.insert(cur.begin() + to, source);
|
||||
updateLayout(true);
|
||||
updateTabBar();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ChartsWidget::startAutoScroll(const QPoint &global_pos) {
|
||||
auto_scroll_pos = global_pos;
|
||||
auto_scroll_timer->start(50);
|
||||
}
|
||||
|
||||
void ChartsWidget::stopAutoScroll() {
|
||||
auto_scroll_timer->stop();
|
||||
auto_scroll_count = 0;
|
||||
}
|
||||
|
||||
void ChartsWidget::doAutoScroll() {
|
||||
QScrollBar *scroll = charts_scroll->verticalScrollBar();
|
||||
if (auto_scroll_count < scroll->pageStep()) {
|
||||
++auto_scroll_count;
|
||||
}
|
||||
|
||||
int value = scroll->value();
|
||||
QPoint pos = charts_scroll->viewport()->mapFromGlobal(auto_scroll_pos);
|
||||
QRect area = charts_scroll->viewport()->rect();
|
||||
|
||||
if (pos.y() - area.top() < settings.chart_height / 2) {
|
||||
scroll->setValue(value - auto_scroll_count);
|
||||
} else if (area.bottom() - pos.y() < settings.chart_height / 2) {
|
||||
scroll->setValue(value + auto_scroll_count);
|
||||
}
|
||||
if (value == scroll->value()) {
|
||||
stopAutoScroll();
|
||||
} else if (chartDragActive()) {
|
||||
// refresh the drop indicator/target at the new scroll position
|
||||
dragChartMove(auto_scroll_pos);
|
||||
}
|
||||
}
|
||||
|
||||
QSize ChartsWidget::minimumSizeHint() const {
|
||||
return QSize(CHART_MIN_WIDTH * 1.5, QWidget::minimumSizeHint().height());
|
||||
}
|
||||
|
||||
void ChartsWidget::newChart() {
|
||||
SignalSelector dlg(tr("New Chart"), this);
|
||||
if (dlg.exec() == QDialog::Accepted) {
|
||||
auto items = dlg.seletedItems();
|
||||
if (!items.empty()) {
|
||||
auto c = createChart();
|
||||
for (auto it : items) {
|
||||
c->addSignal(it->msg_id, it->sig);
|
||||
}
|
||||
updateState();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ChartsWidget::removeChart(ChartView *chart) {
|
||||
if (drag.source == chart) cancelChartDrag();
|
||||
if (drop_target == chart) drop_target = nullptr;
|
||||
charts.erase(std::remove(charts.begin(), charts.end(), chart), charts.end());
|
||||
chart->deleteLater();
|
||||
for (auto &[_, list] : tab_charts) {
|
||||
list.erase(std::remove(list.begin(), list.end(), chart), list.end());
|
||||
}
|
||||
updateToolBar();
|
||||
updateLayout(true);
|
||||
alignCharts();
|
||||
emit seriesChanged();
|
||||
}
|
||||
|
||||
void ChartsWidget::removeAll() {
|
||||
while (tabbar->count() > 1) {
|
||||
tabbar->removeTab(1);
|
||||
}
|
||||
tab_charts.clear();
|
||||
|
||||
if (!charts.empty()) {
|
||||
for (auto c : charts) {
|
||||
delete c;
|
||||
}
|
||||
charts.clear();
|
||||
emit seriesChanged();
|
||||
}
|
||||
zoomReset();
|
||||
}
|
||||
|
||||
void ChartsWidget::alignCharts() {
|
||||
int plot_left = 0;
|
||||
for (auto c : charts) {
|
||||
plot_left = std::max(plot_left, c->y_label_width);
|
||||
}
|
||||
plot_left = std::max((plot_left / 10) * 10 + 10, 50);
|
||||
for (auto c : charts) {
|
||||
c->updatePlotArea(plot_left);
|
||||
}
|
||||
}
|
||||
|
||||
bool ChartsWidget::eventFilter(QObject *o, QEvent *e) {
|
||||
// route all mouse events to the chart drag, even when the source chart is hidden by a tab switch
|
||||
if (chartDragActive()) {
|
||||
if (e->type() == QEvent::MouseMove) {
|
||||
dragChartMove(static_cast<QMouseEvent *>(e)->globalPos());
|
||||
return true;
|
||||
} else if (e->type() == QEvent::MouseButtonRelease && static_cast<QMouseEvent *>(e)->button() == Qt::LeftButton) {
|
||||
dragChartRelease(static_cast<QMouseEvent *>(e)->globalPos());
|
||||
return false; // let the release through so Qt clears the implicit mouse grab
|
||||
} else if (e->type() == QEvent::MouseButtonPress || e->type() == QEvent::MouseButtonRelease) {
|
||||
return true; // swallow other buttons during the drag
|
||||
}
|
||||
}
|
||||
|
||||
if (!value_tip_visible_) return false;
|
||||
|
||||
if (e->type() == QEvent::MouseMove) {
|
||||
bool on_tip = qobject_cast<TipLabel *>(o) != nullptr;
|
||||
auto global_pos = static_cast<QMouseEvent *>(e)->globalPos();
|
||||
|
||||
for (const auto &c : charts) {
|
||||
auto local_pos = c->mapFromGlobal(global_pos);
|
||||
if (c->plot_area.contains(local_pos)) {
|
||||
if (on_tip) {
|
||||
showValueTip(c->secondsAtPoint(local_pos));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
showValueTip(-1);
|
||||
} else if (e->type() == QEvent::Wheel) {
|
||||
if (auto tip = qobject_cast<TipLabel *>(o)) {
|
||||
// Forward the event to the parent widget
|
||||
QCoreApplication::sendEvent(tip->parentWidget(), e);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ChartsWidget::event(QEvent *event) {
|
||||
bool back_button = false;
|
||||
switch (event->type()) {
|
||||
case QEvent::Resize:
|
||||
updateLayout();
|
||||
break;
|
||||
case QEvent::MouseButtonPress:
|
||||
back_button = static_cast<QMouseEvent *>(event)->button() == Qt::BackButton;
|
||||
break;
|
||||
case QEvent::NativeGesture:
|
||||
back_button = (static_cast<QNativeGestureEvent *>(event)->value() == 180);
|
||||
break;
|
||||
case QEvent::WindowDeactivate:
|
||||
case QEvent::FocusOut:
|
||||
if (chartDragActive()) cancelChartDrag();
|
||||
showValueTip(-1);
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (back_button) {
|
||||
zoom_undo_stack.undo();
|
||||
return true; // Return true since the event has been handled
|
||||
}
|
||||
return QFrame::event(event);
|
||||
}
|
||||
|
||||
// ChartsContainer
|
||||
|
||||
ChartsContainer::ChartsContainer(ChartsWidget *parent) : charts_widget(parent), QWidget(parent) {
|
||||
setBackgroundRole(QPalette::Window);
|
||||
QVBoxLayout *charts_main_layout = new QVBoxLayout(this);
|
||||
charts_main_layout->setContentsMargins(0, CHART_SPACING, 0, CHART_SPACING);
|
||||
charts_layout = new QGridLayout();
|
||||
charts_layout->setSpacing(CHART_SPACING);
|
||||
charts_main_layout->addLayout(charts_layout);
|
||||
charts_main_layout->addStretch(0);
|
||||
}
|
||||
|
||||
void ChartsContainer::paintEvent(QPaintEvent *ev) {
|
||||
if (!drop_indictor_pos.isNull() && !childAt(drop_indictor_pos)) {
|
||||
QRect r = geometry();
|
||||
r.setHeight(CHART_SPACING);
|
||||
if (auto insert_after = getDropAfter(drop_indictor_pos)) {
|
||||
r.moveTop(insert_after->geometry().bottom());
|
||||
}
|
||||
|
||||
QPainter p(this);
|
||||
p.fillRect(r, palette().highlight());
|
||||
}
|
||||
}
|
||||
|
||||
ChartView *ChartsContainer::getDropAfter(const QPoint &pos) const {
|
||||
auto it = std::find_if(charts_widget->currentCharts().crbegin(), charts_widget->currentCharts().crend(), [&pos](auto c) {
|
||||
auto area = c->geometry();
|
||||
return pos.x() >= area.left() && pos.x() <= area.right() && pos.y() >= area.bottom();
|
||||
});
|
||||
return it == charts_widget->currentCharts().crend() ? nullptr : *it;
|
||||
}
|
||||
138
iqpilot/tools/cabana/chart/chartswidget.h
Normal file
138
iqpilot/tools/cabana/chart/chartswidget.h
Normal file
@@ -0,0 +1,138 @@
|
||||
#pragma once
|
||||
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
|
||||
#include <QGridLayout>
|
||||
#include <QLabel>
|
||||
#include <QScrollArea>
|
||||
#include <QTimer>
|
||||
#include <QToolBar>
|
||||
|
||||
#include "tools/cabana/chart/signalselector.h"
|
||||
#include "tools/cabana/commands.h"
|
||||
#include "tools/cabana/dbc/dbcmanager.h"
|
||||
#include "tools/cabana/streams/abstractstream.h"
|
||||
|
||||
const int CHART_MIN_WIDTH = 300;
|
||||
|
||||
class ChartView;
|
||||
class ChartsWidget;
|
||||
|
||||
class ChartsContainer : public QWidget {
|
||||
public:
|
||||
ChartsContainer(ChartsWidget *parent);
|
||||
void drawDropIndicator(const QPoint &pt) { drop_indictor_pos = pt; update(); }
|
||||
void paintEvent(QPaintEvent *ev) override;
|
||||
ChartView *getDropAfter(const QPoint &pos) const;
|
||||
|
||||
QGridLayout *charts_layout;
|
||||
ChartsWidget *charts_widget;
|
||||
QPoint drop_indictor_pos;
|
||||
};
|
||||
|
||||
class ChartsWidget : public QFrame {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
ChartsWidget(QWidget *parent = nullptr);
|
||||
void showChart(const MessageId &id, const cabana::Signal *sig, bool show, bool merge);
|
||||
inline bool hasSignal(const MessageId &id, const cabana::Signal *sig) { return findChart(id, sig) != nullptr; }
|
||||
QStringList serializeChartIds() const;
|
||||
void restoreChartsFromIds(const QStringList &chart_ids);
|
||||
|
||||
public slots:
|
||||
void setColumnCount(int n);
|
||||
void removeAll();
|
||||
void timeRangeChanged(const std::optional<std::pair<double, double>> &time_range);
|
||||
void setIsDocked(bool dock);
|
||||
|
||||
signals:
|
||||
void toggleChartsDocking();
|
||||
void seriesChanged();
|
||||
void showTip(double seconds);
|
||||
|
||||
private:
|
||||
QSize minimumSizeHint() const override;
|
||||
bool event(QEvent *event) override;
|
||||
void alignCharts();
|
||||
void newChart();
|
||||
ChartView *createChart(int pos = 0);
|
||||
void removeChart(ChartView *chart);
|
||||
void splitChart(ChartView *chart);
|
||||
QRect chartVisibleRect(ChartView *chart);
|
||||
void eventsMerged(const MessageEventsMap &new_events);
|
||||
void updateState();
|
||||
void zoomReset();
|
||||
void startChartDrag(ChartView *chart, const QPoint &global_pos);
|
||||
void dragChartMove(const QPoint &global_pos);
|
||||
void dragChartRelease(const QPoint &global_pos);
|
||||
void cancelChartDrag();
|
||||
bool chartDragActive() const { return drag.source != nullptr; }
|
||||
void startAutoScroll(const QPoint &global_pos);
|
||||
void stopAutoScroll();
|
||||
void doAutoScroll();
|
||||
void updateToolBar();
|
||||
void updateTabBar();
|
||||
void setMaxChartRange(int value);
|
||||
void updateLayout(bool force = false);
|
||||
void settingChanged();
|
||||
void showValueTip(double sec);
|
||||
bool eventFilter(QObject *obj, QEvent *event) override;
|
||||
void newTab();
|
||||
void removeTab(int index);
|
||||
inline std::vector<ChartView *> ¤tCharts() { return tab_charts[tabbar->tabData(tabbar->currentIndex()).toInt()]; }
|
||||
ChartView *findChart(const MessageId &id, const cabana::Signal *sig);
|
||||
|
||||
QLabel *title_label;
|
||||
QLabel *range_lb;
|
||||
LogSlider *range_slider;
|
||||
QAction *range_lb_action;
|
||||
QAction *range_slider_action;
|
||||
bool is_docked = true;
|
||||
ToolButton *dock_btn;
|
||||
|
||||
QToolBar *toolbar;
|
||||
QAction *undo_zoom_action;
|
||||
QAction *redo_zoom_action;
|
||||
QAction *reset_zoom_action;
|
||||
ToolButton *reset_zoom_btn;
|
||||
UndoStack zoom_undo_stack;
|
||||
|
||||
ToolButton *remove_all_btn;
|
||||
std::vector<ChartView *> charts;
|
||||
std::unordered_map<int, std::vector<ChartView *>> tab_charts;
|
||||
TabBar *tabbar;
|
||||
ChartsContainer *charts_container;
|
||||
QScrollArea *charts_scroll;
|
||||
uint32_t max_chart_range = 0;
|
||||
std::pair<double, double> display_range;
|
||||
QAction *columns_action;
|
||||
int column_count = 1;
|
||||
int current_column_count = 0;
|
||||
struct ChartDrag {
|
||||
ChartView *source = nullptr;
|
||||
QPoint press_pos; // global
|
||||
bool active = false;
|
||||
} drag;
|
||||
QLabel *drag_preview;
|
||||
ChartView *drop_target = nullptr;
|
||||
int auto_scroll_count = 0;
|
||||
QPoint auto_scroll_pos;
|
||||
QTimer *auto_scroll_timer;
|
||||
QTimer *align_timer;
|
||||
int current_theme = 0;
|
||||
bool value_tip_visible_ = false;
|
||||
friend class ChartView;
|
||||
friend class ChartsContainer;
|
||||
};
|
||||
|
||||
class ZoomCommand : public UndoCommand {
|
||||
public:
|
||||
ZoomCommand(std::pair<double, double> range) : range(range) {
|
||||
prev_range = can->timeRange();
|
||||
}
|
||||
void undo() override { can->setTimeRange(prev_range); }
|
||||
void redo() override { can->setTimeRange(range); }
|
||||
std::optional<std::pair<double, double>> prev_range, range;
|
||||
};
|
||||
107
iqpilot/tools/cabana/chart/signalselector.cc
Normal file
107
iqpilot/tools/cabana/chart/signalselector.cc
Normal file
@@ -0,0 +1,107 @@
|
||||
#include "tools/cabana/chart/signalselector.h"
|
||||
#include "tools/cabana/dbc/dbcqt.h"
|
||||
|
||||
#include <QDialogButtonBox>
|
||||
#include <QGridLayout>
|
||||
#include <QLabel>
|
||||
#include <QLineEdit>
|
||||
#include <QPushButton>
|
||||
#include <QVBoxLayout>
|
||||
|
||||
#include "tools/cabana/streams/abstractstream.h"
|
||||
|
||||
SignalSelector::SignalSelector(QString title, QWidget *parent) : QDialog(parent) {
|
||||
setWindowTitle(title);
|
||||
QGridLayout *main_layout = new QGridLayout(this);
|
||||
|
||||
// left column
|
||||
main_layout->addWidget(new QLabel(tr("Available Signals")), 0, 0);
|
||||
main_layout->addWidget(msgs_combo = new QComboBox(this), 1, 0);
|
||||
msgs_combo->setEditable(true);
|
||||
msgs_combo->lineEdit()->setPlaceholderText(tr("Select a msg..."));
|
||||
msgs_combo->setInsertPolicy(QComboBox::NoInsert);
|
||||
|
||||
main_layout->addWidget(available_list = new QListWidget(this), 2, 0);
|
||||
|
||||
// buttons
|
||||
QVBoxLayout *btn_layout = new QVBoxLayout();
|
||||
QPushButton *add_btn = new QPushButton(utils::icon("chevron-right"), "", this);
|
||||
add_btn->setEnabled(false);
|
||||
QPushButton *remove_btn = new QPushButton(utils::icon("chevron-left"), "", this);
|
||||
remove_btn->setEnabled(false);
|
||||
btn_layout->addStretch(0);
|
||||
btn_layout->addWidget(add_btn);
|
||||
btn_layout->addWidget(remove_btn);
|
||||
btn_layout->addStretch(0);
|
||||
main_layout->addLayout(btn_layout, 0, 1, 3, 1);
|
||||
|
||||
// right column
|
||||
main_layout->addWidget(new QLabel(tr("Selected Signals")), 0, 2);
|
||||
main_layout->addWidget(selected_list = new QListWidget(this), 1, 2, 2, 1);
|
||||
|
||||
auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
|
||||
main_layout->addWidget(buttonBox, 3, 2);
|
||||
|
||||
for (const auto &[id, _] : can->lastMessages()) {
|
||||
if (auto m = dbc()->msg(id)) {
|
||||
msgs_combo->addItem(QString("%1 (%2)").arg(QString::fromStdString(m->name)).arg(QString::fromStdString(id.toString())), QVariant::fromValue(id));
|
||||
}
|
||||
}
|
||||
msgs_combo->model()->sort(0);
|
||||
msgs_combo->setCurrentIndex(-1);
|
||||
|
||||
QObject::connect(msgs_combo, qOverload<int>(&QComboBox::currentIndexChanged), this, &SignalSelector::updateAvailableList);
|
||||
QObject::connect(available_list, &QListWidget::currentRowChanged, [=](int row) { add_btn->setEnabled(row != -1); });
|
||||
QObject::connect(selected_list, &QListWidget::currentRowChanged, [=](int row) { remove_btn->setEnabled(row != -1); });
|
||||
QObject::connect(available_list, &QListWidget::itemDoubleClicked, this, &SignalSelector::add);
|
||||
QObject::connect(selected_list, &QListWidget::itemDoubleClicked, this, &SignalSelector::remove);
|
||||
QObject::connect(add_btn, &QPushButton::clicked, [this]() { if (auto item = available_list->currentItem()) add(item); });
|
||||
QObject::connect(remove_btn, &QPushButton::clicked, [this]() { if (auto item = selected_list->currentItem()) remove(item); });
|
||||
QObject::connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
|
||||
QObject::connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
|
||||
}
|
||||
|
||||
void SignalSelector::add(QListWidgetItem *item) {
|
||||
auto it = (ListItem *)item;
|
||||
addItemToList(selected_list, it->msg_id, it->sig, true);
|
||||
delete item;
|
||||
}
|
||||
|
||||
void SignalSelector::remove(QListWidgetItem *item) {
|
||||
auto it = (ListItem *)item;
|
||||
if (it->msg_id == msgs_combo->currentData().value<MessageId>()) {
|
||||
addItemToList(available_list, it->msg_id, it->sig);
|
||||
}
|
||||
delete item;
|
||||
}
|
||||
|
||||
void SignalSelector::updateAvailableList(int index) {
|
||||
if (index == -1) return;
|
||||
available_list->clear();
|
||||
MessageId msg_id = msgs_combo->itemData(index).value<MessageId>();
|
||||
auto selected_items = seletedItems();
|
||||
for (auto s : dbc()->msg(msg_id)->getSignals()) {
|
||||
bool is_selected = std::any_of(selected_items.begin(), selected_items.end(),
|
||||
[sig = s, &msg_id](auto it) { return it->msg_id == msg_id && it->sig == sig; });
|
||||
if (!is_selected) {
|
||||
addItemToList(available_list, msg_id, s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SignalSelector::addItemToList(QListWidget *parent, const MessageId id, const cabana::Signal *sig, bool show_msg_name) {
|
||||
QString text = QString("<span style=\"color:%0;\">■ </span> %1").arg(toQColor(sig->color).name(), QString::fromStdString(sig->name));
|
||||
if (show_msg_name) text += QString(" <font color=\"gray\">%0 %1</font>").arg(QString::fromStdString(msgName(id)), QString::fromStdString(id.toString()));
|
||||
|
||||
QLabel *label = new QLabel(text);
|
||||
label->setContentsMargins(5, 0, 5, 0);
|
||||
auto new_item = new ListItem(id, sig, parent);
|
||||
new_item->setSizeHint(label->sizeHint());
|
||||
parent->setItemWidget(new_item, label);
|
||||
}
|
||||
|
||||
std::vector<SignalSelector::ListItem *> SignalSelector::seletedItems() {
|
||||
std::vector<SignalSelector::ListItem *> ret;
|
||||
for (int i = 0; i < selected_list->count(); ++i) ret.push_back((ListItem *)selected_list->item(i));
|
||||
return ret;
|
||||
}
|
||||
30
iqpilot/tools/cabana/chart/signalselector.h
Normal file
30
iqpilot/tools/cabana/chart/signalselector.h
Normal file
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include <QComboBox>
|
||||
#include <QDialog>
|
||||
#include <QListWidget>
|
||||
|
||||
#include "tools/cabana/dbc/dbcmanager.h"
|
||||
|
||||
class SignalSelector : public QDialog {
|
||||
public:
|
||||
struct ListItem : public QListWidgetItem {
|
||||
ListItem(const MessageId &msg_id, const cabana::Signal *sig, QListWidget *parent) : msg_id(msg_id), sig(sig), QListWidgetItem(parent) {}
|
||||
MessageId msg_id;
|
||||
const cabana::Signal *sig;
|
||||
};
|
||||
|
||||
SignalSelector(QString title, QWidget *parent);
|
||||
std::vector<ListItem *> seletedItems();
|
||||
inline void addSelected(const MessageId &id, const cabana::Signal *sig) { addItemToList(selected_list, id, sig, true); }
|
||||
|
||||
private:
|
||||
void updateAvailableList(int index);
|
||||
void addItemToList(QListWidget *parent, const MessageId id, const cabana::Signal *sig, bool show_msg_name = false);
|
||||
void add(QListWidgetItem *item);
|
||||
void remove(QListWidgetItem *item);
|
||||
|
||||
QComboBox *msgs_combo;
|
||||
QListWidget *available_list;
|
||||
QListWidget *selected_list;
|
||||
};
|
||||
100
iqpilot/tools/cabana/chart/sparkline.cc
Normal file
100
iqpilot/tools/cabana/chart/sparkline.cc
Normal file
@@ -0,0 +1,100 @@
|
||||
#include "tools/cabana/chart/sparkline.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <QPainter>
|
||||
|
||||
void Sparkline::update(const cabana::Signal *sig, CanEventIter first, CanEventIter last, int range, QSize size) {
|
||||
if (first == last || size.isEmpty()) {
|
||||
pixmap = QPixmap();
|
||||
return;
|
||||
}
|
||||
|
||||
points_.clear();
|
||||
min_val = std::numeric_limits<double>::max();
|
||||
max_val = std::numeric_limits<double>::lowest();
|
||||
points_.reserve(std::distance(first, last));
|
||||
|
||||
uint64_t start_time = (*first)->mono_time;
|
||||
double value = 0.0;
|
||||
for (auto it = first; it != last; ++it) {
|
||||
if (sig->getValue((*it)->dat, (*it)->size, &value)) {
|
||||
min_val = std::min(min_val, value);
|
||||
max_val = std::max(max_val, value);
|
||||
points_.emplace_back(((*it)->mono_time - start_time) / 1e9, value);
|
||||
}
|
||||
}
|
||||
|
||||
if (points_.empty()) {
|
||||
pixmap = QPixmap();
|
||||
return;
|
||||
}
|
||||
|
||||
freq_ = points_.size() / std::max(points_.back().x() - points_.front().x(), 1.0);
|
||||
render(toQColor(sig->color), range, size);
|
||||
}
|
||||
|
||||
void Sparkline::render(const QColor &color, int range, QSize size) {
|
||||
// Adjust for flat lines
|
||||
bool is_flat_line = min_val == max_val;
|
||||
if (is_flat_line) {
|
||||
min_val -= 1.0;
|
||||
max_val += 1.0;
|
||||
}
|
||||
|
||||
// Calculate scaling
|
||||
const double xscale = (size.width() - 1) / (double)range;
|
||||
const double yscale = (size.height() - 3) / (max_val - min_val);
|
||||
bool draw_individual_points = (points_.back().x() * xscale / points_.size()) > 8.0;
|
||||
|
||||
// Transform or downsample points
|
||||
render_points_.reserve(points_.size());
|
||||
render_points_.clear();
|
||||
if (draw_individual_points) {
|
||||
for (const auto &p : points_) {
|
||||
render_points_.emplace_back(p.x() * xscale, 1.0 + (max_val - p.y()) * yscale);
|
||||
}
|
||||
} else if (is_flat_line) {
|
||||
double y = size.height() / 2.0;
|
||||
render_points_.emplace_back(0.0, y);
|
||||
render_points_.emplace_back(points_.back().x() * xscale, y);
|
||||
} else {
|
||||
double prev_y = points_.front().y();
|
||||
render_points_.emplace_back(points_.front().x() * xscale, 1.0 + (max_val - prev_y) * yscale);
|
||||
bool in_flat = false;
|
||||
|
||||
for (size_t i = 1; i < points_.size(); ++i) {
|
||||
const auto &p = points_[i];
|
||||
double y = p.y();
|
||||
if (std::abs(y - prev_y) < 1e-6) {
|
||||
in_flat = true;
|
||||
} else {
|
||||
if (in_flat) render_points_.emplace_back(points_[i - 1].x() * xscale, 1.0 + (max_val - prev_y) * yscale);
|
||||
render_points_.emplace_back(p.x() * xscale, 1.0 + (max_val - y) * yscale);
|
||||
in_flat = false;
|
||||
}
|
||||
prev_y = y;
|
||||
}
|
||||
if (in_flat) render_points_.emplace_back(points_.back().x() * xscale, 1.0 + (max_val - prev_y) * yscale);
|
||||
}
|
||||
|
||||
// Render to pixmap
|
||||
qreal dpr = qApp->devicePixelRatio();
|
||||
const QSize pixmap_size = size * dpr;
|
||||
if (pixmap.size() != pixmap_size) {
|
||||
pixmap = QPixmap(pixmap_size);
|
||||
}
|
||||
pixmap.setDevicePixelRatio(dpr);
|
||||
pixmap.fill(Qt::transparent);
|
||||
QPainter painter(&pixmap);
|
||||
painter.setRenderHint(QPainter::Antialiasing, render_points_.size() <= 500);
|
||||
painter.setPen(color);
|
||||
painter.drawPolyline(render_points_.data(), render_points_.size());
|
||||
|
||||
painter.setPen(QPen(color, 3));
|
||||
if (draw_individual_points) {
|
||||
painter.drawPoints(render_points_.data(), render_points_.size());
|
||||
} else {
|
||||
painter.drawPoint(render_points_.back());
|
||||
}
|
||||
}
|
||||
26
iqpilot/tools/cabana/chart/sparkline.h
Normal file
26
iqpilot/tools/cabana/chart/sparkline.h
Normal file
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include <QPixmap>
|
||||
#include <QPointF>
|
||||
#include <vector>
|
||||
|
||||
#include "tools/cabana/dbc/dbc.h"
|
||||
#include "tools/cabana/streams/abstractstream.h"
|
||||
|
||||
class Sparkline {
|
||||
public:
|
||||
void update(const cabana::Signal *sig, CanEventIter first, CanEventIter last, int range, QSize size);
|
||||
inline double freq() const { return freq_; }
|
||||
bool isEmpty() const { return pixmap.isNull(); }
|
||||
|
||||
QPixmap pixmap;
|
||||
double min_val = 0;
|
||||
double max_val = 0;
|
||||
|
||||
private:
|
||||
void render(const QColor &color, int range, QSize size);
|
||||
|
||||
std::vector<QPointF> points_;
|
||||
std::vector<QPointF> render_points_;
|
||||
double freq_ = 0;
|
||||
};
|
||||
58
iqpilot/tools/cabana/chart/tiplabel.cc
Normal file
58
iqpilot/tools/cabana/chart/tiplabel.cc
Normal file
@@ -0,0 +1,58 @@
|
||||
#include "tools/cabana/chart/tiplabel.h"
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include <QApplication>
|
||||
#include <QStylePainter>
|
||||
#include <QToolTip>
|
||||
|
||||
#include "tools/cabana/settings.h"
|
||||
#include "tools/cabana/utils/util.h"
|
||||
|
||||
TipLabel::TipLabel(QWidget *parent) : QLabel(parent, Qt::ToolTip | Qt::FramelessWindowHint) {
|
||||
setAttribute(Qt::WA_ShowWithoutActivating);
|
||||
setAttribute(Qt::WA_TransparentForMouseEvents);
|
||||
|
||||
setForegroundRole(QPalette::ToolTipText);
|
||||
setBackgroundRole(QPalette::ToolTipBase);
|
||||
|
||||
QFont font;
|
||||
font.setPointSizeF(8.34563465);
|
||||
setFont(font);
|
||||
auto palette = QToolTip::palette();
|
||||
if (!utils::isDarkTheme()) {
|
||||
palette.setColor(QPalette::ToolTipBase, QApplication::palette().color(QPalette::Base));
|
||||
palette.setColor(QPalette::ToolTipText, QRgb(0x404044)); // same color as chart label brush
|
||||
}
|
||||
setPalette(palette);
|
||||
ensurePolished();
|
||||
setMargin(1 + style()->pixelMetric(QStyle::PM_ToolTipLabelFrameWidth, nullptr, this));
|
||||
setTextFormat(Qt::RichText);
|
||||
}
|
||||
|
||||
void TipLabel::showText(const QPoint &pt, const QString &text, QWidget *w, const QRect &rect) {
|
||||
setText(text);
|
||||
if (!text.isEmpty()) {
|
||||
QSize extra(1, 1);
|
||||
resize(sizeHint() + extra);
|
||||
QPoint tip_pos(pt.x() + 8, rect.top() + 2);
|
||||
if (tip_pos.x() + size().width() >= rect.right()) {
|
||||
tip_pos.rx() = pt.x() - size().width() - 8;
|
||||
}
|
||||
if (rect.contains({tip_pos, size()})) {
|
||||
move(w->mapToGlobal(tip_pos));
|
||||
setVisible(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setVisible(false);
|
||||
}
|
||||
|
||||
void TipLabel::paintEvent(QPaintEvent *ev) {
|
||||
QStylePainter p(this);
|
||||
QStyleOptionFrame opt;
|
||||
opt.init(this);
|
||||
p.drawPrimitive(QStyle::PE_PanelTipLabel, opt);
|
||||
p.end();
|
||||
QLabel::paintEvent(ev);
|
||||
}
|
||||
12
iqpilot/tools/cabana/chart/tiplabel.h
Normal file
12
iqpilot/tools/cabana/chart/tiplabel.h
Normal file
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include <QLabel>
|
||||
|
||||
class TipLabel : public QLabel {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
TipLabel(QWidget *parent = nullptr);
|
||||
void showText(const QPoint &pt, const QString &sec, QWidget *w, const QRect &rect);
|
||||
void paintEvent(QPaintEvent *ev) override;
|
||||
};
|
||||
Reference in New Issue
Block a user